Merge upstream main into perf/post-edit-cascade-4502

This commit is contained in:
el-j committed 2026-11-15 11:04:24 +01:00
commit db4eff146d
2115 files changed
+783168 -40044

No files matched your search

+7
View File
@@ -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"]
+22 -18
View File
@@ -17,21 +17,25 @@ concurrency:
jobs:
affinity3:
runs-on: ubuntu-latest
timeout-minutes: 30
env:
AFFINITY_CORPUS_REQUIRED: "1"
CARGO_PROFILE_DEV_DEBUG: "0"
CARGO_PROFILE_TEST_DEBUG: "0"
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install Rust
uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
with:
toolchain: "1.95"
- name: Fetch pinned and checksum-verified corpus
run: cargo xtask corpus --affinity
- name: Parse every file and freeze actual Affinity 3 feature retention
run: cargo test -p vectorcraft-affinity --all-features -- --nocapture
- name: Check every artboard, native save, SVG, PDF and PSD exports
run: cargo test -p vectorcraft-engine --test affinity_artboards --test affinity_text --test affinity_corpus -- --nocapture
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
timeout-minutes: 30
toolchain: "1.95"
# As before: no craft-fonts, apt packages, wasm target or nextest.
craft-fonts-ref: ""
targets: ""
tools: ""
dev-debug: "0"
env: |
AFFINITY_CORPUS_REQUIRED=1
CARGO_PROFILE_TEST_DEBUG=0
# Its own cache, apart from ci.yml's gate.
cache-version: v1-affinity
command: |
# Pinned and checksum-verified corpus.
cargo xtask corpus --affinity
# Parse every file and freeze actual Affinity 3 feature retention.
cargo test -p vectorcraft-affinity --all-features -- --nocapture
# Every artboard, native save, SVG, PDF and PSD export.
cargo test -p vectorcraft-engine --test affinity_artboards --test affinity_text --test affinity_corpus -- --nocapture
+5
View File
@@ -31,3 +31,8 @@ jobs:
require-craft-fonts: true
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
run-package-check: true
# The test builds of this workspace's largest crates (engine, ui-egui) need more than the
# VM's 12 GB when two compile at once: the build was killed (exit 137) every night with
# four jobs and again with two. One rustc at a time; it still uses every core.
cargo-build-extra-args: "-j 1"
cargo-test-extra-args: "-j 1"
+28
View File
@@ -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
+4
View File
@@ -29,6 +29,10 @@ jobs:
name: Windows installation policy (no app build)
runs-on: windows-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
+22 -22
View File
@@ -13,27 +13,27 @@ on:
workflow_dispatch:
permissions:
contents: read
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
# A newer push to a PR branch cancels its older run.
concurrency:
group: print-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
# Desktop printing on Windows, through the suite's shared gate. Pull requests restore the cache
# but never save one; a manual run on main saves the cache they restore.
windows:
runs-on: windows-2022
timeout-minutes: 90
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@e2a55d2ffb04f378e9626c28d38b36d230d1e12f # master
with:
toolchain: stable
components: clippy
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
key: desktop-print
- run: cargo clippy --locked -p vectorcraft --all-targets -- -D warnings
- run: cargo test --locked -p vectorcraft
- name: Check pending submission and queue refusal feedback
shell: bash
# A filter that matches nothing still passes, so fail unless some test ran.
run: |
cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee printps.log
grep -Eq 'test result: ok\. [1-9][0-9]* passed' printps.log || { echo "::error::tests::printps matched no tests"; exit 1; }
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
os: '["windows-2022"]'
timeout-minutes: 90
# As before: printing builds and tests without craft-fonts, nextest or the wasm target.
craft-fonts-ref: ""
tools: ""
targets: ""
# A filter that matches nothing still passes, so the printps run fails unless some test ran.
command: |
cargo clippy --locked -p vectorcraft --all-targets -- -D warnings
cargo test --locked -p vectorcraft
log="$RUNNER_TEMP/printps.log"
cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log"
grep -Eq 'test result: ok\. [1-9][0-9]* passed' "$log" || { echo "::error::tests::printps matched no tests"; exit 1; }
+13 -37
View File
@@ -3,6 +3,10 @@
name: Release
on:
# A nightly dry run on main: every release build except macOS, nothing signed or released
# (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day.
schedule:
- cron: "52 2 * * *"
push:
branches: [release]
workflow_dispatch:
@@ -20,57 +24,28 @@ concurrency:
cancel-in-progress: false
jobs:
git-sources:
name: Git dependencies come from storytold
runs-on: ubuntu-latest
# Regenerates contributors/contributors.json for the release commit; every build bundles it.
credits:
permissions:
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Git dependencies come from storytold
run: |
set -euo pipefail
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
# Source replacement, patches and path overrides in cargo config never show up
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
# Cargo still reads the legacy .cargo/config.
python3 - <<'PY'
import os, sys, tomllib
for path in (".cargo/config", ".cargo/config.toml"):
if not os.path.exists(path):
continue
config = tomllib.load(open(path, "rb"))
replaced = [name for name, source in config.get("source", {}).items()
if isinstance(source, dict) and "replace-with" in source]
if replaced or "patch" in config or "paths" in config:
print(f"{path} replaces, patches or overrides a source")
sys.exit(1)
PY
# Fails when Cargo.lock is out of date with the manifests.
cargo metadata --locked --format-version 1 > /dev/null
python3 - <<'PY'
import sys, tomllib
lock = tomllib.load(open("Cargo.lock", "rb"))
bad = sorted({p["source"] for p in lock.get("package", [])
if p.get("source", "").startswith("git+")
and not p["source"].startswith("git+https://github.com/storytold/")})
if bad:
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
sys.exit(1)
PY
pull-requests: read
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
release:
needs: git-sources
needs: credits
permissions:
contents: write
packages: write
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
dry-run: ${{ github.event_name == 'schedule' }}
app-name: vectorcraft
app-title: VectorCraft
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
web-craft-fonts: true
version: ${{ inputs.version }}
contributors-artifact: ${{ needs.credits.outputs.artifact-name }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
@@ -81,6 +56,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 }}
+2 -2
View File
@@ -27,8 +27,8 @@ permissions:
jobs:
windows-arm64:
# Immutable supporting workflow revision until the new install contract lands upstream.
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main
with:
app-name: vectorcraft
app-dir: VectorCraft
+66 -13
View File
@@ -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:
@@ -28,7 +78,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
- Creative Commons with redistribution allowed.
- **Every asset file must have a row in [`ASSETS.md`](ASSETS.md)** (path, author, source URL, licence, notes). Put licence texts next to the assets (e.g. `assets/fonts/OFL-*.txt`) and summarize them in `NOTICE`.
- `cargo xtask assets` (run by `cargo xtask ci`) fails on any unattributed asset.
- **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo** (rules: craftrules [`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)). Never commit a font file here; add new fonts to craft-fonts. The app uses it only through the optional `CRAFT_FONTS_DIR` build option (`CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci`; use an absolute path), read by `crates/text/build.rs` into `vectorcraft_text::CRAFT_FONTS`; never add it to a `Cargo.toml`. Everything must build, test and run with `CRAFT_FONTS` empty, and tests of its glyphs skip when it is. Details: `docs/development.md` › Fonts.
- **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo**. Never commit a font file here; add new fonts to craft-fonts. The app uses it only through the optional `CRAFT_FONTS_DIR` build option (`CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci`; use an absolute path), read by `crates/text/build.rs` into `vectorcraft_text::CRAFT_FONTS`; never add it to a `Cargo.toml`. Everything must build, test and run with `CRAFT_FONTS` empty, and tests of its glyphs skip when it is. Details: `docs/development.md` › Fonts.
- Code and original assets are MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). The ArtCraft logos in `docs/brand/` are trademarks, not open source, under `docs/brand/LICENSE-brand.txt`: never modify them or use them outside VectorCraft.
- Prefer art generated in code for defaults (swatches, brushes, symbols, patterns, cursors). If the provenance of an asset is unclear, don't add it.
- Reference screenshots of Illustrator stay local under the gitignored `plan/` and are never committed, published or used as assets.
@@ -45,8 +95,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd.
- **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`.
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`).
## Running and looking at the app
@@ -59,7 +108,7 @@ Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format
- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; write manifests atomically. Each target dir grows to ~30 GB: delete yours when you finish (a full disk fails links with `errno=28`).
## Roadmap and progress docs
The progress docs follow craftrules' [`standards/progress-docs.md`](https://github.com/storytold/craftrules/blob/main/standards/progress-docs.md):
The progress docs:
- [`ROADMAP.md`](ROADMAP.md): stage, headline numbers, dimensions, features, languages, upcoming, progress log.
- [`docs/target-app-parity.md`](docs/target-app-parity.md): the authoritative parity assessment (area table, methodology, calibration, evidence of what ships).
- [`docs/gaps.md`](docs/gaps.md): every known shortfall, ranked; the work list. [`docs/roadmap.md`](docs/roadmap.md): milestones and current focus.
@@ -72,17 +121,21 @@ When a task lands, update in the same PR: the area row in `docs/target-app-parit
## Contributor credits (About window)
- About ▸ Contributors/Models are compiled into the binary from `contributors/contributors.json`
(commit stats; generated, never hand-edit) and `contributors/people.toml` (names people chose for
(commit stats; never hand-edit) and `contributors/people.toml` (names people chose for
themselves). See `docs/contributors.md`.
- **Agents working for a contributor:** when you prepare a PR, check whether your human's GitHub
username has a `[people.<username>]` entry in `contributors/people.toml`. If not, ask them once
whether they want to be credited by more than their username: a real name, a display name, and/or
their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry
(copy the template at the top of the file, or run
`python3 ../../craftrules/scripts/contributors.py --add-me . --real-name "…" --sync-github-name`)
(copy the template at the top of the file)
and include it in their PR, committed as them. If no, change nothing: they are credited as
`@username` anyway.
- Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or
GitHub profiles). Never hand-edit `contributors.json`.
- Maintainers refresh the stats with `python3 ../../craftrules/scripts/contributors.py .` (it also
re-verifies who wrote each `people.toml` entry; `--check` only verifies).
## CI workflows
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
New workspace crates include `[lints] workspace = true` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them.
+61 -23
View File
@@ -1,12 +1,28 @@
# Asset attribution
## Indic hyphenation patterns
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
| `crates/text/patterns/hyph-hi.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-hi.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-mr.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-mr.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-gu.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-gu.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-bn.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-bn.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-pa.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-pa.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-ta.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-ta.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-te.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-te.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-kn.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-kn.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-ml.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-ml.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-or.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-or.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-as.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-as.tex | MIT (selected option) | Unmodified; full license in file |
Every non-code asset in this repository (icons, images, fonts, example art, colour profiles, presets) is listed here with its author, source and licence. `cargo xtask assets` (part of `cargo xtask ci`) fails if an asset file is missing from this table.
**Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets and the vector tool cursors (`crates/ui-egui/src/cursors.rs`).
Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets, the vector tool cursors (`crates/ui-egui/src/cursors.rs`) and the Learn panel's practice samples (`crates/ui-egui/src/panels/learn/samples.rs`).
**Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts) (rules: craftrules [`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)). The small Latin UI/document fonts below predate that rule and stay.
**Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay.
**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=<craft-fonts checkout>` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-<family>.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them.
@@ -115,6 +131,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | |
| `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-dash-align.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -142,6 +159,8 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-free-transform.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-fx.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-gamut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grad-conic.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grad-diamond.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grad-freeform.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grad-linear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grad-radial.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -224,13 +243,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 | |
@@ -245,6 +267,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/flip-vertical-2.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
| `assets/icons/folder-open.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
| `assets/icons/frame.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
| `assets/icons/graduation-cap.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | Learn panel, Explore tutorials button |
| `assets/icons/grid-3x3.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
| `assets/icons/group.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
| `assets/icons/hand.svg` | Lucide Icons and Contributors | https://lucide.dev (lucide-static v1.49.0; header kept in file) | ISC (`assets/icons/LICENSE-lucide.txt`) | |
@@ -345,6 +368,21 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `examples/ribbons.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | |
| `examples/feature-sheet.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | |
| `examples/perspective-city.vectorcraft` | VectorCraft contributors | Original artwork built through the VectorCraft command API | MIT OR Apache-2.0 | |
| `crates/engine/tests/fixtures/jpeg2000/checker.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `3de9c2bb5b8aaec241d939b795002a68eb3d50e41d51c43368000804ad3de057` |
| `crates/engine/tests/fixtures/jpeg2000/checker-raw.j2k` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `76fa51ab8ccbc2534098b26b8e7fe16dd886e2b6298ba52d06a6b1bde9b61d9e` |
| `crates/engine/tests/fixtures/jpeg2000/checker-300ppi.jp2` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | a 2 × 2 checker encoded with FFmpeg's JPEG 2000 encoder; SHA-256 `1b1aeed8975d3cdc832da6ecf5855852d07d0c490105121e61a8aefb31af009b` |
| `crates/engine/tests/fixtures/heif/quadrants.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 red, green, blue and white quadrants encoded with libheif's `heif-enc` 1.23.2 (x265); SHA-256 `122d14963fe899daa736cd216902cf4fc8f2192b3a0ba81f94004adcd71a0ff5` |
| `crates/engine/tests/fixtures/heif/quadrants-alpha.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants with a transparent right half, encoded with `heif-enc` 1.23.2; SHA-256 `55b5a537401ead742714c3a1bc526559ec8c1ba97cdb7f43ac63f4037167475b` |
| `crates/engine/tests/fixtures/heif/quadrants-10bit.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants at 10 bits, encoded with `heif-enc` 1.23.2; SHA-256 `11014848c6a838e5799d87e034eff1b06b816712ed70ba451bd582d72741774f` |
| `crates/engine/tests/fixtures/heif/quadrants-grid.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 128 × 128 quadrants as a 2 × 2 grid of 64 × 64 tiles, encoded with `heif-enc` 1.23.2; SHA-256 `5802f8715110954eb9c58d4bdcc10d1200426a48cf726f1b88dfb60da825ba7a` |
| `crates/engine/tests/fixtures/heif/quadrants-300ppi.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the quadrants with EXIF resolution tags of 300 ppi, encoded with `heif-enc` 1.23.2; SHA-256 `6a344a6de04fc5fceaee46b6e0028b12478c90bdcb6f6f14ed8c86a44cb203d7` |
| `crates/engine/tests/fixtures/heif/wide-rotated.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 16 red and blue halves stored with a quarter-turn rotation, encoded with `heif-enc` 1.23.2; SHA-256 `e3a2c3a9beb4066c13d6deb8e1311805c6aac485fde8784f1ee317dd95b89973` |
| `crates/engine/tests/fixtures/heif/wide-rotated-300x150.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the rotated halves with EXIF resolution tags of 300 ppi across and 150 ppi down, encoded with `heif-enc` 1.23.2; SHA-256 `79ad7945cd2c1ea9d3e70ac9b93d9a162fd8ce37541a0f3de44e12f04745921d` |
| `crates/engine/tests/fixtures/heif/tones.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 quadrants of four mid tones, encoded with `heif-enc` 1.23.2; SHA-256 `29ed7d75fbfbc4c298eb2da3a6b62625a150cd6bfe5b7ff1d847437501b1b4b1` |
| `crates/engine/tests/fixtures/heif/tones-p3-nclx.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones labeled Display P3 in an `nclx` color box, encoded with `heif-enc` 1.23.2; SHA-256 `baeb32ffa58ac1ac29a00c9e388b9281f4acb4695c4681e4933d0ad061447101` |
| `crates/engine/tests/fixtures/heif/tones-p3-icc.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones with VectorCraft's own Display P3 ICC profile (`vectorcraft_color::cms::icc_bytes`), encoded with `heif-enc` 1.23.2; SHA-256 `472e1a123b9515926a8985a04c3f680387e8c410dbf8f7ff0cfb8cb99c89e93b` |
| `crates/engine/tests/fixtures/heif/tones-p3-icc-only.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | the tones with VectorCraft's own Display P3 ICC profile as their only color box, encoded with `heif-enc` 1.23.2; SHA-256 `2654fdd21e56641107db20b3f4d0a66a86420ac040d42ddf55e20f7e789d5c55` |
| `crates/engine/tests/fixtures/heif/quadrants-grid16.heic` | VectorCraft contributors | Original test image authored for VectorCraft's tests | MIT OR Apache-2.0 | 32 × 32 quadrants as a 2 × 2 grid of 16 × 16 tiles, each cropped from a 64 × 64 picture, encoded with `heif-enc` 1.23.2; SHA-256 `bd114ee66cdac10142729dc9dddfa1cd96993a5cefa54c2f25b65496652f007f` |
## Assets embedded by the PDF backend
@@ -352,20 +390,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 |
+17
View File
@@ -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 -71
View File
@@ -1,71 +1 @@
# VectorCraft — instructions for agents
VectorCraft is a clean-room, open-source, Rust-native vector illustration app targeting Adobe Illustrator parity (and beyond). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings: `../photocraft` (Photoshop-class) and `../pdfcraft` (Acrobat-class); same conventions.
Formerly **DrawCraft** (renamed 2026-10-01): old `.drawcraft` files and `"format": "drawcraft"` headers still open (`vectorcraft_format::LEGACY_EXTENSION`), and preferences migrate from the old config folder. Keep those paths working; use the new name everywhere else.
## Start every session here
1. Read [`ROADMAP.md`](ROADMAP.md) (stage, numbers by dimension, what's next) and the ranked work list in [`docs/gaps.md`](docs/gaps.md). Unless the user gives you a task, pick work from that list.
2. Read `plan/STATUS.md` (local session notes, may lag the ROADMAP), then the task in `plan/execution-plan.md` §3 and the relevant `plan/architecture.md` section. Behaviour reference: public documentation only (see Clean-room below); `plan/illustrator/*.md` holds notes from it.
3. Follow the autonomous operation protocol (`plan/execution-plan.md` §7): orient → plan → implement + test → verify → record → commit. Don't stop to ask unless §7 lists the decision as the user's.
`plan/` is gitignored (local only).
## Non-negotiables
- **Clean-room: never use Adobe software (absolute rule, from the project owner).** Adobe's Terms of Use forbid reverse engineering, including observing a program's inputs and outputs to recreate it. So:
- Never launch, run, script, automate (COM, AppleScript, ExtendScript, UI automation), screenshot or measure Illustrator or any other Adobe application, and never compare our output against one. Don't make test files with them, not even "synthetic" ones.
- Never read, disassemble or copy anything inside an Adobe install (binaries, plug-ins, presets, procsets, resources, help files, fonts, ICC profiles).
- Never copy Adobe-authored code or text into this repo, tests included: no PostScript procsets or prologs (AGM, CoolType, the Illustrator prologs), no sample files. Write test inputs from scratch from the public specifications (PostScript Language Reference, PDF / ISO 32000, TIFF, EPSF/DCS).
- Behaviour comes only from public documentation (helpx, published specs, public forum posts), cited by URL, and from files users send us that they own (used locally, never committed). Never copy Adobe icons, artwork, presets or wording beyond feature names.
- If a task seems to need any of this, stop and say so instead. `cargo xtask cleanroom` (run by `cargo xtask ci`) fails on Adobe copyright notices and on fixtures made with Adobe applications.
- Never copy GPL/AGPL code (Inkscape, lib2geom…).
- **Assets: no Adobe iconography or images — ever (absolute rule, from the project owner).**
- Never add, copy, trace, redraw-from, embed or ship any icon, image, artwork, cursor, preset, swatch/brush/symbol/pattern/style library, ICC profile or screenshot from Adobe products or from any other source whose licence doesn't allow it.
- Every image, icon, font or other asset must be one of:
- original work created for VectorCraft by a contributor (who licenses it MIT OR Apache-2.0);
- OSI open source;
- public domain / CC0;
- Creative Commons with redistribution allowed.
- **Every asset file must have a row in [`ASSETS.md`](ASSETS.md)** (path, author, source URL, licence, notes). Put licence texts next to the assets (e.g. `assets/fonts/OFL-*.txt`) and summarize them in `NOTICE`.
- `cargo xtask assets` (run by `cargo xtask ci`) fails on any unattributed asset.
- **Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never in this repo** (rules: craftrules [`standards/fonts.md`](https://github.com/storytold/craftrules/blob/main/standards/fonts.md)). Never commit a font file here; add new fonts to craft-fonts. The app uses it only through the optional `CRAFT_FONTS_DIR` build option (`CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci`; use an absolute path), read by `crates/text/build.rs` into `vectorcraft_text::CRAFT_FONTS`; never add it to a `Cargo.toml`. Everything must build, test and run with `CRAFT_FONTS` empty, and tests of its glyphs skip when it is. Details: `docs/development.md` › Fonts.
- Code and original assets are MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, `NOTICE`). The ArtCraft logos in `docs/brand/` are trademarks, not open source, under `docs/brand/LICENSE-brand.txt`: never modify them or use them outside VectorCraft.
- Prefer art generated in code for defaults (swatches, brushes, symbols, patterns, cursors). If the provenance of an asset is unclear, don't add it.
- Reference screenshots of Illustrator stay local under the gitignored `plan/` and are never committed, published or used as assets.
- **Never crash: no panics in shipped code.** A crash loses the user's unsaved work. Files, pasted data, MCP and control messages, and command params are all untrusted input.
- Fallible work returns `Result` (or `Option`); callers handle it or propagate it with `?`. Failures reach the user as an error message (`EngineError` for commands, the crate's own error type or `String` below the engine), never as an abort.
- Workspace clippy lints ban these outside tests, so `cargo xtask ci` fails on them: `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!`, `unimplemented!`. Use instead: `?`, `.ok_or(…)?`, `let … else { return … }`, `if let`, `unwrap_or` / `unwrap_or_default` / `unwrap_or_else`, `.first()` / `.last()` / `.split_last()`, and a real error for a match arm you believe is impossible.
- New workspace crates must include `[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`. Production crate roots must declare `#![forbid(unsafe_code)]` before modules or other crate items; crate-level `//!` documentation may precede it.
- Don't panic implicitly either: use `.get(i)` instead of `v[i]` or `&s[a..b]` when the index comes from data. Don't divide integers by something that can be zero, cap sizes and counts read from input (allocations, images, loops), and check that floats are finite before casting them or looping on them.
- Don't silence errors just to satisfy the lint: use `let _ =` or `.ok()` only where ignoring the failure is the right behaviour, with a comment saying why.
- Tests may unwrap and panic (`#[test]`, `#[cfg(test)]`, `tests/`, `testkit`). Integration-test files start with an `#![allow(…)]` for that.
- `vectorcraft_engine::guard` is the last line of defence. Every entry point (commands, tool events, MCP requests, the UI frame, control requests) catches a panic, rolls the document back and reports an internal error. It exists for bugs and doesn't replace `Result`: wasm aborts on panic, so the web app has no safety net.
- Untrusted input is fuzzed (`engine/tests/import_fuzz.rs`, `engine/tests/command_sweep.rs`, `format/tests/prop_format.rs`, `mcp/tests/protocol_props.rs`). Extend these when you add an importer, a parser or a protocol method.
- **Everything is a command.** User-visible behaviour = a command in `crates/engine/src/cmd/*` (id, label, menu path, shortcut, params doc, `enabled`, `run`) + tests. Tools emit commands (Begin/Preview/Commit). UI-only commands live in `crates/ui-egui/src/menus.rs` (`UI_COMMANDS`). The control channel and MCP reach all of them.
- **Adding a cursor.** The app decides which cursors exist; whoever draws them works from the list. For a new tool state with a cursor of its own: add the `Cursor` variant (`crates/tools/src/lib.rs`, with a doc comment), return it from the tool's `cursor()` with a tool test, cover it in `cursor_icon` (`crates/ui-egui/src/canvas.rs`), draw it in `crates/ui-egui/src/cursors.rs` or give it a stand-in in `Cursor::stand_in()` until it's drawn, and add its `[[cursor]]` entry to `crates/tools/src/cursors.toml` (when it shows, in plain behaviour terms, and its hotspot; never another app's look). A missing entry only warns (`cargo xtask cursors`): the cursor still works.
- **Layering** is enforced by `cargo xtask layers`. Nothing below L6 depends on egui/eframe/winit/rfd.
- **The UI is thin**: panels read engine state and act through `app.run(id, params)`. Colours come from `theme::Tokens`.
- **Rust only** (no handwritten JS/TS). **Never break wasm** (`cargo xtask wasm`).
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Shared test corpora.** Real-file test oracles (Photoshop-authored PSDs, etc.) live in [`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus), explained in [craftrules `standards/test-corpora.md`](https://github.com/storytold/craftrules/blob/main/standards/test-corpora.md). Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, as PhotoCraft does with `cargo xtask corpus`.
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings including the no-panic lints, tests, layers, wasm). One task id per commit (`M2.1: pen tool`).
## Running and looking at the app
- `cargo run --release -p vectorcraft -- --control 7979 [file.svg|file.vectorcraft]` (sibling apps' agents use the same default port: if the log says it failed to bind, pick another port — otherwise your requests reach a different app).
- Drive it: JSON lines on `127.0.0.1:7979`, e.g. `{"id":1,"method":"engine.execute","params":{"command":"shape.rectangle","params":{"x":10,"y":10,"width":100,"height":50}}}` then `{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}`. Methods: `crates/ui-egui/src/control.rs`.
- **For UI work, look at the result** (take `ui.screenshot`, read the PNG) and compare with the public documentation (`plan/illustrator/02-ui-ux.md` notes). `ui.screenshot` needs a presented frame: if it errors (screen locked), check the art with `ui.render` / `vectorcraft-cli run … --export x.png`, and cover panels with a headless egui frame test (see `panels/transparency.rs` tests).
- **Performance:** `vectorcraft-cli perf` checks the budgets (render/pan/zoom, hit test, save/open, SVG, Pathfinder) on a synthetic 50k-path document; `vectorcraft-cli bench FILE` times one file. Run them before and after renderer, format or geometry changes, on an idle machine (the report warns when the load average makes timings noise).
- MCP: `vectorcraft-cli mcp` (see `docs/mcp.md`).
- Shell gotcha: `mv`/`cp` are aliased interactive here — use `/bin/mv -f` / `/bin/cp -f`.
- Parallel agents: separate `CARGO_TARGET_DIR` per agent; edit only the crates you own; write manifests atomically. Each target dir grows to ~30 GB: delete yours when you finish (a full disk fails links with `errno=28`).
## Roadmap and progress docs
The progress docs follow craftrules' [`standards/progress-docs.md`](https://github.com/storytold/craftrules/blob/main/standards/progress-docs.md):
- [`ROADMAP.md`](ROADMAP.md): stage, headline numbers, dimensions, features, languages, upcoming, progress log.
- [`docs/target-app-parity.md`](docs/target-app-parity.md): the authoritative parity assessment (area table, methodology, calibration, evidence of what ships).
- [`docs/gaps.md`](docs/gaps.md): every known shortfall, ranked; the work list. [`docs/roadmap.md`](docs/roadmap.md): milestones and current focus.
- Checklists: [`ui-parity.md`](docs/ui-parity.md), [`file-format-parity.md`](docs/file-format-parity.md), [`hardware-parity.md`](docs/hardware-parity.md), [`localization-parity.md`](docs/localization-parity.md), [`effects-parity.md`](docs/effects-parity.md), [`type-parity.md`](docs/type-parity.md); [`architecture.md`](docs/architecture.md).
When a task lands, update in the same PR: the area row in `docs/target-app-parity.md` (score, missing items, hours) and its evidence list, the gap entry in `docs/gaps.md` if it closed or shrank, the checklist it belongs to, the milestone row in `docs/roadmap.md`, and the ROADMAP's tables and progress log when a headline number moves. Update each touched doc's status line and revision history.
- Grade by behaviour against the public documentation (`plan/illustrator/` notes), not by whether a menu item exists. Scores are self-assessed, so err low; mark each number measured or estimated.
- Keep the README's Status section in step with the ROADMAP headline.
@AGENTS.md
Generated
+593 -154
View File
File diff suppressed because it is too large. Load diff
+44 -14
View File
@@ -4,22 +4,36 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
[workspace.package]
version = "0.18.0"
version = "0.24.1"
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 = "c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280" }
# craft-update: app-specific pretend versions apply to startup and manual checks.
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2", features = ["tree"] }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -50,6 +64,8 @@ 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" }
vectorcraft-apischema = { path = "crates/apischema" }
# foundation
kurbo = { version = "0.13", features = ["serde"] }
@@ -95,12 +111,25 @@ ruzstd = { version = "0.9.1", default-features = false, features = ["std"] }
hayro-ccitt = "0.3"
# Substring search for the EPS reader's PostScript `search`.
memchr = "2"
# The WHATWG Encoding Standard's legacy encodings: names in legacy .ai files read in the code page
# the user picks (Mac OS Roman, Korean, Japanese, Chinese).
encoding_rs = "0.8.42"
jpeg-encoder = { version = "0.6", default-features = false, features = ["std"] }
gif = { version = "0.14", default-features = false, features = ["std", "raii_no_panic"] }
# CMYK image samples (vectorcraft-doc's cmyk module): the image crate's own TIFF and JPEG
# decoders, read directly (the image crate converts CMYK to RGB).
tiff = "0.11"
zune-jpeg = "0.5"
# JPEG XL decoder (pure Rust, MIT OR Apache-2.0): File › Open and Place read `.jxl` images. It is
# built without its default `rayon` feature and decodes on one thread.
jxl-oxide = { version = "0.12.6", default-features = false }
# jxl-oxide's color conversions, run on colors after their alpha is divided out.
jxl-color = "0.11.0"
# jxl-oxide's buffer allocation error, told apart from other decoding errors.
jxl-grid = "0.6.2"
# Tests: a lossless JPEG XL encoder (pure Rust, MIT OR Apache-2.0 OR Zlib) for the `.jxl` test files.
zune-jpegxl = { version = "0.5.2", default-features = false, features = ["std"] }
zune-core = "0.5"
# ui
egui = "0.37"
@@ -144,12 +173,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" }
+13 -3
View File
@@ -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.
+17 -8
View File
@@ -205,10 +205,10 @@ drag-and-drop, set **Preferences › Performance › Linux Display Server** to *
the app with `WAYLAND_DISPLAY= vectorcraft`: the window then opens through XWayland, where drops work
(see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)).
On Linux with Wayland, under KDE Plasma 6.3 or later and under GNOME, VectorCraft doesn't respond to a drawing tablet's
pen yet (#491, #2028). Open the window through XWayland instead, where the pen works as a mouse and the app reads its
pressure: set the same preference to **X11 (XWayland)**, or to **X11 (XWayland) When a Pen Is Attached** to use
XWayland only when a pen is attached as VectorCraft starts, and restart; or start the app with
On Linux with Wayland, under KDE Plasma 6.3 or later and under GNOME, VectorCraft can't get a drawing tablet's pen
input on native Wayland yet (#491, #2028). When a pen is attached as VectorCraft starts, the window opens through
XWayland, where the pen works as a mouse and the app reads its pressure (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps
Wayland). For a pen attached later, set the same preference to **X11 (XWayland)** and restart, or start the app with
`WAYLAND_DISPLAY= vectorcraft` (see [`docs/development.md`](docs/development.md#linux-wayland-and-x11)).
### Use it from Claude Code and other agents
@@ -237,7 +237,7 @@ and what's next; [`docs/target-app-parity.md`](docs/target-app-parity.md) the fu
(92.5% of menu items do something), feature depth is ~75%, and we estimate ~65% ready for real work for a mainstream illustrator (~62% across all tracked features): everyday
vector illustration is close to usable: drawing and path tools,
Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out and PSD/PSB in as their merged image, Print, Package).
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out, PSD/PSB opened with their layers and placed as their merged image, JPEG XL in, Print, Package).
Affinity documents (`.af` from Affinity 3, `.afdesign`, `.afpub` and, by their content, `.afphoto` from Affinity 1 and 2) open
and place natively: layers, groups, artboards and pages, curves and shapes, fills, gradients and strokes, clipping
and masks, text with each paragraph's indents, spacing and leading, tables (as text frames and lines), master
@@ -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
@@ -328,12 +328,21 @@ stand on its own.
| | App | What it's for | Code | Learn more |
|:-:|---|---|---|---|
| <img src="https://raw.githubusercontent.com/storytold/photocraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.photocraft.png" alt="" width="32" height="32"> | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) |
| <img src="https://raw.githubusercontent.com/storytold/vectorcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.vectorcraft.png" alt="" width="32" height="32"> | **VectorCraft** | **Vector illustration · you are here** | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) |
| <img src="https://raw.githubusercontent.com/storytold/vectorcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.vectorcraft.png" alt="" width="32" height="32"> | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) |
| <img src="https://raw.githubusercontent.com/storytold/filmcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.filmcraft.png" alt="" width="32" height="32"> | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) |
| <img src="https://raw.githubusercontent.com/storytold/lightcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.lightcraft.png" alt="" width="32" height="32"> | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) |
| <img src="https://raw.githubusercontent.com/storytold/pdfcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png" alt="" width="32" height="32"> | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
| <img src="https://raw.githubusercontent.com/storytold/effectcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png" alt="" width="32" height="32"> | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
| <img src="https://raw.githubusercontent.com/storytold/designcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png" alt="" width="32" height="32"> | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
| <img src="https://raw.githubusercontent.com/storytold/figcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.figcraft.png" alt="" width="32" height="32"> | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) |
| <img src="https://raw.githubusercontent.com/storytold/wordcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.wordcraft.png" alt="" width="32" height="32"> | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) |
| <img src="https://raw.githubusercontent.com/storytold/soundcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.soundcraft.png" alt="" width="32" height="32"> | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) |
| <img src="https://raw.githubusercontent.com/storytold/deckcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.deckcraft.png" alt="" width="32" height="32"> | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) |
| <img src="https://raw.githubusercontent.com/storytold/cadcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.cadcraft.png" alt="" width="32" height="32"> | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) |
| <img src="https://raw.githubusercontent.com/storytold/gridcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.gridcraft.png" alt="" width="32" height="32"> | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) |
| <img src="https://raw.githubusercontent.com/storytold/texturecraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png" alt="" width="32" height="32"> | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) |
| <img src="https://raw.githubusercontent.com/storytold/craft-anything/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.craft-anything.png" alt="" width="32" height="32"> | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) |
| <img src="https://raw.githubusercontent.com/tangency-labs/solidcraft/main/assets/icons/app/linux/exports/hicolor/64x64/apps/io.tangencylabs.solidcraft.png" alt="" width="32" height="32"> | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | |
And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control.
+78 -18
View File
@@ -1,15 +1,8 @@
# VectorCraft Roadmap
- 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.
- UI.5: Shared docking adds tab reordering, docking into other groups, dock splits and resizable floating panel groups. Panel positions and return locations persist with workspaces; the native icon rail and Tools panel remain available.
- UI.4: Dock and floating-panel headers use shared accessible tabs with bounded overflow. Widget-state theme application uses `craft-ui`; all four palettes, font stacks and preferences remain app-owned.
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-23 · **Change:** minor (OpenType SVG colour fonts draw and export as vector art; previously: COLR colour fonts (v0 and v1) draw and export as vector art; previously: G2: the Effect Gallery shipped (#2883): Effect › Effect Gallery… browses the Artistic, Brush Strokes, Distort, Sketch, Stylize and Texture filters, edits each filter's settings, builds an ordered stack (add, reorder, hide, remove) with a live canvas preview, and OK applies it as separate appearance effects in one undo step; remaining: filter thumbnails and a preview area inside the dialog; G2 estimate 4–6 → 1–2 h; Raster effects 82% → 85% (power-user view 49% → 52%), estimated, a modest move because the named missing dialog landed without thumbnails or an in-dialog preview; previously: colour emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; headline numbers unchanged; previously:; Affinity import AF.5: master pages, tables, paragraph formats, shadows, glows, outlines, overlays and embedded documents; ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range, above or below (right of the column in vertical type), aligned, sized and overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present); headline numbers unchanged; previously:; 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged; Print: Japanese paper sizes in the Print dialog's Media list — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (which keep their ISO 216 sizes), はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判; about 90 community PRs of 2026-10-19: Objects on Path, the Simplify slider, Pencil Edit Selected Paths in the middle of a path, Georgian, and more; Background Export progress dialog with Cancel, #2564; about 85 community PRs of 2026-10-18: Justification…, Word .docx placed as area type, CCITT Group 3 TIFF, Roman Hanging Punctuation, blend spines edited with the Anchor Point tool, shadows and glows in stack order, coloured 3D lights, a Dutch catalog completed; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; about 145 community PRs of 2026-10-17: image-decode overflow guards, opaque floating panels, MCP export cancel and progress, editable Illustrator EPS import, scoped `doc_inspect`, Dutch, Danish and Indonesian, Simplified Chinese messages, screen-reader names; headline numbers unchanged; about 160 community PRs of 2026-10-15/16: PDF import crash fixes, Dimension tool, legacy `.ai` save, Intertwine, web pen input, Image Trace fixes, `.ai`/EPS/PDF import fidelity, Bulgarian, Greek, Swedish and Finnish catalogs; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously 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,13 +11,15 @@ 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
blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged.
## Headline numbers
| | Value | Kind |
@@ -76,11 +71,11 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so
| Strokes, brushes, width profiles | 88% | 8–15 |
| Appearance, transparency, graphic styles, masks | 97% | 1–2 |
| Live vector effects | 85% | 4–8 |
| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 85% | 1–2 |
| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 88% | — |
| 3D and Materials | ~25% | 30–55 |
| Type core — [type-parity.md](docs/type-parity.md) | 80% | 14–19 |
| Type advanced (CJK, spelling, Touch Type) | 50% | 20–28 |
| Symbols, blends, envelopes, Repeat, perspective | 87% | 5–9 |
| Symbols, blends, envelopes, Repeat, perspective | 88% | 4–7 |
| Image Trace, graphs, image tools | 75% | 5–8 |
| Layers, artboards, document setup | 78% | 5–8 |
| View & navigation | 70% | 9–14 |
@@ -102,7 +97,8 @@ 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 |
| Gujarati | `gu` | 4,673 contributor-reviewed catalog rows; 11 corrections applied to the 387 additions | menus and dialogs; status/error messages partial |
| Arabic | `ar` | none (no right-to-left interface) | 0% |
| French | `fr` | full | 100% |
| Portuguese (Brazil) | `pt-br` | full | 100% |
@@ -110,6 +106,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
| Japanese | `ja` | full | 100% |
| German | `de` | full | 98% |
| Korean | `ko` | full | 100% |
| Bosnian | `bs` | full (AI-assisted, native review pending) | 100% |
| Vietnamese | `vi` | full | 100% |
Also shipped: Traditional Chinese (partial, 80%), Bulgarian, Finnish, Greek, Hungarian, Italian, Polish, Russian, Swedish, Ukrainian and Georgian (full), Catalan (full; AI-drafted, native review welcome), Czech (catalog complete; render-site gaps reduced; native review pending).
@@ -123,11 +120,38 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h.
3. **Launch and stability on real machines** (G10): 20–35 h.
4. **Core-tool correctness** (G11: Shape Builder regions, Asset Export borders): 8–15 h.
5. **Raster effects** (G2) alongside: the Effect Gallery's filter thumbnails and in-dialog preview area (the gallery and every Photoshop-style filter are in), 1–2 h.
6. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3).
5. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2).
## Progress log
- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
- 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged.
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923).
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
- 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<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.
- 2026-11-11: Window › Swatch Libraries › Gradients › Organic Fades: fifteen soft fades (ten linear, five radial) through three to five unevenly spaced stops with off-center midpoints, mixed with the Perceptual method, that thin out to transparent at the end of a linear one and at the edge of a radial one; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
- 2026-11-13: Gradient panel › Method: Hue Clockwise and Hue Counterclockwise mix a linear, radial, conic or diamond gradient's colors around the hue wheel in one direction, so red to blue passes through magenta one way and through yellow and green the other (`paint.editGradient` `method`: `hue-clockwise`, `hue-counterclockwise`); SVG and PDF exports write such a gradient as an image.
- 2026-11-11: Window › Swatch Libraries › Gradients › Holographic: seven foils (opaque linear gradients of six narrow pastel and pearl bands with off-center midpoints) and seven glows (radial gradients from a bright center out to a clear edge), mixed with the Perceptual method; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
- 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`).
- 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged.
- 2026-10-23: OpenType SVG colour fonts draw as vector art: each glyph's SVG document is read by the SVG importer, in the text's colours where it asks for them, and draws, exports and outlines as COLR glyphs do; all colour font formats are now drawn.
- 2026-10-23: COLR colour fonts (v0 and v1, as in Noto Color Emoji's vector build, Segoe UI Emoji, Nabla) draw as vector art: their layers' colours, gradients, clips and blend modes on the canvas and in SVG, EPS, legacy `.ai` and PDF, and as editable paths with Create Outlines; glyphs using sweep gradients or compositing modes are drawn as images of the glyph.
@@ -137,6 +161,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-10-22: Effect › Sketch › Conté Crayon: a black crayon in the dark areas and a white one in the light areas, on mid-grey paper whose texture (Brick, Burlap, Canvas, Sandstone; Scaling, Relief, Light Direction, Invert) breaks the strokes, with Foreground Level and Background Level; an original approximation, defaults unverified. Every Photoshop-style filter is now in (57/57); the Effect Gallery remains (4–6 h).
- 2026-10-22: Ruby (ふりがな) for live text: `type.ruby` sets or removes a reading over a byte range of the selected type — above it in horizontal type, right of the column in vertical type (or below/left), start/centre/end aligned, at 1–100% of the base size (default half), overhanging or squeezed to the base width. It is saved in the native file, laid out with its line growing (following lines move on), drawn on the canvas, and written in SVG and PDF as outlines where ruby is present. UI panel and type on a path are next. Headline numbers unchanged.
- 2026-10-22: PDF accessibility: titled exports set `/ViewerPreferences << /DisplayDocTitle true >>`, so viewers show the document title rather than the file name and title checks can pass (#3646). Headline numbers unchanged.
- 2026-10-22: Pen tilt, bearing and barrel rotation (part of #764): Calligraphic and Scatter brushes take Tilt, Bearing and Rotation beside Pressure, the Paintbrush records them along each stroke, and the app reads a pen's tilt and an Art Pen's barrel rotation from XInput2 on Linux under X11 and XWayland and from AppKit's tablet events on macOS. Headline numbers unchanged.
- 2026-10-14: Document fonts register every explicitly supplied craft-fonts family after the existing Japanese, Arabic and Thai prefix; optional empty input remains supported. Headline scores and estimates are unchanged.
@@ -144,6 +169,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
| Date | What landed |
|---|---|
| 2026-10-29 | Linux: the Flatpak on GNOME copies and pastes text with other apps through the compositor's core Wayland protocol (smithay-clipboard on the window's connection), where arboard has neither data-control nor X11. Scores and estimates unchanged. |
| 2026-10-29 | Linux: a clipboard that can't be opened (the Flatpak on GNOME, where arboard has neither data-control nor X11) is retried after 1 s, doubling to a minute, and logged once, where the background Paste check used to reconnect and log a warning every 250 ms (267k warnings in 18 h). Scores and estimates unchanged. |
| 2026-10-21 | 3D lighting: four original lighting presets shared by Revolve, Extrude & Bevel, Inflate and Rotate, with command access and manual Custom settings; scores and estimates unchanged. |
| 2026-10-21 | Print: the Print dialog's Media list has the Japanese papers — JIS B4 (257 × 364 mm), JIS B5 (182 × 257 mm) and JIS B6 next to the ISO B4/B5 (which keep their ISO 216 dimensions for settings saved before them), はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm / 長形4号 90 × 225 mm / 角形2号 240 × 332 mm / 角形3号 216 × 277 mm and 四六判 127 × 188 mm. A paper is named by its JSON id or its dialog label, any case and spacing (`B5 (JIS)` or `b5jis`), and every added size prints as its own PDF page size. Headline numbers unchanged. |
| 2026-10-18 | Inch rulers divide the inch in half, not in ten. Zooming in stepped an inch ruler through 0.2, 0.1 and 0.05 of an inch, marks an inch ruler does not carry; below an inch the steps are binary fractions now, 1/2 down to 1/16, with the unlabelled ticks between them binary too (down to 1/128, so the 32nds, 64ths and 128ths appear as the report expects), while the metric units, points, pixels and picas keep their tenths. A label carries the decimals its step needs, so a sixteenth reads 0.0625 rather than the rounded 0.06, with trailing zeros dropped (#2827). Headline numbers unchanged. |
@@ -182,7 +209,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
| 2026-10-12 | Graphs: Object › Graph › Design… and Marker… (designs with a preview, New Design, Rename, Delete Design, Paste Design, Select Unused, and markers drawn with a design or None) (#1092); Graph Data opens as a worksheet with Import Data…, column width and decimals (#1138), and takes Transpose, Switch x/y, `|` line breaks in labels and the pie Legend, Position and Sort options (#1115); Graph Type adds Add Drop Shadow and Add Legend Across Top (#1119), widths past 100%, First Row and First Column in Front, and Draw Filled Lines (#1136); graphs keep their label formatting when drawn again (#1137). Align: a Horizontal & Vertical Align Center button (#1073); Align to Key Object makes the topmost selected object the key (#1221), and the palette's key entry reads Cancel Key Object (#1224). Pen: the nearest end wins over snapping, Alt on the last anchor edits it, and Enter, Escape or a tool switch finish a handle preview as one undo step (#821). Direct Selection: a click on an anchor of an already selected path selects that anchor alone (#1237). Make Compound Path keeps the backmost object's paint, and a selected member reads and changes the compound's fill rule (#1225). Shape Builder and Live Paint no longer turn a line's loose end past a crossing into a piece that runs out and back (#1230). Art moved or duplicated with an artboard follows Transform Pattern Tiles (#1219). A click with the Rectangular Grid tool opens its options dialog (#1169). Commands that change nothing (Lock, Hide, Transform Each, Rearrange Artboards and others) add no undo step (#1233). Saving with missing placed files keeps their relink data, and .ai export honours the chosen artboards (#718). SVG export keeps Unicode data-attribute names, and SVG Options refuses an invalid artboard range (#989). CMYK colours given in percent with a component under 1 keep their scale (#1249). Colour Image Trace keeps close dark tones apart (#1247). macOS: the Save sheet has a Format menu (#1235). The Hand and Zoom tools show drawn cursors on every platform (#1238). Czech: the remaining strings are translated, and Pathfinder's Add reads "Sjednotit" (#1226). MCP: a lost reply reports that the edit may have happened instead of replaying it (#1246); `select.key` checks its id and agents can read the key object (#1222). Tests: the command sweeps and import fuzz tests fail on a panic caught by the engine's guard (#1218), and the envelope export test ignores PDF dates and file IDs (#1220). Effect › Artistic › Film Grain (Grain, Highlight Area, Intensity; Photoshop-style filters 29/57) (#1282), and Craquelure, Mosaic Tiles and Stained Glass redraw 25–30% faster with identical pixels (#1265). Direct Selection: clicking a segment selects only that segment, and Delete removes just it (#1300); Shift-click deselects one anchor of a path selected whole (#1263). Pen + Alt converts anchors of paths inside a selected group or compound path (#1306). The Curvature tool shows circular point markers without direction handles (#1284). Snap to Point: pressing near an anchor drags by that anchor, with Smart Guides on or off (#1313). Transform Again repeats the options of the transform it repeats (#1303). Aligning anchors that are already aligned adds no undo step (#1276), and type commands that change nothing record none either (#1316). Simplify keeps the path selected with its new anchors, and its dialog previews and shows the anchor count (#1305). Adding a stroke colour to an unpainted zero-width stroke gives it a visible 1 pt width (#1256). The Eyedropper samples locked objects, template layers and art outside isolation mode (#1260), and shows a pipette cursor (#1288). Fonts named by their full name resolve to the right face (#1267), and Proportional Metrics brings the matching kerning (`apkn`, `vkrn`, `vapk`) (#1291). Artboards: Escape leaves Artboard editing (#1296), Document Setup's Edit Artboards switches to the Artboard tool (#1294), and the Artboard tool starts on the active artboard (#1309). New and imported documents use the Gridline every and Subdivisions preferences (#1314). Send to Current Layer refuses a hidden or locked current layer (#1301), and layer row commands check explicit ids (#1255). Links: Find in Folder… finds missing linked files in a folder and its subfolders and can copy them into the document's folder (#1287). Image Trace traces images over 64 megapixels scaled down instead of refusing them (#1315). DXF export marks closed curves as closed SPLINE entities (#1320). EPS import: closepath respects the path size limit (#1311). The interface is available in Hungarian (#1302), and more Czech labels are translated (#1259). Linux RPMs declare shared-library capabilities (#1290). CI pins every third-party action to a verified commit (#1321). Select menu commands skip hidden and locked art and stay inside the isolated group in isolation mode (#1325). Fill, stroke, gradient and Appearance panel commands that change nothing add no undLine truncated
| 2026-10-12 | Georgian interface (`ka`, ქართული): the whole catalog, plurals and messages, tested complete; Georgian letters come from an installed font (SF Georgian, Sylfaen, Noto Sans Georgian, DejaVu Sans) from the first frame; Type › Change Case › Title Case and Sentence case leave Georgian lower case instead of turning it into Mtavruli. |
| 2026-10-11 | Effect › Brush Strokes: Accented Edges, Angled Strokes, Crosshatch, Dark Strokes, Ink Outlines, Spatter, Sprayed Strokes, Sumi-e (G2). Command parameters from agents and files checked before anything changes (paint, place, cuts, dashes, crop, asset ids, anchors, paths, distort; #984–#999); command dialogs keep whole numbers whole, so Create Object Mosaic takes the tiles typed (#1000); stepper arrows take Shift (×10) and Ctrl/Cmd (÷10) like the arrow keys (#991). Exports and Rasterize supersample Art Optimized edges, so shapes meeting edge to edge leave no seam (#983). Character and paragraph styles take leading, kerning, mojikumi and the other attributes left out at their defaults (#1001). Drawing, typing and pasting with no layer shown and unlocked is refused instead of adding art to a hidden or locked layer (#1002). MCP `add_text` gives type on or in a path the colour asked for (#1003). MCP `screenshot` of a connected app renders the artboard asked for (#1004). `vectorcraft-cli run` ends quietly when its reader closes early (#1005). Select › All on Active Artboard selects on the artboard made active, not always the first (#1006). Reverse Gradient keeps off-centre midpoints, mirrored (#1007). A polar grid with no radial dividers draws none (#1008). Use Precise Cursors also covers the Pen's join pointer (#1009). SVGs with one absolute and one unitless root side import at their size, unstretched (#1010). DXF US survey inches, yards and miles open at their size and name (#1011). A file placed into a document with no other links follows its first change even while the app sits idle (#1031). PDF import keeps the style a font name says when the file doesn't embed the font (#1023). Shift selects ruler guides and art together, and Delete removes both (#1022). Open filled paths are hit by their fill on every side, the rotate cursor bows around the corner it is at, the flip icons match their flips, the Color Picker previews on the selection, and Properties › Transform reaches Scale Corners and Scale Strokes & Effects (#1036). Offset Path and the other booleans finish on outlines where the sweep used to loop until memory ran out (linesweeper 0.5, #1028). Floating panel groups stack into sets that move together, collapse to their tabs and dock as extra dock columns that scroll (#1020). Ruler guides live on layers: listed in the Layers panel, shown, hidden, locked, duplicated, merged and deleted with their layer, and moved between layers (#1021). A `.ai` whose editing data uses global process colours (`Xk`/`XK`) or pattern fills keeps its sublayers: the colours come in as global swatches at their tint, the patterns as pattern swatches (#1025). A `.ai` in PostScript form opens through its layers, read from the program itself, also when it names the prolog defining its operators without including it, as Rhino and other CAD apps write it (#1027). A fill or stroke chosen while the Type tool has characters selected colours just those characters (#1063). Scaled type shows its scaled font size, leading, baseline shift and horizontal scale in the Character panel, and a size typed there is the size you get (#1034). Character panel menu › Proportional Metrics sets Japanese and Chinese full-width glyphs on the font's proportional widths in horizontal type (#966). Align, Distribute, Move, Arrange, Lock, Hide, Ungroup and other Object commands that would change nothing no longer record an undo step or mark the document changed (#1060). Spot colours defined in Lab open with their Lab values from `.ai` and PDF files, instead of as wrong RGB colours or their CMYK equivalents (#1032). Build scripts leave a generated source they wouldn't change untouched, so the next build doesn't compile most of the workspace again where file times lose their sub-second part (#1051). A fill colour recolours the gradient mesh point last clicked with the Mesh tool or Direct Selection, and a Mesh tool click on a mesh's point selects that mesh (#1052). The All Tools drawer stays two tools wide instead of filling a wide window (#1054). Text Wrap's Make, Release and Options refuse a list of object ids with a malformed or unknown id instead of skipping it (#1055). A freeform gradient line with a malformed point index is refused instead of being shortened to the indices that are valid (#1056). The Corners dialog (`ui.corners`) refuses a malformed object id or a listed anchor that isn't a corner instead of editing the selection or the other corners (#1057). New View refuses a centre that isn't exactly [x, y] and a rotation that isn't a number, instead of trimming the one and saving the other as 0° (#1058). The command sweeps try junk scale, spacing and artboard values too, which they had skipped since before those bugs were fixed (#1059). EPS and PostScript `arc` and `arcn` with huge angles no longer hang the import, and an arc whose angles are whole turns apart is empty, as the PostScript reference defines it (#1062). Align and DisLine truncated
| 2026-10-10 | Initial live Revolve (Effect › 3D and Materials, #846, #605), in its own `three-d` crate. Progress docs re-measured and restructured to the craftrules standard (this page, `docs/target-app-parity.md`, `gaps.md`, `ui-parity.md`, the format, hardware, localization, effects and type checklists). Same day: v0.8.0; Effect › Distort, Pixelate and Texture filters (13); German interface; Variables (data merge); Graph Type value axes and tick marks; restart when the first frame never reaches the screen (#964) |
| 2026-10-10 | Initial live Revolve (Effect › 3D and Materials, #846, #605), in its own `three-d` crate. Progress docs re-measured and restructured (this page, `docs/target-app-parity.md`, `gaps.md`, `ui-parity.md`, the format, hardware, localization, effects and type checklists). Same day: v0.8.0; Effect › Distort, Pixelate and Texture filters (13); German interface; Variables (data merge); Graph Type value axes and tick marks; restart when the first frame never reaches the screen (#964) |
| 2026-10-09 | Radial Blur, Smart Blur, Unsharp Mask (gap 2 begins); 340 commits, the busiest day |
| 2026-10-08 | v0.5.0–v0.7.0; community contributions: Pen and shape-tool modifiers, Layers, Artboards, Japanese composition, Hebrew/Arabic type, interface languages, saved selections |
| 2026-10-07 | v0.4.0; issue fixes; Layers panel rework |
@@ -192,12 +219,41 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
| 2026-10-01 | Renamed from DrawCraft to VectorCraft |
| 2026-09-30 | Repository history begins |
The full pre-standard record of what landed is kept in [docs/roadmap.md](docs/roadmap.md#progress-log-before-the-progress-docs-standard).
The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap.md#earlier-progress-log).
## Revision history
| Date | Change | Summary |
|---|---|---|
| 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). |
| 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. |
| 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. |
| 2026-11-10 | minor | Tidy-up, no content change: the unheaded change bullets at the top of the file and a revision row inside the headline-numbers table move to this table under their commit dates. Scores and estimates unchanged. |
| 2026-11-10 | minor | Raster effects: Effect Gallery thumbnails and an in-dialog preview (an original drawing through each filter). Features-table Raster effects 85% → 88%, hours 1–2 → none. Headline numbers unchanged, so the progress log is unchanged. |
| 2026-11-05 | minor | 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. |
| 2026-11-04 | minor | 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. |
| 2026-11-03 | minor | Paint: new gradients use the document's color model for default stops, including Gradient tool creation. Scores and estimates unchanged. |
| 2026-11-03 | minor | UI: Window → Help Bar toggles the tool-help strip separately from the status bar and saves visibility with workspaces. Scores and estimates unchanged. |
| 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. |
| 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-12 | minor | Gujarati (`gu`): reviewed by a native speaker; zero/one singular plurals (CLDR); Gujarati craft-fonts faces join the UI fonts; strings added on main since branching translated (4,286 rows) |
| 2026-11-11 | minor | Gujarati (`gu`): 4,235-row machine-assisted interface catalog, one/other plurals, desktop Gujarati font fallback; messages not yet translated; native review pending |
| 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged |
| 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. |
| 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. |
| 2026-11-02 | minor | Closed font-family fields accept wheel input for selected text in Character, Properties and Control (#5253); scores and estimates unchanged. |
| 2026-11-01 | minor | Progress log row for the Color Effects add-on's Find Nearest Swatch (#4923); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Path Precision Tools add-on's Expand Dashes into Paths (#4922); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Randomize Opacity (#4925); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Arrange Tools add-on's Sort Objects (#4917); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Document Tools add-on's New Symbols from Layers (#4927); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for the Document Tools add-on's Save a Timestamped Copy (#4926); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for Divide into Dashes (Path Precision Tools add-on, #4950); headline numbers unchanged. |
| 2026-11-01 | minor | Progress log row for Group Overlapping Objects (Arrange Tools add-on, #4928); headline numbers unchanged. |
| 2026-10-31 | minor | Progress log row for Export for Screens laid out as the reference app's (#4895) and the 2026-10-31 community landings; headline numbers unchanged. |
| 2026-10-31 | minor | Progress log row for the Arrange Tools add-on; headline numbers unchanged. |
| 2026-10-29 | minor | Progress log row for the Linux Flatpak clipboard's core Wayland protocol text fallback; headline numbers unchanged. |
| 2026-10-29 | minor | Progress log row for the Linux clipboard retry backoff; headline numbers unchanged. |
| 2026-10-23 | minor | Progress log row for Pathfinder › Trap; Live vector effects hours 6–10 → 4–8; headline numbers unchanged. |
| 2026-10-23 | minor | Progress log row for OpenType SVG colour fonts; headline numbers unchanged. |
| 2026-10-23 | minor | Progress log row for COLR colour fonts; headline numbers unchanged. |
@@ -217,10 +273,14 @@ The full pre-standard record of what landed is kept in [docs/roadmap.md](docs/ro
| 2026-10-13 | minor | Bounded synthetic control input (#1709): counts and queued events validated before mutation; control-channel bursts yield between frames. Scores and hours unchanged. |
| 2026-10-14 | minor | Progress log row for the merges of 2026-10-14 (#1641–#1808 as listed there) and Image Trace's #1647 and #1657; the 2026-10-13 row now says that a guide's position in the Transform panel (#1659) is not established by the documentation found and is kept as a convenience pending the owner's decision; headline numbers unchanged. |
| 2026-10-13 | minor | Control transport deadlines (#1726): idle and partial clients and blocked replies release connection slots; parity scores and estimates unchanged. |
| 2026-10-10 | minor | Method aligned with the standard, no new evidence: full ready for real work is the additive weighted sum, ~62%; hours per audience; beta ~13 points away |
| 2026-10-13 | minor | PDF.R1: editable PDF import uses the shared reader, scans page content in windows, and rejects known incomplete input before returning a document. |
| 2026-10-13 | minor | 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. |
| 2026-10-10 | minor | Method changed, no new evidence: full ready for real work is the additive weighted sum, ~62%; hours per audience; beta ~13 points away |
| 2026-10-10 | minor | Added the essentials-user readiness score (~75%) |
| 2026-10-10 | minor | Ready for real work re-examined against the issue tracker and user feedback: 50% → 55% (full), 65% mainstream added; see target-app-parity.md |
| 2026-10-10 | minor | Applied the core-workflow gate (docs/roadmap.md › Alpha gate): passes, stage stays alpha |
| 2026-10-10 | major | Re-measured against Illustrator 2026 (30.x) from code counts, 71 open issues and public docs; stage set to alpha; moved the parity estimate, honest assessment and "Shipped so far" to `docs/target-app-parity.md`, the gap list to `docs/gaps.md`, milestones to `docs/roadmap.md`, the `.ai` scope to `docs/file-format-parity.md` |
| 2026-10-10 | minor | UI.5: Shared docking adds tab reordering, docking into other groups, dock splits and resizable floating panel groups. Panel positions and return locations persist with workspaces; the native icon rail and Tools panel remain available. |
| 2026-10-10 | minor | UI.4: Dock and floating-panel headers use shared accessible tabs with bounded overflow. Widget-state theme application uses `craft-ui`; all four palettes, font stacks and preferences remain app-owned. |
| 2026-10-05 | major | Honest assessment by dimension and the prioritized gap list |
| 2026-10-02 | major | First 22-area weighted parity estimate |
+5 -3
View File
@@ -16,7 +16,7 @@ workspace = true
[dependencies]
vectorcraft-color = { workspace = true }
vectorcraft-doc = { workspace = true }
vectorcraft-engine = { workspace = true, features = ["bundled-fonts"] }
vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] }
vectorcraft-format = { workspace = true }
vectorcraft-geom = { workspace = true }
vectorcraft-svg = { workspace = true }
@@ -34,8 +34,9 @@ winsafe = { version = "0.0.29", default-features = false, features = ["kernel",
# DirectWrite's system font collection and GDI's font list (the desktop app's src/system_fonts.rs,
# shared): fonts that font services such as Adobe Fonts load in place (#579, #1258). MIT OR
# Apache-2.0.
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi"] }
# Apache-2.0. Win32_System_Threading has `GetProcessAffinityMask`, which the desktop app's
# src/windows_cores.rs, shared, uses to count the cores the process may run on.
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Threading"] }
# CoreText's font manager (the desktop app's src/mac_fonts.rs, shared): fonts that apps and font
# managers register from their own folders (#579). Zlib OR Apache-2.0 OR MIT.
@@ -44,5 +45,6 @@ objc2-core-foundation = { version = "0.3", default-features = false, features =
objc2-core-text = { version = "0.3", default-features = false, features = ["std", "CTFontManager"] }
[dev-dependencies]
tempfile = "3"
vectorcraft-testkit = { workspace = true }
serde_json = { workspace = true }
+169 -37
View File
@@ -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] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
//! vectorcraft-cli info FILE
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
//! vectorcraft-cli perf [--paths 50000] [--deep]
@@ -49,6 +50,10 @@ mod prefs_dir;
#[cfg(windows)]
#[path = "../../vectorcraft/src/system_fonts.rs"]
mod system_fonts;
/// The desktop app's affinity-mask reader, shared: renders start workers only for usable cores.
#[cfg(windows)]
#[path = "../../vectorcraft/src/windows_cores.rs"]
mod windows_cores;
use serde_json::{Value, json};
use vectorcraft_engine::file_access::{self, AutomationRoots};
@@ -68,7 +73,12 @@ const USAGE: &str = "\
vectorcraft-cli — VectorCraft automation
USAGE:
vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
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]... [--allow-plugin-grants]
Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979
(vectorcraft --control 7979), falling back to a headless in-process session.
--automation-read-root / --automation-write-root confine the files the agent's commands read
@@ -76,24 +86,37 @@ USAGE:
DIR, links followed; each may be given more than once, a path inside any of its folders being
allowed, and a kind left out grants none of its access. They imply --headless: a running app
enforces its own (vectorcraft --control PORT --automation-read-root DIR …).
--allow-plugin-grants lets plugin.install's grant and allowHeavy take effect in this session,
so whoever sends the commands can give a plug-in the permissions it lists, and a heavy budget,
with nobody approving them. Without it they are refused, and a plug-in that lists permissions
installs only when its hash is already recorded in grants.json, by a person's approval in the
desktop app or by a grant accepted under this flag. A grant accepted under this flag stays
recorded and counts as approved in later sessions. It implies --headless. It can't be used
with --automation-read-root or --automation-write-root: a server confined to folders has no
plug-in store, so it reads no grants.json, and a plug-in that lists permissions or asks for a
heavy budget does not install there. With VECTORCRAFT_NO_PREFS set there is no store either,
and a grant accepted under this flag lasts for that session only.
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] [--allow-plugin-grants]
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.
Errors name the step, counting from 0 as \"$N\" references do.
--allow-plugin-grants lets plugin.install's grant and allowHeavy take effect in this run, as
for mcp.
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] [--legacy-name-encoding ENC] [--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).
@@ -103,7 +126,10 @@ USAGE:
IN left things out (hidden text, art or layers it could not read; the notes say which) unless
--replace-lossy is given. --editing-data opens a .ai or an EPS with editing data from its editing copy
even where that draws differently from its PDF part or page (which can be older), as long as
it can be read. A PDF OUT omits the embedded native document unless --preserve-editing is
it can be read. --legacy-name-encoding reads the names in a .ai's or an EPS's editing data
that aren't UTF-8 (layers, objects, artboards, colors, gradients, patterns, graphic styles,
swatches, brushes, symbols, variables and data sets, and data sets' text values) in
windows-1252 (the default), macintosh, windows-949, shift_jis, gbk or big5. A PDF OUT omits the embedded native document unless --preserve-editing is
given (the app's Save As PDF still defaults to keeping it). With --preserve-editing, when the
attachment is written the result's warnings say so (it is left out, with its own warning, for
--artboard or a --range without every artboard).
@@ -123,12 +149,17 @@ USAGE:
Render FILE (any readable format) fitted to WxH (default 2880x1800) and print ms per frame
(warm), multithreaded and single-threaded.
vectorcraft-cli perf [--paths N] [--deep]
vectorcraft-cli perf [--paths N] [--deep] [--native-io [--artboards 1..4]]
Check the performance budgets (render, pan, hit test, save/load, SVG, Pathfinder, handle
and segment drags) on a synthetic N-path document (default 50000). Exits non-zero if a
budget is exceeded, unless the report says the machine is busy. --deep also times work with
no budget yet and prints memory use (the working set on Windows), with the peak so far on
Windows and Linux.
--native-io instead measures the application's native save/open commands (one warmup,
five samples, no disk I/O), including preview, PDF, compression and API base64 costs.
It reports the default and explicit PDF opt-out, with and without preview/compression;
--artboards repeats the same artwork
on 1 to 4 overlapping artboards. This mode allows at most 50000 paths.
";
/// The usage text plus the formats `document.open` reads and `document.export` writes.
@@ -161,18 +192,27 @@ fn help() -> Result<(), String> {
}
fn main() -> ExitCode {
// Before the first render: the cores the process may run on.
#[cfg(windows)]
windows_cores::install();
// Before any font lookup: the fonts font services load (#579).
#[cfg(windows)]
system_fonts::install();
#[cfg(target_os = "macos")]
mac_fonts::install();
prefs_dir::install_fonts();
let args: Vec<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..]),
@@ -196,21 +236,39 @@ fn main() -> ExitCode {
}
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
/// ICC profiles loaded and the plug-ins installed (#2168, #2174, #2541), in the folders next to the preferences that the desktop
/// app uses too. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they do there.
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_scripts_dir(&mut h.session);
prefs_dir::attach_new_doc_profiles(&mut h.session);
prefs_dir::attach_profile_store(&mut h.session);
prefs_dir::attach_color_settings(&mut h.session);
prefs_dir::attach_plugin_store(&mut h.session);
prefs_dir::attach_pdf_preset_store(&mut h.session);
prefs_dir::attach_custom_dictionary(&mut h.session);
prefs_dir::attach_arrowheads(&mut h.session);
h
}
fn mcp(args: &[String]) -> Result<(), String> {
/// Makes `h`'s `plugin.install` accept `grant` and `allowHeavy` when `allow` (`--allow-plugin-grants`).
fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
if allow {
h.session.allow_plugin_grants_from_requests();
}
h
}
/// `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();
}
let mut connect: Option<String> = None;
let mut headless = false;
let mut allow_grants = false;
let (mut read_roots, mut write_roots): (Vec<String>, Vec<String>) = (vec![], vec![]);
let mut it = args.iter();
while let Some(a) = it.next() {
@@ -222,6 +280,7 @@ fn mcp(args: &[String]) -> Result<(), String> {
match flag {
"--connect" => connect = Some(it.next().cloned().ok_or("--connect needs an address")?),
"--headless" => headless = true,
"--allow-plugin-grants" => allow_grants = true,
"--automation-read-root" | "--automation-write-root" => {
let dir = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("{flag} needs a folder"))?;
if flag == "--automation-read-root" { read_roots.push(dir) } else { write_roots.push(dir) }
@@ -232,6 +291,15 @@ fn mcp(args: &[String]) -> Result<(), String> {
if headless && connect.is_some() {
return Err("use either --connect or --headless".into());
}
if allow_grants && connect.is_some() {
return Err("--allow-plugin-grants applies to the headless server; in a running app a person approves each plug-in".into());
}
if allow_grants && !(read_roots.is_empty() && write_roots.is_empty()) {
return Err("--allow-plugin-grants can't be used with --automation-read-root or --automation-write-root: a server confined to folders has no plug-in store to record a grant in".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)?;
@@ -243,9 +311,9 @@ fn mcp(args: &[String]) -> Result<(), String> {
// Every thread of this process, not only the server's: nothing reaches past the roots.
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 {
Box::new(with_stores(Headless::with_document()))
Box::new(accepting_grants(Headless::with_document().with_automation_roots(Some(roots)), allow_grants))
} else if headless || safe_mode || allow_grants {
Box::new(accepting_grants(with_stores(Headless::with_document()), allow_grants))
} else if let Some(addr) = connect {
// Explicit address: fail loudly if the app isn't there.
Box::new(Remote::connect(&addr).map_err(|e| format!("cannot connect to {addr}: {e}"))?)
@@ -272,21 +340,46 @@ 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",
"--legacy-name-encoding",
];
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>;
// The encoding of a legacy `.ai`'s names that aren't UTF-8, passed on as `document.open`'s
// `legacyNameEncoding`; the engine checks it.
let mut legacy_names = None::<String>;
// Legacy `.ai` options, passed on as the export's own (`aiVersion`, `hiddenObjects`,
// `transparentImages`); the engine checks their values.
let mut legacy: Vec<(&str, String)> = vec![];
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,
@@ -294,6 +387,9 @@ fn convert(args: &[String]) -> Result<(), String> {
"--replace-lossy" => replace_lossy = true,
"--editing-data" => editing_data = true,
"--preserve-editing" => preserve_editing = true,
"--legacy-name-encoding" => {
legacy_names = Some(it.next().cloned().ok_or("--legacy-name-encoding needs an encoding such as windows-949")?);
}
"--ai-version" => legacy.push(("aiVersion", it.next().cloned().ok_or("--ai-version needs 7 or pdf")?)),
"--hidden-objects" => legacy.push(("hiddenObjects", it.next().cloned().ok_or("--hidden-objects needs layer, omit or visible")?)),
"--transparent-images" => legacy.push(("transparentImages", it.next().cloned().ok_or("--transparent-images needs flatten or omit")?)),
@@ -306,8 +402,14 @@ fn convert(args: &[String]) -> Result<(), String> {
return Err("a .ait template holds every artboard: --artboard and --range don't apply".into());
}
let mut h = Headless::new();
let opened = if editing_data {
let params = json!({"path": input, "editingData": "always"});
let opened = if editing_data || legacy_names.is_some() {
let mut params = json!({"path": input});
if editing_data {
params["editingData"] = json!("always");
}
if let Some(e) = &legacy_names {
params["legacyNameEncoding"] = json!(e);
}
h.call("engine.execute", json!({"command": "document.open", "params": params})).map_err(|e| format!("open {input}: {e}"))?
} else {
h.call("app.open", json!({"path": input})).map_err(|e| format!("open {input}: {e}"))?
@@ -316,10 +418,18 @@ fn convert(args: &[String]) -> Result<(), String> {
// Save as Template writes every artboard, with the .ai options.
("file.saveAsTemplate", json!({"path": output, "format": "ait", "outlineText": outline_text, "acknowledgeLoss": replace_lossy}))
} else {
// A conversion keeps hidden layers and objects, written hidden, where the format can (SVG,
// PSD).
let params = json!({"path": output, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true, "acknowledgeLoss": replace_lossy});
let mut params = with_pixel_scale(params, &output, scale);
let params = json!({"path": output, "artboard": artboard, "range": range, "acknowledgeLoss": replace_lossy});
let mut params = with_pixel_scale(params, &output, scale, ppi);
// An option the format doesn't read comes back in the warnings, so each goes out only
// when it was asked for: `outlineText` with --outline-text, and `hiddenLayers` to the
// formats that have it (SVG, PSD), where a conversion keeps hidden layers and objects,
// written hidden.
if outline_text {
params["outlineText"] = json!(true);
}
if vectorcraft_engine::cmd::fileio::writable_format(None, Some(&output)).is_ok_and(|f| f.options.iter().any(|o| o.name == "hiddenLayers")) {
params["hiddenLayers"] = json!(true);
}
if let Some(decimals) = decimals {
params["decimals"] = json!(decimals);
}
@@ -365,12 +475,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
}
@@ -382,7 +497,12 @@ fn info(args: &[String]) -> Result<(), String> {
let base = h.call("engine.execute", json!({"command": "file.info", "params": {}}))?;
let doc = h.session.doc().map_err(|e| e.to_string())?.doc.clone();
let mut kinds: std::collections::BTreeMap<&'static str, usize> = Default::default();
doc.walk(|n| *kinds.entry(n.kind_label()).or_default() += 1);
// Ruler guides are not counted among the objects.
doc.walk(|n| {
if !n.is_ruler_guide() {
*kinds.entry(n.kind_label()).or_default() += 1;
}
});
let fonts = h.call("engine.execute", json!({"command": "text.fonts", "params": {}})).unwrap_or(Value::Null);
let artboards: Vec<Value> =
doc.artboards.iter().map(|a| json!({"name": a.name, "rect": [a.rect.x0, a.rect.y0, a.rect.width(), a.rect.height()]})).collect();
@@ -478,7 +598,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();
}
@@ -487,7 +607,9 @@ 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 allow_grants = false;
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}"));
@@ -522,15 +644,25 @@ fn run(args: &[String]) -> Result<(), String> {
steps.push(Step::Export(val("a file")?));
params_for = None;
}
"--allow-plugin-grants" => allow_grants = true,
"--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}`")),
}
}
let mut h = with_stores(Headless::new());
let mut h = accepting_grants(with_stores(Headless::new()), allow_grants);
let mut out = std::io::stdout().lock();
// A reader that stopped early (a closed pipe) isn't an error, and the batch goes on: its later
// steps (an export…) still run, unprinted.
@@ -569,7 +701,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}))?;
+158 -4
View File
@@ -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", &params).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(), 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(), 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,
+120 -28
View File
@@ -3,8 +3,6 @@ use std::process::{Command, Stdio};
use serde_json::{Value, json};
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli");
/// Returns the path of `name` in `vectorcraft-cli-test-<pid>` in the temp folder. The first call removes
/// that folder and creates it again empty.
fn tmp(name: &str) -> std::path::PathBuf {
@@ -19,9 +17,86 @@ fn empty_dir(dir: std::path::PathBuf) -> std::path::PathBuf {
dir
}
/// `run` and `mcp --headless` refuse `plugin.install` with this param unless the process was started
/// with `--allow-plugin-grants`.
fn approval_param_needs_the_start_up_flag(key: &str, value: Value) {
let module = vectorcraft_format::base64_encode(include_bytes!("../../../../crates/plugins/tests/fixtures/desaturate.wasm"));
let steps = tmp(&format!("{key}.json"));
std::fs::write(&steps, json!([{"command": "plugin.install", "params": {"dataBase64": module, key: value}}]).to_string()).unwrap();
let config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-{key}-{}", std::process::id())));
let run = |extra: &[&str]| {
Command::new(crate::bin())
.env("VECTORCRAFT_CONFIG_DIR", &config)
.args(["run", "--commands", steps.to_str().unwrap()])
.args(extra)
.output()
.unwrap()
};
let out = run(&[]);
assert!(!out.status.success());
let shown = String::from_utf8_lossy(&out.stderr).into_owned() + &String::from_utf8_lossy(&out.stdout);
assert!(shown.contains("--allow-plugin-grants"), "{shown}");
let out = run(&["--allow-plugin-grants"]);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let mcp_config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-mcp-{key}-{}", std::process::id())));
let mcp_install = |extra: &[&str]| -> Value {
let mut child = Command::new(crate::bin())
.env("VECTORCRAFT_CONFIG_DIR", &mcp_config)
.args(["mcp", "--headless"])
.args(extra)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
{
let mut stdin = child.stdin.take().unwrap();
let params = json!({"dataBase64": module, key: value});
for m in [
json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}),
json!({"jsonrpc":"2.0","method":"notifications/initialized"}),
json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"run_command","arguments":{"command":"plugin.install","params":params}}}),
] {
writeln!(stdin, "{m}").unwrap();
}
}
let out = child.wait_with_output().unwrap();
assert!(out.status.success());
let replies: Vec<Value> = String::from_utf8(out.stdout).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
replies.into_iter().find(|r| r["id"] == 2).unwrap()["result"].take()
};
let refused = mcp_install(&[]);
assert_eq!(refused["isError"], true, "without the flag: {refused}");
assert!(refused["content"][0]["text"].as_str().unwrap().contains("--allow-plugin-grants"), "{refused}");
let accepted = mcp_install(&["--allow-plugin-grants"]);
assert_eq!(accepted["isError"], false, "with the flag: {accepted}");
}
/// `run` and `mcp --headless` refuse `plugin.install`'s `grant` and `allowHeavy` unless the process was
/// started with `--allow-plugin-grants`, which `mcp` won't take with `--connect` or the automation roots.
#[test]
fn plugin_grants_need_the_start_up_flag() {
approval_param_needs_the_start_up_flag("grant", json!(["doc.read"]));
approval_param_needs_the_start_up_flag("allowHeavy", json!(true));
let out = Command::new(crate::bin()).args(["mcp", "--allow-plugin-grants", "--connect", "127.0.0.1:1"]).output().unwrap();
assert!(!out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants applies to the headless server"));
let root = std::env::temp_dir();
for flag in ["--automation-read-root", "--automation-write-root"] {
let out =
Command::new(crate::bin()).args(["mcp", "--allow-plugin-grants", flag, root.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap();
assert!(!out.status.success(), "{flag}");
assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants can't be used with"), "{flag}");
}
let usage = Command::new(crate::bin()).arg("help").output().unwrap();
assert!(String::from_utf8_lossy(&usage.stdout).contains("--allow-plugin-grants lets plugin.install's grant and allowHeavy take effect"));
}
#[test]
fn commands_prints_catalogue() {
let out = Command::new(BIN).arg("commands").output().unwrap();
let out = Command::new(crate::bin()).arg("commands").output().unwrap();
assert!(out.status.success());
let v: Value = serde_json::from_slice(&out.stdout).unwrap();
let ids: Vec<&str> = v.as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect();
@@ -33,7 +108,7 @@ fn run_batch_exports() {
let svg = tmp("batch.svg");
let png = tmp("batch.png");
let dc = tmp("batch.vectorcraft");
let out = Command::new(BIN)
let out = Command::new(crate::bin())
.args(["run", "--cmd", "file.new", "--params", r#"{"width":200,"height":100}"#])
.args(["--cmd", "shape.ellipse", "--params", r#"{"x":10,"y":10,"width":80,"height":60}"#])
.args(["--cmd", "paint.setFill", "--params", r##"{"color":"#3366ff"}"##])
@@ -50,7 +125,7 @@ fn run_batch_exports() {
assert_eq!(u32::from_be_bytes(png_bytes[16..20].try_into().unwrap()), 400);
// Re-open the native file and inspect.
let out = Command::new(BIN).args(["run", "--in", dc.to_str().unwrap(), "--cmd", "document.inspect"]).output().unwrap();
let out = Command::new(crate::bin()).args(["run", "--in", dc.to_str().unwrap(), "--cmd", "document.inspect"]).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let last: Value = serde_json::from_str(String::from_utf8(out.stdout).unwrap().lines().last().unwrap()).unwrap();
assert_eq!(last["result"]["artboards"][0]["width"], 200.0);
@@ -66,7 +141,7 @@ fn scale_sizes_raster_exports_only() {
let svg = svg.to_str().unwrap();
let (plain, scaled, png) = (tmp("plain.dxf"), tmp("scaled.dxf"), tmp("scaled.png"));
let ok = |args: &[&str]| {
let out = Command::new(BIN).args(args).output().unwrap();
let out = Command::new(crate::bin()).args(args).output().unwrap();
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
};
ok(&["convert", svg, plain.to_str().unwrap()]);
@@ -80,11 +155,11 @@ fn scale_sizes_raster_exports_only() {
#[test]
fn run_reports_errors() {
let out = Command::new(BIN).args(["run", "--cmd", "nope.nothing"]).output().unwrap();
let out = Command::new(crate::bin()).args(["run", "--cmd", "nope.nothing"]).output().unwrap();
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr).to_string();
assert!(stderr.contains("step 0 (nope.nothing)"), "{stderr}");
let out = Command::new(BIN).args(["run", "--params", "{}"]).output().unwrap();
let out = Command::new(crate::bin()).args(["run", "--params", "{}"]).output().unwrap();
assert!(!out.status.success());
}
@@ -113,7 +188,7 @@ fn run_reads_steps_from_a_commands_file() {
{"id": "object.setProps", "params": {"id": "$2.ids.0", "name": "barcode"}},
]);
std::fs::write(&steps, serde_json::to_string_pretty(&file).unwrap()).unwrap();
let out = Command::new(BIN)
let out = Command::new(crate::bin())
.args(["run", "--cmd", "file.new", "--params", r#"{"width":200,"height":100}"#, "--commands", steps.to_str().unwrap()])
.args(["--cmd", "document.node", "--params", r#"{"id":"$2.ids.0"}"#, "--export", svg.to_str().unwrap()])
.output()
@@ -133,7 +208,7 @@ fn run_reads_steps_from_a_commands_file() {
#[test]
fn run_reads_json_lines_from_standard_input() {
let svg = tmp("stdin.svg");
let mut child = Command::new(BIN)
let mut child = Command::new(crate::bin())
.args(["run", "--commands", "-", "--export", svg.to_str().unwrap()])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
@@ -156,7 +231,7 @@ fn run_reads_json_lines_from_standard_input() {
#[test]
fn run_refuses_malformed_commands_naming_the_step() {
let fails = |args: &[&str]| {
let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap();
let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap();
assert!(!out.status.success(), "{args:?}");
(String::from_utf8_lossy(&out.stderr).to_string(), json_lines(&out.stdout).len())
};
@@ -204,11 +279,11 @@ fn run_refuses_malformed_commands_naming_the_step() {
/// `--help` and `-h` right after a subcommand print the usage that `vectorcraft-cli help` prints.
#[test]
fn help_after_a_subcommand_prints_the_usage() {
let usage = Command::new(BIN).arg("help").output().unwrap();
let usage = Command::new(crate::bin()).arg("help").output().unwrap();
assert!(usage.status.success() && String::from_utf8_lossy(&usage.stdout).contains("USAGE:"));
for sub in ["mcp", "run", "commands", "convert", "info", "bench", "perf"] {
for flag in ["--help", "-h"] {
let out = Command::new(BIN).args([sub, flag]).stdin(Stdio::null()).output().unwrap();
let out = Command::new(crate::bin()).args([sub, flag]).stdin(Stdio::null()).output().unwrap();
assert!(out.status.success(), "{sub} {flag}: {}", String::from_utf8_lossy(&out.stderr));
assert!(out.stdout == usage.stdout, "{sub} {flag}: {}", String::from_utf8_lossy(&out.stdout));
}
@@ -219,7 +294,7 @@ fn help_after_a_subcommand_prints_the_usage() {
/// with them.
#[test]
fn help_later_in_the_line_prints_the_usage() {
let usage = Command::new(BIN).arg("help").output().unwrap();
let usage = Command::new(crate::bin()).arg("help").output().unwrap();
let mut wrong = vec![];
for args in [
&["mcp", "--headless", "--help"][..],
@@ -240,7 +315,7 @@ fn help_later_in_the_line_prints_the_usage() {
&["perf", "--paths", "many", "-h"],
&["convert", "--decimals", "many", "--help"],
] {
let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap();
let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap();
if !out.status.success() || out.stdout != usage.stdout {
wrong.push(format!("{args:?}: {}{}", String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout)));
}
@@ -251,17 +326,18 @@ fn help_later_in_the_line_prints_the_usage() {
/// Further along the line, `-h` is the value of the option before it.
#[test]
fn help_as_an_option_value_goes_to_the_option() {
let out = Command::new(BIN).args(["run", "--cmd", "-h"]).output().unwrap();
let out = Command::new(crate::bin()).args(["run", "--cmd", "-h"]).output().unwrap();
let err = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success() && err.contains("vectorcraft-cli: step 0 (-h):") && out.stdout.is_empty(), "{err}");
let out = Command::new(BIN).args(["convert", "in.svg", "--range", "-h"]).output().unwrap();
let out = Command::new(crate::bin()).args(["convert", "in.svg", "--range", "-h"]).output().unwrap();
let err = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success() && err.contains("convert needs IN and OUT") && out.stdout.is_empty(), "{err}");
}
#[test]
fn mcp_headless_over_stdio() {
let mut child = Command::new(BIN).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
let mut child =
Command::new(crate::bin()).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
{
let mut stdin = child.stdin.take().unwrap();
for m in [
@@ -283,6 +359,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(crate::bin()).args(["--safe-mode", "mcp", "--connect", "127.0.0.1:9"]).env("VECTORCRAFT_NO_PREFS", "1").output().unwrap();
let err = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success() && err.contains("--safe-mode runs a headless session"), "{err}");
// Something listening on the default address, as a running app does; a running app or another
// program already holding it serves as well.
let _app = std::net::TcpListener::bind(vectorcraft_mcp::DEFAULT_ADDR);
let out = Command::new(crate::bin()).args(["--safe-mode", "mcp"]).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success() && err.contains("MCP server on stdio (headless)"), "{err}");
}
/// `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]
@@ -315,7 +407,7 @@ fn mcp_automation_roots_take_several_folders() {
}
let dir = |d: &str| base.join(d).to_string_lossy().into_owned();
let file = |d: &str, f: &str| base.join(d).join(f).to_string_lossy().into_owned();
let mut child = Command::new(BIN)
let mut child = Command::new(crate::bin())
.args(["mcp", "--automation-read-root", &dir("in"), &format!("--automation-read-root={}", dir("in2"))])
.args(["--automation-write-root", &dir("out"), "--automation-write-root", &dir("out2")])
.stdin(Stdio::piped())
@@ -370,7 +462,7 @@ fn automation_roots(base: &std::path::Path) {
}
let dir = |d: &str| base.join(d).to_string_lossy().into_owned();
let fails = |args: &[&str], why: &str| {
let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap();
let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap();
let err = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success() && err.contains(why), "{args:?}: {err}");
};
@@ -382,7 +474,7 @@ fn automation_roots(base: &std::path::Path) {
"a running app enforces its own roots: start it with `vectorcraft --control <port>",
);
let mut child = Command::new(BIN)
let mut child = Command::new(crate::bin())
.args(["mcp", "--automation-read-root", &dir("in"), &format!("--automation-write-root={}", dir("out"))])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
@@ -443,7 +535,7 @@ fn automation_roots(base: &std::path::Path) {
fn mcp_protocol_over_stdio() {
use std::io::{BufRead, BufReader};
let mut child =
Command::new(BIN).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
Command::new(crate::bin()).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
let mut stdin = child.stdin.take().unwrap();
let mut lines = BufReader::new(child.stdout.take().unwrap()).lines();
let mut notes = vec![];
@@ -510,7 +602,7 @@ fn exercise_mcp_core(
assert!(r["result"]["completion"]["values"].as_array().is_some_and(|v| v.contains(&json!("svg"))), "{r}");
mcp_send(stdin, json!({"jsonrpc":"2.0","id":5,"method":"resources/list","params":{}}));
assert!(mcp_recv(lines, notes, 5)["result"]["resources"].as_array().is_some_and(|v| v.len() == 3));
assert!(mcp_recv(lines, notes, 5)["result"]["resources"].as_array().is_some_and(|v| v.len() == 4));
mcp_send(stdin, json!({"jsonrpc":"2.0","id":6,"method":"resources/templates/list","params":{}}));
assert!(mcp_recv(lines, notes, 6)["result"]["resourceTemplates"].as_array().is_some_and(|v| v.len() >= 4));
@@ -624,7 +716,7 @@ fn run_command(id: u64, command: &str, params: Value) -> Value {
#[test]
fn closed_stdout_ends_quietly() {
use std::io::Read;
let mut child = Command::new(BIN).arg("commands").stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
let mut child = Command::new(crate::bin()).arg("commands").stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
let mut first = [0u8; 16];
child.stdout.as_mut().unwrap().read_exact(&mut first).unwrap();
drop(child.stdout.take());
@@ -641,13 +733,13 @@ fn run_with_a_closed_stdout_ends_quietly_and_finishes_the_batch() {
let _ = std::fs::remove_file(&svg);
let rect = r#"{"x":1,"y":1,"width":5,"height":5}"#;
let args = ["run", "--cmd", "document.json", "--cmd", "shape.rectangle", "--params", rect, "--export", svg.to_str().unwrap()];
let mut child = Command::new(BIN).args(args).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
let mut child = Command::new(crate::bin()).args(args).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
drop(child.stdout.take());
let out = child.wait_with_output().unwrap();
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success() && err.is_empty(), "{:?}: {err}", out.status);
assert!(svg.is_file(), "the export after the closed reader still ran");
let out = Command::new(BIN).args(["run", "--cmd", "not-a-command"]).stdout(Stdio::null()).output().unwrap();
let out = Command::new(crate::bin()).args(["run", "--cmd", "not-a-command"]).stdout(Stdio::null()).output().unwrap();
assert!(!out.status.success());
}
@@ -662,7 +754,7 @@ fn config_dir(name: &str) -> std::path::PathBuf {
/// One `vectorcraft-cli run` with `steps` ((command, params)) against the settings folder `config`;
/// the result of each step.
fn run_in(config: &std::path::Path, steps: &[(&str, Value)]) -> Vec<Value> {
let mut cmd = Command::new(BIN);
let mut cmd = Command::new(crate::bin());
cmd.arg("run").env("VECTORCRAFT_CONFIG_DIR", config).env_remove("VECTORCRAFT_NO_PREFS");
for (id, params) in steps {
cmd.args(["--cmd", id, "--params", &params.to_string()]);
@@ -733,7 +825,7 @@ fn saved_pdf_presets_and_loaded_profiles_survive_a_restart() {
#[test]
fn runs_without_preferences_remember_nothing() {
let config = config_dir("noprefs");
let out = Command::new(BIN)
let out = Command::new(crate::bin())
.args(["run", "--cmd", "pdf.preset.save", "--params", r#"{"name":"Press"}"#])
.env("VECTORCRAFT_CONFIG_DIR", &config)
.env("VECTORCRAFT_NO_PREFS", "1")
+56 -5
View File
@@ -4,8 +4,6 @@ use std::process::Command;
use serde_json::Value;
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli");
/// Returns the path of `name` in `vectorcraft-cli-fileio-<pid>` in the temp folder. The first call
/// removes that folder and creates it again empty.
fn tmp(name: &str) -> String {
@@ -20,7 +18,7 @@ fn tmp(name: &str) -> String {
}
fn ok(args: &[&str]) -> String {
let out = Command::new(BIN).args(args).output().unwrap();
let out = Command::new(crate::bin()).args(args).output().unwrap();
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8(out.stdout).unwrap()
}
@@ -105,6 +103,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(crate::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"]);
@@ -147,6 +177,27 @@ fn convert_reports_import_warnings() {
assert!(w.iter().any(|w| w.as_str().unwrap().contains("nowhere-to-be-found.png")), "{out}");
}
/// A conversion sends each format only the options it reads, so its warnings name an unused
/// option only when the command line gave one: `--outline-text` for a format without it.
#[test]
fn convert_warns_about_an_unused_option_only_when_one_was_given() {
let svg = tmp("unused-option.svg");
std::fs::write(&svg, r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><rect width="20" height="10"/></svg>"#).unwrap();
let unused = |out: &Value| -> Vec<String> {
let w = out["warnings"].as_array().unwrap_or_else(|| panic!("{out}"));
w.iter().filter_map(Value::as_str).filter(|w| w.contains("was not used")).map(str::to_string).collect()
};
for ext in ["png", "jpg", "pdf", "ai", "eps", "psd", "dxf", "svg", "txt", "vectorcraft", "vctemplate"] {
let path = tmp(&format!("unused-option.{ext}"));
let out: Value = serde_json::from_str(ok(&["convert", &svg, &path]).trim()).unwrap();
assert!(unused(&out).is_empty(), "{ext}: {out}");
}
let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.svg"), "--outline-text"]).trim()).unwrap();
assert!(unused(&out).is_empty(), "{out}");
let out: Value = serde_json::from_str(ok(&["convert", &svg, &tmp("unused-option-outlined.png"), "--outline-text"]).trim()).unwrap();
assert_eq!(unused(&out), ["`outlineText` was not used: PNG files don't read it"], "{out}");
}
#[test]
fn convert_writes_legacy_ai_with_its_options() {
// Two artboards, a shown rectangle and a hidden one.
@@ -196,7 +247,7 @@ fn convert_writes_legacy_ai_with_its_options() {
assert!(r["warnings"].to_string().contains("hidden objects are left out"), "{r}");
assert!(std::fs::read(&one).unwrap().starts_with(b"%!PS-Adobe-3.0"));
// A value the engine doesn't take is an error.
let bad = Command::new(BIN).args(["convert", &src, &tmp("bad.ai"), "--ai-version", "7", "--hidden-objects", "behind"]).output().unwrap();
let bad = Command::new(crate::bin()).args(["convert", &src, &tmp("bad.ai"), "--ai-version", "7", "--hidden-objects", "behind"]).output().unwrap();
assert!(!bad.status.success());
assert!(String::from_utf8_lossy(&bad.stderr).contains("hiddenObjects"), "{}", String::from_utf8_lossy(&bad.stderr));
}
@@ -221,7 +272,7 @@ fn convert_and_run_write_ait_templates() {
assert_eq!(info(ait)["artboards"].as_array().unwrap().len(), 2, "{ait}");
}
// A template holds every artboard: one can't be picked.
let one = Command::new(BIN).args(["convert", &pdf, &tmp("one.ait"), "--artboard", "0"]).output().unwrap();
let one = Command::new(crate::bin()).args(["convert", &pdf, &tmp("one.ait"), "--artboard", "0"]).output().unwrap();
assert!(!one.status.success());
assert!(String::from_utf8_lossy(&one.stderr).contains("every artboard"), "{}", String::from_utf8_lossy(&one.stderr));
}
+9
View File
@@ -5,3 +5,12 @@
mod cli;
mod fileio;
mod mcp_e2e;
mod script;
/// Nextest relocates archived binaries; Cargo's compile-time path still names the build runner.
fn bin() -> std::path::PathBuf {
std::env::var_os("NEXTEST_BIN_EXE_vectorcraft_cli")
.or_else(|| std::env::var_os("CARGO_BIN_EXE_vectorcraft-cli"))
.map(std::path::PathBuf::from)
.unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft-cli").into())
}
+1 -3
View File
@@ -6,8 +6,6 @@ use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
use serde_json::{Value, json};
use vectorcraft_testkit::raster::Image;
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli");
struct Mcp {
child: Child,
stdin: Option<ChildStdin>,
@@ -17,7 +15,7 @@ struct Mcp {
impl Mcp {
fn spawn() -> Self {
let mut child = Command::new(BIN)
let mut child = Command::new(crate::bin())
.args(["mcp", "--headless"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
+37
View File
@@ -0,0 +1,37 @@
use std::process::Command;
use serde_json::{Value, json};
/// `run` with `script.run` after `file.new`, with `params`.
fn run_script(params: &Value) -> std::process::Output {
Command::new(crate::bin()).args(["run", "--cmd", "file.new", "--cmd", "script.run", "--params", &params.to_string()]).output().unwrap()
}
/// `run` runs a script headless: the reply holds the report, with what the script logged and the
/// documents it changed.
#[test]
fn run_gives_the_report_of_a_script() {
let source = "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); vc.log(vc.args.n * 2);";
let out = run_script(&json!({"source": source, "name": "double.js", "args": {"n": 21}}));
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let lines: Vec<Value> = String::from_utf8_lossy(&out.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(lines.len(), 2, "{lines:?}");
assert_eq!(lines[1]["command"], "script.run");
let report = &lines[1]["result"];
assert_eq!(report["ok"], true, "{report}");
assert_eq!(report["name"], "double.js");
assert_eq!(report["log"], json!([42]), "{report}");
assert_eq!(report["changed"].as_array().map(Vec::len), Some(1), "{report}");
}
/// A script that throws fails its step with the script's message, and the steps before it ran.
#[test]
fn run_fails_the_step_of_a_script_that_throws() {
let out = run_script(&json!({"source": "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); throw new Error('no margin given');"}));
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("step 1 (script.run)") && stderr.contains("no margin given"), "{stderr}");
let printed: Vec<Value> = String::from_utf8_lossy(&out.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(printed.len(), 1, "only file.new printed: {printed:?}");
assert_eq!(printed[0]["command"], "file.new");
}
+4 -2
View File
@@ -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 }
@@ -24,7 +26,7 @@ log = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
rfd = { workspace = true }
rfd = { workspace = true, features = ["file-handle-inner"] }
wasm-bindgen = "0.2"
serde_json = { workspace = true }
wasm-bindgen-futures = "0.4"
+7
View File
@@ -9,6 +9,13 @@
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="theme-color" content="#262626">
<title>VectorCraft</title>
<!-- Tab and home-screen icons: copied from assets/app-icon (one folder per size, the PNG names are equal). -->
<link data-trunk rel="copy-file" href="../../assets/app-icon/hicolor/scalable/apps/ai.storyteller.vectorcraft.svg" data-target-path="icons" />
<link data-trunk rel="copy-file" href="../../assets/app-icon/hicolor/32x32/apps/ai.storyteller.vectorcraft.png" data-target-path="icons/32" />
<link data-trunk rel="copy-file" href="../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.vectorcraft.png" data-target-path="icons/256" />
<link rel="icon" type="image/svg+xml" href="icons/ai.storyteller.vectorcraft.svg">
<link rel="icon" type="image/png" sizes="32x32" href="icons/32/ai.storyteller.vectorcraft.png">
<link rel="apple-touch-icon" href="icons/256/ai.storyteller.vectorcraft.png">
<link data-trunk rel="rust" data-bin="vectorcraft-web" data-wasm-opt="z" data-weak-refs />
<style>
/* iPad: no page scroll, bounce, pinch zoom, text selection or callout; the app takes the gestures. */
+84 -60
View File
@@ -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(&params)))
.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(&params)}))
})
.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(&params))).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(())
}
+40
View File
@@ -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);
}
}
+49 -4
View File
@@ -8,23 +8,40 @@
//! Pages that aren't secure (plain `http://` other than localhost) and older browsers have none:
//! heartbeats alone decide there.
#[cfg(target_arch = "wasm32")]
use std::cell::RefCell;
#[cfg(target_arch = "wasm32")]
use std::collections::{BTreeMap, BTreeSet};
#[cfg(target_arch = "wasm32")]
use std::sync::{Arc, Mutex};
#[cfg(target_arch = "wasm32")]
use js_sys::{Function, Promise, Reflect};
#[cfg(target_arch = "wasm32")]
use vectorcraft_engine::cmd::recovery::Hold;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsCast as _;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsValue;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::closure::Closure;
/// How often the snapshot of the locks held is refreshed (ms).
#[cfg(target_arch = "wasm32")]
const REFRESH_MS: i32 = 10_000;
/// How old a snapshot may be and still be trusted (ms). A lock asked for after the snapshot was
/// taken comes with a heartbeat, which stays fresh for at least three minutes, so anything under
/// that is safe; an older snapshot counts every area as held.
const FRESH_MS: f64 = 60_000.0;
/// Whether a snapshot asked for at `asked` can still be trusted at `now`, both in ms on
/// [`vectorcraft_ui_egui::now_ms`]'s clock: it is at most [`FRESH_MS`] old, and not stamped later
/// than `now`.
fn trusted(asked: f64, now: f64) -> bool {
(0.0..=FRESH_MS).contains(&(now - asked))
}
#[cfg(target_arch = "wasm32")]
thread_local! {
/// What releases each lock this tab holds, by name: it resolves the promise the lock is held
/// by (wasm runs on one thread).
@@ -32,26 +49,31 @@ thread_local! {
}
/// The locks of the page, named `<prefix><area>`.
#[cfg(target_arch = "wasm32")]
#[derive(Clone)]
pub struct WebLocks {
prefix: &'static str,
/// The areas whose locks were held at the last snapshot, and when it was asked for (ms since
/// the epoch). `navigator.locks.query()` is asynchronous, so the snapshot is refreshed every
/// The areas whose locks were held at the last snapshot, and when it was asked for (ms on
/// [`vectorcraft_ui_egui::now_ms`]'s monotonic clock, which a change to the system clock does
/// not move). `navigator.locks.query()` is asynchronous, so the snapshot is refreshed every
/// [`REFRESH_MS`] and read from here.
seen: Arc<Mutex<(f64, BTreeSet<String>)>>,
}
/// `navigator.locks`, if the browser has it here.
#[cfg(target_arch = "wasm32")]
fn manager() -> Option<JsValue> {
let locks = Reflect::get(&web_sys::window()?.navigator(), &"locks".into()).ok()?;
locks.is_object().then_some(locks)
}
/// Method `name` of `obj`.
#[cfg(target_arch = "wasm32")]
fn method(obj: &JsValue, name: &str) -> Option<Function> {
Reflect::get(obj, &name.into()).ok()?.dyn_into().ok()
}
#[cfg(target_arch = "wasm32")]
impl WebLocks {
/// The page's Web Locks with a first snapshot of them, kept fresh from then on; `None` when
/// the browser has none or won't say which are held (heartbeats alone decide then).
@@ -75,7 +97,7 @@ impl WebLocks {
/// Take a new snapshot of the locks held.
async fn refresh(&self) -> Option<()> {
let m = manager()?;
let asked = js_sys::Date::now();
let asked = vectorcraft_ui_egui::now_ms();
let query: Promise = method(&m, "query")?.call0(&m).ok()?.dyn_into().ok()?;
let snapshot = wasm_bindgen_futures::JsFuture::from(query).await.ok()?;
let held = js_sys::Array::from(&Reflect::get(&snapshot, &"held".into()).ok()?);
@@ -91,7 +113,7 @@ impl WebLocks {
/// Does a tab hold `area`'s lock? Yes when the last snapshot is too old to tell.
pub fn held(&self, area: &str) -> bool {
let seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
js_sys::Date::now() - seen.0 > FRESH_MS || seen.1.contains(area)
!trusted(seen.0, vectorcraft_ui_egui::now_ms()) || seen.1.contains(area)
}
/// Hold `area`'s lock until the returned hold is dropped (or the page goes).
@@ -110,8 +132,10 @@ impl WebLocks {
}
/// A lock this tab holds (by name), released when dropped.
#[cfg(target_arch = "wasm32")]
struct LockHold(String);
#[cfg(target_arch = "wasm32")]
impl Drop for LockHold {
fn drop(&mut self) {
if let Some(resolve) = RELEASE.with(|r| r.borrow_mut().remove(&self.0)) {
@@ -120,3 +144,24 @@ impl Drop for LockHold {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_snapshot_is_trusted_for_a_minute() {
assert!(trusted(1_000.0, 1_000.0));
assert!(trusted(1_000.0, 1_000.0 + FRESH_MS));
assert!(!trusted(1_000.0, 1_001.0 + FRESH_MS));
// Before the first snapshot every area counts as held.
assert!(!trusted(f64::NEG_INFINITY, 0.0));
}
#[test]
fn a_snapshot_stamped_later_than_now_is_not_trusted() {
// A clock that went back reads an old snapshot as taken in the future.
assert!(!trusted(5_000_000.0, 1_000.0));
assert!(!trusted(1_001.0, 1_000.0));
}
}
+2 -2
View File
@@ -7,7 +7,7 @@
//! Differences from the desktop app:
//! - no TCP control server (browsers can't listen on sockets);
//! - File → Open uses the browser file picker; bytes arrive asynchronously through
//! `Services::inbox`;
//! `Services::picked_inbox`;
//! - Save / Export trigger a browser download;
//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox;
//! - pen and finger input is read from Pointer Events by `pencil` (Apple Pencil pressure and
@@ -25,7 +25,7 @@ mod api;
mod fonts;
#[cfg(any(target_arch = "wasm32", test))]
mod keys;
#[cfg(target_arch = "wasm32")]
#[cfg(any(target_arch = "wasm32", test))]
mod locks;
#[cfg(any(target_arch = "wasm32", test))]
mod pencil;
+2 -2
View File
@@ -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>) {
+60 -16
View File
@@ -9,12 +9,15 @@ use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::clipboard::{FILE_HEAD, Flavour, PASTE_ORDER, file_flavour, is_address};
use vectorcraft_engine::cmd::fileio;
use vectorcraft_engine::cmd::recovery::{self, Hold, RecoveryStore};
use vectorcraft_engine::cmd::scripts::RUN_EXTS;
use vectorcraft_engine::script::MAX_SOURCE_BYTES;
use vectorcraft_ui_egui::dialogs::script_run::ScriptInbox;
use vectorcraft_ui_egui::graphics::GraphicsLoss;
use vectorcraft_ui_egui::i18n;
use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox};
use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
use vectorcraft_ui_egui::stylus::StylusFeed;
use vectorcraft_ui_egui::{Services, VectorcraftApp};
use vectorcraft_ui_egui::{PickedInbox, Services, VectorcraftApp};
use wasm_bindgen::JsCast as _;
use crate::locks::WebLocks;
@@ -22,6 +25,18 @@ use crate::pencil::SharedPointers;
pub(crate) type Inbox = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
/// The files waiting to open, by where they came from (`Services::inbox`, `picked_inbox` and
/// `page_inbox`).
#[derive(Clone, Default)]
struct OpenInboxes {
/// Dropped on the page.
dropped: Inbox,
/// The open picker's answers.
picked: PickedInbox,
/// Handed over by the page's script (`window.vectorcraft.openFile`).
page: Inbox,
}
/// Where the pointer was over the canvas during the last file drag (CSS px from its top-left) and
/// whether Shift was held: where dropped files land.
type DragPos = Rc<Cell<Option<(f32, f32, bool)>>>;
@@ -45,8 +60,9 @@ const MAX_RESTARTS: u32 = 3;
#[derive(Clone)]
struct Host {
runner: eframe::WebRunner,
inbox: Inbox,
inbox: OpenInboxes,
place_inbox: PlaceInbox,
script_inbox: ScriptInbox,
drag: DragPos,
pasted: Rc<RefCell<Pasted>>,
/// Pen and finger input read from the page's Pointer Events (`crate::pencil`).
@@ -73,8 +89,9 @@ pub fn start() {
crate::fonts::load_startup_fonts().await;
let host = Host {
runner: eframe::WebRunner::new(),
inbox: Arc::default(),
inbox: OpenInboxes::default(),
place_inbox: Arc::default(),
script_inbox: Arc::default(),
drag: DragPos::default(),
pasted: Rc::default(),
pointers: SharedPointers::default(),
@@ -120,19 +137,20 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
}
host.pasted.borrow_mut().ctx = Some(ctx.clone());
let stylus = host.pointers.borrow().stylus();
let services = services(host.inbox.clone(), host.place_inbox.clone(), ctx.clone(), host.locks.clone(), stylus);
let services =
services(host.inbox.clone(), host.place_inbox.clone(), host.script_inbox.clone(), ctx.clone(), host.locks.clone(), stylus);
let app = match taken.borrow_mut().take() {
Some(mut app) => {
// The old services asked the old context for frames.
app.services = services;
app.status("The graphics were lost and have been restarted");
crate::api::connect(None, host.inbox.clone(), ctx.clone());
crate::api::connect(None, host.inbox.page.clone(), ctx.clone());
app
}
None => {
// `window.vectorcraft`: the page's control channel (crate::api).
let (control_tx, control_rx) = std::sync::mpsc::channel();
crate::api::connect(Some(control_tx), host.inbox.clone(), ctx.clone());
crate::api::connect(Some(control_tx), host.inbox.page.clone(), ctx.clone());
if let Err(e) = crate::api::install() {
log::error!("vectorcraft-web: couldn't install window.vectorcraft: {}", js_err(e));
}
@@ -370,7 +388,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 +395,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);
}
@@ -402,7 +421,7 @@ impl eframe::App for WebShell {
for f in dropped {
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
let target = app.drop_target(&name, pos, shift);
let (inbox, place_inbox, repaint) = (self.host.inbox.clone(), self.host.place_inbox.clone(), ctx.clone());
let (inbox, place_inbox, repaint) = (self.host.inbox.dropped.clone(), self.host.place_inbox.clone(), ctx.clone());
wasm_bindgen_futures::spawn_local(async move {
match f.bytes_async().await {
Ok(bytes) => {
@@ -421,16 +440,38 @@ impl eframe::App for WebShell {
}
app.ui(ui);
}
crate::api::poll_replies();
}
}
fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context, locks: Option<WebLocks>, stylus: StylusFeed) -> Services {
let open_inbox = inbox.clone();
fn services(
inbox: OpenInboxes,
place_inbox: PlaceInbox,
script_inbox: ScriptInbox,
ctx: egui::Context,
locks: Option<WebLocks>,
stylus: StylusFeed,
) -> Services {
let open_inbox = inbox.picked.clone();
let picked = place_inbox.clone();
let place_ctx = ctx.clone();
let screen_color = eye_dropper(ctx.clone());
let (script_picked, script_ctx) = (script_inbox.clone(), ctx.clone());
Services {
// File › Scripts › Other Script…: the picked file goes to the warning before it runs.
script_async: Some(Box::new(move || {
let inbox = script_picked.clone();
let ctx = script_ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
let filter = vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", "Scripts");
let Some(file) = rfd::AsyncFileDialog::new().add_filter(filter, RUN_EXTS).pick_file().await else {
return;
};
let bytes = if file.inner().size() > MAX_SOURCE_BYTES as f64 { None } else { Some(file.read().await) };
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes));
ctx.request_repaint();
});
})),
script_inbox: Some(script_inbox),
// File → Place…: the picked files go to the Place dialog.
place_async: Some(Box::new(move || {
let inbox = picked.clone();
@@ -459,11 +500,12 @@ fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context, locks: Op
let dialog = fileio::open_filters().fold(rfd::AsyncFileDialog::new(), |d, (name, exts)| {
d.add_filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts)
});
let Some(file) = dialog.pick_file().await else {
return;
// A canceled pick answers `None`.
let answer = match dialog.pick_file().await {
Some(file) => Some((file.file_name(), file.read().await)),
None => None,
};
let bytes = file.read().await;
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes));
inbox.lock().unwrap_or_else(|e| e.into_inner()).push(answer);
ctx.request_repaint();
});
})),
@@ -471,7 +513,9 @@ fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context, locks: Op
screen_color,
// A download that couldn't be started fails the save or export it is for (#1693).
download: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes).inspect_err(|e| log::error!("download of {name} failed: {e}")))),
inbox: Some(inbox),
inbox: Some(inbox.dropped),
picked_inbox: Some(inbox.picked),
page_inbox: Some(inbox.page),
recovery_store: Some(Arc::new(BrowserStore { locks })),
// File → Print: the browser's print dialog.
print: Some(Box::new(BrowserPrint)),
+39 -6
View File
@@ -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)
@@ -44,6 +44,9 @@ clipboard-win = { workspace = true }
# GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over
# Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter.
winsafe = { version = "0.0.29", default-features = false, features = ["user"], optional = true }
# Waits for Direct3D 12's adapter list before the window starts (src/gpu.rs, #4150). MIT OR
# Apache-2.0, already in the build through eframe.
pollster = "1"
# DirectWrite's system font collection and GDI's font list (src/system_fonts.rs): fonts that font
# services such as Adobe Fonts load in place (#579, #1258). MIT OR Apache-2.0, already in the build
@@ -51,14 +54,23 @@ winsafe = { version = "0.0.29", default-features = false, features = ["user"], o
# Win32_UI_WindowsAndMessaging has `MSG` and `WM_POINTERDOWN`, which src/windows_stylus.rs uses to
# read a pen's barrel button from its pointer messages. Win32_UI_Input_Pointer has
# `GetPointerPenInfo`, which it uses to read the pen's pressure and which end of the pen is down.
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
# 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. Win32_System_Registry has `RegGetValueW`,
# which src/host_services.rs uses to read the path PhotoCraft registers under App Paths.
# Win32_Devices_Display has `QueryDisplayConfig`, Win32_UI_ColorSystem the display's ICC profile and
# Win32_System_LibraryLoader `GetProcAddress`, which src/display_profile.rs uses to read the
# display's color profile for the canvas.
windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Foundation", "Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_ColorSystem", "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 }
[target.'cfg(target_os = "macos")'.dependencies]
# The macOS menu bar (src/mac_menu.rs): Tauri's menu crate, AppKit menus behind a safe API (no GTK
# with default features off). Pinned exactly: review the diff before bumping.
muda = { version = "=0.21.2", default-features = false }
objc2 = "0.6"
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "NSApplication", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
# Files opened from Finder and the Dock (src/open_documents.rs), pasted bitmaps (src/clipboard.rs) and the control channel's App Nap activity (src/control_server.rs); both already come with winit, muda and rfd.
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] }
block2 = "0.6"
@@ -70,6 +82,10 @@ raw-window-handle = "0.6"
# objc2-foundation.
objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFArray", "CFString", "CFURL"] }
objc2-core-text = { version = "0.3", default-features = false, features = ["std", "CTFontManager"] }
# The windows' Metal layers and the sRGB color space they are tagged with (src/mac_color_space.rs).
# Zlib OR Apache-2.0 OR MIT, already in the build through wgpu with these features.
objc2-quartz-core = { version = "0.3", default-features = false, features = ["std", "objc2-core-foundation", "objc2-core-graphics", "CALayer", "CAMetalLayer"] }
objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGColorSpace"] }
# Waits for the answer of a file dialog shown as a sheet (src/main.rs, #867). MIT OR Apache-2.0,
# already in the build through eframe.
pollster = "1"
@@ -79,29 +95,46 @@ pollster = "1"
winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita-notitle"] }
# A drawing tablet's pen pressure under X11 and XWayland (src/tablet.rs): XInput2 raw events on a
# second X connection, x11rb's pure-Rust `RustConnection`. MIT OR Apache-2.0, already in the build
# through winit with the `xinput` feature.
x11rb = { version = "0.13", default-features = false, features = ["xinput"] }
# through winit with the `xinput` feature. XKB reads Caps Lock's locked modifier state (src/caps_lock.rs).
# RandR reads a display's `_ICC_PROFILE` for the canvas (src/display_profile.rs).
x11rb = { version = "0.13", default-features = false, features = ["randr", "xinput", "xkb"] }
# Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback, src/compositor_gpu.rs),
# so Automatic draws on that one. Both are already in the build through winit.
# so Automatic draws on that one, and copies and pastes text, SVG and PNG through the compositor's
# core data-device protocol on the window's connection (src/clipboard.rs), where arboard has neither
# data-control (GNOME) nor X11 (a Flatpak on a Wayland session). Both are already in the build
# through winit.
wayland-client = "0.31"
wayland-protocols = { version = "0.32", features = ["client", "unstable"] }
# The save dialog's parent window on Wayland (src/portal_save.rs): an xdg-foreign handle (in
# wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build
# through winit and rfd.
wayland-backend = { version = "0.3", features = ["client_system"] }
# The Wayland clipboard's pipes (src/clipboard.rs): `poll` and the nonblocking flag give up a read
# or send when the other app moves no data for a while. Apache-2.0 WITH LLVM-exception OR
# Apache-2.0 OR MIT, already in the build through the workspace.
rustix = { workspace = true, features = ["std", "event", "fs"] }
# The save dialog's file type (src/portal_save.rs, #2679): the desktop portal over D-Bus, on the
# systems where rfd shows the portal's dialog. MIT, already in the build through accesskit. Pinned
# exactly: review the diff before bumping.
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))'.dependencies]
zbus = "=5.19.0"
# Waits for a portal answer (the save dialog's and the screen color sampler's) and for the portal
# leaving the bus at the same time (src/portal_request.rs). Apache-2.0 OR MIT, already in the build
# through zbus.
futures-lite = "2"
# Tells whether arboard reads through the compositor's data-control protocol or through X11, the
# same check arboard makes (src/clipboard.rs). MIT OR Apache-2.0, already in the build through
# arboard.
wl-clipboard-rs = "0.9"
[build-dependencies]
# Icon + VERSIONINFO for vectorcraft.exe; build.rs only uses it when targeting Windows.
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.
+113 -11
View File
@@ -1,11 +1,15 @@
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
use super::gpu;
use super::prefs::save_prefs;
use super::prefs::{save_prefs, save_prefs_soon};
#[cfg(not(target_os = "macos"))]
use super::single_instance;
#[cfg(all(windows, not(target_vendor = "win7")))]
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;
use vectorcraft_ui_egui::hang_beacon::{self, BEACON, FrameTime, Stage};
/// The parts of [`App::raw_input_hook`] that every window needs, for the OS windows of floating
/// panels: a click or Escape that closes the macOS menu bar's open menu, and the pen barrel
@@ -31,12 +35,16 @@ impl eframe::App for App {
// control channel asks for, and the frames carrying input it injected, to the automation roots
// (`VectorcraftApp::with_automation_roots`), which are in force elsewhere in the process.
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
let _timed = BEACON.enter_timed(Stage::Logic);
file_access::unconfined(|| self.logic_frame(ctx, frame));
self.app.finish_ime_logic(ctx);
BEACON.enter(Stage::Idle);
}
/// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the
/// app's raw-input hook while the keyboard user is unconfined.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
let _timed = BEACON.enter_timed(Stage::Input);
self.frame_start = Some(std::time::Instant::now());
// winit gives the window its caption back when it changes the window's flags (maximize,
// restore, …): take it off again before the frame is laid out (#1758).
if let Some(window_frame) = self.window_frame.as_mut() {
@@ -49,40 +57,100 @@ 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.
#[cfg(target_os = "macos")]
self.app.release_lost_buttons(ctx, raw, objc2_app_kit::NSEvent::pressedMouseButtons() != 0);
BEACON.enter(Stage::Idle);
}
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
let _timed = BEACON.enter_timed(Stage::Interface);
#[cfg(target_os = "macos")]
{
let bar = vectorcraft_ui_egui::chrome::APP_BAR_HEIGHT;
let inset = mac_window::center_buttons(frame, ui.ctx().zoom_factor(), bar);
self.app.titlebar_inset = inset.unwrap_or(mac_window::DEFAULT_INSET);
}
// macOS converts the frame from sRGB to the display's profile (#2249).
#[cfg(all(target_os = "macos", feature = "wgpu"))]
super::mac_color_space::tag(ui);
if let Some(on) = self.host_caps_lock.read_transition() {
self.app.set_caps_lock(on);
}
file_access::unconfined(|| self.app.ui(ui));
// Preferences are written when confirmed, not only at exit: a session ended any other way
// (the system shutting down, the process ended or crashing) used to lose them (#1747).
if self.app.take_prefs_changed() {
file_access::unconfined(|| save_prefs(&self.app));
} else {
// The workspace, panels and other UI settings change without the dialog (#4625).
file_access::unconfined(|| save_prefs_soon(&self.app));
}
// Not while a file dialog's sheet has the keyboard: its name field's composition would go.
#[cfg(target_os = "macos")]
if !self.app.file_dialog_open() && self.app.take_ime_discard() {
discard_marked_text();
}
self.end_frame(ui.ctx(), frame);
}
fn on_exit(&mut self) {
// The window is closing: saving and teardown are not timed for the hang report, and a report
// of a stall the interface came back from is removed.
let log_dir = super::prefs::log_dir().filter(|_| super::prefs::prefs_enabled());
super::hang_watch::closing(log_dir.as_deref(), &super::hang_watch::CLOSING, &BEACON);
file_access::unconfined(|| save_prefs(&self.app));
// A ready update installs once the process has exited. The macOS exit below skips
// dropping the app, so the helper is started here.
self.app.start_pending_update();
#[cfg(target_os = "macos")]
super::mac_cursor::release();
// Dropping the app can wait for the clipboard handles to let go: the windows leave the
// screen first (`quit_windows`).
#[cfg(not(any(target_os = "macos", windows)))]
super::quit_windows::before_teardown(self.winit_window.as_deref());
end_before_teardown(self.frames);
}
}
impl App {
/// The frame's times for the hang report, and its last stage ([`hang_beacon::after_frame`]): a
/// focused, shown window whose windows had input waits for the renderer and the next frame,
/// which the input asks for at once; any other frame leaves the interface thread idle
/// (`hang_watch`).
fn end_frame(&mut self, ctx: &egui::Context, frame: &eframe::Frame) {
// A pass egui discards and runs again is not the frame's end: the pass after it is.
if ctx.will_discard() {
return;
}
if let Some(start) = self.frame_start.take() {
let work_ms = start.elapsed().as_secs_f32() * 1000.0;
let previous_total_ms = frame.info().cpu_usage.map(|s| s * 1000.0);
BEACON.frame(FrameTime { work_ms, previous_total_ms }, self.app.session.documents().len());
}
// Hide on macOS hides the window at once, before the window reports losing focus.
let main_shown = ctx.input(|i| i.focused && i.viewport().minimized != Some(true))
&& self.winit_window.as_ref().is_none_or(|w| w.is_visible() != Some(false));
// A floating panel or document window with the focus counts as well, with the commands it
// was sent after its pass, and those its pass sent (`hang_beacon::watch_input`).
let shown = ctx.input(|i| hang_beacon::shown_window(main_shown, &i.raw.viewports));
let handed_off = BEACON.take_handed_off();
let input = BEACON.take_input();
let stage = match shown {
Some(id) => ctx.viewport_for(id, |vp| hang_beacon::after_frame(input && !handed_off.contains(&id), true, &vp.commands)),
None => hang_beacon::after_frame(input, false, &[]),
};
BEACON.enter(stage);
}
fn logic_frame(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
if self.winit_window.as_ref().is_some_and(|w| !w.has_focus() || w.is_visible() == Some(false) || w.is_minimized() == Some(true)) {
super::mac_cursor::release();
}
self.frames = ctx.cumulative_frame_nr();
if let Some(why) = self.graphics_loss.take() {
// eframe can't give a window a new device: the user saves and starts again.
@@ -99,16 +167,38 @@ impl App {
vectorcraft_ui_egui::background::wait_all(&mut self.app);
return;
}
// Files from the Finder and the Dock wait while a file dialog is open: what asked for it runs
// again on its document when it answers.
#[cfg(target_os = "macos")]
if !self.app.file_dialog_open() {
// 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. 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_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));
}
if let Some(w) = &self.winit_window {
self.display_profile.tick(w, now, self.app.session.prefs.monitor_profile_display, &self.app.display_profile, ctx);
}
self.app.tick(ctx);
if self.pending_maximize {
if let Some(w) = &self.winit_window {
@@ -128,28 +218,40 @@ 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);
}
}
/// Show the window when files are opened from the Finder or the Dock: a minimized window comes back
/// out of the Dock and the app takes focus, as a document-based Mac app does (#3769).
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
/// Show the window when files are opened from the Finder or the Dock, or handed over by a later
/// launch (#4892): a minimized window comes back and the app takes focus, as a document-based app
/// does (#3769).
pub(crate) fn bring_window_forward(ctx: &egui::Context) {
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
}
/// Open files handed to the app (command line, macOS Finder and Dock) as documents. A file that
/// 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>) {
for f in files {
+216
View File
@@ -0,0 +1,216 @@
//! Read the host's Caps Lock state, which gives the drawing tools the precise crosshair while it is on.
/// Only host transitions replace a value set by a script through `view.capsLock`.
#[derive(Default)]
pub struct HostCapsLock {
previous: Option<bool>,
#[cfg(target_os = "linux")]
x11: Option<X11CapsLock>,
}
#[cfg(target_os = "linux")]
struct X11CapsLock {
connection: x11rb::rust_connection::RustConnection,
locked: bool,
initial_sequence: u16,
}
impl HostCapsLock {
pub fn new(window: Option<&winit::window::Window>) -> Self {
#[cfg(target_os = "linux")]
let x11 = window.and_then(x11_connection);
#[cfg(not(target_os = "linux"))]
let _ = window;
Self {
previous: None,
#[cfg(target_os = "linux")]
x11,
}
}
pub fn read_transition(&mut self) -> Option<bool> {
#[cfg(target_os = "linux")]
let current = match self.x11.as_mut() {
Some(state) => match state.poll() {
Some(locked) => Some(locked),
None => {
self.x11 = None;
None
}
},
None => {
// Native Wayland does not expose the seat's XKB lock bit through winit or egui.
None
}
};
#[cfg(any(target_os = "macos", windows))]
let current = Some(read());
// This platform has no lock-state reader.
#[cfg(not(any(target_os = "macos", windows, target_os = "linux")))]
let current = None;
self.transition(current)
}
fn transition(&mut self, reading: Option<bool>) -> Option<bool> {
reading.and_then(|current| self.observe(current))
}
fn observe(&mut self, current: bool) -> Option<bool> {
if self.previous.replace(current) == Some(current) { None } else { Some(current) }
}
}
#[cfg(target_os = "linux")]
fn x11_connection(window: &winit::window::Window) -> Option<X11CapsLock> {
use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle};
use x11rb::protocol::xkb;
if !matches!(window.window_handle().ok()?.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)) {
return None;
}
let (connection, _) = x11rb::connect(None).ok()?;
let supported = x11rb::protocol::xkb::use_extension(&connection, 1, 0).ok()?.reply().ok()?.supported;
if !supported {
return None;
}
// Subscribe before the initial read so changes during setup remain queued.
xkb::select_events(
&connection,
xkb::ID::USE_CORE_KBD.into(),
xkb::EventType::default(),
xkb::EventType::default(),
xkb::MapPart::default(),
xkb::MapPart::default(),
&xkb::SelectEventsAux {
state_notify: Some(xkb::SelectEventsAuxStateNotify {
affect_state: xkb::StatePart::MODIFIER_LOCK,
state_details: xkb::StatePart::MODIFIER_LOCK,
}),
..Default::default()
},
)
.ok()?
.check()
.ok()?;
let (locked, initial_sequence) = read_x11(&connection)?;
Some(X11CapsLock { connection, locked, initial_sequence })
}
#[cfg(target_os = "linux")]
impl X11CapsLock {
fn poll(&mut self) -> Option<bool> {
use x11rb::connection::Connection as _;
use x11rb::protocol::Event;
while let Some(event) = self.connection.poll_for_event().ok()? {
if let Event::XkbStateNotify(state) = event
// Events queued before the initial GetState reply must not replace that newer snapshot.
&& state.sequence.wrapping_sub(self.initial_sequence) < 0x8000
{
self.locked = lock_modifier_is_set(state.locked_mods);
}
}
Some(self.locked)
}
}
#[cfg(target_os = "linux")]
fn read_x11(connection: &x11rb::rust_connection::RustConnection) -> Option<(bool, u16)> {
use x11rb::protocol::xkb;
let state = xkb::get_state(connection, xkb::ID::USE_CORE_KBD.into()).ok()?.reply().ok()?;
Some((lock_modifier_is_set(state.locked_mods), state.sequence))
}
#[cfg(target_os = "linux")]
fn lock_modifier_is_set(modifiers: x11rb::protocol::xproto::ModMask) -> bool {
use x11rb::protocol::xproto::ModMask;
u16::from(modifiers) & u16::from(ModMask::LOCK) != 0
}
#[cfg(target_os = "macos")]
const MAC_CAPS_LOCK: usize = 1 << 16;
#[cfg(target_os = "macos")]
fn mac_flags_have_caps_lock(flags: usize) -> bool {
flags & MAC_CAPS_LOCK != 0
}
#[cfg(target_os = "macos")]
pub fn read() -> bool {
mac_flags_have_caps_lock(objc2_app_kit::NSEvent::modifierFlags_class().bits())
}
#[cfg(windows)]
fn windows_state_has_caps_lock(state: i16) -> bool {
state & 1 != 0
}
#[cfg(windows)]
#[allow(unsafe_code)]
pub fn read() -> bool {
// GetKeyState reports the toggle bit for the calling UI thread's keyboard state.
use windows::Win32::UI::Input::KeyboardAndMouse::{GetKeyState, VK_CAPITAL};
// SAFETY: `GetKeyState` takes a virtual-key code by value and reads no caller memory.
windows_state_has_caps_lock(unsafe { GetKeyState(i32::from(VK_CAPITAL.0)) })
}
// Querying XWayland for a native Wayland window would read a different keyboard.
#[cfg(test)]
mod tests {
#[test]
fn no_host_reader_preserves_scripted_value_and_next_reading_transitions() {
let mut host = super::HostCapsLock::default();
let mut session = vectorcraft_engine::Session::new();
session.execute("view.capsLock", &serde_json::json!({"on": true})).unwrap();
if let Some(on) = host.transition(None) {
session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap();
}
assert!(session.caps_lock);
assert_eq!(host.transition(Some(false)), Some(false));
}
#[cfg(target_os = "linux")]
#[test]
fn no_x11_reader_has_no_transition() {
assert_eq!(super::HostCapsLock::default().read_transition(), None);
}
#[test]
fn scripted_value_survives_unchanged_host_until_transition() {
let mut host = super::HostCapsLock::default();
let mut session = vectorcraft_engine::Session::new();
if let Some(on) = host.observe(false) {
session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap();
}
session.execute("view.capsLock", &serde_json::json!({"on": true})).unwrap();
if let Some(on) = host.observe(false) {
session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap();
}
assert!(session.caps_lock);
session.execute("view.capsLock", &serde_json::json!({"on": false})).unwrap();
if let Some(on) = host.observe(true) {
session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap();
}
assert!(session.caps_lock);
if let Some(on) = host.observe(false) {
session.execute("view.capsLock", &serde_json::json!({"on": on})).unwrap();
}
assert!(!session.caps_lock);
}
#[cfg(target_os = "macos")]
#[test]
fn mac_modifier_flags_map_caps_lock() {
assert!(!super::mac_flags_have_caps_lock(0));
assert!(!super::mac_flags_have_caps_lock(1 << 17));
assert!(super::mac_flags_have_caps_lock(1 << 16));
assert!(super::mac_flags_have_caps_lock((1 << 16) | (1 << 17)));
}
#[cfg(windows)]
#[test]
fn windows_key_state_maps_toggle_bit() {
assert!(!super::windows_state_has_caps_lock(0));
assert!(!super::windows_state_has_caps_lock(i16::MIN));
assert!(super::windows_state_has_caps_lock(1));
}
}
File diff suppressed because it is too large. Load diff
+8 -10
View File
@@ -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);
+28
View File
@@ -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.
+10 -4
View File
@@ -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();
+629
View File
@@ -0,0 +1,629 @@
//! Reads the ICC profile of the display that shows most of the main window, for Preferences ›
//! Performance › Use Monitor Profile for Canvas, and hands it to [`DisplayProfile::report`].
//!
//! - Windows: the display's default profile for its standard color mode. A display with Advanced
//! Color on (HDR or Automatic Color Management) is converted by Windows, and nothing is read.
//! - X11: colord's profile for the RandR output, then the output's `_ICC_PROFILE` property, then
//! the screen's `_ICC_PROFILE` when only one output is active.
//! - Wayland, XWayland included: the compositor gives applications no display profile, and the
//! canvas stays sRGB.
//! - macOS: the window's layer is tagged sRGB and macOS converts it (`mac_color_space`).
//!
//! While the preference is on, a background thread reads the display every [`EVERY`] seconds,
//! and at once when the window moves to another display.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use vectorcraft_ui_egui::display_profile::{DisplayProfile, Found, Reading};
/// Seconds between two readings of the same display.
const EVERY: f64 = 10.0;
/// Seconds between two checks of which display shows the window.
const LOOK_EVERY: f64 = 1.0;
/// Starts the readings from the main window's frames.
#[derive(Default)]
pub(crate) struct Reader {
/// When the last reading started, and the display it was for.
last: Option<(f64, Option<String>)>,
/// When the window's display was last looked up.
looked: Option<f64>,
/// A reading is running.
busy: Arc<AtomicBool>,
}
/// Clears [`Reader::busy`] when the reading thread ends, also by a panic.
struct Done(Arc<AtomicBool>);
impl Drop for Done {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
impl Reader {
/// Starts a reading when one is due and none is running. `now` is the frame's time in seconds.
pub(crate) fn tick(&mut self, window: &winit::window::Window, now: f64, enabled: bool, profile: &DisplayProfile, ctx: &egui::Context) {
if !enabled || self.busy.load(Ordering::Acquire) || self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) {
return;
}
self.looked = Some(now);
let display = window.current_monitor().and_then(|m| m.name());
if !due(self.last.as_ref(), now, display.as_deref()) {
return;
}
self.last = Some((now, display.clone()));
profile.pending();
self.busy.store(true, Ordering::Release);
let done = Done(self.busy.clone());
let (profile, ctx) = (profile.clone(), ctx.clone());
let spawned = std::thread::Builder::new().name("display profile".into()).spawn(move || {
let _done = done;
if profile.report(read(display)) {
ctx.request_repaint();
}
});
if let Err(e) = spawned {
log::warn!("couldn't start reading the display profile: {e}");
}
}
}
/// Whether a reading of `display` is due at `now`, after the last one (`last`): none yet, another
/// display, [`EVERY`] seconds later, or a clock that went back.
fn due(last: Option<&(f64, Option<String>)>, now: f64, display: Option<&str>) -> bool {
last.is_none_or(|(at, shown)| shown.as_deref() != display || !(*at..at + EVERY).contains(&now))
}
#[cfg(windows)]
fn read(display: Option<String>) -> Reading {
let found = win::read(display.as_deref());
Reading { display, found }
}
#[cfg(target_os = "linux")]
fn read(display: Option<String>) -> Reading {
let found = if wayland_session(|k| std::env::var_os(k)) {
Found::NoProfile("a Wayland session doesn't give applications the display's profile".into())
} else {
x11::read(display.as_deref())
};
Reading { display, found }
}
#[cfg(all(target_os = "macos", feature = "wgpu"))]
fn read(display: Option<String>) -> Reading {
Reading { display, found: Found::System("macOS converts the window to the display's profile".into()) }
}
#[cfg(not(any(windows, target_os = "linux", all(target_os = "macos", feature = "wgpu"))))]
fn read(display: Option<String>) -> Reading {
Reading { display, found: Found::NoProfile("this build doesn't read display profiles on this system".into()) }
}
/// Whether the app runs in a Wayland session, read from the environment `var` gives. XWayland
/// windows count: the variables stay set for them.
#[cfg(any(target_os = "linux", test))]
fn wayland_session(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> bool {
["WAYLAND_DISPLAY", "WAYLAND_SOCKET"].iter().any(|k| var(k).is_some_and(|v| !v.is_empty()))
}
/// The X11 reading from colord's answer `colord` (the profile file it names, read) and the X11
/// properties `properties`: colord's profile when its file can be read, otherwise the
/// properties' profile. When neither has one, the reason colord gave is kept.
#[cfg(any(target_os = "linux", test))]
fn x11_choice(colord: Option<Result<Option<Found>, String>>, properties: impl FnOnce() -> Result<Option<Found>, String>) -> Found {
let colord_reason = match colord {
Some(Ok(Some(found @ Found::Profile { .. }))) => return found,
Some(Ok(Some(Found::NoProfile(e) | Found::System(e)))) | Some(Err(e)) => Some(e),
Some(Ok(None)) | None => None,
};
match properties() {
Ok(Some(found)) => found,
Ok(None) => Found::NoProfile(match colord_reason {
Some(e) => format!("no profile is set for this display ({e})"),
None => "no profile is set for this display".into(),
}),
Err(e) => Found::NoProfile(e),
}
}
/// `found` when it is not a profile or the profile can be used, otherwise why it can't, so the
/// next source is tried.
#[cfg(any(target_os = "linux", test))]
fn usable(found: Found) -> Found {
match found {
Found::Profile { icc, from } => match vectorcraft_ui_egui::display_profile::check_profile(&icc) {
Ok(()) => Found::Profile { icc, from },
Err(e) => Found::NoProfile(format!("{from}: {e}")),
},
other => other,
}
}
/// The ICC file at `path`, refused before it is read when it is larger than [`MAX_PROFILE_BYTES`].
///
/// [`MAX_PROFILE_BYTES`]: vectorcraft_ui_egui::display_profile::MAX_PROFILE_BYTES
#[cfg(any(windows, target_os = "linux", test))]
fn read_icc(path: &std::path::Path) -> Result<Vec<u8>, String> {
use std::io::Read as _;
let max = vectorcraft_ui_egui::display_profile::MAX_PROFILE_BYTES;
let too_large = || format!("{} is larger than {} MiB", path.display(), max >> 20);
let file = std::fs::File::open(path).map_err(|e| format!("couldn't open {}: {e}", path.display()))?;
let len = file.metadata().map_err(|e| format!("couldn't read {}: {e}", path.display()))?.len();
if len > max as u64 {
return Err(too_large());
}
let mut bytes = Vec::with_capacity(len as usize);
file.take(max as u64 + 1).read_to_end(&mut bytes).map_err(|e| format!("couldn't read {}: {e}", path.display()))?;
if bytes.len() > max { Err(too_large()) } else { Ok(bytes) }
}
/// The file a profile `name` stands for: `name` itself when it is a path, otherwise the file of
/// that name in the system's color folder `dir`.
#[cfg(any(windows, test))]
fn profile_path(dir: Option<&std::path::Path>, name: &str) -> std::path::PathBuf {
match dir {
Some(dir) if !name.contains(['\\', '/']) => dir.join(name),
_ => std::path::PathBuf::from(name),
}
}
/// `path`'s profile, or why there is none.
#[cfg(any(windows, target_os = "linux"))]
fn profile_file(path: &std::path::Path) -> Found {
let from = path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned());
match read_icc(path) {
Ok(icc) => Found::Profile { icc, from },
Err(e) => Found::NoProfile(e),
}
}
#[cfg(windows)]
#[allow(unsafe_code)]
mod win {
use std::path::PathBuf;
use std::sync::OnceLock;
use vectorcraft_ui_egui::display_profile::Found;
use windows::Win32::Devices::Display::{
DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO, DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_DEVICE_INFO_HEADER,
DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO, DISPLAYCONFIG_MODE_INFO, DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SOURCE_DEVICE_NAME,
DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes, QDC_ONLY_ACTIVE_PATHS, QueryDisplayConfig,
};
use windows::Win32::Foundation::{ERROR_INSUFFICIENT_BUFFER, ERROR_SUCCESS, HLOCAL, LUID, LocalFree};
use windows::Win32::Graphics::Gdi::{CreateDCW, DeleteDC};
use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW};
use windows::Win32::UI::ColorSystem::{
CPST_STANDARD_DISPLAY_COLOR_MODE, CPT_ICC, GetColorDirectoryW, GetICMProfileW, WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER,
};
use windows::core::{HRESULT, PCWSTR, PWSTR, s, w};
/// `ColorProfileGetDisplayDefault` and `ColorProfileGetDisplayUserScope` (mscms.dll), which
/// older Windows versions don't have.
type GetDefault = unsafe extern "system" fn(i32, LUID, u32, i32, i32, *mut PWSTR) -> HRESULT;
type GetScope = unsafe extern "system" fn(LUID, u32, *mut i32) -> HRESULT;
/// The display path that shows a GDI device.
struct Path {
source: u32,
target_adapter: LUID,
target: u32,
}
pub(super) fn read(display: Option<&str>) -> Found {
let Some(device) = display else { return Found::NoProfile("Windows didn't name the window's display".into()) };
let path = match find_path(device) {
Ok(path) => path,
Err(e) => return Found::NoProfile(e),
};
if path.as_ref().is_some_and(advanced_color) {
return Found::System("Windows manages this display's colors (Advanced Color)".into());
}
let name = match path.as_ref().and_then(default_profile) {
Some(Ok(name)) => name,
Some(Err(e)) => return Found::NoProfile(e),
// Older Windows, or a display without an active path: GDI's profile for the device.
None => match icm_profile(device) {
Ok(name) => name,
Err(e) => return Found::NoProfile(e),
},
};
match name {
Some(name) => super::profile_file(&super::profile_path(color_directory().as_deref(), &name)),
None => Found::NoProfile("no color profile is set for this display".into()),
}
}
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain([0]).collect()
}
fn until_nul(w: &[u16]) -> String {
String::from_utf16_lossy(&w[..w.iter().position(|&c| c == 0).unwrap_or(w.len())])
}
/// The active display paths.
fn paths() -> Result<Vec<DISPLAYCONFIG_PATH_INFO>, String> {
for _ in 0..4 {
let (mut paths_len, mut modes_len) = (0u32, 0u32);
// SAFETY: both pointers are to live `u32`s.
let e = unsafe { GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut paths_len, &mut modes_len) };
if e != ERROR_SUCCESS {
return Err(format!("Windows couldn't list the displays (error {})", e.0));
}
let mut paths = vec![DISPLAYCONFIG_PATH_INFO::default(); paths_len as usize];
let mut modes = vec![DISPLAYCONFIG_MODE_INFO::default(); modes_len as usize];
// SAFETY: the arrays hold as many elements as the lengths passed with them.
let e =
unsafe { QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &mut paths_len, paths.as_mut_ptr(), &mut modes_len, modes.as_mut_ptr(), None) };
if e == ERROR_INSUFFICIENT_BUFFER {
// The displays changed between the two calls.
continue;
}
if e != ERROR_SUCCESS {
return Err(format!("Windows couldn't list the displays (error {})", e.0));
}
paths.truncate(paths_len as usize);
return Ok(paths);
}
Err("the displays kept changing while Windows listed them".into())
}
/// The path whose source is the GDI device `device` (`\\.\DISPLAY1`), if one is active.
fn find_path(device: &str) -> Result<Option<Path>, String> {
for p in paths()? {
let mut name = DISPLAYCONFIG_SOURCE_DEVICE_NAME {
header: DISPLAYCONFIG_DEVICE_INFO_HEADER {
r#type: DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME,
size: size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as u32,
adapterId: p.sourceInfo.adapterId,
id: p.sourceInfo.id,
},
..Default::default()
};
// SAFETY: the header starts a `DISPLAYCONFIG_SOURCE_DEVICE_NAME` of the size it states.
if unsafe { DisplayConfigGetDeviceInfo(&mut name.header) } == 0 && until_nul(&name.viewGdiDeviceName).eq_ignore_ascii_case(device) {
return Ok(Some(Path { source: p.sourceInfo.id, target_adapter: p.targetInfo.adapterId, target: p.targetInfo.id }));
}
}
Ok(None)
}
/// Whether Windows color-manages the path's display itself: Advanced Color is on (HDR), or
/// wide color is enforced (Automatic Color Management on an SDR display).
fn advanced_color(path: &Path) -> bool {
let mut info = DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO {
header: DISPLAYCONFIG_DEVICE_INFO_HEADER {
r#type: DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO,
size: size_of::<DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO>() as u32,
adapterId: path.target_adapter,
id: path.target,
},
..Default::default()
};
// SAFETY: the header starts a `DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO` of the size it states.
if unsafe { DisplayConfigGetDeviceInfo(&mut info.header) } != 0 {
return false;
}
// SAFETY: every bit pattern is a valid `u32`.
let bits = unsafe { info.Anonymous.value };
// advancedColorEnabled is bit 1 and wideColorEnforced bit 2.
bits & 0b110 != 0
}
fn api() -> Option<(GetDefault, GetScope)> {
static API: OnceLock<Option<(GetDefault, GetScope)>> = OnceLock::new();
*API.get_or_init(|| {
// SAFETY: mscms.dll is loaded from System32 only, and stays loaded for the process.
let module = unsafe { LoadLibraryExW(w!("mscms.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) }.ok()?;
// SAFETY: the names are NUL-terminated, and the module is loaded.
let (default, scope) = unsafe {
(GetProcAddress(module, s!("ColorProfileGetDisplayDefault"))?, GetProcAddress(module, s!("ColorProfileGetDisplayUserScope"))?)
};
// SAFETY: both exports have these signatures (icm.h).
unsafe {
Some((
std::mem::transmute::<unsafe extern "system" fn() -> isize, GetDefault>(default),
std::mem::transmute::<unsafe extern "system" fn() -> isize, GetScope>(scope),
))
}
})
}
/// The display's default profile name for its standard color mode, `None` without the API.
fn default_profile(path: &Path) -> Option<Result<Option<String>, String>> {
let (get_default, get_scope) = api()?;
let mut scope = WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER.0;
// SAFETY: `scope` is a live `i32`.
if unsafe { get_scope(path.target_adapter, path.source, &mut scope) }.is_err() {
scope = WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER.0;
}
let mut name = PWSTR::null();
// SAFETY: `name` is a live pointer the function fills with a string it allocates.
let hr = unsafe { get_default(scope, path.target_adapter, path.source, CPT_ICC.0, CPST_STANDARD_DISPLAY_COLOR_MODE.0, &mut name) };
if hr.is_err() {
return Some(Err(format!("Windows couldn't give the display's profile (error {:#010x})", hr.0)));
}
if name.is_null() {
return Some(Ok(None));
}
// SAFETY: `name` is a NUL-terminated string from the call above, freed once with LocalFree.
let text = unsafe { name.to_string() };
// SAFETY: as above.
let _ = unsafe { LocalFree(Some(HLOCAL(name.0.cast()))) };
Some(text.map(|t| Some(t).filter(|t| !t.is_empty())).map_err(|e| format!("the display's profile name isn't readable: {e}")))
}
/// GDI's profile file for the display device `device`.
fn icm_profile(device: &str) -> Result<Option<String>, String> {
let device = wide(device);
// SAFETY: both strings are NUL-terminated and outlive the call.
let dc = unsafe { CreateDCW(w!("DISPLAY"), PCWSTR(device.as_ptr()), PCWSTR::null(), None) };
if dc.is_invalid() {
return Err("Windows couldn't open the display".into());
}
let mut len = 0u32;
// SAFETY: a null buffer asks for the length only.
let _ = unsafe { GetICMProfileW(dc, &mut len, None) };
let mut buf = vec![0u16; len.clamp(1, 32 * 1024) as usize];
len = buf.len() as u32;
// SAFETY: `buf` holds `len` characters.
let ok = unsafe { GetICMProfileW(dc, &mut len, Some(PWSTR(buf.as_mut_ptr()))) }.as_bool();
// SAFETY: `dc` came from CreateDCW above.
let _ = unsafe { DeleteDC(dc) };
Ok(ok.then(|| until_nul(&buf)).filter(|n| !n.is_empty()))
}
/// The system's color folder (`…\spool\drivers\color`).
fn color_directory() -> Option<PathBuf> {
let mut bytes = 0u32;
// SAFETY: a null buffer asks for the size only, in bytes.
let _ = unsafe { GetColorDirectoryW(PCWSTR::null(), None, &mut bytes) };
let mut buf = vec![0u16; (bytes as usize / 2).clamp(1, 32 * 1024)];
bytes = (buf.len() * 2) as u32;
// SAFETY: `buf` holds `bytes` bytes.
unsafe { GetColorDirectoryW(PCWSTR::null(), Some(PWSTR(buf.as_mut_ptr())), &mut bytes) }.as_bool().then(|| PathBuf::from(until_nul(&buf)))
}
#[cfg(test)]
mod tests {
use windows::Win32::Graphics::Gdi::{DISPLAY_DEVICE_ATTACHED_TO_DESKTOP, DISPLAY_DEVICEW, EnumDisplayDevicesW};
use super::*;
/// The GDI names (`\\.\DISPLAY1`) of the displays attached to the desktop.
fn attached_displays() -> Vec<String> {
let mut names = Vec::new();
for i in 0.. {
let mut device = DISPLAY_DEVICEW { cb: size_of::<DISPLAY_DEVICEW>() as u32, ..Default::default() };
// SAFETY: `device` is a live `DISPLAY_DEVICEW` with `cb` set to its size.
if !unsafe { EnumDisplayDevicesW(PCWSTR::null(), i, &mut device, 0) }.as_bool() {
break;
}
if device.StateFlags.contains(DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) {
names.push(until_nul(&device.DeviceName));
}
}
names
}
#[test]
fn windows_reads_each_attached_display_and_refuses_an_unknown_one() {
assert_eq!(read(None), Found::NoProfile("Windows didn't name the window's display".into()));
assert!(color_directory().is_none_or(|dir| dir.is_absolute()));
match find_path(r"\\.\DISPLAY999") {
Ok(path) => {
assert!(path.is_none());
assert_eq!(read(Some(r"\\.\DISPLAY999")), Found::NoProfile("Windows couldn't open the display".into()));
}
// A session without displays (a service): the reading gives Windows' error.
Err(e) => {
eprintln!("the displays couldn't be listed: {e}");
assert_eq!(read(Some(r"\\.\DISPLAY999")), Found::NoProfile(e));
return;
}
}
for name in attached_displays() {
// A display without an active path is read through GDI (`icm_profile`).
let path = find_path(&name).unwrap();
// winit names the display in GDI's spelling; the match ignores letter case.
let lower = find_path(&name.to_lowercase()).unwrap();
assert_eq!(lower.map(|p| (p.source, p.target)), path.as_ref().map(|p| (p.source, p.target)), "{name} in lowercase");
match read(Some(&name)) {
Found::Profile { icc, from } => {
eprintln!("{name}: profile {from}, {} bytes", icc.len());
assert!(!icc.is_empty() && !from.is_empty());
assert!(!path.as_ref().is_some_and(advanced_color));
}
Found::System(e) => {
eprintln!("{name}: system, {e}");
assert!(path.as_ref().is_some_and(advanced_color));
}
Found::NoProfile(e) => {
eprintln!("{name}: no profile, {e}");
assert!(!e.is_empty());
}
}
}
}
}
}
#[cfg(target_os = "linux")]
mod x11 {
use std::collections::HashMap;
use std::path::Path;
use std::time::Duration;
use vectorcraft_ui_egui::display_profile::{Found, MAX_PROFILE_BYTES};
use x11rb::connection::Connection as _;
use x11rb::protocol::randr;
use x11rb::protocol::xproto::{self, AtomEnum};
use zbus::blocking::{connection::Builder, proxy::Proxy};
use zbus::zvariant::OwnedObjectPath;
const COLORD: &str = "org.freedesktop.ColorManager";
const COLORD_ROOT: &str = "/org/freedesktop/ColorManager";
const COLORD_MANAGER: &str = "org.freedesktop.ColorManager";
const COLORD_DEVICE: &str = "org.freedesktop.ColorManager.Device";
const COLORD_PROFILE: &str = "org.freedesktop.ColorManager.Profile";
pub(super) fn read(output: Option<&str>) -> Found {
let colord = output.map(|o| colord_profile(o).map(|path| path.map(|path| super::usable(super::profile_file(Path::new(&path))))));
super::x11_choice(colord, || properties(output))
}
/// The file colord assigns the RandR output `output`.
fn colord_profile(output: &str) -> Result<Option<String>, String> {
let connection = Builder::system()
.map_err(|e| format!("couldn't connect to the system bus: {e}"))?
.method_timeout(Duration::from_secs(2))
.build()
.map_err(|e| format!("couldn't connect to the system bus: {e}"))?;
let manager = Proxy::new(&connection, COLORD, COLORD_ROOT, COLORD_MANAGER).map_err(|e| format!("couldn't reach colord: {e}"))?;
let devices: Vec<OwnedObjectPath> =
manager.call("GetDevicesByKind", &("display",)).map_err(|e| format!("colord couldn't list the displays: {e}"))?;
for path in devices {
let Ok(device) = Proxy::new(&connection, COLORD, &path, COLORD_DEVICE) else { continue };
let Ok(metadata) = device.get_property::<HashMap<String, String>>("Metadata") else { continue };
if metadata.get("XRANDR_name").map(String::as_str) != Some(output) {
continue;
}
// `*` asks for the device's default profile.
let Ok(profile_path) = device.call::<_, _, OwnedObjectPath>("GetProfileForQualifiers", &(vec!["*"],)) else { return Ok(None) };
let profile =
Proxy::new(&connection, COLORD, &profile_path, COLORD_PROFILE).map_err(|e| format!("couldn't reach colord's profile: {e}"))?;
return Ok(profile.get_property::<String>("Filename").ok().filter(|f| !f.is_empty()));
}
Ok(None)
}
/// The `_ICC_PROFILE` property of the RandR output `output`, or of the screen when only one
/// output is active.
fn properties(output: Option<&str>) -> Result<Option<Found>, String> {
let (conn, screen) = x11rb::connect(None).map_err(|e| format!("couldn't connect to the X11 display: {e}"))?;
let root = conn.setup().roots.get(screen).ok_or_else(|| "the X11 display has no screen".to_string())?.root;
let atom = xproto::intern_atom(&conn, true, b"_ICC_PROFILE")
.map_err(|e| format!("couldn't ask the X11 display for profiles: {e}"))?
.reply()
.map_err(|e| format!("couldn't ask the X11 display for profiles: {e}"))?
.atom;
if atom == 0 {
return Ok(None);
}
let resources = randr::get_screen_resources_current(&conn, root)
.map_err(|e| format!("couldn't list the X11 outputs: {e}"))?
.reply()
.map_err(|e| format!("couldn't list the X11 outputs: {e}"))?;
let (mut active, mut shown) = (0usize, None);
for o in resources.outputs {
let Ok(Ok(info)) = randr::get_output_info(&conn, o, resources.config_timestamp).map(|c| c.reply()) else { continue };
if info.connection != randr::Connection::CONNECTED || info.crtc == 0 {
continue;
}
active += 1;
if output.is_some_and(|name| info.name == name.as_bytes()) {
shown = Some(o);
}
}
let longs = (MAX_PROFILE_BYTES / 4) as u32;
let too_large = || Found::NoProfile(format!("the display's profile is larger than {} MiB", MAX_PROFILE_BYTES >> 20));
if let Some(o) = shown
&& let Ok(Ok(p)) = randr::get_output_property(&conn, o, atom, AtomEnum::ANY, 0, longs, false, false).map(|c| c.reply())
&& !p.data.is_empty()
{
if p.bytes_after > 0 {
return Ok(Some(too_large()));
}
return Ok(Some(Found::Profile { icc: p.data, from: "the X11 output's _ICC_PROFILE".into() }));
}
if active != 1 {
return Ok(None);
}
let Ok(Ok(p)) = xproto::get_property(&conn, false, root, atom, AtomEnum::ANY, 0, longs).map(|c| c.reply()) else { return Ok(None) };
if p.value.is_empty() {
return Ok(None);
}
if p.bytes_after > 0 {
return Ok(Some(too_large()));
}
Ok(Some(Found::Profile { icc: p.value, from: "the X11 screen's _ICC_PROFILE".into() }))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_reading_is_due_first_after_ten_seconds_and_when_the_window_changes_display() {
assert!(due(None, 0.0, None));
let last = (100.0, Some("DP-1".to_string()));
assert!(!due(Some(&last), 100.0, Some("DP-1")));
assert!(!due(Some(&last), 109.9, Some("DP-1")));
assert!(due(Some(&last), 110.0, Some("DP-1")));
assert!(due(Some(&last), 101.0, Some("HDMI-1")));
assert!(due(Some(&last), 101.0, None));
// A clock that went back.
assert!(due(Some(&last), 50.0, Some("DP-1")));
}
#[test]
fn wayland_sessions_are_told_apart_from_x11_by_the_environment() {
let env = |pairs: &'static [(&'static str, &'static str)]| {
move |k: &str| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| std::ffi::OsString::from(v))
};
assert!(wayland_session(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")])));
assert!(wayland_session(env(&[("WAYLAND_SOCKET", "5")])));
assert!(!wayland_session(env(&[("DISPLAY", ":0")])));
assert!(!wayland_session(env(&[("WAYLAND_DISPLAY", ""), ("DISPLAY", ":0")])));
}
#[test]
fn profile_files_larger_than_the_limit_are_refused_before_they_are_read() {
let dir = tempfile::tempdir().unwrap();
let small = dir.path().join("small.icc");
std::fs::write(&small, [1u8, 2, 3]).unwrap();
assert_eq!(read_icc(&small).unwrap(), [1, 2, 3]);
let big = dir.path().join("big.icc");
let f = std::fs::File::create(&big).unwrap();
f.set_len(vectorcraft_ui_egui::display_profile::MAX_PROFILE_BYTES as u64 + 1).unwrap();
assert!(read_icc(&big).unwrap_err().contains("larger than 1 MiB"));
assert!(read_icc(&dir.path().join("missing.icc")).unwrap_err().starts_with("couldn't open"));
}
#[test]
fn x11_takes_the_output_property_when_colord_s_file_cannot_be_read() {
let icc = |b: u8| Found::Profile { icc: vec![b], from: "test".into() };
let property = || Ok(Some(icc(2)));
// colord's profile, read: the property is not asked for.
assert_eq!(x11_choice(Some(Ok(Some(icc(1)))), || panic!("not asked")), icc(1));
// colord names a file that can't be read, or has no profile, or isn't running.
assert_eq!(x11_choice(Some(Ok(Some(Found::NoProfile("couldn't open a.icc".into())))), property), icc(2));
assert_eq!(x11_choice(Some(Ok(None)), property), icc(2));
assert_eq!(x11_choice(Some(Err("no colord".into())), property), icc(2));
assert_eq!(x11_choice(None, property), icc(2));
// Neither has a profile: colord's reason is kept.
assert_eq!(
x11_choice(Some(Ok(Some(Found::NoProfile("couldn't open a.icc".into())))), || Ok(None)),
Found::NoProfile("no profile is set for this display (couldn't open a.icc)".into())
);
assert_eq!(x11_choice(None, || Ok(None)), Found::NoProfile("no profile is set for this display".into()));
assert_eq!(x11_choice(None, || Err("no X11".into())), Found::NoProfile("no X11".into()));
// colord's file holds no usable profile: the property is used.
let broken = usable(Found::Profile { icc: vec![1, 2, 3], from: "a.icc".into() });
assert_eq!(broken, Found::NoProfile("a.icc: the file is not an ICC profile".into()));
assert_eq!(x11_choice(Some(Ok(Some(broken))), property), icc(2));
assert_eq!(usable(Found::NoProfile("none".into())), Found::NoProfile("none".into()));
}
#[test]
fn a_profile_name_is_found_in_the_color_folder_and_a_path_is_kept() {
let dir = std::path::Path::new("C:/Windows/System32/spool/drivers/color");
assert_eq!(profile_path(Some(dir), "Display.icm"), dir.join("Display.icm"));
assert_eq!(profile_path(Some(dir), "D:\\profiles\\Display.icm"), std::path::PathBuf::from("D:\\profiles\\Display.icm"));
assert_eq!(profile_path(None, "Display.icm"), std::path::PathBuf::from("Display.icm"));
}
}
+95 -20
View File
@@ -126,20 +126,70 @@ pub fn preferred_compositor(pref: Option<&str>, env: Option<PowerPreference>) ->
if automatic(pref, env) { crate::compositor_gpu::compositor_gpu() } else { None }
}
/// The graphics backends the window starts with: on Windows Direct3D 12, falling back to OpenGL,
/// unless `WGPU_BACKEND` names others (`env_set`; `default` then holds them). Creating a Vulkan
/// instance loads every installed Vulkan driver into the process, and a faulty one (Intel's
/// `igvk64.dll`, #806) crashed the app before its window appeared. DX12 is Windows' own backend,
/// as in PdfCraft. Elsewhere, `default`.
pub fn backends(default: Backends, env_set: bool) -> Backends {
if cfg!(windows) && !env_set { Backends::DX12 | Backends::GL } else { default }
/// The graphics backends the window starts with: on Windows Direct3D 12, with OpenGL beside it
/// only when `opengl` ([`windows_opengl`]), unless `WGPU_BACKEND` names others (`env_set`;
/// `default` then holds them). Creating a Vulkan instance loads every installed Vulkan driver into
/// the process, and a faulty one (Intel's `igvk64.dll`, #806) crashed the app before its window
/// appeared. DX12 is Windows' own backend, as in PdfCraft. Elsewhere, `default`.
pub fn backends(default: Backends, env_set: bool, opengl: bool) -> Backends {
match (cfg!(windows) && !env_set, opengl) {
(true, true) => Backends::DX12 | Backends::GL,
(true, false) => Backends::DX12,
(false, _) => default,
}
}
/// The largest texture side to ask the device for, which bounds the window's surface: the
/// adapter's own limit when it is above eframe's `default` (8192 px), so a window larger than
/// that keeps its surface (#1459). Never below `default`, which is what was asked for before.
pub fn surface_limit(default: u32, adapter: u32) -> u32 {
default.max(adapter)
/// Whether a Windows start lists OpenGL's adapters beside Direct3D 12's: only when it leaves an
/// adapter out (an earlier start crashed on it, or a restart failed on it), when
/// `WGPU_ADAPTER_NAME` names one (it may be an OpenGL adapter), or when DX12 lists no hardware
/// adapter (Windows 7, or a GPU without a DX12 driver, which then draws through OpenGL as before
/// rather than on the CPU with WARP). wgpu's OpenGL backend keeps a hidden window on a thread that
/// pumps no messages, and Windows waits on it when the input language changes, so the whole app
/// hung on a switch to another keyboard layout (#4150, gfx-rs/wgpu#10504), even drawing with DX12.
pub fn windows_opengl(left_out: &LeftOut) -> bool {
opengl_needed(left_out, !skipped().is_empty(), std::env::var_os(NAME_ENV).is_some(), dx12_lists_hardware)
}
/// [`windows_opengl`], with a restart leaving adapters out (`skipping`) and an adapter named
/// (`named`): `dx12_hardware` is asked only when nothing else decides.
fn opengl_needed(left_out: &LeftOut, skipping: bool, named: bool, dx12_hardware: impl FnOnce() -> bool) -> bool {
left_out.opengl_only || !left_out.adapters.is_empty() || skipping || named || !dx12_hardware()
}
/// Whether Direct3D 12 lists a hardware adapter; WARP, its software one, doesn't count. A driver
/// that crashes here crashes a start while it lists the adapters, which the next start answers with
/// OpenGL alone.
#[cfg(windows)]
fn dx12_lists_hardware() -> bool {
let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
descriptor.backends = Backends::DX12;
// The shader compiler the window's own instance takes (#1194).
descriptor.backend_options.dx12.shader_compiler = wgpu::Dx12Compiler::from_env().unwrap_or(wgpu::Dx12Compiler::Fxc);
let instance = wgpu::Instance::new(descriptor);
let kinds: Vec<DeviceType> = pollster::block_on(instance.enumerate_adapters(Backends::DX12)).iter().map(|a| a.get_info().device_type).collect();
log::info!("Direct3D 12 lists these graphics adapters: {kinds:?}");
any_hardware(&kinds)
}
#[cfg(not(windows))]
fn dx12_lists_hardware() -> bool {
false
}
/// Is one of the adapters of these kinds hardware, not software such as WARP?
#[cfg(any(windows, test))]
fn any_hardware(kinds: &[DeviceType]) -> bool {
kinds.iter().any(|k| *k != DeviceType::Cpu)
}
/// The limits to ask the device for: what eframe `asked` for, lowered to what the `adapter` offers
/// wherever it offers less, so a GPU short of one of them still gets a device (#2105). The texture
/// side, which bounds the window's surface, is the adapter's own, above eframe's 8192 px when the
/// adapter allows more, so a window larger than that keeps its surface (#1459).
pub fn device_limits(asked: wgpu::Limits, adapter: &wgpu::Limits) -> wgpu::Limits {
let mut limits = asked.or_worse_values_from(adapter);
limits.max_texture_dimension_2d = adapter.max_texture_dimension_2d;
limits
}
/// One adapter, as [`adapter_order`] sees it.
@@ -260,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_")?))
@@ -703,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
@@ -717,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;
+110 -28
View File
@@ -5,11 +5,34 @@ fn gpu(name: &str, backend: Backend, device_type: DeviceType) -> Candidate {
}
/// #1459: a 9048 px wide window (two display scales' ratio past 8192) fits an adapter that
/// takes 16384 px textures; an adapter with less than eframe asks for changes nothing.
/// takes 16384 px textures.
#[test]
fn the_surface_may_be_as_large_as_the_adapter_allows() {
assert_eq!(surface_limit(8192, 16384), 16384);
assert_eq!(surface_limit(8192, 4096), 8192);
let adapter = wgpu::Limits { max_texture_dimension_2d: 16384, ..wgpu::Limits::default() };
let asked = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() };
assert_eq!(device_limits(asked, &adapter).max_texture_dimension_2d, 16384);
}
/// #2105: a GPU that offers less than eframe asks for on any limit (here a Raspberry Pi 5's V3D 7.1:
/// 15 inter-stage variables on Vulkan, 4096 px textures on OpenGL) gets a device with what it
/// offers, instead of failing and leaving the window to the software rasterizer. A GPU that offers
/// more is asked for no more than before, except for the texture side.
#[test]
fn the_device_asks_for_no_more_than_the_adapter_offers() {
let asked = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() };
let vulkan = wgpu::Limits { max_inter_stage_shader_variables: 15, max_texture_dimension_2d: 7680, ..wgpu::Limits::default() };
let limits = device_limits(asked.clone(), &vulkan);
assert_eq!((limits.max_inter_stage_shader_variables, limits.max_texture_dimension_2d), (15, 7680));
assert!(limits.check_limits(&vulkan), "{limits:?}");
let gl = wgpu::Limits { max_texture_dimension_2d: 4096, ..wgpu::Limits::downlevel_webgl2_defaults() };
let webgl2 = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::downlevel_webgl2_defaults() };
let limits = device_limits(webgl2.clone(), &gl);
assert_eq!(limits.max_texture_dimension_2d, 4096);
assert!(limits.check_limits(&gl), "{limits:?}");
let ample = wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::default() };
assert_eq!(device_limits(asked.clone(), &ample), asked);
let better = wgpu::Limits { max_inter_stage_shader_variables: 31, max_texture_dimension_2d: 8192, ..wgpu::Limits::default() };
assert_eq!(device_limits(asked.clone(), &better), asked, "never more than eframe asked for");
}
fn names(c: &[Candidate], order: &[usize]) -> Vec<String> {
@@ -219,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"))?;
@@ -239,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]
@@ -343,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);
@@ -451,13 +479,50 @@ fn a_windows_gpu_renders_through_dx12_before_vulkan() {
#[test]
fn windows_never_loads_vulkan_drivers_unless_asked() {
let all = Backends::all();
let start = backends(all, false);
let start = backends(all, false, false);
let fallback = backends(all, false, true);
if cfg!(windows) {
assert_eq!(start, Backends::DX12 | Backends::GL, "#806");
assert_eq!(start, Backends::DX12, "#806, and no OpenGL unless needed (#4150)");
assert_eq!(fallback, Backends::DX12 | Backends::GL);
} else {
assert_eq!(start, all);
assert_eq!((start, fallback), (all, all));
}
assert_eq!(backends(Backends::VULKAN, true), Backends::VULKAN, "WGPU_BACKEND=vulkan still picks it");
assert_eq!(backends(Backends::VULKAN, true, false), Backends::VULKAN, "WGPU_BACKEND=vulkan still picks it");
assert_eq!(backends(Backends::GL, true, false), Backends::GL, "WGPU_BACKEND=gl still picks it");
}
#[test]
fn windows_lists_opengl_once_a_start_leaves_an_adapter_out() {
let crashed = LeftOut { adapters: vec!["Dx12:8086:3ea0".into()], ..LeftOut::default() };
assert!(windows_opengl(&crashed), "#2243: the next start can fall back to OpenGL");
let listing = LeftOut { opengl_only: true, ..LeftOut::default() };
assert!(windows_opengl(&listing));
assert_eq!(listing.backends(backends(Backends::all(), false, true)), Backends::GL);
}
/// OpenGL stays where it drew before #4150's fix: a GPU without a Direct3D 12 driver (DX12 lists
/// WARP alone) and an adapter `WGPU_ADAPTER_NAME` names; a start with a DX12 GPU lists DX12 alone.
#[test]
fn windows_lists_opengl_without_a_dx12_gpu_or_with_an_adapter_named() {
let start = LeftOut::default();
let asked = std::cell::Cell::new(false);
let hardware = |found: bool| {
asked.set(true);
found
};
assert!(!opengl_needed(&start, false, false, || hardware(true)), "a DX12 GPU: DX12 alone (#4150)");
assert!(asked.replace(false));
assert!(opengl_needed(&start, false, false, || hardware(false)), "WARP alone: the GPU draws through OpenGL, not the CPU");
assert!(opengl_needed(&start, false, true, || hardware(true)), "a named adapter may be an OpenGL one");
assert!(opengl_needed(&start, true, false, || hardware(true)), "a restart left an adapter out");
let listing = LeftOut { opengl_only: true, ..LeftOut::default() };
asked.set(false);
assert!(opengl_needed(&listing, false, false, || hardware(true)));
assert!(!asked.get(), "DX12 isn't listed once OpenGL must be");
assert!(any_hardware(&[DeviceType::Cpu, DeviceType::IntegratedGpu]));
assert!(any_hardware(&[DeviceType::VirtualGpu]));
assert!(!any_hardware(&[DeviceType::Cpu]), "WARP");
assert!(!any_hardware(&[]), "Windows 7");
}
#[test]
@@ -551,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.
@@ -605,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,
@@ -628,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
@@ -656,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
@@ -677,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
@@ -712,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]
@@ -745,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);
}
+445
View File
@@ -0,0 +1,445 @@
//! The hang report. A thread reads the interface thread's marks
//! ([`vectorcraft_ui_egui::hang_beacon`]) every [`POLL`]. When the interface thread has made no
//! mark for [`STALL`] while inside a stage of its frame, the thread writes what the app knows to the
//! log (`logs/vectorcraft.log`) and to `logs/hang-report-<process id>.txt`: the stage, a clipboard
//! call in progress, the last commands, the last frames' times, the platform, the window system, the
//! graphics processor and the present mode the app asked for, and how long the session has run with
//! how many documents open. The process holds a lock on the file until the interface thread answers
//! again; then the log says after how long and the file is removed. A file nobody holds at a later
//! launch was left by a session that was closed while it did not answer, and a locked one belongs to
//! another instance that is stalled now and is left alone. That launch writes the report to the log,
//! moves the newest abandoned file to `hang-report.1.txt` and removes the others, says so in the
//! status bar, and Help › Copy Troubleshooting Info copies the reports. Where the file system has no
//! file locks, the file is written and taken without one.
//!
//! No native stack is recorded: the marks are what the report has. The report holds command ids and
//! counts, never document contents or file paths. [`STALL`] is VectorCraft's own value.
//!
//! A stall in the renderer is timed only after a frame that had input in any window: input asks for
//! the next frame at once, so a frame that does not start then is late. After a frame without
//! input, the window waiting for input looks the same as one stuck drawing, so that time is not
//! timed. Nor is the time after a frame that minimizes or hides the main window or hands it to the
//! system to move or resize. A window the system stops redrawing while it is hidden can still look
//! like a stall after a frame with input; the report's stage says so. A system file dialog shown in
//! line (on Windows and Linux) and an open menu of the macOS menu bar wait for the user and are not
//! timed.
use std::fs::File;
use std::io::{Read as _, Write as _};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant, SystemTime};
#[cfg(target_os = "macos")]
use vectorcraft_ui_egui::hang_beacon::Activity;
use vectorcraft_ui_egui::hang_beacon::{BEACON, Beacon, FrameTime, Sample, Stage};
use super::logging::timestamp;
/// How long the interface thread may stay in one stage before the report is written.
pub const STALL: Duration = Duration::from_secs(3);
/// How often the watching thread reads the marks.
pub const POLL: Duration = Duration::from_millis(500);
/// The report of a stall that has not ended, in the log folder: this, the process id, `.txt`.
pub const REPORT_PREFIX: &str = "hang-report-";
/// At most this many report files are taken when a launch looks for abandoned ones; older abandoned
/// ones are removed.
const MAX_REPORT_FILES: usize = 16;
/// At most this many entries of the log folder are looked at for report files.
const MAX_SCANNED_ENTRIES: usize = 1024;
/// The report the last session left, moved here at launch.
pub const PREVIOUS_FILE: &str = "hang-report.1.txt";
/// A report file larger than this is not read.
pub const MAX_REPORT_BYTES: u64 = 64 * 1024;
/// Environment values in the report are cut to this many characters.
const MAX_VALUE_CHARS: usize = 64;
/// What [`Watch::check`] found.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Event {
/// The interface thread has been in the sample's stage, without a mark, for this long.
Stalled(Duration),
/// The interface thread made a mark again after a [`Event::Stalled`], about this long after
/// the stall began.
Answered(Duration),
}
/// Decides from successive samples when the interface thread has stalled and when it answers
/// again. Time comes from the caller, so tests drive it without waiting.
#[derive(Debug)]
pub struct Watch {
stall: Duration,
/// The step seen in a busy stage and when it was first seen.
seen: Option<(u64, Duration)>,
reported: bool,
}
impl Watch {
pub fn new(stall: Duration) -> Watch {
Watch { stall, seen: None, reported: false }
}
/// The marks read at `now` (any monotonic clock that started before the first call).
pub fn check(&mut self, now: Duration, sample: Sample) -> Option<Event> {
let same = self.seen.is_some_and(|(step, _)| step == sample.step);
if same && sample.busy() {
let since = self.seen.map_or(now, |(_, since)| since);
let stalled = now.saturating_sub(since);
if !self.reported && stalled >= self.stall {
self.reported = true;
return Some(Event::Stalled(stalled));
}
return None;
}
let answered = match (self.reported, self.seen) {
(true, Some((_, since))) => Some(Event::Answered(now.saturating_sub(since))),
_ => None,
};
self.reported = false;
self.seen = sample.busy().then_some((sample.step, now));
answered
}
}
/// What the report says about the platform.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Facts {
/// The window system the window opened on: Wayland, X11, AppKit, Win32, other or unknown.
pub window_system: String,
/// `XDG_CURRENT_DESKTOP`.
pub desktop: Option<String>,
/// `XDG_SESSION_TYPE`.
pub session_type: Option<String>,
/// Running in a Flatpak sandbox.
pub flatpak: bool,
/// The graphics processor the window draws with.
pub graphics: Option<String>,
/// The present mode and frame queue the app asked the window surface for.
pub surface: String,
}
impl Facts {
/// The facts from the environment (`env`, `flatpak_info`: whether `/.flatpak-info` exists) and
/// what the app knows.
pub fn new(env: impl Fn(&str) -> Option<String>, flatpak_info: bool, window_system: &str, graphics: Option<String>, surface: String) -> Facts {
let value = |name: &str| env(name).map(|v| clean(&v)).filter(|v| !v.is_empty());
Facts {
window_system: window_system.to_string(),
desktop: value("XDG_CURRENT_DESKTOP"),
session_type: value("XDG_SESSION_TYPE"),
flatpak: flatpak_info || env("FLATPAK_ID").is_some_and(|v| !v.is_empty()),
graphics,
surface,
}
}
/// The facts as report lines.
pub fn lines(&self) -> String {
let or_unknown = |v: &Option<String>| v.clone().unwrap_or_else(|| "unknown".to_string());
format!(
"VectorCraft {} on {} {}\nWindow system: {}; desktop: {}; session type: {}; Flatpak: {}\nGraphics: {}; {}\n",
env!("CARGO_PKG_VERSION"),
std::env::consts::OS,
std::env::consts::ARCH,
self.window_system,
or_unknown(&self.desktop),
or_unknown(&self.session_type),
if self.flatpak { "yes" } else { "no" },
or_unknown(&self.graphics),
self.surface,
)
}
}
/// `v` with control characters removed, cut to [`MAX_VALUE_CHARS`] characters.
fn clean(v: &str) -> String {
v.chars().filter(|c| !c.is_control()).take(MAX_VALUE_CHARS).collect::<String>().trim().to_string()
}
/// The marks other than the stage: the last commands, the last frames and the session.
fn activity_lines(beacon: &Beacon, uptime: Duration) -> String {
let commands = match beacon.recent_commands() {
Some(c) if c.is_empty() => "none".to_string(),
Some(c) => c.join(", "),
None => "unavailable (being written)".to_string(),
};
let (work, total) = match beacon.recent_frames() {
Some(frames) => {
let list = |f: &dyn Fn(&FrameTime) -> Option<f32>| {
let times: Vec<String> = frames.iter().filter_map(f).map(|ms| format!("{ms:.1}")).collect();
if times.is_empty() { "none".to_string() } else { times.join(", ") }
};
(list(&|t| Some(t.work_ms)), list(&|t| t.previous_total_ms))
}
None => ("unavailable (being written)".to_string(), "unavailable (being written)".to_string()),
};
format!(
"Recent commands, oldest first: {commands}\nApp work per frame (ms), oldest first: {work}\nWork and drawing per frame, without waiting for the display (ms), oldest first: {total}\nSession: running for {} s, {} documents open\n",
uptime.as_secs(),
beacon.documents(),
)
}
/// The report of a stall that has lasted `stalled` in `sample`'s stage, written at `at`.
pub fn report(at: SystemTime, stalled: Duration, sample: Sample, beacon: &Beacon, uptime: Duration, facts: &Facts) -> String {
let waiting = sample.activity.describe().map(|a| format!("Waiting on: {a}\n")).unwrap_or_default();
format!(
"VectorCraft hang report, {}\nThe interface thread has not moved on for {:.1} s.\nStage: {}\n{waiting}{}{}No native stack is recorded: the stage and the activity are what the app marks.\n",
timestamp(at),
stalled.as_secs_f64(),
sample.stage.describe(),
activity_lines(beacon, uptime),
facts.lines(),
)
}
/// What the watching thread and Help › Copy Troubleshooting Info share.
pub struct Shared {
pub facts: Facts,
pub started: Instant,
/// This session's last report.
pub last: Mutex<Option<String>>,
/// The report the last session left ([`take_previous`]).
pub previous: Option<String>,
}
/// The text Help › Copy Troubleshooting Info copies.
pub fn troubleshooting(shared: &Shared, beacon: &Beacon, at: SystemTime) -> String {
let last = shared.last.lock().unwrap_or_else(PoisonError::into_inner).clone();
format!(
"VectorCraft troubleshooting info, {}\n{}{}\nThis session's last hang report:\n{}\nThe hang report the last session left (it was closed while it did not answer):\n{}\n",
timestamp(at),
shared.facts.lines(),
activity_lines(beacon, shared.started.elapsed()),
last.as_deref().unwrap_or("none\n"),
shared.previous.as_deref().unwrap_or("none\n"),
)
}
/// The report file of this process in `dir`.
fn report_path(dir: &Path) -> PathBuf {
dir.join(format!("{REPORT_PREFIX}{}.txt", std::process::id()))
}
/// A report file this process wrote and holds locked until the interface answers again.
#[derive(Debug)]
pub struct Held {
path: PathBuf,
_file: File,
}
/// Write `text` to this process's report file in `dir` and lock it. Where the file system has no
/// file locks, the file is written unlocked and the log says so.
fn write_report(dir: &Path, text: &str) -> std::io::Result<Held> {
std::fs::create_dir_all(dir)?;
let path = report_path(dir);
let mut file = File::create(&path)?;
if let Err(e) = file.lock() {
log::warn!("the hang report file is written without a lock: {e}");
}
file.write_all(text.as_bytes())?;
Ok(Held { path, _file: file })
}
/// Whether a report file whose `try_lock` gave `locked` was abandoned: nobody holds it. A file
/// system without file locks answers [`std::io::ErrorKind::Unsupported`], and its files count as
/// abandoned; any other error leaves the file alone.
fn abandoned(locked: Result<(), std::fs::TryLockError>) -> bool {
match locked {
Ok(()) => true,
Err(std::fs::TryLockError::Error(e)) => e.kind() == std::io::ErrorKind::Unsupported,
Err(std::fs::TryLockError::WouldBlock) => false,
}
}
/// The report file at `path`, opened and locked, with its length, when it was abandoned
/// ([`abandoned`]) and is not empty (an empty one may be being written).
fn open_abandoned(path: &Path) -> Option<(File, u64)> {
let file = File::options().read(true).write(true).open(path).ok()?;
if !abandoned(file.try_lock()) {
return None;
}
let len = file.metadata().map_or(0, |m| m.len());
(len > 0).then_some((file, len))
}
/// The reports that sessions closed while they did not answer left in `dir`, oldest first; `None`
/// when there are none. The newest file is moved to [`PREVIOUS_FILE`] and the others are removed
/// once read. Of more than [`MAX_REPORT_FILES`], the newest are taken and the older ones removed
/// unread; the first [`MAX_SCANNED_ENTRIES`] entries of `dir` are looked at. A report file another
/// process holds locked, or one still empty, is left alone. A file over [`MAX_REPORT_BYTES`] is
/// taken without being read. A file that can't be moved is removed, so no later launch offers it
/// again: the caller writes the reports to the log. Each file is opened once.
pub fn take_previous(dir: &Path) -> Option<String> {
let mut found: Vec<(SystemTime, PathBuf)> = std::fs::read_dir(dir)
.ok()?
.take(MAX_SCANNED_ENTRIES)
.filter_map(Result::ok)
.filter(|e| {
e.file_name()
.to_str()
.and_then(|n| n.strip_prefix(REPORT_PREFIX)?.strip_suffix(".txt"))
.is_some_and(|pid| !pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit()))
})
.map(|e| (e.metadata().and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH), e.path()))
.collect();
found.sort();
// Newest first: only abandoned reports count toward the limit.
let mut texts = Vec::new();
for (_, path) in found.into_iter().rev() {
let Some((file, len)) = open_abandoned(&path) else { continue };
if texts.len() == MAX_REPORT_FILES {
drop(file);
remove_quietly(&path);
continue;
}
let mut bytes = Vec::new();
let text = if len <= MAX_REPORT_BYTES && (&file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() {
String::from_utf8_lossy(&bytes).into_owned()
} else {
format!("The report was larger than {MAX_REPORT_BYTES} bytes and was not read.\n")
};
// Closed (and unlocked) before it is moved: Windows moves no open file.
drop(file);
if !texts.is_empty() {
remove_quietly(&path);
} else if let Err(e) = std::fs::rename(&path, dir.join(PREVIOUS_FILE)) {
log::warn!("couldn't move the hang report file to {PREVIOUS_FILE}: {e}");
remove_quietly(&path);
}
texts.push(text);
}
texts.reverse();
(!texts.is_empty()).then(|| texts.join("\n"))
}
/// Remove the report file at `path`; a failure goes to the log.
fn remove_quietly(path: &Path) {
if let Err(e) = std::fs::remove_file(path) {
log::warn!("couldn't remove the hang report file: {e}");
}
}
/// Set when the app closes normally ([`closing`]): the watching thread writes no report file after it.
pub static CLOSING: AtomicBool = AtomicBool::new(false);
/// Remove `held`'s file, closing it first. → the error message; a file already gone is none.
fn remove(held: Held) -> Option<String> {
let Held { path, _file: file } = held;
drop(file);
match std::fs::remove_file(&path) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Some(e.to_string()),
_ => None,
}
}
/// Act on what [`Watch::check`] found: write (and hold) or remove this process's report file in
/// `dir`, then log it. The file comes first: logging can wait on what the interface thread waits on.
#[allow(clippy::too_many_arguments)]
pub fn record(
event: Event,
sample: Sample,
beacon: &Beacon,
shared: &Shared,
dir: Option<&Path>,
held: &mut Option<Held>,
closing: &AtomicBool,
at: SystemTime,
) {
match event {
Event::Stalled(stalled) => {
let text = report(at, stalled, sample, beacon, shared.started.elapsed(), &shared.facts);
let mut failed = None;
if let Some(dir) = dir.filter(|_| !closing.load(Ordering::Acquire)) {
match write_report(dir, &text) {
Ok(file) => *held = Some(file),
Err(e) => failed = Some(e.to_string()),
}
// The app began to close while the file was written: it is not a report to leave.
if closing.load(Ordering::Acquire) {
failed = held.take().and_then(remove).or(failed);
}
}
*shared.last.lock().unwrap_or_else(PoisonError::into_inner) = Some(text.clone());
log::warn!("the interface stopped answering:\n{}", text.trim_end());
if let Some(e) = failed {
log::warn!("couldn't write or remove the hang report file: {e}");
}
}
Event::Answered(after) => {
let failed = held.take().and_then(remove);
log::warn!("the interface answered again about {:.1} s after it stopped", after.as_secs_f64());
if let Some(e) = failed {
log::warn!("couldn't remove the hang report file: {e}");
}
}
}
}
/// The app is closing normally: mark the interface thread idle on `beacon` (saving and teardown are
/// not timed), remove this process's report file in `dir` and have the watching thread write no
/// more. It does not wait for the watching thread. The file can be removed while that thread holds
/// it open and locked: the standard library opens files with `FILE_SHARE_DELETE` on Windows, and a
/// byte-range lock does not prevent deletion. Where Windows deletes a file only once its last
/// handle closes, the name goes when the process ends.
pub fn closing(dir: Option<&Path>, closing: &AtomicBool, beacon: &Beacon) {
beacon.enter(Stage::Idle);
closing.store(true, Ordering::Release);
if let Some(dir) = dir {
match std::fs::remove_file(report_path(dir)) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => log::warn!("couldn't remove the hang report file: {e}"),
_ => {}
}
}
}
/// The window system `window` opened on, for [`Facts::window_system`].
pub fn window_system(window: Option<&winit::window::Window>) -> &'static str {
use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle};
match window.and_then(|w| w.window_handle().ok()).map(|h| h.as_raw()) {
Some(RawWindowHandle::Wayland(_)) => "Wayland",
Some(RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)) => "X11",
Some(RawWindowHandle::AppKit(_)) => "AppKit",
Some(RawWindowHandle::Win32(_)) => "Win32",
Some(_) => "other",
None => "unknown",
}
}
/// The present mode and frame queue the app asked the window surface for, for [`Facts::surface`];
/// `None` when the window has no wgpu renderer.
pub fn surface(config: Option<(String, Option<u32>)>) -> String {
match config {
Some((mode, Some(frames))) => format!("requested present mode {mode}, frame latency {frames}"),
Some((mode, None)) => format!("requested present mode {mode}"),
None => "no wgpu renderer".to_string(),
}
}
/// Start the watching thread; the report file goes in `dir` (none: the log only).
pub fn start(dir: Option<PathBuf>, shared: Arc<Shared>) {
let spawned = std::thread::Builder::new().name("hang-watch".into()).spawn(move || {
let mut watch = Watch::new(STALL);
let mut held = None;
loop {
std::thread::sleep(POLL);
#[cfg_attr(not(target_os = "macos"), allow(unused_mut))]
let mut sample = BEACON.sample();
// An open menu of the menu bar waits for the user.
#[cfg(target_os = "macos")]
if super::mac_menu::is_tracking() {
sample.activity = Activity::Menu;
}
if let Some(event) = watch.check(shared.started.elapsed(), sample) {
record(event, sample, &BEACON, &shared, dir.as_deref(), &mut held, &CLOSING, SystemTime::now());
}
}
});
if let Err(e) = spawned {
log::warn!("no hang report this session: the watching thread didn't start: {e}");
}
}
#[cfg(test)]
mod tests;
+270
View File
@@ -0,0 +1,270 @@
use super::*;
use std::time::UNIX_EPOCH;
use vectorcraft_ui_egui::hang_beacon::{Activity, Stage};
fn ms(n: u64) -> Duration {
Duration::from_millis(n)
}
fn sample(step: u64, stage: Stage) -> Sample {
Sample { step, stage, activity: Activity::None }
}
fn facts() -> Facts {
let env = |name: &str| match name {
"XDG_CURRENT_DESKTOP" => Some("KDE".to_string()),
"XDG_SESSION_TYPE" => Some("wayland\u{7}".to_string()),
_ => None,
};
Facts::new(env, true, "Wayland", Some("Test GPU (Vulkan, DiscreteGpu)".to_string()), surface(Some(("AutoVsync".to_string(), Some(1)))))
}
fn shared(previous: Option<String>) -> Shared {
Shared { facts: facts(), started: Instant::now(), last: Mutex::new(None), previous }
}
#[test]
fn a_stage_held_for_the_stall_time_is_reported_once_and_its_end_after_it() {
let mut w = Watch::new(STALL);
assert_eq!(w.check(ms(0), sample(5, Stage::Interface)), None);
assert_eq!(w.check(ms(2_999), sample(5, Stage::Interface)), None);
assert_eq!(w.check(ms(3_000), sample(5, Stage::Interface)), Some(Event::Stalled(ms(3_000))));
assert_eq!(w.check(ms(9_000), sample(5, Stage::Interface)), None);
assert_eq!(w.check(ms(9_500), sample(6, Stage::Idle)), Some(Event::Answered(ms(9_500))));
assert_eq!(w.check(ms(20_000), sample(6, Stage::Idle)), None);
}
#[test]
fn frames_that_keep_moving_and_an_idle_window_are_never_reported() {
let mut w = Watch::new(STALL);
// A long animation: the step changes at every read.
for n in 0..100 {
assert_eq!(w.check(ms(n * 500), sample(n, Stage::Drawing)), None);
}
// A window waiting for input for a minute.
for n in 0..120 {
assert_eq!(w.check(ms(50_000 + n * 500), sample(1_000, Stage::Idle)), None);
}
}
#[test]
fn a_file_dialog_shown_in_line_is_waiting_for_the_user_not_stalled() {
let mut w = Watch::new(STALL);
let dialog = Sample { step: 7, stage: Stage::Interface, activity: Activity::Dialog };
for n in 0..60 {
assert_eq!(w.check(ms(n * 500), dialog), None);
}
// Back from the dialog, the command goes on and is timed again.
assert_eq!(w.check(ms(30_000), sample(8, Stage::Interface)), None);
assert_eq!(w.check(ms(33_000), sample(8, Stage::Interface)), Some(Event::Stalled(ms(3_000))));
}
#[test]
fn an_open_menu_bar_menu_is_waiting_for_the_user_not_stalled() {
let mut w = Watch::new(STALL);
let menu = Sample { step: 3, stage: Stage::Drawing, activity: Activity::Menu };
for n in 0..60 {
assert_eq!(w.check(ms(n * 500), menu), None);
}
}
#[test]
fn a_new_busy_step_starts_the_time_again() {
let mut w = Watch::new(STALL);
assert_eq!(w.check(ms(0), sample(1, Stage::Logic)), None);
assert_eq!(w.check(ms(2_500), sample(2, Stage::Interface)), None);
assert_eq!(w.check(ms(5_000), sample(2, Stage::Interface)), None);
assert_eq!(w.check(ms(5_500), sample(2, Stage::Interface)), Some(Event::Stalled(ms(3_000))));
// A mark inside the stall (a clipboard read ending) is an answer.
assert_eq!(w.check(ms(6_000), sample(3, Stage::Interface)), Some(Event::Answered(ms(3_500))));
}
#[test]
fn the_report_names_the_stage_the_activity_the_commands_and_the_platform() {
let beacon = Beacon::new();
beacon.command("edit.copy");
beacon.command("edit.paste");
beacon.frame(FrameTime { work_ms: 1.24, previous_total_ms: Some(3.5) }, 2);
let s = Sample { step: 9, stage: Stage::Interface, activity: Activity::ClipboardRead };
let text = report(UNIX_EPOCH + Duration::from_secs(1_794_385_145), ms(3_240), s, &beacon, Duration::from_secs(754), &facts());
for want in [
"VectorCraft hang report, 2026-11-11T08:19:05.000Z",
"has not moved on for 3.2 s",
"Stage: running the interface",
"Waiting on: reading the system clipboard",
"Recent commands, oldest first: edit.copy, edit.paste",
"App work per frame (ms), oldest first: 1.2",
"without waiting for the display (ms), oldest first: 3.5",
"Session: running for 754 s, 2 documents open",
"Window system: Wayland; desktop: KDE; session type: wayland; Flatpak: yes",
"Graphics: Test GPU (Vulkan, DiscreteGpu); requested present mode AutoVsync, frame latency 1",
] {
assert!(text.contains(want), "{want:?} missing from:\n{text}");
}
}
#[test]
fn environment_values_lose_control_characters_and_are_cut_short() {
let long = "x".repeat(500);
let env = |name: &str| (name == "XDG_CURRENT_DESKTOP").then(|| format!("A\nB{long}"));
let f = Facts::new(env, false, "X11", None, String::new());
assert_eq!(f.desktop.as_deref().map(str::len), Some(MAX_VALUE_CHARS));
assert!(f.desktop.as_deref().is_some_and(|d| d.starts_with("ABx")));
assert!(!f.flatpak);
assert!(f.lines().contains("Graphics: unknown"));
}
#[test]
fn a_stall_writes_the_report_file_and_its_end_removes_it() {
let dir = tempfile::tempdir().unwrap();
let shared = shared(None);
let beacon = Beacon::new();
let s = sample(4, Stage::Drawing);
let (mut held, open) = (None, AtomicBool::new(false));
record(Event::Stalled(ms(3_000)), s, &beacon, &shared, Some(dir.path()), &mut held, &open, UNIX_EPOCH);
let path = report_path(dir.path());
// Windows refuses reads through another handle while the file is locked: the length is read.
let last = shared.last.lock().unwrap().clone().unwrap_or_default();
assert!(last.contains("Stage: after a frame with input went to the renderer"));
assert_eq!(std::fs::metadata(&path).unwrap().len(), last.len() as u64);
// While the stall lasts, a launch of another instance leaves the file alone.
assert_eq!(take_previous(dir.path()), None);
assert!(path.exists());
record(Event::Answered(ms(4_000)), s, &beacon, &shared, Some(dir.path()), &mut held, &open, UNIX_EPOCH);
assert!(!path.exists());
// This session's report stays for Copy Troubleshooting Info.
assert!(shared.last.lock().unwrap().is_some());
}
#[test]
fn closing_normally_removes_the_report_and_writes_no_more() {
let dir = tempfile::tempdir().unwrap();
let shared = shared(None);
let beacon = Beacon::new();
let (mut held, flag) = (None, AtomicBool::new(false));
record(Event::Stalled(ms(3_000)), sample(4, Stage::Interface), &beacon, &shared, Some(dir.path()), &mut held, &flag, UNIX_EPOCH);
let path = report_path(dir.path());
assert!(path.exists());
// The interface answered after a frame with input, and the app quit before the watching thread
// looked again: saving and teardown are not timed.
beacon.enter(Stage::Drawing);
closing(Some(dir.path()), &flag, &beacon);
assert_eq!(beacon.sample().stage, Stage::Idle);
assert!(!path.exists());
assert_eq!(take_previous(dir.path()), None);
// The watching thread then sees the answer.
record(Event::Answered(ms(3_500)), sample(5, Stage::Idle), &beacon, &shared, Some(dir.path()), &mut held, &flag, UNIX_EPOCH);
assert!(held.is_none());
// A stall the watching thread finds while the app closes goes to the log only.
record(Event::Stalled(ms(3_000)), sample(9, Stage::Interface), &beacon, &shared, Some(dir.path()), &mut held, &flag, UNIX_EPOCH);
assert!(!path.exists());
assert!(held.is_none());
}
#[test]
fn the_next_launch_takes_a_left_report_once_and_keeps_a_copy() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(take_previous(dir.path()), None);
let left = dir.path().join(format!("{REPORT_PREFIX}4242.txt"));
std::fs::write(&left, "VectorCraft hang report, then\n").unwrap();
// Other files in the log folder are not reports.
std::fs::write(dir.path().join(format!("{REPORT_PREFIX}notes.txt")), "x").unwrap();
std::fs::write(dir.path().join(format!("{REPORT_PREFIX}17.txt")), "").unwrap();
assert_eq!(take_previous(dir.path()).as_deref(), Some("VectorCraft hang report, then\n"));
assert!(!left.exists());
assert_eq!(std::fs::read_to_string(dir.path().join(PREVIOUS_FILE)).unwrap(), "VectorCraft hang report, then\n");
assert_eq!(take_previous(dir.path()), None);
// An empty file may be one being written: it stays.
assert!(dir.path().join(format!("{REPORT_PREFIX}17.txt")).exists());
}
#[test]
fn of_several_left_reports_the_newest_is_kept_and_all_are_offered_oldest_first() {
let dir = tempfile::tempdir().unwrap();
for (pid, text, secs) in [(9, "newer\n", 2_000), (10, "older\n", 1_000)] {
let path = dir.path().join(format!("{REPORT_PREFIX}{pid}.txt"));
std::fs::write(&path, text).unwrap();
let file = std::fs::File::options().write(true).open(&path).unwrap();
file.set_modified(UNIX_EPOCH + Duration::from_secs(secs)).unwrap();
}
assert_eq!(take_previous(dir.path()).as_deref(), Some("older\n\nnewer\n"));
assert_eq!(std::fs::read_to_string(dir.path().join(PREVIOUS_FILE)).unwrap(), "newer\n");
}
#[test]
fn a_report_that_cannot_be_moved_is_offered_once() {
let dir = tempfile::tempdir().unwrap();
// Something that is not a file is in the way.
std::fs::create_dir_all(dir.path().join(PREVIOUS_FILE).join("x")).unwrap();
let left = dir.path().join(format!("{REPORT_PREFIX}5.txt"));
std::fs::write(&left, "kept\n").unwrap();
assert_eq!(take_previous(dir.path()).as_deref(), Some("kept\n"));
assert!(!left.exists());
assert_eq!(take_previous(dir.path()), None);
}
#[test]
fn reports_beyond_the_newest_are_removed_not_left_for_a_later_launch() {
let dir = tempfile::tempdir().unwrap();
let count = MAX_REPORT_FILES + 3;
for n in 0..count {
let path = dir.path().join(format!("{REPORT_PREFIX}{}.txt", 100 + n));
std::fs::write(&path, format!("report {n}\n")).unwrap();
let file = std::fs::File::options().write(true).open(&path).unwrap();
file.set_modified(UNIX_EPOCH + Duration::from_secs(1_000 + n as u64)).unwrap();
}
let text = take_previous(dir.path()).unwrap();
assert!(text.starts_with("report 3\n"), "{text}");
assert!(text.ends_with(&format!("report {}\n", count - 1)), "{text}");
assert!(!text.contains("report 2\n"));
assert_eq!(take_previous(dir.path()), None);
let left: Vec<_> = std::fs::read_dir(dir.path()).unwrap().filter_map(Result::ok).map(|e| e.file_name()).collect();
assert_eq!(left, vec![std::ffi::OsString::from(PREVIOUS_FILE)]);
}
#[test]
fn newer_empty_files_do_not_push_out_an_abandoned_report() {
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join(format!("{REPORT_PREFIX}1.txt"));
std::fs::write(&old, "old\n").unwrap();
std::fs::File::options().write(true).open(&old).unwrap().set_modified(UNIX_EPOCH + Duration::from_secs(1_000)).unwrap();
for n in 0..MAX_REPORT_FILES + 1 {
let path = dir.path().join(format!("{REPORT_PREFIX}{}.txt", 100 + n));
std::fs::write(&path, "").unwrap();
std::fs::File::options().write(true).open(&path).unwrap().set_modified(UNIX_EPOCH + Duration::from_secs(2_000)).unwrap();
}
assert_eq!(take_previous(dir.path()).as_deref(), Some("old\n"));
}
#[test]
fn a_file_system_without_locks_does_not_hide_a_report() {
use std::io::{Error, ErrorKind};
assert!(abandoned(Ok(())));
assert!(!abandoned(Err(std::fs::TryLockError::WouldBlock)));
assert!(abandoned(Err(std::fs::TryLockError::Error(Error::from(ErrorKind::Unsupported)))));
// Any other error may hide a live session's lock: the file is left alone.
assert!(!abandoned(Err(std::fs::TryLockError::Error(Error::from(ErrorKind::PermissionDenied)))));
}
#[test]
fn an_oversized_report_file_is_not_read() {
let dir = tempfile::tempdir().unwrap();
let big = vec![b'x'; usize::try_from(MAX_REPORT_BYTES).unwrap() + 1];
let left = dir.path().join(format!("{REPORT_PREFIX}7.txt"));
std::fs::write(&left, big).unwrap();
let text = take_previous(dir.path()).unwrap();
assert!(text.starts_with("The report was larger than"));
assert!(!left.exists());
}
#[test]
fn troubleshooting_info_holds_both_sessions_reports() {
let shared = shared(Some("VectorCraft hang report, last session\n".to_string()));
*shared.last.lock().unwrap() = Some("VectorCraft hang report, this session\n".to_string());
let beacon = Beacon::new();
let text = troubleshooting(&shared, &beacon, UNIX_EPOCH);
assert!(text.starts_with("VectorCraft troubleshooting info, 1970-01-01T00:00:00.000Z\n"));
assert!(text.contains("This session's last hang report:\nVectorCraft hang report, this session\n"));
assert!(text.contains("(it was closed while it did not answer):\nVectorCraft hang report, last session\n"));
assert!(text.contains("Recent commands, oldest first: none"));
}
+515 -15
View File
@@ -1,10 +1,10 @@
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
use super::portal_save;
#[cfg(target_os = "linux")]
use super::tablet;
#[cfg(all(windows, not(target_vendor = "win7")))]
use super::windows_stylus;
use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing};
#[cfg(target_os = "linux")]
use super::{linux_screen_color, tablet};
#[cfg(target_os = "macos")]
use super::{mac_save_format, mac_screen_color, mac_tablet};
@@ -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),
@@ -89,7 +120,6 @@ fn make_folder(request: &PickRequest) {
#[cfg(not(target_os = "macos"))]
#[cfg_attr(windows, allow(unused_variables))]
fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) -> Vec<String> {
make_folder(request);
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
if let PickRequest::Save(pick) = request
&& let Some(answer) = portal_save::pick(pick, parent.as_deref())
@@ -108,7 +138,30 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent)
/// Show the dialog for `request` over `parent` now → the paths picked.
#[cfg(not(target_os = "macos"))]
fn pick_now(request: PickRequest, parent: &Parent) -> Vec<String> {
show_dialog(file_dialog(&request, parent), &request, parent)
let beacon = &vectorcraft_ui_egui::hang_beacon::BEACON;
marked_dialog(beacon, || make_folder(&request), || show_dialog(file_dialog(&request, parent), &request, parent))
}
/// Run `prepare` (making the dialog's folder), then `show`, marked on `beacon` as a dialog: the
/// dialog waits for the user and is not a stall for the hang report (`hang_watch`), while `prepare`
/// is still timed.
#[cfg(not(target_os = "macos"))]
fn marked_dialog<T>(beacon: &vectorcraft_ui_egui::hang_beacon::Beacon, prepare: impl FnOnce(), show: impl FnOnce() -> T) -> T {
prepare();
let _mark = beacon.activity(vectorcraft_ui_egui::hang_beacon::Activity::Dialog);
show()
}
#[cfg(all(test, not(target_os = "macos")))]
#[test]
fn making_a_dialogs_folder_is_timed_and_the_dialog_is_not() {
use vectorcraft_ui_egui::hang_beacon::{Activity, Beacon};
let beacon = Beacon::new();
let mut preparing = None;
let showing = marked_dialog(&beacon, || preparing = Some(beacon.sample().activity), || beacon.sample().activity);
assert_eq!(preparing, Some(Activity::None), "making the folder is timed");
assert_eq!(showing, Activity::Dialog, "the dialog is not");
assert_eq!(beacon.sample().activity, Activity::None, "the mark ends with the dialog");
}
/// macOS shows no dialog in line: its modal loop would run inside winit's event handler, and an
@@ -151,6 +204,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())
@@ -168,6 +261,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
std::thread::Builder::new()
.name("file-dialog".into())
.spawn(move || {
make_folder(&request);
// The app gone meanwhile has no use for the answer.
let _ = tx.send(show_dialog(dialog, &request, &parent));
ui.request_repaint();
@@ -227,13 +321,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();
@@ -255,9 +352,12 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
.as_ref()
.and_then(|w| w.window_handle().ok())
.is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
let (clip, clip_probe) = (parent.clone(), parent.clone());
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
#[cfg(target_os = "macos")]
#[cfg(any(target_os = "macos", target_os = "linux"))]
let sampled_ui = ui.clone();
#[cfg(target_os = "linux")]
let sampled_parent = p1.clone();
Services {
pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())),
pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))),
@@ -276,21 +376,28 @@ 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())),
exists: Some(std::sync::Arc::new(|p: &str| std::path::Path::new(p).exists())),
// Background Save and Export write from a worker thread.
write_shared: Some(std::sync::Arc::new(write_file)),
save_write: Some(std::sync::Arc::new(fileio::write_save_file)),
save_stream: Some(std::sync::Arc::new(fileio::write_save_file_with)),
// Native saves stream into the file as they are encoded.
stream_shared: Some(std::sync::Arc::new(|p: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| {
fileio::write_file_with(p, fill).map_err(|e| e.to_string())
})),
// Every format Copy offers and Paste reads (menu-bar Paste never sees egui's Paste event).
system_clipboard: Some(clipboard::system_clipboard()),
// Its calls are marked for the hang report (`hang_watch`).
system_clipboard: Some(Box::new(vectorcraft_ui_egui::hang_beacon::Marked(clipboard::system_clipboard(clip)))),
// Linux checks whether Paste has something to take on a background thread: an X11 clipboard
// owner that never answers holds a read for up to 4 s. Windows only asks which formats the
// clipboard holds and macOS asks the pasteboard server, so they check in line.
clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(clipboard::system_clipboard) as ClipboardProbeFactory),
// owner that never answers holds a text read for up to 4 s for each format it tries, and
// quitting waits up to `CLIPBOARD_PROBE_STOP_WAIT` for that thread. Windows only asks which
// formats the clipboard holds and macOS asks the pasteboard server, so they check in line.
// The probe's handle is made on its own thread, from the window (`Send`), not its raw display.
clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(move || clipboard::system_clipboard(clip_probe)) as ClipboardProbeFactory),
// Help → Discord / website / GitHub, the Discord button, About and Home links.
open_url: Some(Box::new(|url: &str| {
let _ = webbrowser::open(url);
@@ -298,10 +405,14 @@ 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")]
screen_color: Some(mac_screen_color::sampler(sampled_ui)),
#[cfg(target_os = "linux")]
screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)),
// File → Print: the system's printers and print queue.
print: Some(Box::new(printing::SystemPrint)),
..Default::default()
@@ -332,3 +443,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(&reg).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(&reg).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);
}
}
@@ -0,0 +1,41 @@
//! Linux: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`) through the XDG desktop
//! portal's color sampler ([`portal`]). A thread of its own asks the portal and waits for the
//! person, so the UI keeps drawing; it sends the color to the UI and wakes the window. The dialog's
//! parent is the window, named on that thread as for the portal's save dialog (`portal_save`).
mod portal;
/// The portal's color sampler over the window `parent` holds; `ui` is woken when it answers.
pub fn sampler(ui: egui::Context, parent: super::host_services::Parent) -> vectorcraft_ui_egui::screen_color::StartSampler {
Box::new(move || {
let (tx, rx) = std::sync::mpsc::channel();
let (ui, window) = (ui.clone(), parent.clone());
std::thread::Builder::new()
.name("screen-color".into())
.spawn(move || {
// The thread names the window and holds it until the export that names it is dropped.
let (handle, export) = match window.as_deref() {
Some(window) => {
let (handle, export) = super::portal_save::exported_parent(window);
(handle, Some(export))
}
None => (String::new(), None),
};
let picked = portal::connect(zbus::blocking::connection::Builder::session()).and_then(|conn| portal::pick(&conn, &handle));
drop(export);
drop(window);
let answer = picked.map_err(|failure| {
log::warn!("the portal's screen color sampler gave no color: {}", failure.detail());
failure.message().to_string()
});
// The UI may be gone (the app quitting): nothing waits for the color then.
let _ = tx.send(answer);
ui.request_repaint();
})
.map_err(|e| {
log::warn!("could not start the screen color sampler's thread: {e}");
"the screen color sampler failed".to_string()
})?;
Ok(rx)
})
}
@@ -0,0 +1,291 @@
//! The XDG desktop portal's `Screenshot.PickColor`
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html>):
//! the call returns a request path at once, and the request's `Response` signal later carries the
//! color the person picked, as sRGB components from 0 to 1, or a code for a cancel or another end.
use std::collections::HashMap;
use zbus::blocking::{Connection, Proxy};
use zbus::zvariant::{OwnedValue, Value};
/// How long the portal has to return a request path for `PickColor`. VectorCraft's own limit,
/// 25 seconds as libdbus's default for a method call. The portal returns the path before it shows
/// the sampler, so the person's time with the sampler does not count.
const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);
/// Why no color came back, as the status bar shows it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Failure {
/// No session bus, no portal, or a portal without the Screenshot interface's `PickColor`.
Unavailable(String),
/// The portal did not return a request path in time, or it left the bus before it answered.
NoAnswer(String),
/// The portal ended the request without a color, or its answer can't be read.
Failed(String),
}
impl Failure {
/// The status bar's message (English; the status bar translates it).
pub(super) fn message(&self) -> &'static str {
match self {
Failure::Unavailable(_) => "this system has no screen color sampler",
Failure::NoAnswer(_) => "the screen color sampler did not answer",
Failure::Failed(_) => "the screen color sampler failed",
}
}
/// What went wrong, for the log.
pub(super) fn detail(&self) -> &str {
match self {
Failure::Unavailable(d) | Failure::NoAnswer(d) | Failure::Failed(d) => d,
}
}
}
/// D-Bus errors that mean the session has no portal, or none that answers `PickColor`.
const UNAVAILABLE: &[&str] = &[
"org.freedesktop.DBus.Error.ServiceUnknown",
"org.freedesktop.DBus.Error.NameHasNoOwner",
"org.freedesktop.DBus.Error.UnknownMethod",
"org.freedesktop.DBus.Error.UnknownInterface",
"org.freedesktop.DBus.Error.UnknownObject",
];
/// The connection `builder` makes, with [`CALL_TIMEOUT`] for its method calls.
pub(super) fn connect(builder: zbus::Result<zbus::blocking::connection::Builder<'_>>) -> Result<Connection, Failure> {
builder.and_then(|b| b.method_timeout(CALL_TIMEOUT).build()).map_err(|e| Failure::Unavailable(e.to_string()))
}
/// Shows the portal's color sampler over the window `parent` names and waits for the color, `None`
/// when the person canceled it. `conn`'s method timeout bounds the call; the wait for the person
/// after it has no bound, and ends when the portal answers or leaves the bus.
pub(super) fn pick(conn: &Connection, parent: &str) -> Result<Option<[f32; 3]>, Failure> {
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
let token = crate::portal_request::token("vectorcraft_color").map_err(Failure::Failed)?;
// Made before the call: a portal can send its answer before the call returns.
let replies = crate::portal_request::Responses::new(conn).map_err(Failure::Failed)?;
let proxy = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Screenshot")
.map_err(|e| Failure::Failed(e.to_string()))?;
let options = HashMap::from([("handle_token", Value::from(token.as_str()))]);
let call = proxy.call_method("PickColor", &(parent, options)).map_err(|e| call_failure(&e))?;
let reply = replies.wait(&call).map_err(Failure::NoAnswer)?;
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| Failure::Failed(e.to_string()))?;
answer(code, &results)
}
/// The [`Failure`] for an error the `PickColor` call returned. zbus reports a call that outlives
/// the connection's method timeout as an `InputOutput` error of kind `TimedOut`.
fn call_failure(e: &zbus::Error) -> Failure {
match e {
zbus::Error::MethodError(name, ..) if UNAVAILABLE.contains(&name.as_str()) => Failure::Unavailable(e.to_string()),
zbus::Error::InputOutput(io) if io.kind() == std::io::ErrorKind::TimedOut => Failure::NoAnswer(e.to_string()),
_ => Failure::Failed(e.to_string()),
}
}
/// The color in a `Response` with `code` and `results`: response 0 carries it, 1 is a cancel, and
/// any other code ends the request without one. The components are passed on as given;
/// `screen_color::sampled` clamps them to 0 to 1, as for the other systems' samplers.
fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<[f32; 3]>, Failure> {
match code {
0 => {}
1 => return Ok(None),
_ => return Err(Failure::Failed(format!("the portal ended the request (response {code})"))),
}
let color = results.get("color").ok_or_else(|| Failure::Failed("no color in the portal's answer".into()))?;
// Matched field by field: zvariant's tuple conversion panics on a structure with fewer fields.
match &**color {
Value::Structure(s) => match s.fields() {
[Value::F64(r), Value::F64(g), Value::F64(b)] => Ok(Some([*r, *g, *b].map(|v| v as f32))),
_ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))),
},
_ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::portal_request::test_bus::private_bus;
fn color(rgb: (f64, f64, f64)) -> HashMap<String, OwnedValue> {
HashMap::from([("color".into(), OwnedValue::try_from(Value::from(rgb)).unwrap())])
}
fn failed<T: std::fmt::Debug>(r: Result<T, Failure>) -> bool {
matches!(r, Err(Failure::Failed(_)))
}
#[test]
fn a_picked_color_keeps_its_srgb_values() {
assert_eq!(answer(0, &color((0.25, 0.5, 0.75))), Ok(Some([0.25, 0.5, 0.75])));
assert_eq!(answer(0, &color((0.0, 1.0, 0.0))), Ok(Some([0.0, 1.0, 0.0])));
// Outside 0 to 1: passed on for `screen_color::sampled` to clamp.
assert_eq!(answer(0, &color((-0.5, 1.5, 1.0))), Ok(Some([-0.5, 1.5, 1.0])));
}
#[test]
fn a_cancel_needs_no_color() {
assert_eq!(answer(1, &HashMap::new()), Ok(None));
assert_eq!(answer(1, &color((0.25, 0.5, 0.75))), Ok(None));
}
#[test]
fn other_response_codes_are_failures() {
for code in [2, 3, u32::MAX] {
assert!(failed(answer(code, &color((0.25, 0.5, 0.75)))), "{code}");
}
}
#[test]
fn a_success_without_a_valid_color_is_a_failure() {
assert!(failed(answer(0, &HashMap::new())));
let wrong = HashMap::from([("color".into(), OwnedValue::from(1_u32))]);
assert!(failed(answer(0, &wrong)));
// Fewer fields, more fields, and fields of another type: an error, not a panic.
for wrong in [Value::from((0.5, 0.5)), Value::from((0.5, 0.5, 0.5, 0.5)), Value::from((1_u32, 0.5, 0.5)), Value::from(vec![0.5, 0.5, 0.5])] {
let wrong = HashMap::from([("color".into(), OwnedValue::try_from(wrong).unwrap())]);
assert!(failed(answer(0, &wrong)));
}
}
#[test]
fn call_errors_say_whether_the_system_has_a_sampler() {
let reply = |name: &str| {
let call = zbus::Message::method_call("/org/freedesktop/portal/desktop", "PickColor").unwrap().build(&()).unwrap();
let error = zbus::Message::error(&call.header(), name).unwrap().build(&("detail",)).unwrap();
zbus::Error::from(error)
};
for name in UNAVAILABLE {
assert!(matches!(call_failure(&reply(name)), Failure::Unavailable(_)), "{name}");
}
assert!(matches!(call_failure(&reply("org.freedesktop.portal.Error.NotAllowed")), Failure::Failed(_)));
let timed_out = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::TimedOut.into()));
assert!(matches!(call_failure(&timed_out), Failure::NoAnswer(_)));
let broken = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::BrokenPipe.into()));
assert!(matches!(call_failure(&broken), Failure::Failed(_)));
let messages = [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())].map(|f| f.message());
assert_eq!(
messages,
["this system has no screen color sampler", "the screen color sampler did not answer", "the screen color sampler failed"]
);
assert_eq!(call_failure(&broken).detail(), broken.to_string());
}
/// Every language that translates the sampler's other messages translates these too. The
/// i18n tests of `vectorcraft-ui-egui` do not read this crate's messages.
#[test]
fn the_messages_are_translated_where_the_sampler_is() {
use vectorcraft_ui_egui::i18n::{Lang, message};
const OPEN: &str = "the screen color sampler is already open";
let langs: Vec<Lang> = Lang::all().filter(|&lang| message(lang, OPEN) != OPEN).collect();
assert!(!langs.is_empty(), "no language translates {OPEN:?}");
for lang in langs {
for failure in [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())] {
assert_ne!(message(lang, failure.message()), failure.message(), "{}", lang.code());
}
}
}
/// The client's connection to the private bus at `address`, made as the sampler makes its own.
fn client(address: &str) -> Connection {
connect(zbus::blocking::connection::Builder::address(address)).unwrap()
}
/// The portal's name, owned on the private bus at `address` before any call, so the bus never
/// starts an installed portal in its place.
fn portal(address: &str) -> Connection {
zbus::blocking::connection::Builder::address(address).unwrap().name("org.freedesktop.portal.Desktop").unwrap().build().unwrap()
}
/// Through a real D-Bus: an answer that comes before the call returns is kept; answers on
/// other request paths or from other connections are ignored; a cancel gives no color; and a
/// portal that leaves the bus while the person picks ends the wait.
#[test]
fn the_answer_is_the_portals_response_on_the_returned_path() {
use zbus::blocking::MessageIterator;
use zbus::zvariant::OwnedObjectPath;
let Some((_daemon, address)) = private_bus() else { return };
let address = address.as_str();
let server = portal(address);
let impostor = zbus::blocking::connection::Builder::address(address).unwrap().build().unwrap();
let incoming = MessageIterator::from(&server);
let worker = std::thread::spawn(move || {
let mut calls = Vec::new();
for msg in incoming {
let msg = msg.unwrap();
let header = msg.header();
if header.message_type() != zbus::message::Type::MethodCall || header.member().map(|m| m.as_str()) != Some("PickColor") {
continue;
}
let (parent, options): (String, HashMap<String, OwnedValue>) = msg.body().deserialize().unwrap();
let token = String::try_from(options.get("handle_token").unwrap().try_clone().unwrap()).unwrap();
assert!(token.starts_with("vectorcraft_color_"));
assert!(token.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_'));
assert!(!calls.iter().any(|(_, old)| old == &token));
calls.push((parent, token));
// A portal older than version 0.9 answers on a path of its own, not the token's.
let path = format!("/org/freedesktop/portal/desktop/request/independent/pick_{}", calls.len());
let handle = OwnedObjectPath::try_from(path.as_str()).unwrap();
if calls.len() == 4 {
server.reply(&header, &handle).unwrap();
assert!(server.release_name("org.freedesktop.portal.Desktop").unwrap());
break;
}
let to = header.sender().cloned().map(zbus::names::BusName::from);
// Another connection can't end the wait by claiming the portal left.
impostor
.emit_signal(
to.clone(),
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"NameOwnerChanged",
&("org.freedesktop.portal.Desktop", server.unique_name().unwrap().as_str(), ""),
)
.unwrap();
let wrong = color((1.0, 0.0, 0.0));
impostor.emit_signal(to.clone(), path.as_str(), "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap();
let unrelated = "/org/freedesktop/portal/desktop/request/unrelated";
server.emit_signal(to.clone(), unrelated, "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap();
let code = if calls.len() == 2 { 1_u32 } else { 0_u32 };
server.emit_signal(to, path.as_str(), "org.freedesktop.portal.Request", "Response", &(code, &color((0.25, 0.5, 0.75)))).unwrap();
// The reply that names the path goes last: every answer above came before it.
server.reply(&header, &handle).unwrap();
}
calls
});
let client = client(address);
assert_eq!(pick(&client, "x11:12"), Ok(Some([0.25, 0.5, 0.75])));
assert_eq!(pick(&client, "wayland:example"), Ok(None));
assert_eq!(pick(&client, ""), Ok(Some([0.25, 0.5, 0.75])));
assert!(matches!(pick(&client, ""), Err(Failure::NoAnswer(_))));
let calls = worker.join().unwrap();
assert_eq!(calls.iter().map(|(parent, _)| parent.as_str()).collect::<Vec<_>>(), ["x11:12", "wayland:example", "", ""]);
}
/// Through a real D-Bus: a portal without `PickColor` ends the request as a system without a
/// sampler, and the sampler's connection gives the call [`CALL_TIMEOUT`].
#[test]
fn a_portal_without_pick_color_ends_the_request() {
let Some((_daemon, address)) = private_bus() else { return };
let address = address.as_str();
let server = portal(address);
let incoming = zbus::blocking::MessageIterator::from(&server);
let worker = std::thread::spawn(move || {
for msg in incoming {
let msg = msg.unwrap();
let header = msg.header();
if header.member().map(|m| m.as_str()) == Some("PickColor") {
server.reply_error(&header, "org.freedesktop.DBus.Error.UnknownMethod", &("no PickColor",)).unwrap();
break;
}
}
});
let client = client(address);
assert_eq!(client.method_timeout(), Some(CALL_TIMEOUT));
let failure = pick(&client, "");
assert!(matches!(failure, Err(Failure::Unavailable(_))), "{failure:?}");
worker.join().unwrap();
}
}
+23 -6
View File
@@ -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 {
+139
View File
@@ -0,0 +1,139 @@
//! macOS: the windows' Metal layers are tagged sRGB, so macOS converts what VectorCraft draws to
//! the display's color profile (#2249, #3161).
//!
//! VectorCraft draws sRGB values. Apple's documentation of `CAMetalLayer.colorspace` says: "When a
//! color space is present, Core Animation performs any necessary color space transformations when
//! compositing this content. The default value is `nil`, indicating that the rendered content
//! isn’t color-matched"
//! (<https://developer.apple.com/documentation/quartzcore/cametallayer/colorspace>). Without a
//! color space, a wide-gamut display shows the sRGB values as its own, so `#FF0000` is drawn as
//! the display's most saturated red, brighter than the same color in an exported PNG.
//!
//! wgpu 30 sets the layer's color space to nil each time it configures the surface: at start, on
//! a resize and when the window moves to a display with another scale (gfx-rs/wgpu#10013). egui
//! configures the surface while it paints a frame, after [`eframe::App::ui`] has run, so [`tag`]
//! adds a paint callback that draws nothing. egui calls it after the configuration and before the
//! frame is presented, and it sets sRGB on every window's Metal layer that has no color space. A
//! layer that already has a color space keeps it.
//!
//! Reading a layer's sublayers has no safe API, hence the scoped `unsafe_code` allowance.
#![allow(unsafe_code)]
use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, wgpu};
use objc2::MainThreadMarker;
use objc2::rc::Retained;
use objc2::{DowncastTarget, Message};
use objc2_app_kit::NSApplication;
use objc2_core_graphics::{CGColorSpace, kCGColorSpaceSRGB};
use objc2_quartz_core::{CALayer, CAMetalLayer};
/// Adds the callback that tags the windows' Metal layers to the frame `ui` draws: a point in its
/// top-left corner, in the background layer, with nothing drawn.
pub fn tag(ui: &egui::Ui) {
let ctx = ui.ctx();
let rect = egui::Rect::from_min_size(ctx.content_rect().min, egui::vec2(1.0, 1.0));
ctx.layer_painter(egui::LayerId::background()).add(egui_wgpu::Callback::new_paint_callback(rect, TagLayers));
}
struct TagLayers;
impl CallbackTrait for TagLayers {
fn paint(&self, _: egui::PaintCallbackInfo, _: &mut wgpu::RenderPass<'static>, _: &CallbackResources) {
// AppKit's windows and views are read on the main thread only, where eframe paints.
let Some(mtm) = MainThreadMarker::new() else {
return;
};
for window in NSApplication::sharedApplication(mtm).windows() {
if let Some(root) = window.contentView().and_then(|view| view.layer()) {
for layer in metal_layers(&root) {
tag_srgb(&layer);
}
}
}
}
}
/// The Metal layers that draw a view whose layer is `root`: `root` itself, or the sublayers wgpu
/// adds to it when it is a plain layer.
fn metal_layers(root: &CALayer) -> Vec<Retained<CAMetalLayer>> {
if let Some(layer) = downcast(root) {
return vec![layer];
}
// SAFETY: the returned array is a copy; the layers in it are retained while it lives.
let Some(sublayers) = (unsafe { root.sublayers() }) else {
return Vec::new();
};
sublayers.iter().filter_map(|layer| downcast(&layer)).collect()
}
fn downcast<T: DowncastTarget>(layer: &CALayer) -> Option<Retained<T>> {
layer.retain().downcast::<T>().ok()
}
/// Sets sRGB as `layer`'s color space when it has none. Returns whether it was set.
fn tag_srgb(layer: &CAMetalLayer) -> bool {
if layer.colorspace().is_some() {
return false;
}
// SAFETY: a constant that CoreGraphics exports.
let Some(srgb) = CGColorSpace::with_name(Some(unsafe { kCGColorSpaceSRGB })) else {
return false;
};
layer.setColorspace(Some(&srgb));
true
}
#[cfg(test)]
mod tests {
use objc2_core_foundation::CFString;
use objc2_core_graphics::kCGColorSpaceDisplayP3;
use super::*;
fn space_name(layer: &CAMetalLayer) -> Option<String> {
CGColorSpace::name(layer.colorspace().as_deref()).map(|name| name.to_string())
}
fn name(constant: &CFString) -> String {
constant.to_string()
}
/// A layer without a color space is tagged sRGB once; the second call leaves it as it is.
#[test]
fn an_untagged_layer_becomes_srgb() {
let layer = CAMetalLayer::new();
assert_eq!(space_name(&layer), None, "a new layer has no color space");
assert!(tag_srgb(&layer));
assert_eq!(space_name(&layer), Some(name(unsafe { kCGColorSpaceSRGB })));
assert!(!tag_srgb(&layer));
assert_eq!(space_name(&layer), Some(name(unsafe { kCGColorSpaceSRGB })));
}
/// A layer with a color space of its own keeps it.
#[test]
fn a_layer_with_a_color_space_keeps_it() {
let layer = CAMetalLayer::new();
let p3 = CGColorSpace::with_name(Some(unsafe { kCGColorSpaceDisplayP3 })).unwrap();
layer.setColorspace(Some(&p3));
assert!(!tag_srgb(&layer));
assert_eq!(space_name(&layer), Some(name(unsafe { kCGColorSpaceDisplayP3 })));
}
/// The Metal layer is found as the view's layer or as one of its sublayers, and only Metal
/// layers are returned.
#[test]
fn metal_layers_are_found_under_the_view_layer() {
let metal = CAMetalLayer::new();
assert_eq!(metal_layers(&metal), vec![metal.clone()]);
let root = CALayer::new();
assert!(metal_layers(&root).is_empty());
root.addSublayer(&CALayer::new());
root.addSublayer(&metal);
assert_eq!(metal_layers(&root), vec![metal.clone()]);
for layer in metal_layers(&root) {
tag_srgb(&layer);
}
assert_eq!(space_name(&metal), Some(name(unsafe { kCGColorSpaceSRGB })));
}
}
+238
View File
@@ -0,0 +1,238 @@
//! AppKit delivery of the UI's existing cursor artwork, independent of canvas presentation.
#![forbid(unsafe_code)]
// Interim #2292: remove when pinned winit correctly handles macOS cursor image and hotspot sizing.
use egui::{Context, FullOutput, Plugin, ViewportId};
use objc2::{AllocAnyThread, MainThreadMarker, rc::Retained};
use objc2_app_kit::{NSApplication, NSBitmapImageRep, NSCursor, NSImage, NSWindow};
use objc2_foundation::{NSData, NSPoint, NSSize};
use std::cell::RefCell;
use vectorcraft_ui_egui::cursors::native_request::{self, Bitmap, Key, Request};
const CAPACITY: usize = 128;
fn build(bitmap: &Bitmap) -> Option<Retained<NSCursor>> {
let one = &bitmap.representations[0];
let size = NSSize::new(f64::from(one.size[0]), f64::from(one.size[1]));
let image = NSImage::initWithSize(NSImage::alloc(), size);
for bitmap in &bitmap.representations {
let pixels = image::RgbaImage::from_raw(u32::from(bitmap.size[0]), u32::from(bitmap.size[1]), bitmap.rgba.to_vec())?;
let mut png = std::io::Cursor::new(Vec::new());
pixels.write_to(&mut png, image::ImageFormat::Png).ok()?;
let rep = NSBitmapImageRep::imageRepWithData(&NSData::with_bytes(png.get_ref()))?;
rep.setSize(size);
image.addRepresentation(&rep);
}
Some(NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, NSPoint::new(f64::from(one.hotspot[0]), f64::from(one.hotspot[1]))))
}
/// The ownership protocol also runs against a headless backend in tests.
trait Backend {
type Window: Clone + PartialEq;
type Cursor: Clone + PartialEq;
fn window(&self) -> Option<Self::Window>;
fn enabled(&self, window: &Self::Window) -> bool;
fn suspend(&mut self, window: &Self::Window);
fn restore(&mut self, window: &Self::Window);
fn build(&mut self, request: &Request) -> Option<Self::Cursor>;
fn set(&mut self, cursor: &Self::Cursor);
}
struct State<B: Backend> {
backend: B,
candidate: Option<B::Window>,
cache: Vec<(Key, Option<B::Cursor>)>,
// Retain the active object independently of cache eviction.
active: Option<(Key, B::Window, B::Cursor)>,
}
impl<B: Backend> State<B> {
fn new(backend: B) -> Self {
Self { backend, candidate: None, cache: Vec::new(), active: None }
}
fn begin(&mut self) {
self.candidate = self.backend.window();
}
fn release(&mut self) {
self.candidate = None;
if let Some((_, window, _)) = self.active.take() {
self.backend.restore(&window);
}
}
fn finish(&mut self, request: Option<Request>) {
let window = self.candidate.take().filter(|w| self.backend.window().as_ref() == Some(w));
let (Some(request), Some(window)) = (request, window) else {
self.release();
return;
};
if let Some((key, owned, cursor)) = &self.active
&& *key == request.key
&& *owned == window
{
// AppKit can show the system arrow when the pointer moves while
// `NSCursor.currentCursor` (the app's last set cursor) still reads as ours, so a
// comparison would keep the arrow. Setting the cursor again costs nothing.
self.backend.set(cursor);
return;
}
self.release();
// Never take another component's suspension (a sheet or native tracking session).
if !self.backend.enabled(&window) {
return;
}
let cursor = if let Some((_, cursor)) = self.cache.iter().find(|(key, _)| *key == request.key) {
cursor.clone()
} else {
let cursor = self.backend.build(&request);
if self.cache.len() >= CAPACITY {
self.cache.clear();
}
self.cache.push((request.key, cursor.clone()));
cursor
};
if let Some(cursor) = cursor {
self.backend.suspend(&window);
self.backend.set(&cursor);
self.active = Some((request.key, window, cursor));
}
}
}
#[derive(Default)]
struct AppKit {
root: std::sync::Weak<winit::window::Window>,
}
impl Backend for AppKit {
type Window = Retained<NSWindow>;
type Cursor = Retained<NSCursor>;
fn window(&self) -> Option<Self::Window> {
let mtm = MainThreadMarker::new()?;
// Bind the candidate to the host's actual root window without converting raw pointers.
// A floating native panel may be key while egui still has stale root focus input.
let root = self.root.upgrade()?;
if !root.has_focus() || root.is_visible() == Some(false) || root.is_minimized() == Some(true) {
return None;
}
NSApplication::sharedApplication(mtm).keyWindow().filter(|w| w.isVisible() && w.isKeyWindow())
}
fn enabled(&self, window: &Self::Window) -> bool {
window.areCursorRectsEnabled()
}
fn suspend(&mut self, window: &Self::Window) {
window.disableCursorRects();
}
fn restore(&mut self, window: &Self::Window) {
window.enableCursorRects();
window.resetCursorRects();
// egui-winit may skip an unchanged fallback icon. Rebuild its stored rectangle anyway.
if let Some(view) = window.contentView() {
window.invalidateCursorRectsForView(&view);
}
}
fn build(&mut self, request: &Request) -> Option<Self::Cursor> {
build(&request.bitmap)
}
fn set(&mut self, cursor: &Self::Cursor) {
cursor.set();
}
}
thread_local! { static STATE: RefCell<State<AppKit>> = RefCell::new(State::new(AppKit::default())); }
fn with_state(f: impl FnOnce(&mut State<AppKit>)) {
// All production AppKit access, including restoration, stays on the main thread.
if MainThreadMarker::new().is_some() {
STATE.with(|state| {
if let Ok(mut state) = state.try_borrow_mut() {
f(&mut state);
}
});
}
}
/// Also called synchronously when native menu tracking begins and before process teardown.
pub(crate) fn release() {
with_state(State::release);
}
struct EndedPass {
viewport: ViewportId,
discarded: bool,
request: Option<Request>,
}
struct Delivery {
begin: fn(),
finish: fn(Option<Request>),
release: fn(),
tracking: fn() -> bool,
ended: Vec<EndedPass>,
}
impl Plugin for Delivery {
fn debug_name(&self) -> &'static str {
"macOS canvas cursor"
}
fn on_begin_pass(&mut self, ui: &mut egui::Ui) {
native_request::clear(ui.ctx());
// Floating panels must not acquire or release the main canvas's window.
if ui.ctx().viewport_id() == ViewportId::ROOT {
(self.begin)();
}
}
fn on_end_pass(&mut self, ui: &mut egui::Ui) {
// egui restores the parent viewport before output_hook. Capture this pass here so
// a floating panel's output cannot consume or release its parent's cursor.
self.ended.push(EndedPass { viewport: ui.ctx().viewport_id(), discarded: ui.ctx().will_discard(), request: native_request::take(ui.ctx()) });
}
fn input_hook(&mut self, _: &Context, input: &mut egui::RawInput) {
if input.viewport_id == ViewportId::ROOT
&& (!input.focused || input.viewports.get(&ViewportId::ROOT).is_some_and(|v| v.minimized == Some(true)))
{
(self.release)();
}
}
fn output_hook(&mut self, ctx: &Context, output: &mut FullOutput) {
let Some(ended) = self.ended.pop() else { return };
if ended.viewport != ViewportId::ROOT {
return;
}
if ended.discarded
|| (output.platform_output.requested_discard() && output.platform_output.num_completed_passes < ctx.options(|o| o.max_passes.get()))
{
return;
}
let request = ended.request.filter(|r| {
r.viewport == ended.viewport
&& r.pass.checked_add(1) == Some(ctx.cumulative_pass_nr_for(ended.viewport))
&& ctx.input(|i| i.focused && i.pointer.hover_pos().is_some())
&& output.platform_output.cursor_icon == r.fallback
&& output.platform_output.cursor_image.is_none()
&& !(self.tracking)()
});
// This is BEFORE egui-winit's platform output. In pinned winit, fallback changes update
// the view's stored cursor and invalidate rectangles. Our owned suspension is intended
// to keep that update from replacing the native cursor; native timing needs hand testing.
(self.finish)(request);
}
fn on_exit(&mut self, _: &Context) {
(self.release)();
}
}
pub(crate) fn install(ctx: &Context, window: Option<&std::sync::Arc<winit::window::Window>>) {
with_state(|state| state.backend.root = window.map(std::sync::Arc::downgrade).unwrap_or_default());
ctx.add_plugin(Delivery {
begin: || with_state(State::begin),
finish: |request| with_state(|state| state.finish(request)),
release,
tracking: super::mac_menu::is_tracking,
ended: Vec::new(),
});
}
#[cfg(test)]
mod tests;
+227
View File
@@ -0,0 +1,227 @@
use super::*;
use egui::{CursorIcon, RawInput};
use std::cell::Cell;
#[derive(Default)]
struct Fake {
window: Option<u8>,
suspended: Vec<u8>,
sets: usize,
builds: usize,
restores: Vec<u8>,
fail: bool,
}
impl Backend for Fake {
type Window = u8;
type Cursor = Key;
fn window(&self) -> Option<u8> {
self.window
}
fn enabled(&self, w: &u8) -> bool {
!self.suspended.contains(w)
}
fn suspend(&mut self, w: &u8) {
self.suspended.push(*w);
}
fn restore(&mut self, w: &u8) {
self.suspended.retain(|v| v != w);
self.restores.push(*w);
}
fn build(&mut self, r: &Request) -> Option<Key> {
self.builds += 1;
(!self.fail).then_some(r.key)
}
fn set(&mut self, _: &Key) {
self.sets += 1;
}
}
fn fake_state() -> State<Fake> {
State::new(Fake { window: Some(1), ..Default::default() })
}
fn raw(id: ViewportId, focused: bool) -> RawInput {
let mut input = RawInput { viewport_id: id, focused, events: vec![egui::Event::PointerMoved(egui::pos2(10.0, 10.0))], ..Default::default() };
input.viewports.entry(id).or_default();
input
}
fn publish(ctx: &Context, scale: f32) {
let mut session = vectorcraft_engine::Session::new();
let cursor = session.cursor(Default::default(), Default::default(), Default::default());
let fallback = native_request::request(ctx, cursor, CursorIcon::Default, true, scale);
ctx.set_cursor_icon(fallback);
}
fn request(scale: f32) -> Request {
let ctx = Context::default();
let _ = headless(&ctx, raw(ViewportId::ROOT, true), |ui| publish(ui.ctx(), scale));
native_request::take(&ctx).unwrap()
}
fn deliver(state: &mut State<Fake>, request: Option<Request>) {
state.begin();
state.finish(request);
}
#[test]
fn mac_cursor_ownership_reasserts_every_pass_and_restores() {
let req = request(1.0);
let mut state = fake_state();
deliver(&mut state, Some(req.clone()));
assert_eq!(state.backend.suspended, [1]);
assert_eq!((state.backend.builds, state.backend.sets), (1, 1));
// The pointer moves and AppKit shows the system arrow, but the app's current cursor
// still reads as ours. The next pass sets it again without rebuilding or re-suspending.
deliver(&mut state, Some(req.clone()));
assert_eq!((state.backend.builds, state.backend.sets, state.backend.suspended.len()), (1, 2, 1));
deliver(&mut state, None);
assert_eq!(state.backend.restores, [1]);
deliver(&mut state, Some(req.clone()));
state.backend.window = None;
deliver(&mut state, Some(req.clone()));
assert!(state.active.is_none());
state.backend.window = Some(1);
deliver(&mut state, Some(req.clone()));
state.begin();
state.backend.window = Some(2);
state.finish(Some(req));
assert!(state.active.is_none(), "never acquire a different key window mid-pass");
assert_eq!(state.backend.restores, [1, 1, 1]);
}
#[test]
fn mac_cursor_respects_other_suspensions_failures_and_cache_eviction() {
let mut state = fake_state();
state.backend.suspended.push(1);
deliver(&mut state, Some(request(1.0)));
assert_eq!(state.backend.builds, 0);
state.release();
assert_eq!(state.backend.suspended, [1]);
assert!(state.backend.restores.is_empty());
state.backend.suspended.clear();
state.backend.fail = true;
for _ in 0..2 {
deliver(&mut state, Some(request(1.0)));
}
assert_eq!(state.backend.builds, 1, "cache failed constructions");
state.backend.fail = false;
for i in 1..140 {
deliver(&mut state, Some(request(1.0 + i as f32 / 1000.0)));
}
assert!(state.cache.len() <= CAPACITY);
let active = state.active.unwrap();
state.cache.clear();
assert_eq!(state.active, Some(active));
state.release();
assert!(state.backend.suspended.is_empty());
}
thread_local! {
static FAKE: RefCell<State<Fake>> = RefCell::new(fake_state());
static TRACKING: Cell<bool> = const { Cell::new(false) };
}
fn install_fake(ctx: &Context) {
ctx.add_plugin(Delivery {
begin: || FAKE.with(|s| s.borrow_mut().begin()),
finish: |r| FAKE.with(|s| s.borrow_mut().finish(r)),
release: || FAKE.with(|s| s.borrow_mut().release()),
tracking: || TRACKING.with(Cell::get),
ended: Vec::new(),
});
}
#[test]
fn mac_cursor_plugin_consumes_passes_and_releases_for_menu_focus_and_overrides() {
FAKE.with(|s| *s.borrow_mut() = fake_state());
TRACKING.with(|t| t.set(false));
let ctx = Context::default();
install_fake(&ctx);
install_fake(&ctx);
let root = ViewportId::ROOT;
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
FAKE.with(|s| assert_eq!(s.borrow().backend.sets, 1, "one installed plugin consumes the request"));
let _ = headless(&ctx, raw(ViewportId::from_hash_of("floating-panel"), true), |_| {});
FAKE.with(|s| assert!(s.borrow().active.is_some()));
let _ = headless(&ctx, raw(root, true), |_| {});
FAKE.with(|s| assert!(s.borrow().active.is_none(), "empty pass hands back even an unchanged Default icon"));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
let _ = headless(&ctx, raw(root, true), |ui| {
publish(ui.ctx(), 1.0);
ui.ctx().set_cursor_icon(CursorIcon::Text);
});
FAKE.with(|s| assert!(s.borrow().active.is_none(), "changed-icon handback"));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
// The notification calls release without waiting for another UI pass.
TRACKING.with(|t| t.set(true));
FAKE.with(|s| s.borrow_mut().release());
FAKE.with(|s| assert!(s.borrow().active.is_none()));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
FAKE.with(|s| assert!(s.borrow().active.is_none()));
TRACKING.with(|t| t.set(false));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
let _ = headless(&ctx, raw(root, false), |_| {});
FAKE.with(|s| assert!(s.borrow().active.is_none()));
let _ = headless(&ctx, raw(root, true), |ui| publish(ui.ctx(), 1.0));
FAKE.with(|s| assert!(s.borrow().active.is_some()));
}
#[test]
fn mac_cursor_discarded_pass_does_not_commit_and_installation_does_not_repaint() {
FAKE.with(|s| *s.borrow_mut() = fake_state());
TRACKING.with(|t| t.set(false));
let ctx = Context::default();
install_fake(&ctx);
let mut passes = 0;
let _ = headless(&ctx, raw(ViewportId::ROOT, true), |ui| {
passes += 1;
if passes == 1 {
publish(ui.ctx(), 1.0);
ui.ctx().request_discard("cursor regression");
}
});
assert_eq!(passes, 2);
FAKE.with(|s| assert_eq!(s.borrow().backend.sets, 0));
let idle = || {
let mut input = raw(ViewportId::ROOT, true);
input.events.clear();
input.time = Some(ctx.input(|i| i.time) + 0.1);
input
};
for _ in 0..3 {
let _ = headless(&ctx, idle(), |ui| publish(ui.ctx(), 1.0));
}
let out = headless(&ctx, idle(), |ui| publish(ui.ctx(), 1.0));
assert!(out.viewport_output[&ViewportId::ROOT].repaint_delay > std::time::Duration::ZERO);
}
#[test]
fn mac_cursor_appkit_representations_have_pixel_sizes_and_point_hotspots() {
// Only construct and inspect image/cursor objects: no NSApplication, window or cursor.set().
for scale in [0.75, 1.0, 1.25, 1.5, 2.0] {
let request = request(scale);
let cursor = build(&request.bitmap).unwrap();
let image = cursor.image();
let one = &request.bitmap.representations[0];
let size = NSSize::new(f64::from(one.size[0]), f64::from(one.size[1]));
assert_eq!(image.size(), size);
assert_eq!(cursor.hotSpot(), NSPoint::new(f64::from(one.hotspot[0]), f64::from(one.hotspot[1])));
let reps = image.representations();
assert_eq!(reps.len(), 2);
let mut dimensions: Vec<_> = reps
.iter()
.map(|rep| {
assert_eq!(rep.size(), size);
(rep.pixelsWide(), rep.pixelsHigh())
})
.collect();
dimensions.sort_unstable();
assert_eq!(
dimensions,
[
(isize::try_from(one.size[0]).unwrap(), isize::try_from(one.size[1]).unwrap()),
(isize::try_from(one.size[0]).unwrap() * 2, isize::try_from(one.size[1]).unwrap() * 2)
]
);
}
}
fn headless(ctx: &egui::Context, input: egui::RawInput, draw: impl FnMut(&mut egui::Ui)) -> egui::FullOutput {
let mut output = ctx.run_ui(input, draw);
output.textures_delta.clear();
output
}
+2 -4
View File
@@ -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);
}
}
+18 -2
View File
@@ -30,6 +30,13 @@ use vectorcraft_ui_egui::native_menu::{self, Backend, Event, MenuBar, MenuRole,
// AppKit can deliver window input while its system menu is still tracking (especially with
// asynchronous menu presentation). Keep the native tracking state separate from egui popups.
static TRACKING: AtomicBool = AtomicBool::new(false);
/// A tracking session began since the last [`Backend::drain`], which reports it as
/// [`Event::Opened`].
static OPENED: AtomicBool = AtomicBool::new(false);
pub(crate) fn is_tracking() -> bool {
TRACKING.load(Ordering::Relaxed)
}
fn observe_tracking(ctx: &egui::Context) {
static INSTALL: Once = Once::new();
@@ -41,13 +48,19 @@ fn observe_tracking(ctx: &egui::Context) {
let repaint = ctx.clone();
let block = RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
TRACKING.store(tracking, Ordering::Relaxed);
// Apply any deferred menu updates as soon as the tracking session ends.
if tracking {
OPENED.store(true, Ordering::Relaxed);
super::mac_cursor::release();
}
// Report the opened menu and apply any deferred menu updates as soon as the
// tracking session ends.
if !tracking {
repaint.request_repaint();
}
});
// SAFETY: these are AppKit's notification names. The notification center retains
// the observer and block for the application's lifetime; callbacks update an atomic and request repaint.
// the observer and block for the application's lifetime; callbacks update tracking, restore
// owned cursor rectangles and request repaint.
#[allow(unsafe_code)]
unsafe {
NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock(Some(name), None, None, &block);
@@ -259,6 +272,9 @@ impl Backend for MacMenu {
fn drain(&mut self) -> Vec<Event> {
let mut out = Vec::new();
if OPENED.swap(false, Ordering::Relaxed) {
out.push(Event::Opened);
}
while let Ok(chosen) = self.rx.try_recv() {
cancel_tracking();
// Ids that aren't ours are AppKit's own items (Services, Zoom…), already handled.
+58 -11
View File
@@ -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() {
+116 -21
View File
@@ -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");
}
+243 -50
View File
@@ -1,7 +1,13 @@
//! VectorCraft desktop app.
//!
//! Usage: `vectorcraft [--control <port> [--automation-read-root <dir>]... [--automation-write-root <dir>]...]
//! [--in-window-menus] [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`).
//!
//! `--in-window-menus` (or `VECTORCRAFT_IN_WINDOW_MENUS=1`) keeps the menus inside the window on
//! macOS instead of the macOS menu bar (`mac_menu`).
@@ -16,16 +22,25 @@
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
mod automation_args;
mod caps_lock;
mod clipboard;
#[cfg(feature = "wgpu")]
mod compositor_gpu;
mod control_server;
mod cursor_theme;
mod display_profile;
#[cfg(feature = "wgpu")]
mod gpu;
mod hang_watch;
#[cfg(target_os = "linux")]
mod linux_screen_color;
#[cfg(target_os = "linux")]
mod linux_stylus;
mod logging;
#[cfg(all(target_os = "macos", feature = "wgpu"))]
mod mac_color_space;
#[cfg(target_os = "macos")]
mod mac_cursor;
#[cfg(target_os = "macos")]
mod mac_fonts;
#[cfg(target_os = "macos")]
@@ -39,21 +54,31 @@ mod mac_tablet;
mod mac_window;
#[cfg(target_os = "macos")]
mod open_documents;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
mod portal_request;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))]
mod portal_save;
mod prefs_dir;
mod printing;
#[cfg(not(any(target_os = "macos", windows)))]
mod quit_windows;
#[cfg(not(target_os = "macos"))]
mod single_instance;
#[cfg(windows)]
mod system_fonts;
mod tablet;
mod window;
mod window_frame;
mod windows_alt_codes;
#[cfg(windows)]
mod windows_cores;
mod windows_stylus;
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};
@@ -66,7 +91,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};
@@ -81,10 +106,13 @@ 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, caption_layout_from, opted_into_app_title_bar, start_frame, system_title_bar_applies};
use titlebar::{custom_titlebar, native_options, titlebar_from_env};
struct App {
app: VectorcraftApp,
host_caps_lock: caps_lock::HostCapsLock,
/// Reported by wgpu when the window's graphics device is lost (a driver reset).
graphics_loss: GraphicsLoss,
/// The graphics device was lost and the unsaved changes are kept for Data Recovery.
@@ -93,12 +121,21 @@ struct App {
frames: u64,
/// Keeps the custom title bar's window borderless (Windows, #1758).
window_frame: Option<window_frame::WindowFrameFn>,
/// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635).
/// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635),
/// and to take the window off screen on quit before the clipboard handles let go (`quit_windows`).
winit_window: Option<std::sync::Arc<winit::window::Window>>,
/// A saved or fitted geometry asked for maximize once the window is mapped (Linux).
pending_maximize: bool,
/// Frames left to retry [`window::apply_pending_maximize`].
maximize_tries: u8,
/// 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)>,
/// Reads the profile of the display that shows the main window, for the canvas.
display_profile: display_profile::Reader,
/// When this frame's input hook started, for the hang report's frame times (`hang_watch`).
frame_start: Option<std::time::Instant>,
}
/// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s.
@@ -116,17 +153,95 @@ Options:
(may be given more than once)
--in-window-menus Keep the menus inside the window on macOS
(or VECTORCRAFT_IN_WINDOW_MENUS=1)
--version Print the version and exit
--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)]
if let Some(result) = craft_update::self_update::finish(&craft_update::suite::VECTORCRAFT, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if let Some(result) = craft_update::self_update::finish(&vectorcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
std::process::exit(i32::from(result.is_err()));
}
// Before any thread starts: the pointer must find a cursor theme on Wayland (#2450).
@@ -138,35 +253,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 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,
"--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 {
@@ -181,7 +272,19 @@ fn main() -> std::process::ExitCode {
};
// Before desktop services, so every start-up warning is recorded (`logging`).
let logger = logging::install();
// 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"))]
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) => single_instance::hold(primary),
}
#[cfg(target_os = "macos")]
let _ = new_instance;
vectorcraft_ui_egui::i18n::detect_system_lang_in_background();
// Before the first render: the cores the process may run on.
#[cfg(windows)]
windows_cores::install();
// Before the first font scan (the app's start): the fonts font services load (#579).
#[cfg(windows)]
system_fonts::install();
@@ -203,6 +306,11 @@ fn main() -> std::process::ExitCode {
None => logger.no_file(),
}
}
// The report a session left when it was closed while it did not answer (`hang_watch`).
let previous_hang = log_dir().filter(|_| prefs_enabled()).and_then(|dir| hang_watch::take_previous(&dir));
if let Some(report) = &previous_hang {
log::warn!("the last session was closed while it did not answer; its report:\n{}", report.trim_end());
}
// The roots confine the control channel: a bad one keeps the app from starting rather than
// leaving agents unconfined. Without a control port there is nothing to confine.
let roots = if control_port.is_none() {
@@ -259,19 +367,22 @@ fn main() -> std::process::ExitCode {
};
#[cfg(feature = "wgpu")]
let crash = left_out.crash.clone();
let custom_titlebar = custom_titlebar(saved.as_ref());
let (custom_titlebar, caption_layout) = custom_titlebar(saved.as_ref());
let options = native_options(custom_titlebar);
// winit picks Wayland whenever `WAYLAND_DISPLAY` is set; Preferences › Performance › Linux
// Display Server › X11 opens the window through XWayland instead, where file drops work (#1151),
// and X11 (XWayland) When a Pen Is Attached does so when a pen is attached, where the pen draws (#2028).
// and the other choices do so when a pen is attached, where the pen draws (#2028, #4967).
#[cfg(target_os = "linux")]
let mut forced_to_x11 = false;
#[cfg(target_os = "linux")]
let options = {
let mut options = options;
let pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str);
if xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) {
if xwayland::x11_libraries_found() {
if pref == Some("x11WithPen") {
log::info!("pen found: opening the window through XWayland (Preferences › Performance › Linux Display Server)");
forced_to_x11 = true;
if pref != Some("x11") {
log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)");
} else {
log::info!("opening the window through XWayland (Preferences › Performance › Linux Display Server)");
}
@@ -285,18 +396,32 @@ fn main() -> std::process::ExitCode {
}
options
};
#[cfg(not(target_os = "linux"))]
let forced_to_x11 = false;
// Preferences › User Interface notes under System Title Bar when the desktop draws the frame
// with it on or off.
let desktop_keeps_frame = titlebar::desktop_keeps_frame(forced_to_x11);
// 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
};
// Quitting takes the X11 windows of floating panels and documents off screen with the main
// window, so eframe's windows are recorded as it makes and drops them (`quit_windows`).
#[cfg(target_os = "linux")]
let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(quit_windows::Hooks)), ..options };
#[cfg(feature = "wgpu")]
let options = {
let mut options = options;
@@ -311,21 +436,23 @@ fn main() -> std::process::ExitCode {
// Metal on an Iris Pro, #651). `WGPU_VALIDATION_INDIRECT_CALL=1` turns it back on.
create.instance_descriptor.flags =
(eframe::wgpu::InstanceFlags::from_build_config() - eframe::wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL).with_env();
create.instance_descriptor.backends =
left_out.backends(gpu::backends(create.instance_descriptor.backends, std::env::var_os("WGPU_BACKEND").is_some()));
let env_set = std::env::var_os("WGPU_BACKEND").is_some();
let opengl = cfg!(windows) && !env_set && gpu::windows_opengl(&left_out);
create.instance_descriptor.backends = left_out.backends(gpu::backends(create.instance_descriptor.backends, env_set, opengl));
// DX12 shaders compile with FXC, part of Windows: wgpu's default loads whichever
// dxcompiler.dll the search path finds, and one without its dxil.dll fails every shader,
// losing the device before the first frame (#1194). `WGPU_DX12_COMPILER` picks another.
create.instance_descriptor.backend_options.dx12.shader_compiler =
eframe::wgpu::Dx12Compiler::from_env().unwrap_or(eframe::wgpu::Dx12Compiler::Fxc);
// The window's surface may be as large as the adapter allows, not eframe's fixed
// 8192 px: a window stretched over several monitors, or grown by a display scale
// change, otherwise fails to configure its surface and the app closes (#1459).
// The device asks for no more than the adapter offers, so a GPU short of one of
// eframe's limits still gets a device (#2105). The window's surface may be as large as
// the adapter allows, not eframe's fixed 8192 px: a window stretched over several
// monitors, or grown by a display scale change, otherwise fails to configure its
// surface and the app closes (#1459).
let device = create.device_descriptor.clone();
create.device_descriptor = std::sync::Arc::new(move |adapter: &eframe::wgpu::Adapter| {
let mut descriptor = device(adapter);
let limit = &mut descriptor.required_limits.max_texture_dimension_2d;
*limit = gpu::surface_limit(*limit, adapter.limits().max_texture_dimension_2d);
descriptor.required_limits = gpu::device_limits(descriptor.required_limits, &adapter.limits());
descriptor
});
}
@@ -340,6 +467,9 @@ fn main() -> std::process::ExitCode {
open_documents::install();
#[cfg(feature = "wgpu")]
let created = startup.clone();
// For the hang report (`hang_watch`).
#[cfg(feature = "wgpu")]
let requested_surface = options.wgpu_options.surface;
// A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash.
let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| {
#[cfg(target_os = "linux")]
@@ -359,13 +489,27 @@ 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);
// Then Edit › Color Settings, which may name one of those profiles.
prefs_dir::attach_color_settings(&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);
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
prefs_dir::attach_scripts_dir(&mut session);
prefs_dir::attach_new_doc_profiles(&mut session);
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
app.set_startup_update_check(true);
load_prefs(&mut app, saved);
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);
// The custom dictionary's words, kept in their own file next to the preferences.
prefs_dir::attach_custom_dictionary(&mut app.session);
// The custom arrowheads, kept in their own file next to the preferences.
prefs_dir::attach_arrowheads(&mut app.session);
// Fit the window to its monitor, or put it back where it was (still hidden).
let winit_window = cc.winit_window().cloned();
if let Some(w) = &winit_window {
@@ -429,7 +573,41 @@ fn main() -> std::process::ExitCode {
let (loss, ctx) = (graphics_loss.clone(), cc.egui_ctx.clone());
rs.device.set_device_lost_callback(move |reason, msg| loss.report(&ctx, format!("{reason:?}: {msg}")));
}
// The hang report and Help › Copy Troubleshooting Info (`hang_watch`).
// The surface settings the options asked for; the driver resolves the present mode.
#[cfg(feature = "wgpu")]
let surface = cc
.wgpu_render_state
.as_ref()
.map(|_| (format!("{:?}", requested_surface.present_mode), requested_surface.desired_maximum_frame_latency));
#[cfg(not(feature = "wgpu"))]
let surface = None;
let hang = std::sync::Arc::new(hang_watch::Shared {
facts: hang_watch::Facts::new(
|name| std::env::var(name).ok(),
std::path::Path::new("/.flatpak-info").exists(),
hang_watch::window_system(winit_window.as_deref()),
app.graphics_adapter.clone(),
hang_watch::surface(surface),
),
started: std::time::Instant::now(),
last: std::sync::Mutex::new(None),
previous: previous_hang.clone(),
});
vectorcraft_ui_egui::hang_beacon::watch_input(&vectorcraft_ui_egui::hang_beacon::BEACON, &cc.egui_ctx);
hang_watch::start(log_dir().filter(|_| prefs_enabled()), hang.clone());
app.services.troubleshooting = Some(Box::new(move || {
hang_watch::troubleshooting(&hang, &vectorcraft_ui_egui::hang_beacon::BEACON, std::time::SystemTime::now())
}));
// A message about the graphics processor, or a stopped plug-in, comes first.
if previous_hang.is_some() && app.ui.status.is_empty() {
vectorcraft_ui_egui::troubleshooting::last_session_stopped(&mut app);
}
app.titlebar_from_env = titlebar_from_env();
app.custom_titlebar = custom_titlebar;
app.caption_layout = caption_layout;
app.desktop_frame = !custom_titlebar;
app.desktop_keeps_frame = desktop_keeps_frame;
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());
@@ -447,17 +625,22 @@ fn main() -> std::process::ExitCode {
if !in_window_menus {
app.services.native_menu = mac_menu::install(&cc.egui_ctx, &app);
}
mac_cursor::install(&cc.egui_ctx, winit_window.as_ref());
}
#[cfg(not(target_os = "macos"))]
let _ = in_window_menus;
{
let _ = in_window_menus;
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();
// The content and the pointer stay aligned on Windows (#1758).
let window_frame = window_frame::service(cc, custom_titlebar);
Ok(Box::new(App {
host_caps_lock: caps_lock::HostCapsLock::new(winit_window.as_deref()),
app,
graphics_loss,
graphics_lost: false,
@@ -466,10 +649,20 @@ fn main() -> std::process::ExitCode {
winit_window,
pending_maximize,
maximize_tries: 8,
held_files,
monitors_listed: None,
display_profile: Default::default(),
frame_start: None,
}))
}),
)
});
// The window is gone: later launches start their own app, including the one a graphics
// failure starts again below.
#[cfg(not(target_os = "macos"))]
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"))]
+231
View File
@@ -0,0 +1,231 @@
//! Linux and the BSDs: the answer to an XDG desktop portal request
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Request.html>),
//! for the save dialog (`portal_save`) and, on Linux, the screen color sampler
//! (`linux_screen_color`). The wait ends with the request's `Response`, or with an error when the
//! portal leaves the bus first.
use futures_lite::{StreamExt as _, future};
use zbus::blocking::{Connection, MessageIterator};
use zbus::zvariant::OwnedObjectPath;
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
/// A request token: `prefix`, then 128 bits from the operating system's random device, so the
/// token is unique and can't be guessed, as the Request documentation asks.
#[cfg(target_os = "linux")]
pub(crate) fn token(prefix: &str) -> Result<String, String> {
use std::io::Read as _;
let mut bytes = [0; 16];
std::fs::File::open("/dev/urandom")
.and_then(|mut file| file.read_exact(&mut bytes))
.map_err(|e| format!("could not create a portal request token: {e}"))?;
let random: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
Ok(format!("{prefix}_{random}"))
}
/// Subscriptions made before a portal method call, on every request path: a portal older than
/// version 0.9 ignores `handle_token` and answers on the request path it returns, and its answer
/// can come before the call's reply. Each stream keeps every signal from the time it is made.
pub(crate) struct Responses {
replies: MessageIterator,
owners: MessageIterator,
}
impl Responses {
pub(crate) fn new(conn: &Connection) -> Result<Self, String> {
let reply_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender(DESKTOP)
.and_then(|b| b.interface("org.freedesktop.portal.Request"))
.and_then(|b| b.member("Response"))
.map_err(|e| e.to_string())?
.build();
let owner_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender("org.freedesktop.DBus")
.and_then(|b| b.path("/org/freedesktop/DBus"))
.and_then(|b| b.interface("org.freedesktop.DBus"))
.and_then(|b| b.member("NameOwnerChanged"))
.and_then(|b| b.arg(0, DESKTOP))
.map_err(|e| e.to_string())?
.build();
Ok(Self {
replies: MessageIterator::for_match_rule(reply_rule, conn, None).map_err(|e| e.to_string())?,
owners: MessageIterator::for_match_rule(owner_rule, conn, None).map_err(|e| e.to_string())?,
})
}
/// The `Response` on the request path `call` returned, from the connection that returned it.
/// An error when that connection leaves the bus first, or the bus connection closes. A
/// `Response` the portal sent before it left is still the answer.
pub(crate) fn wait(self, call: &zbus::Message) -> Result<zbus::Message, String> {
enum Event {
Reply(Option<zbus::Result<zbus::Message>>),
Owner(Option<zbus::Result<zbus::Message>>),
}
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
let portal = call.header().sender().map(|s| s.as_str().to_string()).ok_or("the portal answered without a sender")?;
let answers = |reply: &zbus::Message| {
let header = reply.header();
header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == Some(portal.as_str())
};
let mut replies = self.replies.into_inner();
let mut owners = self.owners.into_inner();
future::block_on(async {
loop {
let event = future::or(async { Event::Owner(owners.next().await) }, async { Event::Reply(replies.next().await) }).await;
match event {
Event::Reply(reply) => {
let reply = reply.ok_or("the portal closed without an answer")?.map_err(|e| e.to_string())?;
if answers(&reply) {
return Ok(reply);
}
}
Event::Owner(message) => {
let message = message.ok_or("the portal connection closed")?.map_err(|e| e.to_string())?;
if owner_disappeared(&message, &portal)? {
// zbus puts each message in every matching stream before it reads the
// next one, so a `Response` that came before the bus's report is
// already queued: it is still the answer.
while let Some(Some(reply)) = future::poll_once(replies.next()).await {
if let Ok(reply) = reply
&& answers(&reply)
{
return Ok(reply);
}
}
return Err("the desktop portal disappeared while waiting for its answer".into());
}
}
}
}
})
}
}
/// Whether `message` is the bus's `NameOwnerChanged` saying that the connection `portal` no longer
/// owns the portal's name. The bus itself must send it: another connection can't end the wait.
fn owner_disappeared(message: &zbus::Message, portal: &str) -> Result<bool, String> {
if message.header().sender().map(|s| s.as_str()) != Some("org.freedesktop.DBus") {
return Ok(false);
}
let (name, old, new): (String, String, String) = message.body().deserialize().map_err(|e| e.to_string())?;
Ok(name == DESKTOP && old == portal && new != portal)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_bus_can_report_portal_owner_loss() {
let changed = |sender, name, old, new| {
zbus::Message::signal("/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged")
.unwrap()
.sender(sender)
.unwrap()
.build(&(name, old, new))
.unwrap()
};
let forged = changed(":1.42", DESKTOP, ":1.7", "");
assert!(!owner_disappeared(&forged, ":1.7").unwrap());
let real = changed("org.freedesktop.DBus", DESKTOP, ":1.7", "");
assert!(owner_disappeared(&real, ":1.7").unwrap());
let other = changed("org.freedesktop.DBus", "org.example.Other", ":1.7", "");
assert!(!owner_disappeared(&other, ":1.7").unwrap());
let old = changed("org.freedesktop.DBus", DESKTOP, ":1.8", "");
assert!(!owner_disappeared(&old, ":1.7").unwrap());
let acquired = changed("org.freedesktop.DBus", DESKTOP, "", ":1.7");
assert!(!owner_disappeared(&acquired, ":1.7").unwrap());
}
/// Through a real D-Bus: when the bus has reported the portal gone, a `Response` the portal sent
/// before it left is still the answer; without one the wait ends with an error.
#[test]
fn a_queued_answer_wins_over_the_portal_leaving() {
use std::collections::HashMap;
use zbus::blocking::connection::Builder;
use zbus::zvariant::OwnedValue;
for answered in [true, false] {
let Some((_daemon, address)) = test_bus::private_bus() else { return };
let address = address.as_str();
let portal = Builder::address(address).unwrap().name(DESKTOP).unwrap().build().unwrap();
let unique = portal.unique_name().unwrap().to_string();
let client = Builder::address(address).unwrap().build().unwrap();
let responses = Responses::new(&client).unwrap();
// zbus puts each message in every matching stream before it reads the next one
// (`src/connection/socket_reader.rs`), so once this stream has the bus's report,
// `responses` holds the `Response` sent before it.
let gone_rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender("org.freedesktop.DBus")
.unwrap()
.member("NameOwnerChanged")
.unwrap()
.arg(0, DESKTOP)
.unwrap()
.build();
let gone = MessageIterator::for_match_rule(gone_rule, &client, None).unwrap();
let path = "/org/freedesktop/portal/desktop/request/test/t1";
if answered {
let results = HashMap::<String, OwnedValue>::new();
portal.emit_signal(None::<&str>, path, "org.freedesktop.portal.Request", "Response", &(0_u32, results)).unwrap();
}
portal.close().unwrap();
// On a thread of its own, so a report that never comes fails the test instead of
// hanging it.
let (seen, report) = std::sync::mpsc::channel();
let left = unique.clone();
std::thread::spawn(move || {
let mut gone = gone;
let _ = seen.send(gone.any(|m| m.is_ok_and(|m| owner_disappeared(&m, &left).unwrap_or(false))));
});
assert_eq!(report.recv_timeout(std::time::Duration::from_secs(30)), Ok(true), "the bus did not report the portal gone");
// The call's reply as `wait` reads it: the request path, from the portal's connection.
let call = zbus::Message::signal("/", "org.example.Test", "Reply")
.unwrap()
.sender(unique.as_str())
.unwrap()
.build(&OwnedObjectPath::try_from(path).unwrap())
.unwrap();
let waited = responses.wait(&call);
assert_eq!(waited.is_ok(), answered, "{waited:?}");
}
}
}
/// The private session bus that the D-Bus tests of the portal requests run on.
#[cfg(test)]
pub(crate) mod test_bus {
/// A session bus of its own (`dbus-daemon`), `None` when there is none to run.
pub(crate) fn private_bus() -> Option<(Daemon, String)> {
use std::io::BufRead as _;
let spawning = crate::spawning();
let daemon = std::process::Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(std::process::Stdio::piped())
.spawn();
drop(spawning);
let Ok(daemon) = daemon else {
eprintln!("no dbus-daemon: skipped");
return None;
};
let mut daemon = Daemon(daemon);
let mut address = String::new();
std::io::BufReader::new(daemon.0.stdout.take().unwrap()).read_line(&mut address).unwrap();
Some((daemon, address.trim().to_string()))
}
/// Stops the private bus when the test ends, unwinding included.
pub(crate) struct Daemon(std::process::Child);
impl Drop for Daemon {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
}
+127 -63
View File
@@ -8,6 +8,7 @@
//! ([`vectorcraft_ui_egui::picks::PickAnswer`]); the app gives the name that type's extension.
//! rfd shows the dialog when the portal can't (no session bus, no file chooser), with zenity as its
//! own fallback. PhotoCraft's `portal_save.rs` (storytold/photocraft#6151) makes the same call.
//! rfd also shows the dialog when the portal leaves the bus before it answers.
//!
//! The dialog's parent is the window: `x11:<window id>` on X11, and on Wayland (Linux) a handle
//! from the compositor's xdg-foreign protocol, as rfd names it (its `window_identifier`).
@@ -96,16 +97,31 @@ 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}"))?;
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)
});
// 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| filter_label(v));
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> {
/// The label of a file type as the portal sends it, a `(sa(us))` structure; `None` for a value of
/// another shape.
fn filter_label(value: &Value<'_>) -> Option<String> {
match value {
Value::Structure(s) => match s.fields() {
[Value::Str(label), Value::Array(globs)] if globs.element_signature() == "(us)" => Some(label.to_string()),
_ => None,
},
_ => None,
}
}
/// `file:///home/me/A%20b.svg` → `/home/me/A b.svg` (its bytes); `None` for a file elsewhere
/// (`file://host/`) or another scheme.
fn file_uri_path(uri: &str) -> Option<Vec<u8>> {
let rest = uri.strip_prefix("file://")?;
let rest = rest.strip_prefix("localhost").unwrap_or(rest);
if !rest.starts_with('/') {
@@ -126,8 +142,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
@@ -169,37 +184,18 @@ pub fn pick(pick: &FilePick, window: Option<&winit::window::Window>) -> Option<V
fn save_file(conn: &zbus::blocking::Connection, request: &SaveRequest) -> Result<Option<Saved>, String> {
use std::sync::atomic::{AtomicU32, Ordering};
use zbus::blocking::{MessageIterator, Proxy};
use zbus::zvariant::OwnedObjectPath;
use zbus::blocking::Proxy;
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
const REQUEST: &str = "org.freedesktop.portal.Request";
static NEXT: AtomicU32 = AtomicU32::new(0);
let token = format!("vectorcraft_save_{}_{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed));
// Listen before asking, on every request path: a portal older than version 0.9 ignores
// `handle_token` and answers on the request path it returns, and its answer can come before
// the call's reply. The stream keeps every `Response` from the time it is made.
let rule = zbus::MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender(DESKTOP)
.and_then(|b| b.interface(REQUEST))
.and_then(|b| b.member("Response"))
.map_err(|e| e.to_string())?
.build();
let responses = MessageIterator::for_match_rule(rule, conn, None).map_err(|e| e.to_string())?;
// Made before the call: a portal can send its answer before the call returns, and a portal
// that leaves the bus while its dialog is open ends the wait.
let responses = crate::portal_request::Responses::new(conn)?;
let chooser = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.FileChooser").map_err(|e| e.to_string())?;
// The title is empty, as rfd sends it for a save.
let call = chooser.call_method("SaveFile", &(request.parent.as_str(), "", options(request, &token))).map_err(|e| e.to_string())?;
let handle: OwnedObjectPath = call.body().deserialize().map_err(|e| e.to_string())?;
// The answer is the `Response` on the path returned, from the connection that returned it.
let portal = call.header().sender().map(|s| s.as_str().to_string());
let reply = responses
.filter_map(Result::ok)
.find(|m| {
let header = m.header();
header.path().map(|p| p.as_str()) == Some(handle.as_str()) && header.sender().map(|s| s.as_str()) == portal.as_deref()
})
.ok_or("the save dialog closed without an answer")?;
let reply = responses.wait(&call)?;
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| e.to_string())?;
answer(code, &results)
}
@@ -228,6 +224,13 @@ fn parent(window: &winit::window::Window) -> (String, Option<wayland::Export>) {
}
}
/// [`parent`] for another dialog of the portal (the screen color sampler, `linux_screen_color`):
/// the identifier stays valid until the second value is dropped.
#[cfg(target_os = "linux")]
pub(crate) fn exported_parent(window: &winit::window::Window) -> (String, impl Send + 'static) {
parent(window)
}
/// The portal's identifier of `window`: its X11 id, else empty (no Wayland export is made off
/// Linux).
#[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
@@ -239,7 +242,7 @@ fn parent(window: &winit::window::Window) -> (String, Option<()>) {
/// (<https://wayland.app/protocols/xdg-foreign-unstable-v2>), made as rfd's `window_identifier`
/// makes it.
#[cfg(target_os = "linux")]
mod wayland {
pub(crate) mod wayland {
use wayland_client::globals::{GlobalListContents, registry_queue_init};
use wayland_client::protocol::wl_registry::{self, WlRegistry};
use wayland_client::protocol::wl_surface::WlSurface;
@@ -305,9 +308,10 @@ mod wayland {
}
}
/// `window`'s Wayland connection and surface, from its raw handles.
/// `window`'s Wayland connection and surface, from its raw handles. The caller holds `window`
/// while it uses them (`quit_windows` unmaps the main window's surface through them).
#[allow(unsafe_code)]
fn surface(window: &winit::window::Window) -> Option<(Connection, WlSurface)> {
pub(crate) fn surface(window: &winit::window::Window) -> Option<(Connection, WlSurface)> {
use wayland_backend::sys::client::{Backend, ObjectId};
use winit::raw_window_handle::{HasDisplayHandle as _, HasWindowHandle as _, RawDisplayHandle, RawWindowHandle};
let (RawWindowHandle::Wayland(w), RawDisplayHandle::Wayland(d)) =
@@ -316,8 +320,8 @@ mod wayland {
return None;
};
// SAFETY: the display is winit's open `wl_display`, which outlives `window` (the caller
// holds it until the export is dropped); a backend made from a foreign display does not
// close it when dropped.
// holds it while it uses the connection, and the export holds it until it is dropped); a
// backend made from a foreign display does not close it when dropped.
let backend = unsafe { Backend::from_foreign_display(d.display.as_ptr().cast()) };
let conn = Connection::from_backend(backend);
// SAFETY: the pointer is the window's live `wl_surface` proxy on that display.
@@ -391,6 +395,36 @@ mod tests {
assert_eq!(pick_answer(saved, &request), ["/home/me/Art/poster"]);
}
/// A `current_filter` of another shape than `(sa(us))` (a structure with fewer, other or more
/// fields, a string) gives the path alone; `uris` of another shape is an error.
#[test]
fn an_answer_of_another_shape_is_not_read() {
let malformed = [
Value::from(("SVG".to_string(),)),
Value::from(("SVG".to_string(), vec![(0u32,)])),
Value::from(("SVG".to_string(), vec![("*.svg".to_string(), 0u32)])),
Value::from((1u32, vec![(0u32, "*.svg".to_string())])),
Value::from(("SVG".to_string(), vec![(0u32, "*.svg".to_string())], 1u32)),
Value::from("SVG"),
];
for filter in malformed {
let mut r = results("file:///tmp/card", None);
r.insert("current_filter".to_string(), OwnedValue::try_from(filter).unwrap());
assert_eq!(answer(0, &r), Ok(Some(Saved { path: "/tmp/card".into(), filter: None })));
}
let malformed = [
Value::from(vec![1u32]),
Value::from(vec![("file:///tmp/card".to_string(),)]),
Value::from(Vec::<String>::new()),
Value::from("file:///tmp/card"),
];
for uris in malformed {
let mut r = HashMap::new();
r.insert("uris".to_string(), OwnedValue::try_from(uris).unwrap());
assert!(answer(0, &r).is_err());
}
}
/// Cancel (1) and a dialog closed another way (2) answer no file; an answer without a local file
/// is an error, and rfd shows the dialog instead.
#[test]
@@ -406,6 +440,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 +448,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]
@@ -440,26 +478,22 @@ mod tests {
Old,
/// As `Old`, with the `Response` sent before the reply that names its path.
OldEarly,
/// As `Current`, but it leaves the bus 300 ms after its reply without a `Response`, as a
/// portal that exits while its dialog is open.
Exits,
/// Leaves the bus right after its reply, without a `Response`.
ExitsAtOnce,
/// Sends its `Response` right after its reply, then leaves the bus.
AnswersAndExits,
}
/// A session bus of its own (`dbus-daemon`) with a mock `org.freedesktop.portal.FileChooser`
/// that answers `SaveFile` from `script` as `portal` says, as PhotoCraft's portal tests run it.
/// `None` when there is no `dbus-daemon` to run.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, std::process::Child)> {
use std::io::BufRead as _;
fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, crate::portal_request::test_bus::Daemon)> {
use zbus::zvariant::OwnedObjectPath;
let spawning = crate::spawning();
let daemon = std::process::Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(std::process::Stdio::piped())
.spawn();
drop(spawning);
let mut daemon = daemon.ok()?;
let mut address = String::new();
std::io::BufReader::new(daemon.stdout.take()?).read_line(&mut address).ok()?;
let address = address.trim().to_string();
let (daemon, address) = crate::portal_request::test_bus::private_bus()?;
let server =
zbus::blocking::connection::Builder::address(address.as_str()).ok()?.name("org.freedesktop.portal.Desktop").ok()?.build().ok()?;
let seen = Seen::default();
@@ -477,18 +511,15 @@ mod tests {
}
let Ok((_parent, _title, options)) = msg.body().deserialize::<(String, String, HashMap<String, OwnedValue>)>() else { break };
let text = |key: &str| options.get(key).and_then(|v| String::try_from(v.try_clone().ok()?).ok());
let filter = options.get("current_filter").and_then(|v| {
let (label, _): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
Some(label)
});
let filter = options.get("current_filter").and_then(|v| filter_label(v));
let calls = log.lock().map(|mut l| {
l.push((text("current_name"), filter));
l.len()
});
let Some(sender) = header.sender().map(|s| s.as_str().trim_start_matches(':').replace('.', "_")) else { break };
let token = match portal {
Portal::Current => text("handle_token").unwrap_or_default(),
Portal::Old | Portal::OldEarly => format!("old{}", calls.unwrap_or_default()),
Portal::Current | Portal::Exits | Portal::ExitsAtOnce | Portal::AnswersAndExits => text("handle_token").unwrap_or_default(),
};
let path = format!("/org/freedesktop/portal/desktop/request/{sender}/{token}");
let Ok(handle) = OwnedObjectPath::try_from(path.as_str()) else { break };
@@ -506,14 +537,22 @@ mod tests {
if server.reply(&header, &handle).is_err() {
break;
}
if portal == Portal::Old {
if matches!(portal, Portal::Old | Portal::Exits) {
// As a person answers the dialog: after the caller has the path returned.
std::thread::sleep(std::time::Duration::from_millis(300));
}
if matches!(portal, Portal::Exits | Portal::ExitsAtOnce) {
break;
}
if portal != Portal::OldEarly && respond().is_err() {
break;
}
if portal == Portal::AnswersAndExits {
break;
}
}
// The portal leaves the bus: the bus sends `NameOwnerChanged` for its name.
let _ = server.close();
});
let client = zbus::blocking::connection::Builder::address(address.as_str()).ok()?.build().ok()?;
Some((client, seen, daemon))
@@ -537,7 +576,7 @@ mod tests {
#[test]
fn the_portal_is_asked_on_the_first_file_type_and_answers_the_one_picked() {
let script = vec![(0, Some(("file:///home/me/Art/poster", "PDF-compatible .ai"))), (1, None)];
let Some((conn, seen, mut daemon)) = mock_portal(script, Portal::Current) else {
let Some((conn, seen, _daemon)) = mock_portal(script, Portal::Current) else {
eprintln!("no dbus-daemon: skipped");
return;
};
@@ -547,7 +586,6 @@ mod tests {
assert_eq!(save_within(&conn, &request), Ok(None));
let seen = seen.lock().map(|s| s.clone()).unwrap_or_default();
assert_eq!(seen.first(), Some(&(Some("Untitled-1.vectorcraft".to_string()), Some(request.filters[0].0.clone()))));
let _ = daemon.kill();
}
/// A portal older than 0.9 answers on the request path it returns, and the answer is awaited
@@ -555,13 +593,12 @@ mod tests {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn the_answer_is_awaited_on_the_path_the_portal_returns() {
let Some((conn, _seen, mut daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else {
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else {
eprintln!("no dbus-daemon: skipped");
return;
};
let request = request();
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
let _ = daemon.kill();
}
/// A portal older than 0.9 can answer before its reply names the request path: the answer is
@@ -570,14 +607,41 @@ mod tests {
#[test]
fn an_answer_that_comes_before_the_path_is_kept() {
let script = vec![(0, Some(("file:///tmp/card", "SVG"))), (1, None)];
let Some((conn, _seen, mut daemon)) = mock_portal(script, Portal::OldEarly) else {
let Some((conn, _seen, _daemon)) = mock_portal(script, Portal::OldEarly) else {
eprintln!("no dbus-daemon: skipped");
return;
};
let request = request();
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
assert_eq!(save_within(&conn, &request), Ok(None));
let _ = daemon.kill();
}
/// A portal that leaves the bus after its reply without answering, while its dialog is open or
/// at once, ends the wait with an error, and rfd shows the dialog.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn a_portal_that_exits_during_the_dialog_ends_the_wait() {
for portal in [Portal::Exits, Portal::ExitsAtOnce] {
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], portal) else {
eprintln!("no dbus-daemon: skipped");
return;
};
assert_eq!(save_within(&conn, &request()), Err("the desktop portal disappeared while waiting for its answer".to_string()));
}
}
/// A portal that answers and then leaves the bus: the save reads the answer. Whether the answer
/// or the bus's report comes first depends on timing here; `portal_request`'s
/// `a_queued_answer_wins_over_the_portal_leaving` queues both before the wait.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn an_answer_sent_just_before_the_portal_exits_is_kept() {
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::AnswersAndExits) else {
eprintln!("no dbus-daemon: skipped");
return;
};
let request = request();
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
}
/// The labels go to the dialog in the interface's language, which is how the answer is matched.
+424 -7
View File
@@ -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;
@@ -84,24 +89,436 @@ pub(crate) fn load_prefs(app: &mut VectorcraftApp, saved: Option<vectorcraft_ui_
app.ui = ui.sanitized();
}
vectorcraft_ui_egui::prefs_dialog::restore(app);
// What this window started from: only what changes after it is this window's to save.
set_saved_base(prefs_value(app).ok());
}
/// Save what this window changed since it last read or saved the preferences, merged into the
/// file as it is now ([`merge_changes`]): another VectorCraft window open at the same time, which
/// read the file before this one saved, then keeps this window's changes when it saves or quits
/// (#4625). Nothing is written when nothing changed.
pub(crate) fn save_prefs(app: &VectorcraftApp) {
if !prefs_enabled() || KEEP_UI_PREFS.load(std::sync::atomic::Ordering::Relaxed) {
return;
}
if let Some(p) = prefs_path() {
let _ = std::fs::create_dir_all(p.parent().unwrap_or(std::path::Path::new(".")));
if let Ok(bytes) = prefs_bytes(app) {
// Preferences are best effort: a failed write keeps the previous file.
let _ = fileio::write_atomic(&p, &bytes);
let Some(p) = prefs_path() else { return };
let Ok(mine) = prefs_value(app) else { return };
let base = saved_base();
if base.as_ref().is_some_and(|b| same_lasting(b, &mine)) {
return;
}
// The file as another window may have saved it since (none, or unreadable: this one's own).
let on_disk = std::fs::read(&p).ok().and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok());
let merged = match (base.as_ref(), on_disk) {
(Some(base), Some(on_disk)) => merge_changes(base, &mine, on_disk),
_ => mine.clone(),
};
let _ = std::fs::create_dir_all(p.parent().unwrap_or(std::path::Path::new(".")));
let Ok(bytes) = serde_json::to_vec_pretty(&merged) else { return };
// Preferences are best effort: a failed write keeps the previous file, and the changes are
// tried again on the next save.
if fileio::write_atomic(&p, &bytes).is_ok() {
set_saved_base(Some(mine));
}
}
/// How often [`save_prefs_soon`] looks for changes to save.
const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(2);
/// Save the preferences at most every [`SAVE_EVERY`] while the app runs, when something changed:
/// the workspace, panels, toolbars and the other UI settings kept only in the UI state were saved
/// only on quitting, so a session ended any other way (the window closed by the system, the
/// process ended or crashing) started the next one from the settings before it (#4625).
pub(crate) fn save_prefs_soon(app: &VectorcraftApp) {
static LAST: std::sync::Mutex<Option<std::time::Instant>> = std::sync::Mutex::new(None);
let Ok(mut last) = LAST.lock() else { return };
if last.is_some_and(|t| t.elapsed() < SAVE_EVERY) {
return;
}
*last = Some(std::time::Instant::now());
drop(last);
save_prefs(app);
}
/// The preferences as this window last read or saved them (`None`: not read yet).
static SAVED_BASE: std::sync::Mutex<Option<serde_json::Value>> = std::sync::Mutex::new(None);
fn saved_base() -> Option<serde_json::Value> {
SAVED_BASE.lock().ok().and_then(|b| b.clone())
}
fn set_saved_base(value: Option<serde_json::Value>) {
if let Ok(mut b) = SAVED_BASE.lock() {
*b = value;
}
}
/// Fields of the UI state that a start resets ([`vectorcraft_ui_egui::UiState::sanitized`]): a
/// change to them alone isn't saved, and they are never merged over another window's.
const PASSING: &[&str] = &["status", "dialog", "flyout", "palette_open", "palette_query", "about", "open_panel"];
/// Do `a` and `b` hold the same preferences, leaving out what a start resets ([`PASSING`])?
fn same_lasting(a: &serde_json::Value, b: &serde_json::Value) -> bool {
match (a.as_object(), b.as_object()) {
(Some(a), Some(b)) => {
let keys: std::collections::BTreeSet<&String> = a.keys().chain(b.keys()).filter(|k| !PASSING.contains(&k.as_str())).collect();
keys.into_iter().all(|k| a.get(k) == b.get(k))
}
_ => a == b,
}
}
/// 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).
fn merge_changes(base: &serde_json::Value, mine: &serde_json::Value, on_disk: serde_json::Value) -> serde_json::Value {
use serde_json::Value;
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()) {
if let Some(v) = mine.get(key) {
out.entry(key.clone()).or_insert_with(|| v.clone());
}
continue;
}
let (was, now) = (base.get(key), mine.get(key));
if was == now || key == "action_set" {
continue;
}
if key == "engine_prefs"
&& let (Some(Value::Object(was)), Some(Value::Object(now)), Some(Value::Object(theirs))) = (was, now, out.get_mut(key))
{
let names: std::collections::BTreeSet<&String> = was.keys().chain(now.keys()).collect();
for name in names {
match (was.get(name), now.get(name)) {
(a, b) if a == b => {}
(_, Some(v)) => {
theirs.insert(name.clone(), v.clone());
}
(_, None) => {
theirs.remove(name);
}
}
}
continue;
}
match now {
Some(v) => {
out.insert(key.clone(), v.clone());
}
None => {
out.remove(key);
}
}
}
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>> {
serde_json::to_vec_pretty(&prefs_value(app)?)
}
/// [`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_vec_pretty(&ui)
serde_json::to_value(&ui)
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::{merge_changes, same_lasting};
/// 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}});
// The other window switched the workspace and the accent, and saved.
let on_disk = json!({"workspace": "Painting", "toolbar": true, "engine_prefs": {"uiAccent": "violet", "uiScaling": 1.0}});
// This one changed only the UI scaling.
let mine = json!({"workspace": "Essentials", "toolbar": true, "engine_prefs": {"uiAccent": "blue", "uiScaling": 1.25}});
let merged = merge_changes(&base, &mine, on_disk);
assert_eq!(merged, json!({"workspace": "Painting", "toolbar": true, "engine_prefs": {"uiAccent": "violet", "uiScaling": 1.25}}));
}
#[test]
fn a_setting_both_windows_changed_takes_the_last_saved() {
let base = json!({"workspace": "Essentials", "engine_prefs": {"uiAccent": "blue"}});
let on_disk = json!({"workspace": "Painting", "engine_prefs": {"uiAccent": "violet"}});
let mine = json!({"workspace": "Typography", "engine_prefs": {"uiAccent": "green"}});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"workspace": "Typography", "engine_prefs": {"uiAccent": "green"}}));
}
#[test]
fn fields_added_or_removed_by_this_window_are_saved() {
let base = json!({"docking": {"root": 1}, "engine_prefs": {"old": 1}});
let on_disk = json!({"docking": {"root": 1}, "recent_files": ["a.svg"], "engine_prefs": {"old": 1}});
let mine = json!({"dock_width": 300.0, "engine_prefs": {"new": 2}});
assert_eq!(merge_changes(&base, &mine, on_disk), json!({"dock_width": 300.0, "recent_files": ["a.svg"], "engine_prefs": {"new": 2}}));
}
/// The status line and open dialogs reset at start: they don't make a save, and they don't
/// replace another window's.
#[test]
fn what_a_start_resets_is_left_out() {
let base = json!({"status": "", "dialog": null, "workspace": "Essentials"});
let mine = json!({"status": "Saved", "dialog": {"kind": "preferences"}, "workspace": "Essentials"});
assert!(same_lasting(&base, &mine));
let on_disk = json!({"status": "Opened", "dialog": null, "workspace": "Painting"});
let mine = json!({"status": "Saved", "dialog": {"kind": "preferences"}, "workspace": "Essentials", "toolbar": false});
let merged = merge_changes(&base, &mine, on_disk);
assert_eq!(merged, json!({"status": "Opened", "dialog": null, "workspace": "Painting", "toolbar": false}));
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"});
let mine = json!({"workspace": "Painting"});
assert_eq!(merge_changes(&base, &mine, json!([1, 2])), mine);
}
}
+40
View File
@@ -41,6 +41,14 @@ pub fn attach_profile_store(session: &mut vectorcraft_engine::Session) {
}
}
/// Make Edit › Color Settings kept in `Color Settings.json` the active ones (#6335), and keep them
/// there when they change. After [`attach_profile_store`]: they may name a loaded profile.
pub fn attach_color_settings(session: &mut vectorcraft_engine::Session) {
if let Some(path) = store_dir("Color Settings.json") {
session.attach_color_settings(path);
}
}
/// Install the plug-ins Install Plug-in kept in the `Plug-ins` folder (#2541), and keep the ones
/// installed from now on there.
pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) {
@@ -49,6 +57,22 @@ pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) {
}
}
/// Have File › Scripts and `script.listInstalled` list the scripts of the `Scripts` folder. The
/// folder is only read: the user makes it.
pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
if let Some(dir) = store_dir("Scripts") {
session.attach_scripts_dir(dir);
}
}
/// Have File › New start each category's documents from its profile in the `New Document
/// Profiles` folder, which `file.newProfiles.edit` makes.
pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
if let Some(dir) = store_dir("New Document Profiles") {
session.attach_new_doc_profiles(dir);
}
}
/// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from
/// now on there. After the preferences were restored: the folder is the one place the presets live.
pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
@@ -57,6 +81,22 @@ pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
}
}
/// Keep the custom dictionary (Edit › Spelling › Add, Edit Custom Dictionary) in the
/// `Custom Dictionary.txt` file next to the settings, one word per line, and take in its words.
pub fn attach_custom_dictionary(session: &mut vectorcraft_engine::Session) {
if let Some(path) = store_dir("Custom Dictionary.txt") {
session.attach_custom_dictionary(path);
}
}
/// Keep the custom arrowheads (Stroke panel menu › Edit Arrowheads…) in the `Arrowheads.vectorcraft`
/// file next to the settings, and list the heads it holds.
pub fn attach_arrowheads(session: &mut vectorcraft_engine::Session) {
if let Some(path) = store_dir(vectorcraft_engine::cmd::arrowheads::FILE_NAME) {
session.attach_arrowheads_file(path.to_string_lossy().to_string());
}
}
#[cfg(test)]
mod tests {
use super::*;
+48 -8
View File
@@ -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);
}
}
+280
View File
@@ -0,0 +1,280 @@
//! Takes the app's windows off screen when it quits on Linux and the BSDs, before eframe drops the
//! app. Dropping the app waits up to [`vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT`] for the
//! clipboard handles to let go, and eframe closes the windows only after that wait.
//!
//! The main window is hidden on X11 (XWayland included). winit cannot hide a Wayland window, so on
//! Linux a Wayland main window is unmapped instead: its surface gets no buffer, and the window stays
//! open with the connection the Wayland clipboard copies and reads on. On Linux the X11 windows of
//! floating panels and documents are recorded as eframe creates and drops them ([`Hooks`]), and
//! quitting unmaps them through an X11 connection of its own. On native Wayland, floating panels and
//! documents are normally drawn inside the main window.
#[cfg(target_os = "linux")]
use std::collections::HashMap;
#[cfg(target_os = "linux")]
use std::sync::{LazyLock, Mutex, MutexGuard, PoisonError};
#[cfg(target_os = "linux")]
use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle};
/// The main window as quitting sees it.
pub(crate) trait QuittingWindow {
/// The window is a Wayland surface.
fn is_wayland(&self) -> bool;
/// Hides an X11 window.
fn hide(&self);
/// Takes a Wayland window off screen and keeps it open.
fn unmap(&self);
}
impl QuittingWindow for winit::window::Window {
#[cfg(target_os = "linux")]
fn is_wayland(&self) -> bool {
matches!(self.window_handle().map(|h| h.as_raw()), Ok(RawWindowHandle::Wayland(_)))
}
/// The BSDs have no Wayland unmap: their windows are hidden through winit.
#[cfg(not(target_os = "linux"))]
fn is_wayland(&self) -> bool {
false
}
fn hide(&self) {
self.set_visible(false);
}
#[cfg(target_os = "linux")]
fn unmap(&self) {
unmap_wayland(self);
}
#[cfg(not(target_os = "linux"))]
fn unmap(&self) {
self.set_visible(false);
}
}
/// Takes the main window and the floating windows `x11` lists off screen: a Wayland main window is
/// unmapped and any other main window hidden, and `unmap_x11` unmaps the floating windows.
pub(crate) fn off_screen<W: QuittingWindow + ?Sized>(main: Option<&W>, x11: &[u32], unmap_x11: impl FnOnce(&[u32])) {
if let Some(window) = main {
if window.is_wayland() {
window.unmap();
} else {
window.hide();
}
}
if !x11.is_empty() {
unmap_x11(x11);
}
}
/// [`off_screen`] with the running app's main window and the floating windows [`Hooks`] recorded.
/// Runs on quit, before eframe drops the app.
pub(crate) fn before_teardown(main: Option<&winit::window::Window>) {
#[cfg(target_os = "linux")]
off_screen(main, &CHILD_WINDOWS.x11(), unmap_x11);
#[cfg(not(target_os = "linux"))]
off_screen(main, &[], |_| {});
}
/// The X11 windows of floating panels and documents, by viewport, while eframe holds them.
#[cfg(target_os = "linux")]
#[derive(Default)]
pub(crate) struct ChildWindows(Mutex<HashMap<egui::ViewportId, u32>>);
#[cfg(target_os = "linux")]
impl ChildWindows {
/// eframe made `viewport`'s window, with `handle`. The main window, and windows of other window
/// systems, are not recorded; a window made again for the same viewport replaces its record.
pub(crate) fn created(&self, viewport: egui::ViewportId, handle: Option<RawWindowHandle>) {
let mut windows = self.lock();
match handle.and_then(x11_window) {
Some(id) if viewport != egui::ViewportId::ROOT => windows.insert(viewport, id),
_ => windows.remove(&viewport),
};
}
/// eframe dropped `viewport`'s window.
pub(crate) fn destroyed(&self, viewport: egui::ViewportId) {
self.lock().remove(&viewport);
}
/// The recorded windows, in id order.
pub(crate) fn x11(&self) -> Vec<u32> {
let mut ids: Vec<u32> = self.lock().values().copied().collect();
ids.sort_unstable();
ids.dedup();
ids
}
fn lock(&self) -> MutexGuard<'_, HashMap<egui::ViewportId, u32>> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
/// The X11 window id of `handle`, None for another window system.
#[cfg(target_os = "linux")]
fn x11_window(handle: RawWindowHandle) -> Option<u32> {
match handle {
RawWindowHandle::Xlib(h) => u32::try_from(h.window).ok(),
RawWindowHandle::Xcb(h) => Some(h.window.get()),
_ => None,
}
}
/// The running app's floating windows, which [`Hooks`] records.
#[cfg(target_os = "linux")]
static CHILD_WINDOWS: LazyLock<ChildWindows> = LazyLock::new(ChildWindows::default);
/// Records the windows eframe creates and drops in [`CHILD_WINDOWS`]; set as
/// [`eframe::NativeOptions::viewport_hooks`].
#[cfg(target_os = "linux")]
pub(crate) struct Hooks;
#[cfg(target_os = "linux")]
impl eframe::ViewportHooks for Hooks {
fn window_created(&self, viewport: egui::ViewportId, window: &winit::window::Window) {
CHILD_WINDOWS.created(viewport, window.window_handle().ok().map(|h| h.as_raw()));
}
fn window_destroyed(&self, viewport: egui::ViewportId) {
CHILD_WINDOWS.destroyed(viewport);
}
}
/// Unmaps the X11 `windows` through a connection of its own, and waits until the server has done so.
/// An id whose window is gone gets an error, which is ignored.
#[cfg(target_os = "linux")]
fn unmap_x11(windows: &[u32]) {
use x11rb::protocol::xproto::ConnectionExt as _;
let conn = match x11rb::connect(None) {
Ok((conn, _)) => conn,
Err(e) => {
log::warn!("couldn't reach the X server to hide the floating windows on quit: {e}");
return;
}
};
for &window in windows {
if let Ok(cookie) = conn.unmap_window(window) {
cookie.ignore_error();
}
}
// The server answers once it has handled the requests before this one.
if let Ok(cookie) = conn.get_input_focus() {
let _ = cookie.reply();
}
}
/// Attaches no buffer to `window`'s Wayland surface and commits it, which unmaps the window: the
/// compositor stops showing it, and the window and its connection stay open.
#[cfg(target_os = "linux")]
fn unmap_wayland(window: &winit::window::Window) {
let Some((conn, surface)) = super::portal_save::wayland::surface(window) else { return };
surface.attach(None, 0, 0);
surface.commit();
if let Err(e) = conn.flush() {
log::warn!("couldn't reach the compositor to hide the window on quit: {e}");
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
/// A main window that records what quitting did to it.
struct Window<'a> {
wayland: bool,
done: &'a RefCell<Vec<String>>,
}
impl QuittingWindow for Window<'_> {
fn is_wayland(&self) -> bool {
self.wayland
}
fn hide(&self) {
self.done.borrow_mut().push("hide".into());
}
fn unmap(&self) {
self.done.borrow_mut().push("unmap".into());
}
}
fn quit(wayland: Option<bool>, x11: &[u32]) -> Vec<String> {
let done = RefCell::new(Vec::new());
let window = wayland.map(|wayland| Window { wayland, done: &done });
off_screen(window.as_ref(), x11, |ids| done.borrow_mut().push(format!("unmap x11 {ids:?}")));
done.into_inner()
}
/// winit cannot hide a Wayland window: quitting unmaps it, and never only asks winit to hide it.
#[test]
fn quitting_unmaps_a_wayland_main_window() {
assert_eq!(quit(Some(true), &[]), ["unmap"]);
}
/// An X11 main window (XWayland included) is hidden, and the floating panels' and documents' X11
/// windows are unmapped with it.
#[test]
fn quitting_hides_an_x11_main_window_and_its_floating_windows() {
assert_eq!(quit(Some(false), &[]), ["hide"]);
assert_eq!(quit(Some(false), &[7, 9]), ["hide", "unmap x11 [7, 9]"]);
}
/// Without a main window (none was made), the floating windows still go, and with none at all
/// nothing is done.
#[test]
fn quitting_without_a_main_window() {
assert_eq!(quit(None, &[3]), ["unmap x11 [3]"]);
assert!(quit(None, &[]).is_empty());
}
#[cfg(target_os = "linux")]
fn xlib(id: std::os::raw::c_ulong) -> Option<RawWindowHandle> {
Some(RawWindowHandle::Xlib(winit::raw_window_handle::XlibWindowHandle::new(id)))
}
#[cfg(target_os = "linux")]
fn viewport(name: &str) -> egui::ViewportId {
egui::ViewportId::from_hash_of(name)
}
/// The floating windows eframe made are recorded until it drops them; the main window, which
/// quitting reaches through winit, is not.
#[cfg(target_os = "linux")]
#[test]
fn floating_x11_windows_are_recorded_while_they_exist() {
let windows = ChildWindows::default();
windows.created(egui::ViewportId::ROOT, xlib(1));
windows.created(viewport("Layers"), xlib(9));
let xcb = winit::raw_window_handle::XcbWindowHandle::new(std::num::NonZeroU32::new(5).expect("not zero"));
windows.created(viewport("Untitled-2"), Some(RawWindowHandle::Xcb(xcb)));
windows.created(viewport("Color"), xlib(7));
assert_eq!(windows.x11(), [5, 7, 9]);
windows.destroyed(viewport("Color"));
assert_eq!(windows.x11(), [5, 9]);
// A viewport that eframe has already dropped, or never made, is no error.
windows.destroyed(viewport("Color"));
windows.destroyed(viewport("Swatches"));
assert_eq!(windows.x11(), [5, 9]);
}
/// A window made again for a viewport replaces its record, and one of another window system, or
/// one whose handle could not be read, removes it.
#[cfg(target_os = "linux")]
#[test]
fn a_window_made_again_replaces_its_record() {
let windows = ChildWindows::default();
windows.created(viewport("Layers"), xlib(9));
windows.created(viewport("Layers"), xlib(11));
assert_eq!(windows.x11(), [11]);
let surface = std::ptr::NonNull::<std::ffi::c_void>::dangling();
let wayland = winit::raw_window_handle::WaylandWindowHandle::new(surface);
windows.created(viewport("Layers"), Some(RawWindowHandle::Wayland(wayland)));
assert!(windows.x11().is_empty());
windows.created(viewport("Layers"), xlib(11));
windows.created(viewport("Layers"), None);
assert!(windows.x11().is_empty());
}
}
+533
View File
@@ -0,0 +1,533 @@
//! One app per user (#4892): a file opened from the file manager (double-click, Open With, a drop
//! on the executable) while VectorCraft runs opens as a new document tab in the running app, which
//! comes to the front, instead of in a second app.
//!
//! The running app (the primary) listens on a loopback port and records the port and two random
//! tokens in `instance.json` next to the preferences (owner-only on Unix; on Windows the settings
//! folder is the user's own). A later launch with files connects; the primary greets it with
//! `hello`, which only a process that could read the file (or talk to the primary) knows; only then
//! does the launch send `token` and the absolute paths of its files, one JSON line. The primary
//! checks the token, keeps the paths that are existing files, acknowledges and opens them; the
//! launch exits. Anything else (no file, no listener, a wrong greeting, no answer) starts the launch
//! 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 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};
use std::io::{self, BufRead as _, BufReader, Read as _, Write as _};
use std::net::{Ipv4Addr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock, PoisonError};
use std::time::Duration;
use serde_json::{Value, json};
use super::prefs::{prefs_enabled, prefs_path};
/// The endpoint file, next to the preferences.
const FILE_NAME: &str = "instance.json";
/// The longest message either side reads, and the longest endpoint file.
const MAX_MESSAGE: u64 = 64 * 1024;
/// The most files one launch hands over.
const MAX_FILES: usize = 256;
/// A live primary's kernel accepts at once, even while its window is busy; a stale port on Windows
/// would otherwise retry for about two seconds.
const CONNECT_TIMEOUT: Duration = Duration::from_millis(500);
/// How long the primary waits on one launch; it serves launches one at a time.
const SERVER_TIMEOUT: Duration = Duration::from_secs(2);
/// How long a launch waits on the primary: longer than a launch served before it can take.
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();
/// What this launch does about an app already running.
pub enum Start {
/// The running app took the files: this launch exits.
Forwarded,
/// This launch runs; `Some` while it is the app later launches hand their files to.
Running(Option<Primary>),
}
/// 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, 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) {
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))
}
}
}
/// 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.
let _ = UI.set(ctx.clone());
}
/// The paths later launches handed over since the last call.
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() {
ctx.request_repaint();
}
}
/// This app is the one recorded in the endpoint file; dropping it removes the file, unless a later
/// app has replaced it since.
pub struct Primary {
path: PathBuf,
token: String,
}
impl Drop for Primary {
fn drop(&mut self) {
if read_endpoint(&self.path).is_some_and(|e| e.token == self.token) {
// Best effort: a file left behind is stale, and the next launch replaces it.
let _ = fs::remove_file(&self.path);
}
}
}
struct Endpoint {
port: u16,
token: String,
hello: String,
}
fn invalid(why: &str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, why)
}
fn read_endpoint(path: &Path) -> Option<Endpoint> {
let mut text = String::new();
fs::File::open(path).ok()?.take(MAX_MESSAGE).read_to_string(&mut text).ok()?;
let v: Value = serde_json::from_str(&text).ok()?;
let port = u16::try_from(v.get("port")?.as_u64()?).ok().filter(|p| *p != 0)?;
Some(Endpoint { port, token: v.get("token")?.as_str()?.to_owned(), hello: v.get("hello")?.as_str()?.to_owned() })
}
/// Hand `files` (made absolute against this launch's folder) to the app recorded at `path`; `Ok`
/// once it acknowledged them.
fn forward(path: &Path, files: &[String]) -> io::Result<()> {
let endpoint = read_endpoint(path).ok_or_else(|| invalid("no endpoint file"))?;
let files = files.iter().map(|f| std::path::absolute(f).map(|p| p.to_string_lossy().into_owned())).collect::<io::Result<Vec<_>>>()?;
let stream = TcpStream::connect_timeout(&(Ipv4Addr::LOCALHOST, endpoint.port).into(), CONNECT_TIMEOUT)?;
stream.set_read_timeout(Some(CLIENT_TIMEOUT))?;
stream.set_write_timeout(Some(CLIENT_TIMEOUT))?;
// The token and the paths go only to a listener that knows the greeting.
if !same(read_message(&stream)?.get("hello"), &endpoint.hello) {
return Err(invalid("the listener isn't VectorCraft"));
}
write_message(&stream, &json!({ "token": endpoint.token, "files": files }))?;
match read_message(&stream)?.get("ok") {
Some(Value::Bool(true)) => Ok(()),
_ => Err(invalid("refused")),
}
}
/// Listen for later launches and record this app at `path`; each launch's files go to `deliver`.
/// `None` when that fails (logged): the app then runs on its own, as before.
fn listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> Option<Primary> {
try_listen(path, deliver).inspect_err(|e| log::warn!("files opened while VectorCraft runs will open in another window: {e}")).ok()
}
fn try_listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> io::Result<Primary> {
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
let port = listener.local_addr()?.port();
let (token, hello) = random_tokens();
write_endpoint(path, &json!({ "port": port, "token": token, "hello": hello }))?;
// From here on a failure removes the file again.
let primary = Primary { path: path.to_path_buf(), token: token.clone() };
std::thread::Builder::new().name("open-files-listener".into()).spawn(move || {
for stream in listener.incoming() {
match stream.and_then(|s| receive(&s, &hello, &token)) {
Ok(files) if files.is_empty() => {}
Ok(files) => deliver(files),
Err(e) => {
log::warn!("refused files from another launch: {e}");
// An accept that keeps failing (out of handles) doesn't spin.
std::thread::sleep(Duration::from_millis(50));
}
}
}
})?;
Ok(primary)
}
/// Serve one launch: greet it, check its token, keep the paths that are existing files.
fn receive(stream: &TcpStream, hello: &str, token: &str) -> io::Result<Vec<String>> {
stream.set_read_timeout(Some(SERVER_TIMEOUT))?;
stream.set_write_timeout(Some(SERVER_TIMEOUT))?;
write_message(stream, &json!({ "hello": hello }))?;
let message = read_message(stream)?;
if !same(message.get("token"), token) {
return Err(invalid("wrong token"));
}
let files = message.get("files").and_then(Value::as_array).ok_or_else(|| invalid("no file list"))?;
if files.len() > MAX_FILES {
return Err(invalid("too many files"));
}
let files = files
.iter()
.filter_map(Value::as_str)
.filter(|f| {
let p = Path::new(f);
let ok = p.is_absolute() && p.is_file();
if !ok {
log::warn!("another launch named {f}, which isn't a file");
}
ok
})
.map(str::to_owned)
.collect();
write_message(stream, &json!({ "ok": true }))?;
Ok(files)
}
/// One JSON line of at most [`MAX_MESSAGE`] bytes. Each side sends one line and waits for the
/// other's, so nothing read past it is lost.
fn read_message(stream: &TcpStream) -> io::Result<Value> {
let mut line = Vec::new();
BufReader::new(stream.take(MAX_MESSAGE)).read_until(b'\n', &mut line)?;
if line.last() != Some(&b'\n') {
return Err(invalid("message too long or cut short"));
}
serde_json::from_slice(&line).map_err(|e| invalid(&e.to_string()))
}
fn write_message(mut stream: &TcpStream, message: &Value) -> io::Result<()> {
let mut line = serde_json::to_vec(message).map_err(io::Error::other)?;
line.push(b'\n');
stream.write_all(&line)
}
/// `given` is the string `expected`, compared in constant time.
fn same(given: Option<&Value>, expected: &str) -> bool {
given
.and_then(Value::as_str)
.is_some_and(|g| g.len() == expected.len() && g.bytes().zip(expected.bytes()).fold(0, |acc, (a, b)| acc | (a ^ b)) == 0)
}
/// Two unrelated 128-bit hex tokens. `RandomState` is keyed from the system's random numbers, and
/// its keyed hash of distinct values gives unpredictable, independent output (no crate needed).
fn random_tokens() -> (String, String) {
let keyed = RandomState::new();
let token = |a: u8, b: u8| format!("{:016x}{:016x}", keyed.hash_one(a), keyed.hash_one(b));
(token(1, 2), token(3, 4))
}
/// Replace `path` with `endpoint` at once (a temporary file renamed over it), readable only by the
/// user on Unix.
fn write_endpoint(path: &Path, endpoint: &Value) -> io::Result<()> {
if let Some(dir) = path.parent() {
fs::create_dir_all(dir)?;
}
let tmp = path.with_extension(format!("{}.tmp", std::process::id()));
// A leftover of an earlier app with the same process id; `create_new` sets the mode below.
let _ = fs::remove_file(&tmp);
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
let bytes = serde_json::to_vec(endpoint).map_err(io::Error::other)?;
let written = options.open(&tmp).and_then(|mut f| f.write_all(&bytes)).and_then(|()| fs::rename(&tmp, path));
if written.is_err() {
// Best effort: the temporary file is all there is to clean up.
let _ = fs::remove_file(&tmp);
}
written
}
#[cfg(test)]
mod tests {
use std::sync::mpsc;
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, 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.path().join(FILE_NAME), TestDir(dir), file)
}
fn primary(path: &Path) -> (Primary, mpsc::Receiver<Vec<String>>) {
let (tx, rx) = mpsc::channel();
let primary = listen(path, move |files| tx.send(files).unwrap()).unwrap();
(primary, rx)
}
/// Connects as a launch would and sends `message` after the greeting; what came back.
fn send_raw(path: &Path, message: &[u8]) -> io::Result<Value> {
let endpoint = read_endpoint(path).unwrap();
let stream = TcpStream::connect((Ipv4Addr::LOCALHOST, endpoint.port)).unwrap();
stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap();
assert!(same(read_message(&stream).unwrap().get("hello"), &endpoint.hello));
(&stream).write_all(message)?;
read_message(&stream)
}
#[test]
fn a_launch_hands_its_files_to_the_running_app() {
let (path, dir, file) = folder("forward");
let (primary, rx) = primary(&path);
let missing = dir.join("missing.svg").to_string_lossy().into_owned();
forward(&path, &[file.clone(), missing]).unwrap();
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file), "the missing file is left out");
// An empty list only asks whether the app runs: nothing is delivered.
forward(&path, &[]).unwrap();
forward(&path, std::slice::from_ref(&file)).unwrap();
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
drop(primary);
assert!(!path.exists(), "the endpoint file goes with the app");
}
#[test]
fn a_new_instance_or_safe_mode_launch_keeps_its_files() {
let (path, _dir, file) = folder("own");
let (primary, rx) = primary(&path);
for (new_instance, safe_mode) in [(true, false), (false, true)] {
let start = start_at(&path, new_instance, safe_mode, std::slice::from_ref(&file));
assert!(matches!(start, Start::Running(None)), "runs as its own app (new instance {new_instance}, Safe Mode {safe_mode})");
}
assert!(matches!(start_at(&path, false, false, std::slice::from_ref(&file)), Start::Forwarded));
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file));
assert!(rx.try_recv().is_err(), "only the plain launch handed its file over");
drop(primary);
}
#[test]
fn a_safe_mode_launch_leaves_later_launches_their_own_app() {
let _globals = globals();
let (path, _dir, file) = folder("safe-mode-alone");
// With no app running, a Safe Mode launch runs without listening.
assert!(matches!(start_at(&path, false, true, std::slice::from_ref(&file)), Start::Running(None)));
assert!(!path.exists(), "a Safe Mode launch records no endpoint");
// A plain launch after it starts its own app and takes later launches' files.
let Start::Running(Some(primary)) = start_at(&path, false, false, std::slice::from_ref(&file)) else {
panic!("the plain launch runs and listens")
};
assert!(path.exists());
// An app that stays in Safe Mode after the choice gives that up.
hold(Some(primary));
resign();
assert!(!path.exists(), "the endpoint file goes with resign");
}
#[test]
fn files_handed_to_an_app_staying_in_safe_mode_go_to_a_new_app_with_plug_ins() {
let _globals = globals();
// Nothing left over from a test that failed.
resign();
drop(take());
let (path, _dir, file) = folder("safe-mode-later");
let Start::Running(Some(primary)) = start_at(&path, false, false, &[]) else { panic!("the first launch listens") };
hold(Some(primary));
// A later launch handed its file over while the choice about a stopped plug-in was up.
queue(vec![file.clone()]);
let mut launched = Vec::new();
let here = take_for_frame(true, |files| {
launched = files.to_vec();
Ok(())
});
assert!(here.is_empty(), "nothing opens in the Safe Mode app");
assert_eq!(launched, std::slice::from_ref(&file), "a new app with plug-ins opens it");
assert!(!path.exists(), "the app resigned before starting the new one");
// When the new app can't start, the file opens here rather than being lost.
queue(vec![file.clone()]);
assert_eq!(take_for_frame(true, |_| Err(io::Error::other("no program"))), std::slice::from_ref(&file));
// An app with plug-ins opens what it is handed.
queue(vec![file.clone()]);
assert_eq!(take_for_frame(false, |_| panic!("no new app")), [file]);
}
#[test]
fn the_new_app_takes_every_name_as_a_file() {
let command = app_with_plug_ins(Path::new("vectorcraft"), &["-a.svg".to_owned(), "b.svg".to_owned()]);
let args: Vec<_> = command.get_args().collect();
assert_eq!(args, ["--", "-a.svg", "b.svg"]);
}
#[test]
fn a_wrong_token_garbage_and_oversized_messages_are_refused() {
let (path, _dir, file) = folder("refused");
let (_primary, rx) = primary(&path);
let token = read_endpoint(&path).unwrap().token;
let wrong = format!("{}\n", json!({ "token": "0".repeat(token.len()), "files": [file] }));
assert!(send_raw(&path, wrong.as_bytes()).is_err());
assert!(send_raw(&path, b"not json\n").is_err());
assert!(send_raw(&path, &vec![b'a'; MAX_MESSAGE as usize + 10]).is_err());
let many = format!("{}\n", json!({ "token": token, "files": vec![file.clone(); MAX_FILES + 1] }));
assert!(send_raw(&path, many.as_bytes()).is_err());
let relative = format!("{}\n", json!({ "token": token, "files": ["a b.svg", 7] }));
assert_eq!(send_raw(&path, relative.as_bytes()).unwrap(), json!({ "ok": true }));
assert!(rx.try_recv().is_err(), "nothing was delivered");
// 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]);
}
#[test]
fn a_stale_endpoint_file_is_ignored_and_replaced() {
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();
write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap();
let heard = std::thread::spawn(move || {
let (stream, _) = impostor.accept().unwrap();
write_message(&stream, &json!({ "hello": "x" })).unwrap();
stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap();
read_message(&stream).ok()
});
assert!(forward(&path, std::slice::from_ref(&file)).is_err());
assert!(heard.join().unwrap().is_none());
// Garbage in the file is no endpoint either.
fs::write(&path, b"\xff not json").unwrap();
assert!(forward(&path, std::slice::from_ref(&file)).is_err());
// A new primary replaces the stale file.
let (_primary, rx) = primary(&path);
forward(&path, std::slice::from_ref(&file)).unwrap();
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
}
#[test]
fn a_replaced_endpoint_file_stays_when_the_earlier_app_ends() {
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));
}
#[test]
fn tokens_are_random_and_distinct() {
let (a, b) = random_tokens();
let (c, _) = random_tokens();
assert_eq!(a.len(), 32);
assert!(a != b && a != c);
}
#[cfg(unix)]
#[test]
fn the_endpoint_file_is_the_users_alone() {
use std::os::unix::fs::PermissionsExt as _;
let (path, _dir, _) = folder("mode");
let _primary = primary(&path);
assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
}
}
+2 -3
View File
@@ -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());
}
+214 -55
View File
@@ -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();
+212 -4
View File
@@ -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,189 @@ 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` set to `app`, `system` or `desktop` 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, an app frame the desktop left to the app keeps its own buttons,
/// one that `VECTORCRAFT_TITLEBAR=app` forced or the preference kept through XWayland gets the
/// default 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(Layout::default())),
((Frame::Desktop, Some(false), false, true), Frame::Desktop),
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(Layout::default())),
((Frame::App(gnome.clone()), Some(true), false, false), Frame::App(Layout::default())),
];
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 app bar's caption buttons follow the window-button layout of the app frame on Linux and the
/// BSDs (Close alone at the right, or all three at the left with Close outermost); the desktop frame,
/// macOS and Windows keep all three at the right.
#[test]
fn the_caption_buttons_follow_the_frame_layout() {
use craft_window::{Button, Frame, Layout};
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
let close_only = Layout::parse("appmenu:close");
let at_left = Layout { left: vec![Button::Close, Button::Minimize, Button::Maximize], right: vec![] };
let split = Layout { left: vec![Button::Close], right: vec![Button::Minimize, Button::Maximize] };
let probed = [
(close_only, CaptionLayout { left: vec![], right: vec![Caption::Close] }),
(at_left, CaptionLayout { left: vec![Caption::Close, Caption::Minimize, Caption::Maximize], right: vec![] }),
(split, CaptionLayout { left: vec![Caption::Close], right: vec![Caption::Minimize, Caption::Maximize] }),
];
for (layout, expected) in probed {
let shown = super::caption_layout_from(&Frame::App(layout.clone()));
let expected = if cfg!(any(target_os = "macos", target_os = "windows")) { CaptionLayout::default() } else { expected };
assert_eq!(shown, expected, "{layout:?}");
}
assert_eq!(super::caption_layout_from(&Frame::Desktop), CaptionLayout::default());
assert_eq!(CaptionLayout::default().right, vec![Caption::Minimize, Caption::Maximize, Caption::Close]);
}
/// `VECTORCRAFT_TITLEBAR` chooses the frame for the run it is set in, with System Title Bar off and
/// on. The saved preference still decides while the variable is unset.
#[test]
fn the_titlebar_variable_takes_precedence_over_system_title_bar() {
use craft_window::Frame;
assert!(super::system_title_bar_applies(true, false));
assert!(!super::system_title_bar_applies(true, true));
assert!(!super::system_title_bar_applies(false, false));
assert!(!super::system_title_bar_applies(false, true));
// VECTORCRAFT_TITLEBAR=app with System Title Bar on: VectorCraft draws its own title bar.
let frame = super::start_frame(Frame::Desktop, Some(true), false, false);
assert_eq!(super::custom_titlebar_from(&frame, super::system_title_bar_applies(true, true)), !cfg!(target_os = "macos"));
// VECTORCRAFT_TITLEBAR=desktop with System Title Bar off keeps the desktop's frame.
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
let frame = super::start_frame(Frame::App(craft_window::Layout::default()), Some(false), false, false);
assert!(!super::custom_titlebar_from(&frame, super::system_title_bar_applies(false, true)));
}
}
/// `VECTORCRAFT_TITLEBAR` read from the environment at startup, with System Title Bar off and on.
/// The variable is process-wide and read once, so each value runs in a separate test process.
#[test]
fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
const CHILD: &str = "VECTORCRAFT_TEST_TITLEBAR_CHILD";
if std::env::var_os(CHILD).is_none() {
for value in ["app", "system", "desktop", "unknown"] {
// Linux and the BSDs: hold `spawning` while the child starts, so it does not keep a
// copy of a GPU start test's locked start file (see `CHILD_SPAWN`).
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
let spawning = super::spawning();
let child = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::the_titlebar_variable_decides_the_frame_before_the_window_opens", "--nocapture"])
.env(CHILD, "1")
.env("VECTORCRAFT_TITLEBAR", value)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn();
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
drop(spawning);
let output = child.unwrap().wait_with_output().unwrap();
assert!(
output.status.success(),
"VECTORCRAFT_TITLEBAR={value}\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
return;
}
let value = std::env::var("VECTORCRAFT_TITLEBAR").unwrap();
let not_read = cfg!(any(target_os = "macos", target_os = "windows"));
assert_eq!(super::titlebar_from_env(), !not_read && value != "unknown", "VECTORCRAFT_TITLEBAR={value}");
let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false}));
let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true}));
for (saved, opted_into_system) in [(None, false), (Some(&off), false), (Some(&on), true)] {
let (custom, _) = super::custom_titlebar(saved);
let expected = match value.as_str() {
_ if not_read => !cfg!(target_os = "macos") && !opted_into_system,
"app" => true,
"system" | "desktop" => false,
// Not a value the variable takes: System Title Bar decides when it is on. Otherwise the
// `craft-window` probe decides, the same with System Title Bar off as with no saved
// preferences.
_ if opted_into_system => false,
_ => super::custom_titlebar(None).0,
};
assert_eq!(custom, expected, "{value}, preference {opted_into_system}");
assert_eq!(super::native_options(custom).viewport.decorations, Some(!custom), "{value}, preference {opted_into_system}");
}
}
/// Preferences says under System Title Bar that the desktop draws the frame with it on or off
/// exactly where the start frame without VectorCraft Title Bar on Every Desktop is the desktop's
/// with System Title Bar off as well as on and `VECTORCRAFT_TITLEBAR` is unset: Linux and the BSDs
/// only.
#[test]
fn the_desktop_keeps_the_frame_where_system_title_bar_does_not_change_it() {
use crate::titlebar::desktop_keeps_frame_from;
use craft_window::{Frame, Layout};
let linux = cfg!(not(any(target_os = "macos", target_os = "windows")));
for probed in [Frame::Desktop, Frame::App(Layout::default())] {
for forced_to_x11 in [false, true] {
let frame = super::start_frame(probed.clone(), None, forced_to_x11, false);
let either_way = !super::custom_titlebar_from(&frame, false) && !super::custom_titlebar_from(&frame, true);
assert_eq!(desktop_keeps_frame_from(&probed, None, forced_to_x11), linux && either_way, "{probed:?} {forced_to_x11}");
}
}
// KDE, Sway and X11, and GNOME through XWayland, keep the desktop's frame; GNOME on Wayland does not.
assert_eq!(desktop_keeps_frame_from(&Frame::Desktop, None, false), linux);
assert_eq!(desktop_keeps_frame_from(&Frame::App(Layout::default()), None, true), linux);
assert!(!desktop_keeps_frame_from(&Frame::App(Layout::default()), None, false));
// While `VECTORCRAFT_TITLEBAR` chooses the frame, System Title Bar does not apply and there is no note.
for (frame, overridden) in [(Frame::App(Layout::default()), Some(true)), (Frame::Desktop, Some(false))] {
for forced_to_x11 in [false, true] {
assert!(!desktop_keeps_frame_from(&frame, overridden, forced_to_x11), "{overridden:?} {forced_to_x11}");
}
}
}
/// 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>"]
+130 -22
View File
@@ -31,7 +31,7 @@ pub(crate) fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String {
format!("{} ({:?}, {:?})", info.name.trim(), info.backend, info.device_type)
}
/// Windows and Linux: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`).
/// Windows: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`).
/// macOS keeps its traffic lights over the integrated title strip.
///
/// Used on macOS and Windows (where VectorCraft keeps today's frame regardless of the
@@ -41,11 +41,93 @@ pub(crate) const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos");
/// Whether the user asked for the system title bar in Preferences › User Interface › System Title
/// Bar. Read from the saved preferences before the window opens; a missing or unreadable value is
/// `false` (the default). This preference forces the desktop/native frame back on.
/// `false` (the default). This preference forces the desktop/native frame back on unless
/// `VECTORCRAFT_TITLEBAR` is set to `app`, `system` or `desktop` ([`system_title_bar_applies`]).
pub(crate) fn opted_into_system_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
saved.map(|ui| ui.engine_prefs.get("systemTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false)
}
/// Whether 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 the
/// variable is set to `app`, `system` or `desktop`;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. An app frame
/// the desktop left to the app (no `VECTORCRAFT_TITLEBAR` override, not forced onto XWayland) keeps
/// its window-button layout. An app frame turned on by `VECTORCRAFT_TITLEBAR=app` or by VectorCraft
/// Title Bar on Every Desktop gets the default layout: on those desktops the `button-layout` key that `craft-window` reads can
/// hold its schema default (`appmenu:close`) rather than the desktop's own buttons.
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(_)) if overridden.is_none() && !forced_to_x11 => frame,
(true, _) => craft_window::Frame::App(craft_window::Layout::default()),
(false, _) => craft_window::Frame::Desktop,
}
}
/// Where the app bar puts its caption buttons for `frame`: on Linux and the BSDs, the window-button
/// layout of an app frame, which `craft-window` reads from the desktop (the `button-layout` key of
/// `org.gnome.desktop.wm.preferences`); otherwise all three at the right. Each list is copied in the
/// key's order, first item leftmost, so `close,minimize,maximize:` puts Close at the left edge.
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub(crate) fn caption_layout_from(frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout {
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
let caption = |b: &craft_window::Button| match b {
craft_window::Button::Minimize => Caption::Minimize,
craft_window::Button::Maximize => Caption::Maximize,
craft_window::Button::Close => Caption::Close,
};
match frame.layout() {
Some(layout) => CaptionLayout { left: layout.left.iter().map(caption).collect(), right: layout.right.iter().map(caption).collect() },
None => CaptionLayout::default(),
}
}
/// macOS and Windows: all three caption buttons at the right, whatever the probe says (see
/// [`custom_titlebar_from`]).
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub(crate) fn caption_layout_from(_frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout {
vectorcraft_ui_egui::titlebar::CaptionLayout::default()
}
/// 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 › System Title Bar and VectorCraft Title Bar on Every Desktop do not apply while
/// it is set to `app`, `system` or `desktop`. 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 System Title Bar decides this start: `opted_into_system` unless `VECTORCRAFT_TITLEBAR`
/// is set to `app`, `system` or `desktop` (`from_env`), which chooses the frame for the run it is
/// set in.
pub(crate) fn system_title_bar_applies(opted_into_system: bool, from_env: bool) -> bool {
opted_into_system && !from_env
}
/// 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.
///
@@ -53,9 +135,10 @@ pub(crate) fn opted_into_system_title_bar(saved: Option<&vectorcraft_ui_egui::Ui
/// ([`craft_window::Frame::Desktop`]) on macOS, Windows, X11 and any Wayland compositor with
/// server-side decorations (KDE, Sway, Hyprland, COSMIC); the app draws it
/// ([`craft_window::Frame::App`]) only where the compositor leaves it to the app (GNOME's Mutter),
/// or when `VECTORCRAFT_TITLEBAR` overrides the probe. VectorCraft draws its own title bar exactly
/// or when `VECTORCRAFT_TITLEBAR` set to `app`, `system` or `desktop` overrides the probe. VectorCraft draws its own title bar exactly
/// when `craft-window` says the app owns the frame **and** the user has not opted into the system
/// title bar; the preference always forces the native frame back on.
/// title bar; the preference forces the native frame back on unless `VECTORCRAFT_TITLEBAR` is set
/// to one of those values ([`system_title_bar_applies`]).
///
/// macOS and Windows keep today's behavior and are decided by [`CUSTOM_TITLEBAR`] rather than the
/// probe: `craft-window` returns `Frame::Desktop` for both (the OS always draws a frame), but
@@ -75,31 +158,56 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
CUSTOM_TITLEBAR && !opted_into_system
}
/// Whether this start draws its own title bar. Probes the shared `craft-window` crate once (its
/// Whether this start draws its own title bar, and where its caption buttons go
/// ([`caption_layout_from`]). Probes the shared `craft-window` crate once (its
/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System
/// Title Bar preference. Call once at startup, before [`native_options`].
/// Title Bar preference, which does not apply while the variable is set to `app`, `system` or
/// `desktop`. Call once at startup,
/// before [`native_options`].
///
/// On Linux, Preferences › Performance › Linux Display Server › X11 opens the window through
/// XWayland (below). A GNOME/Wayland probe would say `Frame::App` there, but the window really runs
/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native
/// frame, the same as a real X11 session. An explicit `VECTORCRAFT_TITLEBAR` override still wins.
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
let choice = craft_window::Choice::probe(craft_window::Prefix::new("VECTORCRAFT"));
let opted_into_system = opted_into_system_title_bar(saved);
/// frame, the same as a real X11 session. A recognized `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, vectorcraft_ui_egui::titlebar::CaptionLayout) {
let choice = probed_choice();
let opted_into_system = system_title_bar_applies(opted_into_system_title_bar(saved), titlebar_from_env());
// 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), caption_layout_from(&frame))
}
/// Whether the desktop would draw this window's frame with System Title Bar on or off while
/// VectorCraft Title Bar on Every Desktop is off: `VECTORCRAFT_TITLEBAR` is not set to `app`,
/// `system` or `desktop` (`overridden` is `None`), and the probe chose
/// [`craft_window::Frame::Desktop`] or the window opens through XWayland (`forced_to_x11`)
/// ([`app_draws_frame`]). The saved VectorCraft Title Bar on Every Desktop is left out, so the value
/// stays `true` on such a desktop while that preference gives the app the frame. Always `false` on
/// macOS and Windows, where System Title Bar decides the frame by itself.
pub(crate) fn desktop_keeps_frame_from(probed: &craft_window::Frame, overridden: Option<bool>, forced_to_x11: bool) -> bool {
let probed_app = matches!(probed, craft_window::Frame::App(_));
cfg!(not(any(target_os = "macos", target_os = "windows"))) && overridden.is_none() && !app_draws_frame(probed_app, None, forced_to_x11, false)
}
/// [`desktop_keeps_frame_from`] for this start's probe, given whether the launch path opens the
/// window through XWayland.
pub(crate) fn desktop_keeps_frame(forced_to_x11: bool) -> bool {
let choice = probed_choice();
desktop_keeps_frame_from(choice.frame(), choice.overridden(), forced_to_x11)
}
pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
+85
View File
@@ -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)];
+338
View File
@@ -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);
}
}
+40
View File
@@ -0,0 +1,40 @@
//! Windows: the cores the process may run on, from its affinity mask, for the renderer's worker
//! count (`vectorcraft_render::set_usable_cores`). `available_parallelism` counts every processor
//! in the machine, also when the process may run on fewer (started with `start /affinity`, or
//! pinned by a launcher). The desktop app and `vectorcraft-cli` (exports, MCP) both install it; the
//! CLI shares this file.
//!
//! `GetProcessAffinityMask` is a C API with no safe binding, hence the scoped `unsafe_code`
//! allowance.
#![allow(unsafe_code)]
use windows::Win32::System::Threading::{GetCurrentProcess, GetProcessAffinityMask};
/// Tells the renderer how many cores the process may run on.
pub fn install() {
vectorcraft_render::set_usable_cores(usable_cores());
}
/// The number of cores in the process's affinity mask, or `None` when Windows reports none (a
/// process with threads in more than one processor group).
fn usable_cores() -> Option<usize> {
let (mut process, mut system) = (0usize, 0usize);
// SAFETY: `GetCurrentProcess` returns a pseudo-handle that needs no closing, and both pointers
// point at live `usize`s for the length of the call.
unsafe { GetProcessAffinityMask(GetCurrentProcess(), &mut process, &mut system) }.ok()?;
(process != 0).then(|| process.count_ones() as usize)
}
#[cfg(test)]
mod tests {
/// The mask Windows reports for this process gives at least one core and no more than the
/// machine has. (A child process started with `start /affinity` would test a one-core mask
/// end to end, but a process spawned while other tests hold sockets inherits them and resets
/// their connections; `automatic_threads` covers the one-core count.)
#[test]
fn the_affinity_mask_gives_the_cores_the_process_may_use() {
let cores = super::usable_cores().unwrap();
let all = std::thread::available_parallelism().unwrap().get();
assert!((1..=all).contains(&cores), "{cores} of {all}");
}
}
+56 -15
View File
@@ -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") };
+32 -21
View File
@@ -1,8 +1,10 @@
//! Linux: Preferences › Performance › Linux Display Server › X11 opens the window through XWayland
//! on a Wayland session, where dropped files arrive (winit 0.30 has no Wayland drag and drop,
//! #1151). X11 (XWayland) When a Pen Is Attached does so only when a pen is attached as the app
//! starts: winit 0.30 doesn't bind the Wayland tablet protocol, and XWayland hands the pen to X11
//! windows as a pointer (#2028). Only when XWayland can run the window: an X display is set and
//! #1151). Automatic and X11 (XWayland) When a Pen Is Attached do so only when a pen is attached
//! as the app starts, as PhotoCraft does: winit 0.30 doesn't bind the Wayland tablet protocol, so
//! on native Wayland the pen moves only the compositor's cursor, and XWayland hands the pen to X11
//! windows as a pointer (#2028, #4967). `VECTORCRAFT_NATIVE_WAYLAND=1` keeps a pen's window on
//! Wayland. Only when XWayland can run the window: an X display is set and
//! the X11 libraries winit loads at runtime are installed. Otherwise the window opens on Wayland,
//! so a missing library never keeps the app from starting.
//!
@@ -21,16 +23,17 @@ const X11_LIBS: &[&str] =
&["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"];
/// Whether the saved `linuxDisplayServer` and the environment ask for XWayland: `x11` chosen, or
/// `x11WithPen` chosen and `pen` finding a pen; a Wayland session (winit picks Wayland whenever
/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only for
/// `x11WithPen`, after the session checks.
/// any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen and
/// `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`); a Wayland session (winit picks Wayland whenever
/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only after
/// the other checks.
pub fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option<OsString>, pen: impl FnOnce() -> bool) -> bool {
let set = |name: &str| var(name).is_some_and(|v| !v.is_empty());
let session = (set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET")) && set("DISPLAY");
let native_wayland = var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0");
match pref {
Some("x11") => session,
Some("x11WithPen") => session && pen(),
_ => false,
_ => session && !native_wayland && pen(),
}
}
@@ -149,27 +152,35 @@ mod tests {
let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]);
assert!(wanted(Some("x11"), &wayland, no_probe));
assert!(wanted(Some("x11"), env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), no_probe));
assert!(!wanted(Some("automatic"), &wayland, no_probe));
assert!(!wanted(None, &wayland, no_probe));
assert!(!wanted(Some("wayland"), &wayland, no_probe));
assert!(!wanted(Some("automatic"), &wayland, || false));
assert!(!wanted(None, &wayland, || false));
// An X11 session already opens on X11; without an X display there is no XWayland to use.
assert!(!wanted(Some("x11"), env(&[("DISPLAY", ":0")]), no_probe));
assert!(!wanted(Some("x11"), env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe));
assert!(!wanted(Some("x11"), env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe));
}
/// X11 (XWayland) When a Pen Is Attached (#2028): XWayland on a Wayland session with an X
/// display when a pen is found, the session's own display server otherwise. The pen check
/// runs only on such a session.
/// Automatic and X11 (XWayland) When a Pen Is Attached (#2028, #4967): XWayland on a Wayland
/// session with an X display when a pen is found, where the pen reaches the window, the
/// session's own display server otherwise. The pen check runs only on such a session, and
/// `VECTORCRAFT_NATIVE_WAYLAND` keeps Wayland.
#[test]
fn the_pen_choice_opens_xwayland_only_with_a_pen() {
fn a_pen_opens_xwayland_unless_native_wayland_is_asked_for() {
let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]);
assert!(wanted(Some("x11WithPen"), &wayland, || true));
assert!(wanted(Some("x11WithPen"), env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), || true));
assert!(!wanted(Some("x11WithPen"), &wayland, || false));
assert!(!wanted(Some("x11WithPen"), env(&[("DISPLAY", ":0")]), no_probe));
assert!(!wanted(Some("x11WithPen"), env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe));
assert!(!wanted(Some("x11WithPen"), env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe));
let native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "1")]);
let not_native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "0")]);
for pref in [Some("automatic"), None, Some("x11WithPen")] {
assert!(wanted(pref, &wayland, || true), "{pref:?}");
assert!(wanted(pref, env(&[("WAYLAND_SOCKET", "3"), ("DISPLAY", ":0")]), || true), "{pref:?}");
assert!(!wanted(pref, &wayland, || false), "{pref:?}");
assert!(!wanted(pref, env(&[("DISPLAY", ":0")]), no_probe), "{pref:?}");
assert!(!wanted(pref, env(&[("WAYLAND_DISPLAY", "wayland-0")]), no_probe), "{pref:?}");
assert!(!wanted(pref, env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", "")]), no_probe), "{pref:?}");
assert!(!wanted(pref, &native, no_probe), "{pref:?}");
assert!(wanted(pref, &not_native, || true), "{pref:?}");
}
// The X11 choice opens XWayland with or without a pen; the opt-out is for the pen only.
assert!(wanted(Some("x11"), &native, no_probe));
}
/// `/proc/bus/input/devices` of a laptop with a Wacom Intuos Pro attached (64-bit longs: the
+5 -6
View File
@@ -1,8 +1,6 @@
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft");
/// Invalid roots must exit before desktop initialization on every platform, including a CI
/// machine with no display. A regression must fail rather than hang with a window open.
fn rejects(args: &[&str], message: &str) {
@@ -10,7 +8,7 @@ fn rejects(args: &[&str], message: &str) {
}
fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) {
let mut child = Command::new(BIN)
let mut child = Command::new(crate::bin())
.args(args)
.env_remove("VECTORCRAFT_CONTROL_PORT")
.env_remove("VECTORCRAFT_AUTOMATION_READ_ROOT")
@@ -62,7 +60,7 @@ fn missing_empty_or_option_operands_fail_before_startup() {
#[test]
fn repeated_roots_are_accepted_for_both_spellings() {
for flag in ["--automation-read-root", "--automation-write-root"] {
let out = Command::new(BIN).args([flag, ".", format!("{flag}=.").as_str(), flag, "./", "--version"]).output().unwrap();
let out = Command::new(crate::bin()).args([flag, ".", format!("{flag}=.").as_str(), flag, "./", "--version"]).output().unwrap();
assert!(out.status.success(), "{flag}: {}", String::from_utf8_lossy(&out.stderr));
assert_eq!(String::from_utf8(out.stdout).unwrap(), format!("vectorcraft {}\n", env!("CARGO_PKG_VERSION")));
assert!(out.stderr.is_empty());
@@ -73,7 +71,8 @@ fn repeated_roots_are_accepted_for_both_spellings() {
#[test]
fn explicit_dash_folder_does_not_consume_version() {
let out = Command::new(BIN).args(["--automation-read-root=-folder", "--automation-write-root", "./-folder", "--version"]).output().unwrap();
let out =
Command::new(crate::bin()).args(["--automation-read-root=-folder", "--automation-write-root", "./-folder", "--version"]).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert_eq!(String::from_utf8(out.stdout).unwrap(), format!("vectorcraft {}\n", env!("CARGO_PKG_VERSION")));
assert!(out.stderr.is_empty());
@@ -95,7 +94,7 @@ fn control_without_a_valid_port_fails_before_startup() {
#[test]
fn version_wins_over_a_bad_control_port_variable() {
let out = Command::new(BIN).arg("--version").env("VECTORCRAFT_CONTROL_PORT", "abc").output().unwrap();
let out = Command::new(crate::bin()).arg("--version").env("VECTORCRAFT_CONTROL_PORT", "abc").output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert_eq!(String::from_utf8(out.stdout).unwrap(), format!("vectorcraft {}\n", env!("CARGO_PKG_VERSION")));
}
+26 -4
View File
@@ -6,12 +6,10 @@ use std::process::{Command, Output, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft");
/// Runs the desktop binary without a display and with a control port it cannot parse, so a
/// regression exits with that error instead of opening a window.
fn run(args: &[&str], env: &[(&str, &str)]) -> Output {
let mut child = Command::new(BIN)
let mut child = Command::new(crate::bin())
.args(args)
.env_remove("DISPLAY")
.env_remove("WAYLAND_DISPLAY")
@@ -54,7 +52,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 +72,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}");
}
+8
View File
@@ -4,3 +4,11 @@
mod automation_args;
mod help;
/// Nextest relocates archived binaries; Cargo's compile-time path still names the build runner.
fn bin() -> std::path::PathBuf {
std::env::var_os("NEXTEST_BIN_EXE_vectorcraft")
.or_else(|| std::env::var_os("CARGO_BIN_EXE_vectorcraft"))
.map(std::path::PathBuf::from)
.unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft").into())
}
+1 -3
View File
@@ -16,9 +16,7 @@ head-and-shoulders portrait on a full-bleed field, no frame or roundel, with the
**Tile:** `viewBox="0 0 512 512"`, a rounded square with `rx=112`, clipped. The macOS files add Apple's
transparent margin (tile = 824/1024 of the canvas); Windows and Linux use the tile edge to edge.
**Provenance:** the owner's original ArtCraft drawing (2880 px, keyed to the palette), vectorised with
craftrules `assets/logo-options/_tools/vectorize_tile.py`. The drawing is kept in craftrules at
`craftrules/assets/app-icons/vectorcraft/source.png`, not here. `vectorcraft.svg` is the canonical
**Provenance:** the owner's original ArtCraft drawing, vectorised. `vectorcraft.svg` is the canonical
artwork. Licence: see `LICENSE.txt`.
## Files
+1
View File
@@ -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
View File
@@ -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="butt" stroke-linejoin="miter"><defs><clipPath id="c"><rect x="3.5" y="3.5" width="17" height="17"/></clipPath></defs><g clip-path="url(#c)" stroke="none" fill="white"><path d="M12 12L26 12L21.9 21.9Z" fill-opacity="0.1"/><path d="M12 12L21.9 21.9L12 26Z" fill-opacity="0.23"/><path d="M12 12L12 26L2.1 21.9Z" fill-opacity="0.36"/><path d="M12 12L2.1 21.9L-2 12Z" fill-opacity="0.49"/><path d="M12 12L-2 12L2.1 2.1Z" fill-opacity="0.61"/><path d="M12 12L2.1 2.1L12 -2Z" fill-opacity="0.74"/><path d="M12 12L12 -2L21.9 2.1Z" fill-opacity="0.87"/><path d="M12 12L21.9 2.1L26 12Z"/></g><rect x="3.5" y="3.5" width="17" height="17" stroke="currentColor" stroke-width="1"/></svg>

After

Width:  |  Height:  |  Size: 826 B

+1
View File
@@ -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="butt" stroke-linejoin="miter"><defs><linearGradient id="a" gradientUnits="userSpaceOnUse" x1="12" y1="12" x2="3.5" y2="3.5"><stop offset="0" stop-color="white" stop-opacity="0.1"/><stop offset="1" stop-color="white"/></linearGradient><linearGradient id="b" gradientUnits="userSpaceOnUse" x1="12" y1="12" x2="20.5" y2="3.5"><stop offset="0" stop-color="white" stop-opacity="0.1"/><stop offset="1" stop-color="white"/></linearGradient><linearGradient id="c" gradientUnits="userSpaceOnUse" x1="12" y1="12" x2="20.5" y2="20.5"><stop offset="0" stop-color="white" stop-opacity="0.1"/><stop offset="1" stop-color="white"/></linearGradient><linearGradient id="d" gradientUnits="userSpaceOnUse" x1="12" y1="12" x2="3.5" y2="20.5"><stop offset="0" stop-color="white" stop-opacity="0.1"/><stop offset="1" stop-color="white"/></linearGradient></defs><g stroke="none"><rect x="3.5" y="3.5" width="8.5" height="8.5" fill="url(#a)"/><rect x="12" y="3.5" width="8.5" height="8.5" fill="url(#b)"/><rect x="12" y="12" width="8.5" height="8.5" fill="url(#c)"/><rect x="3.5" y="12" width="8.5" height="8.5" fill="url(#d)"/></g><rect x="3.5" y="3.5" width="17" height="17" stroke="currentColor" stroke-width="1"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

+1 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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

+1
View File
@@ -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

+1
View File
@@ -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
View File
@@ -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

+1
View File
@@ -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

+17
View File
@@ -0,0 +1,17 @@
<!-- @license lucide-static v1.49.0 - ISC -->
<svg
class="lucide lucide-graduation-cap"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z" />
<path d="M22 10v6" />
<path d="M6 12.5V16a6 3 0 0 0 12 0v-3.5" />
</svg>

After

Width:  |  Height:  |  Size: 497 B

+58 -5
View File
@@ -1,13 +1,10 @@
# Contributor names for the About window (craftrules standards/contributors.md).
# Contributor names for the About window.
#
# Everyone who contributes is credited by GitHub username automatically. Anything more is up to
# you: add YOUR OWN entry below, in your own PR (commit it yourself). Never add someone else; a
# maintainer may add a person only when that person asked, recording where in consent_source.
#
# Easiest: python3 ../../craftrules/scripts/contributors.py --add-me . \
# [--real-name "Ada Lovelace"] [--display-name "Ada"] [--sync-github-name]
#
# Or copy this block, replacing your-github-username (every field is optional):
# Copy this block, replacing your-github-username (every field is optional):
#
# [people.your-github-username]
# real_name = "Your Name" # shown when the viewer picks "Real name"
@@ -17,6 +14,11 @@
# To remove your names, delete your entry (or set fields empty) in a PR. The next
# contributors.py run, and the next build, drop them.
[people.el-j]
real_name = "Fabian Althaus"
display_name = "faff (el-j)"
sync_github_name = false
[people.lollinoo]
sync_github_name = true
@@ -172,3 +174,54 @@ sync_github_name = false
[people.krosk93]
sync_github_name = true
[people.ashokram-si]
real_name = "Ashok Ram"
[people.dylanmtaylor]
sync_github_name = true
[people.marshiyar]
display_name = "Arshiya"
real_name = "Arshiya Rahgozar"
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
[people.Hassan1305]
real_name = "Hassan Nawaz Khan"
display_name = "Hassan Nawaz Khan"
sync_github_name = false
+6 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "vectorcraft-affinity"
description = "Bounded reader for native Affinity documents: archive, object stream and document model"
description = "craft-affinity under its old name, for the corpus tests and fuzz targets"
version.workspace = true
edition.workspace = true
license.workspace = true
@@ -11,13 +11,13 @@ workspace = true
[features]
# Synthetic-container builders for tests and fuzz seeds; not an Affinity exporter.
synth = []
synth = ["craft-affinity/synth"]
[dependencies]
crc32fast = { workspace = true }
flate2 = { workspace = true }
image = { workspace = true }
ruzstd = "0.9.1"
craft-affinity = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
# The tests build containers and decode previews.
crc32fast = { workspace = true }
image = { workspace = true }
+6 -3
View File
@@ -1,5 +1,7 @@
# vectorcraft-affinity
The reader is [`craft-affinity`](https://github.com/storytold/craft-libs/tree/main/crates/affinity) in craft-libs; this crate re-exports it under its old name for the corpus tests and fuzz targets. The engine maps its document onto VectorCraft art (`crates/engine/src/cmd/fileio/affinity`), as described below.
An independent, bounded Rust reader for native Affinity documents: `.af` from Affinity 3 and
`.afdesign`, `.afphoto` and `.afpub` from Affinity 1 and 2 (container versions 8 to 12). It reads
the archive, the tagged object stream in `doc.dat` and the part of the document model listed below,
@@ -17,12 +19,13 @@ Affinity files.
| Curves (`PCrv`): cubic subpaths, closed flags, live corners (`CnrD`) | paths (multi-subpath curves fill even-odd) |
| Rectangles with corner radii (relative or absolute, locked or per corner) and round or straight corners, ellipses, polygons (smooth too), stars, square stars, pies, triangles, trapezoids | paths |
| Compound shapes (`Comp`, add and subtract) | one even-odd path |
| A shape or curve with children clips them | clip group whose clipping path keeps its fill (behind) and stroke (over) |
| A shape, curve or text with children clips them | clip group whose clipping path keeps its fill (behind) and stroke (over) |
| Vector masks (`AdCh` curves and shapes) | clip group |
| Pixel masks (`MRst`, attached or as a layer in a group) | opacity mask |
| Solid fills: RGBA, HSLA, CMYK, grey, Lab (D50) | fill appearance (alpha as fill opacity) |
| Linear, elliptical and radial gradients with Affinity's midpoint bias | gradients (the bias as the midpoint where the blend is half way) |
| Strokes: weight, scale with object, dash pattern and phase, alignment, miter limit, behind the fill; 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,8 +36,8 @@ 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,
transparency gradients, fill opacity, bitmap fills, master pages based on other master pages, conical gradients (as radial),
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,
special shapes (cloud, heart, cog, callouts, arrows…, imported as their bounding ellipse), corner
types other than round or straight, stars with rounded points, several fills or strokes on one object (the
active one is used), skewed or flipped text, characters of different transparency in one text, text fields such as page numbers, text threading, frames with
-105
View File
@@ -1,105 +0,0 @@
//! Typed reads of [`Stream`] objects. Every accessor returns `None` when a field is missing or has
//! another type, so the document mapping treats odd data as absent rather than failing.
use crate::stream::{ObjId, Object, Stream, Tag, Value};
impl Stream {
pub fn object(&self, id: ObjId) -> Option<&Object> {
self.objects.get(id)
}
pub fn field(&self, id: ObjId, tag: &[u8; 4]) -> Option<&Value> {
self.object(id)?.get(Tag::of(tag))
}
pub fn class(&self, id: ObjId) -> Option<Tag> {
self.object(id).map(|o| o.class)
}
pub fn is(&self, id: ObjId, class: &[u8; 4]) -> bool {
self.class(id) == Some(Tag::of(class))
}
/// A child object (shared, linked or inline); `None` for null or missing.
pub fn obj(&self, id: ObjId, tag: &[u8; 4]) -> Option<ObjId> {
match self.field(id, tag)? {
Value::Obj(o) => *o,
_ => None,
}
}
/// An array of objects (nulls skipped).
pub fn objs(&self, id: ObjId, tag: &[u8; 4]) -> Vec<ObjId> {
match self.field(id, tag) {
Some(Value::Array(a)) => a.iter().filter_map(|v| if let Value::Obj(Some(o)) = v { Some(*o) } else { None }).collect(),
_ => Vec::new(),
}
}
pub fn f64(&self, id: ObjId, tag: &[u8; 4]) -> Option<f64> {
match self.field(id, tag)? {
Value::Float(f) if f.is_finite() => Some(*f),
_ => None,
}
}
pub fn int(&self, id: ObjId, tag: &[u8; 4]) -> Option<i64> {
match self.field(id, tag)? {
Value::Int(i) => Some(*i),
Value::UInt(u) => i64::try_from(*u).ok(),
_ => None,
}
}
pub fn bool(&self, id: ObjId, tag: &[u8; 4]) -> Option<bool> {
match self.field(id, tag)? {
Value::Bool(b) => Some(*b),
_ => None,
}
}
pub fn str(&self, id: ObjId, tag: &[u8; 4]) -> Option<&str> {
match self.field(id, tag)? {
Value::Str(s) => Some(s),
_ => None,
}
}
pub fn enumeration(&self, id: ObjId, tag: &[u8; 4]) -> Option<(u16, u16)> {
match self.field(id, tag)? {
Value::Enum { id, version } => Some((*id, *version)),
_ => None,
}
}
/// A fixed vector of `N` finite floats (points, rectangles, transforms).
pub fn floats<const N: usize>(&self, id: ObjId, tag: &[u8; 4]) -> Option<[f64; N]> {
match self.field(id, tag)? {
Value::Floats(v) if v.len() == N && v.iter().all(|f| f.is_finite()) => {
let mut a = [0.0; N];
a.copy_from_slice(v);
Some(a)
}
_ => None,
}
}
pub fn bytes(&self, id: ObjId, tag: &[u8; 4]) -> Option<&[u8]> {
match self.field(id, tag)? {
Value::Bytes(b) | Value::Blob(b) => Some(b),
_ => None,
}
}
pub fn entry(&self, id: ObjId, tag: &[u8; 4]) -> Option<&str> {
match self.field(id, tag)? {
Value::Entry(s) => Some(s),
_ => None,
}
}
/// Untagged fields of a positional object, in order.
pub fn positional(&self, id: ObjId) -> impl Iterator<Item = &Value> {
self.object(id).into_iter().flat_map(|o| o.fields.iter().map(|(_, v)| v))
}
}
-386
View File
@@ -1,386 +0,0 @@
//! The Affinity archive: header, the chain of file allocation tables (one per save) and
//! bounded, CRC-checked extraction of named entries such as `doc.dat` and raster tiles.
use std::collections::{HashMap, HashSet};
use std::io::Read;
use crate::Error;
pub const MAGIC: &[u8; 4] = b"\x00\xffKA";
/// Oldest and newest container versions seen in real documents (Affinity 1.x writes 8,
/// Affinity 3 writes 12). Version 7 is described by afread but no sample exists.
pub const VERSIONS: std::ops::RangeInclusive<u16> = 8..=12;
/// `Prsn` (stored byte-reversed): documents. Asset, brush and style libraries share the magic.
const DOCUMENT_KIND: &[u8; 4] = b"nsrP";
/// A save appends one table; real files have one to a few hundred.
const MAX_TABLES: usize = 4096;
/// zstd window ceiling: real documents use a few MiB; this stops a header from reserving gigabytes.
const MAX_ZSTD_WINDOW: u64 = 64 << 20;
/// Decompression budget for one import. Every entry declares its size, which is checked against
/// these limits before anything is allocated, and the decoded length must match it exactly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limits {
/// Largest single entry (`doc.dat` or one tile).
pub max_entry: usize,
/// Total bytes extracted over the whole import.
pub max_total: usize,
}
impl Default for Limits {
fn default() -> Self {
Self { max_entry: 256 << 20, max_total: 1 << 30 }
}
}
/// The container header, all integers little-endian.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Header {
pub version: u16,
/// Seen as 0, 4 or 8 in real files; bits 0 and 1 mark container variants that are rejected.
pub flags: u16,
pub(crate) fat_offset: u64,
pub(crate) thumbnail_offset: u64,
/// Save time in Unix seconds, as written by the application.
pub saved: u32,
}
/// One FAT record, as of the newest table that mentions its id.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
pub id: u32,
pub name: String,
offset: u64,
size: u64,
compressed: u64,
crc: u32,
compression: u8,
}
impl Entry {
/// Decompressed size declared by the table.
pub fn size(&self) -> u64 {
self.size
}
}
#[derive(Debug)]
pub struct Archive<'a> {
bytes: &'a [u8],
pub header: Header,
/// Head revision of every named, non-deleted entry.
entries: HashMap<String, Entry>,
/// Number of tables (saves) in the chain.
pub revisions: usize,
extracted: usize,
limits: Limits,
}
pub(crate) struct Cursor<'a> {
bytes: &'a [u8],
pub(crate) pos: usize,
}
impl<'a> Cursor<'a> {
pub(crate) fn new(bytes: &'a [u8], pos: usize) -> Self {
Self { bytes, pos }
}
pub(crate) fn remaining(&self) -> usize {
self.bytes.len().saturating_sub(self.pos)
}
pub(crate) fn take(&mut self, n: usize) -> Result<&'a [u8], Error> {
let end = self.pos.checked_add(n).ok_or(Error::Malformed("length overflow"))?;
let s = self.bytes.get(self.pos..end).ok_or(Error::Malformed("truncated data"))?;
self.pos = end;
Ok(s)
}
pub(crate) fn array<const N: usize>(&mut self) -> Result<[u8; N], Error> {
let s = self.take(N)?;
let mut a = [0u8; N];
a.copy_from_slice(s);
Ok(a)
}
pub(crate) fn u8(&mut self) -> Result<u8, Error> {
Ok(self.array::<1>()?[0])
}
pub(crate) fn u16(&mut self) -> Result<u16, Error> {
Ok(u16::from_le_bytes(self.array()?))
}
pub(crate) fn u32(&mut self) -> Result<u32, Error> {
Ok(u32::from_le_bytes(self.array()?))
}
pub(crate) fn u64(&mut self) -> Result<u64, Error> {
Ok(u64::from_le_bytes(self.array()?))
}
}
fn offset(v: u64) -> Result<usize, Error> {
usize::try_from(v).map_err(|_| Error::Malformed("offset beyond addressable memory"))
}
/// True when `bytes` start with the Affinity container signature (documents and libraries).
pub fn is_affinity(bytes: &[u8]) -> bool {
bytes.starts_with(MAGIC)
}
/// Check the signature, version and document kind.
pub fn header(bytes: &[u8]) -> Result<Header, Error> {
if !is_affinity(bytes) {
return Err(Error::Malformed("missing container signature"));
}
let mut c = Cursor::new(bytes, 4);
let version = c.u16()?;
let flags = c.u16()?;
if !VERSIONS.contains(&version) {
return Err(Error::Unsupported("unknown container version"));
}
if flags & 3 != 0 {
return Err(Error::Unsupported("container variant"));
}
if c.take(4)? != DOCUMENT_KIND {
return Err(Error::Unsupported("this Affinity file is a library (assets, brushes or styles), not a document"));
}
if c.take(4)? != b"#Inf" {
return Err(Error::Malformed("missing information header"));
}
let fat_offset = c.u64()?;
let thumbnail_offset = c.u64()?;
c.take(16)?;
let saved = u32::try_from(c.u64()?).unwrap_or(0);
c.take(8)?;
if c.take(4)? != b"Prot" {
return Err(Error::Malformed("missing protocol header"));
}
Ok(Header { version, flags, fat_offset, thumbnail_offset, saved })
}
impl<'a> Archive<'a> {
pub fn open(bytes: &'a [u8], limits: Limits) -> Result<Self, Error> {
let header = header(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();
let mut seen = HashSet::new();
let mut next = header.fat_offset;
let mut tables = 0usize;
while next != 0 {
if !seen.insert(next) {
return Err(Error::Malformed("allocation tables form a cycle"));
}
tables += 1;
if tables > MAX_TABLES {
return Err(Error::Limit("too many saved revisions"));
}
let mut c = Cursor::new(bytes, offset(next)?);
let tag = c.array::<4>()?;
let level = match &tag {
b"#FAT" => 1,
b"#FT2" => 2,
b"#FT3" => 3,
b"#FT4" => 4,
_ => return Err(Error::Malformed("missing allocation table")),
};
next = c.u64()?;
let date = c.u64()?;
c.take(24)?;
let files = c.u32()?;
c.take(8)?;
let dirs = c.u16()?;
c.take(1)?;
for _ in 0..files {
let id = c.u32()?;
let flag = c.u8()?;
let mut record = None;
match flag {
0 | 1 => {
let offset = c.u64()?;
let size = c.u64()?;
let compressed = c.u64()?;
let crc = c.u32()?;
let stored = c.u8()?;
if level >= 2 {
c.take(4)?;
}
if level >= 4 {
c.take(4)?;
}
// Old tables number the methods; newer ones store the method byte itself.
let compression = if level <= 2 {
match stored {
1 => 0x01,
2 => 0x41,
3 => 0x81,
4 => 0xC1,
_ => 0,
}
} else {
stored
};
record = Some(Entry { id, name: String::new(), offset, size, compressed, crc, compression });
}
2 => {}
_ => return Err(Error::Malformed("unknown allocation record")),
}
if flag == 0 {
let len = usize::from(c.u16()?);
let name = String::from_utf8_lossy(c.take(len)?).into_owned();
names.entry(id).or_insert(name);
}
// Equal dates: the first table in the chain (the newest) wins, as in afread.
let replace = latest.get(&id).is_none_or(|(d, _, _)| date > *d);
if replace {
latest.insert(id, (date, tables, record));
}
}
for _ in 0..dirs {
let len = usize::from(c.u16()?);
c.take(10)?;
c.take(len)?;
}
}
let mut entries = HashMap::new();
for (id, (_, _, record)) in latest {
if let (Some(mut e), Some(name)) = (record, names.get(&id)) {
e.name = name.clone();
entries.insert(e.name.clone(), e);
}
}
Ok(Self { bytes, header, entries, revisions: tables, extracted: 0, limits })
}
pub fn entry(&self, name: &str) -> Option<&Entry> {
self.entries.get(name)
}
pub fn entry_names(&self) -> impl Iterator<Item = &str> {
self.entries.keys().map(String::as_str)
}
/// Bytes extracted so far, counted against [`Limits::max_total`].
pub fn extracted(&self) -> usize {
self.extracted
}
/// Extract an entry by name: decompress, undo the byte predictor and verify the CRC.
/// What is left of the limits for documents embedded in this one.
pub(crate) fn remaining(&self) -> Limits {
Limits { max_entry: self.limits.max_entry, max_total: self.limits.max_total.saturating_sub(self.extracted) }
}
/// Count `n` bytes extracted elsewhere (from embedded documents) against this import.
pub(crate) fn charge(&mut self, n: usize) -> Result<(), Error> {
let total = self.extracted.checked_add(n).ok_or(Error::Limit("document too large"))?;
if total > self.limits.max_total {
return Err(Error::Limit("document too large"));
}
self.extracted = total;
Ok(())
}
pub fn read(&mut self, name: &str) -> Result<Vec<u8>, Error> {
let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?.clone();
let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?;
if size > self.limits.max_entry {
return Err(Error::Limit("archive entry too large"));
}
let total = self.extracted.checked_add(size).ok_or(Error::Limit("document too large"))?;
if total > self.limits.max_total {
return Err(Error::Limit("document too large"));
}
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"));
}
self.extracted = total;
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> {
let mut out = Vec::with_capacity(size.min(64 << 20));
let cap = u64::try_from(size).unwrap_or(u64::MAX).saturating_add(1);
r.by_ref().take(cap).read_to_end(&mut out).map_err(|_| Error::Malformed("corrupt compressed entry"))?;
Ok(out)
}
fn inflate(data: &[u8], size: usize) -> Result<Vec<u8>, Error> {
read_bounded(flate2::read::ZlibDecoder::new(data), size)
}
fn unzstd(data: &[u8], size: usize) -> Result<Vec<u8>, Error> {
let mut src = data;
let mut out = Vec::new();
// Entries may hold several concatenated frames.
while !src.is_empty() {
let left = size.checked_sub(out.len()).ok_or(Error::Malformed("archive entry size mismatch"))?;
let decoder = ruzstd::decoding::StreamingDecoder::new_with_max_window_size(&mut src, MAX_ZSTD_WINDOW)
.map_err(|_| Error::Malformed("corrupt compressed entry"))?;
let frame = read_bounded(decoder, left)?;
if frame.is_empty() {
return Err(Error::Malformed("corrupt compressed entry"));
}
out.extend_from_slice(&frame);
if out.len() > size {
return Err(Error::Malformed("archive entry size mismatch"));
}
}
Ok(out)
}
/// Undo the byte predictor selected by the high bits of the compression byte.
fn unpredict(b: &mut [u8], compression: u8) -> Result<(), Error> {
match (compression & 0xC0, compression & 0x20 != 0) {
(0x00, _) => {}
(0x40, _) => byte_delta(b),
(0x80, false) => {
let mut prev = 0u16;
for pair in b.as_chunks_mut::<2>().0.iter_mut() {
let v = u16::from_le_bytes([pair[0], pair[1]]).wrapping_add(prev);
pair.copy_from_slice(&v.to_le_bytes());
prev = v;
}
}
(0x80, true) => {
byte_delta(b);
// A 64 KiB tile of 16-bit samples is stored as all high bytes, then all low bytes.
if b.len() == 0x10000 {
let planes = b.to_vec();
let (hi, lo) = planes.split_at(0x8000);
for (i, out) in b.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let (Some(h), Some(l)) = (hi.get(2 * i..2 * i + 2), lo.get(2 * i..2 * i + 2)) else {
return Err(Error::Malformed("tile size"));
};
out.copy_from_slice(&[l[0], h[0], l[1], h[1]]);
}
}
}
_ => return Err(Error::Unsupported("archive entry predictor")),
}
Ok(())
}
fn byte_delta(b: &mut [u8]) {
let mut prev = 0u8;
for v in b {
*v = v.wrapping_add(prev);
prev = *v;
}
}
-262
View File
@@ -1,262 +0,0 @@
//! Outlines of curves (`PCvD` node lists), parametric shapes (`Shpe` objects) and compounds, in
//! node space.
use crate::model::{Affine, Path, Point, Reader, SubPath};
use crate::stream::{ObjId, Tag, Value};
/// Nodes per curve object.
const MAX_NODES: usize = 4_000_000;
/// A shared-object stream is bounded, but a compound graph can expand exponentially. Count
/// each visit and each curve record / generated contour / transformed segment across the whole
/// outline, including repeated references. Match the document reader's nesting limit.
const MAX_OUTLINE_DEPTH: usize = 128;
const MAX_OUTLINE_VISITS: usize = 100_000;
struct OutlineBudget {
active: Vec<ObjId>,
visits: usize,
work: usize,
failed: bool,
}
impl OutlineBudget {
fn fail(&mut self, r: &mut Reader, warning: &'static str) -> Option<()> {
if !self.failed {
r.warn(warning);
}
self.failed = true;
None
}
fn spend(&mut self, r: &mut Reader, work: usize) -> Option<()> {
if work > self.work {
return self.fail(r, "compound outlines exceeding the geometry work limit");
}
self.work -= work;
Some(())
}
fn path(&mut self, r: &mut Reader, path: &Path) -> Option<()> {
for subpath in &path.subpaths {
self.spend(r, 1)?;
self.spend(r, subpath.segments.len())?;
}
Some(())
}
}
/// The node-space outline of a curve, shape or compound node, and whether it fills even-odd.
/// Instances (master-page or symbol copies) take the geometry of their master.
pub(crate) fn outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine) -> Option<(Path, bool)> {
let mut budget = OutlineBudget { active: Vec::new(), visits: MAX_OUTLINE_VISITS, work: MAX_NODES, failed: false };
bounded_outline(r, id, class, world, &mut budget)
}
fn bounded_outline(r: &mut Reader, id: ObjId, class: Tag, world: Affine, budget: &mut OutlineBudget) -> Option<(Path, bool)> {
if budget.active.contains(&id) {
budget.fail(r, "a compound outline that contains itself")?;
}
if budget.active.len() >= MAX_OUTLINE_DEPTH {
budget.fail(r, "compound outlines nested deeper than 128 levels")?;
}
if budget.visits == 0 {
budget.fail(r, "compound outlines exceeding the operand visit limit")?;
}
budget.visits -= 1;
budget.active.push(id);
let result = outline_inner(r, id, class, world, budget);
// The popped value is our own stack marker, and is no longer needed.
let _ = budget.active.pop();
result
}
fn outline_inner(r: &mut Reader, id: ObjId, class: Tag, world: Affine, budget: &mut OutlineBudget) -> Option<(Path, bool)> {
let s = r.s;
match &class.0.to_be_bytes() {
b"PCrv" | b"TxtC" => {
let crvs = s.obj(id, b"Crvs").or_else(|| s.obj(id, b"MCrM").and_then(|m| s.obj(m, b"Crvs")))?;
let path = curves(r, crvs, budget)?;
budget.path(r, &path)?;
let multi = path.subpaths.len() > 1;
Some((path, multi))
}
b"Comp" => {
// One path of all the operands' contours in the compound's space, filled even-odd: this
// matches add and subtract operands in every public sample; a true union of overlapping
// added operands would differ.
let mut path = Path::default();
for c in s.objs(id, b"Chld") {
let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
let class = s.class(c)?;
if s.enumeration(c, b"ComO").is_some_and(|(op, _)| op != 0 && op != 2) {
r.warn("compound shapes that intersect or exclude (imported as add)");
}
let child_world = local.then(world);
if !child_world.is_finite() {
budget.fail(r, "a compound operand with an invalid transform")?;
}
if let Some((mut p, _)) = bounded_outline(r, c, class, child_world, budget) {
// Charge before transforming or extending. Transform the owned path in place
// so nested compounds do not make an additional copy of every contour.
budget.path(r, &p)?;
for subpath in &mut p.subpaths {
subpath.start = local.apply(subpath.start);
for segment in &mut subpath.segments {
*segment = segment.map(|point| local.apply(point));
}
}
path.subpaths.extend(p.subpaths);
} else if budget.failed {
// Never present a partial compound as complete after a cycle or budget limit.
return None;
}
}
Some((path, true))
}
_ => {
let (shape, box_owner) = match s.obj(id, b"Shpe") {
Some(sh) => (sh, id),
None => {
let master = s.obj(id, b"ShpM")?;
(s.obj(master, b"Shpe")?, master)
}
};
let b = s.floats::<4>(box_owner, b"ShpB")?;
let path = crate::shapes::shape(r, shape, b, world)?;
budget.path(r, &path)?;
Some((path, false))
}
}
}
/// `PCvD.Data`: positional `[u8, u32 count, then per subpath: bool closed, 18-byte records]`.
/// A record is (f64 x, f64 y, u8 kind, u8 role): role 0 is an anchor, 1 the out-handle of the
/// anchor before it, 2 the in-handle of the anchor after it. A closed subpath repeats its first
/// anchor at the end. `CnrD` live corners are rounded on the stored polyline.
fn curves(r: &mut Reader, crvs: ObjId, budget: &mut OutlineBudget) -> Option<Path> {
let s = r.s;
let data = s.obj(crvs, b"Data")?;
let mut fields = s.positional(data);
fields.next()?;
let count = match fields.next()? {
Value::UInt(n) => usize::try_from(*n).ok()?,
_ => return None,
};
budget.spend(r, count)?;
let corners = s.obj(crvs, b"CnrD").and_then(|c| corner_radii(s.positional(c).collect()));
let mut path = Path::default();
let mut seen = 0usize;
for index in 0..count {
let closed = match fields.next()? {
Value::Bool(b) => *b,
_ => return None,
};
let Value::Array(records) = fields.next()? else { return None };
seen = seen.checked_add(records.len())?;
if seen > MAX_NODES {
budget.fail(r, "curves with more than four million nodes")?;
}
budget.spend(r, records.len())?;
let anchors = anchors(records)?;
let radii = if index == 0 { corners.as_ref() } else { None };
if let Some(sp) = subpath(&anchors, closed, radii) {
path.subpaths.push(sp);
}
}
if corners.is_some() && count > 1 {
r.warn("rounded corners on curves with several subpaths (only the first is rounded)");
}
Some(path)
}
struct Anchor {
p: Point,
inh: Option<Point>,
out: Option<Point>,
/// Index of the anchor's record (live corners refer to records).
record: usize,
}
fn record(v: &Value) -> Option<(Point, u8)> {
let Value::Bytes(b) = v else { return None };
if b.len() != 18 {
return None;
}
let x = f64::from_le_bytes(b.get(0..8)?.try_into().ok()?);
let y = f64::from_le_bytes(b.get(8..16)?.try_into().ok()?);
if !x.is_finite() || !y.is_finite() {
return None;
}
Some((Point { x, y }, *b.get(17)?))
}
fn anchors(records: &[Value]) -> Option<Vec<Anchor>> {
let mut out: Vec<Anchor> = Vec::with_capacity(records.len() / 3 + 1);
let mut pending_in = None;
for (i, v) in records.iter().enumerate() {
let (p, role) = record(v)?;
match role {
0 => {
out.push(Anchor { p, inh: pending_in.take(), out: None, record: i });
}
1 => {
// A leading out-handle without an anchor is edit state only.
if let Some(a) = out.last_mut() {
a.out = Some(p);
}
}
2 => pending_in = Some(p),
_ => return None,
}
}
Some(out)
}
fn subpath(anchors: &[Anchor], closed: bool, radii: Option<&Vec<(usize, f64)>>) -> Option<SubPath> {
let first = anchors.first()?;
if let Some(radii) = radii.filter(|r| !r.is_empty()) {
// The largest radius of each record, once (not a scan of all of them for each anchor).
let mut largest: std::collections::HashMap<usize, f64> = std::collections::HashMap::new();
for (rec, r) in radii {
let e = largest.entry(*rec).or_insert(0.0);
*e = e.max(*r);
}
let corner = |a: &Anchor| largest.get(&a.record).copied().unwrap_or(0.0);
let polyline = anchors.iter().all(|a| a.inh.is_none_or(|h| h == a.p) && a.out.is_none_or(|h| h == a.p));
if polyline {
let mut pts: Vec<(Point, f64)> = anchors.iter().map(|a| (a.p, corner(a))).collect();
// A closed subpath repeats its first anchor; its radius may be on either copy.
if closed
&& pts.len() > 1
&& pts.first().map(|p| p.0) == pts.last().map(|p| p.0)
&& let Some((_, r)) = pts.pop()
&& let Some(f) = pts.first_mut()
{
f.1 = f.1.max(r);
}
return Some(crate::shapes::fillet(&pts, closed));
}
}
let segments = anchors
.windows(2)
.filter_map(|w| {
let [a, b] = w else { return None };
Some([a.out.unwrap_or(a.p), b.inh.unwrap_or(b.p), b.p])
})
.collect();
Some(SubPath { start: first.p, segments, closed })
}
/// `CnrD`: positional `[u8, i32[] record indices, f64[] radii, u8[] types]`.
fn corner_radii(fields: Vec<&Value>) -> Option<Vec<(usize, f64)>> {
let (Some(Value::Array(idx)), Some(Value::Array(rad))) = (fields.get(1), fields.get(2)) else { return None };
Some(
idx.iter()
.zip(rad)
.filter_map(|(i, r)| match (i, r) {
(Value::Int(i), Value::Float(r)) if r.is_finite() && *r > 0.0 => Some((usize::try_from(*i).ok()?, *r)),
_ => None,
})
.collect(),
)
}
+3 -49
View File
@@ -1,52 +1,6 @@
//! Reader for native Affinity documents (`.af`, and `.afdesign`/`.afphoto`/`.afpub` from
//! Affinity 1 and 2): the archive container, the tagged object stream in `doc.dat`, and the
//! subset of the document model VectorCraft imports.
//!
//! Layouts follow the MIT-licensed afread reference and were checked against public documents
//! saved by Affinity 1.x to 3.x (container versions 8 to 12); see the crate README for provenance
//! and the exact supported subset. Nothing here writes Affinity files.
//! The Affinity reader is `craft-affinity` (storytold/craft-libs). This crate keeps its name so
//! the corpus tests and fuzz targets under it, and the CI job that runs them, still build.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
use std::fmt;
mod access;
pub mod container;
mod geometry;
pub mod model;
pub mod overlay;
pub mod paint;
pub mod preview;
mod raster;
mod shapes;
pub mod stream;
#[cfg(any(test, feature = "synth"))]
pub mod synth;
mod text;
pub use container::{Archive, Limits, MAGIC, is_affinity};
pub use model::{Document, read};
pub use preview::{MAX_PREVIEW_BYTES, MAX_PREVIEW_DIMENSION, Preview, preview};
/// Why a file could not be read. Messages are short reasons; callers add advice.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
Malformed(&'static str),
Unsupported(&'static str),
Limit(&'static str),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Malformed(s) => write!(f, "damaged Affinity file: {s}"),
Self::Unsupported(s) => write!(f, "unsupported Affinity file: {s}"),
Self::Limit(s) => write!(f, "Affinity file exceeds a safety limit: {s}"),
}
}
}
impl std::error::Error for Error {}
#[cfg(test)]
mod tests;
pub use craft_affinity::*;
-471
View File
@@ -1,471 +0,0 @@
//! The document model the Craft apps import: spreads, artboards, layers, groups, curves, shapes,
//! text and images, with transforms composed into document space. Anything else is reported
//! by [`Document::warnings`] instead of being dropped silently.
use std::collections::{BTreeMap, HashSet};
use crate::paint::{self, Paint, Stroke};
use crate::stream::{ObjId, Stream, Tag};
use crate::{Archive, Error, Limits, stream};
mod bounds;
mod read;
pub(crate) use bounds::rect;
pub use bounds::{kind_bounds, nodes_bounds};
pub(crate) use read::Reader;
pub use read::read;
#[cfg(test)]
pub(crate) use read::read_within;
/// Affine map `x' = a·x + c·y + e`, `y' = b·x + d·y + f` (kurbo's coefficient order).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Affine(pub [f64; 6]);
impl Affine {
pub const IDENTITY: Self = Self([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
/// Affinity's `Xfrm`, stored row by row: (a, c, e, b, d, f).
pub(crate) fn from_xfrm(m: [f64; 6]) -> Self {
Self([m[0], m[3], m[1], m[4], m[2], m[5]])
}
pub fn then(self, outer: Self) -> Self {
let [a, b, c, d, e, f] = self.0;
let [oa, ob, oc, od, oe, of] = outer.0;
Self([oa * a + oc * b, ob * a + od * b, oa * c + oc * d, ob * c + od * d, oa * e + oc * f + oe, ob * e + od * f + of])
}
pub fn apply(&self, p: Point) -> Point {
let [a, b, c, d, e, f] = self.0;
Point { x: a * p.x + c * p.y + e, y: b * p.x + d * p.y + f }
}
/// Geometric mean of the axis scales: how much a stroke width or font size grows.
pub fn scale(&self) -> f64 {
let [a, b, c, d, ..] = self.0;
(a * d - b * c).abs().sqrt()
}
pub fn is_finite(&self) -> bool {
self.0.iter().all(|v| v.is_finite())
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Point {
pub x: f64,
pub y: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rect {
pub x0: f64,
pub y0: f64,
pub x1: f64,
pub y1: f64,
}
/// One cubic Bézier subpath, in document pixels.
#[derive(Debug, Clone, PartialEq)]
pub struct SubPath {
pub start: Point,
/// (control 1, control 2, end) per segment.
pub segments: Vec<[Point; 3]>,
pub closed: bool,
}
/// An outline in document pixels.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Path {
pub subpaths: Vec<SubPath>,
}
impl Path {
pub fn transformed(&self, m: Affine) -> Self {
Self {
subpaths: self
.subpaths
.iter()
.map(|s| SubPath {
start: m.apply(s.start),
segments: s.segments.iter().map(|seg| seg.map(|p| m.apply(p))).collect(),
closed: s.closed,
})
.collect(),
}
}
}
/// Affinity's blend modes, numbered by the `Blnd` enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Blend {
#[default]
Normal,
PassThrough,
Darken,
DarkerColor,
Multiply,
ColorBurn,
Lighten,
LighterColor,
Screen,
ColorDodge,
Add,
Overlay,
SoftLight,
HardLight,
VividLight,
PinLight,
LinearLight,
HardMix,
Difference,
Exclusion,
Subtract,
Hue,
Saturation,
Luminosity,
Color,
Average,
Negation,
Reflect,
Glow,
Erase,
}
impl Blend {
/// The enum (id, version) pairs observed in a document whose layers are named after their mode.
fn from_enum(id: u16, version: u16) -> Option<Self> {
use Blend::*;
Some(match (id, version) {
(0, _) => Normal,
(1, 0) => Darken,
(2, 1) => DarkerColor,
(2, 0) => Multiply,
(3, 0) => ColorBurn,
(4, 0) => Lighten,
(6, 1) => LighterColor,
(5, 0) => Screen,
(6, 0) => ColorDodge,
(7, 0) => Add,
(8, 0) => Overlay,
(9, 0) => SoftLight,
(10, 0) => HardLight,
(11, 0) => VividLight,
(12, 0) => PinLight,
(15, 1) => LinearLight,
(13, 0) => HardMix,
(14, 0) => Difference,
(15, 0) => Exclusion,
(16, 0) => Subtract,
(17, 0) => Hue,
(18, 0) => Saturation,
(19, 0) => Luminosity,
(20, 0) => Color,
(21, 0) => Average,
(22, 0) => Negation,
(23, 0) => Reflect,
(24, 0) => Glow,
(25, 0) => Erase,
_ => return None,
})
}
}
/// A run of text with one set of character attributes.
#[derive(Debug, Clone, PartialEq)]
pub struct TextRun {
pub text: String,
/// PostScript name and family of the chosen font.
pub postscript: String,
pub family: String,
/// CSS weight (400 regular, 700 bold).
pub weight: i64,
pub italic: bool,
/// Boolean OpenType feature overrides, as tags or `-tag` for disabled features.
pub features: Vec<String>,
pub all_caps: bool,
/// Underlined characters (`Ints` slot 0 is 1; identified on underlined words in a document its
/// owner made, all other characters there and in the public corpus have 0).
pub underline: bool,
/// Struck-through characters (`Ints` slot 1 is 1; identified the same way, on prices struck
/// through in another document its owner made).
pub strikethrough: bool,
/// Font size in document pixels, before the node's transform.
pub size: f64,
/// Tracking in em.
pub tracking: f64,
/// Horizontal scale of the glyphs (1 = as designed).
pub h_scale: f64,
/// Fixed line pitch in document pixels, when the run overrides automatic leading.
pub leading: Option<f64>,
pub fill: Paint,
/// Outlined characters: the outline's paint and width (node space).
pub stroke: Option<crate::paint::Stroke>,
/// The run's paragraph: alignment, indents and spacing.
pub paragraph: Paragraph,
}
/// Paragraph alignment, indents, spacing and leading, in node space (document pixels before the
/// node's text scale).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Paragraph {
pub align: Align,
/// Indent of every line but the first, from the left.
pub left: f64,
pub right: f64,
/// Indent of the first line, from the left.
pub first: f64,
pub space_before: f64,
pub space_after: f64,
/// Fixed distance between baselines, when the paragraph sets one.
pub leading: Option<f64>,
/// Automatic leading as a multiple of the font's own line height (ascent plus descent).
pub auto_leading: f64,
}
impl Default for Paragraph {
fn default() -> Self {
Self { align: Align::Left, left: 0.0, right: 0.0, first: 0.0, space_before: 0.0, space_after: 0.0, leading: None, auto_leading: 1.0 }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Align {
#[default]
Left,
Center,
Right,
Justify,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Text {
pub runs: Vec<TextRun>,
pub align: Align,
/// Artistic text: the first baseline's anchor point in node space (start, centre or end of the
/// line according to `align`). Frame text: the frame box in node space.
pub anchor: Point,
pub frame: Option<Rect>,
/// Node space to document pixels.
pub transform: Affine,
/// Node space to document pixels for the type (its linear part matters): artistic text scales
/// with its node, frame text only with its frame's text scale.
pub text_transform: Affine,
}
/// Vertical alignment of a table cell's text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VAlign {
Top,
Center,
Bottom,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TableCell {
pub runs: Vec<TextRun>,
/// Space between the cell edges and its text, in node space: left, top, right, bottom.
pub inset: [f64; 4],
pub valign: VAlign,
/// Part of the cell to its left (merged): it has no text of its own.
pub merged_left: bool,
}
/// A table: a grid of cells with text, and a line on every cell edge.
#[derive(Debug, Clone, PartialEq)]
pub struct Table {
/// Column boundaries (one more than the columns), increasing, in node space.
pub columns: Vec<f64>,
/// Row boundaries (one more than the rows), increasing, in node space.
pub rows: Vec<f64>,
/// Row by row.
pub cells: Vec<TableCell>,
/// Vertical edges row by row, one more per row than the columns; `None` draws no line, and
/// the list is empty when the file's didn't match the grid.
pub vertical: Vec<Option<Stroke>>,
/// Horizontal edges boundary by boundary (one more than the rows), one per column (empty
/// as `vertical` can be).
pub horizontal: Vec<Option<Stroke>>,
/// Node space to document pixels.
pub transform: Affine,
/// Node space to document pixels for the cells' type: resizing a table moves its grid, not
/// its type.
pub text_transform: Affine,
}
impl Table {
pub fn ncols(&self) -> usize {
self.columns.len().saturating_sub(1)
}
pub fn nrows(&self) -> usize {
self.rows.len().saturating_sub(1)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Pixels {
/// Straight-alpha RGBA, 8 bits per channel, row by row.
Rgba8(Vec<u8>),
/// A CMYK pixel layer: cyan, magenta, yellow and black ink amounts (0 none, 255 full) and
/// straight alpha, 8 bits each, row by row. Left in CMYK for the importer to show through a
/// colour profile: the profile-free formula turns the extra cyan of a separation's neutrals
/// into a blue cast.
Cmyka8(Vec<u8>),
/// The original file a placed image was made from (PNG, JPEG…), as embedded.
Encoded(Vec<u8>),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Image {
pub width: u32,
pub height: u32,
pub pixels: Pixels,
/// Pixel space (0..w, 0..h) to document pixels.
pub transform: Affine,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Kind {
/// Layer container (`Scop`).
Layer,
Group,
/// Artboard: an export rectangle and vector outline that clips its children.
/// `background` paints behind them, and `strokes` over them.
Artboard {
rect: Rect,
/// Actual clipping outline in document pixels. The artboard's export rectangle is its
/// bounding box, but a rotated or non-rectangular board still clips to this outline.
path: Path,
even_odd: bool,
background: Vec<Paint>,
strokes: Vec<Stroke>,
},
/// Curve, parametric shape or compound shape: an outline with its fills and strokes.
/// Children of a shape are clipped by its outline (painted over its fills, under its strokes).
Shape {
path: Path,
fills: Vec<Paint>,
strokes: Vec<Stroke>,
even_odd: bool,
},
Text(Text),
Table(Table),
Image(Image),
/// A master page shown on this spread's pages: pages `page..page + count` show the master
/// spread [`Document::masters`]`[master]`'s pages from `master_page` on.
MasterInstance {
master: usize,
page: usize,
master_page: usize,
count: usize,
},
/// Something this reader does not import; its children are still imported.
Unsupported,
}
/// A layer effect. Lengths are document pixels; `angle` is the direction the shadow is offset in
/// (radians, clockwise from +x as y points down: π/2 puts it below).
#[derive(Debug, Clone, PartialEq)]
pub enum Effect {
DropShadow {
color: crate::paint::Color,
opacity: f64,
radius: f64,
distance: f64,
angle: f64,
},
InnerShadow {
color: crate::paint::Color,
opacity: f64,
radius: f64,
distance: f64,
angle: f64,
},
OuterGlow {
color: crate::paint::Color,
opacity: f64,
radius: f64,
},
/// An outline of `width` around the node's shape: `align` 0 outside, 1 inside, 2 centred.
Outline {
color: crate::paint::Color,
opacity: f64,
width: f64,
align: u16,
},
/// Bevel and emboss: lit and shaded edges `size` wide. `angle` is the light's azimuth
/// (radians, counter-clockwise from +x with y up), `depth` Affinity's depth (5 by default);
/// `inner` is false for the outer, emboss and pillow kinds.
Bevel {
size: f64,
depth: f64,
angle: f64,
highlight: crate::paint::Color,
highlight_opacity: f64,
shadow: crate::paint::Color,
shadow_opacity: f64,
inner: bool,
},
/// Colour overlay: everything the node paints takes `color`, laid over it in `blend` mode at
/// `opacity` (the node's own alpha is kept).
ColorOverlay {
color: crate::paint::Color,
opacity: f64,
blend: Blend,
},
/// Gradient overlay: a colour overlay whose colour comes from `gradient` (document pixels).
GradientOverlay {
gradient: crate::paint::Gradient,
opacity: f64,
blend: Blend,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct Node {
pub class: Tag,
pub name: String,
pub visible: bool,
pub locked: bool,
pub opacity: f64,
pub blend: Blend,
pub kind: Kind,
/// Vector mask in document pixels: the node shows only inside it (nonzero fill).
pub mask: Option<Path>,
/// Pixel mask: grey levels (white shows the node, black hides it); outside it the node is hidden.
pub pixel_mask: Option<Image>,
/// Layer effects the importer can show or bake in (others are reported).
pub effects: Vec<Effect>,
/// Bottom to top.
pub children: Vec<Node>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Spread {
/// Spread bounds in document pixels (the canvas, or the union of the artboards).
pub bounds: Rect,
/// Pages of a Publisher-style spread (one, or two facing pages), in document pixels.
pub pages: Vec<Rect>,
/// Transparent background; otherwise the page is white.
pub transparent: bool,
/// Bottom to top.
pub nodes: Vec<Node>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Document {
/// Pixels per inch: all geometry is in document pixels at this resolution.
pub dpi: f64,
pub spreads: Vec<Spread>,
/// Master spreads, which [`Kind::MasterInstance`] nodes show on pages.
pub masters: Vec<Spread>,
/// Application that last saved the file, as stored (`Affinity 3.0.2`), when present.
pub saved_by: Option<String>,
/// Content that was not imported or was approximated, one line per kind, deduplicated.
pub warnings: Vec<String>,
/// The document's CMYK colour profile (an ICC file), when it embeds one: the root's `CMYP`,
/// which each CMYK pixel layer's colour settings (`Prof`) also name, with relative
/// colorimetric intent and black-point compensation in every document checked.
pub cmyk_profile: Option<Vec<u8>>,
}
-142
View File
@@ -1,142 +0,0 @@
use super::read::MAX_TREE_DEPTH;
use super::{Affine, Kind, Node, ObjId, Point, Rect, Stream, Tag};
/// The bounds of what visible `nodes` draw (control points of outlines, corners of images, frames
/// and tables), in document pixels.
pub fn nodes_bounds(nodes: &[Node]) -> Option<Rect> {
let mut out = None;
walk_bounds(nodes, true, 0, &mut out);
out
}
/// The bounds of `node` and everything in it, hidden or not.
pub(super) fn tree_bounds(node: &Node) -> Option<Rect> {
let mut out = None;
walk_bounds(std::slice::from_ref(node), false, 0, &mut out);
out
}
fn walk_bounds(nodes: &[Node], visible_only: bool, depth: usize, out: &mut Option<Rect>) {
if depth > MAX_TREE_DEPTH {
return;
}
for n in nodes.iter().filter(|n| n.visible || !visible_only) {
kind_points(&n.kind, &mut |p| add_point(out, p));
walk_bounds(&n.children, visible_only, depth + 1, out);
}
}
/// What a pixel mask over a node of `kind` with `children` is read over: the bounds of what they
/// draw, strokes included, or `None` (all of the mask) when some of it has no bounds known here:
/// artistic text, whose glyphs only the layout places.
pub(super) fn mask_extent(kind: &Kind, children: &[Node]) -> Option<Rect> {
fn visit(kind: &Kind, children: &[Node], depth: usize, out: &mut Option<Rect>) -> bool {
if depth > MAX_TREE_DEPTH || matches!(kind, Kind::Text(t) if t.frame.is_none()) {
return false;
}
let mut own = kind_bounds(kind);
if let (Some(r), Kind::Shape { strokes, .. } | Kind::Artboard { strokes, .. }) = (own, kind) {
// As far as a stroke can reach out of its path, miter joins included.
let reach = strokes.iter().map(|s| s.width * s.miter_limit.clamp(1.0, 10.0)).filter(|w| w.is_finite()).fold(0.0, f64::max);
own = Some(Rect { x0: r.x0 - reach, y0: r.y0 - reach, x1: r.x1 + reach, y1: r.y1 + reach });
}
if let Some(r) = own {
*out = Some(out.map_or(r, |o| union(o, r)));
}
children.iter().filter(|n| n.visible).all(|n| visit(&n.kind, &n.children, depth + 1, out))
}
let mut out = None;
if visit(kind, children, 0, &mut out) { out } else { None }
}
/// The bounds of what one node's own kind draws (not its children): its outline's points, its
/// image's or frame's corners, or artistic text's anchor.
pub fn kind_bounds(kind: &Kind) -> Option<Rect> {
let mut out = None;
kind_points(kind, &mut |p| add_point(&mut out, p));
out
}
fn add_point(out: &mut Option<Rect>, p: Point) {
if p.x.is_finite() && p.y.is_finite() {
let r = Rect { x0: p.x, y0: p.y, x1: p.x, y1: p.y };
*out = Some(out.map_or(r, |o| union(o, r)));
}
}
fn kind_points(kind: &Kind, add: &mut dyn FnMut(Point)) {
let corners = |r: Rect, m: Affine| [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| m.apply(Point { x, y }));
match kind {
Kind::Shape { path, .. } | Kind::Artboard { path, .. } => {
for sp in &path.subpaths {
add(sp.start);
for seg in &sp.segments {
seg.iter().for_each(|p| add(*p));
}
}
}
Kind::Image(img) => {
corners(Rect { x0: 0.0, y0: 0.0, x1: f64::from(img.width), y1: f64::from(img.height) }, img.transform).into_iter().for_each(add)
}
Kind::Text(t) => match t.frame {
Some(f) => corners(f, t.transform).into_iter().for_each(add),
None => add(t.transform.apply(t.anchor)),
},
Kind::Table(t) => {
if let (Some(&x0), Some(&x1), Some(&y0), Some(&y1)) = (t.columns.first(), t.columns.last(), t.rows.first(), t.rows.last()) {
corners(Rect { x0, y0, x1, y1 }, t.transform).into_iter().for_each(add);
}
}
Kind::Layer | Kind::Group | Kind::Unsupported | Kind::MasterInstance { .. } => {}
}
}
/// Page rectangles: `SpMd.PagR[].rctp` (Publisher 2, Affinity 3) or `SprB` split into `PagC`
/// equal pages (Publisher 1 facing spreads).
pub(super) fn pages(s: &Stream, spread: ObjId) -> Vec<Rect> {
if let Some(md) = s.obj(spread, b"SpMd") {
let v: Vec<Rect> =
s.objs(md, b"PagR").into_iter().filter_map(|p| s.floats::<4>(p, b"rctp").map(rect)).filter(|r| r.x1 > r.x0 && r.y1 > r.y0).collect();
if !v.is_empty() {
return v;
}
}
match (s.floats::<4>(spread, b"SprB").map(rect), s.int(spread, b"PagC")) {
(Some(b), Some(n @ 2..=16)) => {
let w = (b.x1 - b.x0) / n as f64;
(0..n).map(|i| Rect { x0: b.x0 + w * i as f64, x1: b.x0 + w * (i + 1) as f64, ..b }).collect()
}
_ => Vec::new(),
}
}
pub(crate) fn union(a: Rect, b: Rect) -> Rect {
Rect { x0: a.x0.min(b.x0), y0: a.y0.min(b.y0), x1: a.x1.max(b.x1), y1: a.y1.max(b.y1) }
}
pub(super) fn is_container(class: Tag) -> bool {
class == Tag::of(b"Scop") || class == Tag::of(b"Grup")
}
pub(crate) fn rect(v: [f64; 4]) -> Rect {
Rect { x0: v[0], y0: v[1], x1: v[2], y1: v[3] }
}
/// A readable name for a layer class in warnings.
pub(crate) fn describe(class: Tag) -> &'static str {
match &class.0.to_be_bytes() {
b"PCrv" => "curve",
b"ShpN" | b"SNEN" | b"SNRR" | b"ShRN" => "shape",
b"Comp" => "compound",
b"Rstr" => "pixel",
b"ImgN" => "image",
b"EmbN" => "embedded document",
b"MPIN" => "master page instance",
b"FRst" => "fill",
b"MRst" => "mask",
b"Slic" | b"SlcP" => "slice",
b"3DLA" => "3D",
[_, _, b'R', b'A'] => "adjustment",
_ => "unknown",
}
}
-608
View File
@@ -1,608 +0,0 @@
use super::bounds::{describe, is_container, mask_extent, nodes_bounds, pages, rect, tree_bounds, union};
use super::{
Affine, Archive, BTreeMap, Blend, Document, Effect, Error, HashSet, Image, Kind, Limits, Node, ObjId, Paint, Path, Point, Rect, Spread, Stream,
Tag, paint, stream,
};
/// Largest embedded colour profile kept (real CMYK profiles are a few megabytes).
const MAX_PROFILE_BYTES: usize = 32 << 20;
/// Deepest layer nesting followed; deeper content is reported, not imported.
pub(super) const MAX_TREE_DEPTH: usize = 128;
/// Total layer nodes imported.
const MAX_NODES: usize = 500_000;
/// Pixels decoded from pixel layers over a whole document (2 GB as RGBA). The archive's limits
/// count the bytes extracted from it, and a layer of one flat colour needs none (#1704).
const MAX_LAYER_PIXELS: u64 = 512 << 20;
/// Embedded documents inside embedded documents are followed this deep.
const MAX_EMBED_DEPTH: usize = 4;
/// Characters of all stories together (a story may be shared by many text layers).
const MAX_DOCUMENT_CHARS: usize = 16 << 20;
/// Table cells of all tables together (each becomes a text object with its edge lines).
const MAX_DOCUMENT_CELLS: usize = 1 << 18;
/// What a whole read may still use. Shared objects can be linked from many layers, and embedded
/// documents are read with what their embedding document left, so linking or embedding the
/// same content many times can't multiply the work.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Budget {
/// Layer nodes ([`MAX_NODES`] in all).
pub(crate) nodes: usize,
/// Pixels the pixel layers may decode ([`MAX_LAYER_PIXELS`] in all).
pub(crate) pixels: u64,
/// Characters of stories ([`MAX_DOCUMENT_CHARS`] in all).
pub(crate) chars: usize,
/// Table cells ([`MAX_DOCUMENT_CELLS`] in all).
pub(crate) cells: usize,
}
impl Budget {
pub(crate) const FULL: Budget = Budget { nodes: MAX_NODES, pixels: MAX_LAYER_PIXELS, chars: MAX_DOCUMENT_CHARS, cells: MAX_DOCUMENT_CELLS };
}
/// Read a document: archive, `doc.dat` and the model.
pub fn read(bytes: &[u8], limits: Limits) -> Result<Document, Error> {
read_within(bytes, limits, MAX_LAYER_PIXELS)
}
/// [`read`], its pixel layers holding at most `pixels` pixels together.
pub(crate) fn read_within(bytes: &[u8], limits: Limits, pixels: u64) -> Result<Document, Error> {
read_at(bytes, limits, &mut Budget { pixels, ..Budget::FULL }, Affine::IDENTITY, 0).document
}
/// A document read by [`read_at`] (or why it couldn't be), with the bytes its archive extracted
/// either way.
struct ReadAt {
document: Result<Document, Error>,
extracted: usize,
}
/// Read a document whose spreads are placed by `base` (for embedded documents, nested `depth`
/// deep). What it uses is taken from `budget`, also when it fails part of the way.
/// The most characters of a layer's name kept.
const MAX_NAME_CHARS: usize = 1024;
fn read_at(bytes: &[u8], limits: Limits, budget: &mut Budget, base: Affine, depth: usize) -> ReadAt {
let mut archive = match Archive::open(bytes, limits) {
Ok(a) => a,
Err(e) => return ReadAt { document: Err(e), extracted: 0 },
};
let document = read_archive(&mut archive, budget, base, depth);
ReadAt { document, extracted: archive.extracted() }
}
fn read_archive(archive: &mut Archive, budget: &mut Budget, base: Affine, depth: usize) -> Result<Document, Error> {
let doc = archive.read("doc.dat")?;
let s = stream::parse(&doc)?;
let mut reader = Reader::new(&s, archive, base, depth);
reader.budget = *budget;
let document = reader.document();
*budget = reader.budget;
document
}
pub(crate) struct Reader<'s, 'a, 'b> {
pub(crate) s: &'s Stream,
pub(crate) archive: &'b mut Archive<'a>,
pub(crate) dpi: f64,
pub(crate) warnings: BTreeMap<String, usize>,
active: HashSet<ObjId>,
/// Where the spreads go: the identity, or an embedding document's placement.
base: Affine,
/// The linear part of `base`, which also scales frame text.
pub(crate) type_base: Affine,
/// How deep inside embedded documents this one is.
depth: usize,
/// An embedded document's content, waiting to become its node's children.
pending: Option<Vec<Node>>,
/// The master spreads, in the order of [`Document::masters`].
master_ids: Vec<ObjId>,
/// What the rest of the read may use.
pub(crate) budget: Budget,
}
impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
pub(crate) fn new(s: &'s Stream, archive: &'b mut Archive<'a>, base: Affine, depth: usize) -> Self {
let [a, b, c, d, ..] = base.0;
Self {
s,
archive,
dpi: 72.0,
warnings: BTreeMap::new(),
active: HashSet::new(),
base,
type_base: Affine([a, b, c, d, 0.0, 0.0]),
depth,
pending: None,
master_ids: Vec::new(),
budget: Budget::FULL,
}
}
pub(crate) fn warn(&mut self, what: impl Into<String>) {
*self.warnings.entry(what.into()).or_default() += 1;
}
/// The document.
fn document(&mut self) -> Result<Document, Error> {
let s = self.s;
let root = s.root;
self.dpi = s.obj(root, b"UVCn").and_then(|u| s.f64(u, b"UPPI")).filter(|d| *d > 0.0 && *d < 100_000.0).unwrap_or(72.0);
let saved_by = s.obj(root, b"NVer").map(|v| {
let product = s.str(v, b"Prod").unwrap_or("Affinity");
match (s.int(v, b"Majr"), s.int(v, b"Minr"), s.int(v, b"Bild")) {
(Some(a), Some(b), Some(c)) => format!("{product} {a}.{b}.{c}"),
_ => product.to_string(),
}
});
let doc = s.obj(root, b"DocR").ok_or(Error::Malformed("document has no root node"))?;
self.master_ids = s.objs(doc, b"MpCh").into_iter().filter(|m| s.is(*m, b"Sprd")).collect();
let mut spreads = Vec::new();
for spread in s.objs(doc, b"Chld") {
if let Some(sp) = self.spread(doc, spread)? {
spreads.push(sp);
}
}
if spreads.is_empty() {
return Err(Error::Malformed("document has no pages"));
}
let mut masters = Vec::new();
for master in self.master_ids.clone() {
match self.spread(doc, master)? {
Some(sp) => masters.push(sp),
// Keep the indices of `MasterInstance::master` valid.
None => masters.push(Spread {
bounds: Rect { x0: 0.0, y0: 0.0, x1: 0.0, y1: 0.0 },
pages: Vec::new(),
transparent: true,
nodes: Vec::new(),
}),
}
}
let cmyk_profile = s
.obj(root, b"CMYP")
.and_then(|p| s.bytes(p, b"Data"))
.filter(|b| b.len() <= MAX_PROFILE_BYTES && b.get(16..20) == Some(b"CMYK".as_slice()))
.map(<[u8]>::to_vec);
let warnings = std::mem::take(&mut self.warnings).into_iter().map(|(w, n)| if n > 1 { format!("{w} ({n}×)") } else { w }).collect();
Ok(Document { dpi: self.dpi, spreads, masters, saved_by, warnings, cmyk_profile })
}
/// A spread (`Sprd`) of the document `doc`, or of its master spreads.
fn spread(&mut self, doc: ObjId, spread: ObjId) -> Result<Option<Spread>, Error> {
let s = self.s;
if !s.is(spread, b"Sprd") {
self.warn("an unknown kind of page");
return Ok(None);
}
let pages = pages(s, spread);
let default_size = s.floats::<2>(doc, b"DfSz").filter(|[w, h]| *w > 0.0 && *h > 0.0).map(|[w, h]| Rect { x0: 0.0, y0: 0.0, x1: w, y1: h });
let bounds = s.floats::<4>(spread, b"SprB").map(rect).or_else(|| pages.iter().copied().reduce(union)).or(default_size).unwrap_or(Rect {
x0: 0.0,
y0: 0.0,
x1: 0.0,
y1: 0.0,
});
let transparent = s.bool(spread, b"SprT").unwrap_or(false);
let (nodes, mask) = self.children(spread, self.base, 0)?;
if mask.is_some() {
self.warn("mask layers directly on a page (imported without them)");
}
Ok(Some(Spread { bounds, pages, transparent, nodes }))
}
/// The children of `parent`, and the mask layer among them that masks the parent (with its
/// placement), read later over just what it masks.
#[allow(clippy::type_complexity)]
fn children(&mut self, parent: ObjId, world: Affine, depth: usize) -> Result<(Vec<Node>, Option<(ObjId, Affine)>), Error> {
let s = self.s;
let mut out = Vec::new();
let mut mask = None;
for c in s.objs(parent, b"Chld") {
if s.is(c, b"MRst") {
// A mask layer inside a group or layer masks that container.
if s.bool(c, b"Visi") == Some(false) {
continue;
}
let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
if mask.is_none() {
mask = Some((c, local.then(world)));
} else {
self.warn("several pixel masks on one layer (only the first is used)");
}
continue;
}
if let Some(n) = self.node(c, world, depth + 1)? {
out.push(n);
}
}
Ok((out, mask))
}
fn node(&mut self, id: ObjId, parent: Affine, depth: usize) -> Result<Option<Node>, Error> {
let s = self.s;
if depth > MAX_TREE_DEPTH {
self.warn("layers nested deeper than 128 levels");
return Ok(None);
}
let Some(left) = self.budget.nodes.checked_sub(1) else {
return Err(Error::Limit("too many layers"));
};
self.budget.nodes = left;
// A node that contains itself (a shared object linked back into its own subtree).
if !self.active.insert(id) {
self.warn("a layer that contains itself");
return Ok(None);
}
let local = s.floats::<6>(id, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
let world = local.then(parent);
let class = s.class(id).unwrap_or(Tag(0));
// A layer name is short; a long one is cut, as every visit of a shared object keeps a copy.
let name: String = s.str(id, b"Desc").unwrap_or_default().chars().take(MAX_NAME_CHARS).collect();
let visible = s.bool(id, b"Visi").unwrap_or(true);
let locked = s.bool(id, b"Edtb").is_some_and(|e| !e);
let opacity = s.f64(id, b"Opac").map_or(1.0, |o| o.clamp(0.0, 1.0));
let blend = match s.enumeration(id, b"Blnd") {
None if s.bool(id, b"PasT") != Some(false) && is_container(class) => Blend::PassThrough,
None => Blend::Normal,
Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| {
self.warn("an unknown blend mode (imported as Normal)");
Blend::Normal
}),
};
let kind = if !world.is_finite() {
self.warn("a layer with an invalid transform");
Kind::Unsupported
} else {
self.kind(id, class, world, parent)?
};
// This node's embedded content, before its children's `node` calls can take it.
let embedded = self.pending.take();
// A compound's children are its operands, already merged into its outline.
let (mut children, child_mask) = if class == Tag::of(b"Comp") { (Vec::new(), None) } else { self.children(id, world, depth)? };
if let Some(embedded) = embedded {
children.extend(embedded);
}
// Pixel masks are read only over what they mask (they can span a whole spread at print
// resolution, a gigapixel).
let over = mask_extent(&kind, &children);
let child_mask = match child_mask {
Some((c, at)) => crate::raster::mask(self, c, at, over)?,
None => None,
};
let (mask, attached_mask) = self.attached_masks(id, world, over)?;
let pixel_mask = attached_mask.or(child_mask);
self.active.remove(&id);
let mut node = Node { class, name, visible, locked, opacity, blend, kind, mask, pixel_mask, effects: Vec::new(), children };
// Gradient overlays are laid out over the node's bounds, also while it is hidden.
let bounds = tree_bounds(&node);
node.effects = self.effects(id, world, bounds);
Ok(Some(node))
}
fn kind(&mut self, id: ObjId, class: Tag, world: Affine, parent: Affine) -> Result<Kind, Error> {
let s = self.s;
Ok(match &class.0.to_be_bytes() {
b"Scop" => Kind::Layer,
b"Grup" => Kind::Group,
b"PCrv" | b"ShpN" | b"Comp" | b"SNEN" | b"SNRR" | b"ShRN" => {
// Affinity 3.2.3's two-board public fixture marks board shapes with an `aprp`
// property object in `phrp`, while older documents use `ABEn`. Ordinary shapes
// in that fixture have neither. See the pinned corpus and validation audit.
if s.bool(id, b"ABEn") == Some(true) || s.obj(id, b"phrp").is_some_and(|p| s.is(p, b"aprp")) {
return Ok(self.artboard(id, world));
}
let Some((local, even_odd)) = crate::geometry::outline(self, id, class, world) else {
self.warn(format!("a {} that could not be read", describe(class)));
return Ok(Kind::Unsupported);
};
let (fills, strokes) = paint::node_paint(self, id, world);
Kind::Shape { path: local.transformed(world), fills, strokes, even_odd }
}
b"TxtT" => match crate::text::table(self, id, world) {
Some(t) => Kind::Table(t),
None => {
self.warn("tables that could not be read");
Kind::Unsupported
}
},
b"TxtA" | b"TxtF" | b"TxtC" => match crate::text::read(self, id, world) {
Some(t) => Kind::Text(t),
None => {
self.warn("text whose story could not be read (master-page text, or an unknown layout)");
Kind::Unsupported
}
},
b"ImgN" | b"Rstr" => match crate::raster::node_image(self, id, world)? {
Some(img) => Kind::Image(img),
None => Kind::Unsupported,
},
b"MPIN" => {
// `SLnk` links the instance with the master spread it shows.
let linked = s.obj(id, b"SLnk").map(|l| s.objs(l, b"ILOb")).unwrap_or_default();
let master = linked.iter().find_map(|o| self.master_ids.iter().position(|m| m == o));
let at = |t: &[u8; 4], default: usize| s.int(id, t).and_then(|v| usize::try_from(v).ok()).unwrap_or(default).min(4096);
match master {
Some(master) => Kind::MasterInstance { master, page: at(b"PgOf", 0), master_page: at(b"MPOf", 0), count: at(b"PgCt", 1) },
None => {
self.warn("master page instances without their master");
Kind::Unsupported
}
}
}
b"EmbN" => match self.embedded_document(id, world) {
// The embedded document itself, as editable content.
Some(nodes) => {
self.pending = Some(nodes);
Kind::Group
}
None => match crate::raster::embedded(self, id, world)? {
Some(img) => {
self.warn("embedded documents and symbols (imported as pictures of them)");
Kind::Image(img)
}
None => {
self.warn("embedded documents and symbols without a cached picture");
Kind::Unsupported
}
},
},
b"FRst" => {
// A fill layer paints its whole bitmap area; its gradient lives in page space.
let b = s.obj(id, b"Bitm");
let size = |t: &[u8; 4]| b.and_then(|b| s.int(b, t)).map(|v| v as f64).filter(|v| *v > 0.0);
match (size(b"BmpW"), size(b"BmpH")) {
(Some(w), Some(h)) => {
let local = Path { subpaths: vec![crate::shapes::rectangle(0.0, 0.0, w, h)] };
let fills = paint::fills(self, id, parent, b"BFFl");
Kind::Shape { path: local.transformed(world), fills, strokes: Vec::new(), even_odd: false }
}
_ => {
self.warn("fill layers without an area");
Kind::Unsupported
}
}
}
_ => {
self.warn(format!("{} layers", describe(class)));
Kind::Unsupported
}
})
}
/// The enabled layer effects (`FiEf`) of node `id`. The angle convention was measured on the
/// public MIT fx fixture (Patchy): an angle of π/2 with offset 10 shadows 10 below.
fn effects(&mut self, id: ObjId, world: Affine, bounds: Option<Rect>) -> Vec<Effect> {
let s = self.s;
let mut out = Vec::new();
for e in s.objs(id, b"FiEf").into_iter().take(64) {
if s.bool(e, b"Enab") == Some(false) {
continue;
}
// "Scale with object": lengths follow the node's transform; otherwise they are absolute.
let k = if s.bool(e, b"SclO") == Some(true) { world.scale() } else { 1.0 };
let len = |t: &[u8; 4]| s.f64(e, t).filter(|v| v.is_finite() && *v >= 0.0 && *v < 1e6).unwrap_or(0.0) * k;
let opacity = s.f64(e, b"Opac").filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0);
let angle = s.f64(e, b"Angl").filter(|v| v.is_finite()).unwrap_or(0.0);
let color = s.obj(e, b"Colr").and_then(|c| crate::paint::color(self, c));
let class = s.class(e).map(|c| c.0.to_be_bytes());
match (class.as_ref(), color) {
(Some(b"Shad"), Some(color)) => out.push(Effect::DropShadow { color, opacity, radius: len(b"Radi"), distance: len(b"Offs"), angle }),
(Some(b"InnS"), Some(color)) => out.push(Effect::InnerShadow { color, opacity, radius: len(b"Radi"), distance: len(b"Offs"), angle }),
(Some(b"OutG"), Some(color)) => out.push(Effect::OuterGlow { color, opacity, radius: len(b"Radi") }),
(Some(b"Strk"), Some(color)) if s.enumeration(e, b"Ftyp").is_none_or(|(t, _)| t == 0) => {
let align = s.enumeration(e, b"Alig").map_or(0, |(a, _)| a);
out.push(Effect::Outline { color, opacity, width: len(b"Radi"), align });
}
(Some(b"Strk"), _) => self.warn("gradient outline effects (left out)"),
(Some(b"BevE" | b"EmbE"), _) => {
// No radius, no bevel (as Affinity draws it).
let size = len(b"Radi");
if size > 0.0 {
let white = crate::paint::Color::Rgb { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
let black = crate::paint::Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 1.0 };
let highlight = s.obj(e, b"HiCl").and_then(|c| crate::paint::color(self, c)).unwrap_or(white);
let shadow = s.obj(e, b"ShCl").and_then(|c| crate::paint::color(self, c)).unwrap_or(black);
let shadow_opacity = s.f64(e, b"ShOp").filter(|v| v.is_finite()).unwrap_or(0.75).clamp(0.0, 1.0);
let depth = s.f64(e, b"Dept").filter(|v| v.is_finite()).unwrap_or(5.0);
let azimuth = s.f64(e, b"Azim").filter(|v| v.is_finite()).unwrap_or(std::f64::consts::FRAC_PI_4 * 3.0);
let inner = s.enumeration(e, b"Beve").is_none_or(|(k, _)| k == 0);
out.push(Effect::Bevel { size, depth, angle: azimuth, highlight, highlight_opacity: opacity, shadow, shadow_opacity, inner });
}
}
(Some(b"ColO"), Some(color)) => {
let blend = self.effect_blend(e);
out.push(Effect::ColorOverlay { color, opacity, blend });
}
(Some(b"GrdO"), _) => {
let blend = self.effect_blend(e);
// The gradient's unit space spans the node's bounding box from -1 to 1, centred
// on it (y down): checked against the stored previews of real documents.
let space =
bounds.map(|b| Affine([(b.x1 - b.x0) / 2.0, 0.0, 0.0, (b.y1 - b.y0) / 2.0, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0]));
match (s.obj(e, b"GrFl"), space) {
(Some(fill), Some(space)) => match paint::descriptor(self, fill, space) {
Some(Paint::Gradient(gradient)) => out.push(Effect::GradientOverlay { gradient, opacity, blend }),
Some(Paint::Solid(color)) => out.push(Effect::ColorOverlay { color, opacity, blend }),
_ => {}
},
// Nothing visible to lay it over.
(Some(_), None) => {}
(None, _) => self.warn("gradient overlay effects that could not be read (left out)"),
}
}
(Some(b"ColO"), None) => self.warn("colour overlay effects that could not be read (left out)"),
(Some(b"Gaus"), _) => self.warn("blur effects (left out)"),
_ => self.warn("layer effects of other kinds (left out)"),
}
}
out
}
/// A layer effect's blend mode (`BlnM`); unknown modes are Normal (warned).
fn effect_blend(&mut self, e: ObjId) -> Blend {
match self.s.enumeration(e, b"BlnM") {
None => Blend::Normal,
Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| {
self.warn("an unknown blend mode (imported as Normal)");
Blend::Normal
}),
}
}
/// Vector shapes attached to a node (`AdCh`) mask it: it shows only inside their outlines;
/// an attached mask layer is a pixel mask. Adjustments attached the same way are reported.
fn attached_masks(&mut self, id: ObjId, world: Affine, over: Option<Rect>) -> Result<(Option<Path>, Option<Image>), Error> {
let s = self.s;
let attached = s.objs(id, b"AdCh");
let mut mask: Option<Path> = None;
let mut pixels: Option<Image> = None;
for a in attached {
let class = s.class(a).unwrap_or(Tag(0));
if s.bool(a, b"Visi") == Some(false) {
continue;
}
if class == Tag::of(b"PCrv") || class == Tag::of(b"ShpN") || class == Tag::of(b"Comp") {
let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world);
if let Some((p, _)) = crate::geometry::outline(self, a, class, local) {
mask.get_or_insert_with(Path::default).subpaths.extend(p.transformed(local).subpaths);
}
} else if class == Tag::of(b"MRst") {
let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world);
match crate::raster::mask(self, a, local, over)? {
Some(m) if pixels.is_none() => pixels = Some(m),
Some(_) => self.warn("several pixel masks on one layer (only the first is used)"),
None => {}
}
} else {
self.warn(format!("{} layers attached to other layers (imported without them)", describe(class)));
}
}
Ok((mask, pixels))
}
/// The content of an Affinity document embedded in this one (`EmbN` whose `EmbC` entry holds
/// `EmDc`, four more bytes and a complete Affinity document): its first spread's nodes,
/// placed so the centre of its page, first artboard or content is the node's origin.
fn embedded_document(&mut self, id: ObjId, world: Affine) -> Option<Vec<Node>> {
let s = self.s;
let entry = s.obj(id, b"Bitm").and_then(|b| s.obj(b, b"EmCn")).and_then(|c| s.entry(c, b"EmbC"))?.to_string();
if entry.is_empty() {
return None;
}
if self.depth >= MAX_EMBED_DEPTH {
self.warn("embedded documents nested more than four deep");
return None;
}
let data = self.archive.read(&entry).ok()?;
let inner = data.strip_prefix(b"EmDc").and_then(|d| d.get(4..))?;
if !crate::is_affinity(inner) {
return None;
}
// A first reading finds its page and resolution, the second places it.
// Both readings are charged to the budget and the archive's limits, also when they fail:
// each does the work.
let mut budget = self.budget;
let probe = read_at(inner, self.archive.remaining(), &mut budget, Affine::IDENTITY, self.depth + 1);
self.budget = budget;
if self.archive.charge(probe.extracted).is_err() {
self.warn("embedded documents beyond the size limit (left out)");
return None;
}
let probe = match probe.document {
Ok(d) => d,
Err(e) => {
self.warn(format!("embedded documents that could not be read ({e})"));
return None;
}
};
let spread = probe.spreads.first()?;
// `PBBx` 2 places the content's own bounds (as with a cached picture); otherwise its page.
let content = s.obj(id, b"Bitm").and_then(|b| s.enumeration(b, b"PBBx")).is_some_and(|(k, _)| k == 2);
let first_board = spread.nodes.iter().find_map(|n| if let Kind::Artboard { rect, .. } = &n.kind { Some(*rect) } else { None });
let page = if content { None } else { spread.pages.first().copied().or(first_board) };
let page = page.or_else(|| nodes_bounds(&spread.nodes)).unwrap_or(spread.bounds);
// Its pixels aren't needed any more: never hold both readings' at once.
drop(probe);
// Its document pixels are the node's units, whatever either document's resolution.
let k = 1.0;
let (cx, cy) = ((page.x0 + page.x1) / 2.0, (page.y0 + page.y1) / 2.0);
let base = Affine([k, 0.0, 0.0, k, -cx * k, -cy * k]).then(world);
if !base.is_finite() {
self.warn("embedded documents with an invalid placement");
return None;
}
let mut budget = self.budget;
let placed = read_at(inner, self.archive.remaining(), &mut budget, base, self.depth + 1);
self.budget = budget;
if self.archive.charge(placed.extracted).is_err() {
self.warn("embedded documents beyond the size limit (left out)");
return None;
}
let doc = placed.document.ok()?;
for w in doc.warnings {
self.warn(format!("{w} [in embedded documents]"));
}
if doc.spreads.len() > 1 {
self.warn("embedded documents with several pages (the first is used)");
}
let mut nodes = doc.spreads.into_iter().next()?.nodes;
// Its master page instances count its own masters, which aren't kept: in this document
// they would show other masters.
fn strip_masters(nodes: &mut [Node], depth: usize) -> bool {
let mut found = false;
for n in nodes {
if matches!(n.kind, Kind::MasterInstance { .. }) {
n.kind = Kind::Unsupported;
found = true;
}
if depth < MAX_TREE_DEPTH {
found |= strip_masters(&mut n.children, depth + 1);
}
}
found
}
if strip_masters(&mut nodes, 0) {
self.warn("master pages of embedded documents (left out)");
}
Some(nodes)
}
fn artboard(&mut self, id: ObjId, world: Affine) -> Kind {
let s = self.s;
let Some(b) = s.floats::<4>(id, b"ShpB").map(rect).filter(|b| b.x1 > b.x0 && b.y1 > b.y0) else {
self.warn("an artboard without valid bounds (its children are kept without clipping)");
return Kind::Unsupported;
};
let corners =
[Point { x: b.x0, y: b.y0 }, Point { x: b.x1, y: b.y0 }, Point { x: b.x1, y: b.y1 }, Point { x: b.x0, y: b.y1 }].map(|p| world.apply(p));
let [a, b2, c, d, ..] = world.0;
if b2.abs() > 1e-9 || c.abs() > 1e-9 || a <= 0.0 || d <= 0.0 {
self.warn("a rotated or flipped artboard (export bounds are its bounding box; artwork keeps its outline)");
}
let xs = corners.map(|p| p.x);
let ys = corners.map(|p| p.y);
let rect = Rect {
x0: xs.iter().copied().fold(f64::INFINITY, f64::min),
y0: ys.iter().copied().fold(f64::INFINITY, f64::min),
x1: xs.iter().copied().fold(f64::NEG_INFINITY, f64::max),
y1: ys.iter().copied().fold(f64::NEG_INFINITY, f64::max),
};
if ![rect.x0, rect.y0, rect.x1, rect.y1].iter().all(|v| v.is_finite()) || rect.x1 <= rect.x0 || rect.y1 <= rect.y0 {
self.warn("an artboard with an invalid transformed size (its children are kept without clipping)");
return Kind::Unsupported;
}
let class = s.class(id).unwrap_or(Tag::of(b"ShpN"));
let (path, even_odd) = crate::geometry::outline(self, id, class, world).unwrap_or_else(|| {
self.warn("an artboard whose outline could not be read (clipped to its rectangle)");
(Path { subpaths: vec![crate::shapes::rectangle(b.x0, b.y0, b.x1, b.y1)] }, false)
});
let (background, strokes) = paint::node_paint(self, id, world);
Kind::Artboard { rect, path: path.transformed(world), even_odd, background, strokes }
}
}
-663
View File
@@ -1,663 +0,0 @@
//! Colour and gradient overlays. VectorCraft has no such effect, so an overlay is baked into what
//! its node paints: fill, stroke and text colours, and pixels. The overlay lies over the node's
//! own paint in its blend mode at its opacity, inside the node's alpha (which it keeps).
//!
//! Blend modes follow the W3C Compositing and Blending formulas; the modes PDF lacks (Vivid
//! Light, Linear Light, Pin Light, Hard Mix, Add, Subtract, Average, Negation, Reflect, Glow,
//! Darker/Lighter Color) use their usual definitions.
use std::borrow::Cow;
use crate::model::{Affine, Blend, Effect, Image, Kind, Node, Pixels, Point};
use crate::paint::{Color, Gradient, GradientKind, Paint, Stop, Stroke};
/// Deepest subtree an overlay is baked into (the reader bounds trees well below this).
const MAX_DEPTH: usize = 256;
/// Most pixels an overlay is baked into per image.
const MAX_PIXELS: usize = 64 << 20;
/// Work the overlays of one import may take together: each overlay counts the nodes and pixels
/// of the subtree it is baked into (which is copied once more for them all). Nested overlays
/// and shared content would otherwise multiply it; past it, overlays are left out and said.
pub const MAX_WORK: u64 = 1 << 29;
#[derive(Clone, Copy)]
enum Source<'a> {
Solid(Color),
Gradient(&'a Gradient),
}
#[derive(Clone, Copy)]
struct Overlay<'a> {
source: Source<'a>,
opacity: f64,
blend: Blend,
}
/// `node` with its colour and gradient overlays baked in, and those of everything in it
/// (borrowed unchanged when `node` has none, or when what is left of `work`, see [`MAX_WORK`],
/// can't pay for copying it). `warn` hears what could only be approximated or was left out.
pub fn apply<'a>(node: &'a Node, work: &mut u64, warn: &mut dyn FnMut(&str)) -> Cow<'a, Node> {
if overlays(&node.effects).is_empty() {
return Cow::Borrowed(node);
}
let Some(left) = work.checked_sub(subtree_cost(node, *work, 0)) else {
warn("overlay effects beyond the work one import may take (left out)");
return Cow::Borrowed(node);
};
*work = left;
let mut out = node.clone();
bake_tree(&mut out, work, 0, warn);
Cow::Owned(out)
}
/// The visible colour and gradient overlays among `effects`.
fn overlays(effects: &[Effect]) -> Vec<Overlay<'_>> {
effects
.iter()
.filter_map(|e| match e {
Effect::ColorOverlay { color, opacity, blend } => Some(Overlay { source: Source::Solid(*color), opacity: *opacity, blend: *blend }),
Effect::GradientOverlay { gradient, opacity, blend } => {
Some(Overlay { source: Source::Gradient(gradient), opacity: *opacity, blend: *blend })
}
_ => None,
})
.filter(|o| o.opacity > 0.0)
.collect()
}
fn is_overlay(e: &Effect) -> bool {
matches!(e, Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. })
}
/// Bakes the overlays of `node` and its subtree into their paint, innermost first: an overlay
/// lies over what its node shows, its children's overlays included. Each overlay pays for the
/// subtree it is baked into out of `work`; past it, it is left out (and said).
fn bake_tree(node: &mut Node, work: &mut u64, depth: usize, warn: &mut dyn FnMut(&str)) {
if depth > MAX_DEPTH {
return;
}
for c in &mut node.children {
bake_tree(c, work, depth + 1, warn);
}
if !node.effects.iter().any(is_overlay) {
return;
}
let (effects, rest): (Vec<Effect>, Vec<Effect>) = std::mem::take(&mut node.effects).into_iter().partition(is_overlay);
node.effects = rest;
let overlays = overlays(&effects);
if overlays.is_empty() {
return;
}
let count = u64::try_from(overlays.len()).unwrap_or(u64::MAX);
let cost = subtree_cost(node, *work / count, 0).saturating_mul(count);
let Some(left) = work.checked_sub(cost) else {
warn("overlay effects beyond the work one import may take (left out)");
return;
};
*work = left;
for o in &overlays {
if matches!(o.blend, Blend::Erase | Blend::PassThrough) {
warn("overlay effects in a blend mode VectorCraft doesn't have (imported as Normal)");
}
bake_node(node, o, 0, warn);
}
}
/// Nodes and pixels in `node`'s subtree, counted only until they pass `limit`.
fn subtree_cost(node: &Node, limit: u64, depth: usize) -> u64 {
if depth > MAX_DEPTH {
return 0;
}
let mut cost: u64 = match &node.kind {
Kind::Image(img) => (u64::from(img.width) * u64::from(img.height)).saturating_add(1),
Kind::Text(t) => u64::try_from(t.runs.len()).unwrap_or(u64::MAX).saturating_add(1),
Kind::Table(t) => u64::try_from(t.cells.len()).unwrap_or(u64::MAX).saturating_add(1),
_ => 1,
};
for c in &node.children {
if cost > limit {
break;
}
cost = cost.saturating_add(subtree_cost(c, limit - cost, depth + 1));
}
cost
}
fn bake_node(node: &mut Node, o: &Overlay, depth: usize, warn: &mut dyn FnMut(&str)) {
if depth > MAX_DEPTH {
return;
}
match &mut node.kind {
Kind::Shape { fills, strokes, .. } => {
for f in fills.iter_mut() {
*f = paint(f, o, warn);
}
strokes.iter_mut().for_each(|s| stroke(s, o, warn));
}
Kind::Artboard { background, strokes, .. } => {
for f in background.iter_mut() {
*f = paint(f, o, warn);
}
strokes.iter_mut().for_each(|s| stroke(s, o, warn));
}
Kind::Text(t) => {
for r in &mut t.runs {
r.fill = paint(&r.fill, o, warn);
if let Some(s) = &mut r.stroke {
stroke(s, o, warn);
}
}
}
Kind::Table(t) => {
for c in &mut t.cells {
for r in &mut c.runs {
r.fill = paint(&r.fill, o, warn);
if let Some(s) = &mut r.stroke {
stroke(s, o, warn);
}
}
}
for s in t.vertical.iter_mut().chain(t.horizontal.iter_mut()).flatten() {
stroke(s, o, warn);
}
}
Kind::Image(img) => {
if !pixels(img, o) {
warn("overlay effects on images too large to recolour (left out)");
}
}
Kind::Layer | Kind::Group | Kind::Unsupported | Kind::MasterInstance { .. } => {}
}
for e in &mut node.effects {
match e {
Effect::Outline { color, .. } => *color = over(*color, o.source.at_solid(), o),
Effect::DropShadow { .. } | Effect::InnerShadow { .. } | Effect::OuterGlow { .. } | Effect::Bevel { .. } => {}
Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. } => {}
}
}
for c in &mut node.children {
bake_node(c, o, depth + 1, warn);
}
}
fn stroke(s: &mut Stroke, o: &Overlay, warn: &mut dyn FnMut(&str)) {
s.paint = paint(&s.paint, o, warn);
}
/// A paint with the overlay over it.
fn paint(p: &Paint, o: &Overlay, warn: &mut dyn FnMut(&str)) -> Paint {
match (p, o.source) {
(Paint::None, _) => Paint::None,
(Paint::Solid(c), Source::Solid(s)) => Paint::Solid(over(*c, s, o)),
(Paint::Gradient(g), Source::Solid(s)) => {
Paint::Gradient(Gradient { stops: g.stops.iter().map(|st| Stop { color: over(st.color, s, o), ..*st }).collect(), ..g.clone() })
}
// Over one colour, the result is the overlay's gradient with each stop laid over it.
(Paint::Solid(c), Source::Gradient(g)) => {
Paint::Gradient(Gradient { stops: g.stops.iter().map(|st| Stop { color: over(*c, st.color, o), ..*st }).collect(), ..g.clone() })
}
(Paint::Gradient(base), Source::Gradient(g)) => {
if !(o.blend == Blend::Normal && o.opacity >= 1.0) {
warn("gradient overlays on gradients (approximated)");
}
// Exact when the overlay covers it; otherwise over the base gradient's average colour.
let avg = average(base);
Paint::Gradient(Gradient { stops: g.stops.iter().map(|st| Stop { color: over(avg, st.color, o), ..*st }).collect(), ..g.clone() })
}
}
}
impl Source<'_> {
/// One colour for the source (a gradient's average) where only one fits.
fn at_solid(&self) -> Color {
match self {
Source::Solid(c) => *c,
Source::Gradient(g) => average(g),
}
}
}
fn average(g: &Gradient) -> Color {
let n = g.stops.len().max(1) as f64;
let (mut r, mut gr, mut b, mut a) = (0.0, 0.0, 0.0, 0.0);
for s in &g.stops {
let [sr, sg, sb] = rgb(s.color);
r += sr;
gr += sg;
b += sb;
a += s.color.alpha();
}
Color::Rgb { r: r / n, g: gr / n, b: b / n, a: a / n }
}
/// `source` laid over `base` in the overlay's mode and opacity; `base`'s alpha is kept.
fn over(base: Color, source: Color, o: &Overlay) -> Color {
let k = (o.opacity * source.alpha()).clamp(0.0, 1.0);
let alpha = base.alpha();
// Normal mixes within the colour model when both share it, so CMYK stays CMYK.
if matches!(o.blend, Blend::Normal | Blend::PassThrough | Blend::Erase) {
let mix = |a: f64, b: f64| a + (b - a) * k;
match (base, source) {
(Color::Cmyk { c, m, y, k: kk, .. }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2, .. }) => {
return Color::Cmyk { c: mix(c, c2), m: mix(m, m2), y: mix(y, y2), k: mix(kk, k2), a: alpha };
}
(Color::Gray { v, .. }, Color::Gray { v: v2, .. }) => return Color::Gray { v: mix(v, v2), a: alpha },
(_, s) if k >= 1.0 => return with_alpha(s, alpha),
_ => {}
}
}
let b = rgb(base);
let s = rgb(source);
let blended = blend(o.blend, b, s);
let [r, g, bl] = [0, 1, 2].map(|i| b[i] + (blended[i] - b[i]) * k);
Color::Rgb { r, g, b: bl, a: alpha }
}
fn with_alpha(c: Color, a: f64) -> Color {
match c {
Color::Rgb { r, g, b, .. } => Color::Rgb { r, g, b, a },
Color::Cmyk { c, m, y, k, .. } => Color::Cmyk { c, m, y, k, a },
Color::Gray { v, .. } => Color::Gray { v, a },
Color::Lab { l, a: la, b, .. } => Color::Lab { l, a: la, b, alpha: a },
}
}
/// sRGB components (0..1) of a colour. CMYK uses the profile-free formula (the engine shows the
/// node's other CMYK colours through the document's profile), Lab its D50 sRGB colour.
fn rgb(c: Color) -> [f64; 3] {
let f = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
match c {
Color::Rgb { r, g, b, .. } => [f(r), f(g), f(b)],
Color::Gray { v, .. } => [f(v); 3],
Color::Cmyk { c, m, y, k, .. } => {
let w = 1.0 - f(k);
[(1.0 - f(c)) * w, (1.0 - f(m)) * w, (1.0 - f(y)) * w]
}
Color::Lab { l, a, b, .. } => lab_to_srgb(l, a, b).map(f),
}
}
/// CIE L*a*b* (D50) to sRGB, through XYZ and the Bradford adaptation to D65.
fn lab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
let finite = |v: f64| if v.is_finite() { v } else { 0.0 };
let (l, a, b) = (finite(l), finite(a), finite(b));
let fy = (l + 16.0) / 116.0;
let (fx, fz) = (fy + a / 500.0, fy - b / 200.0);
let inv = |t: f64| if t > 6.0 / 29.0 { t * t * t } else { 3.0 * (6.0f64 / 29.0).powi(2) * (t - 4.0 / 29.0) };
// D50 white.
let (x, y, z) = (0.964_22 * inv(fx), inv(fy), 0.825_21 * inv(fz));
// XYZ (D50) to linear sRGB, Bradford-adapted.
let r = 3.133_856 * x - 1.616_867 * y - 0.490_615 * z;
let g = -0.978_768 * x + 1.916_142 * y + 0.033_454 * z;
let bl = 0.071_945 * x - 0.228_991 * y + 1.405_243 * z;
let gamma = |v: f64| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.max(0.0).powf(1.0 / 2.4) - 0.055 };
[gamma(r), gamma(g), gamma(bl)]
}
/// Bake the overlay into an image's pixels. False if they couldn't be read or are too many.
fn pixels(img: &mut Image, o: &Overlay) -> bool {
let Some(n) = (img.width as usize).checked_mul(img.height as usize).filter(|n| *n <= MAX_PIXELS) else { return false };
let Some(len) = n.checked_mul(4) else { return false };
let mut px = match &img.pixels {
Pixels::Rgba8(p) => match p.get(..len) {
Some(p) => p.to_vec(),
None => return false,
},
Pixels::Encoded(bytes) => match decode(bytes, img.width, img.height) {
Some(p) => p,
None => return false,
},
// An overlay is blended in RGB: CMYK pixels take the profile-free formula here.
Pixels::Cmyka8(p) => match p.get(..n.saturating_mul(5)) {
Some(p) if p.len() == n * 5 => p
.as_chunks::<5>()
.0
.iter()
.flat_map(|[c, m, y, k, a]| {
let w = 255 - u16::from(*k);
let ch = |v: u8| ((u16::from(255 - v) * w + 127) / 255) as u8;
[ch(*c), ch(*m), ch(*y), *a]
})
.collect(),
_ => return false,
},
};
let width = img.width.max(1) as usize;
// A solid source is converted once; a gradient is sampled at each pixel's centre.
let solid = match o.source {
Source::Solid(c) => Some((rgb(c), c.alpha())),
Source::Gradient(_) => None,
};
let to_unit = match o.source {
Source::Gradient(g) => match invert(g.transform) {
Some(m) => Some((img.transform.then(m), g)),
None => return false,
},
Source::Solid(_) => None,
};
for (i, p) in px.as_chunks_mut::<4>().0.iter_mut().enumerate() {
if p[3] == 0 {
continue;
}
let (s, sa) = match (solid, &to_unit) {
(Some(s), _) => s,
(None, Some((m, g))) => {
let q = m.apply(Point { x: (i % width) as f64 + 0.5, y: (i / width) as f64 + 0.5 });
let c = sample(g, q);
(rgb(c), c.alpha())
}
(None, None) => continue,
};
let k = (o.opacity * sa).clamp(0.0, 1.0);
let b = [p[0], p[1], p[2]].map(|v| f64::from(v) / 255.0);
let m = blend(o.blend, b, s);
for c in 0..3 {
p[c] = ((b[c] + (m[c] - b[c]) * k).clamp(0.0, 1.0) * 255.0).round() as u8;
}
}
img.pixels = Pixels::Rgba8(px);
true
}
/// An encoded original's RGBA pixels, decoded only if it is `width` × `height` as its layer says.
fn decode(bytes: &[u8], width: u32, height: u32) -> Option<Vec<u8>> {
let probe = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
if probe.into_dimensions().ok()? != (width, height) {
return None;
}
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
let mut limits = image::Limits::default();
limits.max_image_width = Some(width);
limits.max_image_height = Some(height);
limits.max_alloc = u64::try_from(MAX_PIXELS).ok().map(|n| n * 8);
reader.limits(limits);
Some(reader.decode().ok()?.into_rgba8().into_raw())
}
/// The gradient's colour at unit-space point `q`.
fn sample(g: &Gradient, q: Point) -> Color {
let t = match g.kind {
GradientKind::Linear => q.x,
GradientKind::Radial => q.x.hypot(q.y),
GradientKind::Conical => q.y.atan2(q.x).rem_euclid(std::f64::consts::TAU) / std::f64::consts::TAU,
};
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
let (Some(first), Some(last)) = (g.stops.first(), g.stops.last()) else { return Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 0.0 } };
if t <= first.offset {
return first.color;
}
for w in g.stops.windows(2) {
let [a, b] = [&w[0], &w[1]];
if t <= b.offset {
let span = b.offset - a.offset;
let u = if span > 1e-9 { (t - a.offset) / span } else { 1.0 };
// Affinity's midpoint bias (see `Stop::half_point`).
let k = 1.0 + 8.0 * (a.bias - 0.5).abs();
let u = if a.bias >= 0.5 { u.powf(k) } else { 1.0 - (1.0 - u).powf(k) };
let (x, y) = (rgb(a.color), rgb(b.color));
let [r, g, bl] = [0, 1, 2].map(|i| x[i] + (y[i] - x[i]) * u);
return Color::Rgb { r, g, b: bl, a: a.color.alpha() + (b.color.alpha() - a.color.alpha()) * u };
}
}
last.color
}
fn invert(m: Affine) -> Option<Affine> {
let [a, b, c, d, e, f] = m.0;
let det = a * d - b * c;
if !(det.is_finite() && det.abs() > 1e-12) {
return None;
}
let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det);
Some(Affine([ia, ib, ic, id, -(ia * e + ic * f), -(ib * e + id * f)]))
}
/// The blend of backdrop `b` and source `s` (sRGB, 0..1).
fn blend(mode: Blend, b: [f64; 3], s: [f64; 3]) -> [f64; 3] {
use Blend::*;
let sep = |f: fn(f64, f64) -> f64| [0, 1, 2].map(|i| f(b[i], s[i]).clamp(0.0, 1.0));
match mode {
Normal | PassThrough | Erase => s,
Darken => sep(f64::min),
Lighten => sep(f64::max),
Multiply => sep(|b, s| b * s),
Screen => sep(screen),
ColorBurn => sep(burn),
ColorDodge => sep(dodge),
Blend::Overlay => sep(|b, s| hard_light(s, b)),
HardLight => sep(hard_light),
SoftLight => sep(soft_light),
Difference => sep(|b, s| (b - s).abs()),
Exclusion => sep(|b, s| b + s - 2.0 * b * s),
Add => sep(|b, s| b + s),
Subtract => sep(|b, s| b - s),
VividLight => sep(|b, s| if s <= 0.5 { burn(b, 2.0 * s) } else { dodge(b, 2.0 * s - 1.0) }),
LinearLight => sep(|b, s| b + 2.0 * s - 1.0),
PinLight => sep(|b, s| if s <= 0.5 { b.min(2.0 * s) } else { b.max(2.0 * s - 1.0) }),
HardMix => sep(|b, s| if b + s >= 1.0 { 1.0 } else { 0.0 }),
Average => sep(|b, s| (b + s) / 2.0),
Negation => sep(|b, s| 1.0 - (1.0 - b - s).abs()),
Reflect => sep(reflect),
Glow => sep(|b, s| reflect(s, b)),
DarkerColor => {
if lum(s) < lum(b) {
s
} else {
b
}
}
LighterColor => {
if lum(s) > lum(b) {
s
} else {
b
}
}
Hue => set_lum(set_sat(s, sat(b)), lum(b)),
Saturation => set_lum(set_sat(b, sat(s)), lum(b)),
Blend::Color => set_lum(s, lum(b)),
Luminosity => set_lum(b, lum(s)),
}
}
fn screen(b: f64, s: f64) -> f64 {
b + s - b * s
}
fn burn(b: f64, s: f64) -> f64 {
if b >= 1.0 {
1.0
} else if s <= 0.0 {
0.0
} else {
1.0 - ((1.0 - b) / s).min(1.0)
}
}
fn dodge(b: f64, s: f64) -> f64 {
if b <= 0.0 {
0.0
} else if s >= 1.0 {
1.0
} else {
(b / (1.0 - s)).min(1.0)
}
}
fn hard_light(b: f64, s: f64) -> f64 {
if s <= 0.5 { b * 2.0 * s } else { screen(b, 2.0 * s - 1.0) }
}
fn soft_light(b: f64, s: f64) -> f64 {
if s <= 0.5 {
b - (1.0 - 2.0 * s) * b * (1.0 - b)
} else {
let d = if b <= 0.25 { ((16.0 * b - 12.0) * b + 4.0) * b } else { b.sqrt() };
b + (2.0 * s - 1.0) * (d - b)
}
}
fn reflect(b: f64, s: f64) -> f64 {
if s >= 1.0 { 1.0 } else { (b * b / (1.0 - s)).min(1.0) }
}
fn lum(c: [f64; 3]) -> f64 {
0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]
}
fn clip_color(c: [f64; 3]) -> [f64; 3] {
let l = lum(c);
let n = c[0].min(c[1]).min(c[2]);
let x = c[0].max(c[1]).max(c[2]);
c.map(|v| {
let mut v = v;
if n < 0.0 && l - n > 1e-12 {
v = l + (v - l) * l / (l - n);
}
if x > 1.0 && x - l > 1e-12 {
v = l + (v - l) * (1.0 - l) / (x - l);
}
v.clamp(0.0, 1.0)
})
}
fn set_lum(c: [f64; 3], l: f64) -> [f64; 3] {
let d = l - lum(c);
clip_color(c.map(|v| v + d))
}
fn sat(c: [f64; 3]) -> f64 {
c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2])
}
fn set_sat(c: [f64; 3], s: f64) -> [f64; 3] {
let max = c[0].max(c[1]).max(c[2]);
let min = c[0].min(c[1]).min(c[2]);
if max - min <= 1e-12 {
return [0.0; 3];
}
c.map(|v| (v - min) * s / (max - min))
}
#[cfg(test)]
mod tests {
use super::*;
fn solid(c: Color, opacity: f64, blend: Blend) -> Node {
Node {
class: crate::stream::Tag::of(b"ShpN"),
name: String::new(),
visible: true,
locked: false,
opacity: 1.0,
blend: Blend::Normal,
kind: Kind::Shape {
path: Default::default(),
fills: vec![Paint::Solid(Color::Rgb { r: 1.0, g: 0.5, b: 0.0, a: 1.0 })],
strokes: vec![],
even_odd: false,
},
mask: None,
pixel_mask: None,
effects: vec![Effect::ColorOverlay { color: c, opacity, blend }],
children: vec![],
}
}
fn fill(n: &Node) -> Color {
match &n.kind {
Kind::Shape { fills, .. } => match fills.first() {
Some(Paint::Solid(c)) => *c,
other => panic!("{other:?}"),
},
other => panic!("{other:?}"),
}
}
#[test]
fn a_full_colour_overlay_replaces_the_fill_and_keeps_its_alpha() {
let white = Color::Rgb { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
let n = apply(&solid(white, 1.0, Blend::Normal), &mut { MAX_WORK }, &mut |_| {}).into_owned();
assert_eq!(fill(&n), white);
assert!(n.effects.is_empty(), "the overlay is baked, not kept");
// Half way, mixed in RGB.
let n = apply(&solid(white, 0.5, Blend::Normal), &mut { MAX_WORK }, &mut |_| {}).into_owned();
assert_eq!(fill(&n), Color::Rgb { r: 1.0, g: 0.75, b: 0.5, a: 1.0 });
}
#[test]
fn blend_modes_follow_their_formulas() {
let b = [0.25, 0.5, 1.0];
assert_eq!(blend(Blend::Multiply, b, [0.5; 3]), [0.125, 0.25, 0.5]);
assert_eq!(blend(Blend::Screen, b, [0.5; 3]), [0.625, 0.75, 1.0]);
assert_eq!(blend(Blend::VividLight, [0.5; 3], [0.75; 3]), [1.0; 3]);
assert_eq!(blend(Blend::HardMix, [0.5; 3], [0.6; 3]), [1.0; 3]);
// Color keeps the backdrop's luminosity with the source's hue and saturation.
let c = blend(Blend::Color, [0.5; 3], [1.0, 0.0, 0.0]);
assert!((lum(c) - 0.5).abs() < 1e-9 && c[0] > c[1] && (c[1] - c[2]).abs() < 1e-9, "{c:?}");
}
#[test]
fn overlays_recolour_pixels_inside_their_alpha() {
let mut n = solid(Color::Rgb { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }, 1.0, Blend::Normal);
n.kind = Kind::Image(Image { width: 2, height: 1, pixels: Pixels::Rgba8(vec![255, 0, 0, 255, 255, 0, 0, 0]), transform: Affine::IDENTITY });
let out = apply(&n, &mut { MAX_WORK }, &mut |_| {}).into_owned();
let Kind::Image(img) = &out.kind else { panic!() };
assert_eq!(img.pixels, Pixels::Rgba8(vec![0, 0, 255, 255, 255, 0, 0, 0]));
}
#[test]
fn a_gradient_overlay_over_one_colour_becomes_that_gradient() {
let g = Gradient {
kind: GradientKind::Linear,
stops: vec![
Stop { offset: 0.0, color: Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }, bias: 0.5 },
Stop { offset: 1.0, color: Color::Rgb { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }, bias: 0.5 },
],
transform: Affine([10.0, 0.0, 0.0, 10.0, 0.0, 0.0]),
};
let mut n = solid(Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }, 1.0, Blend::Normal);
n.effects = vec![Effect::GradientOverlay { gradient: g.clone(), opacity: 1.0, blend: Blend::Normal }];
let out = apply(&n, &mut { MAX_WORK }, &mut |_| {}).into_owned();
let Kind::Shape { fills, .. } = &out.kind else { panic!() };
assert_eq!(fills.first(), Some(&Paint::Gradient(g)));
}
#[test]
fn a_group_overlay_lies_over_its_childrens_overlays() {
let red = Color::Rgb { r: 1.0, g: 0.0, b: 0.0, a: 1.0 };
let blue = Color::Rgb { r: 0.0, g: 0.0, b: 1.0, a: 1.0 };
let mut group = solid(red, 0.5, Blend::Normal);
group.kind = Kind::Group;
group.children = vec![solid(blue, 1.0, Blend::Normal)];
// The copy (2 nodes), the child's overlay (1) and the group's (2).
let mut work = 5;
let out = apply(&group, &mut work, &mut |_| {}).into_owned();
assert_eq!(work, 0);
let child = out.children.first().unwrap();
// Blue first, then half of the group's red over it.
assert_eq!(fill(child), Color::Rgb { r: 0.5, g: 0.0, b: 0.5, a: 1.0 });
assert!(out.effects.is_empty() && child.effects.is_empty(), "both overlays are baked");
// With no work left for the group's overlay, the child's still applies.
let mut warnings = Vec::new();
let out = apply(&group, &mut { 4 }, &mut |w| warnings.push(w.to_string())).into_owned();
assert_eq!(fill(out.children.first().unwrap()), blue);
assert!(warnings.iter().any(|w| w.contains("beyond the work")), "{warnings:?}");
}
#[test]
fn overlays_stop_at_the_work_one_import_may_take() {
let mut n = solid(Color::Rgb { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }, 1.0, Blend::Normal);
n.kind = Kind::Image(Image { width: 4, height: 4, pixels: Pixels::Rgba8(vec![255; 64]), transform: Affine::IDENTITY });
// 16 pixels and the node, for the copy and for the overlay: 34.
let mut work = 40;
let mut warnings = Vec::new();
assert!(matches!(apply(&n, &mut work, &mut |w| warnings.push(w.to_string())), Cow::Owned(_)));
assert_eq!((work, warnings.len()), (6, 0));
assert!(matches!(apply(&n, &mut work, &mut |w| warnings.push(w.to_string())), Cow::Borrowed(_)));
assert_eq!(work, 6);
assert!(warnings.iter().any(|w| w.contains("beyond the work")), "{warnings:?}");
}
}
-357
View File
@@ -1,357 +0,0 @@
//! Fills, strokes and colours. Two schemas exist: Affinity 1 (`BFil` fill, `PFil` stroke paint,
//! `LSty` stroke style) and Affinity 2/3 (`BFFl`, `LIFl` and `LILn` lists with a current index).
use crate::model::{Affine, Reader};
use crate::stream::{ObjId, Value};
/// A colour as stored: RGB and grey values are encoded in the document's RGB space (sRGB unless
/// the document embeds another profile), CMYK values go through its CMYK profile. Alpha is straight.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Color {
Rgb {
r: f64,
g: f64,
b: f64,
a: f64,
},
Cmyk {
c: f64,
m: f64,
y: f64,
k: f64,
a: f64,
},
Gray {
v: f64,
a: f64,
},
/// CIE L*a*b* (D50).
Lab {
l: f64,
a: f64,
b: f64,
alpha: f64,
},
}
impl Color {
pub fn alpha(&self) -> f64 {
match self {
Color::Rgb { a, .. } | Color::Cmyk { a, .. } | Color::Gray { a, .. } => *a,
Color::Lab { alpha, .. } => *alpha,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GradientKind {
Linear,
/// Elliptical and radial: distance from the centre in unit space.
Radial,
/// Angle around the centre.
Conical,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Stop {
pub offset: f64,
pub color: Color,
/// Affinity's midpoint bias for the segment from this stop to the next (0.5 = even blend).
pub bias: f64,
}
impl Stop {
/// Where, between this stop (0) and the next (1), the blend reaches half way: the bias curve
/// fitted to Affinity's renders is `t^k` (bias ≥ 0.5) or `1-(1-t)^k`, with `k = 1 + 8·|bias-0.5|`.
pub fn half_point(&self) -> f64 {
let k = 1.0 + 8.0 * (self.bias - 0.5).abs();
let h = 0.5f64.powf(1.0 / k);
if self.bias >= 0.5 { h } else { 1.0 - h }
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Gradient {
pub kind: GradientKind,
pub stops: Vec<Stop>,
/// Unit space to document pixels: linear runs from unit (0,0) to (1,0); radial is the unit
/// circle; conical starts along unit +x and turns towards unit +y.
pub transform: Affine,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub enum Paint {
#[default]
None,
Solid(Color),
Gradient(Gradient),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Cap {
Butt,
Round,
Square,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Join {
Miter,
Round,
Bevel,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Align {
Center,
Inside,
Outside,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Stroke {
pub paint: Paint,
/// Width in document pixels.
pub width: f64,
pub cap: Cap,
pub join: Join,
pub miter_limit: f64,
pub align: Align,
/// Dash and gap lengths in document pixels, and the phase.
pub dash: Option<(Vec<f64>, f64)>,
/// Painted below the fill instead of above it.
pub behind: bool,
}
/// Gradient stops per gradient.
const MAX_STOPS: usize = 1024;
/// Dash and gap lengths per dash pattern (a pattern has a few; strokes and text runs copy theirs).
const MAX_DASHES: usize = 64;
fn floats(v: &Value) -> Option<Vec<f64>> {
match v {
Value::Floats(f) => Some(f.clone()),
Value::Bytes(b) if b.len() % 4 == 0 => Some(b.as_chunks::<4>().0.iter().map(|c| f64::from(f32::from_le_bytes(*c))).collect()),
_ => None,
}
}
/// A colour object (`RGBA`, `HSLA`, `CMYK`, `GRAY`, `LABA`, `Pant`).
pub(crate) fn color(r: &mut Reader, id: ObjId) -> Option<Color> {
color_within(r, id, 0)
}
/// The most spot colours that stand for one another followed.
const MAX_SPOT_CHAIN: u32 = 8;
/// [`color`], `depth` spot colours deep: one that stands for itself (or a ring of them) ends here.
fn color_within(r: &mut Reader, id: ObjId, depth: u32) -> Option<Color> {
let s = r.s;
let class = s.class(id)?;
let col = || -> Option<Vec<f64>> {
let v = floats(s.field(id, b"_col")?)?;
v.iter().all(|f| f.is_finite()).then_some(v)
};
Some(match &class.0.to_be_bytes() {
b"RGBA" => {
let v = col()?;
Color::Rgb { r: *v.first()?, g: *v.get(1)?, b: *v.get(2)?, a: v.get(3)?.clamp(0.0, 1.0) }
}
b"HSLA" => {
let v = col()?;
let (r2, g, b) = hsl(*v.first()?, *v.get(1)?, *v.get(2)?);
Color::Rgb { r: r2, g, b, a: v.get(3)?.clamp(0.0, 1.0) }
}
b"CMYK" => {
let v = col()?;
Color::Cmyk { c: *v.first()?, m: *v.get(1)?, y: *v.get(2)?, k: *v.get(3)?, a: v.get(4)?.clamp(0.0, 1.0) }
}
b"GRAY" => {
let v = col()?;
Color::Gray { v: *v.first()?, a: v.get(1)?.clamp(0.0, 1.0) }
}
b"LABA" => {
let b = s.bytes(id, b"_col")?;
let u = |i: usize| -> Option<f64> { Some(f64::from(u16::from_le_bytes([*b.get(2 * i)?, *b.get(2 * i + 1)?])) / 65535.0) };
Color::Lab { l: 100.0 * u(0)?, a: 255.0 * u(1)? - 128.0, b: 255.0 * u(2)? - 128.0, alpha: u(3)? }
}
b"Pant" => {
r.warn("spot colours (imported as their RGB equivalent)");
if depth >= MAX_SPOT_CHAIN {
return None;
}
return s
.obj(id, b"srgb")
.and_then(|c| color_within(r, c, depth + 1))
.or_else(|| s.obj(id, b"base").and_then(|c| color_within(r, c, depth + 1)));
}
b"RegC" => Color::Cmyk { c: 1.0, m: 1.0, y: 1.0, k: 1.0, a: 1.0 },
_ => {
r.warn("colours in an unknown model");
return None;
}
})
}
fn hsl(h: f64, s: f64, l: f64) -> (f64, f64, f64) {
let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
let hp = (h.rem_euclid(1.0)) * 6.0;
let x = c * (1.0 - (hp % 2.0 - 1.0).abs());
let (r, g, b) = match hp as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = l - c / 2.0;
(r + m, g + m, b + m)
}
/// A fill descriptor (`FDsc`) or, in Affinity 1 files, a bare `FilS`; `local` maps the node's
/// space to document pixels.
pub(crate) fn descriptor(r: &mut Reader, id: ObjId, local: Affine) -> Option<Paint> {
let s = r.s;
let (fill, unit) = if s.is(id, b"FDsc") {
let unit = s.floats::<6>(id, b"FDeX").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
(s.obj(id, b"FDeF")?, unit)
} else {
(id, Affine::IDENTITY)
};
match &s.class(fill)?.0.to_be_bytes() {
b"FilN" => Some(Paint::None),
b"FilS" => Some(Paint::Solid(color(r, s.obj(fill, b"Colr")?)?)),
b"FilG" => {
let kind = match s.enumeration(fill, b"Type").map(|(i, _)| i) {
Some(0) | None => GradientKind::Linear,
Some(1 | 2) => GradientKind::Radial,
Some(3) => GradientKind::Conical,
Some(_) => {
r.warn("gradients of an unknown kind (imported as linear)");
GradientKind::Linear
}
};
let grad = s.obj(fill, b"Grad")?;
let cols = s.objs(grad, b"Cols");
let posn: Vec<Vec<f64>> = match s.field(grad, b"Posn") {
Some(Value::Array(a)) => a.iter().filter_map(floats).collect(),
_ => Vec::new(),
};
let mut stops = Vec::new();
for (c, p) in cols.iter().zip(&posn).take(MAX_STOPS) {
let color = color(r, *c)?;
let offset = p.first().copied().filter(|v| v.is_finite()).unwrap_or(0.0).clamp(0.0, 1.0);
let bias = p.get(1).copied().filter(|v| v.is_finite()).unwrap_or(0.5).clamp(0.0, 1.0);
stops.push(Stop { offset, color, bias });
}
if stops.is_empty() {
return Some(Paint::None);
}
Some(Paint::Gradient(Gradient { kind, stops, transform: unit.then(local) }))
}
b"FilB" => {
r.warn("bitmap and pattern fills (left empty)");
Some(Paint::None)
}
_ => {
r.warn("fills of an unknown kind (left empty)");
Some(Paint::None)
}
}
}
fn current(r: &Reader, id: ObjId, list: &[u8; 4], index: &[u8; 4]) -> Option<ObjId> {
let items = r.s.objs(id, list);
let i = r.s.int(id, index).and_then(|i| usize::try_from(i).ok()).unwrap_or(0);
items.get(i).or_else(|| items.first()).copied()
}
/// The fills of `list` (artboard backgrounds use `BFFl`).
pub(crate) fn fills(r: &mut Reader, id: ObjId, local: Affine, list: &[u8; 4]) -> Vec<crate::paint::Paint> {
let d = current(r, id, list, b"BFCr").or_else(|| r.s.obj(id, b"BFil"));
d.and_then(|d| descriptor(r, d, local)).filter(|p| *p != Paint::None).into_iter().collect()
}
/// A node's fill and stroke. `local` maps the node's space to document pixels.
pub(crate) fn node_paint(r: &mut Reader, id: ObjId, local: Affine) -> (Vec<Paint>, Vec<Stroke>) {
let s = r.s;
let fills = fills(r, id, local, b"BFFl");
if r.s.objs(id, b"BFFl").len() > 1 || r.s.objs(id, b"LIFl").len() > 1 {
r.warn("several fills or strokes on one object (only the active one is imported)");
}
if s.f64(id, b"FOpc").is_some_and(|o| o < 0.999) {
r.warn("fill opacity (imported at full fill opacity)");
}
if s.obj(id, b"Trns").is_some() {
r.warn("transparency gradients (imported without them)");
}
let (pen, style) = if s.field(id, b"LIFl").is_some() {
(current(r, id, b"LIFl", b"LICr"), current(r, id, b"LILn", b"LICr"))
} else {
(s.obj(id, b"PFil"), s.obj(id, b"LSty"))
};
let behind = matches!(s.field(id, b"DrwO"), Some(Value::Array(a)) if a.first() == Some(&Value::Enum { id: 1, version: 0 }));
let stroke = match (pen, style) {
(Some(pen), Some(style)) => stroke(r, pen, style, local, behind),
_ => None,
};
(fills, stroke.into_iter().collect())
}
pub(crate) fn stroke(r: &mut Reader, pen: ObjId, ldsc: ObjId, local: Affine, behind: bool) -> Option<Stroke> {
let s = r.s;
let paint = descriptor(r, pen, local)?;
if paint == Paint::None {
return None;
}
let lsty = if s.is(ldsc, b"LDsc") { s.obj(ldsc, b"LDeL")? } else { ldsc };
let weight = s.f64(lsty, b"Wght").filter(|w| *w > 0.0 && *w < 1e7)?;
// "Scale with object": the weight follows the object's transform; otherwise it is absolute.
let scales = s.bool(ldsc, b"LDSc").unwrap_or(true);
let width = if scales { weight * local.scale() } else { weight };
let data = s.bytes(lsty, b"Data").unwrap_or_default();
// Byte 10 is the stroke's style: 0 none, 1 solid, 2 dashed, 3 a brush. A shape without a
// stroke still stores one (black, 1 px wide), with style 0. Identified on two documents their
// owner made, where every such stroke is invisible in Affinity's own PDF export, and checked
// against the public corpus's thumbnails.
if data.get(10) == Some(&0) {
return None;
}
let miter_limit = data.get(0..8).and_then(|b| b.try_into().ok()).map(f64::from_le_bytes).filter(|m| m.is_finite() && *m >= 1.0).unwrap_or(4.0);
// Cap and join bytes are only partly understood: (0, 0) is butt/miter in every clean sample;
// (2, 2) ends plain lines square and brush lines round; joins import round, which never
// looks wrong.
let (cap, join) = match (data.get(8).copied(), data.get(9).copied(), data.get(10).copied()) {
(Some(0), Some(0), _) => (Cap::Butt, Join::Miter),
(Some(0), Some(_), _) => (Cap::Butt, Join::Round),
(Some(2), Some(2), Some(3)) => (Cap::Round, Join::Round),
(Some(2), Some(2), _) => (Cap::Square, Join::Round),
_ => (Cap::Round, Join::Round),
};
let align = match s.int(ldsc, b"LDSa") {
Some(1) => Align::Inside,
Some(2) => Align::Outside,
_ => Align::Center,
};
let dash = match s.field(lsty, b"Patn") {
Some(Value::Array(a)) if a.len() > MAX_DASHES => {
r.warn("dash patterns of more than 64 lengths (imported as solid lines)");
None
}
Some(Value::Array(a)) if data.get(10) == Some(&2) || !a.is_empty() => {
let mut v: Vec<f64> = a.iter().filter_map(|x| if let Value::Float(f) = x { Some(*f) } else { None }).collect();
while v.len() >= 2 && v.iter().rev().take(2).all(|x| *x == 0.0) {
v.truncate(v.len() - 2);
}
let valid = !v.is_empty() && v.iter().all(|x| x.is_finite() && *x >= 0.0) && v.iter().any(|x| *x > 0.0);
valid.then(|| (v.iter().map(|x| x * width).collect(), s.f64(lsty, b"Phse").unwrap_or(0.0) * width))
}
_ => None,
};
if s.obj(lsty, b"Brus").is_some() || s.obj(ldsc, b"LDeP").is_some() {
r.warn("brush and pressure strokes (imported as plain strokes)");
}
Some(Stroke { paint, width, cap, join, miter_limit, align, dash, behind })
}
Loaded 100 of 2115 files, more files were not shown because too many files have changed in this diff. Show more