Merge main into fix/shape-escape-restores-options
No files matched your search
@@ -1,2 +1,9 @@
|
||||
[alias]
|
||||
xtask = "run --package xtask --"
|
||||
|
||||
# WebAssembly SIMD for the web build: without it vello_cpu's SIMD layer (fearless_simd) runs its
|
||||
# scalar fallback on wasm32 and the canvas renders about 2.4x slower (#2786). The web build then
|
||||
# needs Chrome/Edge 91+, Firefox 89+ or Safari 16.4+. A RUSTFLAGS environment variable replaces
|
||||
# these flags.
|
||||
[target.wasm32-unknown-unknown]
|
||||
rustflags = ["-C", "target-feature=+simd128"]
|
||||
@@ -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
|
||||
@@ -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,7 +66,7 @@ jobs:
|
||||
PY
|
||||
|
||||
release:
|
||||
needs: git-sources
|
||||
needs: [git-sources, credits]
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
@@ -72,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 }}
|
||||
@@ -82,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 }}
|
||||
|
||||
@@ -1,3 +1,56 @@
|
||||
<!-- craft-house-rules:start core source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=540e6cea75d12d0710c3dca89658328e81e508ecef102446ca5bb95b7c0b92bb -->
|
||||
## 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.
|
||||
<!-- craft-house-rules:end -->
|
||||
<!-- craft-house-rules:start rust source=dde09ea31e2e457f5b4653a6e76f7cdf55944bdf sha256=387e0ccb4b49e567f60951d7d6fff7305054c89f43ad812b9993dc7c38528013 -->
|
||||
## 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.
|
||||
<!-- craft-house-rules:end -->
|
||||
|
||||
# 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:
|
||||
@@ -45,7 +95,6 @@ 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). 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`).
|
||||
|
||||
@@ -88,3 +137,5 @@ When a task lands, update in the same PR: the area row in `docs/target-app-parit
|
||||
- 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.
|
||||
@@ -1,5 +1,21 @@
|
||||
# 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).
|
||||
@@ -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 | |
|
||||
@@ -348,6 +368,18 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `crates/engine/tests/fixtures/jpeg2000/checker.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `3de9c2bb5b8aaec241d939b795002a68eb3d50e41d51c43368000804ad3de057` |
|
||||
| `crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `76fa51ab8ccbc2534098b26b8e7fe16dd886e2b6298ba52d06a6b1bde9b61d9e` |
|
||||
| `crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `1b1aeed8975d3cdc832da6ecf5855852d07d0c490105121e61a8aefb31af009b` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 red, green, blue and white quadrants encoded with libheif's `heif-enc` 1.23.2 (x265); SHA-256 `122d14963fe899daa736cd216902cf4fc8f2192b3a0ba81f94004adcd71a0ff5` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-alpha.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants with a transparent right half, encoded with `heif-enc` 1.23.2; SHA-256 `55b5a537401ead742714c3a1bc526559ec8c1ba97cdb7f43ac63f4037167475b` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-10bit.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants at 10 bits, encoded with `heif-enc` 1.23.2; SHA-256 `11014848c6a838e5799d87e034eff1b06b816712ed70ba451bd582d72741774f` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-grid.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 128 × 128 quadrants as a 2 × 2 grid of 64 × 64 tiles, encoded with `heif-enc` 1.23.2; SHA-256 `5802f8715110954eb9c58d4bdcc10d1200426a48cf726f1b88dfb60da825ba7a` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-300ppi.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants with EXIF resolution tags of 300 ppi, encoded with `heif-enc` 1.23.2; SHA-256 `6a344a6de04fc5fceaee46b6e0028b12478c90bdcb6f6f14ed8c86a44cb203d7` |
|
||||
| `crates/engine/tests/fixtures/heif/wide-rotated.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 16 red and blue halves stored with a quarter-turn rotation, encoded with `heif-enc` 1.23.2; SHA-256 `e3a2c3a9beb4066c13d6deb8e1311805c6aac485fde8784f1ee317dd95b89973` |
|
||||
| `crates/engine/tests/fixtures/heif/wide-rotated-300x150.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the rotated halves with EXIF resolution tags of 300 ppi across and 150 ppi down, encoded with `heif-enc` 1.23.2; SHA-256 `79ad7945cd2c1ea9d3e70ac9b93d9a162fd8ce37541a0f3de44e12f04745921d` |
|
||||
| `crates/engine/tests/fixtures/heif/tones.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 quadrants of four mid tones, encoded with `heif-enc` 1.23.2; SHA-256 `29ed7d75fbfbc4c298eb2da3a6b62625a150cd6bfe5b7ff1d847437501b1b4b1` |
|
||||
| `crates/engine/tests/fixtures/heif/tones-p3-nclx.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones labeled Display P3 in an `nclx` color box, encoded with `heif-enc` 1.23.2; SHA-256 `baeb32ffa58ac1ac29a00c9e388b9281f4acb4695c4681e4933d0ad061447101` |
|
||||
| `crates/engine/tests/fixtures/heif/tones-p3-icc.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones with VectorCraft's own Display P3 ICC profile (`vectorcraft_color::cms::icc_bytes`), encoded with `heif-enc` 1.23.2; SHA-256 `472e1a123b9515926a8985a04c3f680387e8c410dbf8f7ff0cfb8cb99c89e93b` |
|
||||
| `crates/engine/tests/fixtures/heif/tones-p3-icc-only.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones with VectorCraft's own Display P3 ICC profile as their only color box, encoded with `heif-enc` 1.23.2; SHA-256 `2654fdd21e56641107db20b3f4d0a66a86420ac040d42ddf55e20f7e789d5c55` |
|
||||
| `crates/engine/tests/fixtures/heif/quadrants-grid16.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 quadrants as a 2 × 2 grid of 16 × 16 tiles, each cropped from a 64 × 64 picture, encoded with `heif-enc` 1.23.2; SHA-256 `bd114ee66cdac10142729dc9dddfa1cd96993a5cefa54c2f25b65496652f007f` |
|
||||
|
||||
## Assets embedded by the PDF backend
|
||||
|
||||
@@ -355,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 |
|
||||
@@ -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 |
|
||||
@@ -1,76 +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**. 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). 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:
|
||||
- [`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.
|
||||
|
||||
## 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.
|
||||
@AGENTS.md
|
||||
@@ -970,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",
|
||||
@@ -1003,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",
|
||||
@@ -1013,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",
|
||||
@@ -1024,9 +1024,10 @@ 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.2",
|
||||
"tempfile",
|
||||
@@ -1037,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",
|
||||
@@ -1081,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",
|
||||
@@ -1419,7 +1442,7 @@ dependencies = [
|
||||
"itertools",
|
||||
"log",
|
||||
"profiling",
|
||||
"resvg",
|
||||
"resvg 0.45.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2194,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",
|
||||
@@ -2203,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",
|
||||
@@ -2221,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",
|
||||
@@ -2239,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",
|
||||
@@ -2263,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"
|
||||
@@ -2852,7 +2884,7 @@ 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",
|
||||
@@ -2955,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",
|
||||
@@ -4407,11 +4438,29 @@ dependencies = [
|
||||
"pico-args",
|
||||
"rgb",
|
||||
"svgtypes 0.15.3",
|
||||
"tiny-skia",
|
||||
"tiny-skia 0.11.4",
|
||||
"usvg 0.45.1",
|
||||
"zune-jpeg 0.4.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "resvg"
|
||||
version = "0.48.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"gif 0.14.2",
|
||||
"image-webp",
|
||||
"log",
|
||||
"pico-args",
|
||||
"rgb",
|
||||
"svgtypes 0.16.1",
|
||||
"tiny-skia 0.12.0",
|
||||
"usvg 0.48.1",
|
||||
"zune-jpeg 0.5.15",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rfd"
|
||||
version = "0.17.2"
|
||||
@@ -4696,7 +4745,7 @@ checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"
|
||||
dependencies = [
|
||||
"log",
|
||||
"smithay-client-toolkit 0.19.2",
|
||||
"tiny-skia",
|
||||
"tiny-skia 0.11.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5562,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"
|
||||
@@ -6061,7 +6125,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"block2 0.6.2",
|
||||
@@ -6088,6 +6152,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"smithay-clipboard",
|
||||
"socket2",
|
||||
"tempfile",
|
||||
"vectorcraft-engine",
|
||||
"vectorcraft-render",
|
||||
"vectorcraft-text",
|
||||
@@ -6106,7 +6171,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-affinity"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -6117,7 +6182,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-brush"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"serde",
|
||||
@@ -6129,7 +6194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cad"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6145,12 +6210,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cli"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-engine",
|
||||
@@ -6167,7 +6233,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-color"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"moxcms",
|
||||
@@ -6179,7 +6245,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-doc"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"hayro-ccitt",
|
||||
@@ -6198,11 +6264,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-effects"
|
||||
version = "0.20.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",
|
||||
@@ -6214,17 +6282,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-engine"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"chrono",
|
||||
"craft-docpath",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"hayro-jpeg2000",
|
||||
"heic-rs",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
"proptest",
|
||||
"rayon",
|
||||
"roxmltree 0.21.2",
|
||||
"rustix 1.1.6",
|
||||
"ruzstd",
|
||||
@@ -6239,6 +6310,7 @@ dependencies = [
|
||||
"vectorcraft-eps",
|
||||
"vectorcraft-format",
|
||||
"vectorcraft-geom",
|
||||
"vectorcraft-js",
|
||||
"vectorcraft-metafile",
|
||||
"vectorcraft-pathops",
|
||||
"vectorcraft-pdf",
|
||||
@@ -6255,8 +6327,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-eps"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-pdf",
|
||||
"fax",
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -6265,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",
|
||||
@@ -6279,8 +6354,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-format"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-vectorcraft-format",
|
||||
"flate2",
|
||||
"proptest",
|
||||
"rustix 1.1.6",
|
||||
@@ -6294,7 +6370,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-geom"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"proptest",
|
||||
@@ -6304,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.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
@@ -6325,7 +6410,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-metafile"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6339,7 +6424,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pathops"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"linesweeper",
|
||||
@@ -6351,7 +6436,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pdf"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"chrono",
|
||||
@@ -6383,10 +6468,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-plugins"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror 2.0.21",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
@@ -6397,7 +6484,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-render"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"gif 0.14.2",
|
||||
@@ -6427,23 +6514,24 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-scriptcheck"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-svg"
|
||||
version = "0.20.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",
|
||||
@@ -6453,13 +6541,14 @@ dependencies = [
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-effects",
|
||||
"vectorcraft-geom",
|
||||
"vectorcraft-pathops",
|
||||
"vectorcraft-testkit",
|
||||
"vectorcraft-text",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-testkit"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"image",
|
||||
@@ -6477,7 +6566,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-text"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"harfrust 0.13.3",
|
||||
"icu_segmenter",
|
||||
@@ -6498,7 +6587,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-three-d"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"vectorcraft-geom",
|
||||
"vectorcraft-pathops",
|
||||
@@ -6506,7 +6595,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-tools"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6523,7 +6612,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-trace"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6535,7 +6624,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-ui-egui"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"craft-keymap",
|
||||
@@ -6573,8 +6662,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-web"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"craft-web-api",
|
||||
"eframe",
|
||||
"egui",
|
||||
"js-sys",
|
||||
@@ -6740,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]]
|
||||
@@ -6800,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",
|
||||
@@ -6811,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",
|
||||
@@ -6824,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",
|
||||
]
|
||||
@@ -7704,7 +7794,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.20.0"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -4,21 +4,23 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.20.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-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
|
||||
@@ -51,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"] }
|
||||
@@ -145,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" }
|
||||
|
||||
@@ -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.
|
||||
@@ -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-<ver>.zip` | Runs in a modern browser; host it on any static server |
|
||||
| Static site | `vectorcraft-web-<ver>.zip` | Runs in a browser with WebAssembly SIMD (Chrome/Edge 91, Firefox 89, Safari 16.4 or newer), see `packaging/web/README.md`; host it on any static server |
|
||||
|
||||
## The Crafting Apps
|
||||
|
||||
|
||||
@@ -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-11-01 · **Change:** minor (Progress log row for the Color Effects add-on's Find Nearest Swatch; 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% |
|
||||
@@ -129,6 +136,11 @@ 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).
|
||||
@@ -136,6 +148,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 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 `<name>_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.
|
||||
@@ -149,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.
|
||||
|
||||
@@ -212,6 +226,11 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-02 | minor | Selection QoL: saved marquee modes, screen drag direction with a 3 px dead zone, and translated mode/E feedback (#5313); VectorCraft addition, scores and estimates unchanged. |
|
||||
| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged |
|
||||
| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. |
|
||||
| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. |
|
||||
| 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. |
|
||||
|
||||
@@ -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 }
|
||||
@@ -45,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 }
|
||||
@@ -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]
|
||||
@@ -72,6 +73,11 @@ const USAGE: &str = "\
|
||||
vectorcraft-cli — VectorCraft automation
|
||||
|
||||
USAGE:
|
||||
vectorcraft-cli --safe-mode SUBCOMMAND ...
|
||||
Run any subcommand without plug-ins: none loads or runs, and plug-in commands report that
|
||||
Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and
|
||||
does not take --connect.
|
||||
|
||||
vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
|
||||
Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979
|
||||
(vectorcraft --control 7979), falling back to a headless in-process session.
|
||||
@@ -81,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.
|
||||
@@ -94,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).
|
||||
@@ -127,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.
|
||||
@@ -174,12 +186,18 @@ fn main() -> ExitCode {
|
||||
#[cfg(target_os = "macos")]
|
||||
mac_fonts::install();
|
||||
prefs_dir::install_fonts();
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let mut args: Vec<String> = std::env::args().skip(1).collect();
|
||||
// Before any subcommand attaches the plug-in folder.
|
||||
let safe_mode = args.first().is_some_and(|a| a == "--safe-mode");
|
||||
if safe_mode {
|
||||
args.remove(0);
|
||||
vectorcraft_engine::cmd::plugin::start_in_safe_mode();
|
||||
}
|
||||
let r = match args.first().map(String::as_str) {
|
||||
// `commands` and `info` take no options, so `--help` or `-h` anywhere after them prints the
|
||||
// usage. The other subcommands check for it themselves.
|
||||
Some("commands" | "info") if help_requested(&args[1..], &[]) => help(),
|
||||
Some("mcp") => mcp(&args[1..]),
|
||||
Some("mcp") => mcp(&args[1..], safe_mode),
|
||||
Some("run") => run(&args[1..]),
|
||||
Some("commands") => commands(),
|
||||
Some("convert") => convert(&args[1..]),
|
||||
@@ -212,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();
|
||||
}
|
||||
@@ -239,6 +259,9 @@ fn mcp(args: &[String]) -> Result<(), String> {
|
||||
if headless && connect.is_some() {
|
||||
return Err("use either --connect or --headless".into());
|
||||
}
|
||||
if safe_mode && connect.is_some() {
|
||||
return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control <port>`".into());
|
||||
}
|
||||
let read: Vec<&Path> = read_roots.iter().map(Path::new).collect();
|
||||
let write: Vec<&Path> = write_roots.iter().map(Path::new).collect();
|
||||
let roots = AutomationRoots::new(&read, &write)?;
|
||||
@@ -251,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.
|
||||
@@ -279,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::<u64>, None::<String>, false, false, false, false);
|
||||
(None::<f64>, None::<u64>, None::<String>, false, false, false, false);
|
||||
let mut ppi = None::<f64>;
|
||||
let mut decimals = None::<u64>;
|
||||
// Legacy `.ai` options, passed on as the export's own (`aiVersion`, `hiddenObjects`,
|
||||
// `transparentImages`); the engine checks their values.
|
||||
@@ -293,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,
|
||||
@@ -326,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);
|
||||
}
|
||||
@@ -372,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<f64>, ppi: Option<f64>) -> 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
|
||||
}
|
||||
@@ -485,7 +523,7 @@ fn command_step(v: Value) -> Result<Step, String> {
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
@@ -494,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<usize> = None;
|
||||
let mut stdin_read = false;
|
||||
let mut scale = 1.0;
|
||||
let mut scale = None::<f64>;
|
||||
let mut ppi = None::<f64>;
|
||||
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}"));
|
||||
@@ -531,7 +570,16 @@ fn run(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
"--scale" | "-s" => {
|
||||
let raw = val("a number")?;
|
||||
scale = raw.parse::<f64>().map_err(|_| format!("--scale {raw}: not a number"))?;
|
||||
scale = Some(raw.parse::<f64>().map_err(|_| format!("--scale {raw}: not a number"))?);
|
||||
}
|
||||
"--ppi" => {
|
||||
let raw = val("a number")?;
|
||||
ppi = Some(
|
||||
raw.parse::<f64>()
|
||||
.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}`")),
|
||||
}
|
||||
@@ -576,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}))?;
|
||||
|
||||
@@ -64,6 +64,61 @@ fn median_ms(runs: usize, mut f: impl FnMut()) -> f64 {
|
||||
v.get(v.len() / 2).copied().unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// Exercise the application's native save/open commands, including previews, PDF output,
|
||||
/// compression and API base64 conversion. Session setup and validation are outside timing.
|
||||
/// Five measured runs follow one warmup; no filesystem or GPU window is involved.
|
||||
fn native_io(doc: &Document) -> Result<(), String> {
|
||||
for (label, compatible, preview) in [
|
||||
("default options", None, false),
|
||||
("PDF disabled", Some(false), false),
|
||||
("preview+gzip", None, true),
|
||||
("preview+gzip, PDF disabled", Some(false), true),
|
||||
] {
|
||||
let mut session = vectorcraft_engine::Session::new();
|
||||
session.add_document(doc.clone(), None);
|
||||
let mut params = json!({"format":"vectorcraft","modified":null,"preview":preview,"compress":preview});
|
||||
if let Some(value) = compatible {
|
||||
params["pdfCompatible"] = json!(value);
|
||||
}
|
||||
let (mut saves, mut opens) = (Vec::new(), Vec::new());
|
||||
let (mut size, mut has_pdf, mut compressed) = (0, false, false);
|
||||
for run in 0..6 {
|
||||
let start = Instant::now();
|
||||
let saved = session.execute("file.saveAs", ¶ms).map_err(|e| e.to_string())?;
|
||||
let save_ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
let data = saved["dataBase64"].as_str().ok_or("native save returned no dataBase64")?;
|
||||
let bytes = vectorcraft_format::base64_decode(data).ok_or("native save returned invalid base64")?;
|
||||
size = bytes.len();
|
||||
has_pdf = vectorcraft_format::pdf_content(&bytes).is_some();
|
||||
if compatible == Some(false) && has_pdf {
|
||||
return Err("native save ignored the explicit PDF opt-out".into());
|
||||
}
|
||||
compressed = vectorcraft_format::is_compressed(&bytes);
|
||||
if compressed != preview || vectorcraft_format::preview(&bytes).is_some() != preview {
|
||||
return Err("native save did not apply the requested preview/compression options".into());
|
||||
}
|
||||
let args = json!({"name":"perf.vectorcraft","dataBase64":data});
|
||||
let mut opened = vectorcraft_engine::Session::new();
|
||||
let start = Instant::now();
|
||||
opened.execute("document.open", &args).map_err(|e| e.to_string())?;
|
||||
let open_ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
if opened.doc().map_err(|e| e.to_string())?.doc.artboards.len() != doc.artboards.len() {
|
||||
return Err("native round trip changed the artboard count".into());
|
||||
}
|
||||
if run > 0 {
|
||||
saves.push(save_ms);
|
||||
opens.push(open_ms);
|
||||
}
|
||||
}
|
||||
saves.sort_by(f64::total_cmp);
|
||||
opens.sort_by(f64::total_cmp);
|
||||
let save = saves.get(2).copied().ok_or("no save measurements")?;
|
||||
let open = opens.get(2).copied().ok_or("no open measurements")?;
|
||||
outln!(" native {label}: save {save:.2} ms, open {open:.2} ms, {size} bytes, PDF {has_pdf}, compressed {compressed}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 1-minute load average (macOS / Linux), if available.
|
||||
#[cfg(not(windows))]
|
||||
fn load_average() -> Option<f64> {
|
||||
@@ -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<f64, String> {
|
||||
let ev = |kind, y: f64| PointerEvent { kind, pos: down + Vec2::new(0.0, y), mods: Mods::default(), backquote: false, 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<u64> = 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(), backquote: false, 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::<usize>;
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--deep" => want_deep = true,
|
||||
"--native-io" => want_native = true,
|
||||
"--artboards" => {
|
||||
artboards =
|
||||
Some(it.next().and_then(|v| v.parse().ok()).filter(|n| (1..=4).contains(n)).ok_or("--artboards needs a number from 1 to 4")?)
|
||||
}
|
||||
"--paths" => n = it.next().and_then(|v| v.parse().ok()).ok_or("--paths needs a number")?,
|
||||
other => return Err(format!("unknown perf option `{other}`")),
|
||||
}
|
||||
}
|
||||
if want_native && n > 50_000 {
|
||||
return Err("--native-io allows at most 50000 paths".into());
|
||||
}
|
||||
if want_native && want_deep {
|
||||
return Err("--native-io and --deep are separate measurement modes".into());
|
||||
}
|
||||
if artboards.is_some() && !want_native {
|
||||
return Err("--artboards requires --native-io".into());
|
||||
}
|
||||
let artboards = artboards.unwrap_or(1);
|
||||
let cores = std::thread::available_parallelism().map_or(1, |c| c.get());
|
||||
// The figure is the 1-minute load average, or on Windows the cores busy over one second.
|
||||
#[cfg(not(windows))]
|
||||
@@ -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::<Vec<_>>()).unwrap_err().contains(expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_share_leaves_out_idle_time() {
|
||||
// In one second four processors log 40,000,000 ticks of 100 ns of kernel and user time,
|
||||
|
||||
@@ -283,6 +283,22 @@ fn mcp_headless_over_stdio() {
|
||||
assert_eq!(replies[3]["result"]["content"][0]["type"], "image");
|
||||
}
|
||||
|
||||
/// `--safe-mode mcp` serves a headless session without plug-ins: it refuses `--connect`, and by
|
||||
/// default it does not connect to an app listening on the default address, which loads its own
|
||||
/// plug-ins.
|
||||
#[test]
|
||||
fn safe_mode_mcp_does_not_connect_to_a_running_app() {
|
||||
let out = Command::new(BIN).args(["--safe-mode", "mcp", "--connect", "127.0.0.1:9"]).env("VECTORCRAFT_NO_PREFS", "1").output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success() && err.contains("--safe-mode runs a headless session"), "{err}");
|
||||
// Something listening on the default address, as a running app does; a running app or another
|
||||
// program already holding it serves as well.
|
||||
let _app = std::net::TcpListener::bind(vectorcraft_mcp::DEFAULT_ADDR);
|
||||
let out = Command::new(BIN).args(["--safe-mode", "mcp"]).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success() && err.contains("MCP server on stdio (headless)"), "{err}");
|
||||
}
|
||||
|
||||
/// `mcp --automation-read-root` / `--automation-write-root` (#832): the flags are checked before the
|
||||
/// server starts, and the process then reads and writes only inside its roots.
|
||||
#[test]
|
||||
|
||||
@@ -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"]);
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
//! `window.vectorcraft`: the control channel for the page, as promises.
|
||||
//!
|
||||
//! `request`, `execute`, `commands`, `docInspect`, `uiInspect` and `screenshot` come from
|
||||
//! `craft-web-api` (storytold/craft-libs#413), the same in every Craft app; VectorCraft adds its own
|
||||
//! functions on the same object.
|
||||
//!
|
||||
//! The same JSON methods as the desktop control server (`docs/control-protocol.md`), so an agent
|
||||
//! driving VectorCraft in a browser tab (or an `<iframe>` in another app) uses the same commands as
|
||||
//! the CLI and the MCP server:
|
||||
//!
|
||||
//! ```js
|
||||
//! await vectorcraft.execute("object.rectangle", {x: 0, y: 0, width: 100, height: 50}) // engine command → its result
|
||||
//! await vectorcraft.execute("shape.rectangle", {x: 0, y: 0, width: 100, height: 50}) // engine command → its result
|
||||
//! await vectorcraft.request("ui.inspect") // control method → its result
|
||||
//! await vectorcraft.commands() // command list
|
||||
//! const {base64} = await vectorcraft.screenshot() // the canvas as PNG (base64)
|
||||
//! const {data} = await vectorcraft.screenshot() // the canvas as PNG (base64)
|
||||
//! await vectorcraft.openFile("logo.svg", bytes) // opened as a dropped file is
|
||||
//! vectorcraft.captureDownloads(true) // saves stay in the page…
|
||||
//! vectorcraft.files(); await vectorcraft.readFile("logo.png") // …to be read back
|
||||
@@ -17,21 +21,24 @@
|
||||
//! Results resolve with the method's `result`; errors reject with an `Error`.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::rc::Rc;
|
||||
use std::sync::mpsc::{Receiver, Sender, TryRecvError};
|
||||
|
||||
use craft_web_api::methods::Methods;
|
||||
use craft_web_api::page::{PageApi, Request};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_ui_egui::ControlRequest;
|
||||
use vectorcraft_ui_egui::{ControlRequest, ControlTicket as Ticket};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use wasm_bindgen_futures::{JsFuture, future_to_promise};
|
||||
|
||||
use crate::saved_files::SavedFiles;
|
||||
|
||||
use crate::web::Inbox;
|
||||
|
||||
type Waiting = (Receiver<Value>, js_sys::Function, js_sys::Function);
|
||||
|
||||
thread_local! {
|
||||
static TX: RefCell<Option<Sender<ControlRequest>>> = const { RefCell::new(None) };
|
||||
static WAITING: RefCell<Vec<Waiting>> = const { RefCell::new(Vec::new()) };
|
||||
static CTX: RefCell<Option<egui::Context>> = const { RefCell::new(None) };
|
||||
static INBOX: RefCell<Option<Inbox>> = const { RefCell::new(None) };
|
||||
static CAPTURE: Cell<bool> = const { Cell::new(false) };
|
||||
@@ -69,77 +76,96 @@ fn to_js(v: &Value) -> JsValue {
|
||||
js_sys::JSON::parse(&v.to_string()).unwrap_or(JsValue::NULL)
|
||||
}
|
||||
|
||||
fn from_js(v: &JsValue) -> Value {
|
||||
if v.is_undefined() || v.is_null() {
|
||||
return json!({});
|
||||
/// A reply as a promise outcome: the `result`, or an `Error` carrying the `error`.
|
||||
fn outcome(reply: &Value) -> Result<JsValue, JsValue> {
|
||||
if reply.get("ok").and_then(Value::as_bool) == Some(true) {
|
||||
Ok(to_js(reply.get("result").unwrap_or(&Value::Null)))
|
||||
} else {
|
||||
Err(js_sys::Error::new(reply.get("error").and_then(Value::as_str).unwrap_or("error")).into())
|
||||
}
|
||||
js_sys::JSON::stringify(v).ok().and_then(|s| s.as_string()).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or(json!({}))
|
||||
}
|
||||
|
||||
/// Settle the promises of answered requests (called every frame).
|
||||
pub fn poll_replies() {
|
||||
WAITING.with(|w| {
|
||||
w.borrow_mut().retain(|(rx, resolve, reject)| match rx.try_recv() {
|
||||
Ok(v) => {
|
||||
if v.get("ok").and_then(Value::as_bool) == Some(true) {
|
||||
let _ = resolve.call1(&JsValue::NULL, &to_js(v.get("result").unwrap_or(&Value::Null)));
|
||||
} else {
|
||||
let msg = v.get("error").and_then(Value::as_str).unwrap_or("error").to_string();
|
||||
let _ = reject.call1(&JsValue::NULL, &js_sys::Error::new(&msg));
|
||||
}
|
||||
false
|
||||
/// How often a waiting call looks for the app's reply, in milliseconds (about a frame).
|
||||
const POLL_MS: i32 = 16;
|
||||
|
||||
/// A queued control request whose reply has not arrived. Dropping it before the reply (the page's
|
||||
/// timeout fired) gives the request up if the app has not started it, so the app never runs it late.
|
||||
struct Waiting {
|
||||
reply: Receiver<Value>,
|
||||
ticket: Ticket,
|
||||
answered: bool,
|
||||
}
|
||||
|
||||
impl Waiting {
|
||||
/// The app's reply once it has answered or gone away; `None` while the request is waiting.
|
||||
fn poll(&mut self) -> Option<Value> {
|
||||
match self.reply.try_recv() {
|
||||
Ok(reply) => {
|
||||
self.answered = true;
|
||||
Some(reply)
|
||||
}
|
||||
Err(TryRecvError::Empty) => true,
|
||||
Err(TryRecvError::Empty) => None,
|
||||
Err(TryRecvError::Disconnected) => {
|
||||
let _ = reject.call1(&JsValue::NULL, &js_sys::Error::new("request dropped"));
|
||||
false
|
||||
self.answered = true;
|
||||
Some(json!({"ok": false, "error": "request dropped"}))
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn request(method: &str, params: Value) -> js_sys::Promise {
|
||||
let method = method.to_string();
|
||||
let p = js_sys::Promise::new(&mut |resolve, reject| {
|
||||
let (req, rx) = ControlRequest::new(method.clone(), params.clone());
|
||||
let sent = TX.with(|t| t.borrow().as_ref().is_some_and(|tx| tx.send(req).is_ok()));
|
||||
if sent {
|
||||
WAITING.with(|w| w.borrow_mut().push((rx, resolve, reject)));
|
||||
} else {
|
||||
let _ = reject.call1(&JsValue::NULL, &js_sys::Error::new("VectorCraft is not running yet"));
|
||||
impl Drop for Waiting {
|
||||
fn drop(&mut self) {
|
||||
if !self.answered {
|
||||
self.ticket.give_up();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Queue a control request for the app and wait for its reply, as the protocol's `{ok, result}` /
|
||||
/// `{ok: false, error}` object.
|
||||
fn send(method: &str, params: Value) -> Pin<Box<dyn Future<Output = Value>>> {
|
||||
let (req, rx) = ControlRequest::new(method, params);
|
||||
let ticket = req.ticket();
|
||||
let sent = TX.with(|t| t.borrow().as_ref().is_some_and(|tx| tx.send(req).is_ok()));
|
||||
if !sent {
|
||||
return Box::pin(async { json!({"ok": false, "error": "VectorCraft is not running yet"}) });
|
||||
}
|
||||
repaint();
|
||||
let mut waiting = Waiting { reply: rx, ticket, answered: false };
|
||||
Box::pin(async move {
|
||||
loop {
|
||||
if let Some(reply) = waiting.poll() {
|
||||
return reply;
|
||||
}
|
||||
sleep(POLL_MS).await;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn sleep(ms: i32) {
|
||||
let promise = js_sys::Promise::new(&mut |resolve, _| {
|
||||
if let Some(window) = web_sys::window() {
|
||||
let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
|
||||
}
|
||||
});
|
||||
repaint();
|
||||
p
|
||||
let _ = JsFuture::from(promise).await;
|
||||
}
|
||||
|
||||
fn set_fn(obj: &js_sys::Object, name: &str, f: JsValue) -> Result<(), JsValue> {
|
||||
js_sys::Reflect::set(obj, &name.into(), &f).map(|_| ())
|
||||
}
|
||||
|
||||
/// Install `window.vectorcraft`.
|
||||
/// Install `window.vectorcraft`: the crate's functions, then VectorCraft's own (`inspect` is its
|
||||
/// `ui.inspect`).
|
||||
pub fn install() -> Result<(), JsValue> {
|
||||
let obj = js_sys::Object::new();
|
||||
let request: Request = Rc::new(|method, params| send(&method, params));
|
||||
Rc::new(PageApi::new("vectorcraft", Methods::default(), request)).install()?;
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let obj: js_sys::Object = js_sys::Reflect::get(&window, &"vectorcraft".into())?.unchecked_into();
|
||||
set_fn(
|
||||
&obj,
|
||||
"request",
|
||||
Closure::<dyn Fn(String, JsValue) -> js_sys::Promise>::new(|method: String, params: JsValue| request(&method, from_js(¶ms)))
|
||||
.into_js_value(),
|
||||
)?;
|
||||
set_fn(
|
||||
&obj,
|
||||
"execute",
|
||||
Closure::<dyn Fn(String, JsValue) -> js_sys::Promise>::new(|command: String, params: JsValue| {
|
||||
request("engine.execute", json!({"command": command, "params": from_js(¶ms)}))
|
||||
})
|
||||
.into_js_value(),
|
||||
)?;
|
||||
set_fn(&obj, "commands", Closure::<dyn Fn() -> js_sys::Promise>::new(|| request("engine.commands", json!({}))).into_js_value())?;
|
||||
set_fn(&obj, "inspect", Closure::<dyn Fn() -> js_sys::Promise>::new(|| request("ui.inspect", json!({}))).into_js_value())?;
|
||||
set_fn(
|
||||
&obj,
|
||||
"screenshot",
|
||||
Closure::<dyn Fn(JsValue) -> js_sys::Promise>::new(|params: JsValue| request("ui.screenshot", from_js(¶ms))).into_js_value(),
|
||||
"inspect",
|
||||
Closure::<dyn Fn() -> js_sys::Promise>::new(|| future_to_promise(async { outcome(&send("ui.inspect", json!({})).await) })).into_js_value(),
|
||||
)?;
|
||||
set_fn(
|
||||
&obj,
|
||||
@@ -178,7 +204,5 @@ pub fn install() -> Result<(), JsValue> {
|
||||
})
|
||||
.into_js_value(),
|
||||
)?;
|
||||
let w = web_sys::window().ok_or("no window")?;
|
||||
js_sys::Reflect::set(&w, &"vectorcraft".into(), &obj)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -27,6 +27,19 @@ pub(crate) fn kept_from_browser(key: &str, code: &str, modifiers: Modifiers, alt
|
||||
vectorcraft_ui_egui::shortcuts::runs_a_shortcut(key, code, modifiers)
|
||||
}
|
||||
|
||||
/// Leave a paste to its Paste event (#5555). eframe's web runner reports a Cmd+V press both as the
|
||||
/// key press and, with the clipboard's text, as a Paste event (the browser's `paste` comes in the
|
||||
/// same task as the `keydown`, so both are in one frame's input); the app pastes on each, as egui's
|
||||
/// window integration sends only the Paste. With a Paste in `events`, the paste key's press is
|
||||
/// dropped; its release stays, so the paste chord is still followed (`PasteChord`). A Cmd+V without
|
||||
/// a Paste (a clipboard with no text) keeps its press.
|
||||
pub(crate) fn drop_paste_key_presses(events: &mut Vec<egui::Event>) {
|
||||
if !events.iter().any(|e| matches!(e, egui::Event::Paste(_))) {
|
||||
return;
|
||||
}
|
||||
events.retain(|e| !matches!(e, egui::Event::Key { key: Key::V, pressed: true, modifiers, .. } if modifiers.command));
|
||||
}
|
||||
|
||||
/// The modifiers of a key event as eframe reports them to egui (its `modifiers_from_kb_event`).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn modifiers(e: &web_sys::KeyboardEvent) -> Modifiers {
|
||||
@@ -115,4 +128,31 @@ mod tests {
|
||||
assert!(!kept_from_browser("ż", "KeyZ", ctrl_alt, true));
|
||||
assert!(!kept_from_browser("}", "Digit0", ctrl_alt, true));
|
||||
}
|
||||
|
||||
fn key(key: Key, pressed: bool, modifiers: Modifiers) -> egui::Event {
|
||||
egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paste_chord_pastes_once() {
|
||||
// Cmd+V and Cmd+Shift+V (Paste in Place): the press goes, the Paste and the release stay.
|
||||
for mods in [cmd(), cmd() | Modifiers::SHIFT] {
|
||||
let mut events = vec![key(Key::V, true, mods), egui::Event::Paste("<svg/>".into()), key(Key::V, false, mods)];
|
||||
drop_paste_key_presses(&mut events);
|
||||
assert_eq!(events, vec![egui::Event::Paste("<svg/>".into()), key(Key::V, false, mods)], "{mods:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_without_a_paste_stay() {
|
||||
// No text on the clipboard: no Paste event, so the press is the paste chord's only report.
|
||||
let mut events = vec![key(Key::V, true, cmd()), key(Key::V, false, cmd())];
|
||||
drop_paste_key_presses(&mut events);
|
||||
assert_eq!(events.len(), 2);
|
||||
// Typing V, and other chords, beside a paste.
|
||||
let typed = vec![key(Key::V, true, Modifiers::NONE), key(Key::C, true, cmd()), egui::Event::Paste("a".into())];
|
||||
let mut events = typed.clone();
|
||||
drop_paste_key_presses(&mut events);
|
||||
assert_eq!(events, typed);
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use egui::{Event, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase};
|
||||
use vectorcraft_ui_egui::stylus::{PenSample, StylusFeed};
|
||||
use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed};
|
||||
use vectorcraft_ui_egui::touch::{self, Source};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use wasm_bindgen::JsCast as _;
|
||||
@@ -95,7 +95,7 @@ impl Pointers {
|
||||
|
||||
/// A pen moved or pressed with `pressure`, with the end it last pressed with.
|
||||
fn pen_sample(&self, pressure: f32) {
|
||||
self.stylus.set_sample(Some(PenSample { pressure, eraser: self.eraser }));
|
||||
self.stylus.set_sample(Some(PenSample { pressure, eraser: self.eraser, pose: PenPose::default() }));
|
||||
}
|
||||
|
||||
fn touch(&mut self, device: TouchDeviceId, id: i32, phase: TouchPhase, pos: Pos2, force: Option<f32>) {
|
||||
|
||||
@@ -370,7 +370,6 @@ impl eframe::App for WebShell {
|
||||
}
|
||||
let Some(app) = &mut self.app else { return };
|
||||
app.tick(ctx);
|
||||
crate::api::poll_replies();
|
||||
app.finish_ime_logic(ctx);
|
||||
}
|
||||
|
||||
@@ -378,6 +377,8 @@ impl eframe::App for WebShell {
|
||||
/// shared input hook before egui runs.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
raw.events.extend(self.host.pointers.borrow_mut().take());
|
||||
// A Cmd+V comes as its key and as a Paste: one paste (#5555).
|
||||
crate::keys::drop_paste_key_presses(&mut raw.events);
|
||||
if let Some(app) = &mut self.app {
|
||||
app.raw_input_hook(ctx, raw);
|
||||
}
|
||||
@@ -421,7 +422,6 @@ impl eframe::App for WebShell {
|
||||
}
|
||||
app.ui(ui);
|
||||
}
|
||||
crate::api::poll_replies();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ wgpu = ["eframe/wgpu", "dep:winsafe"]
|
||||
accessibility = ["eframe/accesskit"]
|
||||
|
||||
[dependencies]
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] }
|
||||
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
|
||||
vectorcraft-ui-egui = { workspace = true }
|
||||
vectorcraft-text = { workspace = true }
|
||||
# Shared across the Craft suite: decides who draws the window frame per desktop (compositor vs app)
|
||||
@@ -56,8 +56,9 @@ pollster = "1"
|
||||
# `GetPointerPenInfo`, which it uses to read the pen's pressure and which end of the pen is down.
|
||||
# Win32_System_Threading has `GetProcessAffinityMask`, which src/windows_cores.rs uses to count the
|
||||
# cores the process may run on. Win32_UI_Input_KeyboardAndMouse has `GetKeyState`, which
|
||||
# src/caps_lock.rs uses to read whether Caps Lock is on.
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
|
||||
# src/caps_lock.rs uses to read whether Caps Lock is on. Win32_System_Registry has `RegGetValueW`,
|
||||
# which src/host_services.rs uses to read the path PhotoCraft registers under App Paths.
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
|
||||
# The renderer's worker count follows those cores (src/windows_cores.rs).
|
||||
vectorcraft-render = { workspace = true }
|
||||
|
||||
@@ -118,6 +119,7 @@ zbus = "=5.19.0"
|
||||
winresource = "0.1"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
# Bound socket buffers in real loopback transport deadline regressions.
|
||||
socket2 = { workspace = true }
|
||||
# src/portal_save.rs's tests build and read the portal's D-Bus values on every system.
|
||||
|
||||
@@ -8,6 +8,7 @@ use super::windows_stylus;
|
||||
use super::{App, VectorcraftApp, file_access, window};
|
||||
#[cfg(target_os = "macos")]
|
||||
use super::{mac_menu, mac_window, open_documents};
|
||||
use vectorcraft_ui_egui::dialogs::safe_mode;
|
||||
|
||||
/// The parts of [`App::raw_input_hook`] that every window needs, for the OS windows of floating
|
||||
/// panels: a click or Escape that closes the macOS menu bar's open menu, and the pen barrel
|
||||
@@ -51,6 +52,9 @@ impl eframe::App for App {
|
||||
// A pen contact with the barrel button held presses the secondary button (Windows Ink).
|
||||
#[cfg(windows)]
|
||||
windows_stylus::raw_input_hook(raw);
|
||||
// The characters Alt + keypad codes typed (#5108).
|
||||
#[cfg(windows)]
|
||||
super::windows_alt_codes::raw_input_hook(raw);
|
||||
file_access::unconfined(|| self.app.raw_input_hook(ctx, raw));
|
||||
// A mouse-up that never reached the window (#4326) is delivered once AppKit reports
|
||||
// that no mouse button is down.
|
||||
@@ -110,18 +114,35 @@ impl App {
|
||||
vectorcraft_ui_egui::background::wait_all(&mut self.app);
|
||||
return;
|
||||
}
|
||||
// An app that stays in Safe Mode leaves later launches to start their own app with plug-ins.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
if safe_mode::staying_on(&self.app) {
|
||||
single_instance::resign();
|
||||
}
|
||||
// Files from the Finder and the Dock (macOS) or from later launches (#4892) wait while a file
|
||||
// dialog is open: what asked for it runs again on its document when it answers.
|
||||
if !self.app.file_dialog_open() {
|
||||
// dialog is open: what asked for it runs again on its document when it answers. They also
|
||||
// wait for the choice about a stopped plug-in, so they open after the plug-ins it loads, as
|
||||
// do the command line's files held back for it. Files later launches handed over before the
|
||||
// choice ended in Safe Mode open in a new app with plug-ins.
|
||||
if !self.app.file_dialog_open() && !safe_mode::choosing(&self.app) {
|
||||
let held = std::mem::take(&mut self.held_files);
|
||||
#[cfg(target_os = "macos")]
|
||||
let files = open_documents::take();
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let files = single_instance::take();
|
||||
let files = single_instance::take_for_frame(safe_mode::staying_on(&self.app), single_instance::launch_with_plug_ins);
|
||||
if !files.is_empty() {
|
||||
bring_window_forward(ctx);
|
||||
}
|
||||
open_files(&mut self.app, held);
|
||||
open_files(&mut self.app, files);
|
||||
}
|
||||
let (now, zoom) = (ctx.input(|i| i.time), ctx.zoom_factor());
|
||||
if let Some(w) = &self.winit_window
|
||||
&& window::monitors_due(self.monitors_listed, now, zoom)
|
||||
{
|
||||
self.app.services.dock_monitors = window::dock_monitors(w, zoom);
|
||||
self.monitors_listed = Some((now, zoom));
|
||||
}
|
||||
self.app.tick(ctx);
|
||||
if self.pending_maximize {
|
||||
if let Some(w) = &self.winit_window {
|
||||
@@ -141,13 +162,15 @@ impl App {
|
||||
/// On macOS with accessibility, end the process once the app has saved what it keeps on quitting,
|
||||
/// before eframe tears the window down (#661). AccessKit then gives the window's content view back
|
||||
/// its own class, which AppKit's Touch Bar support was observing it under, and AppKit aborts the
|
||||
/// app as it quits on Macs with a Touch Bar. Nothing after the window is needed on a normal quit.
|
||||
/// app as it quits on Macs with a Touch Bar. On a normal quit, only the launch marker is needed
|
||||
/// after the window, so it is ended here as `main` ends it after the window on other platforms.
|
||||
/// Not while the window is still starting up (`frames` below [`gpu::STARTUP_FRAMES`]): a graphics
|
||||
/// failure then starts the app again on another adapter (#651).
|
||||
#[allow(unused_variables)]
|
||||
fn end_before_teardown(frames: u64) {
|
||||
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
|
||||
if frames >= gpu::STARTUP_FRAMES {
|
||||
safe_mode::end_launch();
|
||||
log::info!("quitting");
|
||||
log::logger().flush();
|
||||
std::process::exit(0);
|
||||
@@ -162,6 +185,16 @@ pub(crate) fn bring_window_forward(ctx: &egui::Context) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
|
||||
}
|
||||
|
||||
/// Open the command line's `files` now, or, while the choice about a stopped plug-in is up
|
||||
/// ([`safe_mode::choosing`]), return them to open once it is made, with the plug-ins it loads.
|
||||
pub(crate) fn open_or_hold(app: &mut VectorcraftApp, files: Vec<String>) -> Vec<String> {
|
||||
if safe_mode::choosing(app) {
|
||||
return files;
|
||||
}
|
||||
open_files(app, files);
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Open files handed to the app (command line, macOS Finder and Dock, later launches) as documents. A file that
|
||||
/// can't be opened is reported to the user and on stderr; the others still open.
|
||||
pub(crate) fn open_files(app: &mut VectorcraftApp, files: Vec<String>) {
|
||||
|
||||
@@ -20,7 +20,7 @@ use std::io::{Cursor, Read};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vectorcraft_engine::cmd::clipboard::{BITMAP, EPS, FILE_HEAD, Flavour, PDF, PNG, SVG, TEXT, file_flavour};
|
||||
use vectorcraft_ui_egui::SystemClipboard;
|
||||
use vectorcraft_ui_egui::{ClipboardRead, SystemClipboard};
|
||||
|
||||
/// This platform's system clipboard. On Linux, `window`'s Wayland connection carries text where
|
||||
/// arboard can't open (GNOME has no data-control protocol, a Flatpak there no X11).
|
||||
@@ -157,6 +157,10 @@ fn copied_file(paths: Vec<PathBuf>, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
None if vectorcraft_engine::file_access::current().is_none() => {}
|
||||
None => return None,
|
||||
}
|
||||
// A device or pipe may never end: only a regular file is read whole.
|
||||
if !std::fs::metadata(&path).ok()?.is_file() {
|
||||
return None;
|
||||
}
|
||||
let mut head = Vec::with_capacity(FILE_HEAD);
|
||||
std::fs::File::open(&path).ok()?.take(FILE_HEAD as u64).read_to_end(&mut head).ok()?;
|
||||
let mime = file_flavour(&path.to_string_lossy(), &head, mimes)?;
|
||||
@@ -172,7 +176,7 @@ mod win {
|
||||
use clipboard_win::{formats, options::NoClear, raw};
|
||||
|
||||
use super::{
|
||||
BITMAP, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, text_of, windows_formats,
|
||||
BITMAP, ClipboardRead, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, windows_formats,
|
||||
};
|
||||
|
||||
/// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the
|
||||
@@ -206,8 +210,6 @@ mod win {
|
||||
pub struct Clipboard {
|
||||
/// The clipboard's sequence number right after our last write.
|
||||
seq: Option<NonZeroU32>,
|
||||
/// The text of our last write.
|
||||
text: Option<String>,
|
||||
}
|
||||
|
||||
impl SystemClipboard for Clipboard {
|
||||
@@ -238,21 +240,26 @@ mod win {
|
||||
}
|
||||
}
|
||||
self.seq = raw::seq_num();
|
||||
self.text = text_of(flavours);
|
||||
result
|
||||
}
|
||||
|
||||
fn holds_ours(&mut self) -> bool {
|
||||
if self.seq.is_some() && raw::seq_num() == self.seq {
|
||||
return true;
|
||||
}
|
||||
// A clipboard manager may have copied our data again as its own.
|
||||
let Some(ours) = self.text.as_deref() else { return false };
|
||||
let Ok(_open) = clipboard_win::Clipboard::new_attempts(10) else { return false };
|
||||
read_one(TEXT).is_some_and(|f| f.data == ours.as_bytes())
|
||||
// The same text copied later by another app is a different clipboard entry. A
|
||||
// clipboard manager that republishes our data is also a new entry.
|
||||
self.seq.is_some() && raw::seq_num() == self.seq
|
||||
}
|
||||
|
||||
fn change_count(&mut self) -> Option<u64> {
|
||||
raw::seq_num().map(|n| u64::from(n.get()))
|
||||
}
|
||||
|
||||
fn read(&mut self, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
self.read_deferred(mimes)?.flavour()
|
||||
}
|
||||
|
||||
/// A device-independent bitmap is copied off the clipboard here and decoded and encoded
|
||||
/// as PNG by the work that comes back.
|
||||
fn read_deferred(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
|
||||
let mut files = vec![];
|
||||
{
|
||||
let _open = clipboard_win::Clipboard::new_attempts(10).ok()?;
|
||||
@@ -260,7 +267,7 @@ mod win {
|
||||
let _ = raw::get_file_list_path(&mut files);
|
||||
}
|
||||
// The files are read with the clipboard closed again, not keeping other apps waiting.
|
||||
copied_file(files, mimes).or_else(|| {
|
||||
copied_file(files, mimes).map(ClipboardRead::Now).or_else(|| {
|
||||
let _open = clipboard_win::Clipboard::new_attempts(10).ok()?;
|
||||
mimes.iter().find_map(|m| read_one(m))
|
||||
})
|
||||
@@ -284,16 +291,28 @@ mod win {
|
||||
})
|
||||
}
|
||||
|
||||
/// One flavour, while the clipboard is open.
|
||||
fn read_one(mime: &'static str) -> Option<Flavour> {
|
||||
/// A device-independent bitmap as a PNG flavour.
|
||||
fn dib_png(dib: &[u8]) -> Option<Flavour> {
|
||||
png_flavour(&dib_image(dib)?)
|
||||
}
|
||||
|
||||
/// Copy both bitmap formats while the clipboard is open, then decode them in preference order.
|
||||
pub(super) fn read_dibs(mut get: impl FnMut(u32) -> Option<Vec<u8>>) -> Option<ClipboardRead> {
|
||||
let dibs: Vec<_> = DIBS.into_iter().filter_map(&mut get).collect();
|
||||
(!dibs.is_empty()).then_some(ClipboardRead::Later(Box::new(move || dibs.iter().find_map(|dib| dib_png(dib)))))
|
||||
}
|
||||
|
||||
/// One flavour, while the clipboard is open. A device-independent bitmap is copied here, and
|
||||
/// the work that comes back decodes each captured format in preference order.
|
||||
fn read_one(mime: &'static str) -> Option<ClipboardRead> {
|
||||
let mut data = vec![];
|
||||
let mime = match mime {
|
||||
BITMAP if read_registered(PNG, &mut data) => PNG,
|
||||
BITMAP => {
|
||||
return DIBS.into_iter().find_map(|id| {
|
||||
data.clear();
|
||||
raw::get_vec(id, &mut data).ok()?;
|
||||
png_flavour(&dib_image(&data)?)
|
||||
return read_dibs(|id| {
|
||||
let mut dib = vec![];
|
||||
raw::get_vec(id, &mut dib).ok()?;
|
||||
Some(dib)
|
||||
});
|
||||
}
|
||||
TEXT => {
|
||||
@@ -309,7 +328,7 @@ mod win {
|
||||
{
|
||||
data.truncate(end);
|
||||
}
|
||||
(!data.is_empty()).then_some(Flavour { mime, data })
|
||||
(!data.is_empty()).then_some(ClipboardRead::Now(Flavour { mime, data }))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -322,7 +341,7 @@ mod portable {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::{BITMAP, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of};
|
||||
use super::{BITMAP, ClipboardRead, Flavour, PNG, SystemClipboard, TEXT, copied_file, decode_png, png_flavour, text_of};
|
||||
|
||||
/// What our last write put on the clipboard.
|
||||
enum Ours {
|
||||
@@ -580,22 +599,27 @@ mod portable {
|
||||
}
|
||||
|
||||
fn read(&mut self, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
self.read_deferred(mimes)?.flavour()
|
||||
}
|
||||
|
||||
/// arboard's image is read here and encoded as PNG by the work that comes back.
|
||||
fn read_deferred(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
|
||||
let cb = self.cb(Asker::User).ok()?;
|
||||
if let Some(f) = copied_file(cb.file_list(), mimes) {
|
||||
return Some(f);
|
||||
return Some(ClipboardRead::Now(f));
|
||||
}
|
||||
mimes.iter().find_map(|m| {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(f) = super::mac::read(m) {
|
||||
return Some(f);
|
||||
return Some(ClipboardRead::Now(f));
|
||||
}
|
||||
match *m {
|
||||
TEXT => cb.get_text().ok().filter(|t| !t.is_empty()).map(|t| Flavour { mime: TEXT, data: t.into_bytes() }),
|
||||
TEXT => cb.get_text().ok().filter(|t| !t.is_empty()).map(|t| ClipboardRead::Now(Flavour { mime: TEXT, data: t.into_bytes() })),
|
||||
BITMAP => {
|
||||
let img = cb.get_image().ok()?;
|
||||
let rgba =
|
||||
image::RgbaImage::from_raw(u32::try_from(img.width).ok()?, u32::try_from(img.height).ok()?, img.bytes.into_owned())?;
|
||||
png_flavour(&rgba)
|
||||
let (width, height) = (u32::try_from(img.width).ok()?, u32::try_from(img.height).ok()?);
|
||||
let bytes = img.bytes.into_owned();
|
||||
Some(ClipboardRead::Later(Box::new(move || png_flavour(&image::RgbaImage::from_raw(width, height, bytes)?))))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
@@ -954,10 +978,17 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
fn dir(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("vectorcraft-clipboard-{name}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
fn dir(name: &str) -> tempfile::TempDir {
|
||||
tempfile::Builder::new().prefix(&format!("vectorcraft-clipboard-{name}-")).tempdir().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_directory_is_removed_when_its_handle_is_dropped() {
|
||||
let dir = dir("cleanup");
|
||||
let path = dir.path().to_path_buf();
|
||||
assert!(path.exists());
|
||||
drop(dir);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
fn png(w: u32, h: u32) -> Vec<u8> {
|
||||
@@ -969,12 +1000,12 @@ mod tests {
|
||||
#[test]
|
||||
fn the_first_copied_file_that_is_art_pastes() {
|
||||
let d = dir("art");
|
||||
let (notes, red, art) = (d.join("notes.txt"), d.join("red image.png"), d.join("art.svg"));
|
||||
let (notes, red, art) = (d.path().join("notes.txt"), d.path().join("red image.png"), d.path().join("art.svg"));
|
||||
std::fs::write(¬es, "not art").unwrap();
|
||||
std::fs::write(&red, png(3, 2)).unwrap();
|
||||
std::fs::write(&art, "<svg xmlns=\"http://www.w3.org/2000/svg\"/>").unwrap();
|
||||
// Missing files, folders and text are skipped.
|
||||
let f = copied_file(vec![d.join("gone.png"), d.clone(), notes.clone(), red.clone(), art.clone()], &PASTE_ORDER).unwrap();
|
||||
let f = copied_file(vec![d.path().join("gone.png"), d.path().to_path_buf(), notes.clone(), red.clone(), art.clone()], &PASTE_ORDER).unwrap();
|
||||
assert_eq!((f.mime, f.data), (PNG, png(3, 2)));
|
||||
assert_eq!(copied_file(vec![art.clone(), red.clone()], &PASTE_ORDER).map(|f| f.mime), Some(SVG));
|
||||
// Only what Paste asks for.
|
||||
@@ -1008,7 +1039,8 @@ mod tests {
|
||||
/// An .eps file copied in a file manager pastes as EPS.
|
||||
#[test]
|
||||
fn a_copied_eps_file_pastes() {
|
||||
let eps = dir("eps").join("equation.eps");
|
||||
let d = dir("eps");
|
||||
let eps = d.path().join("equation.eps");
|
||||
std::fs::write(&eps, "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10 10\n0 0 10 10 rectfill\n").unwrap();
|
||||
assert_eq!(copied_file(vec![eps.clone()], &PASTE_ORDER).map(|f| f.mime), Some(EPS));
|
||||
assert!(copied_file(vec![eps], &[BITMAP, TEXT]).is_none());
|
||||
@@ -1016,7 +1048,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_crlf_left_by_the_uri_list_is_ignored() {
|
||||
let red = dir("crlf").join("red.png");
|
||||
let d = dir("crlf");
|
||||
let red = d.path().join("red.png");
|
||||
std::fs::write(&red, png(2, 2)).unwrap();
|
||||
let with_cr = PathBuf::from(format!("{}\r", red.display()));
|
||||
assert_eq!(copied_file(vec![with_cr], &PASTE_ORDER).map(|f| f.mime), Some(PNG));
|
||||
@@ -1057,6 +1090,28 @@ mod tests {
|
||||
img.pixels().map(|p| p.0).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn dib_fallback_captures_both_formats_before_decoding() {
|
||||
use clipboard_win::formats::{CF_DIB, CF_DIBV5};
|
||||
|
||||
let valid = dib(40, 1, 1, 32, 0, &[], &bgra(&[RED]));
|
||||
let mut captured = Vec::new();
|
||||
let read = win::read_dibs(|id| {
|
||||
captured.push(id);
|
||||
match id {
|
||||
CF_DIBV5 => Some(vec![40, 0, 0]),
|
||||
CF_DIB => Some(valid.clone()),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(captured, [CF_DIBV5, CF_DIB]);
|
||||
let flavour = read.flavour().unwrap();
|
||||
assert_eq!(flavour.mime, PNG);
|
||||
assert_eq!(pixels(&decode_png(&flavour.data).unwrap()), [RED]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_screenshot_dib_pastes_opaque_and_upright() {
|
||||
// CF_DIB as screenshots copy it: 32-bit BI_RGB, bottom row first, the fourth byte zero.
|
||||
|
||||
@@ -150,18 +150,16 @@ mod tests {
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn the_gpu_behind_a_device_number_comes_from_sysfs() -> std::io::Result<()> {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-dev-char-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let dir = tempfile::Builder::new().prefix("vectorcraft-dev-char-").tempdir()?;
|
||||
// /sys/dev/char/226:128 links to the render node, whose `device` is the PCI GPU.
|
||||
std::fs::create_dir_all(dir.join("226:128/device"))?;
|
||||
std::fs::write(dir.join("226:128/device/vendor"), "0x10de\n")?;
|
||||
std::fs::write(dir.join("226:128/device/device"), "0x25ac\n")?;
|
||||
std::fs::create_dir_all(dir.path().join("226:128/device"))?;
|
||||
std::fs::write(dir.path().join("226:128/device/vendor"), "0x10de\n")?;
|
||||
std::fs::write(dir.path().join("226:128/device/device"), "0x25ac\n")?;
|
||||
// A device that isn't a PCI GPU (a virtual one) has no ids.
|
||||
std::fs::create_dir_all(dir.join("226:0/device"))?;
|
||||
let render = super::pci_ids(&dir, makedev(226, 128));
|
||||
let virtual_gpu = super::pci_ids(&dir, makedev(226, 0));
|
||||
let missing = super::pci_ids(&dir, makedev(226, 1));
|
||||
std::fs::remove_dir_all(&dir)?;
|
||||
std::fs::create_dir_all(dir.path().join("226:0/device"))?;
|
||||
let render = super::pci_ids(dir.path(), makedev(226, 128));
|
||||
let virtual_gpu = super::pci_ids(dir.path(), makedev(226, 0));
|
||||
let missing = super::pci_ids(dir.path(), makedev(226, 1));
|
||||
assert_eq!(render, Some((0x10de, 0x25ac)));
|
||||
assert_eq!(virtual_gpu, None);
|
||||
assert_eq!(missing, None);
|
||||
|
||||
@@ -152,6 +152,7 @@ fn spawn_connection(
|
||||
|
||||
fn serve_socket(stream: TcpStream, timeouts: ConnectionTimeouts, handle: impl FnMut(String, Value) -> Option<Value>) {
|
||||
let Ok(read) = stream.try_clone() else { return };
|
||||
let closer = stream.try_clone().ok();
|
||||
let read = DeadlineReader::new(read, timeouts.idle, timeouts.line);
|
||||
// Replies reach the writer in [`REPLY_CHUNK`] pieces ([`write_line`]), so checking the remaining
|
||||
// budget costs one socket option call per piece, not one per JSON token.
|
||||
@@ -166,6 +167,33 @@ fn serve_socket(stream: TcpStream, timeouts: ConnectionTimeouts, handle: impl Fn
|
||||
},
|
||||
DeadlineWriter::begin_reply,
|
||||
);
|
||||
if let Some(s) = closer {
|
||||
close_gracefully(s);
|
||||
}
|
||||
}
|
||||
|
||||
/// How long [`close_gracefully`] waits for the peer to close its side.
|
||||
const CLOSE_DRAIN: Duration = Duration::from_secs(1);
|
||||
|
||||
/// The most [`close_gracefully`] reads from a peer that keeps sending.
|
||||
const MAX_DRAIN: usize = 1 << 20;
|
||||
|
||||
/// Ends a connection: no more replies (the peer reads them all, then end of stream), then what the
|
||||
/// peer still sends is read and dropped until it closes too, for at most [`CLOSE_DRAIN`] and
|
||||
/// [`MAX_DRAIN`] bytes. On Windows, dropping a socket with unread input resets the connection, and
|
||||
/// the reset can discard replies the peer has not read yet.
|
||||
fn close_gracefully(mut s: TcpStream) {
|
||||
// Each step is best effort: a peer that is already gone needs none of them.
|
||||
let _ = s.shutdown(std::net::Shutdown::Write);
|
||||
let _ = s.set_read_timeout(Some(CLOSE_DRAIN));
|
||||
let deadline = std::time::Instant::now() + CLOSE_DRAIN;
|
||||
let (mut buf, mut left) = ([0u8; 4096], MAX_DRAIN);
|
||||
while left > 0 && std::time::Instant::now() < deadline {
|
||||
match s.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => left = left.saturating_sub(n),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One parsed line.
|
||||
|
||||
@@ -58,7 +58,12 @@ fn idle_control_socket_releases_its_worker() {
|
||||
fn idle_expiry_closes_without_writing_a_line() {
|
||||
let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected"));
|
||||
let mut got = Vec::new();
|
||||
client.read_to_end(&mut got).unwrap();
|
||||
match client.read_to_end(&mut got) {
|
||||
// On Windows the server's close can reach the client as a reset.
|
||||
Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => {}
|
||||
Ok(_) => {}
|
||||
Err(e) => panic!("reading the idle connection: {e}"),
|
||||
}
|
||||
assert_eq!(String::from_utf8_lossy(&got), "", "the app wrote to an idle connection");
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
@@ -329,12 +334,13 @@ fn tcp_connection_is_closed_after_junk() {
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (s, _) = listener.accept().unwrap();
|
||||
let read = s.try_clone().unwrap();
|
||||
serve_lines(read, s, |_, _| Some(json!({"ok": true})));
|
||||
serve_socket(s, ConnectionTimeouts::default(), |_, _| Some(json!({"ok": true})));
|
||||
});
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(WAIT)).unwrap();
|
||||
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n{\"method\":\"y\"}\n").unwrap();
|
||||
// The server closes gracefully ([`close_gracefully`]): the client reads both replies and then
|
||||
// the end of the stream, not a reset.
|
||||
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n").unwrap();
|
||||
let mut text = String::new();
|
||||
c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection
|
||||
server.join().unwrap();
|
||||
|
||||
@@ -310,7 +310,7 @@ fn pci_ids(device_id: &str) -> Option<(u32, u32)> {
|
||||
let field = |key: &str| {
|
||||
device_id.split(['\\', '&']).find_map(|part| {
|
||||
let (name, hex) = part.split_at_checked(key.len())?;
|
||||
if name.eq_ignore_ascii_case(key) { u32::from_str_radix(hex, 16).ok() } else { None }
|
||||
if name.eq_ignore_ascii_case(key) && hex.bytes().all(|b| b.is_ascii_hexdigit()) { u32::from_str_radix(hex, 16).ok() } else { None }
|
||||
})
|
||||
};
|
||||
Some((field("VEN_")?, field("DEV_")?))
|
||||
@@ -753,13 +753,22 @@ enum FirstFrame {
|
||||
Shown,
|
||||
/// Overdue.
|
||||
Hung,
|
||||
/// Overdue, but the UI is still building the first frame: the app's own work (on a slow
|
||||
/// machine, or with antivirus reading every font file), not the adapter, which has been given
|
||||
/// nothing to show yet.
|
||||
Busy,
|
||||
}
|
||||
|
||||
/// The window's start after `frames` frames run, `since` its first frame was due.
|
||||
fn first_frame(frames: u64, since: Duration, minimized: bool) -> FirstFrame {
|
||||
/// The window's start after `frames` frames run, `since` its first frame was due and
|
||||
/// `since_built` the first frame's UI pass ended (`None` while it runs). A frame counts once its
|
||||
/// UI pass ends, before it is painted, so the adapter's time starts there: with no frame run, the
|
||||
/// UI thread is in the app's code, and starting again without the adapter wouldn't help (#5160).
|
||||
fn first_frame(frames: u64, since: Duration, since_built: Option<Duration>, minimized: bool) -> FirstFrame {
|
||||
if frames >= 2 || minimized {
|
||||
FirstFrame::Shown
|
||||
} else if since >= FIRST_FRAME_TIMEOUT {
|
||||
} else if frames == 0 {
|
||||
if since >= FIRST_FRAME_TIMEOUT { FirstFrame::Busy } else { FirstFrame::Wait }
|
||||
} else if since_built.unwrap_or(since) >= FIRST_FRAME_TIMEOUT {
|
||||
FirstFrame::Hung
|
||||
} else {
|
||||
FirstFrame::Wait
|
||||
@@ -767,18 +776,34 @@ fn first_frame(frames: u64, since: Duration, minimized: bool) -> FirstFrame {
|
||||
}
|
||||
|
||||
/// Watch the window's first frame from another thread: once it reaches the screen, clear the start
|
||||
/// from [`START_FILE`]; when it hasn't reached the screen [`FIRST_FRAME_TIMEOUT`] after the app was
|
||||
/// created ([`Startup::ready`]), start the app again without the adapter, as [`finish`] does for
|
||||
/// one that failed, and end this process, whose UI thread is stuck in the graphics driver.
|
||||
/// from [`START_FILE`]; when it hasn't reached the screen [`FIRST_FRAME_TIMEOUT`] after its UI pass
|
||||
/// ended, start the app again without the adapter, as [`finish`] does for one that failed, and end
|
||||
/// this process, whose UI thread is stuck in the graphics driver. A first frame still being built
|
||||
/// that long is waited for, with a note in the log.
|
||||
pub fn watch_first_frame(startup: Arc<Startup>) {
|
||||
let mut built: Option<Instant> = None;
|
||||
let mut noted = false;
|
||||
let watch = move || loop {
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
let Some(due) = startup.ready.get() else { continue };
|
||||
let ui = startup.ui.get();
|
||||
let frames = ui.map_or(0, egui::Context::cumulative_frame_nr);
|
||||
if frames >= 1 && built.is_none() {
|
||||
built = Some(Instant::now());
|
||||
}
|
||||
let minimized = ui.and_then(|c| c.input(|i| i.viewport().minimized)).unwrap_or(false);
|
||||
match first_frame(frames, due.elapsed(), minimized) {
|
||||
match first_frame(frames, due.elapsed(), built.map(|t| t.elapsed()), minimized) {
|
||||
FirstFrame::Wait => continue,
|
||||
FirstFrame::Busy => {
|
||||
if !noted {
|
||||
log::warn!(
|
||||
"the window's first frame is still being built after {}s: waiting for it (the app's work, not the graphics adapter)",
|
||||
FIRST_FRAME_TIMEOUT.as_secs()
|
||||
);
|
||||
noted = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
FirstFrame::Shown => {
|
||||
startup.presented();
|
||||
return;
|
||||
|
||||
@@ -242,8 +242,8 @@ fn internal_panels_are_edp_lvds_and_dsi_connectors() {
|
||||
/// PCI ids. Each GPU is listed once, the one with the panel as primary.
|
||||
#[test]
|
||||
fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<()> {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-drm-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let temp = tempfile::Builder::new().prefix("vectorcraft-drm-").tempdir()?;
|
||||
let dir = temp.path();
|
||||
let card = |name: &str, (vendor, device): (u32, u32)| -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir.join(name).join("device"))?;
|
||||
std::fs::write(dir.join(name).join("device/vendor"), format!("{vendor:#06x}\n"))?;
|
||||
@@ -262,11 +262,11 @@ fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<()
|
||||
connector("card1-DP-2", "connected")?;
|
||||
connector("card2-Virtual-1", "connected")?;
|
||||
std::fs::write(dir.join("renderD128"), "")?;
|
||||
let mut gpus = linux_display_gpus(&dir);
|
||||
let mut gpus = linux_display_gpus(dir);
|
||||
gpus.sort_by_key(|g| g.pci);
|
||||
assert_eq!(gpus, [primary(AMD_IGPU), monitor(NVIDIA_3090)]);
|
||||
assert!(linux_display_gpus(&dir.join("no such dir")).is_empty());
|
||||
std::fs::remove_dir_all(&dir)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -366,14 +366,19 @@ fn gpus_without_pci_ids_are_told_apart_by_name() {
|
||||
fn a_first_frame_that_never_reaches_the_screen_hangs_its_adapter() {
|
||||
let s = Duration::from_secs;
|
||||
// The second frame began: the first was presented.
|
||||
assert_eq!(first_frame(2, s(60), false), FirstFrame::Shown);
|
||||
// Still drawing (or presenting) the first frame: waited for, then given up on (#964).
|
||||
for frames in [0, 1] {
|
||||
assert_eq!(first_frame(frames, s(3), false), FirstFrame::Wait);
|
||||
assert_eq!(first_frame(frames, FIRST_FRAME_TIMEOUT, false), FirstFrame::Hung);
|
||||
}
|
||||
assert_eq!(first_frame(2, s(60), Some(s(1)), false), FirstFrame::Shown);
|
||||
// The first frame built and not yet presented: waited for, then given up on (#964), counting
|
||||
// from when its UI pass ended.
|
||||
assert_eq!(first_frame(1, s(3), Some(s(1)), false), FirstFrame::Wait);
|
||||
assert_eq!(first_frame(1, FIRST_FRAME_TIMEOUT, Some(FIRST_FRAME_TIMEOUT), false), FirstFrame::Hung);
|
||||
assert_eq!(first_frame(1, s(45), Some(s(5)), false), FirstFrame::Wait, "a first frame built slowly gets its full time to show");
|
||||
assert_eq!(first_frame(1, FIRST_FRAME_TIMEOUT, None, false), FirstFrame::Hung);
|
||||
// The first frame still being built: the app's work, not the adapter's (#5160).
|
||||
assert_eq!(first_frame(0, s(3), None, false), FirstFrame::Wait);
|
||||
assert_eq!(first_frame(0, FIRST_FRAME_TIMEOUT, None, false), FirstFrame::Busy);
|
||||
assert_eq!(first_frame(0, s(600), None, false), FirstFrame::Busy, "never a restart without an adapter");
|
||||
// A window minimized at the start may not draw again until restored.
|
||||
assert_eq!(first_frame(1, s(60), true), FirstFrame::Shown);
|
||||
assert_eq!(first_frame(1, s(60), Some(s(60)), true), FirstFrame::Shown);
|
||||
// A hung adapter is left out once, like one that failed.
|
||||
let skip = vec!["Dx12:10de:28a0".to_string()];
|
||||
assert_eq!(restart_without(true, 1, Some("Dx12:10de:28a0"), &skip), None);
|
||||
@@ -611,11 +616,26 @@ fn a_normal_exit_or_another_failure_does_not_restart() {
|
||||
/// A log folder of its own for each test, and the guard that keeps other tests from starting a
|
||||
/// program while it runs: the test releases the start file's lock and takes it again, and a child
|
||||
/// starting meanwhile would keep it held (`crate::no_spawns`).
|
||||
fn start_dir(tag: &str) -> (std::path::PathBuf, std::sync::RwLockReadGuard<'static, ()>) {
|
||||
struct TestDir(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
type Target = std::path::Path;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0.path()
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<std::path::Path> for TestDir {
|
||||
fn as_ref(&self) -> &std::path::Path {
|
||||
self.0.path()
|
||||
}
|
||||
}
|
||||
|
||||
fn start_dir(tag: &str) -> (TestDir, std::sync::RwLockReadGuard<'static, ()>) {
|
||||
let spawns = crate::no_spawns();
|
||||
let d = std::env::temp_dir().join(format!("vectorcraft-gpu-start-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
(d, spawns)
|
||||
let dir = tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap();
|
||||
(TestDir(dir), spawns)
|
||||
}
|
||||
|
||||
/// What a start in `dir` leaves out; it then ends without crashing.
|
||||
@@ -665,7 +685,6 @@ fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
|
||||
assert_eq!(left_out.adapters, ["Dx12:8086:3184"], "kept");
|
||||
assert_eq!(left_out.crash, None, "the note is shown once");
|
||||
third.ended();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A start whose first frame reached the screen, or that ended without crashing (a normal exit,
|
||||
@@ -688,7 +707,6 @@ fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
|
||||
assert!(finish(Ok(Ok(())), &first).is_ok());
|
||||
drop(first);
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The process ended while the adapters were being listed (wgpu's DX12 backend creates a
|
||||
@@ -716,7 +734,6 @@ fn a_crash_while_listing_lists_opengl_alone() {
|
||||
second.none_left();
|
||||
second.ended();
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` choose for a start whatever crashed before; when that
|
||||
@@ -737,7 +754,6 @@ fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
|
||||
explicit.picked(&c[0].key, &c[0].name, true);
|
||||
explicit.presented();
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default(), "a new driver shows the window");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A damaged record, a file that can't be opened and one another starting copy of the app holds
|
||||
@@ -772,10 +788,9 @@ fn a_damaged_or_unreadable_start_file_is_ignored() {
|
||||
assert_eq!(next_start(&dir, false).adapters, ["Dx12:8086:3184"]);
|
||||
|
||||
// A folder in the file's place.
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::remove_file(dir.join(START_FILE)).unwrap();
|
||||
std::fs::create_dir_all(dir.join(START_FILE)).unwrap();
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -805,3 +820,10 @@ fn crashes_are_forgotten_in_another_version_or_under_another_preference() {
|
||||
assert_eq!(record.crashed.len(), CRASHED_LIMIT);
|
||||
assert_eq!(record.crashed.last().map(|c| c.key.as_str()), Some("Dx12:10de:0013"));
|
||||
}
|
||||
|
||||
/// `u32::from_str_radix` accepts a leading `+`; a device id with one is not a PCI id.
|
||||
#[test]
|
||||
fn pci_ids_reject_a_sign_in_the_hex_digits() {
|
||||
assert_eq!(pci_ids("PCI\\VEN_+10DE&DEV_2204"), None);
|
||||
assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_+2204"), None);
|
||||
}
|
||||
@@ -44,19 +44,50 @@ macro_rules! dialog_settings {
|
||||
|
||||
dialog_settings!(rfd::FileDialog, rfd::AsyncFileDialog);
|
||||
|
||||
/// On Linux and the BSDs the dialog is GTK's or the desktop portal's, which match a file type's
|
||||
/// `*.ext` patterns case-sensitively.
|
||||
const CASE_SENSITIVE_FILTERS: bool =
|
||||
cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"));
|
||||
|
||||
/// The extensions an open dialog's filter is given for `exts`: with `any_case`, each extension
|
||||
/// that has a letter is followed by a pattern with each letter as a `[xX]` pair, so the filter for
|
||||
/// `dib` also lists `image.DIB` and `image.Dib`.
|
||||
fn open_extensions(exts: &[impl AsRef<str>], any_case: bool) -> Vec<String> {
|
||||
let mut out = Vec::with_capacity(exts.len() * 2);
|
||||
for e in exts {
|
||||
let e = e.as_ref();
|
||||
out.push(e.to_string());
|
||||
if any_case && e.chars().any(|c| c.is_ascii_alphabetic()) {
|
||||
out.push(
|
||||
e.chars()
|
||||
.map(|c| if c.is_ascii_alphabetic() { format!("[{}{}]", c.to_ascii_lowercase(), c.to_ascii_uppercase()) } else { c.to_string() })
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `d` set up for `request`: its title, file types, folder and suggested name.
|
||||
fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
let pick = match request {
|
||||
PickRequest::Open(pick) | PickRequest::Save(pick) => pick,
|
||||
PickRequest::OpenMany => {
|
||||
return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| {
|
||||
d.filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts)
|
||||
d.filter(
|
||||
vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name),
|
||||
&open_extensions(exts, CASE_SENSITIVE_FILTERS),
|
||||
)
|
||||
});
|
||||
}
|
||||
PickRequest::Folder => return d,
|
||||
};
|
||||
let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_));
|
||||
let d = pick.filters.iter().fold(d, |d, (name, exts)| {
|
||||
d.filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), exts)
|
||||
d.filter(
|
||||
vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()),
|
||||
&open_extensions(exts, any_case),
|
||||
)
|
||||
});
|
||||
let d = match &pick.folder {
|
||||
Some(folder) => d.folder(folder),
|
||||
@@ -151,6 +182,46 @@ fn reveal_command(path: &str) -> std::process::Command {
|
||||
c
|
||||
}
|
||||
|
||||
/// Read a whole file. A device or pipe may never end: only a regular file is read.
|
||||
fn read_file(path: &str) -> Result<Vec<u8>, String> {
|
||||
if !std::fs::metadata(path).map_err(|e| e.to_string())?.is_file() {
|
||||
return Err(format!("{path}: not a file"));
|
||||
}
|
||||
std::fs::read(path).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn read_file_refuses_what_is_not_a_regular_file() {
|
||||
assert!(read_file(&std::env::temp_dir().to_string_lossy()).is_err());
|
||||
#[cfg(unix)]
|
||||
assert!(read_file("/dev/zero").is_err());
|
||||
}
|
||||
|
||||
/// Read the first `max` bytes of a file (all of it when it is shorter), and nothing past them. Only
|
||||
/// a regular file is read.
|
||||
fn read_file_head(path: &str, max: usize) -> Result<Vec<u8>, String> {
|
||||
use std::io::Read;
|
||||
if !std::fs::metadata(path).map_err(|e| e.to_string())?.is_file() {
|
||||
return Err(format!("{path}: not a file"));
|
||||
}
|
||||
let mut out = vec![];
|
||||
std::fs::File::open(path).and_then(|f| f.take(max as u64).read_to_end(&mut out)).map_err(|e| e.to_string())?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn read_file_head_reads_no_more_than_it_is_asked_for() {
|
||||
use std::io::Write as _;
|
||||
let mut f = tempfile::Builder::new().prefix("vectorcraft-read-head-").tempfile().unwrap();
|
||||
f.write_all(b"0123456789").unwrap();
|
||||
let p = f.path().to_string_lossy();
|
||||
assert_eq!(read_file_head(&p, 4).unwrap(), b"0123");
|
||||
assert_eq!(read_file_head(&p, 20).unwrap(), b"0123456789", "a shorter file is read whole");
|
||||
assert!(read_file_head(&std::env::temp_dir().to_string_lossy(), 4).is_err(), "a folder is not read");
|
||||
}
|
||||
|
||||
/// Write a file the safe way: a failed write keeps the old file ([`fileio::write_atomic`]).
|
||||
fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string())
|
||||
@@ -227,13 +298,16 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
|
||||
// up its Format menu before the sheet begins (#866); rfd shows the others.
|
||||
PickRequest::Save(pick) => match mac_save_format::begin(window, &pick) {
|
||||
// The dialog thread blocks here until the sheet answers.
|
||||
Some(picked) => Box::pin(async move { picked.recv().unwrap_or_default() }),
|
||||
None => {
|
||||
Ok(mac_save_format::Begin::Shown(picked)) => Box::pin(async move { picked.recv().unwrap_or_default() }),
|
||||
Ok(mac_save_format::Begin::DeferToRfd) => {
|
||||
// Nothing is added to the sheet once rfd has begun it: an accessory view set then
|
||||
// made recent macOS versions dismiss the sheet at once (#1800).
|
||||
let picked = dialog.save_file();
|
||||
Box::pin(async move { picked.await.iter().map(path).collect() })
|
||||
}
|
||||
// AppKit returned nil for the panel. rfd uses the same `+savePanel` and would panic
|
||||
// on that nil; treat the pick as cancelled instead (#5980).
|
||||
Err(()) => Box::pin(async move { Vec::new() }),
|
||||
},
|
||||
PickRequest::Folder => {
|
||||
let picked = dialog.pick_folder();
|
||||
@@ -277,7 +351,9 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
// Windows reads it from the pen's pointer messages (`windows_stylus`).
|
||||
#[cfg(windows)]
|
||||
stylus: Some(windows_stylus::start()),
|
||||
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
|
||||
read: Some(Box::new(read_file)),
|
||||
// Load Actions… refuses a file over its size limit without reading all of it.
|
||||
read_head: Some(Box::new(read_file_head)),
|
||||
write: Some(Box::new(write_file)),
|
||||
exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())),
|
||||
// Background Save and Export write from a worker thread.
|
||||
@@ -300,6 +376,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
reveal: Some(Box::new(reveal)),
|
||||
// Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders.
|
||||
open_file: Some(Box::new(open_file)),
|
||||
// Edit Original of a raster image with Use System Defaults for Edit Original off (#5236).
|
||||
open_in_photocraft: Some(Box::new(open_in_photocraft)),
|
||||
pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())),
|
||||
// Sample Color from Screen: the system's color sampler.
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -334,3 +412,392 @@ fn open_file(path: &str) -> Result<(), String> {
|
||||
c.arg(path);
|
||||
c.spawn().map(|_| ()).map_err(|e| format!("can't open {path}: {e}"))
|
||||
}
|
||||
|
||||
/// Edit Original with Preferences › File Handling › Use System Defaults for Edit Original off
|
||||
/// (#5236): open the raster image `path` in PhotoCraft, found only where it installs
|
||||
/// ([`find_photocraft`]); `Ok(false)` when it isn't installed. PhotoCraft gets the path as its only
|
||||
/// argument and is never started through a shell.
|
||||
fn open_in_photocraft(path: &str) -> Result<bool, String> {
|
||||
explorer_safe(path)?;
|
||||
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(std::path::PathBuf::from);
|
||||
let Some(app) = find_photocraft(home.as_deref(), std::env::var_os("PATH").as_deref()) else { return Ok(false) };
|
||||
#[cfg(target_os = "macos")]
|
||||
let mut c = {
|
||||
let mut c = std::process::Command::new("open");
|
||||
c.arg("-a").arg(&app).arg(path);
|
||||
c
|
||||
};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let mut c = {
|
||||
let mut c = std::process::Command::new(&app);
|
||||
c.arg(path);
|
||||
c
|
||||
};
|
||||
// macOS: `open` returns once Launch Services has the request, so a short wait reports an app
|
||||
// it can't open (a folder named `.app` that isn't a bundle). The wait is capped so a stalled
|
||||
// `open` never holds the window: past it, the launch is left to run. Elsewhere the editor
|
||||
// itself runs: waiting would last until it closes.
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
const WAIT: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
let fail = |why: String| format!("can't open {path} in {}: {why}", app.display());
|
||||
let mut child = c.stderr(std::process::Stdio::piped()).spawn().map_err(|e| fail(e.to_string()))?;
|
||||
let started = std::time::Instant::now();
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) if status.success() => return Ok(true),
|
||||
Ok(Some(status)) => {
|
||||
let mut why = String::new();
|
||||
if let Some(mut err) = child.stderr.take() {
|
||||
// Best effort: without its message the exit status says why.
|
||||
let _ = std::io::Read::read_to_string(&mut err, &mut why);
|
||||
}
|
||||
let why = why.trim().to_string();
|
||||
return Err(fail(if why.is_empty() { status.to_string() } else { why }));
|
||||
}
|
||||
Ok(None) if started.elapsed() < WAIT => std::thread::sleep(std::time::Duration::from_millis(20)),
|
||||
Ok(None) => {
|
||||
// Reaped off the UI thread once it ends.
|
||||
std::thread::spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
return Ok(true);
|
||||
}
|
||||
Err(e) => return Err(fail(e.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
c.spawn().map(|_| true).map_err(|e| format!("can't open {path} in {}: {e}", app.display()))
|
||||
}
|
||||
|
||||
/// PhotoCraft where it is installed: the first of [`photocraft_candidates`] that is an application.
|
||||
pub(crate) fn find_photocraft(home: Option<&std::path::Path>, path_var: Option<&std::ffi::OsStr>) -> Option<std::path::PathBuf> {
|
||||
photocraft_candidates(home, path_var).into_iter().find(|p| check_app(p).is_ok())
|
||||
}
|
||||
|
||||
/// Where PhotoCraft may be installed: the Applications folders on macOS; on Windows where its
|
||||
/// installer puts it ([`windows_candidates`]); else a `photocraft` program on the `PATH`.
|
||||
pub(crate) fn photocraft_candidates(home: Option<&std::path::Path>, path_var: Option<&std::ffi::OsStr>) -> Vec<std::path::PathBuf> {
|
||||
if cfg!(target_os = "macos") {
|
||||
let mut v = vec![std::path::PathBuf::from("/Applications/PhotoCraft.app")];
|
||||
v.extend(home.map(|h| h.join("Applications/PhotoCraft.app")));
|
||||
return v;
|
||||
}
|
||||
let name = if cfg!(windows) { "photocraft.exe" } else { "photocraft" };
|
||||
let on_path = path_var.map(|p| std::env::split_paths(p).map(|dir| dir.join(name)).collect()).unwrap_or_default();
|
||||
if cfg!(windows) {
|
||||
let folders: Vec<std::path::PathBuf> = [
|
||||
std::env::var_os("LOCALAPPDATA").map(|d| std::path::PathBuf::from(d).join("Programs")),
|
||||
std::env::var_os("ProgramW6432").map(std::path::PathBuf::from),
|
||||
std::env::var_os("ProgramFiles").map(std::path::PathBuf::from),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect();
|
||||
return windows_candidates(registered_photocraft(), &folders, on_path);
|
||||
}
|
||||
on_path
|
||||
}
|
||||
|
||||
/// Windows: PhotoCraft's installer puts it in `ArtCraft\PhotoCraft` under a folder of
|
||||
/// `program_folders` (for the current user `%LOCALAPPDATA%\Programs`, for everyone Program Files)
|
||||
/// and registers its path under App Paths, which also covers a folder chosen in setup. So: the
|
||||
/// `registered` paths first, then those folders, then `on_path`.
|
||||
pub(crate) fn windows_candidates(
|
||||
registered: Vec<std::path::PathBuf>,
|
||||
program_folders: &[std::path::PathBuf],
|
||||
on_path: Vec<std::path::PathBuf>,
|
||||
) -> Vec<std::path::PathBuf> {
|
||||
let mut v = registered;
|
||||
for f in program_folders {
|
||||
let p = f.join("ArtCraft").join("PhotoCraft").join("photocraft.exe");
|
||||
if !v.contains(&p) {
|
||||
v.push(p);
|
||||
}
|
||||
}
|
||||
v.extend(on_path);
|
||||
v
|
||||
}
|
||||
|
||||
/// The paths PhotoCraft's installer registers under App Paths, for the current user and then for
|
||||
/// everyone.
|
||||
#[cfg(windows)]
|
||||
fn registered_photocraft() -> Vec<std::path::PathBuf> {
|
||||
use windows::Win32::System::Registry::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
|
||||
[HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE]
|
||||
.into_iter()
|
||||
.filter_map(|hive| registry_default_path(hive, r"Software\Microsoft\Windows\CurrentVersion\App Paths\photocraft.exe"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn registered_photocraft() -> Vec<std::path::PathBuf> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// The default `REG_SZ` value of `subkey` under `hive` as a path ([`registered_path`]), or `None`
|
||||
/// when the key or the value is missing. The value is read as UTF-16, so a folder name in any
|
||||
/// script comes back as stored.
|
||||
#[cfg(windows)]
|
||||
#[allow(unsafe_code)]
|
||||
fn registry_default_path(hive: windows::Win32::System::Registry::HKEY, subkey: &str) -> Option<std::path::PathBuf> {
|
||||
use windows::Win32::System::Registry::{RRF_RT_REG_SZ, RegGetValueW};
|
||||
use windows::core::PCWSTR;
|
||||
let subkey: Vec<u16> = subkey.encode_utf16().chain([0]).collect();
|
||||
let mut size = 0u32;
|
||||
// SAFETY: `subkey` is a NUL-terminated UTF-16 string that outlives the call, a null value name
|
||||
// reads the default value, and with no buffer the call only writes the value's size to `size`.
|
||||
unsafe { RegGetValueW(hive, PCWSTR(subkey.as_ptr()), PCWSTR::null(), RRF_RT_REG_SZ, None, None, Some(&mut size)) }.ok().ok()?;
|
||||
let mut value = vec![0u16; (size as usize).div_ceil(2)];
|
||||
let mut size = u32::try_from(value.len() * 2).ok()?;
|
||||
// SAFETY: as above, and `value` holds the `size` bytes the call may write.
|
||||
unsafe { RegGetValueW(hive, PCWSTR(subkey.as_ptr()), PCWSTR::null(), RRF_RT_REG_SZ, None, Some(value.as_mut_ptr().cast()), Some(&mut size)) }
|
||||
.ok()
|
||||
.ok()?;
|
||||
registered_path(&value)
|
||||
}
|
||||
|
||||
/// The path in a registry string value read as UTF-16, up to its first NUL, without surrounding
|
||||
/// spaces or quotes, like `C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe`.
|
||||
#[cfg_attr(not(any(windows, test)), allow(dead_code))]
|
||||
pub(crate) fn registered_path(value: &[u16]) -> Option<std::path::PathBuf> {
|
||||
let end = value.iter().position(|&c| c == 0).unwrap_or(value.len());
|
||||
let text = String::from_utf16(&value[..end]).ok()?;
|
||||
Some(text.trim().trim_matches('"')).filter(|v| !v.is_empty()).map(std::path::PathBuf::from)
|
||||
}
|
||||
|
||||
/// Is `app` an application Edit Original may start: an `.app` bundle on macOS, an `.exe` on
|
||||
/// Windows, an executable file elsewhere? Anything else (a document, a folder, a script on
|
||||
/// Windows) found where PhotoCraft installs is not taken for it.
|
||||
pub(crate) fn check_app(app: &std::path::Path) -> Result<(), String> {
|
||||
let ext = app.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
|
||||
let ok = if cfg!(target_os = "macos") {
|
||||
ext == "app" && app.is_dir()
|
||||
} else if cfg!(windows) {
|
||||
ext == "exe" && app.is_file()
|
||||
} else {
|
||||
executable_file(app)
|
||||
};
|
||||
if ok { Ok(()) } else { Err(format!("{} isn't an application Edit Original can open files in", app.display())) }
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn executable_file(p: &std::path::Path) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn executable_file(p: &std::path::Path) -> bool {
|
||||
p.is_file()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod open_with_tests {
|
||||
use super::{check_app, find_photocraft, photocraft_candidates, registered_path, windows_candidates};
|
||||
|
||||
/// A fresh, empty folder under the system's temporary folder.
|
||||
fn scratch(name: &str) -> tempfile::TempDir {
|
||||
tempfile::Builder::new().prefix(&format!("vc-open-with-{name}-")).tempdir().unwrap()
|
||||
}
|
||||
|
||||
/// #5236: only an application counts as PhotoCraft, never a document, a folder or a missing
|
||||
/// path.
|
||||
#[test]
|
||||
fn only_applications_are_started() {
|
||||
let temp = scratch("check");
|
||||
let d = temp.path();
|
||||
let doc = d.join("notes.txt");
|
||||
std::fs::write(&doc, "hi").unwrap();
|
||||
assert!(check_app(&doc).is_err(), "a document");
|
||||
assert!(check_app(d).is_err(), "a folder");
|
||||
assert!(check_app(&d.join("Missing.app")).is_err(), "a missing path");
|
||||
if cfg!(target_os = "macos") {
|
||||
let app = d.join("Editor.app");
|
||||
std::fs::create_dir_all(&app).unwrap();
|
||||
assert!(check_app(&app).is_ok(), "an .app bundle");
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
let tool = d.join("editor");
|
||||
std::fs::write(&tool, "#!/bin/sh\n").unwrap();
|
||||
assert!(check_app(&tool).is_err(), "not executable yet");
|
||||
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert!(check_app(&tool).is_ok(), "an executable file");
|
||||
}
|
||||
}
|
||||
|
||||
/// PhotoCraft is looked for only where it installs.
|
||||
#[test]
|
||||
fn photocraft_is_found_where_it_installs() {
|
||||
let temp = scratch("find");
|
||||
let d = temp.path();
|
||||
if cfg!(target_os = "macos") {
|
||||
let candidates = photocraft_candidates(Some(d), None);
|
||||
assert_eq!(candidates.first().map(|p| p.to_string_lossy().into_owned()).as_deref(), Some("/Applications/PhotoCraft.app"));
|
||||
assert!(candidates.contains(&d.join("Applications/PhotoCraft.app")), "{candidates:?}");
|
||||
std::fs::create_dir_all(d.join("Applications/PhotoCraft.app")).unwrap();
|
||||
assert!(find_photocraft(Some(d), None).unwrap().ends_with("PhotoCraft.app"));
|
||||
} else {
|
||||
let bin = d.join("bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
let path_var = std::env::join_paths([&bin]).unwrap();
|
||||
// On Windows an installed PhotoCraft (registered, or in a program folder) comes first, so
|
||||
// there only the `PATH` candidate is checked.
|
||||
if !cfg!(windows) {
|
||||
assert!(find_photocraft(None, Some(&path_var)).is_none(), "not installed");
|
||||
}
|
||||
let exe = bin.join(if cfg!(windows) { "photocraft.exe" } else { "photocraft" });
|
||||
std::fs::write(&exe, "").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
if cfg!(windows) {
|
||||
assert_eq!(photocraft_candidates(None, Some(&path_var)).last(), Some(&exe));
|
||||
assert!(check_app(&exe).is_ok());
|
||||
} else {
|
||||
assert_eq!(find_photocraft(None, Some(&path_var)), Some(exe));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #5327 review: on Windows PhotoCraft is looked for where its installer puts it: the path it
|
||||
/// registers, then `ArtCraft\PhotoCraft` in the per-user and per-machine program folders, then
|
||||
/// the `PATH`.
|
||||
#[test]
|
||||
fn windows_looks_where_the_photocraft_installer_puts_it() {
|
||||
use std::path::PathBuf;
|
||||
let registered = vec![PathBuf::from("D:/Tools/PhotoCraft/photocraft.exe")];
|
||||
let folders = [PathBuf::from("C:/Users/me/AppData/Local/Programs"), PathBuf::from("C:/Program Files"), PathBuf::from("C:/Program Files")];
|
||||
let on_path = vec![PathBuf::from("C:/bin/photocraft.exe")];
|
||||
let exe = |f: &str| PathBuf::from(f).join("ArtCraft").join("PhotoCraft").join("photocraft.exe");
|
||||
assert_eq!(
|
||||
windows_candidates(registered, &folders, on_path),
|
||||
[
|
||||
PathBuf::from("D:/Tools/PhotoCraft/photocraft.exe"),
|
||||
exe("C:/Users/me/AppData/Local/Programs"),
|
||||
exe("C:/Program Files"),
|
||||
PathBuf::from("C:/bin/photocraft.exe"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// The registered path is read from the UTF-16 value up to its NUL, spaces, quotes and
|
||||
/// characters outside ASCII included; an empty value or one that is not UTF-16 gives no path.
|
||||
#[test]
|
||||
fn the_registered_path_is_read_from_the_utf16_value() {
|
||||
let wide = |s: &str| s.encode_utf16().chain([0, 0]).collect::<Vec<u16>>();
|
||||
assert_eq!(
|
||||
registered_path(&wide(r"C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe")),
|
||||
Some(std::path::PathBuf::from(r"C:\Program Files\ArtCraft\PhotoCraft\photocraft.exe"))
|
||||
);
|
||||
assert_eq!(
|
||||
registered_path(&wide(" \"C:\\Prögram Fïles\\Тест\\写真\\photocraft.exe\" ")),
|
||||
Some(std::path::PathBuf::from(r"C:\Prögram Fïles\Тест\写真\photocraft.exe"))
|
||||
);
|
||||
assert_eq!(registered_path(&wide("")), None);
|
||||
assert_eq!(registered_path(&[0xD800, 0]), None);
|
||||
}
|
||||
|
||||
/// On Windows a registered path with characters outside the console's code page is read as
|
||||
/// stored, from a scratch key under the current user's hive.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_registered_path_outside_ascii_is_read_as_stored() {
|
||||
let key = format!(r"Software\VectorCraftTest-app-paths-{}", std::process::id());
|
||||
let path = r"C:\Prögram Fïles\Тест\写真\photocraft.exe";
|
||||
let reg = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| r"C:\Windows".into()).join(r"System32\reg.exe");
|
||||
let full = format!(r"HKCU\{key}");
|
||||
let added = std::process::Command::new(®).args(["add", &full, "/ve", "/t", "REG_SZ", "/d", path, "/f"]).output().unwrap();
|
||||
assert!(added.status.success(), "{added:?}");
|
||||
let read = super::registry_default_path(windows::Win32::System::Registry::HKEY_CURRENT_USER, &key);
|
||||
let _ = std::process::Command::new(®).args(["delete", &full, "/f"]).output();
|
||||
assert_eq!(read, Some(std::path::PathBuf::from(path)));
|
||||
assert_eq!(super::registry_default_path(windows::Win32::System::Registry::HKEY_CURRENT_USER, &key), None, "deleted");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod dialog_tests {
|
||||
use super::{CASE_SENSITIVE_FILTERS, DialogSettings, FilePick, PickRequest, dialog_for, fileio, open_extensions};
|
||||
|
||||
/// The file types a dialog was given, by label.
|
||||
#[derive(Default)]
|
||||
struct Filters(Vec<(String, Vec<String>)>);
|
||||
|
||||
impl DialogSettings for Filters {
|
||||
fn parent(self, _window: &winit::window::Window) -> Self {
|
||||
self
|
||||
}
|
||||
fn title(self, _title: &str) -> Self {
|
||||
self
|
||||
}
|
||||
fn filter(mut self, name: &str, exts: &[impl ToString]) -> Self {
|
||||
self.0.push((name.to_string(), exts.iter().map(ToString::to_string).collect()));
|
||||
self
|
||||
}
|
||||
fn folder(self, _folder: &str) -> Self {
|
||||
self
|
||||
}
|
||||
fn file_name(self, _name: &str) -> Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Does the case-sensitive pattern `*.{ext}` match `name`? `ext` may hold literal characters,
|
||||
/// `*` and `[..]` sets.
|
||||
fn matches(ext: &str, name: &str) -> bool {
|
||||
fn here(p: &[char], n: &[char]) -> bool {
|
||||
match p.split_first() {
|
||||
None => n.is_empty(),
|
||||
Some(('*', rest)) => (0..=n.len()).any(|i| here(rest, &n[i..])),
|
||||
Some(('[', rest)) => {
|
||||
let Some(end) = rest.iter().position(|&c| c == ']') else { return false };
|
||||
n.split_first().is_some_and(|(c, n)| rest[..end].contains(c) && here(&rest[end + 1..], n))
|
||||
}
|
||||
Some((c, rest)) => n.split_first().is_some_and(|(d, n)| d == c && here(rest, n)),
|
||||
}
|
||||
}
|
||||
let pattern: Vec<char> = format!("*.{ext}").chars().collect();
|
||||
here(&pattern, &name.chars().collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// Where filters match case-sensitively, every extension of File › Open and Place lists files
|
||||
/// whose extension is in capitals or mixed case, `image.DIB` and `image.Pns` included.
|
||||
#[test]
|
||||
fn open_and_place_filters_list_extensions_in_any_case() {
|
||||
let all = fileio::open_filters().chain(fileio::place_filters());
|
||||
for (label, exts) in all {
|
||||
let patterns = open_extensions(exts, true);
|
||||
for ext in exts {
|
||||
let mut mixed = ext.to_ascii_uppercase();
|
||||
mixed.replace_range(..1, &ext[..1]);
|
||||
for name in [format!("a.{ext}"), format!("a.{}", ext.to_ascii_uppercase()), format!("a.{mixed}")] {
|
||||
assert!(patterns.iter().any(|p| matches(p, &name)), "{label}: {patterns:?} don't match {name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(open_extensions(&["dib", "jp2", "*"], true), ["dib", "[dD][iI][bB]", "jp2", "[jJ][pP]2", "*"]);
|
||||
assert_eq!(open_extensions(&["dib", "PNS"], false), ["dib", "PNS"]);
|
||||
}
|
||||
|
||||
/// Open and Place dialogs get the any-case patterns on Linux and the BSDs; a save dialog's file
|
||||
/// types stay as listed.
|
||||
#[test]
|
||||
fn open_dialogs_get_any_case_patterns_where_filters_are_case_sensitive() {
|
||||
let dib = vec![FilePick::filter("BMP", &["bmp", "dib"])];
|
||||
let pick = FilePick { filters: dib.clone(), ..Default::default() };
|
||||
let expected = |any_case: bool| open_extensions(&["bmp", "dib"], any_case);
|
||||
let opened = dialog_for(Filters::default(), &PickRequest::Open(pick.clone())).0;
|
||||
assert_eq!(opened[0].1, expected(CASE_SENSITIVE_FILTERS));
|
||||
let saved = dialog_for(Filters::default(), &PickRequest::Save(pick)).0;
|
||||
assert_eq!(saved, dib);
|
||||
let placed = dialog_for(Filters::default(), &PickRequest::OpenMany).0;
|
||||
let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS));
|
||||
assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,29 @@
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let d = std::env::temp_dir().join(format!("vectorcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
d
|
||||
struct TestPath {
|
||||
_parent: tempfile::TempDir,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for TestPath {
|
||||
type Target = Path;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<Path> for TestPath {
|
||||
fn as_ref(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> TestPath {
|
||||
let parent = tempfile::Builder::new().prefix(&format!("vectorcraft-logging-{tag}-")).tempdir().unwrap();
|
||||
let path = parent.path().join("log");
|
||||
TestPath { _parent: parent, path }
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> String {
|
||||
|
||||
@@ -63,11 +63,10 @@ mod tests {
|
||||
/// fonts, is listed while it is registered.
|
||||
#[test]
|
||||
fn fonts_registered_from_other_folders_are_listed() {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-mac-fonts-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let dir = tempfile::Builder::new().prefix("vectorcraft-mac-fonts-").tempdir().unwrap();
|
||||
// A space in the name: the URL's escapes are decoded. The bundled serif isn't a font macOS
|
||||
// installs.
|
||||
let file = dir.join("Registered Font.ttf");
|
||||
let file = dir.path().join("Registered Font.ttf");
|
||||
std::fs::copy(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf"), &file).unwrap();
|
||||
let want = std::fs::canonicalize(&file).unwrap();
|
||||
let listed = || super::font_files().iter().any(|f| f.ends_with("/Registered Font.ttf") && std::fs::canonicalize(f).is_ok_and(|p| p == want));
|
||||
@@ -78,7 +77,6 @@ mod tests {
|
||||
let registered = listed();
|
||||
// SAFETY: as above.
|
||||
unsafe { CTFontManagerUnregisterFontsForURL(&url, CTFontManagerScope::Process, std::ptr::null_mut()) };
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert!(registered);
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ use std::sync::mpsc::{Receiver, channel};
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2::rc::{Retained, Weak};
|
||||
use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
|
||||
use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
|
||||
use objc2_app_kit::{NSModalResponse, NSModalResponseOK, NSPopUpButton, NSSavePanel, NSTextField, NSView};
|
||||
use objc2_foundation::{NSArray, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString, NSURL};
|
||||
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
|
||||
@@ -108,21 +108,42 @@ fn set_allowed_types(panel: &NSSavePanel, filters: &[Filter], selected: usize) {
|
||||
panel.setAllowedFileTypes(Some(&NSArray::from_retained_slice(&types)));
|
||||
}
|
||||
|
||||
/// Show the save panel for `pick` as a sheet on `window`, with a Format menu, and answer on the
|
||||
/// receiver with the path picked (none when canceled). `None` when the request has fewer than two
|
||||
/// named file types, or `window` has no AppKit window; nothing is shown then.
|
||||
pub fn begin(window: &winit::window::Window, pick: &FilePick) -> Option<Receiver<Vec<String>>> {
|
||||
let mtm = MainThreadMarker::new()?;
|
||||
/// How [`begin`] decided to show a save sheet.
|
||||
#[derive(Debug)]
|
||||
pub enum Begin {
|
||||
/// The Format-menu sheet is open; wait on the receiver for the path (empty when canceled).
|
||||
Shown(Receiver<Vec<String>>),
|
||||
/// Fewer than two named file types: the caller should show an rfd panel instead.
|
||||
DeferToRfd,
|
||||
}
|
||||
|
||||
/// Show the save panel for `pick` as a sheet on `window`, with a Format menu.
|
||||
///
|
||||
/// `Ok(Begin::Shown(…))` when the sheet is open. `Ok(Begin::DeferToRfd)` when the request has
|
||||
/// fewer than two named file types (or no AppKit window yet) so rfd should show the panel.
|
||||
/// `Err(())` when AppKit returned no panel: the caller must not call rfd, whose `+savePanel`
|
||||
/// panics on the same nil (#5980).
|
||||
pub fn begin(window: &winit::window::Window, pick: &FilePick) -> Result<Begin, ()> {
|
||||
let Some(mtm) = MainThreadMarker::new() else {
|
||||
return Ok(Begin::DeferToRfd);
|
||||
};
|
||||
let filters = menu_formats(&pick.filters);
|
||||
if filters.is_empty() {
|
||||
return None;
|
||||
return Ok(Begin::DeferToRfd);
|
||||
}
|
||||
let RawWindowHandle::AppKit(handle) = window.window_handle().ok()?.as_raw() else { return None };
|
||||
let Some(RawWindowHandle::AppKit(handle)) = window.window_handle().ok().map(|h| h.as_raw()) else {
|
||||
return Ok(Begin::DeferToRfd);
|
||||
};
|
||||
// SAFETY: the handle's view is the window's content view, which AppKit keeps alive while the
|
||||
// window is open, and winit hands out the handle only while it is.
|
||||
let view = unsafe { handle.ns_view.cast::<NSView>().as_ref() };
|
||||
let parent = view.window()?;
|
||||
let panel = NSSavePanel::savePanel(mtm);
|
||||
let Some(parent) = view.window() else {
|
||||
return Ok(Begin::DeferToRfd);
|
||||
};
|
||||
let Some(panel) = new_panel(mtm) else {
|
||||
log::error!("macOS save panel unavailable: AppKit returned nil for NSSavePanel (#5980)");
|
||||
return Err(());
|
||||
};
|
||||
let selected = initial_format(&pick.name, &filters);
|
||||
set_allowed_types(&panel, &filters, selected);
|
||||
if let Some(folder) = &pick.folder {
|
||||
@@ -145,7 +166,23 @@ pub fn begin(window: &winit::window::Window, pick: &FilePick) -> Option<Receiver
|
||||
// The panel and its accessory are set up; AppKit keeps the handler (and the panel it holds)
|
||||
// until the sheet closes.
|
||||
panel.beginSheetModalForWindow_completionHandler(&parent, &handler);
|
||||
Some(rx)
|
||||
Ok(Begin::Shown(rx))
|
||||
}
|
||||
|
||||
/// An `NSSavePanel` without panicking when AppKit returns nil (#5980).
|
||||
///
|
||||
/// Prefers `-[NSSavePanel init]` (Apple's current Swift API) over `+[NSSavePanel savePanel]`,
|
||||
/// which objc2 turns into a panic on nil. Falls back to the class method, still as `Option`.
|
||||
fn new_panel(mtm: MainThreadMarker) -> Option<Retained<NSSavePanel>> {
|
||||
// SAFETY: designated initializer for a bare save panel; returns nil when AppKit refuses.
|
||||
let panel: Option<Retained<NSSavePanel>> = unsafe { msg_send![NSSavePanel::alloc(mtm), init] };
|
||||
if panel.is_some() {
|
||||
return panel;
|
||||
}
|
||||
// SAFETY: class method; returns an autoreleased panel or nil. Typed as Option so nil is not a
|
||||
// panic (unlike `NSSavePanel::savePanel`).
|
||||
let panel: Option<Retained<NSSavePanel>> = unsafe { msg_send![NSSavePanel::class(), savePanel] };
|
||||
panel
|
||||
}
|
||||
|
||||
/// The "Format:" label and menu of `filters`, `selected` chosen, that rename `panel`'s file.
|
||||
@@ -234,6 +271,16 @@ mod tests {
|
||||
assert_eq!(allowed_types(&filters(), 9), ["vectorcraft", "svg", "pdf"]);
|
||||
}
|
||||
|
||||
/// A nil AppKit panel must be `None`, not a panic. `NSSavePanel::savePanel` used to panic here
|
||||
/// (#5980); `new_panel` types the same message send as `Option`.
|
||||
#[test]
|
||||
fn a_null_save_panel_pointer_is_none_not_a_panic() {
|
||||
let null: *mut NSSavePanel = std::ptr::null_mut();
|
||||
// SAFETY: retaining a null object pointer is defined to yield None.
|
||||
let panel: Option<Retained<NSSavePanel>> = unsafe { Retained::retain(null) };
|
||||
assert!(panel.is_none());
|
||||
}
|
||||
|
||||
/// Each entry of the Save As menu gives a name the save command reads as that entry's format.
|
||||
#[test]
|
||||
fn each_menu_entry_names_a_file_the_save_command_writes_in_that_format() {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! macOS: a drawing tablet's pen pressure (#852). winit 0.30 hands a pen to the window there as a
|
||||
//! mouse, without its pressure, so the app reads it from AppKit itself and writes it into the UI's
|
||||
//! [`StylusFeed`] (`Services::stylus`), which the canvas reads, as on X11 ([`crate::tablet`]).
|
||||
//! macOS: a drawing tablet's pen pressure (#852), tilt and barrel rotation (#764). winit 0.30
|
||||
//! hands a pen to the window there as a mouse, without them, so the app reads them from AppKit
|
||||
//! itself and writes them into the UI's [`StylusFeed`] (`Services::stylus`), which the canvas
|
||||
//! reads, as on X11 ([`crate::tablet`]).
|
||||
//!
|
||||
//! A local event monitor (`addLocalMonitorForEventsMatchingMask:handler:`, which AppKit calls "with
|
||||
//! each event it is about to dispatch" in this app:
|
||||
@@ -9,9 +10,14 @@
|
||||
//! it on unchanged:
|
||||
//! - A mouse event whose `subtype` is `NSEventSubtypeTabletPoint` comes from a pen: its `pressure`
|
||||
//! (0..1) goes into the feed, kept for the pointer move winit makes of the event
|
||||
//! ([`StylusFeed::set_move`]), so each move of a fast stroke has its own pressure. A mouse event
|
||||
//! of any other subtype is a mouse's or a trackpad's: the feed is set to `None`.
|
||||
//! - An `NSEventTypeTabletPoint` event carries the same pressure without a move.
|
||||
//! ([`StylusFeed::set_move`]), so each move of a fast stroke has its own pressure. Its `tilt`
|
||||
//! (−1..1 on each axis, ±[`TILT_DEGREES`] at the ends) and its `rotation` go into the feed as the
|
||||
//! pen's pose, kept for that move too. AppKit gives a rotation of 0 for a pen that does not read
|
||||
//! one and a tilt of 0 for an upright pen, so one event cannot tell a pen without tilt or rotation
|
||||
//! from one held upright and unturned. Each reads as none until the pen reports a value other
|
||||
//! than 0 after it comes near ([`Pen`]).
|
||||
//! A mouse event of any other subtype is a mouse's or a trackpad's: the feed is set to `None`.
|
||||
//! - An `NSEventTypeTabletPoint` event carries the same pressure, tilt and rotation without a move.
|
||||
//! - A tablet proximity event (`NSEventTypeTabletProximity`, or a mouse event of that subtype) says
|
||||
//! which end of the pen came near (`pointingDeviceType`): the eraser end's samples are marked so,
|
||||
//! and the canvas switches to the Eraser tool ([`vectorcraft_ui_egui::stylus`]). A puck
|
||||
@@ -20,12 +26,14 @@
|
||||
//! The monitor also turns off mouse event coalescing (`NSEvent.mouseCoalescingEnabled`), which
|
||||
//! merges the drags that queue up between two reads into one: every report of the pen arrives.
|
||||
//!
|
||||
//! The mapping comes from PhotoCraft's `crates/tablet` (`appkit.rs` and `macos.rs`), with the
|
||||
//! pressure and the pen's end only. It is plain values, tested on every platform; the monitor
|
||||
//! reads them.
|
||||
//! The event mapping comes from PhotoCraft's `crates/tablet` (`appkit.rs` and `macos.rs`). The tilt
|
||||
//! and rotation follow Apple's `NSEvent` documentation, as [`RawEvent::pose`] describes. The mapping
|
||||
//! works on plain values and is tested on every platform; the monitor reads them.
|
||||
#![cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
|
||||
use vectorcraft_ui_egui::stylus::{PenSample, StylusFeed};
|
||||
use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed};
|
||||
|
||||
use crate::tablet::TILT_DEGREES;
|
||||
|
||||
/// `NSEventType` values (AppKit headers).
|
||||
mod event_type {
|
||||
@@ -56,6 +64,10 @@ struct RawEvent {
|
||||
subtype: i16,
|
||||
/// `pressure` (tablet point events and mouse events of that subtype only).
|
||||
pressure: f32,
|
||||
/// `tilt` (x, y), each −1..1 (the same events as `pressure`).
|
||||
tilt: (f64, f64),
|
||||
/// `rotation`, in degrees (the same events as `pressure`).
|
||||
rotation: f32,
|
||||
/// `pointingDeviceType` (proximity events only).
|
||||
device: usize,
|
||||
/// `isEnteringProximity` (proximity events only).
|
||||
@@ -74,6 +86,40 @@ impl RawEvent {
|
||||
fn point(&self) -> bool {
|
||||
self.kind == event_type::TABLET_POINT || (self.mouse() && self.subtype == subtype::TABLET_POINT)
|
||||
}
|
||||
|
||||
/// The pen's tilt and rotation in [`PenPose`]'s units.
|
||||
///
|
||||
/// AppKit's `tilt` is −1.0..1.0 on each axis and 0.0 on both with the pen perpendicular to the
|
||||
/// tablet. A negative x is a tilt to the left and a positive x a tilt to the right; a negative y
|
||||
/// is a tilt to the top and a positive y a tilt to the bottom
|
||||
/// (<https://developer.apple.com/documentation/appkit/nsevent/tilt>). [`PenPose`]'s x is positive
|
||||
/// to the right and its y positive down the page, the same signs, so each axis keeps its sign.
|
||||
/// Apple gives the ends of the range as maximum tilt and does not give them in degrees
|
||||
/// (<https://developer.apple.com/documentation/coregraphics/cgeventfield/tableteventtiltx>), so
|
||||
/// ±1.0 is scaled to ±[`TILT_DEGREES`], the degrees the X11 reader ([`crate::tablet`]) gives the
|
||||
/// ends of a tilt range that is not in degrees. A value past ±1.0 is clamped.
|
||||
///
|
||||
/// AppKit's `rotation` is in degrees, and a device without rotation reports 0.0
|
||||
/// (<https://developer.apple.com/documentation/appkit/nsevent/rotation>). Apple's tablet pages give
|
||||
/// no direction for rotation; the Cocoa Event Handling Guide gives the `rotation` accessor's
|
||||
/// degrees as counterclockwise for the rotate gesture
|
||||
/// (<https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/HandlingTouchEvents/HandlingTouchEvents.html>),
|
||||
/// and the pen's rotation is taken the same way. [`PenPose`]'s rotation runs clockwise, so the
|
||||
/// angle is negated and brought into 0..360.
|
||||
///
|
||||
/// The tilt is left out unless `tilts`, and the rotation unless `turns` ([`Pen`]).
|
||||
fn pose(&self, tilts: bool, turns: bool) -> PenPose {
|
||||
let degrees = |v: f64| (v.clamp(-1.0, 1.0) * TILT_DEGREES) as f32;
|
||||
// `0.0 - r` rather than `-r`: a rotation of 0 gives 0, not −0.
|
||||
let rotation = turns.then(|| (0.0 - self.rotation).rem_euclid(360.0));
|
||||
PenPose { tilt: tilts.then(|| [degrees(self.tilt.0), degrees(self.tilt.1)]), rotation }
|
||||
}
|
||||
|
||||
/// Whether the event reports a tilt other than 0, and a rotation other than 0.
|
||||
fn reads(&self) -> (bool, bool) {
|
||||
let read = |v: f64| v.is_finite() && v != 0.0;
|
||||
(read(self.tilt.0) || read(self.tilt.1), read(f64::from(self.rotation)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The events the monitor reads (`NSEventMask` bits are `1 << type`).
|
||||
@@ -86,7 +132,7 @@ fn event_mask() -> u64 {
|
||||
enum Update {
|
||||
/// Nothing: an event the monitor doesn't map.
|
||||
Keep,
|
||||
/// The pressure and end of a pen, or `None` for a mouse.
|
||||
/// The sample of a pen, or `None` for a mouse.
|
||||
Set(Option<PenSample>),
|
||||
/// A pen's sample that comes with a pointer move.
|
||||
Move(PenSample),
|
||||
@@ -102,10 +148,14 @@ impl Update {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which end of the pen is near the tablet.
|
||||
/// Which end of the pen is near the tablet, and whether it has reported a tilt or a rotation other
|
||||
/// than 0 since it came near: until it has, its tilt or rotation reads as none, since AppKit gives
|
||||
/// 0 for a pen without one and for one held upright or unturned.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
struct Pen {
|
||||
eraser: bool,
|
||||
tilts: bool,
|
||||
turns: bool,
|
||||
}
|
||||
|
||||
impl Pen {
|
||||
@@ -113,10 +163,16 @@ impl Pen {
|
||||
if e.proximity() {
|
||||
// Entering with the tip or the eraser end: it hovers. A puck, or leaving, is a mouse.
|
||||
self.eraser = e.entering && e.device == device::ERASER;
|
||||
(self.tilts, self.turns) = (false, false);
|
||||
let pen = e.entering && e.device != device::CURSOR;
|
||||
return Update::Set(pen.then_some(PenSample { pressure: 0.0, eraser: self.eraser }));
|
||||
return Update::Set(pen.then_some(PenSample { pressure: 0.0, eraser: self.eraser, ..PenSample::default() }));
|
||||
}
|
||||
let sample = PenSample { pressure: e.pressure, eraser: self.eraser };
|
||||
if e.point() {
|
||||
let (tilts, turns) = e.reads();
|
||||
self.tilts |= tilts;
|
||||
self.turns |= turns;
|
||||
}
|
||||
let sample = PenSample { pressure: e.pressure, eraser: self.eraser, pose: e.pose(self.tilts, self.turns) };
|
||||
match (e.point(), e.mouse()) {
|
||||
(true, true) => Update::Move(sample),
|
||||
(true, false) => Update::Set(Some(sample)),
|
||||
@@ -187,6 +243,9 @@ mod monitor {
|
||||
}
|
||||
if raw.point() {
|
||||
raw.pressure = e.pressure();
|
||||
let tilt = e.tilt();
|
||||
raw.tilt = (tilt.x, tilt.y);
|
||||
raw.rotation = e.rotation();
|
||||
}
|
||||
if raw.proximity() {
|
||||
raw.device = e.pointingDeviceType().0;
|
||||
@@ -211,8 +270,14 @@ mod tests {
|
||||
RawEvent { kind: event_type::TABLET_PROXIMITY, device, entering, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A sample of the tip of a pen that has reported no tilt or rotation.
|
||||
fn tip(pressure: f32) -> PenSample {
|
||||
PenSample { pressure, eraser: false }
|
||||
PenSample { pressure, eraser: false, pose: PenPose::default() }
|
||||
}
|
||||
|
||||
/// A sample of the pen near the tablet but not yet read: no pose.
|
||||
fn near(eraser: bool) -> PenSample {
|
||||
PenSample { pressure: 0.0, eraser, pose: PenPose::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -240,16 +305,45 @@ mod tests {
|
||||
#[test]
|
||||
fn proximity_says_which_end_is_near() {
|
||||
let mut p = Pen::default();
|
||||
let eraser = |pressure| PenSample { pressure, eraser: true };
|
||||
assert_eq!(p.handle(&proximity(device::ERASER, true)), Update::Set(Some(eraser(0.0))));
|
||||
let eraser = |pressure| PenSample { pressure, eraser: true, pose: PenPose::default() };
|
||||
assert_eq!(p.handle(&proximity(device::ERASER, true)), Update::Set(Some(near(true))));
|
||||
assert_eq!(p.handle(&pen(DRAG, 0.4)), Update::Move(eraser(0.4)));
|
||||
assert_eq!(p.handle(&proximity(device::ERASER, false)), Update::Set(None), "it left");
|
||||
assert_eq!(p.handle(&pen(DRAG, 0.4)), Update::Move(tip(0.4)));
|
||||
assert_eq!(p.handle(&proximity(1, true)), Update::Set(Some(tip(0.0))), "the tip");
|
||||
assert_eq!(p.handle(&proximity(0, true)), Update::Set(Some(tip(0.0))), "an unknown tool draws as the tip");
|
||||
assert_eq!(p.handle(&proximity(1, true)), Update::Set(Some(near(false))), "the tip");
|
||||
assert_eq!(p.handle(&proximity(0, true)), Update::Set(Some(near(false))), "an unknown tool draws as the tip");
|
||||
assert_eq!(p.handle(&proximity(device::CURSOR, true)), Update::Set(None), "a puck is a mouse");
|
||||
let e = RawEvent { kind: 5, subtype: subtype::TABLET_PROXIMITY, device: device::ERASER, entering: true, ..Default::default() };
|
||||
assert_eq!(p.handle(&e), Update::Set(Some(eraser(0.0))), "as a mouse event's subtype");
|
||||
assert_eq!(p.handle(&e), Update::Set(Some(near(true))), "as a mouse event's subtype");
|
||||
}
|
||||
|
||||
/// #764: AppKit's tilt (−1..1, x positive to the right, y positive to the bottom) reaches the
|
||||
/// feed in degrees with the same signs, and its rotation, taken as counterclockwise, reaches it
|
||||
/// clockwise.
|
||||
#[test]
|
||||
fn a_pens_tilt_and_rotation_go_into_the_feed() {
|
||||
let mut p = Pen::default();
|
||||
let sample = |pressure, pose| PenSample { pressure, eraser: false, pose };
|
||||
assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Move(tip(0.5)), "no tilt or rotation reported yet");
|
||||
let leaning = RawEvent { tilt: (0.5, -0.25), rotation: 30.0, ..pen(DRAG, 0.5) };
|
||||
let pose = PenPose { tilt: Some([30.0, -15.0]), rotation: Some(330.0) };
|
||||
assert_eq!(p.handle(&leaning), Update::Move(sample(0.5, pose)));
|
||||
let past_the_ends = RawEvent { tilt: (-4.0, 1.5), rotation: 270.0, ..pen(event_type::TABLET_POINT, 0.8) };
|
||||
let pose = PenPose { tilt: Some([-60.0, 60.0]), rotation: Some(90.0) };
|
||||
assert_eq!(p.handle(&past_the_ends), Update::Set(Some(sample(0.8, pose))), "clamped");
|
||||
let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
let Update::Move(upright) = p.handle(&pen(DRAG, 0.6)) else { panic!("a pen's drag is a move") };
|
||||
assert_eq!(upright, sample(0.6, pose), "once reported, 0 is upright and unturned");
|
||||
assert!(upright.pose.rotation.is_some_and(f32::is_sign_positive), "{upright:?}");
|
||||
let feed = StylusFeed::default();
|
||||
p.handle(&RawEvent { tilt: (f64::NAN, 0.0), rotation: -90.0, ..pen(DRAG, 0.3) }).apply(&feed);
|
||||
assert_eq!(feed.pose(), Some(PenPose { tilt: None, rotation: Some(90.0) }), "a tilt that is not a number is left out");
|
||||
p.handle(&proximity(1, true));
|
||||
let tilted = RawEvent { tilt: (0.0, 0.5), ..pen(event_type::TABLET_POINT, 0.8) };
|
||||
let pose = PenPose { tilt: Some([0.0, 30.0]), rotation: None };
|
||||
assert_eq!(p.handle(&tilted), Update::Set(Some(sample(0.8, pose))), "no rotation reported since the pen came near");
|
||||
p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&feed);
|
||||
assert_eq!(feed.pose(), None, "a mouse moved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -259,7 +353,8 @@ mod tests {
|
||||
for e in [pen(DRAG, f32::NAN), pen(DRAG, 4.0), pen(DRAG, -1.0), pen(event_type::TABLET_POINT, 0.3)] {
|
||||
p.handle(&e).apply(&feed);
|
||||
}
|
||||
assert_eq!((feed.take_moves(), feed.held()), (vec![1.0, 1.0, 0.0], Some(0.3)));
|
||||
let pressures: Vec<f32> = feed.take_moves().into_iter().map(|(p, _)| p).collect();
|
||||
assert_eq!((pressures, feed.held()), (vec![1.0, 1.0, 0.0], Some(0.3)));
|
||||
p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&feed);
|
||||
assert_eq!(feed.held(), None, "a mouse moved");
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
//! VectorCraft desktop app.
|
||||
//!
|
||||
//! Usage: `vectorcraft [--control <port> [--automation-read-root <dir>]... [--automation-write-root <dir>]...]
|
||||
//! [--in-window-menus] [--new-instance] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`)
|
||||
//! [--in-window-menus] [--new-instance] [--safe-mode] [--] [files…]`, `vectorcraft --version`, `vectorcraft --help` (or `-h`)
|
||||
//!
|
||||
//! Any other argument starting with '-' (not `-` alone) is an error; after `--`, every argument is
|
||||
//! a file.
|
||||
//!
|
||||
//! Files given while VectorCraft already runs open in that window, unless `--new-instance` is given
|
||||
//! (Windows and Linux; `single_instance`).
|
||||
@@ -56,6 +59,7 @@ mod system_fonts;
|
||||
mod tablet;
|
||||
mod window;
|
||||
mod window_frame;
|
||||
mod windows_alt_codes;
|
||||
#[cfg(windows)]
|
||||
mod windows_cores;
|
||||
mod windows_stylus;
|
||||
@@ -64,6 +68,7 @@ mod xwayland;
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_engine::cmd::fileio;
|
||||
use vectorcraft_engine::file_access::{self, AutomationRoots};
|
||||
use vectorcraft_ui_egui::dialogs::safe_mode;
|
||||
use vectorcraft_ui_egui::graphics::GraphicsLoss;
|
||||
use vectorcraft_ui_egui::picks::PickRequest;
|
||||
use vectorcraft_ui_egui::{ClipboardProbeFactory, FilePick, Services, VectorcraftApp};
|
||||
@@ -76,7 +81,7 @@ mod titlebar;
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
use app::bring_window_forward;
|
||||
use app::native_input_hook;
|
||||
use app::open_files;
|
||||
use app::open_or_hold;
|
||||
use host_services::services;
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes};
|
||||
@@ -91,7 +96,9 @@ use titlebar::custom_titlebar_from;
|
||||
use titlebar::opted_into_system_title_bar;
|
||||
#[cfg(windows)]
|
||||
use titlebar::set_taskbar_icon;
|
||||
use titlebar::{custom_titlebar, native_options};
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame};
|
||||
use titlebar::{custom_titlebar, native_options, titlebar_from_env};
|
||||
|
||||
struct App {
|
||||
app: VectorcraftApp,
|
||||
@@ -110,6 +117,10 @@ struct App {
|
||||
pending_maximize: bool,
|
||||
/// Frames left to retry [`window::apply_pending_maximize`].
|
||||
maximize_tries: u8,
|
||||
/// The command line's files, held back until the choice about a stopped plug-in is made.
|
||||
held_files: Vec<String>,
|
||||
/// The time and UI zoom of the last monitor list ([`window::monitors_due`]).
|
||||
monitors_listed: Option<(f64, f32)>,
|
||||
}
|
||||
|
||||
/// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s.
|
||||
@@ -129,13 +140,89 @@ Options:
|
||||
(or VECTORCRAFT_IN_WINDOW_MENUS=1)
|
||||
--new-instance Open the files in a new window even when VectorCraft
|
||||
already runs (Windows and Linux)
|
||||
--safe-mode Start without plug-ins: none loads or runs until
|
||||
VectorCraft starts normally (Help › Safe Mode); the
|
||||
files open in a new window, as with --new-instance
|
||||
--version Print the version and exit
|
||||
-h, --help Print this help and exit
|
||||
-- Treat every argument after it as a file
|
||||
|
||||
Any other argument starting with '-' is an error.
|
||||
|
||||
Without a window (converting, scripting, the MCP server), use vectorcraft-cli:
|
||||
vectorcraft-cli --help
|
||||
";
|
||||
|
||||
/// The command line's options other than the automation roots and the control port.
|
||||
struct CommandLine {
|
||||
files: Vec<String>,
|
||||
in_window_menus: bool,
|
||||
new_instance: bool,
|
||||
/// `--safe-mode`: no plug-in loads or runs in this launch.
|
||||
safe_mode: bool,
|
||||
}
|
||||
|
||||
/// Reads the arguments after the program name. The automation roots and the control port go into
|
||||
/// `roots_args` and `control`. `Err` is the exit code when the process ends here: `--version` and
|
||||
/// `--help` print and succeed; a bad automation option or an unknown option prints an error and fails.
|
||||
fn read_command_line(
|
||||
mut args: impl Iterator<Item = String>,
|
||||
control: &mut automation_args::ControlArg,
|
||||
roots_args: &mut automation_args::AutomationArgs,
|
||||
) -> Result<CommandLine, std::process::ExitCode> {
|
||||
let mut files = Vec::new();
|
||||
let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
|
||||
let mut new_instance = false;
|
||||
let mut safe_mode = false;
|
||||
let mut unknown = None;
|
||||
while let Some(a) = args.next() {
|
||||
// After `--`, every argument is a file, even one whose name starts with '-'.
|
||||
if a == "--" {
|
||||
files.extend(args.by_ref());
|
||||
break;
|
||||
}
|
||||
match roots_args.consume(&a, &mut args).and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) {
|
||||
Ok(true) => continue,
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
eprintln!("vectorcraft: {e}");
|
||||
return Err(std::process::ExitCode::FAILURE);
|
||||
}
|
||||
}
|
||||
match a.as_str() {
|
||||
"--in-window-menus" => in_window_menus = true,
|
||||
"--new-instance" => new_instance = true,
|
||||
"--safe-mode" => safe_mode = true,
|
||||
"--version" => {
|
||||
println!("vectorcraft {}", env!("CARGO_PKG_VERSION"));
|
||||
return Err(std::process::ExitCode::SUCCESS);
|
||||
}
|
||||
// Before anything starts, like `--version`: from a terminal or an agent's shell the app
|
||||
// used to open (or hang without a display) instead (#2110).
|
||||
"--help" | "-h" => {
|
||||
// Not `print!`, which panics when standard output is closed (`| head -0`):
|
||||
// there is nothing left to tell then.
|
||||
let _ = std::io::Write::write_all(&mut std::io::stdout(), USAGE.as_bytes());
|
||||
return Err(std::process::ExitCode::SUCCESS);
|
||||
}
|
||||
// The process serial number older macOS versions pass to an app the Finder starts.
|
||||
#[cfg(target_os = "macos")]
|
||||
_ if a.starts_with("-psn_") => {}
|
||||
// An option this version doesn't know (a typo such as `--safe-mod`) is an error, not a
|
||||
// file to open. Reported after the loop, so a later `--help` or `--version` still wins.
|
||||
_ if a.starts_with('-') && a != "-" => {
|
||||
unknown.get_or_insert(a);
|
||||
}
|
||||
_ => files.push(a),
|
||||
}
|
||||
}
|
||||
if let Some(a) = unknown {
|
||||
eprintln!("vectorcraft: unknown option {a}; see vectorcraft --help, or put -- before a file whose name starts with '-'");
|
||||
return Err(std::process::ExitCode::FAILURE);
|
||||
}
|
||||
Ok(CommandLine { files, in_window_menus, new_instance, safe_mode })
|
||||
}
|
||||
|
||||
fn main() -> std::process::ExitCode {
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`.
|
||||
#[cfg(windows)]
|
||||
@@ -151,37 +238,11 @@ fn main() -> std::process::ExitCode {
|
||||
let root_env = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()).map(std::path::PathBuf::from);
|
||||
let mut roots_args =
|
||||
automation_args::AutomationArgs::new(root_env("VECTORCRAFT_AUTOMATION_READ_ROOT"), root_env("VECTORCRAFT_AUTOMATION_WRITE_ROOT"));
|
||||
let mut files = Vec::new();
|
||||
let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
|
||||
let mut new_instance = false;
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
match roots_args.consume(&a, &mut args).and_then(|root| if root { Ok(true) } else { control.consume(&a, &mut args) }) {
|
||||
Ok(true) => continue,
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
eprintln!("vectorcraft: {e}");
|
||||
return std::process::ExitCode::FAILURE;
|
||||
}
|
||||
}
|
||||
match a.as_str() {
|
||||
"--in-window-menus" => in_window_menus = true,
|
||||
"--new-instance" => new_instance = true,
|
||||
"--version" => {
|
||||
println!("vectorcraft {}", env!("CARGO_PKG_VERSION"));
|
||||
return std::process::ExitCode::SUCCESS;
|
||||
}
|
||||
// Before anything starts, like `--version`: from a terminal or an agent's shell the app
|
||||
// used to open (or hang without a display) instead (#2110).
|
||||
"--help" | "-h" => {
|
||||
// Not `print!`, which panics when standard output is closed (`| head -0`):
|
||||
// there is nothing left to tell then.
|
||||
let _ = std::io::Write::write_all(&mut std::io::stdout(), USAGE.as_bytes());
|
||||
return std::process::ExitCode::SUCCESS;
|
||||
}
|
||||
_ => files.push(a),
|
||||
}
|
||||
}
|
||||
let CommandLine { files, in_window_menus, new_instance, safe_mode: safe_mode_flag } =
|
||||
match read_command_line(std::env::args().skip(1), &mut control, &mut roots_args) {
|
||||
Ok(command_line) => command_line,
|
||||
Err(code) => return code,
|
||||
};
|
||||
let automation_args::AutomationArgs { read_roots, write_roots, .. } = roots_args;
|
||||
// After the arguments: `--control` and `--version` win over a bad environment value.
|
||||
let control_port = match control.port {
|
||||
@@ -199,10 +260,10 @@ fn main() -> std::process::ExitCode {
|
||||
// Files opened from the file manager while VectorCraft runs open in its window (#4892). Before
|
||||
// the log file is attached: a launch that hands its files over leaves the running app's log be.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let instance = match single_instance::start(control_port.is_some(), new_instance, &files) {
|
||||
match single_instance::start(control_port.is_some(), new_instance, safe_mode_flag, &files) {
|
||||
single_instance::Start::Forwarded => return std::process::ExitCode::SUCCESS,
|
||||
single_instance::Start::Running(primary) => primary,
|
||||
};
|
||||
single_instance::Start::Running(primary) => single_instance::hold(primary),
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
let _ = new_instance;
|
||||
vectorcraft_ui_egui::i18n::detect_system_lang_in_background();
|
||||
@@ -314,13 +375,18 @@ fn main() -> std::process::ExitCode {
|
||||
};
|
||||
// With Windows Ink, winit reports a pen as a touch and drops its barrel button and which end
|
||||
// is down; the message hook notes each pointer contact and whether it starts with the barrel
|
||||
// button held, and writes the pen's end into the pen feed (`windows_stylus`).
|
||||
// button held, and writes the pen's end into the pen feed (`windows_stylus`). It also notes the
|
||||
// characters Alt + keypad codes type (`windows_alt_codes`).
|
||||
#[cfg(windows)]
|
||||
let options = {
|
||||
use winit::platform::windows::EventLoopBuilderExtWindows as _;
|
||||
let mut options = options;
|
||||
options.event_loop_builder = Some(Box::new(|builder| {
|
||||
builder.with_msg_hook(windows_stylus::msg_hook);
|
||||
builder.with_msg_hook(|msg| {
|
||||
// Alt + keypad codes (#5108), which winit drops; neither hook consumes a message.
|
||||
windows_alt_codes::msg_hook(msg);
|
||||
windows_stylus::msg_hook(msg)
|
||||
});
|
||||
}));
|
||||
options
|
||||
};
|
||||
@@ -388,10 +454,15 @@ fn main() -> std::process::ExitCode {
|
||||
let mut session = Session::new();
|
||||
// The profiles loaded before come back before the preferences name any of them.
|
||||
prefs_dir::attach_profile_store(&mut session);
|
||||
// Before any plug-in loads: this launch's marker in the Launch folder next to the
|
||||
// preferences (none for runs without preferences), and Safe Mode.
|
||||
let launch_dir = prefs_path().filter(|_| prefs_enabled()).and_then(|p| Some(p.parent()?.join("Launch")));
|
||||
let stopped = safe_mode::begin_launch(launch_dir.as_deref(), safe_mode_flag);
|
||||
prefs_dir::attach_plugin_store(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
|
||||
app.set_startup_update_check(true);
|
||||
load_prefs(&mut app, saved);
|
||||
safe_mode::after_start(&mut app, stopped);
|
||||
// The saved PDF presets live in their own folder (also read by vectorcraft-cli),
|
||||
// which takes over from the copy the preferences file used to hold.
|
||||
prefs_dir::attach_pdf_preset_store(&mut app.session);
|
||||
@@ -458,7 +529,9 @@ fn main() -> std::process::ExitCode {
|
||||
let (loss, ctx) = (graphics_loss.clone(), cc.egui_ctx.clone());
|
||||
rs.device.set_device_lost_callback(move |reason, msg| loss.report(&ctx, format!("{reason:?}: {msg}")));
|
||||
}
|
||||
app.titlebar_from_env = titlebar_from_env();
|
||||
app.custom_titlebar = custom_titlebar;
|
||||
app.desktop_frame = !custom_titlebar;
|
||||
if let Some(port) = control_port {
|
||||
let rx = control_server::start(port, cc.egui_ctx.clone());
|
||||
app = app.with_control(rx).with_automation_roots(roots.clone());
|
||||
@@ -483,7 +556,7 @@ fn main() -> std::process::ExitCode {
|
||||
single_instance::set_ui(&cc.egui_ctx);
|
||||
}
|
||||
app.services.native_input_hook = native_input_hook(&app);
|
||||
file_access::unconfined(|| open_files(&mut app, files));
|
||||
let held_files = file_access::unconfined(|| open_or_hold(&mut app, files));
|
||||
// The first frame is due from now (`gpu::watch_first_frame`).
|
||||
#[cfg(feature = "wgpu")]
|
||||
created.ready();
|
||||
@@ -499,6 +572,8 @@ fn main() -> std::process::ExitCode {
|
||||
winit_window,
|
||||
pending_maximize,
|
||||
maximize_tries: 8,
|
||||
held_files,
|
||||
monitors_listed: None,
|
||||
}))
|
||||
}),
|
||||
)
|
||||
@@ -506,7 +581,9 @@ fn main() -> std::process::ExitCode {
|
||||
// The window is gone: later launches start their own app, including the one a graphics
|
||||
// failure starts again below.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
drop(instance);
|
||||
single_instance::resign();
|
||||
// The process ends normally from here: this launch didn't stop while a plug-in was loading.
|
||||
safe_mode::end_launch();
|
||||
#[cfg(feature = "wgpu")]
|
||||
let outcome = gpu::finish(outcome, &startup);
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
|
||||
@@ -96,6 +96,12 @@ fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<Sav
|
||||
.map_err(|e: zbus::zvariant::Error| e.to_string())?;
|
||||
let uri = uris.first().ok_or("no file in the portal's answer")?;
|
||||
let path = file_uri_path(uri).ok_or_else(|| format!("not a local file: {uri}"))?;
|
||||
// A name that isn't UTF-8 can't be written as picked: replacing its bytes would save over (and
|
||||
// ask to replace) another file. The dialog ends without a file instead.
|
||||
let Ok(path) = String::from_utf8(path) else {
|
||||
log::warn!("the portal's save dialog picked a file name that isn't UTF-8: nothing is saved");
|
||||
return Ok(None);
|
||||
};
|
||||
let filter = results.get("current_filter").and_then(|v| {
|
||||
let (label, _globs): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
|
||||
Some(label)
|
||||
@@ -103,9 +109,9 @@ fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<Sav
|
||||
Ok(Some(Saved { path, filter }))
|
||||
}
|
||||
|
||||
/// `file:///home/me/A%20b.svg` → `/home/me/A b.svg`; `None` for a file elsewhere (`file://host/`)
|
||||
/// or another scheme.
|
||||
fn file_uri_path(uri: &str) -> Option<String> {
|
||||
/// `file:///home/me/A%20b.svg` → `/home/me/A b.svg` (its bytes); `None` for a file elsewhere
|
||||
/// (`file://host/`) or another scheme.
|
||||
fn file_uri_path(uri: &str) -> Option<Vec<u8>> {
|
||||
let rest = uri.strip_prefix("file://")?;
|
||||
let rest = rest.strip_prefix("localhost").unwrap_or(rest);
|
||||
if !rest.starts_with('/') {
|
||||
@@ -126,8 +132,7 @@ fn file_uri_path(uri: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// `show_dialog` makes rfd's path a string with `to_string_lossy` too.
|
||||
Some(String::from_utf8_lossy(&out).into_owned())
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// `saved` as the answer of the save dialog for `request`: the path, then the first extension of
|
||||
@@ -406,6 +411,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn file_uris_become_local_paths() {
|
||||
let file_uri_path = |uri: &str| super::file_uri_path(uri).map(|b| String::from_utf8(b).unwrap());
|
||||
assert_eq!(file_uri_path("file:///home/me/Untitled-1.vectorcraft").as_deref(), Some("/home/me/Untitled-1.vectorcraft"));
|
||||
assert_eq!(file_uri_path("file:///home/me/A%20b%C3%A9.svg").as_deref(), Some("/home/me/A bé.svg"));
|
||||
assert_eq!(file_uri_path("file://localhost/tmp/x.pdf").as_deref(), Some("/tmp/x.pdf"));
|
||||
@@ -413,6 +419,9 @@ mod tests {
|
||||
assert_eq!(file_uri_path("file:///tmp/100%+1%2").as_deref(), Some("/tmp/100%+1%2"));
|
||||
assert_eq!(file_uri_path("file://host/x.svg"), None);
|
||||
assert_eq!(file_uri_path("sftp://host/x.svg"), None);
|
||||
// Not UTF-8: the bytes as they are, which `answer` refuses rather than changing them.
|
||||
assert_eq!(super::file_uri_path("file:///tmp/a%FF.svg"), Some(b"/tmp/a\xff.svg".to_vec()));
|
||||
assert!(matches!(answer(0, &results("file:///tmp/a%FF.svg", None)), Ok(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -62,7 +62,12 @@ pub(crate) fn keep_prefs_copy(path: &std::path::Path, bytes: &[u8], stem: &str)
|
||||
use std::io::Write as _;
|
||||
for n in 1..100u32 {
|
||||
let name = if n == 1 { format!("{stem}.json") } else { format!("{stem}-{n}.json") };
|
||||
match std::fs::OpenOptions::new().write(true).create_new(true).open(path.with_file_name(name)) {
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
// The preferences hold recent document paths: the copy is owner-only, whatever the umask.
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
|
||||
match options.open(path.with_file_name(name)) {
|
||||
Ok(mut file) => {
|
||||
if file.write_all(bytes).is_ok() {
|
||||
return;
|
||||
@@ -163,6 +168,11 @@ fn same_lasting(a: &serde_json::Value, b: &serde_json::Value) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fields that a read fills in from other fields when the file lacks them
|
||||
/// (`vectorcraft_ui_egui::layout_migration`): `help_bar` follows `status_bar`. A save writes them
|
||||
/// whenever the file lacks them, so the next read does not fill them in again from a changed field.
|
||||
const DERIVED: &[&str] = &["help_bar"];
|
||||
|
||||
/// `on_disk` with what changed from `base` to `mine` put over it: each top-level field of the UI
|
||||
/// state, and each engine preference (`engine_prefs`) on its own, so two windows that change
|
||||
/// different settings keep both. A field both changed takes this window's value (it saves last).
|
||||
@@ -171,6 +181,11 @@ fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: se
|
||||
let (Some(base), Some(mine), Value::Object(mut out)) = (base.as_object(), mine.as_object(), on_disk) else {
|
||||
return mine.clone();
|
||||
};
|
||||
// The current Actions set (`action_set`, an index) is this window's when this window chose
|
||||
// another one or the other window did not; otherwise it is the other window's.
|
||||
let use_mine = chose_another_action_set(base, mine) || !chose_another_action_set(base, &out);
|
||||
// The list the saved current set was chosen from.
|
||||
let chosen_from = if use_mine { mine.get("action_sets").cloned() } else { out.get("action_sets").cloned() };
|
||||
let keys: std::collections::BTreeSet<&String> = base.keys().chain(mine.keys()).collect();
|
||||
for key in keys {
|
||||
if PASSING.contains(&key.as_str()) {
|
||||
@@ -180,7 +195,7 @@ fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: se
|
||||
continue;
|
||||
}
|
||||
let (was, now) = (base.get(key), mine.get(key));
|
||||
if was == now {
|
||||
if was == now || key == "action_set" {
|
||||
continue;
|
||||
}
|
||||
if key == "engine_prefs"
|
||||
@@ -209,9 +224,102 @@ fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: se
|
||||
}
|
||||
}
|
||||
}
|
||||
for key in DERIVED {
|
||||
if !out.contains_key(*key)
|
||||
&& let Some(v) = mine.get(*key)
|
||||
{
|
||||
out.insert((*key).to_string(), v.clone());
|
||||
}
|
||||
}
|
||||
if use_mine {
|
||||
match mine.get("action_set") {
|
||||
Some(v) => {
|
||||
out.insert("action_set".to_string(), v.clone());
|
||||
}
|
||||
None => {
|
||||
out.remove("action_set");
|
||||
}
|
||||
}
|
||||
}
|
||||
keep_current_action_set(&mut out, chosen_from.as_ref());
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
/// Point the saved current Actions set (`action_set`) at the same set in the merged
|
||||
/// `action_sets` when the merge took the index from one window and the list from another
|
||||
/// ([`find_action_set`]). With no such set, no set is current.
|
||||
fn keep_current_action_set(out: &mut serde_json::Map<String, serde_json::Value>, chosen_from: Option<&serde_json::Value>) {
|
||||
use serde_json::Value;
|
||||
let Some(i) = out.get("action_set").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()) else { return };
|
||||
let merged = out.get("action_sets");
|
||||
if merged == chosen_from {
|
||||
return;
|
||||
}
|
||||
match find_action_set(chosen_from, i, merged) {
|
||||
Some(j) => {
|
||||
out.insert("action_set".to_string(), Value::from(j));
|
||||
}
|
||||
None => {
|
||||
out.remove("action_set");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Was another Actions set made current from `base` to `now`? Recording into the current set,
|
||||
/// renaming it, deleting it, or deleting a set before it changes the list or the index without
|
||||
/// choosing another set.
|
||||
fn chose_another_action_set(base: &serde_json::Map<String, serde_json::Value>, now: &serde_json::Map<String, serde_json::Value>) -> bool {
|
||||
use serde_json::Value;
|
||||
let index = |v: &serde_json::Map<String, Value>| v.get("action_set").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok());
|
||||
let (was, sets) = (base.get("action_sets"), now.get("action_sets"));
|
||||
let (Some(i), Some(k)) = (index(base), index(now)) else {
|
||||
return match (index(base), index(now)) {
|
||||
(None, None) => false,
|
||||
// No set is current: another set was chosen only if the current one is still there.
|
||||
(Some(i), None) => find_action_set(was, i, sets).is_some(),
|
||||
_ => true,
|
||||
};
|
||||
};
|
||||
if was == sets {
|
||||
return i != k;
|
||||
}
|
||||
if let Some(j) = find_action_set(was, i, sets) {
|
||||
return j != k;
|
||||
}
|
||||
// The set at the same place changed while every other set stayed as it was: it was edited.
|
||||
let edited_in_place = was
|
||||
.and_then(Value::as_array)
|
||||
.zip(sets.and_then(Value::as_array))
|
||||
.is_some_and(|(was, sets)| was.len() == sets.len() && was.iter().zip(sets).enumerate().all(|(j, (a, b))| j == i || a == b));
|
||||
!(i == k && edited_in_place)
|
||||
}
|
||||
|
||||
/// Where the Actions set at index `i` of `old` is in `new` (two `action_sets` lists): found by
|
||||
/// its contents when no other set in either list has the same contents, otherwise by its name when
|
||||
/// no other set in either list has it.
|
||||
fn find_action_set(old: Option<&serde_json::Value>, i: usize, new: Option<&serde_json::Value>) -> Option<usize> {
|
||||
use serde_json::Value;
|
||||
let (old, new) = (old?.as_array()?, new?.as_array()?);
|
||||
let set = old.get(i)?;
|
||||
let only = |list: &[Value], same: &dyn Fn(&Value) -> bool| {
|
||||
let mut found = list.iter().enumerate().filter(|(_, s)| same(s));
|
||||
match (found.next(), found.next()) {
|
||||
(Some((j, _)), None) => Some(j),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let same_contents = |s: &Value| s == set;
|
||||
if only(old, &same_contents).is_some()
|
||||
&& let Some(j) = only(new, &same_contents)
|
||||
{
|
||||
return Some(j);
|
||||
}
|
||||
let name = set.get("name")?;
|
||||
let same_name = |s: &Value| s.get("name") == Some(name);
|
||||
only(old, &same_name)?;
|
||||
only(new, &same_name)
|
||||
}
|
||||
|
||||
/// The preferences file's contents: the UI state with the engine preferences.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn prefs_bytes(app: &VectorcraftApp) -> serde_json::Result<Vec<u8>> {
|
||||
@@ -221,6 +329,8 @@ pub(crate) fn prefs_bytes(app: &VectorcraftApp) -> serde_json::Result<Vec<u8>> {
|
||||
/// [`prefs_bytes`] as JSON.
|
||||
fn prefs_value(app: &VectorcraftApp) -> serde_json::Result<serde_json::Value> {
|
||||
let mut ui = app.ui.clone();
|
||||
// An open dialog is never restored, and its fields can hold passwords (PDF import and save).
|
||||
ui.dialog = None;
|
||||
ui.engine_prefs = app.session.prefs.to_json();
|
||||
serde_json::to_value(&ui)
|
||||
}
|
||||
@@ -233,6 +343,17 @@ mod tests {
|
||||
|
||||
/// Two windows open at once (#4625): the one that saves last keeps the other's changes and
|
||||
/// adds its own, instead of putting back the preferences it started from.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_kept_preferences_copy_is_owner_only() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
let temp = tempfile::Builder::new().prefix("vc-prefs-copy-").tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
super::keep_prefs_copy(&dir.join("ui.json"), b"{}", "ui.unreadable");
|
||||
let mode = std::fs::metadata(dir.join("ui.unreadable.json")).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_saves_only_what_it_changed_over_another_windows_save() {
|
||||
let base = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.0}});
|
||||
@@ -274,6 +395,126 @@ mod tests {
|
||||
assert!(!same_lasting(&base, &mine));
|
||||
}
|
||||
|
||||
/// A file from before the Help Bar setting: the read shows the Help Bar with the status bar.
|
||||
/// After the status bar is hidden and the Help Bar left showing, the save writes `help_bar`,
|
||||
/// so the next read does not hide it with the status bar. A value on disk is kept.
|
||||
#[test]
|
||||
fn a_help_bar_setting_the_file_lacks_is_saved() {
|
||||
let base = json!({"status_bar": true, "help_bar": true});
|
||||
let mine = json!({"status_bar": false, "help_bar": true});
|
||||
let on_disk = json!({"status_bar": true});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"status_bar": false, "help_bar": true}));
|
||||
// Another window saved its own Help Bar setting: it stays.
|
||||
let on_disk = json!({"status_bar": true, "help_bar": false});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"status_bar": false, "help_bar": false}));
|
||||
}
|
||||
|
||||
/// One window deleted the first Actions set and saved; this one made the second set current.
|
||||
/// The saved index follows that set to its place in the merged list.
|
||||
#[test]
|
||||
fn the_current_action_set_follows_its_set_in_the_merged_list() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 0});
|
||||
let on_disk = json!({"action_sets": [set("B"), set("C")]});
|
||||
let mine = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B"), set("C")], "action_set": 0}));
|
||||
// The other window also recorded into B: B is found by its name.
|
||||
let on_disk = json!({"action_sets": [{"name": "B", "actions": [{"name": "Action 1", "steps": []}]}, set("C")]});
|
||||
let merged = merge_changes(&base, &mine, on_disk);
|
||||
assert_eq!(merged["action_set"], json!(0));
|
||||
// The other window deleted B: no set is current.
|
||||
let on_disk = json!({"action_sets": [set("A"), set("C")]});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("A"), set("C")]}));
|
||||
}
|
||||
|
||||
/// This window deleted the first set while the index saved by the other window still stands.
|
||||
#[test]
|
||||
fn the_other_windows_current_action_set_follows_its_set() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("B"), set("C")]});
|
||||
let on_disk = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 2});
|
||||
let mine = json!({"action_sets": [set("B"), set("C")]});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B"), set("C")], "action_set": 1}));
|
||||
}
|
||||
|
||||
/// The other window replaced or renamed the set this one made current (the saved sets do not
|
||||
/// tell the two apart): no set is current.
|
||||
#[test]
|
||||
fn a_set_in_the_place_of_the_current_set_is_not_made_current() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("B"), set("C")]});
|
||||
let on_disk = json!({"action_sets": [set("A"), set("D"), set("C")]});
|
||||
let mine = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk).get("action_set"), None);
|
||||
let on_disk = json!({"action_sets": [set("A"), set("C"), set("D")]});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk).get("action_set"), None);
|
||||
}
|
||||
|
||||
/// This window deleted a set and made the set now at the old index current: its choice is
|
||||
/// saved, though the index is the same number.
|
||||
#[test]
|
||||
fn a_new_current_set_at_the_same_index_is_saved() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1});
|
||||
let on_disk = json!({"action_sets": [{"name": "A", "actions": [{"name": "Action 1", "steps": []}]}, set("B"), set("C")], "action_set": 1});
|
||||
let mine = json!({"action_sets": [set("B"), set("C")], "action_set": 1});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B"), set("C")], "action_set": 1}));
|
||||
}
|
||||
|
||||
/// Recording into the current set does not choose it again: the other window's choice stays.
|
||||
#[test]
|
||||
fn recording_into_the_current_set_keeps_the_other_windows_choice() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let recorded = json!({"name": "A", "actions": [{"name": "Action 1", "steps": []}]});
|
||||
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 0});
|
||||
let on_disk = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 2});
|
||||
let mine = json!({"action_sets": [recorded.clone(), set("B"), set("C")], "action_set": 0});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [recorded, set("B"), set("C")], "action_set": 2}));
|
||||
}
|
||||
|
||||
/// Renaming the current set does not choose it again: the other window's choice stays. With no
|
||||
/// other choice, the renamed set stays current.
|
||||
#[test]
|
||||
fn renaming_the_current_set_keeps_the_other_windows_choice() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 0});
|
||||
let on_disk = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 1});
|
||||
let mine = json!({"action_sets": [set("A2"), set("B"), set("C")], "action_set": 0});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk)["action_set"], json!(1));
|
||||
assert_eq!(merge_changes(&base, &mine, base.clone())["action_set"], json!(0));
|
||||
}
|
||||
|
||||
/// Deleting the current set does not override the other window's choice.
|
||||
#[test]
|
||||
fn deleting_the_current_set_keeps_the_other_windows_choice() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("B")], "action_set": 0});
|
||||
let on_disk = json!({"action_sets": [set("A"), set("B")], "action_set": 1});
|
||||
let mine = json!({"action_sets": [set("B")]});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("B")], "action_set": 0}));
|
||||
assert_eq!(merge_changes(&base, &mine, base.clone()), json!({"action_sets": [set("B")]}));
|
||||
}
|
||||
|
||||
/// Deleting a set before the current one moves its index without choosing it again.
|
||||
#[test]
|
||||
fn deleting_a_set_before_the_current_one_keeps_it_current() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("B"), set("C")], "action_set": 2});
|
||||
let mine = json!({"action_sets": [set("B"), set("C")], "action_set": 1});
|
||||
assert_eq!(merge_changes(&base, &mine, base.clone()), json!({"action_sets": [set("B"), set("C")], "action_set": 1}));
|
||||
}
|
||||
|
||||
/// Two sets with the same contents: when the other window deleted the one this window made
|
||||
/// current, the one left is not made current in its place.
|
||||
#[test]
|
||||
fn a_set_with_the_same_contents_does_not_take_the_place_of_the_current_set() {
|
||||
let set = |name: &str| json!({"name": name, "actions": []});
|
||||
let base = json!({"action_sets": [set("A"), set("A"), set("C")]});
|
||||
let on_disk = json!({"action_sets": [set("A"), set("C")]});
|
||||
let mine = json!({"action_sets": [set("A"), set("A"), set("C")], "action_set": 1});
|
||||
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"action_sets": [set("A"), set("C")]}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_is_not_an_object_is_replaced() {
|
||||
let base = json!({"workspace": "Essentials"});
|
||||
|
||||
@@ -149,6 +149,15 @@ fn copy_dir(from: &Path, to: &Path) -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Make folder `dir`, owner-only on Unix.
|
||||
fn private_dir(dir: &Path) -> std::io::Result<()> {
|
||||
let mut builder = std::fs::DirBuilder::new();
|
||||
builder.recursive(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
|
||||
builder.create(dir)
|
||||
}
|
||||
|
||||
fn copy_dir_into(from: &Path, to: &Path, skip: &mut impl FnMut(String)) {
|
||||
let entries = match std::fs::read_dir(from) {
|
||||
Ok(entries) => entries,
|
||||
@@ -165,7 +174,12 @@ fn copy_dir_into(from: &Path, to: &Path, skip: &mut impl FnMut(String)) {
|
||||
let (src, dst) = (entry.path(), to.join(entry.file_name()));
|
||||
// A symbolic link is copied as what it points to, or skipped when that is a folder.
|
||||
let copied = match entry.file_type() {
|
||||
Ok(kind) if kind.is_dir() => std::fs::create_dir_all(&dst).map(|()| copy_dir_into(&src, &dst, skip)),
|
||||
// The copy keeps the folder's permissions (a private recovery folder stays private):
|
||||
// owner-only while it fills, then the source's.
|
||||
Ok(kind) if kind.is_dir() => private_dir(&dst).and_then(|()| {
|
||||
copy_dir_into(&src, &dst, skip);
|
||||
std::fs::set_permissions(&dst, std::fs::metadata(&src)?.permissions())
|
||||
}),
|
||||
Ok(_) => std::fs::copy(&src, &dst).map(|_| ()),
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
@@ -178,7 +192,22 @@ fn copy_dir_into(from: &Path, to: &Path, skip: &mut impl FnMut(String)) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
struct TestDir(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
type Target = Path;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0.path()
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<Path> for TestDir {
|
||||
fn as_ref(&self) -> &Path {
|
||||
self.0.path()
|
||||
}
|
||||
}
|
||||
|
||||
fn environment(key: &str) -> Option<OsString> {
|
||||
match key {
|
||||
@@ -273,12 +302,8 @@ mod tests {
|
||||
assert_eq!(install_dir("macos", mounted, &appimage), Some("/tmp/.mount_vc/usr/bin".into()));
|
||||
}
|
||||
|
||||
fn temp(tag: &str) -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let d = std::env::temp_dir().join(format!("vectorcraft-profile-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
fn temp(tag: &str) -> TestDir {
|
||||
TestDir(tempfile::Builder::new().prefix(&format!("vectorcraft-profile-{tag}-")).tempdir().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -387,4 +412,19 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&from);
|
||||
let _ = std::fs::remove_dir_all(&to);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_copied_folder_keeps_its_permissions() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
let from = temp("copy-mode-from");
|
||||
let to = temp("copy-mode-to");
|
||||
std::fs::create_dir_all(from.join("recovery")).unwrap();
|
||||
std::fs::write(from.join("recovery/copy.vectorcraft"), b"unsaved").unwrap();
|
||||
std::fs::set_permissions(from.join("recovery"), std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
copy_dir(&from, &to).unwrap();
|
||||
assert_eq!(std::fs::metadata(to.join("recovery")).unwrap().permissions().mode() & 0o777, 0o700);
|
||||
let _ = std::fs::remove_dir_all(&from);
|
||||
let _ = std::fs::remove_dir_all(&to);
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,12 @@
|
||||
//! as its own app, which replaces a stale file. Nothing received is ever run.
|
||||
//!
|
||||
//! Runs that start many apps side by side (`--control`, `VECTORCRAFT_NO_PREFS`) neither forward
|
||||
//! nor listen, and `--new-instance` opens a launch's files in an app of its own. macOS hands files
|
||||
//! opened from Finder to the running app itself (`open_documents`), so this is off there.
|
||||
//! nor listen, and neither does a `--safe-mode` launch, which opens its files in an app of its own
|
||||
//! and leaves later launches to start theirs with plug-ins. `--new-instance` opens a launch's files
|
||||
//! in an app of its own. An app that stays in Safe Mode after the choice about a stopped plug-in
|
||||
//! stops listening ([`resign`]), and files later launches handed it before then open in a new app
|
||||
//! with plug-ins ([`take_for_frame`]). macOS hands files opened from Finder to the running app itself
|
||||
//! (`open_documents`), so this is off there.
|
||||
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::hash::{BuildHasher as _, RandomState};
|
||||
@@ -43,6 +47,8 @@ const CLIENT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Paths handed over by later launches that the UI hasn't opened yet.
|
||||
static PENDING: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
/// This app while it is the one later launches hand their files to ([`hold`]).
|
||||
static HELD: Mutex<Option<Primary>> = Mutex::new(None);
|
||||
/// The UI to wake when files arrive (unset until the window exists; the first frame opens them).
|
||||
static UI: OnceLock<egui::Context> = OnceLock::new();
|
||||
|
||||
@@ -56,23 +62,46 @@ pub enum Start {
|
||||
|
||||
/// Hand `files` to the app already running, or become the app later launches hand theirs to.
|
||||
/// `automation`: started with `--control`.
|
||||
pub fn start(automation: bool, new_instance: bool, files: &[String]) -> Start {
|
||||
pub fn start(automation: bool, new_instance: bool, safe_mode: bool, files: &[String]) -> Start {
|
||||
if automation || !prefs_enabled() {
|
||||
return Start::Running(None);
|
||||
}
|
||||
let Some(path) = prefs_path().and_then(|p| Some(p.parent()?.join(FILE_NAME))) else { return Start::Running(None) };
|
||||
start_at(&path, new_instance, safe_mode, files)
|
||||
}
|
||||
|
||||
/// [`start`] with the endpoint file `path`. A launch with `--new-instance` or `--safe-mode` keeps
|
||||
/// its files and runs as its own app: a running app would open them with its plug-ins loaded. A
|
||||
/// `--safe-mode` launch never becomes the app later launches hand their files to, which would open
|
||||
/// them without plug-ins.
|
||||
fn start_at(path: &Path, new_instance: bool, safe_mode: bool, files: &[String]) -> Start {
|
||||
if safe_mode {
|
||||
return Start::Running(None);
|
||||
}
|
||||
// With nothing to hand over, the same exchange only asks whether an app is running.
|
||||
let send: &[String] = if new_instance { &[] } else { files };
|
||||
match forward(&path, send) {
|
||||
match forward(path, send) {
|
||||
Ok(()) if send.is_empty() => Start::Running(None),
|
||||
Ok(()) => Start::Forwarded,
|
||||
Err(e) => {
|
||||
log::debug!("no running VectorCraft to hand files to ({e})");
|
||||
Start::Running(listen(&path, queue))
|
||||
Start::Running(listen(path, queue))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep `primary` ([`start`]'s) until [`resign`].
|
||||
pub fn hold(primary: Option<Primary>) {
|
||||
*HELD.lock().unwrap_or_else(PoisonError::into_inner) = primary;
|
||||
}
|
||||
|
||||
/// Later launches start their own app from now on: the endpoint file goes. The app calls it when
|
||||
/// its window is gone, and when it stays in Safe Mode after the choice about a stopped plug-in.
|
||||
pub fn resign() {
|
||||
let primary = HELD.lock().unwrap_or_else(PoisonError::into_inner).take();
|
||||
drop(primary);
|
||||
}
|
||||
|
||||
/// Wake `ctx` when files arrive from later launches.
|
||||
pub fn set_ui(ctx: &egui::Context) {
|
||||
// Set once; a second call would hand over the same context.
|
||||
@@ -84,6 +113,43 @@ pub fn take() -> Vec<String> {
|
||||
std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner))
|
||||
}
|
||||
|
||||
/// The paths later launches handed over since the last call, to open in this app. An app that
|
||||
/// stays in Safe Mode (`safe_mode`) resigns and hands them to a new app with plug-ins (`launch`,
|
||||
/// [`launch_with_plug_ins`] in the app) instead: they arrived while it was the primary, before the
|
||||
/// choice about a stopped plug-in ended in Safe Mode, or just before it resigned. When `launch`
|
||||
/// fails (logged), they open here.
|
||||
pub fn take_for_frame(safe_mode: bool, launch: impl FnOnce(&[String]) -> io::Result<()>) -> Vec<String> {
|
||||
let files = take();
|
||||
if !safe_mode {
|
||||
return files;
|
||||
}
|
||||
// First, so the new app becomes the primary instead of handing the files back.
|
||||
resign();
|
||||
if files.is_empty() {
|
||||
return files;
|
||||
}
|
||||
match launch(&files) {
|
||||
Ok(()) => Vec::new(),
|
||||
Err(e) => {
|
||||
log::warn!("couldn't start VectorCraft with plug-ins for the files another launch opened: {e}");
|
||||
files
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start this program again, with plug-ins, on `files`.
|
||||
pub fn launch_with_plug_ins(files: &[String]) -> io::Result<()> {
|
||||
app_with_plug_ins(&std::env::current_exe()?, files).spawn().map(drop)
|
||||
}
|
||||
|
||||
/// The command [`launch_with_plug_ins`] runs: `exe -- files…`, so a file whose name starts with '-'
|
||||
/// stays a file.
|
||||
fn app_with_plug_ins(exe: &Path, files: &[String]) -> std::process::Command {
|
||||
let mut command = std::process::Command::new(exe);
|
||||
command.arg("--").args(files);
|
||||
command
|
||||
}
|
||||
|
||||
fn queue(files: Vec<String>) {
|
||||
PENDING.lock().unwrap_or_else(PoisonError::into_inner).extend(files);
|
||||
if let Some(ctx) = UI.get() {
|
||||
@@ -263,15 +329,30 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Held by the tests that use the process-wide [`HELD`] and [`PENDING`], one at a time.
|
||||
static GLOBALS: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn globals() -> std::sync::MutexGuard<'static, ()> {
|
||||
GLOBALS.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
struct TestDir(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
type Target = Path;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0.path()
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder for one test, with an existing file in it.
|
||||
fn folder(name: &str) -> (PathBuf, PathBuf, String) {
|
||||
let dir = std::env::temp_dir().join(format!("vc-single-instance-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("a b.svg");
|
||||
fn folder(name: &str) -> (PathBuf, TestDir, String) {
|
||||
let dir = tempfile::Builder::new().prefix(&format!("vc-single-instance-{name}-")).tempdir().unwrap();
|
||||
let file = dir.path().join("a b.svg");
|
||||
fs::write(&file, "<svg/>").unwrap();
|
||||
let file = file.to_string_lossy().into_owned();
|
||||
(dir.join(FILE_NAME), dir, file)
|
||||
(dir.path().join(FILE_NAME), TestDir(dir), file)
|
||||
}
|
||||
|
||||
fn primary(path: &Path) -> (Primary, mpsc::Receiver<Vec<String>>) {
|
||||
@@ -303,12 +384,77 @@ mod tests {
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
|
||||
drop(primary);
|
||||
assert!(!path.exists(), "the endpoint file goes with the app");
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_instance_or_safe_mode_launch_keeps_its_files() {
|
||||
let (path, _dir, file) = folder("own");
|
||||
let (primary, rx) = primary(&path);
|
||||
for (new_instance, safe_mode) in [(true, false), (false, true)] {
|
||||
let start = start_at(&path, new_instance, safe_mode, std::slice::from_ref(&file));
|
||||
assert!(matches!(start, Start::Running(None)), "runs as its own app (new instance {new_instance}, Safe Mode {safe_mode})");
|
||||
}
|
||||
assert!(matches!(start_at(&path, false, false, std::slice::from_ref(&file)), Start::Forwarded));
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file));
|
||||
assert!(rx.try_recv().is_err(), "only the plain launch handed its file over");
|
||||
drop(primary);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_safe_mode_launch_leaves_later_launches_their_own_app() {
|
||||
let _globals = globals();
|
||||
let (path, _dir, file) = folder("safe-mode-alone");
|
||||
// With no app running, a Safe Mode launch runs without listening.
|
||||
assert!(matches!(start_at(&path, false, true, std::slice::from_ref(&file)), Start::Running(None)));
|
||||
assert!(!path.exists(), "a Safe Mode launch records no endpoint");
|
||||
// A plain launch after it starts its own app and takes later launches' files.
|
||||
let Start::Running(Some(primary)) = start_at(&path, false, false, std::slice::from_ref(&file)) else {
|
||||
panic!("the plain launch runs and listens")
|
||||
};
|
||||
assert!(path.exists());
|
||||
// An app that stays in Safe Mode after the choice gives that up.
|
||||
hold(Some(primary));
|
||||
resign();
|
||||
assert!(!path.exists(), "the endpoint file goes with resign");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_handed_to_an_app_staying_in_safe_mode_go_to_a_new_app_with_plug_ins() {
|
||||
let _globals = globals();
|
||||
// Nothing left over from a test that failed.
|
||||
resign();
|
||||
drop(take());
|
||||
let (path, _dir, file) = folder("safe-mode-later");
|
||||
let Start::Running(Some(primary)) = start_at(&path, false, false, &[]) else { panic!("the first launch listens") };
|
||||
hold(Some(primary));
|
||||
// A later launch handed its file over while the choice about a stopped plug-in was up.
|
||||
queue(vec![file.clone()]);
|
||||
let mut launched = Vec::new();
|
||||
let here = take_for_frame(true, |files| {
|
||||
launched = files.to_vec();
|
||||
Ok(())
|
||||
});
|
||||
assert!(here.is_empty(), "nothing opens in the Safe Mode app");
|
||||
assert_eq!(launched, std::slice::from_ref(&file), "a new app with plug-ins opens it");
|
||||
assert!(!path.exists(), "the app resigned before starting the new one");
|
||||
// When the new app can't start, the file opens here rather than being lost.
|
||||
queue(vec![file.clone()]);
|
||||
assert_eq!(take_for_frame(true, |_| Err(io::Error::other("no program"))), std::slice::from_ref(&file));
|
||||
// An app with plug-ins opens what it is handed.
|
||||
queue(vec![file.clone()]);
|
||||
assert_eq!(take_for_frame(false, |_| panic!("no new app")), [file]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_new_app_takes_every_name_as_a_file() {
|
||||
let command = app_with_plug_ins(Path::new("vectorcraft"), &["-a.svg".to_owned(), "b.svg".to_owned()]);
|
||||
let args: Vec<_> = command.get_args().collect();
|
||||
assert_eq!(args, ["--", "-a.svg", "b.svg"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_token_garbage_and_oversized_messages_are_refused() {
|
||||
let (path, dir, file) = folder("refused");
|
||||
let (path, _dir, file) = folder("refused");
|
||||
let (_primary, rx) = primary(&path);
|
||||
let token = read_endpoint(&path).unwrap().token;
|
||||
let wrong = format!("{}\n", json!({ "token": "0".repeat(token.len()), "files": [file] }));
|
||||
@@ -323,16 +469,20 @@ mod tests {
|
||||
// The listener still serves a launch with the right token.
|
||||
forward(&path, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_endpoint_file_is_ignored_and_replaced() {
|
||||
let (path, dir, file) = folder("stale");
|
||||
// No listener on the recorded port any more.
|
||||
let port = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap().local_addr().unwrap().port();
|
||||
let (path, _dir, file) = folder("stale");
|
||||
// The recorded app is gone: whatever holds the port closes without a greeting. (A freed
|
||||
// port can be taken by another test's listener meanwhile, which would then accept this
|
||||
// connection in place of its own client's.)
|
||||
let gone = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let port = gone.local_addr().unwrap().port();
|
||||
write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap();
|
||||
let closed = std::thread::spawn(move || drop(gone.accept()));
|
||||
assert!(forward(&path, std::slice::from_ref(&file)).is_err());
|
||||
closed.join().unwrap();
|
||||
// A listener that doesn't know the greeting gets neither the token nor the paths.
|
||||
let impostor = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let port = impostor.local_addr().unwrap().port();
|
||||
@@ -352,18 +502,16 @@ mod tests {
|
||||
let (_primary, rx) = primary(&path);
|
||||
forward(&path, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replaced_endpoint_file_stays_when_the_earlier_app_ends() {
|
||||
let (path, dir, _) = folder("replaced");
|
||||
let (path, _dir, _) = folder("replaced");
|
||||
let (first, _rx1) = primary(&path);
|
||||
let (_second, _rx2) = primary(&path);
|
||||
let second_token = read_endpoint(&path).unwrap().token;
|
||||
drop(first);
|
||||
assert_eq!(read_endpoint(&path).map(|e| e.token), Some(second_token));
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -378,9 +526,8 @@ mod tests {
|
||||
#[test]
|
||||
fn the_endpoint_file_is_the_users_alone() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
let (path, dir, _) = folder("mode");
|
||||
let (path, _dir, _) = folder("mode");
|
||||
let _primary = primary(&path);
|
||||
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -284,8 +284,8 @@ mod tests {
|
||||
#[test]
|
||||
fn fonts_only_gdi_has_loaded_are_listed_by_their_files() {
|
||||
use windows::Win32::Graphics::Gdi::{AddFontResourceExW, FR_PRIVATE, RemoveFontResourceExW};
|
||||
let dir = std::env::temp_dir().join(format!("vc-gdi-fonts-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let temp = tempfile::Builder::new().prefix("vc-gdi-fonts-").tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
let file = dir.join("29457");
|
||||
let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf");
|
||||
let mut data = std::fs::read(source).unwrap();
|
||||
@@ -303,7 +303,6 @@ mod tests {
|
||||
assert_eq!(unsafe { AddFontResourceExW(&path, FR_PRIVATE, None) }, 1);
|
||||
let files = super::font_files();
|
||||
let _ = unsafe { RemoveFontResourceExW(&path, FR_PRIVATE.0, None) };
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let wanted = file.to_string_lossy().to_lowercase();
|
||||
assert!(files.iter().any(|f| f.to_lowercase() == wanted), "{wanted} not in {} files", files.len());
|
||||
}
|
||||
|
||||
@@ -1,17 +1,24 @@
|
||||
//! Linux: a drawing tablet's pen pressure under X11, XWayland included (#764). winit 0.30 hands a
|
||||
//! pen to the window there as a mouse, without its pressure, so the app reads the pressure from
|
||||
//! XInput2 itself and writes it into the UI's [`StylusFeed`] (`Services::stylus`), which the canvas
|
||||
//! reads.
|
||||
//! Linux: a drawing tablet's pen pressure, tilt and barrel rotation under X11, XWayland included
|
||||
//! (#764). winit 0.30 hands a pen to the window there as a mouse, without any of them, so the app
|
||||
//! reads them from XInput2 itself and writes them into the UI's [`StylusFeed`]
|
||||
//! (`Services::stylus`), which the canvas reads.
|
||||
//!
|
||||
//! The reader opens a second connection to the X server (x11rb's `RustConnection`, without
|
||||
//! `unsafe` or libxcb) and selects XInput2 raw events for every device on the root window. Raw
|
||||
//! events reach every client that selects them, also while winit holds the pointer grab of a
|
||||
//! drag, and name the device that moved. A pointer device with an "Abs Pressure" valuator is a pen
|
||||
//! (xf86-input-wacom, xf86-input-libinput and XWayland give a pen's pressure axis that label),
|
||||
//! unless its XInput type is a touchpad's or a touchscreen's: its pressure, scaled from the
|
||||
//! valuator's range to 0..1, goes into the feed. Any other pointer
|
||||
//! device moving sets the feed to `None`. Raw events carry only the valuators that changed, so
|
||||
//! the last pressure of each pen is kept.
|
||||
//! unless its XInput type is a touchpad's or a touchscreen's. Its valuators go into the feed:
|
||||
//!
|
||||
//! - "Abs Pressure", scaled from the valuator's range to 0..1;
|
||||
//! - "Abs Tilt X" and "Abs Tilt Y" (a pen that has both), in degrees as they are when the range
|
||||
//! fits in ±90, otherwise scaled to ±[`TILT_DEGREES`];
|
||||
//! - "Abs Rotary Z" (the barrel rotation of an Art Pen), scaled to a turn with the middle of the
|
||||
//! range at 0°.
|
||||
//!
|
||||
//! Any other pointer device moving sets the feed to `None`. Raw events carry only the valuators
|
||||
//! that changed, so the last value of each axis of each pen is kept; an axis the pen has that no
|
||||
//! event has carried yet reads 0 (upright, unturned), and an axis it lacks reads nothing.
|
||||
//!
|
||||
//! The X server lists a pen's eraser end as a device of its own, whose name or XInput type contains
|
||||
//! "eraser" (xf86-input-wacom's "… Pen eraser" of type `ERASER`, xf86-input-libinput's
|
||||
@@ -22,13 +29,18 @@
|
||||
//! The reader starts only for a window on X11. On native Wayland, `DISPLAY` names an XWayland
|
||||
//! that receives none of the window's input.
|
||||
//!
|
||||
//! The mapping and the reader come from PhotoCraft's `crates/tablet` (`xi.rs` and `x11.rs`), with
|
||||
//! the pressure axis only.
|
||||
//! The mapping and the reader come from PhotoCraft's `crates/tablet` (`xi.rs` and `x11.rs`).
|
||||
//! PhotoCraft maps the rotation to 0..360° and reads an axis a pen lacks as 0; here the middle of
|
||||
//! the rotation's range is 0°, and an axis a pen lacks reads nothing.
|
||||
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vectorcraft_ui_egui::stylus::{PenSample, StylusFeed};
|
||||
use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed};
|
||||
|
||||
/// The tilt of a valuator whose range does not fit in ±90 (so does not give degrees), at the ends
|
||||
/// of its range.
|
||||
pub(crate) const TILT_DEGREES: f64 = 60.0;
|
||||
|
||||
/// Valuator numbers from this one on are ignored (the protocol allows 65,535; tablets have fewer
|
||||
/// than 16).
|
||||
@@ -41,33 +53,76 @@ const MAX_DEVICES: usize = 256;
|
||||
/// a touchpad's or a touchscreen's pressure axis "Abs Pressure" too, and they are not pens.
|
||||
const FINGER_TYPES: &[&str] = &["TOUCHPAD", "TOUCHSCREEN"];
|
||||
|
||||
/// The "Abs Pressure" valuator of a pen: its number in a raw event's valuator mask, and its range.
|
||||
/// Which pen axis a valuator carries.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum AxisKind {
|
||||
Pressure,
|
||||
TiltX,
|
||||
TiltY,
|
||||
Rotation,
|
||||
}
|
||||
|
||||
impl AxisKind {
|
||||
/// The kind of the valuator labeled `label`, if it is one of a pen's.
|
||||
fn from_label(label: &str) -> Option<Self> {
|
||||
match label {
|
||||
"Abs Pressure" => Some(Self::Pressure),
|
||||
"Abs Tilt X" => Some(Self::TiltX),
|
||||
"Abs Tilt Y" => Some(Self::TiltY),
|
||||
"Abs Rotary Z" => Some(Self::Rotation),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where [`Pens`] keeps the last value of this axis.
|
||||
fn slot(self) -> usize {
|
||||
match self {
|
||||
Self::Pressure => 0,
|
||||
Self::TiltX => 1,
|
||||
Self::TiltY => 2,
|
||||
Self::Rotation => 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A valuator of a pen: what it carries, its number in a raw event's valuator mask, and its range.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Axis {
|
||||
kind: AxisKind,
|
||||
number: u16,
|
||||
min: f64,
|
||||
max: f64,
|
||||
}
|
||||
|
||||
impl Axis {
|
||||
/// A raw value of this valuator as a pressure of 0..1; a value that is not a number is a
|
||||
/// mouse's, 1.
|
||||
fn pressure(&self, v: f64) -> f32 {
|
||||
/// A raw value of this valuator as a pressure of 0..1, a tilt in degrees (−90..90) or a
|
||||
/// rotation in degrees (−180..180, the middle of the range at 0). A value that is not a number
|
||||
/// is a mouse's pressure, 1, or a tilt or rotation of 0.
|
||||
fn map(&self, v: f64) -> f32 {
|
||||
if !v.is_finite() {
|
||||
return 1.0;
|
||||
return if self.kind == AxisKind::Pressure { 1.0 } else { 0.0 };
|
||||
}
|
||||
let span = self.max - self.min;
|
||||
let unit = if span.is_finite() && span > 0.0 { (v - self.min) / span } else { v };
|
||||
unit.clamp(0.0, 1.0) as f32
|
||||
let unit = unit.clamp(0.0, 1.0);
|
||||
match self.kind {
|
||||
AxisKind::Pressure => unit as f32,
|
||||
AxisKind::TiltX | AxisKind::TiltY if self.min >= -90.0 && self.max <= 90.0 && span > 0.0 => v.clamp(-90.0, 90.0) as f32,
|
||||
AxisKind::TiltX | AxisKind::TiltY => ((unit * 2.0 - 1.0) * TILT_DEGREES) as f32,
|
||||
AxisKind::Rotation => ((unit - 0.5) * 360.0) as f32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A pointer device the X server lists.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Device {
|
||||
id: u16,
|
||||
/// The pressure valuator: a pen has one, a mouse, a touchpad or a touchscreen has none.
|
||||
pressure: Option<Axis>,
|
||||
/// The name the X server lists, so that another device under the same id compares unequal.
|
||||
name: String,
|
||||
/// The pen's valuators: a pen has a pressure valuator, a mouse, a touchpad or a touchscreen
|
||||
/// has none (and keeps none).
|
||||
axes: Vec<Axis>,
|
||||
/// The eraser end of a pen: its name or its XInput type contains "eraser", in any case.
|
||||
eraser: bool,
|
||||
}
|
||||
@@ -77,14 +132,31 @@ impl Device {
|
||||
/// minimum and maximum (`XIQueryDevice`), and its XInput type (`ListInputDevices`).
|
||||
fn new(id: u16, name: &str, kind: Option<&str>, valuators: impl IntoIterator<Item = (u16, String, f64, f64)>) -> Self {
|
||||
let finger = kind.is_some_and(|k| FINGER_TYPES.contains(&k));
|
||||
let pressure = valuators
|
||||
.into_iter()
|
||||
.filter(|(number, ..)| *number < MAX_AXES)
|
||||
.find(|(_, label, ..)| label == "Abs Pressure")
|
||||
.map(|(number, _, min, max)| Axis { number, min, max })
|
||||
.filter(|_| !finger);
|
||||
let mut axes: Vec<Axis> = Vec::new();
|
||||
for (number, label, min, max) in valuators {
|
||||
// The first valuator of each kind.
|
||||
if let Some(kind) = AxisKind::from_label(&label)
|
||||
&& number < MAX_AXES
|
||||
&& !axes.iter().any(|a| a.kind == kind)
|
||||
{
|
||||
axes.push(Axis { kind, number, min, max });
|
||||
}
|
||||
}
|
||||
if finger || !axes.iter().any(|a| a.kind == AxisKind::Pressure) {
|
||||
axes.clear();
|
||||
}
|
||||
let eraser = [Some(name), kind].into_iter().flatten().any(|s| s.to_ascii_lowercase().contains("eraser"));
|
||||
Self { id, pressure, eraser }
|
||||
Self { id, name: name.to_string(), axes, eraser }
|
||||
}
|
||||
|
||||
/// The valuator of `kind`, if the device is a pen that has one.
|
||||
fn axis(&self, kind: AxisKind) -> Option<&Axis> {
|
||||
self.axes.iter().find(|a| a.kind == kind)
|
||||
}
|
||||
|
||||
/// A pen: a device with a pressure valuator.
|
||||
fn is_pen(&self) -> bool {
|
||||
!self.axes.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,36 +165,46 @@ impl Device {
|
||||
enum Update {
|
||||
/// Nothing: a device the last listing didn't have (a master, or one added since).
|
||||
Keep,
|
||||
/// The pressure and end of a pen, or `None` for another pointer.
|
||||
/// The pressure, end, tilt and rotation of a pen, or `None` for another pointer.
|
||||
Set(Option<PenSample>),
|
||||
}
|
||||
|
||||
/// The pointer devices and the last pressure of each pen.
|
||||
/// The pointer devices and the last pressure, tilt and rotation of each pen.
|
||||
#[derive(Debug, Default)]
|
||||
struct Pens {
|
||||
devices: HashMap<u16, Device>,
|
||||
last: HashMap<u16, f32>,
|
||||
last: HashMap<u16, [Option<f32>; 4]>,
|
||||
}
|
||||
|
||||
impl Pens {
|
||||
/// Replace the device list (at the start, and when devices come and go or change).
|
||||
/// A device keeps its last values only while it is listed unchanged: another device under the
|
||||
/// same id starts without them.
|
||||
fn set_devices(&mut self, devices: impl IntoIterator<Item = Device>) {
|
||||
self.devices = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect();
|
||||
self.last.retain(|id, _| self.devices.contains_key(id));
|
||||
let devices: HashMap<u16, Device> = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect();
|
||||
self.last.retain(|id, _| devices.get(id).is_some_and(|d| self.devices.get(id) == Some(d)));
|
||||
self.devices = devices;
|
||||
}
|
||||
|
||||
/// A raw motion or button event of device `id`, with the valuators that changed.
|
||||
fn handle(&mut self, id: u16, valuators: impl IntoIterator<Item = (u16, f64)>) -> Update {
|
||||
let Some(device) = self.devices.get(&id) else { return Update::Keep };
|
||||
let Some(axis) = device.pressure else { return Update::Set(None) };
|
||||
let eraser = device.eraser;
|
||||
let last = self.last.entry(id).or_insert(0.0);
|
||||
if !device.is_pen() {
|
||||
return Update::Set(None);
|
||||
}
|
||||
let last = self.last.entry(id).or_default();
|
||||
for (number, v) in valuators {
|
||||
if number == axis.number {
|
||||
*last = axis.pressure(v);
|
||||
for axis in device.axes.iter().filter(|a| a.number == number) {
|
||||
if let Some(slot) = last.get_mut(axis.kind.slot()) {
|
||||
*slot = Some(axis.map(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
Update::Set(Some(PenSample { pressure: *last, eraser }))
|
||||
// An axis the pen has reads 0 until an event carries it; one it lacks reads nothing.
|
||||
let value = |kind: AxisKind| device.axis(kind).map(|_| last.get(kind.slot()).copied().flatten().unwrap_or(0.0));
|
||||
let tilt = value(AxisKind::TiltX).zip(value(AxisKind::TiltY)).map(|(x, y)| [x, y]);
|
||||
let pose = PenPose { tilt, rotation: value(AxisKind::Rotation) };
|
||||
Update::Set(Some(PenSample { pressure: value(AxisKind::Pressure).unwrap_or(0.0), eraser: device.eraser, pose }))
|
||||
}
|
||||
|
||||
/// A raw event as the X server sends it: its valuator mask and the values of the valuators
|
||||
@@ -149,8 +231,8 @@ fn fp3232(integral: i32, frac: u32) -> f64 {
|
||||
f64::from(integral) + f64::from(frac) / 4_294_967_296.0
|
||||
}
|
||||
|
||||
/// Start reading pen pressure for a window on X11: the feed the reader writes into, or `None`
|
||||
/// (logged) when the X server can't be reached or has no XInput 2.1.
|
||||
/// Start reading pen pressure, tilt and rotation for a window on X11: the feed the reader writes
|
||||
/// into, or `None` (logged) when the X server can't be reached or has no XInput 2.1.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn start() -> Option<StylusFeed> {
|
||||
let feed = StylusFeed::default();
|
||||
@@ -224,7 +306,7 @@ mod x11 {
|
||||
}
|
||||
}
|
||||
|
||||
/// The slave pointer devices with their names and pressure valuators (none on any error).
|
||||
/// The slave pointer devices with their names and pen valuators (none on any error).
|
||||
fn query_devices(conn: &RustConnection) -> Vec<Device> {
|
||||
let Ok(reply) = conn.xinput_xi_query_device(ALL_DEVICES).map_err(drop).and_then(|c| c.reply().map_err(drop)) else { return Vec::new() };
|
||||
let kinds = device_kinds(conn);
|
||||
@@ -265,14 +347,16 @@ mod x11 {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The valuators of a Wacom pen as the X server lists them: x and y, then pressure from 0 to
|
||||
/// 65,535.
|
||||
/// The valuators of a Wacom pen as the X server lists them: x and y, pressure from 0 to
|
||||
/// 65,535, tilt in degrees, and an Art Pen's barrel rotation.
|
||||
fn pen_valuators() -> Vec<(u16, String, f64, f64)> {
|
||||
vec![
|
||||
(0, "Abs X".to_string(), 0.0, 44704.0),
|
||||
(1, "Abs Y".to_string(), 0.0, 27940.0),
|
||||
(2, "Abs Pressure".to_string(), 0.0, 65535.0),
|
||||
(3, "Abs Tilt X".to_string(), -64.0, 63.0),
|
||||
(4, "Abs Tilt Y".to_string(), -64.0, 63.0),
|
||||
(5, "Abs Rotary Z".to_string(), -900.0, 899.0),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -295,19 +379,22 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_device_with_an_abs_pressure_valuator_is_a_pen() {
|
||||
assert_eq!(pen(9).pressure, Some(Axis { number: 2, min: 0.0, max: 65535.0 }));
|
||||
assert_eq!(mouse(12).pressure, None);
|
||||
assert_eq!(pen(9).axis(AxisKind::Pressure), Some(&Axis { kind: AxisKind::Pressure, number: 2, min: 0.0, max: 65535.0 }));
|
||||
assert_eq!(pen(9).axes.len(), 4, "pressure, tilt and rotation");
|
||||
assert!(!mouse(12).is_pen());
|
||||
let pad = Device::new(13, "Wacom Intuos Pro M Pad pad", Some("PAD"), [(5, "Abs Wheel".to_string(), 0.0, 71.0)]);
|
||||
assert_eq!(pad.pressure, None, "a tablet's pad is no pen");
|
||||
assert!(!pad.is_pen() && pad.axes.is_empty(), "a tablet's pad is no pen");
|
||||
let far = Device::new(14, "", Some("STYLUS"), [(MAX_AXES, "Abs Pressure".to_string(), 0.0, 1.0)]);
|
||||
assert_eq!(far.pressure, None, "valuator numbers past the limit are ignored");
|
||||
assert!(!far.is_pen(), "valuator numbers past the limit are ignored");
|
||||
let tilt_only = Device::new(14, "", Some("STYLUS"), [(3, "Abs Tilt X".to_string(), -64.0, 63.0), (4, "Abs Tilt Y".to_string(), -64.0, 63.0)]);
|
||||
assert!(!tilt_only.is_pen() && tilt_only.axes.is_empty(), "no pressure, no pen");
|
||||
// The types libinput and XWayland give pens, and a device whose type wasn't listed.
|
||||
for kind in [Some("TABLET"), Some("ERASER"), Some("xwayland-tablet stylus"), None] {
|
||||
assert!(Device::new(15, "", kind, pen_valuators()).pressure.is_some(), "{kind:?}");
|
||||
assert!(Device::new(15, "", kind, pen_valuators()).is_pen(), "{kind:?}");
|
||||
}
|
||||
// xf86-input-evdev labels a touchpad's and a touchscreen's finger pressure "Abs Pressure".
|
||||
for kind in ["TOUCHPAD", "TOUCHSCREEN"] {
|
||||
assert_eq!(Device::new(16, "", Some(kind), pen_valuators()).pressure, None, "{kind}");
|
||||
assert!(Device::new(16, "", Some(kind), pen_valuators()).axes.is_empty(), "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,7 +411,7 @@ mod tests {
|
||||
];
|
||||
for (name, kind) in erasers {
|
||||
let d = Device::new(10, name, kind, pen_valuators());
|
||||
assert!(d.eraser && d.pressure.is_some(), "{name} ({kind:?})");
|
||||
assert!(d.eraser && d.is_pen(), "{name} ({kind:?})");
|
||||
}
|
||||
let tips = [
|
||||
("Wacom Intuos Pro M Pen stylus", Some("STYLUS")),
|
||||
@@ -343,13 +430,14 @@ mod tests {
|
||||
let mut pens = Pens::default();
|
||||
pens.set_devices([pen(9), Device::new(10, "Wacom Intuos Pro M Pen eraser", Some("ERASER"), pen_valuators()), mouse(12)]);
|
||||
let feed = StylusFeed::default();
|
||||
let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
pens.raw_event(&feed, 9, &[0b100], &[32767.5]);
|
||||
assert_eq!(pens.handle(9, []), Update::Set(Some(PenSample { pressure: 0.5, eraser: false })));
|
||||
assert_eq!(pens.handle(9, []), Update::Set(Some(PenSample { pressure: 0.5, eraser: false, pose })));
|
||||
assert_eq!(feed.eraser(), Some(false));
|
||||
// Turned over, the pen hovers with its eraser end: the eraser device's first event, with
|
||||
// no pressure yet.
|
||||
pens.raw_event(&feed, 10, &[0b1], &[100.0]);
|
||||
assert_eq!(pens.handle(10, []), Update::Set(Some(PenSample { pressure: 0.0, eraser: true })));
|
||||
assert_eq!(pens.handle(10, []), Update::Set(Some(PenSample { pressure: 0.0, eraser: true, pose })));
|
||||
assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(0.0)));
|
||||
pens.raw_event(&feed, 10, &[0b100], &[65535.0]);
|
||||
assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(1.0)));
|
||||
@@ -361,6 +449,71 @@ mod tests {
|
||||
assert_eq!(feed.eraser(), None);
|
||||
}
|
||||
|
||||
/// #764: a pen's tilt goes into the feed in degrees and its barrel rotation as a turn, the
|
||||
/// middle of the valuator's range at 0°; a pen without those valuators reads neither.
|
||||
#[test]
|
||||
fn a_pens_tilt_and_rotation_go_into_the_feed() {
|
||||
let mut pens = Pens::default();
|
||||
let pressure_only = Device::new(10, "", Some("STYLUS"), pen_valuators().into_iter().take(3));
|
||||
let one_tilt = Device::new(11, "", Some("STYLUS"), pen_valuators().into_iter().take(4));
|
||||
pens.set_devices([pen(9), pressure_only, one_tilt, mouse(12)]);
|
||||
let feed = StylusFeed::default();
|
||||
// Pressure, tilt x, tilt y and rotation: valuators 2 to 5.
|
||||
pens.raw_event(&feed, 9, &[0b11_1100], &[32767.5, -30.0, 45.0, 0.0]);
|
||||
let pose = feed.pose().unwrap();
|
||||
assert_eq!((feed.held(), pose.tilt), (Some(0.5), Some([-30.0, 45.0])));
|
||||
assert!(pose.rotation.is_some_and(|r| r < 0.2), "{pose:?}");
|
||||
// A quarter of the range back is a quarter turn back; the tilt stays as it was.
|
||||
pens.raw_event(&feed, 9, &[0b10_0000], &[-450.0]);
|
||||
let pose = feed.pose().unwrap();
|
||||
assert_eq!(pose.tilt, Some([-30.0, 45.0]));
|
||||
assert!(pose.rotation.is_some_and(|r| (r - 270.0).abs() < 0.2), "{pose:?}");
|
||||
// A pen with no tilt or rotation valuators, or with one tilt valuator only, reads none.
|
||||
pens.raw_event(&feed, 10, &[0b100], &[65535.0]);
|
||||
assert_eq!((feed.held(), feed.pose()), (Some(1.0), None));
|
||||
pens.raw_event(&feed, 11, &[0b1100], &[65535.0, 20.0]);
|
||||
assert_eq!(feed.pose(), None);
|
||||
// The mouse: none.
|
||||
pens.raw_event(&feed, 12, &[0b1], &[3.0]);
|
||||
assert_eq!(feed.pose(), None);
|
||||
// A pen whose tilt and rotation no event has carried yet is upright and unturned.
|
||||
let mut fresh = Pens::default();
|
||||
fresh.set_devices([pen(9)]);
|
||||
let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
assert_eq!(fresh.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright })));
|
||||
}
|
||||
|
||||
/// A device listed again unchanged keeps its last tilt and rotation; another device listed
|
||||
/// under the same id starts upright and unturned.
|
||||
#[test]
|
||||
fn a_device_replaced_under_the_same_id_starts_without_the_old_pose() {
|
||||
let mut pens = Pens::default();
|
||||
pens.set_devices([pen(9)]);
|
||||
pens.handle(9, [(3, -30.0), (4, 45.0), (5, -450.0)]);
|
||||
pens.set_devices([pen(9)]);
|
||||
let Update::Set(Some(PenSample { pose, .. })) = pens.handle(9, [(2, 0.0)]) else { panic!("no pen") };
|
||||
assert_eq!(pose.tilt, Some([-30.0, 45.0]));
|
||||
let other = Device::new(9, "HUION Kamvas Pen Pen (0x1)", Some("STYLUS"), pen_valuators());
|
||||
pens.set_devices([other]);
|
||||
let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) };
|
||||
assert_eq!(pens.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright })));
|
||||
}
|
||||
|
||||
/// Tilt valuators whose range does not fit in ±90 are scaled to ±60°.
|
||||
#[test]
|
||||
fn tilt_ranges_that_are_not_degrees_are_scaled() {
|
||||
let d = Device::new(
|
||||
1,
|
||||
"",
|
||||
None,
|
||||
[(2, "Abs Pressure".into(), 0.0, 1023.0), (3, "Abs Tilt X".into(), 0.0, 127.0), (4, "Abs Tilt Y".into(), -1000.0, 1000.0)],
|
||||
);
|
||||
let mut pens = Pens::default();
|
||||
pens.set_devices([d]);
|
||||
let Update::Set(Some(PenSample { pose, .. })) = pens.handle(1, [(3, 127.0), (4, -1000.0)]) else { panic!("no pen") };
|
||||
assert_eq!(pose.tilt, Some([60.0, -60.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pens_valuator_becomes_its_pressure_and_another_pointer_clears_it() {
|
||||
let mut pens = Pens::default();
|
||||
@@ -389,13 +542,19 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn hostile_device_data_gives_a_pressure_within_0_to_1() {
|
||||
let ranges = [(5.0, 5.0), (1.0, -1.0), (f64::NEG_INFINITY, f64::INFINITY), (f64::NAN, f64::NAN)];
|
||||
let ranges = [(5.0, 5.0), (1.0, -1.0), (f64::NEG_INFINITY, f64::INFINITY), (f64::NAN, f64::NAN), (90.0, -90.0)];
|
||||
for (min, max) in ranges {
|
||||
let mut pens = Pens::default();
|
||||
pens.set_devices([Device::new(1, "", None, [(2, "Abs Pressure".to_string(), min, max)])]);
|
||||
let labels = ["Abs Pressure", "Abs Tilt X", "Abs Tilt Y", "Abs Rotary Z"];
|
||||
pens.set_devices([Device::new(1, "", None, (2..).zip(labels).map(|(n, l)| (n, l.to_string(), min, max)))]);
|
||||
for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, f64::MIN, -0.0, 1e300, 0.5] {
|
||||
let Update::Set(Some(PenSample { pressure: p, .. })) = pens.handle(1, [(2, v)]) else { panic!("{min}..{max}: {v} gave no pressure") };
|
||||
let Update::Set(Some(PenSample { pressure: p, pose, .. })) = pens.handle(1, (2..6).map(|n| (n, v))) else {
|
||||
panic!("{min}..{max}: {v} gave no pressure")
|
||||
};
|
||||
assert!((0.0..=1.0).contains(&p), "{min}..{max}: {v} gave {p}");
|
||||
let tilt = pose.tilt.unwrap_or_default();
|
||||
assert!(tilt.iter().all(|t| (-90.0..=90.0).contains(t)), "{min}..{max}: {v} gave {pose:?}");
|
||||
assert!(pose.rotation.is_some_and(|r| (-180.0..=180.0).contains(&r)), "{min}..{max}: {v} gave {pose:?}");
|
||||
}
|
||||
}
|
||||
let mut pens = Pens::default();
|
||||
|
||||
@@ -36,6 +36,33 @@ fn shortcut_overrides_from_an_earlier_version_load() {
|
||||
assert!(km.problems().iter().any(|p| format!("{p:?}") == r#"UnknownCommand { key: "test.unknown" }"#), "reported");
|
||||
}
|
||||
|
||||
/// The command line's files wait for the choice about a stopped plug-in, so they open with the
|
||||
/// plug-ins it loads; with no choice up they open at once.
|
||||
#[test]
|
||||
fn command_line_files_wait_for_the_choice_about_a_stopped_plug_in() {
|
||||
let temp = tempfile::Builder::new().prefix("vectorcraft-held-files-").tempdir().unwrap();
|
||||
let file = temp.path().join("a.svg");
|
||||
std::fs::write(&file, r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>"#).unwrap();
|
||||
let files = vec![file.to_string_lossy().into_owned()];
|
||||
// The files the app reads to open them.
|
||||
let read = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
|
||||
let reads = read.clone();
|
||||
let services = vectorcraft_ui_egui::Services {
|
||||
read: Some(Box::new(move |p: &str| {
|
||||
reads.borrow_mut().push(p.to_owned());
|
||||
std::fs::read(p).map_err(|e| e.to_string())
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), services);
|
||||
app.ui.stopped_plugin = Some(serde_json::json!({"id": "test.held", "name": "Held"}));
|
||||
assert_eq!(open_or_hold(&mut app, files.clone()), files, "held while the choice is up");
|
||||
assert!(read.borrow().is_empty(), "nothing opened before the choice");
|
||||
app.ui.stopped_plugin = None;
|
||||
assert!(open_or_hold(&mut app, files.clone()).is_empty());
|
||||
assert_eq!(*read.borrow(), files, "opened with no choice up");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_files_unminimizes_and_focuses_the_window() {
|
||||
let ctx = egui::Context::default();
|
||||
@@ -99,9 +126,8 @@ fn unreadable_saved_docking_keeps_preferences_and_every_workspace() {
|
||||
|
||||
#[test]
|
||||
fn an_unreadable_ui_json_is_kept_beside_it() {
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-ui-prefs-{}-{stamp}", std::process::id()));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let temp = tempfile::Builder::new().prefix("vectorcraft-ui-prefs-").tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
let path = dir.join("ui.json");
|
||||
super::keep_prefs_copy(&path, b"{\"docking\": {\"root\": {\"FutureNode\": {}}}}", "ui.unreadable");
|
||||
super::keep_prefs_copy(&path, b"not json", "ui.unreadable");
|
||||
@@ -109,7 +135,6 @@ fn an_unreadable_ui_json_is_kept_beside_it() {
|
||||
let first = std::fs::read(dir.join("ui.unreadable.json")).unwrap();
|
||||
let second = std::fs::read(dir.join("ui.unreadable-2.json")).unwrap();
|
||||
let before = std::fs::read(dir.join("ui.before-layout-migration.json")).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert!(first.starts_with(b"{\"docking\""), "the first copy is not replaced");
|
||||
assert_eq!(second, b"not json");
|
||||
assert_eq!(before, b"{}");
|
||||
@@ -166,6 +191,60 @@ fn the_system_title_bar_preference_keeps_the_window_decorations() {
|
||||
assert_eq!(super::native_options(true).viewport.decorations, Some(false));
|
||||
}
|
||||
|
||||
/// Preferences › User Interface › VectorCraft Title Bar on Every Desktop gives the app frame where
|
||||
/// the probe chose the desktop's (KDE, X11, a window opened through XWayland); without it the probe
|
||||
/// decides, and `VECTORCRAFT_TITLEBAR` takes precedence over both.
|
||||
#[test]
|
||||
fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() {
|
||||
assert!(!super::opted_into_app_title_bar(None), "no preferences: the default");
|
||||
let off = ui_state_with_prefs(serde_json::json!({"appTitleBar": false}));
|
||||
assert!(!super::opted_into_app_title_bar(Some(&off)));
|
||||
let on = ui_state_with_prefs(serde_json::json!({"appTitleBar": true}));
|
||||
assert!(super::opted_into_app_title_bar(Some(&on)));
|
||||
|
||||
// (probed_app, overridden, forced_to_x11): without the preference, then with it.
|
||||
let cases = [
|
||||
((false, None, false), false, true), // KDE, Sway, X11: the desktop frame
|
||||
((true, None, false), true, true), // GNOME on Wayland: the app frame either way
|
||||
((true, None, true), false, true), // GNOME, the window opened through XWayland
|
||||
((false, Some(true), false), true, true), // VECTORCRAFT_TITLEBAR=app
|
||||
((false, Some(true), true), true, true), // VECTORCRAFT_TITLEBAR=app, the window opened through XWayland
|
||||
((true, Some(false), false), false, false), // VECTORCRAFT_TITLEBAR=desktop takes precedence over the preference
|
||||
((false, Some(false), true), false, false),
|
||||
];
|
||||
for ((probed_app, overridden, forced_to_x11), without, with) in cases {
|
||||
assert_eq!(super::app_draws_frame(probed_app, overridden, forced_to_x11, false), without, "{probed_app} {overridden:?} {forced_to_x11}");
|
||||
assert_eq!(super::app_draws_frame(probed_app, overridden, forced_to_x11, true), with, "{probed_app} {overridden:?} {forced_to_x11}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame a start uses: the preference turns the desktop frame the probe chose into the app frame
|
||||
/// with the default window buttons, a probed app frame keeps its own buttons, and the desktop frame
|
||||
/// stays where the app frame is not drawn. System Title Bar takes precedence over the preference.
|
||||
#[test]
|
||||
fn the_start_frame_applies_the_app_title_bar_preference() {
|
||||
use craft_window::{Button, Frame, Layout};
|
||||
let gnome = Layout { left: vec![Button::Close], right: vec![] };
|
||||
let cases = [
|
||||
// (probed, overridden, forced_to_x11, opted_into_app), expected
|
||||
((Frame::Desktop, None, false, false), Frame::Desktop),
|
||||
((Frame::Desktop, None, false, true), Frame::App(Layout::default())),
|
||||
((Frame::Desktop, None, true, true), Frame::App(Layout::default())),
|
||||
((Frame::App(gnome.clone()), None, false, false), Frame::App(gnome.clone())),
|
||||
((Frame::App(gnome.clone()), None, true, false), Frame::Desktop),
|
||||
((Frame::App(gnome.clone()), None, true, true), Frame::App(gnome.clone())),
|
||||
((Frame::Desktop, Some(false), false, true), Frame::Desktop),
|
||||
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(gnome.clone())),
|
||||
];
|
||||
for ((probed, overridden, forced_to_x11, opted_into_app), expected) in cases {
|
||||
let label = format!("{probed:?} {overridden:?} {forced_to_x11} {opted_into_app}");
|
||||
assert_eq!(super::start_frame(probed, overridden, forced_to_x11, opted_into_app), expected, "{label}");
|
||||
}
|
||||
// With both preferences on, System Title Bar takes precedence: the desktop draws the frame.
|
||||
let both = super::start_frame(Frame::Desktop, None, false, true);
|
||||
assert!(!super::custom_titlebar_from(&both, true), "System Title Bar takes precedence over the app title bar preference");
|
||||
}
|
||||
|
||||
/// The file extensions the macOS bundle declares: its document types and its own exported type.
|
||||
fn plist_extensions(plist: &str) -> Vec<&str> {
|
||||
["<key>CFBundleTypeExtensions</key>", "<key>public.filename-extension</key>"]
|
||||
|
||||
@@ -46,6 +46,53 @@ pub(crate) fn opted_into_system_title_bar(saved: Option<&vectorcraft_ui_egui::Ui
|
||||
saved.map(|ui| ui.engine_prefs.get("systemTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the user asked for VectorCraft's own title bar in Preferences › User Interface ›
|
||||
/// VectorCraft Title Bar on Every Desktop (Linux and the BSDs). Read like
|
||||
/// [`opted_into_system_title_bar`]; a missing or unreadable value is `false` (the default).
|
||||
pub(crate) fn opted_into_app_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
|
||||
saved.map(|ui| ui.engine_prefs.get("appTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the app draws the frame on this start, before the System Title Bar preference is
|
||||
/// applied ([`custom_titlebar_from`]). `probed_app` is the `craft-window` probe's answer and
|
||||
/// `overridden` its `VECTORCRAFT_TITLEBAR` override. In order: the override decides when it is
|
||||
/// set; VectorCraft Title Bar on Every Desktop (`opted_into_app`) gives the app frame; a window
|
||||
/// that opens through XWayland (`forced_to_x11`) gets the desktop frame; otherwise the probe
|
||||
/// decides.
|
||||
pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> bool {
|
||||
match overridden {
|
||||
Some(app) => app,
|
||||
None => opted_into_app || (probed_app && !forced_to_x11),
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame this start uses, before the System Title Bar preference is applied
|
||||
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. A probed
|
||||
/// app frame keeps its window-button layout; an app frame the probe did not choose gets the default
|
||||
/// layout, since `custom_titlebar_from` reads only which frame it is.
|
||||
pub(crate) fn start_frame(probed: craft_window::Frame, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> craft_window::Frame {
|
||||
let probed_app = matches!(probed, craft_window::Frame::App(_));
|
||||
match (app_draws_frame(probed_app, overridden, forced_to_x11, opted_into_app), probed) {
|
||||
(true, frame @ craft_window::Frame::App(_)) => frame,
|
||||
(true, craft_window::Frame::Desktop) => craft_window::Frame::App(craft_window::Layout::default()),
|
||||
(false, _) => craft_window::Frame::Desktop,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `craft-window` probe's answer for this process (its override variable is
|
||||
/// `VECTORCRAFT_TITLEBAR`). The probe runs once; on a Wayland session it opens a connection.
|
||||
fn probed_choice() -> &'static craft_window::Choice {
|
||||
static CHOICE: std::sync::OnceLock<craft_window::Choice> = std::sync::OnceLock::new();
|
||||
CHOICE.get_or_init(|| craft_window::Choice::probe(craft_window::Prefix::new("VECTORCRAFT")))
|
||||
}
|
||||
|
||||
/// Whether `VECTORCRAFT_TITLEBAR` chose this window's frame (Linux and the BSDs), so Preferences ›
|
||||
/// User Interface › VectorCraft Title Bar on Every Desktop does not apply while it is set. Always
|
||||
/// `false` on macOS and Windows.
|
||||
pub(crate) fn titlebar_from_env() -> bool {
|
||||
cfg!(not(any(target_os = "macos", target_os = "windows"))) && probed_choice().overridden().is_some()
|
||||
}
|
||||
|
||||
/// Whether this start draws its own title bar, given the frame the shared `craft-window` crate
|
||||
/// decided and the user's System Title Bar preference.
|
||||
///
|
||||
@@ -82,24 +129,27 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
|
||||
/// On Linux, Preferences › Performance › Linux Display Server › X11 opens the window through
|
||||
/// XWayland (below). A GNOME/Wayland probe would say `Frame::App` there, but the window really runs
|
||||
/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native
|
||||
/// frame, the same as a real X11 session. An explicit `VECTORCRAFT_TITLEBAR` override still wins.
|
||||
/// frame, the same as a real X11 session. An explicit `VECTORCRAFT_TITLEBAR` override still wins,
|
||||
/// and so does VectorCraft Title Bar on Every Desktop ([`app_draws_frame`]).
|
||||
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
|
||||
let choice = craft_window::Choice::probe(craft_window::Prefix::new("VECTORCRAFT"));
|
||||
let choice = probed_choice();
|
||||
let opted_into_system = opted_into_system_title_bar(saved);
|
||||
// macOS and Windows never read VectorCraft Title Bar on Every Desktop (`custom_titlebar_from`
|
||||
// ignores the frame there).
|
||||
let opted_into_app = cfg!(not(any(target_os = "macos", target_os = "windows"))) && opted_into_app_title_bar(saved);
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
// When the window will actually open on X11 (XWayland) — the user asked for it *and* the X11
|
||||
// libraries are present, the same two conditions the launch path checks below — that run is
|
||||
// effectively X11, so keep the native frame. If the libraries are missing, startup stays on
|
||||
// Wayland, so the probe's own decision (app-drawn on GNOME) must stand.
|
||||
let forced_to_x11 = {
|
||||
let pref = saved.and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str);
|
||||
// `overridden() == None` means the probe decided (no VECTORCRAFT_TITLEBAR). When the window
|
||||
// will actually open on X11 (XWayland) — the user asked for it *and* the X11 libraries are
|
||||
// present, the same two conditions the launch path checks below — that run is effectively
|
||||
// X11, so keep the native frame. If the libraries are missing, startup stays on Wayland, so
|
||||
// the probe's own decision (app-drawn on GNOME) must stand.
|
||||
let forced_to_x11 = xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) && xwayland::x11_libraries_found();
|
||||
if choice.overridden().is_none() && forced_to_x11 {
|
||||
return custom_titlebar_from(&craft_window::Frame::Desktop, opted_into_system);
|
||||
}
|
||||
}
|
||||
custom_titlebar_from(choice.frame(), opted_into_system)
|
||||
xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) && xwayland::x11_libraries_found()
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let forced_to_x11 = false;
|
||||
let frame = start_frame(choice.frame().clone(), choice.overridden(), forced_to_x11, opted_into_app);
|
||||
custom_titlebar_from(&frame, opted_into_system)
|
||||
}
|
||||
|
||||
pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! the size, position and maximized state saved with the UI preferences (`UiState::window`), moved
|
||||
//! onto a monitor that is still connected.
|
||||
|
||||
use vectorcraft_ui_egui::DockMonitor;
|
||||
use vectorcraft_ui_egui::state::WindowGeometry;
|
||||
use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize};
|
||||
|
||||
@@ -14,6 +15,9 @@ pub const MIN_SIZE: [f32; 2] = [800.0, 500.0];
|
||||
/// say how much of the screen they take): a monitor with less room opens it maximized.
|
||||
const SCREEN_ROOM: [f32; 2] = [64.0, 128.0];
|
||||
|
||||
/// Seconds between readings of the monitor list, which picks up a monitor connected while the app runs.
|
||||
const MONITORS_EVERY: f64 = 1.0;
|
||||
|
||||
/// A monitor: its top-left corner and size in physical pixels, and its scale factor.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Monitor {
|
||||
@@ -67,6 +71,15 @@ impl Monitor {
|
||||
i32::try_from(want.max(lo).min(hi)).unwrap_or_default()
|
||||
})
|
||||
}
|
||||
|
||||
/// This monitor for floating panels, in the points egui reports for a window on it: physical
|
||||
/// pixels divided by the monitor's scale factor and the UI zoom.
|
||||
fn docking(&self, name: Option<String>, zoom: f32) -> DockMonitor {
|
||||
let scale = self.scale * zoom;
|
||||
let [x, y] = self.pos;
|
||||
let [w, h] = self.size;
|
||||
DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale }
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the window opens: `saved` (the last session's geometry) kept on a connected monitor, else
|
||||
@@ -109,6 +122,33 @@ fn fit(size: [f32; 2], room: [f32; 2]) -> [f32; 2] {
|
||||
std::array::from_fn(|i| size[i].min(room[i]).max(MIN_SIZE[i].min(room[i])).max(1.0))
|
||||
}
|
||||
|
||||
/// Whether to list the monitors again: on the first frame, when the UI zoom changed, and at most
|
||||
/// every [`MONITORS_EVERY`] seconds while the app draws. `listed` holds the last list's time and zoom.
|
||||
pub fn monitors_due(listed: Option<(f64, f32)>, now: f64, zoom: f32) -> bool {
|
||||
listed.is_none_or(|(at, listed_zoom)| listed_zoom != zoom || now - at >= MONITORS_EVERY)
|
||||
}
|
||||
|
||||
/// The connected monitors for floating panels (`Services::dock_monitors`).
|
||||
pub fn dock_monitors(window: &winit::window::Window, zoom: f32) -> Vec<DockMonitor> {
|
||||
let monitors: Vec<_> = window.available_monitors().map(|m| (Monitor::new(m.position(), m.size(), m.scale_factor()), m.name())).collect();
|
||||
docking_list(&monitors, zoom, cfg!(target_os = "macos"))
|
||||
}
|
||||
|
||||
/// The list for floating panels, empty when `monitors` have different scales and `shared_points` is
|
||||
/// false. macOS has one desktop of points. Elsewhere a new window multiplies its saved position by the
|
||||
/// scale of the monitor it is created on, which can put a window saved on another scale off every
|
||||
/// monitor. With an empty list craft-ui opens the window on the main window's monitor.
|
||||
///
|
||||
/// A name that two monitors share is left out, so craft-ui finds those monitors by their rects: macOS
|
||||
/// can give two displays of one model the same name.
|
||||
fn docking_list(monitors: &[(Monitor, Option<String>)], zoom: f32, shared_points: bool) -> Vec<DockMonitor> {
|
||||
if !shared_points && monitors.windows(2).any(|pair| pair[0].0.scale != pair[1].0.scale) {
|
||||
return Vec::new();
|
||||
}
|
||||
let unique = |name: &String| monitors.iter().filter(|(_, other)| other.as_ref() == Some(name)).count() == 1;
|
||||
monitors.iter().map(|(monitor, name)| monitor.docking(name.clone().filter(unique), zoom)).collect()
|
||||
}
|
||||
|
||||
/// Size and place the new window (eframe shows it after drawing the first frame) and return its
|
||||
/// geometry. On Linux the window may not be mapped yet, so [`apply_pending_maximize`] must run
|
||||
/// until the host reports maximized (fixes #3635).
|
||||
@@ -204,6 +244,51 @@ mod tests {
|
||||
assert_eq!(place(saved(Some([9000, 9000]), [1e9, 1e9], true), &[], None).size, DEFAULT_SIZE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floating_panels_get_monitors_in_the_points_a_window_on_them_reports() {
|
||||
let dock = |m: Monitor, zoom| m.docking(Some("m".into()), zoom);
|
||||
let plain = dock(monitor(1920, 0, 1920, 1080, 1.0), 1.0);
|
||||
assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0 });
|
||||
// A window at (3000, 200) on this monitor reports (1500, 100).
|
||||
let scaled = dock(monitor(1920, -200, 3840, 2160, 2.0), 1.0);
|
||||
assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0 });
|
||||
// The UI zoom divides what egui reports as well.
|
||||
let zoomed = dock(monitor(-2560, 0, 2560, 1440, 1.0), 1.25);
|
||||
assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitors_of_different_scales_are_listed_only_on_a_desktop_of_shared_points() {
|
||||
let named = |m: Monitor, name: &str| (m, Some(name.to_string()));
|
||||
let same = [named(monitor(0, 0, 1920, 1080, 1.5), "a"), named(monitor(1920, 0, 1920, 1080, 1.5), "b")];
|
||||
assert_eq!(docking_list(&same, 1.0, false).len(), 2);
|
||||
let mixed = [named(monitor(0, 0, 3840, 2160, 2.0), "a"), named(monitor(3840, 0, 1920, 1080, 1.0), "b")];
|
||||
assert_eq!(docking_list(&mixed, 1.0, false), Vec::new());
|
||||
assert_eq!(docking_list(&mixed, 1.0, true).len(), 2);
|
||||
assert_eq!(docking_list(&[], 1.0, false), Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_two_monitors_share_is_left_out_of_the_list() {
|
||||
let list = [
|
||||
(monitor(0, 0, 1920, 1080, 1.0), Some("Monitor #1".to_string())),
|
||||
(monitor(1920, 0, 1920, 1080, 1.0), Some("Monitor #1".to_string())),
|
||||
(monitor(3840, 0, 1920, 1080, 1.0), Some("Monitor #2".to_string())),
|
||||
(monitor(5760, 0, 1920, 1080, 1.0), None),
|
||||
];
|
||||
let names: Vec<_> = docking_list(&list, 1.0, false).into_iter().map(|m| m.name).collect();
|
||||
assert_eq!(names, [None, None, Some("Monitor #2".to_string()), None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_monitor_list_is_read_on_the_first_frame_then_once_a_second_or_on_a_zoom_change() {
|
||||
assert!(monitors_due(None, 0.0, 1.0));
|
||||
assert!(!monitors_due(Some((5.0, 1.0)), 5.0, 1.0));
|
||||
assert!(!monitors_due(Some((5.0, 1.0)), 5.5, 1.0));
|
||||
assert!(monitors_due(Some((5.0, 1.0)), 6.0, 1.0));
|
||||
assert!(monitors_due(Some((5.0, 1.0)), 5.5, 1.25));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_saved_window_comes_back_where_it_was() {
|
||||
let two = [monitor(0, 0, 2560, 1440, 1.0), monitor(2560, 0, 1920, 1080, 1.0)];
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
//! Alt + numeric-keypad codes on Windows (#5108): holding Alt, typing a decimal code on the
|
||||
//! numeric keypad (NumLock on) and releasing Alt types that character (`Alt+0176` → `°`).
|
||||
//!
|
||||
//! Windows does the work: when Alt comes up after keypad digits, `TranslateMessage` posts a
|
||||
//! `WM_CHAR` holding the character the code stands for (in the system's ANSI code page for a code
|
||||
//! with a leading 0, else its OEM code page), the convention every Windows text field follows
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input>). winit
|
||||
//! 0.30 reads a `WM_CHAR` only as part of the key press before it, so it drops this one, which
|
||||
//! follows a key release, and egui never sees the text. winit's message hook ([`msg_hook`]) sees
|
||||
//! the message before winit handles it: [`AltCodes`] notes keypad digits typed with Alt held, takes
|
||||
//! the character that follows Alt's release, and [`raw_input_hook`] hands it to the frame as typed
|
||||
//! text, so the Type tool (or a panel's text field) types it like any other character, in the
|
||||
//! same undo step as the typing round it. The keypad digits themselves are taken out of the frame,
|
||||
//! so they don't run a shortcut bound to Alt and a digit.
|
||||
//!
|
||||
//! With NumLock off the keypad keys arrive as Insert, End, Down, Page Down, Left, Clear, Right,
|
||||
//! Home, Up and Page Up, and Windows still composes the code from them. They are told from the
|
||||
//! separate navigation keys by the extended-key flag, which only the separate keys set
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input#extended-key-flag>),
|
||||
//! so with Alt held they count as digits and are taken out of the frame too, rather than moving
|
||||
//! the caret before the character arrives.
|
||||
//!
|
||||
//! egui reports a keypad digit as the same key as the digit above the letters, so the other
|
||||
//! platforms, whose systems have no such convention, can't tell them apart either.
|
||||
|
||||
#![cfg_attr(not(windows), allow(dead_code))]
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
use egui::{Event, Key};
|
||||
|
||||
const WM_KEYDOWN: u32 = 0x0100;
|
||||
const WM_KEYUP: u32 = 0x0101;
|
||||
const WM_CHAR: u32 = 0x0102;
|
||||
const WM_SYSKEYDOWN: u32 = 0x0104;
|
||||
const WM_SYSKEYUP: u32 = 0x0105;
|
||||
const WM_SYSCHAR: u32 = 0x0106;
|
||||
/// `VK_NUMPAD0` to `VK_NUMPAD9` (`winuser.h`): keypad digits with NumLock on.
|
||||
const VK_NUMPAD0: usize = 0x60;
|
||||
const VK_NUMPAD9: usize = 0x69;
|
||||
/// The keypad's virtual keys with NumLock off, by digit (`winuser.h`): `VK_INSERT`, `VK_END`,
|
||||
/// `VK_DOWN`, `VK_NEXT`, `VK_LEFT`, `VK_CLEAR`, `VK_RIGHT`, `VK_HOME`, `VK_UP` and `VK_PRIOR`.
|
||||
const NUMLOCK_OFF_KEYS: [usize; 10] = [0x2D, 0x23, 0x28, 0x22, 0x25, 0x0C, 0x27, 0x24, 0x26, 0x21];
|
||||
/// The keys egui reports for the keypad with NumLock off, by digit (Clear has no egui key, so it
|
||||
/// comes as the top-row digit key, `Num5`).
|
||||
const NUMLOCK_OFF_EGUI_KEYS: [Key; 10] =
|
||||
[Key::Insert, Key::End, Key::ArrowDown, Key::PageDown, Key::ArrowLeft, Key::Num5, Key::ArrowRight, Key::Home, Key::ArrowUp, Key::PageUp];
|
||||
const DIGIT_KEYS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key::Num4, Key::Num5, Key::Num6, Key::Num7, Key::Num8, Key::Num9];
|
||||
/// Bit 24 of a key message's `lParam`: an extended key, such as the navigation keys beside the
|
||||
/// keypad (the keypad's own keys clear it).
|
||||
const EXTENDED_KEY: isize = 1 << 24;
|
||||
/// `VK_MENU`, `VK_LMENU` and `VK_RMENU`: Alt.
|
||||
const ALT_KEYS: [usize; 3] = [0x12, 0xA4, 0xA5];
|
||||
|
||||
thread_local! {
|
||||
/// The UI thread's sequence: [`msg_hook`] and [`raw_input_hook`] both run on it.
|
||||
static CODES: RefCell<AltCodes> = RefCell::new(AltCodes::default());
|
||||
}
|
||||
|
||||
/// Where an Alt + keypad code stands, from the keyboard messages of the thread's queue.
|
||||
#[derive(Default)]
|
||||
struct AltCodes {
|
||||
/// Keypad digits typed while Alt has been held.
|
||||
digits: usize,
|
||||
/// Alt came up after keypad digits: the next character message is the code's character.
|
||||
armed: bool,
|
||||
/// A high surrogate waiting for its low half.
|
||||
high: Option<u16>,
|
||||
/// Characters the codes typed, for the next frame.
|
||||
typed: String,
|
||||
/// The digits of the keypad presses and releases with Alt held since the last frame, which
|
||||
/// egui reports as Alt and a digit (or, with NumLock off, Alt and a navigation key): taken
|
||||
/// out of the frame.
|
||||
keypad_events: Vec<usize>,
|
||||
}
|
||||
|
||||
/// The digit a keypad key stands for in an Alt code: `wparam` is its virtual-key code and
|
||||
/// `lparam` the message's flags.
|
||||
fn keypad_digit(wparam: usize, lparam: isize) -> Option<usize> {
|
||||
if (VK_NUMPAD0..=VK_NUMPAD9).contains(&wparam) {
|
||||
return Some(wparam - VK_NUMPAD0);
|
||||
}
|
||||
if lparam & EXTENDED_KEY != 0 {
|
||||
return None;
|
||||
}
|
||||
NUMLOCK_OFF_KEYS.iter().position(|&k| k == wparam)
|
||||
}
|
||||
|
||||
impl AltCodes {
|
||||
/// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit)
|
||||
/// and `lparam` (its flags).
|
||||
fn message(&mut self, message: u32, wparam: usize, lparam: isize) {
|
||||
let keypad = match message {
|
||||
WM_SYSKEYDOWN | WM_SYSKEYUP => keypad_digit(wparam, lparam),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(d) = keypad {
|
||||
// Windows sends a key pressed with Alt held as a system key.
|
||||
if message == WM_SYSKEYDOWN {
|
||||
self.digits += 1;
|
||||
self.armed = false;
|
||||
}
|
||||
self.keypad_events.push(d);
|
||||
return;
|
||||
}
|
||||
match message {
|
||||
WM_KEYDOWN | WM_SYSKEYDOWN if ALT_KEYS.contains(&wparam) => {}
|
||||
// Any other key ends the sequence and keeps its own meaning.
|
||||
WM_KEYDOWN | WM_SYSKEYDOWN => self.reset(),
|
||||
WM_KEYUP | WM_SYSKEYUP if ALT_KEYS.contains(&wparam) => {
|
||||
self.armed = self.digits > 0;
|
||||
self.digits = 0;
|
||||
}
|
||||
WM_CHAR | WM_SYSCHAR if self.armed => {
|
||||
let unit = (wparam & 0xffff) as u16;
|
||||
if (0xd800..0xdc00).contains(&unit) {
|
||||
self.high = Some(unit);
|
||||
return;
|
||||
}
|
||||
let units: Vec<u16> = self.high.take().into_iter().chain([unit]).collect();
|
||||
self.typed.extend(char::decode_utf16(units).filter_map(Result::ok).filter(|c| !c.is_control()));
|
||||
self.armed = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.digits = 0;
|
||||
self.armed = false;
|
||||
self.high = None;
|
||||
}
|
||||
|
||||
/// Hand the frame `events` the characters typed since the last frame, as typed text, and take
|
||||
/// out the keypad digits typed with Alt held.
|
||||
fn drain(&mut self, events: &mut Vec<Event>) {
|
||||
let mut keypad = std::mem::take(&mut self.keypad_events);
|
||||
if !keypad.is_empty() {
|
||||
events.retain(|e| {
|
||||
let Event::Key { key, modifiers, .. } = e else {
|
||||
return true;
|
||||
};
|
||||
if !modifiers.alt {
|
||||
return true;
|
||||
}
|
||||
// The first keypad key still to take out that egui reports as `key`.
|
||||
let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key);
|
||||
match keypad.iter().position(stands_for) {
|
||||
Some(i) => {
|
||||
keypad.remove(i);
|
||||
false
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
});
|
||||
}
|
||||
if !self.typed.is_empty() {
|
||||
events.push(Event::Text(std::mem::take(&mut self.typed)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// winit's message hook for the keyboard: notes Alt + keypad codes and the characters they type.
|
||||
/// It never consumes the message.
|
||||
#[cfg(windows)]
|
||||
#[allow(unsafe_code)]
|
||||
pub fn msg_hook(msg: *const std::ffi::c_void) {
|
||||
use windows::Win32::UI::WindowsAndMessaging::MSG;
|
||||
// SAFETY: winit passes the `MSG` that `PeekMessageW` has just filled, which lives for this
|
||||
// call; `as_ref` gives `None` for a null pointer.
|
||||
let Some(msg) = (unsafe { msg.cast::<MSG>().as_ref() }) else {
|
||||
return;
|
||||
};
|
||||
if (WM_KEYDOWN..=WM_SYSCHAR).contains(&msg.message) {
|
||||
CODES.with(|c| {
|
||||
if let Ok(mut c) = c.try_borrow_mut() {
|
||||
c.message(msg.message, msg.wParam.0, msg.lParam.0);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Before egui reads the main window's frame: the characters Alt + keypad codes typed, as text.
|
||||
pub fn raw_input_hook(raw: &mut egui::RawInput) {
|
||||
CODES.with(|c| {
|
||||
if let Ok(mut c) = c.try_borrow_mut() {
|
||||
c.drain(&mut raw.events);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ALT: usize = 0x12;
|
||||
|
||||
/// Alt held, keypad digits `code`, Alt released, and the character Windows then posts.
|
||||
fn alt_code(c: &mut AltCodes, code: &str, posted: u16) {
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
for d in code.bytes() {
|
||||
let vk = VK_NUMPAD0 + usize::from(d - b'0');
|
||||
c.message(WM_SYSKEYDOWN, vk, 0);
|
||||
c.message(WM_SYSKEYUP, vk, 0);
|
||||
}
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, usize::from(posted), 0);
|
||||
}
|
||||
|
||||
fn key(key: Key, alt: bool, pressed: bool) -> Event {
|
||||
let modifiers = egui::Modifiers { alt, ..Default::default() };
|
||||
Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alt_code_types_its_character_when_alt_comes_up() {
|
||||
let mut c = AltCodes::default();
|
||||
alt_code(&mut c, "0176", 0xB0);
|
||||
alt_code(&mut c, "0151", 0x2014);
|
||||
let mut events = vec![key(Key::Num0, true, true), key(Key::Num0, true, false), key(Key::Num1, false, true)];
|
||||
c.drain(&mut events);
|
||||
// The keypad digits typed with Alt are gone (eight presses and eight releases, two here);
|
||||
// the digit typed without Alt stays, and the characters follow.
|
||||
assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°—".into())]);
|
||||
let mut events = vec![key(Key::Num0, true, true)];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events.len(), 1, "counts don't carry over to a later frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_character_without_a_code_before_it_is_left_to_winit() {
|
||||
let mut c = AltCodes::default();
|
||||
// A plain key press's character (winit types it), and Alt pressed and released alone.
|
||||
c.message(WM_KEYDOWN, 0x41, 0);
|
||||
c.message(WM_CHAR, usize::from(b'a'), 0);
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, usize::from(b'b'), 0);
|
||||
let mut events = vec![];
|
||||
c.drain(&mut events);
|
||||
assert!(events.is_empty(), "{events:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_key_while_alt_is_held_cancels_the_code() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0);
|
||||
// Alt+F: a shortcut, not a code.
|
||||
c.message(WM_SYSKEYDOWN, 0x46, 0);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, 0x41, 0);
|
||||
let mut events = vec![];
|
||||
c.drain(&mut events);
|
||||
assert!(!events.iter().any(|e| matches!(e, Event::Text(_))), "{events:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_code_above_the_basic_plane_arrives_as_two_halves() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, 0xD83D, 0);
|
||||
c.message(WM_CHAR, 0xDE00, 0);
|
||||
let mut events = vec![];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![Event::Text("😀".into())]);
|
||||
}
|
||||
|
||||
/// Alt held, keypad digits `code` with NumLock off (keypad Insert, End, …, flags without the
|
||||
/// extended-key bit), Alt released, and the character Windows then posts.
|
||||
fn alt_code_numlock_off(c: &mut AltCodes, code: &str, posted: u16) {
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
for d in code.bytes() {
|
||||
let vk = NUMLOCK_OFF_KEYS[usize::from(d - b'0')];
|
||||
c.message(WM_SYSKEYDOWN, vk, 0);
|
||||
c.message(WM_SYSKEYUP, vk, 0);
|
||||
}
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, usize::from(posted), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_numlock_off_the_keypad_keys_type_the_code_and_leave_the_caret_alone() {
|
||||
let mut c = AltCodes::default();
|
||||
alt_code_numlock_off(&mut c, "0176", 0xB0);
|
||||
// What egui reports for keypad 0, 1, 7 and 6 with NumLock off and Alt held, a press and a
|
||||
// release each, then a plain Home typed after Alt came up.
|
||||
let mut events = vec![];
|
||||
for k in [Key::Insert, Key::End, Key::Home, Key::ArrowRight] {
|
||||
events.push(key(k, true, true));
|
||||
events.push(key(k, true, false));
|
||||
}
|
||||
events.push(key(Key::Home, false, true));
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![key(Key::Home, false, true), Event::Text("°".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_numlock_off_keypad_five_counts_too() {
|
||||
let mut c = AltCodes::default();
|
||||
// Keypad 5 is Clear, which egui reports as the top-row 5. 0151 uses Insert, End and Clear;
|
||||
// 0234 uses Insert, Down, Page Down and Left.
|
||||
alt_code_numlock_off(&mut c, "0151", 0x2014);
|
||||
alt_code_numlock_off(&mut c, "0234", 0xEA);
|
||||
let mut events =
|
||||
vec![key(Key::Num5, true, true), key(Key::ArrowDown, true, true), key(Key::PageDown, true, true), key(Key::ArrowLeft, true, true)];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![Event::Text("—ê".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_separate_navigation_keys_still_move_the_caret_and_cancel_the_code() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_SYSKEYDOWN, ALT, 0);
|
||||
c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[1], 0);
|
||||
c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[1], 0);
|
||||
// Alt+Home on the separate Home key (extended): a shortcut, not a digit.
|
||||
c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY);
|
||||
c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY);
|
||||
c.message(WM_KEYUP, ALT, 0);
|
||||
c.message(WM_CHAR, 0x41, 0);
|
||||
let mut events = vec![key(Key::End, true, true), key(Key::End, true, false), key(Key::Home, true, true), key(Key::Home, true, false)];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events, vec![key(Key::Home, true, true), key(Key::Home, true, false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numlock_off_keys_without_alt_are_left_alone() {
|
||||
let mut c = AltCodes::default();
|
||||
c.message(WM_KEYDOWN, NUMLOCK_OFF_KEYS[7], 0);
|
||||
c.message(WM_KEYUP, NUMLOCK_OFF_KEYS[7], 0);
|
||||
let mut events = vec![key(Key::Home, false, true), key(Key::Home, false, false)];
|
||||
c.drain(&mut events);
|
||||
assert_eq!(events.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -16,13 +16,21 @@
|
||||
//! mouse message that Windows did not make from a pen or a touch
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages>)
|
||||
//! clears the feed.
|
||||
//!
|
||||
//! The same `POINTER_PEN_INFO` gives the pen's tilt and barrel rotation (#372: a 6D Art Pen turns a
|
||||
//! Calligraphic brush's nib with its barrel), each only where its `PEN_MASK_*` bit says the pen
|
||||
//! reports it (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/pen-mask-constants>):
|
||||
//! `tiltX` and `tiltY` in degrees −90..90, positive to the right and toward the user, and
|
||||
//! `rotation` in degrees 0..359 clockwise
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-pointer_pen_info>).
|
||||
//! Toward the user is down the screen, so they are [`PenPose`]'s axes and direction as they come.
|
||||
#![cfg_attr(not(windows), allow(dead_code))]
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, TouchId, TouchPhase};
|
||||
use vectorcraft_ui_egui::stylus::{PenSample, StylusFeed};
|
||||
use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed};
|
||||
|
||||
/// `POINTER_MESSAGE_FLAG_SECONDBUTTON` (`winuser.h`): in the high word of a pointer message's
|
||||
/// `wParam`, a pen in contact with its barrel button pressed.
|
||||
@@ -37,6 +45,11 @@ const PEN_FLAG_INVERTED: u32 = 0x0002;
|
||||
const PEN_FLAG_ERASER: u32 = 0x0004;
|
||||
/// `PEN_MASK_PRESSURE` (`winuser.h`), in `POINTER_PEN_INFO::penMask`: the pen reports pressure.
|
||||
const PEN_MASK_PRESSURE: u32 = 0x0001;
|
||||
/// `PEN_MASK_ROTATION`, `PEN_MASK_TILT_X` and `PEN_MASK_TILT_Y` (`winuser.h`): the pen reports its
|
||||
/// barrel rotation, its tilt along x and its tilt along y.
|
||||
const PEN_MASK_ROTATION: u32 = 0x0002;
|
||||
const PEN_MASK_TILT_X: u32 = 0x0004;
|
||||
const PEN_MASK_TILT_Y: u32 = 0x0008;
|
||||
/// `MI_WP_SIGNATURE` and `SIGNATURE_MASK`: the extra information of a mouse message that Windows
|
||||
/// made from a pen or a touch.
|
||||
const MI_WP_SIGNATURE: u32 = 0xFF51_5700;
|
||||
@@ -94,7 +107,8 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
|
||||
// pointer that is not a pen.
|
||||
unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?;
|
||||
let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0;
|
||||
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact))
|
||||
let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation);
|
||||
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose))
|
||||
};
|
||||
// SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message.
|
||||
let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32);
|
||||
@@ -106,15 +120,25 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
|
||||
|
||||
/// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags`
|
||||
/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen
|
||||
/// in contact that reports none; and the eraser end while it is inverted or its eraser button is
|
||||
/// pressed.
|
||||
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool) -> PenSample {
|
||||
/// in contact that reports none; the eraser end while it is inverted or its eraser button is
|
||||
/// pressed; and how it is held, `pose` ([`pen_pose`]).
|
||||
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, pose: PenPose) -> PenSample {
|
||||
let pressure = match pressure {
|
||||
1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0,
|
||||
_ if in_contact => 1.0,
|
||||
_ => 0.0,
|
||||
};
|
||||
PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0 }
|
||||
PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0, pose }
|
||||
}
|
||||
|
||||
/// How a pen whose `POINTER_PEN_INFO` holds `pen_mask`, `tilt_x`, `tilt_y` and `rotation` is
|
||||
/// held: the tilt when the pen reports it along either axis (0 along an axis it doesn't), the
|
||||
/// rotation when it reports one, each kept within [`PenPose`]'s ranges.
|
||||
fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> PenPose {
|
||||
let along = |mask: u32, t: i32| if pen_mask & mask != 0 { t as f32 } else { 0.0 };
|
||||
let tilt = (pen_mask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0).then(|| [along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)]);
|
||||
let rotation = (pen_mask & PEN_MASK_ROTATION != 0).then_some(rotation as f32);
|
||||
PenPose { tilt, rotation }.sanitized()
|
||||
}
|
||||
|
||||
/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse,
|
||||
@@ -390,7 +414,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() {
|
||||
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true).eraser;
|
||||
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, PenPose::default()).eraser;
|
||||
assert!(!eraser(0), "the tip");
|
||||
assert!(!eraser(PEN_FLAG_BARREL), "the barrel button");
|
||||
assert!(eraser(PEN_FLAG_INVERTED), "turned over");
|
||||
@@ -399,15 +423,32 @@ mod tests {
|
||||
assert!(eraser(PEN_FLAG_INVERTED | PEN_FLAG_BARREL));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pens_tilt_and_rotation_come_where_it_reports_them() {
|
||||
let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION;
|
||||
assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0) });
|
||||
assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), PenPose::default(), "a pen that reports neither");
|
||||
assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), rotation: None }, "one axis");
|
||||
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { tilt: None, rotation: Some(359.0) }, "a 6D Art Pen's barrel");
|
||||
let wild = pen_pose(all, 400, i32::MIN, 720);
|
||||
assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0) }, "kept within the ranges");
|
||||
let pose = pen_pose(all, 10, 20, 180);
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose).pose, pose);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pens_pressure_is_the_one_winit_gives_its_touch() {
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true).pressure, 0.5);
|
||||
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true).pressure, 1.0);
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false), PenSample { pressure: 0.0, eraser: true }, "hovering");
|
||||
assert_eq!(pen_sample(0, 0, 0, true).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
|
||||
assert_eq!(pen_sample(300, 0, 0, true).pressure, 1.0, "a pressure without the pressure mask is not one");
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true).pressure, 1.0, "as winit, which gives no force for 0");
|
||||
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false).pressure, 0.0);
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 0.5);
|
||||
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 1.0);
|
||||
assert_eq!(
|
||||
pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, PenPose::default()),
|
||||
PenSample { pressure: 0.0, eraser: true, pose: PenPose::default() },
|
||||
"hovering"
|
||||
);
|
||||
assert_eq!(pen_sample(0, 0, 0, true, PenPose::default()).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
|
||||
assert_eq!(pen_sample(300, 0, 0, true, PenPose::default()).pressure, 1.0, "a pressure without the pressure mask is not one");
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 1.0, "as winit, which gives no force for 0");
|
||||
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, PenPose::default()).pressure, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -420,7 +461,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn pen_messages_set_the_feed_and_other_pointers_clear_it() {
|
||||
let pen = PenSample { pressure: 0.0, eraser: true };
|
||||
let pen = PenSample { pressure: 0.0, eraser: true, pose: PenPose::default() };
|
||||
// `POINTER_MESSAGE_FLAG_INRANGE` in the high word of `wParam`, pointer 7 in the low word.
|
||||
let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7;
|
||||
let no_mouse = || -> bool { panic!("a pointer message is not a mouse message") };
|
||||
|
||||
@@ -54,7 +54,7 @@ fn prints_usage(args: &[&str], env: &[(&str, &str)]) {
|
||||
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(out.stderr.is_empty(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(stdout.starts_with("Usage: vectorcraft "), "{args:?}: {stdout}");
|
||||
for flag in ["--control", "--automation-read-root", "--automation-write-root", "--in-window-menus", "--version", "--help"] {
|
||||
for flag in ["--control", "--automation-read-root", "--automation-write-root", "--in-window-menus", "--safe-mode", "--version", "--help"] {
|
||||
assert!(stdout.contains(flag), "{args:?}: usage doesn't mention {flag}: {stdout}");
|
||||
}
|
||||
// Headless work is the CLI's: the usage says where to go.
|
||||
@@ -74,3 +74,27 @@ fn help_prints_usage_and_exits_before_startup() {
|
||||
fn help_wins_over_a_bad_control_port_variable() {
|
||||
prints_usage(&["--help"], &[("VECTORCRAFT_CONTROL_PORT", "abc")]);
|
||||
}
|
||||
|
||||
/// An option the app doesn't know (a typo of `--safe-mode`) is an error, not a file to open with
|
||||
/// plug-ins; a later `--help` still wins.
|
||||
#[test]
|
||||
fn an_unknown_option_is_an_error_and_not_a_file() {
|
||||
for args in [&["--safe-mod"][..], &["drawing.svg", "--safe-mod"], &["-x"]] {
|
||||
let out = run(args, &[]);
|
||||
assert!(!out.status.success(), "{args:?}");
|
||||
assert!(out.stdout.is_empty(), "{args:?}");
|
||||
let stderr = String::from_utf8(out.stderr).unwrap();
|
||||
let unknown = args.iter().find(|a| a.starts_with('-')).unwrap();
|
||||
assert_eq!(
|
||||
stderr,
|
||||
format!("vectorcraft: unknown option {unknown}; see vectorcraft --help, or put -- before a file whose name starts with '-'\n"),
|
||||
"{args:?}"
|
||||
);
|
||||
}
|
||||
prints_usage(&["--safe-mod", "--help"], &[]);
|
||||
// After `--`, a name starting with '-' is a file: the run goes on to the control port, which
|
||||
// `run` makes fail.
|
||||
let out = run(&["--", "-x.svg"], &[]);
|
||||
let stderr = String::from_utf8(out.stderr).unwrap();
|
||||
assert!(stderr.contains("VECTORCRAFT_CONTROL_PORT") && !stderr.contains("unknown option"), "{stderr}");
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="7" width="10" height="10" rx="1.5"/><rect x="3.5" y="3.5" width="17" height="17" rx="5" stroke-dasharray="7.854 7" stroke-dashoffset="7.854"/></svg>
|
||||
|
After Width: | Height: | Size: 347 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 5h9M10.5 5v11"/><rect x="14" y="12" width="7" height="8" stroke-dasharray="1.5 1.5"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4h10M20 7v10M17 20H7M4 17V7" stroke-width="1"/><path d="M8 10V8h8v2M12 8v8"/><rect x="2.5" y="2.5" width="3" height="3" rx=".75" stroke-width="1"/><rect x="18.5" y="2.5" width="3" height="3" rx=".75" stroke-width="1"/><rect x="18.5" y="18.5" width="3" height="3" rx=".75" stroke-width="1"/><rect x="2.5" y="18.5" width="3" height="3" rx=".75" stroke-width="1"/></svg>
|
||||
|
Before Width: | Height: | Size: 287 B After Width: | Height: | Size: 563 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" stroke-dasharray="2 2"/><path d="M8 8h8M12 8v9"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3.5" y="2.5" width="17" height="19" rx="2.5" stroke-width="1.25"/><path d="M8 8V6h8v2M12 6v7"/><path d="M7.5 16.5h9M7.5 18.5H13" stroke-width="1"/></svg>
|
||||
|
Before Width: | Height: | Size: 280 B After Width: | Height: | Size: 346 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 19 C8 9 16 9 21 19"/><path d="M8 5h8M12 5v8"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 5.5v-2h8v2M12 3.5v10"/><path d="M3 18.5c3-3.5 6-3.5 9 0s6 3.5 9 0" stroke-width="1.25"/></svg>
|
||||
|
Before Width: | Height: | Size: 248 B After Width: | Height: | Size: 290 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="8.5" y="2.5" width="13" height="19" rx="2.5" stroke-width="1.25"/><path d="M11.5 8V6h7v2M15 6v8"/><path d="M12 17h6" stroke-width="1"/><path d="M4 4v15.5M1.75 17.25 4 19.5l2.25-2.25" stroke-width="1.25"/></svg>
|
||||
|
After Width: | Height: | Size: 403 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 5.5v-2h10v2M15 3.5V13"/><path d="M4 3v10.5M1.75 11.25 4 13.5l2.25-2.25" stroke-width="1.25"/><path d="M3 18.5c3-3.5 6-3.5 9 0s6 3.5 9 0" stroke-width="1.25"/></svg>
|
||||
|
After Width: | Height: | Size: 361 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4h10M12 4v8"/><path d="M9 15h6M12 15v6"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 6.5v-2h10v2M15 4.5V19"/><path d="M4 4v15.5M1.75 17.25 4 19.5l2.25-2.25" stroke-width="1.25"/></svg>
|
||||
|
Before Width: | Height: | Size: 243 B After Width: | Height: | Size: 296 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 6.5v-2h14v2M12 4.5v15"/></svg>
|
||||
|
After Width: | Height: | Size: 226 B |
@@ -189,3 +189,34 @@ sync_github_name = false
|
||||
[people.WadahBadawi]
|
||||
display_name = "Wadah Badawi"
|
||||
sync_github_name = true
|
||||
|
||||
[people.JonRC]
|
||||
real_name = "Jonathan Cardoso"
|
||||
display_name = "Jonathan Cardoso"
|
||||
|
||||
[people.vangel76]
|
||||
real_name = "Valentin Klein"
|
||||
display_name = "vangel76"
|
||||
sync_github_name = false
|
||||
|
||||
[people.FrancoJacquet]
|
||||
real_name = "Franco Jacquet"
|
||||
|
||||
[people.FractalEncrypt]
|
||||
sync_github_name = true
|
||||
|
||||
[people.sadkotheguest]
|
||||
real_name = "Alexander Buraga"
|
||||
display_name = "Alexander Buraga"
|
||||
sync_github_name = false
|
||||
|
||||
[people.adikshan11]
|
||||
real_name = "Adithya Shankaran"
|
||||
sync_github_name = true
|
||||
|
||||
[people.slafebre]
|
||||
real_name = "Sven Lafebre"
|
||||
|
||||
[people.kylekanouse]
|
||||
real_name = "Kyle Kanouse"
|
||||
sync_github_name = true
|
||||
@@ -23,6 +23,7 @@ Affinity files.
|
||||
| Solid fills: RGBA, HSLA, CMYK, grey, Lab (D50) | fill appearance (alpha as fill opacity) |
|
||||
| Linear, elliptical and radial gradients with Affinity's midpoint bias | gradients (the bias as the midpoint where the blend is half way) |
|
||||
| Strokes: weight, scale with object, dash pattern and phase, alignment, miter limit, behind the fill; a stroke whose style is None (every shape stores one, black and 1 px) is left out | stroke appearance |
|
||||
| A stroke's pressure curve (`LDeP`: position along the path against width) | the stroke's width profile, the curve sampled at 2 to 8 points per segment (256 segments at most), widths up to the full weight |
|
||||
| Fill layers (`FRst`) | filled rectangles |
|
||||
| Artistic and frame text: Unicode scalar-indexed runs, stored fallback font, family/weight/style, boolean OpenType features, all caps, underline, strikethrough, size, tracking, horizontal scale, fixed leading, colour, outlined characters, first baseline; each paragraph's alignment, indents, space before and after, fixed and automatic leading; frame text sized by its text scale (`FTxS`), not its frame's transform | point type and area type, one paragraph style per paragraph; artistic text whose paragraphs align differently keeps them aligned within its longest line (by indents), as Affinity draws it; a frame's first line hangs from its capitals' tops, and a frame whose last lines' descenders hang out of it is made just tall enough to show them; line breaks inside a paragraph become paragraphs without spacing between them; table cells place their text as Affinity does (centred from the capitals' tops to the last baseline, reaching out of a cell too short for it) |
|
||||
| Tables (`TxtT`): grid, cell text, merged cells, cell insets and vertical alignment, the line on every cell edge | a group of area type per cell and a stroked line per edge (VectorCraft has no tables) |
|
||||
@@ -33,7 +34,7 @@ Affinity files.
|
||||
| Opacity, visibility, lock, names, the blend modes VectorCraft has | the same |
|
||||
|
||||
Everything else is reported in the import warnings, one line per kind with a count, never
|
||||
dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush and pressure strokes,
|
||||
dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush strokes, pressure curves that can't be read or that go past the million points one document may hold,
|
||||
transparency gradients, fill opacity, bitmap fills, master pages based on other master pages, conical gradients (as radial),
|
||||
special shapes (cloud, heart, cog, callouts, arrows…, imported as their bounding ellipse), corner
|
||||
types other than round or straight, stars with rounded points, several fills or strokes on one object (the
|
||||
|
||||
@@ -15,6 +15,13 @@ const DOCUMENT_KIND: &[u8; 4] = b"nsrP";
|
||||
|
||||
/// A save appends one table; real files have one to a few hundred.
|
||||
const MAX_TABLES: usize = 4096;
|
||||
/// Allocation records read over the whole table chain. Each save lists every entry again, so a
|
||||
/// document with a few hundred saves of a few thousand entries stays far below; tables whose
|
||||
/// record regions overlap (or a table chain of thousands of huge tables) can't multiply the work.
|
||||
const MAX_INDEX_RECORDS: usize = 1 << 22;
|
||||
/// Bytes of entry names kept by the index (after lossy UTF-8 decoding, which can triple a name).
|
||||
/// Real names (`doc.dat`, `d/12`) are a few bytes each.
|
||||
const MAX_INDEX_NAME_BYTES: usize = 16 << 20;
|
||||
/// zstd window ceiling: real documents use a few MiB; this stops a header from reserving gigabytes.
|
||||
const MAX_ZSTD_WINDOW: u64 = 64 << 20;
|
||||
|
||||
@@ -75,6 +82,9 @@ pub struct Archive<'a> {
|
||||
pub revisions: usize,
|
||||
extracted: usize,
|
||||
limits: Limits,
|
||||
/// Entries whose extraction failed after their size was charged: asked again, they fail
|
||||
/// again without being decompressed again.
|
||||
failed: HashMap<String, Error>,
|
||||
}
|
||||
|
||||
pub(crate) struct Cursor<'a> {
|
||||
@@ -157,7 +167,15 @@ pub fn header(bytes: &[u8]) -> Result<Header, Error> {
|
||||
|
||||
impl<'a> Archive<'a> {
|
||||
pub fn open(bytes: &'a [u8], limits: Limits) -> Result<Self, Error> {
|
||||
Self::open_within(bytes, limits, MAX_INDEX_RECORDS, MAX_INDEX_NAME_BYTES)
|
||||
}
|
||||
|
||||
/// [`Archive::open`] reading at most `max_records` allocation records and keeping at most
|
||||
/// `max_name_bytes` bytes of entry names, both over the whole table chain.
|
||||
pub(crate) fn open_within(bytes: &'a [u8], limits: Limits, max_records: usize, max_name_bytes: usize) -> Result<Self, Error> {
|
||||
let header = header(bytes)?;
|
||||
let mut records_left = max_records;
|
||||
let mut name_bytes_left = max_name_bytes;
|
||||
// Newest record per id: (table date, table index, record).
|
||||
let mut latest: HashMap<u32, (u64, usize, Option<Entry>)> = HashMap::new();
|
||||
let mut names: HashMap<u32, String> = HashMap::new();
|
||||
@@ -189,6 +207,7 @@ impl<'a> Archive<'a> {
|
||||
let dirs = c.u16()?;
|
||||
c.take(1)?;
|
||||
for _ in 0..files {
|
||||
records_left = records_left.checked_sub(1).ok_or(Error::Limit("too many archive entries"))?;
|
||||
let id = c.u32()?;
|
||||
let flag = c.u8()?;
|
||||
let mut record = None;
|
||||
@@ -224,8 +243,13 @@ impl<'a> Archive<'a> {
|
||||
}
|
||||
if flag == 0 {
|
||||
let len = usize::from(c.u16()?);
|
||||
let name = String::from_utf8_lossy(c.take(len)?).into_owned();
|
||||
names.entry(id).or_insert(name);
|
||||
let raw = c.take(len)?;
|
||||
// Only the first name of an id is kept: later ones are not even decoded.
|
||||
if let std::collections::hash_map::Entry::Vacant(slot) = names.entry(id) {
|
||||
let name = String::from_utf8_lossy(raw);
|
||||
name_bytes_left = name_bytes_left.checked_sub(name.len()).ok_or(Error::Limit("archive entry names too long"))?;
|
||||
slot.insert(name.into_owned());
|
||||
}
|
||||
}
|
||||
// Equal dates: the first table in the chain (the newest) wins, as in afread.
|
||||
let replace = latest.get(&id).is_none_or(|(d, _, _)| date > *d);
|
||||
@@ -234,6 +258,7 @@ impl<'a> Archive<'a> {
|
||||
}
|
||||
}
|
||||
for _ in 0..dirs {
|
||||
records_left = records_left.checked_sub(1).ok_or(Error::Limit("too many archive entries"))?;
|
||||
let len = usize::from(c.u16()?);
|
||||
c.take(10)?;
|
||||
c.take(len)?;
|
||||
@@ -241,12 +266,12 @@ impl<'a> Archive<'a> {
|
||||
}
|
||||
let mut entries = HashMap::new();
|
||||
for (id, (_, _, record)) in latest {
|
||||
if let (Some(mut e), Some(name)) = (record, names.get(&id)) {
|
||||
e.name = name.clone();
|
||||
if let (Some(mut e), Some(name)) = (record, names.remove(&id)) {
|
||||
e.name = name;
|
||||
entries.insert(e.name.clone(), e);
|
||||
}
|
||||
}
|
||||
Ok(Self { bytes, header, entries, revisions: tables, extracted: 0, limits })
|
||||
Ok(Self { bytes, header, entries, revisions: tables, extracted: 0, limits, failed: HashMap::new() })
|
||||
}
|
||||
|
||||
pub fn entry(&self, name: &str) -> Option<&Entry> {
|
||||
@@ -279,7 +304,10 @@ impl<'a> Archive<'a> {
|
||||
}
|
||||
|
||||
pub fn read(&mut self, name: &str) -> Result<Vec<u8>, Error> {
|
||||
let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?.clone();
|
||||
if let Some(e) = self.failed.get(name) {
|
||||
return Err(*e);
|
||||
}
|
||||
let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?;
|
||||
let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?;
|
||||
if size > self.limits.max_entry {
|
||||
return Err(Error::Limit("archive entry too large"));
|
||||
@@ -288,30 +316,41 @@ impl<'a> Archive<'a> {
|
||||
if total > self.limits.max_total {
|
||||
return Err(Error::Limit("document too large"));
|
||||
}
|
||||
let mut c = Cursor::new(self.bytes, offset(e.offset)?);
|
||||
if c.take(4)? != b"#Fil" {
|
||||
return Err(Error::Malformed("archive entry has no data block"));
|
||||
}
|
||||
let method = e.compression & 3;
|
||||
let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size };
|
||||
let data = c.take(offset(stored_len)?)?;
|
||||
let mut out = match method {
|
||||
1 => inflate(data, size)?,
|
||||
2 => unzstd(data, size)?,
|
||||
_ => data.to_vec(),
|
||||
};
|
||||
if out.len() != size {
|
||||
return Err(Error::Malformed("archive entry size mismatch"));
|
||||
}
|
||||
unpredict(&mut out, e.compression)?;
|
||||
if crc32fast::hash(&out) != e.crc {
|
||||
return Err(Error::Malformed("archive entry checksum mismatch"));
|
||||
}
|
||||
// Charged before the work, and kept when it fails: an entry that fails its checksum
|
||||
// can't be decompressed over and over for free.
|
||||
self.extracted = total;
|
||||
Ok(out)
|
||||
let result = extract(self.bytes, e, size);
|
||||
if let Err(err) = result {
|
||||
self.failed.insert(name.to_owned(), err);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// Decompress entry `e` of `bytes` (declared `size` bytes), undo its predictor and check its CRC.
|
||||
fn extract(bytes: &[u8], e: &Entry, size: usize) -> Result<Vec<u8>, Error> {
|
||||
let mut c = Cursor::new(bytes, offset(e.offset)?);
|
||||
if c.take(4)? != b"#Fil" {
|
||||
return Err(Error::Malformed("archive entry has no data block"));
|
||||
}
|
||||
let method = e.compression & 3;
|
||||
let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size };
|
||||
let data = c.take(offset(stored_len)?)?;
|
||||
let mut out = match method {
|
||||
1 => inflate(data, size)?,
|
||||
2 => unzstd(data, size)?,
|
||||
_ => data.to_vec(),
|
||||
};
|
||||
if out.len() != size {
|
||||
return Err(Error::Malformed("archive entry size mismatch"));
|
||||
}
|
||||
unpredict(&mut out, e.compression)?;
|
||||
if crc32fast::hash(&out) != e.crc {
|
||||
return Err(Error::Malformed("archive entry checksum mismatch"));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Read at most `size + 1` bytes so a stream that decodes past its declared size is caught
|
||||
/// without unbounded allocation.
|
||||
fn read_bounded(mut r: impl Read, size: usize) -> Result<Vec<u8>, Error> {
|
||||
|
||||
@@ -169,6 +169,88 @@ fn curves(r: &mut Reader, crvs: ObjId, budget: &mut OutlineBudget) -> Option<Pat
|
||||
Some(path)
|
||||
}
|
||||
|
||||
/// Most segments a stroke's pressure curve may have; the curves in real documents have a handful.
|
||||
const MAX_PRESSURE_SEGMENTS: usize = 256;
|
||||
|
||||
/// Most regular samples of a pressure curve: each segment gets an equal share, at least 2 (its
|
||||
/// middle and its end) and 8 at most. The points where a segment's width stops rising or falling
|
||||
/// come on top (at most two per segment), so a curve has at most 1 + 4 × [`MAX_PRESSURE_SEGMENTS`]
|
||||
/// points; the document's limit counts all of them.
|
||||
const PRESSURE_POINTS: usize = 512;
|
||||
|
||||
/// Most points one pressure curve can have (see [`PRESSURE_POINTS`]). A curve that can't be read
|
||||
/// counts this many against the document's limit.
|
||||
pub(crate) const MAX_PRESSURE_CURVE_POINTS: usize = 1 + 4 * MAX_PRESSURE_SEGMENTS;
|
||||
|
||||
/// A stroke's pressure curve (`LDsc.LDeP`, a `CrvD` whose positional `Data` holds an array of
|
||||
/// 18-byte records as in [`curves`]): x is the position along the path (0 to 1) and y the width as
|
||||
/// a fraction of the stroke's weight. Each segment is sampled at 2 to 8 points, at most
|
||||
/// [`PRESSURE_POINTS`] in all, and also where its width stops rising or falling (at most two more
|
||||
/// points), so a dip between samples is kept → (position, width) in order along the path,
|
||||
/// positions clamped into 0..1 and never going back, widths clamped into 0..1. `None` when the
|
||||
/// curve can't be read or has more than [`MAX_PRESSURE_SEGMENTS`] segments.
|
||||
pub(crate) fn pressure(r: &Reader, crvd: ObjId) -> Option<Vec<(f64, f64)>> {
|
||||
let s = r.s;
|
||||
let data = s.obj(crvd, b"Data")?;
|
||||
let records = s.positional(data).find_map(|v| if let Value::Array(a) = v { Some(a) } else { None })?;
|
||||
// Every segment takes at least an anchor record.
|
||||
if records.len() > MAX_PRESSURE_SEGMENTS * 3 + 1 {
|
||||
return None;
|
||||
}
|
||||
let curve = subpath(&anchors(records)?, false, None)?;
|
||||
if curve.segments.len() > MAX_PRESSURE_SEGMENTS {
|
||||
return None;
|
||||
}
|
||||
let steps = u32::try_from((PRESSURE_POINTS / curve.segments.len().max(1)).clamp(2, 8)).unwrap_or(2);
|
||||
let mut samples = vec![(curve.start.x, curve.start.y)];
|
||||
let mut from = curve.start;
|
||||
for [c1, c2, to] in &curve.segments {
|
||||
let mut ts: Vec<f64> = (1..=steps).map(|i| f64::from(i) / f64::from(steps)).collect();
|
||||
ts.extend(turning_points(from.y, c1.y, c2.y, to.y).into_iter().flatten());
|
||||
ts.sort_by(f64::total_cmp);
|
||||
ts.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
|
||||
for t in ts {
|
||||
let u = 1.0 - t;
|
||||
let at = |a: f64, b: f64, c: f64, d: f64| u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d;
|
||||
samples.push((at(from.x, c1.x, c2.x, to.x), at(from.y, c1.y, c2.y, to.y)));
|
||||
}
|
||||
from = *to;
|
||||
}
|
||||
let mut last = 0.0f64;
|
||||
Some(
|
||||
samples
|
||||
.into_iter()
|
||||
.map(|(x, y)| {
|
||||
last = x.clamp(last, 1.0);
|
||||
(last, y.clamp(0.0, 1.0))
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The parameters strictly between 0 and 1 where the cubic Bézier with control values `a`, `b`,
|
||||
/// `c` and `d` stops rising or falling (where its derivative is 0). The values are scaled into
|
||||
/// -1..1 first, so huge ones can't overflow the discriminant.
|
||||
fn turning_points(a: f64, b: f64, c: f64, d: f64) -> [Option<f64>; 2] {
|
||||
let scale = a.abs().max(b.abs()).max(c.abs()).max(d.abs());
|
||||
if !(scale.is_finite() && scale > 0.0) {
|
||||
return [None, None];
|
||||
}
|
||||
let (a, b, c, d) = (a / scale, b / scale, c / scale, d / scale);
|
||||
let (d0, d1, d2) = (b - a, c - b, d - c);
|
||||
let (qa, qb, qc) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0);
|
||||
let inside = |t: f64| (t.is_finite() && t > 0.0 && t < 1.0).then_some(t);
|
||||
if qa.abs() < 1e-12 {
|
||||
return [if qb.abs() < 1e-12 { None } else { inside(-qc / qb) }, None];
|
||||
}
|
||||
let disc = qb * qb - 4.0 * qa * qc;
|
||||
if disc < 0.0 {
|
||||
return [None, None];
|
||||
}
|
||||
let root = disc.sqrt();
|
||||
[inside((-qb - root) / (2.0 * qa)), inside((-qb + root) / (2.0 * qa))]
|
||||
}
|
||||
|
||||
struct Anchor {
|
||||
p: Point,
|
||||
inh: Option<Point>,
|
||||
@@ -260,3 +342,19 @@ fn corner_radii(fields: Vec<&Value>) -> Option<Vec<(usize, f64)>> {
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn turning_points_of_huge_control_values_are_found() {
|
||||
let small = turning_points(1.0, -3.0, 3.0, 1.0);
|
||||
let huge = turning_points(1e200, -3e200, 3e200, 1e200);
|
||||
assert!(small.iter().all(Option::is_some), "{small:?}");
|
||||
for (s, h) in small.iter().zip(&huge) {
|
||||
let (Some(s), Some(h)) = (s, h) else { panic!("{huge:?}") };
|
||||
assert!((s - h).abs() < 1e-12, "{small:?} {huge:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,17 @@ const MAX_DOCUMENT_CHARS: usize = 16 << 20;
|
||||
/// Table cells of all tables together (each becomes a text object with its edge lines).
|
||||
const MAX_DOCUMENT_CELLS: usize = 1 << 18;
|
||||
|
||||
/// Points of all strokes' pressure curves together (a stroke style may be shared by many layers).
|
||||
const MAX_DOCUMENT_PRESSURE_POINTS: usize = 1 << 20;
|
||||
|
||||
/// Child references inspected, page rectangles produced, and outline segments retained, in all
|
||||
/// (shared objects are visited once per link, so each visit is charged). Real documents stay
|
||||
/// within a few times [`MAX_NODES`]; this leaves ~30x headroom over that.
|
||||
const MAX_DOCUMENT_WORK: usize = 1 << 24;
|
||||
|
||||
/// Owned layer-name characters kept in all (each visit of a shared object keeps its own copy).
|
||||
const MAX_DOCUMENT_NAME_CHARS: usize = 16 << 20;
|
||||
|
||||
/// What a whole read may still use. Shared objects can be linked from many layers, and embedded
|
||||
/// documents are read with what their embedding document left, so linking or embedding the
|
||||
/// same content many times can't multiply the work.
|
||||
@@ -39,10 +50,30 @@ pub(crate) struct Budget {
|
||||
pub(crate) chars: usize,
|
||||
/// Table cells ([`MAX_DOCUMENT_CELLS`] in all).
|
||||
pub(crate) cells: usize,
|
||||
/// Points of pressure curves ([`MAX_DOCUMENT_PRESSURE_POINTS`] in all).
|
||||
pub(crate) pressure: usize,
|
||||
/// Child references, page rectangles and outline segments ([`MAX_DOCUMENT_WORK`] in all).
|
||||
pub(crate) work: usize,
|
||||
/// Layer-name characters ([`MAX_DOCUMENT_NAME_CHARS`] in all).
|
||||
pub(crate) name_chars: usize,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
pub(crate) const FULL: Budget = Budget { nodes: MAX_NODES, pixels: MAX_LAYER_PIXELS, chars: MAX_DOCUMENT_CHARS, cells: MAX_DOCUMENT_CELLS };
|
||||
pub(crate) const FULL: Budget = Budget {
|
||||
nodes: MAX_NODES,
|
||||
pixels: MAX_LAYER_PIXELS,
|
||||
chars: MAX_DOCUMENT_CHARS,
|
||||
cells: MAX_DOCUMENT_CELLS,
|
||||
pressure: MAX_DOCUMENT_PRESSURE_POINTS,
|
||||
work: MAX_DOCUMENT_WORK,
|
||||
name_chars: MAX_DOCUMENT_NAME_CHARS,
|
||||
};
|
||||
|
||||
/// Take `n` units of work, or fail the read.
|
||||
pub(crate) fn spend(&mut self, n: usize) -> Result<(), Error> {
|
||||
self.work = self.work.checked_sub(n).ok_or(Error::Limit("too much shared geometry or page data"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a document: archive, `doc.dat` and the model.
|
||||
@@ -181,6 +212,7 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
return Ok(None);
|
||||
}
|
||||
let pages = pages(s, spread);
|
||||
self.budget.spend(pages.len() + 1)?;
|
||||
let default_size = s.floats::<2>(doc, b"DfSz").filter(|[w, h]| *w > 0.0 && *h > 0.0).map(|[w, h]| Rect { x0: 0.0, y0: 0.0, x1: w, y1: h });
|
||||
let bounds = s.floats::<4>(spread, b"SprB").map(rect).or_else(|| pages.iter().copied().reduce(union)).or(default_size).unwrap_or(Rect {
|
||||
x0: 0.0,
|
||||
@@ -203,7 +235,10 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
let s = self.s;
|
||||
let mut out = Vec::new();
|
||||
let mut mask = None;
|
||||
for c in s.objs(parent, b"Chld") {
|
||||
let kids = s.objs(parent, b"Chld");
|
||||
// Invisible masks and skipped children cost no node, so the visit is charged here.
|
||||
self.budget.spend(kids.len())?;
|
||||
for c in kids {
|
||||
if s.is(c, b"MRst") {
|
||||
// A mask layer inside a group or layer masks that container.
|
||||
if s.bool(c, b"Visi") == Some(false) {
|
||||
@@ -243,7 +278,8 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
let world = local.then(parent);
|
||||
let class = s.class(id).unwrap_or(Tag(0));
|
||||
// A layer name is short; a long one is cut, as every visit of a shared object keeps a copy.
|
||||
let name: String = s.str(id, b"Desc").unwrap_or_default().chars().take(MAX_NAME_CHARS).collect();
|
||||
let name: String = s.str(id, b"Desc").unwrap_or_default().chars().take(MAX_NAME_CHARS.min(self.budget.name_chars)).collect();
|
||||
self.budget.name_chars -= name.chars().count();
|
||||
let visible = s.bool(id, b"Visi").unwrap_or(true);
|
||||
let locked = s.bool(id, b"Edtb").is_some_and(|e| !e);
|
||||
let opacity = s.f64(id, b"Opac").map_or(1.0, |o| o.clamp(0.0, 1.0));
|
||||
@@ -301,6 +337,7 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
self.warn(format!("a {} that could not be read", describe(class)));
|
||||
return Ok(Kind::Unsupported);
|
||||
};
|
||||
self.budget.spend(local.subpaths.iter().map(|sp| sp.segments.len() + 1).sum())?;
|
||||
let (fills, strokes) = paint::node_paint(self, id, world);
|
||||
Kind::Shape { path: local.transformed(world), fills, strokes, even_odd }
|
||||
}
|
||||
@@ -634,3 +671,15 @@ impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
Kind::Artboard { rect, path: path.transformed(world), even_odd, background, strokes }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod budget_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shared_work_is_bounded() {
|
||||
let mut b = Budget::FULL;
|
||||
assert!(b.spend(MAX_DOCUMENT_WORK).is_ok());
|
||||
assert_eq!(b.spend(1), Err(Error::Limit("too much shared geometry or page data")));
|
||||
}
|
||||
}
|
||||
@@ -332,7 +332,7 @@ fn pixels(img: &mut Image, o: &Overlay) -> bool {
|
||||
};
|
||||
let to_unit = match o.source {
|
||||
Source::Gradient(g) => match invert(g.transform) {
|
||||
Some(m) => Some((img.transform.then(m), g)),
|
||||
Some(m) => Some((img.transform.then(m), g, stop_reach(g))),
|
||||
None => return false,
|
||||
},
|
||||
Source::Solid(_) => None,
|
||||
@@ -343,9 +343,9 @@ fn pixels(img: &mut Image, o: &Overlay) -> bool {
|
||||
}
|
||||
let (s, sa) = match (solid, &to_unit) {
|
||||
(Some(s), _) => s,
|
||||
(None, Some((m, g))) => {
|
||||
(None, Some((m, g, reach))) => {
|
||||
let q = m.apply(Point { x: (i % width) as f64 + 0.5, y: (i / width) as f64 + 0.5 });
|
||||
let c = sample(g, q);
|
||||
let c = sample(g, reach, q);
|
||||
(rgb(c), c.alpha())
|
||||
}
|
||||
(None, None) => continue,
|
||||
@@ -376,8 +376,22 @@ fn decode(bytes: &[u8], width: u32, height: u32) -> Option<Vec<u8>> {
|
||||
Some(reader.decode().ok()?.into_rgba8().into_raw())
|
||||
}
|
||||
|
||||
/// The gradient's colour at unit-space point `q`.
|
||||
fn sample(g: &Gradient, q: Point) -> Color {
|
||||
/// For each pair of neighbouring stops (`k`, `k + 1`), the largest offset of stops `1..=k + 1`:
|
||||
/// the first pair whose end offset a `t` doesn't pass is the first whose reach it doesn't pass, and
|
||||
/// reaches never decrease, so [`sample`] finds it by binary search, sorted stops or not.
|
||||
fn stop_reach(g: &Gradient) -> Vec<f64> {
|
||||
g.stops
|
||||
.iter()
|
||||
.skip(1)
|
||||
.scan(f64::NEG_INFINITY, |m, s| {
|
||||
*m = m.max(s.offset);
|
||||
Some(*m)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The gradient's colour at unit-space point `q` (`reach`: [`stop_reach`] of `g`).
|
||||
fn sample(g: &Gradient, reach: &[f64], q: Point) -> Color {
|
||||
let t = match g.kind {
|
||||
GradientKind::Linear => q.x,
|
||||
GradientKind::Radial => q.x.hypot(q.y),
|
||||
@@ -388,18 +402,16 @@ fn sample(g: &Gradient, q: Point) -> Color {
|
||||
if t <= first.offset {
|
||||
return first.color;
|
||||
}
|
||||
for w in g.stops.windows(2) {
|
||||
let [a, b] = [&w[0], &w[1]];
|
||||
if t <= b.offset {
|
||||
let span = b.offset - a.offset;
|
||||
let u = if span > 1e-9 { (t - a.offset) / span } else { 1.0 };
|
||||
// Affinity's midpoint bias (see `Stop::half_point`).
|
||||
let k = 1.0 + 8.0 * (a.bias - 0.5).abs();
|
||||
let u = if a.bias >= 0.5 { u.powf(k) } else { 1.0 - (1.0 - u).powf(k) };
|
||||
let (x, y) = (rgb(a.color), rgb(b.color));
|
||||
let [r, g, bl] = [0, 1, 2].map(|i| x[i] + (y[i] - x[i]) * u);
|
||||
return Color::Rgb { r, g, b: bl, a: a.color.alpha() + (b.color.alpha() - a.color.alpha()) * u };
|
||||
}
|
||||
let k = reach.partition_point(|r| *r < t);
|
||||
if let (Some(a), Some(b)) = (g.stops.get(k), g.stops.get(k + 1)) {
|
||||
let span = b.offset - a.offset;
|
||||
let u = if span > 1e-9 { (t - a.offset) / span } else { 1.0 };
|
||||
// Affinity's midpoint bias (see `Stop::half_point`).
|
||||
let k = 1.0 + 8.0 * (a.bias - 0.5).abs();
|
||||
let u = if a.bias >= 0.5 { u.powf(k) } else { 1.0 - (1.0 - u).powf(k) };
|
||||
let (x, y) = (rgb(a.color), rgb(b.color));
|
||||
let [r, g, bl] = [0, 1, 2].map(|i| x[i] + (y[i] - x[i]) * u);
|
||||
return Color::Rgb { r, g, b: bl, a: a.color.alpha() + (b.color.alpha() - a.color.alpha()) * u };
|
||||
}
|
||||
last.color
|
||||
}
|
||||
|
||||
@@ -121,6 +121,9 @@ pub struct Stroke {
|
||||
pub dash: Option<(Vec<f64>, f64)>,
|
||||
/// Painted below the fill instead of above it.
|
||||
pub behind: bool,
|
||||
/// The pressure curve: (position 0..1 along the path, width as a fraction of `width`) in
|
||||
/// order along the path, `None` for a stroke of the same width all along.
|
||||
pub profile: Option<Vec<(f64, f64)>>,
|
||||
}
|
||||
|
||||
/// Gradient stops per gradient.
|
||||
@@ -235,12 +238,13 @@ pub(crate) fn descriptor(r: &mut Reader, id: ObjId, local: Affine) -> Option<Pai
|
||||
};
|
||||
let grad = s.obj(fill, b"Grad")?;
|
||||
let cols = s.objs(grad, b"Cols");
|
||||
let posn: Vec<Vec<f64>> = match s.field(grad, b"Posn") {
|
||||
Some(Value::Array(a)) => a.iter().filter_map(floats).collect(),
|
||||
_ => Vec::new(),
|
||||
// Convert only the positions that pair with a colour, as shared attributes repeat this per run.
|
||||
let posn: &[Value] = match s.field(grad, b"Posn") {
|
||||
Some(Value::Array(a)) => a,
|
||||
_ => &[],
|
||||
};
|
||||
let mut stops = Vec::new();
|
||||
for (c, p) in cols.iter().zip(&posn).take(MAX_STOPS) {
|
||||
for (c, p) in cols.iter().zip(posn.iter().filter_map(floats)).take(MAX_STOPS) {
|
||||
let color = color(r, *c)?;
|
||||
let offset = p.first().copied().filter(|v| v.is_finite()).unwrap_or(0.0).clamp(0.0, 1.0);
|
||||
let bias = p.get(1).copied().filter(|v| v.is_finite()).unwrap_or(0.5).clamp(0.0, 1.0);
|
||||
@@ -350,10 +354,38 @@ pub(crate) fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, beh
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if s.obj(lsty, b"Brus").is_some() || s.obj(ldsc, b"LDeP").is_some() {
|
||||
r.warn("brush and pressure strokes (imported as plain strokes)");
|
||||
if s.obj(lsty, b"Brus").is_some() {
|
||||
r.warn("brush strokes (imported as plain strokes)");
|
||||
}
|
||||
Some(Stroke { paint, width, cap, join, miter_limit, align, dash, behind })
|
||||
// The pressure curve sets the width along the path; one at full width all along is a plain
|
||||
// stroke. Every curve read counts against the document's points: one at full width counts its
|
||||
// points, and one that can't be read counts the most a curve may have. Once the points are
|
||||
// used up the rest are not read.
|
||||
const BEYOND: &str = "pressure strokes beyond the pressure points one document may hold (imported as plain strokes)";
|
||||
let ldep = s.obj(ldsc, b"LDeP");
|
||||
if ldep.is_some() && r.budget.pressure == 0 {
|
||||
r.warn(BEYOND);
|
||||
}
|
||||
let profile = match ldep.filter(|_| r.budget.pressure > 0).map(|p| crate::geometry::pressure(r, p)) {
|
||||
Some(Some(points)) => match r.budget.pressure.checked_sub(points.len()) {
|
||||
Some(left) => {
|
||||
r.budget.pressure = left;
|
||||
(!points.iter().all(|(_, w)| (w - 1.0).abs() < 1e-9)).then_some(points)
|
||||
}
|
||||
None => {
|
||||
r.budget.pressure = 0;
|
||||
r.warn(BEYOND);
|
||||
None
|
||||
}
|
||||
},
|
||||
Some(None) => {
|
||||
r.budget.pressure = r.budget.pressure.saturating_sub(crate::geometry::MAX_PRESSURE_CURVE_POINTS);
|
||||
r.warn("pressure strokes whose pressure curve can't be read (imported as plain strokes)");
|
||||
None
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Some(Stroke { paint, width, cap, join, miter_limit, align, dash, behind, profile })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -195,6 +195,11 @@ fn decode_within(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), worl
|
||||
if let Some(name) = s.entry(bitmap, b"Bckg") {
|
||||
let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
// The whole source is decoded for every layer that reads it, so charge it all, not only the crop.
|
||||
let Some(left) = r.budget.pixels.checked_sub(u64::from(width) * u64::from(height)) else {
|
||||
return Err(Error::Limit("embedded image pixels"));
|
||||
};
|
||||
r.budget.pixels = left;
|
||||
match original(r, name).and_then(|bytes| source_pixels(&bytes, width, height)) {
|
||||
Ok(pixels) => Some((width as usize, pixels)),
|
||||
Err(Error::Limit(e)) => return Err(Error::Limit(e)),
|
||||
@@ -318,8 +323,10 @@ fn grid(s: &stream::Stream, bitmap: ObjId, c: usize, bps: usize) -> (usize, usiz
|
||||
let height = s.int(bitmap, b"BmpH").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
|
||||
let tw = s.int(bitmap, &tag(b"TWi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| width.saturating_mul(bps).div_ceil(TILE));
|
||||
let th = s.int(bitmap, &tag(b"THi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| height.div_ceil(TILE));
|
||||
// A grid larger than the bitmap has tiles no crop can reach: don't convert or scan them on every reference.
|
||||
let tiles = width.saturating_mul(bps).div_ceil(TILE).saturating_mul(height.div_ceil(TILE));
|
||||
let states: Vec<u8> = match s.field(bitmap, &tag(b"Sta", c)) {
|
||||
Some(Value::Array(a)) => a.iter().map(|v| if let Value::UInt(u) = v { u8::try_from(*u).unwrap_or(255) } else { 255 }).collect(),
|
||||
Some(Value::Array(a)) => a.iter().take(tiles).map(|v| if let Value::UInt(u) = v { u8::try_from(*u).unwrap_or(255) } else { 255 }).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
(tw, th, states)
|
||||
|
||||
@@ -13,8 +13,7 @@ const MAX_SIDES: i64 = 10_000;
|
||||
|
||||
/// The last value of a tag: a shape changed from one kind to another keeps a stale first block.
|
||||
fn last<'a>(r: &'a Reader, id: ObjId, tag: &[u8; 4]) -> Option<&'a Value> {
|
||||
let t = Tag::of(tag);
|
||||
r.s.object(id)?.fields.iter().rev().find(|(k, _)| *k == t).map(|(_, v)| v)
|
||||
r.s.object(id)?.get_last(Tag::of(tag))
|
||||
}
|
||||
|
||||
fn num(r: &Reader, id: ObjId, tag: &[u8; 4]) -> Option<f64> {
|
||||
@@ -51,12 +50,13 @@ pub(crate) fn shape(r: &mut Reader, shape: ObjId, b: [f64; 4], world: Affine) ->
|
||||
let class = r.s.class(shape)?;
|
||||
let sub = match &class.0.to_be_bytes() {
|
||||
b"ShNR" | b"ShRR" => {
|
||||
let types = match last(r, shape, b"CTyp") {
|
||||
Some(Value::Array(a)) => a.iter().map(|t| if let Value::Enum { id, .. } = t { Some(*id) } else { None }).collect(),
|
||||
// Only the four corners' entries can matter: longer arrays are read no further.
|
||||
let types: Vec<Option<u16>> = match last(r, shape, b"CTyp") {
|
||||
Some(Value::Array(a)) => a.iter().take(4).map(|t| if let Value::Enum { id, .. } = t { Some(*id) } else { None }).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let radii = match last(r, shape, b"ShCR") {
|
||||
Some(Value::Floats(v)) => v.iter().map(|f| if f.is_finite() && *f > 0.0 { *f } else { 0.0 }).collect(),
|
||||
let radii: Vec<f64> = match last(r, shape, b"ShCR") {
|
||||
Some(Value::Floats(v)) => v.iter().take(4).map(|f| if f.is_finite() && *f > 0.0 { *f } else { 0.0 }).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
// Corners follow the first one (top left) unless they were unlocked; then each has
|
||||
|
||||
@@ -73,11 +73,67 @@ pub struct Object {
|
||||
pub chain: Vec<Tag>,
|
||||
/// Fields in stream order; positional fields have tag 0.
|
||||
pub fields: Vec<(Tag, Value)>,
|
||||
/// For objects with many fields: each tag with the positions of its first and last field,
|
||||
/// sorted by tag, so a lookup isn't a scan of every field (a shared object is looked up
|
||||
/// again on every visit). Built by [`Object::index`]; empty for small objects.
|
||||
index: Vec<(Tag, u32, u32)>,
|
||||
}
|
||||
|
||||
/// Objects with more fields than this get an [`Object::index`]; fewer are scanned.
|
||||
const INDEXED_FIELDS: usize = 16;
|
||||
|
||||
impl Object {
|
||||
pub fn new(class: Tag, kind: Kind, chain: Vec<Tag>, fields: Vec<(Tag, Value)>) -> Self {
|
||||
let mut o = Self { class, kind, chain, fields, index: Vec::new() };
|
||||
o.index();
|
||||
o
|
||||
}
|
||||
|
||||
/// (Re)build the tag index after `fields` changed.
|
||||
fn index(&mut self) {
|
||||
self.index.clear();
|
||||
if self.fields.len() <= INDEXED_FIELDS {
|
||||
return;
|
||||
}
|
||||
let mut index: Vec<(Tag, u32, u32)> = Vec::new();
|
||||
if index.try_reserve_exact(self.fields.len()).is_err() {
|
||||
return;
|
||||
}
|
||||
// Fields beyond u32 positions are impossible: a stream holds at most MAX_VALUES values.
|
||||
index.extend(self.fields.iter().enumerate().filter_map(|(i, (t, _))| u32::try_from(i).ok().map(|i| (*t, i, i))));
|
||||
// Stable: equal tags stay in stream order, so the run of a tag starts at its first field.
|
||||
index.sort_by_key(|(t, _, _)| *t);
|
||||
index.dedup_by(|later, first| {
|
||||
if later.0 == first.0 {
|
||||
first.2 = later.2;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
index.shrink_to_fit();
|
||||
self.index = index;
|
||||
}
|
||||
|
||||
fn position(&self, tag: Tag, last: bool) -> Option<usize> {
|
||||
if self.index.is_empty() {
|
||||
let mut fields = self.fields.iter().enumerate();
|
||||
let hit = if last { fields.rev().find(|(_, (t, _))| *t == tag) } else { fields.find(|(_, (t, _))| *t == tag) };
|
||||
return hit.map(|(i, _)| i);
|
||||
}
|
||||
let at = self.index.binary_search_by_key(&tag, |(t, _, _)| *t).ok()?;
|
||||
let (_, first, end) = self.index.get(at)?;
|
||||
usize::try_from(if last { *end } else { *first }).ok()
|
||||
}
|
||||
|
||||
/// The first field tagged `tag`.
|
||||
pub fn get(&self, tag: Tag) -> Option<&Value> {
|
||||
self.fields.iter().find(|(t, _)| *t == tag).map(|(_, v)| v)
|
||||
self.fields.get(self.position(tag, false)?).map(|(_, v)| v)
|
||||
}
|
||||
|
||||
/// The last field tagged `tag` (a shape changed from one kind to another keeps a stale first one).
|
||||
pub fn get_last(&self, tag: Tag) -> Option<&Value> {
|
||||
self.fields.get(self.position(tag, true)?).map(|(_, v)| v)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,10 +180,11 @@ pub fn parse(bytes: &[u8]) -> Result<Stream, Error> {
|
||||
c.u32()?;
|
||||
}
|
||||
let mut p = Parser { c, objects: Vec::new(), shared: std::collections::HashMap::new(), depth: 0, values: 0 };
|
||||
let root = p.push(Object { class, kind: Kind::Root, chain: vec![class], fields: Vec::new() })?;
|
||||
let root = p.push(Object::new(class, Kind::Root, vec![class], Vec::new()))?;
|
||||
let fields = p.fields(true, class)?;
|
||||
if let Some(o) = p.objects.get_mut(root) {
|
||||
o.fields = fields;
|
||||
o.index();
|
||||
}
|
||||
Ok(Stream { root, objects: p.objects })
|
||||
}
|
||||
@@ -252,7 +309,7 @@ impl Parser<'_> {
|
||||
}
|
||||
0x30 => {
|
||||
let fields = self.fields(false, class)?;
|
||||
let id = self.push(Object { class, kind: Kind::Positional, chain: Vec::new(), fields })?;
|
||||
let id = self.push(Object::new(class, Kind::Positional, Vec::new(), fields))?;
|
||||
Value::Obj(Some(id))
|
||||
}
|
||||
0x31 | 0x32 if !tagged => return Err(Error::Malformed("object without a field tag")),
|
||||
@@ -354,7 +411,7 @@ impl Parser<'_> {
|
||||
}
|
||||
};
|
||||
let fields = self.fields(true, class)?;
|
||||
let id = self.push(Object { class, kind: Kind::Inline, chain: vec![class], fields })?;
|
||||
let id = self.push(Object::new(class, Kind::Inline, vec![class], fields))?;
|
||||
Ok(Value::Obj(Some(id)))
|
||||
}
|
||||
|
||||
@@ -373,7 +430,7 @@ impl Parser<'_> {
|
||||
return Err(Error::Malformed("object defined twice"));
|
||||
}
|
||||
// Register before the fields: an object's own fields may refer back to it.
|
||||
let id = self.push(Object { class: Tag(0), kind: Kind::Shared, chain: Vec::new(), fields: Vec::new() })?;
|
||||
let id = self.push(Object::new(Tag(0), Kind::Shared, Vec::new(), Vec::new()))?;
|
||||
self.shared.insert(key, id);
|
||||
let mut chain = Vec::new();
|
||||
let mut fields = Vec::new();
|
||||
@@ -399,8 +456,36 @@ impl Parser<'_> {
|
||||
let class = chain.first().copied().unwrap_or(Tag(0));
|
||||
fields.extend(self.fields(true, class)?);
|
||||
if let Some(o) = self.objects.get_mut(id) {
|
||||
*o = Object { class, kind: Kind::Shared, chain, fields };
|
||||
*o = Object::new(class, Kind::Shared, chain, fields);
|
||||
}
|
||||
Ok(Value::Obj(Some(id)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lookups_in_a_large_object_find_the_first_and_last_fields_of_a_tag() {
|
||||
let tag = |i: u32| Tag(0x4100_0000 + i);
|
||||
let mut fields: Vec<(Tag, Value)> = (0..1000).map(|i| (tag(i % 300), Value::UInt(u64::from(i)))).collect();
|
||||
fields.push((tag(7), Value::Str("last".into())));
|
||||
let o = Object::new(Tag::of(b"Grup"), Kind::Shared, Vec::new(), fields.clone());
|
||||
assert!(!o.index.is_empty());
|
||||
// The index has one entry per distinct tag, not per field.
|
||||
assert_eq!(o.index.len(), 300);
|
||||
for t in 0..300 {
|
||||
let first = fields.iter().find(|(k, _)| *k == tag(t)).map(|(_, v)| v);
|
||||
let last = fields.iter().rev().find(|(k, _)| *k == tag(t)).map(|(_, v)| v);
|
||||
assert_eq!(o.get(tag(t)), first);
|
||||
assert_eq!(o.get_last(tag(t)), last);
|
||||
}
|
||||
assert_eq!(o.get(tag(300)), None);
|
||||
assert_eq!(o.get_last(tag(7)), Some(&Value::Str("last".into())));
|
||||
let small = Object::new(Tag::of(b"Grup"), Kind::Shared, Vec::new(), vec![(tag(1), Value::Bool(true)), (tag(1), Value::Bool(false))]);
|
||||
assert!(small.index.is_empty());
|
||||
assert_eq!(small.get(tag(1)), Some(&Value::Bool(true)));
|
||||
assert_eq!(small.get_last(tag(1)), Some(&Value::Bool(false)));
|
||||
}
|
||||
}
|
||||
@@ -261,6 +261,34 @@ mod archive {
|
||||
assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_that_fails_its_checksum_is_charged_once_and_not_decompressed_again() {
|
||||
let d = doc();
|
||||
let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None);
|
||||
let mut broken = file.clone();
|
||||
broken[90] ^= 0x55;
|
||||
let mut a = Archive::open(&broken, Limits::default()).unwrap();
|
||||
let first = a.read("doc.dat").unwrap_err();
|
||||
// The work was done, so it counts against the import even though it failed.
|
||||
assert_eq!(a.extracted(), d.len());
|
||||
assert_eq!(a.read("doc.dat").unwrap_err(), first);
|
||||
assert_eq!(a.extracted(), d.len());
|
||||
// A budget that only covers one attempt is not exceeded by asking again.
|
||||
let mut a = Archive::open(&broken, Limits { max_entry: usize::MAX, max_total: d.len() }).unwrap();
|
||||
assert!(a.read("doc.dat").is_err());
|
||||
assert_eq!(a.read("doc.dat").unwrap_err(), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_table_index_has_a_budget_for_records_and_names() {
|
||||
let d = doc();
|
||||
let long = "n".repeat(300);
|
||||
let file = synth::container(&[("doc.dat", &d, Method::Stored), (&long, b"tile", Method::Stored)], None);
|
||||
Archive::open_within(&file, Limits::default(), 2, 307).unwrap();
|
||||
assert_eq!(Archive::open_within(&file, Limits::default(), 1, 1 << 20).unwrap_err(), Error::Limit("too many archive entries"));
|
||||
assert_eq!(Archive::open_within(&file, Limits::default(), 2, 306).unwrap_err(), Error::Limit("archive entry names too long"));
|
||||
}
|
||||
|
||||
// Regression test for #1710: ruzstd 0.9.0 let a block decompress to more than its frame's
|
||||
// window allows (RUSTSEC-2026-0344), so a crafted entry made the decoder produce far more than
|
||||
// the format permits for a block. 0.9.1 refuses it.
|
||||
|
||||
@@ -51,6 +51,9 @@ const MAX_TABLE_LINES: usize = 4096;
|
||||
/// Cells a table may have (rows × columns): each becomes a text object with its edge lines.
|
||||
const MAX_TABLE_CELLS: usize = 1 << 16;
|
||||
|
||||
/// Work charged for each copy of a run's formatting a table cell keeps.
|
||||
const TABLE_RUN_COST: usize = 16;
|
||||
|
||||
/// A table node (`TxtT`): the grid, the cells' text and the lines on the cell edges.
|
||||
pub(crate) fn table(r: &mut Reader, id: ObjId, world: Affine) -> Option<Table> {
|
||||
let s = r.s;
|
||||
@@ -108,9 +111,10 @@ pub(crate) fn table(r: &mut Reader, id: ObjId, world: Affine) -> Option<Table> {
|
||||
let mut parts = run.text.split(CELL_BREAK).peekable();
|
||||
while let Some(part) = parts.next() {
|
||||
if !part.is_empty() {
|
||||
// Each cell keeps its own copy of the run's formatting, so each copy is charged.
|
||||
match target.and_then(|i| cells.get_mut(i)) {
|
||||
Some(cell) => cell.runs.push(TextRun { text: part.to_string(), ..run.clone() }),
|
||||
None => extra = true,
|
||||
Some(cell) if r.budget.spend(TABLE_RUN_COST).is_ok() => cell.runs.push(TextRun { text: part.to_string(), ..run.clone() }),
|
||||
_ => extra = true,
|
||||
}
|
||||
}
|
||||
if parts.peek().is_some() {
|
||||
@@ -157,6 +161,13 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
let mut placeholders = false;
|
||||
let mut attribute_budget = Some(MAX_ATTRIBUTE_BYTES);
|
||||
for block in s.objs(story, b"Blok") {
|
||||
// Shared blocks and run lists are visited once per link, so every visit is charged, empty or not.
|
||||
let paragraph_runs = s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default();
|
||||
let attribute_runs = s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default();
|
||||
if r.budget.spend(1 + paragraph_runs.len() + attribute_runs.len()).is_err() {
|
||||
r.warn("text beyond the work one document may hold (truncated)");
|
||||
break;
|
||||
}
|
||||
let Some(glyphs) = s.obj(block, b"Glyp") else {
|
||||
r.warn("a text block without readable characters (left out)");
|
||||
continue;
|
||||
@@ -209,7 +220,7 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
// Paragraph formats by end index; a run without an index covers the rest of the block.
|
||||
let mut paragraphs: Vec<(usize, Paragraph)> = Vec::new();
|
||||
let mut open: Option<Paragraph> = None;
|
||||
for run in s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default() {
|
||||
for run in paragraph_runs {
|
||||
let Some(attrs) = s.obj(run, b"Item") else { continue };
|
||||
let a = paragraph(r, attrs);
|
||||
first_align.get_or_insert(a.align);
|
||||
@@ -238,7 +249,7 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
|
||||
}
|
||||
};
|
||||
let mut start = 0usize;
|
||||
for run in s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default() {
|
||||
for run in attribute_runs {
|
||||
let Some(index) = s.int(run, b"Indx").and_then(|v| usize::try_from(v).ok()) else {
|
||||
r.warn("invalid text attribute range (bounded; unassigned characters use defaults)");
|
||||
continue;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=d23a6900;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)", "brush and pressure strokes (imported as plain strokes) (114×)"]
|
||||
affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=b8cecb1c;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)", "brush and pressure strokes (imported as plain strokes) (534×)"]
|
||||
affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=23d1e39c;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)", "brush and pressure strokes (imported as plain strokes) (54×)"]
|
||||
affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=cafb7572;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush and pressure strokes (imported as plain strokes)"]
|
||||
affinity3-mexican-guy.af dpi=300;spreads=1;model_crc32=32b7cf3f;counts={"depth": 8, "fills": 169, "gradients": 0, "groups": 23, "nodes": 283, "opacity": 1, "segments": 1491, "shapes": 260, "strokes": 114, "subpaths": 264};boards=[];fonts={};warnings=["blur effects (left out) (156×)"]
|
||||
affinity3-mexican-man.af dpi=300;spreads=1;model_crc32=c10daaea;counts={"depth": 7, "fills": 277, "gradients": 2, "groups": 29, "nodes": 903, "segments": 3225, "shapes": 874, "strokes": 540, "subpaths": 881};boards=[];fonts={};warnings=["blur effects (left out) (244×)"]
|
||||
affinity3-mexican-woman.af dpi=300;spreads=1;model_crc32=3bc13374;counts={"depth": 9, "fills": 527, "gradients": 0, "groups": 28, "nodes": 595, "segments": 3562, "shapes": 567, "strokes": 60, "subpaths": 570};boards=[];fonts={};warnings=["blur effects (left out) (278×)"]
|
||||
affinity3-playing-cards.af dpi=300;spreads=1;model_crc32=bc0c838d;counts={"depth": 5, "fills": 363, "gradients": 0, "groups": 758, "nodes": 1350, "segments": 4864, "shapes": 592, "strokes": 17, "subpaths": 656};boards=[];fonts={};warnings=["blur effects (left out) (309×)", "brush strokes (imported as plain strokes)"]
|
||||
patchy-adjust-curves.af dpi=72;spreads=1;model_crc32=36ab962f;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
|
||||
patchy-adjust-hsl.af dpi=72;spreads=1;model_crc32=e2eac05e;counts={"depth": 1, "images": 1, "nodes": 2, "unsupported": 1};boards=[];fonts={};warnings=["adjustment layers"]
|
||||
patchy-artboards.af dpi=72;spreads=1;model_crc32=0037a28e;counts={"artboards": 2, "depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2};boards=["board-a:0.0000,0.0000,80.0000,60.0000", "board-b:100.0000,10.0000,160.0000,70.0000"];fonts={};warnings=[]
|
||||
@@ -30,4 +30,4 @@ patchy-text-rotated.af dpi=72;spreads=1;model_crc32=3d1de559;counts={"depth": 1,
|
||||
patchy-text-runs.af dpi=72;spreads=1;model_crc32=7820b881;counts={"depth": 1, "nodes": 1, "text_chars": 7, "text_runs": 5, "texts": 1};boards=[];fonts={"Arial:ArialNarrow:400:false", "Courier New:CourierNewPSMT:400:false", "Segoe UI Emoji:SegoeUIEmoji:400:false", "Times New Roman:TimesNewRomanPSMT:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font)", "text uses a stored fallback font (imported with that font)"]
|
||||
patchy-transform.af dpi=72;spreads=1;model_crc32=8d56df84;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-vector-mask.af dpi=72;spreads=1;model_crc32=80ca946a;counts={"depth": 1, "fills": 2, "gradients": 0, "nodes": 2, "segments": 7, "shapes": 2, "strokes": 0, "subpaths": 2, "vector_masks": 1};boards=[];fonts={};warnings=["unknown layers attached to other layers (imported without them)"]
|
||||
patchy-vector.af dpi=72;spreads=1;model_crc32=b36a9767;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[]
|
||||
patchy-vector.af dpi=72;spreads=1;model_crc32=3b16c7ed;counts={"depth": 1, "fills": 3, "gradients": 0, "nodes": 4, "segments": 17, "shapes": 4, "strokes": 2, "subpaths": 5};boards=[];fonts={};warnings=[]
|
||||
@@ -5,16 +5,16 @@
|
||||
//! support point in direction `d` is `(a²(u·d)u + b²(v·d)v) / √(a²(u·d)² + b²(v·d)²)`, so the
|
||||
//! stroke's local width across direction `n` is `2·√(a²(u·n)² + b²(v·n)²)`.
|
||||
//!
|
||||
//! A Calligraphic brush with Pressure variation changes its nib along the stroke with the pen
|
||||
//! pressure recorded on it (`StrokeLayer::pressure`): the sweep is sampled densely and each
|
||||
//! sample takes the nib for the pressure there.
|
||||
//! A Calligraphic brush with Pressure, Tilt, Bearing or Rotation variation changes its nib along
|
||||
//! the stroke with what the pen recorded on it (`StrokeLayer::pressure`, `tilt`, `bearing` and
|
||||
//! `rotation`): the sweep is sampled densely and each sample takes the nib for the pen there.
|
||||
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Node, PressureProfile, StrokeLayer};
|
||||
use vectorcraft_doc::{Node, StrokeLayer};
|
||||
use vectorcraft_geom::{BezPath, PathData, Point, SubPath, Vec2};
|
||||
|
||||
use crate::track::{Rng, Track, normal, seed_of, tracks};
|
||||
use crate::{Bristle, BristleShape, Calligraphic, Variation, filled, tolerance};
|
||||
use crate::{Bristle, BristleShape, Calligraphic, PenAt, Variation, filled, tolerance};
|
||||
|
||||
/// The most pieces a varying nib cuts one segment of a subpath into, and about how many samples
|
||||
/// it takes along a whole subpath.
|
||||
@@ -127,18 +127,16 @@ fn randomized(c: &Calligraphic, rng: &mut Rng) -> [f64; 3] {
|
||||
[angle, round.clamp(1.0, 100.0), size.max(0.05)]
|
||||
}
|
||||
|
||||
/// The nib's angle, roundness and size at pen pressure `p` (0..1): each Pressure value goes from
|
||||
/// the brush's value less its variation (lightest) to the value plus the variation (heaviest),
|
||||
/// kept within its range; the others are `base`'s.
|
||||
fn pressured(c: &Calligraphic, base: [f64; 3], p: f64) -> [f64; 3] {
|
||||
/// The nib's angle, roundness and size where the pen recorded `pen`: each value on a mode that
|
||||
/// follows the pen goes from the brush's value less its variation (where the pen reads 0 for it)
|
||||
/// to the value plus the variation (where it reads 1), the angle turning round past ±180° and the
|
||||
/// others kept within their ranges; the other values are `base`'s.
|
||||
fn pressured(c: &Calligraphic, base: [f64; 3], pen: PenAt) -> [f64; 3] {
|
||||
let values = [c.angle, c.roundness, c.size];
|
||||
let mut out = base;
|
||||
for (i, (v, mode)) in out.iter_mut().zip(c.modes()).enumerate() {
|
||||
let (Some(&value), Some(&var), Some(&(lo, hi))) = (values.get(i), c.variation.get(i), Calligraphic::RANGES.get(i)) else { continue };
|
||||
if mode == Variation::Pressure {
|
||||
let x = value + var * (2.0 * p.clamp(0.0, 1.0) - 1.0);
|
||||
*v = if x.is_finite() { x.clamp(lo, hi) } else { value.clamp(lo, hi) };
|
||||
}
|
||||
let (Some(&value), Some(&var), Some(p)) = (values.get(i), c.variation.get(i), pen.control(mode)) else { continue };
|
||||
*v = Calligraphic::moved(i, value, var * (2.0 * p - 1.0));
|
||||
}
|
||||
let [angle, round, size] = out;
|
||||
[angle, round.clamp(1.0, 100.0), size.max(0.05)]
|
||||
@@ -147,14 +145,13 @@ fn pressured(c: &Calligraphic, base: [f64; 3], p: f64) -> [f64; 3] {
|
||||
pub(crate) fn calligraphic(c: &Calligraphic, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec<Node> {
|
||||
let mut rng = Rng::new(seed_of(bp, name));
|
||||
let base = randomized(c, &mut rng);
|
||||
let subs: Vec<SubPath> = if c.uses_pressure() {
|
||||
let pressure = stroke.pressure.as_ref();
|
||||
let subs: Vec<SubPath> = if c.uses_pen() {
|
||||
let nib = |f: f64| {
|
||||
let [angle, round, size] = pressured(c, base, pressure.map_or(PressureProfile::MID, |p| p.at(f)));
|
||||
let [angle, round, size] = pressured(c, base, PenAt::of(stroke, f));
|
||||
Nib::new(angle, round / 100.0, size * weight)
|
||||
};
|
||||
// Flattened for the largest nib the pressure gives.
|
||||
let size = pressured(c, base, 0.0)[2].max(pressured(c, base, 1.0)[2]) * weight;
|
||||
// Flattened for the largest nib the pen gives.
|
||||
let size = pressured(c, base, PenAt::uniform(0.0))[2].max(pressured(c, base, PenAt::uniform(1.0))[2]) * weight;
|
||||
tracks(bp, tolerance(size)).iter().flat_map(|t| sweep(t, &nib, Some((t.len() / MAX_STEPS).max(0.25)))).collect()
|
||||
} else {
|
||||
let [angle, round, size] = base;
|
||||
|
||||
@@ -13,15 +13,26 @@ fn luminance(c: &Color) -> f32 {
|
||||
}
|
||||
|
||||
fn map_color(c: &Color, mode: Colorization, key: &Color) -> Color {
|
||||
let lum = luminance(c);
|
||||
// Black ink alone is its own tint: its amount is the tint, not how light it displays (100% K
|
||||
// displays lighter than black).
|
||||
let light = match *c {
|
||||
Color::Cmyk { c, m, y, k } if c == 0.0 && m == 0.0 && y == 0.0 => 1.0 - k,
|
||||
_ => luminance(c),
|
||||
};
|
||||
// A process or gray stroke color's tints and shades stay in its model.
|
||||
let (white, black) = match key {
|
||||
Color::Cmyk { .. } => (Color::cmyk(0.0, 0.0, 0.0, 0.0), Color::cmyk(0.0, 0.0, 0.0, 1.0)),
|
||||
Color::Gray { .. } => (Color::gray(0.0), Color::gray(1.0)),
|
||||
_ => (Color::WHITE, Color::BLACK),
|
||||
};
|
||||
match mode {
|
||||
Colorization::None => *c,
|
||||
Colorization::Tints => key.lerp(&Color::WHITE, lum),
|
||||
Colorization::Tints => key.lerp_keep_model(&white, light),
|
||||
Colorization::TintsAndShades => {
|
||||
if lum < 0.5 {
|
||||
Color::BLACK.lerp(key, lum * 2.0)
|
||||
if light < 0.5 {
|
||||
key.lerp_keep_model(&black, 1.0 - light * 2.0)
|
||||
} else {
|
||||
key.lerp(&Color::WHITE, (lum - 0.5) * 2.0)
|
||||
key.lerp_keep_model(&white, (light - 0.5) * 2.0)
|
||||
}
|
||||
}
|
||||
Colorization::HueShift { key: art_key } => {
|
||||
@@ -132,9 +143,10 @@ pub fn tint_node(n: &mut Node, color: &Color, amount: f32) {
|
||||
}
|
||||
|
||||
/// The stain instance `inst` puts on its symbol's art: its visible fill colour and that fill's
|
||||
/// opacity (how far the art mixes towards it). `None` for an unstained instance.
|
||||
/// opacity (how far the art mixes towards it). `None` for an unstained instance, including one
|
||||
/// whose fill has an opacity of 0, so its art keeps its paints and their swatch links.
|
||||
pub fn stain(inst: &Node) -> Option<(Color, f32)> {
|
||||
let f = inst.appearance.fill().filter(|f| f.visible)?;
|
||||
let f = inst.appearance.fill().filter(|f| f.visible && f.opacity > 0.0)?;
|
||||
Some((f.paint.color()?, f.opacity))
|
||||
}
|
||||
|
||||
|
||||
@@ -159,6 +159,24 @@ impl Calligraphic {
|
||||
pub fn uses_pressure(&self) -> bool {
|
||||
self.modes().contains(&Variation::Pressure)
|
||||
}
|
||||
/// Does the pen (its pressure, tilt, bearing or rotation) change the nib?
|
||||
pub fn uses_pen(&self) -> bool {
|
||||
self.modes().iter().any(|m| m.follows_pen())
|
||||
}
|
||||
/// Value `i` (0 angle, 1 roundness, 2 size) moved by `by`: the angle turns round past ±180°,
|
||||
/// roundness and size stay within their [`Self::RANGES`]. A result that is not a number is
|
||||
/// `value`, kept within its range.
|
||||
pub fn moved(i: usize, value: f64, by: f64) -> f64 {
|
||||
let (lo, hi) = Self::RANGES.get(i).copied().unwrap_or((f64::MIN, f64::MAX));
|
||||
let x = value + by;
|
||||
if !x.is_finite() {
|
||||
value.clamp(lo, hi)
|
||||
} else if i == 0 {
|
||||
vectorcraft_geom::normalize_deg(x)
|
||||
} else {
|
||||
x.clamp(lo, hi)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a Calligraphic brush's angle, roundness or size varies (Brush Options). Saved by name: new
|
||||
@@ -174,16 +192,29 @@ pub enum Variation {
|
||||
/// From the value less the variation at the lightest pen pressure to the value plus the
|
||||
/// variation at the heaviest.
|
||||
Pressure,
|
||||
/// From the value less the variation with the pen lying flat to the value plus the variation
|
||||
/// with it upright.
|
||||
Tilt,
|
||||
/// The value plus the variation times the pen's bearing over 180°: the bearing is which way the
|
||||
/// pen leans, counter-clockwise on the page from leaning to the right (0°) round to ±180°.
|
||||
Bearing,
|
||||
/// The value plus the variation times the pen barrel's rotation over 180°, counter-clockwise
|
||||
/// from where the pen reports 0° round to ±180°.
|
||||
Rotation,
|
||||
}
|
||||
|
||||
impl Variation {
|
||||
pub const ALL: [Variation; 3] = [Variation::Fixed, Variation::Random, Variation::Pressure];
|
||||
pub const ALL: [Variation; 6] =
|
||||
[Variation::Fixed, Variation::Random, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation];
|
||||
/// The name brush definitions use.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Variation::Fixed => "fixed",
|
||||
Variation::Random => "random",
|
||||
Variation::Pressure => "pressure",
|
||||
Variation::Tilt => "tilt",
|
||||
Variation::Bearing => "bearing",
|
||||
Variation::Rotation => "rotation",
|
||||
}
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
@@ -191,11 +222,63 @@ impl Variation {
|
||||
Variation::Fixed => "Fixed",
|
||||
Variation::Random => "Random",
|
||||
Variation::Pressure => "Pressure",
|
||||
Variation::Tilt => "Tilt",
|
||||
Variation::Bearing => "Bearing",
|
||||
Variation::Rotation => "Rotation",
|
||||
}
|
||||
}
|
||||
pub fn parse(id: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|v| v.id() == id)
|
||||
}
|
||||
/// Does the value follow something the pen records along a stroke (Pressure, Tilt, Bearing,
|
||||
/// Rotation)?
|
||||
pub fn follows_pen(self) -> bool {
|
||||
matches!(self, Variation::Pressure | Variation::Tilt | Variation::Bearing | Variation::Rotation)
|
||||
}
|
||||
}
|
||||
|
||||
/// What the pen recorded at one point of a stroke, each as the 0..1 that [`Variation`]'s pen modes
|
||||
/// read: 0 gives the value less the variation (a Scatter brush's first value), 1 the value plus it
|
||||
/// (the second value), and ½ the value itself, as a stroke without that recording does.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct PenAt {
|
||||
/// The pressure, lightest 0.
|
||||
pressure: f64,
|
||||
/// 1 upright, 0 lying flat.
|
||||
tilt: f64,
|
||||
/// ½ plus the bearing over 360°.
|
||||
bearing: f64,
|
||||
/// ½ plus the counter-clockwise barrel rotation over 360°.
|
||||
rotation: f64,
|
||||
}
|
||||
|
||||
impl PenAt {
|
||||
/// Every input at `c`.
|
||||
pub(crate) fn uniform(c: f64) -> Self {
|
||||
Self { pressure: c, tilt: c, bearing: c, rotation: c }
|
||||
}
|
||||
/// What `stroke` recorded at `f` (the fraction of its path's length).
|
||||
pub(crate) fn of(stroke: &StrokeLayer, f: f64) -> Self {
|
||||
let mid = vectorcraft_doc::PressureProfile::MID;
|
||||
let turn = |p: Option<&vectorcraft_doc::AngleProfile>| 0.5 + p.map_or(0.0, |p| p.at(f)) / 360.0;
|
||||
Self {
|
||||
pressure: stroke.pressure.as_ref().map_or(mid, |p| p.at(f)),
|
||||
tilt: 1.0 - stroke.tilt.as_ref().map_or(mid, |p| p.at(f)),
|
||||
bearing: turn(stroke.bearing.as_ref()),
|
||||
rotation: turn(stroke.rotation.as_ref()),
|
||||
}
|
||||
}
|
||||
/// The 0..1 a value on `mode` takes, or `None` for a mode that doesn't follow the pen.
|
||||
pub(crate) fn control(&self, mode: Variation) -> Option<f64> {
|
||||
let c = match mode {
|
||||
Variation::Fixed | Variation::Random => return None,
|
||||
Variation::Pressure => self.pressure,
|
||||
Variation::Tilt => self.tilt,
|
||||
Variation::Bearing => self.bearing,
|
||||
Variation::Rotation => self.rotation,
|
||||
};
|
||||
Some(if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.5 })
|
||||
}
|
||||
}
|
||||
|
||||
/// Scatter brush: copies of the art along the path.
|
||||
@@ -216,8 +299,10 @@ pub struct Scatter {
|
||||
pub colorization: Colorization,
|
||||
/// How size, spacing, scatter and rotation vary between their two values: Fixed takes the
|
||||
/// first, Random any value between them, Pressure the first at the lightest pen pressure and
|
||||
/// the second at the heaviest. `None` (brushes saved before there were modes): Random where
|
||||
/// the two differ, else Fixed — see [`Scatter::modes`].
|
||||
/// the second at the heaviest, Tilt the first with the pen lying flat and the second upright,
|
||||
/// Bearing and Rotation the first at −180° and the second at 180° (half way at 0°). `None`
|
||||
/// (brushes saved before there were modes): Random where the two differ, else Fixed (see
|
||||
/// [`Scatter::modes`]).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub modes: Option<[Variation; 4]>,
|
||||
}
|
||||
@@ -390,6 +475,10 @@ pub struct PatternBrush {
|
||||
pub side_frame: Option<Rect>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub side_swatch: Option<String>,
|
||||
/// Art for the corners where the path turns towards the side tile's top (`-y`); `inner_corner`
|
||||
/// is the art for the corners where it turns the other way. Both are drawn as the corner that
|
||||
/// joins a side tile on its right to one below it, and each corner tile is turned so that
|
||||
/// those two arms meet the sides.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub outer_corner: Option<Node>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -696,10 +785,9 @@ pub fn unique_name(lib: &[Brush], base: &str) -> String {
|
||||
return base.to_string();
|
||||
}
|
||||
// At most `lib.len()` names are taken, so one of the first `lib.len() + 1` candidates is free.
|
||||
(2..=lib.len() + 2)
|
||||
.map(|i| format!("{base} {i}"))
|
||||
.find(|n| !lib.iter().any(|b| &b.name == n))
|
||||
.unwrap_or_else(|| format!("{base} {}", lib.len() + 2))
|
||||
// Each is looked up in a set: scanning the library per candidate is quadratic in its size.
|
||||
let taken: std::collections::HashSet<&str> = lib.iter().map(|b| b.name.as_str()).collect();
|
||||
(2..=lib.len() + 2).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n.as_str())).unwrap_or_else(|| format!("{base} {}", lib.len() + 2))
|
||||
}
|
||||
|
||||
// ---------- geometry ----------
|
||||
@@ -719,7 +807,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
|
||||
BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name),
|
||||
BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name),
|
||||
BrushKind::Art(a) => warp::art(a, bp, w, stroke.pressure.as_ref()),
|
||||
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke.pressure.as_ref(), &brush.name),
|
||||
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name),
|
||||
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
|
||||
};
|
||||
let colorization = brush.kind.colorization();
|
||||
@@ -764,9 +852,15 @@ fn draws_brushed(doc: &Document, def: Named<'_>, known: &mut Known) -> bool {
|
||||
};
|
||||
// Without recursion, each one looked at once: they may use one another without end.
|
||||
let (mut seen, mut stack) = (std::collections::HashSet::from([key.clone()]), art(def));
|
||||
// A brush name the library lacks draws a plain stroke ([`node_pieces`]), which runs no brush.
|
||||
let mut names: Option<std::collections::HashSet<String>> = None;
|
||||
let mut resolves = |n: &Node| {
|
||||
let names = names.get_or_insert_with(|| library(doc).into_iter().map(|b| b.name).collect());
|
||||
n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.visible && s.brush.as_ref().is_some_and(|b| names.contains(b))))
|
||||
};
|
||||
let mut answer = false;
|
||||
while let Some(n) = stack.pop() {
|
||||
if has_brush(n) {
|
||||
if has_brush(n) && resolves(n) {
|
||||
answer = true;
|
||||
break;
|
||||
}
|
||||
@@ -799,7 +893,16 @@ fn leave_out_brushed(doc: &Document, nodes: &mut Vec<Node>, known: &mut Known) {
|
||||
walk(doc, Arc::make_mut(c), known);
|
||||
}
|
||||
}
|
||||
if n.extras().mask.is_some()
|
||||
// A mask's art is drawn too. Its root is filtered like any other node: a symbol instance
|
||||
// there that draws a brushed stroke would run the brush again from inside the mask, so the
|
||||
// mask goes, as such an instance goes from the pieces and their children.
|
||||
let rejected_root = matches!(
|
||||
n.extras().mask.as_ref().map(|m| &m.art.kind),
|
||||
Some(NodeKind::SymbolInstance { symbol, .. }) if draws_brushed(doc, (false, symbol.as_str()), known)
|
||||
);
|
||||
if rejected_root {
|
||||
n.extras_mut().mask = None;
|
||||
} else if n.extras().mask.is_some()
|
||||
&& let Some(mask) = n.extras_mut().mask.as_mut()
|
||||
{
|
||||
walk(doc, Arc::make_mut(&mut mask.art), known);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, BezPath, Point, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, BezPath, Point, Rect, Vec2, shapes};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -299,6 +299,101 @@ fn pattern_places_corner_tiles() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A pattern brush whose corner tiles have a 4 × 4 pt frame and, as art, a 2 × 2 pt square in the
|
||||
/// top-left quarter of the frame. Corner art joins a side tile on its right to one below it, so
|
||||
/// that quarter is on the outside of the turn. `inner` and `outer` say which kinds of corner have
|
||||
/// art; `flips` are the brush's Flip Along and Flip Across.
|
||||
fn marked_corner_brush(inner: bool, outer: bool, (flip_along, flip_across): (bool, bool)) -> Brush {
|
||||
let marker =
|
||||
Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, -2.0, 2.0, 0.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let mut b = pattern_brush(PatternFit::Stretch, false);
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
let frame = Some(Rect::new(0.0, -2.0, 4.0, 2.0));
|
||||
if inner {
|
||||
(p.inner_corner, p.inner_corner_frame) = (Some(marker.clone()), frame);
|
||||
}
|
||||
if outer {
|
||||
(p.outer_corner, p.outer_corner_frame) = (Some(marker), frame);
|
||||
}
|
||||
(p.flip_along, p.flip_across) = (flip_along, flip_across);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Each combination of corner art (both kinds, inner only, outer only) and of the two flips.
|
||||
fn marked_corner_brushes() -> Vec<(String, Brush)> {
|
||||
let mut v = vec![];
|
||||
for (inner, outer) in [(true, true), (true, false), (false, true)] {
|
||||
for flips in [(false, false), (true, false), (false, true), (true, true)] {
|
||||
v.push((format!("inner {inner}, outer {outer}, flips {flips:?}"), marked_corner_brush(inner, outer, flips)));
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The bounds of the 2 × 2 pt corner markers among `out`, turned or not.
|
||||
fn marker_bounds(out: &[Node]) -> Vec<Rect> {
|
||||
out.iter().filter_map(Node::geometric_bounds).filter(|r| r.width() < 3.0 && r.height() < 3.0).collect()
|
||||
}
|
||||
|
||||
/// Corner tiles are square to the sides at a right angle and turn 90° with each turn of the path:
|
||||
/// on a square drawn either way round, each corner's marker fills the quarter of the band's corner
|
||||
/// outside the turn, with the brush flipped or not and with art for one kind of corner only
|
||||
/// (#6110).
|
||||
#[test]
|
||||
fn pattern_corner_tiles_are_square_to_the_sides() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let sq = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)).to_bezpath();
|
||||
let mut reversed = BezPath::new();
|
||||
reversed.move_to((0.0, 0.0));
|
||||
for (x, y) in [(0.0, 100.0), (100.0, 100.0), (100.0, 0.0)] {
|
||||
reversed.line_to((x, y));
|
||||
}
|
||||
reversed.close_path();
|
||||
// The square turns the same way at all four corners, and the reversed square the other way,
|
||||
// so one draws only inner corner tiles and the other only outer ones.
|
||||
for (name, brush) in marked_corner_brushes() {
|
||||
for path in [&sq, &reversed] {
|
||||
let out = stroke_pieces(&doc, &brush, path, &stroke(1.0));
|
||||
let marks = marker_bounds(&out);
|
||||
assert_eq!(marks.len(), 4, "{name}: one marker a corner");
|
||||
for (corner, outside) in SQUARE_CORNERS {
|
||||
let want = Rect::from_points(corner, outside);
|
||||
assert!(
|
||||
marks
|
||||
.iter()
|
||||
.any(|r| near(r.x0, want.x0, 1e-6) && near(r.y0, want.y0, 1e-6) && near(r.x1, want.x1, 1e-6) && near(r.y1, want.y1, 1e-6)),
|
||||
"{name}: the marker at {corner:?} fills {want:?}: {marks:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// At a corner that is not a right angle, a corner tile splits the difference between the two
|
||||
/// sides: its marker lies on the line that halves the angle, outside the turn, for sharp and
|
||||
/// shallow turns either way. Near a hairpin the marker moves smoothly towards the line the path
|
||||
/// arrives on.
|
||||
#[test]
|
||||
fn pattern_corner_tiles_sit_on_the_corners_diagonal() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
for (name, brush) in marked_corner_brushes() {
|
||||
for turn in [-179.9_f64, -170.0, -135.0, -60.0, -45.0, 45.0, 60.0, 135.0, 170.0, 179.9] {
|
||||
let (a, b) = (Vec2::new(1.0, 0.0), Vec2::new(turn.to_radians().cos(), turn.to_radians().sin()));
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((0.0, 0.0));
|
||||
bp.line_to((50.0, 0.0));
|
||||
bp.line_to(Point::new(50.0, 0.0) + b * 50.0);
|
||||
let out = stroke_pieces(&doc, &brush, &bp, &stroke(1.0));
|
||||
let marks = marker_bounds(&out);
|
||||
assert_eq!(marks.len(), 1, "{name}, {turn}°: one corner marker");
|
||||
let away = a - b;
|
||||
let want = Point::new(50.0, 0.0) + away / away.hypot() * 2.0_f64.sqrt();
|
||||
assert!(marks[0].center().distance(want) < 1e-6, "{name}, {turn}°: the marker is at {:?}, not {want:?}", marks[0].center());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The 10 × 4 pt side tile of [`pattern_brush`] with the given corner sources and no corner art.
|
||||
fn auto_corner_brush(outer: Option<CornerSource>, inner: Option<CornerSource>) -> Brush {
|
||||
let mut b = pattern_brush(PatternFit::Stretch, false);
|
||||
@@ -701,6 +796,55 @@ fn tints_colorization_uses_stroke_colour() {
|
||||
assert_eq!(white.appearance.fill_paint().color().unwrap().to_rgb(), [1.0, 1.0, 1.0]);
|
||||
}
|
||||
|
||||
/// Black ink alone is a tint by its amount: a process black stroke leaves it as it is, and another
|
||||
/// process stroke color takes that share of its inks. Tints of a process color stay process.
|
||||
#[test]
|
||||
fn tints_of_black_ink_are_its_amount_of_the_stroke_color() {
|
||||
let tinted = |art: Color, stroke: Color| {
|
||||
let mut n = rect_art(1.0, 1.0);
|
||||
n.appearance.set_fill(Paint::solid(art));
|
||||
colorize(&mut n, Colorization::Tints, &Paint::solid(stroke));
|
||||
n.appearance.fill_paint().color().unwrap()
|
||||
};
|
||||
let ink = Color::cmyk(0.0, 0.0, 0.0, 0.6);
|
||||
let close = |a: Color, b: Color| {
|
||||
let (Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) = (a, b) else { panic!("{a:?} {b:?}") };
|
||||
(c - c2).abs() < 1e-5 && (m - m2).abs() < 1e-5 && (y - y2).abs() < 1e-5 && (k - k2).abs() < 1e-5
|
||||
};
|
||||
assert!(close(tinted(ink, Color::cmyk(0.0, 0.0, 0.0, 1.0)), ink));
|
||||
assert!(close(tinted(ink, Color::cmyk(0.0, 1.0, 1.0, 0.0)), Color::cmyk(0.0, 0.6, 0.6, 0.0)));
|
||||
let [r, g, b] = tinted(ink, Color::rgb(1.0, 0.0, 0.0)).to_rgb();
|
||||
assert!((r - 1.0).abs() < 1e-5 && (g - 0.4).abs() < 1e-5 && (b - 0.4).abs() < 1e-5, "{r} {g} {b}");
|
||||
let Color::Gray { k } = tinted(ink, Color::gray(0.5)) else { panic!("tints of a gray stroke color stay gray") };
|
||||
assert!((k - 0.3).abs() < 1e-5, "{k}");
|
||||
}
|
||||
|
||||
/// Under Tints and Shades black ink stays black, however light 100% K displays, and a band of black
|
||||
/// ink is its amount: K 0.5 is the stroke color. A process or gray stroke color stays in its model.
|
||||
#[test]
|
||||
fn tints_and_shades_of_black_ink_go_by_its_amount() {
|
||||
let mapped = |k: f32, stroke: Color| {
|
||||
let mut n = rect_art(1.0, 1.0);
|
||||
n.appearance.set_fill(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, k)));
|
||||
colorize(&mut n, Colorization::TintsAndShades, &Paint::solid(stroke));
|
||||
n.appearance.fill_paint().color().unwrap()
|
||||
};
|
||||
let close = |a: [f32; 4], b: [f32; 4]| a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-5);
|
||||
let inks = |c: Color| {
|
||||
let Color::Cmyk { c, m, y, k } = c else { panic!("a process color: {c:?}") };
|
||||
[c, m, y, k]
|
||||
};
|
||||
let orange = Color::cmyk(0.0, 0.6, 1.0, 0.0);
|
||||
assert!(close(inks(mapped(1.0, orange)), [0.0, 0.0, 0.0, 1.0]), "black stays black");
|
||||
assert!(close(inks(mapped(0.5, orange)), [0.0, 0.6, 1.0, 0.0]), "the stroke color");
|
||||
assert!(close(inks(mapped(0.25, orange)), [0.0, 0.3, 0.5, 0.0]), "a tint");
|
||||
assert!(close(inks(mapped(0.75, orange)), [0.0, 0.3, 0.5, 0.5]), "a shade");
|
||||
let Color::Gray { k } = mapped(0.75, Color::gray(0.4)) else { panic!("a gray stroke color stays gray") };
|
||||
assert!((k - 0.7).abs() < 1e-5, "{k}");
|
||||
let [r, g, b] = mapped(1.0, Color::rgb(1.0, 0.0, 0.0)).to_rgb();
|
||||
assert!(r < 1e-5 && g < 1e-5 && b < 1e-5, "black stays black: {r} {g} {b}");
|
||||
}
|
||||
|
||||
/// Point type at (0, 0) whose characters are painted `fill` and `stroke` (1 pt wide).
|
||||
fn type_art(fill: Paint, stroke: Paint) -> Node {
|
||||
use vectorcraft_doc::{CharStyle, TextObject};
|
||||
@@ -764,6 +908,26 @@ fn stain_mixes_type_strokes_too() {
|
||||
assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]);
|
||||
}
|
||||
|
||||
/// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its
|
||||
/// swatch links.
|
||||
#[test]
|
||||
fn a_fill_with_no_opacity_leaves_the_symbol_art_linked() {
|
||||
let spot = Paint::Solid { color: Color::cmyk(1.0, 0.7, 0.0, 0.4), swatch: Some("Spot".into()), tint: 1.0 };
|
||||
let art = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(spot.clone(), Paint::None, 0.0));
|
||||
let mut inst = Node::new(NodeId(2), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY });
|
||||
inst.appearance = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into();
|
||||
if let Some(f) = inst.appearance.fill_mut() {
|
||||
f.opacity = 0.0;
|
||||
}
|
||||
assert_eq!(stain(&inst), None);
|
||||
assert_eq!(instance_art(&art, &inst).appearance.fill_paint(), spot);
|
||||
// Any opacity above 0 still stains.
|
||||
if let Some(f) = inst.appearance.fill_mut() {
|
||||
f.opacity = 0.01;
|
||||
}
|
||||
assert_ne!(instance_art(&art, &inst).appearance.fill_paint(), spot);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_defaults_store_and_find() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
@@ -889,6 +1053,163 @@ fn pressure_varies_angle_and_roundness() {
|
||||
};
|
||||
assert!(near(wide(0.0), 0.1, 0.05), "{}", wide(0.0));
|
||||
assert!(near(wide(1.0), 10.0, 0.05), "{}", wide(1.0));
|
||||
// The angle turns on past 180°: 170 + 40 is 210°, the nib at 30° (not stopped at 180°).
|
||||
let turned = Calligraphic { angle: 170.0, roundness: 10.0, variation: [40.0, 0.0, 0.0], ..c([Pressure, Fixed, Fixed]) };
|
||||
let expected = 2.0 * (25.0 * 0.25 + 0.25 * 0.75f64).sqrt();
|
||||
let h = draw(turned, 1.0);
|
||||
assert!(near(h, expected, 0.05), "{h} vs {expected}");
|
||||
}
|
||||
|
||||
/// A stroke that recorded the pen's tilt (`tilt`: 0 upright to 1 flat), bearing and barrel
|
||||
/// rotation (degrees counter-clockwise), each the same all along it where given.
|
||||
fn posed(tilt: Option<f64>, bearing: Option<f64>, rotation: Option<f64>) -> StrokeLayer {
|
||||
let flat = |v: f64| vec![(0.0, v), (1.0, v)];
|
||||
StrokeLayer {
|
||||
tilt: tilt.map(|t| vectorcraft_doc::PressureProfile { points: flat(t) }),
|
||||
bearing: bearing.map(|b| vectorcraft_doc::AngleProfile { points: flat(b) }),
|
||||
rotation: rotation.map(|r| vectorcraft_doc::AngleProfile { points: flat(r) }),
|
||||
..stroke(1.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// #764: with Roundness on Tilt the nib goes from roundness − variation with the pen lying flat to
|
||||
/// roundness + variation with it upright, along the stroke as the pen leaned.
|
||||
#[test]
|
||||
fn tilt_maps_to_roundness_along_the_stroke() {
|
||||
let c = Calligraphic {
|
||||
roundness: 50.0,
|
||||
size: 10.0,
|
||||
variation: [0.0, 50.0, 0.0],
|
||||
modes: Some([Variation::Fixed, Variation::Tilt, Variation::Fixed]),
|
||||
..Default::default()
|
||||
};
|
||||
let b = Brush { name: "t".into(), kind: BrushKind::Calligraphic(c) };
|
||||
let upright_to_flat = StrokeLayer { tilt: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) };
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 100.0, 0.0), &upright_to_flat);
|
||||
// Upright: round (half 5); half way: roundness 50 (half 2.5); flat: a hairline.
|
||||
assert!(near(half_width(&out, 0.5, 1.5), 5.0, 0.1), "{}", half_width(&out, 0.5, 1.5));
|
||||
assert!(near(half_width(&out, 49.5, 50.5), 2.5, 0.1), "{}", half_width(&out, 49.5, 50.5));
|
||||
assert!(half_width(&out, 98.5, 99.5) < 0.2, "{}", half_width(&out, 98.5, 99.5));
|
||||
}
|
||||
|
||||
/// #764: with Angle on Bearing or on Rotation and a variation of 180°, the nib turns with the way
|
||||
/// the pen leans or with its barrel.
|
||||
#[test]
|
||||
fn bearing_and_rotation_turn_the_nib() {
|
||||
let horizontal = line(0.0, 0.0, 100.0, 0.0);
|
||||
let height = |mode: Variation, st: &StrokeLayer| {
|
||||
let c = Calligraphic {
|
||||
roundness: 10.0,
|
||||
size: 10.0,
|
||||
variation: [180.0, 0.0, 0.0],
|
||||
modes: Some([mode, Variation::Fixed, Variation::Fixed]),
|
||||
..Default::default()
|
||||
};
|
||||
let b = Brush { name: "b".into(), kind: BrushKind::Calligraphic(c) };
|
||||
bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &horizontal, st)).height()
|
||||
};
|
||||
// Leaning right (0°): the nib lies along the stroke (1 pt across); leaning up the page (90°)
|
||||
// or down it (−90°), the nib stands across it (10 pt).
|
||||
assert!(near(height(Variation::Bearing, &posed(Some(0.5), Some(0.0), None)), 1.0, 0.05));
|
||||
assert!(near(height(Variation::Bearing, &posed(Some(0.5), Some(90.0), None)), 10.0, 0.05));
|
||||
assert!(near(height(Variation::Bearing, &posed(Some(0.5), Some(-90.0), None)), 10.0, 0.05));
|
||||
// The barrel turned a quarter turn stands it across the stroke too.
|
||||
assert!(near(height(Variation::Rotation, &posed(None, None, Some(0.0))), 1.0, 0.05));
|
||||
assert!(near(height(Variation::Rotation, &posed(None, None, Some(90.0))), 10.0, 0.05));
|
||||
// Each reads only its own recording.
|
||||
assert!(near(height(Variation::Rotation, &posed(None, Some(90.0), None)), 1.0, 0.05));
|
||||
assert!(near(height(Variation::Bearing, &posed(None, None, Some(90.0))), 1.0, 0.05));
|
||||
}
|
||||
|
||||
/// A stroke without the pen's tilt, bearing or rotation (a mouse, a pen without that input, or a
|
||||
/// path the brush was applied to) draws Tilt, Bearing and Rotation values at the brush's own value.
|
||||
#[test]
|
||||
fn pen_modes_without_a_recording_draw_the_value_itself() {
|
||||
let horizontal = line(0.0, 0.0, 100.0, 0.0);
|
||||
for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation] {
|
||||
let c = Calligraphic { angle: 90.0, roundness: 50.0, size: 10.0, variation: [90.0, 50.0, 6.0], modes: Some([mode; 3]) };
|
||||
let b = Brush { name: "n".into(), kind: BrushKind::Calligraphic(c) };
|
||||
let h = bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &horizontal, &stroke(1.0))).height();
|
||||
assert!(near(h, 10.0, 0.05), "{mode:?}: {h}");
|
||||
let sc = Scatter {
|
||||
size: (50.0, 300.0),
|
||||
modes: Some([mode, Variation::Fixed, Variation::Fixed, Variation::Fixed]),
|
||||
..scatter(&scatter_brush(100.0))
|
||||
};
|
||||
let s = Brush { name: "s".into(), kind: BrushKind::Scatter(sc) };
|
||||
let heights: Vec<f64> =
|
||||
stroke_pieces(&Document::new(1.0, 1.0), &s, &horizontal, &stroke(1.0)).iter().map(|n| n.geometric_bounds().unwrap().height()).collect();
|
||||
assert!(!heights.is_empty() && heights.iter().all(|h| near(*h, 7.0, 1e-6)), "{mode:?}: {heights:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A mouse stroke records no pressure, tilt, bearing or rotation. On it, a brush whose values are
|
||||
/// on Tilt, Bearing or Rotation draws exactly what the same brush on Pressure draws, the output a
|
||||
/// mouse stroke gave before these modes existed.
|
||||
#[test]
|
||||
fn a_mouse_stroke_draws_pen_modes_as_pressure_did() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let wavy = {
|
||||
let mut bp = line(0.0, 0.0, 60.0, 0.0);
|
||||
bp.curve_to((90.0, 0.0), (90.0, 40.0), (120.0, 40.0));
|
||||
bp
|
||||
};
|
||||
let mouse = stroke(1.0);
|
||||
assert!(mouse.pressure.is_none() && mouse.tilt.is_none() && mouse.bearing.is_none() && mouse.rotation.is_none());
|
||||
let calli = |mode: Variation| {
|
||||
let c = Calligraphic { angle: 30.0, roundness: 40.0, size: 8.0, variation: [60.0, 30.0, 4.0], modes: Some([mode; 3]) };
|
||||
stroke_pieces(&doc, &Brush { name: "c".into(), kind: BrushKind::Calligraphic(c) }, &wavy, &mouse)
|
||||
};
|
||||
let scattered = |mode: Variation| {
|
||||
let sc = Scatter {
|
||||
size: (50.0, 300.0),
|
||||
spacing: (80.0, 160.0),
|
||||
scatter: (-40.0, 40.0),
|
||||
rotation: (-90.0, 90.0),
|
||||
modes: Some([mode; 4]),
|
||||
..scatter(&scatter_brush(100.0))
|
||||
};
|
||||
stroke_pieces(&doc, &Brush { name: "s".into(), kind: BrushKind::Scatter(sc) }, &wavy, &mouse)
|
||||
};
|
||||
let (calli_before, scatter_before) = (calli(Variation::Pressure), scattered(Variation::Pressure));
|
||||
assert!(!calli_before.is_empty() && !scatter_before.is_empty());
|
||||
for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation] {
|
||||
assert_eq!(calli(mode), calli_before, "{mode:?}");
|
||||
assert_eq!(scattered(mode), scatter_before, "{mode:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The scatter brush of `b`.
|
||||
fn scatter(b: &Brush) -> Scatter {
|
||||
let BrushKind::Scatter(sc) = &b.kind else { panic!("not a scatter brush") };
|
||||
sc.clone()
|
||||
}
|
||||
|
||||
/// #764: Scatter values on Tilt go from the first value with the pen lying flat to the second
|
||||
/// upright; on Bearing, from the first at −180° to the second at 180°.
|
||||
#[test]
|
||||
fn scatter_values_follow_tilt_and_bearing() {
|
||||
let bp = line(0.0, 0.0, 400.0, 0.0);
|
||||
let boxes = |b: &Brush, st: &StrokeLayer| -> Vec<Rect> {
|
||||
stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st).iter().map(|n| n.geometric_bounds().unwrap()).collect()
|
||||
};
|
||||
// Size on Tilt, 50 % to 300 %: upright at the start (12 pt tall), flat at the end (2 pt).
|
||||
let upright_to_flat = StrokeLayer { tilt: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) };
|
||||
let h: Vec<f64> = boxes(&sized_scatter(50.0, 300.0, Variation::Tilt), &upright_to_flat).iter().map(Rect::height).collect();
|
||||
assert!(near(h[0], 12.0, 0.2) && h[h.len() - 1] < 3.0, "{h:?}");
|
||||
assert!(h.windows(2).all(|w| w[1] <= w[0] + 1e-9), "shrinks as the pen tips over: {h:?}");
|
||||
// Rotation on Bearing, −180° to 180°: the copies turn with the bearing, a quarter turn
|
||||
// standing the 10 × 4 pt art on end.
|
||||
let sc = Scatter {
|
||||
rotation: (-180.0, 180.0),
|
||||
modes: Some([Variation::Fixed, Variation::Fixed, Variation::Fixed, Variation::Bearing]),
|
||||
..scatter(&scatter_brush(100.0))
|
||||
};
|
||||
let turning = Brush { name: "r".into(), kind: BrushKind::Scatter(sc) };
|
||||
for (bearing, (w, h)) in [(0.0, (10.0, 4.0)), (90.0, (4.0, 10.0)), (-90.0, (4.0, 10.0))] {
|
||||
let b = boxes(&turning, &posed(Some(0.5), Some(bearing), None));
|
||||
assert!(!b.is_empty() && b.iter().all(|r| near(r.width(), w, 1e-6) && near(r.height(), h, 1e-6)), "{bearing}: {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Brushes saved before the variation modes keep their look: a variation means Random, none
|
||||
@@ -920,7 +1241,7 @@ fn brushes_without_modes_vary_randomly_as_before() {
|
||||
stroke_pieces(&Document::new(1.0, 1.0), &old, &bp, &pressed(vec![(0.0, 0.0), (1.0, 1.0)]))
|
||||
);
|
||||
// Modes are saved by name.
|
||||
assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(["fixed", "random", "pressure"]));
|
||||
assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation"]));
|
||||
assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v)));
|
||||
}
|
||||
|
||||
@@ -1144,6 +1465,7 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() {
|
||||
};
|
||||
let art = Node::group(NodeId(0), [instance("plain"), instance("brushed"), painted("plain"), painted("brushed")].map(std::sync::Arc::new).into());
|
||||
let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) };
|
||||
store(&mut doc, std::slice::from_ref(&b));
|
||||
let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 100.0, 0.0), &stroke(1.0));
|
||||
assert!(!out.is_empty());
|
||||
for piece in &out {
|
||||
@@ -1159,6 +1481,46 @@ fn pieces_leave_out_what_draws_a_brushed_stroke_by_name() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A symbol instance at the root of an opacity mask is filtered like one among the children: when
|
||||
/// its symbol draws a brushed stroke the mask goes (it would run the brush again from inside the
|
||||
/// mask, without end), and a mask whose root symbol is plain stays.
|
||||
#[test]
|
||||
fn pieces_leave_out_a_mask_whose_root_draws_a_brushed_stroke() {
|
||||
use vectorcraft_doc::{OpacityMask, Symbol};
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let mut brushed = rect_art(10.0, 4.0);
|
||||
brushed.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("s".into()), ..stroke(1.0) }));
|
||||
// A brush the library lacks draws a plain stroke: its mask stays.
|
||||
let mut unresolved = rect_art(10.0, 4.0);
|
||||
unresolved.appearance.items.push(vectorcraft_doc::AppearanceItem::Stroke(StrokeLayer { brush: Some("missing".into()), ..stroke(1.0) }));
|
||||
for (name, art) in [("plain", rect_art(10.0, 4.0)), ("brushed", brushed), ("unresolved", unresolved)] {
|
||||
doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: std::sync::Arc::new(art) });
|
||||
}
|
||||
let instance = |symbol: &str| Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
let masked = |symbol: &str| {
|
||||
let mut n = rect_art(10.0, 4.0);
|
||||
n.extras_mut().mask = Some(Box::new(OpacityMask::new(instance(symbol), true)));
|
||||
n
|
||||
};
|
||||
let art = Node::group(NodeId(0), [masked("plain"), masked("brushed"), masked("unresolved")].map(std::sync::Arc::new).into());
|
||||
let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) };
|
||||
store(&mut doc, std::slice::from_ref(&b));
|
||||
let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 100.0, 0.0), &stroke(1.0));
|
||||
assert!(!out.is_empty());
|
||||
for piece in &out {
|
||||
let roots: Vec<Option<&str>> = piece
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|c| match c.extras().mask.as_ref().map(|m| &m.art.kind) {
|
||||
Some(NodeKind::SymbolInstance { symbol, .. }) => Some(symbol.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(roots, [Some("plain"), None, Some("unresolved")], "the plain and unresolved masks stay and the brushed one goes");
|
||||
}
|
||||
}
|
||||
|
||||
/// Anchors a brushed stroke emitted, which is what the output budget counts.
|
||||
fn anchors(nodes: &[Node]) -> usize {
|
||||
nodes
|
||||
|
||||
@@ -236,7 +236,8 @@ pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
|
||||
return out;
|
||||
}
|
||||
let mut els = vec![];
|
||||
kurbo::flatten(bp.iter(), tol.max(1e-4), |el| {
|
||||
// Guarded: kurbo works out every subdivision of a curve even when the callback drops them.
|
||||
vectorcraft_geom::flatten(bp.iter(), tol.max(1e-4), |el| {
|
||||
if els.len() < MAX_FLATTENED {
|
||||
els.push(el);
|
||||
}
|
||||
|
||||
@@ -8,11 +8,11 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::ParamCurveNearest;
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, PressureProfile};
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, PressureProfile, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, BezPath, CubicBez, ParamCurve, PathData, PathEl, Point, Rect, SubPath, Vec2};
|
||||
|
||||
use crate::track::{Rng, Track, normal, seed_of, tracks};
|
||||
use crate::{ArtBrush, ArtScale, CornerSource, Direction, PatternBrush, PatternFit, Scatter, Variation, tolerance};
|
||||
use crate::{ArtBrush, ArtScale, CornerSource, Direction, PatternBrush, PatternFit, PenAt, Scatter, Variation, tolerance};
|
||||
|
||||
/// Longest mapped segment (points in document space).
|
||||
const MAX_SEG: f64 = 1.5;
|
||||
@@ -103,7 +103,7 @@ fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
|
||||
let mut bp = BezPath::new();
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
let mut pts = vec![];
|
||||
kurbo::flatten(bp.iter(), flat_tol.max(1e-4), |e| {
|
||||
vectorcraft_geom::flatten(bp.iter(), flat_tol.max(1e-4), |e| {
|
||||
if let PathEl::MoveTo(q) | PathEl::LineTo(q) = e {
|
||||
pts.push(q);
|
||||
}
|
||||
@@ -536,18 +536,19 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, pressure: Option<&Pre
|
||||
}
|
||||
|
||||
/// One of a scatter brush's values for the next copy: Fixed takes the first of `(a, b)`, Random a
|
||||
/// value between them, Pressure the first at pen pressure 0 and the second at 1. Every value
|
||||
/// draws, so a copy's random values stay the same whatever the other modes.
|
||||
fn vary(rng: &mut Rng, (a, b): (f64, f64), mode: Variation, pressure: f64) -> f64 {
|
||||
/// value between them, and a mode that follows the pen the first where `pen` reads 0 for it and
|
||||
/// the second where it reads 1. Every value draws, so a copy's random values stay the same
|
||||
/// whatever the other modes.
|
||||
fn vary(rng: &mut Rng, (a, b): (f64, f64), mode: Variation, pen: PenAt) -> f64 {
|
||||
let r = rng.range(a, b);
|
||||
match mode {
|
||||
Variation::Fixed => a,
|
||||
Variation::Random => r,
|
||||
Variation::Pressure => a + (b - a) * pressure.clamp(0.0, 1.0),
|
||||
match pen.control(mode) {
|
||||
Some(c) => a + (b - a) * c,
|
||||
None if mode == Variation::Random => r,
|
||||
None => a,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, pressure: Option<&PressureProfile>, name: &str) -> Vec<Node> {
|
||||
pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec<Node> {
|
||||
let Some(b) = sc.art.geometric_bounds() else { return vec![] };
|
||||
let (aw, ah) = (b.width().max(1e-3), b.height().max(1e-3));
|
||||
let mut rng = Rng::new(seed_of(bp, name));
|
||||
@@ -558,8 +559,8 @@ pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, pressure: Option<
|
||||
break;
|
||||
}
|
||||
let l = t.len();
|
||||
// The pen pressure at arc length `at` (half way without a recorded one).
|
||||
let pressure_at = |at: f64| pressure.map_or(PressureProfile::MID, |p| p.at(if l > 1e-9 { at / l } else { 0.0 }));
|
||||
// What the pen recorded at arc length `at` (the values themselves without a recording).
|
||||
let pen_at = |at: f64| PenAt::of(stroke, if l > 1e-9 { at / l } else { 0.0 });
|
||||
let mut s: Option<f64> = None;
|
||||
let mut guard = 0;
|
||||
loop {
|
||||
@@ -567,8 +568,8 @@ pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, pressure: Option<
|
||||
if guard > 20000 {
|
||||
break;
|
||||
}
|
||||
// Size and spacing place the next copy, so they take the pressure at the last one.
|
||||
let p = pressure_at(s.unwrap_or(0.0));
|
||||
// Size and spacing place the next copy, so they take the pen at the last one.
|
||||
let p = pen_at(s.unwrap_or(0.0));
|
||||
let size = vary(&mut rng, sc.size, size_mode, p).max(1.0) / 100.0 * weight;
|
||||
let spacing = vary(&mut rng, sc.spacing, spacing_mode, p).max(1.0) / 100.0;
|
||||
let step = aw * size * spacing;
|
||||
@@ -580,7 +581,7 @@ pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, pressure: Option<
|
||||
break;
|
||||
}
|
||||
s = Some(pos);
|
||||
let p = pressure_at(pos);
|
||||
let p = pen_at(pos);
|
||||
let off = vary(&mut rng, sc.scatter, scatter_mode, p) / 100.0 * ah * size;
|
||||
let rot = vary(&mut rng, sc.rotation, rotation_mode, p).to_radians();
|
||||
let (p, tg) = t.frame(pos);
|
||||
@@ -878,12 +879,16 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
};
|
||||
trims.push(None);
|
||||
corner_half = corner_half.max(bb.width() * k / 2.0);
|
||||
let bis = a + b;
|
||||
let bis = if bis.hypot() < 1e-9 { a } else { bis / bis.hypot() };
|
||||
let xf = Affine::translate(t.verts[i].to_vec2())
|
||||
* Affine::rotate(bis.y.atan2(bis.x))
|
||||
* Affine::scale(k)
|
||||
* Affine::translate(-bb.center().to_vec2());
|
||||
// Inner and outer corner art is the corner that joins a side tile on its right to one
|
||||
// below it, so its arms point along +x and +y (as the flips leave them). The tile is
|
||||
// turned so that the line halving its arms lies on the line halving the sides at the
|
||||
// corner, back along the incoming side and on along the outgoing one: at a right angle
|
||||
// the arms meet the side tiles, and at other angles the difference is split between
|
||||
// the two sides (#6110).
|
||||
let arms = Vec2::new(if pb.flip_along { -1.0 } else { 1.0 }, if pb.flip_across { -1.0 } else { 1.0 });
|
||||
let sides = b - a;
|
||||
let angle = sides.y.atan2(sides.x) - arms.y.atan2(arms.x);
|
||||
let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(k) * Affine::translate(-bb.center().to_vec2());
|
||||
let mut n = art.clone();
|
||||
n.transform(xf, true);
|
||||
out.take(Some(n));
|
||||
|
||||
@@ -23,10 +23,19 @@ const PT_PER_MM: f64 = 72.0 / 25.4;
|
||||
const THINNEST: f64 = 0.25;
|
||||
/// The most objects an import makes.
|
||||
const MAX_NODES: usize = 2_000_000;
|
||||
/// The most block visits (one per insert copy) an import makes, whatever they produce.
|
||||
const MAX_VISITS: usize = 10_000_000;
|
||||
/// The most block work an import does, whatever it produces: one per insert copy drawn, and one
|
||||
/// per item of the block looked at for it (art on hidden layers too).
|
||||
const MAX_VISITS: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 };
|
||||
/// The most path elements an import makes (blocks drawn as art are copied for every placement).
|
||||
const MAX_ELEMENTS: usize = if cfg!(test) { 1_000_000 } else { 4_000_000 };
|
||||
/// The most dash lengths an import keeps (every dashed path holds its own copy of its pattern).
|
||||
const MAX_DASH_VALUES: usize = if cfg!(test) { 1_000 } else { 4_000_000 };
|
||||
/// The most bytes of text, font names and symbol names an import copies into objects (a block's
|
||||
/// text and name are copied for every placement).
|
||||
const MAX_TEXT_BYTES: usize = if cfg!(test) { 64 << 10 } else { 64 << 20 };
|
||||
/// The longest font family a text style may name; a longer one is not a font, and is set in the
|
||||
/// default.
|
||||
const MAX_FAMILY_BYTES: usize = 256;
|
||||
/// How far from the origin art may lie (points): the canvas.
|
||||
pub(crate) const MAX_EXTENT: f64 = 4.0e6;
|
||||
|
||||
@@ -34,6 +43,9 @@ const NESTED: &str = "blocks nested more than 8 deep, or inside themselves, are
|
||||
const XREFS: &str = "blocks referencing other drawings (external references) are left out";
|
||||
const TOO_MANY: &str = "the drawing has more than 2,000,000 objects: the rest are left out";
|
||||
const TOO_MANY_POINTS: &str = "the drawing has more than 4,000,000 path points: the rest are left out";
|
||||
const TOO_MUCH_BLOCK_WORK: &str = "the drawing's blocks take too much work to place: the rest are left out";
|
||||
const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid";
|
||||
const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out";
|
||||
|
||||
/// What a block's art takes from the insert that places it: its colour, lineweight, linetype
|
||||
/// and opacity where the art says "by block", and its layer for art on layer 0.
|
||||
@@ -71,6 +83,9 @@ pub(crate) struct Build<'d, 'a> {
|
||||
visits: usize,
|
||||
/// Path elements made so far.
|
||||
elements: usize,
|
||||
/// Dash lengths and text bytes kept so far.
|
||||
dash_values: usize,
|
||||
text_bytes: usize,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -128,6 +143,8 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
nodes: 0,
|
||||
visits: 0,
|
||||
elements: 0,
|
||||
dash_values: 0,
|
||||
text_bytes: 0,
|
||||
warnings: vec![],
|
||||
}
|
||||
}
|
||||
@@ -138,6 +155,20 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Take `bytes` of text from [`MAX_TEXT_BYTES`]; false (with a warning) when they don't fit.
|
||||
fn charge_text(&mut self, bytes: usize) -> bool {
|
||||
match self.text_bytes.checked_add(bytes).filter(|t| *t <= MAX_TEXT_BYTES) {
|
||||
Some(t) => {
|
||||
self.text_bytes = t;
|
||||
true
|
||||
}
|
||||
None => {
|
||||
self.warn(TOO_MUCH_TEXT);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Import `layout`; `natural` and `ratio` are points per drawing unit in the drawing's own
|
||||
/// unit and at the scale asked for (fitting computes its own).
|
||||
pub fn run(mut self, layout: &LayoutDef, natural: f64, ratio: f64) -> Result<(Document, Vec<String>), String> {
|
||||
@@ -469,6 +500,9 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
super::curve::bounds(&bp)?;
|
||||
let paint = Paint::solid(rgb_color(self.rgb(p, inh)));
|
||||
let scale = map.determinant().abs().sqrt();
|
||||
let path = PathData::from_bezpath(&bp);
|
||||
// A compound path's loops each keep a copy of its appearance, beside its own.
|
||||
let copies = if path.subpaths.len() > 1 { path.subpaths.len() + 1 } else { 1 };
|
||||
let appearance = if fill {
|
||||
Appearance::basic(paint, Paint::None, 0.0)
|
||||
} else {
|
||||
@@ -484,15 +518,20 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
|
||||
&& let Some((dash, dots)) = self.dash(&self.linetype(p, inh), p, scale)
|
||||
{
|
||||
s.dash = Some(dash);
|
||||
if dots {
|
||||
s.cap = LineCap::Round;
|
||||
match dash.pattern.len().checked_mul(copies).and_then(|v| self.dash_values.checked_add(v)).filter(|n| *n <= MAX_DASH_VALUES) {
|
||||
Some(n) => {
|
||||
self.dash_values = n;
|
||||
s.dash = Some(dash);
|
||||
if dots {
|
||||
s.cap = LineCap::Round;
|
||||
}
|
||||
}
|
||||
None => self.warn(TOO_MANY_DASHES),
|
||||
}
|
||||
}
|
||||
ap
|
||||
};
|
||||
let rule = if fill { FillRule::EvenOdd } else { FillRule::NonZero };
|
||||
let path = PathData::from_bezpath(&bp);
|
||||
let kind = |path: PathData| NodeKind::Path { path, rule, live: None, clipping: false, guide: false };
|
||||
let mut n = if path.subpaths.len() > 1 {
|
||||
// Several loops (a hatch with islands) paint as one compound path. Each loop is an
|
||||
@@ -527,10 +566,15 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
if !(s > 1e-12 && s.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let family = t.family.clone().or_else(|| self.d.styles.get(&t.style).filter(|f| !f.is_empty()).cloned());
|
||||
let d = self.d;
|
||||
let family = t.family.as_deref().or_else(|| d.styles.get(&t.style).map(String::as_str).filter(|f| !f.is_empty()));
|
||||
let family = family.filter(|f| f.len() <= MAX_FAMILY_BYTES);
|
||||
if !self.charge_text(t.text.len().saturating_add(family.map_or(0, str::len))) {
|
||||
return None;
|
||||
}
|
||||
let default = CharStyle::default();
|
||||
let style = CharStyle {
|
||||
font_family: family.unwrap_or(default.font_family.clone()),
|
||||
font_family: family.map_or_else(|| default.font_family.clone(), str::to_string),
|
||||
size: t.height / CAP_HEIGHT * s,
|
||||
h_scale: t.width * 100.0,
|
||||
leading: t.leading.map(|l| l * s),
|
||||
@@ -558,6 +602,13 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
for cell in &ins.cells {
|
||||
let node = match &symbol {
|
||||
Some(name) => {
|
||||
if self.nodes >= MAX_NODES {
|
||||
self.warn(TOO_MANY);
|
||||
break;
|
||||
}
|
||||
if !self.charge_text(name.len()) {
|
||||
break;
|
||||
}
|
||||
let xf = map * *cell * self.symbol_map.inverse();
|
||||
self.nodes += 1;
|
||||
Some(Node::new(self.doc.alloc_id(), NodeKind::SymbolInstance { symbol: name.clone(), xf }))
|
||||
@@ -581,14 +632,19 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
|
||||
/// The art of block `name` drawn by `map`, as one object.
|
||||
fn art(&mut self, name: &str, map: Affine, inh: &Inherit, depth: u32) -> Option<Node> {
|
||||
self.visits += 1;
|
||||
if self.visits > MAX_VISITS {
|
||||
if self.visits == MAX_VISITS + 1 {
|
||||
self.warn(TOO_MANY);
|
||||
}
|
||||
if self.visits >= MAX_VISITS {
|
||||
self.warn(TOO_MUCH_BLOCK_WORK);
|
||||
return None;
|
||||
}
|
||||
let items = self.block(name)?;
|
||||
let items = self.block(name);
|
||||
// Each placement looks at every item of the block, drawn or not (art on a hidden layer
|
||||
// makes nothing, so the node budget doesn't bound it).
|
||||
self.visits = self.visits.saturating_add(1 + items.as_ref().map_or(0, |i| i.len()));
|
||||
if self.visits > MAX_VISITS {
|
||||
self.warn(TOO_MUCH_BLOCK_WORK);
|
||||
return None;
|
||||
}
|
||||
let items = items?;
|
||||
if !self.enter(name, depth) {
|
||||
return None;
|
||||
}
|
||||
@@ -618,12 +674,16 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base);
|
||||
let map = self.symbol_map * Affine::translate(-base.to_vec2());
|
||||
let art = self.art(name, map, &key.1, depth);
|
||||
let made = art.map(|art| {
|
||||
let made = art.and_then(|art| {
|
||||
let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str());
|
||||
// The symbol keeps its name: text, as its instances' copies of it are.
|
||||
if !self.charge_text(label.len()) {
|
||||
return None;
|
||||
}
|
||||
let symbol = unique(label, &mut self.next_suffix, &self.symbol_names);
|
||||
self.symbol_names.insert(symbol.clone());
|
||||
self.doc.symbols.push(Symbol { dynamic: false, name: symbol.clone(), art: Arc::new(art) });
|
||||
symbol
|
||||
Some(symbol)
|
||||
});
|
||||
self.symbols.insert(key, made.clone());
|
||||
made
|
||||
|
||||
@@ -814,7 +814,7 @@ fn nested_array_inserts_of_nothing_stop_at_the_work_budget() {
|
||||
blocks.extend(block("*C", None));
|
||||
let top = [(0, "INSERT"), (2, "*A"), (10, "0"), (20, "0"), (70, "300"), (44, "1")];
|
||||
let r = open(&drawing(&[], &[], &blocks, &top), &points());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("more than")), "{:?}", r.warnings);
|
||||
assert!(r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1177,3 +1177,173 @@ fn many_array_inserts_of_a_missing_block_stay_bounded() {
|
||||
assert!(total <= 2_000_000 + 3000, "total cells materialised: {total}");
|
||||
assert!(conv.warnings.iter().any(|w| w.contains("array inserts")), "{:?}", conv.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dashed_lines_past_the_dash_budget_are_drawn_solid() {
|
||||
// 600 lines of a two-length linetype: 1,200 dash lengths, past the 1,000 tests import with.
|
||||
let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")];
|
||||
let line = [(0, "LINE"), (6, "DASHED"), (10, "0"), (20, "0"), (11, "100"), (21, "0")];
|
||||
let e: Vec<(i32, &str)> = (0..600).flat_map(|_| line).collect();
|
||||
let r = open(&drawing(&[], &tables, &[], &e), &points());
|
||||
let (mut dashed, mut solid, mut kept) = (0, 0, 0);
|
||||
r.document.walk(|n| {
|
||||
if let NodeKind::Path { .. } = n.kind {
|
||||
match n.appearance.stroke().and_then(|s| s.dash.as_ref()) {
|
||||
Some(d) => {
|
||||
dashed += 1;
|
||||
kept += d.pattern.len();
|
||||
}
|
||||
None => solid += 1,
|
||||
}
|
||||
}
|
||||
});
|
||||
assert_eq!(dashed + solid, 600);
|
||||
assert!(dashed > 0 && solid > 0, "{dashed} dashed, {solid} solid");
|
||||
assert!(kept <= 1_000, "{kept} dash lengths kept");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("drawn solid")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// The bytes of text in the document's text objects.
|
||||
fn text_bytes(doc: &Document) -> usize {
|
||||
let mut bytes = 0;
|
||||
doc.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
bytes += t.runs.iter().map(|r| r.text.len()).sum::<usize>();
|
||||
}
|
||||
});
|
||||
bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_copied_into_array_cells_stops_at_the_text_budget() {
|
||||
// 1,000 characters of text in an anonymous block placed 10 × 10: 100 KB of copies, past the
|
||||
// 64 KB tests import with.
|
||||
let long = "x".repeat(1000);
|
||||
let blocks =
|
||||
[(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0"), (0, "TEXT"), (10, "0"), (20, "0"), (40, "1"), (1, long.as_str()), (0, "ENDBLK")];
|
||||
let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "10"), (71, "10"), (44, "1"), (45, "1")];
|
||||
let r = open(&drawing(&[], &[], &blocks, &insert), &points());
|
||||
let bytes = text_bytes(&r.document);
|
||||
assert!(bytes > 0, "some copies are kept");
|
||||
assert!(bytes <= 64 << 10, "{bytes} bytes of text");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_style_naming_an_overlong_font_family_takes_the_default() {
|
||||
let family = "F".repeat(10_000);
|
||||
let tables = [(0, "TABLE"), (2, "STYLE"), (0, "STYLE"), (2, "Big"), (3, "x.ttf"), (1001, "ACAD"), (1000, family.as_str()), (0, "ENDTAB")];
|
||||
let e = [(0, "TEXT"), (10, "0"), (20, "0"), (40, "1"), (1, "Hi"), (7, "Big")];
|
||||
let doc = open(&drawing(&[], &tables, &[], &e), &points()).document;
|
||||
let mut families = vec![];
|
||||
doc.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
families.extend(t.runs.iter().map(|r| r.style.font_family.clone()));
|
||||
}
|
||||
});
|
||||
assert_eq!(families, [vectorcraft_doc::CharStyle::default().font_family]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_instances_of_a_long_block_name_stop_at_the_text_budget() {
|
||||
// A 1,000-byte block name placed 10 × 10: each instance keeps its own copy of the name.
|
||||
let name = "N".repeat(1000);
|
||||
let blocks = [(0, "BLOCK"), (2, name.as_str()), (10, "0"), (20, "0"), (0, "LINE"), (10, "0"), (20, "0"), (11, "1"), (21, "0"), (0, "ENDBLK")];
|
||||
let insert = [(0, "INSERT"), (2, name.as_str()), (10, "0"), (20, "0"), (70, "10"), (71, "10"), (44, "2"), (45, "2")];
|
||||
let r = open(&drawing(&[], &[], &blocks, &insert), &points());
|
||||
let mut instances = 0;
|
||||
r.document.walk(|n| {
|
||||
if let NodeKind::SymbolInstance { .. } = n.kind {
|
||||
instances += 1;
|
||||
}
|
||||
});
|
||||
assert!(instances > 0 && instances < 100, "{instances} instances");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrays_of_blocks_of_hidden_art_stop_at_the_work_budget() {
|
||||
// 500 lines on a hidden layer in an anonymous block placed 50 × 50: they make nothing, but
|
||||
// each placement looks at all of them (1,250,000 items, past the 1,000,000 tests import with).
|
||||
let tables = [(0, "TABLE"), (2, "LAYER"), (0, "LAYER"), (2, "Off"), (70, "0"), (62, "-1"), (0, "ENDTAB")];
|
||||
let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")];
|
||||
for _ in 0..500 {
|
||||
blocks.extend([(0, "LINE"), (8, "Off"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]);
|
||||
}
|
||||
blocks.push((0, "ENDBLK"));
|
||||
let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "50"), (71, "50"), (44, "1"), (45, "1")];
|
||||
let r = open(&drawing(&[], &tables, &blocks, &insert), &points());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dashed_compound_paths_charge_every_copy_of_their_pattern() {
|
||||
// 100 pattern hatches of 9 loops in a two-length linetype: each keeps its dashes on the
|
||||
// compound path and on each loop, 2,000 dash lengths, past the 1,000 tests import with.
|
||||
let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")];
|
||||
let corners = ["0", "10", "20", "30", "40", "50", "60", "70", "80", "90"];
|
||||
let mut hatch = vec![(0, "HATCH"), (6, "DASHED"), (10, "0"), (20, "0"), (30, "0"), (2, "ANSI31"), (70, "0"), (71, "0"), (91, "9")];
|
||||
for i in 0..9 {
|
||||
let (a, b) = (corners[i], corners[i + 1]);
|
||||
hatch.extend([
|
||||
(92, "2"),
|
||||
(72, "0"),
|
||||
(73, "1"),
|
||||
(93, "4"),
|
||||
(10, a),
|
||||
(20, "0"),
|
||||
(10, b),
|
||||
(20, "0"),
|
||||
(10, b),
|
||||
(20, "5"),
|
||||
(10, a),
|
||||
(20, "5"),
|
||||
(97, "0"),
|
||||
]);
|
||||
}
|
||||
hatch.extend([(75, "0"), (76, "1"), (98, "0")]);
|
||||
let e: Vec<(i32, &str)> = (0..100).flat_map(|_| hatch.iter().copied()).collect();
|
||||
let r = open(&drawing(&[], &tables, &[], &e), &points());
|
||||
let (mut compounds, mut kept) = (0, 0);
|
||||
r.document.walk(|n| {
|
||||
compounds += usize::from(matches!(n.kind, NodeKind::Compound { .. }));
|
||||
kept += n.appearance.stroke().and_then(|s| s.dash.as_ref()).map_or(0, |d| d.pattern.len());
|
||||
});
|
||||
assert_eq!(compounds, 100, "{:?}", r.warnings);
|
||||
assert!(kept > 0 && kept <= 1_000, "{kept} dash lengths kept");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("drawn solid")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbols_of_a_long_block_name_stop_at_the_text_budget() {
|
||||
// A 1,000-byte block name inserted in 100 colours its art takes: a symbol per colour, each
|
||||
// keeping its own copy of the name, past the 64 KB tests import with.
|
||||
let name = "N".repeat(1000);
|
||||
let blocks = [
|
||||
(0, "BLOCK"),
|
||||
(2, name.as_str()),
|
||||
(10, "0"),
|
||||
(20, "0"),
|
||||
(0, "LINE"),
|
||||
(8, "0"),
|
||||
(62, "0"),
|
||||
(10, "0"),
|
||||
(20, "0"),
|
||||
(11, "1"),
|
||||
(21, "0"),
|
||||
(0, "ENDBLK"),
|
||||
];
|
||||
let colours: Vec<String> = (1..=100).map(|c| c.to_string()).collect();
|
||||
let inserts: Vec<(i32, &str)> =
|
||||
colours.iter().flat_map(|c| [(0, "INSERT"), (2, name.as_str()), (62, c.as_str()), (10, "0"), (20, "0")]).collect();
|
||||
let r = open(&drawing(&[], &[], &blocks, &inserts), &points());
|
||||
let mut bytes: usize = r.document.symbols.iter().map(|s| s.name.len()).sum();
|
||||
r.document.walk(|n| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
bytes += symbol.len();
|
||||
}
|
||||
});
|
||||
assert!(!r.document.symbols.is_empty());
|
||||
assert!(bytes <= 64 << 10, "{bytes} bytes of symbol names");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("64 MB of text")), "{:?}", r.warnings);
|
||||
}
|
||||
@@ -62,6 +62,33 @@ fn until_semicolon(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> Stri
|
||||
arg
|
||||
}
|
||||
|
||||
/// The character a `\U+XXXX` escape writes (`after` is the text just after its backslash), with
|
||||
/// the escape's length; a UTF-16 surrogate pair written as two escapes is one character.
|
||||
fn unicode_escape(after: &str) -> Option<(char, usize)> {
|
||||
let hex = after.strip_prefix("U+").or_else(|| after.strip_prefix("u+"))?.get(..4)?;
|
||||
if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let value = u32::from_str_radix(hex, 16).ok()?;
|
||||
if (0xD800..=0xDBFF).contains(&value) {
|
||||
let next = after.get(6..)?;
|
||||
let low = next.strip_prefix("\\U+").or_else(|| next.strip_prefix("\\u+"))?.get(..4)?;
|
||||
if !low.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let low = u32::from_str_radix(low, 16).ok()?;
|
||||
if !(0xDC00..=0xDFFF).contains(&low) {
|
||||
return None;
|
||||
}
|
||||
let scalar = 0x1_0000 + ((value - 0xD800) << 10) + (low - 0xDC00);
|
||||
return char::from_u32(scalar).map(|ch| (ch, 13));
|
||||
}
|
||||
if (0xDC00..=0xDFFF).contains(&value) {
|
||||
return None;
|
||||
}
|
||||
char::from_u32(value).map(|ch| (ch, 6))
|
||||
}
|
||||
|
||||
/// `\U+XXXX` Unicode escapes (how files before DXF 2007 hold characters outside their code page)
|
||||
/// and caret escapes: `^ ` is a caret, `^I` a tab; other control characters are dropped. In
|
||||
/// multiline text (`mtext`) `\\` is an escaped backslash and is kept as is, so that a `U+` after
|
||||
@@ -77,12 +104,10 @@ fn escapes(s: &str, mtext: bool) -> String {
|
||||
continue;
|
||||
}
|
||||
if c == '\\'
|
||||
&& let Some(hex) = after.strip_prefix("U+").or_else(|| after.strip_prefix("u+")).and_then(|h| h.get(..4))
|
||||
&& hex.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
&& let Some(ch) = u32::from_str_radix(hex, 16).ok().and_then(char::from_u32)
|
||||
&& let Some((ch, consumed)) = unicode_escape(after)
|
||||
{
|
||||
out.push(ch);
|
||||
rest = after.get(6..).unwrap_or("");
|
||||
rest = after.get(consumed..).unwrap_or("");
|
||||
continue;
|
||||
}
|
||||
if mtext
|
||||
@@ -161,6 +186,14 @@ mod tests {
|
||||
assert_eq!(plain("\\U+00C9"), "É");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_escape_decodes_surrogate_pairs() {
|
||||
assert_eq!(plain("\\U+D83D\\U+DE00"), "😀");
|
||||
assert_eq!(plain("\\U+D83D"), "\\U+D83D");
|
||||
assert_eq!(plain("\\U+DE00"), "\\U+DE00");
|
||||
assert_eq!(plain("\\U+D83D\\U+0041"), "\\U+D83DA");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_codes_and_escapes() {
|
||||
assert_eq!(plain("45%%d %%p0.1 %%c20 100%%% %%uunder%%u"), "45° ±0.1 ⌀20 100% under");
|
||||
|
||||
@@ -308,6 +308,78 @@ impl Default for DxfOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// A named set of DXF options (the `dxfPreset` param): the options it sets, and the ones a set of
|
||||
/// options matches.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum DxfPreset {
|
||||
/// The options as chosen (the export's defaults for those left out).
|
||||
#[default]
|
||||
Custom,
|
||||
/// For CNC and CAM cutting software: version 2000 (the oldest version that has both lightweight
|
||||
/// polylines and lineweights), 1 mm = 1 unit, 256 indexed colors (all version 2000 holds), Maximize
|
||||
/// Editability with Alter Paths off (every stroke a center line), Outline Text (type as paths),
|
||||
/// and placed images as PNG.
|
||||
Cnc,
|
||||
}
|
||||
|
||||
impl DxfPreset {
|
||||
pub const ALL: [Self; 2] = [Self::Custom, Self::Cnc];
|
||||
|
||||
/// The `dxfPreset` param value.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Custom => "custom",
|
||||
Self::Cnc => "cnc",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Custom => "Custom",
|
||||
Self::Cnc => "CNC / CAM",
|
||||
}
|
||||
}
|
||||
|
||||
/// A preset by id (`custom`, `cnc`), any case.
|
||||
pub fn from_id(s: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|p| s.trim().eq_ignore_ascii_case(p.id()))
|
||||
}
|
||||
|
||||
/// The options the preset sets (Custom: the defaults); the region and crop are the defaults.
|
||||
pub fn options(self) -> DxfOptions {
|
||||
match self {
|
||||
Self::Custom => DxfOptions::default(),
|
||||
Self::Cnc => DxfOptions {
|
||||
version: DxfVersion::R2000,
|
||||
unit: Unit::Millimeters,
|
||||
scale: 1.0,
|
||||
scale_lineweights: false,
|
||||
colors: ColorDepth::Aci256,
|
||||
raster: RasterFormat::Png,
|
||||
preserve: Preserve::Editability,
|
||||
alter_paths: false,
|
||||
outline_text: true,
|
||||
..DxfOptions::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The preset `o` matches: CNC / CAM when every option it sets is as it sets it, else Custom.
|
||||
pub fn of(o: &DxfOptions) -> Self {
|
||||
let c = Self::Cnc.options();
|
||||
let same = o.version == c.version
|
||||
&& o.unit == c.unit
|
||||
&& o.scale == c.scale
|
||||
&& o.scale_lineweights == c.scale_lineweights
|
||||
&& o.colors == c.colors
|
||||
&& o.raster == c.raster
|
||||
&& o.preserve == c.preserve
|
||||
&& o.alter_paths == c.alter_paths
|
||||
&& o.outline_text == c.outline_text;
|
||||
if same { Self::Cnc } else { Self::Custom }
|
||||
}
|
||||
}
|
||||
|
||||
/// An image file a drawing links to, to be written next to it under `name`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DxfImage {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The document walk: each visible object becomes DXF entities on its layer's DXF layer, in paint
|
||||
//! order. Fills are their outlines then solid hatches (the outlines alone in R12), strokes
|
||||
//! polylines and cubic splines with a lineweight and dashes, or filled outlines where the look
|
||||
//! needs them.
|
||||
//! polylines (with bulges for circular arcs) and cubic splines with a lineweight and dashes, or
|
||||
//! filled outlines where the look needs them.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::Cursor;
|
||||
@@ -66,6 +66,8 @@ struct CircularSub {
|
||||
centre: Point,
|
||||
radius: f64,
|
||||
samples: Vec<Point>,
|
||||
/// The signed angle (radians) the curve turns through about `centre` in document space.
|
||||
turn: f64,
|
||||
}
|
||||
|
||||
fn cubic_point(p0: Point, p1: Point, p2: Point, p3: Point, t: f64) -> Point {
|
||||
@@ -122,7 +124,12 @@ fn circular_subpath(sub: &Sub) -> Option<CircularSub> {
|
||||
if !centre.x.is_finite() || !centre.y.is_finite() || !radius.is_finite() || radius <= 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let tolerance = (radius * 5e-4).max(1e-6);
|
||||
// The tolerance is a fraction of the smaller of the radius and the curve's extent, so the large
|
||||
// radius of a shallow curve does not loosen it.
|
||||
let (lo, hi) = samples
|
||||
.iter()
|
||||
.fold((samples[0], samples[0]), |(lo, hi), p| (Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y))));
|
||||
let tolerance = (radius.min(lo.distance(hi)) * 5e-4).max(1e-6);
|
||||
if samples.iter().any(|p| (centre.distance(*p) - radius).abs() > tolerance) {
|
||||
return None;
|
||||
}
|
||||
@@ -181,7 +188,76 @@ fn circular_subpath(sub: &Sub) -> Option<CircularSub> {
|
||||
} else if total_turn.abs() < 1e-6 || total_turn.abs() >= std::f64::consts::TAU - 1e-3 {
|
||||
return None;
|
||||
}
|
||||
Some(CircularSub { centre, radius, samples })
|
||||
Some(CircularSub { centre, radius, samples, turn: total_turn })
|
||||
}
|
||||
|
||||
/// The points of the circle about `centre` of `radius` furthest left, right, up and down that lie on
|
||||
/// its arc from `from` through `turn` radians, for the drawing extents.
|
||||
fn arc_extrema(centre: Point, radius: f64, from: Point, turn: f64) -> Vec<Point> {
|
||||
let start = (from.y - centre.y).atan2(from.x - centre.x);
|
||||
(0..4)
|
||||
.map(|k| f64::from(k) * std::f64::consts::FRAC_PI_2)
|
||||
.filter(|a| ((a - start) * turn.signum()).rem_euclid(std::f64::consts::TAU) <= turn.abs())
|
||||
.map(|a| Point::new(centre.x + radius * a.cos(), centre.y + radius * a.sin()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The most cubics one bulge arc is fitted to; the cubics after them start the next arc.
|
||||
const MAX_ARC_RUN: usize = 64;
|
||||
|
||||
/// A subpath of straight segments and circular arcs as polyline vertices, in document space.
|
||||
struct BulgedSub {
|
||||
/// The anchors, without a closed subpath's repeated start.
|
||||
pts: Vec<Point>,
|
||||
/// For each anchor, the angle (radians, document space) the segment that starts there turns
|
||||
/// through: 0 for a straight segment.
|
||||
turns: Vec<f64>,
|
||||
/// The arcs' extreme points ([`arc_extrema`]), for the drawing extents.
|
||||
extrema: Vec<Point>,
|
||||
}
|
||||
|
||||
/// Fit a subpath with curves to straight segments and circular arcs: each run of cubics on one
|
||||
/// circle, turning one way and less than a whole turn, becomes one arc ([`circular_subpath`]'s
|
||||
/// tolerance). `None` when the subpath has no curves or a curve that is not a circular arc.
|
||||
fn bulged_subpath(sub: &Sub) -> Option<BulgedSub> {
|
||||
if !sub.segs.iter().any(|s| matches!(s, Seg::Cubic(..))) {
|
||||
return None;
|
||||
}
|
||||
let mut pts = vec![sub.start];
|
||||
let mut turns = vec![];
|
||||
let mut extrema = vec![];
|
||||
let mut from = sub.start;
|
||||
let mut i = 0;
|
||||
while let Some(seg) = sub.segs.get(i) {
|
||||
if let Seg::Line(p) = *seg {
|
||||
turns.push(0.0);
|
||||
pts.push(p);
|
||||
from = p;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut best = None;
|
||||
let mut j = i;
|
||||
while j < sub.segs.len() && j - i < MAX_ARC_RUN && matches!(sub.segs[j], Seg::Cubic(..)) {
|
||||
let run = Sub { start: from, segs: sub.segs[i..=j].to_vec(), closed: false };
|
||||
let Some(arc) = circular_subpath(&run) else { break };
|
||||
best = Some((j, arc));
|
||||
j += 1;
|
||||
}
|
||||
let (j, arc) = best?;
|
||||
turns.push(arc.turn);
|
||||
extrema.extend(arc_extrema(arc.centre, arc.radius, from, arc.turn));
|
||||
from = sub.segs[j].end();
|
||||
pts.push(from);
|
||||
i = j + 1;
|
||||
}
|
||||
if sub.closed && pts.last().is_some_and(|p| p.distance(sub.start) <= 1e-9) {
|
||||
pts.pop();
|
||||
} else {
|
||||
// The segment from the last anchor: the straight closing edge, or none for an open subpath.
|
||||
turns.push(0.0);
|
||||
}
|
||||
(pts.len() >= 2).then_some(BulgedSub { pts, turns, extrema })
|
||||
}
|
||||
|
||||
/// A closed subpath that is the four-cubic circle under an affine map: an ellipse, or a circle
|
||||
@@ -271,7 +347,11 @@ const MAX_ENTITIES: u32 = 10_000_000;
|
||||
|
||||
/// The largest x or y a path may have to be flattened, and the most points its polygons keep.
|
||||
const MAX_COORD: f64 = 1e9;
|
||||
const MAX_POINTS: usize = 4_000_000;
|
||||
const MAX_POINTS: usize = if cfg!(test) { 100_000 } else { 4_000_000 };
|
||||
/// The most segments flattening one path makes, kept or not (repeats of a point are dropped).
|
||||
const MAX_FLATTEN_SEGMENTS: usize = 4 * MAX_POINTS;
|
||||
|
||||
const SYMBOLS_LEFT_OUT: &str = "symbols placed inside symbols hold too many objects for DXF: the instances past that were left out";
|
||||
|
||||
/// Do the dashes of `d` start at the start of their pattern, as a linetype's do? A pattern of
|
||||
/// odd length repeats twice in its linetype.
|
||||
@@ -296,14 +376,19 @@ fn polygons(bp: &BezPath) -> Vec<Vec<Point>> {
|
||||
}
|
||||
let mut out: Vec<Vec<Point>> = vec![];
|
||||
let mut cur: Vec<Point> = vec![];
|
||||
let mut points = 0usize;
|
||||
let mut push = |p: Point, cur: &mut Vec<Point>| {
|
||||
if points < MAX_POINTS && cur.last().is_none_or(|q| q.distance(p) > 1e-9) {
|
||||
points += 1;
|
||||
// Points kept, and segments made: once either budget is spent, no further curve is flattened.
|
||||
let points = std::cell::Cell::new(0usize);
|
||||
let segments = std::cell::Cell::new(0usize);
|
||||
let push = |p: Point, cur: &mut Vec<Point>| {
|
||||
segments.set(segments.get() + 1);
|
||||
if points.get() < MAX_POINTS && cur.last().is_none_or(|q| q.distance(p) > 1e-9) {
|
||||
points.set(points.get() + 1);
|
||||
cur.push(p);
|
||||
}
|
||||
};
|
||||
kurbo::flatten(bp.iter(), FLATNESS, |el| match el {
|
||||
let elements = bp.iter().take_while(|_| points.get() < MAX_POINTS && segments.get() < MAX_FLATTEN_SEGMENTS);
|
||||
// Each curve is flattened into a bounded number of segments, however large it is.
|
||||
vectorcraft_geom::flatten(elements, FLATNESS, |el| match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
out.push(std::mem::take(&mut cur));
|
||||
push(p, &mut cur);
|
||||
@@ -412,6 +497,9 @@ pub(crate) struct Scene<'a> {
|
||||
opacity: f32,
|
||||
/// Symbols and brush art being written inside one another.
|
||||
nest: u32,
|
||||
/// Objects the symbol instances written held, together
|
||||
/// ([`vectorcraft_doc::MAX_SYMBOL_NODES`]).
|
||||
symbol_nodes: u64,
|
||||
}
|
||||
|
||||
impl<'a> Scene<'a> {
|
||||
@@ -441,6 +529,8 @@ impl<'a> Scene<'a> {
|
||||
extents: None,
|
||||
opacity: 1.0,
|
||||
nest: 0,
|
||||
// Tests spend all but a million of it up front.
|
||||
symbol_nodes: if cfg!(test) { vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000 } else { 0 },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -542,14 +632,36 @@ impl<'a> Scene<'a> {
|
||||
NodeKind::Text(t) => self.text(n, t),
|
||||
NodeKind::Image(im) => self.image(im),
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol)
|
||||
let doc = self.doc;
|
||||
if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES {
|
||||
// Spent: no more instances are looked at, so what's left costs nothing.
|
||||
self.warn(SYMBOLS_LEFT_OUT);
|
||||
} else if let Some(sym) = doc.symbols.iter().find(|s| &s.name == symbol)
|
||||
&& self.nest < MAX_NEST
|
||||
{
|
||||
let mut art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
|
||||
art.transform(*xf, false);
|
||||
self.nest += 1;
|
||||
self.node(&art, true);
|
||||
self.nest -= 1;
|
||||
// Symbols holding instances of symbols are written in full for each instance,
|
||||
// empty or not: every instance's art counts against one budget for the export.
|
||||
let art = vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n);
|
||||
let count = art.count_with_masks() as u64;
|
||||
// Counted as `place_symbol_art_unclipped` places it: no clip groups.
|
||||
let most = doc.symbol_slice_map(symbol, *xf).map_or(count, |m| m.most_placed_unclipped(&art, doc));
|
||||
let placed = vectorcraft_doc::charge_symbol_art(&mut self.symbol_nodes, most, || {
|
||||
let placed = doc.place_symbol_art_unclipped(symbol, &art, *xf);
|
||||
let n = placed.as_ref().map_or(0, |a| a.count_with_masks() as u64);
|
||||
(placed, n)
|
||||
});
|
||||
match placed {
|
||||
Some(Some(art)) => {
|
||||
self.nest += 1;
|
||||
self.node(&art, true);
|
||||
self.nest -= 1;
|
||||
}
|
||||
Some(None) => {}
|
||||
None => {
|
||||
self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
self.warn(SYMBOLS_LEFT_OUT);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Live blends, envelopes, meshes and repeats are written as their evaluated art.
|
||||
@@ -810,7 +922,9 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
|
||||
/// Path `bp` as lines: a line for an open subpath of one straight segment, polylines for
|
||||
/// other straight subpaths (and for curves in R12, flattened), cubic splines for curved ones.
|
||||
/// other straight subpaths, circles, arcs and ellipses where the curves are one, polylines
|
||||
/// with bulges for subpaths of straight segments and circular arcs, and cubic splines for
|
||||
/// other curved ones (flattened polylines in R12).
|
||||
/// `width`: the stroke weight, which DXF before 2000 gives polylines as a width.
|
||||
fn lines(&mut self, bp: &BezPath, style: &EntityStyle, width: f64) {
|
||||
let v = self.o.version;
|
||||
@@ -827,7 +941,7 @@ impl<'a> Scene<'a> {
|
||||
// A LINE has no width, so a stroke before 2000 keeps its polyline width.
|
||||
match (sub.closed, width, pts.as_slice()) {
|
||||
(false, None, &[a, b]) => self.line(a, b, style),
|
||||
_ => self.polyline(&pts, sub.closed, style, width),
|
||||
_ => self.polyline(&pts, &[], sub.closed, style, width),
|
||||
}
|
||||
} else if (v.handles() || width.is_none()) && self.circular(&sub, style) {
|
||||
// Native circles/arcs are preferred by CAD/CAM software. In R12, however, a
|
||||
@@ -835,6 +949,12 @@ impl<'a> Scene<'a> {
|
||||
// its width. Non-circular curves continue through the existing fallback.
|
||||
} else if v.handles() && self.elliptical(&sub, style) {
|
||||
// R13 and later write an ellipse as a native ELLIPSE.
|
||||
} else if let Some(b) = bulged_subpath(&sub) {
|
||||
// Straight segments and circular arcs: one polyline whose bulges draw the arcs.
|
||||
b.extrema.iter().for_each(|p| _ = self.pt(*p));
|
||||
let flip = if self.to_dxf.determinant() < 0.0 { -1.0 } else { 1.0 };
|
||||
let bulges: Vec<f64> = b.turns.iter().map(|t| flip * (t / 4.0).tan()).collect();
|
||||
self.polyline(&b.pts, &bulges, sub.closed, style, width);
|
||||
} else if v.handles() {
|
||||
self.spline(&sub, style);
|
||||
} else {
|
||||
@@ -847,7 +967,7 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
}
|
||||
for pts in polygons(&path) {
|
||||
self.polyline(&pts, sub.closed, style, width);
|
||||
self.polyline(&pts, &[], sub.closed, style, width);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -864,8 +984,9 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
|
||||
/// A polyline through `pts` (document space): lightweight from R14, else a polyline with a
|
||||
/// vertex entity per point.
|
||||
fn polyline(&mut self, pts: &[Point], closed: bool, style: &EntityStyle, width: Option<f64>) {
|
||||
/// vertex entity per point. `bulges`: the bulge (group 42) of the segment that starts at each
|
||||
/// point, in drawing space; empty for straight segments only.
|
||||
fn polyline(&mut self, pts: &[Point], bulges: &[f64], closed: bool, style: &EntityStyle, width: Option<f64>) {
|
||||
if pts.len() < 2 {
|
||||
return;
|
||||
}
|
||||
@@ -881,8 +1002,11 @@ impl<'a> Scene<'a> {
|
||||
if let Some(w) = width {
|
||||
self.e.num(43, w);
|
||||
}
|
||||
for p in &pts {
|
||||
for (i, p) in pts.iter().enumerate() {
|
||||
self.e.xy(10, p.x, p.y);
|
||||
if let Some(&b) = bulges.get(i).filter(|b| **b != 0.0) {
|
||||
self.e.num(42, b);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -894,13 +1018,16 @@ impl<'a> Scene<'a> {
|
||||
self.e.num(40, w);
|
||||
self.e.num(41, w);
|
||||
}
|
||||
for p in &pts {
|
||||
for (i, p) in pts.iter().enumerate() {
|
||||
let vh = self.handle();
|
||||
self.e.entity("VERTEX", vh, h, &layer, style, "AcDbVertex");
|
||||
if self.o.version.handles() {
|
||||
self.e.raw(100, "AcDb2dVertex");
|
||||
}
|
||||
self.e.xyz(10, p.x, p.y);
|
||||
if let Some(&b) = bulges.get(i).filter(|b| **b != 0.0) {
|
||||
self.e.num(42, b);
|
||||
}
|
||||
}
|
||||
let end = self.handle();
|
||||
self.e.entity("SEQEND", end, h, &layer, style, "");
|
||||
@@ -924,8 +1051,8 @@ impl<'a> Scene<'a> {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Count sampled points in the drawing extents. For a full circle include all cardinal
|
||||
// points exactly; for an arc, the dense samples conservatively cover its visible span.
|
||||
// Count the curve's extreme points in the drawing extents: all four cardinal points of a
|
||||
// full circle; an arc's ends and the cardinal points on it.
|
||||
if sub.closed {
|
||||
let r = circle.radius;
|
||||
for p in [
|
||||
@@ -937,8 +1064,8 @@ impl<'a> Scene<'a> {
|
||||
self.pt(p);
|
||||
}
|
||||
} else {
|
||||
for p in &circle.samples {
|
||||
self.pt(*p);
|
||||
for p in [sub.start, last].into_iter().chain(arc_extrema(circle.centre, circle.radius, sub.start, circle.turn)) {
|
||||
self.pt(p);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1100,10 +1227,10 @@ impl<'a> Scene<'a> {
|
||||
let Some(&first) = run.first() else { continue };
|
||||
let lo = run.iter().map(|g| g.byte).min().unwrap_or(first.byte);
|
||||
let hi = run.iter().map(|g| g.byte + g.len).max().unwrap_or(lo);
|
||||
// A right-to-left paragraph's marker is drawn with its tab first and its number's
|
||||
// period at the number's left; the TEXT entity holds the characters in that order.
|
||||
// A right-to-left paragraph's marker is drawn with its number's period at the
|
||||
// number's left; the TEXT entity holds the characters in that order.
|
||||
let marker = chunk.first().and_then(|(_, _, m)| *m).map(|m| match m.text.strip_suffix('.') {
|
||||
Some(number) if m.tab == m.glyphs.start => format!(".{number}"),
|
||||
Some(number) if layout.glyphs.get(m.tab).is_some_and(|g| g.rtl) => format!(".{number}"),
|
||||
_ => m.text.clone(),
|
||||
});
|
||||
let Some(s) = marker.as_deref().or_else(|| plain.get(lo..hi).map(str::trim_end)).filter(|s| !s.trim().is_empty()) else { continue };
|
||||
@@ -1263,3 +1390,47 @@ fn first_solid(n: &Node) -> Option<vectorcraft_color::Color> {
|
||||
});
|
||||
own.or_else(|| n.children().into_iter().flatten().find_map(|c| first_solid(c)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod budget_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn flattening_a_path_of_huge_curves_stops_at_its_budget() {
|
||||
// Each curve, a hundred million points across, flattens to thousands of segments at
|
||||
// FLATNESS; a small square after them is past the budget and left out.
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((0.0, 0.0));
|
||||
for i in 0..20_000 {
|
||||
let y = if i % 2 == 0 { 1e8 } else { -1e8 };
|
||||
bp.curve_to((1e8, y), (-1e8, y), (0.0, 0.0));
|
||||
}
|
||||
bp.move_to((10.0, 10.0));
|
||||
bp.line_to((20.0, 10.0));
|
||||
bp.line_to((20.0, 20.0));
|
||||
bp.close_path();
|
||||
let polys = polygons(&bp);
|
||||
let points: usize = polys.iter().map(Vec::len).sum();
|
||||
assert!(points <= MAX_POINTS, "{points} points");
|
||||
assert!(!polys.iter().any(|p| p.contains(&Point::new(20.0, 20.0))), "the square past the budget is left out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flattening_a_path_of_repeated_points_stops_at_its_segment_budget() {
|
||||
// Repeats of a point are dropped, so these keep one point but still count as segments:
|
||||
// the segment budget, not the point budget, leaves out the square after them.
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((0.0, 0.0));
|
||||
for _ in 0..MAX_FLATTEN_SEGMENTS {
|
||||
bp.line_to((0.0, 0.0));
|
||||
}
|
||||
bp.move_to((10.0, 10.0));
|
||||
bp.line_to((20.0, 10.0));
|
||||
bp.line_to((20.0, 20.0));
|
||||
bp.close_path();
|
||||
let polys = polygons(&bp);
|
||||
let points: usize = polys.iter().map(Vec::len).sum();
|
||||
assert!(points < MAX_POINTS, "{points} points");
|
||||
assert!(!polys.iter().any(|p| p.contains(&Point::new(20.0, 20.0))), "the square past the budget is left out");
|
||||
}
|
||||
}
|
||||
@@ -275,6 +275,197 @@ fn circles_and_circular_arcs_are_native_dxf_entities() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cubic arc about `c` of radius `r` from `deg0` to `deg1` (degrees, y down), from the current
|
||||
/// point, which is the arc's start.
|
||||
fn arc_cubic(b: &mut vectorcraft_geom::BezPath, c: Point, r: f64, deg0: f64, deg1: f64) {
|
||||
let (a0, a1) = (deg0.to_radians(), deg1.to_radians());
|
||||
let k = 4.0 / 3.0 * ((a1 - a0) / 4.0).tan() * r;
|
||||
let (p0, p3) = (Point::new(c.x + r * a0.cos(), c.y + r * a0.sin()), Point::new(c.x + r * a1.cos(), c.y + r * a1.sin()));
|
||||
b.curve_to(Point::new(p0.x - k * a0.sin(), p0.y + k * a0.cos()), Point::new(p3.x + k * a1.sin(), p3.y - k * a1.cos()), p3);
|
||||
}
|
||||
|
||||
/// A slot (two lines, two half circles) about y = 50, a D shape (a half circle closed by its
|
||||
/// diameter) and a rounded rectangle with 10 pt corners.
|
||||
fn lines_and_arcs() -> [PathData; 3] {
|
||||
let mut slot = vectorcraft_geom::BezPath::new();
|
||||
slot.move_to((60.0, 30.0));
|
||||
slot.line_to((140.0, 30.0));
|
||||
arc_cubic(&mut slot, Point::new(140.0, 50.0), 20.0, -90.0, 0.0);
|
||||
arc_cubic(&mut slot, Point::new(140.0, 50.0), 20.0, 0.0, 90.0);
|
||||
slot.line_to((60.0, 70.0));
|
||||
arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 90.0, 180.0);
|
||||
arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 180.0, 270.0);
|
||||
slot.close_path();
|
||||
let mut d = vectorcraft_geom::BezPath::new();
|
||||
d.move_to((150.0, 20.0));
|
||||
arc_cubic(&mut d, Point::new(150.0, 50.0), 30.0, -90.0, 0.0);
|
||||
arc_cubic(&mut d, Point::new(150.0, 50.0), 30.0, 0.0, 90.0);
|
||||
d.close_path();
|
||||
[PathData::from_bezpath(&slot), PathData::from_bezpath(&d), shapes::rounded_rectangle(Rect::new(20.0, 20.0, 100.0, 80.0), 10.0)]
|
||||
}
|
||||
|
||||
/// A polyline entity's vertices as (x, y, bulge): an LWPOLYLINE's, or those of the VERTEX
|
||||
/// entities that follow a POLYLINE at `e[i]`.
|
||||
fn vertices(e: &[Pairs], i: usize) -> Vec<(f64, f64, f64)> {
|
||||
let mut out = vec![];
|
||||
let mut read = |o: &Pairs| {
|
||||
for (code, value) in o {
|
||||
let v: f64 = value.trim().parse().unwrap_or(0.0);
|
||||
match code {
|
||||
10 => out.push((v, 0.0, 0.0)),
|
||||
20 => out.last_mut().expect("x before y").1 = v,
|
||||
42 => out.last_mut().expect("a vertex before its bulge").2 = v,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
};
|
||||
if kind(&e[i]) == "LWPOLYLINE" {
|
||||
read(&e[i]);
|
||||
} else {
|
||||
e[i + 1..].iter().take_while(|o| kind(o) == "VERTEX").for_each(&mut read);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paths_of_lines_and_circular_arcs_are_polylines_with_bulges() {
|
||||
let [slot, d_shape, rounded] = lines_and_arcs();
|
||||
let d = doc_with(|d| {
|
||||
let black = || Paint::solid(Color::BLACK);
|
||||
let mut open = vectorcraft_geom::BezPath::new();
|
||||
open.move_to((10.0, 90.0));
|
||||
open.line_to((30.0, 90.0));
|
||||
arc_cubic(&mut open, Point::new(30.0, 80.0), 10.0, 90.0, 0.0);
|
||||
vec![
|
||||
path(d, slot, Paint::None, black(), 1.0),
|
||||
path(d, d_shape, Paint::None, black(), 1.0),
|
||||
path(d, rounded, Paint::None, black(), 1.0),
|
||||
path(d, PathData::from_bezpath(&open), Paint::None, black(), 1.0),
|
||||
]
|
||||
});
|
||||
let b = (std::f64::consts::PI / 8.0).tan();
|
||||
for version in DxfVersion::ALL {
|
||||
let out = export(&d, &DxfOptions { version, ..opts(&d) }).unwrap();
|
||||
let e = entities(&out);
|
||||
let polys: Vec<usize> = (0..e.len()).filter(|i| matches!(kind(&e[*i]), "LWPOLYLINE" | "POLYLINE")).collect();
|
||||
let k = kinds(&out);
|
||||
assert_eq!(polys.len(), 4, "{version:?}: {k:?}");
|
||||
assert!(!k.iter().any(|k| matches!(k.as_str(), "SPLINE" | "ARC" | "CIRCLE")), "{version:?}: {k:?}");
|
||||
let want = if version.lwpolyline() { "LWPOLYLINE" } else { "POLYLINE" };
|
||||
assert!(polys.iter().all(|i| kind(&e[*i]) == want), "{version:?}: {k:?}");
|
||||
let flags: Vec<i64> = polys.iter().map(|i| get(&e[*i], 70).unwrap().parse::<i64>().unwrap() & 1).collect();
|
||||
assert_eq!(flags, [1, 1, 1, 0], "{version:?}: closed, closed, closed, open");
|
||||
// The slot's half circles turn clockwise with y up: a bulge of -1 after each long side.
|
||||
assert_eq!(vertices(&e, polys[0]), [(60.0, 70.0, 0.0), (140.0, 70.0, -1.0), (140.0, 30.0, 0.0), (60.0, 30.0, -1.0)], "{version:?}");
|
||||
// The D shape: the half circle, then the straight closing edge.
|
||||
assert_eq!(vertices(&e, polys[1]), [(150.0, 80.0, -1.0), (150.0, 20.0, 0.0)], "{version:?}");
|
||||
// The rounded rectangle: eight anchors, a quarter circle (bulge tan 22.5°) at each corner.
|
||||
let r = vertices(&e, polys[2]);
|
||||
assert_eq!(r.len(), 8, "{version:?}: {r:?}");
|
||||
let bulges: Vec<f64> = r.iter().map(|v| v.2).filter(|b| *b != 0.0).collect();
|
||||
assert!(close_to(&bulges, &[-b; 4], 1e-6), "{version:?}: {r:?}");
|
||||
// An open line then a quarter circle turning counterclockwise with y up.
|
||||
let o = vertices(&e, polys[3]);
|
||||
assert!(
|
||||
close_to(&o.iter().flat_map(|v| [v.0, v.1, v.2]).collect::<Vec<_>>(), &[10.0, 10.0, 0.0, 30.0, 10.0, b, 40.0, 20.0, 0.0], 1e-6),
|
||||
"{version:?}: {o:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polylines_with_bulges_read_back_as_the_same_outline() {
|
||||
for (i, shape) in lines_and_arcs().into_iter().enumerate() {
|
||||
let original = shape.to_bezpath();
|
||||
let d = doc_with(|d| vec![path(d, shape, Paint::None, Paint::solid(Color::BLACK), 1.0)]);
|
||||
let out = export(&d, &opts(&d)).unwrap();
|
||||
assert_eq!(kinds(&out), ["LWPOLYLINE"], "shape {i}");
|
||||
let o = ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() };
|
||||
let back = import(&out.bytes, &o).unwrap().document;
|
||||
let mut paths = vec![];
|
||||
back.walk(|n| {
|
||||
if let NodeKind::Path { path, .. } = &n.kind {
|
||||
paths.push(path.to_bezpath());
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 1, "shape {i}");
|
||||
assert!(paths[0].elements().last().is_some_and(|el| matches!(el, kurbo::PathEl::ClosePath)), "shape {i} reads back closed");
|
||||
let (a, b) = (original.bounding_box(), paths[0].bounding_box());
|
||||
assert!(close_to(&[a.width(), a.height()], &[b.width(), b.height()], 1e-2), "shape {i}: {a:?} against {b:?}");
|
||||
// Every point read back lies on the original outline, once both are centered.
|
||||
let shift = a.center() - b.center();
|
||||
let outline: Vec<Point> = original.segments().flat_map(|s| (0..=64).map(move |t| s.eval(f64::from(t) / 64.0))).collect();
|
||||
for seg in paths[0].segments() {
|
||||
for t in 0..=16 {
|
||||
let p = seg.eval(f64::from(t) / 16.0) + shift;
|
||||
let near = outline
|
||||
.windows(2)
|
||||
.map(|w| {
|
||||
let (u, v) = (w[1] - w[0], p - w[0]);
|
||||
let s = if u.hypot2() > 0.0 { (v.dot(u) / u.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(v - u * s).hypot()
|
||||
})
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
assert!(near < 1e-2, "shape {i}: {p:?} is {near} pt off the outline");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_with_a_curve_that_is_not_a_circular_arc_stays_a_spline() {
|
||||
// The slot with one end drawn by a longer-handled curve.
|
||||
let mut slot = vectorcraft_geom::BezPath::new();
|
||||
slot.move_to((60.0, 30.0));
|
||||
slot.line_to((140.0, 30.0));
|
||||
slot.curve_to((165.0, 30.0), (165.0, 70.0), (140.0, 70.0));
|
||||
slot.line_to((60.0, 70.0));
|
||||
arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 90.0, 180.0);
|
||||
arc_cubic(&mut slot, Point::new(60.0, 50.0), 20.0, 180.0, 270.0);
|
||||
slot.close_path();
|
||||
let d = doc_with(|d| {
|
||||
vec![
|
||||
path(d, PathData::from_bezpath(&slot), Paint::None, Paint::solid(Color::BLACK), 1.0),
|
||||
path(d, shapes::ellipse(Rect::new(150.0, 20.0, 190.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 1.0),
|
||||
]
|
||||
});
|
||||
assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE", "CIRCLE"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawing_extents_reach_the_extreme_points_of_arcs() {
|
||||
// An arc about (100, 50) of radius 40 from -60° to 30° passes x = 140 at 0°, between the points
|
||||
// along it that recognition samples.
|
||||
let arc = |closed: bool| {
|
||||
let mut b = vectorcraft_geom::BezPath::new();
|
||||
let start = Point::new(100.0 + 40.0 * 60f64.to_radians().cos(), 50.0 - 40.0 * 60f64.to_radians().sin());
|
||||
b.move_to(start);
|
||||
arc_cubic(&mut b, Point::new(100.0, 50.0), 40.0, -60.0, 30.0);
|
||||
if closed {
|
||||
b.close_path();
|
||||
}
|
||||
PathData::from_bezpath(&b)
|
||||
};
|
||||
for (closed, entity) in [(false, "ARC"), (true, "LWPOLYLINE")] {
|
||||
let d = doc_with(|d| vec![path(d, arc(closed), Paint::None, Paint::solid(Color::BLACK), 1.0)]);
|
||||
let out = export(&d, &opts(&d)).unwrap();
|
||||
assert_eq!(kinds(&out), [entity]);
|
||||
let x: f64 = header(&pairs(&out.bytes), "$EXTMAX").unwrap().trim().parse().unwrap();
|
||||
assert!((x - 140.0).abs() < 1e-6, "{entity}: $EXTMAX x {x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shallow_curve_that_is_not_circular_is_not_an_arc() {
|
||||
// 100 pt across and 1.5 pt deep: the circle through its ends and middle has a radius of about
|
||||
// 834 pt, and the curve is 0.12 pt off it a quarter of the way along.
|
||||
let mut b = vectorcraft_geom::BezPath::new();
|
||||
b.move_to((0.0, 50.0));
|
||||
b.curve_to((20.0, 48.0), (80.0, 48.0), (100.0, 50.0));
|
||||
let d = doc_with(|d| vec![path(d, PathData::from_bezpath(&b), Paint::None, Paint::solid(Color::BLACK), 1.0)]);
|
||||
assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE"]);
|
||||
}
|
||||
|
||||
/// The path `p` with `xf` applied.
|
||||
fn transformed(p: &PathData, xf: Affine) -> PathData {
|
||||
PathData::from_bezpath(&(xf * p.to_bezpath()))
|
||||
@@ -391,11 +582,12 @@ fn closed_four_cubic_shapes_that_are_not_writable_ellipses_stay_splines() {
|
||||
vec![
|
||||
path(d, PathData::from_bezpath(&squircle), Paint::None, Paint::solid(Color::BLACK), 1.0),
|
||||
path(d, PathData::from_bezpath(&kurbo::BezPath::from_vec(els)), Paint::None, Paint::solid(Color::BLACK), 1.0),
|
||||
// An ellipse thinner than the smallest ratio DXF readers take (5e-7 against 1e-6).
|
||||
// An ellipse thinner than the smallest ratio DXF readers take (5e-7 against 1e-6). Its
|
||||
// quarters fit shallow circular arcs within the tolerance, so it is a polyline with bulges.
|
||||
path(d, shapes::ellipse(Rect::new(0.0, 90.0, 200.0, 90.0001)), Paint::None, Paint::solid(Color::BLACK), 1.0),
|
||||
]
|
||||
});
|
||||
assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE", "SPLINE", "SPLINE"]);
|
||||
assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), ["SPLINE", "SPLINE", "LWPOLYLINE"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -462,8 +654,12 @@ fn closed_circular_arc_with_a_closing_chord_is_not_a_circle() {
|
||||
vec![path(d, PathData::from_bezpath(&arc), Paint::None, Paint::solid(Color::BLACK), 1.0)]
|
||||
});
|
||||
|
||||
// The three quarters turn counterclockwise with y up (bulge tan 67.5°), then the chord closes it.
|
||||
let modern = export(&d, &opts(&d)).unwrap();
|
||||
assert_eq!(kinds(&modern), ["SPLINE"]);
|
||||
assert_eq!(kinds(&modern), ["LWPOLYLINE"]);
|
||||
let v = vertices(&entities(&modern), 0);
|
||||
let flat: Vec<f64> = v.iter().flat_map(|v| [v.0, v.1, v.2]).collect();
|
||||
assert!(close_to(&flat, &[80.0, 50.0, 67.5f64.to_radians().tan(), 50.0, 20.0, 0.0], 1e-6), "{v:?}");
|
||||
let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, ..opts(&d) }).unwrap();
|
||||
assert!(kinds(&r12).iter().any(|k| k == "POLYLINE"));
|
||||
assert!(!kinds(&r12).iter().any(|k| k == "CIRCLE"));
|
||||
@@ -497,9 +693,13 @@ fn a_closed_sliver_along_a_circle_is_not_a_circle() {
|
||||
vec![path(d, PathData::from_bezpath(&sliver), Paint::None, Paint::solid(Color::BLACK), 1.0)]
|
||||
});
|
||||
|
||||
// Two arcs, out along the circle and back: one polyline with a bulge each way.
|
||||
let modern = export(&d, &opts(&d)).unwrap();
|
||||
assert_ne!(kinds(&modern), ["CIRCLE"]);
|
||||
assert_eq!(kinds(&modern), ["SPLINE"]);
|
||||
assert_eq!(kinds(&modern), ["LWPOLYLINE"]);
|
||||
let bulges: Vec<f64> = vertices(&entities(&modern), 0).iter().map(|v| v.2).collect();
|
||||
let b = 10f64.to_radians().tan();
|
||||
assert!(close_to(&bulges, &[-b, b], 1e-6) || close_to(&bulges, &[b, -b], 1e-6), "{bulges:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -623,6 +823,30 @@ fn units_scale_coordinates_and_set_insunits() {
|
||||
assert!(export(&d, &DxfOptions { scale: f64::NAN, ..opts(&d) }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_strokes_as_lines() {
|
||||
let mut d = text_doc("Cut", 20.0);
|
||||
let layer = d.layers[0].id;
|
||||
let frame = path(&mut d, shapes::rectangle(Rect::new(5.0, 5.0, 195.0, 95.0)), Paint::None, Paint::solid(Color::BLACK), 10.0);
|
||||
d.insert(Some(layer), usize::MAX, frame).unwrap();
|
||||
let o = DxfOptions { region: d.artboards[0].rect, ..DxfPreset::Cnc.options() };
|
||||
let out = export(&d, &o).unwrap();
|
||||
let p = pairs(&out.bytes);
|
||||
assert_eq!(header(&p, "$ACADVER").as_deref(), Some("AC1015"));
|
||||
assert_eq!(header(&p, "$INSUNITS").as_deref(), Some("4"));
|
||||
let k = kinds(&out);
|
||||
assert!(!k.iter().any(|k| matches!(k.as_str(), "TEXT" | "MTEXT" | "IMAGE")), "type is paths: {k:?}");
|
||||
assert!(k.len() > 2, "the glyphs' outlines: {k:?}");
|
||||
// The 10 pt stroke (wider than the widest lineweight) is one center line, not a filled outline.
|
||||
assert_eq!(k.last().map(String::as_str), Some("LWPOLYLINE"), "{k:?}");
|
||||
assert_ne!(k.get(k.len() - 2).map(String::as_str), Some("LWPOLYLINE"), "{k:?}");
|
||||
assert!(out.images.is_empty());
|
||||
assert_eq!(DxfPreset::of(&o), DxfPreset::Cnc);
|
||||
assert_eq!(DxfPreset::of(&DxfOptions { colors: ColorDepth::True, ..o.clone() }), DxfPreset::Custom);
|
||||
assert_eq!(DxfPreset::of(&DxfOptions::default()), DxfPreset::Custom);
|
||||
assert_eq!(DxfPreset::from_id(" CNC "), Some(DxfPreset::Cnc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_become_dxf_layers() {
|
||||
let mut d = shapes_doc();
|
||||
@@ -852,15 +1076,15 @@ fn a_bullet_is_text_of_its_own_before_its_paragraph() {
|
||||
|
||||
/// A numbered list paragraph's number and period are a TEXT entity of their own where they are
|
||||
/// drawn, in the order they are drawn: in a right-to-left paragraph the period comes first, at the
|
||||
/// number's left.
|
||||
/// number's left, with the marker aligned left or right.
|
||||
#[test]
|
||||
fn a_number_is_text_of_its_own_before_its_paragraph() {
|
||||
use vectorcraft_doc::text::{NumberStyle, ParaList};
|
||||
let numbered = |text: &str, count: u32| {
|
||||
use vectorcraft_doc::text::{ListAlign, NumberStyle, ParaList};
|
||||
let numbered_aligned = |text: &str, count: u32, align: ListAlign| {
|
||||
let mut d = text_doc(text, 20.0);
|
||||
let id = d.layers[0].children().unwrap()[0].id;
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
t.para.list = Some(ParaList::numbered(NumberStyle::Arabic));
|
||||
t.para.list = Some(ParaList::numbered(NumberStyle::Arabic).aligned(align));
|
||||
t.para.left_indent = 30.0;
|
||||
t.para.first_line_indent = -30.0;
|
||||
t.list_count = count;
|
||||
@@ -868,10 +1092,27 @@ fn a_number_is_text_of_its_own_before_its_paragraph() {
|
||||
let out = export(&d, &DxfOptions { version: DxfVersion::R2018, preserve: Preserve::Editability, ..opts(&d) }).unwrap();
|
||||
entities(&out).iter().map(|e| (get(e, 1).map(str::to_string), all(e, 10)[0])).collect::<Vec<_>>()
|
||||
};
|
||||
let numbered = |text: &str, count: u32| numbered_aligned(text, count, ListAlign::Left);
|
||||
assert_eq!(numbered("Item", 11), [(Some("12.".to_string()), 10.0), (Some("Item".to_string()), 40.0)]);
|
||||
let rtl = numbered("שלום", 11);
|
||||
assert_eq!(rtl.iter().map(|(s, _)| s.clone().unwrap_or_default()).collect::<Vec<_>>(), ["שלום", ".12"]);
|
||||
assert!(rtl[1].1 > rtl[0].1, "the number right of the text: {rtl:?}");
|
||||
// Aligned right, the number keeps its order and moves right, against the text.
|
||||
let right = numbered_aligned("Item", 11, ListAlign::Right);
|
||||
assert_eq!((right[0].0.as_deref(), right[1].clone()), (Some("12."), (Some("Item".to_string()), 40.0)));
|
||||
assert!(right[0].1 > 10.0 && right[0].1 < 40.0, "{right:?}");
|
||||
let rtl = numbered_aligned("שלום", 11, ListAlign::Right);
|
||||
assert_eq!(rtl.iter().map(|(s, _)| s.clone().unwrap_or_default()).collect::<Vec<_>>(), ["שלום", ".12"]);
|
||||
// A mixed paragraph: the period follows the paragraph's direction, not the script of the
|
||||
// words it holds, with either alignment.
|
||||
let marker = |text: &str, align: ListAlign| {
|
||||
let out = numbered_aligned(text, 11, align);
|
||||
out.into_iter().filter_map(|(s, _)| s).find(|s| s.contains("12")).unwrap_or_default()
|
||||
};
|
||||
for align in [ListAlign::Left, ListAlign::Right] {
|
||||
assert_eq!(marker("Item שלום", align), "12.", "{align:?}");
|
||||
assert_eq!(marker("שלום Item", align), ".12", "{align:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Area type that Shrink Text to Fit scales down is written at the height it draws at.
|
||||
@@ -1007,3 +1248,22 @@ fn crop_keeps_an_instance_whose_art_reaches_the_region() {
|
||||
let o = DxfOptions { crop: true, ..opts(&d) };
|
||||
assert!(!kinds(&export(&d, &o).unwrap()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() {
|
||||
// Five levels of 100 instances of the level below, ending in an empty symbol: 10^10 empty
|
||||
// instances, which write no entities, past the million objects tests export with.
|
||||
let mut d = doc_with(|d| vec![Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "L5".into(), xf: Affine::IDENTITY })]);
|
||||
let empty = Node::group(d.alloc_id(), vec![]);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "L0".into(), art: Arc::new(empty) });
|
||||
for level in 1..=5 {
|
||||
let below = format!("L{}", level - 1);
|
||||
let children =
|
||||
(0..100).map(|_| Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: below.clone(), xf: Affine::IDENTITY }))).collect();
|
||||
let art = Node::group(d.alloc_id(), children);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(art) });
|
||||
}
|
||||
let out = export(&d, &opts(&d)).unwrap();
|
||||
assert!(entities(&out).is_empty());
|
||||
assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings);
|
||||
}
|
||||
@@ -1,19 +1,26 @@
|
||||
//! "VectorCraft Generic CMYK (SWOP-like)": our own parametric press model.
|
||||
//!
|
||||
//! We can't redistribute Adobe's or ECI's characterisation profiles, so the built-in CMYK space is
|
||||
//! a small physical model instead of an ICC LUT. It is *ours* and only SWOP-*like*: the numbers
|
||||
//! are rounded, typical values for coated web offset, not a measured dataset.
|
||||
//! a small physical model instead of an ICC LUT. It is *ours* and only SWOP-*like*. Two of its
|
||||
//! figures are published values for SWOP printing: the tone value increase of each ink at 40% and
|
||||
//! 50% from CGATS TR 001 (<https://registry.color.org/cmyk-registry/cgats_tr_001>), and the 300%
|
||||
//! total ink limit (<https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications>).
|
||||
//! The paper, solid and overprint colors and the black-generation curve are VectorCraft's own values.
|
||||
//!
|
||||
//! * **Forward (CMYK → XYZ):** each ink's nominal dot area is widened by a parabolic dot-gain
|
||||
//! curve (`a + 4·g·a·(1−a)`, i.e. `g` gain at 50%); the effective areas mix the eight CMY
|
||||
//! Neugebauer primaries with Demichel weights; black is mixed in the same way against
|
||||
//! "primary + K" colours whose optical densities add but saturate towards a maximum density
|
||||
//! (normalised so K on paper is exact), so rich blacks don't multiply to an unrealistic depth.
|
||||
//! * **Forward (CMYK → XYZ):** each ink's nominal dot area `a` is widened by a tone curve
|
||||
//! `a + 4·g·a·(1−a)·(1 + s·(2a−1))` that passes through the TR 001 tone value increase at 50%
|
||||
//! (`g`) and 40% (which sets `s`). The effective areas mix the 16 Neugebauer primaries (paper and
|
||||
//! every solid and overprint of C, M, Y and K, media-relative) with Demichel weights, linearly in
|
||||
//! XYZ, so a single ink's colorimetric tone value increase (Murray–Davies) is the TR 001 value.
|
||||
//! * **Inverse (Lab → CMYK):** damped, bounded Gauss–Newton on the forward model solves CMY for a
|
||||
//! fixed K. Black generation is GCR: solve CMY with K = 0, take the grey component
|
||||
//! `min(C, M, Y)`, map it through the black-generation curve to K, re-solve CMY. Under-colour
|
||||
//! fixed K. Black generation is GCR: solve CMY with K = 0, take the gray component
|
||||
//! `min(C, M, Y)`, add [`BlackGeneration::shortfall`] for each L* point by which that solve stays
|
||||
//! lighter than the target, map the sum through the black curve to K, re-solve CMY. Under-color
|
||||
//! removal enforces the total area coverage (TAC) limit by adding K and re-solving, then scaling
|
||||
//! CMY as a last resort.
|
||||
//! CMY as a last resort. The black point, which source black separates to and which displays as
|
||||
//! black with black-point compensation, is [`BlackGeneration::black_point_k`] black with neutral
|
||||
//! CMY filling the TAC. With compensation, a build darker than it in every XYZ channel also
|
||||
//! displays as black (see [`GenericCmyk::display_xyz`]).
|
||||
//! * **Rendering intents:** colorimetric intents map the source white to paper (relative) or not
|
||||
//! (absolute) and clip; perceptual applies black-point compensation plus soft chroma compression
|
||||
//! against a gamut boundary descriptor (segment maxima of the forward model); saturation keeps
|
||||
@@ -24,50 +31,82 @@ use std::sync::OnceLock;
|
||||
use super::Intent;
|
||||
use super::lab::{D50, Lab, delta_e2000, lab_to_xyz, srgb_to_lab, xyz_to_lab, xyz_to_srgb};
|
||||
|
||||
/// Black generation strength.
|
||||
/// Black generation.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct BlackGeneration {
|
||||
/// Grey component below which no black is generated.
|
||||
pub start: f32,
|
||||
/// Maximum black.
|
||||
pub max_k: f32,
|
||||
/// Curve exponent (>1 = lighter black in the midtones).
|
||||
pub gamma: f32,
|
||||
/// The black curve as `(x, K)` knots with rising `x`, read by linear interpolation. `x` is the
|
||||
/// gray component of the solve without black plus [`Self::shortfall`] per L* point by which
|
||||
/// that solve stays lighter than the target.
|
||||
pub curve: [(f32, f32); 13],
|
||||
/// Added to the gray component for each L* point the black-free solve stays too light.
|
||||
pub shortfall: f32,
|
||||
/// Black of the black point, whose CMY is neutral and fills the TAC.
|
||||
pub black_point_k: f32,
|
||||
}
|
||||
|
||||
/// Parameters of the parametric press model.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GenericCmykParams {
|
||||
pub name: &'static str,
|
||||
/// Paper color (absolute Lab, D50).
|
||||
pub paper: Lab,
|
||||
/// Solid overprints, Demichel order: C, M, CM, Y, CY, MY, CMY.
|
||||
pub solids: [Lab; 7],
|
||||
pub black: Lab,
|
||||
/// Dot gain at 50% per ink (C, M, Y, K).
|
||||
pub dot_gain: [f32; 4],
|
||||
/// Media-relative Lab of the solids and overprints, Demichel order (index `c | m<<1 | y<<2 |
|
||||
/// k<<3`, paper left out): C, M, CM, Y, CY, MY, CMY, then K, CK, MK, CMK, YK, CYK, MYK, CMYK.
|
||||
pub primaries: [Lab; 15],
|
||||
/// Tone value increase at 50% per ink (C, M, Y, K).
|
||||
pub tvi50: [f32; 4],
|
||||
/// Tone value increase at 40% per ink (C, M, Y, K).
|
||||
pub tvi40: [f32; 4],
|
||||
/// Total area coverage limit (sum of inks, 1.0 = 100%).
|
||||
pub tac: f32,
|
||||
pub bg: BlackGeneration,
|
||||
}
|
||||
|
||||
/// Rounded, typical SWOP-like values (not measured data).
|
||||
/// The built-in SWOP-like press: TR 001 tone value increase, a 300% ink limit, and VectorCraft's
|
||||
/// own paper, primaries and black curve.
|
||||
pub fn swop_like() -> GenericCmykParams {
|
||||
GenericCmykParams {
|
||||
name: super::GENERIC_CMYK,
|
||||
paper: Lab::new(93.0, -0.5, 2.5),
|
||||
solids: [
|
||||
Lab::new(55.0, -37.0, -50.0), // C
|
||||
Lab::new(48.0, 74.0, -3.0), // M
|
||||
Lab::new(24.0, 22.0, -46.0), // CM (blue)
|
||||
Lab::new(89.0, -5.0, 93.0), // Y
|
||||
Lab::new(50.0, -65.0, 27.0), // CY (green)
|
||||
Lab::new(47.0, 68.0, 48.0), // MY (red)
|
||||
Lab::new(24.0, 1.0, 0.0), // CMY
|
||||
primaries: [
|
||||
Lab::new(65.7, -42.6, -47.2), // C
|
||||
Lab::new(55.5, 76.2, -9.4), // M
|
||||
Lab::new(31.1, 20.3, -49.7), // CM (blue)
|
||||
Lab::new(96.2, -7.0, 90.1), // Y
|
||||
Lab::new(61.0, -68.4, 30.1), // CY (green)
|
||||
Lab::new(55.0, 69.8, 45.0), // MY (red)
|
||||
Lab::new(28.3, 0.7, -0.5), // CMY
|
||||
Lab::new(21.5, 0.8, -0.9), // K
|
||||
Lab::new(15.9, -8.4, -10.0), // CK
|
||||
Lab::new(14.7, 15.4, -1.0), // MK
|
||||
Lab::new(11.2, 8.9, -6.6), // CMK
|
||||
Lab::new(20.2, -2.4, 12.0), // YK
|
||||
Lab::new(15.7, -14.6, 4.6), // CYK
|
||||
Lab::new(14.5, 11.2, 5.7), // MYK
|
||||
Lab::new(11.0, -0.7, 0.1), // CMYK
|
||||
],
|
||||
black: Lab::new(19.0, 0.5, 0.5),
|
||||
dot_gain: [0.20, 0.20, 0.20, 0.22],
|
||||
tvi50: [0.200, 0.176, 0.168, 0.216],
|
||||
tvi40: [0.200, 0.173, 0.167, 0.219],
|
||||
tac: 3.0,
|
||||
bg: BlackGeneration { start: 0.1, max_k: 0.95, gamma: 1.25 },
|
||||
bg: BlackGeneration {
|
||||
curve: [
|
||||
(0.0, 0.0),
|
||||
(0.25, 0.0),
|
||||
(0.35, 0.006),
|
||||
(0.45, 0.059),
|
||||
(0.55, 0.139),
|
||||
(0.65, 0.23),
|
||||
(0.75, 0.322),
|
||||
(0.85, 0.41),
|
||||
(0.95, 0.511),
|
||||
(1.05, 0.6),
|
||||
(1.2, 0.733),
|
||||
(1.35, 0.858),
|
||||
(1.5, 1.0),
|
||||
],
|
||||
shortfall: 0.03,
|
||||
black_point_k: 0.9,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,11 +122,12 @@ const GBD_H: usize = 72; // 5° bins
|
||||
|
||||
pub struct GenericCmyk {
|
||||
pub params: GenericCmykParams,
|
||||
/// XYZ of the 8 CMY primaries (index = c | m<<1 | y<<2), without and with K.
|
||||
prim: [[f32; 3]; 8],
|
||||
prim_k: [[f32; 3]; 8],
|
||||
/// Media-relative XYZ of the 16 primaries (index = c | m<<1 | y<<2 | k<<3; 0 is paper).
|
||||
prim: [[f32; 3]; 16],
|
||||
/// Shape `s` of each ink's tone curve, from its 40% and 50% tone value increase.
|
||||
skew: [f32; 4],
|
||||
paper_xyz: [f32; 3],
|
||||
/// Media-relative XYZ of the darkest printable black (for black-point compensation).
|
||||
/// Media-relative XYZ of the black point (for black-point compensation).
|
||||
black_rel: [f32; 3],
|
||||
gbd: OnceLock<Gbd>,
|
||||
}
|
||||
@@ -95,37 +135,17 @@ pub struct GenericCmyk {
|
||||
impl GenericCmyk {
|
||||
pub fn new(params: GenericCmykParams) -> Self {
|
||||
let paper_xyz = lab_to_xyz(params.paper);
|
||||
let mut prim = [[0.0f32; 3]; 8];
|
||||
prim[0] = paper_xyz;
|
||||
for (p, lab) in prim[1..].iter_mut().zip(params.solids.iter()) {
|
||||
*p = lab_to_xyz(*lab);
|
||||
let mut prim = [D50; 16];
|
||||
for (p, lab) in prim[1..].iter_mut().zip(params.primaries.iter()) {
|
||||
*p = lab_to_xyz(*lab).map(|v| v.max(1e-6));
|
||||
}
|
||||
let k_xyz = lab_to_xyz(params.black);
|
||||
// Black over other inks: optical densities add, but saturate towards a maximum density
|
||||
// (ink trapping / surface reflection), normalised so that K on paper is exact.
|
||||
const D_MAX: f32 = 2.0;
|
||||
let sat = |d: f32| D_MAX * (1.0 - (-d / D_MAX).exp());
|
||||
let mut prim_k = [[0.0f32; 3]; 8];
|
||||
for i in 0..8 {
|
||||
for ch in 0..3 {
|
||||
let di = -(prim[i][ch] / paper_xyz[ch]).max(1e-6).log10();
|
||||
let dk = -(k_xyz[ch] / paper_xyz[ch]).max(1e-6).log10();
|
||||
let d = sat(di + dk) * dk / sat(dk).max(1e-6);
|
||||
prim_k[i][ch] = paper_xyz[ch] * 10f32.powf(-d.max(di));
|
||||
}
|
||||
}
|
||||
let mut g = Self { params, prim, prim_k, paper_xyz, black_rel: [0.0; 3], gbd: OnceLock::new() };
|
||||
// Darkest black within TAC: search a few rich blacks.
|
||||
let mut best = [1.0f32; 3];
|
||||
for k in [0.8f32, 0.9, 1.0] {
|
||||
let rest = (g.params.tac - k).max(0.0) / 3.0;
|
||||
let cmy = rest.min(1.0);
|
||||
let x = g.to_xyz_rel([cmy, cmy, cmy, k]);
|
||||
if x[1] < best[1] {
|
||||
best = x;
|
||||
}
|
||||
}
|
||||
g.black_rel = best;
|
||||
// The curve's increase at 40% is 0.96·g·(1 − 0.2·s), so `s` follows from the 40% value.
|
||||
let skew = [0, 1, 2, 3].map(|i| {
|
||||
let g = params.tvi50[i];
|
||||
if g > 1e-6 { (1.0 - params.tvi40[i] / (0.96 * g)) / 0.2 } else { 0.0 }
|
||||
});
|
||||
let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], gbd: OnceLock::new() };
|
||||
g.black_rel = g.to_xyz_rel(g.black_point_build());
|
||||
g
|
||||
}
|
||||
|
||||
@@ -133,35 +153,81 @@ impl GenericCmyk {
|
||||
self.params.name
|
||||
}
|
||||
|
||||
fn gain(a: f32, g: f32) -> f32 {
|
||||
let a = a.clamp(0.0, 1.0);
|
||||
(a + 4.0 * g * a * (1.0 - a)).clamp(0.0, 1.0)
|
||||
/// The black point: [`BlackGeneration::black_point_k`] black, with C, M and Y
|
||||
/// chosen so that they fill the TAC and the color is neutral (a* = b* = 0).
|
||||
pub fn black_point_build(&self) -> [f32; 4] {
|
||||
let k = self.params.bg.black_point_k.clamp(0.0, 1.0);
|
||||
let rest = (self.params.tac - k).clamp(0.0, 3.0);
|
||||
let build = |c: f32, m: f32| [c, m, (rest - c - m).clamp(0.0, 1.0), k];
|
||||
let ab = |c: f32, m: f32| {
|
||||
let l = self.to_lab_rel(build(c, m));
|
||||
[l.a, l.b]
|
||||
};
|
||||
let lo = (rest - 2.0).max(0.0);
|
||||
let hi = rest.min(1.0);
|
||||
let (mut c, mut m) = ((rest / 3.0).clamp(lo, hi), (rest / 3.0).clamp(lo, hi));
|
||||
for _ in 0..30 {
|
||||
let r = ab(c, m);
|
||||
if r[0].abs() + r[1].abs() < 1e-4 {
|
||||
break;
|
||||
}
|
||||
let h = 1e-3;
|
||||
let rc = ab(c - h, m);
|
||||
let rm = ab(c, m - h);
|
||||
let j = [[(r[0] - rc[0]) / h, (r[0] - rm[0]) / h], [(r[1] - rc[1]) / h, (r[1] - rm[1]) / h]];
|
||||
let det = j[0][0] * j[1][1] - j[0][1] * j[1][0];
|
||||
if det.abs() < 1e-9 {
|
||||
break;
|
||||
}
|
||||
let dc = (-r[0] * j[1][1] + r[1] * j[0][1]) / det;
|
||||
let dm = (-r[1] * j[0][0] + r[0] * j[1][0]) / det;
|
||||
c = (c + dc.clamp(-0.1, 0.1)).clamp(lo, hi);
|
||||
m = (m + dm.clamp(-0.1, 0.1)).clamp(lo, hi);
|
||||
// Yellow takes the rest, so keep it within 0..1 as well.
|
||||
let y = rest - c - m;
|
||||
if y > 1.0 {
|
||||
c += (y - 1.0) / 2.0;
|
||||
m += (y - 1.0) / 2.0;
|
||||
} else if y < 0.0 {
|
||||
c += y / 2.0;
|
||||
m += y / 2.0;
|
||||
}
|
||||
c = c.clamp(lo, hi);
|
||||
m = m.clamp(lo, hi);
|
||||
}
|
||||
build(c.clamp(lo, hi), m.clamp(lo, hi))
|
||||
}
|
||||
|
||||
/// Effective dot area of ink `i` at nominal area `a`: the TR 001-style tone curve.
|
||||
fn gain(&self, i: usize, a: f32) -> f32 {
|
||||
let a = if a.is_finite() { a.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let g = self.params.tvi50[i];
|
||||
(a + 4.0 * g * a * (1.0 - a) * (1.0 + self.skew[i] * (2.0 * a - 1.0))).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// CMYK (0..1) → absolute XYZ (D50).
|
||||
pub fn to_xyz(&self, cmyk: [f32; 4]) -> [f32; 3] {
|
||||
let dg = self.params.dot_gain;
|
||||
let c = Self::gain(cmyk[0], dg[0]);
|
||||
let m = Self::gain(cmyk[1], dg[1]);
|
||||
let y = Self::gain(cmyk[2], dg[2]);
|
||||
let k = Self::gain(cmyk[3], dg[3]);
|
||||
let mut out = [0.0f32; 3];
|
||||
for i in 0..8 {
|
||||
let w = (if i & 1 != 0 { c } else { 1.0 - c }) * (if i & 2 != 0 { m } else { 1.0 - m }) * (if i & 4 != 0 { y } else { 1.0 - y });
|
||||
if w == 0.0 {
|
||||
continue;
|
||||
}
|
||||
for (ch, o) in out.iter_mut().enumerate() {
|
||||
*o += w * ((1.0 - k) * self.prim[i][ch] + k * self.prim_k[i][ch]);
|
||||
}
|
||||
}
|
||||
out
|
||||
let x = self.to_xyz_rel(cmyk);
|
||||
[x[0] * self.paper_xyz[0] / D50[0], x[1] * self.paper_xyz[1] / D50[1], x[2] * self.paper_xyz[2] / D50[2]]
|
||||
}
|
||||
|
||||
/// Media-relative XYZ (paper = D50 white).
|
||||
pub fn to_xyz_rel(&self, cmyk: [f32; 4]) -> [f32; 3] {
|
||||
let x = self.to_xyz(cmyk);
|
||||
[x[0] * D50[0] / self.paper_xyz[0], x[1] * D50[1] / self.paper_xyz[1], x[2] * D50[2] / self.paper_xyz[2]]
|
||||
let e = [0, 1, 2, 3].map(|i| self.gain(i, cmyk[i]));
|
||||
let mut out = [0.0f32; 3];
|
||||
for (i, p) in self.prim.iter().enumerate() {
|
||||
let mut w = 1.0;
|
||||
for (bit, a) in e.iter().enumerate() {
|
||||
w *= if i & (1 << bit) != 0 { *a } else { 1.0 - a };
|
||||
}
|
||||
if w == 0.0 {
|
||||
continue;
|
||||
}
|
||||
for (o, v) in out.iter_mut().zip(p) {
|
||||
*o += w * v;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn to_lab_rel(&self, cmyk: [f32; 4]) -> Lab {
|
||||
@@ -174,7 +240,9 @@ impl GenericCmyk {
|
||||
/// Display XYZ: media-relative (paper shows as white) or absolute (simulate paper colour).
|
||||
/// With `bpc` (media-relative only) the press black displays as black, undoing the
|
||||
/// compensation [`Self::gamut_map`] applies on the way in, so sRGB black separated to the
|
||||
/// darkest rich black shows as black again.
|
||||
/// black point shows as black again. Each XYZ channel is clamped at 0 on its own, so a build
|
||||
/// darker than the black point in every channel shows as black, and one darker in only some
|
||||
/// channels shows as a colored near-black.
|
||||
pub fn display_xyz(&self, cmyk: [f32; 4], absolute: bool, bpc: bool) -> [f32; 3] {
|
||||
if absolute {
|
||||
return self.to_xyz(cmyk);
|
||||
@@ -192,7 +260,7 @@ impl GenericCmyk {
|
||||
xyz_to_srgb(self.display_xyz(cmyk, absolute, bpc))
|
||||
}
|
||||
|
||||
/// Lab of the darkest printable black (media-relative).
|
||||
/// Lab of the black point (media-relative), see [`Self::black_point_build`].
|
||||
pub fn black_point(&self) -> Lab {
|
||||
xyz_to_lab(self.black_rel)
|
||||
}
|
||||
@@ -231,6 +299,21 @@ impl GenericCmyk {
|
||||
}
|
||||
g[p] = -(0..3).map(|i| j[i][p] * r[i]).sum::<f32>();
|
||||
}
|
||||
// An ink at a bound whose descent direction points out of the box stays where it is; the step moves the other inks.
|
||||
for p in 0..3 {
|
||||
if (x[p] <= 0.0 && g[p] < 0.0) || (x[p] >= 1.0 && g[p] > 0.0) {
|
||||
a[p] = [0.0; 3];
|
||||
for row in &mut a {
|
||||
row[p] = 0.0;
|
||||
}
|
||||
a[p][p] = 1.0;
|
||||
g[p] = 0.0;
|
||||
}
|
||||
}
|
||||
// Every ink is held at a bound, or the gradient is zero: no step can lower the error.
|
||||
if g == [0.0; 3] {
|
||||
break;
|
||||
}
|
||||
let mut improved = false;
|
||||
for _ in 0..8 {
|
||||
let mut al = a;
|
||||
@@ -268,12 +351,21 @@ impl GenericCmyk {
|
||||
rgb.map(|v| ((1.0 - v - k) / d).clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
fn black_for_grey(&self, grey: f32) -> f32 {
|
||||
let bg = self.params.bg;
|
||||
if grey <= bg.start {
|
||||
return 0.0;
|
||||
/// Black for `x` on the black curve (see [`BlackGeneration::curve`]).
|
||||
fn black_for(&self, x: f32) -> f32 {
|
||||
let curve = &self.params.bg.curve;
|
||||
let mut prev = curve[0];
|
||||
if x <= prev.0 {
|
||||
return prev.1.clamp(0.0, 1.0);
|
||||
}
|
||||
(((grey - bg.start) / (1.0 - bg.start)).clamp(0.0, 1.0).powf(bg.gamma) * bg.max_k).clamp(0.0, 1.0)
|
||||
for &(kx, kk) in &curve[1..] {
|
||||
if x <= kx {
|
||||
let t = if kx > prev.0 { (x - prev.0) / (kx - prev.0) } else { 1.0 };
|
||||
return (prev.1 + (kk - prev.1) * t).clamp(0.0, 1.0);
|
||||
}
|
||||
prev = (kx, kk);
|
||||
}
|
||||
prev.1.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// Separate a media-relative Lab (already gamut-mapped) into CMYK with GCR/UCR and the TAC limit.
|
||||
@@ -282,13 +374,10 @@ impl GenericCmyk {
|
||||
return [0.0; 4];
|
||||
}
|
||||
let cmy0 = self.solve_cmy(target, 0.0, Self::initial_cmy(target, 0.0));
|
||||
let grey = cmy0[0].min(cmy0[1]).min(cmy0[2]);
|
||||
let mut k = self.black_for_grey(grey);
|
||||
// If CMY alone can't get dark enough, black must carry the rest.
|
||||
let gray = cmy0[0].min(cmy0[1]).min(cmy0[2]);
|
||||
// When CMY alone can't get dark enough, black carries the rest.
|
||||
let l0 = self.to_lab_rel([cmy0[0], cmy0[1], cmy0[2], 0.0]).l;
|
||||
if l0 > target.l + 1.0 {
|
||||
k = k.max(((l0 - target.l) / l0.max(1.0)).clamp(0.0, 1.0));
|
||||
}
|
||||
let mut k = self.black_for(gray + self.params.bg.shortfall * (l0 - target.l).max(0.0));
|
||||
let mut cmy = if k > 0.0 { self.solve_cmy(target, k, Self::initial_cmy(target, k)) } else { cmy0 };
|
||||
// UCR: trade CMY for K until within the TAC limit.
|
||||
for _ in 0..6 {
|
||||
|
||||
@@ -106,6 +106,12 @@ impl IccProfile {
|
||||
if !localized_text_fits(bytes) {
|
||||
return Err(CmsError::BadProfile(format!("its localized names take more than {} KB", MAX_LOCALIZED_TEXT >> 10)));
|
||||
}
|
||||
if let Some(tag) = repeated_tag(bytes) {
|
||||
return Err(CmsError::BadProfile(format!(
|
||||
"its tag table lists the `{}` tag more than once",
|
||||
String::from_utf8_lossy(&tag.to_be_bytes())
|
||||
)));
|
||||
}
|
||||
let p = ColorProfile::new_from_slice(bytes).map_err(|e| CmsError::BadProfile(format!("{e:?}")))?;
|
||||
Ok(Self { source: bytes.to_vec(), ..Self::from_profile(name, p)? })
|
||||
}
|
||||
@@ -417,6 +423,23 @@ pub(super) fn gray_profile(name: &str) -> ColorProfile {
|
||||
labelled(p, name)
|
||||
}
|
||||
|
||||
/// The first tag signature the tag table of ICC `bytes` lists twice, which the ICC
|
||||
/// specification forbids. moxcms parses every entry of the table, so a profile listing one
|
||||
/// description, copyright or table tag thousands of times, each pointing at the same large data,
|
||||
/// would decode and copy that data once per entry. A table it can't read is left to moxcms.
|
||||
pub(crate) fn repeated_tag(bytes: &[u8]) -> Option<u32> {
|
||||
let be32 = |at: usize| bytes.get(at..at.checked_add(4)?).map(|v| u32::from_be_bytes([v[0], v[1], v[2], v[3]]));
|
||||
let tags = be32(128)? as usize;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for i in 0..tags {
|
||||
let sig = be32(i.checked_mul(12)?.checked_add(132)?)?;
|
||||
if !seen.insert(sig) {
|
||||
return Some(sig);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Most bytes of UTF-16 the localized names (`mluc` tags) of a profile may take together.
|
||||
const MAX_LOCALIZED_TEXT: usize = 1 << 20;
|
||||
|
||||
|
||||
@@ -245,8 +245,8 @@ fn loads_system_cmyk_icc() {
|
||||
assert_eq!(c.cmyk_to_srgb([0.0; 4], false).map(|v| (v * 255.0).round() as u8), [255, 255, 255]);
|
||||
}
|
||||
|
||||
/// With black-point compensation, sRGB black separates to the press's darkest black and that black
|
||||
/// displays as black again (hex 000000 -> C67 M67 Y67 K100 -> 000000, not a dark grey).
|
||||
/// With black-point compensation, sRGB black separates to the press's black point and that black
|
||||
/// displays as black again (hex 000000 -> C75 M68 Y67 K90 -> 000000, not a dark gray).
|
||||
#[test]
|
||||
fn generic_cmyk_black_round_trips_with_bpc() {
|
||||
let c = cms();
|
||||
@@ -259,6 +259,125 @@ fn generic_cmyk_black_round_trips_with_bpc() {
|
||||
assert!(raw.iter().all(|v| *v > 0.05), "{raw:?}");
|
||||
}
|
||||
|
||||
/// Each ink's 40% and 50% tints gain like CGATS TR 001 (SWOP): the colorimetric tone value increase
|
||||
/// (Murray–Davies on X for cyan, Y for magenta and black, Z for yellow) is C 20.0, M 17.6, Y 16.8 and
|
||||
/// K 21.6 points at 50%, and C 20.0, M 17.3, Y 16.7 and K 21.9 points at 40%.
|
||||
#[test]
|
||||
fn generic_cmyk_tints_gain_like_tr001() {
|
||||
let g = generic();
|
||||
let tvi = |ink: usize, a: f32| {
|
||||
let ch = [0, 1, 2, 1][ink];
|
||||
let mut cmyk = [0.0f32; 4];
|
||||
cmyk[ink] = a;
|
||||
let tint = g.to_xyz_rel(cmyk)[ch];
|
||||
cmyk[ink] = 1.0;
|
||||
let solid = g.to_xyz_rel(cmyk)[ch];
|
||||
let paper = g.to_xyz_rel([0.0; 4])[ch];
|
||||
(paper - tint) / (paper - solid) - a
|
||||
};
|
||||
for (ink, (at50, at40)) in [(0.200, 0.200), (0.176, 0.173), (0.168, 0.167), (0.216, 0.219)].into_iter().enumerate() {
|
||||
assert!((tvi(ink, 0.5) - at50).abs() < 0.002, "ink {ink} at 50%: {}", tvi(ink, 0.5));
|
||||
assert!((tvi(ink, 0.4) - at40).abs() < 0.002, "ink {ink} at 40%: {}", tvi(ink, 0.4));
|
||||
}
|
||||
}
|
||||
|
||||
/// More of any ink never makes a Generic CMYK color lighter, in any XYZ channel: on a 10% grid of
|
||||
/// builds within the 300% ink limit, adding 10% of one ink keeps X, Y and Z or lowers them.
|
||||
#[test]
|
||||
fn generic_cmyk_more_ink_is_never_lighter() {
|
||||
let g = generic();
|
||||
let steps = (0..=10).map(|i| i as f32 / 10.0);
|
||||
for c in steps.clone() {
|
||||
for m in steps.clone() {
|
||||
for y in steps.clone() {
|
||||
for k in steps.clone() {
|
||||
let base = [c, m, y, k];
|
||||
if base.iter().sum::<f32>() > 3.0 - 0.1 + 1e-4 {
|
||||
continue;
|
||||
}
|
||||
let x0 = g.to_xyz_rel(base);
|
||||
for ink in 0..4 {
|
||||
if base[ink] >= 1.0 {
|
||||
continue;
|
||||
}
|
||||
let mut more = base;
|
||||
more[ink] += 0.1;
|
||||
let x1 = g.to_xyz_rel(more);
|
||||
assert!((0..3).all(|ch| x1[ch] <= x0[ch] + 1e-5), "{base:?} plus ink {ink}: {x0:?} to {x1:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// sRGB black separates to 90% black under neutral CMY that fills the 300% ink limit, light grays
|
||||
/// carry no black, and black rises steadily from the light end of the gray ramp to the dark end.
|
||||
#[test]
|
||||
fn generic_cmyk_black_generation_follows_the_black_curve() {
|
||||
let c = cms();
|
||||
let black = c.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric);
|
||||
assert!((black[3] - 0.9).abs() < 0.005, "{black:?}");
|
||||
assert!((black.iter().sum::<f32>() - 3.0).abs() < 0.01, "{black:?}");
|
||||
let lab = c.cmyk_to_lab(black);
|
||||
assert!(lab.a.abs() < 0.05 && lab.b.abs() < 0.05, "neutral: {lab:?}");
|
||||
let light = c.srgb_to_cmyk([0.7; 3], Intent::RelativeColorimetric);
|
||||
assert_eq!(light[3], 0.0, "{light:?}");
|
||||
let mut prev = 0.0;
|
||||
for v in (0..=50).rev().map(|i| i as f32 / 50.0) {
|
||||
let k = c.srgb_to_cmyk([v; 3], Intent::RelativeColorimetric)[3];
|
||||
assert!(k >= prev - 1e-4, "gray {v}: K {k} after {prev}");
|
||||
prev = k;
|
||||
}
|
||||
}
|
||||
|
||||
/// A color whose solve holds an ink at a bound separates to the same inks when its values change by
|
||||
/// a few float steps: hex f01482 (cyan held at 0) and hex ed1e79 (magenta held at 100%), each with
|
||||
/// its red stepped one `f32` at a time over 4,001 values (about 0.00024 in all), stay within 0.001
|
||||
/// on every ink.
|
||||
#[test]
|
||||
fn generic_cmyk_separates_nearby_colors_at_the_gamut_edge_alike() {
|
||||
let c = cms();
|
||||
let spread = |pink: [f32; 3]| {
|
||||
let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]);
|
||||
for step in -2000i32..=2000 {
|
||||
let mut rgb = pink;
|
||||
rgb[0] = f32::from_bits(pink[0].to_bits().wrapping_add_signed(step));
|
||||
let ink = c.srgb_to_cmyk(rgb, Intent::RelativeColorimetric);
|
||||
for i in 0..4 {
|
||||
lo[i] = lo[i].min(ink[i]);
|
||||
hi[i] = hi[i].max(ink[i]);
|
||||
}
|
||||
}
|
||||
(lo, hi)
|
||||
};
|
||||
let (lo, hi) = spread([240.0f32 / 255.0, 20.0 / 255.0, 130.0 / 255.0]);
|
||||
assert!((0..4).all(|i| hi[i] - lo[i] < 1e-3), "{lo:?} to {hi:?}");
|
||||
assert_eq!(lo[0], 0.0, "{lo:?}");
|
||||
let (lo, hi) = spread([237.0f32 / 255.0, 30.0 / 255.0, 121.0 / 255.0]);
|
||||
assert!((0..4).all(|i| hi[i] - lo[i] < 1e-3), "{lo:?} to {hi:?}");
|
||||
assert_eq!(hi[1], 1.0, "{hi:?}");
|
||||
}
|
||||
|
||||
/// A color whose solve holds cyan and magenta at 1 separates to the same inks when its values change
|
||||
/// by a few float steps: sRGB (0, 0, 0.25) with its blue stepped one `f32` at a time over 121 values
|
||||
/// stays within 0.001 on every ink.
|
||||
#[test]
|
||||
fn generic_cmyk_separates_nearby_colors_with_inks_at_full_alike() {
|
||||
let c = cms();
|
||||
let (mut lo, mut hi) = ([f32::MAX; 4], [f32::MIN; 4]);
|
||||
for step in -60i32..=60 {
|
||||
let blue = f32::from_bits(0.25f32.to_bits().wrapping_add_signed(step));
|
||||
let ink = c.srgb_to_cmyk([0.0, 0.0, blue], Intent::RelativeColorimetric);
|
||||
for i in 0..4 {
|
||||
lo[i] = lo[i].min(ink[i]);
|
||||
hi[i] = hi[i].max(ink[i]);
|
||||
}
|
||||
}
|
||||
assert!((0..4).all(|i| hi[i] - lo[i] < 1e-3), "{lo:?} to {hi:?}");
|
||||
assert_eq!((lo[0], lo[1]), (1.0, 1.0), "{lo:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lab_colours_round_trip_through_the_cms() {
|
||||
let c = cms_no_bpc();
|
||||
|
||||
@@ -181,6 +181,32 @@ fn aliased_localized_names_are_refused() {
|
||||
assert!(!super::icc::localized_text_fits(&profile(4096, 64 << 10)));
|
||||
}
|
||||
|
||||
/// A tag table that lists one tag many times, every entry pointing at the same long text, is
|
||||
/// refused before moxcms decodes the text once per entry; distinct tags pass.
|
||||
#[test]
|
||||
fn repeated_tags_are_refused() {
|
||||
let profile = |sigs: &[&[u8; 4]], text: usize| {
|
||||
let mut b = vec![0u8; 128];
|
||||
b.extend((sigs.len() as u32).to_be_bytes());
|
||||
let tag_at = 128 + 4 + 12 * sigs.len();
|
||||
let size = 8 + text;
|
||||
for sig in sigs {
|
||||
b.extend(*sig);
|
||||
b.extend((tag_at as u32).to_be_bytes());
|
||||
b.extend((size as u32).to_be_bytes());
|
||||
}
|
||||
b.extend(b"text");
|
||||
b.extend([0; 4]);
|
||||
b.extend(vec![b'a'; text]);
|
||||
b
|
||||
};
|
||||
assert_eq!(super::icc::repeated_tag(&profile(&[b"desc", b"cprt", b"dmdd"], 64)), None);
|
||||
let many: Vec<&[u8; 4]> = std::iter::repeat_n(b"desc", 4096).collect();
|
||||
let bytes = profile(&many, 256 << 10);
|
||||
assert_eq!(super::icc::repeated_tag(&bytes), Some(u32::from_be_bytes(*b"desc")));
|
||||
assert!(matches!(super::icc::IccProfile::from_bytes(None, &bytes), Err(super::CmsError::BadProfile(_))));
|
||||
}
|
||||
|
||||
/// Reloading an RGB profile under the name it had (a new file for "My RGB") changes what CMYK
|
||||
/// converts to in it: the direct CMYK → RGB transform isn't kept from the old file.
|
||||
#[test]
|
||||
|
||||
@@ -79,13 +79,16 @@ const PERCEPTUAL_TOLERANCE: f32 = 0.4 / 255.0;
|
||||
/// halved to keep within [`PERCEPTUAL_TOLERANCE`].
|
||||
const PERCEPTUAL_DEPTH: u32 = 10;
|
||||
/// How many times [`Gradient::ink_tints`] halves the range of tints it searches: to within
|
||||
/// 1/65536 of a tint, finer than the 1/255 steps PDF writes.
|
||||
/// 1/65536 of a tint.
|
||||
const TINT_STEPS: u32 = 16;
|
||||
/// The least OKLab lightness by which an ink at 100% must differ from paper white for
|
||||
/// [`Gradient::ink_tints`] to tell its tints apart by lightness.
|
||||
const MIN_INK_LIGHTNESS_SPAN: f64 = 1.0 / 255.0;
|
||||
/// Most stops on a gradient's curve that [`Gradient::ink_tints`] finds tints for.
|
||||
const MAX_INK_TINTS: usize = 4096;
|
||||
/// How many even steps [`Gradient::ink_mixes`] checks the lightness of two stops' display RGB mix
|
||||
/// at, to tell whether it moves steadily from one stop's lightness to the other's.
|
||||
const INK_MIX_STEPS: u32 = 64;
|
||||
|
||||
/// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly
|
||||
/// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved
|
||||
@@ -148,16 +151,23 @@ pub struct GradientStop {
|
||||
/// Tint of the linked swatch (0..1; 1 without a link), as on a solid paint.
|
||||
#[serde(default = "crate::full_tint", skip_serializing_if = "crate::is_full_tint")]
|
||||
pub tint: f32,
|
||||
/// Process inks (C, M, Y, K, 0..1) printed together with the linked spot swatch's tint: a
|
||||
/// DeviceN colour of a file that mixes a spot ink with process plates. `color` is how the mix
|
||||
/// looks; separations print the spot ink at `tint` and these plates. `None`: the ink alone.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub plates: Option<[f32; 4]>,
|
||||
}
|
||||
|
||||
impl GradientStop {
|
||||
/// An opaque, unlinked stop of `color` at `offset` with a centred midpoint.
|
||||
pub fn new(offset: f32, color: Color) -> Self {
|
||||
Self { offset, color, opacity: 1.0, midpoint: 0.5, swatch: None, tint: 1.0 }
|
||||
Self { offset, color, opacity: 1.0, midpoint: 0.5, swatch: None, tint: 1.0, plates: None }
|
||||
}
|
||||
/// Give the stop `color`, linked to `link` (a global swatch and tint) or unlinked.
|
||||
/// Give the stop `color`, linked to `link` (a global swatch and tint) or unlinked, without
|
||||
/// process plates.
|
||||
pub fn set_color(&mut self, color: Color, link: Option<(String, f32)>) {
|
||||
self.color = color;
|
||||
self.plates = None;
|
||||
(self.swatch, self.tint) = match link {
|
||||
Some((n, t)) => (Some(n), t),
|
||||
None => (None, 1.0),
|
||||
@@ -175,6 +185,40 @@ fn between(a: &GradientStop, b: &GradientStop, t: f32, mix: &impl Fn(&Color, &Co
|
||||
(mix(&a.color, &b.color, v), a.opacity + (b.opacity - a.opacity) * v)
|
||||
}
|
||||
|
||||
/// For each pair of neighbouring stops (`k`, `k + 1`), the largest offset among stops `1..=k + 1`.
|
||||
/// [`Gradient::sample_with`] picks the first pair whose end offset `t` doesn't pass; that is the
|
||||
/// first pair whose reach `t` doesn't pass, and the reaches never decrease, so the pair is found by
|
||||
/// binary search whether or not the stops are in order.
|
||||
struct StopReach(Vec<f32>);
|
||||
|
||||
impl StopReach {
|
||||
fn new(stops: &[GradientStop]) -> Self {
|
||||
// `f32::max` skips a NaN offset, which `t <= offset` never chooses either.
|
||||
let reach = stops.iter().skip(1).scan(f32::NEG_INFINITY, |m, s| {
|
||||
*m = m.max(s.offset);
|
||||
Some(*m)
|
||||
});
|
||||
Self(reach.collect())
|
||||
}
|
||||
|
||||
/// What [`Gradient::sample_with`] gives at `t` for `stops`, the stops this was built from.
|
||||
fn sample_with(&self, stops: &[GradientStop], t: f32, mix: &impl Fn(&Color, &Color, f32) -> Color) -> (Color, f32) {
|
||||
let Some(first) = stops.first() else { return (Color::BLACK, 1.0) };
|
||||
if t <= first.offset {
|
||||
return (first.color, first.opacity);
|
||||
}
|
||||
let last = || stops.last().map_or((Color::BLACK, 1.0), |l| (l.color, l.opacity));
|
||||
if t.is_nan() {
|
||||
return last();
|
||||
}
|
||||
let k = self.0.partition_point(|r| *r < t);
|
||||
match (stops.get(k), stops.get(k + 1)) {
|
||||
(Some(a), Some(b)) => between(a, b, t, mix),
|
||||
_ => last(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn one() -> f32 {
|
||||
1.0
|
||||
}
|
||||
@@ -211,6 +255,12 @@ impl Gradient {
|
||||
pub fn sample(&self, t: f32) -> (Color, f32) {
|
||||
self.sample_with(t, |a, b, v| self.method.mix(a, b, v))
|
||||
}
|
||||
/// [`Self::sample`] for many points in no order (a gradient drawn pixel by pixel): the stops
|
||||
/// are prepared once, so each sample costs a binary search rather than a scan of the stops.
|
||||
pub fn sampler(&self) -> impl Fn(f32) -> (Color, f32) + '_ {
|
||||
let reach = StopReach::new(&self.stops);
|
||||
move |t| reach.sample_with(&self.stops, t, &|a, b, v| self.method.mix(a, b, v))
|
||||
}
|
||||
/// [`Self::sample`], a Classic gradient's neighbouring stop colours of one model mixed in it
|
||||
/// (CMYK stays CMYK; [`Color::lerp_keep_model`]) rather than in display RGB, a Perceptual
|
||||
/// gradient's as [`Self::sample`] mixes them.
|
||||
@@ -245,9 +295,11 @@ impl Gradient {
|
||||
/// the one before it stopped, so the work is the samples plus the stops, not their product.
|
||||
pub fn sample_increasing_with(&self, ts: impl IntoIterator<Item = f32>, mix: impl Fn(&Color, &Color, f32) -> Color) -> Vec<(Color, f32)> {
|
||||
let stops = &self.stops;
|
||||
// The shared index assumes ordered stops; others (a file's, unsorted) sample one by one.
|
||||
// The shared cursor assumes ordered stops; others (a file's, unsorted) look each sample up
|
||||
// in a [`StopReach`], so they cost a binary search each rather than a scan of the stops.
|
||||
if stops.windows(2).any(|w| w[1].offset < w[0].offset) {
|
||||
return ts.into_iter().map(|t| self.sample_with(t, &mix)).collect();
|
||||
let reach = StopReach::new(stops);
|
||||
return ts.into_iter().map(|t| reach.sample_with(stops, t, &mix)).collect();
|
||||
}
|
||||
let mut j = 0;
|
||||
ts.into_iter()
|
||||
@@ -277,8 +329,16 @@ impl Gradient {
|
||||
/// [`Self::expanded_stops`], each stop that stands for a midpoint with that midpoint (`None`
|
||||
/// on the gradient's own stops and a Perceptual gradient's other in-between stops).
|
||||
pub fn expanded(&self) -> impl Iterator<Item = (f32, Color, f32, Option<f32>)> + '_ {
|
||||
self.expanded_with_stops().map(|(t, c, o, mid, _)| (t, c, o, mid))
|
||||
}
|
||||
/// [`Self::expanded`], each of the gradient's own stops with its index in [`Self::stops`]
|
||||
/// (`None` on the stops in between).
|
||||
fn expanded_with_stops(&self) -> impl Iterator<Item = (f32, Color, f32, Option<f32>, Option<usize>)> + '_ {
|
||||
// Direct interpolation matches `sample` only for strictly increasing offsets.
|
||||
let increasing = self.stops.windows(2).all(|w| w[0].offset < w[1].offset);
|
||||
// Otherwise (repeated or unsorted offsets) each midpoint is looked up as `sample` would
|
||||
// find it, but by binary search: a scan of all the stops per midpoint cost their square.
|
||||
let reach = if increasing || !self.method.is_classic() { None } else { Some(StopReach::new(&self.stops)) };
|
||||
self.stops.iter().enumerate().flat_map(move |(i, s)| {
|
||||
let next = self.stops.get(i + 1);
|
||||
let off_centre = (s.midpoint - 0.5).abs() > 1e-3;
|
||||
@@ -288,8 +348,11 @@ impl Gradient {
|
||||
// Mixed from the two stops it lies between, as `sample` would: searching all the
|
||||
// stops again for each midpoint made many stops cost their square.
|
||||
let mix = |a: &Color, b: &Color, v| self.method.mix(a, b, v);
|
||||
let (c, o) = if increasing { between(s, n, t, &mix) } else { self.sample_with(t, mix) };
|
||||
(t, c, o, Some(s.midpoint))
|
||||
let (c, o) = match &reach {
|
||||
Some(reach) => reach.sample_with(&self.stops, t, &mix),
|
||||
None => between(s, n, t, &mix),
|
||||
};
|
||||
(t, c, o, Some(s.midpoint), None)
|
||||
});
|
||||
// Perceptual: stops along the mix (`v`) where a straight line would stray from it, the
|
||||
// midpoint (v = ½) among them, placed through the midpoint as [`Self::sample`] maps them.
|
||||
@@ -298,26 +361,27 @@ impl Gradient {
|
||||
let mid = v == 0.5;
|
||||
let t = curve_offset(s, n, v);
|
||||
let o = s.opacity + (n.opacity - s.opacity) * v;
|
||||
(t, self.method.mix(&s.color, &n.color, v), o, (mid && off_centre).then_some(s.midpoint))
|
||||
(t, self.method.mix(&s.color, &n.color, v), o, (mid && off_centre).then_some(s.midpoint), None)
|
||||
})
|
||||
});
|
||||
std::iter::once((s.offset, s.color, s.opacity, None)).chain(classic).chain(perceptual.into_iter().flatten())
|
||||
std::iter::once((s.offset, s.color, s.opacity, None, Some(i))).chain(classic).chain(perceptual.into_iter().flatten())
|
||||
})
|
||||
}
|
||||
/// A gradient of tints of one ink `ink` (its color at 100%; paper white is 0% of it) as
|
||||
/// (offset, tint, opacity) at each of [`Self::expanded_stops`]: the tint (0..1) whose OKLab
|
||||
/// lightness is the lightness of the color there, found to [`TINT_STEPS`] halvings. Mixed
|
||||
/// linearly between them, the tints follow a Perceptual gradient's curve. `None` when the
|
||||
/// ink's lightness is within [`MIN_INK_LIGHTNESS_SPAN`] of paper white's (a white or nearly
|
||||
/// white ink), so lightness does not tell its tints apart, and when the curve has more than
|
||||
/// [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
|
||||
pub fn ink_tints(&self, ink: &Color) -> Option<Vec<(f32, f32, f32)>> {
|
||||
/// lightness is the lightness of the color there, found to [`TINT_STEPS`] halvings, except at
|
||||
/// the gradient's own stops, which take their tints from `stop_tints` (one per stop, in
|
||||
/// order) where it has one. Mixed linearly between them, the tints follow a Perceptual
|
||||
/// gradient's curve. `None` when the ink's lightness is within [`MIN_INK_LIGHTNESS_SPAN`] of
|
||||
/// paper white's (a white or nearly white ink), so lightness does not tell its tints apart,
|
||||
/// and when the curve has more than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
|
||||
pub fn ink_tints(&self, ink: &Color, stop_tints: &[f32]) -> Option<Vec<(f32, f32, f32)>> {
|
||||
use crate::libraries::srgb_to_oklab;
|
||||
let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0];
|
||||
if lightness(&ink.tinted(0.0)) - lightness(ink) < MIN_INK_LIGHTNESS_SPAN {
|
||||
return None;
|
||||
}
|
||||
let curve: Vec<_> = self.expanded().take(MAX_INK_TINTS + 1).collect();
|
||||
let curve: Vec<_> = self.expanded_with_stops().take(MAX_INK_TINTS + 1).collect();
|
||||
if curve.len() > MAX_INK_TINTS {
|
||||
return None;
|
||||
}
|
||||
@@ -334,7 +398,7 @@ impl Gradient {
|
||||
}
|
||||
(lo + hi) / 2.0
|
||||
};
|
||||
Some(curve.into_iter().map(|(t, c, o, _)| (t, tint(&c), o)).collect())
|
||||
Some(curve.into_iter().map(|(t, c, o, _, i)| (t, i.and_then(|i| stop_tints.get(i).copied()).unwrap_or_else(|| tint(&c)), o)).collect())
|
||||
}
|
||||
/// Does the gradient's curve ([`Self::expanded`]) have at most [`MAX_INK_TINTS`] stops, so
|
||||
/// [`Self::ink_tints`] finds tints for it?
|
||||
@@ -347,8 +411,10 @@ impl Gradient {
|
||||
/// The weight is the one at which the two stops' colors mixed in display RGB have the OKLab
|
||||
/// lightness of the color on the curve there, found to [`TINT_STEPS`] halvings, or the mix
|
||||
/// position itself when the two colors' lightness differs by less than
|
||||
/// [`MIN_INK_LIGHTNESS_SPAN`]. `None` for a Classic gradient, and when the curve has more than
|
||||
/// [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
|
||||
/// [`MIN_INK_LIGHTNESS_SPAN`], or when the display RGB mix's lightness turns back somewhere
|
||||
/// on the way from one color's lightness to the other's (checked at [`INK_MIX_STEPS`] even
|
||||
/// steps), as from red to blue. `None` for a Classic gradient, and when the curve has more
|
||||
/// than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
|
||||
pub fn ink_mixes(&self) -> Option<Vec<(f32, usize, f32, f32)>> {
|
||||
use crate::libraries::srgb_to_oklab;
|
||||
if self.method.is_classic() || !self.fits_ink_tints() {
|
||||
@@ -360,8 +426,16 @@ impl Gradient {
|
||||
out.push((s.offset, i, 0.0, s.opacity));
|
||||
let Some(n) = self.stops.get(i + 1) else { continue };
|
||||
let (l0, l1) = (lightness(&s.color), lightness(&n.color));
|
||||
let mixed_lightness = |w: f32| lightness(&GradientMethod::Classic.mix(&s.color, &n.color, w));
|
||||
// The mix position itself when the lightness doesn't tell the mixes apart.
|
||||
let by_position = (l1 - l0).abs() < MIN_INK_LIGHTNESS_SPAN
|
||||
|| !(0..=INK_MIX_STEPS)
|
||||
.map(|k| mixed_lightness(k as f32 / INK_MIX_STEPS as f32))
|
||||
.collect::<Vec<_>>()
|
||||
.windows(2)
|
||||
.all(|w| (w[1] - w[0]) * (l1 - l0) >= 0.0);
|
||||
for v in perceptual_mixes(s, n) {
|
||||
let weight = if (l1 - l0).abs() < MIN_INK_LIGHTNESS_SPAN {
|
||||
let weight = if by_position {
|
||||
v
|
||||
} else {
|
||||
let want = lightness(&self.method.mix(&s.color, &n.color, v));
|
||||
@@ -369,7 +443,7 @@ impl Gradient {
|
||||
for _ in 0..TINT_STEPS {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
// The mix at `mid` has not yet gone from stop `i`'s lightness to the wanted one.
|
||||
if (lightness(&GradientMethod::Classic.mix(&s.color, &n.color, mid)) - want) * (l1 - l0) < 0.0 {
|
||||
if (mixed_lightness(mid) - want) * (l1 - l0) < 0.0 {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid;
|
||||
|
||||
@@ -23,6 +23,64 @@ fn increasing_samples_match_single_samples() {
|
||||
assert_eq!(g.sample_increasing_with(ts, Color::lerp_keep_model), one_by_one);
|
||||
}
|
||||
|
||||
/// The prepared sampler gives what sampling each position alone does, out-of-order stops included.
|
||||
#[test]
|
||||
fn the_sampler_matches_single_samples() {
|
||||
let stop = |offset: f32, hex: &str| GradientStop::new(offset, Color::from_hex(hex).unwrap());
|
||||
let g = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![stop(0.1, "#ff0000"), stop(0.4, "#00ff00"), stop(0.4, "#0000ff"), stop(0.2, "#ffff00"), stop(0.9, "#000000")],
|
||||
);
|
||||
let sample = g.sampler();
|
||||
for k in (0..=40).rev() {
|
||||
let t = k as f32 / 40.0;
|
||||
assert_eq!(sample(t), g.sample(t), "{t}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Looking stops up by their reach finds what scanning them does, for any order of offsets,
|
||||
/// repeated, out-of-order and NaN ones included, and for positions outside and between them.
|
||||
#[test]
|
||||
fn stop_reach_matches_scanning_the_stops() {
|
||||
let colors = ["#ff0000", "#00ff00", "#0000ff", "#ffff00", "#00ffff", "#000000"];
|
||||
let offsets: [&[f32]; 5] = [
|
||||
&[0.1, 0.4, 0.4, 0.2, 0.9, 0.5],
|
||||
&[0.5, 0.5, 0.5, 0.5],
|
||||
&[0.9, 0.1, 0.8, 0.2, 0.7, 0.3],
|
||||
&[0.2, f32::NAN, 0.6, 0.1, f32::NAN, 1.0],
|
||||
&[f32::NAN, 0.3, 0.3, 0.8],
|
||||
];
|
||||
for offsets in offsets {
|
||||
let stops: Vec<GradientStop> = offsets
|
||||
.iter()
|
||||
.zip(colors.iter().cycle())
|
||||
.map(|(&o, hex)| GradientStop { midpoint: 0.3, ..GradientStop::new(o, Color::from_hex(hex).unwrap()) })
|
||||
.collect();
|
||||
let g = Gradient::new(GradientKind::Linear, stops);
|
||||
let reach = StopReach::new(&g.stops);
|
||||
for t in (-4..=44).map(|k| k as f32 / 40.0).chain([f32::NAN, f32::INFINITY, f32::NEG_INFINITY]) {
|
||||
// Compared as printed: a NaN offset mixes NaN colours, which are equal only so.
|
||||
let (got, want) = (reach.sample_with(&g.stops, t, &Color::lerp_keep_model), g.sample_with(t, Color::lerp_keep_model));
|
||||
assert_eq!(format!("{got:?}"), format!("{want:?}"), "{offsets:?} at {t}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Repeated offsets turn off the direct midpoint mix, and the midpoints still come out as
|
||||
/// `sample` gives them, with work that stays near linear in the stops (thousands of stops at one
|
||||
/// offset used to scan them all for each midpoint).
|
||||
#[test]
|
||||
fn expanded_with_repeated_offsets_samples_midpoints() {
|
||||
let stop = |offset: f32, hex: &str| GradientStop { midpoint: 0.25, ..GradientStop::new(offset, Color::from_hex(hex).unwrap()) };
|
||||
let g = Gradient::new(GradientKind::Linear, vec![stop(0.0, "#ff0000"), stop(0.5, "#00ff00"), stop(0.5, "#0000ff"), stop(1.0, "#000000")]);
|
||||
for (t, c, o, mid) in g.expanded().filter(|e| e.3.is_some()) {
|
||||
assert_eq!(mid, Some(0.25));
|
||||
assert_eq!((c, o), g.sample(t), "midpoint at {t}");
|
||||
}
|
||||
let many = Gradient::new(GradientKind::Linear, (0..200_000).map(|i| stop(if i == 0 { 0.0 } else { 0.5 }, "#808080")).collect());
|
||||
assert_eq!(many.expanded().count(), 2 * 200_000 - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midpoint_shifts() {
|
||||
let mut g = Gradient::default();
|
||||
@@ -466,10 +524,14 @@ fn ink_tints_follow_the_perceptual_curve() {
|
||||
let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, ink.tinted(0.8)), GradientStop::new(1.0, Color::WHITE)]);
|
||||
g.method = GradientMethod::Perceptual;
|
||||
assert!(g.fits_ink_tints());
|
||||
let tints = g.ink_tints(&ink).expect("a magenta ink's tints differ in lightness");
|
||||
let tints = g.ink_tints(&ink, &[]).expect("a magenta ink's tints differ in lightness");
|
||||
assert!(tints.len() > 2, "the curve's stops: {tints:?}");
|
||||
let (first, last) = (tints[0], tints[tints.len() - 1]);
|
||||
assert!((first.0, last.0) == (0.0, 1.0) && (first.1 - 0.8).abs() < 1e-4 && last.1 < 1e-4, "{tints:?}");
|
||||
// The stops' own tints, when given, are kept exactly; the tints in between are the same.
|
||||
let own = g.ink_tints(&ink, &[0.8, 0.0]).expect("tints");
|
||||
assert!(own.len() == tints.len() && own[0].1 == 0.8 && own[own.len() - 1].1 == 0.0, "{own:?}");
|
||||
assert!(own[1..own.len() - 1] == tints[1..tints.len() - 1], "{own:?}");
|
||||
assert!(tints.windows(2).all(|w| w[0].0 <= w[1].0 && w[0].1 >= w[1].1), "in order, lighter along the way: {tints:?}");
|
||||
let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0];
|
||||
for (t, tint, _) in &tints {
|
||||
@@ -479,11 +541,11 @@ fn ink_tints_follow_the_perceptual_curve() {
|
||||
let mid = tints.iter().find(|s| (s.0 - 0.5).abs() < 1e-6).expect("the midpoint");
|
||||
assert!((mid.1 - 0.4).abs() > 0.01, "not halfway in tint: {mid:?}");
|
||||
// A white ink's tints all have paper white's lightness: no tints by lightness.
|
||||
assert_eq!(g.ink_tints(&Color::WHITE), None);
|
||||
assert_eq!(g.ink_tints(&Color::WHITE, &[]), None);
|
||||
// More stops on the curve than MAX_INK_TINTS: no tints.
|
||||
let n = MAX_INK_TINTS + 1;
|
||||
g.stops = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { ink } else { Color::WHITE })).collect();
|
||||
assert_eq!(g.ink_tints(&ink), None);
|
||||
assert_eq!(g.ink_tints(&ink, &[]), None);
|
||||
assert!(!g.fits_ink_tints());
|
||||
}
|
||||
|
||||
@@ -523,3 +585,22 @@ fn ink_mixes_follow_the_perceptual_curve() {
|
||||
g.stops = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { magenta } else { Color::WHITE })).collect();
|
||||
assert_eq!(g.ink_mixes(), None);
|
||||
}
|
||||
|
||||
/// From red to blue the display RGB mix darkens past blue's lightness and comes back, so a
|
||||
/// weight found by lightness near the blue stop would be a red-side one and the inks would jump
|
||||
/// there. The weights are the mix positions instead, and reach the blue stop's inks steadily.
|
||||
#[test]
|
||||
fn ink_mixes_use_the_mix_position_when_the_lightness_turns_back() {
|
||||
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red), GradientStop::new(1.0, blue)]);
|
||||
g.method = GradientMethod::Perceptual;
|
||||
let mixes = g.ink_mixes().expect("a Perceptual gradient's curve");
|
||||
assert_eq!(mixes[mixes.len() - 1], (1.0, 1, 0.0, 1.0), "the blue stop");
|
||||
let between: Vec<_> = mixes.iter().filter(|m| m.1 == 0 && m.0 > 0.0).collect();
|
||||
assert!(!between.is_empty(), "stops on the curve between red and blue: {mixes:?}");
|
||||
// With the midpoint at ½, a stop's offset on the curve is its mix position.
|
||||
for (t, _, w, _) in &between {
|
||||
assert!((w - t).abs() < 1e-6, "at {t}: weight {w}");
|
||||
}
|
||||
assert!(mixes.windows(2).filter(|p| p[1].1 == 0).all(|p| p[0].2 <= p[1].2), "the weights rise: {mixes:?}");
|
||||
}
|
||||
@@ -244,6 +244,12 @@ pub fn is_tint(c: Color, base: Color) -> bool {
|
||||
a.iter().zip(b).all(|(x, y)| (x - y * t).abs() <= 0.01)
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` carry the same ink in `a`'s model, within [`is_tint`]'s tolerance.
|
||||
pub fn same_ink(a: Color, b: Color) -> bool {
|
||||
let (x, y) = (ink(a, a.model()), ink(b, a.model()));
|
||||
x.iter().zip(y).all(|(p, q)| (p - q).abs() <= 0.01)
|
||||
}
|
||||
|
||||
/// `c` darkened by `f` (0..1) toward black: more K for CMYK and Gray, scaled RGB and Lab.
|
||||
pub fn shaded(c: Color, f: f32) -> Color {
|
||||
let f = f.clamp(0.0, 1.0);
|
||||
@@ -255,6 +261,77 @@ pub fn shaded(c: Color, f: f32) -> Color {
|
||||
}
|
||||
}
|
||||
|
||||
/// Recolor Artwork's Global Adjust: the same change to every color, by four amounts from -1 to 1
|
||||
/// (-100% to +100%), where 0 leaves a color as it is. The steps run in this order:
|
||||
///
|
||||
/// 1. Saturation multiplies HSB saturation by 1 + `saturation` (-1 gives a gray, 1 doubles it).
|
||||
/// 2. Brightness moves HSB brightness that share of the way to its top (above 0) or to black
|
||||
/// (below 0).
|
||||
/// 3. Temperature adds 0.2 × `temperature` to display red and takes as much from blue (warmer
|
||||
/// above 0, cooler below).
|
||||
/// 4. Luminosity moves Lab lightness that share of the way to 100 (above 0) or to 0 (below 0),
|
||||
/// with Lab a and b, and so the Lab hue, kept.
|
||||
///
|
||||
/// The result is in the model of the color it changes, with its components clamped to their
|
||||
/// ranges. An amount that is not finite counts as 0.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct GlobalAdjust {
|
||||
pub saturation: f32,
|
||||
pub brightness: f32,
|
||||
pub temperature: f32,
|
||||
pub luminosity: f32,
|
||||
}
|
||||
|
||||
impl GlobalAdjust {
|
||||
/// The four amounts, in order, each finite and within -1..=1.
|
||||
fn amounts(&self) -> [f32; 4] {
|
||||
[self.saturation, self.brightness, self.temperature, self.luminosity].map(|v| if v.is_finite() { v.clamp(-1.0, 1.0) } else { 0.0 })
|
||||
}
|
||||
|
||||
/// Whether every color stays as it is (all four amounts 0).
|
||||
pub fn is_identity(&self) -> bool {
|
||||
self.amounts().iter().all(|v| *v == 0.0)
|
||||
}
|
||||
|
||||
/// `c` with the adjustment, in `c`'s model; `c` itself when [`GlobalAdjust::is_identity`].
|
||||
pub fn apply(&self, c: Color) -> Color {
|
||||
let [sat, bri, temp, lum] = self.amounts();
|
||||
if [sat, bri, temp, lum].iter().all(|v| *v == 0.0) {
|
||||
return c;
|
||||
}
|
||||
// `v` moved the share `a` of the way to `top` (a > 0) or to 0 (a < 0).
|
||||
let toward = |v: f32, a: f32, top: f32| if a >= 0.0 { v + (top - v) * a } else { v * (1.0 + a) };
|
||||
let mut out = c;
|
||||
if sat != 0.0 || bri != 0.0 {
|
||||
let [h, s, v] = out.to_hsb();
|
||||
out = Color::from_hsb(h, (s * (1.0 + sat)).clamp(0.0, 1.0), toward(v.clamp(0.0, 1.0), bri, 1.0));
|
||||
}
|
||||
if temp != 0.0 {
|
||||
let [r, g, b] = out.to_rgb();
|
||||
out = Color::rgb((r + 0.2 * temp).clamp(0.0, 1.0), g.clamp(0.0, 1.0), (b - 0.2 * temp).clamp(0.0, 1.0));
|
||||
}
|
||||
if lum != 0.0 {
|
||||
let Lab { l, a, b } = match out {
|
||||
Color::Lab { l, a, b } => Lab::new(l, a, b),
|
||||
_ => out.to_lab(),
|
||||
};
|
||||
out = Color::lab(toward(l.clamp(0.0, 100.0), lum, 100.0), a, b);
|
||||
}
|
||||
clamped(keep_model(c, out))
|
||||
}
|
||||
}
|
||||
|
||||
/// `c` with its components in their ranges: RGB, CMYK and Gray 0..1, Lab lightness 0..100.
|
||||
fn clamped(c: Color) -> Color {
|
||||
let u = |v: f32| v.clamp(0.0, 1.0);
|
||||
match c {
|
||||
Color::Rgb { r, g, b } => Color::rgb(u(r), u(g), u(b)),
|
||||
Color::Cmyk { c, m, y, k } => Color::cmyk(u(c), u(m), u(y), u(k)),
|
||||
Color::Gray { k } => Color::gray(u(k)),
|
||||
Color::Lab { l, a, b } => Color::lab(l.clamp(0.0, 100.0), a, b),
|
||||
}
|
||||
}
|
||||
|
||||
/// One row of Recolor Artwork prepared for mapping: its current colours take `to` by `method`.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct RowMap {
|
||||
@@ -356,10 +433,11 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec<Vec<usize>> {
|
||||
.collect();
|
||||
let w = |i: usize| weights.get(i).copied().unwrap_or(1.0).max(1e-6);
|
||||
let d2 = |a: &[f32; 3], b: &[f32; 3]| (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2);
|
||||
let n = n.max(1);
|
||||
if pts.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
// No more rows than colours: each colour seeds one at most.
|
||||
let n = n.clamp(1, pts.len());
|
||||
// Seeds: the heaviest colour, then each time the one farthest from every seed so far.
|
||||
let first = (0..pts.len()).fold(0, |best, i| if w(i) > w(best) { i } else { best });
|
||||
let mut centres = vec![pts[first]];
|
||||
@@ -370,6 +448,8 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec<Vec<usize>> {
|
||||
break;
|
||||
}
|
||||
centres.push(pts[i]);
|
||||
// Picked: a colour whose distances aren't finite (an infinite coordinate) stays farthest.
|
||||
near[i] = 0.0;
|
||||
for (j, p) in pts.iter().enumerate() {
|
||||
near[j] = near[j].min(d2(p, &pts[i]));
|
||||
}
|
||||
@@ -593,6 +673,12 @@ mod tests {
|
||||
assert!(matches!(shaded(lab[0], 0.5), Color::Lab { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clustering_seeds_each_colour_once_even_unbounded() {
|
||||
let colors = [Color::lab(f32::INFINITY, 0.0, 0.0), Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)];
|
||||
assert!(cluster(&colors, &[], usize::MAX).len() <= colors.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clustering_reduces_to_n_rows_of_similar_colours() {
|
||||
let colors =
|
||||
@@ -615,6 +701,77 @@ mod tests {
|
||||
assert!(row.iter().all(|c| kept.map(*c).model() == c.model()));
|
||||
}
|
||||
|
||||
fn adjust(saturation: f32, brightness: f32, temperature: f32, luminosity: f32) -> GlobalAdjust {
|
||||
GlobalAdjust { saturation, brightness, temperature, luminosity }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_adjust_at_zero_leaves_every_color_as_it_is() {
|
||||
let zero = GlobalAdjust::default();
|
||||
assert!(zero.is_identity());
|
||||
assert!(adjust(f32::NAN, 0.0, f32::INFINITY, 0.0).is_identity(), "amounts that aren't finite count as 0");
|
||||
for c in [Color::rgb(0.3, 0.6, 0.9), Color::cmyk(0.1234, 0.5, 0.0, 0.07), Color::gray(0.4), Color::lab(55.0, 60.5, -40.25)] {
|
||||
assert_eq!(zero.apply(c), c);
|
||||
}
|
||||
assert!(!adjust(0.0, 0.0, 0.0, 0.01).is_identity());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_adjust_saturation_and_brightness_reach_their_ends() {
|
||||
let c = Color::rgb(0.8, 0.4, 0.2);
|
||||
let [h, s, v] = c.to_hsb();
|
||||
let gray = adjust(-1.0, 0.0, 0.0, 0.0).apply(c).to_hsb();
|
||||
assert!(gray[1].abs() < 1e-4 && (gray[2] - v).abs() < 1e-4, "-100% saturation gives a gray as bright: {gray:?}");
|
||||
let more = adjust(0.5, 0.0, 0.0, 0.0).apply(c).to_hsb();
|
||||
assert!((more[0] - h).abs() < 0.5 && more[1] > s && (more[1] - (s * 1.5).min(1.0)).abs() < 1e-3, "{more:?}");
|
||||
assert!(adjust(-1.0, 0.0, 0.0, 0.0).apply(Color::rgb(0.5, 0.5, 0.5)) == Color::rgb(0.5, 0.5, 0.5), "a gray stays gray");
|
||||
assert!(adjust(0.0, -1.0, 0.0, 0.0).apply(c).to_hsb()[2] < 1e-4, "-100% brightness is black");
|
||||
assert!((adjust(0.0, 1.0, 0.0, 0.0).apply(c).to_hsb()[2] - 1.0).abs() < 1e-4, "+100% brightness is full brightness");
|
||||
let half = adjust(0.0, 0.5, 0.0, 0.0).apply(c).to_hsb();
|
||||
assert!((half[2] - (v + (1.0 - v) * 0.5)).abs() < 1e-3 && (half[1] - s).abs() < 1e-3, "{half:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_adjust_temperature_warms_and_cools() {
|
||||
let c = Color::rgb(0.5, 0.5, 0.5);
|
||||
let warm = adjust(0.0, 0.0, 1.0, 0.0).apply(c).to_rgb();
|
||||
let cool = adjust(0.0, 0.0, -1.0, 0.0).apply(c).to_rgb();
|
||||
assert!(warm[0] > warm[1] && warm[1] > warm[2], "warmer: more red, less blue {warm:?}");
|
||||
assert!(cool[2] > cool[1] && cool[1] > cool[0], "cooler: more blue, less red {cool:?}");
|
||||
let edge = adjust(0.0, 0.0, 1.0, 0.0).apply(Color::rgb(1.0, 0.0, 0.0));
|
||||
assert_eq!(edge, Color::rgb(1.0, 0.0, 0.0), "clamped at the ends of the channels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_adjust_luminosity_keeps_the_hue() {
|
||||
let lab = Color::lab(50.0, 30.0, -20.0);
|
||||
assert_eq!(adjust(0.0, 0.0, 0.0, 0.5).apply(lab), Color::lab(75.0, 30.0, -20.0), "a Lab color keeps a and b exactly");
|
||||
assert_eq!(adjust(0.0, 0.0, 0.0, -0.5).apply(lab), Color::lab(25.0, 30.0, -20.0));
|
||||
let c = Color::rgb(0.6, 0.35, 0.3);
|
||||
let (before, after) = (c.to_lab(), adjust(0.0, 0.0, 0.0, 0.2).apply(c).to_lab());
|
||||
assert!(after.l > before.l, "lighter: {after:?}");
|
||||
assert!((after.hue() - before.hue()).abs() < 2.0, "hue kept: {} vs {}", after.hue(), before.hue());
|
||||
let darkest = adjust(0.0, 0.0, 0.0, -1.0).apply(c).to_lab();
|
||||
assert!(darkest.l < before.l * 0.5, "-100% is far darker: {darkest:?}");
|
||||
assert_eq!(adjust(0.0, 0.0, 0.0, -1.0).apply(Color::gray(0.4)), Color::gray(1.0), "-100% makes a gray black");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_adjust_keeps_the_model_and_the_ranges() {
|
||||
let all = adjust(1.0, 1.0, 1.0, 1.0);
|
||||
for c in [Color::rgb(0.3, 0.6, 0.9), Color::cmyk(0.2, 0.9, 0.1, 0.3), Color::gray(0.4), Color::lab(55.0, 60.0, -40.0)] {
|
||||
let out = all.apply(c);
|
||||
assert_eq!(out.model(), c.model(), "{c:?} → {out:?}");
|
||||
let comps: Vec<f32> = match out {
|
||||
Color::Rgb { r, g, b } => vec![r, g, b],
|
||||
Color::Cmyk { c, m, y, k } => vec![c, m, y, k],
|
||||
Color::Gray { k } => vec![k],
|
||||
Color::Lab { l, .. } => vec![l / 100.0],
|
||||
};
|
||||
assert!(comps.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{out:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn palette_snaps_to_the_nearest_colour() {
|
||||
let p = Palette::new([Color::rgb(1.0, 0.0, 0.0), Color::cmyk(1.0, 0.0, 0.0, 0.0), Color::gray(0.5)]);
|
||||
|
||||
@@ -10,10 +10,12 @@ mod stroke_style;
|
||||
|
||||
pub(crate) use layers::HEAD_REACH;
|
||||
pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds};
|
||||
pub use profile::{PressureProfile, ProfilePreset, SavedProfile, WidthProfile};
|
||||
pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile};
|
||||
pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
|
||||
|
||||
/// One entry of the appearance stack.
|
||||
// A stroke takes 328 bytes and a fill 104; an appearance holds a few of each.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "lowercase")]
|
||||
pub enum AppearanceItem {
|
||||
@@ -126,11 +128,15 @@ impl Appearance {
|
||||
pub fn stroke_mut(&mut self) -> Option<&mut StrokeLayer> {
|
||||
self.items.iter_mut().rev().find_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None })
|
||||
}
|
||||
/// This appearance for other art: the pen pressure its strokes were drawn with stays with them.
|
||||
/// This appearance for other art: the pen pressure, tilt, bearing and rotation its strokes
|
||||
/// were drawn with stay with them.
|
||||
pub fn without_pressure(mut self) -> Self {
|
||||
for it in &mut self.items {
|
||||
if let AppearanceItem::Stroke(s) = it {
|
||||
s.pressure = None;
|
||||
s.tilt = None;
|
||||
s.bearing = None;
|
||||
s.rotation = None;
|
||||
}
|
||||
}
|
||||
self
|
||||
@@ -290,6 +296,28 @@ impl Appearance {
|
||||
scale(e, s);
|
||||
}
|
||||
}
|
||||
/// The id of Effect › SVG Filters' effect, whose `origin` parameter is a point of the document.
|
||||
pub const SVG_FILTER: &str = "svg.filter";
|
||||
|
||||
/// Does any effect (the object's or a fill's or stroke's) hold an SVG filter?
|
||||
pub fn has_svg_filter(&self) -> bool {
|
||||
self.effects.iter().chain(self.items.iter().flat_map(|i| i.effects().iter())).any(|e| e.id == Self::SVG_FILTER)
|
||||
}
|
||||
|
||||
/// Move the `origin` of every SVG filter effect (where its user space starts in the document)
|
||||
/// by `a`, as the object it is on moves.
|
||||
pub fn transform_svg_filters(&mut self, a: kurbo::Affine) {
|
||||
let items = self.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
|
||||
for e in self.effects.iter_mut().chain(items).filter(|e| e.id == Self::SVG_FILTER) {
|
||||
let at =
|
||||
|i: usize| e.params.get("origin").and_then(|o| o.get(i)).and_then(serde_json::Value::as_f64).filter(|v| v.is_finite()).unwrap_or(0.0);
|
||||
let p = a * kurbo::Point::new(at(0), at(1));
|
||||
if p.x.is_finite() && p.y.is_finite() && e.params.is_object() {
|
||||
e.params["origin"] = serde_json::json!([p.x, p.y]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gradient paints of the fills and strokes.
|
||||
fn gradients_mut(&mut self) -> impl Iterator<Item = &mut vectorcraft_color::GradientPaint> {
|
||||
self.items.iter_mut().filter_map(|i| match i {
|
||||
@@ -348,6 +376,11 @@ impl Appearance {
|
||||
pub fn has_placed_gradient(&self) -> bool {
|
||||
self.has_gradient(true)
|
||||
}
|
||||
/// Does a fill or stroke carry a gradient that is drawn at a place in document space: a placed
|
||||
/// one, or a freeform gradient with points of its own whose vector is fitted to the bounds?
|
||||
pub fn has_positioned_gradient(&self) -> bool {
|
||||
self.gradients().any(|g| g.is_placed() || g.has_freeform_points())
|
||||
}
|
||||
/// Fix unplaced gradients to their fit on `bounds` (the object's geometric bounds; strokes fit
|
||||
/// the stroke-inflated box), so they can follow transforms that refitting wouldn't reproduce.
|
||||
pub fn pin_gradients(&mut self, bounds: vectorcraft_geom::Rect) {
|
||||
@@ -504,6 +537,27 @@ impl Appearance {
|
||||
self.set_contents_at(others_below + usize::from(now_below));
|
||||
Some(to)
|
||||
}
|
||||
/// Move items `from` (ascending paint-order indices, no repeats) as one block, in their order,
|
||||
/// so the lowest lands at `to` (clamped); returns it. The contents stay between the same unmoved
|
||||
/// items; a block landing right at them keeps its lowest item's side. None (and nothing changed)
|
||||
/// when an index is missing.
|
||||
pub fn move_items(&mut self, from: &[usize], to: usize) -> Option<usize> {
|
||||
let (&first, _) = from.split_first()?;
|
||||
if from.iter().any(|i| *i >= self.items.len()) {
|
||||
return None;
|
||||
}
|
||||
let below = first < self.contents_at();
|
||||
// From the top down, so the lower indices stay valid; then back in order.
|
||||
let mut block: Vec<AppearanceItem> = from.iter().rev().filter_map(|&i| self.remove_item(i)).collect();
|
||||
block.reverse();
|
||||
let others_below = self.contents_at();
|
||||
let to = to.min(self.items.len());
|
||||
let m = block.len();
|
||||
self.items.splice(to..to, block);
|
||||
let now_below = if below { to <= others_below } else { to < others_below };
|
||||
self.set_contents_at(others_below + if now_below { m } else { 0 });
|
||||
Some(to)
|
||||
}
|
||||
}
|
||||
|
||||
/// The most fills, strokes or effects a stack may have to be matched against another's
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::profile::{PressureProfile, WidthProfile};
|
||||
use super::profile::{AngleProfile, PressureProfile, WidthProfile};
|
||||
use super::stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
|
||||
use super::{BlendMode, Deserialize, Paint, Serialize};
|
||||
|
||||
@@ -93,6 +93,21 @@ pub struct StrokeLayer {
|
||||
/// art leave it behind ([`Appearance::without_pressure`]).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub pressure: Option<PressureProfile>,
|
||||
/// How far the pen leaned from upright along the stroke (Paintbrush with a tablet that reads
|
||||
/// tilt): 0 upright to 1 lying flat (90°). Brushes with Tilt variation vary with it. Like the
|
||||
/// pressure, it stays with this path.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tilt: Option<PressureProfile>,
|
||||
/// Which way the pen leaned along the stroke, in degrees counter-clockwise on the page from the
|
||||
/// x axis. Brushes with Bearing variation vary with it. Like the pressure, it stays with this
|
||||
/// path.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub bearing: Option<AngleProfile>,
|
||||
/// How far the pen's barrel was turned along the stroke, in degrees counter-clockwise (a pen
|
||||
/// that reads barrel rotation). Brushes with Rotation variation vary with it. Like the
|
||||
/// pressure, it stays with this path.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub rotation: Option<AngleProfile>,
|
||||
}
|
||||
|
||||
/// How a gradient on a stroke is laid out (the Gradient panel's Stroke buttons). Saved by variant
|
||||
@@ -167,6 +182,9 @@ impl StrokeLayer {
|
||||
overprint: false,
|
||||
gradient_mode: StrokeGradientMode::Within,
|
||||
pressure: None,
|
||||
tilt: None,
|
||||
bearing: None,
|
||||
rotation: None,
|
||||
}
|
||||
}
|
||||
/// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use super::{Deserialize, Serialize};
|
||||
|
||||
/// Variable-width profile: (position 0..1 along the path, left width factor, right width factor),
|
||||
@@ -20,11 +22,15 @@ pub struct ProfilePreset {
|
||||
}
|
||||
|
||||
impl WidthProfile {
|
||||
/// (left, right) width factors at `t`, linear between points.
|
||||
/// (left, right) width factors at `t`: a smooth curve through the points ([`Self::at_points`]).
|
||||
pub fn at(&self, t: f64) -> (f64, f64) {
|
||||
Self::at_points(&self.points, t)
|
||||
}
|
||||
/// [`Self::at`] of a profile's points (a preset's or a saved profile's).
|
||||
/// [`Self::at`] of a profile's points (a preset's or a saved profile's). Each side runs through
|
||||
/// its points on a monotone cubic curve (Fritsch–Carlson): it flows through a width point
|
||||
/// without a kink, turns flat at a point wider or narrower than both neighbours, and never
|
||||
/// goes past either point of the span it is in (#5714). Points on one straight line stay on
|
||||
/// it. A step (two points at one position, [`Self::around`]) ends the curve on each side of it.
|
||||
pub fn at_points(p: &[(f64, f64, f64)], t: f64) -> (f64, f64) {
|
||||
if p.is_empty() {
|
||||
return (1.0, 1.0);
|
||||
@@ -32,11 +38,23 @@ impl WidthProfile {
|
||||
if t <= p[0].0 {
|
||||
return (p[0].1, p[0].2);
|
||||
}
|
||||
for w in p.windows(2) {
|
||||
if t <= w[1].0 {
|
||||
let u = (t - w[0].0) / (w[1].0 - w[0].0).max(1e-9);
|
||||
return (w[0].1 + (w[1].1 - w[0].1) * u, w[0].2 + (w[1].2 - w[0].2) * u);
|
||||
// (Positions go forward; found in log time, so a long profile read from a file is cheap to ask.)
|
||||
let i = p.partition_point(|q| q.0 < t);
|
||||
if let (Some(j), Some(b)) = (i.checked_sub(1), p.get(i))
|
||||
&& let Some(a) = p.get(j)
|
||||
{
|
||||
let h = b.0 - a.0;
|
||||
let u = (t - a.0) / h.max(1e-9);
|
||||
let linear = (a.1 + (b.1 - a.1) * u, a.2 + (b.2 - a.2) * u);
|
||||
if h <= STEP {
|
||||
return linear;
|
||||
}
|
||||
let side = |v: fn(&(f64, f64, f64)) -> f64, straight: f64| {
|
||||
let y = hermite(v(a), v(b), tangent(p, j, v) * h, tangent(p, i, v) * h, u);
|
||||
// Widths read from a file may be huge: where the curve overflows, the straight line.
|
||||
if y.is_finite() { y } else { straight }
|
||||
};
|
||||
return (side(|q| q.1, linear.0), side(|q| q.2, linear.1));
|
||||
}
|
||||
p.last().map_or((1.0, 1.0), |l| (l.1, l.2))
|
||||
}
|
||||
@@ -53,14 +71,17 @@ impl WidthProfile {
|
||||
// Two swells between narrow necks.
|
||||
ProfilePreset { id: "wave", label: "Wave", points: &[(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)] },
|
||||
];
|
||||
/// The widest the stroke gets, as a multiple of its weight: the largest total of the left and
|
||||
/// right factors at any of the points (between them the profile is straight), 1 for a profile
|
||||
/// without points.
|
||||
/// The widest the stroke gets, as a multiple of its weight, 1 for a profile without points. Each
|
||||
/// side stays between the widths of the two points of each span ([`Self::at_points`]), but the
|
||||
/// two sides needn't peak together, so a span counts its wider left and its wider right.
|
||||
pub fn widest(&self) -> f64 {
|
||||
if self.points.is_empty() {
|
||||
let p = &self.points;
|
||||
if p.is_empty() {
|
||||
return 1.0;
|
||||
}
|
||||
self.points.iter().map(|&(_, l, r)| (l.max(0.0) + r.max(0.0)) / 2.0).fold(0.0, f64::max)
|
||||
let total = |l: f64, r: f64| (l.max(0.0) + r.max(0.0)) / 2.0;
|
||||
let spans = p.windows(2).map(|w| total(w[0].1.max(w[1].1), w[0].2.max(w[1].2)));
|
||||
p.iter().map(|&(_, l, r)| total(l, r)).chain(spans).fold(0.0, f64::max)
|
||||
}
|
||||
/// The built-in profile with this id.
|
||||
pub fn preset(id: &str) -> Option<Self> {
|
||||
@@ -88,10 +109,12 @@ impl WidthProfile {
|
||||
/// discontinuous point (two points at `t`, within `1e-7`).
|
||||
pub fn around(&self, t: f64) -> ((f64, f64), (f64, f64)) {
|
||||
let p = &self.points;
|
||||
if let Some(i) = p.iter().position(|q| (q.0 - t).abs() <= 1e-7) {
|
||||
let j = i + p[i..].iter().take_while(|q| (q.0 - p[i].0).abs() <= 1e-9).count() - 1;
|
||||
// The same distance test below, so a point exactly 1e-7 before `t` is never skipped by rounding.
|
||||
let i = p.partition_point(|q| q.0 < t && (q.0 - t).abs() > 1e-7);
|
||||
if let Some(first) = p.get(i).filter(|q| (q.0 - t).abs() <= 1e-7) {
|
||||
let j = i + p[i..].partition_point(|q| q.0 - first.0 <= 1e-9) - 1;
|
||||
if j > i {
|
||||
return ((p[i].1, p[i].2), (p[j].1, p[j].2));
|
||||
return ((first.1, first.2), (p[j].1, p[j].2));
|
||||
}
|
||||
}
|
||||
let v = self.at(t);
|
||||
@@ -101,7 +124,8 @@ impl WidthProfile {
|
||||
|
||||
/// Pen pressure recorded along a stroke (the Paintbrush with a graphics tablet): (position 0..1
|
||||
/// along the path, pressure 0..1) samples in order, positions measured as a [`WidthProfile`]'s
|
||||
/// are. Calligraphic brushes with Pressure variation read it; everything else ignores it.
|
||||
/// are. The pen's tilt is kept the same way ([`StrokeLayer::tilt`]). Calligraphic and Scatter
|
||||
/// brushes with Pressure or Tilt variation read them; everything else ignores them.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PressureProfile {
|
||||
pub points: Vec<(f64, f64)>,
|
||||
@@ -118,18 +142,7 @@ impl PressureProfile {
|
||||
|
||||
/// The pressure at `t` (0..1), linear between samples; [`Self::MID`] without any.
|
||||
pub fn at(&self, t: f64) -> f64 {
|
||||
let p = &self.points;
|
||||
let (Some(first), Some(last)) = (p.first(), p.last()) else { return Self::MID };
|
||||
// (Positions go forward; a profile read from a file is searched as if they do, in log time.)
|
||||
let v = if t <= first.0 {
|
||||
first.1
|
||||
} else {
|
||||
let i = p.partition_point(|q| q.0 < t);
|
||||
match (i.checked_sub(1).and_then(|j| p.get(j)), p.get(i)) {
|
||||
(Some(a), Some(b)) => a.1 + (b.1 - a.1) * ((t - a.0) / (b.0 - a.0).max(1e-9)).clamp(0.0, 1.0),
|
||||
_ => last.1,
|
||||
}
|
||||
};
|
||||
let v = interpolated(&self.points, t).unwrap_or(Self::MID);
|
||||
if v.is_finite() { v.clamp(0.0, 1.0) } else { Self::MID }
|
||||
}
|
||||
|
||||
@@ -139,44 +152,21 @@ impl PressureProfile {
|
||||
pub fn from_samples(samples: impl IntoIterator<Item = (f64, f64)>) -> Option<Self> {
|
||||
let pts: Vec<(f64, f64)> =
|
||||
samples.into_iter().filter(|(t, p)| t.is_finite() && p.is_finite()).map(|(t, p)| (t.clamp(0.0, 1.0), p.clamp(0.0, 1.0))).collect();
|
||||
if pts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Simplifying is quadratic at worst: a huge stroke is thinned evenly first.
|
||||
let mut pts = thin(pts, 16 * Self::MAX_POINTS);
|
||||
// Positions only ever go forward.
|
||||
let mut prev = 0.0;
|
||||
for p in &mut pts {
|
||||
p.0 = p.0.max(prev);
|
||||
prev = p.0;
|
||||
}
|
||||
let keep = simplify_1d(&pts, Self::TOLERANCE);
|
||||
let pts = thin(pts.iter().zip(keep).filter(|(_, k)| *k).map(|(p, _)| *p).collect(), Self::MAX_POINTS);
|
||||
let round = |v: f64| (v * 1e4).round() / 1e4;
|
||||
Some(Self { points: pts.into_iter().map(|(t, p)| (round(t), round(p))).collect() })
|
||||
simplified(pts, Self::TOLERANCE).map(|points| Self { points })
|
||||
}
|
||||
|
||||
/// The pressure of a path `old_len` long (`old`; None: drawn without pressure) continued at its
|
||||
/// end by a stroke `added_len` long (`added`). None when neither has pressure.
|
||||
pub fn extended(old: Option<&Self>, old_len: f64, added: Option<&Self>, added_len: f64) -> Option<Self> {
|
||||
if old.is_none() && added.is_none() {
|
||||
return None;
|
||||
match extended_points(old.map(|p| p.points.as_slice()), old_len, added.map(|p| p.points.as_slice()), added_len, Self::MID)? {
|
||||
Cow::Borrowed(points) => Some(Self { points: points.to_vec() }),
|
||||
Cow::Owned(points) => Self::from_samples(points),
|
||||
}
|
||||
let (old_len, added_len) = (old_len.max(0.0), added_len.max(0.0));
|
||||
let total = old_len + added_len;
|
||||
if !total.is_finite() || total <= 1e-9 {
|
||||
return old.or(added).cloned();
|
||||
}
|
||||
let flat = Self { points: vec![(0.0, Self::MID), (1.0, Self::MID)] };
|
||||
let (old, added) = (old.unwrap_or(&flat), added.unwrap_or(&flat));
|
||||
let o = old_len / total;
|
||||
let old_pts = old.points.iter().map(|&(t, p)| (t * o, p));
|
||||
Self::from_samples(old_pts.chain(added.points.iter().map(|&(u, p)| (o + u * (1.0 - o), p))))
|
||||
}
|
||||
|
||||
/// The pressure of the path reversed.
|
||||
pub fn reversed(&self) -> Self {
|
||||
Self { points: self.points.iter().rev().map(|&(t, p)| (1.0 - t, p)).collect() }
|
||||
Self { points: reversed_points(&self.points) }
|
||||
}
|
||||
|
||||
/// A light–heavy–light stroke, for previews of pressure-sensitive brushes.
|
||||
@@ -185,6 +175,177 @@ impl PressureProfile {
|
||||
}
|
||||
}
|
||||
|
||||
/// A pen angle recorded along a stroke (the Paintbrush with a tablet that reads it): (position 0..1
|
||||
/// along the path, degrees) samples in order, positions measured as a [`PressureProfile`]'s are.
|
||||
/// Each sample is joined to the one before it the shorter way round, so the degrees can run past
|
||||
/// ±180° and the angle read between two samples turns through the smaller angle between them.
|
||||
/// Calligraphic and Scatter brushes with Bearing or Rotation variation read it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AngleProfile {
|
||||
pub points: Vec<(f64, f64)>,
|
||||
}
|
||||
|
||||
impl AngleProfile {
|
||||
/// How far (in degrees) simplifying may move the recorded curve.
|
||||
const TOLERANCE: f64 = 1.0;
|
||||
|
||||
/// The angle at `t` (0..1), linear between samples, in degrees above −180 up to 180; 0
|
||||
/// without any samples.
|
||||
pub fn at(&self, t: f64) -> f64 {
|
||||
let v = interpolated(&self.points, t).unwrap_or(0.0);
|
||||
if v.is_finite() { vectorcraft_geom::normalize_deg(v) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// A profile from (position, degrees) samples in order along the stroke: non-finite ones are
|
||||
/// dropped, each sample is joined to the one before it the shorter way round, and the curve is
|
||||
/// simplified to within 1° and kept to [`PressureProfile::MAX_POINTS`]. `None` without a sample.
|
||||
pub fn from_samples(samples: impl IntoIterator<Item = (f64, f64)>) -> Option<Self> {
|
||||
let mut prev: Option<f64> = None;
|
||||
let pts: Vec<(f64, f64)> = samples
|
||||
.into_iter()
|
||||
.filter(|(t, a)| t.is_finite() && a.is_finite())
|
||||
.map(|(t, a)| {
|
||||
let a = prev.map_or(vectorcraft_geom::normalize_deg(a), |p| p + vectorcraft_geom::normalize_deg(a - p));
|
||||
prev = Some(a);
|
||||
(t.clamp(0.0, 1.0), a)
|
||||
})
|
||||
.collect();
|
||||
simplified(pts, Self::TOLERANCE).map(|points| Self { points })
|
||||
}
|
||||
|
||||
/// The angle of a path `old_len` long (`old`; None: drawn without it, 0°) continued at its end
|
||||
/// by a stroke `added_len` long (`added`). None when neither has one. Each part keeps the turns
|
||||
/// it recorded, more than half a turn between two samples included; the added part is moved by
|
||||
/// whole turns so that it starts the shorter way round from where the old part ends.
|
||||
pub fn extended(old: Option<&Self>, old_len: f64, added: Option<&Self>, added_len: f64) -> Option<Self> {
|
||||
let end = old.map_or(Some(0.0), |o| o.points.last().map(|p| p.1));
|
||||
let added = added.map(|a| {
|
||||
let shift = match (end, a.points.first()) {
|
||||
(Some(end), Some(&(_, start))) => end + vectorcraft_geom::normalize_deg(start - end) - start,
|
||||
_ => 0.0,
|
||||
};
|
||||
Self { points: a.points.iter().map(|&(t, v)| (t, v + shift)).collect() }
|
||||
});
|
||||
match extended_points(old.map(|p| p.points.as_slice()), old_len, added.as_ref().map(|p| p.points.as_slice()), added_len, 0.0)? {
|
||||
Cow::Borrowed(points) => Some(Self { points: points.to_vec() }),
|
||||
Cow::Owned(points) => {
|
||||
let pts = points.into_iter().filter(|(t, a)| t.is_finite() && a.is_finite()).map(|(t, a)| (t.clamp(0.0, 1.0), a)).collect();
|
||||
simplified(pts, Self::TOLERANCE).map(|points| Self { points })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The angle along the path reversed (the angles stay as they were on the page).
|
||||
pub fn reversed(&self) -> Self {
|
||||
Self { points: reversed_points(&self.points) }
|
||||
}
|
||||
|
||||
/// One turn through every angle along the stroke, for previews of brushes that vary with one.
|
||||
pub fn sample() -> Self {
|
||||
Self { points: vec![(0.0, -179.0), (1.0, 179.0)] }
|
||||
}
|
||||
}
|
||||
|
||||
/// How close two width points' positions are to make a step ([`WidthProfile::around`]).
|
||||
const STEP: f64 = 1e-7;
|
||||
|
||||
/// The slope of one side (`v` reads it from a point) of width profile `p` at its point `j`, in
|
||||
/// width per unit of position: Fritsch–Carlson's choice for a monotone cubic curve. It is 0 where
|
||||
/// the point is wider or narrower than both neighbours, the weighted harmonic mean of the slopes
|
||||
/// of the spans on either side elsewhere (never more than three times either, so no span
|
||||
/// overshoots its points), and the span's own slope at an end of the profile or beside a step.
|
||||
fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f64 {
|
||||
let Some(q) = p.get(j) else { return 0.0 };
|
||||
let before = j.checked_sub(1).and_then(|k| p.get(k)).filter(|a| q.0 - a.0 > STEP);
|
||||
let after = p.get(j + 1).filter(|b| b.0 - q.0 > STEP);
|
||||
let slope = |a: &(f64, f64, f64), b: &(f64, f64, f64)| (v(b) - v(a)) / (b.0 - a.0);
|
||||
match (before, after) {
|
||||
(Some(a), Some(b)) => {
|
||||
let (d0, d1) = (slope(a, q), slope(q, b));
|
||||
if d0 * d1 <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let (h0, h1) = (q.0 - a.0, b.0 - q.0);
|
||||
3.0 * (h0 + h1) / ((2.0 * h1 + h0) / d0 + (h1 + 2.0 * h0) / d1)
|
||||
}
|
||||
(Some(a), None) => slope(a, q),
|
||||
(None, Some(b)) => slope(q, b),
|
||||
(None, None) => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The cubic Hermite curve from `y0` to `y1` at `u` (0..1), with end slopes `m0` and `m1` per
|
||||
/// whole span.
|
||||
fn hermite(y0: f64, y1: f64, m0: f64, m1: f64, u: f64) -> f64 {
|
||||
let (u2, u3) = (u * u, u * u * u);
|
||||
(2.0 * u3 - 3.0 * u2 + 1.0) * y0 + (u3 - 2.0 * u2 + u) * m0 + (-2.0 * u3 + 3.0 * u2) * y1 + (u3 - u2) * m1
|
||||
}
|
||||
|
||||
/// The value of samples `p` (position, value) at `t`, linear between them; `None` without any.
|
||||
fn interpolated(p: &[(f64, f64)], t: f64) -> Option<f64> {
|
||||
let (first, last) = (p.first()?, p.last()?);
|
||||
if t <= first.0 {
|
||||
return Some(first.1);
|
||||
}
|
||||
// (Positions go forward; a profile read from a file is searched as if they do, in log time.)
|
||||
let i = p.partition_point(|q| q.0 < t);
|
||||
Some(match (i.checked_sub(1).and_then(|j| p.get(j)), p.get(i)) {
|
||||
(Some(a), Some(b)) => a.1 + (b.1 - a.1) * ((t - a.0) / (b.0 - a.0).max(1e-9)).clamp(0.0, 1.0),
|
||||
_ => last.1,
|
||||
})
|
||||
}
|
||||
|
||||
/// Samples (position, value) with positions in 0..1 and finite values, simplified to within `tol`
|
||||
/// of the value and kept to [`PressureProfile::MAX_POINTS`]. `None` without a sample.
|
||||
fn simplified(pts: Vec<(f64, f64)>, tol: f64) -> Option<Vec<(f64, f64)>> {
|
||||
if pts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Simplifying is quadratic at worst: a huge stroke is thinned evenly first.
|
||||
let mut pts = thin(pts, 16 * PressureProfile::MAX_POINTS);
|
||||
// Positions only ever go forward.
|
||||
let mut prev = 0.0;
|
||||
for p in &mut pts {
|
||||
p.0 = p.0.max(prev);
|
||||
prev = p.0;
|
||||
}
|
||||
let keep = simplify_1d(&pts, tol);
|
||||
let pts = thin(pts.iter().zip(keep).filter(|(_, k)| *k).map(|(p, _)| *p).collect(), PressureProfile::MAX_POINTS);
|
||||
let round = |v: f64| (v * 1e4).round() / 1e4;
|
||||
Some(pts.into_iter().map(|(t, p)| (round(t), round(p))).collect())
|
||||
}
|
||||
|
||||
/// The samples of a path `old_len` long (`old`) continued at its end by a stroke `added_len` long
|
||||
/// (`added`), in order along the whole path, a side without samples (`None`) flat at `none`.
|
||||
/// `None` when neither side has samples; the side that has them, as they are, when the two
|
||||
/// lengths add up to no length.
|
||||
fn extended_points<'a>(
|
||||
old: Option<&'a [(f64, f64)]>,
|
||||
old_len: f64,
|
||||
added: Option<&'a [(f64, f64)]>,
|
||||
added_len: f64,
|
||||
none: f64,
|
||||
) -> Option<Cow<'a, [(f64, f64)]>> {
|
||||
if old.is_none() && added.is_none() {
|
||||
return None;
|
||||
}
|
||||
let (old_len, added_len) = (old_len.max(0.0), added_len.max(0.0));
|
||||
let total = old_len + added_len;
|
||||
if !total.is_finite() || total <= 1e-9 {
|
||||
return old.or(added).map(Cow::Borrowed);
|
||||
}
|
||||
let flat = [(0.0, none), (1.0, none)];
|
||||
let (old, added) = (old.unwrap_or(&flat), added.unwrap_or(&flat));
|
||||
let o = old_len / total;
|
||||
let old_pts = old.iter().map(|&(t, p)| (t * o, p));
|
||||
Some(Cow::Owned(old_pts.chain(added.iter().map(|&(u, p)| (o + u * (1.0 - o), p))).collect()))
|
||||
}
|
||||
|
||||
/// Samples (position, value) of a path, for the path reversed.
|
||||
fn reversed_points(points: &[(f64, f64)]) -> Vec<(f64, f64)> {
|
||||
points.iter().rev().map(|&(t, p)| (1.0 - t, p)).collect()
|
||||
}
|
||||
|
||||
/// At most `max` of `pts`, evenly spread (the ends kept).
|
||||
fn thin(pts: Vec<(f64, f64)>, max: usize) -> Vec<(f64, f64)> {
|
||||
let n = pts.len();
|
||||
@@ -229,3 +390,116 @@ pub struct SavedProfile {
|
||||
pub name: String,
|
||||
pub profile: WidthProfile,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Widths and steps are found by search, at the ends, between points and at a step.
|
||||
#[test]
|
||||
fn width_profile_lookups_by_search() {
|
||||
let p = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (0.5, 0.5, 0.25), (1.0, 0.0, 0.0)] };
|
||||
assert_eq!(p.at(-1.0), (0.0, 0.0));
|
||||
assert_eq!(p.at(0.25), (0.5, 0.5));
|
||||
assert_eq!(p.at(0.75), (0.25, 0.125));
|
||||
assert_eq!(p.at(2.0), (0.0, 0.0));
|
||||
// A step: the widths just before and just after it.
|
||||
assert_eq!(p.around(0.5), ((1.0, 1.0), (0.5, 0.25)));
|
||||
assert_eq!(p.around(0.25), ((0.5, 0.5), (0.5, 0.5)));
|
||||
// Many points at one position are one step, found without a pass over them all.
|
||||
let many = WidthProfile { points: (0..1000).map(|i| (0.5, i as f64, i as f64)).collect() };
|
||||
assert_eq!(many.around(0.5), ((0.0, 0.0), (999.0, 999.0)));
|
||||
// 0.4999999 == 0.5 - 1e-7, yet its distance from 0.5 rounds above 1e-7: it is not part of the step.
|
||||
let near = WidthProfile { points: vec![(0.4999999, 2.0, 2.0), (0.5, 1.0, 1.0), (0.5, 0.5, 0.25)] };
|
||||
assert_eq!(near.around(0.5), ((1.0, 1.0), (0.5, 0.25)));
|
||||
}
|
||||
|
||||
/// The slope of one side of `p` just before and just after `t`.
|
||||
fn slopes(p: &WidthProfile, t: f64) -> (f64, f64) {
|
||||
let e = 1e-6;
|
||||
((p.at(t).0 - p.at(t - e).0) / e, (p.at(t + e).0 - p.at(t).0) / e)
|
||||
}
|
||||
|
||||
/// #5714: the width flows through a width point instead of turning a corner there.
|
||||
#[test]
|
||||
fn widths_run_smoothly_through_width_points() {
|
||||
// A swell in the middle: flat at its widest, and a quarter of the way along above the
|
||||
// straight ramp from 1 to 3 (2).
|
||||
let swell = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 2.0), (1.0, 1.0, 1.0)] };
|
||||
let (before, after) = slopes(&swell, 0.5);
|
||||
assert!(before.abs() < 1e-4 && after.abs() < 1e-4, "{before} {after}");
|
||||
let (l, r) = swell.at(0.25);
|
||||
assert!((l - 2.25).abs() < 1e-12 && (r - 1.625).abs() < 1e-12, "{l} {r}");
|
||||
// Rising on both sides of a point: the slope is the same either side of it.
|
||||
let rise = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.3, 1.0, 1.0), (1.0, 4.0, 4.0)] };
|
||||
let (before, after) = slopes(&rise, 0.3);
|
||||
assert!(before > 0.0 && (before - after).abs() < 1e-3 * before, "{before} {after}");
|
||||
// Points on one line stay on it.
|
||||
let straight = WidthProfile { points: vec![(0.0, 0.0, 1.0), (0.25, 0.5, 1.0), (1.0, 2.0, 1.0)] };
|
||||
for t in [0.1, 0.25, 0.6, 0.9] {
|
||||
let (l, r) = straight.at(t);
|
||||
assert!((l - 2.0 * t).abs() < 1e-12 && (r - 1.0).abs() < 1e-12, "{t}: {l} {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Neither side of a profile goes wider or narrower than the two points of the span it is in.
|
||||
#[test]
|
||||
fn widths_never_pass_the_points_either_side() {
|
||||
for preset in WidthProfile::PRESETS {
|
||||
let p = WidthProfile { points: preset.points.to_vec() };
|
||||
for w in p.points.windows(2) {
|
||||
let (lo, hi) = (w[0].1.min(w[1].1), w[0].1.max(w[1].1));
|
||||
for k in 0..=100 {
|
||||
let t = w[0].0 + (w[1].0 - w[0].0) * k as f64 / 100.0;
|
||||
let l = p.at(t).0;
|
||||
assert!(l >= lo - 1e-12 && l <= hi + 1e-12, "{}: {l} at {t} outside {lo}..{hi}", preset.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Uneven spacing and a steep jump next to a gentle rise.
|
||||
let p = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.05, 1.0, 1.0), (0.9, 1.1, 1.1), (1.0, 5.0, 5.0)] };
|
||||
for k in 0..=1000 {
|
||||
let t = k as f64 / 1000.0;
|
||||
let l = p.at(t).0;
|
||||
let span = p.points.windows(2).find(|w| t >= w[0].0 && t <= w[1].0).map(|w| (w[0].1.min(w[1].1), w[0].1.max(w[1].1)));
|
||||
let (lo, hi) = span.unwrap();
|
||||
assert!(l >= lo - 1e-12 && l <= hi + 1e-12, "{l} at {t}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A step still breaks the width sharply, and the curve on either side ends at it.
|
||||
#[test]
|
||||
fn a_step_ends_the_curve_on_each_side() {
|
||||
let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 3.0), (0.5, 1.0, 1.0), (1.0, 2.0, 2.0)] };
|
||||
assert_eq!(p.around(0.5), ((3.0, 3.0), (1.0, 1.0)));
|
||||
// Two points between ends: each side of the step is a straight ramp.
|
||||
assert!((p.at(0.25).0 - 2.0).abs() < 1e-12 && (p.at(0.75).0 - 1.5).abs() < 1e-12);
|
||||
}
|
||||
|
||||
/// `widest()` is at least the stroke's width anywhere along the profile, even where the sides peak apart.
|
||||
#[test]
|
||||
fn widest_covers_every_width_along_the_profile() {
|
||||
let profiles = [
|
||||
vec![(0.0, 1.0, 0.0), (0.5, 0.2, 1.0), (1.0, 1.0, 0.0)],
|
||||
vec![(0.0, 0.0, 1.0), (0.3, 1.0, 0.0), (0.6, 0.0, 1.0), (1.0, 1.0, 1.0)],
|
||||
vec![(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)],
|
||||
];
|
||||
for points in profiles {
|
||||
let p = WidthProfile { points };
|
||||
let most = (0..=1000).map(|k| p.at(k as f64 / 1000.0)).map(|(l, r)| (l.max(0.0) + r.max(0.0)) / 2.0).fold(0.0, f64::max);
|
||||
assert!(p.widest() >= most - 1e-12, "{} < {most}: {:?}", p.widest(), p.points);
|
||||
}
|
||||
assert_eq!(WidthProfile::lens().widest(), 1.0);
|
||||
assert_eq!(WidthProfile::default().widest(), 1.0);
|
||||
}
|
||||
|
||||
/// Widths read from a file may be absurd: the curve stays finite or falls back to the line.
|
||||
#[test]
|
||||
fn huge_widths_stay_finite() {
|
||||
let p = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.5, f64::MAX, 1.0), (1.0, -f64::MAX, 0.0)] };
|
||||
for k in 0..=10 {
|
||||
let (l, r) = p.at(k as f64 / 10.0);
|
||||
assert!(!l.is_nan() && r.is_finite(), "{l} {r}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,11 +125,50 @@ fn pressure_profile_extends_and_reverses() {
|
||||
assert_eq!(old.reversed().points, vec![(0.0, 1.0), (1.0, 0.0)]);
|
||||
}
|
||||
|
||||
/// #764: a pen's bearing or barrel rotation is kept the shorter way round between samples, so
|
||||
/// 170° then −170° turns through 180°, not through 0°.
|
||||
#[test]
|
||||
fn angle_profiles_join_samples_the_shorter_way_round() {
|
||||
let across = AngleProfile::from_samples([(0.0, 170.0), (1.0, -170.0)]).unwrap();
|
||||
assert_eq!(across.points, vec![(0.0, 170.0), (1.0, 190.0)]);
|
||||
assert_eq!(across.at(0.5), 180.0);
|
||||
assert!((across.at(0.75) + 175.0).abs() < 1e-9, "{}", across.at(0.75));
|
||||
// Turns past a whole turn keep counting, and read back within −180..180°.
|
||||
let spin = AngleProfile::from_samples((0..=40).map(|i| (f64::from(i) / 40.0, f64::from(i * 30) - 180.0))).unwrap();
|
||||
assert!((spin.points.last().unwrap().1 - 1380.0).abs() < 1e-9, "{spin:?}");
|
||||
assert!((spin.at(1.0) + 60.0).abs() < 1e-9 && spin.points.len() == 2, "{spin:?}");
|
||||
// Junk is dropped; nothing at all is no profile, and no profile reads 0°.
|
||||
let junk = AngleProfile::from_samples([(f64::NAN, 5.0), (0.5, f64::INFINITY), (0.2, 400.0)]).unwrap();
|
||||
assert_eq!(junk.points, vec![(0.2, 40.0)]);
|
||||
assert!(AngleProfile::from_samples([(0.5, f64::NAN)]).is_none());
|
||||
assert_eq!(AngleProfile::default().at(0.3), 0.0);
|
||||
let noisy = AngleProfile::from_samples((0..1_000_000).map(|i| (f64::from(i) / 1e6, f64::from(i % 2) * 90.0))).unwrap();
|
||||
assert!(noisy.points.len() <= PressureProfile::MAX_POINTS);
|
||||
// Continued: the old part, then the new one; a side without an angle is 0°. Reversed, the
|
||||
// angles stay what they were.
|
||||
let old = AngleProfile { points: vec![(0.0, 90.0), (1.0, 90.0)] };
|
||||
let joined = AngleProfile::extended(Some(&old), 30.0, None, 10.0).unwrap();
|
||||
assert!((joined.at(0.5) - 90.0).abs() < 1e-9 && joined.at(1.0) == 0.0, "{joined:?}");
|
||||
assert!(AngleProfile::extended(None, 10.0, None, 10.0).is_none());
|
||||
assert_eq!(AngleProfile::extended(Some(&old), 0.0, None, 0.0), Some(old.clone()));
|
||||
assert_eq!(across.reversed().points, vec![(0.0, 190.0), (1.0, 170.0)]);
|
||||
// A part that turned more than half a turn between two of its samples keeps that turn when
|
||||
// the path is continued, and so does the new part.
|
||||
let quarter_turns = AngleProfile::from_samples([(0.0, 0.0), (1.0 / 3.0, 90.0), (2.0 / 3.0, 180.0), (1.0, 270.0)]).unwrap();
|
||||
assert_eq!(quarter_turns.points, vec![(0.0, 0.0), (1.0, 270.0)]);
|
||||
let added = AngleProfile { points: vec![(0.0, -80.0), (1.0, 280.0)] };
|
||||
let joined = AngleProfile::extended(Some(&quarter_turns), 10.0, Some(&added), 10.0).unwrap();
|
||||
assert!((joined.at(0.25) - 135.0).abs() < 1e-9, "{joined:?}");
|
||||
assert!((joined.at(0.75) - 100.0).abs() < 1e-9, "{joined:?}");
|
||||
}
|
||||
|
||||
/// Strokes saved before pen pressure load as they were, and are written without it.
|
||||
#[test]
|
||||
fn strokes_without_pressure_round_trip_unchanged() {
|
||||
let json = serde_json::to_value(StrokeLayer::new(Paint::None, 2.0)).unwrap();
|
||||
assert!(json.get("pressure").is_none());
|
||||
for key in ["pressure", "tilt", "bearing", "rotation"] {
|
||||
assert!(json.get(key).is_none(), "{key}");
|
||||
}
|
||||
let st: StrokeLayer = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(st.pressure, None);
|
||||
let pressed = StrokeLayer { pressure: Some(PressureProfile::sample()), ..st };
|
||||
@@ -138,13 +177,29 @@ fn strokes_without_pressure_round_trip_unchanged() {
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0);
|
||||
ap.stroke_mut().unwrap().pressure = Some(PressureProfile::sample());
|
||||
assert_eq!(ap.without_pressure().stroke().unwrap().pressure, None);
|
||||
// The pen's tilt, bearing and rotation load, save and stay behind the same way.
|
||||
let posed = StrokeLayer {
|
||||
tilt: Some(PressureProfile::sample()),
|
||||
bearing: Some(AngleProfile::sample()),
|
||||
rotation: Some(AngleProfile { points: vec![(0.0, -45.0)] }),
|
||||
..back
|
||||
};
|
||||
let again: StrokeLayer = serde_json::from_value(serde_json::to_value(&posed).unwrap()).unwrap();
|
||||
assert_eq!(again, posed);
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0);
|
||||
*ap.stroke_mut().unwrap() = posed;
|
||||
let st = ap.without_pressure().stroke().cloned().unwrap();
|
||||
assert_eq!((st.pressure, st.tilt, st.bearing, st.rotation), (None, None, None, None));
|
||||
}
|
||||
|
||||
/// The Lens profile's widths at its middle, a quarter of the way along and past its end.
|
||||
#[test]
|
||||
fn profile_interp() {
|
||||
let p = WidthProfile::lens();
|
||||
assert_eq!(p.at(0.5), (1.0, 1.0));
|
||||
assert_eq!(p.at(0.25), (0.5, 0.5));
|
||||
// Half way up the lens the width curves above the straight ramp (0.5), flattening into its
|
||||
// widest point (#5714).
|
||||
assert_eq!(p.at(0.25), (0.625, 0.625));
|
||||
assert_eq!(p.at(2.0), (0.0, 0.0));
|
||||
}
|
||||
|
||||
|
||||
@@ -106,6 +106,60 @@ impl super::Document {
|
||||
d.layers.insert(0, Arc::new(layer));
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// Where an artboard the size of artboard `i` goes on `side` of it, [`ARTBOARD_GAP`] away,
|
||||
/// when there is room for it there: every side within [`crate::MAX_COORD`] of the origin and
|
||||
/// no other artboard overlapping it (touching edges don't overlap). `None` when there is no
|
||||
/// such artboard or no room.
|
||||
pub fn room_beside_artboard(&self, i: usize, side: ArtboardSide) -> Option<Rect> {
|
||||
let src = self.artboards.get(i)?.rect;
|
||||
let r = src + side.offset(src);
|
||||
let in_canvas = [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD);
|
||||
let clear = self.artboards.iter().all(|a| !(r.x0 < a.rect.x1 && a.rect.x0 < r.x1 && r.y0 < a.rect.y1 && a.rect.y0 < r.y1));
|
||||
(in_canvas && clear).then_some(r)
|
||||
}
|
||||
}
|
||||
|
||||
/// The space between an artboard and one added or duplicated beside it (VectorCraft's own value,
|
||||
/// the space New Artboard and Duplicate Artboards leave right of the last artboard).
|
||||
pub const ARTBOARD_GAP: f64 = 20.0;
|
||||
|
||||
/// A side of an artboard, where an artboard added or duplicated beside it goes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ArtboardSide {
|
||||
Left,
|
||||
Right,
|
||||
Top,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
impl ArtboardSide {
|
||||
pub const ALL: [Self; 4] = [Self::Top, Self::Right, Self::Bottom, Self::Left];
|
||||
|
||||
/// The side a command's `side` param names: "left", "right", "top" or "bottom".
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|s| s.name() == name)
|
||||
}
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Left => "left",
|
||||
Self::Right => "right",
|
||||
Self::Top => "top",
|
||||
Self::Bottom => "bottom",
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a copy of `r` moves to sit on this side of it, [`ARTBOARD_GAP`] away (y down).
|
||||
pub fn offset(self, r: Rect) -> vectorcraft_geom::Vec2 {
|
||||
let (w, h) = (r.width() + ARTBOARD_GAP, r.height() + ARTBOARD_GAP);
|
||||
match self {
|
||||
Self::Left => vectorcraft_geom::Vec2::new(-w, 0.0),
|
||||
Self::Right => vectorcraft_geom::Vec2::new(w, 0.0),
|
||||
Self::Top => vectorcraft_geom::Vec2::new(0.0, -h),
|
||||
Self::Bottom => vectorcraft_geom::Vec2::new(0.0, h),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A document's locked artboards ([`Document::locked_artboards`]).
|
||||
|
||||
@@ -11,12 +11,16 @@ use serde::{Deserialize, Serialize};
|
||||
use crate::{Document, NodeId};
|
||||
|
||||
/// One asset: what it is called (its files' names) and the objects it exports, cropped to their
|
||||
/// visual bounds.
|
||||
/// visual bounds, or for a 3D asset its object's solids as a mesh file.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ExportAsset {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub nodes: Vec<NodeId>,
|
||||
/// A 3D asset's mesh format (`usda`, `usdz`, `gltf` or `obj`): its object exports as a 3D
|
||||
/// file. `None` for art exported as pictures.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub format_3d: Option<String>,
|
||||
}
|
||||
|
||||
/// What the assets are named when they aren't named after their object: `Asset 1`, `Asset 2`…
|
||||
@@ -30,7 +34,16 @@ impl Document {
|
||||
|
||||
/// The name of the next unnamed asset: one more than the highest `Asset N` so far.
|
||||
pub fn next_asset_name(&self) -> String {
|
||||
let n = self.assets.iter().filter_map(|a| a.name.strip_prefix(ASSET)?.parse::<u64>().ok()).max().unwrap_or(0);
|
||||
let n = self
|
||||
.assets
|
||||
.iter()
|
||||
.filter_map(|a| {
|
||||
let digits = a.name.strip_prefix(ASSET)?;
|
||||
// `parse` alone would accept a leading `+`.
|
||||
digits.bytes().all(|b| b.is_ascii_digit()).then(|| digits.parse::<u64>().ok()).flatten()
|
||||
})
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
format!("{ASSET}{}", n.saturating_add(1))
|
||||
}
|
||||
|
||||
@@ -57,3 +70,23 @@ impl Document {
|
||||
v.into_iter().map(|(_, id)| id).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn name_after(names: &[&str]) -> String {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
for (i, n) in names.iter().enumerate() {
|
||||
doc.assets.push(ExportAsset { id: i as u64 + 1, name: (*n).to_string(), nodes: vec![], format_3d: None });
|
||||
}
|
||||
doc.next_asset_name()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_asset_name_ignores_non_digit_suffixes() {
|
||||
assert_eq!(name_after(&["Asset +5"]), "Asset 1");
|
||||
assert_eq!(name_after(&["Asset ", "Asset 5x"]), "Asset 1");
|
||||
assert_eq!(name_after(&["Asset 5"]), "Asset 6");
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ use std::f64::consts::PI;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_geom::kurbo::ParamCurveArclen;
|
||||
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
|
||||
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
|
||||
|
||||
use crate::appearance::{Appearance, AppearanceItem, Dash, StrokeLayer, WidthProfile};
|
||||
@@ -699,6 +699,34 @@ fn compound(path: PathData, rule: FillRule, counts: &[usize], total: usize) -> N
|
||||
/// Interpolate text `x` → `y` into `o` (a copy of the nearer): the transform by its parts, an
|
||||
/// area frame anchor by anchor, and each run's colours, stroke weight and size from the runs at
|
||||
/// the same place (by character) of both.
|
||||
/// The run of `of` at fraction `u` of its characters.
|
||||
fn run_at(of: &TextObject, u: f64) -> Option<&crate::text::TextRun> {
|
||||
let total: usize = of.runs.iter().map(|r| r.text.chars().count()).sum();
|
||||
let target = (u * total as f64) as usize;
|
||||
let mut seen = 0;
|
||||
for r in &of.runs {
|
||||
seen += r.text.chars().count();
|
||||
if seen > target {
|
||||
return Some(r);
|
||||
}
|
||||
}
|
||||
of.runs.last()
|
||||
}
|
||||
|
||||
/// The fraction of the characters of `runs` at the middle of each run.
|
||||
fn run_middles(runs: &[crate::text::TextRun]) -> Vec<f64> {
|
||||
let total: usize = runs.iter().map(|r| r.text.chars().count()).sum::<usize>().max(1);
|
||||
let mut start = 0usize;
|
||||
runs.iter()
|
||||
.map(|r| {
|
||||
let len = r.text.chars().count();
|
||||
let u = (start as f64 + len as f64 / 2.0) / total as f64;
|
||||
start += len;
|
||||
u
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64, tc: f64) {
|
||||
o.xf = lerp_affine(x.xf, y.xf, t);
|
||||
if let (crate::text::TextKind::Area { frame: f }, crate::text::TextKind::Area { frame: fx }, crate::text::TextKind::Area { frame: fy }) =
|
||||
@@ -706,27 +734,10 @@ fn lerp_text(o: &mut TextObject, x: &TextObject, y: &TextObject, t: f64, tc: f64
|
||||
{
|
||||
*f = lerp_path(fx, fy, t);
|
||||
}
|
||||
// The run of `of` at fraction `u` of its characters.
|
||||
fn run_at(of: &TextObject, u: f64) -> Option<&crate::text::TextRun> {
|
||||
let total: usize = of.runs.iter().map(|r| r.text.chars().count()).sum();
|
||||
let target = (u * total as f64) as usize;
|
||||
let mut seen = 0;
|
||||
for r in &of.runs {
|
||||
seen += r.text.chars().count();
|
||||
if seen > target {
|
||||
return Some(r);
|
||||
}
|
||||
}
|
||||
of.runs.last()
|
||||
}
|
||||
let total: usize = o.runs.iter().map(|r| r.text.chars().count()).sum::<usize>().max(1);
|
||||
let mut start = 0usize;
|
||||
let tf = tc as f32;
|
||||
let mut resized = false;
|
||||
for r in &mut o.runs {
|
||||
let len = r.text.chars().count();
|
||||
let u = (start as f64 + len as f64 / 2.0) / total as f64;
|
||||
start += len;
|
||||
let middles = run_middles(&o.runs);
|
||||
for (r, u) in o.runs.iter_mut().zip(middles) {
|
||||
let (Some(rx), Some(ry)) = (run_at(x, u), run_at(y, u)) else { continue };
|
||||
let (sx, sy) = (&rx.style, &ry.style);
|
||||
r.style.fill = lerp_paint(&sx.fill, &sy.fill, tf);
|
||||
@@ -752,33 +763,115 @@ pub fn lerp_node(a: &Node, b: &Node, t: f64) -> Node {
|
||||
// Step counts
|
||||
// =====================================================================================
|
||||
|
||||
/// Largest channel difference (0..1) between the solid colours of two objects' top fill and stroke.
|
||||
fn color_distance(a: &Node, b: &Node) -> f32 {
|
||||
let mut d = 0.0f32;
|
||||
let mut cmp = |x: &Paint, y: &Paint| {
|
||||
let cols = |p: &Paint| -> Vec<Color> {
|
||||
match p {
|
||||
Paint::Solid { color, .. } => vec![*color],
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().map(|s| s.color).collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
};
|
||||
let (cx, cy) = (cols(x), cols(y));
|
||||
for (i, c) in cx.iter().enumerate() {
|
||||
if let Some(o) = cy.get(i).or(cy.first()) {
|
||||
let (p, q) = (c.to_rgb(), o.to_rgb());
|
||||
for k in 0..3 {
|
||||
d = d.max((p[k] - q[k]).abs());
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Largest channel difference between two solid colors, as a fraction of the channel's range: two
|
||||
/// tints of the same swatch by their tints, RGB by its 0 to 255 values over 256, CMYK and gray by
|
||||
/// their percentages, and colors in different spaces (or Lab) by the difference of their RGB
|
||||
/// values over 255. A solid paint against no paint, or anything that isn't solid, differs by 0:
|
||||
/// [`lerp_paint`] switches such paints halfway rather than mixing them.
|
||||
fn paint_difference(x: &Paint, y: &Paint) -> f64 {
|
||||
let (Paint::Solid { color: p, swatch: sp, tint: tp }, Paint::Solid { color: q, swatch: sq, tint: tq }) = (x, y) else {
|
||||
return 0.0;
|
||||
};
|
||||
cmp(&a.appearance.fill_paint(), &b.appearance.fill_paint());
|
||||
cmp(&a.appearance.stroke_paint(), &b.appearance.stroke_paint());
|
||||
d
|
||||
if sp.is_some() && sp == sq && tp != tq {
|
||||
return f64::from((tp - tq).abs());
|
||||
}
|
||||
let most = |a: &[f32], b: &[f32]| a.iter().zip(b).fold(0.0f64, |m, (u, v)| m.max(f64::from((u - v).abs())));
|
||||
match (p, q) {
|
||||
(Color::Rgb { r, g, b }, Color::Rgb { r: r2, g: g2, b: b2 }) => most(&[*r, *g, *b], &[*r2, *g2, *b2]) * 255.0 / 256.0,
|
||||
(Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => most(&[*c, *m, *y, *k], &[*c2, *m2, *y2, *k2]),
|
||||
(Color::Gray { k }, Color::Gray { k: k2 }) => most(&[*k], &[*k2]),
|
||||
_ => most(&p.to_rgb(), &q.to_rgb()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of intermediate steps between two keys `len` apart (along the spine).
|
||||
/// Largest difference (see [`paint_difference`]) between pairs of fills and strokes, or `None`
|
||||
/// when any of them is a gradient or a pattern.
|
||||
fn paints_difference(pairs: &[(&Paint, &Paint)]) -> Option<f64> {
|
||||
let mut d = 0.0f64;
|
||||
for (x, y) in pairs {
|
||||
if [x, y].iter().any(|p| matches!(p, Paint::Gradient(_) | Paint::Pattern { .. })) {
|
||||
return None;
|
||||
}
|
||||
d = d.max(paint_difference(x, y));
|
||||
}
|
||||
Some(d)
|
||||
}
|
||||
|
||||
/// Largest channel difference (0..1, see [`paint_difference`]) between the solid colors of two
|
||||
/// keys: their top fill and stroke, the runs of two text objects paired as [`lerp_text`] pairs
|
||||
/// them, and the members of two groups paired as [`Lerp::new`] pairs them. `None` when any of
|
||||
/// these holds a gradient or a pattern, whose steps Smooth Color counts by distance.
|
||||
fn color_distance(a: &Node, b: &Node) -> Option<f64> {
|
||||
let mut d =
|
||||
paints_difference(&[(&a.appearance.fill_paint(), &b.appearance.fill_paint()), (&a.appearance.stroke_paint(), &b.appearance.stroke_paint())])?;
|
||||
match (&a.kind, &b.kind) {
|
||||
(NodeKind::Group { children: ca, clip: k1 }, NodeKind::Group { children: cb, clip: k2 }) if k1 == k2 && !(*k1 && ca.len() != cb.len()) => {
|
||||
for (x, y) in ca.iter().zip(cb) {
|
||||
d = d.max(color_distance(x, y)?);
|
||||
}
|
||||
}
|
||||
(NodeKind::Text(x), NodeKind::Text(y)) => {
|
||||
// The runs `lerp_text` pairs: those of `x` and of `y` at the middle of each run of either.
|
||||
for u in run_middles(&x.runs).into_iter().chain(run_middles(&y.runs)) {
|
||||
let (Some(rx), Some(ry)) = (run_at(x, u), run_at(y, u)) else { continue };
|
||||
d = d.max(paints_difference(&[(&rx.style.fill, &ry.style.fill), (&rx.style.stroke, &ry.style.stroke)])?);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
d.is_finite().then_some(d)
|
||||
}
|
||||
|
||||
/// Smooth Color's steps between two keys by distance: the largest distance between their
|
||||
/// corresponding visible bounding-box edges, in mean key widths (left and right edges) or heights
|
||||
/// (top and bottom), rounded, less one, from 1 to 1000. Keys with no width are measured in their
|
||||
/// mean height across as well, keys with no height in their mean width, and keys with neither in
|
||||
/// points.
|
||||
fn spatial_steps(ba: Rect, bb: Rect) -> usize {
|
||||
let (w, h) = ((ba.width() + bb.width()) / 2.0, (ba.height() + bb.height()) / 2.0);
|
||||
let size = |s: f64, other: f64| {
|
||||
if s > 1e-9 {
|
||||
s
|
||||
} else if other > 1e-9 {
|
||||
other
|
||||
} else {
|
||||
1.0
|
||||
}
|
||||
};
|
||||
let (w, h) = (size(w, h), size(h, w));
|
||||
let q = ((ba.x0 - bb.x0).abs().max((ba.x1 - bb.x1).abs()) / w).max((ba.y0 - bb.y0).abs().max((ba.y1 - bb.y1).abs()) / h);
|
||||
if !q.is_finite() {
|
||||
return 1;
|
||||
}
|
||||
((q + 0.5).floor() - 1.0).clamp(1.0, 1000.0) as usize
|
||||
}
|
||||
|
||||
/// `255 × d` steps for a color difference `d` (see [`color_distance`]), a half step rounding down,
|
||||
/// from 1 to 254.
|
||||
fn level_steps(d: f64) -> f64 {
|
||||
// The tolerance keeps a difference that lands on a half step (128 of 256 RGB values gives
|
||||
// 127.5), stored as an `f32`, from rounding up.
|
||||
(255.0 * d - 0.5 - 1e-4).ceil().clamp(1.0, 254.0)
|
||||
}
|
||||
|
||||
/// Smooth Color's steps between two keys whose colors differ by `d` (see [`color_distance`]):
|
||||
/// [`level_steps`], and at most eight per point of the largest of the keys' widths and heights
|
||||
/// and the distance between their centers along either axis.
|
||||
fn color_steps(d: f64, ba: Rect, bb: Rect) -> usize {
|
||||
let by_color = level_steps(d);
|
||||
let (ca, cb) = (ba.center(), bb.center());
|
||||
let reach = [(ca.x - cb.x).abs(), (ca.y - cb.y).abs(), ba.width(), ba.height(), bb.width(), bb.height()].into_iter().fold(0.0f64, f64::max);
|
||||
let by_density = (8.0 * reach + 0.5).floor().clamp(1.0, 254.0);
|
||||
if !by_density.is_finite() {
|
||||
return by_color as usize;
|
||||
}
|
||||
by_color.min(by_density) as usize
|
||||
}
|
||||
|
||||
/// Number of intermediate steps between two keys. Specified Distance counts along the spine, `len`
|
||||
/// long between them. Smooth Color counts from the keys' colors and visible bounds, whatever the
|
||||
/// spine: keys whose colors differ make [`color_steps`] ([`level_steps`] when either key has no
|
||||
/// bounds), and others make [`spatial_steps`] (1 when either key has no bounds).
|
||||
pub fn blend_step_count(a: &Node, b: &Node, spacing: BlendSpacing, len: f64) -> usize {
|
||||
match spacing {
|
||||
BlendSpacing::Steps(n) => n.clamp(1, 1000) as usize,
|
||||
@@ -787,17 +880,14 @@ pub fn blend_step_count(a: &Node, b: &Node, spacing: BlendSpacing, len: f64) ->
|
||||
((len / d).round() as i64 - 1).clamp(0, 1000) as usize
|
||||
}
|
||||
BlendSpacing::SmoothColor => {
|
||||
let cd = color_distance(a, b);
|
||||
if cd > 1.0 / 255.0 {
|
||||
((cd * 255.0 / 2.0).ceil() as usize).clamp(1, 256)
|
||||
} else {
|
||||
// Same colours: base the count on the distance between the objects.
|
||||
let (ba, bb) = (a.geometric_bounds(), b.geometric_bounds());
|
||||
let dist = match (ba, bb) {
|
||||
(Some(x), Some(y)) => (x.x0 - y.x0).abs().max((x.x1 - y.x1).abs()).max((x.y0 - y.y0).abs()).max((x.y1 - y.y1).abs()),
|
||||
_ => len,
|
||||
};
|
||||
((dist / 2.0).ceil() as usize).clamp(1, 256)
|
||||
let bounds = a.visual_bounds().zip(b.visual_bounds());
|
||||
match (color_distance(a, b), bounds) {
|
||||
// Colors that differ by less than a thousandth of a step count as the same.
|
||||
(Some(d), Some((ba, bb))) if d * 255.0 > 1e-3 => color_steps(d, ba, bb),
|
||||
(Some(d), None) if d * 255.0 > 1e-3 => level_steps(d) as usize,
|
||||
// Same colors, gradients and patterns: the distance between the objects.
|
||||
(_, Some((ba, bb))) => spatial_steps(ba, bb),
|
||||
(_, None) => 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -814,9 +904,12 @@ pub struct Spine {
|
||||
cum: Vec<f64>,
|
||||
anchors: Vec<f64>,
|
||||
closed: bool,
|
||||
path: PathData,
|
||||
}
|
||||
|
||||
impl Spine {
|
||||
/// Build a spine from the first subpath of `path`: flatten it to a polyline, record cumulative
|
||||
/// arc lengths, and the arc length at each anchor.
|
||||
pub fn new(path: &PathData) -> Option<Self> {
|
||||
let sp = path.subpaths.first()?;
|
||||
let mut pts: Vec<Point> = Vec::new();
|
||||
@@ -853,8 +946,9 @@ impl Spine {
|
||||
if pts.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
Some(Self { pts, cum, anchors, closed: sp.closed })
|
||||
Some(Self { pts, cum, anchors, closed: sp.closed, path: path.clone() })
|
||||
}
|
||||
/// The spine's flattened length in arc length.
|
||||
pub fn length(&self) -> f64 {
|
||||
*self.cum.last().unwrap_or(&0.0)
|
||||
}
|
||||
@@ -862,24 +956,82 @@ impl Spine {
|
||||
pub fn anchor_length(&self, i: usize) -> Option<f64> {
|
||||
self.anchors.get(i).copied()
|
||||
}
|
||||
/// Arc length of the point of the spine nearest `p`. An open spine's end segments run on past
|
||||
/// its ends as lines, so the result is below 0 before the start and above [`Spine::length`]
|
||||
/// beyond the end. With `from`, the arc length of an earlier point a drag followed, each point
|
||||
/// counts as farther by half its distance along the spine from there, so a pointer passing
|
||||
/// near another part of the spine stays on the part it follows. Where two points count as
|
||||
/// near as each other, the one earlier along the spine counts.
|
||||
pub fn length_near(&self, p: Point, from: Option<f64>) -> f64 {
|
||||
self.nearest(p, from).map_or(0.0, |(_, s)| s)
|
||||
}
|
||||
/// [`Spine::length_near`] with how near the point counts: its distance from `p`, plus half its
|
||||
/// distance along the spine from `from`. `None` for a point that is not finite.
|
||||
pub fn nearest(&self, p: Point, from: Option<f64>) -> Option<(f64, f64)> {
|
||||
if !p.x.is_finite() || !p.y.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let last = self.pts.len().saturating_sub(2);
|
||||
let mut best: Option<(f64, f64)> = None;
|
||||
for (i, (w, c)) in self.pts.windows(2).zip(&self.cum).enumerate() {
|
||||
let [a, b] = [w[0], w[1]];
|
||||
let d = b - a;
|
||||
let l2 = d.dot(d);
|
||||
if !l2.is_finite() || l2 <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let t = (p - a).dot(d) / l2;
|
||||
let t = match (self.closed, i == 0, i == last) {
|
||||
(false, true, true) => t,
|
||||
(false, true, false) => t.min(1.0),
|
||||
(false, false, true) => t.max(0.0),
|
||||
_ => t.clamp(0.0, 1.0),
|
||||
};
|
||||
let s = c + t * l2.sqrt();
|
||||
let dist = p.distance(a + d * t) + from.filter(|f| f.is_finite()).map_or(0.0, |f| self.apart(s, f) / 2.0);
|
||||
if dist.is_finite() && best.is_none_or(|(b, _)| dist < b) {
|
||||
best = Some((dist, s));
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
/// How far apart arc lengths `s` and `f` are along the spine: the shorter way round a closed
|
||||
/// spine, across its first anchor.
|
||||
pub fn apart(&self, s: f64, f: f64) -> f64 {
|
||||
let len = self.length();
|
||||
let d = (s - f).abs();
|
||||
if self.closed && len > 0.0 { d.rem_euclid(len).min(len - d.rem_euclid(len)) } else { d }
|
||||
}
|
||||
/// Point and tangent angle (radians) at arc-length fraction `f` (0..1).
|
||||
pub fn at(&self, f: f64) -> (Point, f64) {
|
||||
self.at_length(f.clamp(0.0, 1.0) * self.length())
|
||||
}
|
||||
/// Point and tangent angle (radians) at arc length `s` (clamped to the spine).
|
||||
/// Point and tangent angle (radians) at arc length `s` (clamped to the spine). The point and
|
||||
/// tangent come from the original curve at that arc length, not from the flattened polyline: a
|
||||
/// flattened chord's direction is piecewise constant, so steps oriented to a curved spine with
|
||||
/// `Align to Path` jump between chords instead of following the curve smoothly.
|
||||
pub fn at_length(&self, s: f64) -> (Point, f64) {
|
||||
let last = self.pts.len().saturating_sub(2);
|
||||
let s = if s.is_finite() { s.clamp(0.0, self.length()) } else { 0.0 };
|
||||
let i = match self.cum.binary_search_by(|c| c.total_cmp(&s)) {
|
||||
Ok(i) => i.min(last),
|
||||
Err(i) => i.saturating_sub(1).min(last),
|
||||
};
|
||||
let (Some(p0), Some(p1), Some(c0), Some(c1)) = (self.pts.get(i), self.pts.get(i + 1), self.cum.get(i), self.cum.get(i + 1)) else {
|
||||
return (self.pts.first().copied().unwrap_or_default(), 0.0);
|
||||
};
|
||||
let u = ((s - c0) / (c1 - c0).max(1e-12)).clamp(0.0, 1.0);
|
||||
let d = *p1 - *p0;
|
||||
(p0.lerp(*p1, u), d.y.atan2(d.x))
|
||||
let Some(sp) = self.path.subpaths.first() else { return (self.pts.first().copied().unwrap_or_default(), 0.0) };
|
||||
let n = sp.segment_count();
|
||||
let mut start = 0.0;
|
||||
for i in 0..n {
|
||||
let c = sp.segment(i);
|
||||
let end = self.anchor_length(i + 1).unwrap_or(self.length());
|
||||
if s <= end || i + 1 == n {
|
||||
let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9);
|
||||
let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0);
|
||||
let e = c.eval(t);
|
||||
let tv = c.deriv().eval(t).to_vec2();
|
||||
// Where a handle sits on its anchor the derivative vanishes there: take the
|
||||
// direction between points a little before and after instead.
|
||||
let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv };
|
||||
return (Point::new(e.x, e.y), tv.y.atan2(tv.x));
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
// Only a spine without segments gets here: the loop returns at the last one.
|
||||
(self.pts.first().copied().unwrap_or_default(), 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1102,13 +1254,19 @@ fn requested_steps(keys: &[Arc<Node>], spec: &BlendSpec, rail: Option<&Rail>) ->
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Most steps `spacing` makes between two keys, whatever their size and distance
|
||||
/// ([`blend_step_count`]'s clamps).
|
||||
fn most_steps(spacing: BlendSpacing) -> usize {
|
||||
/// Most steps `spacing` makes between keys `a` and `b`, whatever their size and distance
|
||||
/// ([`blend_step_count`]'s clamps). A copy of a blend is moved and scaled, never recolored
|
||||
/// ([`Shape::Other`]), so Smooth Color between colors that differ makes no more than their color
|
||||
/// change asks for, whatever the copy's scale or rotation. By distance, a copy turned by Align to
|
||||
/// Path can measure its edges differently, so it counts as up to 1000.
|
||||
fn most_steps(a: &Node, b: &Node, spacing: BlendSpacing) -> usize {
|
||||
match spacing {
|
||||
BlendSpacing::Steps(n) => n.clamp(1, 1000) as usize,
|
||||
BlendSpacing::Distance(_) => 1000,
|
||||
BlendSpacing::SmoothColor => 256,
|
||||
BlendSpacing::SmoothColor => match color_distance(a, b) {
|
||||
Some(d) if d * 255.0 > 1e-3 => level_steps(d) as usize,
|
||||
_ => 1000,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1136,8 +1294,8 @@ struct StepCount {
|
||||
impl StepCount {
|
||||
/// Steps the blends in `n` make in all when drawn, each keeping to [`MAX_BLEND_STEPS`].
|
||||
/// `copy`: `n` is part of a blend's step, a copy moved and scaled into place. A blend spaced
|
||||
/// by distance (or by distance where the colours match) makes more steps scaled up, so a
|
||||
/// copy counts the most its spacing can make between each pair, an upper bound for any scale.
|
||||
/// by distance, or by Smooth Color, can make more steps scaled up, so a copy counts the most
|
||||
/// its spacing can make between each pair ([`most_steps`]), an upper bound for any scale.
|
||||
fn node(&mut self, n: &Node, copy: bool) -> usize {
|
||||
let at = (std::ptr::from_ref(n) as usize, copy);
|
||||
if let Some(&known) = self.known.get(&at) {
|
||||
@@ -1203,7 +1361,11 @@ impl StepCount {
|
||||
fn most(&mut self, keys: &[Arc<Node>], spec: &BlendSpec) -> usize {
|
||||
let inside = self.nodes(keys, true);
|
||||
let each = self.steps(keys);
|
||||
let demand = each.iter().map(|&c| c.saturating_mul(most_steps(spec.spacing))).fold(0, usize::saturating_add);
|
||||
let most = keys.windows(2).map(|w| match w {
|
||||
[a, b] => most_steps(a, b, spec.spacing),
|
||||
_ => 0,
|
||||
});
|
||||
let demand = each.iter().zip(most).map(|(&c, m)| c.saturating_mul(m)).fold(0, usize::saturating_add);
|
||||
inside.saturating_add(demand.min(MAX_BLEND_STEPS.saturating_sub(inside)))
|
||||
}
|
||||
}
|
||||
@@ -1300,6 +1462,45 @@ mod tests {
|
||||
assert_eq!(out[0].geometric_bounds().unwrap().center(), Point::new(5.0, 5.0), "keys stay put");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orientations_follow_a_curved_spine_smoothly() {
|
||||
// A curved spine: from (0, 0) with handles (+50, +50) / (-50, -50) to (100, 0) with handles
|
||||
// (+50, -50) / (-50, +50) — the classic up-bow arc.
|
||||
let spine = PathData::single(SubPath::new(
|
||||
vec![Anchor::smooth(Point::new(0.0, 0.0), Point::new(50.0, 50.0)), Anchor::smooth(Point::new(100.0, 0.0), Point::new(50.0, -50.0))],
|
||||
false,
|
||||
));
|
||||
let sp = Spine::new(&spine).unwrap();
|
||||
// Many steps along the bow: each step's tangent comes from the curve at its arc length,
|
||||
// not from a flattened chord — so the orientations must sweep the true angle, smoothly.
|
||||
let len = sp.length();
|
||||
let mut prev: Option<f64> = None;
|
||||
for i in 1..=200 {
|
||||
let (pt, ang) = sp.at_length(len * i as f64 / 201.0);
|
||||
if let Some(p) = prev {
|
||||
let step = (ang - p).abs().min(2.0 * std::f64::consts::PI - (ang - p).abs());
|
||||
assert!(step < 0.1, "tangent step {} is too big at {} ({}, {})", step, i, pt.x, pt.y);
|
||||
}
|
||||
prev = Some(ang);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the spine starts at an anchor whose handle sits on it, the first step still faces along
|
||||
/// the curve (towards the next handle), not along a direction of zero length.
|
||||
#[test]
|
||||
fn a_handle_on_its_anchor_still_gives_the_curve_direction() {
|
||||
let spine = PathData::single(SubPath::new(
|
||||
vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::smooth(Point::new(100.0, 0.0), Point::new(150.0, -50.0))],
|
||||
false,
|
||||
));
|
||||
let sp = Spine::new(&spine).unwrap();
|
||||
let (p, angle) = sp.at_length(0.0);
|
||||
assert!(p.x.abs() < 1e-6 && p.y.abs() < 1e-6, "{p:?}");
|
||||
assert!((angle - std::f64::consts::FRAC_PI_4).abs() < 0.05, "faces the in handle at (50, 50): {angle}");
|
||||
let (_, end) = sp.at_length(sp.length());
|
||||
assert!(end.is_finite(), "{end}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn easing_keeps_the_ends_and_stays_monotone() {
|
||||
use crate::live::{BlendEase, BlendEaseType as K};
|
||||
@@ -1588,4 +1789,180 @@ mod tests {
|
||||
assert_eq!(blend_steps(&keys[..50], &spec), vec![1000; 49]);
|
||||
assert_eq!(fit_steps(&[10, 20], &[1, 1], MAX_BLEND_STEPS), vec![0, 0]);
|
||||
}
|
||||
|
||||
/// A key for the Smooth Color tests: a rectangle of `size` (width, height) centered on `c`,
|
||||
/// with `fill`, and `stroke` at `width`.
|
||||
fn smooth_key(c: (f64, f64), size: (f64, f64), fill: Paint, stroke: Paint, width: f64) -> Node {
|
||||
let ((cx, cy), (w, h)) = (c, size);
|
||||
let rect = Rect::new(cx - w / 2.0, cy - h / 2.0, cx + w / 2.0, cy + h / 2.0);
|
||||
Node::path(NodeId(1), shapes::rectangle(rect), Appearance::basic(fill, stroke, width))
|
||||
}
|
||||
|
||||
/// Smooth Color's steps between two filled `size` rectangles centered on `a` and `b`.
|
||||
fn smooth(a: (f64, f64), b: (f64, f64), size: (f64, f64), fill_a: Color, fill_b: Color) -> usize {
|
||||
let key = |c, fill| smooth_key(c, size, Paint::solid(fill), Paint::None, 0.0);
|
||||
blend_step_count(&key(a, fill_a), &key(b, fill_b), BlendSpacing::SmoothColor, a.0.max(b.0) - a.0.min(b.0))
|
||||
}
|
||||
|
||||
/// Smooth Color counts 255 steps for a full change of the channel that changes most, a half
|
||||
/// step rounding down: RGB values over 256, CMYK and gray in percent, a spot color by its
|
||||
/// tint, colors in different spaces by their RGB values over 255, a fill or a stroke,
|
||||
/// whichever changes more.
|
||||
#[test]
|
||||
fn smooth_color_counts_a_step_per_level_of_color_change() {
|
||||
let (a, b, size) = ((50.0, 150.0), (250.0, 150.0), (20.0, 20.0));
|
||||
let black = Color::rgb8(0, 0, 0);
|
||||
for (level, steps) in [(1, 1), (2, 2), (5, 5), (64, 64), (127, 127), (128, 127), (129, 128), (200, 199), (254, 253), (255, 254)] {
|
||||
assert_eq!(smooth(a, b, size, black, Color::rgb8(level, 0, 0)), steps, "black to red {level}");
|
||||
assert_eq!(smooth(a, b, size, black, Color::rgb8(level, level, level)), steps, "black to gray {level}");
|
||||
}
|
||||
assert_eq!(smooth(a, b, size, Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255)), 254);
|
||||
assert_eq!(smooth(a, b, size, black, Color::rgb8(64, 128, 0)), 127, "the channel that changes most");
|
||||
assert_eq!(smooth(a, b, size, Color::rgb8(17, 42, 93), Color::rgb8(91, 147, 220)), 127);
|
||||
for (percent, steps) in [(0.2, 1), (1.0, 3), (5.0, 13), (10.0, 25), (25.0, 64), (50.0, 127), (100.0, 254)] {
|
||||
let p = percent / 100.0;
|
||||
assert_eq!(smooth(a, b, size, Color::cmyk(0.0, 0.0, 0.0, 0.0), Color::cmyk(p, 0.0, 0.0, 0.0)), steps, "cyan {percent}%");
|
||||
assert_eq!(smooth(a, b, size, Color::gray(0.0), Color::gray(p)), steps, "gray {percent}%");
|
||||
}
|
||||
let spot = |tint: f32| Paint::Solid { color: Color::rgb8(255, 0, 0).tinted(tint), swatch: Some("Spot".into()), tint };
|
||||
let key = |c, fill| smooth_key(c, size, fill, Paint::None, 0.0);
|
||||
assert_eq!(blend_step_count(&key(a, spot(1.0)), &key(b, spot(0.5)), BlendSpacing::SmoothColor, 200.0), 127, "a tint of 50%");
|
||||
let stroked = |c, fill: Color, stroke: Color| smooth_key(c, size, Paint::solid(fill), Paint::solid(stroke), 1.0);
|
||||
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
|
||||
assert_eq!(blend_step_count(&stroked(a, red, black), &stroked(b, red, blue), BlendSpacing::SmoothColor, 200.0), 254, "the stroke changes");
|
||||
let outline = |c, stroke: Color| smooth_key(c, size, Paint::None, Paint::solid(stroke), 1.0);
|
||||
assert_eq!(blend_step_count(&outline(a, red), &outline(b, blue), BlendSpacing::SmoothColor, 200.0), 254, "strokes alone");
|
||||
assert_eq!(smooth(a, b, size, Color::rgb8(255, 255, 127), Color::cmyk(0.0, 0.0, 0.0, 0.0)), 128, "RGB against CMYK white");
|
||||
assert_eq!(smooth(a, b, size, Color::rgb8(255, 255, 127), Color::rgb8(255, 255, 255)), 127, "RGB against RGB white");
|
||||
}
|
||||
|
||||
/// Smooth Color reads the colors of group members paired in order and of text runs, and
|
||||
/// counts a solid paint against no paint by distance, since such a paint switches halfway
|
||||
/// instead of mixing.
|
||||
#[test]
|
||||
fn smooth_color_reads_the_colors_inside_groups_and_text() {
|
||||
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
|
||||
let square = |x: f64, c: Color| Arc::new(smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(c), Paint::None, 0.0));
|
||||
let group = |x: f64, top: Color| Node::new(NodeId(1), NodeKind::Group { children: vec![square(x, red), square(x, top)], clip: false });
|
||||
let steps = |a: &Node, b: &Node| blend_step_count(a, b, BlendSpacing::SmoothColor, 200.0);
|
||||
assert_eq!(steps(&group(50.0, red), &group(250.0, blue)), 254, "groups whose members change color");
|
||||
assert_eq!(steps(&group(50.0, red), &group(250.0, red)), 9, "groups of the same colors");
|
||||
let text = |x: f64, c: Color| {
|
||||
let style = crate::CharStyle { fill: Paint::solid(c), ..Default::default() };
|
||||
Node::new(NodeId(1), NodeKind::Text(Box::new(crate::TextObject::point(Point::new(x, 150.0), "Hi", style))))
|
||||
};
|
||||
assert_eq!(steps(&text(50.0, red), &text(250.0, blue)), 254, "text whose runs change color");
|
||||
let mut two_runs = text(250.0, red);
|
||||
if let NodeKind::Text(t) = &mut two_runs.kind {
|
||||
let style = crate::CharStyle { fill: Paint::solid(blue), ..t.runs[0].style.clone() };
|
||||
t.runs.push(crate::text::TextRun::new("Hi", style));
|
||||
}
|
||||
assert_eq!(steps(&text(50.0, red), &two_runs), 254, "a run that turns blue against one red run");
|
||||
let empty = |x: f64| smooth_key((x, 150.0), (20.0, 20.0), Paint::None, Paint::None, 0.0);
|
||||
assert_eq!(steps(&smooth_key((50.0, 150.0), (20.0, 20.0), Paint::solid(red), Paint::None, 0.0), &empty(250.0)), 9, "a fill against none");
|
||||
let nothing = |c: Color| Node::path(NodeId(1), PathData::new(vec![]), Appearance::basic(Paint::solid(c), Paint::None, 0.0));
|
||||
assert_eq!(steps(¬hing(red), ¬hing(blue)), 254, "keys without bounds whose colors differ");
|
||||
assert_eq!(steps(¬hing(red), ¬hing(red)), 1, "keys without bounds of the same color");
|
||||
}
|
||||
|
||||
/// Smooth Color makes at most eight steps per point of the largest of the keys' widths and
|
||||
/// heights and the distance between their centers along either axis.
|
||||
#[test]
|
||||
fn smooth_color_makes_at_most_eight_steps_a_point() {
|
||||
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
|
||||
for (dx, steps) in [(0.0, 160), (20.0, 160), (20.1, 161), (25.0, 200), (31.5, 252), (40.0, 254)] {
|
||||
assert_eq!(smooth((50.0, 150.0), (50.0 + dx, 150.0), (20.0, 20.0), red, blue), steps, "{dx} pt apart");
|
||||
}
|
||||
assert_eq!(smooth((100.0, 150.0), (100.0, 175.0), (20.0, 20.0), red, blue), 200, "25 pt apart vertically");
|
||||
assert_eq!(smooth((100.0, 150.0), (100.0, 150.0), (5.0, 5.0), red, blue), 40, "5 pt squares on each other");
|
||||
assert_eq!(smooth((100.0, 150.0), (100.0, 150.0), (25.0, 5.0), red, blue), 200, "the longer side counts");
|
||||
assert_eq!(smooth((100.0, 150.0), (100.0, 150.0), (1.0, 1.0), red, blue), 8);
|
||||
}
|
||||
|
||||
/// Smooth Color between keys of the same colors counts the largest distance between their
|
||||
/// corresponding visible edges in mean key widths or heights, rounded, less one; so do keys
|
||||
/// with gradients, whatever their colors.
|
||||
#[test]
|
||||
fn smooth_color_between_the_same_colors_counts_by_distance() {
|
||||
let red = Color::rgb8(255, 0, 0);
|
||||
let same = |a, b, size| smooth(a, b, size, red, red);
|
||||
for (dx, steps) in [(25.0, 1), (50.0, 2), (100.0, 4), (200.0, 9), (400.0, 19), (800.0, 39)] {
|
||||
assert_eq!(same((50.0, 150.0), (50.0 + dx, 150.0), (20.0, 20.0)), steps, "20 pt squares {dx} pt apart");
|
||||
}
|
||||
for (side, steps) in [(5.0, 39), (10.0, 19), (40.0, 4), (80.0, 2)] {
|
||||
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (side, side)), steps, "{side} pt squares");
|
||||
}
|
||||
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (80.0, 10.0)), 2, "wide");
|
||||
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (10.0, 80.0)), 19, "tall");
|
||||
assert_eq!(same((50.0, 250.0), (250.0, 50.0), (20.0, 20.0)), 9, "diagonal");
|
||||
assert_eq!(same((50.0, 250.0), (250.0, 50.0), (80.0, 10.0)), 19, "wide and diagonal");
|
||||
assert_eq!(same((50.0, 150.0), (1050.0, 150.0), (1.0, 1.0)), 999);
|
||||
assert_eq!(same((50.0, 150.0), (1052.0, 150.0), (1.0, 1.0)), 1000, "at most 1000");
|
||||
assert_eq!(same((50.0, 150.0), (50.0, 150.0), (20.0, 20.0)), 1, "at least one");
|
||||
assert_eq!(same((50.0, 150.0), (250.0, 150.0), (0.0, 20.0)), 9, "vertical lines, measured in their height");
|
||||
assert_eq!(same((50.0, 150.0), (50.0, 350.0), (20.0, 0.0)), 9, "horizontal lines, measured in their width");
|
||||
assert_eq!(same((50.0, 150.0), (60.0, 150.0), (0.0, 0.0)), 9, "points, measured in points");
|
||||
let key = |c, size, stroke: f64| smooth_key(c, size, Paint::solid(red), Paint::solid(Color::BLACK), stroke);
|
||||
let wide =
|
||||
blend_step_count(&key((50.0, 150.0), (10.0, 20.0), 0.0), &key((250.0, 150.0), (80.0, 20.0), 0.0), BlendSpacing::SmoothColor, 200.0);
|
||||
assert_eq!(wide, 4, "keys of different widths");
|
||||
let strokes =
|
||||
blend_step_count(&key((50.0, 150.0), (20.0, 20.0), 1.0), &key((250.0, 150.0), (20.0, 20.0), 10.0), BlendSpacing::SmoothColor, 200.0);
|
||||
assert_eq!(strokes, 7, "strokes widen the visible edges");
|
||||
let gradient = |a: Color, b: Color| {
|
||||
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
|
||||
Default::default(),
|
||||
vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)],
|
||||
))))
|
||||
};
|
||||
let shaded = |c, fill| smooth_key(c, (20.0, 20.0), fill, Paint::None, 0.0);
|
||||
let blue = Color::rgb8(0, 0, 255);
|
||||
for (from, to) in [(gradient(red, blue), gradient(red, blue)), (gradient(red, blue), gradient(blue, red))] {
|
||||
assert_eq!(blend_step_count(&shaded((50.0, 150.0), from), &shaded((250.0, 150.0), to), BlendSpacing::SmoothColor, 200.0), 9);
|
||||
}
|
||||
}
|
||||
|
||||
/// A Smooth Color blend counts each pair of keys on its own.
|
||||
#[test]
|
||||
fn smooth_color_counts_each_pair_of_keys() {
|
||||
let key = |x: f64, c: Color| Arc::new(smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(c), Paint::None, 0.0));
|
||||
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
|
||||
let spec = BlendSpec::default();
|
||||
assert_eq!(blend_steps(&[key(50.0, red), key(150.0, red), key(250.0, blue)], &spec), vec![4, 254]);
|
||||
assert_eq!(blend_steps(&[key(50.0, red), key(150.0, blue), key(250.0, red)], &spec), vec![254, 254]);
|
||||
}
|
||||
|
||||
/// A Smooth Color blend between different colors inside another blend's keys counts as the
|
||||
/// steps its colors ask for, so the outer blend keeps the steps it asks for within
|
||||
/// [`MAX_BLEND_STEPS`]: 200 steps, each a copy making 254 more. The copies keep their keys'
|
||||
/// colors, also halfway between a red-to-blue and a blue-to-red blend.
|
||||
#[test]
|
||||
fn a_smooth_color_blend_in_a_key_counts_its_color_steps() {
|
||||
let (red, blue) = (Color::rgb8(255, 0, 0), Color::rgb8(0, 0, 255));
|
||||
let key = |x: f64, c: Color| smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(c), Paint::None, 0.0);
|
||||
let inner = |x: f64, from: Color, to: Color| blend_of(key(x, from), key(x + 100.0, to), BlendSpacing::SmoothColor);
|
||||
let outer = blend_of(inner(0.0, red, blue), inner(500.0, red, blue), BlendSpacing::Steps(200));
|
||||
let (keys, spec) = blend_parts(&outer).unwrap();
|
||||
assert_eq!(blend_steps(keys, spec), vec![200]);
|
||||
let crossed = blend_of(inner(0.0, red, blue), inner(500.0, blue, red), BlendSpacing::Steps(199));
|
||||
let (keys, spec) = blend_parts(&crossed).unwrap();
|
||||
assert_eq!(blend_steps(keys, spec), vec![199]);
|
||||
let drawn = blend_expand(keys, spec);
|
||||
let Some(NodeKind::Blend { children, .. }) = drawn.get(100).map(|n| &n.kind) else { panic!("a copy of a blend halfway") };
|
||||
let fills: Vec<_> = children.iter().map(|k| k.appearance.fill_paint().color()).collect();
|
||||
assert!(fills == [Some(red), Some(blue)] || fills == [Some(blue), Some(red)], "{fills:?}");
|
||||
}
|
||||
|
||||
/// A Smooth Color blend between the same colors inside another blend's keys counts as up to
|
||||
/// 1000 steps, which a copy turned to a path can ask for: 200 steps of copies of it come
|
||||
/// down to 99.
|
||||
#[test]
|
||||
fn a_smooth_color_blend_of_the_same_colors_in_a_key_counts_up_to_1000_steps() {
|
||||
let red = Color::rgb8(255, 0, 0);
|
||||
let key = |x: f64| smooth_key((x, 150.0), (20.0, 20.0), Paint::solid(red), Paint::None, 0.0);
|
||||
let inner = |x: f64| blend_of(key(x), key(x + 100.0), BlendSpacing::SmoothColor);
|
||||
let outer = blend_of(inner(0.0), inner(500.0), BlendSpacing::Steps(200));
|
||||
let (keys, spec) = blend_parts(&outer).unwrap();
|
||||
assert_eq!(blend_steps(keys, spec), vec![99]);
|
||||
}
|
||||
}
|
||||
@@ -313,8 +313,8 @@ mod tests {
|
||||
d.guides = vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d.layers[0].id), ..Guide::new(true, 5.0) }];
|
||||
d.saved_selections = vec![crate::records::SavedSelection { name: "s".into(), objects: vec![NodeId(10), NodeId(11)] }].into();
|
||||
d.assets = vec![
|
||||
crate::assets::ExportAsset { id: 1, name: "far".into(), nodes: vec![NodeId(11)] },
|
||||
crate::assets::ExportAsset { id: 2, name: "both".into(), nodes: vec![NodeId(10), NodeId(11)] },
|
||||
crate::assets::ExportAsset { id: 1, name: "far".into(), nodes: vec![NodeId(11)], format_3d: None },
|
||||
crate::assets::ExportAsset { id: 2, name: "both".into(), nodes: vec![NodeId(10), NodeId(11)], format_3d: None },
|
||||
];
|
||||
d.variables.bindings.insert(NodeId(11), ["v".to_string()].into());
|
||||
d.variables.bindings.insert(NodeId(10), ["w".to_string()].into());
|
||||
|
||||
@@ -195,6 +195,24 @@ impl ImageBlob {
|
||||
jpeg_components(&self.bytes) == Some(4) || tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(8 | 16)))
|
||||
}
|
||||
|
||||
/// Does the image hold CMYK samples of 16 bits (a CMYK TIFF), which [`Self::cmyk`] gives at 8
|
||||
/// bits? Reads only its header.
|
||||
pub fn is_cmyk16(&self) -> bool {
|
||||
tiff(&self.bytes).is_some_and(|(t, _)| matches!(t, tiff::ColorType::CMYK(16)))
|
||||
}
|
||||
|
||||
/// The width and height a JPEG or TIFF says it has, for any color type. Reads only its header.
|
||||
pub fn header_size(&self) -> Option<(u32, u32)> {
|
||||
let bytes = self.bytes.as_slice();
|
||||
if bytes.starts_with(&[0xFF, 0xD8]) {
|
||||
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
|
||||
d.decode_headers().ok()?;
|
||||
let (w, h) = d.dimensions()?;
|
||||
return Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?));
|
||||
}
|
||||
tiff(bytes).and_then(|(_, mut d)| d.dimensions().ok())
|
||||
}
|
||||
|
||||
/// The ink amounts of a CMYK image; `None` for other images, and ones that can't be decoded
|
||||
/// or are larger than [`MAX_CMYK_PIXELS`].
|
||||
pub fn cmyk(&self) -> Option<Inks> {
|
||||
@@ -633,6 +651,38 @@ mod tests {
|
||||
assert_eq!(rgb.get_pixel(1, 0).0, [0, 255, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_gives_the_size_without_the_samples() {
|
||||
assert_eq!(ImageBlob::cmyk_tiff(&inks()).unwrap().header_size(), Some((3, 2)));
|
||||
// A CMYK TIFF of 6000 × 6000 pixels whose samples aren't there.
|
||||
let mut t = b"II*\0\x08\0\0\0\x07\0".to_vec();
|
||||
// Bits per sample: four values, after the entries (8 + 2 + 7 × 12 + 4 = 98).
|
||||
let entries = [
|
||||
(256u16, 4u16, 1u32, 6000u32),
|
||||
(257, 4, 1, 6000),
|
||||
(258, 3, 4, 98),
|
||||
(262, 3, 1, 5),
|
||||
(273, 4, 1, 106),
|
||||
(277, 3, 1, 4),
|
||||
(279, 4, 1, 144_000_000),
|
||||
];
|
||||
for (tag, kind, count, value) in entries {
|
||||
t.extend_from_slice(&tag.to_le_bytes());
|
||||
t.extend_from_slice(&kind.to_le_bytes());
|
||||
t.extend_from_slice(&count.to_le_bytes());
|
||||
t.extend_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
t.extend_from_slice(&0u32.to_le_bytes());
|
||||
t.extend_from_slice(&[8, 0, 8, 0, 8, 0, 8, 0]);
|
||||
let big = ImageBlob::new("image/tiff", t);
|
||||
assert!(big.is_cmyk());
|
||||
assert_eq!(big.header_size(), Some((6000, 6000)));
|
||||
assert_eq!(big.cmyk(), None);
|
||||
let mut png = Vec::new();
|
||||
image::RgbaImage::new(2, 2).write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
assert_eq!(ImageBlob::png(png).header_size(), None, "not a JPEG or TIFF");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmyk_image_samples_its_ink_amounts() {
|
||||
let b = ImageBlob::cmyk_tiff(&inks()).unwrap();
|
||||
|
||||
@@ -107,15 +107,21 @@ fn nested_deeper(now: &[Arc<Node>], depth: usize) -> bool {
|
||||
/// an opacity mask too deep are left out); what it held stays hidden or locked as it was. Returns
|
||||
/// whether anything changed. Recurses no deeper than the cap.
|
||||
fn limit(nodes: &mut Vec<Arc<Node>>, depth: usize) -> bool {
|
||||
let mut changed = false;
|
||||
let mut i = 0;
|
||||
while let Some(n) = nodes.get_mut(i) {
|
||||
if !nested_deeper(std::slice::from_ref(n), depth) {
|
||||
i += 1;
|
||||
if !nested_deeper(nodes, depth) {
|
||||
return false;
|
||||
}
|
||||
// The list is rebuilt in order rather than spliced in place: replacing one container of many
|
||||
// by what it holds would move all the siblings after it each time.
|
||||
let mut out = Vec::with_capacity(nodes.len());
|
||||
// What is left to look at, the next one last.
|
||||
let mut left: Vec<Arc<Node>> = std::mem::take(nodes);
|
||||
left.reverse();
|
||||
while let Some(mut a) = left.pop() {
|
||||
if !nested_deeper(std::slice::from_ref(&a), depth) {
|
||||
out.push(a);
|
||||
continue;
|
||||
}
|
||||
changed = true;
|
||||
let n = Arc::make_mut(n);
|
||||
let n = Arc::make_mut(&mut a);
|
||||
if n.extras().mask.as_ref().is_some_and(|m| nested_deeper(std::slice::from_ref(&m.art), depth + 1)) {
|
||||
n.extras_mut().mask = None;
|
||||
}
|
||||
@@ -123,7 +129,7 @@ fn limit(nodes: &mut Vec<Arc<Node>>, depth: usize) -> bool {
|
||||
if let Some(ch) = n.children_mut() {
|
||||
limit(ch, depth + 1);
|
||||
}
|
||||
i += 1;
|
||||
out.push(a);
|
||||
continue;
|
||||
}
|
||||
let clip = matches!(n.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. });
|
||||
@@ -140,9 +146,10 @@ fn limit(nodes: &mut Vec<Arc<Node>>, depth: usize) -> bool {
|
||||
}
|
||||
}
|
||||
// What it held takes its place, and is looked at in its turn.
|
||||
nodes.splice(i..=i, held);
|
||||
left.extend(held.into_iter().rev());
|
||||
}
|
||||
changed
|
||||
*nodes = out;
|
||||
true
|
||||
}
|
||||
|
||||
/// A symbol (`false`) or a pattern (`true`) of the document, by name: what art draws by name, an
|
||||
@@ -439,6 +446,24 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_containers_at_the_cap_are_merged_in_order() {
|
||||
// A group just above the cap holding many groups of two paths each: every group is
|
||||
// replaced by its two paths, in order (in time linear in their number).
|
||||
const PAIRS: u64 = 50_000;
|
||||
let path = |id| Arc::new(Node::path(NodeId(id), Default::default(), Default::default()));
|
||||
let pairs = (0..PAIRS).map(|i| Arc::new(Node::group(NodeId(1_000_000 + i), vec![path(2 * i + 1), path(2 * i + 2)]))).collect();
|
||||
let mut art = Arc::new(Node::group(NodeId(500_000), pairs));
|
||||
for i in 0..MAX_DEPTH - 3 {
|
||||
art = Arc::new(Node::group(NodeId(600_000 + i as u64), vec![art]));
|
||||
}
|
||||
let mut d = doc(art);
|
||||
assert!(d.limit_depth());
|
||||
assert!(!d.too_deep(None));
|
||||
let holder = d.node(NodeId(500_000)).and_then(Node::children).map(|c| c.iter().map(|c| c.id.0).collect::<Vec<_>>());
|
||||
assert_eq!(holder, Some((1..=2 * PAIRS).collect()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clipping_path_and_a_mask_too_deep_are_left_out_and_hidden_art_stays_hidden() {
|
||||
let mut inner = Node::new(NodeId(9000), NodeKind::Group { children: vec![nested(0), nested(0)], clip: true });
|
||||
|
||||
@@ -34,6 +34,7 @@ impl Document {
|
||||
graphic_styles,
|
||||
char_styles,
|
||||
para_styles,
|
||||
composite_fonts,
|
||||
text_threads,
|
||||
symbols,
|
||||
graph_designs,
|
||||
@@ -68,10 +69,12 @@ impl Document {
|
||||
print_setup,
|
||||
assets,
|
||||
svg_scripts,
|
||||
svg_filters,
|
||||
puppet,
|
||||
new_art,
|
||||
dimensions,
|
||||
retired_artboard_id: _,
|
||||
opened_artboard: _,
|
||||
index: _,
|
||||
} = self;
|
||||
*version == other.version
|
||||
@@ -88,6 +91,7 @@ impl Document {
|
||||
&& *graphic_styles == other.graphic_styles
|
||||
&& *char_styles == other.char_styles
|
||||
&& *para_styles == other.para_styles
|
||||
&& *composite_fonts == other.composite_fonts
|
||||
&& *text_threads == other.text_threads
|
||||
&& symbols.len() == other.symbols.len()
|
||||
&& symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
@@ -134,6 +138,7 @@ impl Document {
|
||||
&& *print_setup == other.print_setup
|
||||
&& *assets == other.assets
|
||||
&& *svg_scripts == other.svg_scripts
|
||||
&& *svg_filters == other.svg_filters
|
||||
&& match (puppet, &other.puppet) {
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
|
||||
(a, b) => a.is_none() && b.is_none(),
|
||||
@@ -210,6 +215,7 @@ impl Document {
|
||||
graphic_styles: default_graphic_styles().into(),
|
||||
char_styles: Default::default(),
|
||||
para_styles: Default::default(),
|
||||
composite_fonts: Default::default(),
|
||||
text_threads: vec![],
|
||||
symbols: vec![],
|
||||
graph_designs: vec![],
|
||||
@@ -244,10 +250,12 @@ impl Document {
|
||||
print_setup: None,
|
||||
assets: vec![],
|
||||
svg_scripts: vec![],
|
||||
svg_filters: vec![],
|
||||
puppet: None,
|
||||
new_art: Default::default(),
|
||||
dimensions: false,
|
||||
retired_artboard_id: Default::default(),
|
||||
opened_artboard: None,
|
||||
index: Default::default(),
|
||||
};
|
||||
let id = d.alloc_id();
|
||||
@@ -350,6 +358,7 @@ impl Document {
|
||||
}
|
||||
false
|
||||
}
|
||||
crate::id_index::note_tree_walk();
|
||||
let mut p = vec![];
|
||||
find(&self.layers, id, &mut p).then_some(p)
|
||||
}
|
||||
@@ -391,6 +400,7 @@ impl Document {
|
||||
});
|
||||
}
|
||||
if !want.is_empty() {
|
||||
crate::id_index::note_tree_walk();
|
||||
let mut rest = HashMap::with_capacity(want.len());
|
||||
walk(&self.layers, &want, &mut Vec::new(), &mut rest);
|
||||
out.extend(rest);
|
||||
|
||||
@@ -2,8 +2,8 @@ use super::graphic_style::GraphicStyle;
|
||||
use super::limits::MAX_NEXT_ID;
|
||||
use super::records::{ImageBlob, SavedSelection, SavedView};
|
||||
use super::{
|
||||
Arc, Document, ImageObject, Node, NodeKind, SYMBOL_EXPORT_TYPE, SYMBOL_NINE_SLICE, SYMBOL_REGISTRATION, SymbolExportType, SymbolNineSlice,
|
||||
SymbolRegistration,
|
||||
Arc, Document, EnvelopeKind, ImageObject, LiveShape, Node, NodeKind, Point, SYMBOL_EXPORT_TYPE, SYMBOL_NINE_SLICE, SYMBOL_REGISTRATION,
|
||||
SymbolExportType, SymbolNineSlice, SymbolRegistration, placed_document,
|
||||
};
|
||||
|
||||
impl Document {
|
||||
@@ -99,13 +99,15 @@ impl Document {
|
||||
}
|
||||
|
||||
/// Leave opacity-mask editing and symbol editing: drop the temporary editing layer, a working
|
||||
/// copy of art the mask or the symbol already holds (the engine syncs it after every edit).
|
||||
/// copy of art the mask or the symbol already holds (the engine syncs it after every edit). The
|
||||
/// layer is removed wherever it is, also as a sublayer of another layer; an id that names
|
||||
/// anything other than a layer is left alone.
|
||||
pub fn drop_edit_modes(&mut self) {
|
||||
if let Some(me) = self.mask_edit.take() {
|
||||
self.layers.retain(|l| l.id != me.layer);
|
||||
}
|
||||
if let Some(se) = self.symbol_edit.take() {
|
||||
self.layers.retain(|l| l.id != se.layer);
|
||||
let layers = [self.mask_edit.take().map(|me| me.layer), self.symbol_edit.take().map(|se| se.layer)];
|
||||
for id in layers.into_iter().flatten() {
|
||||
if self.node(id).is_some_and(Node::is_layer) {
|
||||
let _ = self.remove(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,6 +122,165 @@ impl Document {
|
||||
d.drop_edit_modes();
|
||||
std::borrow::Cow::Owned(d)
|
||||
}
|
||||
|
||||
/// Does `wants` hold for a node anywhere in the document's art: the layers, symbol definitions,
|
||||
/// graph designs, pattern swatches (the one being edited included) and their opacity masks?
|
||||
pub fn any_node(&self, wants: impl Fn(&Node) -> bool) -> bool {
|
||||
let roots = self
|
||||
.layers
|
||||
.iter()
|
||||
.chain(self.symbols.iter().map(|s| &s.art))
|
||||
.chain(self.graph_designs.iter().map(|g| &g.art))
|
||||
.chain(self.patterns.iter().flat_map(|p| p.art.iter()))
|
||||
.chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter()));
|
||||
let mut any = false;
|
||||
for root in roots {
|
||||
crate::swatches::walk_with_masks(root, &mut |n| any |= wants(n));
|
||||
}
|
||||
any
|
||||
}
|
||||
|
||||
/// Change with `f` every node for which `wants` holds, anywhere in the document's art (as
|
||||
/// [`Self::any_node`] looks). Only the trees that hold such a node are copied out of the art
|
||||
/// they share.
|
||||
pub fn edit_nodes_where(&mut self, wants: impl Fn(&Node) -> bool, mut f: impl FnMut(&mut Node)) {
|
||||
let roots = self
|
||||
.layers
|
||||
.iter_mut()
|
||||
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
|
||||
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
|
||||
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
|
||||
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
|
||||
for root in roots {
|
||||
edit_branches_where(root, &wants, &mut f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Round every path's anchors and handles to `decimals` decimal places: path objects (with
|
||||
/// Live Corners' uncut outlines), blend spines, envelopes' top-object outlines and Intertwine
|
||||
/// areas, in the layers, symbol definitions, graph designs, pattern swatches (the one being
|
||||
/// edited included), opacity masks and the brushes kept as foreign data. Colors, transforms,
|
||||
/// opacity, live shapes' own sizes, meshes and type (its frames and paths included) are left
|
||||
/// as they are.
|
||||
pub fn round_geometry(&mut self, decimals: u8) {
|
||||
let scale = 10f64.powi(i32::from(decimals));
|
||||
let round = |v: f64| {
|
||||
let r = (v * scale).round() / scale;
|
||||
if !r.is_finite() {
|
||||
v
|
||||
} else if r == 0.0 {
|
||||
// `-0.0` is written as `0.0`.
|
||||
0.0
|
||||
} else {
|
||||
r
|
||||
}
|
||||
};
|
||||
let round_path = |path: &mut vectorcraft_geom::PathData| {
|
||||
for a in path.subpaths.iter_mut().flat_map(|s| s.anchors.iter_mut()) {
|
||||
for p in [&mut a.p, &mut a.h_in, &mut a.h_out] {
|
||||
*p = Point::new(round(p.x), round(p.y));
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut fix = |n: &mut Node| {
|
||||
match &mut n.kind {
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
round_path(path);
|
||||
// Live Corners' uncut outline.
|
||||
if let Some(LiveShape::Path { base, .. }) = live.as_deref_mut() {
|
||||
round_path(base);
|
||||
}
|
||||
}
|
||||
NodeKind::Blend { spec, .. } => {
|
||||
if let Some(spine) = &mut spec.spine {
|
||||
round_path(spine);
|
||||
}
|
||||
}
|
||||
NodeKind::Envelope { kind, .. } => {
|
||||
if let EnvelopeKind::TopObject { path, .. } = kind.as_mut() {
|
||||
round_path(path);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(e) = n.extras_if_any() {
|
||||
for area in e.intertwine.as_deref_mut().into_iter().chain(e.intertwine_tiers.iter_mut()) {
|
||||
round_path(area);
|
||||
}
|
||||
}
|
||||
};
|
||||
let roots = self
|
||||
.layers
|
||||
.iter_mut()
|
||||
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
|
||||
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
|
||||
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
|
||||
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
|
||||
for root in roots {
|
||||
placed_document::each_mut(Arc::make_mut(root), &mut fix);
|
||||
}
|
||||
if self.unknown.contains_key("brushes")
|
||||
&& let Some(brushes) = self.unknown.get_mut("brushes")
|
||||
{
|
||||
round_json_paths(brushes, &round);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Change with `f` the nodes of `n`'s tree (opacity-mask art included) for which `wants` holds,
|
||||
/// copying out of the shared art only the branches that hold one.
|
||||
fn edit_branches_where(n: &mut Arc<Node>, wants: &impl Fn(&Node) -> bool, f: &mut impl FnMut(&mut Node)) {
|
||||
let mut any = false;
|
||||
crate::swatches::walk_with_masks(n, &mut |c| any |= wants(c));
|
||||
if !any {
|
||||
return;
|
||||
}
|
||||
let node = Arc::make_mut(n);
|
||||
if wants(node) {
|
||||
f(node);
|
||||
}
|
||||
if let Some(m) = node.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
edit_branches_where(&mut m.art, wants, f);
|
||||
}
|
||||
for c in node.children_mut().into_iter().flatten() {
|
||||
edit_branches_where(c, wants, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// Round with `round` the anchors of the paths in `v`, nodes in their file form kept as JSON: every
|
||||
/// `{"subpaths": [{"anchors": [{"p", "in", "out"}]}]}` outside type (`{"type": "text"}`), as
|
||||
/// [`Document::round_geometry`] rounds the nodes it holds.
|
||||
fn round_json_paths(v: &mut serde_json::Value, round: &impl Fn(f64) -> f64) {
|
||||
use serde_json::Value;
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
if o.get("type").and_then(Value::as_str) == Some("text") {
|
||||
return;
|
||||
}
|
||||
if let Some(subpaths) = o.get_mut("subpaths").and_then(Value::as_array_mut) {
|
||||
let anchors = subpaths.iter_mut().filter_map(|s| s.get_mut("anchors").and_then(Value::as_array_mut)).flatten();
|
||||
for a in anchors.filter_map(Value::as_object_mut) {
|
||||
let points = a.iter_mut().filter(|(k, _)| matches!(k.as_str(), "p" | "in" | "out")).filter_map(|(_, v)| v.as_array_mut());
|
||||
for xy in points {
|
||||
for n in xy.iter_mut().filter(|n| n.is_f64()) {
|
||||
if let Some(r) = n.as_f64().and_then(|x| serde_json::Number::from_f64(round(x))) {
|
||||
*n = Value::Number(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for c in o.values_mut() {
|
||||
round_json_paths(c, round);
|
||||
}
|
||||
}
|
||||
Value::Array(a) => {
|
||||
for c in a {
|
||||
round_json_paths(c, round);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Graphic styles.
|
||||
|
||||