mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-24 19:34:12 +01:00
#6613: reconcile Gujarati catalog and complete current interface coverage
This commit is contained in:
commit
6f6746bd72
1281 files changed
+220712
-20028
No files matched your search
@@ -17,25 +17,25 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
affinity3:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
AFFINITY_CORPUS_REQUIRED: "1"
|
||||
CARGO_PROFILE_DEV_DEBUG: "0"
|
||||
CARGO_PROFILE_TEST_DEBUG: "0"
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install Rust
|
||||
uses: 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
|
||||
@@ -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:
|
||||
@@ -26,57 +30,16 @@ jobs:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
|
||||
git-sources:
|
||||
name: Git dependencies come from storytold
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Git dependencies come from storytold
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
|
||||
# Source replacement, patches and path overrides in cargo config never show up
|
||||
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
|
||||
# Cargo still reads the legacy .cargo/config.
|
||||
python3 - <<'PY'
|
||||
import os, sys, tomllib
|
||||
for path in (".cargo/config", ".cargo/config.toml"):
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
config = tomllib.load(open(path, "rb"))
|
||||
replaced = [name for name, source in config.get("source", {}).items()
|
||||
if isinstance(source, dict) and "replace-with" in source]
|
||||
if replaced or "patch" in config or "paths" in config:
|
||||
print(f"{path} replaces, patches or overrides a source")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Fails when Cargo.lock is out of date with the manifests.
|
||||
cargo metadata --locked --format-version 1 > /dev/null
|
||||
python3 - <<'PY'
|
||||
import sys, tomllib
|
||||
lock = tomllib.load(open("Cargo.lock", "rb"))
|
||||
bad = sorted({p["source"] for p in lock.get("package", [])
|
||||
if p.get("source", "").startswith("git+")
|
||||
and not p["source"].startswith("git+https://github.com/storytold/")})
|
||||
if bad:
|
||||
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
|
||||
sys.exit(1)
|
||||
PY
|
||||
|
||||
release:
|
||||
needs: [git-sources, credits]
|
||||
needs: credits
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
# 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
|
||||
|
||||
@@ -20,7 +20,7 @@ Every non-code asset in this repository (icons, images, fonts, example art, colo
|
||||
|
||||
**Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
|
||||
|
||||
Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets and the vector tool cursors (`crates/ui-egui/src/cursors.rs`).
|
||||
Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets, the vector tool cursors (`crates/ui-egui/src/cursors.rs`) and the Learn panel's practice samples (`crates/ui-egui/src/panels/learn/samples.rs`).
|
||||
|
||||
**Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay.
|
||||
|
||||
@@ -159,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 | |
|
||||
@@ -265,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`) | |
|
||||
|
||||
Generated
+64
-57
@@ -217,7 +217,7 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
"wl-clipboard-rs",
|
||||
"x11rb",
|
||||
]
|
||||
@@ -967,6 +967,17 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-affinity"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=228f6d0c50f1fdee4c5124603602993fc79d4c9d#228f6d0c50f1fdee4c5124603602993fc79d4c9d"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"image",
|
||||
"ruzstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
@@ -975,12 +986,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
|
||||
dependencies = [
|
||||
"fixed_decimal",
|
||||
"icu_decimal",
|
||||
@@ -1049,7 +1060,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
|
||||
dependencies = [
|
||||
"craft-fonts-build",
|
||||
"craft-i18n",
|
||||
@@ -1070,7 +1081,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"dunce",
|
||||
@@ -1097,7 +1108,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -1609,7 +1620,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3858,7 +3869,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4380,7 +4391,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4758,7 +4769,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys 0.12.1",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4817,7 +4828,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4879,9 +4890,6 @@ name = "ruzstd"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69e4ce4a039f42bf25920b95667e4d789e98749ab11bbb8d2c2936f788421bb5"
|
||||
dependencies = [
|
||||
"twox-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
@@ -5679,7 +5687,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix 1.1.6",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6066,12 +6074,6 @@ dependencies = [
|
||||
"core_maths",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "twox-hash"
|
||||
version = "2.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2"
|
||||
|
||||
[[package]]
|
||||
name = "type-map"
|
||||
version = "0.5.1"
|
||||
@@ -6313,7 +6315,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"arboard",
|
||||
"block2 0.6.2",
|
||||
@@ -6324,6 +6326,7 @@ dependencies = [
|
||||
"craft-window",
|
||||
"eframe",
|
||||
"egui",
|
||||
"futures-lite",
|
||||
"image",
|
||||
"log",
|
||||
"muda",
|
||||
@@ -6338,7 +6341,6 @@ dependencies = [
|
||||
"raw-window-handle",
|
||||
"rfd",
|
||||
"serde_json",
|
||||
"smithay-clipboard",
|
||||
"socket2",
|
||||
"tempfile",
|
||||
"vectorcraft-engine",
|
||||
@@ -6353,31 +6355,31 @@ dependencies = [
|
||||
"winit",
|
||||
"winresource",
|
||||
"winsafe",
|
||||
"wl-clipboard-rs",
|
||||
"x11rb",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-affinity"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-affinity",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"image",
|
||||
"proptest",
|
||||
"ruzstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-apischema"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-brush"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"serde",
|
||||
@@ -6389,7 +6391,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cad"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6405,7 +6407,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-cli"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"log",
|
||||
"objc2-core-foundation",
|
||||
@@ -6428,7 +6430,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-color"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"moxcms",
|
||||
@@ -6440,7 +6442,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-doc"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"hayro-ccitt",
|
||||
@@ -6459,7 +6461,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-effects"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6473,11 +6475,13 @@ dependencies = [
|
||||
"vectorcraft-plugins",
|
||||
"vectorcraft-text",
|
||||
"vectorcraft-three-d",
|
||||
"vectorcraft-trace",
|
||||
"wat",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-engine"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"cfb",
|
||||
"chrono",
|
||||
@@ -6498,6 +6502,7 @@ dependencies = [
|
||||
"roxmltree 0.21.2",
|
||||
"rustix 1.1.6",
|
||||
"ruzstd",
|
||||
"same-file",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa 0.47.0",
|
||||
@@ -6530,7 +6535,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-eps"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-pdf",
|
||||
"encoding_rs",
|
||||
@@ -6558,7 +6563,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-format"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-vectorcraft-format",
|
||||
"flate2",
|
||||
@@ -6574,7 +6579,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-geom"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"proptest",
|
||||
@@ -6586,17 +6591,17 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-js"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"getrandom 0.4.3",
|
||||
"proptest",
|
||||
"unicode-general-category",
|
||||
"unicode-properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-mcp"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"log",
|
||||
@@ -6615,7 +6620,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-metafile"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6629,7 +6634,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pathops"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"linesweeper",
|
||||
@@ -6641,7 +6646,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-pdf"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"chrono",
|
||||
@@ -6660,6 +6665,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"siphasher",
|
||||
"skrifa 0.47.0",
|
||||
"smallvec",
|
||||
"thiserror 2.0.21",
|
||||
@@ -6675,7 +6681,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-plugins"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-vectorcraft-format",
|
||||
"image",
|
||||
@@ -6694,7 +6700,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-render"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"gif 0.14.2",
|
||||
@@ -6724,15 +6730,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-scriptcheck"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"unicode-general-category",
|
||||
"unicode-properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-svg"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-docpath",
|
||||
"flate2",
|
||||
@@ -6759,7 +6765,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-testkit"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"image",
|
||||
@@ -6777,7 +6783,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-text"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"harfrust 0.13.3",
|
||||
"icu_segmenter",
|
||||
@@ -6798,7 +6804,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-three-d"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"vectorcraft-geom",
|
||||
"vectorcraft-pathops",
|
||||
@@ -6806,7 +6812,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-tools"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6823,7 +6829,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-trace"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6835,7 +6841,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-ui-egui"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"craft-keymap",
|
||||
@@ -6850,6 +6856,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"toml",
|
||||
"vectorcraft-apischema",
|
||||
"vectorcraft-brush",
|
||||
"vectorcraft-cad",
|
||||
"vectorcraft-color",
|
||||
@@ -6873,7 +6880,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-web"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-web-api",
|
||||
"eframe",
|
||||
@@ -7513,7 +7520,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8005,7 +8012,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
+6
-4
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
|
||||
default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.24.0"
|
||||
version = "0.24.1"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -14,16 +14,18 @@ repository = "https://github.com/storytold/vectorcraft"
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "bb8320f5fa5d20fa78a026d0de06fe4e2f08a099", features = ["serde"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6", features = ["serde"] }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
|
||||
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
|
||||
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
|
||||
@@ -237,7 +237,7 @@ and what's next; [`docs/target-app-parity.md`](docs/target-app-parity.md) the fu
|
||||
(92.5% of menu items do something), feature depth is ~75%, and we estimate ~65% ready for real work for a mainstream illustrator (~62% across all tracked features): everyday
|
||||
vector illustration is close to usable: drawing and path tools,
|
||||
Pathfinder and Shape Builder, paint, gradients, appearance and transparency, type with styles, threading and Hebrew/Arabic bidirectional layout, and
|
||||
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out and PSD/PSB in as their merged image, JPEG XL in, Print, Package).
|
||||
files (SVG, PDF and PDF-compatible `.ai` with PDF/X, legacy version 7 `.ai` keeping layers, groups and type, EPS, DXF, EMF/WMF, raster formats, PSD out, PSD/PSB opened with their layers and placed as their merged image, JPEG XL in, Print, Package).
|
||||
Affinity documents (`.af` from Affinity 3, `.afdesign`, `.afpub` and, by their content, `.afphoto` from Affinity 1 and 2) open
|
||||
and place natively: layers, groups, artboards and pages, curves and shapes, fills, gradients and strokes, clipping
|
||||
and masks, text with each paragraph's indents, spacing and leading, tables (as text frames and lines), master
|
||||
|
||||
+11
-2
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (Gujarati (`gu`): native review done, zero/one singular plurals; previously minor: Gujarati (`gu`): 4,235-row machine-assisted interface catalog, desktop font fallback; messages and native review pending; 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)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (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,6 +18,8 @@ gate: all six core workflows (path drawing and editing, paint and style, type, l
|
||||
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 retain their contributor review; 387 additions are drafts awaiting native proofreading. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face. Scores and estimates unchanged.
|
||||
|
||||
## Headline numbers
|
||||
|
||||
| | Value | Kind |
|
||||
@@ -96,7 +98,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
|
||||
| Simplified Chinese | `zh-hans` | partial (messages in English) | 85% |
|
||||
| Spanish | `es` | full | 100% |
|
||||
| Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner |
|
||||
| Gujarati | `gu` | catalog of 4,286 interface strings; machine-assisted, reviewed by a native speaker | menus and dialogs; status messages not yet |
|
||||
| Gujarati | `gu` | 4,673 catalog rows: original 4,286 contributor-reviewed; 387 additions are drafts | menus and dialogs; status/error messages partial; new rows need proofreading |
|
||||
| Arabic | `ar` | none (no right-to-left interface) | 0% |
|
||||
| French | `fr` | full | 100% |
|
||||
| Portuguese (Brazil) | `pt-br` | full | 100% |
|
||||
@@ -123,10 +125,14 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
## Progress log
|
||||
|
||||
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
|
||||
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-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-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).
|
||||
@@ -138,6 +144,9 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
|
||||
- 2026-10-31: Arrange Tools, a built-in add-on (Object › Plug-ins › Arrange Tools): Arrange in Grid lays the selected objects out in rows and columns, a row or a column with gaps, from the selection's top-left or centred on the artboard; Swap Objects swaps two objects' places (and, with Swap Objects and Sizes, their sizes); Replace with Top Object puts a copy of the topmost selected object in place of each of the others, kept, stretched or fitted in proportion; Set Size of Each gives every selected object an exact width and/or height about a reference point; Zoom to Selection fits the view to the selection. Each is one undo step with a previewed dialog where it has options. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-11: Window › Swatch Libraries › Gradients › Organic Fades: fifteen soft fades (ten linear, five radial) through three to five unevenly spaced stops with off-center midpoints, mixed with the Perceptual method, that thin out to transparent at the end of a linear one and at the edge of a radial one; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
|
||||
- 2026-11-13: Gradient panel › Method: Hue Clockwise and Hue Counterclockwise mix a linear, radial, conic or diamond gradient's colors around the hue wheel in one direction, so red to blue passes through magenta one way and through yellow and green the other (`paint.editGradient` `method`: `hue-clockwise`, `hue-counterclockwise`); SVG and PDF exports write such a gradient as an image.
|
||||
- 2026-11-11: Window › Swatch Libraries › Gradients › Holographic: seven foils (opaque linear gradients of six narrow pastel and pearl bands with off-center midpoints) and seven glows (radial gradients from a bright center out to a clear edge), mixed with the Perceptual method; they also list in the Swatches panel's library menu, `swatch.library.list` and the Gradient panel's Presets.
|
||||
- 2026-10-30: Gradient panel presets: a Presets menu applies one of the built-in gradient libraries' presets (grouped by theme) or a saved one to the gradient behind the active proxy, keeping its placement, as one undo step; the panel menu saves the current gradient as a preset, kept with the preferences, and deletes saved ones (`gradient.presets.list/apply/save/delete`).
|
||||
- 2026-10-23: Pathfinder › Trap: the Pathfinder panel's Trap… and Effect › Pathfinder › Trap… add a thin overprinting strip of the lighter colour inside the darker one where two solid colours meet, so misregistered plates leave no gap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html)), with Thickness, Height/Width, Tint Reduction, Traps with Process Color and Reverse Traps. Illustrator effects 49/50 (SVG Filters remains); Live vector effects hours 6–10 → 4–8; headline numbers unchanged.
|
||||
- 2026-10-23: OpenType SVG colour fonts draw as vector art: each glyph's SVG document is read by the SVG importer, in the text's colours where it asks for them, and draws, exports and outlines as COLR glyphs do; all colour font formats are now drawn.
|
||||
|
||||
@@ -238,14 +238,17 @@ fn main() -> ExitCode {
|
||||
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
|
||||
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
|
||||
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
|
||||
/// (`script.listInstalled`). `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they do there.
|
||||
/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
|
||||
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
|
||||
fn with_stores(mut h: Headless) -> Headless {
|
||||
prefs_dir::attach_scripts_dir(&mut h.session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut h.session);
|
||||
prefs_dir::attach_profile_store(&mut h.session);
|
||||
prefs_dir::attach_color_settings(&mut h.session);
|
||||
prefs_dir::attach_plugin_store(&mut h.session);
|
||||
prefs_dir::attach_pdf_preset_store(&mut h.session);
|
||||
prefs_dir::attach_custom_dictionary(&mut h.session);
|
||||
prefs_dir::attach_arrowheads(&mut h.session);
|
||||
h
|
||||
}
|
||||
|
||||
@@ -415,10 +418,18 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
// Save as Template writes every artboard, with the .ai options.
|
||||
("file.saveAsTemplate", json!({"path": output, "format": "ait", "outlineText": outline_text, "acknowledgeLoss": replace_lossy}))
|
||||
} else {
|
||||
// A conversion keeps hidden layers and objects, written hidden, where the format can (SVG,
|
||||
// PSD).
|
||||
let params = json!({"path": output, "artboard": artboard, "range": range, "outlineText": outline_text, "hiddenLayers": true, "acknowledgeLoss": replace_lossy});
|
||||
let params = json!({"path": output, "artboard": artboard, "range": range, "acknowledgeLoss": replace_lossy});
|
||||
let mut params = with_pixel_scale(params, &output, scale, ppi);
|
||||
// An option the format doesn't read comes back in the warnings, so each goes out only
|
||||
// when it was asked for: `outlineText` with --outline-text, and `hiddenLayers` to the
|
||||
// formats that have it (SVG, PSD), where a conversion keeps hidden layers and objects,
|
||||
// written hidden.
|
||||
if outline_text {
|
||||
params["outlineText"] = json!(true);
|
||||
}
|
||||
if vectorcraft_engine::cmd::fileio::writable_format(None, Some(&output)).is_ok_and(|f| f.options.iter().any(|o| o.name == "hiddenLayers")) {
|
||||
params["hiddenLayers"] = json!(true);
|
||||
}
|
||||
if let Some(decimals) = decimals {
|
||||
params["decimals"] = json!(decimals);
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
@@ -27,7 +25,12 @@ fn approval_param_needs_the_start_up_flag(key: &str, value: Value) {
|
||||
std::fs::write(&steps, json!([{"command": "plugin.install", "params": {"dataBase64": module, key: value}}]).to_string()).unwrap();
|
||||
let config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-{key}-{}", std::process::id())));
|
||||
let run = |extra: &[&str]| {
|
||||
Command::new(BIN).env("VECTORCRAFT_CONFIG_DIR", &config).args(["run", "--commands", steps.to_str().unwrap()]).args(extra).output().unwrap()
|
||||
Command::new(crate::bin())
|
||||
.env("VECTORCRAFT_CONFIG_DIR", &config)
|
||||
.args(["run", "--commands", steps.to_str().unwrap()])
|
||||
.args(extra)
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let out = run(&[]);
|
||||
assert!(!out.status.success());
|
||||
@@ -38,7 +41,7 @@ fn approval_param_needs_the_start_up_flag(key: &str, value: Value) {
|
||||
|
||||
let mcp_config = empty_dir(std::env::temp_dir().join(format!("vectorcraft-cli-test-mcp-{key}-{}", std::process::id())));
|
||||
let mcp_install = |extra: &[&str]| -> Value {
|
||||
let mut child = Command::new(BIN)
|
||||
let mut child = Command::new(crate::bin())
|
||||
.env("VECTORCRAFT_CONFIG_DIR", &mcp_config)
|
||||
.args(["mcp", "--headless"])
|
||||
.args(extra)
|
||||
@@ -77,22 +80,23 @@ fn plugin_grants_need_the_start_up_flag() {
|
||||
approval_param_needs_the_start_up_flag("grant", json!(["doc.read"]));
|
||||
approval_param_needs_the_start_up_flag("allowHeavy", json!(true));
|
||||
|
||||
let out = Command::new(BIN).args(["mcp", "--allow-plugin-grants", "--connect", "127.0.0.1:1"]).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["mcp", "--allow-plugin-grants", "--connect", "127.0.0.1:1"]).output().unwrap();
|
||||
assert!(!out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants applies to the headless server"));
|
||||
let root = std::env::temp_dir();
|
||||
for flag in ["--automation-read-root", "--automation-write-root"] {
|
||||
let out = Command::new(BIN).args(["mcp", "--allow-plugin-grants", flag, root.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap();
|
||||
let out =
|
||||
Command::new(crate::bin()).args(["mcp", "--allow-plugin-grants", flag, root.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap();
|
||||
assert!(!out.status.success(), "{flag}");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("--allow-plugin-grants can't be used with"), "{flag}");
|
||||
}
|
||||
let usage = Command::new(BIN).arg("help").output().unwrap();
|
||||
let usage = Command::new(crate::bin()).arg("help").output().unwrap();
|
||||
assert!(String::from_utf8_lossy(&usage.stdout).contains("--allow-plugin-grants lets plugin.install's grant and allowHeavy take effect"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_prints_catalogue() {
|
||||
let out = Command::new(BIN).arg("commands").output().unwrap();
|
||||
let out = Command::new(crate::bin()).arg("commands").output().unwrap();
|
||||
assert!(out.status.success());
|
||||
let v: Value = serde_json::from_slice(&out.stdout).unwrap();
|
||||
let ids: Vec<&str> = v.as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect();
|
||||
@@ -104,7 +108,7 @@ fn run_batch_exports() {
|
||||
let svg = tmp("batch.svg");
|
||||
let png = tmp("batch.png");
|
||||
let dc = tmp("batch.vectorcraft");
|
||||
let out = Command::new(BIN)
|
||||
let out = Command::new(crate::bin())
|
||||
.args(["run", "--cmd", "file.new", "--params", r#"{"width":200,"height":100}"#])
|
||||
.args(["--cmd", "shape.ellipse", "--params", r#"{"x":10,"y":10,"width":80,"height":60}"#])
|
||||
.args(["--cmd", "paint.setFill", "--params", r##"{"color":"#3366ff"}"##])
|
||||
@@ -121,7 +125,7 @@ fn run_batch_exports() {
|
||||
assert_eq!(u32::from_be_bytes(png_bytes[16..20].try_into().unwrap()), 400);
|
||||
|
||||
// Re-open the native file and inspect.
|
||||
let out = Command::new(BIN).args(["run", "--in", dc.to_str().unwrap(), "--cmd", "document.inspect"]).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["run", "--in", dc.to_str().unwrap(), "--cmd", "document.inspect"]).output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
let last: Value = serde_json::from_str(String::from_utf8(out.stdout).unwrap().lines().last().unwrap()).unwrap();
|
||||
assert_eq!(last["result"]["artboards"][0]["width"], 200.0);
|
||||
@@ -137,7 +141,7 @@ fn scale_sizes_raster_exports_only() {
|
||||
let svg = svg.to_str().unwrap();
|
||||
let (plain, scaled, png) = (tmp("plain.dxf"), tmp("scaled.dxf"), tmp("scaled.png"));
|
||||
let ok = |args: &[&str]| {
|
||||
let out = Command::new(BIN).args(args).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(args).output().unwrap();
|
||||
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
};
|
||||
ok(&["convert", svg, plain.to_str().unwrap()]);
|
||||
@@ -151,11 +155,11 @@ fn scale_sizes_raster_exports_only() {
|
||||
|
||||
#[test]
|
||||
fn run_reports_errors() {
|
||||
let out = Command::new(BIN).args(["run", "--cmd", "nope.nothing"]).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["run", "--cmd", "nope.nothing"]).output().unwrap();
|
||||
assert!(!out.status.success());
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).to_string();
|
||||
assert!(stderr.contains("step 0 (nope.nothing)"), "{stderr}");
|
||||
let out = Command::new(BIN).args(["run", "--params", "{}"]).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["run", "--params", "{}"]).output().unwrap();
|
||||
assert!(!out.status.success());
|
||||
}
|
||||
|
||||
@@ -184,7 +188,7 @@ fn run_reads_steps_from_a_commands_file() {
|
||||
{"id": "object.setProps", "params": {"id": "$2.ids.0", "name": "barcode"}},
|
||||
]);
|
||||
std::fs::write(&steps, serde_json::to_string_pretty(&file).unwrap()).unwrap();
|
||||
let out = Command::new(BIN)
|
||||
let out = Command::new(crate::bin())
|
||||
.args(["run", "--cmd", "file.new", "--params", r#"{"width":200,"height":100}"#, "--commands", steps.to_str().unwrap()])
|
||||
.args(["--cmd", "document.node", "--params", r#"{"id":"$2.ids.0"}"#, "--export", svg.to_str().unwrap()])
|
||||
.output()
|
||||
@@ -204,7 +208,7 @@ fn run_reads_steps_from_a_commands_file() {
|
||||
#[test]
|
||||
fn run_reads_json_lines_from_standard_input() {
|
||||
let svg = tmp("stdin.svg");
|
||||
let mut child = Command::new(BIN)
|
||||
let mut child = Command::new(crate::bin())
|
||||
.args(["run", "--commands", "-", "--export", svg.to_str().unwrap()])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
@@ -227,7 +231,7 @@ fn run_reads_json_lines_from_standard_input() {
|
||||
#[test]
|
||||
fn run_refuses_malformed_commands_naming_the_step() {
|
||||
let fails = |args: &[&str]| {
|
||||
let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap();
|
||||
assert!(!out.status.success(), "{args:?}");
|
||||
(String::from_utf8_lossy(&out.stderr).to_string(), json_lines(&out.stdout).len())
|
||||
};
|
||||
@@ -275,11 +279,11 @@ fn run_refuses_malformed_commands_naming_the_step() {
|
||||
/// `--help` and `-h` right after a subcommand print the usage that `vectorcraft-cli help` prints.
|
||||
#[test]
|
||||
fn help_after_a_subcommand_prints_the_usage() {
|
||||
let usage = Command::new(BIN).arg("help").output().unwrap();
|
||||
let usage = Command::new(crate::bin()).arg("help").output().unwrap();
|
||||
assert!(usage.status.success() && String::from_utf8_lossy(&usage.stdout).contains("USAGE:"));
|
||||
for sub in ["mcp", "run", "commands", "convert", "info", "bench", "perf"] {
|
||||
for flag in ["--help", "-h"] {
|
||||
let out = Command::new(BIN).args([sub, flag]).stdin(Stdio::null()).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args([sub, flag]).stdin(Stdio::null()).output().unwrap();
|
||||
assert!(out.status.success(), "{sub} {flag}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(out.stdout == usage.stdout, "{sub} {flag}: {}", String::from_utf8_lossy(&out.stdout));
|
||||
}
|
||||
@@ -290,7 +294,7 @@ fn help_after_a_subcommand_prints_the_usage() {
|
||||
/// with them.
|
||||
#[test]
|
||||
fn help_later_in_the_line_prints_the_usage() {
|
||||
let usage = Command::new(BIN).arg("help").output().unwrap();
|
||||
let usage = Command::new(crate::bin()).arg("help").output().unwrap();
|
||||
let mut wrong = vec![];
|
||||
for args in [
|
||||
&["mcp", "--headless", "--help"][..],
|
||||
@@ -311,7 +315,7 @@ fn help_later_in_the_line_prints_the_usage() {
|
||||
&["perf", "--paths", "many", "-h"],
|
||||
&["convert", "--decimals", "many", "--help"],
|
||||
] {
|
||||
let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap();
|
||||
if !out.status.success() || out.stdout != usage.stdout {
|
||||
wrong.push(format!("{args:?}: {}{}", String::from_utf8_lossy(&out.stderr), String::from_utf8_lossy(&out.stdout)));
|
||||
}
|
||||
@@ -322,17 +326,18 @@ fn help_later_in_the_line_prints_the_usage() {
|
||||
/// Further along the line, `-h` is the value of the option before it.
|
||||
#[test]
|
||||
fn help_as_an_option_value_goes_to_the_option() {
|
||||
let out = Command::new(BIN).args(["run", "--cmd", "-h"]).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["run", "--cmd", "-h"]).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success() && err.contains("vectorcraft-cli: step 0 (-h):") && out.stdout.is_empty(), "{err}");
|
||||
let out = Command::new(BIN).args(["convert", "in.svg", "--range", "-h"]).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["convert", "in.svg", "--range", "-h"]).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success() && err.contains("convert needs IN and OUT") && out.stdout.is_empty(), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_headless_over_stdio() {
|
||||
let mut child = Command::new(BIN).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
|
||||
let mut child =
|
||||
Command::new(crate::bin()).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
|
||||
{
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
for m in [
|
||||
@@ -359,13 +364,13 @@ fn mcp_headless_over_stdio() {
|
||||
/// plug-ins.
|
||||
#[test]
|
||||
fn safe_mode_mcp_does_not_connect_to_a_running_app() {
|
||||
let out = Command::new(BIN).args(["--safe-mode", "mcp", "--connect", "127.0.0.1:9"]).env("VECTORCRAFT_NO_PREFS", "1").output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["--safe-mode", "mcp", "--connect", "127.0.0.1:9"]).env("VECTORCRAFT_NO_PREFS", "1").output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success() && err.contains("--safe-mode runs a headless session"), "{err}");
|
||||
// Something listening on the default address, as a running app does; a running app or another
|
||||
// program already holding it serves as well.
|
||||
let _app = std::net::TcpListener::bind(vectorcraft_mcp::DEFAULT_ADDR);
|
||||
let out = Command::new(BIN).args(["--safe-mode", "mcp"]).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["--safe-mode", "mcp"]).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success() && err.contains("MCP server on stdio (headless)"), "{err}");
|
||||
}
|
||||
@@ -402,7 +407,7 @@ fn mcp_automation_roots_take_several_folders() {
|
||||
}
|
||||
let dir = |d: &str| base.join(d).to_string_lossy().into_owned();
|
||||
let file = |d: &str, f: &str| base.join(d).join(f).to_string_lossy().into_owned();
|
||||
let mut child = Command::new(BIN)
|
||||
let mut child = Command::new(crate::bin())
|
||||
.args(["mcp", "--automation-read-root", &dir("in"), &format!("--automation-read-root={}", dir("in2"))])
|
||||
.args(["--automation-write-root", &dir("out"), "--automation-write-root", &dir("out2")])
|
||||
.stdin(Stdio::piped())
|
||||
@@ -457,7 +462,7 @@ fn automation_roots(base: &std::path::Path) {
|
||||
}
|
||||
let dir = |d: &str| base.join(d).to_string_lossy().into_owned();
|
||||
let fails = |args: &[&str], why: &str| {
|
||||
let out = Command::new(BIN).args(args).stdin(Stdio::null()).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(args).stdin(Stdio::null()).output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!out.status.success() && err.contains(why), "{args:?}: {err}");
|
||||
};
|
||||
@@ -469,7 +474,7 @@ fn automation_roots(base: &std::path::Path) {
|
||||
"a running app enforces its own roots: start it with `vectorcraft --control <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())
|
||||
@@ -530,7 +535,7 @@ fn automation_roots(base: &std::path::Path) {
|
||||
fn mcp_protocol_over_stdio() {
|
||||
use std::io::{BufRead, BufReader};
|
||||
let mut child =
|
||||
Command::new(BIN).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
Command::new(crate::bin()).args(["mcp", "--headless"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
let mut lines = BufReader::new(child.stdout.take().unwrap()).lines();
|
||||
let mut notes = vec![];
|
||||
@@ -711,7 +716,7 @@ fn run_command(id: u64, command: &str, params: Value) -> Value {
|
||||
#[test]
|
||||
fn closed_stdout_ends_quietly() {
|
||||
use std::io::Read;
|
||||
let mut child = Command::new(BIN).arg("commands").stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
let mut child = Command::new(crate::bin()).arg("commands").stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
let mut first = [0u8; 16];
|
||||
child.stdout.as_mut().unwrap().read_exact(&mut first).unwrap();
|
||||
drop(child.stdout.take());
|
||||
@@ -728,13 +733,13 @@ fn run_with_a_closed_stdout_ends_quietly_and_finishes_the_batch() {
|
||||
let _ = std::fs::remove_file(&svg);
|
||||
let rect = r#"{"x":1,"y":1,"width":5,"height":5}"#;
|
||||
let args = ["run", "--cmd", "document.json", "--cmd", "shape.rectangle", "--params", rect, "--export", svg.to_str().unwrap()];
|
||||
let mut child = Command::new(BIN).args(args).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
let mut child = Command::new(crate::bin()).args(args).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
drop(child.stdout.take());
|
||||
let out = child.wait_with_output().unwrap();
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(out.status.success() && err.is_empty(), "{:?}: {err}", out.status);
|
||||
assert!(svg.is_file(), "the export after the closed reader still ran");
|
||||
let out = Command::new(BIN).args(["run", "--cmd", "not-a-command"]).stdout(Stdio::null()).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(["run", "--cmd", "not-a-command"]).stdout(Stdio::null()).output().unwrap();
|
||||
assert!(!out.status.success());
|
||||
}
|
||||
|
||||
@@ -749,7 +754,7 @@ fn config_dir(name: &str) -> std::path::PathBuf {
|
||||
/// One `vectorcraft-cli run` with `steps` ((command, params)) against the settings folder `config`;
|
||||
/// the result of each step.
|
||||
fn run_in(config: &std::path::Path, steps: &[(&str, Value)]) -> Vec<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", ¶ms.to_string()]);
|
||||
@@ -820,7 +825,7 @@ fn saved_pdf_presets_and_loaded_profiles_survive_a_restart() {
|
||||
#[test]
|
||||
fn runs_without_preferences_remember_nothing() {
|
||||
let config = config_dir("noprefs");
|
||||
let out = Command::new(BIN)
|
||||
let out = Command::new(crate::bin())
|
||||
.args(["run", "--cmd", "pdf.preset.save", "--params", r#"{"name":"Press"}"#])
|
||||
.env("VECTORCRAFT_CONFIG_DIR", &config)
|
||||
.env("VECTORCRAFT_NO_PREFS", "1")
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -130,7 +128,7 @@ fn raster_exports_use_document_resolution_unless_overridden() {
|
||||
fn raster_export_rejects_invalid_ppi() {
|
||||
for ppi in ["0", "-150", "NaN", "inf", "high"] {
|
||||
for args in [vec!["run", "--export", "unused.png", "--ppi", ppi], vec!["convert", "unused.svg", "unused.png", "--ppi", ppi]] {
|
||||
let out = Command::new(BIN).args(&args).output().unwrap();
|
||||
let out = Command::new(crate::bin()).args(&args).output().unwrap();
|
||||
assert!(!out.status.success(), "{args:?}");
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("positive finite number"), "{args:?}: {out:?}");
|
||||
}
|
||||
@@ -179,6 +177,27 @@ fn convert_reports_import_warnings() {
|
||||
assert!(w.iter().any(|w| w.as_str().unwrap().contains("nowhere-to-be-found.png")), "{out}");
|
||||
}
|
||||
|
||||
/// A conversion sends each format only the options it reads, so its warnings name an unused
|
||||
/// option only when the command line gave one: `--outline-text` for a format without it.
|
||||
#[test]
|
||||
fn convert_warns_about_an_unused_option_only_when_one_was_given() {
|
||||
let svg = tmp("unused-option.svg");
|
||||
std::fs::write(&svg, r#"<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.
|
||||
@@ -228,7 +247,7 @@ fn convert_writes_legacy_ai_with_its_options() {
|
||||
assert!(r["warnings"].to_string().contains("hidden objects are left out"), "{r}");
|
||||
assert!(std::fs::read(&one).unwrap().starts_with(b"%!PS-Adobe-3.0"));
|
||||
// A value the engine doesn't take is an error.
|
||||
let bad = Command::new(BIN).args(["convert", &src, &tmp("bad.ai"), "--ai-version", "7", "--hidden-objects", "behind"]).output().unwrap();
|
||||
let bad = Command::new(crate::bin()).args(["convert", &src, &tmp("bad.ai"), "--ai-version", "7", "--hidden-objects", "behind"]).output().unwrap();
|
||||
assert!(!bad.status.success());
|
||||
assert!(String::from_utf8_lossy(&bad.stderr).contains("hiddenObjects"), "{}", String::from_utf8_lossy(&bad.stderr));
|
||||
}
|
||||
@@ -253,7 +272,7 @@ fn convert_and_run_write_ait_templates() {
|
||||
assert_eq!(info(ait)["artboards"].as_array().unwrap().len(), 2, "{ait}");
|
||||
}
|
||||
// A template holds every artboard: one can't be picked.
|
||||
let one = Command::new(BIN).args(["convert", &pdf, &tmp("one.ait"), "--artboard", "0"]).output().unwrap();
|
||||
let one = Command::new(crate::bin()).args(["convert", &pdf, &tmp("one.ait"), "--artboard", "0"]).output().unwrap();
|
||||
assert!(!one.status.success());
|
||||
assert!(String::from_utf8_lossy(&one.stderr).contains("every artboard"), "{}", String::from_utf8_lossy(&one.stderr));
|
||||
}
|
||||
@@ -6,3 +6,11 @@ mod cli;
|
||||
mod fileio;
|
||||
mod mcp_e2e;
|
||||
mod script;
|
||||
|
||||
/// Nextest relocates archived binaries; Cargo's compile-time path still names the build runner.
|
||||
fn bin() -> std::path::PathBuf {
|
||||
std::env::var_os("NEXTEST_BIN_EXE_vectorcraft_cli")
|
||||
.or_else(|| std::env::var_os("CARGO_BIN_EXE_vectorcraft-cli"))
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft-cli").into())
|
||||
}
|
||||
@@ -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())
|
||||
|
||||
@@ -2,11 +2,9 @@ use std::process::Command;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft-cli");
|
||||
|
||||
/// `run` with `script.run` after `file.new`, with `params`.
|
||||
fn run_script(params: &Value) -> std::process::Output {
|
||||
Command::new(BIN).args(["run", "--cmd", "file.new", "--cmd", "script.run", "--params", ¶ms.to_string()]).output().unwrap()
|
||||
Command::new(crate::bin()).args(["run", "--cmd", "file.new", "--cmd", "script.run", "--params", ¶ms.to_string()]).output().unwrap()
|
||||
}
|
||||
|
||||
/// `run` runs a script headless: the reply holds the report, with what the script logged and the
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -17,7 +17,7 @@ use vectorcraft_ui_egui::i18n;
|
||||
use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox};
|
||||
use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
|
||||
use vectorcraft_ui_egui::stylus::StylusFeed;
|
||||
use vectorcraft_ui_egui::{Services, VectorcraftApp};
|
||||
use vectorcraft_ui_egui::{PickedInbox, Services, VectorcraftApp};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
use crate::locks::WebLocks;
|
||||
@@ -25,6 +25,18 @@ use crate::pencil::SharedPointers;
|
||||
|
||||
pub(crate) type Inbox = Arc<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)>>>;
|
||||
@@ -48,7 +60,7 @@ const MAX_RESTARTS: u32 = 3;
|
||||
#[derive(Clone)]
|
||||
struct Host {
|
||||
runner: eframe::WebRunner,
|
||||
inbox: Inbox,
|
||||
inbox: OpenInboxes,
|
||||
place_inbox: PlaceInbox,
|
||||
script_inbox: ScriptInbox,
|
||||
drag: DragPos,
|
||||
@@ -77,7 +89,7 @@ pub fn start() {
|
||||
crate::fonts::load_startup_fonts().await;
|
||||
let host = Host {
|
||||
runner: eframe::WebRunner::new(),
|
||||
inbox: Arc::default(),
|
||||
inbox: OpenInboxes::default(),
|
||||
place_inbox: Arc::default(),
|
||||
script_inbox: Arc::default(),
|
||||
drag: DragPos::default(),
|
||||
@@ -132,13 +144,13 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
|
||||
// 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));
|
||||
}
|
||||
@@ -409,7 +421,7 @@ impl eframe::App for WebShell {
|
||||
for f in dropped {
|
||||
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
|
||||
let target = app.drop_target(&name, pos, shift);
|
||||
let (inbox, place_inbox, repaint) = (self.host.inbox.clone(), self.host.place_inbox.clone(), ctx.clone());
|
||||
let (inbox, place_inbox, repaint) = (self.host.inbox.dropped.clone(), self.host.place_inbox.clone(), ctx.clone());
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match f.bytes_async().await {
|
||||
Ok(bytes) => {
|
||||
@@ -432,14 +444,14 @@ impl eframe::App for WebShell {
|
||||
}
|
||||
|
||||
fn services(
|
||||
inbox: Inbox,
|
||||
inbox: OpenInboxes,
|
||||
place_inbox: PlaceInbox,
|
||||
script_inbox: ScriptInbox,
|
||||
ctx: egui::Context,
|
||||
locks: Option<WebLocks>,
|
||||
stylus: StylusFeed,
|
||||
) -> Services {
|
||||
let open_inbox = inbox.clone();
|
||||
let open_inbox = inbox.picked.clone();
|
||||
let picked = place_inbox.clone();
|
||||
let place_ctx = ctx.clone();
|
||||
let screen_color = eye_dropper(ctx.clone());
|
||||
@@ -488,11 +500,12 @@ fn services(
|
||||
let dialog = fileio::open_filters().fold(rfd::AsyncFileDialog::new(), |d, (name, exts)| {
|
||||
d.add_filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts)
|
||||
});
|
||||
let Some(file) = dialog.pick_file().await else {
|
||||
return;
|
||||
// A canceled pick answers `None`.
|
||||
let answer = match dialog.pick_file().await {
|
||||
Some(file) => Some((file.file_name(), file.read().await)),
|
||||
None => None,
|
||||
};
|
||||
let bytes = file.read().await;
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((file.file_name(), bytes));
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push(answer);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
})),
|
||||
@@ -500,7 +513,9 @@ fn services(
|
||||
screen_color,
|
||||
// A download that couldn't be started fails the save or export it is for (#1693).
|
||||
download: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes).inspect_err(|e| log::error!("download of {name} failed: {e}")))),
|
||||
inbox: Some(inbox),
|
||||
inbox: Some(inbox.dropped),
|
||||
picked_inbox: Some(inbox.picked),
|
||||
page_inbox: Some(inbox.page),
|
||||
recovery_store: Some(Arc::new(BrowserStore { locks })),
|
||||
// File → Print: the browser's print dialog.
|
||||
print: Some(Box::new(BrowserPrint)),
|
||||
|
||||
@@ -58,7 +58,10 @@ pollster = "1"
|
||||
# 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.
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
|
||||
# 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 }
|
||||
|
||||
@@ -93,15 +96,15 @@ winit = { version = "0.30", default-features = false, features = ["wayland-csd-a
|
||||
# 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. XKB reads Caps Lock's locked modifier state (src/caps_lock.rs).
|
||||
x11rb = { version = "0.13", default-features = false, features = ["xinput", "xkb"] }
|
||||
# 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"
|
||||
# Copy and Paste of text through the compositor's core data-device protocol on the window's
|
||||
# connection (src/clipboard.rs), where arboard has neither data-control (GNOME) nor X11 (a Flatpak
|
||||
# on a Wayland session). MIT, already in the build through egui-winit.
|
||||
smithay-clipboard = "0.7"
|
||||
wayland-protocols = { version = "0.32", features = ["client", "unstable"] }
|
||||
# The save dialog's parent window on Wayland (src/portal_save.rs): an xdg-foreign handle (in
|
||||
# wayland-protocols' `unstable` set) made on the window's own connection. MIT, already in the build
|
||||
@@ -113,6 +116,14 @@ wayland-backend = { version = "0.3", features = ["client_system"] }
|
||||
# exactly: review the diff before bumping.
|
||||
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))'.dependencies]
|
||||
zbus = "=5.19.0"
|
||||
# Waits for a portal answer (the save dialog's and the screen color sampler's) and for the portal
|
||||
# leaving the bus at the same time (src/portal_request.rs). Apache-2.0 OR MIT, already in the build
|
||||
# through zbus.
|
||||
futures-lite = "2"
|
||||
# Tells whether arboard reads through the compositor's data-control protocol or through X11, the
|
||||
# same check arboard makes (src/clipboard.rs). MIT OR Apache-2.0, already in the build through
|
||||
# arboard.
|
||||
wl-clipboard-rs = "0.9"
|
||||
|
||||
[build-dependencies]
|
||||
# Icon + VERSIONINFO for vectorcraft.exe; build.rs only uses it when targeting Windows.
|
||||
|
||||
@@ -9,6 +9,7 @@ use super::{App, VectorcraftApp, file_access, window};
|
||||
#[cfg(target_os = "macos")]
|
||||
use super::{mac_menu, mac_window, open_documents};
|
||||
use vectorcraft_ui_egui::dialogs::safe_mode;
|
||||
use vectorcraft_ui_egui::hang_beacon::{self, BEACON, FrameTime, Stage};
|
||||
|
||||
/// The parts of [`App::raw_input_hook`] that every window needs, for the OS windows of floating
|
||||
/// panels: a click or Escape that closes the macOS menu bar's open menu, and the pen barrel
|
||||
@@ -34,12 +35,16 @@ impl eframe::App for App {
|
||||
// control channel asks for, and the frames carrying input it injected, to the automation roots
|
||||
// (`VectorcraftApp::with_automation_roots`), which are in force elsewhere in the process.
|
||||
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
|
||||
let _timed = BEACON.enter_timed(Stage::Logic);
|
||||
file_access::unconfined(|| self.logic_frame(ctx, frame));
|
||||
self.app.finish_ime_logic(ctx);
|
||||
BEACON.enter(Stage::Idle);
|
||||
}
|
||||
/// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the
|
||||
/// app's raw-input hook while the keyboard user is unconfined.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
let _timed = BEACON.enter_timed(Stage::Input);
|
||||
self.frame_start = Some(std::time::Instant::now());
|
||||
// winit gives the window its caption back when it changes the window's flags (maximize,
|
||||
// restore, …): take it off again before the frame is laid out (#1758).
|
||||
if let Some(window_frame) = self.window_frame.as_mut() {
|
||||
@@ -60,9 +65,10 @@ impl eframe::App for App {
|
||||
// that no mouse button is down.
|
||||
#[cfg(target_os = "macos")]
|
||||
self.app.release_lost_buttons(ctx, raw, objc2_app_kit::NSEvent::pressedMouseButtons() != 0);
|
||||
BEACON.enter(Stage::Idle);
|
||||
}
|
||||
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
let _timed = BEACON.enter_timed(Stage::Interface);
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let bar = vectorcraft_ui_egui::chrome::APP_BAR_HEIGHT;
|
||||
@@ -89,19 +95,80 @@ impl eframe::App for App {
|
||||
if !self.app.file_dialog_open() && self.app.take_ime_discard() {
|
||||
discard_marked_text();
|
||||
}
|
||||
self.end_frame(ui.ctx(), frame);
|
||||
}
|
||||
fn on_exit(&mut self) {
|
||||
// The window is closing: saving and teardown are not timed for the hang report, and a report
|
||||
// of a stall the interface came back from is removed.
|
||||
let log_dir = super::prefs::log_dir().filter(|_| super::prefs::prefs_enabled());
|
||||
super::hang_watch::closing(log_dir.as_deref(), &super::hang_watch::CLOSING, &BEACON);
|
||||
file_access::unconfined(|| save_prefs(&self.app));
|
||||
// A ready update installs once the process has exited. The macOS exit below skips
|
||||
// dropping the app, so the helper is started here.
|
||||
self.app.start_pending_update();
|
||||
#[cfg(target_os = "macos")]
|
||||
super::mac_cursor::release();
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
hide_before_teardown(self.winit_window.as_deref());
|
||||
end_before_teardown(self.frames);
|
||||
}
|
||||
}
|
||||
|
||||
/// The main window as [`hide_before_teardown`] sees it.
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
pub(crate) trait QuittingWindow {
|
||||
fn hide(&self);
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
impl QuittingWindow for winit::window::Window {
|
||||
fn hide(&self) {
|
||||
self.set_visible(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// On Linux and the BSDs, hide the main window before eframe drops the app. Dropping the app waits
|
||||
/// up to [`vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT`] for the clipboard handles to let go, and
|
||||
/// the window would stay on screen for that time. The window is hidden, not closed: the Wayland
|
||||
/// clipboard reads text on the window's connection. winit hides X11 windows (XWayland included) and
|
||||
/// cannot hide a Wayland window.
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
pub(crate) fn hide_before_teardown<W: QuittingWindow + ?Sized>(window: Option<&W>) {
|
||||
if let Some(window) = window {
|
||||
window.hide();
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// The frame's times for the hang report, and its last stage ([`hang_beacon::after_frame`]): a
|
||||
/// focused, shown window whose windows had input waits for the renderer and the next frame,
|
||||
/// which the input asks for at once; any other frame leaves the interface thread idle
|
||||
/// (`hang_watch`).
|
||||
fn end_frame(&mut self, ctx: &egui::Context, frame: &eframe::Frame) {
|
||||
// A pass egui discards and runs again is not the frame's end: the pass after it is.
|
||||
if ctx.will_discard() {
|
||||
return;
|
||||
}
|
||||
if let Some(start) = self.frame_start.take() {
|
||||
let work_ms = start.elapsed().as_secs_f32() * 1000.0;
|
||||
let previous_total_ms = frame.info().cpu_usage.map(|s| s * 1000.0);
|
||||
BEACON.frame(FrameTime { work_ms, previous_total_ms }, self.app.session.documents().len());
|
||||
}
|
||||
// Hide on macOS hides the window at once, before the window reports losing focus.
|
||||
let main_shown = ctx.input(|i| i.focused && i.viewport().minimized != Some(true))
|
||||
&& self.winit_window.as_ref().is_none_or(|w| w.is_visible() != Some(false));
|
||||
// A floating panel or document window with the focus counts as well, with the commands it
|
||||
// was sent after its pass, and those its pass sent (`hang_beacon::watch_input`).
|
||||
let shown = ctx.input(|i| hang_beacon::shown_window(main_shown, &i.raw.viewports));
|
||||
let handed_off = BEACON.take_handed_off();
|
||||
let input = BEACON.take_input();
|
||||
let stage = match shown {
|
||||
Some(id) => ctx.viewport_for(id, |vp| hang_beacon::after_frame(input && !handed_off.contains(&id), true, &vp.commands)),
|
||||
None => hang_beacon::after_frame(input, false, &[]),
|
||||
};
|
||||
BEACON.enter(stage);
|
||||
}
|
||||
|
||||
fn logic_frame(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
#[cfg(target_os = "macos")]
|
||||
if self.winit_window.as_ref().is_some_and(|w| !w.has_focus() || w.is_visible() == Some(false) || w.is_minimized() == Some(true)) {
|
||||
@@ -152,6 +219,9 @@ impl App {
|
||||
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 {
|
||||
|
||||
+1926
-171
File diff suppressed because it is too large.
Load diff
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
use super::portal_save;
|
||||
#[cfg(target_os = "linux")]
|
||||
use super::tablet;
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
use super::windows_stylus;
|
||||
use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing};
|
||||
#[cfg(target_os = "linux")]
|
||||
use super::{linux_screen_color, tablet};
|
||||
#[cfg(target_os = "macos")]
|
||||
use super::{mac_save_format, mac_screen_color, mac_tablet};
|
||||
|
||||
@@ -120,7 +120,6 @@ fn make_folder(request: &PickRequest) {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[cfg_attr(windows, allow(unused_variables))]
|
||||
fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) -> Vec<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())
|
||||
@@ -139,7 +138,30 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent)
|
||||
/// Show the dialog for `request` over `parent` now → the paths picked.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn pick_now(request: PickRequest, parent: &Parent) -> Vec<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
|
||||
@@ -239,6 +261,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
|
||||
std::thread::Builder::new()
|
||||
.name("file-dialog".into())
|
||||
.spawn(move || {
|
||||
make_folder(&request);
|
||||
// The app gone meanwhile has no use for the answer.
|
||||
let _ = tx.send(show_dialog(dialog, &request, &parent));
|
||||
ui.request_repaint();
|
||||
@@ -331,8 +354,10 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
.is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
|
||||
let (clip, clip_probe) = (parent.clone(), parent.clone());
|
||||
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
let sampled_ui = ui.clone();
|
||||
#[cfg(target_os = "linux")]
|
||||
let sampled_parent = p1.clone();
|
||||
Services {
|
||||
pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())),
|
||||
pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))),
|
||||
@@ -355,18 +380,22 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
// Load Actions… refuses a file over its size limit without reading all of it.
|
||||
read_head: Some(Box::new(read_file_head)),
|
||||
write: Some(Box::new(write_file)),
|
||||
exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())),
|
||||
exists: Some(std::sync::Arc::new(|p: &str| std::path::Path::new(p).exists())),
|
||||
// Background Save and Export write from a worker thread.
|
||||
write_shared: Some(std::sync::Arc::new(write_file)),
|
||||
save_write: Some(std::sync::Arc::new(fileio::write_save_file)),
|
||||
save_stream: Some(std::sync::Arc::new(fileio::write_save_file_with)),
|
||||
// Native saves stream into the file as they are encoded.
|
||||
stream_shared: Some(std::sync::Arc::new(|p: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| {
|
||||
fileio::write_file_with(p, fill).map_err(|e| e.to_string())
|
||||
})),
|
||||
// Every format Copy offers and Paste reads (menu-bar Paste never sees egui's Paste event).
|
||||
system_clipboard: Some(clipboard::system_clipboard(clip)),
|
||||
// Its calls are marked for the hang report (`hang_watch`).
|
||||
system_clipboard: Some(Box::new(vectorcraft_ui_egui::hang_beacon::Marked(clipboard::system_clipboard(clip)))),
|
||||
// Linux checks whether Paste has something to take on a background thread: an X11 clipboard
|
||||
// owner that never answers holds a read for up to 4 s. Windows only asks which formats the
|
||||
// clipboard holds and macOS asks the pasteboard server, so they check in line.
|
||||
// owner that never answers holds a text read for up to 4 s for each format it tries, and
|
||||
// quitting waits up to `CLIPBOARD_PROBE_STOP_WAIT` for that thread. Windows only asks which
|
||||
// formats the clipboard holds and macOS asks the pasteboard server, so they check in line.
|
||||
// The probe's handle is made on its own thread, from the window (`Send`), not its raw display.
|
||||
clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(move || clipboard::system_clipboard(clip_probe)) as ClipboardProbeFactory),
|
||||
// Help → Discord / website / GitHub, the Discord button, About and Home links.
|
||||
@@ -382,6 +411,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
// Sample Color from Screen: the system's color sampler.
|
||||
#[cfg(target_os = "macos")]
|
||||
screen_color: Some(mac_screen_color::sampler(sampled_ui)),
|
||||
#[cfg(target_os = "linux")]
|
||||
screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
..Default::default()
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,6 @@ trait Backend {
|
||||
fn suspend(&mut self, window: &Self::Window);
|
||||
fn restore(&mut self, window: &Self::Window);
|
||||
fn build(&mut self, request: &Request) -> Option<Self::Cursor>;
|
||||
fn current(&self) -> Option<Self::Cursor>;
|
||||
fn set(&mut self, cursor: &Self::Cursor);
|
||||
}
|
||||
|
||||
@@ -73,9 +72,10 @@ impl<B: Backend> State<B> {
|
||||
&& *key == request.key
|
||||
&& *owned == window
|
||||
{
|
||||
if self.backend.current().as_ref() != Some(cursor) {
|
||||
self.backend.set(cursor);
|
||||
}
|
||||
// AppKit can show the system arrow when the pointer moves while
|
||||
// `NSCursor.currentCursor` (the app's last set cursor) still reads as ours, so a
|
||||
// comparison would keep the arrow. Setting the cursor again costs nothing.
|
||||
self.backend.set(cursor);
|
||||
return;
|
||||
}
|
||||
self.release();
|
||||
@@ -135,9 +135,6 @@ impl Backend for AppKit {
|
||||
fn build(&mut self, request: &Request) -> Option<Self::Cursor> {
|
||||
build(&request.bitmap)
|
||||
}
|
||||
fn current(&self) -> Option<Self::Cursor> {
|
||||
Some(NSCursor::currentCursor())
|
||||
}
|
||||
fn set(&mut self, cursor: &Self::Cursor) {
|
||||
cursor.set();
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ use std::cell::Cell;
|
||||
struct Fake {
|
||||
window: Option<u8>,
|
||||
suspended: Vec<u8>,
|
||||
current: Option<Key>,
|
||||
sets: usize,
|
||||
builds: usize,
|
||||
restores: Vec<u8>,
|
||||
@@ -27,17 +26,12 @@ impl Backend for Fake {
|
||||
fn restore(&mut self, w: &u8) {
|
||||
self.suspended.retain(|v| v != w);
|
||||
self.restores.push(*w);
|
||||
self.current = None;
|
||||
}
|
||||
fn build(&mut self, r: &Request) -> Option<Key> {
|
||||
self.builds += 1;
|
||||
(!self.fail).then_some(r.key)
|
||||
}
|
||||
fn current(&self) -> Option<Key> {
|
||||
self.current
|
||||
}
|
||||
fn set(&mut self, cursor: &Key) {
|
||||
self.current = Some(*cursor);
|
||||
fn set(&mut self, _: &Key) {
|
||||
self.sets += 1;
|
||||
}
|
||||
}
|
||||
@@ -66,19 +60,16 @@ fn deliver(state: &mut State<Fake>, request: Option<Request>) {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_cursor_ownership_deduplicates_reasserts_and_restores() {
|
||||
fn mac_cursor_ownership_reasserts_every_pass_and_restores() {
|
||||
let req = request(1.0);
|
||||
let mut state = fake_state();
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
assert_eq!(state.backend.suspended, [1]);
|
||||
assert_eq!((state.backend.builds, state.backend.sets), (1, 1));
|
||||
// The pointer moves and AppKit shows the system arrow, but the app's current cursor
|
||||
// still reads as ours. The next pass sets it again without rebuilding or re-suspending.
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
assert_eq!(state.backend.sets, 1);
|
||||
// Simulate a platform fallback replacing the cursor after finalization. The next pass
|
||||
// reasserts; this proves the protocol, not AppKit timing or absence of transient flicker.
|
||||
state.backend.current = None;
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
assert_eq!(state.backend.sets, 2);
|
||||
assert_eq!((state.backend.builds, state.backend.sets, state.backend.suspended.len()), (1, 2, 1));
|
||||
deliver(&mut state, None);
|
||||
assert_eq!(state.backend.restores, [1]);
|
||||
deliver(&mut state, Some(req.clone()));
|
||||
|
||||
@@ -30,6 +30,9 @@ use vectorcraft_ui_egui::native_menu::{self, Backend, Event, MenuBar, MenuRole,
|
||||
// AppKit can deliver window input while its system menu is still tracking (especially with
|
||||
// asynchronous menu presentation). Keep the native tracking state separate from egui popups.
|
||||
static TRACKING: AtomicBool = AtomicBool::new(false);
|
||||
/// A tracking session began since the last [`Backend::drain`], which reports it as
|
||||
/// [`Event::Opened`].
|
||||
static OPENED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
pub(crate) fn is_tracking() -> bool {
|
||||
TRACKING.load(Ordering::Relaxed)
|
||||
@@ -46,9 +49,11 @@ fn observe_tracking(ctx: &egui::Context) {
|
||||
let block = RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
|
||||
TRACKING.store(tracking, Ordering::Relaxed);
|
||||
if tracking {
|
||||
OPENED.store(true, Ordering::Relaxed);
|
||||
super::mac_cursor::release();
|
||||
}
|
||||
// Apply any deferred menu updates as soon as the tracking session ends.
|
||||
// Report the opened menu and apply any deferred menu updates as soon as the
|
||||
// tracking session ends.
|
||||
if !tracking {
|
||||
repaint.request_repaint();
|
||||
}
|
||||
@@ -267,6 +272,9 @@ impl Backend for MacMenu {
|
||||
|
||||
fn drain(&mut self) -> Vec<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.
|
||||
|
||||
@@ -28,8 +28,12 @@ mod clipboard;
|
||||
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;
|
||||
@@ -50,6 +54,8 @@ mod mac_tablet;
|
||||
mod mac_window;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod open_documents;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
mod portal_request;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd", test))]
|
||||
mod portal_save;
|
||||
mod prefs_dir;
|
||||
@@ -84,6 +90,8 @@ mod titlebar;
|
||||
use app::bring_window_forward;
|
||||
use app::native_input_hook;
|
||||
use app::open_or_hold;
|
||||
#[cfg(all(test, not(any(target_os = "macos", windows))))]
|
||||
use app::{QuittingWindow, hide_before_teardown};
|
||||
use host_services::services;
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes};
|
||||
@@ -99,7 +107,7 @@ use titlebar::opted_into_system_title_bar;
|
||||
#[cfg(windows)]
|
||||
use titlebar::set_taskbar_icon;
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame, system_title_bar_applies};
|
||||
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 {
|
||||
@@ -113,7 +121,8 @@ 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 hide the window on quit before the clipboard handles let go (`app::hide_before_teardown`).
|
||||
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,
|
||||
@@ -123,6 +132,10 @@ struct App {
|
||||
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.
|
||||
@@ -293,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() {
|
||||
@@ -349,7 +367,7 @@ 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),
|
||||
@@ -437,6 +455,9 @@ fn main() -> std::process::ExitCode {
|
||||
open_documents::install();
|
||||
#[cfg(feature = "wgpu")]
|
||||
let created = startup.clone();
|
||||
// For the hang report (`hang_watch`).
|
||||
#[cfg(feature = "wgpu")]
|
||||
let requested_surface = options.wgpu_options.surface;
|
||||
// A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash.
|
||||
let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| {
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -465,6 +486,7 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_plugin_store(&mut session);
|
||||
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
|
||||
prefs_dir::attach_scripts_dir(&mut session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut session);
|
||||
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
|
||||
app.set_startup_update_check(true);
|
||||
load_prefs(&mut app, saved);
|
||||
@@ -474,6 +496,8 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_pdf_preset_store(&mut app.session);
|
||||
// The custom dictionary's words, kept in their own file next to the preferences.
|
||||
prefs_dir::attach_custom_dictionary(&mut app.session);
|
||||
// The custom arrowheads, kept in their own file next to the preferences.
|
||||
prefs_dir::attach_arrowheads(&mut app.session);
|
||||
// Fit the window to its monitor, or put it back where it was (still hidden).
|
||||
let winit_window = cc.winit_window().cloned();
|
||||
if let Some(w) = &winit_window {
|
||||
@@ -537,8 +561,39 @@ 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;
|
||||
if let Some(port) = control_port {
|
||||
let rx = control_server::start(port, cc.egui_ctx.clone());
|
||||
@@ -583,6 +638,8 @@ fn main() -> std::process::ExitCode {
|
||||
maximize_tries: 8,
|
||||
held_files,
|
||||
monitors_listed: None,
|
||||
display_profile: Default::default(),
|
||||
frame_start: None,
|
||||
}))
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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`).
|
||||
@@ -102,13 +103,22 @@ fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<Sav
|
||||
log::warn!("the portal's save dialog picked a file name that isn't UTF-8: nothing is saved");
|
||||
return Ok(None);
|
||||
};
|
||||
let filter = results.get("current_filter").and_then(|v| {
|
||||
let (label, _globs): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
|
||||
Some(label)
|
||||
});
|
||||
let filter = results.get("current_filter").and_then(|v| filter_label(v));
|
||||
Ok(Some(Saved { path, filter }))
|
||||
}
|
||||
|
||||
/// The label of a file type as the portal sends it, a `(sa(us))` structure; `None` for a value of
|
||||
/// another shape.
|
||||
fn filter_label(value: &Value<'_>) -> Option<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>> {
|
||||
@@ -174,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)
|
||||
}
|
||||
@@ -233,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"))]
|
||||
@@ -396,6 +394,36 @@ mod tests {
|
||||
assert_eq!(pick_answer(saved, &request), ["/home/me/Art/poster"]);
|
||||
}
|
||||
|
||||
/// A `current_filter` of another shape than `(sa(us))` (a structure with fewer, other or more
|
||||
/// fields, a string) gives the path alone; `uris` of another shape is an error.
|
||||
#[test]
|
||||
fn an_answer_of_another_shape_is_not_read() {
|
||||
let malformed = [
|
||||
Value::from(("SVG".to_string(),)),
|
||||
Value::from(("SVG".to_string(), vec![(0u32,)])),
|
||||
Value::from(("SVG".to_string(), vec![("*.svg".to_string(), 0u32)])),
|
||||
Value::from((1u32, vec![(0u32, "*.svg".to_string())])),
|
||||
Value::from(("SVG".to_string(), vec![(0u32, "*.svg".to_string())], 1u32)),
|
||||
Value::from("SVG"),
|
||||
];
|
||||
for filter in malformed {
|
||||
let mut r = results("file:///tmp/card", None);
|
||||
r.insert("current_filter".to_string(), OwnedValue::try_from(filter).unwrap());
|
||||
assert_eq!(answer(0, &r), Ok(Some(Saved { path: "/tmp/card".into(), filter: None })));
|
||||
}
|
||||
let malformed = [
|
||||
Value::from(vec![1u32]),
|
||||
Value::from(vec![("file:///tmp/card".to_string(),)]),
|
||||
Value::from(Vec::<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]
|
||||
@@ -449,26 +477,22 @@ mod tests {
|
||||
Old,
|
||||
/// As `Old`, with the `Response` sent before the reply that names its path.
|
||||
OldEarly,
|
||||
/// As `Current`, but it leaves the bus 300 ms after its reply without a `Response`, as a
|
||||
/// portal that exits while its dialog is open.
|
||||
Exits,
|
||||
/// Leaves the bus right after its reply, without a `Response`.
|
||||
ExitsAtOnce,
|
||||
/// Sends its `Response` right after its reply, then leaves the bus.
|
||||
AnswersAndExits,
|
||||
}
|
||||
|
||||
/// A session bus of its own (`dbus-daemon`) with a mock `org.freedesktop.portal.FileChooser`
|
||||
/// that answers `SaveFile` from `script` as `portal` says, as PhotoCraft's portal tests run it.
|
||||
/// `None` when there is no `dbus-daemon` to run.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, std::process::Child)> {
|
||||
use std::io::BufRead as _;
|
||||
|
||||
fn mock_portal(script: Script, portal: Portal) -> Option<(zbus::blocking::Connection, Seen, crate::portal_request::test_bus::Daemon)> {
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
let spawning = crate::spawning();
|
||||
let daemon = std::process::Command::new("dbus-daemon")
|
||||
.args(["--session", "--nofork", "--print-address=1"])
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.spawn();
|
||||
drop(spawning);
|
||||
let mut daemon = daemon.ok()?;
|
||||
let mut address = String::new();
|
||||
std::io::BufReader::new(daemon.stdout.take()?).read_line(&mut address).ok()?;
|
||||
let address = address.trim().to_string();
|
||||
let (daemon, address) = crate::portal_request::test_bus::private_bus()?;
|
||||
let server =
|
||||
zbus::blocking::connection::Builder::address(address.as_str()).ok()?.name("org.freedesktop.portal.Desktop").ok()?.build().ok()?;
|
||||
let seen = Seen::default();
|
||||
@@ -486,18 +510,15 @@ mod tests {
|
||||
}
|
||||
let Ok((_parent, _title, options)) = msg.body().deserialize::<(String, String, HashMap<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 };
|
||||
@@ -515,14 +536,22 @@ mod tests {
|
||||
if server.reply(&header, &handle).is_err() {
|
||||
break;
|
||||
}
|
||||
if portal == Portal::Old {
|
||||
if matches!(portal, Portal::Old | Portal::Exits) {
|
||||
// As a person answers the dialog: after the caller has the path returned.
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
}
|
||||
if matches!(portal, Portal::Exits | Portal::ExitsAtOnce) {
|
||||
break;
|
||||
}
|
||||
if portal != Portal::OldEarly && respond().is_err() {
|
||||
break;
|
||||
}
|
||||
if portal == Portal::AnswersAndExits {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// The portal leaves the bus: the bus sends `NameOwnerChanged` for its name.
|
||||
let _ = server.close();
|
||||
});
|
||||
let client = zbus::blocking::connection::Builder::address(address.as_str()).ok()?.build().ok()?;
|
||||
Some((client, seen, daemon))
|
||||
@@ -546,7 +575,7 @@ mod tests {
|
||||
#[test]
|
||||
fn the_portal_is_asked_on_the_first_file_type_and_answers_the_one_picked() {
|
||||
let script = vec![(0, Some(("file:///home/me/Art/poster", "PDF-compatible .ai"))), (1, None)];
|
||||
let Some((conn, seen, mut daemon)) = mock_portal(script, Portal::Current) else {
|
||||
let Some((conn, seen, _daemon)) = mock_portal(script, Portal::Current) else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
@@ -556,7 +585,6 @@ mod tests {
|
||||
assert_eq!(save_within(&conn, &request), Ok(None));
|
||||
let seen = seen.lock().map(|s| s.clone()).unwrap_or_default();
|
||||
assert_eq!(seen.first(), Some(&(Some("Untitled-1.vectorcraft".to_string()), Some(request.filters[0].0.clone()))));
|
||||
let _ = daemon.kill();
|
||||
}
|
||||
|
||||
/// A portal older than 0.9 answers on the request path it returns, and the answer is awaited
|
||||
@@ -564,13 +592,12 @@ mod tests {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn the_answer_is_awaited_on_the_path_the_portal_returns() {
|
||||
let Some((conn, _seen, mut daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else {
|
||||
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::Old) else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
let request = request();
|
||||
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
|
||||
let _ = daemon.kill();
|
||||
}
|
||||
|
||||
/// A portal older than 0.9 can answer before its reply names the request path: the answer is
|
||||
@@ -579,14 +606,41 @@ mod tests {
|
||||
#[test]
|
||||
fn an_answer_that_comes_before_the_path_is_kept() {
|
||||
let script = vec![(0, Some(("file:///tmp/card", "SVG"))), (1, None)];
|
||||
let Some((conn, _seen, mut daemon)) = mock_portal(script, Portal::OldEarly) else {
|
||||
let Some((conn, _seen, _daemon)) = mock_portal(script, Portal::OldEarly) else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
let request = request();
|
||||
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
|
||||
assert_eq!(save_within(&conn, &request), Ok(None));
|
||||
let _ = daemon.kill();
|
||||
}
|
||||
|
||||
/// A portal that leaves the bus after its reply without answering, while its dialog is open or
|
||||
/// at once, ends the wait with an error, and rfd shows the dialog.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn a_portal_that_exits_during_the_dialog_ends_the_wait() {
|
||||
for portal in [Portal::Exits, Portal::ExitsAtOnce] {
|
||||
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], portal) else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
assert_eq!(save_within(&conn, &request()), Err("the desktop portal disappeared while waiting for its answer".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
/// A portal that answers and then leaves the bus: the save reads the answer. Whether the answer
|
||||
/// or the bus's report comes first depends on timing here; `portal_request`'s
|
||||
/// `a_queued_answer_wins_over_the_portal_leaving` queues both before the wait.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn an_answer_sent_just_before_the_portal_exits_is_kept() {
|
||||
let Some((conn, _seen, _daemon)) = mock_portal(vec![(0, Some(("file:///tmp/card", "SVG")))], Portal::AnswersAndExits) else {
|
||||
eprintln!("no dbus-daemon: skipped");
|
||||
return;
|
||||
};
|
||||
let request = request();
|
||||
assert_eq!(pick_answer(save_within(&conn, &request).unwrap(), &request), ["/tmp/card", "svg"]);
|
||||
}
|
||||
|
||||
/// The labels go to the dialog in the interface's language, which is how the answer is matched.
|
||||
|
||||
@@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Have File › New start each category's documents from its profile in the `New Document
|
||||
/// Profiles` folder, which `file.newProfiles.edit` makes.
|
||||
pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(dir) = store_dir("New Document Profiles") {
|
||||
session.attach_new_doc_profiles(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from
|
||||
/// now on there. After the preferences were restored: the folder is the one place the presets live.
|
||||
pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
|
||||
@@ -81,6 +89,14 @@ pub fn attach_custom_dictionary(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the custom arrowheads (Stroke panel menu › Edit Arrowheads…) in the `Arrowheads.vectorcraft`
|
||||
/// file next to the settings, and list the heads it holds.
|
||||
pub fn attach_arrowheads(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(path) = store_dir(vectorcraft_engine::cmd::arrowheads::FILE_NAME) {
|
||||
session.attach_arrowheads_file(path.to_string_lossy().to_string());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -220,8 +220,10 @@ fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() {
|
||||
}
|
||||
|
||||
/// The frame a start uses: the preference turns the desktop frame the probe chose into the app frame
|
||||
/// with the default window buttons, a probed app frame keeps its own buttons, and the desktop frame
|
||||
/// stays where the app frame is not drawn. System Title Bar takes precedence over the preference.
|
||||
/// 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};
|
||||
@@ -233,9 +235,10 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
|
||||
((Frame::Desktop, None, true, true), Frame::App(Layout::default())),
|
||||
((Frame::App(gnome.clone()), None, false, false), Frame::App(gnome.clone())),
|
||||
((Frame::App(gnome.clone()), None, true, false), Frame::Desktop),
|
||||
((Frame::App(gnome.clone()), None, true, true), Frame::App(gnome.clone())),
|
||||
((Frame::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(gnome.clone())),
|
||||
((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}");
|
||||
@@ -246,6 +249,30 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
|
||||
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]
|
||||
@@ -303,7 +330,7 @@ fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
|
||||
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 (custom, _) = super::custom_titlebar(saved);
|
||||
let expected = match value.as_str() {
|
||||
_ if not_read => !cfg!(target_os = "macos") && !opted_into_system,
|
||||
"app" => true,
|
||||
@@ -312,7 +339,7 @@ fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
|
||||
// `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),
|
||||
_ => 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}");
|
||||
@@ -460,3 +487,21 @@ fn the_linux_desktop_entry_opens_every_readable_format() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On Linux and the BSDs, quitting hides the main window before eframe drops the app, whose
|
||||
/// clipboard handles may take up to `CLIPBOARD_PROBE_STOP_WAIT` to let go.
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
#[test]
|
||||
fn quitting_hides_the_window_before_the_clipboards_let_go() {
|
||||
struct Window(std::cell::Cell<u32>);
|
||||
impl QuittingWindow for Window {
|
||||
fn hide(&self) {
|
||||
self.0.set(self.0.get() + 1);
|
||||
}
|
||||
}
|
||||
let window = Window(std::cell::Cell::new(0));
|
||||
hide_before_teardown(Some(&window));
|
||||
assert_eq!(window.0.get(), 1, "the window was not hidden");
|
||||
// Without a window (none was made), there is nothing to hide.
|
||||
hide_before_teardown::<Window>(None);
|
||||
}
|
||||
@@ -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
|
||||
@@ -68,18 +68,45 @@ pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option<bool>, forced
|
||||
}
|
||||
|
||||
/// The frame this start uses, before the System Title Bar preference is applied
|
||||
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. A probed
|
||||
/// app frame keeps its window-button layout; an app frame the probe did not choose gets the default
|
||||
/// layout, since `custom_titlebar_from` reads only which frame it is.
|
||||
/// ([`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(_)) => frame,
|
||||
(true, craft_window::Frame::Desktop) => craft_window::Frame::App(craft_window::Layout::default()),
|
||||
(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 {
|
||||
@@ -131,7 +158,8 @@ 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, which does not apply while the variable is set to `app`, `system` or
|
||||
/// `desktop`. Call once at startup,
|
||||
@@ -142,7 +170,7 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
|
||||
/// 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. 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 {
|
||||
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`
|
||||
@@ -160,7 +188,7 @@ pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> b
|
||||
#[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)
|
||||
(custom_titlebar_from(&frame, opted_into_system), caption_layout_from(&frame))
|
||||
}
|
||||
|
||||
pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
|
||||
|
||||
@@ -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")));
|
||||
}
|
||||
@@ -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")
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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 |
@@ -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 |
@@ -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 |
@@ -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 }
|
||||
@@ -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,
|
||||
@@ -35,7 +37,7 @@ Affinity files.
|
||||
|
||||
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 strokes, pressure curves that can't be read or that go past the million points one document may hold,
|
||||
transparency gradients, fill opacity, bitmap fills, master pages based on other master pages, conical gradients (as radial),
|
||||
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
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -1,425 +0,0 @@
|
||||
//! The Affinity archive: header, the chain of file allocation tables (one per save) and
|
||||
//! bounded, CRC-checked extraction of named entries such as `doc.dat` and raster tiles.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::io::Read;
|
||||
|
||||
use crate::Error;
|
||||
|
||||
pub const MAGIC: &[u8; 4] = b"\x00\xffKA";
|
||||
/// Oldest and newest container versions seen in real documents (Affinity 1.x writes 8,
|
||||
/// Affinity 3 writes 12). Version 7 is described by afread but no sample exists.
|
||||
pub const VERSIONS: std::ops::RangeInclusive<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;
|
||||
/// Allocation records read over the whole table chain. Each save lists every entry again, so a
|
||||
/// document with a few hundred saves of a few thousand entries stays far below; tables whose
|
||||
/// record regions overlap (or a table chain of thousands of huge tables) can't multiply the work.
|
||||
const MAX_INDEX_RECORDS: usize = 1 << 22;
|
||||
/// Bytes of entry names kept by the index (after lossy UTF-8 decoding, which can triple a name).
|
||||
/// Real names (`doc.dat`, `d/12`) are a few bytes each.
|
||||
const MAX_INDEX_NAME_BYTES: usize = 16 << 20;
|
||||
/// zstd window ceiling: real documents use a few MiB; this stops a header from reserving gigabytes.
|
||||
const MAX_ZSTD_WINDOW: u64 = 64 << 20;
|
||||
|
||||
/// Decompression budget for one import. Every entry declares its size, which is checked against
|
||||
/// these limits before anything is allocated, and the decoded length must match it exactly.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Limits {
|
||||
/// Largest single entry (`doc.dat` or one tile).
|
||||
pub max_entry: usize,
|
||||
/// Total bytes extracted over the whole import.
|
||||
pub max_total: usize,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Self { max_entry: 256 << 20, max_total: 1 << 30 }
|
||||
}
|
||||
}
|
||||
|
||||
/// The container header, all integers little-endian.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Header {
|
||||
pub version: u16,
|
||||
/// Seen as 0, 4 or 8 in real files; bits 0 and 1 mark container variants that are rejected.
|
||||
pub flags: u16,
|
||||
pub(crate) fat_offset: u64,
|
||||
pub(crate) thumbnail_offset: u64,
|
||||
/// Save time in Unix seconds, as written by the application.
|
||||
pub saved: u32,
|
||||
}
|
||||
|
||||
/// One FAT record, as of the newest table that mentions its id.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Entry {
|
||||
pub id: u32,
|
||||
pub name: String,
|
||||
offset: u64,
|
||||
size: u64,
|
||||
compressed: u64,
|
||||
crc: u32,
|
||||
compression: u8,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
/// Decompressed size declared by the table.
|
||||
pub fn size(&self) -> u64 {
|
||||
self.size
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Archive<'a> {
|
||||
bytes: &'a [u8],
|
||||
pub header: Header,
|
||||
/// Head revision of every named, non-deleted entry.
|
||||
entries: HashMap<String, Entry>,
|
||||
/// Number of tables (saves) in the chain.
|
||||
pub revisions: usize,
|
||||
extracted: usize,
|
||||
limits: Limits,
|
||||
/// Entries whose extraction failed after their size was charged: asked again, they fail
|
||||
/// again without being decompressed again.
|
||||
failed: HashMap<String, Error>,
|
||||
}
|
||||
|
||||
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> {
|
||||
Self::open_within(bytes, limits, MAX_INDEX_RECORDS, MAX_INDEX_NAME_BYTES)
|
||||
}
|
||||
|
||||
/// [`Archive::open`] reading at most `max_records` allocation records and keeping at most
|
||||
/// `max_name_bytes` bytes of entry names, both over the whole table chain.
|
||||
pub(crate) fn open_within(bytes: &'a [u8], limits: Limits, max_records: usize, max_name_bytes: usize) -> Result<Self, Error> {
|
||||
let header = header(bytes)?;
|
||||
let mut records_left = max_records;
|
||||
let mut name_bytes_left = max_name_bytes;
|
||||
// Newest record per id: (table date, table index, record).
|
||||
let mut latest: HashMap<u32, (u64, usize, Option<Entry>)> = HashMap::new();
|
||||
let mut names: HashMap<u32, String> = HashMap::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut next = header.fat_offset;
|
||||
let mut tables = 0usize;
|
||||
while next != 0 {
|
||||
if !seen.insert(next) {
|
||||
return Err(Error::Malformed("allocation tables form a cycle"));
|
||||
}
|
||||
tables += 1;
|
||||
if tables > MAX_TABLES {
|
||||
return Err(Error::Limit("too many saved revisions"));
|
||||
}
|
||||
let mut c = Cursor::new(bytes, offset(next)?);
|
||||
let tag = c.array::<4>()?;
|
||||
let level = match &tag {
|
||||
b"#FAT" => 1,
|
||||
b"#FT2" => 2,
|
||||
b"#FT3" => 3,
|
||||
b"#FT4" => 4,
|
||||
_ => return Err(Error::Malformed("missing allocation table")),
|
||||
};
|
||||
next = c.u64()?;
|
||||
let date = c.u64()?;
|
||||
c.take(24)?;
|
||||
let files = c.u32()?;
|
||||
c.take(8)?;
|
||||
let dirs = c.u16()?;
|
||||
c.take(1)?;
|
||||
for _ in 0..files {
|
||||
records_left = records_left.checked_sub(1).ok_or(Error::Limit("too many archive entries"))?;
|
||||
let id = c.u32()?;
|
||||
let flag = c.u8()?;
|
||||
let mut record = None;
|
||||
match flag {
|
||||
0 | 1 => {
|
||||
let offset = c.u64()?;
|
||||
let size = c.u64()?;
|
||||
let compressed = c.u64()?;
|
||||
let crc = c.u32()?;
|
||||
let stored = c.u8()?;
|
||||
if level >= 2 {
|
||||
c.take(4)?;
|
||||
}
|
||||
if level >= 4 {
|
||||
c.take(4)?;
|
||||
}
|
||||
// Old tables number the methods; newer ones store the method byte itself.
|
||||
let compression = if level <= 2 {
|
||||
match stored {
|
||||
1 => 0x01,
|
||||
2 => 0x41,
|
||||
3 => 0x81,
|
||||
4 => 0xC1,
|
||||
_ => 0,
|
||||
}
|
||||
} else {
|
||||
stored
|
||||
};
|
||||
record = Some(Entry { id, name: String::new(), offset, size, compressed, crc, compression });
|
||||
}
|
||||
2 => {}
|
||||
_ => return Err(Error::Malformed("unknown allocation record")),
|
||||
}
|
||||
if flag == 0 {
|
||||
let len = usize::from(c.u16()?);
|
||||
let raw = c.take(len)?;
|
||||
// Only the first name of an id is kept: later ones are not even decoded.
|
||||
if let std::collections::hash_map::Entry::Vacant(slot) = names.entry(id) {
|
||||
let name = String::from_utf8_lossy(raw);
|
||||
name_bytes_left = name_bytes_left.checked_sub(name.len()).ok_or(Error::Limit("archive entry names too long"))?;
|
||||
slot.insert(name.into_owned());
|
||||
}
|
||||
}
|
||||
// Equal dates: the first table in the chain (the newest) wins, as in afread.
|
||||
let replace = latest.get(&id).is_none_or(|(d, _, _)| date > *d);
|
||||
if replace {
|
||||
latest.insert(id, (date, tables, record));
|
||||
}
|
||||
}
|
||||
for _ in 0..dirs {
|
||||
records_left = records_left.checked_sub(1).ok_or(Error::Limit("too many archive entries"))?;
|
||||
let len = usize::from(c.u16()?);
|
||||
c.take(10)?;
|
||||
c.take(len)?;
|
||||
}
|
||||
}
|
||||
let mut entries = HashMap::new();
|
||||
for (id, (_, _, record)) in latest {
|
||||
if let (Some(mut e), Some(name)) = (record, names.remove(&id)) {
|
||||
e.name = name;
|
||||
entries.insert(e.name.clone(), e);
|
||||
}
|
||||
}
|
||||
Ok(Self { bytes, header, entries, revisions: tables, extracted: 0, limits, failed: HashMap::new() })
|
||||
}
|
||||
|
||||
pub fn entry(&self, name: &str) -> Option<&Entry> {
|
||||
self.entries.get(name)
|
||||
}
|
||||
|
||||
pub fn entry_names(&self) -> impl Iterator<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> {
|
||||
if let Some(e) = self.failed.get(name) {
|
||||
return Err(*e);
|
||||
}
|
||||
let e = self.entries.get(name).ok_or(Error::Malformed("missing archive entry"))?;
|
||||
let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?;
|
||||
if size > self.limits.max_entry {
|
||||
return Err(Error::Limit("archive entry too large"));
|
||||
}
|
||||
let total = self.extracted.checked_add(size).ok_or(Error::Limit("document too large"))?;
|
||||
if total > self.limits.max_total {
|
||||
return Err(Error::Limit("document too large"));
|
||||
}
|
||||
// Charged before the work, and kept when it fails: an entry that fails its checksum
|
||||
// can't be decompressed over and over for free.
|
||||
self.extracted = total;
|
||||
let result = extract(self.bytes, e, size);
|
||||
if let Err(err) = result {
|
||||
self.failed.insert(name.to_owned(), err);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// Decompress entry `e` of `bytes` (declared `size` bytes), undo its predictor and check its CRC.
|
||||
fn extract(bytes: &[u8], e: &Entry, size: usize) -> Result<Vec<u8>, Error> {
|
||||
let mut c = Cursor::new(bytes, offset(e.offset)?);
|
||||
if c.take(4)? != b"#Fil" {
|
||||
return Err(Error::Malformed("archive entry has no data block"));
|
||||
}
|
||||
let method = e.compression & 3;
|
||||
let stored_len = if matches!(method, 1 | 2) { e.compressed } else { e.size };
|
||||
let data = c.take(offset(stored_len)?)?;
|
||||
let mut out = match method {
|
||||
1 => inflate(data, size)?,
|
||||
2 => unzstd(data, size)?,
|
||||
_ => data.to_vec(),
|
||||
};
|
||||
if out.len() != size {
|
||||
return Err(Error::Malformed("archive entry size mismatch"));
|
||||
}
|
||||
unpredict(&mut out, e.compression)?;
|
||||
if crc32fast::hash(&out) != e.crc {
|
||||
return Err(Error::Malformed("archive entry checksum mismatch"));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Read at most `size + 1` bytes so a stream that decodes past its declared size is caught
|
||||
/// without unbounded allocation.
|
||||
fn read_bounded(mut r: impl Read, size: usize) -> Result<Vec<u8>, Error> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,360 +0,0 @@
|
||||
//! Outlines of curves (`PCvD` node lists), parametric shapes (`Shpe` objects) and compounds, in
|
||||
//! node space.
|
||||
|
||||
use crate::model::{Affine, Path, Point, Reader, SubPath};
|
||||
use crate::stream::{ObjId, Tag, Value};
|
||||
|
||||
/// Nodes per curve object.
|
||||
const MAX_NODES: usize = 4_000_000;
|
||||
/// A shared-object stream is bounded, but a compound graph can expand exponentially. Count
|
||||
/// each visit and each curve record / generated contour / transformed segment across the whole
|
||||
/// outline, including repeated references. Match the document reader's nesting limit.
|
||||
const MAX_OUTLINE_DEPTH: usize = 128;
|
||||
const MAX_OUTLINE_VISITS: usize = 100_000;
|
||||
|
||||
struct OutlineBudget {
|
||||
active: Vec<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)
|
||||
}
|
||||
|
||||
/// Most segments a stroke's pressure curve may have; the curves in real documents have a handful.
|
||||
const MAX_PRESSURE_SEGMENTS: usize = 256;
|
||||
|
||||
/// Most regular samples of a pressure curve: each segment gets an equal share, at least 2 (its
|
||||
/// middle and its end) and 8 at most. The points where a segment's width stops rising or falling
|
||||
/// come on top (at most two per segment), so a curve has at most 1 + 4 × [`MAX_PRESSURE_SEGMENTS`]
|
||||
/// points; the document's limit counts all of them.
|
||||
const PRESSURE_POINTS: usize = 512;
|
||||
|
||||
/// Most points one pressure curve can have (see [`PRESSURE_POINTS`]). A curve that can't be read
|
||||
/// counts this many against the document's limit.
|
||||
pub(crate) const MAX_PRESSURE_CURVE_POINTS: usize = 1 + 4 * MAX_PRESSURE_SEGMENTS;
|
||||
|
||||
/// A stroke's pressure curve (`LDsc.LDeP`, a `CrvD` whose positional `Data` holds an array of
|
||||
/// 18-byte records as in [`curves`]): x is the position along the path (0 to 1) and y the width as
|
||||
/// a fraction of the stroke's weight. Each segment is sampled at 2 to 8 points, at most
|
||||
/// [`PRESSURE_POINTS`] in all, and also where its width stops rising or falling (at most two more
|
||||
/// points), so a dip between samples is kept → (position, width) in order along the path,
|
||||
/// positions clamped into 0..1 and never going back, widths clamped into 0..1. `None` when the
|
||||
/// curve can't be read or has more than [`MAX_PRESSURE_SEGMENTS`] segments.
|
||||
pub(crate) fn pressure(r: &Reader, crvd: ObjId) -> Option<Vec<(f64, f64)>> {
|
||||
let s = r.s;
|
||||
let data = s.obj(crvd, b"Data")?;
|
||||
let records = s.positional(data).find_map(|v| if let Value::Array(a) = v { Some(a) } else { None })?;
|
||||
// Every segment takes at least an anchor record.
|
||||
if records.len() > MAX_PRESSURE_SEGMENTS * 3 + 1 {
|
||||
return None;
|
||||
}
|
||||
let curve = subpath(&anchors(records)?, false, None)?;
|
||||
if curve.segments.len() > MAX_PRESSURE_SEGMENTS {
|
||||
return None;
|
||||
}
|
||||
let steps = u32::try_from((PRESSURE_POINTS / curve.segments.len().max(1)).clamp(2, 8)).unwrap_or(2);
|
||||
let mut samples = vec![(curve.start.x, curve.start.y)];
|
||||
let mut from = curve.start;
|
||||
for [c1, c2, to] in &curve.segments {
|
||||
let mut ts: Vec<f64> = (1..=steps).map(|i| f64::from(i) / f64::from(steps)).collect();
|
||||
ts.extend(turning_points(from.y, c1.y, c2.y, to.y).into_iter().flatten());
|
||||
ts.sort_by(f64::total_cmp);
|
||||
ts.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
|
||||
for t in ts {
|
||||
let u = 1.0 - t;
|
||||
let at = |a: f64, b: f64, c: f64, d: f64| u * u * u * a + 3.0 * u * u * t * b + 3.0 * u * t * t * c + t * t * t * d;
|
||||
samples.push((at(from.x, c1.x, c2.x, to.x), at(from.y, c1.y, c2.y, to.y)));
|
||||
}
|
||||
from = *to;
|
||||
}
|
||||
let mut last = 0.0f64;
|
||||
Some(
|
||||
samples
|
||||
.into_iter()
|
||||
.map(|(x, y)| {
|
||||
last = x.clamp(last, 1.0);
|
||||
(last, y.clamp(0.0, 1.0))
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The parameters strictly between 0 and 1 where the cubic Bézier with control values `a`, `b`,
|
||||
/// `c` and `d` stops rising or falling (where its derivative is 0). The values are scaled into
|
||||
/// -1..1 first, so huge ones can't overflow the discriminant.
|
||||
fn turning_points(a: f64, b: f64, c: f64, d: f64) -> [Option<f64>; 2] {
|
||||
let scale = a.abs().max(b.abs()).max(c.abs()).max(d.abs());
|
||||
if !(scale.is_finite() && scale > 0.0) {
|
||||
return [None, None];
|
||||
}
|
||||
let (a, b, c, d) = (a / scale, b / scale, c / scale, d / scale);
|
||||
let (d0, d1, d2) = (b - a, c - b, d - c);
|
||||
let (qa, qb, qc) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0);
|
||||
let inside = |t: f64| (t.is_finite() && t > 0.0 && t < 1.0).then_some(t);
|
||||
if qa.abs() < 1e-12 {
|
||||
return [if qb.abs() < 1e-12 { None } else { inside(-qc / qb) }, None];
|
||||
}
|
||||
let disc = qb * qb - 4.0 * qa * qc;
|
||||
if disc < 0.0 {
|
||||
return [None, None];
|
||||
}
|
||||
let root = disc.sqrt();
|
||||
[inside((-qb - root) / (2.0 * qa)), inside((-qb + root) / (2.0 * qa))]
|
||||
}
|
||||
|
||||
struct Anchor {
|
||||
p: Point,
|
||||
inh: Option<Point>,
|
||||
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(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn turning_points_of_huge_control_values_are_found() {
|
||||
let small = turning_points(1.0, -3.0, 3.0, 1.0);
|
||||
let huge = turning_points(1e200, -3e200, 3e200, 1e200);
|
||||
assert!(small.iter().all(Option::is_some), "{small:?}");
|
||||
for (s, h) in small.iter().zip(&huge) {
|
||||
let (Some(s), Some(h)) = (s, h) else { panic!("{huge:?}") };
|
||||
assert!((s - h).abs() < 1e-12, "{small:?} {huge:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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::*;
|
||||
@@ -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>>,
|
||||
}
|
||||
@@ -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",
|
||||
}
|
||||
}
|
||||
@@ -1,685 +0,0 @@
|
||||
use super::bounds::{describe, is_container, mask_extent, nodes_bounds, pages, rect, tree_bounds, union};
|
||||
use super::{
|
||||
Affine, Archive, BTreeMap, Blend, Document, Effect, Error, HashSet, Image, Kind, Limits, Node, ObjId, Paint, Path, Point, Rect, Spread, Stream,
|
||||
Tag, paint, stream,
|
||||
};
|
||||
|
||||
/// Largest embedded colour profile kept (real CMYK profiles are a few megabytes).
|
||||
const MAX_PROFILE_BYTES: usize = 32 << 20;
|
||||
|
||||
/// Deepest layer nesting followed; deeper content is reported, not imported.
|
||||
pub(super) const MAX_TREE_DEPTH: usize = 128;
|
||||
|
||||
/// Total layer nodes imported.
|
||||
const MAX_NODES: usize = 500_000;
|
||||
|
||||
/// Pixels decoded from pixel layers over a whole document (2 GB as RGBA). The archive's limits
|
||||
/// count the bytes extracted from it, and a layer of one flat colour needs none (#1704).
|
||||
const MAX_LAYER_PIXELS: u64 = 512 << 20;
|
||||
|
||||
/// Embedded documents inside embedded documents are followed this deep.
|
||||
const MAX_EMBED_DEPTH: usize = 4;
|
||||
|
||||
/// Characters of all stories together (a story may be shared by many text layers).
|
||||
const MAX_DOCUMENT_CHARS: usize = 16 << 20;
|
||||
|
||||
/// Table cells of all tables together (each becomes a text object with its edge lines).
|
||||
const MAX_DOCUMENT_CELLS: usize = 1 << 18;
|
||||
|
||||
/// Points of all strokes' pressure curves together (a stroke style may be shared by many layers).
|
||||
const MAX_DOCUMENT_PRESSURE_POINTS: usize = 1 << 20;
|
||||
|
||||
/// Child references inspected, page rectangles produced, and outline segments retained, in all
|
||||
/// (shared objects are visited once per link, so each visit is charged). Real documents stay
|
||||
/// within a few times [`MAX_NODES`]; this leaves ~30x headroom over that.
|
||||
const MAX_DOCUMENT_WORK: usize = 1 << 24;
|
||||
|
||||
/// Owned layer-name characters kept in all (each visit of a shared object keeps its own copy).
|
||||
const MAX_DOCUMENT_NAME_CHARS: usize = 16 << 20;
|
||||
|
||||
/// What a whole read may still use. Shared objects can be linked from many layers, and embedded
|
||||
/// documents are read with what their embedding document left, so linking or embedding the
|
||||
/// same content many times can't multiply the work.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Budget {
|
||||
/// Layer nodes ([`MAX_NODES`] in all).
|
||||
pub(crate) nodes: usize,
|
||||
/// Pixels the pixel layers may decode ([`MAX_LAYER_PIXELS`] in all).
|
||||
pub(crate) pixels: u64,
|
||||
/// Characters of stories ([`MAX_DOCUMENT_CHARS`] in all).
|
||||
pub(crate) chars: usize,
|
||||
/// Table cells ([`MAX_DOCUMENT_CELLS`] in all).
|
||||
pub(crate) cells: usize,
|
||||
/// Points of pressure curves ([`MAX_DOCUMENT_PRESSURE_POINTS`] in all).
|
||||
pub(crate) pressure: usize,
|
||||
/// Child references, page rectangles and outline segments ([`MAX_DOCUMENT_WORK`] in all).
|
||||
pub(crate) work: usize,
|
||||
/// Layer-name characters ([`MAX_DOCUMENT_NAME_CHARS`] in all).
|
||||
pub(crate) name_chars: usize,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
pub(crate) const FULL: Budget = Budget {
|
||||
nodes: MAX_NODES,
|
||||
pixels: MAX_LAYER_PIXELS,
|
||||
chars: MAX_DOCUMENT_CHARS,
|
||||
cells: MAX_DOCUMENT_CELLS,
|
||||
pressure: MAX_DOCUMENT_PRESSURE_POINTS,
|
||||
work: MAX_DOCUMENT_WORK,
|
||||
name_chars: MAX_DOCUMENT_NAME_CHARS,
|
||||
};
|
||||
|
||||
/// Take `n` units of work, or fail the read.
|
||||
pub(crate) fn spend(&mut self, n: usize) -> Result<(), Error> {
|
||||
self.work = self.work.checked_sub(n).ok_or(Error::Limit("too much shared geometry or page data"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a document: archive, `doc.dat` and the model.
|
||||
pub fn read(bytes: &[u8], limits: Limits) -> Result<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);
|
||||
self.budget.spend(pages.len() + 1)?;
|
||||
let default_size = s.floats::<2>(doc, b"DfSz").filter(|[w, h]| *w > 0.0 && *h > 0.0).map(|[w, h]| Rect { x0: 0.0, y0: 0.0, x1: w, y1: h });
|
||||
let bounds = s.floats::<4>(spread, b"SprB").map(rect).or_else(|| pages.iter().copied().reduce(union)).or(default_size).unwrap_or(Rect {
|
||||
x0: 0.0,
|
||||
y0: 0.0,
|
||||
x1: 0.0,
|
||||
y1: 0.0,
|
||||
});
|
||||
let transparent = s.bool(spread, b"SprT").unwrap_or(false);
|
||||
let (nodes, mask) = self.children(spread, self.base, 0)?;
|
||||
if mask.is_some() {
|
||||
self.warn("mask layers directly on a page (imported without them)");
|
||||
}
|
||||
Ok(Some(Spread { bounds, pages, transparent, nodes }))
|
||||
}
|
||||
|
||||
/// The children of `parent`, and the mask layer among them that masks the parent (with its
|
||||
/// placement), read later over just what it masks.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn children(&mut self, parent: ObjId, world: Affine, depth: usize) -> Result<(Vec<Node>, Option<(ObjId, Affine)>), Error> {
|
||||
let s = self.s;
|
||||
let mut out = Vec::new();
|
||||
let mut mask = None;
|
||||
let kids = s.objs(parent, b"Chld");
|
||||
// Invisible masks and skipped children cost no node, so the visit is charged here.
|
||||
self.budget.spend(kids.len())?;
|
||||
for c in kids {
|
||||
if s.is(c, b"MRst") {
|
||||
// A mask layer inside a group or layer masks that container.
|
||||
if s.bool(c, b"Visi") == Some(false) {
|
||||
continue;
|
||||
}
|
||||
let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
|
||||
if mask.is_none() {
|
||||
mask = Some((c, local.then(world)));
|
||||
} else {
|
||||
self.warn("several pixel masks on one layer (only the first is used)");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = self.node(c, world, depth + 1)? {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
Ok((out, mask))
|
||||
}
|
||||
|
||||
fn node(&mut self, id: ObjId, parent: Affine, depth: usize) -> Result<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.min(self.budget.name_chars)).collect();
|
||||
self.budget.name_chars -= name.chars().count();
|
||||
let visible = s.bool(id, b"Visi").unwrap_or(true);
|
||||
let locked = s.bool(id, b"Edtb").is_some_and(|e| !e);
|
||||
let opacity = s.f64(id, b"Opac").map_or(1.0, |o| o.clamp(0.0, 1.0));
|
||||
let blend = match s.enumeration(id, b"Blnd") {
|
||||
None if s.bool(id, b"PasT") != Some(false) && is_container(class) => Blend::PassThrough,
|
||||
None => Blend::Normal,
|
||||
Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| {
|
||||
self.warn("an unknown blend mode (imported as Normal)");
|
||||
Blend::Normal
|
||||
}),
|
||||
};
|
||||
let kind = if !world.is_finite() {
|
||||
self.warn("a layer with an invalid transform");
|
||||
Kind::Unsupported
|
||||
} else {
|
||||
self.kind(id, class, world, parent)?
|
||||
};
|
||||
// This node's embedded content, before its children's `node` calls can take it.
|
||||
let embedded = self.pending.take();
|
||||
// A compound's children are its operands, already merged into its outline.
|
||||
let (mut children, child_mask) = if class == Tag::of(b"Comp") { (Vec::new(), None) } else { self.children(id, world, depth)? };
|
||||
if let Some(embedded) = embedded {
|
||||
children.extend(embedded);
|
||||
}
|
||||
// Pixel masks are read only over what they mask (they can span a whole spread at print
|
||||
// resolution, a gigapixel).
|
||||
let over = mask_extent(&kind, &children);
|
||||
let child_mask = match child_mask {
|
||||
Some((c, at)) => crate::raster::mask(self, c, at, over)?,
|
||||
None => None,
|
||||
};
|
||||
let (mask, attached_mask) = self.attached_masks(id, world, over)?;
|
||||
let pixel_mask = attached_mask.or(child_mask);
|
||||
self.active.remove(&id);
|
||||
let mut node = Node { class, name, visible, locked, opacity, blend, kind, mask, pixel_mask, effects: Vec::new(), children };
|
||||
// Gradient overlays are laid out over the node's bounds, also while it is hidden.
|
||||
let bounds = tree_bounds(&node);
|
||||
node.effects = self.effects(id, world, bounds);
|
||||
Ok(Some(node))
|
||||
}
|
||||
|
||||
fn kind(&mut self, id: ObjId, class: Tag, world: Affine, parent: Affine) -> Result<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);
|
||||
};
|
||||
self.budget.spend(local.subpaths.iter().map(|sp| sp.segments.len() + 1).sum())?;
|
||||
let (fills, strokes) = paint::node_paint(self, id, world);
|
||||
Kind::Shape { path: local.transformed(world), fills, strokes, even_odd }
|
||||
}
|
||||
b"TxtT" => match crate::text::table(self, id, world) {
|
||||
Some(t) => Kind::Table(t),
|
||||
None => {
|
||||
self.warn("tables that could not be read");
|
||||
Kind::Unsupported
|
||||
}
|
||||
},
|
||||
b"TxtA" | b"TxtF" | b"TxtC" => match crate::text::read(self, id, world) {
|
||||
Some(t) => Kind::Text(t),
|
||||
None => {
|
||||
self.warn("text whose story could not be read (master-page text, or an unknown layout)");
|
||||
Kind::Unsupported
|
||||
}
|
||||
},
|
||||
b"ImgN" | b"Rstr" => match crate::raster::node_image(self, id, world)? {
|
||||
Some(img) => Kind::Image(img),
|
||||
None => Kind::Unsupported,
|
||||
},
|
||||
b"MPIN" => {
|
||||
// `SLnk` links the instance with the master spread it shows.
|
||||
let linked = s.obj(id, b"SLnk").map(|l| s.objs(l, b"ILOb")).unwrap_or_default();
|
||||
let master = linked.iter().find_map(|o| self.master_ids.iter().position(|m| m == o));
|
||||
let at = |t: &[u8; 4], default: usize| s.int(id, t).and_then(|v| usize::try_from(v).ok()).unwrap_or(default).min(4096);
|
||||
match master {
|
||||
Some(master) => Kind::MasterInstance { master, page: at(b"PgOf", 0), master_page: at(b"MPOf", 0), count: at(b"PgCt", 1) },
|
||||
None => {
|
||||
self.warn("master page instances without their master");
|
||||
Kind::Unsupported
|
||||
}
|
||||
}
|
||||
}
|
||||
b"EmbN" => match self.embedded_document(id, world) {
|
||||
// The embedded document itself, as editable content.
|
||||
Some(nodes) => {
|
||||
self.pending = Some(nodes);
|
||||
Kind::Group
|
||||
}
|
||||
None => match crate::raster::embedded(self, id, world)? {
|
||||
Some(img) => {
|
||||
self.warn("embedded documents and symbols (imported as pictures of them)");
|
||||
Kind::Image(img)
|
||||
}
|
||||
None => {
|
||||
self.warn("embedded documents and symbols without a cached picture");
|
||||
Kind::Unsupported
|
||||
}
|
||||
},
|
||||
},
|
||||
b"FRst" => {
|
||||
// A fill layer paints its whole bitmap area; its gradient lives in page space.
|
||||
let b = s.obj(id, b"Bitm");
|
||||
let size = |t: &[u8; 4]| b.and_then(|b| s.int(b, t)).map(|v| v as f64).filter(|v| *v > 0.0);
|
||||
match (size(b"BmpW"), size(b"BmpH")) {
|
||||
(Some(w), Some(h)) => {
|
||||
let local = Path { subpaths: vec![crate::shapes::rectangle(0.0, 0.0, w, h)] };
|
||||
let fills = paint::fills(self, id, parent, b"BFFl");
|
||||
Kind::Shape { path: local.transformed(world), fills, strokes: Vec::new(), even_odd: false }
|
||||
}
|
||||
_ => {
|
||||
self.warn("fill layers without an area");
|
||||
Kind::Unsupported
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.warn(format!("{} layers", describe(class)));
|
||||
Kind::Unsupported
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The enabled layer effects (`FiEf`) of node `id`. The angle convention was measured on the
|
||||
/// public MIT fx fixture (Patchy): an angle of π/2 with offset 10 shadows 10 below.
|
||||
fn effects(&mut self, id: ObjId, world: Affine, bounds: Option<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)"),
|
||||
}
|
||||
}
|
||||
for a in s.objs(id, b"AdCh") {
|
||||
if let Some(effect) = self.attached_recolor(a) {
|
||||
out.push(effect);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
fn attached_recolor(&mut self, a: ObjId) -> Option<Effect> {
|
||||
let s = self.s;
|
||||
if !s.is(a, b"RcRA") {
|
||||
return None;
|
||||
}
|
||||
if s.bool(a, b"Visi") == Some(false) {
|
||||
return None;
|
||||
}
|
||||
let adjp = s.obj(a, b"AdjP")?;
|
||||
if !s.is(adjp, b"RecP") {
|
||||
return None;
|
||||
}
|
||||
let h = s.f64(adjp, b"RecH").unwrap_or(0.0);
|
||||
let sat = s.f64(adjp, b"RecS").unwrap_or(1.0);
|
||||
let l = s.f64(adjp, b"RecL").unwrap_or(0.5);
|
||||
let (r, g, b) = crate::paint::hsl(h, sat, l);
|
||||
let color = crate::paint::Color::Rgb { r, g, b, a: 1.0 };
|
||||
let opacity = s.f64(a, b"Opac").filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0);
|
||||
let blend = self.effect_blend(a);
|
||||
Some(Effect::ColorOverlay { color, opacity, blend })
|
||||
}
|
||||
|
||||
/// A layer effect's blend mode (`BlnM`); unknown modes are Normal (warned).
|
||||
fn effect_blend(&mut self, e: ObjId) -> Blend {
|
||||
match self.s.enumeration(e, b"BlnM") {
|
||||
None => Blend::Normal,
|
||||
Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| {
|
||||
self.warn("an unknown blend mode (imported as Normal)");
|
||||
Blend::Normal
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Vector shapes attached to a node (`AdCh`) mask it: it shows only inside their outlines;
|
||||
/// an attached mask layer is a pixel mask. Adjustments attached the same way are reported.
|
||||
fn attached_masks(&mut self, id: ObjId, world: Affine, over: Option<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 if class == Tag::of(b"RcRA") {
|
||||
// Handled in `effects` as a colour overlay.
|
||||
} else {
|
||||
self.warn(format!("{} layers attached to other layers (imported without them)", describe(class)));
|
||||
}
|
||||
}
|
||||
Ok((mask, pixels))
|
||||
}
|
||||
|
||||
/// The content of an Affinity document embedded in this one (`EmbN` whose `EmbC` entry holds
|
||||
/// `EmDc`, four more bytes and a complete Affinity document): its first spread's nodes,
|
||||
/// placed so the centre of its page, first artboard or content is the node's origin.
|
||||
fn embedded_document(&mut self, id: ObjId, world: Affine) -> Option<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 }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod budget_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shared_work_is_bounded() {
|
||||
let mut b = Budget::FULL;
|
||||
assert!(b.spend(MAX_DOCUMENT_WORK).is_ok());
|
||||
assert_eq!(b.spend(1), Err(Error::Limit("too much shared geometry or page data")));
|
||||
}
|
||||
}
|
||||
@@ -1,675 +0,0 @@
|
||||
//! Colour and gradient overlays. VectorCraft has no such effect, so an overlay is baked into what
|
||||
//! its node paints: fill, stroke and text colours, and pixels. The overlay lies over the node's
|
||||
//! own paint in its blend mode at its opacity, inside the node's alpha (which it keeps).
|
||||
//!
|
||||
//! Blend modes follow the W3C Compositing and Blending formulas; the modes PDF lacks (Vivid
|
||||
//! Light, Linear Light, Pin Light, Hard Mix, Add, Subtract, Average, Negation, Reflect, Glow,
|
||||
//! Darker/Lighter Color) use their usual definitions.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::model::{Affine, Blend, Effect, Image, Kind, Node, Pixels, Point};
|
||||
use crate::paint::{Color, Gradient, GradientKind, Paint, Stop, Stroke};
|
||||
|
||||
/// Deepest subtree an overlay is baked into (the reader bounds trees well below this).
|
||||
const MAX_DEPTH: usize = 256;
|
||||
|
||||
/// Most pixels an overlay is baked into per image.
|
||||
const MAX_PIXELS: usize = 64 << 20;
|
||||
|
||||
/// Work the overlays of one import may take together: each overlay counts the nodes and pixels
|
||||
/// of the subtree it is baked into (which is copied once more for them all). Nested overlays
|
||||
/// and shared content would otherwise multiply it; past it, overlays are left out and said.
|
||||
pub const MAX_WORK: u64 = 1 << 29;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Source<'a> {
|
||||
Solid(Color),
|
||||
Gradient(&'a Gradient),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Overlay<'a> {
|
||||
source: Source<'a>,
|
||||
opacity: f64,
|
||||
blend: Blend,
|
||||
}
|
||||
|
||||
/// `node` with its colour and gradient overlays baked in, and those of everything in it
|
||||
/// (borrowed unchanged when `node` has none, or when what is left of `work`, see [`MAX_WORK`],
|
||||
/// can't pay for copying it). `warn` hears what could only be approximated or was left out.
|
||||
pub fn apply<'a>(node: &'a Node, work: &mut u64, warn: &mut dyn FnMut(&str)) -> Cow<'a, Node> {
|
||||
if overlays(&node.effects).is_empty() {
|
||||
return Cow::Borrowed(node);
|
||||
}
|
||||
let Some(left) = work.checked_sub(subtree_cost(node, *work, 0)) else {
|
||||
warn("overlay effects beyond the work one import may take (left out)");
|
||||
return Cow::Borrowed(node);
|
||||
};
|
||||
*work = left;
|
||||
let mut out = node.clone();
|
||||
bake_tree(&mut out, work, 0, warn);
|
||||
Cow::Owned(out)
|
||||
}
|
||||
|
||||
/// The visible colour and gradient overlays among `effects`.
|
||||
fn overlays(effects: &[Effect]) -> Vec<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, stop_reach(g))),
|
||||
None => return false,
|
||||
},
|
||||
Source::Solid(_) => None,
|
||||
};
|
||||
for (i, p) in px.as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||
if p[3] == 0 {
|
||||
continue;
|
||||
}
|
||||
let (s, sa) = match (solid, &to_unit) {
|
||||
(Some(s), _) => s,
|
||||
(None, Some((m, g, reach))) => {
|
||||
let q = m.apply(Point { x: (i % width) as f64 + 0.5, y: (i / width) as f64 + 0.5 });
|
||||
let c = sample(g, reach, q);
|
||||
(rgb(c), c.alpha())
|
||||
}
|
||||
(None, None) => continue,
|
||||
};
|
||||
let k = (o.opacity * sa).clamp(0.0, 1.0);
|
||||
let b = [p[0], p[1], p[2]].map(|v| f64::from(v) / 255.0);
|
||||
let m = blend(o.blend, b, s);
|
||||
for c in 0..3 {
|
||||
p[c] = ((b[c] + (m[c] - b[c]) * k).clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
}
|
||||
}
|
||||
img.pixels = Pixels::Rgba8(px);
|
||||
true
|
||||
}
|
||||
|
||||
/// An encoded original's RGBA pixels, decoded only if it is `width` × `height` as its layer says.
|
||||
fn decode(bytes: &[u8], width: u32, height: u32) -> Option<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())
|
||||
}
|
||||
|
||||
/// For each pair of neighbouring stops (`k`, `k + 1`), the largest offset of stops `1..=k + 1`:
|
||||
/// the first pair whose end offset a `t` doesn't pass is the first whose reach it doesn't pass, and
|
||||
/// reaches never decrease, so [`sample`] finds it by binary search, sorted stops or not.
|
||||
fn stop_reach(g: &Gradient) -> Vec<f64> {
|
||||
g.stops
|
||||
.iter()
|
||||
.skip(1)
|
||||
.scan(f64::NEG_INFINITY, |m, s| {
|
||||
*m = m.max(s.offset);
|
||||
Some(*m)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The gradient's colour at unit-space point `q` (`reach`: [`stop_reach`] of `g`).
|
||||
fn sample(g: &Gradient, reach: &[f64], q: Point) -> Color {
|
||||
let t = match g.kind {
|
||||
GradientKind::Linear => q.x,
|
||||
GradientKind::Radial => q.x.hypot(q.y),
|
||||
GradientKind::Conical => q.y.atan2(q.x).rem_euclid(std::f64::consts::TAU) / std::f64::consts::TAU,
|
||||
};
|
||||
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let (Some(first), Some(last)) = (g.stops.first(), g.stops.last()) else { return Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 0.0 } };
|
||||
if t <= first.offset {
|
||||
return first.color;
|
||||
}
|
||||
let k = reach.partition_point(|r| *r < t);
|
||||
if let (Some(a), Some(b)) = (g.stops.get(k), g.stops.get(k + 1)) {
|
||||
let span = b.offset - a.offset;
|
||||
let u = if span > 1e-9 { (t - a.offset) / span } else { 1.0 };
|
||||
// Affinity's midpoint bias (see `Stop::half_point`).
|
||||
let k = 1.0 + 8.0 * (a.bias - 0.5).abs();
|
||||
let u = if a.bias >= 0.5 { u.powf(k) } else { 1.0 - (1.0 - u).powf(k) };
|
||||
let (x, y) = (rgb(a.color), rgb(b.color));
|
||||
let [r, g, bl] = [0, 1, 2].map(|i| x[i] + (y[i] - x[i]) * u);
|
||||
return Color::Rgb { r, g, b: bl, a: a.color.alpha() + (b.color.alpha() - a.color.alpha()) * u };
|
||||
}
|
||||
last.color
|
||||
}
|
||||
|
||||
fn invert(m: Affine) -> Option<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:?}");
|
||||
}
|
||||
}
|
||||
@@ -1,403 +0,0 @@
|
||||
//! Fills, strokes and colours. Two schemas exist: Affinity 1 (`BFil` fill, `PFil` stroke paint,
|
||||
//! `LSty` stroke style) and Affinity 2/3 (`BFFl`, `LIFl` and `LILn` lists with a current index).
|
||||
|
||||
use crate::model::{Affine, Reader};
|
||||
use crate::stream::{ObjId, Value};
|
||||
|
||||
/// A colour as stored: RGB and grey values are encoded in the document's RGB space (sRGB unless
|
||||
/// the document embeds another profile), CMYK values go through its CMYK profile. Alpha is straight.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum Color {
|
||||
Rgb {
|
||||
r: f64,
|
||||
g: f64,
|
||||
b: f64,
|
||||
a: f64,
|
||||
},
|
||||
Cmyk {
|
||||
c: f64,
|
||||
m: f64,
|
||||
y: f64,
|
||||
k: f64,
|
||||
a: f64,
|
||||
},
|
||||
Gray {
|
||||
v: f64,
|
||||
a: f64,
|
||||
},
|
||||
/// CIE L*a*b* (D50).
|
||||
Lab {
|
||||
l: f64,
|
||||
a: f64,
|
||||
b: f64,
|
||||
alpha: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl Color {
|
||||
pub fn alpha(&self) -> f64 {
|
||||
match self {
|
||||
Color::Rgb { a, .. } | Color::Cmyk { a, .. } | Color::Gray { a, .. } => *a,
|
||||
Color::Lab { alpha, .. } => *alpha,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum GradientKind {
|
||||
Linear,
|
||||
/// Elliptical and radial: distance from the centre in unit space.
|
||||
Radial,
|
||||
/// Angle around the centre.
|
||||
Conical,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Stop {
|
||||
pub offset: f64,
|
||||
pub color: Color,
|
||||
/// Affinity's midpoint bias for the segment from this stop to the next (0.5 = even blend).
|
||||
pub bias: f64,
|
||||
}
|
||||
|
||||
impl Stop {
|
||||
/// Where, between this stop (0) and the next (1), the blend reaches half way: the bias curve
|
||||
/// fitted to Affinity's renders is `t^k` (bias ≥ 0.5) or `1-(1-t)^k`, with `k = 1 + 8·|bias-0.5|`.
|
||||
pub fn half_point(&self) -> f64 {
|
||||
let k = 1.0 + 8.0 * (self.bias - 0.5).abs();
|
||||
let h = 0.5f64.powf(1.0 / k);
|
||||
if self.bias >= 0.5 { h } else { 1.0 - h }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Gradient {
|
||||
pub kind: GradientKind,
|
||||
pub stops: Vec<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,
|
||||
/// The pressure curve: (position 0..1 along the path, width as a fraction of `width`) in
|
||||
/// order along the path, `None` for a stroke of the same width all along.
|
||||
pub profile: Option<Vec<(f64, f64)>>,
|
||||
}
|
||||
|
||||
/// Gradient stops per gradient.
|
||||
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;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn hsl(h: f64, s: f64, l: f64) -> (f64, f64, f64) {
|
||||
let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
|
||||
let hp = (h.rem_euclid(1.0)) * 6.0;
|
||||
let x = c * (1.0 - (hp % 2.0 - 1.0).abs());
|
||||
let (r, g, b) = match hp as u32 {
|
||||
0 => (c, x, 0.0),
|
||||
1 => (x, c, 0.0),
|
||||
2 => (0.0, c, x),
|
||||
3 => (0.0, x, c),
|
||||
4 => (x, 0.0, c),
|
||||
_ => (c, 0.0, x),
|
||||
};
|
||||
let m = l - c / 2.0;
|
||||
(r + m, g + m, b + m)
|
||||
}
|
||||
|
||||
/// A fill descriptor (`FDsc`) or, in Affinity 1 files, a bare `FilS`; `local` maps the node's
|
||||
/// space to document pixels.
|
||||
pub(crate) fn descriptor(r: &mut Reader, id: ObjId, local: Affine) -> Option<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");
|
||||
// Convert only the positions that pair with a colour, as shared attributes repeat this per run.
|
||||
let posn: &[Value] = match s.field(grad, b"Posn") {
|
||||
Some(Value::Array(a)) => a,
|
||||
_ => &[],
|
||||
};
|
||||
let mut stops = Vec::new();
|
||||
for (c, p) in cols.iter().zip(posn.iter().filter_map(floats)).take(MAX_STOPS) {
|
||||
let color = color(r, *c)?;
|
||||
let offset = p.first().copied().filter(|v| v.is_finite()).unwrap_or(0.0).clamp(0.0, 1.0);
|
||||
let bias = p.get(1).copied().filter(|v| v.is_finite()).unwrap_or(0.5).clamp(0.0, 1.0);
|
||||
stops.push(Stop { offset, color, bias });
|
||||
}
|
||||
if stops.is_empty() {
|
||||
return Some(Paint::None);
|
||||
}
|
||||
Some(Paint::Gradient(Gradient { kind, stops, transform: unit.then(local) }))
|
||||
}
|
||||
b"FilB" => {
|
||||
r.warn("bitmap and pattern fills (left empty)");
|
||||
Some(Paint::None)
|
||||
}
|
||||
_ => {
|
||||
r.warn("fills of an unknown kind (left empty)");
|
||||
Some(Paint::None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn current(r: &Reader, id: ObjId, list: &[u8; 4], index: &[u8; 4]) -> Option<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() {
|
||||
r.warn("brush strokes (imported as plain strokes)");
|
||||
}
|
||||
// The pressure curve sets the width along the path; one at full width all along is a plain
|
||||
// stroke. Every curve read counts against the document's points: one at full width counts its
|
||||
// points, and one that can't be read counts the most a curve may have. Once the points are
|
||||
// used up the rest are not read.
|
||||
const BEYOND: &str = "pressure strokes beyond the pressure points one document may hold (imported as plain strokes)";
|
||||
let ldep = s.obj(ldsc, b"LDeP");
|
||||
if ldep.is_some() && r.budget.pressure == 0 {
|
||||
r.warn(BEYOND);
|
||||
}
|
||||
let profile = match ldep.filter(|_| r.budget.pressure > 0).map(|p| crate::geometry::pressure(r, p)) {
|
||||
Some(Some(points)) => match r.budget.pressure.checked_sub(points.len()) {
|
||||
Some(left) => {
|
||||
r.budget.pressure = left;
|
||||
(!points.iter().all(|(_, w)| (w - 1.0).abs() < 1e-9)).then_some(points)
|
||||
}
|
||||
None => {
|
||||
r.budget.pressure = 0;
|
||||
r.warn(BEYOND);
|
||||
None
|
||||
}
|
||||
},
|
||||
Some(None) => {
|
||||
r.budget.pressure = r.budget.pressure.saturating_sub(crate::geometry::MAX_PRESSURE_CURVE_POINTS);
|
||||
r.warn("pressure strokes whose pressure curve can't be read (imported as plain strokes)");
|
||||
None
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Some(Stroke { paint, width, cap, join, miter_limit, align, dash, behind, profile })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hsl_lightness_1_is_white_and_0_is_black() {
|
||||
assert_eq!(hsl(0.0, 1.0, 1.0), (1.0, 1.0, 1.0));
|
||||
assert_eq!(hsl(0.5, 1.0, 1.0), (1.0, 1.0, 1.0));
|
||||
assert_eq!(hsl(0.0, 1.0, 0.0), (0.0, 0.0, 0.0));
|
||||
let (r, g, b) = hsl(0.0, 1.0, 0.5);
|
||||
assert!((r - 1.0).abs() < 1e-6 && g.abs() < 1e-6 && b.abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
//! The indexed PNG thumbnail Affinity stores next to the archive: Affinity's own render of the
|
||||
//! document, at most 512 pixels on the long side in real files, never the document itself.
|
||||
|
||||
use crate::Error;
|
||||
use crate::container::header;
|
||||
|
||||
pub const MAX_PREVIEW_BYTES: usize = 16 << 20;
|
||||
pub const MAX_PREVIEW_DIMENSION: u32 = 4096;
|
||||
|
||||
/// Borrowed embedded thumbnail, at its own dimensions, never the native document dimensions.
|
||||
#[derive(Debug)]
|
||||
pub struct Preview<'a> {
|
||||
pub png: &'a [u8],
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
fn bytes_at(bytes: &[u8], offset: usize, length: usize) -> Result<&[u8], Error> {
|
||||
let end = offset.checked_add(length).ok_or(Error::Malformed("offset overflow"))?;
|
||||
bytes.get(offset..end).ok_or(Error::Malformed("truncated record"))
|
||||
}
|
||||
|
||||
fn le32(bytes: &[u8], offset: usize) -> Result<u32, Error> {
|
||||
let b = bytes_at(bytes, offset, 4)?;
|
||||
Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::Malformed("integer"))?))
|
||||
}
|
||||
|
||||
fn be32(bytes: &[u8], offset: usize) -> Result<u32, Error> {
|
||||
let b = bytes_at(bytes, offset, 4)?;
|
||||
Ok(u32::from_be_bytes(b.try_into().map_err(|_| Error::Malformed("PNG integer"))?))
|
||||
}
|
||||
|
||||
/// Read only the indexed `Thmb` record (identical in container versions 8 to 12), checking every PNG chunk CRC. Compressed
|
||||
/// pixels must still be validated by the consuming image decoder, with allocation limits.
|
||||
pub fn preview(bytes: &[u8]) -> Result<Preview<'_>, Error> {
|
||||
let h = header(bytes)?;
|
||||
if h.thumbnail_offset == 0 {
|
||||
return Err(Error::Unsupported("no embedded preview"));
|
||||
}
|
||||
let offset = usize::try_from(h.thumbnail_offset).map_err(|_| Error::Malformed("thumbnail offset overflow"))?;
|
||||
if offset < 72 {
|
||||
return Err(Error::Malformed("thumbnail overlaps the file header"));
|
||||
}
|
||||
let record = bytes.get(offset..).ok_or(Error::Malformed("thumbnail offset outside file"))?;
|
||||
if bytes_at(record, 0, 8)? != b"\xff\xff\xff\xffThmb" {
|
||||
return Err(Error::Malformed("missing indexed thumbnail"));
|
||||
}
|
||||
if le32(record, 8)? != 1 || bytes_at(record, 28, 1)? != [1] {
|
||||
return Err(Error::Unsupported("thumbnail record version or encoding"));
|
||||
}
|
||||
let size = usize::try_from(le32(record, 24)?).map_err(|_| Error::Limit("encoded size"))?;
|
||||
if size > MAX_PREVIEW_BYTES {
|
||||
return Err(Error::Limit("encoded preview exceeds 16 MiB"));
|
||||
}
|
||||
if le32(record, 16)? != 29 || le32(record, 20)? != 0 || u64::from(le32(record, 12)?) != size as u64 + 13 {
|
||||
return Err(Error::Malformed("inconsistent thumbnail record lengths"));
|
||||
}
|
||||
let png = bytes_at(record, 29, size)?;
|
||||
if bytes_at(png, 0, 8)? != b"\x89PNG\r\n\x1a\n" || be32(png, 8)? != 13 || bytes_at(png, 12, 4)? != b"IHDR" {
|
||||
return Err(Error::Malformed("thumbnail is not a PNG"));
|
||||
}
|
||||
let width = be32(png, 16)?;
|
||||
let height = be32(png, 20)?;
|
||||
if width == 0 || height == 0 || width > MAX_PREVIEW_DIMENSION || height > MAX_PREVIEW_DIMENSION {
|
||||
return Err(Error::Limit("preview dimensions must be 1..4096"));
|
||||
}
|
||||
// Bound work by bytes, not a file-supplied chunk count, and require exactly one complete PNG.
|
||||
let mut pos = 8usize;
|
||||
let (mut palette, mut image_data, mut image_data_ended) = (false, false, false);
|
||||
loop {
|
||||
let length = usize::try_from(be32(png, pos)?).map_err(|_| Error::Limit("PNG chunk length"))?;
|
||||
let chunk_size = length.checked_add(12).ok_or(Error::Malformed("PNG chunk overflow"))?;
|
||||
let chunk = bytes_at(png, pos, chunk_size)?;
|
||||
let checksum_input = bytes_at(chunk, 4, chunk_size - 8)?;
|
||||
if crc32fast::hash(checksum_input) != be32(chunk, chunk_size - 4)? {
|
||||
return Err(Error::Malformed("PNG chunk checksum"));
|
||||
}
|
||||
let kind = bytes_at(chunk, 4, 4)?;
|
||||
if !kind.iter().all(u8::is_ascii_alphabetic) {
|
||||
return Err(Error::Malformed("PNG chunk type"));
|
||||
}
|
||||
match kind {
|
||||
b"IHDR" if pos == 8 => {}
|
||||
b"IHDR" => return Err(Error::Malformed("duplicate PNG header")),
|
||||
b"PLTE" => {
|
||||
if palette || image_data {
|
||||
return Err(Error::Malformed("PNG palette order"));
|
||||
}
|
||||
palette = true;
|
||||
}
|
||||
b"IDAT" => {
|
||||
if image_data_ended {
|
||||
return Err(Error::Malformed("non-contiguous PNG image data"));
|
||||
}
|
||||
image_data = true;
|
||||
}
|
||||
b"IEND" if !image_data => return Err(Error::Malformed("PNG has no image data")),
|
||||
b"IEND" => {}
|
||||
_ if kind.first().is_some_and(u8::is_ascii_uppercase) => {
|
||||
return Err(Error::Unsupported("unknown critical PNG chunk"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if image_data && kind != b"IDAT" {
|
||||
image_data_ended = true;
|
||||
}
|
||||
// Native sample previews are plain, single-frame PNGs. Pixel allocation limits do not
|
||||
// necessarily bound aggregate compressed metadata; leave these layouts unsupported.
|
||||
if matches!(kind, b"zTXt" | b"iTXt" | b"iCCP") {
|
||||
return Err(Error::Unsupported("compressed PNG metadata in the preview"));
|
||||
}
|
||||
if matches!(kind, b"acTL" | b"fcTL" | b"fdAT") {
|
||||
return Err(Error::Unsupported("animated PNG preview"));
|
||||
}
|
||||
pos = pos.checked_add(chunk_size).ok_or(Error::Malformed("PNG offset overflow"))?;
|
||||
if kind == b"IEND" {
|
||||
if length != 0 || pos != png.len() {
|
||||
return Err(Error::Malformed("PNG end or trailing data"));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(Preview { png, width, height })
|
||||
}
|
||||
@@ -1,650 +0,0 @@
|
||||
//! Pixel layers (`Rstr`) and placed images (`ImgN`). A placed image keeps its original file
|
||||
//! (`DyBm.Bckg` → archive entry `c/N`), which is imported as is; other pixels are planar tiles of
|
||||
//! 256 bytes × 256 rows per channel, each its own archive entry.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::Error;
|
||||
use crate::model::{Affine, Image, Pixels, Reader};
|
||||
use crate::stream::{self, ObjId, Tag, Value};
|
||||
|
||||
/// Pixels decoded per layer (the content's bounding box, not the canvas).
|
||||
const MAX_PIXELS: u64 = 64 << 20;
|
||||
const TILE: usize = 256;
|
||||
const TILE_BYTES: usize = TILE * TILE;
|
||||
|
||||
struct CachedPixels {
|
||||
tiles: HashMap<String, Vec<u8>>,
|
||||
source: Option<(usize, Vec<u8>)>,
|
||||
}
|
||||
|
||||
pub(crate) fn node_image(r: &mut Reader, id: ObjId, world: Affine) -> Result<Option<Image>, Error> {
|
||||
let s = r.s;
|
||||
let Some(bitmap) = s.obj(id, b"Bitm") else {
|
||||
r.warn("pixel layers without pixels");
|
||||
return Ok(None);
|
||||
};
|
||||
if !s.is(bitmap, b"DyBm") {
|
||||
r.warn("pixel layers stored in an unknown way");
|
||||
return Ok(None);
|
||||
}
|
||||
let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
if width == 0 || height == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
// A placed image: the original file, byte for byte.
|
||||
let has_tiles = s.field(bitmap, b"Sta1").is_some();
|
||||
if let Some(name) = s.entry(bitmap, b"Bckg").filter(|n| !n.is_empty())
|
||||
&& (s.is(id, b"ImgN") || !has_tiles)
|
||||
{
|
||||
match original(r, name) {
|
||||
// HEIF/HEIC (phone photos) and AVIF originals can't be decoded here: the same pixels
|
||||
// stored as tiles are used instead (see `decode` when the tiles point back at the original).
|
||||
Ok(bytes) if is_heif(&bytes) && has_tiles => {}
|
||||
Ok(bytes) => return Ok(Some(Image { width, height, pixels: Pixels::Encoded(bytes), transform: world })),
|
||||
Err(Error::Limit(e)) => return Err(Error::Limit(e)),
|
||||
Err(_) => r.warn("an embedded image file that could not be read (its cached pixels were used)"),
|
||||
}
|
||||
}
|
||||
// The content's bounding box, so a mostly empty canvas-sized layer stays small.
|
||||
let crop = s
|
||||
.field(id, b"BitR")
|
||||
.and_then(|v| if let Value::Ints(i) = v { Some(i.clone()) } else { None })
|
||||
.filter(|v| v.len() == 4 && v[0] > i64::from(i32::MIN) + 1)
|
||||
.map(|v| {
|
||||
(
|
||||
v[0].clamp(0, i64::from(width)) as u32,
|
||||
v[1].clamp(0, i64::from(height)) as u32,
|
||||
v[2].clamp(0, i64::from(width)) as u32,
|
||||
v[3].clamp(0, i64::from(height)) as u32,
|
||||
)
|
||||
})
|
||||
.unwrap_or((0, 0, width, height));
|
||||
let source_tiles_only =
|
||||
(1..=4).all(|c| matches!(s.field(bitmap, &tag(b"Sta", c)), Some(Value::Array(a)) if !a.is_empty() && a.iter().all(|v| *v == Value::UInt(5))));
|
||||
if s.field(bitmap, b"Bckg").is_some() && has_tiles && !source_tiles_only && !s.is(id, b"ImgN") {
|
||||
r.warn("edited placed images use their stored pixels");
|
||||
}
|
||||
decode(r, bitmap, crop, world)
|
||||
}
|
||||
|
||||
/// An ISO base media file holding a HEIF image (HEIC, AVIF): `ftyp` with an image brand.
|
||||
fn is_heif(bytes: &[u8]) -> bool {
|
||||
bytes.get(4..8) == Some(b"ftyp".as_slice())
|
||||
&& bytes.get(8..12).is_some_and(|brand| {
|
||||
[b"heic", b"heix", b"hevc", b"hevx", b"heim", b"heis", b"mif1", b"msf1", b"avif", b"avis"].iter().any(|b| brand == b.as_slice())
|
||||
})
|
||||
}
|
||||
|
||||
/// A mask layer (`MRst`): one channel of coverage as grey pixels (white shows, black hides), read
|
||||
/// over `over` (document pixels) when given; outside its pixels a mask hides everything.
|
||||
pub(crate) fn mask(r: &mut Reader, id: ObjId, world: Affine, over: Option<crate::model::Rect>) -> Result<Option<Image>, Error> {
|
||||
let s = r.s;
|
||||
let Some(bitmap) = s.obj(id, b"Bitm") else { return Ok(None) };
|
||||
let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
if width == 0 || height == 0 || !matches!(s.enumeration(bitmap, b"Frmt"), Some((6 | 7, _))) {
|
||||
r.warn("pixel masks in an unknown format (imported without them)");
|
||||
return Ok(None);
|
||||
}
|
||||
let crop = match over.map(|o| crop_to(o, world, width, height)) {
|
||||
Some(Some(c)) => c,
|
||||
// What it masks lies outside it: all hidden, which one black pixel says as well.
|
||||
Some(None) => return Ok(Some(Image { width: 1, height: 1, pixels: Pixels::Rgba8(vec![0, 0, 0, 255]), transform: world })),
|
||||
None => (0, 0, width, height),
|
||||
};
|
||||
decode(r, bitmap, crop, world)
|
||||
}
|
||||
|
||||
/// The bitmap pixels (x0, y0, x1, y1) of a `width` × `height` bitmap placed by `world` that cover
|
||||
/// document rectangle `over`, one pixel wider all round; `None` if they don't overlap.
|
||||
fn crop_to(over: crate::model::Rect, world: Affine, width: u32, height: u32) -> Option<(u32, u32, u32, u32)> {
|
||||
let inv = invert(world)?;
|
||||
let pts = [(over.x0, over.y0), (over.x1, over.y0), (over.x1, over.y1), (over.x0, over.y1)].map(|(x, y)| inv.apply(crate::model::Point { x, y }));
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
|
||||
for p in pts {
|
||||
if !(p.x.is_finite() && p.y.is_finite()) {
|
||||
return Some((0, 0, width, height));
|
||||
}
|
||||
(x0, y0, x1, y1) = (x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y));
|
||||
}
|
||||
let clamp = |v: f64, max: u32| v.clamp(0.0, f64::from(max)) as u32;
|
||||
let (cx0, cy0, cx1, cy1) =
|
||||
(clamp(x0.floor() - 1.0, width), clamp(y0.floor() - 1.0, height), clamp(x1.ceil() + 1.0, width), clamp(y1.ceil() + 1.0, height));
|
||||
(cx1 > cx0 && cy1 > cy0).then_some((cx0, cy0, cx1, cy1))
|
||||
}
|
||||
|
||||
fn invert(m: Affine) -> Option<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)]))
|
||||
}
|
||||
|
||||
/// An embedded document or symbol instance (`EmbN`), as the picture of it Affinity caches.
|
||||
pub(crate) fn embedded(r: &mut Reader, id: ObjId, world: Affine) -> Result<Option<Image>, Error> {
|
||||
let s = r.s;
|
||||
let Some(cache) = s.obj(id, b"Bitm").and_then(|e| s.obj(e, b"Cach")) else { return Ok(None) };
|
||||
let Some(bbox) = s.obj(id, b"Bitm").and_then(|e| s.floats::<4>(e, b"ChBB")) else { return Ok(None) };
|
||||
let width = s.int(cache, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
let height = s.int(cache, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
if width == 0 || height == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let [x0, y0, x1, y1] = bbox;
|
||||
// The instance's origin is the centre of the embedded content (checked against the
|
||||
// thumbnails of documents with embedded documents and SVG files).
|
||||
let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
|
||||
let place = Affine([(x1 - x0) / f64::from(width), 0.0, 0.0, (y1 - y0) / f64::from(height), x0 - cx, y0 - cy]).then(world);
|
||||
decode(r, cache, (0, 0, width, height), place)
|
||||
}
|
||||
|
||||
/// Decode the tiles of a bitmap inside `crop` (pixels), placed by `world` (bitmap pixels to document).
|
||||
fn decode(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affine) -> Result<Option<Image>, Error> {
|
||||
decode_within(r, bitmap, crop, world, MAX_PIXELS)
|
||||
}
|
||||
|
||||
/// [`decode`] with at most `max_pixels` decoded pixels.
|
||||
fn decode_within(r: &mut Reader, bitmap: ObjId, crop: (u32, u32, u32, u32), world: Affine, max_pixels: u64) -> Result<Option<Image>, Error> {
|
||||
let s = r.s;
|
||||
let (x0, y0, x1, y1) = crop;
|
||||
if x1 <= x0 || y1 <= y0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let (w, h) = (x1 - x0, y1 - y0);
|
||||
// Larger layers (mostly masks of whole spreads) are read at a half, a quarter… of their
|
||||
// resolution: every `step`th pixel of every `step`th row.
|
||||
let mut step = 1u32;
|
||||
while u64::from(w.div_ceil(step)) * u64::from(h.div_ceil(step)) > max_pixels {
|
||||
step *= 2;
|
||||
if step > 1 << 12 {
|
||||
r.warn("pixel layers too large to read (left out)");
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
// Before anything is allocated: a layer's tiles can be flat colour, with nothing to extract.
|
||||
let pixels = u64::from(w.div_ceil(step)) * u64::from(h.div_ceil(step));
|
||||
let Some(left) = r.budget.pixels.checked_sub(pixels) else {
|
||||
r.warn("pixel layers beyond the pixels one document may hold");
|
||||
return Ok(None);
|
||||
};
|
||||
r.budget.pixels = left;
|
||||
let format = s.enumeration(bitmap, b"Frmt").map(|(f, _)| f);
|
||||
let (channels, bps) = match format {
|
||||
Some(0) => (4, 1),
|
||||
Some(1) => (4, 2),
|
||||
Some(6) => (1, 1),
|
||||
Some(7) => (1, 2),
|
||||
Some(4) => (5, 1),
|
||||
_ => {
|
||||
r.warn("pixel layers in grey, Lab or 32-bit formats");
|
||||
return Ok(None);
|
||||
}
|
||||
};
|
||||
let mut planes = Vec::with_capacity(channels);
|
||||
// Current .af documents can keep level-zero tiles in their embedded JPEG/PNG instead of
|
||||
// duplicating the pixels. State 5 is checked in the public Patchy embedded-jpeg fixture.
|
||||
// Support only the observed, same-size RGBA8 image with a zero bitmap origin; other
|
||||
// representations still receive the existing loss warning rather than guessing a mapping.
|
||||
let needs_source = (1..=channels).any(|c| matches!(s.field(bitmap, &tag(b"Sta", c)), Some(Value::Array(a)) if a.contains(&Value::UInt(5))));
|
||||
let source = if needs_source && format == Some(0) && s.int(bitmap, b"LInf") == Some(0) && s.int(bitmap, b"TInf") == Some(0) {
|
||||
if let Some(name) = s.entry(bitmap, b"Bckg") {
|
||||
let width = s.int(bitmap, b"BmpW").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
let height = s.int(bitmap, b"BmpH").and_then(|v| u32::try_from(v).ok()).unwrap_or(0);
|
||||
// The whole source is decoded for every layer that reads it, so charge it all, not only the crop.
|
||||
let Some(left) = r.budget.pixels.checked_sub(u64::from(width) * u64::from(height)) else {
|
||||
return Err(Error::Limit("embedded image pixels"));
|
||||
};
|
||||
r.budget.pixels = left;
|
||||
match original(r, name).and_then(|bytes| source_pixels(&bytes, width, height)) {
|
||||
Ok(pixels) => Some((width as usize, pixels)),
|
||||
Err(Error::Limit(e)) => return Err(Error::Limit(e)),
|
||||
Err(_) => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Tiles kept only in an original that can't be decoded here are left empty (transparent). Where
|
||||
// a tile's colour is in the original but its alpha is stored, as in CMYK layers, it would come
|
||||
// out opaque white instead: such a layer (a HEIC photo in a CMYK document) is left out, and said.
|
||||
if needs_source && source.is_none() && channels > 1 {
|
||||
let states = |c: usize| match s.field(bitmap, &tag(b"Sta", c)) {
|
||||
Some(Value::Array(a)) => a.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let alpha = states(channels);
|
||||
let blank = (1..channels).any(|c| states(c).iter().enumerate().any(|(i, v)| *v == Value::UInt(5) && alpha.get(i) != Some(&Value::UInt(5))));
|
||||
if blank {
|
||||
r.warn("placed images whose pixels are only in an original the reader can't decode, such as HEIC photos (left out)");
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
if step > 1 {
|
||||
// Its stored tiles must fit what is left of the import's extraction budget.
|
||||
let stored: usize = (1..=channels).map(|c| tiles_in(s, bitmap, c, bps, (x0, y0, w, h)).len()).sum();
|
||||
if stored.saturating_mul(TILE_BYTES) > r.archive.remaining().max_total {
|
||||
r.warn("pixel layers too large to read (left out)");
|
||||
return Ok(None);
|
||||
}
|
||||
r.warn("pixel layers larger than 64 megapixels (read at a lower resolution)");
|
||||
}
|
||||
let mut cache = CachedPixels { tiles: HashMap::new(), source };
|
||||
for c in 1..=channels {
|
||||
planes.push(plane(r, bitmap, c, bps, (x0, y0, w, h), step, &mut cache)?);
|
||||
}
|
||||
let (w, h) = (w.div_ceil(step), h.div_ceil(step));
|
||||
let n = (w as usize) * (h as usize);
|
||||
let k = f64::from(step);
|
||||
let transform = Affine([k, 0.0, 0.0, k, f64::from(x0), f64::from(y0)]).then(world);
|
||||
if channels == 5 {
|
||||
// Ink amounts and alpha as stored (8 bits), interleaved.
|
||||
let mut cmyka = vec![0u8; n * 5];
|
||||
for (i, px) in cmyka.as_chunks_mut::<5>().0.iter_mut().enumerate() {
|
||||
for (c, v) in px.iter_mut().enumerate() {
|
||||
*v = planes.get(c).and_then(|p| p.get(i)).copied().unwrap_or(0);
|
||||
}
|
||||
}
|
||||
return Ok(Some(Image { width: w, height: h, pixels: Pixels::Cmyka8(cmyka), transform }));
|
||||
}
|
||||
let mut rgba = vec![0u8; n * 4];
|
||||
let sample = |p: &Vec<u8>, i: usize| -> f64 {
|
||||
if bps == 2 {
|
||||
f64::from(u16::from_le_bytes([p.get(2 * i).copied().unwrap_or(0), p.get(2 * i + 1).copied().unwrap_or(0)])) / 65535.0
|
||||
} else {
|
||||
f64::from(p.get(i).copied().unwrap_or(0)) / 255.0
|
||||
}
|
||||
};
|
||||
for (i, px) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||
let v: Vec<f64> = planes.iter().map(|p| sample(p, i)).collect();
|
||||
let (r2, g, b, a) = if channels == 1 { (v[0], v[0], v[0], 1.0) } else { (v[0], v[1], v[2], v[3]) };
|
||||
px.copy_from_slice(&[r2, g, b, a].map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8));
|
||||
}
|
||||
Ok(Some(Image { width: w, height: h, pixels: Pixels::Rgba8(rgba), transform }))
|
||||
}
|
||||
|
||||
/// The original image file: entry `c/N` is a stream whose root (`Blck`) holds it as `Data`.
|
||||
fn original(r: &mut Reader, name: &str) -> Result<Vec<u8>, Error> {
|
||||
let bytes = r.archive.read(name)?;
|
||||
let s = stream::parse(&bytes)?;
|
||||
let root = s.object(s.root).ok_or(Error::Malformed("embedded image"))?;
|
||||
match root.get(Tag::of(b"Data")) {
|
||||
Some(Value::Blob(b)) if !b.is_empty() => Ok(b.clone()),
|
||||
_ => Err(Error::Malformed("embedded image without data")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode the source under the same pixel budget as tiled layers, checking its actual
|
||||
/// dimensions before allocating decoded pixels. Only JPEG and PNG sources are supported.
|
||||
fn source_pixels(bytes: &[u8], width: u32, height: u32) -> Result<Vec<u8>, Error> {
|
||||
use image::{ImageFormat, ImageReader};
|
||||
use std::io::Cursor;
|
||||
|
||||
if u64::from(width) * u64::from(height) > MAX_PIXELS {
|
||||
return Err(Error::Limit("embedded image pixels"));
|
||||
}
|
||||
let mut reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|_| Error::Malformed("embedded image format"))?;
|
||||
if !matches!(reader.format(), Some(ImageFormat::Jpeg | ImageFormat::Png)) {
|
||||
return Err(Error::Unsupported("embedded source pixel format"));
|
||||
}
|
||||
let dimensions = ImageReader::new(Cursor::new(bytes))
|
||||
.with_guessed_format()
|
||||
.map_err(|_| Error::Malformed("embedded image format"))?
|
||||
.into_dimensions()
|
||||
.map_err(|_| Error::Malformed("embedded image dimensions"))?;
|
||||
if dimensions != (width, height) || width == 0 || height == 0 {
|
||||
return Err(Error::Malformed("embedded source and bitmap dimensions differ"));
|
||||
}
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_image_width = Some(width);
|
||||
limits.max_image_height = Some(height);
|
||||
limits.max_alloc = Some(MAX_PIXELS * 8);
|
||||
reader.limits(limits);
|
||||
let decoded = reader.decode().map_err(|e| match e {
|
||||
image::ImageError::Limits(_) => Error::Limit("embedded image decoding"),
|
||||
_ => Error::Malformed("embedded image decoding"),
|
||||
})?;
|
||||
Ok(decoded.into_rgba8().into_raw())
|
||||
}
|
||||
|
||||
fn tag(prefix: &[u8; 3], c: usize) -> [u8; 4] {
|
||||
[prefix[0], prefix[1], prefix[2], b'0' + c as u8]
|
||||
}
|
||||
|
||||
/// Channel `c`'s tile grid: (tiles across, tiles down, each tile's state).
|
||||
fn grid(s: &stream::Stream, bitmap: ObjId, c: usize, bps: usize) -> (usize, usize, Vec<u8>) {
|
||||
let width = s.int(bitmap, b"BmpW").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
|
||||
let height = s.int(bitmap, b"BmpH").and_then(|v| usize::try_from(v).ok()).unwrap_or(0);
|
||||
let tw = s.int(bitmap, &tag(b"TWi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| width.saturating_mul(bps).div_ceil(TILE));
|
||||
let th = s.int(bitmap, &tag(b"THi", c)).and_then(|v| usize::try_from(v).ok()).unwrap_or_else(|| height.div_ceil(TILE));
|
||||
// A grid larger than the bitmap has tiles no crop can reach: don't convert or scan them on every reference.
|
||||
let tiles = width.saturating_mul(bps).div_ceil(TILE).saturating_mul(height.div_ceil(TILE));
|
||||
let states: Vec<u8> = match s.field(bitmap, &tag(b"Sta", c)) {
|
||||
Some(Value::Array(a)) => a.iter().take(tiles).map(|v| if let Value::UInt(u) = v { u8::try_from(*u).unwrap_or(255) } else { 255 }).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
(tw, th, states)
|
||||
}
|
||||
|
||||
/// The stored tiles (state 4) of channel `c` that overlap the crop, by their index in `Idx`.
|
||||
fn tiles_in(s: &stream::Stream, bitmap: ObjId, c: usize, bps: usize, (x0, y0, w, h): (u32, u32, u32, u32)) -> Vec<usize> {
|
||||
let (tw, th, states) = grid(s, bitmap, c, bps);
|
||||
let (bx0, bx1) = (x0 as usize * bps, (x0 + w) as usize * bps);
|
||||
let (py0, py1) = (y0 as usize, (y0 + h) as usize);
|
||||
let mut out = Vec::new();
|
||||
let mut next = 0usize;
|
||||
for (t, state) in states.iter().enumerate().take(tw.saturating_mul(th)) {
|
||||
if *state != 4 {
|
||||
continue;
|
||||
}
|
||||
let (ox, oy) = ((t % tw.max(1)) * TILE, (t / tw.max(1)) * TILE);
|
||||
if !(ox >= bx1 || ox + TILE <= bx0 || oy >= py1 || oy + TILE <= py0) {
|
||||
out.push(next);
|
||||
}
|
||||
next += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One channel of level 0, cropped to (x0, y0, w, h) pixels and taking every `step`th pixel of
|
||||
/// every `step`th row; `bps` bytes per sample.
|
||||
fn plane(
|
||||
r: &mut Reader,
|
||||
bitmap: ObjId,
|
||||
c: usize,
|
||||
bps: usize,
|
||||
(x0, y0, w, h): (u32, u32, u32, u32),
|
||||
step: u32,
|
||||
cache: &mut CachedPixels,
|
||||
) -> Result<Vec<u8>, Error> {
|
||||
let CachedPixels { tiles: cache, source } = cache;
|
||||
let s = r.s;
|
||||
let (tw, th, states) = grid(s, bitmap, c, bps);
|
||||
let tiles = s.objs(bitmap, &tag(b"Idx", c));
|
||||
let at = Crop { bps, x0: x0 as usize, y0: y0 as usize, w: w as usize, h: h as usize, step: step.max(1) as usize };
|
||||
let row = at.w.div_ceil(at.step) * bps;
|
||||
let mut out = vec![0u8; row * at.h.div_ceil(at.step)];
|
||||
let (bx0, bx1) = (x0 as usize * bps, (x0 + w) as usize * bps);
|
||||
let (py0, py1) = (y0 as usize, (y0 + h) as usize);
|
||||
let mut next = 0usize;
|
||||
for (t, state) in states.iter().enumerate().take(tw.saturating_mul(th)) {
|
||||
let (ty, tx) = (t / tw.max(1), t % tw.max(1));
|
||||
let fill = match state {
|
||||
0 | 1 => None,
|
||||
2 => Some(0xFF),
|
||||
4 => {
|
||||
let Some(blck) = tiles.get(next).copied() else { return Err(Error::Malformed("missing pixel tile")) };
|
||||
next += 1;
|
||||
let (ox, oy) = (tx * TILE, ty * TILE);
|
||||
if ox >= bx1 || ox + TILE <= bx0 || oy >= py1 || oy + TILE <= py0 {
|
||||
continue;
|
||||
}
|
||||
let name = s.entry(blck, b"Data").ok_or(Error::Malformed("pixel tile without data"))?.to_string();
|
||||
let read = |r: &mut Reader| -> Result<Vec<u8>, Error> {
|
||||
let mut data = r.archive.read(&name)?;
|
||||
// Older files wrap a tile in a one-field stream: header, then a 64 KiB blob.
|
||||
if data.len() == TILE_BYTES + 22 && data.starts_with(b"\x00\xffKS") {
|
||||
data = data.get(21..21 + TILE_BYTES).ok_or(Error::Malformed("pixel tile"))?.to_vec();
|
||||
}
|
||||
if data.len() != TILE_BYTES {
|
||||
return Err(Error::Malformed("pixel tile size"));
|
||||
}
|
||||
Ok(data)
|
||||
};
|
||||
// A layer read at a lower resolution is too large to keep its tiles around.
|
||||
if at.step > 1 {
|
||||
let tile = read(r)?;
|
||||
copy(&mut out, &at, (ox, oy), |x, y| tile.get(y * TILE + x).copied().unwrap_or(0));
|
||||
continue;
|
||||
}
|
||||
if !cache.contains_key(&name) {
|
||||
let data = read(r)?;
|
||||
cache.insert(name.clone(), data);
|
||||
}
|
||||
let tile = cache.get(&name).ok_or(Error::Malformed("pixel tile"))?;
|
||||
copy(&mut out, &at, (ox, oy), |x, y| tile.get(y * TILE + x).copied().unwrap_or(0));
|
||||
continue;
|
||||
}
|
||||
3 => {
|
||||
r.warn("32-bit pixel layers");
|
||||
None
|
||||
}
|
||||
5 => {
|
||||
if let Some((source_width, pixels)) = source.as_ref() {
|
||||
let (ox, oy) = (tx * TILE, ty * TILE);
|
||||
copy(&mut out, &at, (ox, oy), |x, y| pixels.get(((oy + y) * source_width + ox + x) * 4 + c - 1).copied().unwrap_or(0));
|
||||
continue;
|
||||
}
|
||||
r.warn("pixel layers drawn from an embedded image (left empty)");
|
||||
None
|
||||
}
|
||||
_ => return Err(Error::Malformed("unknown pixel tile state")),
|
||||
};
|
||||
if let Some(v) = fill {
|
||||
copy(&mut out, &at, (tx * TILE, ty * TILE), |_, _| v);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Where a plane's pixels come from: the crop (pixels) and the sampling step.
|
||||
struct Crop {
|
||||
bps: usize,
|
||||
x0: usize,
|
||||
y0: usize,
|
||||
w: usize,
|
||||
h: usize,
|
||||
step: usize,
|
||||
}
|
||||
|
||||
/// Copy the overlap of a tile at byte column `ox`, row `oy` into the cropped plane, keeping every
|
||||
/// `step`th pixel of every `step`th row.
|
||||
fn copy(out: &mut [u8], c: &Crop, (ox, oy): (usize, usize), at: impl Fn(usize, usize) -> u8) {
|
||||
let row = c.w.div_ceil(c.step) * c.bps;
|
||||
let (bx0, bx1) = (c.x0 * c.bps, (c.x0 + c.w) * c.bps);
|
||||
for y in oy.max(c.y0)..(oy + TILE).min(c.y0 + c.h) {
|
||||
if !(y - c.y0).is_multiple_of(c.step) {
|
||||
continue;
|
||||
}
|
||||
let out_row = (y - c.y0) / c.step * row;
|
||||
for x in ox.max(bx0)..(ox + TILE).min(bx1) {
|
||||
let px = x / c.bps - c.x0;
|
||||
if !px.is_multiple_of(c.step) {
|
||||
continue;
|
||||
}
|
||||
if let Some(b) = out.get_mut(out_row + px / c.step * c.bps + x % c.bps) {
|
||||
*b = at(x - ox, y - oy);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::Kind;
|
||||
use crate::synth::{self, F, Method, tag};
|
||||
|
||||
#[test]
|
||||
fn heif_originals_are_recognised_by_their_brand() {
|
||||
assert!(is_heif(b"\0\0\0\x18ftypheic\0\0\0\0"));
|
||||
assert!(is_heif(b"\0\0\0\x1cftypavif"));
|
||||
assert!(!is_heif(b"\0\0\0\x18ftypisom"), "a video is not a photo");
|
||||
assert!(!is_heif(&png()));
|
||||
assert!(!is_heif(b"ftyp"));
|
||||
}
|
||||
|
||||
fn png() -> Vec<u8> {
|
||||
let pixels = image::RgbaImage::from_fn(300, 2, |x, y| image::Rgba([(x % 251) as u8, (y * 31) as u8, 77, 255]));
|
||||
let mut bytes = std::io::Cursor::new(Vec::new());
|
||||
pixels.write_to(&mut bytes, image::ImageFormat::Png).unwrap();
|
||||
bytes.into_inner()
|
||||
}
|
||||
|
||||
/// An original synthetic mixed source/cache bitmap. It exercises reader recovery,
|
||||
/// not a claim that Affinity itself accepts the synthetic container.
|
||||
fn fixture(source: &[u8], origin: i32) -> Vec<u8> {
|
||||
fixture_in(source, origin, false)
|
||||
}
|
||||
|
||||
/// `cmyk`: a CMYK bitmap whose colour tiles are all in the source and whose alpha is stored.
|
||||
fn fixture_in(source: &[u8], origin: i32, cmyk: bool) -> Vec<u8> {
|
||||
let channels = if cmyk { 5 } else { 4 };
|
||||
let mut bitmap = vec![
|
||||
(tag(b"Frmt"), F::Enum(if cmyk { 4 } else { 0 }, 0)),
|
||||
(tag(b"BmpW"), F::I32(300)),
|
||||
(tag(b"BmpH"), F::I32(2)),
|
||||
(tag(b"LInf"), F::I32(origin)),
|
||||
(tag(b"TInf"), F::I32(0)),
|
||||
(tag(b"Bckg"), F::Entry("c/1".into())),
|
||||
];
|
||||
for c in 1..=channels {
|
||||
let states = match (cmyk, c) {
|
||||
(false, _) => vec![5, 4],
|
||||
(true, 5) => vec![4, 4],
|
||||
(true, _) => vec![5, 5],
|
||||
};
|
||||
bitmap.push((tag(&super::tag(b"TWi", c)), F::I32(2)));
|
||||
bitmap.push((tag(&super::tag(b"THi", c)), F::I32(1)));
|
||||
bitmap.push((tag(&super::tag(b"Sta", c)), F::U8s(states)));
|
||||
bitmap.push((
|
||||
tag(&super::tag(b"Idx", c)),
|
||||
F::Shared(vec![F::Def(c as u32, vec![tag(b"Blck")], vec![(tag(b"Data"), F::Entry(format!("d/{c}")))])]),
|
||||
));
|
||||
}
|
||||
let mut crop = vec![0x17];
|
||||
crop.extend(tag(b"BitR").0.to_le_bytes());
|
||||
crop.extend([250i32, 0, 270, 2].into_iter().flat_map(i32::to_le_bytes));
|
||||
let raster = F::Def(
|
||||
10,
|
||||
vec![tag(b"Rstr")],
|
||||
vec![
|
||||
(tag(b"Bitm"), F::Obj(tag(b"DyBm"), bitmap)),
|
||||
(tag(b"BitR"), F::Raw(crop)),
|
||||
(tag(b"Xfrm"), F::F64s(vec![0.0, -2.0, 10.0, 2.0, 0.0, 20.0])),
|
||||
],
|
||||
);
|
||||
let spread = F::Def(11, vec![tag(b"Sprd")], vec![(tag(b"Chld"), F::Shared(vec![raster]))]);
|
||||
let doc = synth::stream(&[(tag(b"DocR"), F::Obj(tag(b"DocN"), vec![(tag(b"Chld"), F::Shared(vec![spread]))]))]);
|
||||
let mut blob = vec![0x2d];
|
||||
blob.extend(tag(b"Data").0.to_le_bytes());
|
||||
blob.extend((source.len() as u32).to_le_bytes());
|
||||
blob.extend(source);
|
||||
let block = synth::stream(&[(tag(b"Data"), F::Raw(blob))]);
|
||||
let tiles: Vec<_> = [200u8, 10, 30, 255, 255].into_iter().map(|v| vec![v; TILE_BYTES]).collect();
|
||||
let names: Vec<String> = (1..=channels).map(|c| format!("d/{c}")).collect();
|
||||
let mut entries = vec![("doc.dat", doc.as_slice(), Method::Zlib), ("c/1", block.as_slice(), Method::Zlib)];
|
||||
for (name, tile) in names.iter().zip(&tiles) {
|
||||
entries.push((name.as_str(), tile.as_slice(), Method::Zlib));
|
||||
}
|
||||
synth::container(&entries, None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmyk_layer_whose_colours_are_only_in_an_unreadable_original_is_left_out_not_white() {
|
||||
let doc = crate::read(&fixture_in(b"\0\0\0\x18ftypheic not decodable", 0, true), crate::Limits::default()).unwrap();
|
||||
assert!(doc.warnings.iter().any(|w| w.starts_with("placed images whose pixels are only in an original")), "{:?}", doc.warnings);
|
||||
assert!(matches!(doc.spreads[0].nodes[0].kind, Kind::Unsupported), "{:?}", doc.spreads[0].nodes[0].kind);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_over_the_pixel_budget_are_read_at_a_lower_resolution() {
|
||||
let bytes = fixture(&png(), 0);
|
||||
let mut archive = crate::Archive::open(&bytes, crate::Limits::default()).unwrap();
|
||||
let doc = archive.read("doc.dat").unwrap();
|
||||
let s = stream::parse(&doc).unwrap();
|
||||
let bitmap = s.objects.iter().position(|o| o.class == Tag::of(b"DyBm")).unwrap();
|
||||
let mut r = Reader::new(&s, &mut archive, Affine::IDENTITY, 0);
|
||||
// 20 × 2 pixels over a budget of 10: every other pixel of every other row.
|
||||
let image = decode_within(&mut r, bitmap, (250, 0, 270, 2), Affine::IDENTITY, 10).unwrap().unwrap();
|
||||
assert_eq!((image.width, image.height), (10, 1));
|
||||
assert_eq!(image.transform, Affine([2.0, 0.0, 0.0, 2.0, 250.0, 0.0]), "each pixel covers two");
|
||||
let Pixels::Rgba8(pixels) = &image.pixels else { panic!() };
|
||||
for x in 0..10 {
|
||||
let sx = 2 * x;
|
||||
let expected = if sx + 250 < 256 { [((sx + 250) % 251) as u8, 0, 77, 255] } else { [200, 10, 30, 255] };
|
||||
assert_eq!(&pixels[x * 4..x * 4 + 4], &expected, "pixel {x}");
|
||||
}
|
||||
assert!(r.warnings.contains_key("pixel layers larger than 64 megapixels (read at a lower resolution)"));
|
||||
// Within budget, nothing changes.
|
||||
let image = decode_within(&mut r, bitmap, (250, 0, 270, 2), Affine::IDENTITY, 40).unwrap().unwrap();
|
||||
assert_eq!((image.width, image.height), (20, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_tiles_and_cached_edits_survive_crop_rotation_and_tile_boundaries() {
|
||||
let doc = crate::read(&fixture(&png(), 0), crate::Limits::default()).unwrap();
|
||||
assert_eq!(doc.warnings, ["edited placed images use their stored pixels"]);
|
||||
let Kind::Image(image) = &doc.spreads[0].nodes[0].kind else { panic!() };
|
||||
assert_eq!((image.width, image.height), (20, 2));
|
||||
assert_eq!(image.transform, Affine([0.0, 2.0, -2.0, 0.0, 10.0, 520.0]));
|
||||
let Pixels::Rgba8(pixels) = &image.pixels else { panic!() };
|
||||
for y in 0..2 {
|
||||
for x in 0..20 {
|
||||
let expected = if x + 250 < 256 { [((x + 250) % 251) as u8, (y * 31) as u8, 77, 255] } else { [200, 10, 30, 255] };
|
||||
assert_eq!(&pixels[(y * 20 + x) * 4..(y * 20 + x + 1) * 4], &expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_sources_and_unknown_origins_preserve_cached_edits_and_warn() {
|
||||
for bytes in [fixture(b"invalid image", 0), fixture(&png(), 1)] {
|
||||
let doc = crate::read(&bytes, crate::Limits::default()).unwrap();
|
||||
assert!(doc.warnings.iter().any(|w| w == "pixel layers drawn from an embedded image (left empty) (4×)"));
|
||||
let Kind::Image(image) = &doc.spreads[0].nodes[0].kind else { panic!() };
|
||||
let Pixels::Rgba8(pixels) = &image.pixels else { panic!() };
|
||||
assert_eq!(&pixels[..4], &[0, 0, 0, 0]);
|
||||
assert_eq!(&pixels[6 * 4..7 * 4], &[200, 10, 30, 255]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pixel layers of one flat colour: nothing in the archive but `doc.dat` (state 2 is a tile
|
||||
/// of 0xFF). Written by hand for the reader, like [`fixture`].
|
||||
fn flat_layers(count: u32, side: i32) -> Vec<u8> {
|
||||
let layer = |i: u32| {
|
||||
let mut bitmap = vec![(tag(b"Frmt"), F::Enum(0, 0)), (tag(b"BmpW"), F::I32(side)), (tag(b"BmpH"), F::I32(side))];
|
||||
for c in 1..=4 {
|
||||
bitmap.push((tag(&super::tag(b"TWi", c)), F::I32(1)));
|
||||
bitmap.push((tag(&super::tag(b"THi", c)), F::I32(1)));
|
||||
bitmap.push((tag(&super::tag(b"Sta", c)), F::U8s(vec![2])));
|
||||
}
|
||||
F::Def(10 + i, vec![tag(b"Rstr")], vec![(tag(b"Bitm"), F::Obj(tag(b"DyBm"), bitmap))])
|
||||
};
|
||||
let spread = F::Def(1, vec![tag(b"Sprd")], vec![(tag(b"Chld"), F::Shared((0..count).map(layer).collect()))]);
|
||||
let doc = synth::stream(&[(tag(b"DocR"), F::Obj(tag(b"DocN"), vec![(tag(b"Chld"), F::Shared(vec![spread]))]))]);
|
||||
synth::container(&[("doc.dat", &doc, Method::Zlib)], None)
|
||||
}
|
||||
|
||||
/// #1704: the pixels of all pixel layers together are bounded, also when the archive holds
|
||||
/// no data for them: the layers past the allowance are left out with a note.
|
||||
#[test]
|
||||
fn pixel_layers_share_one_allowance_for_the_whole_document() {
|
||||
let file = flat_layers(5, 16);
|
||||
let layers = |pixels: u64| {
|
||||
let doc = crate::model::read_within(&file, crate::Limits::default(), pixels).unwrap();
|
||||
let n = doc.spreads[0].nodes.iter().filter(|n| matches!(n.kind, Kind::Image(_))).count();
|
||||
(n, doc.warnings)
|
||||
};
|
||||
assert_eq!(layers(5 * 256), (5, vec![]));
|
||||
let (kept, warnings) = layers(3 * 256 + 255);
|
||||
assert_eq!(kept, 3);
|
||||
assert_eq!(warnings.len(), 1);
|
||||
assert!(warnings[0].contains("pixel layers beyond the pixels one document may hold"), "{warnings:?}");
|
||||
assert_eq!(crate::read(&file, crate::Limits::default()).unwrap().spreads[0].nodes.len(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_source_dimensions_and_pixel_budget_are_checked_before_decode() {
|
||||
let bytes = png();
|
||||
assert!(matches!(source_pixels(&bytes, 299, 2), Err(Error::Malformed(_))));
|
||||
assert!(matches!(source_pixels(&bytes, u32::MAX, u32::MAX), Err(Error::Limit(_))));
|
||||
assert_eq!(source_pixels(&bytes, 300, 2).unwrap().len(), 300 * 2 * 4);
|
||||
}
|
||||
}
|
||||
@@ -1,292 +0,0 @@
|
||||
//! Parametric shapes: Affinity stores the shape's parameters and its box, never the outline.
|
||||
//! Formulas were fitted to Affinity's own renders (the document thumbnails) of public files.
|
||||
|
||||
use std::f64::consts::{FRAC_PI_2, PI, TAU};
|
||||
|
||||
use crate::model::{Affine, Path, Point, Reader, SubPath};
|
||||
use crate::stream::{ObjId, Tag, Value};
|
||||
|
||||
/// Handle length of a quarter circle of radius 1.
|
||||
const KAPPA: f64 = 0.552_284_749_830_793_4;
|
||||
/// Vertices of a polygon or star.
|
||||
const MAX_SIDES: i64 = 10_000;
|
||||
|
||||
/// The last value of a tag: a shape changed from one kind to another keeps a stale first block.
|
||||
fn last<'a>(r: &'a Reader, id: ObjId, tag: &[u8; 4]) -> Option<&'a Value> {
|
||||
r.s.object(id)?.get_last(Tag::of(tag))
|
||||
}
|
||||
|
||||
fn num(r: &Reader, id: ObjId, tag: &[u8; 4]) -> Option<f64> {
|
||||
match last(r, id, tag)? {
|
||||
Value::Float(f) if f.is_finite() => Some(*f),
|
||||
Value::UInt(u) => Some(*u as f64),
|
||||
Value::Int(i) => Some(*i as f64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn sides(r: &Reader, id: ObjId, tag: &[u8; 4], default: f64) -> usize {
|
||||
let n = num(r, id, tag).unwrap_or(default).round();
|
||||
n.clamp(3.0, MAX_SIDES as f64) as usize
|
||||
}
|
||||
|
||||
fn pt(x: f64, y: f64) -> Point {
|
||||
Point { x, y }
|
||||
}
|
||||
|
||||
fn polygon(pts: impl IntoIterator<Item = Point>) -> Option<SubPath> {
|
||||
let mut it = pts.into_iter();
|
||||
let start = it.next()?;
|
||||
let segments = it.map(|p| [p, p, p]).collect();
|
||||
Some(SubPath { start, segments, closed: true })
|
||||
}
|
||||
|
||||
/// Outline of `shape` (a `Shpe` object) in the node box `b` = (x0, y0, x1, y1).
|
||||
pub(crate) fn shape(r: &mut Reader, shape: ObjId, b: [f64; 4], world: Affine) -> Option<Path> {
|
||||
let [x0, y0, x1, y1] = b;
|
||||
let (w, h) = (x1 - x0, y1 - y0);
|
||||
let (cx, cy, rx, ry) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, w / 2.0, h / 2.0);
|
||||
let on_ellipse = |a: f64, f: f64| pt(cx + f * rx * a.cos(), cy + f * ry * a.sin());
|
||||
let class = r.s.class(shape)?;
|
||||
let sub = match &class.0.to_be_bytes() {
|
||||
b"ShNR" | b"ShRR" => {
|
||||
// Only the four corners' entries can matter: longer arrays are read no further.
|
||||
let types: Vec<Option<u16>> = match last(r, shape, b"CTyp") {
|
||||
Some(Value::Array(a)) => a.iter().take(4).map(|t| if let Value::Enum { id, .. } = t { Some(*id) } else { None }).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let radii: Vec<f64> = match last(r, shape, b"ShCR") {
|
||||
Some(Value::Floats(v)) => v.iter().take(4).map(|f| if f.is_finite() && *f > 0.0 { *f } else { 0.0 }).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
// Corners follow the first one (top left) unless they were unlocked; then each has
|
||||
// its own radius and type, clockwise from the top left.
|
||||
let locked = !matches!(last(r, shape, b"Lock"), Some(Value::Bool(false)));
|
||||
let corners: [(f64, Option<u16>); 4] = std::array::from_fn(|i| {
|
||||
let i = if locked { 0 } else { i };
|
||||
(radii.get(i).copied().unwrap_or(0.0), types.get(i).copied().flatten())
|
||||
});
|
||||
if types.is_empty() || corners.iter().all(|(f, _)| *f == 0.0) {
|
||||
polygon([pt(x0, y0), pt(x1, y0), pt(x1, y1), pt(x0, y1)])?
|
||||
} else {
|
||||
if corners.iter().any(|(f, t)| *f > 0.0 && !matches!(t, Some(0 | 1 | 4))) {
|
||||
r.warn("rectangles with concave or other corner types (imported with round corners)");
|
||||
}
|
||||
let absolute = r.s.bool(shape, b"AbSz") == Some(true);
|
||||
let [a, b2, c, d, ..] = world.0;
|
||||
let (sx, sy) = ((a * a + b2 * b2).sqrt(), (c * c + d * d).sqrt());
|
||||
cornered_rect(
|
||||
b,
|
||||
corners.map(|(f, t)| {
|
||||
let (crx, cry) = if !absolute {
|
||||
(f * w.min(h), f * w.min(h))
|
||||
} else if sx > 0.0 && sy > 0.0 {
|
||||
// An absolute radius is in document pixels, whatever the node's scale.
|
||||
(f / sx, f / sy)
|
||||
} else {
|
||||
(0.0, 0.0)
|
||||
};
|
||||
(crx, cry, t == Some(1))
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
b"ShpE" => ellipse(cx, cy, rx, ry),
|
||||
b"ShPy" => {
|
||||
let n = sides(r, shape, b"Side", 5.0);
|
||||
let a = |i: usize| -FRAC_PI_2 + TAU * i as f64 / n as f64;
|
||||
if r.s.object(shape).is_some_and(|_| matches!(last(r, shape, b"Smth"), Some(Value::Bool(true)))) {
|
||||
// Smoothed: tangent handles of length curv·4/3·tan(π/2n) along the inscribed ellipse.
|
||||
let k = num(r, shape, b"Curv").unwrap_or(0.0) * 4.0 / 3.0 * (PI / (2.0 * n as f64)).tan();
|
||||
let v = |i: usize| on_ellipse(a(i), 1.0);
|
||||
let t = |i: usize| pt(-rx * a(i).sin(), ry * a(i).cos());
|
||||
let segments = (0..n)
|
||||
.map(|i| {
|
||||
let (p, q, tp, tq) = (v(i), v(i + 1), t(i), t(i + 1));
|
||||
[pt(p.x + k * tp.x, p.y + k * tp.y), pt(q.x - k * tq.x, q.y - k * tq.y), q]
|
||||
})
|
||||
.collect();
|
||||
SubPath { start: v(0), segments, closed: true }
|
||||
} else {
|
||||
polygon((0..n).map(|i| on_ellipse(a(i), 1.0)))?
|
||||
}
|
||||
}
|
||||
b"ShSt" => {
|
||||
let n = sides(r, shape, b"Pnts", 5.0);
|
||||
let q = num(r, shape, b"IRad").unwrap_or(0.382).clamp(0.0, 1.0);
|
||||
if [b"CrcI", b"CrcO", b"CrvL", b"CrvR"].iter().any(|t| num(r, shape, t).is_some_and(|v| v.abs() > 1e-9)) {
|
||||
r.warn("stars with rounded or curved points (imported with sharp points)");
|
||||
}
|
||||
polygon((0..2 * n).map(|i| on_ellipse(-FRAC_PI_2 + PI * i as f64 / n as f64, if i % 2 == 0 { 1.0 } else { q })))?
|
||||
}
|
||||
b"ShSS" => {
|
||||
let n = sides(r, shape, b"Side", 5.0);
|
||||
let ri = num(r, shape, b"COut").unwrap_or(0.5).clamp(0.0, 1.0);
|
||||
let step = PI / n as f64;
|
||||
let (l, hw, inner) = (step.cos(), ri * step.sin(), ri * step.cos());
|
||||
polygon((0..n).flat_map(|k| {
|
||||
let phi = -FRAC_PI_2 + step + TAU * k as f64 / n as f64;
|
||||
let (c, s) = (phi.cos(), phi.sin());
|
||||
[(inner, -hw), (l, -hw), (l, hw), (inner, hw)].map(|(u, v)| pt(cx + rx * (u * c - v * s), cy + ry * (u * s + v * c)))
|
||||
}))?
|
||||
}
|
||||
b"ShPi" => {
|
||||
let raw_start = num(r, shape, b"AngS").unwrap_or(0.0);
|
||||
let raw_end = num(r, shape, b"AngE").unwrap_or(TAU);
|
||||
// Normalize in constant time. Repeatedly adding TAU can hang on finite values
|
||||
// large enough that floating-point addition no longer changes the endpoint.
|
||||
let start = raw_start.rem_euclid(TAU);
|
||||
let delta = raw_end - raw_start;
|
||||
let sweep = if raw_end >= raw_start {
|
||||
delta.min(TAU)
|
||||
} else if delta.is_finite() {
|
||||
delta.rem_euclid(TAU)
|
||||
} else {
|
||||
(raw_end.rem_euclid(TAU) - start).rem_euclid(TAU)
|
||||
};
|
||||
let inner = num(r, shape, b"IRad").unwrap_or(0.0).clamp(0.0, 1.0);
|
||||
pie(cx, cy, rx, ry, start, start + sweep, inner)
|
||||
}
|
||||
b"ShpT" => {
|
||||
let p = num(r, shape, b"Pos ").unwrap_or(0.5);
|
||||
polygon([pt(x0 + p * w, y0), pt(x1, y1), pt(x0, y1)])?
|
||||
}
|
||||
b"ShTz" => {
|
||||
let (l, rr) = (num(r, shape, b"PosL").unwrap_or(0.25), num(r, shape, b"PosR").unwrap_or(0.75));
|
||||
polygon([pt(x0 + l * w, y0), pt(x0 + rr * w, y0), pt(x1, y1), pt(x0, y1)])?
|
||||
}
|
||||
_ => {
|
||||
r.warn("cloud, heart, cog, callout, arrow, tear and other special shapes (imported as their bounding ellipse)");
|
||||
ellipse(cx, cy, rx, ry)
|
||||
}
|
||||
};
|
||||
Some(Path { subpaths: vec![sub] })
|
||||
}
|
||||
|
||||
pub(crate) fn rectangle(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath {
|
||||
SubPath { start: pt(x0, y0), segments: [pt(x1, y0), pt(x1, y1), pt(x0, y1)].map(|p| [p, p, p]).to_vec(), closed: true }
|
||||
}
|
||||
|
||||
fn ellipse(cx: f64, cy: f64, rx: f64, ry: f64) -> SubPath {
|
||||
let (kx, ky) = (KAPPA * rx, KAPPA * ry);
|
||||
SubPath {
|
||||
start: pt(cx + rx, cy),
|
||||
segments: vec![
|
||||
[pt(cx + rx, cy + ky), pt(cx + kx, cy + ry), pt(cx, cy + ry)],
|
||||
[pt(cx - kx, cy + ry), pt(cx - rx, cy + ky), pt(cx - rx, cy)],
|
||||
[pt(cx - rx, cy - ky), pt(cx - kx, cy - ry), pt(cx, cy - ry)],
|
||||
[pt(cx + kx, cy - ry), pt(cx + rx, cy - ky), pt(cx + rx, cy)],
|
||||
],
|
||||
closed: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A rectangle whose corners (top left, top right, bottom right, bottom left) are each rounded,
|
||||
/// or cut straight across, by their (horizontal, vertical) radii. Two radii that don't fit along
|
||||
/// one side shrink in proportion until they do.
|
||||
fn cornered_rect([x0, y0, x1, y1]: [f64; 4], corners: [(f64, f64, bool); 4]) -> SubPath {
|
||||
let fit = |r: f64, pair: f64, side: f64| if pair > side { side * (r / pair) } else { r };
|
||||
let [tl, tr, br, bl] = corners;
|
||||
let (w, h) = (x1 - x0, y1 - y0);
|
||||
let rx = [fit(tl.0, tl.0 + tr.0, w), fit(tr.0, tl.0 + tr.0, w), fit(br.0, bl.0 + br.0, w), fit(bl.0, bl.0 + br.0, w)];
|
||||
let ry = [fit(tl.1, tl.1 + bl.1, h), fit(tr.1, tr.1 + br.1, h), fit(br.1, tr.1 + br.1, h), fit(bl.1, tl.1 + bl.1, h)];
|
||||
let (kx, ky) = (rx.map(|r| (1.0 - KAPPA) * r), ry.map(|r| (1.0 - KAPPA) * r));
|
||||
// (where the corner leaves the previous side, its two handles, where it joins the next side)
|
||||
let arcs = [
|
||||
[pt(x1 - rx[1], y0), pt(x1 - kx[1], y0), pt(x1, y0 + ky[1]), pt(x1, y0 + ry[1])],
|
||||
[pt(x1, y1 - ry[2]), pt(x1, y1 - ky[2]), pt(x1 - kx[2], y1), pt(x1 - rx[2], y1)],
|
||||
[pt(x0 + rx[3], y1), pt(x0 + kx[3], y1), pt(x0, y1 - ky[3]), pt(x0, y1 - ry[3])],
|
||||
[pt(x0, y0 + ry[0]), pt(x0, y0 + ky[0]), pt(x0 + kx[0], y0), pt(x0 + rx[0], y0)],
|
||||
];
|
||||
let mut segments = Vec::with_capacity(8);
|
||||
for ([s, c1, c2, e], straight) in arcs.into_iter().zip([tr.2, br.2, bl.2, tl.2]) {
|
||||
segments.push([s, s, s]);
|
||||
if s != e {
|
||||
segments.push(if straight { [e, e, e] } else { [c1, c2, e] });
|
||||
}
|
||||
}
|
||||
SubPath { start: pt(x0 + rx[0], y0), segments, closed: true }
|
||||
}
|
||||
|
||||
/// Elliptical arc from angle `a0` to `a1` (radians, measured y-up as Affinity's pie angles are),
|
||||
/// as cubic segments of at most a quarter turn.
|
||||
fn arc(cx: f64, cy: f64, rx: f64, ry: f64, a0: f64, a1: f64, out: &mut Vec<[Point; 3]>) {
|
||||
let n = ((a1 - a0).abs() / FRAC_PI_2).ceil().clamp(1.0, 8.0) as usize;
|
||||
let step = (a1 - a0) / n as f64;
|
||||
let k = 4.0 / 3.0 * (step / 4.0).tan();
|
||||
let p = |a: f64| pt(cx + rx * a.cos(), cy - ry * a.sin());
|
||||
let d = |a: f64| pt(-rx * a.sin(), -ry * a.cos());
|
||||
for i in 0..n {
|
||||
let (s, e) = (a0 + step * i as f64, a0 + step * (i + 1) as f64);
|
||||
let (ps, pe, ds, de) = (p(s), p(e), d(s), d(e));
|
||||
out.push([pt(ps.x + k * ds.x, ps.y + k * ds.y), pt(pe.x - k * de.x, pe.y - k * de.y), pe]);
|
||||
}
|
||||
}
|
||||
|
||||
fn pie(cx: f64, cy: f64, rx: f64, ry: f64, a0: f64, a1: f64, inner: f64) -> SubPath {
|
||||
let start = pt(cx + rx * a0.cos(), cy - ry * a0.sin());
|
||||
let mut segments = Vec::new();
|
||||
arc(cx, cy, rx, ry, a0, a1, &mut segments);
|
||||
if inner > 0.0 {
|
||||
let p = pt(cx + inner * rx * a1.cos(), cy - inner * ry * a1.sin());
|
||||
segments.push([p, p, p]);
|
||||
arc(cx, cy, inner * rx, inner * ry, a1, a0, &mut segments);
|
||||
} else {
|
||||
let c = pt(cx, cy);
|
||||
segments.push([c, c, c]);
|
||||
}
|
||||
SubPath { start, segments, closed: true }
|
||||
}
|
||||
|
||||
/// A polyline with circular corners of the given radii (Affinity's live corners on curves).
|
||||
pub(crate) fn fillet(pts: &[(Point, f64)], closed: bool) -> SubPath {
|
||||
let n = pts.len();
|
||||
let get = |i: isize| -> Option<Point> {
|
||||
if closed { pts.get(i.rem_euclid(n as isize) as usize).map(|p| p.0) } else { usize::try_from(i).ok().and_then(|i| pts.get(i)).map(|p| p.0) }
|
||||
};
|
||||
let mut corners: Vec<(Point, Point, Point, Point)> = Vec::with_capacity(n);
|
||||
for (i, (p, radius)) in pts.iter().enumerate() {
|
||||
let (prev, next) = (get(i as isize - 1), get(i as isize + 1));
|
||||
let (Some(a), Some(b)) = (prev, next) else {
|
||||
corners.push((*p, *p, *p, *p));
|
||||
continue;
|
||||
};
|
||||
let (u1, l1) = unit(*p, a);
|
||||
let (u2, l2) = unit(*p, b);
|
||||
let cos = (u1.x * u2.x + u1.y * u2.y).clamp(-1.0, 1.0);
|
||||
let phi = cos.acos();
|
||||
if *radius <= 0.0 || phi < 1e-6 || (PI - phi) < 1e-6 {
|
||||
corners.push((*p, *p, *p, *p));
|
||||
continue;
|
||||
}
|
||||
let t = (radius / (phi / 2.0).tan()).min(l1 / 2.0).min(l2 / 2.0);
|
||||
let r = t * (phi / 2.0).tan();
|
||||
let k = 4.0 / 3.0 * ((PI - phi) / 4.0).tan() * r;
|
||||
let s = pt(p.x + u1.x * t, p.y + u1.y * t);
|
||||
let e = pt(p.x + u2.x * t, p.y + u2.y * t);
|
||||
corners.push((s, pt(s.x - u1.x * k, s.y - u1.y * k), pt(e.x - u2.x * k, e.y - u2.y * k), e));
|
||||
}
|
||||
let Some(first) = corners.first().copied() else { return SubPath { start: pt(0.0, 0.0), segments: vec![], closed } };
|
||||
let mut segments = Vec::with_capacity(2 * n);
|
||||
let mut cur = first.0;
|
||||
let start = cur;
|
||||
for (i, (s, c1, c2, e)) in corners.iter().enumerate() {
|
||||
if i > 0 {
|
||||
segments.push([cur, *s, *s]);
|
||||
}
|
||||
if s != e {
|
||||
segments.push([*c1, *c2, *e]);
|
||||
}
|
||||
cur = *e;
|
||||
}
|
||||
if closed && cur != start {
|
||||
segments.push([cur, start, start]);
|
||||
}
|
||||
SubPath { start, segments, closed }
|
||||
}
|
||||
|
||||
fn unit(from: Point, to: Point) -> (Point, f64) {
|
||||
let (dx, dy) = (to.x - from.x, to.y - from.y);
|
||||
let l = (dx * dx + dy * dy).sqrt();
|
||||
if l > 0.0 { (pt(dx / l, dy / l), l) } else { (pt(0.0, 0.0), 0.0) }
|
||||
}
|
||||
@@ -1,491 +0,0 @@
|
||||
//! The tagged object stream inside `doc.dat`: a self-describing tree of objects whose fields carry
|
||||
//! a type code and a four-character tag. Parsing needs no schema; unknown fields are kept, so the
|
||||
//! document mapping can name what it could not import.
|
||||
|
||||
use crate::Error;
|
||||
use crate::container::Cursor;
|
||||
|
||||
/// A four-character tag in its readable order (`Desc`, `Chld`).
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct Tag(pub u32);
|
||||
|
||||
impl Tag {
|
||||
pub const fn of(s: &[u8; 4]) -> Self {
|
||||
Self(u32::from_be_bytes(*s))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Tag {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", String::from_utf8_lossy(&self.0.to_be_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Tag {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
std::fmt::Debug::fmt(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
/// Index of an object in [`Stream::objects`].
|
||||
pub type ObjId = usize;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Value {
|
||||
Int(i64),
|
||||
UInt(u64),
|
||||
Float(f64),
|
||||
Bool(bool),
|
||||
Enum {
|
||||
id: u16,
|
||||
version: u16,
|
||||
},
|
||||
Str(String),
|
||||
/// Fixed-length vectors of i32/f32/f64 (points, rectangles, transforms).
|
||||
Ints(Vec<i64>),
|
||||
Floats(Vec<f64>),
|
||||
/// Fixed-size record (curve nodes, ids) or fixed-size struct (colour components).
|
||||
Bytes(Vec<u8>),
|
||||
Blob(Vec<u8>),
|
||||
/// Name of another archive entry (raster tiles, embedded files).
|
||||
Entry(String),
|
||||
Flags(u64),
|
||||
/// `None` is a null object.
|
||||
Obj(Option<ObjId>),
|
||||
Array(Vec<Value>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
Root,
|
||||
/// Defined once and referenced by id elsewhere.
|
||||
Shared,
|
||||
Inline,
|
||||
/// Untagged fields identified by position (curve data).
|
||||
Positional,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Object {
|
||||
pub class: Tag,
|
||||
pub kind: Kind,
|
||||
/// Class chain, most derived first (`ShpN`, `VNod`, `Node`).
|
||||
pub chain: Vec<Tag>,
|
||||
/// Fields in stream order; positional fields have tag 0.
|
||||
pub fields: Vec<(Tag, Value)>,
|
||||
/// For objects with many fields: each tag with the positions of its first and last field,
|
||||
/// sorted by tag, so a lookup isn't a scan of every field (a shared object is looked up
|
||||
/// again on every visit). Built by [`Object::index`]; empty for small objects.
|
||||
index: Vec<(Tag, u32, u32)>,
|
||||
}
|
||||
|
||||
/// Objects with more fields than this get an [`Object::index`]; fewer are scanned.
|
||||
const INDEXED_FIELDS: usize = 16;
|
||||
|
||||
impl Object {
|
||||
pub fn new(class: Tag, kind: Kind, chain: Vec<Tag>, fields: Vec<(Tag, Value)>) -> Self {
|
||||
let mut o = Self { class, kind, chain, fields, index: Vec::new() };
|
||||
o.index();
|
||||
o
|
||||
}
|
||||
|
||||
/// (Re)build the tag index after `fields` changed.
|
||||
fn index(&mut self) {
|
||||
self.index.clear();
|
||||
if self.fields.len() <= INDEXED_FIELDS {
|
||||
return;
|
||||
}
|
||||
let mut index: Vec<(Tag, u32, u32)> = Vec::new();
|
||||
if index.try_reserve_exact(self.fields.len()).is_err() {
|
||||
return;
|
||||
}
|
||||
// Fields beyond u32 positions are impossible: a stream holds at most MAX_VALUES values.
|
||||
index.extend(self.fields.iter().enumerate().filter_map(|(i, (t, _))| u32::try_from(i).ok().map(|i| (*t, i, i))));
|
||||
// Stable: equal tags stay in stream order, so the run of a tag starts at its first field.
|
||||
index.sort_by_key(|(t, _, _)| *t);
|
||||
index.dedup_by(|later, first| {
|
||||
if later.0 == first.0 {
|
||||
first.2 = later.2;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
index.shrink_to_fit();
|
||||
self.index = index;
|
||||
}
|
||||
|
||||
fn position(&self, tag: Tag, last: bool) -> Option<usize> {
|
||||
if self.index.is_empty() {
|
||||
let mut fields = self.fields.iter().enumerate();
|
||||
let hit = if last { fields.rev().find(|(_, (t, _))| *t == tag) } else { fields.find(|(_, (t, _))| *t == tag) };
|
||||
return hit.map(|(i, _)| i);
|
||||
}
|
||||
let at = self.index.binary_search_by_key(&tag, |(t, _, _)| *t).ok()?;
|
||||
let (_, first, end) = self.index.get(at)?;
|
||||
usize::try_from(if last { *end } else { *first }).ok()
|
||||
}
|
||||
|
||||
/// The first field tagged `tag`.
|
||||
pub fn get(&self, tag: Tag) -> Option<&Value> {
|
||||
self.fields.get(self.position(tag, false)?).map(|(_, v)| v)
|
||||
}
|
||||
|
||||
/// The last field tagged `tag` (a shape changed from one kind to another keeps a stale first one).
|
||||
pub fn get_last(&self, tag: Tag) -> Option<&Value> {
|
||||
self.fields.get(self.position(tag, true)?).map(|(_, v)| v)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Stream {
|
||||
pub root: ObjId,
|
||||
pub objects: Vec<Object>,
|
||||
}
|
||||
|
||||
/// Deepest object nesting accepted; real documents stay well below (each layer level adds three).
|
||||
pub const MAX_DEPTH: usize = 384;
|
||||
|
||||
const MAX_OBJECTS: usize = 8_000_000;
|
||||
|
||||
/// Most values (fields and array elements) one stream may decode. A value takes about 40 bytes
|
||||
/// in memory however few it took in the file (a bool array packs eight in a byte), so the size
|
||||
/// of the input alone doesn't bound what parsing allocates: a small compressed entry could
|
||||
/// otherwise ask for tens of gigabytes. Real documents stay far below.
|
||||
pub const MAX_VALUES: usize = 1 << 24;
|
||||
|
||||
struct Parser<'a> {
|
||||
c: Cursor<'a>,
|
||||
objects: Vec<Object>,
|
||||
/// Shared ids, defined at first use and referenced backwards.
|
||||
shared: std::collections::HashMap<u32, ObjId>,
|
||||
depth: usize,
|
||||
/// Values decoded so far, against [`MAX_VALUES`].
|
||||
values: usize,
|
||||
}
|
||||
|
||||
/// Parse a stream (`00 FF 4B 53` header). Bytes after the root's terminator are ignored.
|
||||
pub fn parse(bytes: &[u8]) -> Result<Stream, Error> {
|
||||
let mut c = Cursor::new(bytes, 0);
|
||||
if c.take(4)? != b"\x00\xffKS" {
|
||||
return Err(Error::Malformed("document stream signature"));
|
||||
}
|
||||
let version = c.u16()?;
|
||||
if version > 2 {
|
||||
return Err(Error::Unsupported("document stream version"));
|
||||
}
|
||||
let class = Tag(c.u32()?);
|
||||
c.u16()?;
|
||||
if version == 2 {
|
||||
c.u32()?;
|
||||
}
|
||||
let mut p = Parser { c, objects: Vec::new(), shared: std::collections::HashMap::new(), depth: 0, values: 0 };
|
||||
let root = p.push(Object::new(class, Kind::Root, vec![class], Vec::new()))?;
|
||||
let fields = p.fields(true, class)?;
|
||||
if let Some(o) = p.objects.get_mut(root) {
|
||||
o.fields = fields;
|
||||
o.index();
|
||||
}
|
||||
Ok(Stream { root, objects: p.objects })
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
fn push(&mut self, o: Object) -> Result<ObjId, Error> {
|
||||
if self.objects.len() >= MAX_OBJECTS {
|
||||
return Err(Error::Limit("too many objects"));
|
||||
}
|
||||
self.objects.push(o);
|
||||
Ok(self.objects.len() - 1)
|
||||
}
|
||||
|
||||
/// Counts `n` more values against [`MAX_VALUES`], before anything is allocated for them.
|
||||
fn spend(&mut self, n: usize) -> Result<(), Error> {
|
||||
self.values = self.values.checked_add(n).filter(|&v| v <= MAX_VALUES).ok_or(Error::Limit("too many values in the document stream"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An empty array with room for `n` values, paid for first; an allocation that still fails
|
||||
/// is an error, not an abort.
|
||||
fn vec<T>(&mut self, n: usize) -> Result<Vec<T>, Error> {
|
||||
self.spend(n)?;
|
||||
let mut v = Vec::new();
|
||||
v.try_reserve_exact(n).map_err(|_| Error::Limit("not enough memory for the document stream"))?;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Element count of an array: each element takes at least `min` bytes, so a count the
|
||||
/// remaining input cannot hold is rejected before anything is allocated.
|
||||
fn count(&mut self, min: usize) -> Result<usize, Error> {
|
||||
let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?;
|
||||
if n.checked_mul(min.max(1)).is_none_or(|bytes| bytes > self.c.remaining()) {
|
||||
return Err(Error::Malformed("array longer than its data"));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn fields(&mut self, tagged: bool, class: Tag) -> Result<Vec<(Tag, Value)>, Error> {
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH {
|
||||
return Err(Error::Limit("objects nested too deeply"));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
loop {
|
||||
let t = self.c.u8()?;
|
||||
let code = t & 0x7F;
|
||||
if code == 0 {
|
||||
break;
|
||||
}
|
||||
self.spend(1)?;
|
||||
let tag = if tagged { Tag(self.c.u32()?) } else { Tag(0) };
|
||||
let v = if t & 0x80 != 0 { self.array(code, class)? } else { self.scalar(code, tagged, class)? };
|
||||
out.push((tag, v));
|
||||
}
|
||||
self.depth -= 1;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn string(&mut self) -> Result<String, Error> {
|
||||
let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("string length"))?;
|
||||
Ok(String::from_utf8_lossy(self.c.take(n)?).into_owned())
|
||||
}
|
||||
|
||||
fn floats(&mut self, n: usize, wide: bool) -> Result<Value, Error> {
|
||||
let mut v = Vec::with_capacity(n);
|
||||
for _ in 0..n {
|
||||
v.push(if wide { f64::from_le_bytes(self.c.array()?) } else { f64::from(f32::from_le_bytes(self.c.array()?)) });
|
||||
}
|
||||
Ok(Value::Floats(v))
|
||||
}
|
||||
|
||||
fn scalar(&mut self, code: u8, tagged: bool, class: Tag) -> Result<Value, Error> {
|
||||
let c = &mut self.c;
|
||||
Ok(match code {
|
||||
0x01 => Value::UInt(c.u8()?.into()),
|
||||
0x02 => Value::UInt(c.u16()?.into()),
|
||||
0x03 | 0x2f | 0x34 => Value::UInt(c.u32()?.into()),
|
||||
0x04 => Value::UInt(c.u64()?),
|
||||
0x05 => Value::Int(i8::from_le_bytes(c.array()?).into()),
|
||||
0x06 => Value::Int(i16::from_le_bytes(c.array()?).into()),
|
||||
0x07 => Value::Int(i32::from_le_bytes(c.array()?).into()),
|
||||
0x08 => Value::Int(i64::from_le_bytes(c.array()?)),
|
||||
0x09 => Value::Float(f32::from_le_bytes(c.array()?).into()),
|
||||
0x0a => Value::Float(f64::from_le_bytes(c.array()?)),
|
||||
0x15..=0x19 => {
|
||||
let n = usize::from(code - 0x13);
|
||||
let mut v = Vec::with_capacity(n);
|
||||
for _ in 0..n {
|
||||
v.push(i32::from_le_bytes(c.array()?).into());
|
||||
}
|
||||
Value::Ints(v)
|
||||
}
|
||||
0x1f..=0x23 => return self.floats(usize::from(code - 0x1d), false),
|
||||
0x24..=0x28 => return self.floats(usize::from(code - 0x22), true),
|
||||
0x29 => Value::Bool(c.u8()? != 0),
|
||||
0x2a => Value::Enum { id: c.u16()?, version: c.u16()? },
|
||||
0x2b | 0x2e => Value::Str(self.string()?),
|
||||
0x2c => {
|
||||
let n = usize::from(c.u16()?);
|
||||
Value::Bytes(c.take(n)?.to_vec())
|
||||
}
|
||||
0x35..=0x74 => Value::Bytes(c.take(usize::from(code - 0x34))?.to_vec()),
|
||||
0x2d => {
|
||||
let n = usize::try_from(c.u32()?).map_err(|_| Error::Malformed("blob length"))?;
|
||||
Value::Blob(c.take(n)?.to_vec())
|
||||
}
|
||||
0x33 => {
|
||||
c.u32()?;
|
||||
let n = usize::try_from(c.u32()?).map_err(|_| Error::Malformed("entry name length"))?;
|
||||
Value::Entry(String::from_utf8_lossy(c.take(n)?).into_owned())
|
||||
}
|
||||
0x75 => {
|
||||
c.u16()?;
|
||||
let n = usize::from(c.u8()?);
|
||||
if n > 8 {
|
||||
return Err(Error::Malformed("flags wider than 64 bits"));
|
||||
}
|
||||
let mut b = [0u8; 8];
|
||||
b.get_mut(..n).ok_or(Error::Malformed("flags"))?.copy_from_slice(c.take(n)?);
|
||||
Value::Flags(u64::from_le_bytes(b))
|
||||
}
|
||||
0x30 => {
|
||||
let fields = self.fields(false, class)?;
|
||||
let id = self.push(Object::new(class, Kind::Positional, Vec::new(), fields))?;
|
||||
Value::Obj(Some(id))
|
||||
}
|
||||
0x31 | 0x32 if !tagged => return Err(Error::Malformed("object without a field tag")),
|
||||
0x31 => self.shared()?,
|
||||
0x32 => self.inline(None)?,
|
||||
_ => return Err(Error::Unsupported("unknown field type in document stream")),
|
||||
})
|
||||
}
|
||||
|
||||
fn array(&mut self, code: u8, class: Tag) -> Result<Value, Error> {
|
||||
let min = match code {
|
||||
0x01 | 0x05 | 0x29 => 1,
|
||||
0x02 | 0x06 => 2,
|
||||
0x03 | 0x07 | 0x09 | 0x2f | 0x34 => 4,
|
||||
0x04 | 0x08 | 0x0a => 8,
|
||||
0x15..=0x19 => 4 * usize::from(code - 0x13),
|
||||
0x1f..=0x23 => 4 * usize::from(code - 0x1d),
|
||||
0x24..=0x28 => 8 * usize::from(code - 0x22),
|
||||
0x35..=0x74 => usize::from(code - 0x34),
|
||||
_ => 1,
|
||||
};
|
||||
match code {
|
||||
0x29 => {
|
||||
let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?;
|
||||
let bits = self.c.take(n.div_ceil(8))?;
|
||||
let mut v = self.vec(n)?;
|
||||
v.extend((0..n).map(|i| Value::Bool(bits.get(i / 8).is_some_and(|b| b >> (i % 8) & 1 != 0))));
|
||||
Ok(Value::Array(v))
|
||||
}
|
||||
0x2a => {
|
||||
let n = self.count(2)?;
|
||||
let version = self.c.u16()?;
|
||||
let mut v = self.vec(n)?;
|
||||
for _ in 0..n {
|
||||
v.push(Value::Enum { id: self.c.u16()?, version });
|
||||
}
|
||||
Ok(Value::Array(v))
|
||||
}
|
||||
0x2b | 0x2e => {
|
||||
self.c.u32()?;
|
||||
let n = self.count(4)?;
|
||||
let mut v = self.vec(n)?;
|
||||
for _ in 0..n {
|
||||
v.push(Value::Str(self.string()?));
|
||||
}
|
||||
Ok(Value::Array(v))
|
||||
}
|
||||
0x2c => {
|
||||
let n = usize::try_from(self.c.u32()?).map_err(|_| Error::Malformed("array length"))?;
|
||||
let size = usize::from(self.c.u16()?);
|
||||
// Records of no bytes take nothing from the data, whatever their number.
|
||||
if n > 0 && size == 0 {
|
||||
return Err(Error::Malformed("array of records without bytes"));
|
||||
}
|
||||
if n.checked_mul(size).is_none_or(|b| b > self.c.remaining()) {
|
||||
return Err(Error::Malformed("array longer than its data"));
|
||||
}
|
||||
let mut v = self.vec(n)?;
|
||||
for _ in 0..n {
|
||||
v.push(Value::Bytes(self.c.take(size)?.to_vec()));
|
||||
}
|
||||
Ok(Value::Array(v))
|
||||
}
|
||||
0x32 => {
|
||||
let n = self.count(1)?;
|
||||
let class = Tag(self.c.u32()?);
|
||||
self.c.u16()?;
|
||||
let mut v = self.vec(n)?;
|
||||
for _ in 0..n {
|
||||
v.push(self.inline(Some(class))?);
|
||||
}
|
||||
Ok(Value::Array(v))
|
||||
}
|
||||
0x2d | 0x33 | 0x75 => Err(Error::Malformed("array of an unarrayable type")),
|
||||
_ => {
|
||||
let n = self.count(min)?;
|
||||
let mut v = self.vec(n)?;
|
||||
for _ in 0..n {
|
||||
v.push(self.scalar(code, true, class)?);
|
||||
}
|
||||
Ok(Value::Array(v))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Inline object; `class` is given once for a whole array of them.
|
||||
fn inline(&mut self, class: Option<Tag>) -> Result<Value, Error> {
|
||||
match self.c.u8()? {
|
||||
0 => return Ok(Value::Obj(None)),
|
||||
1 => {}
|
||||
_ => return Err(Error::Malformed("object marker")),
|
||||
}
|
||||
let class = match class {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
let c = Tag(self.c.u32()?);
|
||||
self.c.u16()?;
|
||||
c
|
||||
}
|
||||
};
|
||||
let fields = self.fields(true, class)?;
|
||||
let id = self.push(Object::new(class, Kind::Inline, vec![class], fields))?;
|
||||
Ok(Value::Obj(Some(id)))
|
||||
}
|
||||
|
||||
fn shared(&mut self) -> Result<Value, Error> {
|
||||
let flag = self.c.u8()?;
|
||||
if flag == 0 {
|
||||
return Ok(Value::Obj(None));
|
||||
}
|
||||
let key = self.c.u32()?;
|
||||
match flag {
|
||||
2 => return self.shared.get(&key).map(|id| Value::Obj(Some(*id))).ok_or(Error::Malformed("reference to an undefined object")),
|
||||
1 => {}
|
||||
_ => return Err(Error::Malformed("object marker")),
|
||||
}
|
||||
if self.shared.contains_key(&key) {
|
||||
return Err(Error::Malformed("object defined twice"));
|
||||
}
|
||||
// Register before the fields: an object's own fields may refer back to it.
|
||||
let id = self.push(Object::new(Tag(0), Kind::Shared, Vec::new(), Vec::new()))?;
|
||||
self.shared.insert(key, id);
|
||||
let mut chain = Vec::new();
|
||||
let mut fields = Vec::new();
|
||||
loop {
|
||||
match self.c.u8()? {
|
||||
0 => {
|
||||
let tag = Tag(self.c.u32()?);
|
||||
self.c.u16()?;
|
||||
chain.push(tag);
|
||||
fields.extend(self.fields(true, tag)?);
|
||||
}
|
||||
1 => {
|
||||
chain.push(Tag(self.c.u32()?));
|
||||
break;
|
||||
}
|
||||
2 => break,
|
||||
_ => return Err(Error::Malformed("object class chain")),
|
||||
}
|
||||
if chain.len() > 64 {
|
||||
return Err(Error::Limit("object class chain too long"));
|
||||
}
|
||||
}
|
||||
let class = chain.first().copied().unwrap_or(Tag(0));
|
||||
fields.extend(self.fields(true, class)?);
|
||||
if let Some(o) = self.objects.get_mut(id) {
|
||||
*o = Object::new(class, Kind::Shared, chain, fields);
|
||||
}
|
||||
Ok(Value::Obj(Some(id)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lookups_in_a_large_object_find_the_first_and_last_fields_of_a_tag() {
|
||||
let tag = |i: u32| Tag(0x4100_0000 + i);
|
||||
let mut fields: Vec<(Tag, Value)> = (0..1000).map(|i| (tag(i % 300), Value::UInt(u64::from(i)))).collect();
|
||||
fields.push((tag(7), Value::Str("last".into())));
|
||||
let o = Object::new(Tag::of(b"Grup"), Kind::Shared, Vec::new(), fields.clone());
|
||||
assert!(!o.index.is_empty());
|
||||
// The index has one entry per distinct tag, not per field.
|
||||
assert_eq!(o.index.len(), 300);
|
||||
for t in 0..300 {
|
||||
let first = fields.iter().find(|(k, _)| *k == tag(t)).map(|(_, v)| v);
|
||||
let last = fields.iter().rev().find(|(k, _)| *k == tag(t)).map(|(_, v)| v);
|
||||
assert_eq!(o.get(tag(t)), first);
|
||||
assert_eq!(o.get_last(tag(t)), last);
|
||||
}
|
||||
assert_eq!(o.get(tag(300)), None);
|
||||
assert_eq!(o.get_last(tag(7)), Some(&Value::Str("last".into())));
|
||||
let small = Object::new(Tag::of(b"Grup"), Kind::Shared, Vec::new(), vec![(tag(1), Value::Bool(true)), (tag(1), Value::Bool(false))]);
|
||||
assert!(small.index.is_empty());
|
||||
assert_eq!(small.get(tag(1)), Some(&Value::Bool(true)));
|
||||
assert_eq!(small.get_last(tag(1)), Some(&Value::Bool(false)));
|
||||
}
|
||||
}
|
||||
@@ -1,259 +0,0 @@
|
||||
//! Synthetic containers for tests and fuzz seeds (cargo feature `synth`).
|
||||
//!
|
||||
//! These builders write the layout the reader accepts, so tests can describe documents in a few
|
||||
//! lines. They are **not** an Affinity exporter: nothing written here has been opened in Affinity.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use crate::stream::Tag;
|
||||
|
||||
/// A field value to encode.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum F {
|
||||
U8(u8),
|
||||
U32(u32),
|
||||
I32(i32),
|
||||
F32(f32),
|
||||
F64(f64),
|
||||
Bool(bool),
|
||||
Enum(u16, u16),
|
||||
Str(String),
|
||||
/// f64 vector of 2..6 values (points, rectangles, transforms).
|
||||
F64s(Vec<f64>),
|
||||
/// Fixed-size struct (colour components), 1..64 bytes.
|
||||
Struct(Vec<u8>),
|
||||
/// Array of fixed-size records, all `size` bytes.
|
||||
Records(u16, Vec<Vec<u8>>),
|
||||
U8s(Vec<u8>),
|
||||
Entry(String),
|
||||
/// Shared object: `Def` defines id with class chain and fields, `Ref` links back.
|
||||
Def(u32, Vec<Tag>, Vec<(Tag, F)>),
|
||||
Ref(u32),
|
||||
Null,
|
||||
/// Inline object.
|
||||
Obj(Tag, Vec<(Tag, F)>),
|
||||
/// Positional (untagged) object.
|
||||
Pos(Vec<F>),
|
||||
/// Array of shared objects / links.
|
||||
Shared(Vec<F>),
|
||||
/// Array of inline objects of one class.
|
||||
Objs(Tag, Vec<Vec<(Tag, F)>>),
|
||||
/// Raw bytes appended verbatim (malformed-input tests).
|
||||
Raw(Vec<u8>),
|
||||
}
|
||||
|
||||
pub fn tag(s: &[u8; 4]) -> Tag {
|
||||
Tag::of(s)
|
||||
}
|
||||
|
||||
fn put_tag(out: &mut Vec<u8>, t: Tag) {
|
||||
out.extend(t.0.to_le_bytes());
|
||||
}
|
||||
|
||||
fn code(f: &F) -> u8 {
|
||||
match f {
|
||||
F::U8(_) => 0x01,
|
||||
F::U32(_) => 0x03,
|
||||
F::I32(_) => 0x07,
|
||||
F::F32(_) => 0x09,
|
||||
F::F64(_) => 0x0a,
|
||||
F::Bool(_) => 0x29,
|
||||
F::Enum(..) => 0x2a,
|
||||
F::Str(_) => 0x2b,
|
||||
F::F64s(v) => 0x22 + v.len() as u8,
|
||||
F::Struct(b) => 0x34 + b.len() as u8,
|
||||
F::Records(..) => 0x80 | 0x2c,
|
||||
F::U8s(_) => 0x80 | 0x01,
|
||||
F::Entry(_) => 0x33,
|
||||
F::Def(..) | F::Ref(_) => 0x31,
|
||||
F::Null => 0x31,
|
||||
F::Obj(..) => 0x32,
|
||||
F::Pos(_) => 0x30,
|
||||
F::Shared(_) => 0x80 | 0x31,
|
||||
F::Objs(..) => 0x80 | 0x32,
|
||||
F::Raw(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn payload(out: &mut Vec<u8>, f: &F) {
|
||||
match f {
|
||||
F::U8(v) => out.push(*v),
|
||||
F::U32(v) => out.extend(v.to_le_bytes()),
|
||||
F::I32(v) => out.extend(v.to_le_bytes()),
|
||||
F::F32(v) => out.extend(v.to_le_bytes()),
|
||||
F::F64(v) => out.extend(v.to_le_bytes()),
|
||||
F::Bool(v) => out.push(u8::from(*v)),
|
||||
F::Enum(id, ver) => {
|
||||
out.extend(id.to_le_bytes());
|
||||
out.extend(ver.to_le_bytes());
|
||||
}
|
||||
F::Str(s) => {
|
||||
out.extend((s.len() as u32).to_le_bytes());
|
||||
out.extend(s.as_bytes());
|
||||
}
|
||||
F::F64s(v) => v.iter().for_each(|x| out.extend(x.to_le_bytes())),
|
||||
F::Struct(b) => out.extend(b),
|
||||
F::Records(size, recs) => {
|
||||
out.extend((recs.len() as u32).to_le_bytes());
|
||||
out.extend(size.to_le_bytes());
|
||||
recs.iter().for_each(|r| out.extend(r));
|
||||
}
|
||||
F::U8s(v) => {
|
||||
out.extend((v.len() as u32).to_le_bytes());
|
||||
out.extend(v);
|
||||
}
|
||||
F::Entry(name) => {
|
||||
put_tag(out, tag(b"Data"));
|
||||
out.extend((name.len() as u32).to_le_bytes());
|
||||
out.extend(name.as_bytes());
|
||||
}
|
||||
F::Def(id, chain, fields) => {
|
||||
out.push(1);
|
||||
out.extend(id.to_le_bytes());
|
||||
// Class chain: each level but the last carries no fields here; the last ends the chain.
|
||||
let (last, rest) = chain.split_last().expect("class chain");
|
||||
for t in rest {
|
||||
out.push(0);
|
||||
put_tag(out, *t);
|
||||
out.extend(0u16.to_le_bytes());
|
||||
out.push(0);
|
||||
}
|
||||
out.push(1);
|
||||
put_tag(out, *last);
|
||||
fields_into(out, fields, true);
|
||||
}
|
||||
F::Ref(id) => {
|
||||
out.push(2);
|
||||
out.extend(id.to_le_bytes());
|
||||
}
|
||||
F::Null => out.push(0),
|
||||
F::Obj(class, fields) => {
|
||||
out.push(1);
|
||||
put_tag(out, *class);
|
||||
out.extend(0u16.to_le_bytes());
|
||||
fields_into(out, fields, true);
|
||||
}
|
||||
F::Pos(items) => {
|
||||
for f in items {
|
||||
out.push(code(f));
|
||||
payload(out, f);
|
||||
}
|
||||
out.push(0);
|
||||
}
|
||||
F::Shared(items) => {
|
||||
out.extend((items.len() as u32).to_le_bytes());
|
||||
items.iter().for_each(|f| payload(out, f));
|
||||
}
|
||||
F::Objs(class, items) => {
|
||||
out.extend((items.len() as u32).to_le_bytes());
|
||||
put_tag(out, *class);
|
||||
out.extend(0u16.to_le_bytes());
|
||||
for fields in items {
|
||||
out.push(1);
|
||||
fields_into(out, fields, true);
|
||||
}
|
||||
}
|
||||
F::Raw(b) => out.extend(b),
|
||||
}
|
||||
}
|
||||
|
||||
fn fields_into(out: &mut Vec<u8>, fields: &[(Tag, F)], tagged: bool) {
|
||||
for (t, f) in fields {
|
||||
if let F::Raw(b) = f {
|
||||
out.extend(b);
|
||||
continue;
|
||||
}
|
||||
out.push(code(f));
|
||||
if tagged {
|
||||
put_tag(out, *t);
|
||||
}
|
||||
payload(out, f);
|
||||
}
|
||||
out.push(0);
|
||||
}
|
||||
|
||||
/// A `doc.dat` stream with root class `Pers`.
|
||||
pub fn stream(root: &[(Tag, F)]) -> Vec<u8> {
|
||||
let mut out = b"\x00\xffKS".to_vec();
|
||||
out.extend(2u16.to_le_bytes());
|
||||
put_tag(&mut out, tag(b"Pers"));
|
||||
out.extend(0u16.to_le_bytes());
|
||||
out.extend(30u32.to_le_bytes());
|
||||
fields_into(&mut out, root, true);
|
||||
out
|
||||
}
|
||||
|
||||
/// How an entry is stored.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Method {
|
||||
Stored,
|
||||
Zlib,
|
||||
Zstd,
|
||||
}
|
||||
|
||||
/// A version-12 container with one `#FT4` table holding `entries`, then an optional thumbnail record.
|
||||
pub fn container(entries: &[(&str, &[u8], Method)], thumbnail_png: Option<&[u8]>) -> Vec<u8> {
|
||||
let mut out = vec![0u8; 72];
|
||||
out[..4].copy_from_slice(crate::container::MAGIC);
|
||||
out[4..6].copy_from_slice(&12u16.to_le_bytes());
|
||||
out[6..8].copy_from_slice(&4u16.to_le_bytes());
|
||||
out[8..12].copy_from_slice(b"nsrP");
|
||||
out[12..16].copy_from_slice(b"#Inf");
|
||||
out[64..68].copy_from_slice(b"Prot");
|
||||
let mut records = Vec::new();
|
||||
for (i, (name, data, method)) in entries.iter().enumerate() {
|
||||
let packed = match method {
|
||||
Method::Stored => data.to_vec(),
|
||||
Method::Zlib => {
|
||||
use std::io::Write;
|
||||
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
e.write_all(data).unwrap();
|
||||
e.finish().unwrap()
|
||||
}
|
||||
Method::Zstd => ruzstd::encoding::compress_to_vec(*data, ruzstd::encoding::CompressionLevel::Fastest),
|
||||
};
|
||||
let offset = out.len() as u64;
|
||||
out.extend(b"#Fil");
|
||||
out.extend(&packed);
|
||||
let mut r = Vec::new();
|
||||
r.extend((i as u32 + 1).to_le_bytes());
|
||||
r.push(0);
|
||||
r.extend(offset.to_le_bytes());
|
||||
r.extend((data.len() as u64).to_le_bytes());
|
||||
r.extend((packed.len() as u64).to_le_bytes());
|
||||
r.extend(crc32fast::hash(data).to_le_bytes());
|
||||
r.push(match method {
|
||||
Method::Stored => 0,
|
||||
Method::Zlib => 1,
|
||||
Method::Zstd => 2,
|
||||
});
|
||||
r.extend(0u32.to_le_bytes());
|
||||
r.extend(0u32.to_le_bytes());
|
||||
r.extend((name.len() as u16).to_le_bytes());
|
||||
r.extend(name.as_bytes());
|
||||
records.push(r);
|
||||
}
|
||||
let fat = out.len() as u64;
|
||||
out.extend(b"#FT4");
|
||||
out.extend(0u64.to_le_bytes());
|
||||
out.extend(1_700_000_000u64.to_le_bytes());
|
||||
out.extend([0u8; 24]);
|
||||
out.extend((records.len() as u32).to_le_bytes());
|
||||
out.extend([0u8; 8]);
|
||||
out.extend(0u16.to_le_bytes());
|
||||
out.push(0);
|
||||
records.iter().for_each(|r| out.extend(r));
|
||||
let thumb = out.len() as u64;
|
||||
out[16..24].copy_from_slice(&fat.to_le_bytes());
|
||||
if let Some(png) = thumbnail_png {
|
||||
out[24..32].copy_from_slice(&thumb.to_le_bytes());
|
||||
out.extend(b"\xff\xff\xff\xffThmb");
|
||||
out.extend(1u32.to_le_bytes());
|
||||
out.extend((png.len() as u32 + 13).to_le_bytes());
|
||||
out.extend(29u32.to_le_bytes());
|
||||
out.extend(0u32.to_le_bytes());
|
||||
out.extend((png.len() as u32).to_le_bytes());
|
||||
out.push(1);
|
||||
out.extend(png);
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1,408 +0,0 @@
|
||||
//! Unit tests on synthetic inputs; `tests/it/real_files.rs` covers public Affinity documents.
|
||||
|
||||
mod preview {
|
||||
use crate::container::header;
|
||||
use crate::*;
|
||||
use proptest::prelude::*;
|
||||
|
||||
fn fixture() -> Vec<u8> {
|
||||
let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
png.extend(13u32.to_be_bytes());
|
||||
png.extend(b"IHDR");
|
||||
png.extend(2u32.to_be_bytes());
|
||||
png.extend(1u32.to_be_bytes());
|
||||
png.extend([8, 6, 0, 0, 0]);
|
||||
png.extend(crc32fast::hash(&png[12..]).to_be_bytes());
|
||||
png.extend([0; 4]);
|
||||
png.extend(b"IDAT");
|
||||
png.extend(crc32fast::hash(b"IDAT").to_be_bytes());
|
||||
png.extend([0; 4]);
|
||||
png.extend(b"IEND");
|
||||
png.extend(crc32fast::hash(b"IEND").to_be_bytes());
|
||||
let mut b = vec![0; 72];
|
||||
b[..4].copy_from_slice(MAGIC);
|
||||
b[4..6].copy_from_slice(&12u16.to_le_bytes());
|
||||
b[8..12].copy_from_slice(b"nsrP");
|
||||
b[12..16].copy_from_slice(b"#Inf");
|
||||
b[24..32].copy_from_slice(&72u64.to_le_bytes());
|
||||
b[64..68].copy_from_slice(b"Prot");
|
||||
b.extend(b"\xff\xff\xff\xffThmb");
|
||||
b.extend(1u32.to_le_bytes());
|
||||
b.extend((png.len() as u32 + 13).to_le_bytes());
|
||||
b.extend(29u32.to_le_bytes());
|
||||
b.extend(0u32.to_le_bytes());
|
||||
b.extend((png.len() as u32).to_le_bytes());
|
||||
b.push(1);
|
||||
b.extend(png);
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_preview_and_header() {
|
||||
let b = fixture();
|
||||
assert_eq!(header(&b).unwrap().version, 12);
|
||||
let p = preview(&b).unwrap();
|
||||
assert_eq!((p.width, p.height), (2, 1));
|
||||
assert_eq!(p.png, &b[101..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_truncation_is_rejected() {
|
||||
let b = fixture();
|
||||
for end in 0..b.len() {
|
||||
assert!(preview(&b[..end]).is_err(), "{end}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_assets_versions_offsets_lengths_and_bombs() {
|
||||
let b = fixture();
|
||||
for (offset, value) in [
|
||||
(4, 13u64.to_le_bytes().to_vec()),
|
||||
(8, b"urBR".to_vec()),
|
||||
(24, u64::MAX.to_le_bytes().to_vec()),
|
||||
(24, 1u64.to_le_bytes().to_vec()),
|
||||
(24, 0u64.to_le_bytes().to_vec()),
|
||||
(84, u32::MAX.to_le_bytes().to_vec()),
|
||||
(88, 30u32.to_le_bytes().to_vec()),
|
||||
(96, u32::MAX.to_le_bytes().to_vec()),
|
||||
(117, 5000u32.to_be_bytes().to_vec()),
|
||||
] {
|
||||
let mut broken = b.clone();
|
||||
broken[offset..offset + value.len()].copy_from_slice(&value);
|
||||
assert!(preview(&broken).is_err(), "offset {offset}");
|
||||
}
|
||||
// Versions 8 to 11 store the same record (checked on public Affinity 1 and 2 files).
|
||||
for version in 8..12 {
|
||||
let mut legacy = b.clone();
|
||||
legacy[4..6].copy_from_slice(&(version as u16).to_le_bytes());
|
||||
assert!(preview(&legacy).is_ok());
|
||||
}
|
||||
// Flags 4 and 8 occur in real files; the low two bits mark other container variants.
|
||||
for (flags, ok) in [(4u16, true), (8, true), (1, false), (2, false)] {
|
||||
let mut variant = b.clone();
|
||||
variant[6..8].copy_from_slice(&flags.to_le_bytes());
|
||||
assert_eq!(preview(&variant).is_ok(), ok, "flags {flags}");
|
||||
}
|
||||
let mut old = b.clone();
|
||||
old[4..6].copy_from_slice(&7u16.to_le_bytes());
|
||||
assert!(matches!(preview(&old), Err(Error::Unsupported(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unindexed_png_or_resource_is_never_used() {
|
||||
let mut b = fixture();
|
||||
b[24..32].copy_from_slice(&0u64.to_le_bytes());
|
||||
assert!(preview(&b).is_err());
|
||||
b[24..32].copy_from_slice(&72u64.to_le_bytes());
|
||||
b[76..80].copy_from_slice(b"Meta");
|
||||
assert!(preview(&b).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_chunk_checksum_including_the_end_is_checked() {
|
||||
let b = fixture();
|
||||
for at in [130, b.len() - 1] {
|
||||
let mut damaged = b.clone();
|
||||
damaged[at] ^= 1;
|
||||
assert_eq!(preview(&damaged).unwrap_err(), Error::Malformed("PNG chunk checksum"));
|
||||
}
|
||||
let mut ancillary = vec![0; 4];
|
||||
ancillary.extend(b"tEXt");
|
||||
ancillary.extend(crc32fast::hash(b"tEXt").to_be_bytes());
|
||||
let mut with_ancillary = b.clone();
|
||||
let at = b.len() - 12;
|
||||
with_ancillary.splice(at..at, ancillary);
|
||||
let png_length = (with_ancillary.len() - 101) as u32;
|
||||
with_ancillary[84..88].copy_from_slice(&(png_length + 13).to_le_bytes());
|
||||
with_ancillary[96..100].copy_from_slice(&png_length.to_le_bytes());
|
||||
assert!(preview(&with_ancillary).is_ok());
|
||||
with_ancillary[at + 8] ^= 1;
|
||||
assert_eq!(preview(&with_ancillary).unwrap_err(), Error::Malformed("PNG chunk checksum"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_metadata_and_animation_are_not_preview_support() {
|
||||
for kind in [b"zTXt", b"iTXt", b"iCCP", b"acTL", b"fcTL", b"fdAT"] {
|
||||
let mut extra = vec![0; 4];
|
||||
extra.extend(kind);
|
||||
extra.extend(crc32fast::hash(kind).to_be_bytes());
|
||||
let mut b = fixture();
|
||||
let at = b.len() - 12;
|
||||
b.splice(at..at, extra);
|
||||
let length = (b.len() - 101) as u32;
|
||||
b[84..88].copy_from_slice(&(length + 13).to_le_bytes());
|
||||
b[96..100].copy_from_slice(&length.to_le_bytes());
|
||||
assert!(matches!(preview(&b), Err(Error::Unsupported(_))));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn critical_chunks_follow_a_single_complete_png_layout() {
|
||||
fn with_chunks(kinds: &[&[u8; 4]]) -> Vec<u8> {
|
||||
let original = fixture();
|
||||
let mut b = original[..134].to_vec(); // File, record and complete first IHDR.
|
||||
for kind in kinds {
|
||||
b.extend([0; 4]);
|
||||
b.extend(*kind);
|
||||
b.extend(crc32fast::hash(*kind).to_be_bytes());
|
||||
}
|
||||
let length = (b.len() - 101) as u32;
|
||||
b[84..88].copy_from_slice(&(length + 13).to_le_bytes());
|
||||
b[96..100].copy_from_slice(&length.to_le_bytes());
|
||||
b
|
||||
}
|
||||
assert!(preview(&with_chunks(&[b"IDAT", b"IDAT", b"IEND"])).is_ok());
|
||||
// PNG readers must not reject an otherwise valid unknown ancillary chunk just
|
||||
// because its reserved (third-letter) bit is set; future versions can define it.
|
||||
assert!(preview(&with_chunks(&[b"abct", b"IDAT", b"IEND"])).is_ok());
|
||||
for kinds in [
|
||||
vec![b"IEND"],
|
||||
vec![b"IDAT", b"IHDR", b"IEND"],
|
||||
vec![b"PLTE", b"PLTE", b"IDAT", b"IEND"],
|
||||
vec![b"IDAT", b"PLTE", b"IEND"],
|
||||
vec![b"IDAT", b"tEXt", b"IDAT", b"IEND"],
|
||||
vec![b"ABCD", b"IDAT", b"IEND"],
|
||||
vec![b"IDAT", b"IEND", b"tEXt"],
|
||||
] {
|
||||
assert!(preview(&with_chunks(&kinds)).is_err(), "{kinds:?}");
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(256))]
|
||||
#[test]
|
||||
fn arbitrary_input_never_panics(b in prop::collection::vec(any::<u8>(), 0..2048)) {
|
||||
let _ = header(&b);
|
||||
let _ = preview(&b);
|
||||
}
|
||||
#[test]
|
||||
fn mutations_never_panic(edits in prop::collection::vec((0usize..200, any::<u8>()), 0..32)) {
|
||||
let mut b = fixture();
|
||||
for (i, value) in edits { if let Some(v) = b.get_mut(i) { *v = value; } }
|
||||
let _ = preview(&b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod archive {
|
||||
use crate::Error;
|
||||
use crate::container::{Archive, Limits};
|
||||
use crate::stream::{self, Kind, Tag, Value};
|
||||
use crate::synth::{self, F, Method, tag};
|
||||
use proptest::prelude::*;
|
||||
|
||||
fn doc() -> Vec<u8> {
|
||||
synth::stream(&[
|
||||
(tag(b"Desc"), F::Str("Document".into())),
|
||||
(tag(b"Visi"), F::Bool(true)),
|
||||
(tag(b"Xfrm"), F::F64s(vec![1.0, 0.0, 5.0, 0.0, 1.0, -2.0])),
|
||||
(tag(b"Colr"), F::Def(7, vec![tag(b"RGBA")], vec![(tag(b"_col"), F::Struct([0u8; 16].to_vec()))])),
|
||||
(tag(b"Same"), F::Ref(7)),
|
||||
(tag(b"Null"), F::Null),
|
||||
(tag(b"Kids"), F::Shared(vec![F::Def(8, vec![tag(b"Grup"), tag(b"Node")], vec![(tag(b"Desc"), F::Str("g".into()))]), F::Ref(8)])),
|
||||
(
|
||||
tag(b"Crvs"),
|
||||
F::Obj(tag(b"PCvD"), vec![(tag(b"Data"), F::Pos(vec![F::U8(0), F::U32(1), F::Bool(true), F::Records(18, vec![vec![0; 18]; 4])]))]),
|
||||
),
|
||||
(tag(b"Enum"), F::Enum(2, 1)),
|
||||
(tag(b"Tile"), F::Entry("d/3".into())),
|
||||
(tag(b"Stat"), F::U8s(vec![4, 0, 2])),
|
||||
])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_method_round_trips_with_checksums() {
|
||||
let d = doc();
|
||||
for method in [Method::Stored, Method::Zlib, Method::Zstd] {
|
||||
let file = synth::container(&[("doc.dat", &d, method), ("d/3", b"tile", method)], None);
|
||||
let mut a = Archive::open(&file, Limits::default()).unwrap();
|
||||
assert_eq!(a.header.version, 12);
|
||||
assert_eq!(a.read("doc.dat").unwrap(), d);
|
||||
assert_eq!(a.read("d/3").unwrap(), b"tile");
|
||||
assert_eq!(a.extracted(), d.len() + 4);
|
||||
assert!(a.read("missing").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stream_parses_into_shared_objects_and_links() {
|
||||
let s = stream::parse(&doc()).unwrap();
|
||||
let root = &s.objects[s.root];
|
||||
assert_eq!(root.class, Tag::of(b"Pers"));
|
||||
assert_eq!(root.get(Tag::of(b"Desc")), Some(&Value::Str("Document".into())));
|
||||
assert_eq!(root.get(Tag::of(b"Xfrm")), Some(&Value::Floats(vec![1.0, 0.0, 5.0, 0.0, 1.0, -2.0])));
|
||||
let (Some(Value::Obj(Some(a))), Some(Value::Obj(Some(b)))) = (root.get(Tag::of(b"Colr")), root.get(Tag::of(b"Same"))) else { panic!() };
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(s.objects[*a].class, Tag::of(b"RGBA"));
|
||||
assert_eq!(s.objects[*a].kind, Kind::Shared);
|
||||
let Some(Value::Array(kids)) = root.get(Tag::of(b"Kids")) else { panic!() };
|
||||
assert_eq!(kids[0], kids[1]);
|
||||
let Value::Obj(Some(g)) = kids[0] else { panic!() };
|
||||
assert_eq!(s.objects[g].chain, vec![Tag::of(b"Grup"), Tag::of(b"Node")]);
|
||||
assert_eq!(root.get(Tag::of(b"Enum")), Some(&Value::Enum { id: 2, version: 1 }));
|
||||
assert_eq!(root.get(Tag::of(b"Tile")), Some(&Value::Entry("d/3".into())));
|
||||
assert_eq!(root.get(Tag::of(b"Null")), Some(&Value::Obj(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksums_sizes_and_budgets_are_enforced() {
|
||||
let d = doc();
|
||||
let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None);
|
||||
// Flip a byte inside the compressed payload, past the "#Fil" tag at offset 72.
|
||||
let mut broken = file.clone();
|
||||
broken[90] ^= 0x55;
|
||||
let mut a = Archive::open(&broken, Limits::default()).unwrap();
|
||||
assert!(a.read("doc.dat").is_err());
|
||||
let mut a = Archive::open(&file, Limits { max_entry: d.len() - 1, max_total: usize::MAX }).unwrap();
|
||||
assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_))));
|
||||
let mut a = Archive::open(&file, Limits { max_entry: usize::MAX, max_total: d.len() + 1 }).unwrap();
|
||||
a.read("doc.dat").unwrap();
|
||||
assert!(matches!(a.read("doc.dat"), Err(Error::Limit(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_that_fails_its_checksum_is_charged_once_and_not_decompressed_again() {
|
||||
let d = doc();
|
||||
let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None);
|
||||
let mut broken = file.clone();
|
||||
broken[90] ^= 0x55;
|
||||
let mut a = Archive::open(&broken, Limits::default()).unwrap();
|
||||
let first = a.read("doc.dat").unwrap_err();
|
||||
// The work was done, so it counts against the import even though it failed.
|
||||
assert_eq!(a.extracted(), d.len());
|
||||
assert_eq!(a.read("doc.dat").unwrap_err(), first);
|
||||
assert_eq!(a.extracted(), d.len());
|
||||
// A budget that only covers one attempt is not exceeded by asking again.
|
||||
let mut a = Archive::open(&broken, Limits { max_entry: usize::MAX, max_total: d.len() }).unwrap();
|
||||
assert!(a.read("doc.dat").is_err());
|
||||
assert_eq!(a.read("doc.dat").unwrap_err(), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_table_index_has_a_budget_for_records_and_names() {
|
||||
let d = doc();
|
||||
let long = "n".repeat(300);
|
||||
let file = synth::container(&[("doc.dat", &d, Method::Stored), (&long, b"tile", Method::Stored)], None);
|
||||
Archive::open_within(&file, Limits::default(), 2, 307).unwrap();
|
||||
assert_eq!(Archive::open_within(&file, Limits::default(), 1, 1 << 20).unwrap_err(), Error::Limit("too many archive entries"));
|
||||
assert_eq!(Archive::open_within(&file, Limits::default(), 2, 306).unwrap_err(), Error::Limit("archive entry names too long"));
|
||||
}
|
||||
|
||||
// Regression test for #1710: ruzstd 0.9.0 let a block decompress to more than its frame's
|
||||
// window allows (RUSTSEC-2026-0344), so a crafted entry made the decoder produce far more than
|
||||
// the format permits for a block. 0.9.1 refuses it.
|
||||
#[test]
|
||||
fn a_zstd_block_larger_than_its_frames_window_is_refused() {
|
||||
const LEN: u32 = 100_000;
|
||||
let plain = vec![0x61u8; LEN as usize];
|
||||
let file = synth::container(&[("doc.dat", &plain, Method::Zstd)], None);
|
||||
// A Zstandard frame with a 1 KiB window (descriptor byte 0, window byte 0) holding one RLE
|
||||
// block, the last, that repeats a byte LEN times: block header = last | RLE << 1 | LEN << 3.
|
||||
let mut frame = vec![0x28, 0xB5, 0x2F, 0xFD, 0x00, 0x00];
|
||||
frame.extend((1 | (1 << 1) | (LEN << 3)).to_le_bytes().get(..3).unwrap());
|
||||
frame.push(0x61);
|
||||
// Swap it in for the entry's compressed bytes (they follow the "#Fil" tag at offset 72).
|
||||
let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()) as usize;
|
||||
let old_len = u64::from_le_bytes(file[fat + 59 + 21..fat + 59 + 29].try_into().unwrap()) as usize;
|
||||
let mut swapped = file[..76].to_vec();
|
||||
swapped.extend(&frame);
|
||||
swapped.extend(&file[76 + old_len..]);
|
||||
let new_fat = fat - old_len + frame.len();
|
||||
swapped[16..24].copy_from_slice(&(new_fat as u64).to_le_bytes());
|
||||
swapped[new_fat + 59 + 21..new_fat + 59 + 29].copy_from_slice(&(frame.len() as u64).to_le_bytes());
|
||||
let mut a = Archive::open(&swapped, Limits::default()).unwrap();
|
||||
assert!(a.read("doc.dat").is_err(), "a block of {LEN} bytes was decompressed from a frame with a 1 KiB window");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declared_size_smaller_than_the_data_is_rejected_not_truncated() {
|
||||
let big = vec![7u8; 1 << 20];
|
||||
let mut file = synth::container(&[("doc.dat", &big, Method::Zlib)], None);
|
||||
// Rewrite the declared size in the table to 1 KiB: decoding must stop and fail.
|
||||
let fat = u64::from_le_bytes(file[16..24].try_into().unwrap()) as usize;
|
||||
let size_at = fat + 59 + 5 + 8;
|
||||
file[size_at..size_at + 8].copy_from_slice(&1024u64.to_le_bytes());
|
||||
let mut a = Archive::open(&file, Limits::default()).unwrap();
|
||||
assert_eq!(a.read("doc.dat").unwrap_err(), Error::Malformed("archive entry size mismatch"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn libraries_and_cyclic_tables_are_rejected() {
|
||||
let d = doc();
|
||||
let mut file = synth::container(&[("doc.dat", &d, Method::Stored)], None);
|
||||
let mut library = file.clone();
|
||||
library[8..12].copy_from_slice(b"rAsA");
|
||||
assert!(matches!(Archive::open(&library, Limits::default()), Err(Error::Unsupported(_))));
|
||||
let fat = u64::from_le_bytes(file[16..24].try_into().unwrap());
|
||||
let at = fat as usize + 4;
|
||||
file[at..at + 8].copy_from_slice(&fat.to_le_bytes());
|
||||
assert_eq!(Archive::open(&file, Limits::default()).unwrap_err(), Error::Malformed("allocation tables form a cycle"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_streams_fail_cleanly() {
|
||||
let deep = (0..2000).fold(Vec::new(), |inner, _| vec![(tag(b"Chld"), F::Obj(tag(b"Grup"), inner))]);
|
||||
assert_eq!(stream::parse(&synth::stream(&deep)).unwrap_err(), Error::Limit("objects nested too deeply"));
|
||||
// An array claiming four billion elements in a few bytes.
|
||||
let huge = synth::stream(&[(tag(b"Big_"), F::Raw(vec![0x81, b'_', b'g', b'i', b'B', 0xff, 0xff, 0xff, 0xff, 0]))]);
|
||||
assert_eq!(stream::parse(&huge).unwrap_err(), Error::Malformed("array longer than its data"));
|
||||
let forward = synth::stream(&[(tag(b"Link"), F::Ref(99))]);
|
||||
assert!(stream::parse(&forward).is_err());
|
||||
let twice = synth::stream(&[(tag(b"A___"), F::Def(1, vec![tag(b"RGBA")], vec![])), (tag(b"B___"), F::Def(1, vec![tag(b"RGBA")], vec![]))]);
|
||||
assert!(stream::parse(&twice).is_err());
|
||||
let unknown = synth::stream(&[(tag(b"X___"), F::Raw(vec![0x0b, 1, 2, 3, 4]))]);
|
||||
assert!(matches!(stream::parse(&unknown), Err(Error::Unsupported(_))));
|
||||
let d = doc();
|
||||
for end in 0..d.len() {
|
||||
assert!(stream::parse(&d[..end]).is_err(), "{end}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_compressed_entry_cannot_make_the_stream_allocate_gigabytes() {
|
||||
// Each decoded value takes about 40 bytes, and a bool array packs eight in a byte: 16 MiB
|
||||
// of zero bits, a few KiB once compressed, would ask for 2^27 values (about 4 GiB). An
|
||||
// array of one-byte values just past the budget fails the same way, before allocating.
|
||||
let field = |code: u8, n: u32, data: usize| {
|
||||
let mut f = vec![0x80 | code];
|
||||
f.extend(tag(b"Big_").0.to_le_bytes());
|
||||
f.extend(n.to_le_bytes());
|
||||
f.resize(f.len() + data, 0);
|
||||
F::Raw(f)
|
||||
};
|
||||
let bools = 1u32 << 27;
|
||||
let bytes = u32::try_from(stream::MAX_VALUES).unwrap() + 1;
|
||||
for f in [field(0x29, bools, (bools / 8) as usize), field(0x01, bytes, bytes as usize)] {
|
||||
let d = synth::stream(&[(tag(b"Big_"), f)]);
|
||||
let file = synth::container(&[("doc.dat", &d, Method::Zstd)], None);
|
||||
assert!(file.len() < d.len() / 100, "{} of {}", file.len(), d.len());
|
||||
let entry = Archive::open(&file, Limits::default()).unwrap().read("doc.dat").unwrap();
|
||||
assert_eq!(stream::parse(&entry).unwrap_err(), Error::Limit("too many values in the document stream"));
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(512))]
|
||||
#[test]
|
||||
fn mutated_containers_and_streams_never_panic(edits in prop::collection::vec((0usize..4096, any::<u8>()), 1..24)) {
|
||||
let d = doc();
|
||||
for method in [Method::Stored, Method::Zlib, Method::Zstd] {
|
||||
let mut file = synth::container(&[("doc.dat", &d, method)], None);
|
||||
for (i, v) in &edits {
|
||||
let n = file.len();
|
||||
file[i % n] = *v;
|
||||
}
|
||||
if let Ok(bytes) = Archive::open(&file, Limits::default()).and_then(|mut a| a.read("doc.dat")) {
|
||||
let _ = stream::parse(&bytes);
|
||||
}
|
||||
}
|
||||
let mut s = d.clone();
|
||||
for (i, v) in &edits {
|
||||
let n = s.len();
|
||||
s[i % n] = *v;
|
||||
}
|
||||
let _ = stream::parse(&s);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,564 +0,0 @@
|
||||
//! Artistic and frame text: the story's characters with their font, size, colour, tracking and
|
||||
//! leading, the paragraph alignment and the first baseline. Layout (line breaks in frames, kerning,
|
||||
//! OpenType features) is left to the importing application.
|
||||
|
||||
use crate::model::{Affine, Align, Paragraph, Point, Reader, Table, TableCell, Text, TextRun, VAlign, rect};
|
||||
use crate::paint::{self, Color, Paint};
|
||||
use crate::stream::{ObjId, Value};
|
||||
|
||||
/// Characters read per text node (stories are split into blocks; this caps hostile ones).
|
||||
const MAX_CHARS: usize = 1 << 20;
|
||||
/// Shared character attributes must not amplify into unbounded font/feature/gradient data.
|
||||
const MAX_ATTRIBUTE_BYTES: usize = 16 << 20;
|
||||
|
||||
/// Ends a table cell in a table's story (Affinity's break glyph of kind 4).
|
||||
pub const CELL_BREAK: char = '\u{1F}';
|
||||
|
||||
pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option<Text> {
|
||||
let s = r.s;
|
||||
let story = s.obj(id, b"StSt")?;
|
||||
let frame = s.obj(id, b"TxtH")?;
|
||||
let artistic = s.is(frame, b"ArFr");
|
||||
let bounds = s.floats::<4>(frame, b"FrmB").map(rect)?;
|
||||
let (runs, align) = story_runs(r, story, world);
|
||||
let first_baseline = bounds.y0 + s.f64(frame, b"ArtV").unwrap_or(0.0);
|
||||
let anchor_x = match align {
|
||||
Align::Center => (bounds.x0 + bounds.x1) / 2.0,
|
||||
Align::Right => bounds.x1,
|
||||
_ => bounds.x0,
|
||||
};
|
||||
if !artistic {
|
||||
if s.objs(frame, b"ColW").len() > 1 || matches!(s.field(frame, b"ColW"), Some(Value::Array(a)) if a.len() > 1) {
|
||||
r.warn("text frames with several columns (imported as one column)");
|
||||
}
|
||||
if s.class(id) == Some(crate::stream::Tag::of(b"TxtC")) {
|
||||
r.warn("text frames with a curved outline (imported as rectangular frames)");
|
||||
}
|
||||
}
|
||||
let text_transform = if artistic { world } else { text_scale(r, id).then(r.type_base) };
|
||||
Some(Text {
|
||||
runs,
|
||||
align,
|
||||
anchor: Point { x: anchor_x, y: first_baseline },
|
||||
frame: if artistic { None } else { Some(bounds) },
|
||||
transform: world,
|
||||
text_transform,
|
||||
})
|
||||
}
|
||||
|
||||
/// Rows and columns a table may have.
|
||||
const MAX_TABLE_LINES: usize = 4096;
|
||||
/// Cells a table may have (rows × columns): each becomes a text object with its edge lines.
|
||||
const MAX_TABLE_CELLS: usize = 1 << 16;
|
||||
|
||||
/// Work charged for each copy of a run's formatting a table cell keeps.
|
||||
const TABLE_RUN_COST: usize = 16;
|
||||
|
||||
/// A table node (`TxtT`): the grid, the cells' text and the lines on the cell edges.
|
||||
pub(crate) fn table(r: &mut Reader, id: ObjId, world: Affine) -> Option<Table> {
|
||||
let s = r.s;
|
||||
let story = s.obj(id, b"StSt")?;
|
||||
let tabl = s.obj(id, b"TxtH").and_then(|h| s.obj(h, b"Tabl"))?;
|
||||
let bounds = |pos: Option<ObjId>| -> Option<Vec<f64>> {
|
||||
let Some(Value::Array(a)) = pos.and_then(|p| s.field(p, b"Posn")) else { return None };
|
||||
let v: Vec<f64> = a.iter().take(MAX_TABLE_LINES + 2).map(float).collect::<Option<_>>()?;
|
||||
(v.len() >= 2 && v.len() <= MAX_TABLE_LINES + 1 && v.windows(2).all(|w| w[1] >= w[0])).then_some(v)
|
||||
};
|
||||
let columns = bounds(s.obj(tabl, b"CPos"))?;
|
||||
let rows = bounds(s.obj(tabl, b"RPos"))?;
|
||||
let (ncols, nrows) = (columns.len() - 1, rows.len() - 1);
|
||||
let count = ncols.checked_mul(nrows)?;
|
||||
if count > MAX_TABLE_CELLS {
|
||||
r.warn("tables with more than 65536 cells (left out)");
|
||||
return None;
|
||||
}
|
||||
let Some(left) = r.budget.cells.checked_sub(count) else {
|
||||
r.warn("tables beyond the cells one document may hold (left out)");
|
||||
return None;
|
||||
};
|
||||
r.budget.cells = left;
|
||||
let cell_objs = s.obj(tabl, b"Cell").map(|c| s.objs(c, b"Cell")).unwrap_or_default();
|
||||
// Formatting that doesn't match the grid would land on the wrong cells (and merging them,
|
||||
// move text between cells): only text then.
|
||||
let cell_objs = if cell_objs.len() == count {
|
||||
cell_objs
|
||||
} else {
|
||||
r.warn("tables whose cells don't match their grid (cell formatting left out)");
|
||||
Vec::new()
|
||||
};
|
||||
let blank = || TableCell { runs: Vec::new(), inset: [0.0; 4], valign: VAlign::Top, merged_left: false };
|
||||
let mut cells: Vec<TableCell> = (0..count).map(|_| blank()).collect();
|
||||
for (i, (cell, obj)) in cells.iter_mut().zip(&cell_objs).enumerate() {
|
||||
if let Some(inset) = s.floats::<4>(*obj, b"Inse").filter(|v| v.iter().all(|x| x.is_finite() && *x >= 0.0)) {
|
||||
cell.inset = inset;
|
||||
}
|
||||
cell.valign = match s.enumeration(*obj, b"AliY").map(|(i, _)| i) {
|
||||
Some(1) => VAlign::Center,
|
||||
Some(2) => VAlign::Bottom,
|
||||
_ => VAlign::Top,
|
||||
};
|
||||
// A cell merged into the one on its left; the first column has nothing to its left.
|
||||
cell.merged_left = i % ncols != 0 && s.bool(*obj, b"BrLf") == Some(true);
|
||||
}
|
||||
// The story holds the text of every cell that isn't merged away, row by row, each ended by a
|
||||
// cell break.
|
||||
let owner_list: Vec<usize> = (0..count).filter(|i| cells.get(*i).is_some_and(|c| !c.merged_left)).collect();
|
||||
let mut owners = owner_list.into_iter();
|
||||
let mut target = owners.next();
|
||||
let mut extra = false;
|
||||
let (runs, _) = story_runs(r, story, world);
|
||||
for run in runs {
|
||||
let mut parts = run.text.split(CELL_BREAK).peekable();
|
||||
while let Some(part) = parts.next() {
|
||||
if !part.is_empty() {
|
||||
// Each cell keeps its own copy of the run's formatting, so each copy is charged.
|
||||
match target.and_then(|i| cells.get_mut(i)) {
|
||||
Some(cell) if r.budget.spend(TABLE_RUN_COST).is_ok() => cell.runs.push(TextRun { text: part.to_string(), ..run.clone() }),
|
||||
_ => extra = true,
|
||||
}
|
||||
}
|
||||
if parts.peek().is_some() {
|
||||
target = owners.next();
|
||||
}
|
||||
}
|
||||
}
|
||||
if extra {
|
||||
r.warn("table text beyond its last cell (left out)");
|
||||
}
|
||||
let mut edges = |tag: &[u8; 4], expected: usize| -> Vec<Option<crate::paint::Stroke>> {
|
||||
let objs = s.obj(tabl, tag).map(|e| s.objs(e, b"Edge")).unwrap_or_default();
|
||||
if objs.len() != expected {
|
||||
r.warn("tables whose lines don't match their grid (lines left out)");
|
||||
return Vec::new();
|
||||
}
|
||||
objs.into_iter()
|
||||
.map(|e| match (s.obj(e, b"Fill"), s.obj(e, b"Line")) {
|
||||
(Some(pen), Some(line)) => paint::stroke(r, pen, line, world, false),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let vertical = edges(b"CEdg", (ncols + 1) * nrows);
|
||||
let horizontal = edges(b"REdg", ncols * (nrows + 1));
|
||||
if let Some(format) = s.obj(tabl, b"TFmt") {
|
||||
let filled =
|
||||
s.objs(format, b"Clls").into_iter().filter_map(|c| s.obj(c, b"Fill")).any(|f| s.obj(f, b"FDeF").is_some_and(|d| !s.is(d, b"FilN")));
|
||||
if filled {
|
||||
r.warn("table cell fills (left out)");
|
||||
}
|
||||
}
|
||||
let text_transform = text_scale(r, id).then(r.type_base);
|
||||
Some(Table { columns, rows, cells, vertical, horizontal, transform: world, text_transform })
|
||||
}
|
||||
|
||||
/// A story's character runs, each with its paragraph's format, and the first paragraph's
|
||||
/// alignment. Table cells end with [`CELL_BREAK`].
|
||||
pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<TextRun>, Align) {
|
||||
let s = r.s;
|
||||
let mut runs = Vec::new();
|
||||
let mut first_align = None;
|
||||
let mut total = 0usize;
|
||||
let mut placeholders = false;
|
||||
let mut attribute_budget = Some(MAX_ATTRIBUTE_BYTES);
|
||||
for block in s.objs(story, b"Blok") {
|
||||
// Shared blocks and run lists are visited once per link, so every visit is charged, empty or not.
|
||||
let paragraph_runs = s.obj(block, b"PAtt").map(|p| s.objs(p, b"Runs")).unwrap_or_default();
|
||||
let attribute_runs = s.obj(block, b"GAtt").map(|g| s.objs(g, b"Runs")).unwrap_or_default();
|
||||
if r.budget.spend(1 + paragraph_runs.len() + attribute_runs.len()).is_err() {
|
||||
r.warn("text beyond the work one document may hold (truncated)");
|
||||
break;
|
||||
}
|
||||
let Some(glyphs) = s.obj(block, b"Glyp") else {
|
||||
r.warn("a text block without readable characters (left out)");
|
||||
continue;
|
||||
};
|
||||
// Bound collection itself, including placeholders, before allocating the character buffer:
|
||||
// by the story's limit and by what the document's other stories left.
|
||||
let budget = (MAX_CHARS - total).min(r.budget.chars.saturating_sub(total));
|
||||
|
||||
let mut chars: Vec<char> = match s.str(glyphs, b"Utf8") {
|
||||
Some(t) => t.chars().take(budget + 1).collect(),
|
||||
None => {
|
||||
// Inline objects (page numbers, anchors, cell ends) each take one index before
|
||||
// the segment text.
|
||||
let segments = s.objs(glyphs, b"Mixd");
|
||||
if segments.is_empty() {
|
||||
r.warn("a text block without readable characters (left out)");
|
||||
continue;
|
||||
}
|
||||
let mut v = Vec::new();
|
||||
for seg in segments {
|
||||
for inline in s.objs(seg, b"Glys") {
|
||||
if v.len() > budget {
|
||||
break;
|
||||
}
|
||||
if s.is(inline, b"BrGl") && s.enumeration(inline, b"HdBk").is_some_and(|(kind, _)| kind == 4) {
|
||||
v.push(CELL_BREAK);
|
||||
} else {
|
||||
v.push('\u{FFFC}');
|
||||
placeholders = true;
|
||||
}
|
||||
}
|
||||
v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take((budget + 1).saturating_sub(v.len())));
|
||||
if v.len() > budget {
|
||||
break;
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
};
|
||||
let truncated = chars.len() > budget;
|
||||
if truncated {
|
||||
chars.truncate(budget);
|
||||
if budget < MAX_CHARS - total {
|
||||
r.warn("text beyond the characters one document may hold (truncated)");
|
||||
} else {
|
||||
r.warn("text longer than a million characters (truncated)");
|
||||
}
|
||||
}
|
||||
total += chars.len();
|
||||
// Paragraph formats by end index; a run without an index covers the rest of the block.
|
||||
let mut paragraphs: Vec<(usize, Paragraph)> = Vec::new();
|
||||
let mut open: Option<Paragraph> = None;
|
||||
for run in paragraph_runs {
|
||||
let Some(attrs) = s.obj(run, b"Item") else { continue };
|
||||
let a = paragraph(r, attrs);
|
||||
first_align.get_or_insert(a.align);
|
||||
match s.int(run, b"Indx").and_then(|v| usize::try_from(v).ok()) {
|
||||
Some(end) => paragraphs.push((end, a)),
|
||||
None => match open {
|
||||
None => open = Some(a),
|
||||
Some(first) if first != a => r.warn("mixed paragraph formats in one block (the first is used)"),
|
||||
_ => {}
|
||||
},
|
||||
}
|
||||
}
|
||||
// Sorted by end (they are in order in every file), so both lookups below are binary
|
||||
// searches: a block can have as many paragraphs and runs as characters.
|
||||
paragraphs.sort_by_key(|(end, _)| *end);
|
||||
let align_at = |i: usize| paragraphs.get(paragraphs.partition_point(|(end, _)| *end <= i)).map(|(_, a)| *a).or(open).unwrap_or_default();
|
||||
let mut cuts: Vec<usize> = paragraphs.iter().map(|(end, _)| *end).filter(|e| *e < chars.len()).collect();
|
||||
cuts.dedup();
|
||||
let push = |r: &mut Reader, runs: &mut Vec<TextRun>, attrs: Option<ObjId>, from: usize, to: usize, budget: &mut Option<usize>| {
|
||||
// Split at paragraph ends so every run has one paragraph format.
|
||||
let inside = cuts.get(cuts.partition_point(|c| *c <= from)..cuts.partition_point(|c| *c < to)).unwrap_or_default();
|
||||
let mut a = from;
|
||||
for &c in inside.iter().chain(std::iter::once(&to)) {
|
||||
push_run(r, runs, attrs, characters(&chars, a, c), world, budget, align_at(a));
|
||||
a = c;
|
||||
}
|
||||
};
|
||||
let mut start = 0usize;
|
||||
for run in attribute_runs {
|
||||
let Some(index) = s.int(run, b"Indx").and_then(|v| usize::try_from(v).ok()) else {
|
||||
r.warn("invalid text attribute range (bounded; unassigned characters use defaults)");
|
||||
continue;
|
||||
};
|
||||
let end = index.min(chars.len());
|
||||
if index > chars.len() || end < start {
|
||||
r.warn("invalid text attribute range (bounded; unassigned characters use defaults)");
|
||||
}
|
||||
if end <= start {
|
||||
continue;
|
||||
}
|
||||
push(r, &mut runs, s.obj(run, b"Item"), start, end, &mut attribute_budget);
|
||||
start = end;
|
||||
}
|
||||
if start < chars.len() {
|
||||
push(r, &mut runs, None, start, chars.len(), &mut attribute_budget);
|
||||
}
|
||||
if truncated {
|
||||
break;
|
||||
}
|
||||
}
|
||||
r.budget.chars = r.budget.chars.saturating_sub(total);
|
||||
if placeholders {
|
||||
r.warn("text fields such as page numbers (left out of the text)");
|
||||
}
|
||||
(runs, first_align.unwrap_or(Align::Left))
|
||||
}
|
||||
|
||||
fn characters(chars: &[char], start: usize, end: usize) -> String {
|
||||
chars.get(start..end).unwrap_or_default().iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect()
|
||||
}
|
||||
|
||||
fn push_run(
|
||||
r: &mut Reader,
|
||||
runs: &mut Vec<TextRun>,
|
||||
attrs: Option<ObjId>,
|
||||
text: String,
|
||||
world: Affine,
|
||||
attribute_budget: &mut Option<usize>,
|
||||
paragraph: Paragraph,
|
||||
) {
|
||||
if text.is_empty() {
|
||||
return;
|
||||
}
|
||||
let run = match attrs {
|
||||
Some(attrs) if attribute_budget.is_some() => TextRun { paragraph, ..run_attrs(r, attrs, text, world, attribute_budget) },
|
||||
_ => {
|
||||
// This is a recovery policy, not an assertion about unspecified Affinity attributes.
|
||||
if attrs.is_none() {
|
||||
r.warn("text without character attributes (characters preserved with default attributes)");
|
||||
}
|
||||
TextRun {
|
||||
text,
|
||||
postscript: String::new(),
|
||||
family: String::new(),
|
||||
weight: 400,
|
||||
italic: false,
|
||||
features: Vec::new(),
|
||||
all_caps: false,
|
||||
underline: false,
|
||||
strikethrough: false,
|
||||
size: 12.0 * r.dpi / 72.0,
|
||||
tracking: 0.0,
|
||||
h_scale: 1.0,
|
||||
leading: None,
|
||||
fill: Paint::Solid(Color::Gray { v: 0.0, a: 1.0 }),
|
||||
stroke: None,
|
||||
paragraph,
|
||||
}
|
||||
}
|
||||
};
|
||||
runs.push(run);
|
||||
}
|
||||
|
||||
fn slot<T: Copy>(v: Option<&Value>, i: usize, f: impl Fn(&Value) -> Option<T>) -> Option<T> {
|
||||
match v? {
|
||||
Value::Array(a) => a.get(i).and_then(f),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn float(v: &Value) -> Option<f64> {
|
||||
match v {
|
||||
Value::Float(f) if f.is_finite() => Some(*f),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn int(v: &Value) -> Option<i64> {
|
||||
match v {
|
||||
Value::Int(i) => Some(*i),
|
||||
Value::UInt(u) => i64::try_from(*u).ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn run_attrs(r: &mut Reader, attrs: ObjId, text: String, world: Affine, attribute_budget: &mut Option<usize>) -> TextRun {
|
||||
let s = r.s;
|
||||
let doubles = s.field(attrs, b"Doub");
|
||||
let ints = s.field(attrs, b"Ints");
|
||||
let size = slot(doubles, 0, float).filter(|v| *v > 0.0 && *v < 1e6).unwrap_or(12.0 * r.dpi / 72.0);
|
||||
let tracking = slot(doubles, 4, float).unwrap_or(0.0);
|
||||
let leading = (slot(ints, 4, int) == Some(1)).then(|| slot(doubles, 13, float)).flatten().filter(|v| *v > 0.0);
|
||||
let objects = match s.field(attrs, b"Objs") {
|
||||
Some(Value::Array(a)) => a.iter().take(8).map(|v| if let Value::Obj(o) = v { *o } else { None }).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let mut fill = match objects.first().copied().flatten().and_then(|f| paint::descriptor(r, f, world)) {
|
||||
Some(fill) => fill,
|
||||
None => {
|
||||
r.warn("text without readable fill attributes (default black used)");
|
||||
Paint::Solid(Color::Gray { v: 0.0, a: 1.0 })
|
||||
}
|
||||
};
|
||||
// A single descriptor decode is bounded by paint::MAX_STOPS. Charge its owned stop data
|
||||
// before keeping it; subsequent runs skip attribute decoding once the budget is exhausted.
|
||||
if let Paint::Gradient(gradient) = &fill {
|
||||
let bytes = gradient.stops.len().saturating_mul(std::mem::size_of::<paint::Stop>());
|
||||
if !charge_attributes(r, attribute_budget, bytes) {
|
||||
fill = Paint::Solid(Color::Gray { v: 0.0, a: 1.0 });
|
||||
}
|
||||
}
|
||||
// Outlined characters: `Objs` 1 is the outline's paint, 2 its line style (as for shapes).
|
||||
let mut stroke = match (attribute_budget.is_some(), objects.get(1).copied().flatten(), objects.get(2).copied().flatten()) {
|
||||
(true, Some(pen), Some(style)) => paint::stroke(r, pen, style, Affine::IDENTITY, false),
|
||||
_ => None,
|
||||
};
|
||||
// Its gradient stops and dashes are owned data too, charged like the fill's.
|
||||
if let Some(st) = &stroke {
|
||||
let stops = match &st.paint {
|
||||
Paint::Gradient(g) => g.stops.len().saturating_mul(std::mem::size_of::<paint::Stop>()),
|
||||
_ => 0,
|
||||
};
|
||||
let dash = st.dash.as_ref().map_or(0, |(d, _)| d.len().saturating_mul(std::mem::size_of::<f64>()));
|
||||
if !charge_attributes(r, attribute_budget, stops.saturating_add(dash)) {
|
||||
stroke = None;
|
||||
}
|
||||
}
|
||||
// Underline (slot 0) and strikethrough (slot 1): 1 is a single line.
|
||||
let mut decoration = |i: usize| match slot(ints, i, int) {
|
||||
Some(1) => true,
|
||||
Some(0) | None => false,
|
||||
Some(_) => {
|
||||
r.warn("text decorations of an unknown kind (left out)");
|
||||
false
|
||||
}
|
||||
};
|
||||
let (underline, strikethrough) = (decoration(0), decoration(1));
|
||||
let h_scale = slot(doubles, 10, float).filter(|h| *h > 0.0 && *h < 100.0).unwrap_or(1.0);
|
||||
// A resolved font is populated on the emoji run of the public Affinity 3 text-runs file
|
||||
// (Courier New requested, Segoe UI Emoji stored in RFnt). Empty RFnt records are common.
|
||||
// Source: https://github.com/SethRobinson/Patchy/tree/de84eab550758b30fa062e479f5778cce7693b73/test-fixtures/af
|
||||
let requested = s.obj(attrs, b"DFnt");
|
||||
let resolved =
|
||||
s.obj(attrs, b"RFnt").filter(|f| !s.str(*f, b"Famy").unwrap_or_default().is_empty() || !s.str(*f, b"Post").unwrap_or_default().is_empty());
|
||||
let font = resolved.or(requested);
|
||||
if let Some(resolved) = resolved {
|
||||
let differs = [b"Famy", b"Post"]
|
||||
.iter()
|
||||
.any(|tag| s.str(resolved, tag).unwrap_or_default() != requested.and_then(|f| s.str(f, tag)).unwrap_or_default());
|
||||
if differs {
|
||||
r.warn("text uses a stored fallback font (imported with that font)");
|
||||
}
|
||||
}
|
||||
if font.and_then(|f| s.int(f, b"Widh")).is_some_and(|w| w != 5) {
|
||||
r.warn("font width variants (exact face depends on the installed PostScript font)");
|
||||
}
|
||||
let postscript = font_name(r, attribute_budget, font.and_then(|f| s.str(f, b"Post")).unwrap_or_default());
|
||||
let family = font_name(r, attribute_budget, font.and_then(|f| s.str(f, b"Famy")).unwrap_or_default());
|
||||
let (features, all_caps) = font_features(r, objects.get(7).copied().flatten(), attribute_budget);
|
||||
let weight = font.and_then(|f| s.int(f, b"Wegt")).unwrap_or(400);
|
||||
let weight = if (1..=1000).contains(&weight) {
|
||||
weight
|
||||
} else {
|
||||
r.warn("invalid font weight (imported as regular)");
|
||||
400
|
||||
};
|
||||
TextRun {
|
||||
text,
|
||||
postscript,
|
||||
family,
|
||||
weight,
|
||||
italic: font.and_then(|f| s.bool(f, b"Ital")).unwrap_or(false),
|
||||
features,
|
||||
all_caps,
|
||||
underline,
|
||||
strikethrough,
|
||||
size,
|
||||
tracking,
|
||||
h_scale,
|
||||
leading,
|
||||
fill,
|
||||
stroke,
|
||||
paragraph: Paragraph::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn charge_attributes(r: &mut Reader, budget: &mut Option<usize>, bytes: usize) -> bool {
|
||||
let Some(remaining) = *budget else { return false };
|
||||
match remaining.checked_sub(bytes) {
|
||||
Some(remaining) => {
|
||||
*budget = Some(remaining);
|
||||
true
|
||||
}
|
||||
None => {
|
||||
*budget = None;
|
||||
r.warn("text attribute budget exceeded (excess font names, features and gradients left out)");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Longest font name kept (OpenType names are far shorter); every run and paragraph carries it.
|
||||
const MAX_FONT_NAME: usize = 256;
|
||||
|
||||
fn font_name(r: &mut Reader, budget: &mut Option<usize>, value: &str) -> String {
|
||||
if value.len() > MAX_FONT_NAME {
|
||||
r.warn("font names longer than 256 bytes (the default font is used)");
|
||||
return String::new();
|
||||
}
|
||||
metadata_string(r, budget, value)
|
||||
}
|
||||
|
||||
fn metadata_string(r: &mut Reader, budget: &mut Option<usize>, value: &str) -> String {
|
||||
let bytes = value.len().saturating_add(std::mem::size_of::<String>());
|
||||
if value.is_empty() || !charge_attributes(r, budget, bytes) { String::new() } else { value.to_owned() }
|
||||
}
|
||||
|
||||
/// The public Affinity 3 caps fixture stores `smcp` and the private `CAP\x01` selector in
|
||||
/// OtAt/Setn. Only the observed all-caps selector and boolean OpenType tags are mapped; other
|
||||
/// values are reported, never guessed. Standard tag syntax: https://learn.microsoft.com/en-us/typography/opentype/spec/featuretags
|
||||
fn font_features(r: &mut Reader, attrs: Option<ObjId>, attribute_budget: &mut Option<usize>) -> (Vec<String>, bool) {
|
||||
let mut features = Vec::new();
|
||||
let mut all_caps = false;
|
||||
if attribute_budget.is_none() {
|
||||
return (features, all_caps);
|
||||
}
|
||||
let s = r.s;
|
||||
let Some(Value::Array(settings)) = attrs.and_then(|a| s.field(a, b"Setn")) else { return (features, all_caps) };
|
||||
for (index, setting) in settings.iter().take(257).enumerate() {
|
||||
if index == 256 {
|
||||
r.warn("more than 256 text feature settings (truncated)");
|
||||
break;
|
||||
}
|
||||
let Value::Obj(Some(setting)) = setting else {
|
||||
r.warn("unreadable text feature settings (imported with defaults)");
|
||||
continue;
|
||||
};
|
||||
let setting = *setting;
|
||||
let tag = s.int(setting, b"Feat").and_then(|v| u32::try_from(v).ok()).map(u32::to_be_bytes);
|
||||
let value = r.s.int(setting, b"Valu");
|
||||
match (tag, value) {
|
||||
(Some([b'C', b'A', b'P', 1]), Some(0 | 1)) => all_caps = value == Some(1),
|
||||
(Some(tag), Some(value @ (0 | 1))) if tag.iter().all(u8::is_ascii_alphanumeric) => {
|
||||
if !charge_attributes(r, attribute_budget, std::mem::size_of::<String>() + if value == 0 { 5 } else { 4 }) {
|
||||
break;
|
||||
}
|
||||
let name = String::from_utf8_lossy(&tag);
|
||||
features.push(if value == 0 { format!("-{name}") } else { name.into_owned() });
|
||||
}
|
||||
_ => r.warn("text feature selectors or non-boolean OpenType settings (imported with defaults)"),
|
||||
}
|
||||
}
|
||||
(features, all_caps)
|
||||
}
|
||||
|
||||
/// A paragraph's alignment, indents, spacing and leading. The `Doub` slots: 0 the automatic
|
||||
/// leading as a multiple of the font's line height (1 in every document checked), 1 fixed leading
|
||||
/// (when `Ints` slot 1 is 2; in every paragraph checked the two go together), 2 indent of the
|
||||
/// lines after the first, 3 right indent, 4 indent of the first line, 5 space before, 6 space
|
||||
/// after. Slots 2, 4, 5 and 6 were identified on the public MIT text-indent and text-para-spacing
|
||||
/// fixtures (Patchy) by measuring their thumbnails, slot 1 by measuring the baseline pitch in the
|
||||
/// thumbnail of a document whose owner made it earlier.
|
||||
fn paragraph(r: &mut Reader, p: ObjId) -> Paragraph {
|
||||
let doubles = r.s.field(p, b"Doub");
|
||||
let ints = r.s.field(p, b"Ints");
|
||||
let at = |i: usize| slot(doubles, i, float).filter(|v| v.abs() < 1e6).unwrap_or(0.0);
|
||||
let align = match slot(ints, 0, int) {
|
||||
Some(1) => Align::Center,
|
||||
Some(2) => Align::Right,
|
||||
Some(3) => Align::Justify,
|
||||
Some(0) | None => Align::Left,
|
||||
Some(_) => {
|
||||
r.warn("an unknown paragraph alignment (imported as left)");
|
||||
Align::Left
|
||||
}
|
||||
};
|
||||
let leading = match slot(ints, 1, int) {
|
||||
Some(2) => Some(at(1)).filter(|l| *l > 0.0),
|
||||
Some(0) | None => None,
|
||||
Some(_) => {
|
||||
r.warn("paragraph leading of an unknown kind (imported as automatic)");
|
||||
None
|
||||
}
|
||||
};
|
||||
let auto_leading = slot(doubles, 0, float).filter(|v| *v > 0.0 && *v < 100.0).unwrap_or(1.0);
|
||||
Paragraph { align, left: at(2), right: at(3), first: at(4), space_before: at(5).max(0.0), space_after: at(6).max(0.0), leading, auto_leading }
|
||||
}
|
||||
|
||||
/// The scale a text frame or table gives its type (`FTxS`, stored like `Xfrm`): none unless set.
|
||||
/// Neither the frame's own transform nor its groups' scale its type (checked against the
|
||||
/// thumbnails of tables and frames inside scaled groups).
|
||||
fn text_scale(r: &mut Reader, id: ObjId) -> Affine {
|
||||
match r.s.floats::<6>(id, b"FTxS").map(Affine::from_xfrm) {
|
||||
Some(m) if m.is_finite() && m.scale() > 1e-9 => Affine([m.0[0], m.0[1], m.0[2], m.0[3], 0.0, 0.0]),
|
||||
Some(_) => {
|
||||
r.warn("text frames with an invalid text scale (imported unscaled)");
|
||||
Affine::IDENTITY
|
||||
}
|
||||
None => Affine::IDENTITY,
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,10 @@ fn shape(id: u32, class: &[u8; 4], parameters: Vec<(vectorcraft_affinity::stream
|
||||
}
|
||||
|
||||
fn read(definitions: Vec<F>, top: u32) -> Document {
|
||||
try_read(definitions, top).unwrap()
|
||||
}
|
||||
|
||||
fn try_read(definitions: Vec<F>, top: u32) -> Result<Document, vectorcraft_affinity::Error> {
|
||||
let data = synth::stream(&[
|
||||
(tag(b"Defs"), F::Shared(definitions)),
|
||||
(
|
||||
@@ -39,7 +43,7 @@ fn read(definitions: Vec<F>, top: u32) -> Document {
|
||||
),
|
||||
]);
|
||||
let bytes = synth::container(&[("doc.dat", &data, Method::Zlib)], None);
|
||||
vectorcraft_affinity::read(&bytes, Limits::default()).unwrap()
|
||||
vectorcraft_affinity::read(&bytes, Limits::default())
|
||||
}
|
||||
|
||||
fn path(document: &Document) -> &Path {
|
||||
@@ -200,3 +204,79 @@ fn unlocked_rectangle_corners_keep_their_own_radius_and_type() {
|
||||
assert_eq!(sub.segments.len(), 8);
|
||||
assert_eq!(sub.segments[3][2], p(5.0, 20.0));
|
||||
}
|
||||
|
||||
/// The special shapes come in as their own outlines: one closed contour of finite points inside
|
||||
/// (or, for a callout's tail, just below) the node's box, and none as the bounding ellipse.
|
||||
#[test]
|
||||
fn special_shapes_have_their_own_closed_outlines() {
|
||||
for class in [b"ShCl", b"ShHt", b"ShCg", b"ShCR", b"ShCE", b"ShDA", b"ShDS", b"ShTr", b"ShCr", b"ShpD", b"ShSg"] {
|
||||
let name = String::from_utf8_lossy(class).into_owned();
|
||||
let document = read(vec![shape(100, class, vec![])], 100);
|
||||
assert!(!document.warnings.iter().any(|w| w.contains("bounding ellipse")), "{name}: {:?}", document.warnings);
|
||||
let (Kind::Shape { path, even_odd, .. }, cog) = (&document.spreads[0].nodes[0].kind, class == b"ShCg") else { panic!("{name}: no shape") };
|
||||
// A cog is its teeth and its hole, filled even-odd.
|
||||
assert_eq!((path.subpaths.len(), *even_odd), if cog { (2, true) } else { (1, false) }, "{name}");
|
||||
for sub in &path.subpaths {
|
||||
assert!(sub.closed && sub.segments.len() >= 2, "{name}");
|
||||
for p in std::iter::once(sub.start).chain(sub.segments.iter().flatten().copied()) {
|
||||
assert!(p.x.is_finite() && p.y.is_finite(), "{name}: {p:?}");
|
||||
assert!((-5.0..=15.0).contains(&p.x) && (-10.0..=30.0).contains(&p.y), "{name}: {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// A class the reader does not know is still its bounding ellipse, and said.
|
||||
let document = read(vec![shape(100, b"ShZZ", vec![])], 100);
|
||||
assert!(document.warnings.iter().any(|w| w.contains("unrecognized parametric shape")), "{:?}", document.warnings);
|
||||
}
|
||||
|
||||
fn group(id: u32, children: Vec<F>) -> F {
|
||||
F::Def(id, vec![tag(b"Grup")], vec![(tag(b"Chld"), F::Shared(children))])
|
||||
}
|
||||
|
||||
/// A list's null slots yield no node, operand or segment, but each visit of a shared object scans
|
||||
/// them all: they are charged to the document's work before the scan.
|
||||
#[test]
|
||||
fn null_slots_of_shared_lists_are_charged_for_every_visit() {
|
||||
// A compound of a million null operands, placed 20 times: 20 million slots, over the 2^24.
|
||||
let document = read(vec![compound(100, vec![F::Null; 1_000_000]), group(200, vec![F::Ref(100); 20])], 200);
|
||||
assert!(document.warnings.iter().any(|w| w.contains("geometry work limit")), "{:?}", document.warnings);
|
||||
let shapes = document.spreads[0].nodes[0].children.iter().filter(|n| matches!(n.kind, Kind::Shape { .. })).count();
|
||||
assert_eq!(shapes, 16, "each placement costs a million slots of the 2^24");
|
||||
// A group of a million null children, placed 20 times, fails the read like too many layers.
|
||||
let result = try_read(vec![group(100, vec![F::Null; 1_000_000]), group(200, vec![F::Ref(100); 20])], 200);
|
||||
assert!(matches!(result, Err(vectorcraft_affinity::Error::Limit(_))), "{:?}", result.map(|d| d.warnings));
|
||||
// Within the work of one document the same lists are read, nulls skipped.
|
||||
let document = read(vec![group(100, vec![F::Null; 1_000]), group(200, vec![F::Ref(100); 20])], 200);
|
||||
assert_eq!((document.spreads[0].nodes[0].children.len(), document.warnings.len()), (20, 0));
|
||||
}
|
||||
|
||||
fn boxed(class: &[u8; 4], b: Vec<f64>) -> F {
|
||||
F::Def(100, vec![tag(b"ShpN")], vec![(tag(b"ShpB"), F::F64s(b)), (tag(b"Shpe"), F::Def(10_100, vec![tag(class)], vec![]))])
|
||||
}
|
||||
|
||||
/// A callout rectangle (`ShCR`) whose box runs right to left (x0 > x1) panicked in `f64::clamp`
|
||||
/// (min > max), found by the `stream` fuzz target. It reads, inside its box.
|
||||
#[test]
|
||||
fn callout_rectangle_with_a_reversed_box_reads_inside_it() {
|
||||
for b in [vec![10.0_f64, 0.0, 0.0, 20.0], vec![6.8e38, 0.0, 10.0, 20.0]] {
|
||||
let (lo, hi) = (b[0].min(b[2]), b[0].max(b[2]));
|
||||
let document = read(vec![boxed(b"ShCR", b)], 100);
|
||||
let sub = &path(&document).subpaths[0];
|
||||
let points = std::iter::once(&sub.start).chain(sub.segments.iter().flatten());
|
||||
assert!(points.into_iter().all(|q| q.x.is_finite() && q.y.is_finite() && (lo..=hi).contains(&q.x)), "{sub:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A box with finite corners whose width overflows gave infinite and NaN outline points. Such a
|
||||
/// shape imports as its box, with a warning.
|
||||
#[test]
|
||||
fn a_shape_too_large_to_compute_imports_as_its_box() {
|
||||
for class in [b"ShCR", b"ShpE", b"ShCg"] {
|
||||
let document = read(vec![boxed(class, vec![f64::MAX, 0.0, -f64::MAX, 20.0])], 100);
|
||||
let sub = &path(&document).subpaths;
|
||||
assert_eq!(sub.len(), 1, "{class:?}");
|
||||
let corners: Vec<Point> = std::iter::once(sub[0].start).chain(sub[0].segments.iter().map(|s| s[2])).collect();
|
||||
assert!(corners.iter().all(|p| p.x.abs() == f64::MAX && (p.y == 0.0 || p.y == 20.0)), "{class:?}: {corners:?}");
|
||||
assert!(document.warnings.iter().any(|w| w.contains("too large to compute")), "{:?}", document.warnings);
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ patchy-lazy-placed.af dpi=72;spreads=1;model_crc32=8776a8a0;counts={"depth": 1,
|
||||
patchy-live-filter.af dpi=72;spreads=1;model_crc32=12235fe9;counts={"depth": 2, "fills": 2, "gradients": 0, "nodes": 4, "segments": 6, "shapes": 2, "strokes": 0, "subpaths": 2, "unsupported": 2};boards=[];fonts={};warnings=["adjustment layers", "unknown layers"]
|
||||
patchy-rgba16.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-rgba8.af dpi=72;spreads=1;model_crc32=688b2475;counts={"depth": 1, "images": 1, "nodes": 1};boards=[];fonts={};warnings=[]
|
||||
patchy-shapes-2.af dpi=72;spreads=1;model_crc32=886e9852;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 62, "shapes": 12, "strokes": 0, "subpaths": 12};boards=[];fonts={};warnings=["cloud, heart, cog, callout, arrow, tear and other special shapes (imported as their bounding ellipse) (9×)"]
|
||||
patchy-shapes-2.af dpi=72;spreads=1;model_crc32=6f174318;counts={"depth": 1, "fills": 12, "gradients": 0, "nodes": 12, "segments": 168, "shapes": 12, "strokes": 0, "subpaths": 13};boards=[];fonts={};warnings=[]
|
||||
patchy-shapes.af dpi=72;spreads=1;model_crc32=c1790e97;counts={"depth": 1, "fills": 4, "gradients": 0, "nodes": 4, "segments": 28, "shapes": 4, "strokes": 0, "subpaths": 4};boards=[];fonts={};warnings=[]
|
||||
patchy-text-artistic.af dpi=72;spreads=1;model_crc32=1d33192c;counts={"depth": 1, "nodes": 1, "text_chars": 5, "text_runs": 1, "texts": 1};boards=[];fonts={"Arial:ArialMT:400:false"};warnings=[]
|
||||
patchy-text-caps.af dpi=72;spreads=1;model_crc32=24e52518;counts={"depth": 1, "nodes": 2, "text_chars": 21, "text_runs": 2, "texts": 2};boards=[];fonts={"Arial:ArialNarrow:400:false"};warnings=["font width variants (exact face depends on the installed PostScript font) (2×)"]
|
||||
|
||||
@@ -250,7 +250,8 @@ impl ParamSchema {
|
||||
/// What is wrong with the schema itself, or `None`: a parameter name that is empty, repeated
|
||||
/// or holds `.`, `[` or `]`; a required parameter with a default; a default that isn't JSON or
|
||||
/// doesn't pass its parameter's type; an enum with no names or a repeated name; a range with
|
||||
/// an end that isn't finite or that no value can be in; nesting past [`MAX_DEPTH`].
|
||||
/// an end that isn't finite or that no value can be in; nesting past [`MAX_DEPTH`], or a
|
||||
/// [`Type::Ids`] or [`Type::Point`], whose values are all lists, at the nesting limit.
|
||||
pub fn definition_problem(&self) -> Option<String> {
|
||||
object_problem("", self.params, 0)
|
||||
}
|
||||
@@ -319,7 +320,9 @@ pub enum Problem {
|
||||
Missing,
|
||||
/// The value is not of the parameter's type: `expected` says what it must be.
|
||||
WrongType { expected: String, got: String },
|
||||
/// The schema nests deeper than [`MAX_DEPTH`] here ([`ParamSchema::definition_problem`]).
|
||||
/// The value nests deeper than [`MAX_DEPTH`] here: a list given for a [`Type::Color`] at the
|
||||
/// nesting limit, or any value under a schema that nests too deeply itself
|
||||
/// ([`ParamSchema::definition_problem`]).
|
||||
TooDeep,
|
||||
}
|
||||
|
||||
@@ -779,6 +782,8 @@ fn type_problem(at: &str, ty: &Type, depth: usize) -> Option<String> {
|
||||
Type::Object(params) => object_problem(at, params, depth + 1),
|
||||
Type::Array(_) if depth >= MAX_DEPTH => Some(format!("`{at}` nests deeper than {MAX_DEPTH} levels")),
|
||||
Type::Array(item) => type_problem(&format!("{at}[]"), item, depth + 1),
|
||||
// Every value of these is a list, and a list at the nesting limit is refused.
|
||||
Type::Ids | Type::Point if depth >= MAX_DEPTH => Some(format!("`{at}` nests deeper than {MAX_DEPTH} levels")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,6 +156,36 @@ fn id_lists_points_and_color_lists_count_toward_the_nesting_limit() {
|
||||
assert!(check(MAX_DEPTH, &Type::Color, &json!("#ff0000")).is_ok());
|
||||
}
|
||||
|
||||
/// `ty` inside `levels` lists.
|
||||
fn in_lists(levels: usize, ty: Type) -> Type {
|
||||
(0..levels).fold(ty, |inner, _| Type::Array(Box::leak(Box::new(inner))))
|
||||
}
|
||||
|
||||
/// `v` inside `levels` lists.
|
||||
fn wrapped(levels: usize, v: Value) -> Value {
|
||||
(0..levels).fold(v, |inner, _| Value::Array(vec![inner]))
|
||||
}
|
||||
|
||||
/// The schema check and the value check agree on the fixed-shape lists at the nesting limit: an id
|
||||
/// list or a point there could take no value, so the schema is wrong in itself, and a color there
|
||||
/// takes a string, while a color list is refused as nested too deeply, at its path.
|
||||
#[test]
|
||||
fn fixed_shape_lists_at_the_nesting_limit_follow_the_schema_check() {
|
||||
for ty in [Type::Ids, Type::Point, Type::Color] {
|
||||
assert_eq!(one(in_lists(MAX_DEPTH - 1, ty)).definition_problem(), None, "{ty:?}");
|
||||
}
|
||||
for ty in [Type::Ids, Type::Point] {
|
||||
let problem = one(in_lists(MAX_DEPTH, ty)).definition_problem();
|
||||
assert!(problem.as_deref().is_some_and(|p| p.contains("nests deeper")), "{ty:?}: {problem:?}");
|
||||
}
|
||||
let color = one(in_lists(MAX_DEPTH, Type::Color));
|
||||
assert_eq!(color.definition_problem(), None);
|
||||
assert_eq!(color.validate(&json!({"x": wrapped(MAX_DEPTH, json!("#ff0000"))})).unwrap(), None);
|
||||
let e = color.validate(&json!({"x": wrapped(MAX_DEPTH, json!([1, 0, 0]))})).unwrap_err();
|
||||
assert_eq!(e.problem, Problem::TooDeep);
|
||||
assert_eq!(e.path, format!("x{}", "[0]".repeat(MAX_DEPTH)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_retired_key_past_the_nesting_limit_is_refused() {
|
||||
let params = holding("older", nested_lists(500_000));
|
||||
|
||||
@@ -78,7 +78,11 @@ fn samples(t: &Track, step: Option<f64>) -> Vec<(Point, Vec2, f64)> {
|
||||
let pieces = (seg / step).ceil().clamp(1.0, MAX_STEPS) as usize;
|
||||
for k in 1..pieces {
|
||||
let u = k as f64 / pieces as f64;
|
||||
out.push((p.lerp(t.verts[i + 1], u), t.dirs[i], (t.cum[i] + seg * u) / len));
|
||||
let s = t.cum[i] + seg * u;
|
||||
// On a chord of a flattened curve the samples follow the smooth frame through the
|
||||
// vertices.
|
||||
let (q, tg) = if t.curved.get(i).copied().unwrap_or(false) { t.frame_in(i, u) } else { (p.lerp(t.verts[i + 1], u), t.dirs[i]) };
|
||||
out.push((q, tg, s / len));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+45
-11
@@ -370,11 +370,14 @@ pub struct ArtBrush {
|
||||
pub scale: ArtScale,
|
||||
/// Width in percent.
|
||||
pub width: f64,
|
||||
/// How the width varies along a stroke: `None` (Fixed) always `width`; Pressure goes from
|
||||
/// `width` at the lightest pen pressure to [`Self::width_max`] at the heaviest.
|
||||
/// How the width varies along a stroke: `None` (Fixed) always `width`; a mode that follows the
|
||||
/// pen goes from `width` to [`Self::width_max`] over the ranges [`Variation`] gives: Pressure
|
||||
/// from the lightest pressure to the heaviest, Tilt from the pen lying flat to upright, Bearing
|
||||
/// and Rotation from −180° to 180° (half way at 0°).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub width_mode: Option<Variation>,
|
||||
/// The width at the heaviest pen pressure (%), for Pressure (`width` without one).
|
||||
/// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, or
|
||||
/// at 180° (`width` without one).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub width_max: Option<f64>,
|
||||
pub flip_along: bool,
|
||||
@@ -388,11 +391,11 @@ impl ArtBrush {
|
||||
/// The range of the width (%).
|
||||
pub const WIDTH_RANGE: (f64, f64) = (1.0, 1000.0);
|
||||
|
||||
/// The widths (%) at the lightest and the heaviest pen pressure: `width` for both unless the
|
||||
/// width follows the pressure.
|
||||
/// The widths (%) where the pen reads 0 and 1 for the width's mode (the lightest and the
|
||||
/// heaviest pressure, for Pressure): `width` for both unless the width follows the pen.
|
||||
pub fn width_range(&self) -> (f64, f64) {
|
||||
match self.width_mode {
|
||||
Some(Variation::Pressure) => (self.width, self.width_max.unwrap_or(self.width)),
|
||||
Some(m) if m.follows_pen() => (self.width, self.width_max.unwrap_or(self.width)),
|
||||
_ => (self.width, self.width),
|
||||
}
|
||||
}
|
||||
@@ -713,8 +716,8 @@ impl Brush {
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
a.width = within(a.width, ArtBrush::WIDTH_RANGE, 100.0);
|
||||
// The width follows the pen's pressure or stays fixed.
|
||||
if a.width_mode != Some(Variation::Pressure) {
|
||||
// The width follows the pen (its pressure, tilt, bearing or rotation) or stays fixed.
|
||||
if !a.width_mode.is_some_and(Variation::follows_pen) {
|
||||
a.width_mode = None;
|
||||
}
|
||||
a.width_max = a.width_max.map(|w| within(w, ArtBrush::WIDTH_RANGE, a.width));
|
||||
@@ -759,9 +762,40 @@ pub fn library(doc: &Document) -> Vec<Brush> {
|
||||
}
|
||||
|
||||
/// Parse a stored library value (malformed entries are skipped, values kept within their
|
||||
/// ranges; see [`Brush::from_json`]).
|
||||
/// ranges; see [`Brush::from_json`]). A name that repeats is kept by its first brush, and each
|
||||
/// later brush of that name is numbered ([`number_repeated_names`]).
|
||||
pub fn parse_library(v: &serde_json::Value) -> Vec<Brush> {
|
||||
v.as_array().map(|a| a.iter().filter_map(|b| Brush::from_json(b.clone()).ok()).collect()).unwrap_or_default()
|
||||
let mut lib: Vec<Brush> = v.as_array().map(|a| a.iter().filter_map(|b| Brush::from_json(b.clone()).ok()).collect()).unwrap_or_default();
|
||||
number_repeated_names(&mut lib);
|
||||
lib
|
||||
}
|
||||
|
||||
/// Renames the second and later brushes of each repeated name in `lib` to the first "Name 2",
|
||||
/// "Name 3"… that no brush in `lib` has. The first brush of a name keeps it, so a stroke that names
|
||||
/// it draws the brush [`find`] gave it before.
|
||||
fn number_repeated_names(lib: &mut [Brush]) {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
if lib.iter().all(|b| seen.insert(b.name.as_str())) {
|
||||
return;
|
||||
}
|
||||
let mut taken: std::collections::HashSet<String> = lib.iter().map(|b| b.name.clone()).collect();
|
||||
let mut kept = std::collections::HashSet::new();
|
||||
// The next number to try for each repeated name, so the brushes of one name try each number
|
||||
// once between them.
|
||||
let mut next: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
|
||||
for b in lib.iter_mut() {
|
||||
if kept.insert(b.name.clone()) {
|
||||
continue;
|
||||
}
|
||||
let from = next.entry(b.name.clone()).or_insert(2);
|
||||
// `taken` is finite, so one of the numbers is free.
|
||||
if let Some((i, name)) = (*from..).map(|i| (i, format!("{} {i}", b.name))).find(|(_, n)| !taken.contains(n)) {
|
||||
*from = i.saturating_add(1);
|
||||
taken.insert(name.clone());
|
||||
kept.insert(name.clone());
|
||||
b.name = name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Store `lib` as the document's brush library.
|
||||
@@ -806,7 +840,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
|
||||
let mut out = match &brush.kind {
|
||||
BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name),
|
||||
BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name),
|
||||
BrushKind::Art(a) => warp::art(a, bp, w, stroke.pressure.as_ref()),
|
||||
BrushKind::Art(a) => warp::art(a, bp, w, stroke),
|
||||
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name),
|
||||
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
|
||||
};
|
||||
|
||||
@@ -945,6 +945,34 @@ fn library_defaults_store_and_find() {
|
||||
assert_eq!(unique_name(&lib, "Arrow"), "Arrow 2");
|
||||
}
|
||||
|
||||
/// A stored library that repeats a name reads with the first brush of that name as stored and each
|
||||
/// later one numbered, past every name the library already has; strokes of the name keep drawing
|
||||
/// the first brush.
|
||||
#[test]
|
||||
fn repeated_brush_names_are_numbered_when_read() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let named = |name: &str, size: f64| Brush { name: name.into(), ..calli(0.0, 100.0, size) };
|
||||
store(&mut d, &[named("Nib", 1.0), named("Nib 2", 2.0), named("Nib", 3.0), named("Other", 4.0), named("Nib", 5.0), named("Nib 2", 6.0)]);
|
||||
let lib = library(&d);
|
||||
let names: Vec<&str> = lib.iter().map(|b| b.name.as_str()).collect();
|
||||
assert_eq!(names, ["Nib", "Nib 2", "Nib 3", "Other", "Nib 4", "Nib 2 2"]);
|
||||
let size = |b: &Brush| if let BrushKind::Calligraphic(c) = &b.kind { c.size } else { 0.0 };
|
||||
assert_eq!(lib.iter().map(size).collect::<Vec<_>>(), [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
|
||||
assert_eq!(find(&d, "Nib").map(|b| size(&b)), Some(1.0));
|
||||
assert_eq!(find(&d, "Nib 3").map(|b| size(&b)), Some(3.0));
|
||||
// Reading again gives the same names, and the numbered library stored again reads as stored.
|
||||
assert_eq!(library(&d), lib);
|
||||
store(&mut d, &lib);
|
||||
assert_eq!(library(&d), lib);
|
||||
// Many brushes of one name take the numbers in order, past the numbered names the file has.
|
||||
let many: Vec<Brush> = (0..5000).map(|i| named(if i == 1 { "Nib 3" } else { "Nib" }, 1.0)).collect();
|
||||
store(&mut d, &many);
|
||||
let names: Vec<String> = library(&d).into_iter().map(|b| b.name).collect();
|
||||
assert_eq!(names[..5], ["Nib", "Nib 3", "Nib 2", "Nib 4", "Nib 5"]);
|
||||
assert_eq!(names.last().map(String::as_str), Some("Nib 5000"));
|
||||
assert_eq!(names.iter().collect::<std::collections::HashSet<_>>().len(), names.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brushes_serde_round_trip() {
|
||||
let lib = defaults().to_vec();
|
||||
@@ -1009,6 +1037,26 @@ fn pressed(points: Vec<(f64, f64)>) -> StrokeLayer {
|
||||
StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) }
|
||||
}
|
||||
|
||||
/// A nib that follows the pen is sampled between the vertices of the flattened path too. Along a
|
||||
/// curve those samples sit on the curve, and the outline keeps its distance from it.
|
||||
#[test]
|
||||
fn pen_driven_nib_outline_follows_the_curve_between_vertices() {
|
||||
// The top half of a circle of radius 50; a round nib 20 pt across, the same at any pressure.
|
||||
let (r, half) = (50.0, 10.0);
|
||||
let c = Point::new(r, r);
|
||||
let ring = shapes::ellipse(Rect::new(0.0, 0.0, 2.0 * r, 2.0 * r)).to_bezpath();
|
||||
let half_circle: BezPath = ring.elements().iter().take(3).copied().collect();
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &pressure_calli(20.0, 0.0), &half_circle, &pressed(vec![(0.0, 0.5), (1.0, 0.5)]));
|
||||
let mut pts = vec![];
|
||||
for n in &out {
|
||||
all_points(n, &mut pts);
|
||||
}
|
||||
// Away from the round caps at the two ends, every outline point is `half` from the curve.
|
||||
let middle = pts.iter().filter(|p| ((p.y - c.y).atan2(p.x - c.x).abs() - std::f64::consts::FRAC_PI_2).abs() <= 1.2);
|
||||
let worst = middle.map(|p| ((p.distance(c) - (r + half)).abs()).min((p.distance(c) - (r - half)).abs())).fold(0.0, f64::max);
|
||||
assert!(worst < 0.05, "an outline point strays {worst:.4} pt from the nib's reach");
|
||||
}
|
||||
|
||||
/// #852: with Size on Pressure the nib goes from size − variation at the lightest pressure to
|
||||
/// size + variation at the heaviest, along the stroke where the pen pressed.
|
||||
#[test]
|
||||
@@ -1371,6 +1419,62 @@ fn art_brush_width_follows_the_pressure() {
|
||||
assert!(plain.get("width_mode").is_none() && plain.get("width_max").is_none(), "{plain}");
|
||||
}
|
||||
|
||||
/// Art Brush Options: Width on Tilt goes from Width with the pen lying flat to the second width
|
||||
/// upright, and on Bearing or Rotation from Width at −180° to the second width at 180°, along the
|
||||
/// stroke as the pen recorded it; each mode reads only its own input.
|
||||
#[test]
|
||||
fn art_brush_width_follows_tilt_bearing_and_rotation() {
|
||||
let brush = |mode: Variation| {
|
||||
let mut b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut b.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (50.0, Some(mode), Some(300.0));
|
||||
}
|
||||
b
|
||||
};
|
||||
let bp = line(0.0, 0.0, 100.0, 0.0);
|
||||
let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st);
|
||||
// Tilt, upright at the start (300 %: 6 pt either side of 4 pt art) to flat at the end (50 %: 1 pt).
|
||||
let upright_to_flat = StrokeLayer { tilt: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) };
|
||||
let out = draw(&brush(Variation::Tilt), &upright_to_flat);
|
||||
assert!(near(half_width(&out, 0.0, 1.0), 6.0, 0.1), "{}", half_width(&out, 0.0, 1.0));
|
||||
assert!(near(half_width(&out, 99.0, 100.0), 1.0, 0.1), "{}", half_width(&out, 99.0, 100.0));
|
||||
assert!(near(half_width(&out, 49.0, 51.0), 3.5, 0.15), "{}", half_width(&out, 49.0, 51.0));
|
||||
// Bearing and Rotation: half way at 0°, a quarter of the way at −90°, three quarters at 90°.
|
||||
for (mode, angle, half) in [
|
||||
(Variation::Bearing, 0.0, 3.5),
|
||||
(Variation::Bearing, -90.0, 2.25),
|
||||
(Variation::Bearing, 90.0, 4.75),
|
||||
(Variation::Rotation, -90.0, 2.25),
|
||||
(Variation::Rotation, 90.0, 4.75),
|
||||
] {
|
||||
let st = if mode == Variation::Bearing { posed(Some(0.5), Some(angle), None) } else { posed(None, None, Some(angle)) };
|
||||
let h = bounds(&draw(&brush(mode), &st)).height();
|
||||
assert!(near(h, 2.0 * half, 1e-6), "{mode:?} {angle}: {h}");
|
||||
}
|
||||
// Each mode reads its own input: without it (the pressure, or another of the pen's values
|
||||
// recorded instead), the art is half way between the two widths.
|
||||
let others = [
|
||||
(Variation::Tilt, posed(None, Some(90.0), Some(90.0))),
|
||||
(Variation::Tilt, pressed(vec![(0.0, 0.0), (1.0, 1.0)])),
|
||||
(Variation::Bearing, posed(Some(0.0), None, Some(90.0))),
|
||||
(Variation::Rotation, posed(Some(0.0), Some(90.0), None)),
|
||||
(Variation::Pressure, posed(Some(0.0), Some(90.0), Some(90.0))),
|
||||
];
|
||||
for (mode, st) in others {
|
||||
let h = bounds(&draw(&brush(mode), &st)).height();
|
||||
assert!(near(h, 7.0, 1e-6), "{mode:?}: {h}");
|
||||
}
|
||||
// The pen's modes are kept when a definition is read, and Random is read as Fixed.
|
||||
let lib = parse_library(&serde_json::json!([
|
||||
{"name": "t", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "tilt", "width_max": 300.0},
|
||||
{"name": "b", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "bearing", "width_max": 300.0},
|
||||
{"name": "r", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "rotation", "width_max": 300.0},
|
||||
{"name": "x", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "random", "width_max": 300.0},
|
||||
]));
|
||||
let modes: Vec<_> = lib.iter().map(|b| if let BrushKind::Art(a) = &b.kind { a.width_mode } else { None }).collect();
|
||||
assert_eq!(modes, [Some(Variation::Tilt), Some(Variation::Bearing), Some(Variation::Rotation), None]);
|
||||
}
|
||||
|
||||
/// Definitions from files and commands are kept within their ranges.
|
||||
#[test]
|
||||
fn sanitize_keeps_values_within_their_ranges() {
|
||||
@@ -1602,6 +1706,35 @@ fn an_ordinary_stroke_is_unaffected_by_the_budget() {
|
||||
assert!(anchors(&out) < 2_000_000);
|
||||
}
|
||||
|
||||
/// A straight-sided art brush on a smooth curve draws smooth edges: they do not turn at the smooth
|
||||
/// anchors the fit puts along them.
|
||||
#[test]
|
||||
fn art_brush_edges_stay_smooth_along_a_curve() {
|
||||
for &(r, w, h, sw) in &[(100.0, 100.0, 10.0, 1.0), (300.0, 100.0, 10.0, 2.0), (30.0, 100.0, 10.0, 1.0), (2000.0, 100.0, 10.0, 1.0)] {
|
||||
// The top half of a circle, as one open path of two curves.
|
||||
let ring = shapes::ellipse(Rect::new(0.0, 0.0, 2.0 * r, 2.0 * r)).to_bezpath();
|
||||
let half_circle: BezPath = ring.elements().iter().take(3).copied().collect();
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &art_brush(rect_art(w, h), ArtScale::Stretch), &half_circle, &stroke(sw));
|
||||
let NodeKind::Path { path, .. } = &out[0].kind else { panic!("an art brush on a path draws a path") };
|
||||
|
||||
// The turn at each smooth anchor of the edges: the angle between the incoming and the
|
||||
// outgoing direction. Real corners (the ends of the art) turn by far more than 60°.
|
||||
let mut kink = 0.0f64;
|
||||
for sp in &path.subpaths {
|
||||
for (k, a) in sp.anchors.iter().enumerate().skip(1).take(sp.anchors.len().saturating_sub(2)) {
|
||||
let h_in = if a.h_in != a.p { a.h_in } else { sp.anchors[k - 1].p };
|
||||
let h_out = if a.h_out != a.p { a.h_out } else { sp.anchors[k + 1].p };
|
||||
let (u, v) = (a.p - h_in, h_out - a.p);
|
||||
if u.hypot() < 1e-9 || v.hypot() < 1e-9 || u.dot(v) < 0.5 * u.hypot() * v.hypot() {
|
||||
continue;
|
||||
}
|
||||
kink = kink.max(u.cross(v).atan2(u.dot(v)).abs().to_degrees());
|
||||
}
|
||||
}
|
||||
assert!(kink < 0.5, "r={r} art={w}x{h} weight {sw}: an edge turns by {kink:.3}° at a smooth anchor");
|
||||
}
|
||||
}
|
||||
|
||||
/// Anchors under `n`, and how many of them keep a handle (so the segment is a curve).
|
||||
fn anchors_and_curved(n: &Node) -> (usize, usize) {
|
||||
let NodeKind::Path { path, .. } = &n.kind else { return (0, 0) };
|
||||
|
||||
+346
-35
@@ -1,8 +1,9 @@
|
||||
//! Arc-length parameterised polylines ("tracks") that brushes lay art along.
|
||||
//!
|
||||
//! A track is one flattened subpath. `frame(s)` gives the point and unit tangent at arc length
|
||||
//! `s`; tangents are blended across the gentle vertices of flattened curves (so warped art bends
|
||||
//! smoothly) but stay discontinuous at real corners (so art folds there, like Illustrator).
|
||||
//! `s`. Along a flattened curve the frame runs on a smooth curve through the vertices, so warped
|
||||
//! art bends smoothly; along a line of the path it stays on the line. At real corners the tangent
|
||||
//! stays discontinuous, so art folds there.
|
||||
|
||||
use vectorcraft_geom::{BezPath, PathEl, Point, Vec2};
|
||||
|
||||
@@ -22,6 +23,11 @@ pub struct Track {
|
||||
pub tangents: Vec<Vec2>,
|
||||
/// Is the vertex a corner (turn > [`CORNER_DEG`])? Open ends are never corners.
|
||||
pub corner: Vec<bool>,
|
||||
/// Does the segment come from flattening a curve (rather than from a line of the path)?
|
||||
pub curved: Vec<bool>,
|
||||
/// How far (radians) a curved segment's end tangents may turn from its direction for `frame`
|
||||
/// to follow a curve through them; 0 for a line.
|
||||
turn: Vec<f64>,
|
||||
}
|
||||
|
||||
fn unit(v: Vec2) -> Vec2 {
|
||||
@@ -35,16 +41,53 @@ fn aligned(a: Vec2, b: Vec2) -> bool {
|
||||
a.dot(b) > 1.0 - 1e-12
|
||||
}
|
||||
|
||||
/// How far a vertex tangent may turn from a chord of a flattened curve, as a multiple of the
|
||||
/// flattening tolerance over the chord's length. A circular arc needs 4; the rest is slack for
|
||||
/// flattening that lands a little inside its tolerance.
|
||||
const TURN_PER_TOL: f64 = 6.0;
|
||||
|
||||
/// `t` turned by the smallest angle that brings it within `limit` radians of each `dir`. When no
|
||||
/// angle satisfies every limit, `t` turns to the middle of the gap between them.
|
||||
fn held_within(t: Vec2, limits: [Option<(Vec2, f64)>; 2]) -> Vec2 {
|
||||
let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY);
|
||||
for (d, limit) in limits.into_iter().flatten() {
|
||||
let to = t.cross(d).atan2(t.dot(d));
|
||||
lo = lo.max(to - limit);
|
||||
hi = hi.min(to + limit);
|
||||
}
|
||||
let turn = if lo <= hi { 0f64.max(lo).min(hi) } else { (lo + hi) / 2.0 };
|
||||
if turn == 0.0 || !turn.is_finite() {
|
||||
return t;
|
||||
}
|
||||
let (sin, cos) = turn.sin_cos();
|
||||
Vec2::new(t.x * cos - t.y * sin, t.x * sin + t.y * cos)
|
||||
}
|
||||
|
||||
/// Left-hand normal in y-down document space (for a path running +x it points +y).
|
||||
pub fn normal(t: Vec2) -> Vec2 {
|
||||
Vec2::new(-t.y, t.x)
|
||||
}
|
||||
|
||||
impl Track {
|
||||
fn new(mut pts: Vec<Point>, closed: bool) -> Option<Track> {
|
||||
pts.dedup_by(|a, b| a.distance(*b) < 1e-9);
|
||||
/// `raw` pairs each vertex with the tolerance the segment ending at it was flattened with
|
||||
/// when it comes from a curve, and `None` when it is a line of the path.
|
||||
fn new(raw: Vec<(Point, Option<f64>)>, closed: bool) -> Option<Track> {
|
||||
let mut pts: Vec<Point> = Vec::with_capacity(raw.len());
|
||||
// `ends_curve[k]`: the flattening tolerance of the segment ending at vertex `k`, when it
|
||||
// comes from a curve.
|
||||
let mut ends_curve: Vec<Option<f64>> = Vec::with_capacity(raw.len());
|
||||
for (p, c) in raw {
|
||||
// A duplicate vertex adds no segment, so it is dropped with its tolerance.
|
||||
if pts.last().is_some_and(|q| q.distance(p) < 1e-9) {
|
||||
continue;
|
||||
}
|
||||
pts.push(p);
|
||||
ends_curve.push(c);
|
||||
}
|
||||
let mut closing_curve = None;
|
||||
if closed && pts.len() > 2 && pts[0].distance(pts[pts.len() - 1]) < 1e-9 {
|
||||
pts.pop();
|
||||
closing_curve = ends_curve.pop().flatten();
|
||||
}
|
||||
if pts.len() < 2 {
|
||||
return None;
|
||||
@@ -52,8 +95,11 @@ impl Track {
|
||||
let closed = closed && pts.len() > 2;
|
||||
if closed {
|
||||
pts.push(pts[0]);
|
||||
ends_curve.push(closing_curve);
|
||||
}
|
||||
let nseg = pts.len() - 1;
|
||||
let curve_tol: Vec<Option<f64>> = (0..nseg).map(|i| ends_curve.get(i + 1).copied().flatten()).collect();
|
||||
let curved: Vec<bool> = curve_tol.iter().map(Option::is_some).collect();
|
||||
let dirs: Vec<Vec2> = (0..nseg).map(|i| unit(pts[i + 1] - pts[i])).collect();
|
||||
let mut cum = vec![0.0];
|
||||
for i in 0..nseg {
|
||||
@@ -62,34 +108,78 @@ impl Track {
|
||||
let mut tangents = Vec::with_capacity(nseg + 1);
|
||||
let mut corner = Vec::with_capacity(nseg + 1);
|
||||
let cos_limit = CORNER_DEG.to_radians().cos();
|
||||
let seg = |i: usize| (dirs[i], cum[i + 1] - cum[i], curved[i]);
|
||||
for i in 0..=nseg {
|
||||
let incoming = if i > 0 {
|
||||
Some(dirs[i - 1])
|
||||
Some(seg(i - 1))
|
||||
} else if closed {
|
||||
Some(dirs[nseg - 1])
|
||||
Some(seg(nseg - 1))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let outgoing = if i < nseg {
|
||||
Some(dirs[i])
|
||||
Some(seg(i))
|
||||
} else if closed {
|
||||
Some(dirs[0])
|
||||
Some(seg(0))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match (incoming, outgoing) {
|
||||
(Some(a), Some(b)) => {
|
||||
(Some((a, la, ca)), Some((b, lb, cb))) => {
|
||||
corner.push(a.dot(b) < cos_limit);
|
||||
tangents.push(unit(a + b));
|
||||
tangents.push(match (ca, cb) {
|
||||
// Between two chords of a flattened curve: each direction weighted by the
|
||||
// length of the other chord, which is the tangent of the circle through
|
||||
// the vertex and its two neighbors.
|
||||
(true, true) => unit(a * lb + b * la),
|
||||
// Where a line of the path meets a curve, the line's direction.
|
||||
(false, true) => a,
|
||||
(true, false) => b,
|
||||
(false, false) => unit(a + b),
|
||||
});
|
||||
}
|
||||
(a, b) => {
|
||||
// An end of an open track (both `None` only for a track without segments).
|
||||
corner.push(false);
|
||||
tangents.push(a.or(b).unwrap_or(Vec2::new(1.0, 0.0)));
|
||||
tangents.push(a.or(b).map_or(Vec2::new(1.0, 0.0), |(d, _, _)| d));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Track { verts: pts, cum, closed, dirs, tangents, corner })
|
||||
// An open track's end on a curve continues the bend of its last chord: the tangent there
|
||||
// is the neighboring vertex's tangent mirrored about the chord, as on the circle through
|
||||
// the last three vertices.
|
||||
if !closed && nseg >= 2 {
|
||||
for (end, inner, d) in [(0, 1, dirs[0]), (nseg, nseg - 1, dirs[nseg - 1])] {
|
||||
let (s_end, s_inner) = if end == 0 { (0, 1) } else { (nseg - 1, nseg - 2) };
|
||||
if !corner[inner] && curved[s_end] && curved[s_inner] {
|
||||
let t = tangents[inner];
|
||||
tangents[end] = unit(d * (2.0 * d.dot(t)) - t);
|
||||
}
|
||||
}
|
||||
}
|
||||
// A curve lies within its flattening tolerance `tol` of each of its chords, so its tangent
|
||||
// at a vertex turns only a little from a chord: at most about `4 * tol / len` on a
|
||||
// circular arc. Next to a long chord the estimates above can turn much further (a
|
||||
// straight curve element beside a tight bend), and `frame` would then bow off the chord.
|
||||
// Between curved chords, each vertex tangent is held within `TURN_PER_TOL * tol / len` of
|
||||
// both chords. Where a line meets a curve the tangent stays the line's direction, and a
|
||||
// curved chord whose end tangents turn further than that from it keeps to the chord.
|
||||
let turn: Vec<f64> = (0..nseg)
|
||||
.map(|j| match curve_tol.get(j) {
|
||||
Some(Some(tol)) => (TURN_PER_TOL * tol / (cum[j + 1] - cum[j]).max(1e-12)).min(1.0).asin(),
|
||||
_ => 0.0,
|
||||
})
|
||||
.collect();
|
||||
for (i, t) in tangents.iter_mut().enumerate() {
|
||||
let incoming = if i > 0 { Some(i - 1) } else { closed.then_some(nseg - 1) };
|
||||
let outgoing = if i < nseg { Some(i) } else { closed.then_some(0) };
|
||||
let sides = [incoming, outgoing];
|
||||
if corner[i] || sides.iter().flatten().any(|&j| !curved[j]) {
|
||||
continue;
|
||||
}
|
||||
*t = held_within(*t, sides.map(|j| j.map(|j| (dirs[j], turn[j]))));
|
||||
}
|
||||
Some(Track { verts: pts, cum, closed, dirs, tangents, corner, curved, turn })
|
||||
}
|
||||
|
||||
pub fn len(&self) -> f64 {
|
||||
@@ -135,11 +225,11 @@ impl Track {
|
||||
let n = self.segments();
|
||||
let s = if self.closed && l > 0.0 { s.rem_euclid(l) } else { s };
|
||||
if s <= 0.0 && !self.closed {
|
||||
let t = self.dirs[0];
|
||||
let t = self.tangents[0];
|
||||
return (self.verts[0] + t * s, t);
|
||||
}
|
||||
if s >= l && !self.closed {
|
||||
let t = self.dirs[n - 1];
|
||||
let t = self.tangents[n];
|
||||
return (self.verts[n] + t * (s - l), t);
|
||||
}
|
||||
// Binary search the segment.
|
||||
@@ -149,10 +239,44 @@ impl Track {
|
||||
};
|
||||
let seg = self.cum[i + 1] - self.cum[i];
|
||||
let u = if seg > 1e-12 { ((s - self.cum[i]) / seg).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let p = self.verts[i].lerp(self.verts[i + 1], u);
|
||||
let t0 = if self.corner[i] { self.dirs[i] } else { self.tangents[i] };
|
||||
let t1 = if self.corner[i + 1] { self.dirs[i] } else { self.tangents[i + 1] };
|
||||
(p, unit(t0 + (t1 - t0) * u))
|
||||
self.frame_in(i, u)
|
||||
}
|
||||
|
||||
/// Segment `i`'s direction and the tangents [`Self::frame`] uses at its two ends: the vertex
|
||||
/// tangents, or the segment's direction at a corner.
|
||||
fn end_tangents(&self, i: usize) -> Option<(Vec2, Vec2, Vec2)> {
|
||||
let (&d, &c0, &c1, &t0, &t1) =
|
||||
(self.dirs.get(i)?, self.corner.get(i)?, self.corner.get(i + 1)?, self.tangents.get(i)?, self.tangents.get(i + 1)?);
|
||||
Some((d, if c0 { d } else { t0 }, if c1 { d } else { t1 }))
|
||||
}
|
||||
|
||||
/// Point and unit tangent at the fraction `u` (0 to 1) of segment `i`, as [`Self::frame`]
|
||||
/// gives them. `i` must be below [`Self::segments`].
|
||||
pub fn frame_in(&self, i: usize, u: f64) -> (Point, Vec2) {
|
||||
let (Some(&p0), Some(&p1), Some((d, t0, t1))) = (self.verts.get(i), self.verts.get(i + 1), self.end_tangents(i)) else {
|
||||
return (self.verts.last().copied().unwrap_or(Point::ZERO), Vec2::new(1.0, 0.0));
|
||||
};
|
||||
let seg = self.cum.get(i + 1).zip(self.cum.get(i)).map_or(0.0, |(b, a)| b - a);
|
||||
if aligned(t0, d) && aligned(t1, d) {
|
||||
return (p0.lerp(p1, u), d);
|
||||
}
|
||||
// The tangents may turn this far from a curved chord, a little beyond it for rounding.
|
||||
let within = self.turn.get(i).map_or(-1.0, |a| a.sin() + 1e-9);
|
||||
let bends = |t: Vec2| t.dot(d) <= 0.0 || t.cross(d).abs() > within;
|
||||
if !self.curved.get(i).copied().unwrap_or(false) || bends(t0) || bends(t1) {
|
||||
// A line of the path, or a curved chord at a sharper turn than the curve can make
|
||||
// there: the point stays on it, and the tangent turns across it toward the vertex
|
||||
// tangents.
|
||||
return (p0.lerp(p1, u), unit(t0 + (t1 - t0) * u));
|
||||
}
|
||||
// On a chord of a flattened curve the frame follows the cubic through both vertices with
|
||||
// their tangents, at the chord's length per unit of `u`. Its position and tangent then
|
||||
// meet those of the next segment at each vertex.
|
||||
let (u2, u3) = (u * u, u * u * u);
|
||||
let (m0, m1) = (t0 * seg, t1 * seg);
|
||||
let p = p0 + (p1 - p0) * (3.0 * u2 - 2.0 * u3) + m0 * (u3 - 2.0 * u2 + u) + m1 * (u3 - u2);
|
||||
let dp = (p1 - p0) * (6.0 * u - 6.0 * u2) + m0 * (3.0 * u2 - 4.0 * u + 1.0) + m1 * (3.0 * u2 - 2.0 * u);
|
||||
(p, unit(dp))
|
||||
}
|
||||
|
||||
/// The point at arc length `s`, offset `d` along the left normal.
|
||||
@@ -183,8 +307,8 @@ impl Track {
|
||||
if self.closed && (lo < -1e-9 || hi > l + 1e-9) {
|
||||
return false;
|
||||
}
|
||||
// Past an open track's ends `frame` extrapolates along the end segment's direction, so
|
||||
// those segments are part of the span too.
|
||||
// Past an open track's ends `frame` extrapolates along the end tangent, which is checked
|
||||
// against the end segment's direction below, so those segments are part of the span too.
|
||||
let ends = [(!self.closed && lo < 0.0).then_some(0), (!self.closed && hi > l).then(|| n - 1)];
|
||||
let touched = (0..n).filter(|&i| {
|
||||
let (a, b) = (self.cum.get(i), self.cum.get(i + 1));
|
||||
@@ -193,9 +317,7 @@ impl Track {
|
||||
let mut dir: Option<Vec2> = None;
|
||||
let mut any = false;
|
||||
for i in touched.chain(ends.into_iter().flatten()) {
|
||||
let (Some(&d), Some(&t0), Some(&t1), Some(&c0), Some(&c1)) =
|
||||
(self.dirs.get(i), self.tangents.get(i), self.tangents.get(i + 1), self.corner.get(i), self.corner.get(i + 1))
|
||||
else {
|
||||
let Some((d, t0, t1)) = self.end_tangents(i) else {
|
||||
return false;
|
||||
};
|
||||
if dir.is_some_and(|first: Vec2| !aligned(first, d)) {
|
||||
@@ -203,11 +325,11 @@ impl Track {
|
||||
}
|
||||
dir = Some(d);
|
||||
any = true;
|
||||
// `frame` blends the two vertex tangents across the segment unless the vertex is a
|
||||
// corner, where it uses the segment's own direction. So a neighbour outside the span
|
||||
// can still bend the tangent inside it, and checking the directions alone would miss
|
||||
// that: segments d, d, e leave vertex 2's tangent at unit(d + e).
|
||||
if !(c0 || aligned(t0, d)) || !(c1 || aligned(t1, d)) {
|
||||
// `frame` blends the two end tangents across a line, and follows a curve through them
|
||||
// on a curved chord. So a neighbour outside the span can still bend the tangent
|
||||
// inside it, and checking the directions alone would miss that: segments d, d, e
|
||||
// leave vertex 2's tangent at unit(d + e).
|
||||
if !aligned(t0, d) || !aligned(t1, d) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -220,9 +342,10 @@ const MAX_FLATTENED: usize = 4_000_000;
|
||||
|
||||
/// Flatten `bp` into tracks (one per subpath) with `tol` accuracy.
|
||||
pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
|
||||
let tol = tol.max(1e-4);
|
||||
let mut out = vec![];
|
||||
let mut cur: Vec<Point> = vec![];
|
||||
let flush = |cur: &mut Vec<Point>, closed: bool, out: &mut Vec<Track>| {
|
||||
let mut cur: Vec<(Point, Option<f64>)> = vec![];
|
||||
let flush = |cur: &mut Vec<(Point, Option<f64>)>, closed: bool, out: &mut Vec<Track>| {
|
||||
if let Some(t) = Track::new(std::mem::take(cur), closed) {
|
||||
out.push(t);
|
||||
}
|
||||
@@ -236,19 +359,40 @@ pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
|
||||
return out;
|
||||
}
|
||||
let mut els = vec![];
|
||||
// When the element being flattened is a curve, the tolerance `flatten` uses for it: `flatten`
|
||||
// pulls each element before it reports that element's lines, and raises the tolerance of a
|
||||
// long curve as `vectorcraft_geom::flatten` describes.
|
||||
let in_curve = std::cell::Cell::new(None);
|
||||
let (last, start) = (std::cell::Cell::new(Point::ZERO), std::cell::Cell::new(Point::ZERO));
|
||||
let source = bp.iter().inspect(|el| {
|
||||
let from = last.get();
|
||||
let (curve, to) = match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
start.set(p);
|
||||
(None, p)
|
||||
}
|
||||
PathEl::LineTo(p) => (None, p),
|
||||
PathEl::QuadTo(a, p) => (Some(from.distance(a) + a.distance(p)), p),
|
||||
PathEl::CurveTo(a, b, p) => (Some(from.distance(a) + a.distance(b) + b.distance(p)), p),
|
||||
PathEl::ClosePath => (None, start.get()),
|
||||
};
|
||||
last.set(to);
|
||||
let per = vectorcraft_geom::MAX_FLATTEN_PER_CURVE * vectorcraft_geom::MAX_FLATTEN_PER_CURVE;
|
||||
in_curve.set(curve.map(|length| if length.is_finite() { tol.max(length / per) } else { f64::INFINITY }));
|
||||
});
|
||||
// Guarded: kurbo works out every subdivision of a curve even when the callback drops them.
|
||||
vectorcraft_geom::flatten(bp.iter(), tol.max(1e-4), |el| {
|
||||
vectorcraft_geom::flatten(source, tol, |el| {
|
||||
if els.len() < MAX_FLATTENED {
|
||||
els.push(el);
|
||||
els.push((el, in_curve.get()));
|
||||
}
|
||||
});
|
||||
for el in els {
|
||||
for (el, from_curve) in els {
|
||||
match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
flush(&mut cur, false, &mut out);
|
||||
cur.push(p);
|
||||
cur.push((p, None));
|
||||
}
|
||||
PathEl::LineTo(p) => cur.push(p),
|
||||
PathEl::LineTo(p) => cur.push((p, from_curve)),
|
||||
PathEl::ClosePath => flush(&mut cur, true, &mut out),
|
||||
_ => {}
|
||||
}
|
||||
@@ -368,6 +512,173 @@ mod tests {
|
||||
assert_eq!(t.map(110.0, 0.0), Point::new(110.0, 0.0));
|
||||
}
|
||||
|
||||
/// Between two lines that meet at a gentle turn, the frame stays on the lines: only the chords
|
||||
/// of a flattened curve are smoothed. Where a line meets a curve at a gentle turn, the frame
|
||||
/// stays on the line with the line's direction, and its tangent does not jump at the join.
|
||||
#[test]
|
||||
fn a_polylines_frame_stays_on_its_lines() {
|
||||
// A line, then a line or a nearly straight curve at a 20° turn, below the corner angle, so
|
||||
// the vertex is not a corner.
|
||||
let turn = 20f64.to_radians();
|
||||
let (c, s) = (100.0 * turn.cos(), 100.0 * turn.sin());
|
||||
for curve in [false, true] {
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((0.0, 0.0));
|
||||
bp.line_to((100.0, 0.0));
|
||||
if curve {
|
||||
bp.curve_to((100.0 + c / 3.0, s / 3.0 + 0.5), (100.0 + 2.0 * c / 3.0, 2.0 * s / 3.0 + 0.5), (100.0 + c, s));
|
||||
} else {
|
||||
bp.line_to((100.0 + c, s));
|
||||
}
|
||||
let t = &tracks(&bp, 0.05)[0];
|
||||
for at in [10.0, 30.0, 50.0, 70.0, 90.0] {
|
||||
let (p, tg) = t.frame(at);
|
||||
assert!(p.y.abs() < 1e-9 && (p.x - at).abs() < 1e-9, "curve {curve}: at {at} the frame left the first line: {p:?}");
|
||||
if curve {
|
||||
assert!(tg.y.abs() < 1e-12, "at {at} the line's tangent turned toward the curve: {tg:?}");
|
||||
}
|
||||
}
|
||||
if curve {
|
||||
// The curve's first chord keeps to the chord rather than bending toward the line.
|
||||
let (a, b) = (t.cum[1], t.cum[2]);
|
||||
let (p, q) = (t.verts[1], t.verts[2]);
|
||||
let mid = t.frame((a + b) / 2.0).0;
|
||||
assert!((mid - p.midpoint(q)).hypot() < 1e-9, "the first curve chord bows: {mid:?}");
|
||||
}
|
||||
let (before, after) = (t.frame(100.0 - 1e-7).1, t.frame(100.0 + 1e-7).1);
|
||||
assert!(before.dot(after) > 1.0 - 1e-9, "curve {curve}: the tangent jumps at the join: {before:?} {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A curve of no length between two lines leaves them lines.
|
||||
#[test]
|
||||
fn a_curve_of_no_length_leaves_a_line_a_line() {
|
||||
let turn = 20f64.to_radians();
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((0.0, 0.0));
|
||||
bp.line_to((100.0, 0.0));
|
||||
bp.curve_to((100.0, 0.0), (100.0, 0.0), (100.0, 0.0));
|
||||
bp.line_to((100.0 + 100.0 * turn.cos(), 100.0 * turn.sin()));
|
||||
let t = &tracks(&bp, 0.05)[0];
|
||||
assert!(t.curved.iter().all(|c| !c), "no segment is a curve: {:?}", t.curved);
|
||||
for at in [10.0, 50.0, 90.0] {
|
||||
let (p, _) = t.frame(at);
|
||||
assert!(p.y.abs() < 1e-9 && (p.x - at).abs() < 1e-9, "at {at} the frame left the first line: {p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a line joins a curve smoothly, the line keeps its direction up to the join.
|
||||
#[test]
|
||||
fn a_line_into_a_smooth_curve_keeps_its_direction() {
|
||||
// A line along y = 0 into a quarter circle of radius 50 that starts along +x.
|
||||
let r = 50.0;
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((-100.0, 0.0));
|
||||
bp.line_to((0.0, 0.0));
|
||||
bp.curve_to((r * K, 0.0), (r, r - r * K), (r, r));
|
||||
let t = &tracks(&bp, 0.05)[0];
|
||||
for s in [10.0, 50.0, 90.0, 99.0] {
|
||||
let (p, tg) = t.frame(s);
|
||||
assert!(p.y.abs() < 1e-9 && tg.y.abs() < 1e-9, "at {s} the line's frame turned: {p:?} {tg:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The handle length of a cubic quarter circle.
|
||||
const K: f64 = 0.552_284_749_8;
|
||||
|
||||
/// A curve element whose handles lie on its chord is a line drawn as a curve. Next to a tight
|
||||
/// bend, at either end of a track, the frame along it stays within the flattening tolerance
|
||||
/// of the line.
|
||||
#[test]
|
||||
fn a_straight_curve_element_beside_a_tight_bend_stays_on_its_line() {
|
||||
let tol = 0.05;
|
||||
for bend_first in [false, true] {
|
||||
// A 200 pt line along y = 0 drawn as a cubic, joined smoothly to a quarter circle of
|
||||
// radius 5 that turns toward +y.
|
||||
let mut bp = BezPath::new();
|
||||
if bend_first {
|
||||
bp.move_to((-5.0, -5.0));
|
||||
bp.curve_to((-5.0, -5.0 + 5.0 * K), (-5.0 * K, 0.0), (0.0, 0.0));
|
||||
bp.curve_to((50.0, 0.0), (150.0, 0.0), (200.0, 0.0));
|
||||
} else {
|
||||
bp.move_to((0.0, 0.0));
|
||||
bp.curve_to((50.0, 0.0), (150.0, 0.0), (200.0, 0.0));
|
||||
bp.curve_to((200.0 + 5.0 * K, 0.0), (205.0, 5.0 - 5.0 * K), (205.0, 5.0));
|
||||
}
|
||||
let t = &tracks(&bp, tol)[0];
|
||||
// The bend lies outside 0 <= x <= 200, so every frame point in that range is on the
|
||||
// line's stretch of the track.
|
||||
let on_line: Vec<(Point, Vec2)> =
|
||||
(0..=2000).map(|k| t.frame(t.len() * k as f64 / 2000.0)).filter(|(p, _)| (0.0..=200.0).contains(&p.x)).collect();
|
||||
let worst = on_line.iter().map(|(p, _)| p.y.abs()).fold(0.0, f64::max);
|
||||
assert!(worst <= 2.0 * tol, "bend first {bend_first}: the frame strays {worst:.4} pt off the line");
|
||||
// Along the line the tangent turns by no more than the line's flattening allows.
|
||||
let lean = on_line.iter().map(|(_, tg)| tg.y.abs()).fold(0.0, f64::max);
|
||||
assert!(lean <= 0.01, "bend first {bend_first}: the tangent turns {lean:.4} off the line");
|
||||
}
|
||||
}
|
||||
|
||||
/// A curve long enough that flattening raises its tolerance still has its frame follow the
|
||||
/// curve between the vertices, not the chords.
|
||||
#[test]
|
||||
fn a_long_curve_flattened_coarser_is_still_followed() {
|
||||
// A line along y = 0 into a cubic quarter circle of radius 5,000,000 that starts along +x.
|
||||
let r = 5.0e6;
|
||||
let curve = kurbo::CubicBez::new((0.0, 0.0), (r * K, 0.0), (r, r - r * K), (r, r));
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((-100.0, 0.0));
|
||||
bp.line_to((0.0, 0.0));
|
||||
bp.curve_to(curve.p1, curve.p2, curve.p3);
|
||||
let t = &tracks(&bp, 0.05)[0];
|
||||
let worst = (1..400)
|
||||
.map(|k| t.frame(100.0 + (t.len() - 100.0) * k as f64 / 400.0).0)
|
||||
.map(|p| kurbo::ParamCurveNearest::nearest(&curve, p, 1e-9).distance_sq.sqrt())
|
||||
.fold(0.0, f64::max);
|
||||
assert!(worst < 0.05, "the frame strays {worst:.4} pt from the curve");
|
||||
}
|
||||
|
||||
/// A closed curve is smooth across its seam: the frame stays on the circle and at right angles
|
||||
/// to its radius all the way round, the start included.
|
||||
#[test]
|
||||
fn a_closed_curves_frame_is_smooth_across_its_seam() {
|
||||
let (r, tol) = (50.0, 0.05);
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((r, 0.0));
|
||||
bp.curve_to((r, r * K), (r * K, r), (0.0, r));
|
||||
bp.curve_to((-r * K, r), (-r, r * K), (-r, 0.0));
|
||||
bp.curve_to((-r, -r * K), (-r * K, -r), (0.0, -r));
|
||||
bp.curve_to((r * K, -r), (r, -r * K), (r, 0.0));
|
||||
bp.close_path();
|
||||
let t = &tracks(&bp, tol)[0];
|
||||
assert!(t.closed && t.curved.iter().all(|c| *c), "every chord of the circle is a chord of a curve");
|
||||
for k in -20..=20 {
|
||||
let (p, tg) = t.frame(k as f64 * 0.37);
|
||||
let radial = p.to_vec2() / p.to_vec2().hypot();
|
||||
assert!((p.to_vec2().hypot() - r).abs() <= tol, "at {k} the frame is off the circle: {p:?}");
|
||||
assert!(tg.dot(radial).abs() < 0.5f64.to_radians().sin(), "at {k} the tangent leans off the circle: {tg:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A closed path whose last side is the implicit line back to the start keeps that line
|
||||
/// straight.
|
||||
#[test]
|
||||
fn an_implicit_closing_line_is_not_a_curve() {
|
||||
let r = 50.0;
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((r, 0.0));
|
||||
bp.curve_to((r, r * K), (r * K, r), (0.0, r));
|
||||
bp.curve_to((-r * K, r), (-r, r * K), (-r, 0.0));
|
||||
bp.close_path();
|
||||
let t = &tracks(&bp, 0.05)[0];
|
||||
assert!(t.closed);
|
||||
assert_eq!(t.curved.last(), Some(&false), "the closing line is a line");
|
||||
let n = t.segments();
|
||||
for u in [0.1, 0.5, 0.9] {
|
||||
let (p, _) = t.frame(t.cum[n - 1] + (t.cum[n] - t.cum[n - 1]) * u);
|
||||
assert!(p.y.abs() < 1e-9, "the frame leaves the closing line: {p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_square_has_four_corners() {
|
||||
let mut bp = BezPath::new();
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::ParamCurveNearest;
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, PressureProfile, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, BezPath, CubicBez, ParamCurve, PathData, PathEl, Point, Rect, SubPath, Vec2};
|
||||
|
||||
use crate::track::{Rng, Track, normal, seed_of, tracks};
|
||||
@@ -503,9 +503,10 @@ fn art_on_run(
|
||||
bend_widened(t, art, b, along, cross, widen)
|
||||
}
|
||||
|
||||
/// An art brush's art along `bp`. With a width that follows the pen's pressure, the art is as
|
||||
/// wide as the pressure recorded at each point of the stroke gives (half way without a recording).
|
||||
pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, pressure: Option<&PressureProfile>) -> Vec<Node> {
|
||||
/// An art brush's art along `bp`. With a width that follows the pen (its pressure, tilt, bearing
|
||||
/// or rotation), the art is as wide as what `stroke` recorded at each point gives (half way
|
||||
/// without a recording).
|
||||
pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) -> Vec<Node> {
|
||||
let Some((art, b)) = oriented(&a.art, a.direction, a.flip_along, a.flip_across) else { return vec![] };
|
||||
let (light, heavy) = a.width_range();
|
||||
let width = light.max(heavy);
|
||||
@@ -522,7 +523,7 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, pressure: Option<&Pre
|
||||
}
|
||||
// A run past the start of a closed track wraps round to it.
|
||||
let at = if s > l { s - l } else { s };
|
||||
let p = pressure.map_or(PressureProfile::MID, |p| p.at(at / l)).clamp(0.0, 1.0);
|
||||
let p = a.width_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5);
|
||||
(light + (heavy - light) * p) / width
|
||||
};
|
||||
let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] };
|
||||
|
||||
@@ -3,7 +3,7 @@ name = "vectorcraft-cad"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018)"
|
||||
description = "VectorCraft CAD interchange: a hand-written ASCII DXF writer (R12 to 2018) and an HP-GL/2 plot file reader and writer"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
//! HP-GL import: a plotter file (HP-GL/2, `.plt`, `.hpgl`, `.hgl`, `.hpg`) as a document. Older
|
||||
//! HP-GL files are read by the HP-GL/2 rules for the instructions the two share.
|
||||
//!
|
||||
//! The pen's moves become paths: each run drawn with the pen down is one stroked path in the
|
||||
//! selected pen's color and width (0.35 mm unless PW sets another), with the line type as a dash
|
||||
//! pattern and the line attributes as caps and joins. Circles, arcs, wedges, rectangles and Bézier
|
||||
//! curves are drawn as curves (the chord angle isn't used). Filled rectangles, wedges and polygons
|
||||
//! (polygon mode, FP) become filled paths, edged ones stroked paths. Plotter units (1016 to the
|
||||
//! inch, y up) become points, through user units (SC, IP, IR) and the rotation (RO). The artboard
|
||||
//! is the bounds of what the art paints, its strokes included.
|
||||
//!
|
||||
//! VectorCraft's own rules where the device decides: before the first SP the pen is pen 1 (a
|
||||
//! device draws nothing until SP), and the hard-clip limits are 11 × 8.5 in from the origin, so
|
||||
//! P2 lies there when the file sets no scaling points. SP0 draws nothing. Labels, symbol mode's symbols and raster
|
||||
//! images (HP RTL) aren't drawn, the input window doesn't clip, hatched fills are filled solid,
|
||||
//! and the art of every page goes on one artboard; each comes back as a warning. Printer escape
|
||||
//! sequences and PJL lines around the instructions are skipped.
|
||||
//!
|
||||
//! [`export`] writes the visible art over a region as an HP-GL or HP-GL/2 plot, and
|
||||
//! [`export_regions`] one plot per region with one pen numbering: see [`write`].
|
||||
//!
|
||||
//! - `lex`: the bytes as instructions, numbers, labels and PE data.
|
||||
//! - `plot`: the instructions played on the pen, as shapes.
|
||||
//! - `write`: the writer, paths to pen moves.
|
||||
|
||||
mod lex;
|
||||
mod plot;
|
||||
pub mod write;
|
||||
|
||||
pub use write::{HpglOptions, HpglOutput, Origin, Version, export, export_regions};
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Dash, Document, FillLayer, LayerColor, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{Affine, PathData, Rect};
|
||||
|
||||
use crate::Imported;
|
||||
use lex::Lexer;
|
||||
use plot::Plot;
|
||||
|
||||
/// Points per plotter unit.
|
||||
const PT_PER_PLU: f64 = 72.0 / 1016.0;
|
||||
/// The weight of a zero-width pen (one device dot), in points.
|
||||
const THINNEST: f64 = 0.25;
|
||||
|
||||
/// Instructions the reader knows and draws nothing for (their parameters are read and dropped).
|
||||
const IGNORED: &[[u8; 2]] = &[
|
||||
*b"AC", *b"AD", *b"AF", *b"AH", *b"AP", *b"AS", *b"CA", *b"CF", *b"CM", *b"CP", *b"CS", *b"CT", *b"CV", *b"DC", *b"DI", *b"DL", *b"DP", *b"DR",
|
||||
*b"DS", *b"DV", *b"EC", *b"ES", *b"FI", *b"FN", *b"FS", *b"GM", *b"IM", *b"IV", *b"KY", *b"LM", *b"LO", *b"MC", *b"MG", *b"MT", *b"NR", *b"OA",
|
||||
*b"OC", *b"OD", *b"OE", *b"OF", *b"OG", *b"OH", *b"OI", *b"OL", *b"OP", *b"OS", *b"OT", *b"OW", *b"PB", *b"PP", *b"PS", *b"PT", *b"QL", *b"RF",
|
||||
*b"RP", *b"SA", *b"SB", *b"SD", *b"SG", *b"SI", *b"SL", *b"SR", *b"SS", *b"ST", *b"SV", *b"TD", *b"TL", *b"TR", *b"UC", *b"VA", *b"VN", *b"VS",
|
||||
*b"XT", *b"YT",
|
||||
];
|
||||
|
||||
/// Instructions the reader plays.
|
||||
const PLAYED: &[[u8; 2]] = &[
|
||||
*b"AA", *b"AR", *b"AT", *b"BL", *b"BP", *b"BR", *b"BZ", *b"CI", *b"CO", *b"CR", *b"DF", *b"DT", *b"EA", *b"EP", *b"ER", *b"EW", *b"FP", *b"FR",
|
||||
*b"FT", *b"IN", *b"IP", *b"IR", *b"IW", *b"LA", *b"LB", *b"LT", *b"NP", *b"PA", *b"PC", *b"PD", *b"PE", *b"PG", *b"PM", *b"PR", *b"PU", *b"PW",
|
||||
*b"RA", *b"RO", *b"RR", *b"RT", *b"SC", *b"SM", *b"SP", *b"UL", *b"WD", *b"WG", *b"WU",
|
||||
];
|
||||
|
||||
/// Instructions a plot file starts with.
|
||||
const FIRST: &[[u8; 2]] = &[
|
||||
*b"IN", *b"DF", *b"BP", *b"CO", *b"PS", *b"SP", *b"PU", *b"PD", *b"PA", *b"PR", *b"IP", *b"IR", *b"SC", *b"NP", *b"PC", *b"PW", *b"WU", *b"RO",
|
||||
*b"QL", *b"MC", *b"PP", *b"TR", *b"CR", *b"LT", *b"LA", *b"FT", *b"VS", *b"FS", *b"AC", *b"PG", *b"PE", *b"DT",
|
||||
];
|
||||
|
||||
/// Does `bytes` start like an HP-GL file? After any printer escapes and PJL lines (however long),
|
||||
/// it must hold nothing but instructions the reader knows, the first one of those a plot file
|
||||
/// starts with, up to the eighth instruction or 4 KB past the first. Their parameters must be
|
||||
/// numbers, but for a comment's quoted string and the text, characters and encoded data of LB, BL,
|
||||
/// WD, DT, SM and PE. An instruction the reader doesn't know counts when its numbers end with a
|
||||
/// semicolon.
|
||||
pub fn is_hpgl(bytes: &[u8]) -> bool {
|
||||
holds_instructions(bytes, true)
|
||||
}
|
||||
|
||||
/// Does `bytes` hold HP-GL instructions as [`is_hpgl`] checks? When `strict` is false, any of them
|
||||
/// may come first: a file picked by its extension may start with one a plot file seldom starts
|
||||
/// with (`SI`, `DI`). Either way, at least one of the instructions checked must be one the reader
|
||||
/// knows.
|
||||
fn holds_instructions(bytes: &[u8], strict: bool) -> bool {
|
||||
let mut lex = Lexer::new(bytes);
|
||||
let mut terminator = lex::ETX;
|
||||
let mut first = 0;
|
||||
let mut any_known = false;
|
||||
for n in 0..8 {
|
||||
if n > 0 && lex.pos() > first + 4096 {
|
||||
return any_known;
|
||||
}
|
||||
let Some(op) = lex.op(true) else { return n > 0 && any_known && lex.done() };
|
||||
if n == 0 {
|
||||
first = lex.pos();
|
||||
}
|
||||
if strict && n == 0 && !FIRST.contains(&op) {
|
||||
return false;
|
||||
}
|
||||
let known = PLAYED.contains(&op) || IGNORED.contains(&op);
|
||||
any_known |= known;
|
||||
match &op {
|
||||
b"CO" => {
|
||||
if !lex.comment() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
b"LB" | b"BL" | b"WD" => lex.label(terminator),
|
||||
b"DT" => {
|
||||
terminator = lex.char().unwrap_or(lex::ETX);
|
||||
lex.params();
|
||||
}
|
||||
b"SM" => {
|
||||
// The symbol character is read so it isn't taken for an instruction.
|
||||
let _ = lex.char();
|
||||
}
|
||||
b"PE" => lex.skip_pe(),
|
||||
_ if known => lex.params(),
|
||||
// An instruction the reader doesn't know (of an older or a device's own set) counts
|
||||
// when numbers and a semicolon follow it.
|
||||
_ => {
|
||||
if !lex.closed_params() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
any_known
|
||||
}
|
||||
|
||||
/// Read an HP-GL file. It may start with any instruction the reader knows, or one of another set
|
||||
/// that a semicolon ends; the rest of [`is_hpgl`]'s check applies, and at least one instruction the
|
||||
/// reader knows must be among those it checks.
|
||||
pub fn import(bytes: &[u8]) -> Result<Imported, String> {
|
||||
if !holds_instructions(bytes, false) {
|
||||
return Err("not an HP-GL file".into());
|
||||
}
|
||||
let mut lex = Lexer::new(bytes);
|
||||
let mut plot = Plot::new();
|
||||
while !plot.full
|
||||
&& let Some(op) = lex.op(false)
|
||||
{
|
||||
plot.op(op, &mut lex);
|
||||
}
|
||||
Ok(build(plot.finish(lex.raster)))
|
||||
}
|
||||
|
||||
fn rgb(c: [u8; 3]) -> Paint {
|
||||
Paint::solid(Color::rgb8(c[0], c[1], c[2]))
|
||||
}
|
||||
|
||||
/// The plot's shapes as paths on one layer, the artboard round what they paint.
|
||||
fn build(plot: Plot) -> Imported {
|
||||
// Plotter units, y up, to points, y down.
|
||||
let flip = Affine::scale_non_uniform(PT_PER_PLU, -PT_PER_PLU);
|
||||
let mut nodes: Vec<Node> = plot.shapes.iter().map(|s| node(s, flip)).collect();
|
||||
// The strokes' caps and miter joins included.
|
||||
let finite = |r: &Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite());
|
||||
let frame = nodes.iter().filter_map(Node::visual_bounds).filter(finite).reduce(|a, b| a.union(b)).unwrap_or(Rect::new(0.0, 0.0, 612.0, 792.0));
|
||||
let mut doc = Document::new(frame.width().max(1.0), frame.height().max(1.0));
|
||||
doc.layers.clear();
|
||||
let shift = Affine::translate(-frame.origin().to_vec2());
|
||||
for n in &mut nodes {
|
||||
n.id = doc.alloc_id();
|
||||
if let NodeKind::Path { path, .. } = &mut n.kind {
|
||||
path.transform(shift);
|
||||
}
|
||||
}
|
||||
let mut layer = Node::layer(doc.alloc_id(), "Layer 1", LayerColor::Preset(0));
|
||||
if let Some(c) = layer.children_mut() {
|
||||
*c = nodes.into_iter().map(Arc::new).collect();
|
||||
}
|
||||
doc.layers = vec![Arc::new(layer)];
|
||||
Imported { document: doc, warnings: plot.warnings }
|
||||
}
|
||||
|
||||
/// A shape as a path, its plotter units through `to_points`.
|
||||
fn node(s: &plot::Shape, to_points: Affine) -> Node {
|
||||
let mut path = s.path.clone();
|
||||
path.apply_affine(to_points);
|
||||
let mut items = vec![];
|
||||
if let Some((c, _)) = s.fill {
|
||||
items.push(AppearanceItem::Fill(FillLayer::new(rgb(c))));
|
||||
}
|
||||
if let Some(st) = &s.stroke {
|
||||
let mut layer = StrokeLayer::new(rgb(st.color), (st.width * PT_PER_PLU).max(THINNEST));
|
||||
(layer.cap, layer.join, layer.miter_limit) = (st.cap, st.join, st.miter);
|
||||
layer.dash = st.dash.as_ref().map(|d| Dash {
|
||||
pattern: d.pattern.iter().map(|v| v * PT_PER_PLU).collect(),
|
||||
offset: d.offset * PT_PER_PLU,
|
||||
align_corners: d.adaptive,
|
||||
});
|
||||
items.push(AppearanceItem::Stroke(layer));
|
||||
}
|
||||
let mut n = Node::path(NodeId(0), PathData::from_bezpath(&path), Appearance { items, ..Appearance::default() });
|
||||
if let (NodeKind::Path { rule, .. }, Some((_, r))) = (&mut n.kind, s.fill) {
|
||||
*rule = r;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,428 @@
|
||||
//! The bytes of an HP-GL file as instructions: two-letter mnemonics and the parameters that follow
|
||||
//! them, read one at a time as the plot asks for them. Printer escape sequences (PCL, HP RTL, the
|
||||
//! HP-GL device-control escapes) and PJL lines around and between the instructions are skipped,
|
||||
//! with the data their escapes carry.
|
||||
|
||||
/// The end-of-text character, the default label terminator.
|
||||
pub(super) const ETX: u8 = 3;
|
||||
const ESC: u8 = 0x1b;
|
||||
|
||||
/// The most digits of a number that count: longer ones are read as their first digits.
|
||||
const MAX_DIGITS: usize = 18;
|
||||
|
||||
/// What the bytes being read hold.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
/// HP-GL instructions.
|
||||
Hpgl,
|
||||
/// PCL or HP RTL: escape sequences and their data, nothing to draw.
|
||||
Pcl,
|
||||
/// After a Universal Exit Language: PJL lines until a language starts.
|
||||
Pjl,
|
||||
}
|
||||
|
||||
/// One item of a PE (Polyline Encoded) instruction.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) enum PeItem {
|
||||
/// Select pen.
|
||||
Pen(i64),
|
||||
/// Rectangle mode: the following coordinates come in fours.
|
||||
Rect,
|
||||
/// A coordinate pair, after a pen-up flag (`up`) and an absolute flag (`absolute`).
|
||||
Point { x: f64, y: f64, up: bool, absolute: bool },
|
||||
}
|
||||
|
||||
/// The state of one PE instruction being read.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(super) struct Pe {
|
||||
seven_bit: bool,
|
||||
fraction_bits: u32,
|
||||
up: bool,
|
||||
absolute: bool,
|
||||
}
|
||||
|
||||
pub(super) struct Lexer<'a> {
|
||||
b: &'a [u8],
|
||||
at: usize,
|
||||
mode: Mode,
|
||||
/// The file holds HP RTL or PCL raster image data.
|
||||
pub raster: bool,
|
||||
}
|
||||
|
||||
/// Is `c` a byte that separates numeric parameters (or white space between instructions)?
|
||||
fn separator(c: u8) -> bool {
|
||||
matches!(c, b' ' | b',' | b'\t' | b'\r' | b'\n' | 0)
|
||||
}
|
||||
|
||||
impl<'a> Lexer<'a> {
|
||||
pub fn new(b: &'a [u8]) -> Self {
|
||||
Self { b, at: 0, mode: Mode::Hpgl, raster: false }
|
||||
}
|
||||
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.b.get(self.at).copied()
|
||||
}
|
||||
|
||||
/// Whether everything has been read.
|
||||
pub fn done(&self) -> bool {
|
||||
self.at >= self.b.len()
|
||||
}
|
||||
|
||||
/// How many bytes have been read.
|
||||
pub fn pos(&self) -> usize {
|
||||
self.at
|
||||
}
|
||||
|
||||
/// The next instruction's mnemonic, in upper case; `strict`: only white space, semicolons and
|
||||
/// escape sequences may come before it (anything else gives `None`, as the end does).
|
||||
pub fn op(&mut self, strict: bool) -> Option<[u8; 2]> {
|
||||
loop {
|
||||
let c = self.peek()?;
|
||||
if c == ESC {
|
||||
self.escape();
|
||||
continue;
|
||||
}
|
||||
match self.mode {
|
||||
Mode::Pcl => {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
Mode::Pjl => {
|
||||
if separator(c) {
|
||||
self.at += 1;
|
||||
} else if c == b'@' {
|
||||
self.pjl_line();
|
||||
} else {
|
||||
self.mode = Mode::Hpgl;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Mode::Hpgl => {}
|
||||
}
|
||||
let next = self.b.get(self.at + 1).copied();
|
||||
if c.is_ascii_alphabetic()
|
||||
&& let Some(n) = next.filter(u8::is_ascii_alphabetic)
|
||||
{
|
||||
self.at += 2;
|
||||
return Some([c.to_ascii_uppercase(), n.to_ascii_uppercase()]);
|
||||
}
|
||||
if strict && !(separator(c) || c == b';' || c < 0x20) {
|
||||
return None;
|
||||
}
|
||||
self.at += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// One `@PJL` line: an `ENTER LANGUAGE` command picks what follows.
|
||||
fn pjl_line(&mut self) {
|
||||
let rest = &self.b[self.at..];
|
||||
let end = rest.iter().position(|&c| c == b'\n').map_or(rest.len(), |n| n + 1);
|
||||
// A command names its language within its first 256 bytes; longer lines aren't copied.
|
||||
let line = String::from_utf8_lossy(&rest[..end.min(256)]).to_ascii_uppercase();
|
||||
if let Some(lang) = line.split_once("LANGUAGE").map(|(_, l)| l.trim_start_matches([' ', '=']).trim()) {
|
||||
self.mode = if lang.starts_with("HPGL") { Mode::Hpgl } else { Mode::Pcl };
|
||||
}
|
||||
self.at += end;
|
||||
}
|
||||
|
||||
/// An escape sequence at the current byte, with the data it carries.
|
||||
fn escape(&mut self) {
|
||||
self.at += 1;
|
||||
let Some(c) = self.peek() else { return };
|
||||
self.at += 1;
|
||||
match c {
|
||||
// Universal Exit Language (`ESC%-12345X`) and the language switches (`ESC%#B` to HP-GL,
|
||||
// `ESC%#A` to PCL or HP RTL).
|
||||
b'%' => {
|
||||
let (_, end) = self.value();
|
||||
match end {
|
||||
Some(b'X') => self.mode = Mode::Pjl,
|
||||
Some(b'B') => self.mode = Mode::Hpgl,
|
||||
Some(b'A') => self.mode = Mode::Pcl,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Reset: PCL follows, until a language switch.
|
||||
b'E' => self.mode = Mode::Pcl,
|
||||
// HP-GL device control: `ESC.` and a letter, with parameters up to a colon.
|
||||
b'.' => {
|
||||
let Some(kind) = self.peek() else { return };
|
||||
self.at += 1;
|
||||
if !b"()YZBEJKLORUX".contains(&kind) {
|
||||
let rest = &self.b[self.at..self.b.len().min(self.at + 80)];
|
||||
if let Some(n) = rest.iter().position(|&c| c == b':')
|
||||
&& rest[..n].iter().all(|c| c.is_ascii_digit() || matches!(c, b';' | b' ' | b','))
|
||||
{
|
||||
self.at += n + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Parameterized PCL: a group character, then values each ending in a letter (upper case
|
||||
// ends the sequence); `W`, `*b…V` (raster data by plane) and `&p…X` (transparent print
|
||||
// data) are followed by that many bytes of data. Without a group character (`ESC(8U`,
|
||||
// `ESC)0N`), one value and the letter ending it.
|
||||
0x21..=0x2f => {
|
||||
let Some(group) = self.peek().filter(|g| (0x60..=0x7e).contains(g)) else {
|
||||
self.value();
|
||||
return;
|
||||
};
|
||||
self.at += 1;
|
||||
loop {
|
||||
let (v, end) = self.value();
|
||||
let Some(end) = end else { return };
|
||||
let upper = end.to_ascii_uppercase();
|
||||
if upper == b'W' || (c, group, upper) == (b'*', b'b', b'V') || (c, group, upper) == (b'&', b'p', b'X') {
|
||||
let n = v.max(0.0).min((self.b.len() - self.at) as f64) as usize;
|
||||
if (c, group) == (b'*', b'b') && n > 0 {
|
||||
self.raster = true;
|
||||
}
|
||||
self.at += n;
|
||||
}
|
||||
if (c, group, end) == (b'*', b'r', b'A') {
|
||||
self.raster = true;
|
||||
}
|
||||
if !end.is_ascii_lowercase() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A two-character escape.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A PCL value (`[+-]digits[.digits]`, any part missing) and the character that ends it; `None`
|
||||
/// when that is not a letter or `@` (which is then left unread).
|
||||
fn value(&mut self) -> (f64, Option<u8>) {
|
||||
let v = self.number_here().unwrap_or(0.0);
|
||||
match self.peek() {
|
||||
Some(c) if c.is_ascii_alphabetic() || c == b'@' => {
|
||||
self.at += 1;
|
||||
(v, Some(c))
|
||||
}
|
||||
_ => (v, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// A number starting at the current byte (`[+-]digits[.digits]`), `None` when it has no digit
|
||||
/// (its sign and point are read all the same).
|
||||
fn number_here(&mut self) -> Option<f64> {
|
||||
let mut neg = false;
|
||||
if let Some(c @ (b'+' | b'-')) = self.peek() {
|
||||
neg = c == b'-';
|
||||
self.at += 1;
|
||||
}
|
||||
let (mut v, mut digits, mut scale) = (0.0f64, 0usize, 1.0f64);
|
||||
let mut point = false;
|
||||
while let Some(c) = self.peek() {
|
||||
if c.is_ascii_digit() {
|
||||
if digits < MAX_DIGITS {
|
||||
if point {
|
||||
scale /= 10.0;
|
||||
v += f64::from(c - b'0') * scale;
|
||||
} else {
|
||||
v = v * 10.0 + f64::from(c - b'0');
|
||||
}
|
||||
} else if !point {
|
||||
// Past the digits that count, an integer part keeps its size.
|
||||
v *= 10.0;
|
||||
}
|
||||
digits += 1;
|
||||
} else if c == b'.' && !point {
|
||||
point = true;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
self.at += 1;
|
||||
}
|
||||
let v = v.min(f64::MAX);
|
||||
(digits > 0).then_some(if neg { -v } else { v })
|
||||
}
|
||||
|
||||
/// The next numeric parameter of the instruction being read, or `None` at its end (a semicolon
|
||||
/// ending it is read).
|
||||
pub fn number(&mut self) -> Option<f64> {
|
||||
loop {
|
||||
let c = self.peek()?;
|
||||
if separator(c) {
|
||||
self.at += 1;
|
||||
} else if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.') {
|
||||
if let Some(v) = self.number_here() {
|
||||
return Some(v);
|
||||
}
|
||||
} else {
|
||||
if c == b';' {
|
||||
self.at += 1;
|
||||
}
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Up to `out.len()` numeric parameters into `out` (the rest are read and dropped) → how many.
|
||||
pub fn numbers(&mut self, out: &mut [f64]) -> usize {
|
||||
let mut n = 0;
|
||||
while let Some(v) = self.number() {
|
||||
if let Some(slot) = out.get_mut(n) {
|
||||
*slot = v;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
n.min(out.len())
|
||||
}
|
||||
|
||||
/// Read and drop the parameters of the instruction being read: numbers and quoted strings.
|
||||
pub fn params(&mut self) {
|
||||
loop {
|
||||
while self.number().is_some() {}
|
||||
if self.peek() != Some(b'"') {
|
||||
return;
|
||||
}
|
||||
self.quoted();
|
||||
}
|
||||
}
|
||||
|
||||
/// Read and drop numeric parameters → whether a semicolon ended them (an instruction the reader
|
||||
/// doesn't know, written out in full).
|
||||
pub fn closed_params(&mut self) -> bool {
|
||||
while self.number().is_some() {}
|
||||
self.at > 0 && self.b.get(self.at - 1) == Some(&b';')
|
||||
}
|
||||
|
||||
/// A comment (CO): its quoted string or nothing, then the terminator or the end → whether it
|
||||
/// is one.
|
||||
pub fn comment(&mut self) -> bool {
|
||||
while self.peek().is_some_and(separator) {
|
||||
self.at += 1;
|
||||
}
|
||||
match self.peek() {
|
||||
Some(b'"') => self.quoted(),
|
||||
Some(b';') => {
|
||||
self.at += 1;
|
||||
true
|
||||
}
|
||||
None => true,
|
||||
Some(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The text of a label, up to and including `terminator` (or the end).
|
||||
pub fn label(&mut self, terminator: u8) {
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == terminator).map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
|
||||
/// A quoted string (CO): the parameters up to its closing quote, then the terminator → whether
|
||||
/// there was one.
|
||||
pub fn quoted(&mut self) -> bool {
|
||||
while self.peek().is_some_and(separator) {
|
||||
self.at += 1;
|
||||
}
|
||||
let found = self.peek() == Some(b'"');
|
||||
if found {
|
||||
self.at += 1;
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == b'"').map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
if self.peek() == Some(b';') {
|
||||
self.at += 1;
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The character right after the mnemonic (DT, SM), `None` when it is a semicolon or the end
|
||||
/// (the semicolon is read).
|
||||
pub fn char(&mut self) -> Option<u8> {
|
||||
let c = self.peek()?;
|
||||
self.at += 1;
|
||||
(c != b';').then_some(c)
|
||||
}
|
||||
|
||||
/// The next item of a PE instruction, `None` at its end (its semicolon is read).
|
||||
pub fn pe(&mut self, st: &mut Pe) -> Option<PeItem> {
|
||||
loop {
|
||||
let raw = self.peek()?;
|
||||
let c = raw & 0x7f;
|
||||
// Spaces, deletes, control characters and bytes 128 to 160 and 255 are ignored.
|
||||
if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
b';' => {
|
||||
self.at += 1;
|
||||
return None;
|
||||
}
|
||||
// Flags keep their meaning with the eighth bit set; digits are 63 and up (191 and up).
|
||||
b':' | b'<' | b'>' | b'=' | b'7' | b'9' if raw < 63 || (0xb7..191).contains(&raw) => {
|
||||
self.at += 1;
|
||||
match c {
|
||||
b':' => return self.pe_value(st).map(PeItem::Pen).or_else(|| self.end_pe()),
|
||||
b'<' => st.up = true,
|
||||
b'>' => match self.pe_value(st) {
|
||||
Some(n) => st.fraction_bits = n.clamp(0, 52) as u32,
|
||||
None => return self.end_pe(),
|
||||
},
|
||||
b'=' => st.absolute = true,
|
||||
b'7' => st.seven_bit = true,
|
||||
_ => return Some(PeItem::Rect),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let scale = 0.5f64.powi(st.fraction_bits as i32);
|
||||
let (Some(x), Some(y)) = (self.pe_value(st), self.pe_value(st)) else { return self.end_pe() };
|
||||
let item = PeItem::Point { x: x as f64 * scale, y: y as f64 * scale, up: st.up, absolute: st.absolute };
|
||||
(st.up, st.absolute) = (false, false);
|
||||
return Some(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The rest of a PE instruction that can't be decoded: see [`Lexer::skip_pe`].
|
||||
fn end_pe(&mut self) -> Option<PeItem> {
|
||||
self.skip_pe();
|
||||
None
|
||||
}
|
||||
|
||||
/// The data of a PE instruction, up to and including its semicolon, unread: its data is never
|
||||
/// read as instructions.
|
||||
pub fn skip_pe(&mut self) {
|
||||
let rest = &self.b[self.at..];
|
||||
self.at += rest.iter().position(|&c| c == b';').map_or(rest.len(), |n| n + 1);
|
||||
}
|
||||
|
||||
/// One encoded PE number, `None` when the instruction ends inside it (or a byte that is no
|
||||
/// digit comes first, which is read).
|
||||
fn pe_value(&mut self, st: &Pe) -> Option<i64> {
|
||||
let (base, low, high): (u64, std::ops::RangeInclusive<u8>, std::ops::RangeInclusive<u8>) =
|
||||
if st.seven_bit { (32, 63..=94, 95..=126) } else { (64, 63..=126, 191..=254) };
|
||||
let (mut v, mut place) = (0u64, 1u64);
|
||||
loop {
|
||||
let raw = self.peek()?;
|
||||
let c = if st.seven_bit { raw & 0x7f } else { raw };
|
||||
if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 {
|
||||
self.at += 1;
|
||||
continue;
|
||||
}
|
||||
if c == b';' {
|
||||
return None;
|
||||
}
|
||||
self.at += 1;
|
||||
let (digit, last) = if low.contains(&c) {
|
||||
(u64::from(c - 63), false)
|
||||
} else if high.contains(&c) {
|
||||
(u64::from(c - high.start()), true)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
v = v.saturating_add(digit.saturating_mul(place));
|
||||
place = place.saturating_mul(base);
|
||||
if last {
|
||||
// The low bit is the sign.
|
||||
let n = i64::try_from(v >> 1).unwrap_or(i64::MAX);
|
||||
return Some(if v & 1 == 1 { -n } else { n });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,630 @@
|
||||
//! HP-GL import: units and the y axis, pens, runs, curves, filled and edged areas, polygon mode,
|
||||
//! line types, scaling, rotation, encoded polylines, escapes around the instructions, what is
|
||||
//! skipped with a warning, which files are taken to be HP-GL, and hostile files.
|
||||
|
||||
use kurbo::{BezPath, PathEl, Point, Shape as _};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, LineCap, LineJoin, Node, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::FillRule;
|
||||
|
||||
use super::plot::{FAR_AWAY, HATCHES, LABELS, PAGES, RASTER, SYMBOLS, TOO_MANY_POINTS, WINDOW};
|
||||
use super::*;
|
||||
|
||||
/// Points per millimeter.
|
||||
const MM: f64 = 72.0 / 25.4;
|
||||
|
||||
fn plot(s: &str) -> Imported {
|
||||
plot_bytes(s.as_bytes())
|
||||
}
|
||||
|
||||
fn plot_bytes(b: &[u8]) -> Imported {
|
||||
match import(b) {
|
||||
Ok(i) => i,
|
||||
Err(e) => panic!("{e}: {:?}", String::from_utf8_lossy(b)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every object, in paint order.
|
||||
fn leaves(doc: &Document) -> Vec<Node> {
|
||||
let mut out = vec![];
|
||||
doc.walk(|n| {
|
||||
if n.children().is_none() {
|
||||
out.push(n.clone());
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn bez(n: &Node) -> BezPath {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.to_bezpath(),
|
||||
k => panic!("a path, got {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn stroke(n: &Node) -> StrokeLayer {
|
||||
n.appearance.items.iter().find_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.clone()) } else { None }).expect("a stroke")
|
||||
}
|
||||
|
||||
fn fill(n: &Node) -> Option<Paint> {
|
||||
n.appearance.items.iter().find_map(|i| if let AppearanceItem::Fill(f) = i { Some(f.paint.clone()) } else { None })
|
||||
}
|
||||
|
||||
fn rule(n: &Node) -> FillRule {
|
||||
match &n.kind {
|
||||
NodeKind::Path { rule, .. } => *rule,
|
||||
k => panic!("a path, got {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn rgb(r: u8, g: u8, b: u8) -> Paint {
|
||||
Paint::solid(Color::rgb8(r, g, b))
|
||||
}
|
||||
|
||||
/// The end points of `bp`'s elements.
|
||||
fn ends(bp: &BezPath) -> Vec<Point> {
|
||||
bp.elements().iter().filter_map(|e| e.end_point()).collect()
|
||||
}
|
||||
|
||||
fn near(a: Point, b: Point) -> bool {
|
||||
(a - b).hypot() < 1e-6
|
||||
}
|
||||
|
||||
fn assert_points(got: &[Point], want: &[(f64, f64)]) {
|
||||
assert_eq!(got.len(), want.len(), "{got:?}");
|
||||
for (g, w) in got.iter().zip(want) {
|
||||
assert!(near(*g, Point::new(w.0, w.1)), "{got:?} != {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A PE number as the reference guide's encoding writes it (base 64, or base 32 for 7-bit data).
|
||||
fn pe_number(v: i64, seven_bit: bool) -> Vec<u8> {
|
||||
let mut n = if v >= 0 { 2 * v as u64 } else { 2 * v.unsigned_abs() + 1 };
|
||||
let (base, high) = if seven_bit { (32, 95) } else { (64, 191) };
|
||||
let mut out = vec![];
|
||||
while n >= base {
|
||||
out.push(63 + (n % base) as u8);
|
||||
n /= base;
|
||||
}
|
||||
out.push(high + n as u8);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plotter_units_become_points_with_y_down() {
|
||||
// An inch right and an inch up, with the thinnest pen (0.25 pt): the artboard reaches 0.125 pt
|
||||
// past the line at the corner's miter, and stops at the line's butt ends.
|
||||
let i = plot("IN;SP1;PW0;PU0,0;PD1016,0,1016,1016;PU;");
|
||||
let doc = &i.document;
|
||||
let r = doc.artboards[0].rect;
|
||||
assert!((r.width() - 72.125).abs() < 1e-9 && (r.height() - 72.125).abs() < 1e-9, "{r:?}");
|
||||
let shapes = leaves(doc);
|
||||
assert_eq!(shapes.len(), 1);
|
||||
assert_points(&ends(&bez(&shapes[0])), &[(0.0, 72.0), (72.0, 72.0), (72.0, 0.0)]);
|
||||
let s = stroke(&shapes[0]);
|
||||
assert_eq!((s.width, s.paint.clone(), s.cap, s.join, s.miter_limit), (0.25, rgb(0, 0, 0), LineCap::Butt, LineJoin::Miter, 5.0));
|
||||
assert!(fill(&shapes[0]).is_none() && i.warnings.is_empty(), "{:?}", i.warnings);
|
||||
|
||||
// The artboard holds what the strokes paint, the tip of a sharp miter join included.
|
||||
let i = plot("IN;SP1;PW2;PD2032,0,0,1000;");
|
||||
let r = i.document.artboards[0].rect;
|
||||
let painted = leaves(&i.document)[0].visual_bounds().unwrap();
|
||||
let path = bez(&leaves(&i.document)[0]).bounding_box();
|
||||
assert!(painted.x1 - path.x1 > 2.0 * MM, "the miter reaches past half the width: {painted:?} {path:?}");
|
||||
let inside = r.x0 <= painted.x0 + 1e-9 && r.y0 <= painted.y0 + 1e-9 && r.x1 >= painted.x1 - 1e-9 && r.y1 >= painted.y1 - 1e-9;
|
||||
assert!(inside, "{r:?} {painted:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pens_pick_colors_and_widths() {
|
||||
// Before any SP the pen is pen 1; SP0 draws nothing; pens past the palette wrap round it.
|
||||
let i = plot("IN;PD0,0,100,0;PU;SP2;PD0,100,100,100;PU;SP0;PD0,200,100,200;PU;SP9;PD0,300,100,300;PU;SP3;PD0,400,100,400;PU;");
|
||||
let colors: Vec<Paint> = leaves(&i.document).iter().map(|n| stroke(n).paint).collect();
|
||||
assert_eq!(colors, [rgb(0, 0, 0), rgb(255, 0, 0), rgb(255, 0, 0), rgb(0, 255, 0)]);
|
||||
|
||||
// PC gives a pen a color in the color range; PC with the pen alone gives back its default.
|
||||
let i = plot("IN;CR0,1,0,1,0,1;PC3,0,0,1;SP3;PD0,0,10,0;PU;PC3;PD0,10,10,10;PU;");
|
||||
let colors: Vec<Paint> = leaves(&i.document).iter().map(|n| stroke(n).paint).collect();
|
||||
assert_eq!(colors, [rgb(0, 0, 255), rgb(0, 255, 0)]);
|
||||
|
||||
// PW in millimeters for every pen, or for one; IN gives back 0.35 mm.
|
||||
let i = plot("IN;SP1;PW1;PD0,0,10,0;PU;PW2,2;SP2;PD0,10,10,10;PU;SP1;PD0,20,10,20;PU;IN;SP1;PD0,30,10,30;");
|
||||
let widths: Vec<f64> = leaves(&i.document).iter().map(|n| stroke(n).width).collect();
|
||||
let want = [MM, 2.0 * MM, MM, 0.35 * MM];
|
||||
assert!(widths.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9), "{widths:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_run_with_the_pen_down_is_one_path() {
|
||||
// Relative moves; a run that comes back to its start is closed; a pen-up move elsewhere starts
|
||||
// another path, and one back to where the line ended continues it.
|
||||
let i = plot("IN;SP1;PW0;PA0,0;PR;PD1016,0,0,1016,-1016,0,0,-1016;PU2032,0;PD0,1016;PU0,1016;PU0,-1016;PD508,0;PU0,500;PD0,500;");
|
||||
let shapes = leaves(&i.document);
|
||||
assert_eq!(shapes.len(), 3, "{shapes:#?}");
|
||||
let NodeKind::Path { path: square, .. } = &shapes[0].kind else { panic!("a path") };
|
||||
assert_eq!((square.subpaths.len(), square.subpaths[0].anchors.len(), square.subpaths[0].closed), (1, 4, true));
|
||||
assert_eq!(ends(&bez(&shapes[1])).len(), 3, "the run went on from where it ended");
|
||||
assert_eq!(ends(&bez(&shapes[2])).len(), 2);
|
||||
|
||||
// A pen-down move of no length draws a dot.
|
||||
let i = plot("IN;SP1;PA500,500;PD;PA500,500;PU;");
|
||||
let shapes = leaves(&i.document);
|
||||
assert_eq!(shapes.len(), 1);
|
||||
let b = bez(&shapes[0]).bounding_box();
|
||||
assert!((b.width() - 72.0 / 1016.0).abs() < 1e-9, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circles_arcs_and_curves_are_drawn_as_curves() {
|
||||
// A circle of an inch round the pen, which stays at its center (the next line starts there).
|
||||
let i = plot("IN;SP1;PW0;PA2032,2032;CI1016;PD3048,2032;");
|
||||
let shapes = leaves(&i.document);
|
||||
assert_eq!(shapes.len(), 2);
|
||||
let c = bez(&shapes[0]);
|
||||
assert!(c.elements().iter().any(|e| matches!(e, PathEl::CurveTo(..))) && matches!(c.elements().last(), Some(PathEl::ClosePath)));
|
||||
// The curves stay within a thousandth of a point of the circle.
|
||||
let b = c.bounding_box();
|
||||
assert!((b.width() - 144.0).abs() < 1e-3 && (b.height() - 144.0).abs() < 1e-3, "{b:?}");
|
||||
let line = ends(&bez(&shapes[1]));
|
||||
assert!((line[0] - b.center()).hypot() < 1e-3, "{line:?} {b:?}");
|
||||
|
||||
// AA: a quarter turn counterclockwise round (0, 0) from (1016, 0) ends at (0, 1016), and the
|
||||
// pen goes on from there. AR takes its center relative to the pen.
|
||||
for s in ["IN;SP1;PW0;PA1016,0;PD;AA0,0,90;PA0,2032;", "IN;SP1;PW0;PA1016,0;PD;AR-1016,0,90;PA0,2032;"] {
|
||||
let shapes = leaves(&plot(s).document);
|
||||
assert_eq!(shapes.len(), 1, "{s}");
|
||||
let p = bez(&shapes[0]);
|
||||
let pts = ends(&p);
|
||||
// y down: (1016, 0) is at the bottom right, the arc's end on the left a quarter turn up.
|
||||
let (start, end) = (pts[0], pts[pts.len() - 2]);
|
||||
assert!(near(start, Point::new(72.125, 144.0)) && near(end, Point::new(0.125, 72.0)), "{s}: {pts:?}");
|
||||
assert!(near(*pts.last().unwrap(), Point::new(0.125, 0.0)), "{s}: {pts:?}");
|
||||
}
|
||||
|
||||
// AT: the arc from the pen through a point to an end; points in a line give a line.
|
||||
let shapes = leaves(&plot("IN;SP1;PW0;PA1016,0;PD;AT0,1016,-1016,0;").document);
|
||||
let pts = ends(&bez(&shapes[0]));
|
||||
let b = bez(&shapes[0]).bounding_box();
|
||||
assert!((b.width() - 144.0).abs() < 1e-6 && (b.height() - 72.0).abs() < 1e-6, "a half circle: {b:?}");
|
||||
assert!(near(pts[0], Point::new(144.125, 72.125)) && near(*pts.last().unwrap(), Point::new(0.125, 72.125)), "{pts:?}");
|
||||
let shapes = leaves(&plot("IN;SP1;PW0;PA0,0;PD;AT508,0,1016,0;").document);
|
||||
assert_eq!(ends(&bez(&shapes[0])).len(), 2);
|
||||
|
||||
// BZ and BR: cubic Béziers, BR's points relative to each curve's start.
|
||||
for s in [
|
||||
"IN;SP1;PW0;PA0,0;PD;BZ0,1016,1016,1016,1016,0,1016,-1016,2032,-1016,2032,0;",
|
||||
"IN;SP1;PW0;PA0,0;PD;BR0,1016,1016,1016,1016,0,0,-1016,1016,-1016,1016,0;",
|
||||
] {
|
||||
let shapes = leaves(&plot(s).document);
|
||||
let els = bez(&shapes[0]).elements().to_vec();
|
||||
assert_eq!(els.iter().filter(|e| matches!(e, PathEl::CurveTo(..))).count(), 2, "{s}");
|
||||
// The curves reach 762 plotter units (three quarters of their control points) up and down.
|
||||
assert!(near(els.last().and_then(PathEl::end_point).unwrap(), Point::new(144.125, 54.125)), "{s}: {els:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rectangles_wedges_and_polygons_fill_and_edge() {
|
||||
// RA fills, EA edges; neither moves the pen.
|
||||
let i = plot("IN;SP2;PW0;PA0,0;RA1016,1016;EA1016,1016;PD508,0;");
|
||||
let shapes = leaves(&i.document);
|
||||
assert_eq!(shapes.len(), 3);
|
||||
assert_eq!((fill(&shapes[0]), shapes[0].appearance.items.len()), (Some(rgb(255, 0, 0)), 1));
|
||||
assert!(fill(&shapes[1]).is_none() && stroke(&shapes[1]).paint == rgb(255, 0, 0));
|
||||
assert!(near(ends(&bez(&shapes[2]))[0], Point::new(0.125, 72.125)), "the line starts where the pen was");
|
||||
|
||||
// WG fills a wedge, EW edges one; a whole turn is a circle.
|
||||
let i = plot("IN;SP1;PA0,0;WG1016,0,90;EW1016,0,360;");
|
||||
let shapes = leaves(&i.document);
|
||||
let wedge = bez(&shapes[0]);
|
||||
assert!(fill(&shapes[0]).is_some() && ends(&wedge).len() >= 3);
|
||||
let ring = bez(&shapes[1]).bounding_box();
|
||||
assert!((ring.width() - 144.0).abs() < 1e-6);
|
||||
|
||||
// Polygon mode: two squares, one inside the other; FP fills even-odd by default, FP1
|
||||
// non-zero; EP edges only what was drawn with the pen down.
|
||||
let poly = "IN;SP1;PW0;PA0,0;PM0;PD3048,0,3048,3048,0,3048,0,0;PM1;PU1016,1016;PD2032,1016;PU2032,2032;PD1016,2032,1016,1016;PM2;";
|
||||
let i = plot(&format!("{poly}FP;FP1;EP;"));
|
||||
let shapes = leaves(&i.document);
|
||||
assert_eq!(shapes.len(), 3);
|
||||
assert_eq!((rule(&shapes[0]), rule(&shapes[1])), (FillRule::EvenOdd, FillRule::NonZero));
|
||||
let filled = bez(&shapes[0]);
|
||||
assert_eq!(filled.elements().iter().filter(|e| matches!(e, PathEl::ClosePath)).count(), 2);
|
||||
let edged = bez(&shapes[2]);
|
||||
assert_eq!(edged.elements().iter().filter(|e| matches!(e, PathEl::MoveTo(..))).count(), 3, "the pen-up side isn't edged: {edged:?}");
|
||||
// Nothing is drawn in polygon mode itself.
|
||||
assert!(leaves(&plot(poly).document).is_empty());
|
||||
|
||||
// A circle in polygon mode is a subpolygon of its own; CI and RA after PM2 work as before.
|
||||
let i = plot("IN;SP1;PA2032,2032;PM0;CI1016;PM2;FP;");
|
||||
assert_eq!(leaves(&i.document).len(), 1);
|
||||
|
||||
// Fill types: shading mixes the pen with white; hatching fills solid with a warning.
|
||||
let i = plot("IN;SP5;PA0,0;FT10,50;RA100,100;FT3,10,45;RA200,200;");
|
||||
let shapes = leaves(&i.document);
|
||||
assert_eq!((fill(&shapes[0]), fill(&shapes[1])), (Some(rgb(128, 128, 255)), Some(rgb(0, 0, 255))));
|
||||
assert_eq!(i.warnings, [HATCHES]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_types_become_dash_patterns() {
|
||||
// A 10 mm pattern of line type 2 is 5 mm on, 5 mm off.
|
||||
let i = plot("IN;SP1;LT2,10,1;PD0,0,4000,0;");
|
||||
let d = stroke(&leaves(&i.document)[0]).dash.expect("dashed");
|
||||
assert!(d.pattern.iter().all(|v| (v - 5.0 * MM).abs() < 1e-9) && d.pattern.len() == 2 && !d.align_corners, "{d:?}");
|
||||
// The default length is 4% of the P1-P2 diagonal; IP sets P1 and P2.
|
||||
let i = plot("IN;IP0,0,3000,4000;SP1;LT3;PD0,0,4000,0;");
|
||||
let d = stroke(&leaves(&i.document)[0]).dash.expect("dashed");
|
||||
let total = 200.0 * 72.0 / 1016.0;
|
||||
assert!((d.pattern[0] - 0.7 * total).abs() < 1e-9 && (d.pattern[1] - 0.3 * total).abs() < 1e-9, "{d:?}");
|
||||
// Adaptive types stretch to each line; a zero length is a dot one plotter unit long.
|
||||
let i = plot("IN;SP1;LT-4,10,1;PD0,0,4000,0;");
|
||||
let d = stroke(&leaves(&i.document)[0]).dash.expect("dashed");
|
||||
assert!(d.align_corners && (d.pattern[2] - 72.0 / 1016.0).abs() < 1e-12, "{d:?}");
|
||||
// UL redefines a type; LT; draws solid and LT99 gives the type back.
|
||||
let i = plot("IN;SP1;UL2,1,3;LT2,10,1;PD0,0,4000,0;PU;LT;PD0,100,4000,100;PU;LT99;PD0,200,4000,200;");
|
||||
let shapes = leaves(&i.document);
|
||||
let d = stroke(&shapes[0]).dash.expect("dashed");
|
||||
assert!((d.pattern[0] - 2.5 * MM).abs() < 1e-9 && (d.pattern[1] - 7.5 * MM).abs() < 1e-9, "{d:?}");
|
||||
assert!(stroke(&shapes[1]).dash.is_none() && stroke(&shapes[2]).dash.is_some());
|
||||
// Line type 0 draws a dot at each point.
|
||||
let i = plot("IN;SP1;LT0;PD0,0,1000,0,2000,0;");
|
||||
assert_eq!(leaves(&i.document).len(), 3);
|
||||
// LA sets the caps, joins and miter limit.
|
||||
let s = stroke(&leaves(&plot("IN;SP1;LA1,4,2,4,3,9;PD0,0,100,0;").document)[0]);
|
||||
assert_eq!((s.cap, s.join, s.miter_limit), (LineCap::Round, LineJoin::Round, 9.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scaling_maps_user_units_onto_p1_and_p2() {
|
||||
// Anisotropic: 100 user units across an inch.
|
||||
let size = |s: &str| {
|
||||
let shapes = leaves(&plot(s).document);
|
||||
bez(&shapes[0]).bounding_box().size()
|
||||
};
|
||||
let s = size("IN;IP0,0,1016,2032;SC0,100,0,100;SP1;PD0,0,100,100;");
|
||||
assert!((s.width - 72.0).abs() < 1e-9 && (s.height - 144.0).abs() < 1e-9, "{s:?}");
|
||||
// Isotropic: the smaller of the two scales on both axes.
|
||||
let s = size("IN;IP0,0,1016,2032;SC0,100,0,100,1;SP1;PU0,0;PD100,100;");
|
||||
assert!((s.width - 72.0).abs() < 1e-9 && (s.height - 72.0).abs() < 1e-9, "{s:?}");
|
||||
// Point factor: 10 plotter units per user unit.
|
||||
let s = size("IN;SC0,10,0,10,2;SP1;PD0,0,101.6,50.8;");
|
||||
assert!((s.width - 72.0).abs() < 1e-9 && (s.height - 36.0).abs() < 1e-9, "{s:?}");
|
||||
// Without IP, P2 lies 11 × 8.5 in from the origin.
|
||||
let s = size("IN;SC0,11,0,8.5;SP1;PD0,0,1,1;");
|
||||
assert!((s.width - 72.0).abs() < 1e-9 && (s.height - 72.0).abs() < 1e-9, "{s:?}");
|
||||
// SC; goes back to plotter units; scaling that makes no area is ignored.
|
||||
let s = size("IN;SC0,1,0,1;SC;SC0,0,0,1;SP1;PD0,0,1016,1016;");
|
||||
assert!((s.width - 72.0).abs() < 1e-9, "{s:?}");
|
||||
// RO turns the coordinate system: x runs up.
|
||||
let shapes = leaves(&plot("IN;RO90;SP1;PW0;PA0,0;PD1016,0;").document);
|
||||
let b = bez(&shapes[0]).bounding_box();
|
||||
assert!(b.width() < 1e-9 && (b.height() - 72.0).abs() < 1e-9, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polyline_encoded_data_is_read() {
|
||||
let mut f = b"IN;SP1;PW0;PE".to_vec();
|
||||
// Pen 2, a pen-up move to the absolute (1016, 0), then a relative line an inch up.
|
||||
f.push(b':');
|
||||
f.extend(pe_number(2, false));
|
||||
f.extend(b"<=");
|
||||
f.extend(pe_number(1016, false));
|
||||
f.extend(pe_number(0, false));
|
||||
f.extend(pe_number(0, false));
|
||||
f.extend(pe_number(1016, false));
|
||||
f.push(b';');
|
||||
let i = plot_bytes(&f);
|
||||
let shapes = leaves(&i.document);
|
||||
assert_eq!(shapes.len(), 1);
|
||||
assert_eq!(stroke(&shapes[0]).paint, rgb(255, 0, 0));
|
||||
assert_points(&ends(&bez(&shapes[0])), &[(0.125, 72.0), (0.125, 0.0)]);
|
||||
|
||||
// 7-bit data with two fractional bits: 4064 / 4 = 1016.
|
||||
let mut f = b"IN;SP1;PW0;PE7>".to_vec();
|
||||
f.extend(pe_number(2, true));
|
||||
f.extend(pe_number(-4064, true));
|
||||
f.extend(pe_number(0, true));
|
||||
f.push(b';');
|
||||
let b = bez(&leaves(&plot_bytes(&f).document)[0]).bounding_box();
|
||||
assert!((b.width() - 72.0).abs() < 1e-9, "{b:?}");
|
||||
|
||||
// Data that can't be decoded ends the instruction at its semicolon: none of it is read as
|
||||
// instructions.
|
||||
let shapes = leaves(&plot("IN;SP1;PE#PD5000,5000;PD1016,0;").document);
|
||||
assert_eq!(shapes.len(), 1);
|
||||
assert!((bez(&shapes[0]).bounding_box().width() - 72.0).abs() < 1e-9);
|
||||
|
||||
// Rectangle mode: a pen-up move, then a filled rectangle relative to it.
|
||||
let mut f = b"IN;SP3;PE9".to_vec();
|
||||
for v in [100, 100, 1016, 508] {
|
||||
f.extend(pe_number(v, false));
|
||||
}
|
||||
f.push(b';');
|
||||
let shapes = leaves(&plot_bytes(&f).document);
|
||||
assert_eq!(fill(&shapes[0]), Some(rgb(0, 255, 0)));
|
||||
let b = bez(&shapes[0]).bounding_box();
|
||||
assert!((b.width() - 72.0).abs() < 1e-9 && (b.height() - 36.0).abs() < 1e-9, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printer_escapes_and_job_lines_are_skipped() {
|
||||
let mut f = b"\x1b%-12345X@PJL JOB\r\n@PJL ENTER LANGUAGE=PCL\r\n\x1bE\x1b%0BIN;SP1;PW0;PD0,0,1016,0;PU;\x1b%0A".to_vec();
|
||||
// An HP RTL raster image whose data spells out instructions.
|
||||
f.extend(b"\x1b*r1A\x1b*b11WPD9999,9999\x1b*rC");
|
||||
f.extend(b"\x1b%1BPD1016,1016;\x1b%-12345X@PJL EOJ\r\n");
|
||||
assert!(is_hpgl(&f));
|
||||
let i = plot_bytes(&f);
|
||||
let shapes = leaves(&i.document);
|
||||
// The pen went up and came down where the line ended, so the line goes on.
|
||||
assert_eq!(shapes.len(), 1, "{shapes:#?}");
|
||||
assert_eq!(ends(&bez(&shapes[0])).len(), 3);
|
||||
assert_eq!(i.warnings, [RASTER], "{:?}", i.warnings);
|
||||
let r = i.document.artboards[0].rect;
|
||||
assert!((r.width() - 72.125).abs() < 1e-9 && (r.height() - 72.125).abs() < 1e-9, "{r:?}");
|
||||
|
||||
// The device-control escapes of older plotters.
|
||||
let f = b"\x1b.(\x1b.I81;;17:\x1b.N;19:IN;SP1;PD0,0,1016,0;\x1b.)";
|
||||
assert!(is_hpgl(f));
|
||||
assert_eq!(leaves(&plot_bytes(f).document).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_comments_and_unknown_instructions_are_skipped() {
|
||||
// A label's text, up to its terminator (ETX, or the one DT sets), isn't read as instructions.
|
||||
let i = plot("IN;SP1;LBPD9999,9999\x03DT*,1;LBPU0,0;PD5000,5000*CO\"PD8000,8000\";PD1016,0;PU;ZZ1,2;QQ;");
|
||||
let shapes = leaves(&i.document);
|
||||
assert_eq!(shapes.len(), 1);
|
||||
assert_eq!(i.warnings, [LABELS.to_string(), "2 instructions of kinds VectorCraft doesn't read were skipped".to_string()]);
|
||||
// Symbol mode's symbols aren't drawn, with a warning; its lines are.
|
||||
let i = plot("IN;SP1;SM*;PD100,0;SM;");
|
||||
assert_eq!((i.warnings.clone(), leaves(&i.document).len()), (vec![SYMBOLS.to_string()], 1));
|
||||
// Later pages and the input window are warned about.
|
||||
let i = plot("IN;IW0,0,10,10;SP1;PD100,0;PU;PG;PD0,100;PG;");
|
||||
assert_eq!(i.warnings, [WINDOW, PAGES]);
|
||||
// A page advance raises the pen at the origin: nothing joins the pages.
|
||||
let i = plot("IN;SP1;PD100,0;PG;PA200,0;PD300,0;");
|
||||
let shapes = leaves(&i.document);
|
||||
assert_eq!(shapes.len(), 2);
|
||||
assert_eq!(ends(&bez(&shapes[1])).len(), 2, "the second page's line starts at (200, 0)");
|
||||
// A page advance at the end changes nothing.
|
||||
assert!(plot("IN;SP1;PD100,0;PG;").warnings.is_empty());
|
||||
// A file that draws nothing opens as a letter-size page.
|
||||
let i = plot("IN;SP1;PU100,100;");
|
||||
assert!(leaves(&i.document).is_empty() && i.document.artboards[0].rect.size() == kurbo::Size::new(612.0, 792.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_plot_files_are_taken_for_hpgl() {
|
||||
for f in [
|
||||
&b"IN;SP1;PU0,0;PD100,100;"[..],
|
||||
b"in;sp1;pu0,0;pd100,100;",
|
||||
b";IN;\r\nSP1;\r\nPA100,100;",
|
||||
b"\x03IN;",
|
||||
b"SP1PD0,0,10,10PU",
|
||||
b"IN",
|
||||
b"CO\"made by hand\";IN;",
|
||||
b"IN;SP1;DT*;LBhello world*PA0,0;SMx;PA1,1;SM;",
|
||||
b"IN;SP1;PE<=\xbf\xbf;PU;",
|
||||
b"\x1b%-12345X@PJL ENTER LANGUAGE=HPGL2\nIN;SP1;",
|
||||
] {
|
||||
assert!(is_hpgl(f), "{:?}", String::from_utf8_lossy(f));
|
||||
}
|
||||
for f in [
|
||||
&b""[..],
|
||||
b"IN THE BEGINNING",
|
||||
b"set terminal png\nplot sin(x)\n",
|
||||
b"Paris, 10 to 12",
|
||||
b"SPDX-License-Identifier: MIT",
|
||||
b"CONTENTS",
|
||||
b"CO \"a comment\";hello world",
|
||||
b"DT*;LBtext*nope",
|
||||
b"\x89PNG\r\n\x1a\n",
|
||||
b"IN;SP1;PD0,0;hello world",
|
||||
b"\x1b%-12345X@PJL ENTER LANGUAGE=PCL\n\x1bE\x1b*r1A",
|
||||
] {
|
||||
assert!(!is_hpgl(f), "{:?}", String::from_utf8_lossy(f));
|
||||
assert_eq!(import(f).err().as_deref(), Some("not an HP-GL file"), "{:?}", String::from_utf8_lossy(f));
|
||||
}
|
||||
// A comment needs no string; instructions of an older or a device's own set count when a
|
||||
// semicolon ends them.
|
||||
for f in [&b"CO;IN;SP1;PD0,0,10,10;"[..], b"IN;CO;SP1;PD0,0,10,10;", b"IN;SP1;VA;VS10;PU0,0;PD1016,0;", b"IN;GC5;SP1;PD0,0,10,0;"] {
|
||||
assert!(is_hpgl(f), "{:?}", String::from_utf8_lossy(f));
|
||||
}
|
||||
assert!(!is_hpgl(b"IN;GC5") && !is_hpgl(b"IN;Hello, world;"));
|
||||
// A printer prolog of any length comes before the first instruction.
|
||||
let long = [&b"\x1b%-12345X"[..], &b"@PJL COMMENT a job line of some length\r\n".repeat(400), b"\x1bE\x1b%0BIN;SP1;PD100,0;"].concat();
|
||||
assert!(long.len() > 16_000 && is_hpgl(&long));
|
||||
assert_eq!(leaves(&plot_bytes(&long).document).len(), 1);
|
||||
// Instructions of any kind may follow the first eight, garbage included.
|
||||
assert!(is_hpgl(b"IN;SP1;PU;PD;PU;PD;PU;PD;hello world"));
|
||||
}
|
||||
|
||||
/// A file read as HP-GL (picked by its extension) may start with any instruction the reader knows,
|
||||
/// or one of another set that a semicolon ends; its content alone doesn't make it HP-GL.
|
||||
#[test]
|
||||
fn a_plot_file_may_start_with_any_instruction() {
|
||||
for f in [&b"SI0.2,0.3;SP1;PA0,0;PD1016,0;"[..], b"DI1,0;SP1;PA0,0;PD1016,0;", b"GC5;SP1;PA0,0;PD1016,0;"] {
|
||||
assert!(!is_hpgl(f), "{:?}", String::from_utf8_lossy(f));
|
||||
assert_eq!(leaves(&plot_bytes(f).document).len(), 1, "{:?}", String::from_utf8_lossy(f));
|
||||
}
|
||||
for f in [&b"GC5"[..], b"SIhello world", b"set terminal png\n"] {
|
||||
assert_eq!(import(f).err().as_deref(), Some("not an HP-GL file"), "{:?}", String::from_utf8_lossy(f));
|
||||
}
|
||||
// Instructions of another set alone, however many or long, are not taken for HP-GL.
|
||||
let long = [&b"GC"[..], "1".repeat(5000).as_bytes(), b";ZZ1;"].concat();
|
||||
for f in [&b"GC5;"[..], b"GC5;ZZ1;", b"GC5;ZZ1;YY2;XX3;WW4;VV5;UU6;TT7;", &long] {
|
||||
assert_eq!(import(f).err().as_deref(), Some("not an HP-GL file"), "{:?}", String::from_utf8_lossy(f));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escapes_that_carry_values_or_data_are_skipped_whole() {
|
||||
// A reset leaves HP-GL until a language switch; symbol-set escapes carry a value and a letter.
|
||||
for f in [
|
||||
&b"\x1bE\x1b(8U\x1b%1BIN;SP1;PD0,0,1016,0;"[..],
|
||||
b"\x1bE\x1b(10U\x1b)0N\x1b%1BIN;SP1;PD0,0,1016,0;",
|
||||
b"\x1bEHello\x1b%1BIN;SP1;PD0,0,1016,0;",
|
||||
] {
|
||||
assert!(is_hpgl(f), "{:?}", String::from_utf8_lossy(f));
|
||||
assert_eq!(leaves(&plot_bytes(f).document).len(), 1, "{:?}", String::from_utf8_lossy(f));
|
||||
}
|
||||
// A letter left over from an escape doesn't join the next mnemonic.
|
||||
let i = plot_bytes(b"IN;SP1;\x1b(8UPD0,0,1016,0;");
|
||||
assert!(i.warnings.is_empty() && leaves(&i.document).len() == 1, "{:?}", i.warnings);
|
||||
// Raster data by plane and transparent print data are skipped by their byte counts, however
|
||||
// they read.
|
||||
let line = |data_escape: &[u8]| {
|
||||
let data = b"\x1b%1BPD0,5000;";
|
||||
let mut f = b"IN;SP1;PW0;PD0,0,0,1016;\x1b%0A".to_vec();
|
||||
f.extend(data_escape);
|
||||
f.extend(data.len().to_string().as_bytes());
|
||||
f.extend(if data_escape.ends_with(b"b") { &b"V"[..] } else { b"X" });
|
||||
f.extend(data);
|
||||
f.extend(b"\x1b*rC\x1b%1BPD0,0;");
|
||||
bez(&leaves(&plot_bytes(&f).document)[0]).bounding_box()
|
||||
};
|
||||
for escape in [&b"\x1b*r1A\x1b*b"[..], b"\x1b&p"] {
|
||||
let b = line(escape);
|
||||
assert!((b.height() - 72.0).abs() < 1e-9, "{:?}: {b:?}", String::from_utf8_lossy(escape));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polygon_mode_follows_its_own_rules() {
|
||||
// The point after a circle starts a new subpolygon: the triangle after it doesn't reach back
|
||||
// to the circle's center, filled or edged.
|
||||
let i = plot("IN;SP1;PW0;PA1000,1000;PM0;CI200;PD2000,1000,2000,2000,1000,2000;PM2;FP;EP;");
|
||||
let shapes = leaves(&i.document);
|
||||
assert_eq!(shapes.len(), 2);
|
||||
for s in &shapes {
|
||||
let p = bez(s);
|
||||
let first = p.elements().iter().position(|e| matches!(e, PathEl::ClosePath)).unwrap_or(p.elements().len());
|
||||
let circle = BezPath::from_vec(p.elements()[..first].to_vec()).bounding_box();
|
||||
let center = circle.center();
|
||||
assert!(ends(&p).iter().all(|e| !near(*e, center)), "{p:?}");
|
||||
}
|
||||
// PM1 closes with the pen up: EP draws two sides of the triangle, not the third; PM2 closes
|
||||
// with the pen as it is.
|
||||
let sides = |s: &str| {
|
||||
let p = bez(&leaves(&plot(s).document)[0]);
|
||||
p.elements().iter().filter(|e| matches!(e, PathEl::LineTo(..))).count()
|
||||
};
|
||||
assert_eq!(sides("IN;SP1;PA0,0;PM0;PD1000,0,1000,1000;PM1;PM2;EP;"), 2);
|
||||
assert_eq!(sides("IN;SP1;PA0,0;PM0;PD1000,0,1000,1000;PM2;EP;"), 3);
|
||||
// The closing point moves the pen: a relative move after PM1 starts from the start.
|
||||
let i = plot("IN;SP1;PA0,0;PM0;PD1000,0,1000,1000;PM1;PU;PR0,2000;PD1000,0,0,1000;PM2;FP;");
|
||||
let b = bez(&leaves(&i.document)[0]).bounding_box();
|
||||
assert!((b.height() - 3000.0 * PT_PER_PLU).abs() < 1e-9, "{b:?}");
|
||||
// A subpolygon of fewer than three points (the closing point counted) is neither filled nor
|
||||
// edged.
|
||||
assert!(leaves(&plot("IN;SP1;PA0,0;PM0;PD0,0;PM2;FP;EP;").document).is_empty());
|
||||
let i = plot("IN;SP1;PA0,0;PM0;PR0,0;PM1;PA;PD1000,0,0,1000,0,0;PM2;FP;");
|
||||
let filled = bez(&leaves(&i.document)[0]);
|
||||
assert_eq!(filled.elements().iter().filter(|e| matches!(e, PathEl::ClosePath)).count(), 1, "{filled:?}");
|
||||
// Polygon mode ignores the instructions it doesn't allow: pens, scaling and labels.
|
||||
let i = plot("IN;SP1;PA0,0;PM0;SP2;SC0,1,0,1;LBPD9999,9999\x03PD1016,0,1016,1016;PM2;FP;");
|
||||
let shapes = leaves(&i.document);
|
||||
assert_eq!((shapes.len(), fill(&shapes[0])), (1, Some(rgb(0, 0, 0))));
|
||||
assert!((bez(&shapes[0]).bounding_box().width() - 72.0).abs() < 1e-9 && i.warnings.is_empty(), "{:?}", i.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_keeps_the_pen_and_turns_the_defaults() {
|
||||
// After RO90, IP's default P2 is the rotated hard-clip corner: the user square spans 8.5 in
|
||||
// across its rotated x axis and 11 in up it, which lie up and across the page.
|
||||
let i = plot("IN;RO90;IP;SC0,100,0,100;SP1;PW0;PA0,0;PD100,0,100,100,0,100,0,0;");
|
||||
let b = bez(&leaves(&i.document)[0]).bounding_box();
|
||||
assert!((b.width() - 792.0).abs() < 1e-9 && (b.height() - 612.0).abs() < 1e-9, "{b:?}");
|
||||
// IR's percentages are of the rotated limits too.
|
||||
let i = plot("IN;RO90;IR0,0,100,100;SC0,1,0,1;SP1;PW0;PA0,0;PD1,1;");
|
||||
let b = bez(&leaves(&i.document)[0]).bounding_box();
|
||||
assert!((b.width() - 792.0).abs() < 1e-9 && (b.height() - 612.0).abs() < 1e-9, "{b:?}");
|
||||
// The pen stays where it was on the page: a line after RO starts where the one before ended.
|
||||
let i = plot("IN;SP1;PW0;PD0,0,1016,0;PU;RO90;PD;PR1016,0;");
|
||||
let all = leaves(&i.document).iter().map(|n| bez(n).bounding_box()).reduce(|a, b| a.union(b)).unwrap();
|
||||
assert!((all.width() - 72.0).abs() < 1e-9 && (all.height() - 72.0).abs() < 1e-9, "{all:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_type_zero_and_odd_patterns_follow_the_reference() {
|
||||
// Line type 0: one dot for an arc (at its end) and one for a circle (at its center).
|
||||
for s in ["IN;SP1;LT0;PA0,0;PD;AA1016,0,180;", "IN;SP1;LT0;PA0,0;CI500;"] {
|
||||
let shapes = leaves(&plot(s).document);
|
||||
assert_eq!(shapes.len(), 1, "{s}");
|
||||
assert!(bez(&shapes[0]).bounding_box().width() < 0.1, "{s}");
|
||||
}
|
||||
// An odd number of gaps repeats with the last pen-down stretch running into the first.
|
||||
let i = plot("IN;SP1;UL3,50,25,25;LT3,10,1;PD0,0,4000,0;");
|
||||
let d = stroke(&leaves(&i.document)[0]).dash.expect("dashed");
|
||||
assert!((d.pattern[0] - 7.5 * MM).abs() < 1e-9 && (d.pattern[1] - 2.5 * MM).abs() < 1e-9 && d.pattern.len() == 2, "{d:?}");
|
||||
assert!((d.offset - 2.5 * MM).abs() < 1e-9, "{d:?}");
|
||||
// One pen-down stretch is a solid line; a dot keeps the pattern's length.
|
||||
let d = stroke(&leaves(&plot("IN;SP1;UL3,100;LT3,10,1;PD0,0,4000,0;").document)[0]).dash.expect("dashed");
|
||||
assert_eq!(d.pattern[1], 0.0);
|
||||
let d = stroke(&leaves(&plot("IN;SP1;LT4,10,1;PD0,0,4000,0;").document)[0]).dash.expect("dashed");
|
||||
assert!((d.pattern.iter().sum::<f64>() - 10.0 * MM).abs() < 1e-9, "{d:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pen_colors_ignore_two_or_three_parameters() {
|
||||
let i = plot("IN;PC3,0,0,255;PC3,255;PC3,255,0;SP3;PD0,0,10,0;");
|
||||
assert_eq!(stroke(&leaves(&i.document)[0]).paint, rgb(0, 0, 255));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_files_import_without_panics() {
|
||||
let mut cases: Vec<Vec<u8>> = vec![
|
||||
// Coordinates past any plotter's range, and numbers with too many digits.
|
||||
b"IN;SP1;PD99999999999999999999999999999,0;PU0,0;PD1016,1016;".to_vec(),
|
||||
b"IN;SP1;PD0.000000000000000000000000001,1e999,--,++,..;".to_vec(),
|
||||
// Unterminated labels, comments and encoded polylines.
|
||||
b"IN;SP1;LBno end".to_vec(),
|
||||
b"IN;CO\"no end".to_vec(),
|
||||
b"IN;SP1;PE<=\xff\xff\xff\xfe\xfe".to_vec(),
|
||||
b"IN;SP1;PE>\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\x7e\xfe\x40\xc0;".to_vec(),
|
||||
// Arcs and wedges of every degenerate kind, with huge sweeps.
|
||||
b"IN;SP1;PD;AA0,0,32767;AR0,0,90;AT0,0,0,0;RT1,1,2,2;CI0;CI-5;WG0,0,0;EW5,99999,-99999;WG-5,0,360;CI99999999999999;".to_vec(),
|
||||
// Scaling onto one point, rotations the format doesn't define, huge palettes and pens.
|
||||
b"IN;IP5,5,5,5;SC0,1,0,1,1;SP1;PD1,1;SC0,0,0,0,2;RO45;NP99999999;SP99999999999;PC99999999,1,2,3;PW99999,99999;PD2,2;".to_vec(),
|
||||
// Polygon mode left open, PM1 and PM2 without PM0, FP and EP with nothing buffered.
|
||||
b"IN;SP1;FP;EP;PM1;PM2;PM0;PD10,10;PM1;PM1;PM1;CI5;PE<\xc0\xc0;".to_vec(),
|
||||
// Escapes cut short, and data lengths past the end.
|
||||
b"\x1b%-12345X@PJL".to_vec(),
|
||||
b"IN;SP1;PD0,0;\x1b*b99999999999W".to_vec(),
|
||||
b"IN;\x1b".to_vec(),
|
||||
b"IN;\x1b.".to_vec(),
|
||||
];
|
||||
// A job line with no end.
|
||||
cases.push([&b"\x1b%-12345X@PJL "[..], &b"x".repeat(1 << 20)].concat());
|
||||
// Bytes of every value after a valid start.
|
||||
cases.push([&b"IN;SP1;PD"[..], &(0..=255u8).collect::<Vec<_>>()].concat());
|
||||
for f in &cases {
|
||||
let r = std::panic::catch_unwind(|| import(f));
|
||||
assert!(r.is_ok(), "{:?}", String::from_utf8_lossy(f));
|
||||
}
|
||||
let far = import(&cases[0]).unwrap();
|
||||
assert!(far.warnings.iter().any(|w| w == FAR_AWAY), "{:?}", far.warnings);
|
||||
assert_eq!(leaves(&far.document).len(), 1, "the line in range is kept");
|
||||
|
||||
// Past the budget for path points, the rest is left out with a warning; pen-up moves, which
|
||||
// make no path, don't count.
|
||||
let many = format!("IN;SP1;PR;PD{}", "1,0,".repeat(300_000));
|
||||
let i = plot(&many);
|
||||
assert!(i.warnings.iter().any(|w| w == TOO_MANY_POINTS), "{:?}", i.warnings);
|
||||
// Scaling points past any range give relative pen widths no wider than the widest pen.
|
||||
let i = plot("IN;IP-99999999999999999999,0,99999999999999999999,0;WU1;PW32767;SP1;PD100,0;");
|
||||
let r = i.document.artboards[0].rect;
|
||||
assert!(r.width().is_finite() && r.height() <= 16384.0 * 72.0 / 1016.0 + 1e-6, "{r:?}");
|
||||
assert!((stroke(&leaves(&i.document)[0]).width - 16384.0 * 72.0 / 1016.0).abs() < 1e-9);
|
||||
|
||||
// Each fill of the polygon buffer is a copy of it, and counts.
|
||||
let big = format!("IN;SP1;PM0;PR;PD{}PM2;{}", "1,1,".repeat(1000), "FP;EP;".repeat(1000));
|
||||
let i = plot(&big);
|
||||
assert!(i.warnings.iter().any(|w| w == TOO_MANY_POINTS) && leaves(&i.document).len() < 400, "{:?}", i.warnings);
|
||||
for pen in ["SP1;PU", "SP0;PD"] {
|
||||
let moves = format!("IN;{pen}{};SP1;PU0,0;PD1016,0;", "1,0,".repeat(300_000));
|
||||
let i = plot(&moves);
|
||||
assert!(i.warnings.is_empty() && leaves(&i.document).len() == 1, "{pen}: {:?}", i.warnings);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,265 @@
|
||||
//! Polylines cut by a region: each segment is split where it crosses the region's edges, and the
|
||||
//! pieces whose middle lies inside are kept, joined where they meet.
|
||||
|
||||
use vectorcraft_geom::{FillRule, Point, Rect};
|
||||
|
||||
/// A clipping region: closed rings (each closes implicitly) and the rule that decides inside.
|
||||
pub(super) struct Region {
|
||||
rings: Vec<Vec<Point>>,
|
||||
rule: FillRule,
|
||||
bounds: Rect,
|
||||
}
|
||||
|
||||
impl Region {
|
||||
/// The region of `rings` under `rule`; `None` when it has no ring of three points or more.
|
||||
pub fn new(rings: Vec<Vec<Point>>, rule: FillRule) -> Option<Self> {
|
||||
let rings: Vec<Vec<Point>> = rings.into_iter().filter(|r| r.len() >= 3).collect();
|
||||
let bounds = rings.iter().flatten().fold(None, |b: Option<Rect>, p| Some(b.map_or(Rect::from_points(*p, *p), |b| b.union_pt(*p))))?;
|
||||
Some(Self { rings, rule, bounds })
|
||||
}
|
||||
|
||||
/// The edges this region has, which [`Region::cut`] tests each segment against.
|
||||
fn edges(&self) -> u64 {
|
||||
self.rings.iter().map(|r| r.len() as u64).sum()
|
||||
}
|
||||
|
||||
/// Does `p` lie on one of the region's edges (within a millionth of a point)?
|
||||
fn on_edge(&self, p: Point) -> bool {
|
||||
self.rings.iter().any(|ring| {
|
||||
ring.iter().enumerate().any(|(i, &a)| {
|
||||
let b = ring[(i + 1) % ring.len()];
|
||||
let ab = b - a;
|
||||
let len2 = ab.hypot2();
|
||||
let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(a + ab * t).distance(p) <= 1e-6
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Is `p` inside (non-zero winding or an odd number of crossings), or on an edge?
|
||||
fn contains(&self, p: Point) -> bool {
|
||||
if self.on_edge(p) {
|
||||
return true;
|
||||
}
|
||||
let mut winding = 0i64;
|
||||
for ring in &self.rings {
|
||||
for (i, &a) in ring.iter().enumerate() {
|
||||
let b = ring[(i + 1) % ring.len()];
|
||||
if a.y <= p.y {
|
||||
if b.y > p.y && cross(a, b, p) > 0.0 {
|
||||
winding += 1;
|
||||
}
|
||||
} else if b.y <= p.y && cross(a, b, p) < 0.0 {
|
||||
winding -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
match self.rule {
|
||||
FillRule::NonZero => winding != 0,
|
||||
FillRule::EvenOdd => winding % 2 != 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where segment `a`–`b` crosses this region's edges, as fractions of its length strictly
|
||||
/// between 0 and 1, sorted.
|
||||
fn crossings(&self, a: Point, b: Point) -> Vec<f64> {
|
||||
let mut ts = vec![];
|
||||
for ring in &self.rings {
|
||||
for (i, &c) in ring.iter().enumerate() {
|
||||
let d = ring[(i + 1) % ring.len()];
|
||||
if let Some(t) = intersect(a, b, c, d)
|
||||
&& t > 1e-12
|
||||
&& t < 1.0 - 1e-12
|
||||
{
|
||||
ts.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
ts.sort_by(f64::total_cmp);
|
||||
ts.dedup_by(|x, y| (*x - *y).abs() <= 1e-12);
|
||||
ts
|
||||
}
|
||||
|
||||
/// The parts of polyline `line` inside the region, each a polyline of two points or more.
|
||||
/// Every test of a point or a segment against an edge takes one from `budget`; `None` when
|
||||
/// the budget runs out first.
|
||||
pub fn cut(&self, line: &[Point], budget: &mut u64) -> Option<Vec<Vec<Point>>> {
|
||||
let edges = self.edges();
|
||||
let mut out: Vec<Vec<Point>> = vec![];
|
||||
let mut cur: Vec<Point> = vec![];
|
||||
for w in line.windows(2) {
|
||||
let (a, b) = (w[0], w[1]);
|
||||
// A segment wholly off the region's box lies outside it.
|
||||
let near = overlaps(Rect::from_points(a, b), self.bounds);
|
||||
let ts = if near {
|
||||
spend(budget, edges)?;
|
||||
self.crossings(a, b)
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let mut from = 0.0;
|
||||
for to in ts.into_iter().chain([1.0]) {
|
||||
let (p, q) = (a.lerp(b, from), a.lerp(b, to));
|
||||
// Each piece between crossings is tested on its own: its edge and winding tests.
|
||||
let inside = if near {
|
||||
spend(budget, edges.saturating_mul(2))?;
|
||||
self.contains(p.midpoint(q))
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if inside {
|
||||
if cur.last().is_none_or(|l| l.distance(p) > 1e-9) {
|
||||
flush(&mut out, &mut cur);
|
||||
cur.push(p);
|
||||
}
|
||||
cur.push(q);
|
||||
} else {
|
||||
flush(&mut out, &mut cur);
|
||||
}
|
||||
from = to;
|
||||
}
|
||||
}
|
||||
flush(&mut out, &mut cur);
|
||||
// A closed line that leaves the region and comes back: its last piece ends where its
|
||||
// first starts, at the line's start, and the two are one piece.
|
||||
if line.len() > 2
|
||||
&& line.first() == line.last()
|
||||
&& out.len() >= 2
|
||||
&& let (Some(end), Some(start)) = (out.last().and_then(|l| l.last()), out.first().and_then(|l| l.first()))
|
||||
&& end.distance(*start) <= 1e-9
|
||||
{
|
||||
let first = out.remove(0);
|
||||
if let Some(last) = out.last_mut() {
|
||||
last.extend(first.into_iter().skip(1));
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Take `n` from `budget`; `None` when it holds less.
|
||||
fn spend(budget: &mut u64, n: u64) -> Option<()> {
|
||||
*budget = budget.checked_sub(n)?;
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn flush(out: &mut Vec<Vec<Point>>, cur: &mut Vec<Point>) {
|
||||
let line = std::mem::take(cur);
|
||||
if line.len() >= 2 {
|
||||
out.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
fn overlaps(a: Rect, b: Rect) -> bool {
|
||||
a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1
|
||||
}
|
||||
|
||||
/// Which side of line `a`–`b` point `p` lies on (positive: left).
|
||||
fn cross(a: Point, b: Point, p: Point) -> f64 {
|
||||
(b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y)
|
||||
}
|
||||
|
||||
/// Where segment `a`–`b` crosses segment `c`–`d`, as a fraction of `a`–`b`; `None` when they
|
||||
/// are parallel or don't meet.
|
||||
fn intersect(a: Point, b: Point, c: Point, d: Point) -> Option<f64> {
|
||||
let (r, s) = (b - a, d - c);
|
||||
let den = r.x * s.y - r.y * s.x;
|
||||
if den.abs() <= f64::EPSILON * (r.hypot() * s.hypot()).max(f64::MIN_POSITIVE) {
|
||||
return None;
|
||||
}
|
||||
let ac = c - a;
|
||||
let t = (ac.x * s.y - ac.y * s.x) / den;
|
||||
let u = (ac.x * r.y - ac.y * r.x) / den;
|
||||
((0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u)).then_some(t)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> Vec<Point> {
|
||||
vec![Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)]
|
||||
}
|
||||
|
||||
/// `line` cut by `r` with no limit on the work.
|
||||
fn cut(r: &Region, line: &[Point]) -> Vec<Vec<Point>> {
|
||||
let mut unlimited = u64::MAX;
|
||||
r.cut(line, &mut unlimited).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_across_a_square_keeps_its_middle() {
|
||||
let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap();
|
||||
let pieces = cut(&r, &[Point::new(-5.0, 5.0), Point::new(15.0, 5.0)]);
|
||||
assert_eq!(pieces, vec![vec![Point::new(0.0, 5.0), Point::new(10.0, 5.0)]]);
|
||||
// Wholly outside, nothing; wholly inside, the line as it is.
|
||||
assert!(cut(&r, &[Point::new(20.0, 0.0), Point::new(30.0, 0.0)]).is_empty());
|
||||
let inside = vec![Point::new(1.0, 1.0), Point::new(9.0, 1.0), Point::new(9.0, 9.0)];
|
||||
assert_eq!(cut(&r, &inside), vec![inside]);
|
||||
}
|
||||
|
||||
/// Each piece between crossings costs a pass over the edges: a line through the teeth of a
|
||||
/// comb spends far more than its two points times the edges.
|
||||
#[test]
|
||||
fn every_piece_between_crossings_is_paid_for() {
|
||||
let mut ring = vec![];
|
||||
for i in 0..100 {
|
||||
let x = f64::from(i) * 4.0;
|
||||
ring.extend([Point::new(x, 0.0), Point::new(x + 2.0, 0.0), Point::new(x + 2.0, 10.0), Point::new(x + 4.0, 10.0)]);
|
||||
}
|
||||
ring.extend([Point::new(400.0, 20.0), Point::new(0.0, 20.0)]);
|
||||
let r = Region::new(vec![ring], FillRule::NonZero).unwrap();
|
||||
let line = [Point::new(-1.0, 5.0), Point::new(401.0, 5.0)];
|
||||
// 402 edges, 200 crossings, 201 pieces: 402 + 201 × 2 × 402 tests.
|
||||
let need = 402 + 201 * 2 * 402;
|
||||
let mut budget = need;
|
||||
assert_eq!(r.cut(&line, &mut budget).map(|p| p.len()), Some(100));
|
||||
assert_eq!(budget, 0);
|
||||
let mut short = need - 1;
|
||||
assert!(r.cut(&line, &mut short).is_none());
|
||||
// A segment off the region's box costs nothing.
|
||||
assert_eq!(r.cut(&[Point::new(0.0, 30.0), Point::new(9.0, 30.0)], &mut 0), Some(vec![]));
|
||||
}
|
||||
|
||||
/// A line along any of the region's edges is inside it.
|
||||
#[test]
|
||||
fn a_line_on_an_edge_is_kept() {
|
||||
let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap();
|
||||
for line in [
|
||||
[Point::new(0.0, 0.0), Point::new(10.0, 0.0)],
|
||||
[Point::new(10.0, 0.0), Point::new(10.0, 10.0)],
|
||||
[Point::new(10.0, 10.0), Point::new(0.0, 10.0)],
|
||||
[Point::new(0.0, 10.0), Point::new(0.0, 0.0)],
|
||||
] {
|
||||
assert_eq!(cut(&r, &line), vec![line.to_vec()], "{line:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_leaving_and_coming_back_is_two_pieces() {
|
||||
let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap();
|
||||
let line = [Point::new(5.0, 5.0), Point::new(15.0, 5.0), Point::new(15.0, 8.0), Point::new(5.0, 8.0)];
|
||||
assert_eq!(cut(&r, &line), vec![vec![Point::new(5.0, 5.0), Point::new(10.0, 5.0)], vec![Point::new(10.0, 8.0), Point::new(5.0, 8.0)]]);
|
||||
}
|
||||
|
||||
/// A closed line that starts inside, leaves and comes back is one piece: the part after it
|
||||
/// comes back runs on into the part before it left.
|
||||
#[test]
|
||||
fn a_closed_line_cut_once_stays_one_piece() {
|
||||
let r = Region::new(vec![square(0.0, 0.0, 10.0, 10.0)], FillRule::NonZero).unwrap();
|
||||
let line = [Point::new(5.0, 5.0), Point::new(15.0, 5.0), Point::new(15.0, 8.0), Point::new(5.0, 8.0), Point::new(5.0, 5.0)];
|
||||
assert_eq!(cut(&r, &line), vec![vec![Point::new(10.0, 8.0), Point::new(5.0, 8.0), Point::new(5.0, 5.0), Point::new(10.0, 5.0)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fill_rule_decides_a_hole() {
|
||||
let rings = vec![square(0.0, 0.0, 10.0, 10.0), square(3.0, 3.0, 7.0, 7.0)];
|
||||
let line = [Point::new(-1.0, 5.0), Point::new(11.0, 5.0)];
|
||||
// Both rings wind the same way: even-odd cuts a hole, non-zero doesn't.
|
||||
let even_odd = cut(&Region::new(rings.clone(), FillRule::EvenOdd).unwrap(), &line);
|
||||
assert_eq!(even_odd, vec![vec![Point::new(0.0, 5.0), Point::new(3.0, 5.0)], vec![Point::new(7.0, 5.0), Point::new(10.0, 5.0)]]);
|
||||
let non_zero = cut(&Region::new(rings, FillRule::NonZero).unwrap(), &line);
|
||||
assert_eq!(non_zero.len(), 1);
|
||||
assert!(Region::new(vec![vec![Point::ZERO, Point::new(1.0, 1.0)]], FillRule::NonZero).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
//! Which of a pen's paths lie inside which of its closed paths, in plotter units, for drawing the
|
||||
//! inner paths first.
|
||||
|
||||
/// The box of `p`: `[x0, y0, x1, y1]`.
|
||||
pub(super) fn bounds(p: &[(i64, i64)]) -> [i64; 4] {
|
||||
p.iter().fold([i64::MAX, i64::MAX, i64::MIN, i64::MIN], |b, q| [b[0].min(q.0), b[1].min(q.1), b[2].max(q.0), b[3].max(q.1)])
|
||||
}
|
||||
|
||||
/// For each of `paths` (`boxes` are their [`bounds`]), the closed paths it lies inside: none of
|
||||
/// its segments crosses the closed path's line, each part of it between the points where it meets
|
||||
/// that line lies inside the closed path (by the even-odd rule) or on the line, and at least one
|
||||
/// part lies inside. A path touching the line of the one around it is inside it, a path crossing
|
||||
/// it is not, and copies of one outline are not inside each other. A path is tested only against
|
||||
/// closed paths larger than it (by the area of their box, then the area they enclose, then paint
|
||||
/// order), so no two paths are each inside the other, and only against the closed paths in the
|
||||
/// [`Grid`] cell of its box's first corner. `None` once `work` is spent: a grid cell filled and a
|
||||
/// box compared cost one each, and each segment tested costs the closed path's points for its
|
||||
/// crossings and again for each part of it.
|
||||
pub(super) fn outer(paths: &[Vec<(i64, i64)>], boxes: &[[i64; 4]], work: &mut u64) -> Option<Vec<Vec<usize>>> {
|
||||
let size: Vec<(i128, i128)> = paths
|
||||
.iter()
|
||||
.zip(boxes)
|
||||
.map(|(p, b)| {
|
||||
let box_area = (i128::from(b[2]) - i128::from(b[0])) * (i128::from(b[3]) - i128::from(b[1]));
|
||||
(box_area, if closed(p) { twice_area(p) } else { 0 })
|
||||
})
|
||||
.collect();
|
||||
let rings: Vec<usize> = (0..paths.len()).filter(|&i| paths.get(i).is_some_and(|p| closed(p))).collect();
|
||||
let mut out = vec![vec![]; paths.len()];
|
||||
if rings.is_empty() {
|
||||
return Some(out);
|
||||
}
|
||||
let grid = Grid::new(&rings, boxes, work)?;
|
||||
for (a, (p, ab)) in paths.iter().zip(boxes).enumerate() {
|
||||
for &r in grid.at(ab[0], ab[1]) {
|
||||
spend(work, 1)?;
|
||||
let (Some(rb), Some(ring)) = (boxes.get(r), paths.get(r)) else { continue };
|
||||
let smaller = (size.get(a), a) < (size.get(r), r);
|
||||
if !smaller || rb[0] > ab[0] || rb[1] > ab[1] || rb[2] < ab[2] || rb[3] < ab[3] {
|
||||
continue;
|
||||
}
|
||||
if inside(p, ring, work)?
|
||||
&& let Some(o) = out.get_mut(a)
|
||||
{
|
||||
o.push(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The most cells along each side of a [`Grid`].
|
||||
const MAX_GRID_SIDE: usize = 512;
|
||||
/// The most cells of a [`Grid`] a closed path is listed in; one whose box covers more is listed
|
||||
/// once, among the wide ones. A closed path has 4 points or more, so the grid lists no more
|
||||
/// entries than the pen has points.
|
||||
const MAX_CELLS_PER_PATH: usize = 4;
|
||||
|
||||
/// A grid over the boxes of a pen's closed paths, about one cell for each, up to
|
||||
/// [`MAX_GRID_SIDE`] a side: each cell lists, in paint order, the closed paths whose box covers
|
||||
/// it, and the closed paths whose box covers more than [`MAX_CELLS_PER_PATH`] cells are listed
|
||||
/// apart. A closed path whose box holds a point is among the wide ones or in that point's cell.
|
||||
struct Grid {
|
||||
/// The first corner of the closed paths' boxes together.
|
||||
x0: i128,
|
||||
y0: i128,
|
||||
/// Their width and height, plus one.
|
||||
w: i128,
|
||||
h: i128,
|
||||
/// Cells along each side.
|
||||
side: usize,
|
||||
/// The cells row by row.
|
||||
cells: Vec<Vec<usize>>,
|
||||
/// The closed paths whose box covers more than [`MAX_CELLS_PER_PATH`] cells.
|
||||
wide: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
/// The grid of the closed paths `rings` (indices into `boxes`). `None` once `work` is spent.
|
||||
fn new(rings: &[usize], boxes: &[[i64; 4]], work: &mut u64) -> Option<Self> {
|
||||
let all = rings
|
||||
.iter()
|
||||
.filter_map(|&r| boxes.get(r))
|
||||
.fold([i64::MAX, i64::MAX, i64::MIN, i64::MIN], |e, b| [e[0].min(b[0]), e[1].min(b[1]), e[2].max(b[2]), e[3].max(b[3])]);
|
||||
let side = ((rings.len() as f64).sqrt().ceil() as usize).clamp(1, MAX_GRID_SIDE);
|
||||
let (x0, y0) = (i128::from(all[0]), i128::from(all[1]));
|
||||
let mut grid = Self {
|
||||
x0,
|
||||
y0,
|
||||
w: (i128::from(all[2]) - x0 + 1).max(1),
|
||||
h: (i128::from(all[3]) - y0 + 1).max(1),
|
||||
side,
|
||||
cells: vec![vec![]; side * side],
|
||||
wide: vec![],
|
||||
};
|
||||
for &r in rings {
|
||||
let Some(b) = boxes.get(r) else { continue };
|
||||
let (Some((cx0, cy0)), Some((cx1, cy1))) = (grid.cell(b[0], b[1]), grid.cell(b[2], b[3])) else { continue };
|
||||
let covered = (cx1 - cx0 + 1) * (cy1 - cy0 + 1);
|
||||
if covered > MAX_CELLS_PER_PATH {
|
||||
spend(work, 1)?;
|
||||
grid.wide.push(r);
|
||||
continue;
|
||||
}
|
||||
spend(work, covered as u64)?;
|
||||
for cy in cy0..=cy1 {
|
||||
for cell in grid.cells.get_mut(cy * side + cx0..=cy * side + cx1).into_iter().flatten() {
|
||||
cell.push(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(grid)
|
||||
}
|
||||
|
||||
/// The column and row of the cell holding `(x, y)`, `None` outside the grid.
|
||||
fn cell(&self, x: i64, y: i64) -> Option<(usize, usize)> {
|
||||
let (dx, dy) = (i128::from(x) - self.x0, i128::from(y) - self.y0);
|
||||
if dx < 0 || dy < 0 || dx >= self.w || dy >= self.h {
|
||||
return None;
|
||||
}
|
||||
let side = self.side as i128;
|
||||
Some(((dx * side / self.w) as usize, (dy * side / self.h) as usize))
|
||||
}
|
||||
|
||||
/// The wide closed paths, then those listed in the cell holding `(x, y)`.
|
||||
fn at(&self, x: i64, y: i64) -> impl Iterator<Item = &usize> {
|
||||
let cell = self.cell(x, y).and_then(|(cx, cy)| self.cells.get(cy * self.side + cx)).map_or(&[][..], Vec::as_slice);
|
||||
self.wide.iter().chain(cell)
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes `n` from `work`; `None`, with `work` at 0, when it has less.
|
||||
fn spend(work: &mut u64, n: u64) -> Option<()> {
|
||||
let left = work.checked_sub(n);
|
||||
*work = left.unwrap_or(0);
|
||||
left.map(|_| ())
|
||||
}
|
||||
|
||||
/// Does `p` start and end at one point, with three other points or more?
|
||||
fn closed(p: &[(i64, i64)]) -> bool {
|
||||
p.len() > 3 && p.first() == p.last()
|
||||
}
|
||||
|
||||
/// Twice the area the closed path `p` encloses.
|
||||
fn twice_area(p: &[(i64, i64)]) -> i128 {
|
||||
let sum: i128 = p
|
||||
.windows(2)
|
||||
.map(|w| match w {
|
||||
[a, b] => i128::from(a.0) * i128::from(b.1) - i128::from(b.0) * i128::from(a.1),
|
||||
_ => 0,
|
||||
})
|
||||
.sum();
|
||||
sum.abs()
|
||||
}
|
||||
|
||||
/// Does `p` lie inside the closed path `ring`, as [`outer`] decides? `None` once `work` is spent.
|
||||
fn inside(p: &[(i64, i64)], ring: &[(i64, i64)], work: &mut u64) -> Option<bool> {
|
||||
let mut any = false;
|
||||
for w in p.windows(2) {
|
||||
let [s, e] = w else { continue };
|
||||
spend(work, ring.len() as u64)?;
|
||||
// Where the segment meets the line without crossing it: its ends and the ring's points on
|
||||
// it. Between two of these the segment is all inside or all outside.
|
||||
let mut stops = vec![*s, *e];
|
||||
for edge in ring.windows(2) {
|
||||
let [a, b] = edge else { continue };
|
||||
if crosses((*s, *e), (*a, *b)) {
|
||||
return Some(false);
|
||||
}
|
||||
if a != s && a != e && on((*s, *e), *a) {
|
||||
stops.push(*a);
|
||||
}
|
||||
}
|
||||
let along = |q: &(i64, i64)| {
|
||||
(i128::from(q.0) - i128::from(s.0)) * (i128::from(e.0) - i128::from(s.0))
|
||||
+ (i128::from(q.1) - i128::from(s.1)) * (i128::from(e.1) - i128::from(s.1))
|
||||
};
|
||||
stops.sort_by_key(along);
|
||||
stops.dedup();
|
||||
for part in stops.windows(2) {
|
||||
let [m, n] = part else { continue };
|
||||
spend(work, ring.len() as u64)?;
|
||||
// The part's middle, doubled so it is whole.
|
||||
match locate((i128::from(m.0) + i128::from(n.0), i128::from(m.1) + i128::from(n.1)), ring) {
|
||||
Some(false) => return Some(false),
|
||||
Some(true) => any = true,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(any)
|
||||
}
|
||||
|
||||
/// Which side of the line through `a` and `b` `c` is on: 1 left, -1 right, 0 on it.
|
||||
fn side(a: (i64, i64), b: (i64, i64), c: (i64, i64)) -> i128 {
|
||||
let d = (i128::from(b.0) - i128::from(a.0)) * (i128::from(c.1) - i128::from(a.1))
|
||||
- (i128::from(b.1) - i128::from(a.1)) * (i128::from(c.0) - i128::from(a.0));
|
||||
d.signum()
|
||||
}
|
||||
|
||||
/// Do segments `u` and `v` cross at a point inside both, each passing from one side of the other
|
||||
/// to the other side?
|
||||
fn crosses(u: ((i64, i64), (i64, i64)), v: ((i64, i64), (i64, i64))) -> bool {
|
||||
side(u.0, u.1, v.0) * side(u.0, u.1, v.1) < 0 && side(v.0, v.1, u.0) * side(v.0, v.1, u.1) < 0
|
||||
}
|
||||
|
||||
/// Does `q` lie on segment `u`?
|
||||
fn on(u: ((i64, i64), (i64, i64)), q: (i64, i64)) -> bool {
|
||||
let ((x0, y0), (x1, y1)) = u;
|
||||
side(u.0, u.1, q) == 0 && q.0 >= x0.min(x1) && q.0 <= x0.max(x1) && q.1 >= y0.min(y1) && q.1 <= y0.max(y1)
|
||||
}
|
||||
|
||||
/// Where the doubled point `q` lies against the closed path `ring`: `Some(true)` inside by the
|
||||
/// even-odd rule, `Some(false)` outside, `None` on its line.
|
||||
fn locate(q: (i128, i128), ring: &[(i64, i64)]) -> Option<bool> {
|
||||
let mut inside = false;
|
||||
for w in ring.windows(2) {
|
||||
let [a, b] = w else { continue };
|
||||
let (a, b) = ((2 * i128::from(a.0), 2 * i128::from(a.1)), (2 * i128::from(b.0), 2 * i128::from(b.1)));
|
||||
// Which side of the segment's line `q` is on, 0 on it.
|
||||
let side = (b.0 - a.0) * (q.1 - a.1) - (b.1 - a.1) * (q.0 - a.0);
|
||||
if side == 0 && q.0 >= a.0.min(b.0) && q.0 <= a.0.max(b.0) && q.1 >= a.1.min(b.1) && q.1 <= a.1.max(b.1) {
|
||||
return None;
|
||||
}
|
||||
// A segment crossing the level of `q` to its right.
|
||||
if (a.1 > q.1) != (b.1 > q.1) && (side > 0) == (b.1 > a.1) {
|
||||
inside = !inside;
|
||||
}
|
||||
}
|
||||
Some(inside)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn square(x0: i64, y0: i64, x1: i64, y1: i64) -> Vec<(i64, i64)> {
|
||||
vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]
|
||||
}
|
||||
|
||||
fn nest(paths: &[Vec<(i64, i64)>]) -> Option<Vec<Vec<usize>>> {
|
||||
let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect();
|
||||
let mut work = u64::MAX;
|
||||
outer(paths, &boxes, &mut work)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn points_inside_outside_and_on_the_line() {
|
||||
let ring = square(0, 0, 10, 10);
|
||||
assert_eq!(locate((10, 10), &ring), Some(true));
|
||||
assert_eq!(locate((30, 10), &ring), Some(false));
|
||||
assert_eq!(locate((10, -2), &ring), Some(false));
|
||||
assert_eq!(locate((20, 10), &ring), None);
|
||||
assert_eq!(locate((0, 0), &ring), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_inside_another_lies_inside_it_and_not_the_other_way() {
|
||||
let paths = [square(0, 0, 100, 100), square(10, 10, 20, 20), vec![(30, 30), (40, 40)]];
|
||||
assert_eq!(nest(&paths), Some(vec![vec![], vec![0], vec![0]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn touching_counts_as_inside_and_crossing_does_not() {
|
||||
// A square with a corner on the outline's left edge, a triangle whose corners lie on the
|
||||
// outline's edges, and a square that crosses the outline.
|
||||
let paths = [square(0, 0, 100, 100), square(0, 40, 20, 60), vec![(0, 50), (50, 0), (100, 50), (0, 50)], square(90, 90, 120, 95)];
|
||||
assert_eq!(nest(&paths), Some(vec![vec![], vec![0], vec![0], vec![]]));
|
||||
}
|
||||
|
||||
/// Every point of a copy lies on the other's line, and none inside it.
|
||||
#[test]
|
||||
fn copies_of_one_outline_do_not_lie_inside_each_other() {
|
||||
let paths = [square(0, 0, 10, 10), square(0, 0, 10, 10), vec![(10, 10), (10, 0), (0, 0), (0, 10), (10, 10)]];
|
||||
assert_eq!(nest(&paths), Some(vec![vec![], vec![], vec![]]));
|
||||
}
|
||||
|
||||
/// A line whose ends and middle lie inside an outline but which crosses a slot cut into it.
|
||||
#[test]
|
||||
fn a_line_across_a_slot_is_not_inside() {
|
||||
let slotted = vec![(0, 0), (100, 0), (100, 100), (14, 100), (14, 40), (12, 40), (12, 100), (0, 100), (0, 0)];
|
||||
assert_eq!(nest(&[slotted, vec![(10, 50), (40, 50)]]), Some(vec![vec![], vec![]]));
|
||||
}
|
||||
|
||||
/// A line that leaves an outline and comes back through two of its corners, crossing none of
|
||||
/// its sides, and one that runs along the bottom of a slot.
|
||||
#[test]
|
||||
fn a_line_through_corners_is_inside_only_where_it_stays_inside() {
|
||||
let v_slot = vec![(0, 0), (100, 0), (100, 100), (20, 100), (20, 50), (15, 40), (10, 50), (10, 100), (0, 100), (0, 0)];
|
||||
assert_eq!(nest(&[v_slot, vec![(5, 50), (40, 50)]]), Some(vec![vec![], vec![]]));
|
||||
let slot = vec![(0, 0), (100, 0), (100, 100), (20, 100), (20, 50), (10, 50), (10, 100), (0, 100), (0, 0)];
|
||||
assert_eq!(nest(&[slot, vec![(5, 50), (40, 50)]]), Some(vec![vec![], vec![0]]));
|
||||
}
|
||||
|
||||
/// An outline that crosses itself encloses no area by its signed sum, yet a line in one of its
|
||||
/// lobes lies inside it.
|
||||
#[test]
|
||||
fn a_line_inside_a_lobe_of_a_crossed_outline_lies_inside_it() {
|
||||
let bow = vec![(0, 0), (100, 100), (0, 100), (100, 0), (0, 0)];
|
||||
assert_eq!(twice_area(&bow), 0);
|
||||
assert_eq!(nest(&[bow, vec![(40, 80), (60, 80)]]), Some(vec![vec![], vec![0]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ring_inside_a_ring_inside_a_ring_lies_inside_both() {
|
||||
let paths = [square(20, 20, 80, 80), square(0, 0, 100, 100), square(40, 40, 60, 60)];
|
||||
assert_eq!(nest(&paths), Some(vec![vec![1], vec![], vec![0, 1]]));
|
||||
}
|
||||
|
||||
/// 10,000 parts in rows, each with a hole: each hole is tested against the few closed paths
|
||||
/// near it, not against every part.
|
||||
#[test]
|
||||
fn parts_in_rows_are_tested_only_against_the_closed_paths_near_them() {
|
||||
let mut paths = vec![];
|
||||
for row in 0..100 {
|
||||
for col in 0..100 {
|
||||
let (x, y) = (col * 30, row * 30);
|
||||
paths.push(square(x, y, x + 20, y + 20));
|
||||
paths.push(square(x + 5, y + 5, x + 15, y + 15));
|
||||
}
|
||||
}
|
||||
let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect();
|
||||
let mut work = 5_000_000;
|
||||
let found = outer(&paths, &boxes, &mut work);
|
||||
let want: Vec<Vec<usize>> = (0..paths.len()).map(|i| if i % 2 == 1 { vec![i - 1] } else { vec![] }).collect();
|
||||
assert_eq!(found, Some(want));
|
||||
}
|
||||
|
||||
/// 400 closed paths that each cover most of the grid are listed once each, not in every cell
|
||||
/// they cover.
|
||||
#[test]
|
||||
fn closed_paths_covering_many_cells_are_listed_once() {
|
||||
let mut paths: Vec<Vec<(i64, i64)>> = (0..400).map(|i| square(i, i, 1000 + i, 1000 + i)).collect();
|
||||
paths.extend((0..400).map(|i| {
|
||||
let (x, y) = ((i % 20) * 50, (i / 20) * 50);
|
||||
square(x, y, x + 10, y + 10)
|
||||
}));
|
||||
let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect();
|
||||
let rings: Vec<usize> = (0..paths.len()).collect();
|
||||
let mut work = u64::MAX;
|
||||
let Some(grid) = Grid::new(&rings, &boxes, &mut work) else { panic!("the budget ran out") };
|
||||
assert_eq!(grid.wide, (0..400).collect::<Vec<_>>());
|
||||
assert!(grid.cells.iter().map(Vec::len).sum::<usize>() <= 400 * MAX_CELLS_PER_PATH);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finding_what_lies_inside_stops_at_its_budget() {
|
||||
let paths: Vec<Vec<(i64, i64)>> = (0..50).map(|i| square(-i, -i, 100 + i, 100 + i)).collect();
|
||||
let boxes: Vec<[i64; 4]> = paths.iter().map(|p| bounds(p)).collect();
|
||||
let mut work = 1_000;
|
||||
assert_eq!(outer(&paths, &boxes, &mut work), None);
|
||||
assert_eq!(work, 0);
|
||||
let mut work = u64::MAX;
|
||||
let found = outer(&paths, &boxes, &mut work);
|
||||
assert_eq!(found.map(|o| o.iter().map(Vec::len).sum::<usize>()), Some(50 * 49 / 2));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+20
-2
@@ -1,4 +1,5 @@
|
||||
//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and reader.
|
||||
//! CAD interchange: a hand-written ASCII DXF writer (versions R12 to 2018) and reader, and an
|
||||
//! HP-GL/2 plot file reader and writer.
|
||||
//!
|
||||
//! [`export`] writes the visible art of a document into one DXF drawing: each layer becomes a DXF
|
||||
//! layer (hidden ones switched off, locked ones locked, non-printing ones not plotted), paths
|
||||
@@ -11,13 +12,16 @@
|
||||
//! clipping) is approximated or left out, and each such loss comes back as a warning.
|
||||
//!
|
||||
//! [`import()`] reads an ASCII DXF drawing (any version) into a document: see [`import`].
|
||||
//! [`hpgl::import`] reads an HP-GL plotter file, and [`hpgl::export`] writes one: see [`hpgl`].
|
||||
//!
|
||||
//! - `aci`: the 256-colour index palette and the nearest index of a colour.
|
||||
//! - `writer`: group codes, handles and the file's sections, tables and objects.
|
||||
//! - `scene`: the document walk that turns objects into entities.
|
||||
//! - `import`: the reader, entities to art, blocks to symbols.
|
||||
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
|
||||
|
||||
mod aci;
|
||||
pub mod hpgl;
|
||||
pub mod import;
|
||||
mod scene;
|
||||
mod writer;
|
||||
@@ -277,6 +281,10 @@ pub struct DxfOptions {
|
||||
pub scale_lineweights: bool,
|
||||
pub colors: ColorDepth,
|
||||
pub raster: RasterFormat,
|
||||
/// Placed images are written as IMAGE entities with their files (else left out, undecoded).
|
||||
pub include_images: bool,
|
||||
/// Filled areas get a solid HATCH after their outlines (else the outlines alone).
|
||||
pub include_hatches: bool,
|
||||
pub preserve: Preserve,
|
||||
/// Alter Paths for Appearance: a stroke a CAD line can't draw (one [`Preserve::Appearance`]
|
||||
/// outlines, one wider than the widest lineweight, or any stroke in R13 and R14, which have
|
||||
@@ -299,6 +307,8 @@ impl Default for DxfOptions {
|
||||
scale_lineweights: false,
|
||||
colors: ColorDepth::default(),
|
||||
raster: RasterFormat::default(),
|
||||
include_images: true,
|
||||
include_hatches: true,
|
||||
preserve: Preserve::default(),
|
||||
alter_paths: false,
|
||||
outline_text: false,
|
||||
@@ -318,7 +328,8 @@ pub enum DxfPreset {
|
||||
/// For CNC and CAM cutting software: version 2000 (the oldest version that has both lightweight
|
||||
/// polylines and lineweights), 1 mm = 1 unit, 256 indexed colors (all version 2000 holds), Maximize
|
||||
/// Editability with Alter Paths off (every stroke a center line), Outline Text (type as paths),
|
||||
/// and placed images as PNG.
|
||||
/// and placed images and fill hatches left out (fills are their outlines), with PNG as the
|
||||
/// format images take when they are put back in.
|
||||
Cnc,
|
||||
}
|
||||
|
||||
@@ -356,6 +367,8 @@ impl DxfPreset {
|
||||
scale_lineweights: false,
|
||||
colors: ColorDepth::Aci256,
|
||||
raster: RasterFormat::Png,
|
||||
include_images: false,
|
||||
include_hatches: false,
|
||||
preserve: Preserve::Editability,
|
||||
alter_paths: false,
|
||||
outline_text: true,
|
||||
@@ -373,6 +386,8 @@ impl DxfPreset {
|
||||
&& o.scale_lineweights == c.scale_lineweights
|
||||
&& o.colors == c.colors
|
||||
&& o.raster == c.raster
|
||||
&& o.include_images == c.include_images
|
||||
&& o.include_hatches == c.include_hatches
|
||||
&& o.preserve == c.preserve
|
||||
&& o.alter_paths == c.alter_paths
|
||||
&& o.outline_text == c.outline_text;
|
||||
@@ -395,6 +410,9 @@ pub struct DxfOutput {
|
||||
pub images: Vec<DxfImage>,
|
||||
/// What was approximated or left out.
|
||||
pub warnings: Vec<String>,
|
||||
/// What was left out because an option turns it off (Include Placed Images or Include Fill
|
||||
/// Hatches off).
|
||||
pub setting_notes: Vec<String>,
|
||||
}
|
||||
|
||||
/// The smallest and largest `scale` (drawing units per unit).
|
||||
|
||||
+58
-7
@@ -1,5 +1,6 @@
|
||||
//! The document walk: each visible object becomes DXF entities on its layer's DXF layer, in paint
|
||||
//! order. Fills are their outlines then solid hatches (the outlines alone in R12), strokes
|
||||
//! order. Fills are their outlines then solid hatches (the outlines alone in R12 or with
|
||||
//! hatches left out), placed images are linked image files unless left out, strokes
|
||||
//! polylines (with bulges for circular arcs) and cubic splines with a lineweight and dashes, or
|
||||
//! filled outlines where the look needs them.
|
||||
|
||||
@@ -28,6 +29,8 @@ const NO_TRUE_COLOR: &str = "true colour needs DXF 2004 or later: colours are wr
|
||||
const NO_TRANSPARENCY: &str = "transparency needs DXF 2004 or later: transparent objects are written opaque";
|
||||
const NO_FILLS: &str = "DXF R12 has no fills: filled areas are written as their outlines";
|
||||
const NO_IMAGES: &str = "DXF R12 has no images: placed images are left out";
|
||||
const IMAGES_OFF: &str = "placed images are left out (Include Placed Images is off)";
|
||||
const HATCHES_OFF: &str = "fill hatches are left out: filled areas are written as their outlines (Include Fill Hatches is off)";
|
||||
const WIDE_LINES: &str =
|
||||
"lines wider than 2.11 mm (the widest lineweight) are written at 2.11 mm: Alter Paths for Appearance writes their true width";
|
||||
const STROKE_EXTRAS: &str = "stroke alignment, width profiles, arrowheads and brushes are left out (Maximize Editability writes strokes as lines)";
|
||||
@@ -339,6 +342,32 @@ fn subpaths(bp: &BezPath) -> Vec<Sub> {
|
||||
out
|
||||
}
|
||||
|
||||
/// `bp` with each open subpath that can enclose an area closed, as a fill closes it: two or more
|
||||
/// segments, or one curve. A single straight segment stays open.
|
||||
fn closed_fill(bp: &BezPath) -> BezPath {
|
||||
let mut out = BezPath::new();
|
||||
let (mut segs, mut curved) = (0usize, false);
|
||||
let close = |out: &mut BezPath, segs: usize, curved: bool| {
|
||||
if segs >= 2 || (segs == 1 && curved) {
|
||||
out.close_path();
|
||||
}
|
||||
};
|
||||
for el in bp.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(_) => {
|
||||
close(&mut out, segs, curved);
|
||||
(segs, curved) = (0, false);
|
||||
}
|
||||
PathEl::ClosePath => (segs, curved) = (0, false),
|
||||
PathEl::LineTo(_) => segs += 1,
|
||||
PathEl::QuadTo(..) | PathEl::CurveTo(..) => (segs, curved) = (segs + 1, true),
|
||||
}
|
||||
out.push(*el);
|
||||
}
|
||||
close(&mut out, segs, curved);
|
||||
out
|
||||
}
|
||||
|
||||
/// The most pixels of an image written (it is held decoded, as RGBA and encoded at once).
|
||||
const MAX_IMAGE_PIXELS: u64 = 64 << 20;
|
||||
|
||||
@@ -491,6 +520,8 @@ pub(crate) struct Scene<'a> {
|
||||
/// Image keys → index into `images` (`None`: left out).
|
||||
by_key: HashMap<String, Option<usize>>,
|
||||
warnings: Vec<String>,
|
||||
/// What was left out because an option asked for it ([`DxfOutput::setting_notes`]).
|
||||
setting_notes: Vec<String>,
|
||||
brushes: Option<Vec<vectorcraft_brush::Brush>>,
|
||||
extents: Option<[f64; 4]>,
|
||||
/// The opacity of the containers around the current object.
|
||||
@@ -525,6 +556,7 @@ impl<'a> Scene<'a> {
|
||||
files: vec![],
|
||||
by_key: HashMap::new(),
|
||||
warnings: vec![],
|
||||
setting_notes: vec![],
|
||||
brushes: None,
|
||||
extents: None,
|
||||
opacity: 1.0,
|
||||
@@ -559,15 +591,24 @@ impl<'a> Scene<'a> {
|
||||
metric: matches!(self.o.unit, Unit::Millimeters | Unit::Centimeters | Unit::Meters),
|
||||
next: self.next,
|
||||
};
|
||||
DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings }
|
||||
DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings, setting_notes: self.setting_notes }
|
||||
}
|
||||
|
||||
/// Note `w`, once, about something of the document that the drawing leaves out or that reaches
|
||||
/// it changed. A note about an option goes to [`Self::note_setting`].
|
||||
fn warn(&mut self, w: &str) {
|
||||
if !self.warnings.iter().any(|x| x == w) {
|
||||
self.warnings.push(w.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Note `w`, once, about something left out because an option turns it off.
|
||||
fn note_setting(&mut self, w: &str) {
|
||||
if !self.setting_notes.iter().any(|x| x == w) {
|
||||
self.setting_notes.push(w.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn handle(&mut self) -> Handle {
|
||||
let h = Handle(self.next);
|
||||
self.next = self.next.saturating_add(1);
|
||||
@@ -631,7 +672,7 @@ impl<'a> Scene<'a> {
|
||||
self.shape(n, &bp, *rule);
|
||||
}
|
||||
NodeKind::Text(t) => self.text(n, t),
|
||||
NodeKind::Image(im) => self.image(im),
|
||||
NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im)),
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let doc = self.doc;
|
||||
if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES {
|
||||
@@ -878,13 +919,13 @@ impl<'a> Scene<'a> {
|
||||
Some(vectorcraft_brush::stroke_pieces(doc, b, bp, st))
|
||||
}
|
||||
|
||||
/// A filled area as its outlines followed by a solid hatch (R12: the outlines alone). Laser
|
||||
/// and cutter software reads the outlines and skips hatches. `clean`: the path has no
|
||||
/// A filled area as its outlines followed by a solid hatch (R12, or with hatches left out: the
|
||||
/// outlines alone). Laser and cutter software reads the outlines and skips hatches. `clean`: the path has no
|
||||
/// overlaps, so the hatch's even-odd rule reads it as it is.
|
||||
fn area(&mut self, bp: &BezPath, rule: FillRule, style: &EntityStyle, clean: bool) {
|
||||
if !self.o.version.handles() {
|
||||
self.warn(NO_FILLS);
|
||||
self.lines(bp, style, 0.0);
|
||||
self.lines(&closed_fill(bp), style, 0.0);
|
||||
return;
|
||||
}
|
||||
let several = bp.elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count() > 1;
|
||||
@@ -893,11 +934,17 @@ impl<'a> Scene<'a> {
|
||||
.flatten()
|
||||
.map(|p| p.to_bezpath());
|
||||
let outline = normalized.as_ref().unwrap_or(bp);
|
||||
// A fill with no loop of three points or more encloses no area: no outline and no hatch.
|
||||
let loops: Vec<Vec<Point>> = polygons(outline).into_iter().filter(|p| p.len() >= 3).collect();
|
||||
if loops.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.lines(outline, style, 0.0);
|
||||
// The outlines close as the fill does, so an open path's fill keeps its closing edge.
|
||||
self.lines(&closed_fill(outline), style, 0.0);
|
||||
if !self.o.include_hatches {
|
||||
self.note_setting(HATCHES_OFF);
|
||||
return;
|
||||
}
|
||||
let h = self.handle();
|
||||
let layer = self.layer.clone();
|
||||
self.e.entity("HATCH", h, fixed::MODEL_RECORD, &layer, style, "AcDbHatch");
|
||||
@@ -1285,6 +1332,10 @@ impl<'a> Scene<'a> {
|
||||
self.warn(NO_IMAGES);
|
||||
return;
|
||||
}
|
||||
if !self.o.include_images {
|
||||
self.note_setting(IMAGES_OFF);
|
||||
return;
|
||||
}
|
||||
let Some(i) = self.image_def(im) else { return };
|
||||
let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return };
|
||||
let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
|
||||
|
||||
@@ -843,10 +843,156 @@ fn the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_stro
|
||||
assert!(out.images.is_empty());
|
||||
assert_eq!(DxfPreset::of(&o), DxfPreset::Cnc);
|
||||
assert_eq!(DxfPreset::of(&DxfOptions { colors: ColorDepth::True, ..o.clone() }), DxfPreset::Custom);
|
||||
assert_eq!(DxfPreset::of(&DxfOptions { include_images: true, ..o.clone() }), DxfPreset::Custom);
|
||||
assert_eq!(DxfPreset::of(&DxfOptions { include_hatches: true, ..o.clone() }), DxfPreset::Custom);
|
||||
assert_eq!(DxfPreset::of(&DxfOptions::default()), DxfPreset::Custom);
|
||||
assert_eq!(DxfPreset::from_id(" CNC "), Some(DxfPreset::Cnc));
|
||||
}
|
||||
|
||||
/// A 4 × 2 px PNG placed at (10, 20) under key `raster-1`, and before it in paint order
|
||||
/// `fill`'s rectangle.
|
||||
fn image_and_fill_doc(fill: Paint) -> Document {
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(4, 2, image::Rgba([0, 0, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut d = doc_with(|d| {
|
||||
let im = ImageObject {
|
||||
key: "raster-1".into(),
|
||||
width: 4,
|
||||
height: 2,
|
||||
xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
vec![
|
||||
path(d, shapes::rectangle(Rect::new(50.0, 10.0, 150.0, 60.0)), fill, Paint::None, 0.0),
|
||||
Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))),
|
||||
]
|
||||
});
|
||||
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
|
||||
d
|
||||
}
|
||||
|
||||
const IMAGES_OFF: &str = "placed images are left out (Include Placed Images is off)";
|
||||
const HATCHES_OFF: &str = "fill hatches are left out: filled areas are written as their outlines (Include Fill Hatches is off)";
|
||||
|
||||
#[test]
|
||||
fn fills_without_hatches_keep_their_outlines() {
|
||||
let d = shapes_doc();
|
||||
let out = export(&d, &DxfOptions { include_hatches: false, ..opts(&d) }).unwrap();
|
||||
assert_eq!(kinds(&out), ["LWPOLYLINE", "LWPOLYLINE", "CIRCLE"], "the fill's outline, the stroke, the circle");
|
||||
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
|
||||
assert_eq!(out.setting_notes, [HATCHES_OFF]);
|
||||
let e = entities(&out);
|
||||
assert_eq!((get(&e[0], 70), get(&e[0], 370)), (Some("1"), None), "the closed outline, without a lineweight");
|
||||
// Hatches stay by default, with no note.
|
||||
let on = export(&d, &opts(&d)).unwrap();
|
||||
assert!(kinds(&on).iter().any(|k| k == "HATCH") && on.setting_notes.is_empty());
|
||||
// The outlines are the ones written beside hatches, also for overlapping subpaths, which are
|
||||
// merged first; a fill with no area (a flat rectangle, a diagonal line) writes nothing either way.
|
||||
let compound = doc_with(|d| {
|
||||
let mut bp = shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 60.0)).to_bezpath();
|
||||
bp.extend(shapes::rectangle(Rect::new(40.0, 40.0, 90.0, 90.0)).to_bezpath().elements().iter().copied());
|
||||
let p = PathData::from_bezpath(&bp);
|
||||
vec![
|
||||
path(d, p, Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
path(d, shapes::rectangle(Rect::new(10.0, 70.0, 90.0, 70.0)), Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
path(d, shapes::line(Point::new(100.0, 10.0), Point::new(150.0, 60.0)), Paint::solid(Color::BLACK), Paint::None, 0.0),
|
||||
]
|
||||
});
|
||||
let without_hatches = |o: &DxfOutput| {
|
||||
let mut e = entities(o);
|
||||
e.retain(|x| kind(x) != "HATCH");
|
||||
e.into_iter().map(|x| x.into_iter().filter(|p| p.0 != 5).collect::<Pairs>()).collect::<Vec<_>>()
|
||||
};
|
||||
let (c_on, c_off) =
|
||||
(export(&compound, &opts(&compound)).unwrap(), export(&compound, &DxfOptions { include_hatches: false, ..opts(&compound) }).unwrap());
|
||||
assert_eq!(kinds(&c_on), ["LWPOLYLINE", "HATCH"], "one merged outline");
|
||||
assert_eq!(without_hatches(&c_off), without_hatches(&c_on));
|
||||
assert_eq!(without_hatches(&out), without_hatches(&on));
|
||||
// Strokes outlined for their look are areas too: their outlines stay.
|
||||
let altered =
|
||||
export(&d, &DxfOptions { include_hatches: false, alter_paths: true, preserve: Preserve::Editability, version: DxfVersion::R14, ..opts(&d) })
|
||||
.unwrap();
|
||||
assert!(!kinds(&altered).iter().any(|k| k == "HATCH") && !kinds(&altered).is_empty(), "{:?}", kinds(&altered));
|
||||
// Nothing filled: no note.
|
||||
let lines = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), Paint::None, Paint::solid(Color::BLACK), 1.0)]);
|
||||
let none = export(&lines, &DxfOptions { include_hatches: false, ..opts(&lines) }).unwrap();
|
||||
assert!(none.warnings.is_empty() && none.setting_notes.is_empty());
|
||||
// R12 has no hatches anyway: the same outlines, and its own note alone.
|
||||
let r12 = |include_hatches| export(&d, &DxfOptions { version: DxfVersion::R12, include_hatches, ..opts(&d) }).unwrap();
|
||||
let (off, on) = (r12(false), r12(true));
|
||||
assert_eq!(off.bytes, on.bytes);
|
||||
assert_eq!(off.warnings, on.warnings);
|
||||
assert!(off.setting_notes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_path_s_fill_outline_keeps_its_closing_edge() {
|
||||
let mut bp = vectorcraft_geom::BezPath::new();
|
||||
bp.move_to((10.0, 10.0));
|
||||
bp.line_to((90.0, 10.0));
|
||||
bp.line_to((50.0, 80.0));
|
||||
let open = PathData::from_bezpath(&bp);
|
||||
let d = doc_with(|d| vec![path(d, open.clone(), Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 1.0)]);
|
||||
let closed = |e: &Pairs| get(e, 70).and_then(|v| v.trim().parse::<i64>().ok()).is_some_and(|v| v & 1 == 1);
|
||||
for include_hatches in [false, true] {
|
||||
let out = export(&d, &DxfOptions { include_hatches, ..opts(&d) }).unwrap();
|
||||
let e: Vec<Pairs> = entities(&out).into_iter().filter(|x| kind(x) == "LWPOLYLINE").collect();
|
||||
assert_eq!(e.len(), 2, "the fill's outline and the stroke: {:?}", kinds(&out));
|
||||
assert!(closed(&e[0]), "the fill's outline closes as the fill does (hatches {include_hatches})");
|
||||
assert!(!closed(&e[1]), "the stroke stays open (hatches {include_hatches})");
|
||||
}
|
||||
// R12 writes the outline alone, closed too.
|
||||
let fill_only = doc_with(|d| vec![path(d, open.clone(), Paint::solid(Color::BLACK), Paint::None, 0.0)]);
|
||||
let r12 = export(&fill_only, &DxfOptions { version: DxfVersion::R12, ..opts(&fill_only) }).unwrap();
|
||||
let e = entities(&r12);
|
||||
assert_eq!(kind(&e[0]), "POLYLINE", "{:?}", kinds(&r12));
|
||||
assert!(closed(&e[0]), "R12's outline closes as the fill does");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_can_be_left_out_with_their_files() {
|
||||
let d = image_and_fill_doc(Paint::None);
|
||||
let out = export(&d, &DxfOptions { include_images: false, ..opts(&d) }).unwrap();
|
||||
assert!(entities(&out).is_empty() && out.images.is_empty(), "{:?}", kinds(&out));
|
||||
let p = pairs(&out.bytes);
|
||||
assert!(!section(&p, "OBJECTS").iter().any(|o| matches!(kind(o), "IMAGEDEF" | "IMAGEDEF_REACTOR" | "RASTERVARIABLES")));
|
||||
assert!(!section(&p, "CLASSES").iter().any(|o| get(o, 1) == Some("IMAGE")));
|
||||
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
|
||||
assert_eq!(out.setting_notes, [IMAGES_OFF]);
|
||||
// An image that can't be decoded is not read when images are left out.
|
||||
let mut broken = d.clone();
|
||||
broken.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None });
|
||||
let left_out = export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap();
|
||||
assert!(left_out.warnings.is_empty(), "{:?}", left_out.warnings);
|
||||
assert_eq!(left_out.setting_notes, [IMAGES_OFF]);
|
||||
assert!(export(&broken, &opts(&broken)).unwrap().warnings.iter().any(|w| w.contains("couldn't be decoded")));
|
||||
// R12 has no images anyway: its own note alone.
|
||||
let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, include_images: false, ..opts(&d) }).unwrap();
|
||||
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && r12.setting_notes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both() {
|
||||
let d = image_and_fill_doc(Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
|
||||
let run = |o: DxfOptions| export(&d, &DxfOptions { region: d.artboards[0].rect, ..o }).unwrap();
|
||||
let both = run(DxfOptions::default());
|
||||
assert_eq!(kinds(&both), ["LWPOLYLINE", "HATCH", "IMAGE"]);
|
||||
assert_eq!(both.images.len(), 1);
|
||||
let no_images = run(DxfOptions { include_images: false, ..DxfOptions::default() });
|
||||
assert_eq!((kinds(&no_images), no_images.images.len()), (vec!["LWPOLYLINE".to_string(), "HATCH".into()], 0));
|
||||
let no_hatches = run(DxfOptions { include_hatches: false, ..DxfOptions::default() });
|
||||
assert_eq!((kinds(&no_hatches), no_hatches.images.len()), (vec!["LWPOLYLINE".to_string(), "IMAGE".into()], 1));
|
||||
// CNC / CAM: the cutting path alone, with no image file and both notes.
|
||||
let cnc = run(DxfPreset::Cnc.options());
|
||||
assert_eq!(kinds(&cnc), ["LWPOLYLINE"]);
|
||||
assert!(cnc.images.is_empty());
|
||||
assert!(cnc.setting_notes.iter().any(|w| w == IMAGES_OFF) && cnc.setting_notes.iter().any(|w| w == HATCHES_OFF), "{:?}", cnc.setting_notes);
|
||||
let custom = DxfPreset::Custom.options();
|
||||
assert!(custom.include_images && custom.include_hatches, "Custom keeps both");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_become_dxf_layers() {
|
||||
let mut d = shapes_doc();
|
||||
|
||||
+82
-15
@@ -2,13 +2,16 @@
|
||||
//! gamut checks and soft-proof transforms.
|
||||
//!
|
||||
//! * **RGB working spaces** are ICC matrix/shaper profiles via [`moxcms`] (sRGB, Wide Gamut RGB
|
||||
//! (1998 primaries), Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB.
|
||||
//! (1998 primaries), Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB;
|
||||
//! the desktop canvas converts it into the display's own profile last ([`display`]).
|
||||
//! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model
|
||||
//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers);
|
||||
//! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles).
|
||||
//! * The **active settings** (Edit → Color Settings) are process-wide; [`crate::Color::to_rgb`]
|
||||
//! uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`].
|
||||
//! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with
|
||||
//! the profiles [`use_document_profiles`] last put in place of the working spaces;
|
||||
//! [`crate::Color::to_rgb`] uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`].
|
||||
|
||||
pub mod display;
|
||||
pub mod generic;
|
||||
pub mod icc;
|
||||
pub mod lab;
|
||||
@@ -320,6 +323,9 @@ pub struct Cms {
|
||||
settings: ColorSettings,
|
||||
rgb: RgbSpace,
|
||||
cmyk: CmykSpace,
|
||||
/// The working settings, when a document's assigned profiles take the place of their spaces
|
||||
/// ([`use_document_profiles`]): a [`ProofTarget::WorkingCmyk`] proof simulates their CMYK space.
|
||||
working: Option<Arc<Cms>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Cms {
|
||||
@@ -330,7 +336,7 @@ impl std::fmt::Debug for Cms {
|
||||
|
||||
impl Default for Cms {
|
||||
fn default() -> Self {
|
||||
Self { settings: ColorSettings::default(), rgb: RgbSpace::Srgb, cmyk: CmykSpace::Generic(generic()) }
|
||||
Self { settings: ColorSettings::default(), rgb: RgbSpace::Srgb, cmyk: CmykSpace::Generic(generic()), working: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,7 +344,7 @@ impl Cms {
|
||||
/// Profiles named by a legacy name are stored under their current name.
|
||||
pub fn new(settings: &ColorSettings) -> Result<Self, CmsError> {
|
||||
let settings = ColorSettings { rgb: canonical_name(&settings.rgb).into(), cmyk: canonical_name(&settings.cmyk).into(), ..settings.clone() };
|
||||
Ok(Self { rgb: rgb_space(&settings.rgb)?, cmyk: cmyk_space(&settings.cmyk)?, settings })
|
||||
Ok(Self { rgb: rgb_space(&settings.rgb)?, cmyk: cmyk_space(&settings.cmyk)?, settings, working: None })
|
||||
}
|
||||
pub fn settings(&self) -> &ColorSettings {
|
||||
&self.settings
|
||||
@@ -527,7 +533,7 @@ impl Cms {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gamut warning: can this colour be printed in the working CMYK space?
|
||||
/// Gamut warning: can this color be printed in this context's CMYK space?
|
||||
pub fn out_of_gamut(&self, c: &Color) -> bool {
|
||||
self.gamut_error(c) > GAMUT_THRESHOLD
|
||||
}
|
||||
@@ -542,8 +548,9 @@ impl Cms {
|
||||
ProofTarget::Deuteranopia => simulate_cvd(srgb, &DEUTERANOPIA),
|
||||
ProofTarget::Tritanopia => TRITANOPIA.simulate(srgb),
|
||||
ProofTarget::WorkingCmyk => {
|
||||
let cmyk = self.srgb_to_cmyk(srgb, proof.intent);
|
||||
self.cmyk_to_srgb(cmyk, proof.simulate_paper)
|
||||
let working = self.working_cms();
|
||||
let cmyk = working.srgb_to_cmyk(srgb, proof.intent);
|
||||
working.cmyk_to_srgb(cmyk, proof.simulate_paper)
|
||||
}
|
||||
ProofTarget::Cmyk(name) => match cmyk_space(name) {
|
||||
Ok(sp) => {
|
||||
@@ -555,20 +562,29 @@ impl Cms {
|
||||
}
|
||||
}
|
||||
|
||||
/// Display sRGB of CMYK inks in the proof's CMYK space (the working space for RGB targets).
|
||||
/// Display sRGB of CMYK inks in the proof's CMYK space (this context's CMYK space for RGB
|
||||
/// targets).
|
||||
pub fn proof_cmyk_to_srgb(&self, cmyk: [f32; 4], proof: &ProofSetup) -> [f32; 3] {
|
||||
match &proof.target {
|
||||
ProofTarget::Cmyk(name) => match cmyk_space(name) {
|
||||
Ok(sp) => Self::cmyk_to_srgb_in(&sp, cmyk, proof.simulate_paper, self.settings.bpc),
|
||||
Err(_) => self.cmyk_to_srgb(cmyk, proof.simulate_paper),
|
||||
},
|
||||
ProofTarget::WorkingCmyk => self.working_cms().cmyk_to_srgb(cmyk, proof.simulate_paper),
|
||||
_ => self.cmyk_to_srgb(cmyk, proof.simulate_paper),
|
||||
}
|
||||
}
|
||||
|
||||
/// The context of the working settings: the one [`use_document_profiles`] put a document's
|
||||
/// profiles in place of, else this one.
|
||||
fn working_cms(&self) -> &Cms {
|
||||
self.working.as_deref().unwrap_or(self)
|
||||
}
|
||||
|
||||
/// A cached 3-D lookup table implementing [`Cms::proof_srgb`] for 8-bit pixels.
|
||||
pub fn proof_lut(&self, proof: &ProofSetup) -> Arc<ProofLut> {
|
||||
let key = format!("{:?}|{:?}|{:?}|{}", self.settings, proof.target, proof.intent, proof.simulate_paper);
|
||||
let working = self.working.as_ref().map(|w| &w.settings);
|
||||
let key = format!("{:?}|{working:?}|{:?}|{:?}|{}", self.settings, proof.target, proof.intent, proof.simulate_paper);
|
||||
let mut cache = PROOF_CACHE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((_, l)) = cache.iter().find(|(k, _)| *k == key) {
|
||||
return l.clone();
|
||||
@@ -890,10 +906,12 @@ impl CmykLut {
|
||||
// ---------- the active (process-wide) settings ----------
|
||||
|
||||
static ACTIVE: RwLock<Option<Arc<Cms>>> = RwLock::new(None);
|
||||
static WORKING: RwLock<Option<Arc<Cms>>> = RwLock::new(None);
|
||||
static RGB_IS_SRGB: AtomicBool = AtomicBool::new(true);
|
||||
static CMYK_IS_DEVICE: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// The active colour-management context (Edit → Color Settings).
|
||||
/// The active color-management context: the working settings, with the profiles
|
||||
/// [`use_document_profiles`] last put in place of the working spaces.
|
||||
pub fn active() -> Arc<Cms> {
|
||||
if let Some(c) = ACTIVE.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
|
||||
return c.clone();
|
||||
@@ -906,13 +924,62 @@ pub fn active_settings() -> ColorSettings {
|
||||
active().settings.clone()
|
||||
}
|
||||
|
||||
/// Replace the active settings (fails, leaving them unchanged, if a profile is unknown).
|
||||
/// The color-management context of Edit → Color Settings (the working spaces, intent and black
|
||||
/// point compensation), as [`set_active`] last set them, whatever profiles a document is assigned.
|
||||
pub fn working() -> Arc<Cms> {
|
||||
if let Some(c) = WORKING.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
|
||||
return c.clone();
|
||||
}
|
||||
let mut w = WORKING.write().unwrap_or_else(|e| e.into_inner());
|
||||
w.get_or_insert_with(|| Arc::new(Cms::default())).clone()
|
||||
}
|
||||
|
||||
/// The settings of [`working`].
|
||||
pub fn working_settings() -> ColorSettings {
|
||||
working().settings.clone()
|
||||
}
|
||||
|
||||
/// Replace the working settings (Edit → Color Settings) and make them the active settings (fails,
|
||||
/// leaving both unchanged, if a profile is unknown).
|
||||
pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> {
|
||||
let cms = Cms::new(settings)?;
|
||||
let cms = Arc::new(Cms::new(settings)?);
|
||||
*WORKING.write().unwrap_or_else(|e| e.into_inner()) = Some(cms.clone());
|
||||
install(cms);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Make the working settings the active settings, with the profiles a document is assigned
|
||||
/// (`None`: none) in place of the working spaces. An assigned profile that is not available, or
|
||||
/// is not of its model, leaves the working space. The working settings stay as they are. True when
|
||||
/// the active settings changed.
|
||||
pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool {
|
||||
let working = working();
|
||||
let mut st = working.settings.clone();
|
||||
if let Some(p) = rgb.and_then(profile).filter(|p| p.kind == ProfileKind::Rgb) {
|
||||
st.rgb = p.name;
|
||||
}
|
||||
if let Some(p) = cmyk.and_then(profile).filter(|p| p.kind == ProfileKind::Cmyk) {
|
||||
st.cmyk = p.name;
|
||||
}
|
||||
if st == active().settings {
|
||||
return false;
|
||||
}
|
||||
if st == working.settings {
|
||||
install(working);
|
||||
return true;
|
||||
}
|
||||
// The working settings were checked when they were set; a working profile removed since then
|
||||
// leaves the active settings as they are.
|
||||
let Ok(mut cms) = Cms::new(&st) else { return false };
|
||||
cms.working = Some(working);
|
||||
install(Arc::new(cms));
|
||||
true
|
||||
}
|
||||
|
||||
fn install(cms: Arc<Cms>) {
|
||||
RGB_IS_SRGB.store(cms.rgb_is_srgb(), Ordering::Relaxed);
|
||||
CMYK_IS_DEVICE.store(matches!(cms.cmyk, CmykSpace::Device), Ordering::Relaxed);
|
||||
*ACTIVE.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(cms));
|
||||
Ok(())
|
||||
*ACTIVE.write().unwrap_or_else(|e| e.into_inner()) = Some(cms);
|
||||
}
|
||||
|
||||
/// Fast path for [`Color::to_rgb`]: RGB colours need no conversion while the working space is sRGB.
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
//! The canvas's last step before the screen: the sRGB the canvas draws, converted into a display's
|
||||
//! ICC profile (Preferences › Performance › Use Monitor Profile for Canvas).
|
||||
//!
|
||||
//! The display profile is a destination only. Document colors, proofs, exports and the web build
|
||||
//! keep their sRGB output; a soft proof is applied first, then this conversion.
|
||||
//!
|
||||
//! [`DisplayTransform::from_icc`] accepts an RGB display-class (`mntr`) profile of at most
|
||||
//! [`MAX_PROFILE_BYTES`] whose declared length fits the data and from which a transform can be built.
|
||||
//! The conversion is relative colorimetric, sampled once into a [`LUT_N`]³ table, so drawing a frame
|
||||
//! costs a table lookup per pixel and never builds a transform.
|
||||
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use super::{Intent, ProfileKind, icc::IccProfile};
|
||||
|
||||
/// The largest display profile read: VectorCraft's own limit. Display profiles are a few kilobytes
|
||||
/// (matrix/shaper) to a few hundred (table-based).
|
||||
pub const MAX_PROFILE_BYTES: usize = 1 << 20;
|
||||
|
||||
/// Grid points per channel of the conversion table.
|
||||
const LUT_N: usize = 33;
|
||||
|
||||
/// Why a display profile can't be used. The canvas then stays sRGB.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ProfileError {
|
||||
/// More bytes than [`MAX_PROFILE_BYTES`].
|
||||
TooLarge(usize),
|
||||
/// No ICC header (`acsp` signature) or a header cut short.
|
||||
NotIcc,
|
||||
/// The header's length is shorter than a header or longer than the data.
|
||||
BadLength { declared: usize, len: usize },
|
||||
/// The profile class isn't a display's (`mntr`): an input, output or other profile.
|
||||
NotDisplay(String),
|
||||
/// The profile's data color space isn't RGB.
|
||||
NotRgb(String),
|
||||
/// The profile doesn't parse.
|
||||
Unreadable(String),
|
||||
/// No conversion from sRGB into the profile can be built.
|
||||
NoTransform,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ProfileError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::TooLarge(n) => write!(f, "the profile is {n} bytes, more than the {MAX_PROFILE_BYTES} a display profile may have"),
|
||||
Self::NotIcc => f.write_str("the file is not an ICC profile"),
|
||||
Self::BadLength { declared, len } => write!(f, "the profile's header gives a length of {declared} bytes for {len} bytes of data"),
|
||||
Self::NotDisplay(class) => write!(f, "the profile's class is `{class}`, not a display profile (`mntr`)"),
|
||||
Self::NotRgb(space) => write!(f, "the profile's color space is `{space}`, not RGB"),
|
||||
Self::Unreadable(e) => write!(f, "the profile can't be read: {e}"),
|
||||
Self::NoTransform => f.write_str("no conversion into the profile can be built"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Four header bytes as text, for an error message.
|
||||
fn signature(b: &[u8]) -> String {
|
||||
String::from_utf8_lossy(b).trim_end().to_string()
|
||||
}
|
||||
|
||||
/// sRGB → a display profile, as a table.
|
||||
pub struct DisplayTransform {
|
||||
name: String,
|
||||
fingerprint: u64,
|
||||
/// `LUT_N`³ display values, red slowest; `None` when the profile shows sRGB unchanged (every
|
||||
/// grid point within half an 8-bit step of itself).
|
||||
table: Option<Vec<[f32; 3]>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DisplayTransform {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DisplayTransform").field("name", &self.name).field("identity", &self.is_identity()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl DisplayTransform {
|
||||
/// Checks `bytes` as a display profile, as [`Self::from_icc`] does, without building the
|
||||
/// conversion table.
|
||||
pub fn check(bytes: &[u8]) -> Result<(), ProfileError> {
|
||||
Self::parse(bytes).map(|_| ())
|
||||
}
|
||||
|
||||
/// Checks `bytes` as a display profile and builds the conversion into it.
|
||||
pub fn from_icc(bytes: &[u8]) -> Result<Self, ProfileError> {
|
||||
let (profile, bytes) = Self::parse(bytes)?;
|
||||
let to_display =
|
||||
|rgb: [f32; 3]| profile.from_srgb(rgb, Intent::RelativeColorimetric).and_then(|v| Some([*v.first()?, *v.get(1)?, *v.get(2)?]));
|
||||
let s = (LUT_N - 1) as f32;
|
||||
let mut table = Vec::with_capacity(LUT_N.pow(3));
|
||||
for r in 0..LUT_N {
|
||||
for g in 0..LUT_N {
|
||||
for b in 0..LUT_N {
|
||||
let rgb = [r as f32 / s, g as f32 / s, b as f32 / s];
|
||||
table.push(to_display(rgb).ok_or(ProfileError::NoTransform)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
let grid = |i: usize| [i / (LUT_N * LUT_N), i / LUT_N % LUT_N, i % LUT_N].map(|v| v as f32 / s);
|
||||
let identity = table.iter().enumerate().all(|(i, v)| v.iter().zip(grid(i)).all(|(a, b)| (a - b).abs() <= 0.5 / 255.0));
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
bytes.hash(&mut h);
|
||||
Ok(Self { name: profile.name.clone(), fingerprint: h.finish(), table: (!identity).then_some(table) })
|
||||
}
|
||||
|
||||
/// The parsed profile and its bytes up to its declared length, when `bytes` is an RGB display
|
||||
/// profile from which a conversion can be built.
|
||||
fn parse(bytes: &[u8]) -> Result<(IccProfile, &[u8]), ProfileError> {
|
||||
if bytes.len() > MAX_PROFILE_BYTES {
|
||||
return Err(ProfileError::TooLarge(bytes.len()));
|
||||
}
|
||||
if bytes.len() < 132 || bytes.get(36..40) != Some(b"acsp") {
|
||||
return Err(ProfileError::NotIcc);
|
||||
}
|
||||
let declared = bytes.get(0..4).map_or(0, |b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize);
|
||||
if declared < 132 || declared > bytes.len() {
|
||||
return Err(ProfileError::BadLength { declared, len: bytes.len() });
|
||||
}
|
||||
let bytes = &bytes[..declared];
|
||||
if &bytes[12..16] != b"mntr" {
|
||||
return Err(ProfileError::NotDisplay(signature(&bytes[12..16])));
|
||||
}
|
||||
if &bytes[16..20] != b"RGB " {
|
||||
return Err(ProfileError::NotRgb(signature(&bytes[16..20])));
|
||||
}
|
||||
let profile = IccProfile::from_bytes(None, bytes).map_err(|e| ProfileError::Unreadable(e.to_string()))?;
|
||||
if profile.kind != ProfileKind::Rgb {
|
||||
return Err(ProfileError::NotRgb(format!("{:?}", profile.kind)));
|
||||
}
|
||||
let to_display =
|
||||
|rgb: [f32; 3]| profile.from_srgb(rgb, Intent::RelativeColorimetric).and_then(|v| Some([*v.first()?, *v.get(1)?, *v.get(2)?]));
|
||||
if to_display([0.5; 3]).is_none() {
|
||||
return Err(ProfileError::NoTransform);
|
||||
}
|
||||
Ok((profile, bytes))
|
||||
}
|
||||
|
||||
/// The profile's description.
|
||||
pub fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
/// A hash of the profile's bytes, which tells two profiles with the same name apart.
|
||||
pub fn fingerprint(&self) -> u64 {
|
||||
self.fingerprint
|
||||
}
|
||||
|
||||
/// The profile shows sRGB unchanged, so nothing is converted.
|
||||
pub fn is_identity(&self) -> bool {
|
||||
self.table.is_none()
|
||||
}
|
||||
|
||||
/// One sRGB color (0..1) in the display profile.
|
||||
pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {
|
||||
let Some(table) = &self.table else { return rgb.map(|v| v.clamp(0.0, 1.0)) };
|
||||
let n = LUT_N;
|
||||
let s = (n - 1) as f32;
|
||||
let p = rgb.map(|v| if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) * s });
|
||||
let i = p.map(|v| (v.floor() as usize).min(n - 2));
|
||||
let t = [p[0] - i[0] as f32, p[1] - i[1] as f32, p[2] - i[2] as f32];
|
||||
let mut out = [0.0f32; 3];
|
||||
for (dr, wr) in [(0, 1.0 - t[0]), (1, t[0])] {
|
||||
for (dg, wg) in [(0, 1.0 - t[1]), (1, t[1])] {
|
||||
for (db, wb) in [(0, 1.0 - t[2]), (1, t[2])] {
|
||||
let w = wr * wg * wb;
|
||||
if w == 0.0 {
|
||||
continue;
|
||||
}
|
||||
let v = table[((i[0] + dr) * n + i[1] + dg) * n + i[2] + db];
|
||||
for c in 0..3 {
|
||||
out[c] += w * v[c];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.map(|v| v.clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
/// One 8-bit sRGB color in the display profile.
|
||||
pub fn apply8(&self, rgb: [u8; 3]) -> [u8; 3] {
|
||||
if self.table.is_none() {
|
||||
return rgb;
|
||||
}
|
||||
self.apply(rgb.map(|v| f32::from(v) / 255.0)).map(|v| (v * 255.0).round() as u8)
|
||||
}
|
||||
|
||||
/// Premultiplied RGBA8 pixels, converted in place. Alpha is kept, and fully transparent
|
||||
/// pixels are left as they are.
|
||||
pub fn apply_premultiplied(&self, pixels: &mut [u8]) {
|
||||
if self.table.is_none() {
|
||||
return;
|
||||
}
|
||||
let mut last_in = [0u8; 4];
|
||||
let mut last_out = [0u8; 4];
|
||||
for px in pixels.as_chunks_mut::<4>().0 {
|
||||
let a = px[3];
|
||||
if a == 0 {
|
||||
continue;
|
||||
}
|
||||
if *px == last_in {
|
||||
*px = last_out;
|
||||
continue;
|
||||
}
|
||||
last_in = *px;
|
||||
let un = |c: u8| if a == 255 { c } else { ((u32::from(c) * 255 + u32::from(a) / 2) / u32::from(a)).min(255) as u8 };
|
||||
let out = self.apply8([un(px[0]), un(px[1]), un(px[2])]);
|
||||
for (c, o) in px.iter_mut().zip(out) {
|
||||
*c = if a == 255 { o } else { ((u32::from(o) * u32::from(a) + 127) / 255) as u8 };
|
||||
}
|
||||
last_out = *px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::cms::{DISPLAY_P3, GENERIC_CMYK, SRGB, icc_bytes};
|
||||
|
||||
/// `name`'s ICC file, marked as a display profile.
|
||||
fn display(name: &str) -> Vec<u8> {
|
||||
let mut b = icc_bytes(name).unwrap().to_vec();
|
||||
b[12..16].copy_from_slice(b"mntr");
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wide_gamut_display_shows_srgb_red_less_saturated_and_srgb_is_left_alone() {
|
||||
let p3 = DisplayTransform::from_icc(&display(DISPLAY_P3)).unwrap();
|
||||
assert!(!p3.is_identity());
|
||||
assert_eq!(p3.name(), DISPLAY_P3);
|
||||
// sRGB red is inside Display P3: its display values have green and blue above 0 and less red.
|
||||
let [r, g, b] = p3.apply8([255, 0, 0]);
|
||||
assert!(r < 245 && g > 40 && b > 10, "{:?}", [r, g, b]);
|
||||
// White and black stay where they are (relative colorimetric).
|
||||
assert_eq!(p3.apply8([255; 3]), [255; 3]);
|
||||
assert_eq!(p3.apply8([0; 3]), [0; 3]);
|
||||
let srgb = DisplayTransform::from_icc(&display(SRGB)).unwrap();
|
||||
assert!(srgb.is_identity());
|
||||
assert_eq!(srgb.apply8([255, 0, 0]), [255, 0, 0]);
|
||||
assert_ne!(srgb.fingerprint(), p3.fingerprint());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_table_matches_the_profile_between_its_grid_points() {
|
||||
let bytes = display(DISPLAY_P3);
|
||||
let p3 = DisplayTransform::from_icc(&bytes).unwrap();
|
||||
let profile = IccProfile::from_bytes(None, &bytes).unwrap();
|
||||
for rgb in [[0.1, 0.7, 0.33], [0.9, 0.05, 0.6], [0.47, 0.47, 0.47], [0.0, 0.2, 1.0]] {
|
||||
let want = profile.from_srgb(rgb, Intent::RelativeColorimetric).unwrap();
|
||||
let got = p3.apply(rgb);
|
||||
for c in 0..3 {
|
||||
assert!((got[c] - want[c]).abs() < 1.0 / 255.0, "{rgb:?}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn premultiplied_pixels_keep_their_alpha_and_transparent_ones_stay_empty() {
|
||||
let p3 = DisplayTransform::from_icc(&display(DISPLAY_P3)).unwrap();
|
||||
let mut px = vec![255, 0, 0, 255, 128, 0, 0, 128, 0, 0, 0, 0, 255, 0, 0, 255];
|
||||
p3.apply_premultiplied(&mut px);
|
||||
let opaque = p3.apply8([255, 0, 0]);
|
||||
assert_eq!(&px[0..4], &[opaque[0], opaque[1], opaque[2], 255]);
|
||||
assert_eq!(&px[12..16], &px[0..4], "a repeated pixel converts the same");
|
||||
assert_eq!(px[7], 128);
|
||||
// Half-covered red: the same color at half coverage, within rounding.
|
||||
for c in 0..3 {
|
||||
assert!((i32::from(px[4 + c]) - i32::from(opaque[c]) / 2).abs() <= 1, "{:?}", &px[4..8]);
|
||||
}
|
||||
assert_eq!(&px[8..12], &[0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profiles_that_are_not_rgb_display_profiles_are_refused() {
|
||||
let cmyk = icc_bytes(GENERIC_CMYK).unwrap().to_vec();
|
||||
assert!(matches!(DisplayTransform::from_icc(&cmyk), Err(ProfileError::NotDisplay(_))));
|
||||
let mut cmyk_display = cmyk.clone();
|
||||
cmyk_display[12..16].copy_from_slice(b"mntr");
|
||||
assert!(matches!(DisplayTransform::from_icc(&cmyk_display), Err(ProfileError::NotRgb(s)) if s == "CMYK"));
|
||||
let mut input = display(DISPLAY_P3);
|
||||
input[12..16].copy_from_slice(b"scnr");
|
||||
assert_eq!(DisplayTransform::from_icc(&input).unwrap_err(), ProfileError::NotDisplay("scnr".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_short_and_oversized_data_is_refused() {
|
||||
assert_eq!(DisplayTransform::from_icc(&[]).unwrap_err(), ProfileError::NotIcc);
|
||||
assert_eq!(DisplayTransform::from_icc(&[0; 132]).unwrap_err(), ProfileError::NotIcc);
|
||||
let good = display(DISPLAY_P3);
|
||||
assert_eq!(DisplayTransform::from_icc(&good[..100]).unwrap_err(), ProfileError::NotIcc);
|
||||
let mut long = good.clone();
|
||||
long[0..4].copy_from_slice(&(good.len() as u32 + 1).to_be_bytes());
|
||||
assert_eq!(DisplayTransform::from_icc(&long).unwrap_err(), ProfileError::BadLength { declared: good.len() + 1, len: good.len() });
|
||||
let mut short = good.clone();
|
||||
short[0..4].copy_from_slice(&64u32.to_be_bytes());
|
||||
assert!(matches!(DisplayTransform::from_icc(&short), Err(ProfileError::BadLength { declared: 64, .. })));
|
||||
// Trailing bytes past the declared length are not part of the profile.
|
||||
let mut padded = good.clone();
|
||||
padded.extend([0xAB; 16]);
|
||||
let a = DisplayTransform::from_icc(&padded).unwrap();
|
||||
assert_eq!(a.fingerprint(), DisplayTransform::from_icc(&good).unwrap().fingerprint());
|
||||
let mut garbage_tags = good.clone();
|
||||
for b in &mut garbage_tags[128..] {
|
||||
*b = 0xFF;
|
||||
}
|
||||
assert!(matches!(DisplayTransform::from_icc(&garbage_tags), Err(ProfileError::Unreadable(_) | ProfileError::NoTransform)));
|
||||
let huge = vec![0u8; MAX_PROFILE_BYTES + 1];
|
||||
assert_eq!(DisplayTransform::from_icc(&huge).unwrap_err(), ProfileError::TooLarge(MAX_PROFILE_BYTES + 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_accepts_and_refuses_what_from_icc_does() {
|
||||
assert_eq!(DisplayTransform::check(&display(DISPLAY_P3)), Ok(()));
|
||||
assert_eq!(DisplayTransform::check(&display(SRGB)), Ok(()));
|
||||
let cmyk = icc_bytes(GENERIC_CMYK).unwrap().to_vec();
|
||||
assert_eq!(DisplayTransform::check(&cmyk), Err(DisplayTransform::from_icc(&cmyk).unwrap_err()));
|
||||
assert_eq!(DisplayTransform::check(&[1, 2, 3]), Err(ProfileError::NotIcc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nan_and_out_of_range_values_stay_in_range() {
|
||||
let p3 = DisplayTransform::from_icc(&display(DISPLAY_P3)).unwrap();
|
||||
for v in p3.apply([f32::NAN, -1.0, 9.0]) {
|
||||
assert!((0.0..=1.0).contains(&v));
|
||||
}
|
||||
}
|
||||
}
|
||||
+515
-39
@@ -8,6 +8,9 @@ use serde::{Deserialize, Serialize};
|
||||
use crate::Color;
|
||||
use crate::freeform::Freeform;
|
||||
|
||||
mod spread;
|
||||
pub use spread::{MAX_SPREAD_LEVEL, MAX_SPREAD_RUNS, MAX_SPREAD_STOPS, Padded};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum GradientKind {
|
||||
#[default]
|
||||
@@ -15,20 +18,42 @@ pub enum GradientKind {
|
||||
Radial,
|
||||
/// Freeform gradients: colour points and lines (see [`crate::freeform`]).
|
||||
Freeform,
|
||||
/// Conic (angle) gradients: the stops sweep once around the center (`start`), clockwise on
|
||||
/// the page from the vector, with a seam where the last stop meets the first. A negative
|
||||
/// `aspect` mirrors the sweep (see [`GradientGeom::transform`]).
|
||||
Conic,
|
||||
/// Diamond gradients: the stops run from the center (`start`) out to a square whose
|
||||
/// half-diagonal is the vector (a diamond when the vector is level), stretched across the
|
||||
/// vector by `aspect` (see [`GradientGeom::diamond_frame`]).
|
||||
Diamond,
|
||||
}
|
||||
|
||||
impl GradientKind {
|
||||
/// Parse a kind name (`linear`, `radial`, `freeform`; any case).
|
||||
/// Every kind, in the order the Gradient panel lists them.
|
||||
pub const ALL: [GradientKind; 5] =
|
||||
[GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond, GradientKind::Freeform];
|
||||
/// Parse a kind name (`linear`, `radial`, `conic`, `diamond`, `freeform`; any case). `angle`
|
||||
/// and `conical` also mean conic.
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
[GradientKind::Linear, GradientKind::Radial, GradientKind::Freeform].into_iter().find(|k| k.label().eq_ignore_ascii_case(s))
|
||||
if s.eq_ignore_ascii_case("angle") || s.eq_ignore_ascii_case("conical") {
|
||||
return Some(GradientKind::Conic);
|
||||
}
|
||||
Self::ALL.into_iter().find(|k| k.label().eq_ignore_ascii_case(s))
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
GradientKind::Linear => "Linear",
|
||||
GradientKind::Radial => "Radial",
|
||||
GradientKind::Freeform => "Freeform",
|
||||
GradientKind::Conic => "Conic",
|
||||
GradientKind::Diamond => "Diamond",
|
||||
}
|
||||
}
|
||||
/// Is it placed by a center (`start`) and an extent around it (radial, conic and diamond),
|
||||
/// rather than by a line?
|
||||
pub fn is_centered(self) -> bool {
|
||||
matches!(self, GradientKind::Radial | GradientKind::Conic | GradientKind::Diamond)
|
||||
}
|
||||
}
|
||||
|
||||
/// How a gradient mixes the colours between its stops (the Gradient panel's Method).
|
||||
@@ -40,24 +65,62 @@ pub enum GradientMethod {
|
||||
/// Mixed in a perceptual colour space (OKLab), so the steps look even to the eye: blue to
|
||||
/// yellow passes through a light blue-grey rather than a dull mid grey.
|
||||
Perceptual,
|
||||
/// Mixed around the hue wheel, clockwise as the color wheels draw it: the hue angle falls
|
||||
/// from each stop to the next (red, magenta, blue, cyan, green, yellow, red), and saturation
|
||||
/// and brightness change evenly ([`hue_mix`]).
|
||||
HueClockwise,
|
||||
/// Mixed around the hue wheel the other way: the hue angle rises from each stop to the next
|
||||
/// (red, yellow, green, cyan, blue, magenta, red).
|
||||
HueCounterclockwise,
|
||||
}
|
||||
|
||||
impl GradientMethod {
|
||||
/// Parse a method name (`classic`, `perceptual`; any case).
|
||||
/// Every method, in the order the Gradient panel lists them.
|
||||
pub const ALL: [GradientMethod; 4] = [Self::Classic, Self::Perceptual, Self::HueClockwise, Self::HueCounterclockwise];
|
||||
/// Parse a method name (`classic`, `perceptual`, `hue-clockwise`, `hue-counterclockwise`;
|
||||
/// any case, and the hyphen may be a space or an underscore, or left out). Any other text,
|
||||
/// one with a separator elsewhere included, is `None`.
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
[Self::Classic, Self::Perceptual].into_iter().find(|m| m.label().eq_ignore_ascii_case(s))
|
||||
let name = s.to_ascii_lowercase();
|
||||
Self::ALL.into_iter().find(|m| ["-", " ", "_", ""].iter().any(|sep| m.id().replace('-', sep) == name))
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Classic => "Classic",
|
||||
Self::Perceptual => "Perceptual",
|
||||
Self::HueClockwise => "Hue Clockwise",
|
||||
Self::HueCounterclockwise => "Hue Counterclockwise",
|
||||
}
|
||||
}
|
||||
/// The method's name in command params (`classic`, `perceptual`, `hue-clockwise`,
|
||||
/// `hue-counterclockwise`).
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Classic => "classic",
|
||||
Self::Perceptual => "perceptual",
|
||||
Self::HueClockwise => "hue-clockwise",
|
||||
Self::HueCounterclockwise => "hue-counterclockwise",
|
||||
}
|
||||
}
|
||||
pub fn is_classic(&self) -> bool {
|
||||
*self == Self::Classic
|
||||
}
|
||||
/// `a` and `b` mixed at `t` (0..1): in display RGB (Classic), or in OKLab (Perceptual: an
|
||||
/// RGB colour between the two).
|
||||
/// Does it mix around the hue wheel (Hue Clockwise or Hue Counterclockwise)? The colors
|
||||
/// between two stops then are not mixes of the stops' inks.
|
||||
pub fn is_hue(&self) -> bool {
|
||||
matches!(self, Self::HueClockwise | Self::HueCounterclockwise)
|
||||
}
|
||||
/// The method that mixes `b` to `a` through the colors this one mixes `a` to `b` through: a
|
||||
/// hue method turned the other way, Classic and Perceptual as they are.
|
||||
pub fn mirrored(self) -> Self {
|
||||
match self {
|
||||
Self::HueClockwise => Self::HueCounterclockwise,
|
||||
Self::HueCounterclockwise => Self::HueClockwise,
|
||||
m => m,
|
||||
}
|
||||
}
|
||||
/// `a` and `b` mixed at `t` (0..1): in display RGB (Classic), in OKLab (Perceptual: an
|
||||
/// RGB colour between the two), or around the hue wheel ([`hue_mix`]: an RGB colour).
|
||||
pub fn mix(self, a: &Color, b: &Color, t: f32) -> Color {
|
||||
match self {
|
||||
Self::Classic => Color::lerp(a, b, t),
|
||||
@@ -68,10 +131,144 @@ impl GradientMethod {
|
||||
let c = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) as f32 } else { 0.0 };
|
||||
Color::rgb(c(r), c(g), c(bl))
|
||||
}
|
||||
Self::HueClockwise => hue_mix(a, b, t, false),
|
||||
Self::HueCounterclockwise => hue_mix(a, b, t, true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The brightness (0..1) at or below which a color is black for [`hue_mix`], and the spread
|
||||
/// between its largest and smallest RGB numbers (saturation × brightness) at or below which it
|
||||
/// has no hue of its own: under half a color level.
|
||||
const NO_HUE: f32 = 0.4 / 255.0;
|
||||
|
||||
/// The hue difference (degrees) that moves an RGB number by half a color level in a color whose
|
||||
/// largest and smallest RGB numbers are 1 apart; a color with a smaller spread takes
|
||||
/// proportionally more degrees. [`hue_mix`] counts two hues closer than this as one hue.
|
||||
const SAME_HUE: f32 = 60.0 * 0.5 / 255.0;
|
||||
|
||||
/// `a` and `b` mixed at `t` (0..1) around the hue wheel, as display RGB: hue (degrees),
|
||||
/// saturation and brightness each change evenly from `a`'s to `b`'s. The hue angle only rises
|
||||
/// (`rising`) or only falls, by the fixed-direction rules of
|
||||
/// <https://www.w3.org/TR/css-color-4/#hue-interpolation>, and two equal hues stay where they are.
|
||||
/// Two hues that differ by less than half a color level ([`SAME_HUE`]) count as equal and take the
|
||||
/// short way, so a color and a tint or shade of it, whose computed hues differ by rounding, do
|
||||
/// not turn the whole wheel. A color whose RGB numbers are less than half a color level apart
|
||||
/// ([`NO_HUE`]) has no hue and takes the other color's; black has no saturation either and takes
|
||||
/// the other color's too. Two colors without a hue mix as grays. A `t` that is not a number
|
||||
/// gives `a`.
|
||||
pub fn hue_mix(a: &Color, b: &Color, t: f32, rising: bool) -> Color {
|
||||
let t = if t.is_nan() { 0.0 } else { t.clamp(0.0, 1.0) };
|
||||
let ([mut h0, mut s0, v0], [mut h1, mut s1, v1]) = (a.to_hsb(), b.to_hsb());
|
||||
let (black0, black1) = (v0 <= NO_HUE, v1 <= NO_HUE);
|
||||
// The spread between each color's own largest and smallest RGB numbers.
|
||||
let (spread0, spread1) = (s0 * v0, s1 * v1);
|
||||
// Black takes the other color's saturation, so it darkens that color rather than graying it.
|
||||
if black0 && !black1 {
|
||||
s0 = s1;
|
||||
} else if black1 && !black0 {
|
||||
s1 = s0;
|
||||
}
|
||||
let (gray0, gray1) = (black0 || spread0 <= NO_HUE, black1 || spread1 <= NO_HUE);
|
||||
match (gray0, gray1) {
|
||||
(true, _) => h0 = h1,
|
||||
(false, true) => h1 = h0,
|
||||
(false, false) => {
|
||||
// The short way from the first hue to the second, -180..180.
|
||||
let short = (h1 - h0 + 180.0).rem_euclid(360.0) - 180.0;
|
||||
h1 = if short.abs() * spread0.min(spread1) <= SAME_HUE {
|
||||
h0 + short
|
||||
} else if rising {
|
||||
h0 + short.rem_euclid(360.0)
|
||||
} else {
|
||||
h0 + short.rem_euclid(360.0) - 360.0
|
||||
};
|
||||
}
|
||||
}
|
||||
let at = |p: f32, q: f32| p + (q - p) * t;
|
||||
let (h, s, v) = (at(h0, h1), at(s0, s1), at(v0, v1));
|
||||
if !(h.is_finite() && s.is_finite() && v.is_finite()) {
|
||||
return Color::rgb(0.0, 0.0, 0.0);
|
||||
}
|
||||
Color::from_hsb(h.rem_euclid(360.0), s.clamp(0.0, 1.0), v.clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
/// What a linear, radial, conic or diamond gradient paints past the ends of its stops (the
|
||||
/// Gradient panel's Spread). With Repeat and Reflect, the stops run [`Gradient::repeats`] times
|
||||
/// along the vector (around the circle, for a conic), and keep going past both of its ends.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
|
||||
pub enum GradientSpread {
|
||||
/// The first and last stops' colors carry on past the ends, as gradients always did.
|
||||
#[default]
|
||||
Pad,
|
||||
/// The stops start again at each end.
|
||||
Repeat,
|
||||
/// The stops run back the other way at each end, so every other run is mirrored.
|
||||
Reflect,
|
||||
}
|
||||
|
||||
impl GradientSpread {
|
||||
/// Every spread, in the order the Gradient panel lists them.
|
||||
pub const ALL: [GradientSpread; 3] = [GradientSpread::Pad, GradientSpread::Repeat, GradientSpread::Reflect];
|
||||
/// Parse a spread name (`pad`, `repeat`, `reflect`; any case).
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|m| m.label().eq_ignore_ascii_case(s))
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Pad => "Pad",
|
||||
Self::Repeat => "Repeat",
|
||||
Self::Reflect => "Reflect",
|
||||
}
|
||||
}
|
||||
pub fn is_pad(&self) -> bool {
|
||||
*self == Self::Pad
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for GradientSpread {
|
||||
/// A spread name; a file's unknown name or other value reads as Pad.
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Raw {
|
||||
Name(String),
|
||||
Other(serde::de::IgnoredAny),
|
||||
}
|
||||
Ok(match Raw::deserialize(d)? {
|
||||
Raw::Name(s) => Self::parse(&s).unwrap_or_default(),
|
||||
Raw::Other(_) => Self::Pad,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Most times a gradient's stops run along its vector ([`Gradient::repeats`]): VectorCraft's own
|
||||
/// limit.
|
||||
pub const MAX_REPEATS: u32 = 100;
|
||||
|
||||
fn one_repeat() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
fn is_one_repeat(n: &u32) -> bool {
|
||||
*n == 1
|
||||
}
|
||||
|
||||
/// A file's repeat count: a number, rounded and kept within 1 to [`MAX_REPEATS`]; anything else
|
||||
/// reads as 1.
|
||||
fn lenient_repeats<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum Raw {
|
||||
Number(f64),
|
||||
Other(serde::de::IgnoredAny),
|
||||
}
|
||||
Ok(match Raw::deserialize(d)? {
|
||||
Raw::Number(n) if n.is_finite() => n.round().clamp(1.0, f64::from(MAX_REPEATS)) as u32,
|
||||
_ => 1,
|
||||
})
|
||||
}
|
||||
|
||||
/// How far (display RGB, 0..1) the straight line between a Perceptual gradient's neighbouring
|
||||
/// expanded stops may stray from the perceptual mix: under half a colour level.
|
||||
const PERCEPTUAL_TOLERANCE: f32 = 0.4 / 255.0;
|
||||
@@ -91,10 +288,11 @@ const MAX_INK_TINTS: usize = 4096;
|
||||
const INK_MIX_STEPS: u32 = 64;
|
||||
|
||||
/// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly
|
||||
/// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved
|
||||
/// where a straight line strays, at most [`PERCEPTUAL_DEPTH`] times, in order.
|
||||
fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: &mut Vec<f32>) {
|
||||
let at = |v: f32| GradientMethod::Perceptual.mix(a, b, v).to_rgb();
|
||||
/// stays within [`PERCEPTUAL_TOLERANCE`] of `method`'s mix of `a` and `b` (Perceptual, or around
|
||||
/// the hue wheel): the span halved where a straight line strays, at most [`PERCEPTUAL_DEPTH`]
|
||||
/// times, in order.
|
||||
fn perceptual_steps(method: GradientMethod, a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out: &mut Vec<f32>) {
|
||||
let at = |v: f32| method.mix(a, b, v).to_rgb();
|
||||
let (c0, c1) = (at(v0), at(v1));
|
||||
let stray = [0.25, 0.5, 0.75]
|
||||
.into_iter()
|
||||
@@ -105,19 +303,20 @@ fn perceptual_steps(a: &Color, b: &Color, (v0, v1): (f32, f32), depth: u32, out:
|
||||
.fold(0.0, f32::max);
|
||||
if depth < PERCEPTUAL_DEPTH && stray > PERCEPTUAL_TOLERANCE {
|
||||
let m = (v0 + v1) / 2.0;
|
||||
perceptual_steps(a, b, (v0, m), depth + 1, out);
|
||||
perceptual_steps(method, a, b, (v0, m), depth + 1, out);
|
||||
out.push(m);
|
||||
perceptual_steps(a, b, (m, v1), depth + 1, out);
|
||||
perceptual_steps(method, a, b, (m, v1), depth + 1, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// The mix positions (`v`, 0..1) of the stops a Perceptual gradient's curve has between stops `a`
|
||||
/// and `b`, in order: [`perceptual_steps`] on either side of the midpoint, and the midpoint (½).
|
||||
fn perceptual_mixes(a: &GradientStop, b: &GradientStop) -> Vec<f32> {
|
||||
/// The mix positions (`v`, 0..1) of the stops the curve of a gradient mixed by `method`
|
||||
/// (Perceptual, or around the hue wheel) has between stops `a` and `b`, in order:
|
||||
/// [`perceptual_steps`] on either side of the midpoint, and the midpoint (½).
|
||||
fn perceptual_mixes(method: GradientMethod, a: &GradientStop, b: &GradientStop) -> Vec<f32> {
|
||||
let mut vs = Vec::new();
|
||||
perceptual_steps(&a.color, &b.color, (0.0, 0.5), 1, &mut vs);
|
||||
perceptual_steps(method, &a.color, &b.color, (0.0, 0.5), 1, &mut vs);
|
||||
vs.push(0.5);
|
||||
perceptual_steps(&a.color, &b.color, (0.5, 1.0), 1, &mut vs);
|
||||
perceptual_steps(method, &a.color, &b.color, (0.5, 1.0), 1, &mut vs);
|
||||
vs
|
||||
}
|
||||
|
||||
@@ -237,6 +436,15 @@ pub struct Gradient {
|
||||
/// How the colours between the stops are mixed (Classic unless set; written only when not).
|
||||
#[serde(default, skip_serializing_if = "GradientMethod::is_classic")]
|
||||
pub method: GradientMethod,
|
||||
/// What it paints past the ends of its stops (Pad unless set; written only when not). A
|
||||
/// freeform gradient has no ends and ignores it.
|
||||
#[serde(default, skip_serializing_if = "GradientSpread::is_pad")]
|
||||
pub spread: GradientSpread,
|
||||
/// How many times the stops run along the vector with Repeat and Reflect, 1 to
|
||||
/// [`MAX_REPEATS`] (use [`Self::repeat_count`]: a value set in code may be out of range); Pad
|
||||
/// ignores it. Written only when it is not 1.
|
||||
#[serde(default = "one_repeat", skip_serializing_if = "is_one_repeat", deserialize_with = "lenient_repeats")]
|
||||
pub repeats: u32,
|
||||
}
|
||||
|
||||
impl Default for Gradient {
|
||||
@@ -249,7 +457,55 @@ impl Default for Gradient {
|
||||
impl Gradient {
|
||||
/// A gradient of `kind` through `stops`, with the default options.
|
||||
pub fn new(kind: GradientKind, stops: Vec<GradientStop>) -> Self {
|
||||
Self { kind, stops, dither: false, method: GradientMethod::Classic }
|
||||
Self { kind, stops, dither: false, method: GradientMethod::Classic, spread: GradientSpread::Pad, repeats: 1 }
|
||||
}
|
||||
/// [`Self::repeats`] kept within 1 to [`MAX_REPEATS`].
|
||||
pub fn repeat_count(&self) -> u32 {
|
||||
self.repeats.clamp(1, MAX_REPEATS)
|
||||
}
|
||||
/// Does it paint something other than its end colors past the ends of its stops, or run its
|
||||
/// stops more than once: a linear, radial, conic or diamond gradient that repeats or reflects?
|
||||
pub fn is_spread(&self) -> bool {
|
||||
!self.spread.is_pad() && self.kind != GradientKind::Freeform
|
||||
}
|
||||
/// The spread and count as the gradient paints them: Pad and 1 for one that pads (whatever
|
||||
/// count it keeps) and for a freeform one, else its spread and [`Self::repeat_count`]. Equal
|
||||
/// for two gradients whose spreads paint alike.
|
||||
pub fn painted_spread(&self) -> (GradientSpread, u32) {
|
||||
if self.is_spread() { (self.spread, self.repeat_count()) } else { (GradientSpread::Pad, 1) }
|
||||
}
|
||||
/// The position (0..1) along the stops that gradient parameter `t` (0 at the start of the
|
||||
/// vector, 1 at its end; [`GradientGeom::param_at`]) samples: `t` itself with Pad (the stops
|
||||
/// clamp it), else `t` × [`Self::repeat_count`] wrapped back into 0..1, every other run
|
||||
/// mirrored with Reflect. A `t` that is not finite is returned as it is.
|
||||
pub fn spread_param(&self, t: f64) -> f64 {
|
||||
self.spreader()(t)
|
||||
}
|
||||
/// How many wedges a conic gradient is written as ([`GradientGeom::conic_wedges`]) where
|
||||
/// `per_turn` would do for stops that run once around: that many for each time the stops run
|
||||
/// around, at most [`MAX_CONIC_WEDGES`]. Sample each wedge at [`Self::spread_param`] of its
|
||||
/// turn.
|
||||
pub fn conic_wedge_count(&self, per_turn: usize) -> usize {
|
||||
let runs = if self.is_spread() { self.repeat_count() as usize } else { 1 };
|
||||
per_turn.saturating_mul(runs).clamp(1, MAX_CONIC_WEDGES)
|
||||
}
|
||||
/// [`Self::spread_param`] as a function that holds no borrow of the gradient.
|
||||
pub fn spreader(&self) -> impl Fn(f64) -> f64 + Copy + use<> {
|
||||
let spread = if self.is_spread() { self.spread } else { GradientSpread::Pad };
|
||||
let n = f64::from(self.repeat_count());
|
||||
move |t: f64| {
|
||||
if !t.is_finite() {
|
||||
return t;
|
||||
}
|
||||
match spread {
|
||||
GradientSpread::Pad => t,
|
||||
GradientSpread::Repeat => (t * n).rem_euclid(1.0),
|
||||
GradientSpread::Reflect => {
|
||||
let w = (t * n).rem_euclid(2.0);
|
||||
if w > 1.0 { 2.0 - w } else { w }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Colour and opacity at `t` (honours midpoints and the method).
|
||||
pub fn sample(&self, t: f32) -> (Color, f32) {
|
||||
@@ -354,10 +610,11 @@ impl Gradient {
|
||||
};
|
||||
(t, c, o, Some(s.midpoint), None)
|
||||
});
|
||||
// Perceptual: stops along the mix (`v`) where a straight line would stray from it, the
|
||||
// midpoint (v = ½) among them, placed through the midpoint as [`Self::sample`] maps them.
|
||||
// Perceptual and the hue methods: stops along the mix (`v`) where a straight line would
|
||||
// stray from it, the midpoint (v = ½) among them, placed through the midpoint as
|
||||
// [`Self::sample`] maps them.
|
||||
let perceptual = next.filter(|_| !self.method.is_classic()).map(|n| {
|
||||
perceptual_mixes(s, n).into_iter().map(move |v| {
|
||||
perceptual_mixes(self.method, s, n).into_iter().map(move |v| {
|
||||
let mid = v == 0.5;
|
||||
let t = curve_offset(s, n, v);
|
||||
let o = s.opacity + (n.opacity - s.opacity) * v;
|
||||
@@ -413,11 +670,12 @@ impl Gradient {
|
||||
/// position itself when the two colors' lightness differs by less than
|
||||
/// [`MIN_INK_LIGHTNESS_SPAN`], or when the display RGB mix's lightness turns back somewhere
|
||||
/// on the way from one color's lightness to the other's (checked at [`INK_MIX_STEPS`] even
|
||||
/// steps), as from red to blue. `None` for a Classic gradient, and when the curve has more
|
||||
/// than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
|
||||
/// steps), as from red to blue. `None` for a Classic gradient, for one mixed around the hue
|
||||
/// wheel (its colors between two stops are not mixes of the stops' inks), and when the curve
|
||||
/// has more than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]).
|
||||
pub fn ink_mixes(&self) -> Option<Vec<(f32, usize, f32, f32)>> {
|
||||
use crate::libraries::srgb_to_oklab;
|
||||
if self.method.is_classic() || !self.fits_ink_tints() {
|
||||
if self.method != GradientMethod::Perceptual || !self.fits_ink_tints() {
|
||||
return None;
|
||||
}
|
||||
let lightness = |c: &Color| srgb_to_oklab(c.to_rgb())[0];
|
||||
@@ -434,7 +692,7 @@ impl Gradient {
|
||||
.collect::<Vec<_>>()
|
||||
.windows(2)
|
||||
.all(|w| (w[1] - w[0]) * (l1 - l0) >= 0.0);
|
||||
for v in perceptual_mixes(s, n) {
|
||||
for v in perceptual_mixes(self.method, s, n) {
|
||||
let weight = if by_position {
|
||||
v
|
||||
} else {
|
||||
@@ -492,8 +750,10 @@ impl Gradient {
|
||||
Some(Ramp { stops })
|
||||
}
|
||||
/// The same ramp the other way round: the stops in reverse order at mirrored offsets, each
|
||||
/// segment's midpoint mirrored with it.
|
||||
/// segment's midpoint mirrored with it, and a hue method turned the other way (red to blue
|
||||
/// through magenta, reversed, is blue to red through magenta).
|
||||
pub fn reverse(&mut self) {
|
||||
self.method = self.method.mirrored();
|
||||
self.stops.reverse();
|
||||
for i in 0..self.stops.len() {
|
||||
// A midpoint belongs to the segment after its stop: reversed, stop i's segment is the
|
||||
@@ -508,6 +768,13 @@ impl Gradient {
|
||||
pub fn sort(&mut self) {
|
||||
self.stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
|
||||
}
|
||||
/// The gradient's colors as a Classic gradient: its curve's stops ([`Self::expanded_stops`]) as
|
||||
/// stops of their own, mixed in display RGB, within [`PERCEPTUAL_TOLERANCE`] of it. The stops
|
||||
/// keep no swatch links, tints or process plates.
|
||||
pub fn as_classic_curve(&self) -> Gradient {
|
||||
let stops = self.expanded().map(|(t, color, opacity, _)| GradientStop { opacity, ..GradientStop::new(t, color) }).collect();
|
||||
Gradient { kind: self.kind, stops, dither: self.dither, method: GradientMethod::Classic, spread: self.spread, repeats: self.repeats }
|
||||
}
|
||||
/// The part of the gradient from `from` to `to` (0..1, either way round) as a linear gradient
|
||||
/// of its own running 0 → 1: the same colours (midpoints become stops, as in
|
||||
/// [`Self::expanded_stops`]). One colour throughout when `from == to`.
|
||||
@@ -522,10 +789,18 @@ impl Gradient {
|
||||
GradientStop { opacity, ..GradientStop::new(offset, color) }
|
||||
};
|
||||
let d = to - from;
|
||||
let mut stops = vec![stop(0.0, from)];
|
||||
let expanded = self.expanded_stops();
|
||||
// Where stops share the offset `from` (a sharp step, as where the runs of a repeating
|
||||
// gradient meet), the piece starts with the color after the step; sampling gives the one
|
||||
// before it.
|
||||
let first = match expanded.iter().rev().find(|(t, ..)| *t == from) {
|
||||
Some(&(_, color, opacity)) if d > 1e-6 => GradientStop { opacity, ..GradientStop::new(0.0, color) },
|
||||
_ => stop(0.0, from),
|
||||
};
|
||||
let mut stops = vec![first];
|
||||
if d > 1e-6 {
|
||||
stops.extend(
|
||||
self.expanded_stops()
|
||||
expanded
|
||||
.into_iter()
|
||||
.filter(|(t, ..)| *t > from && *t < to)
|
||||
.map(|(t, color, opacity)| GradientStop { opacity, ..GradientStop::new((t - from) / d, color) }),
|
||||
@@ -642,19 +917,32 @@ pub struct GradientGeom {
|
||||
/// How far out a focal point may sit, as a fraction of the extent ellipse.
|
||||
const FOCAL_MAX: f64 = 0.99;
|
||||
|
||||
/// Most wedges [`GradientGeom::conic_wedges`] draws a conic gradient as.
|
||||
pub const MAX_CONIC_WEDGES: usize = 4096;
|
||||
|
||||
fn one64() -> f64 {
|
||||
1.0
|
||||
}
|
||||
|
||||
impl GradientGeom {
|
||||
/// Default placement for a bounding box: linear spans the box through the centre at `angle_deg`,
|
||||
/// radial is centred with radius = half the larger dimension and its vector at `angle_deg`.
|
||||
/// radial and conic are centered with radius = half the larger dimension and their vector at
|
||||
/// `angle_deg`, and diamond is centered with its vector at `angle_deg`, its square's edge
|
||||
/// running through the box's farthest corner (at 0 or 90 degrees, through all four).
|
||||
pub fn fit(kind: GradientKind, b: Rect, angle_deg: f64) -> Self {
|
||||
let c = b.center();
|
||||
let a = angle_deg.to_radians();
|
||||
let d = Vec2::new(a.cos(), -a.sin());
|
||||
match kind {
|
||||
GradientKind::Radial => Self { start: c, end: c + d * (b.width().max(b.height()) / 2.0), aspect: 1.0, focal: None },
|
||||
GradientKind::Radial | GradientKind::Conic => Self { start: c, end: c + d * (b.width().max(b.height()) / 2.0), aspect: 1.0, focal: None },
|
||||
GradientKind::Diamond => {
|
||||
// The square through the box's farthest corner: the largest reach along the vector
|
||||
// plus across it, at one corner.
|
||||
let (w, h) = (b.width() / 2.0, b.height() / 2.0);
|
||||
let level = |x: f64, y: f64| (x * d.x + y * d.y).abs() + (y * d.x - x * d.y).abs();
|
||||
let half = level(w, h).max(level(w, -h));
|
||||
Self { start: c, end: c + d * half, aspect: 1.0, focal: None }
|
||||
}
|
||||
_ => {
|
||||
// Project the box corners onto the direction to cover the whole box.
|
||||
let half = (b.width() * d.x.abs() + b.height() * d.y.abs()) / 2.0;
|
||||
@@ -668,7 +956,16 @@ impl GradientGeom {
|
||||
/// Linear (and freeform) gradients keep their isolines: the new vector is the normal to the
|
||||
/// mapped isolines, reaching the line the old end maps onto. Radial gradients map their ellipse
|
||||
/// (the radius along the vector, `aspect` × the radius across it); its principal axes give the
|
||||
/// new end (on the axis nearest the mapped vector) and aspect.
|
||||
/// new end (on the axis nearest the mapped vector) and aspect. Conic gradients keep their
|
||||
/// vector exactly (where the sweep starts, so the seam stays in place) and take the mapped
|
||||
/// extent across it as their aspect, its sign flipping under a mirror so the sweep turns the
|
||||
/// other way: exact for moves, rotations, uniform scales and mirrors, and the nearest frame
|
||||
/// that keeps the seam under a shear or a non-uniform scale. A conic whose vector has no
|
||||
/// length, or whose aspect is 0, still has the sign of its aspect flipped by a mirror.
|
||||
/// Diamond gradients keep their vector (a corner of the square) the same way, with the size
|
||||
/// of the mapped extent across it as their aspect: exact for moves, rotations, scales along or
|
||||
/// across the vector and mirrors, and the nearest square stretched across its vector under a
|
||||
/// shear or another scale.
|
||||
pub fn transform(&mut self, a: Affine, kind: GradientKind) {
|
||||
// The focal point is a point like any other.
|
||||
self.focal = self.focal.map(|f| a * f);
|
||||
@@ -677,9 +974,34 @@ impl GradientGeom {
|
||||
let perp = |v: Vec2| Vec2::new(-v.y, v.x);
|
||||
let start = a * self.start;
|
||||
let u = self.end - self.start;
|
||||
let mirror = m0 * m3 - m1 * m2 < 0.0;
|
||||
if u.hypot2() < 1e-18 {
|
||||
self.start = start;
|
||||
self.end = start;
|
||||
if kind == GradientKind::Conic && mirror {
|
||||
self.aspect = -self.aspect;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if kind == GradientKind::Conic {
|
||||
let (lu, lw) = (lin(u), lin(perp(u) * self.aspect));
|
||||
self.start = start;
|
||||
self.end = start + lu;
|
||||
let aspect = lw.dot(perp(lu)) / lu.hypot2();
|
||||
self.aspect = match (lu.hypot2() > 1e-18 && aspect.is_finite(), aspect == 0.0) {
|
||||
(false, _) => 1.0,
|
||||
// A flat extent keeps its sign, so a mirror still turns the sweep the other way.
|
||||
(true, true) => 0.0f64.copysign(if self.aspect.is_sign_negative() != mirror { -1.0 } else { 1.0 }),
|
||||
(true, false) => aspect,
|
||||
};
|
||||
return;
|
||||
}
|
||||
if kind == GradientKind::Diamond {
|
||||
let (lu, lw) = (lin(u), lin(perp(u) * self.aspect));
|
||||
self.start = start;
|
||||
self.end = start + lu;
|
||||
let aspect = (lw.dot(perp(lu)) / lu.hypot2()).abs();
|
||||
self.aspect = if lu.hypot2() > 1e-18 && aspect.is_finite() { aspect } else { 1.0 };
|
||||
return;
|
||||
}
|
||||
if kind != GradientKind::Radial {
|
||||
@@ -724,8 +1046,24 @@ impl GradientGeom {
|
||||
/// The gradient parameter (0 at the start, 1 at the end) at document point `p`: the projection
|
||||
/// onto the vector for linear gradients, the elliptical radius (honouring `aspect`) for radial,
|
||||
/// measured from the focal point (each level is the ellipse scaled about the line from the
|
||||
/// focal point to the centre).
|
||||
/// focal point to the centre). For conic gradients it is the turn from the vector in
|
||||
/// [`Self::conic_frame`], clockwise on the page (counterclockwise when mirrored), in 0..=1.
|
||||
/// For diamond gradients it is the size of the square through `p`, as a fraction of the one
|
||||
/// [`Self::diamond_frame`] gives (1 everywhere for a diamond without a frame).
|
||||
pub fn param_at(&self, kind: GradientKind, p: Point) -> f64 {
|
||||
if kind == GradientKind::Conic {
|
||||
let q = (self.conic_frame().inverse() * p).to_vec2();
|
||||
let t = q.y.atan2(q.x) / std::f64::consts::TAU;
|
||||
let t = if t < 0.0 { t + 1.0 } else { t };
|
||||
return if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
|
||||
}
|
||||
if kind == GradientKind::Diamond {
|
||||
// Without a frame the square has no inside: every point is past its edge.
|
||||
let Some(m) = self.diamond_frame() else { return 1.0 };
|
||||
let q = (m.inverse() * p).to_vec2();
|
||||
let t = q.x.abs() + q.y.abs();
|
||||
return if t.is_nan() { 1.0 } else { t };
|
||||
}
|
||||
let u = self.end - self.start;
|
||||
if u.hypot2() < 1e-18 {
|
||||
return 0.0;
|
||||
@@ -746,13 +1084,92 @@ impl GradientGeom {
|
||||
(-b - (b * b - a * d.hypot2()).max(0.0).sqrt()) / a
|
||||
}
|
||||
|
||||
/// The map from the unit circle onto a radial's extent ellipse: (1, 0) to the end, (0, 1) to
|
||||
/// `aspect` × the radius across the vector. None when the ellipse is flat (no inverse).
|
||||
/// The map from the unit circle onto a radial's (or conic's) extent ellipse: (1, 0) to the
|
||||
/// end, (0, 1) to `aspect` × the radius across the vector (a conic's negative aspect mirrors
|
||||
/// it). None when the ellipse is flat (no inverse).
|
||||
pub fn unit_frame(&self) -> Option<Affine> {
|
||||
let u = self.end - self.start;
|
||||
(u.hypot2() * self.aspect.abs() > 1e-18).then(|| Affine::new([u.x, u.y, -u.y * self.aspect, u.x * self.aspect, self.start.x, self.start.y]))
|
||||
}
|
||||
|
||||
/// The frame a conic gradient sweeps in: its [`Self::unit_frame`], or, when the extent
|
||||
/// ellipse is flat or not finite (a vector without length, an aspect of 0, or a file's
|
||||
/// out-of-range numbers), the unit circle about the start turning from the vector's direction
|
||||
/// (from the right when the vector has none), mirrored by a negative aspect. The canvas,
|
||||
/// Expand and every export draw a conic in this frame.
|
||||
pub fn conic_frame(&self) -> Affine {
|
||||
if let Some(m) = self.unit_frame().filter(|m| m.is_finite() && m.determinant().abs() > 1e-18) {
|
||||
return m;
|
||||
}
|
||||
if !self.start.is_finite() {
|
||||
return Affine::IDENTITY;
|
||||
}
|
||||
let u = self.end - self.start;
|
||||
let len = u.hypot();
|
||||
let d = if len.is_finite() && len > 1e-9 { u / len } else { Vec2::new(1.0, 0.0) };
|
||||
let s = if self.aspect.is_sign_negative() && !self.aspect.is_nan() { -1.0 } else { 1.0 };
|
||||
Affine::new([d.x, d.y, -d.y * s, d.x * s, self.start.x, self.start.y])
|
||||
}
|
||||
|
||||
/// Is the sweep mirrored (counterclockwise on the page): a conic's negative aspect?
|
||||
pub fn is_mirrored(&self) -> bool {
|
||||
self.conic_frame().determinant() < 0.0
|
||||
}
|
||||
|
||||
/// A conic gradient as `n` solid wedges around its center (at most [`MAX_CONIC_WEDGES`]), for
|
||||
/// formats without conic gradients: each wedge's outline (the center, then an arc that
|
||||
/// reaches past every corner of `b`) and the turn its color is sampled at (its middle). With
|
||||
/// `overlap` (opaque stops), each wedge runs on to the seam and the next is drawn over it, so
|
||||
/// no hairline of what lies below shows between neighbors and the seam stays sharp.
|
||||
pub fn conic_wedges(&self, b: Rect, n: usize, overlap: bool) -> Vec<(Vec<Point>, f64)> {
|
||||
let n = n.clamp(1, MAX_CONIC_WEDGES);
|
||||
let frame = self.conic_frame();
|
||||
let r = fan_radius(frame, b);
|
||||
(0..n)
|
||||
.map(|k| {
|
||||
let from = k as f64 / n as f64;
|
||||
let to = if overlap { 1.0 } else { (k + 1) as f64 / n as f64 };
|
||||
(fan(frame, r, from, to), (k as f64 + 0.5) / n as f64)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The frame a diamond gradient is drawn in: its [`Self::unit_frame`], which maps the square
|
||||
/// with corners (±1, 0) and (0, ±1) onto the diamond (its first corner at the end of the
|
||||
/// vector). `None` when the square is flat or not finite (a vector without length, an aspect
|
||||
/// of 0, or a file's out-of-range numbers): such a diamond has no inside, and every point
|
||||
/// takes its last stop.
|
||||
pub fn diamond_frame(&self) -> Option<Affine> {
|
||||
self.unit_frame().filter(|m| m.is_finite() && m.determinant().abs() > 1e-18)
|
||||
}
|
||||
|
||||
/// A diamond gradient as four linear gradients, one for each quadrant of its
|
||||
/// [`Self::diamond_frame`], for formats without diamond gradients: each quadrant's outline (the
|
||||
/// center, then an arc that reaches past every corner of `b`) and the linear gradient that
|
||||
/// equals the diamond there (its stops run across the square's edge in that quadrant), in the
|
||||
/// order they are drawn. Each of the first three runs on past its last edge under the next,
|
||||
/// and the first also back past its first edge under the last, so every edge drawn lies on
|
||||
/// the quadrant before it and no hairline of what lies below shows between them; where they
|
||||
/// overlap, translucent stops would add up, so the stops must be opaque. `None` for a diamond
|
||||
/// without a frame.
|
||||
pub fn diamond_quadrants(&self, b: Rect) -> Option<[(Vec<Point>, GradientGeom); 4]> {
|
||||
let frame = self.diamond_frame()?;
|
||||
let r = fan_radius(frame, b);
|
||||
Some(std::array::from_fn(|k| {
|
||||
let first = k as f64 / 4.0;
|
||||
let (from, to) = match k {
|
||||
0 => (-0.125, 0.375),
|
||||
3 => (0.75, 1.0),
|
||||
_ => (first, first + 0.375),
|
||||
};
|
||||
// The quadrant's corner of the square, halfway along whose edge t is 1/2.
|
||||
let (sx, sy) = [(1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0)][k];
|
||||
let mut geom = GradientGeom { start: Point::ORIGIN, end: Point::new(sx / 2.0, sy / 2.0), aspect: 1.0, focal: None };
|
||||
geom.transform(frame, GradientKind::Linear);
|
||||
(fan(frame, r, from, to), geom)
|
||||
}))
|
||||
}
|
||||
|
||||
/// The map that squashes a radial gradient's circle (centre `start`, radius the vector's
|
||||
/// length) into its extent ellipse: by `aspect` across the vector, about the centre.
|
||||
pub fn radial_squash(&self) -> Affine {
|
||||
@@ -790,6 +1207,35 @@ impl GradientGeom {
|
||||
self.set_focal(Some(m * q));
|
||||
}
|
||||
}
|
||||
/// The placement whose level `t` is this one's level `k`·`t` (`k` > 0), for a linear, radial or
|
||||
/// diamond gradient: the vector `k` times as long from the same start, and for an off-center
|
||||
/// radial the extent ellipse scaled `k` times about the focal point, which stays. A conic keeps
|
||||
/// its placement (its level is a turn).
|
||||
pub fn levels_scaled(&self, kind: GradientKind, k: f64) -> GradientGeom {
|
||||
if kind == GradientKind::Conic || !(k.is_finite() && k > 0.0) {
|
||||
return *self;
|
||||
}
|
||||
let u = self.end - self.start;
|
||||
let mut out = *self;
|
||||
if kind == GradientKind::Radial
|
||||
&& let (Some(f), Some(frame)) = (self.focal, self.unit_frame())
|
||||
{
|
||||
// Level t of an off-center radial is the extent ellipse scaled by t about the line
|
||||
// from the focal point to the center: the new center sits on that line, `k` times as
|
||||
// far from the focal point.
|
||||
let f = (frame.inverse() * f).to_vec2();
|
||||
out.start = frame * (f * (1.0 - k)).to_point();
|
||||
}
|
||||
out.end = out.start + u * k;
|
||||
out
|
||||
}
|
||||
|
||||
/// The placement over which one run of the stops of a gradient that repeats `n` times along
|
||||
/// its vector lies ([`Self::levels_scaled`] by 1/`n`).
|
||||
pub fn period(&self, kind: GradientKind, n: u32) -> GradientGeom {
|
||||
self.levels_scaled(kind, 1.0 / f64::from(n.max(1)))
|
||||
}
|
||||
|
||||
pub fn angle_deg(&self) -> f64 {
|
||||
let v = self.end - self.start;
|
||||
(-v.y).atan2(v.x).to_degrees()
|
||||
@@ -799,6 +1245,34 @@ impl GradientGeom {
|
||||
}
|
||||
}
|
||||
|
||||
/// Arc points of [`fan`] are at most this much of a turn apart.
|
||||
const FAN_ARC: f64 = 1.0 / 32.0;
|
||||
|
||||
/// The radius of the unit circle of `frame` at which the chords of [`fan`]'s arcs stay outside
|
||||
/// every corner of `b`.
|
||||
fn fan_radius(frame: Affine, b: Rect) -> f64 {
|
||||
let to_unit = frame.inverse();
|
||||
let corners = [b.origin(), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)];
|
||||
let reach = corners.iter().map(|&c| (to_unit * c).to_vec2().hypot()).fold(0.0f64, f64::max).max(1e-6);
|
||||
let reach = if reach.is_finite() { reach * 1.01 } else { 1.0 };
|
||||
reach / (std::f64::consts::PI * FAN_ARC).cos()
|
||||
}
|
||||
|
||||
/// The sector of `frame`'s unit circle, scaled to radius `r`, from turn `from` to turn `to`
|
||||
/// (counted from the frame's x axis toward its y axis) as an outline: the center, then points on
|
||||
/// the arc at most [`FAN_ARC`] of a turn apart.
|
||||
fn fan(frame: Affine, r: f64, from: f64, to: f64) -> Vec<Point> {
|
||||
let at = |turn: f64| {
|
||||
let a = turn * std::f64::consts::TAU;
|
||||
frame * Point::new(r * a.cos(), r * a.sin())
|
||||
};
|
||||
let steps = ((to - from) / FAN_ARC).ceil().max(1.0) as usize;
|
||||
let mut pts = Vec::with_capacity(steps + 2);
|
||||
pts.push(frame * Point::ORIGIN);
|
||||
pts.extend((0..=steps).map(|i| at(from + (to - from) * i as f64 / steps as f64)));
|
||||
pts
|
||||
}
|
||||
|
||||
/// `p` moved from box `from` to box `to`, keeping its position relative to the box (along a side
|
||||
/// `from` has no extent on, its offset from the centre).
|
||||
fn rebase_point(p: Point, from: Rect, to: Rect) -> Point {
|
||||
@@ -896,12 +1370,13 @@ impl GradientPaint {
|
||||
}
|
||||
/// Is this gradient drawn as pixels rather than as a vector gradient when it paints a fill
|
||||
/// (`fill`) or a stroke (SVG and PDF draw such gradients as images): a freeform gradient, a
|
||||
/// dithered fill (dither applies to fills only), or a Perceptual one (its colours don't mix
|
||||
/// linearly between the stops, as SVG's and PDF's gradients do)?
|
||||
/// dithered fill (dither applies to fills only), or a Perceptual one or one mixed around the
|
||||
/// hue wheel (its colours don't mix linearly between the stops, as SVG's and PDF's gradients
|
||||
/// do)?
|
||||
pub fn draws_as_pixels(&self, fill: bool) -> bool {
|
||||
self.gradient.kind == GradientKind::Freeform || (fill && self.gradient.dither) || !self.gradient.method.is_classic()
|
||||
}
|
||||
/// A linear or radial gradient placed on box `bounds` as a `cols` × `rows` grid of
|
||||
/// A linear, radial, conic or diamond gradient placed on box `bounds` as a `cols` × `rows` grid of
|
||||
/// unpremultiplied RGBA8 pixels over `area`, row by row, each sampled at its centre (colours
|
||||
/// as `rgb` gives them, mixed as the renderer mixes them: [`Ramp`]). Dithered and painting a
|
||||
/// fill (`fill`; dither applies to fills only), each colour channel of pixel (column, row) gets
|
||||
@@ -932,7 +1407,7 @@ impl GradientPaint {
|
||||
) -> impl Iterator<Item = [u8; 4]> + use<> {
|
||||
self.grid(Ramp::new(&self.gradient, rgb), bounds, area, cols, rows, cells, fill, false)
|
||||
}
|
||||
/// [`Self::pixels`] of a linear or radial gradient whose stops are all CMYK, as C, M, Y, K
|
||||
/// [`Self::pixels`] of a linear, radial, conic or diamond gradient whose stops are all CMYK, as C, M, Y, K
|
||||
/// and opacity levels mixed from the stops' inks; `None` when a stop is in another model,
|
||||
/// there are no stops, or a Perceptual curve has too many stops for [`Gradient::ink_mixes`].
|
||||
/// Dither's noise adds no ink where the ramp has none.
|
||||
@@ -956,12 +1431,13 @@ impl GradientPaint {
|
||||
inks: bool,
|
||||
) -> impl Iterator<Item = [u8; N]> + use<N> {
|
||||
let (kind, geom, dither) = (self.gradient.kind, self.resolve(bounds), fill && self.gradient.dither);
|
||||
let spread = self.gradient.spreader();
|
||||
let (cw, ch) = (area.width() / f64::from(cols.max(1)), area.height() / f64::from(rows.max(1)));
|
||||
let (x0, y0) = (area.x0, area.y0);
|
||||
let [across, down] = cells.map(|r| u32::from(r.start)..u32::from(r.end));
|
||||
down.flat_map(move |j| across.clone().map(move |i| (i, j))).map(move |(i, j)| {
|
||||
let p = Point::new(x0 + (f64::from(i) + 0.5) * cw, y0 + (f64::from(j) + 0.5) * ch);
|
||||
let c = ramp.at(geom.param_at(kind, p) as f32);
|
||||
let c = ramp.at(spread(geom.param_at(kind, p)) as f32);
|
||||
std::array::from_fn(|k| {
|
||||
if k + 1 == N {
|
||||
return (c[k].clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
//! A repeating or reflecting gradient as one that pads, for formats whose gradients only pad
|
||||
//! past their ends: the stops repeated (every other run mirrored, for Reflect) as many times as
|
||||
//! the painted area needs, and the vector stretched over those runs.
|
||||
|
||||
use kurbo::{Point, Rect, Vec2};
|
||||
|
||||
use super::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientSpread, GradientStop};
|
||||
use crate::Color;
|
||||
|
||||
/// Most runs of the stops [`Gradient::padded_over`] writes.
|
||||
pub const MAX_SPREAD_RUNS: usize = 256;
|
||||
|
||||
/// Most stops [`Gradient::padded_over`] writes, all runs together.
|
||||
pub const MAX_SPREAD_STOPS: usize = 16384;
|
||||
|
||||
/// The farthest level from its center a radial or diamond gradient's runs are written out to by
|
||||
/// [`Gradient::padded_over`] (its stops' offsets, single-precision fractions of it, stay apart),
|
||||
/// nearer for stops closer together than a run ([`MIN_OFFSET_GAP`]).
|
||||
pub const MAX_SPREAD_LEVEL: f64 = 65536.0;
|
||||
|
||||
/// The least difference between two stops' offsets [`Gradient::padded_over`] writes as
|
||||
/// different: sixteen times single precision's step just below 1.
|
||||
const MIN_OFFSET_GAP: f64 = 1e-6;
|
||||
|
||||
/// A repeating or reflecting gradient written as one that pads ([`Gradient::padded_over`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Padded {
|
||||
/// The gradient with its stops repeated, padding past its ends.
|
||||
pub gradient: Gradient,
|
||||
/// Where those runs lie.
|
||||
pub geom: GradientGeom,
|
||||
/// Where along `geom` (0 to 1) the first run written starts: 0 for a linear gradient, the
|
||||
/// first run's level over the last one's outer level for a radial or diamond one.
|
||||
pub first: f64,
|
||||
/// How many runs are written, evenly spaced from [`Self::first`] to 1.
|
||||
pub runs: usize,
|
||||
/// The area needed more runs than [`MAX_SPREAD_RUNS`] (or more than half the stops allowed,
|
||||
/// two to a run), or runs past [`MAX_SPREAD_LEVEL`]: the gradient pads past the runs written.
|
||||
pub capped: bool,
|
||||
}
|
||||
|
||||
impl Gradient {
|
||||
/// A linear, radial or diamond gradient that repeats or reflects, placed at `geom`, as a
|
||||
/// gradient that pads and paints `area` the same way: its stops repeated, each run's
|
||||
/// placement [`GradientGeom::period`] of `geom`, as many runs as the area reaches (a radial or
|
||||
/// diamond from its first level, 0, the first stop's color inside the area's innermost run).
|
||||
/// `None` for a gradient that pads, a conic or
|
||||
/// freeform one, one without stops, and a placement whose levels at the corners are not
|
||||
/// finite.
|
||||
pub fn padded_over(&self, geom: &GradientGeom, area: Rect) -> Option<Padded> {
|
||||
self.padded_within(geom, area, MAX_SPREAD_STOPS)
|
||||
}
|
||||
|
||||
/// [`Self::padded_over`] with at most `max_stops` stops (and at least one run). When the runs
|
||||
/// written need more stops than that, each run leaves out the stops that change its colors
|
||||
/// least ([`fit_run`]), so every run is still written.
|
||||
pub fn padded_within(&self, geom: &GradientGeom, area: Rect, max_stops: usize) -> Option<Padded> {
|
||||
let kind = self.kind;
|
||||
if !self.is_spread() || matches!(kind, GradientKind::Conic | GradientKind::Freeform) || self.stops.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if self.mirrors_a_hue_turn() {
|
||||
return self.as_classic_curve().padded_within(geom, area, max_stops);
|
||||
}
|
||||
let period = geom.period(kind, self.repeat_count());
|
||||
let corners = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)];
|
||||
let ts = corners.map(|p| period.param_at(kind, p));
|
||||
if ts.iter().any(|t| !t.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let centered = kind.is_centered();
|
||||
// The level's range over the area. A linear gradient's extremes lie at corners. Radial and
|
||||
// diamond levels are nested convex rings from level 0: the largest at a corner, the
|
||||
// smallest 0 when the area holds the rings' center, else on its edge.
|
||||
let lo = if centered { inner_level(&period, kind, area).floor() } else { ts.iter().copied().fold(f64::INFINITY, f64::min).floor() };
|
||||
let hi = ts.iter().copied().fold(f64::NEG_INFINITY, f64::max).ceil().max(lo + 1.0);
|
||||
let budget = max_stops.min(MAX_SPREAD_STOPS);
|
||||
let most = MAX_SPREAD_RUNS.min(budget / 2).max(1);
|
||||
let capped = hi - lo > most as f64;
|
||||
// Capped, the runs kept are the area's innermost ones (radial and diamond), or (linear)
|
||||
// those around the vector's start where the area reaches it, else the area's runs nearest
|
||||
// to it.
|
||||
let lo = match capped {
|
||||
true if !centered => (-((most / 2) as f64)).clamp(lo, hi - most as f64),
|
||||
_ => lo,
|
||||
};
|
||||
let n = (hi - lo).min(most as f64).max(1.0);
|
||||
let one = fit_run(whole_run(&self.stops), budget / n as usize, self.method);
|
||||
// A radial or diamond writes its runs among the levels from 0, which its stops' offsets
|
||||
// (single-precision fractions of the outermost level) tell apart only so far out, the
|
||||
// nearer the closer its stops lie: past that, the runs end there and the gradient pads.
|
||||
let gap = one.windows(2).map(|w| f64::from(w[1].offset - w[0].offset)).filter(|d| *d > 0.0).fold(1.0, f64::min);
|
||||
// A whole level, so the runs keep their places (and Reflect its mirrored ones).
|
||||
let farthest = MAX_SPREAD_LEVEL.min(gap / MIN_OFFSET_GAP).floor().max(n);
|
||||
let far = centered && lo + n > farthest;
|
||||
let (lo, capped) = if far { ((farthest - n).max(0.0), true) } else { (lo, capped) };
|
||||
// `lo` is a whole number, possibly past what an integer holds: its parity in floating point.
|
||||
let first_odd = lo.rem_euclid(2.0) >= 1.0;
|
||||
let (stops, geom) = if centered {
|
||||
// The levels from 0, the runs from level `lo` (the first stop's color inside it).
|
||||
(self.runs(&one, first_odd, lo, n as usize, lo + n), period.levels_scaled(kind, lo + n))
|
||||
} else {
|
||||
let u = period.end - period.start;
|
||||
(
|
||||
self.runs(&one, first_odd, 0.0, n as usize, n),
|
||||
GradientGeom { start: period.start + u * lo, end: period.start + u * (lo + n), ..period },
|
||||
)
|
||||
};
|
||||
let gradient = Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() };
|
||||
let first = if centered { lo / (lo + n) } else { 0.0 };
|
||||
Some(Padded { gradient, geom, first, runs: n as usize, capped })
|
||||
}
|
||||
|
||||
/// The gradient as it runs from the start of its vector (0) to its end (1), as one that
|
||||
/// pads: a gradient that repeats or reflects with its stops repeated [`Self::repeat_count`]
|
||||
/// times between 0 and 1 (every other run mirrored, for Reflect), for what only shows that
|
||||
/// stretch (a gradient along or across a stroke, a swatch's preview). Others as they are.
|
||||
pub fn unrolled(&self) -> std::borrow::Cow<'_, Gradient> {
|
||||
self.unrolled_within(MAX_SPREAD_STOPS)
|
||||
}
|
||||
|
||||
/// [`Self::unrolled`] with at most `max_stops` stops: every run, each run without the stops
|
||||
/// that change its colors least ([`fit_run`]) when the runs need more stops than that. Only with
|
||||
/// fewer than two stops for each run do the runs past those that fit pad with the last one.
|
||||
pub fn unrolled_within(&self, max_stops: usize) -> std::borrow::Cow<'_, Gradient> {
|
||||
use std::borrow::Cow;
|
||||
if !self.is_spread() {
|
||||
return Cow::Borrowed(self);
|
||||
}
|
||||
// Without stops there is nothing to repeat: it pads all the same.
|
||||
if self.stops.is_empty() {
|
||||
return Cow::Owned(Gradient { spread: GradientSpread::Pad, repeats: 1, ..self.clone() });
|
||||
}
|
||||
if self.mirrors_a_hue_turn() {
|
||||
return Cow::Owned(self.as_classic_curve().unrolled_within(max_stops).into_owned());
|
||||
}
|
||||
let n = self.repeat_count() as usize;
|
||||
let budget = max_stops.min(MAX_SPREAD_STOPS);
|
||||
let kept = n.min(budget / 2).max(1);
|
||||
let one = fit_run(whole_run(&self.stops), budget / kept, self.method);
|
||||
let stops = self.runs(&one, false, 0.0, kept, n as f64);
|
||||
Cow::Owned(Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() })
|
||||
}
|
||||
|
||||
/// The gradient as [`Self::unrolled`] gives it with at most `max_stops` stops (at least two):
|
||||
/// a gradient that repeats or reflects as [`Self::unrolled_within`] gives it, and one that
|
||||
/// pads with more stops than that without the stops that change its colors least
|
||||
/// ([`fit_run`]). Others as they are.
|
||||
pub fn fitted(&self, max_stops: usize) -> std::borrow::Cow<'_, Gradient> {
|
||||
use std::borrow::Cow;
|
||||
if self.is_spread() {
|
||||
return self.unrolled_within(max_stops);
|
||||
}
|
||||
if self.stops.len() <= max_stops.max(2) {
|
||||
return Cow::Borrowed(self);
|
||||
}
|
||||
Cow::Owned(Gradient { stops: fit_run(whole_run(&self.stops), max_stops, self.method), ..self.clone() })
|
||||
}
|
||||
|
||||
/// One cycle of a gradient that repeats or reflects, which repeated end to end paints it, as
|
||||
/// a gradient that pads: one run of the stops (Repeat), or a run and its mirror (Reflect),
|
||||
/// between 0 and 1, and how many runs that is (1 or 2). `None` for a gradient that pads and
|
||||
/// one without stops.
|
||||
pub fn cycle(&self) -> Option<(Gradient, u32)> {
|
||||
if !self.is_spread() || self.stops.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if self.mirrors_a_hue_turn() {
|
||||
return self.as_classic_curve().cycle();
|
||||
}
|
||||
let one = whole_run(&self.stops);
|
||||
let runs = if self.spread == GradientSpread::Reflect { 2 } else { 1 };
|
||||
let stops = self.runs(&one, false, 0.0, runs, runs as f64);
|
||||
Some((Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() }, runs as u32))
|
||||
}
|
||||
|
||||
/// Does the gradient reflect while mixing around the hue wheel? A mirrored run of its stops
|
||||
/// would turn the wheel the other way, and one gradient has one method, so its runs are
|
||||
/// written from its curve's stops ([`Self::as_classic_curve`]), which mirror as they are.
|
||||
fn mirrors_a_hue_turn(&self) -> bool {
|
||||
self.method.is_hue() && self.spread == GradientSpread::Reflect
|
||||
}
|
||||
|
||||
/// `n` runs of `one` (one run of the stops, [`whole_run`]) on a line of `of` runs from 0 to 1,
|
||||
/// the first of them `start` runs along it and an odd-numbered run when `first_odd` (with
|
||||
/// Reflect, the odd-numbered runs are mirrored).
|
||||
fn runs(&self, one: &[GradientStop], first_odd: bool, start: f64, n: usize, of: f64) -> Vec<GradientStop> {
|
||||
let mirrored_run = (self.spread == GradientSpread::Reflect).then(|| mirror(one));
|
||||
let mut stops = Vec::with_capacity(one.len() * n);
|
||||
for j in 0..n {
|
||||
let run = match &mirrored_run {
|
||||
Some(m) if (j % 2 == 1) != first_odd => m.as_slice(),
|
||||
_ => one,
|
||||
};
|
||||
stops.extend(run.iter().map(|s| GradientStop { offset: ((start + j as f64 + f64::from(s.offset)) / of) as f32, ..s.clone() }));
|
||||
}
|
||||
stops
|
||||
}
|
||||
}
|
||||
|
||||
/// The smallest level of radial or diamond gradient `geom` over `area`, less a run (for rounding):
|
||||
/// 0 when the area holds the rings' center (a radial's focal point, a diamond's center), else the
|
||||
/// smallest along its sides, worked out in the gradient's unit frame from the sides' ends rather
|
||||
/// than from samples along them, so a long side does not hide a run near it. 0 for a placement
|
||||
/// without a frame.
|
||||
fn inner_level(geom: &GradientGeom, kind: GradientKind, area: Rect) -> f64 {
|
||||
let center = if kind == GradientKind::Radial { geom.focal_point() } else { geom.start };
|
||||
if area.contains(center) {
|
||||
return 0.0;
|
||||
}
|
||||
let frame = if kind == GradientKind::Diamond { geom.diamond_frame() } else { geom.unit_frame() };
|
||||
let Some(to_unit) = frame.map(|m| m.inverse()) else { return 0.0 };
|
||||
let focal = geom.focal.filter(|_| kind == GradientKind::Radial).map(|f| (to_unit * f).to_vec2());
|
||||
let corners = [Point::new(area.x0, area.y0), Point::new(area.x1, area.y0), Point::new(area.x1, area.y1), Point::new(area.x0, area.y1)]
|
||||
.map(|p| (to_unit * p).to_vec2());
|
||||
let mut least = f64::INFINITY;
|
||||
for (&a, &b) in corners.iter().zip(corners.iter().cycle().skip(1)) {
|
||||
let side = if kind == GradientKind::Diamond { diamond_least(a, b) } else { radial_least(a, b, focal) };
|
||||
least = least.min(side);
|
||||
}
|
||||
if least.is_finite() { (least - 1.0).max(0.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The smallest diamond level, |x| + |y| in its unit frame, on the segment from `a` to `b`: the
|
||||
/// level is linear between the points where the segment crosses an axis, so the smallest is at
|
||||
/// an end or at one of those crossings.
|
||||
fn diamond_least(a: Vec2, b: Vec2) -> f64 {
|
||||
let d = b - a;
|
||||
let crossings = [(d.x != 0.0).then(|| -a.x / d.x), (d.y != 0.0).then(|| -a.y / d.y)];
|
||||
[Some(0.0), Some(1.0), crossings[0], crossings[1]]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|u| (0.0..=1.0).contains(u))
|
||||
.map(|u| {
|
||||
let p = a + d * u;
|
||||
p.x.abs() + p.y.abs()
|
||||
})
|
||||
.fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// Halvings at most in [`radial_least`]: enough to bring any finite span below a quarter level.
|
||||
const RADIAL_HALVINGS: usize = 1100;
|
||||
|
||||
/// The smallest radial level on the segment from `a` to `b` in the unit frame, at most a quarter
|
||||
/// level under it: the distance to the center for a centered radial. An off-center radial's level
|
||||
/// `t` is the circle of radius `t` about `f`(1 − `t`), `f` its focal point; the segment's distance
|
||||
/// from that center less `t` falls as `t` grows (the center moves |`f`| < 1 per level), and the
|
||||
/// smallest level is where it reaches 0, found by halving. 0 for a focal point not inside the
|
||||
/// extent ellipse.
|
||||
fn radial_least(a: Vec2, b: Vec2, focal: Option<Vec2>) -> f64 {
|
||||
let Some(f) = focal else { return distance_to_segment(a, b, Vec2::ZERO) };
|
||||
let reach = f.hypot();
|
||||
if reach.is_nan() || reach >= 1.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let past = |t: f64| distance_to_segment(a, b, f * (1.0 - t)) <= t;
|
||||
// At this level the circle reaches the segment's nearest point to the ellipse's center.
|
||||
let mut hi = (distance_to_segment(a, b, Vec2::ZERO) / (1.0 - reach)).max(1.0);
|
||||
let mut lo = 0.0;
|
||||
if !hi.is_finite() || past(lo) {
|
||||
return 0.0;
|
||||
}
|
||||
for _ in 0..RADIAL_HALVINGS {
|
||||
let mid = lo + (hi - lo) / 2.0;
|
||||
if hi - lo <= 0.25 || mid <= lo || mid >= hi {
|
||||
break;
|
||||
}
|
||||
if past(mid) { hi = mid } else { lo = mid }
|
||||
}
|
||||
lo
|
||||
}
|
||||
|
||||
/// How far `c` is from the segment from `a` to `b`.
|
||||
fn distance_to_segment(a: Vec2, b: Vec2, c: Vec2) -> f64 {
|
||||
let d = b - a;
|
||||
let along = (c - a).dot(d) / d.hypot2();
|
||||
let u = if along.is_finite() { along.clamp(0.0, 1.0) } else { 0.0 };
|
||||
(a + d * u - c).hypot()
|
||||
}
|
||||
|
||||
/// The stops of one run, from offset 0 to 1: the end colors held out to the ends.
|
||||
fn whole_run(stops: &[GradientStop]) -> Vec<GradientStop> {
|
||||
let mut out = stops.to_vec();
|
||||
if let Some(first) = out.first().filter(|s| s.offset > 0.0).cloned() {
|
||||
out.insert(0, GradientStop { offset: 0.0, ..first });
|
||||
}
|
||||
if let Some(last) = out.last_mut() {
|
||||
// The last stop's midpoint leads nowhere; the copy at 1 takes over.
|
||||
if last.offset < 1.0 {
|
||||
let end = GradientStop { offset: 1.0, ..last.clone() };
|
||||
out.push(end);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `one` (a run of a gradient's stops, [`whole_run`]) with at most `budget` stops (at least two):
|
||||
/// as it is when it fits, else without the stops that change its colors least, left out one at a
|
||||
/// time. Leaving out a stop costs how far its color lies from the one that mixing the stops still
|
||||
/// on either side of it by `method` gives there, and how far its CMYK inks, opacity, tint or
|
||||
/// process plates lie from the line between theirs (a whole unit when its swatch link or color
|
||||
/// model differs from either of theirs, and a whole unit more when its midpoint or the one before
|
||||
/// it is off center), so the ends, sharp steps, ink changes and shaped spans stay. A stop whose
|
||||
/// next stop was left out gets its midpoint centered. The work is the stops times their logarithm.
|
||||
fn fit_run(one: Vec<GradientStop>, budget: usize, method: GradientMethod) -> Vec<GradientStop> {
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::BinaryHeap;
|
||||
let budget = budget.max(2);
|
||||
let n = one.len();
|
||||
if n <= budget {
|
||||
return one;
|
||||
}
|
||||
let mix = |x: &Color, y: &Color, v: f32| match method {
|
||||
GradientMethod::Classic => x.lerp_keep_model(y, v),
|
||||
m => m.mix(x, y, v),
|
||||
};
|
||||
let cost = |a: &GradientStop, s: &GradientStop, b: &GradientStop| -> u32 {
|
||||
let span = b.offset - a.offset;
|
||||
let u = if span > 0.0 { ((s.offset - a.offset) / span).clamp(0.0, 1.0) } else { 0.0 };
|
||||
// Left out, the span from `a` to `b` has a centered midpoint, so it mixes them by `u`.
|
||||
let (want, cs) = (mix(&a.color, &b.color, u).to_rgb(), s.color.to_rgb());
|
||||
let color = (0..3).map(|k| (want[k] - cs[k]).abs()).fold(0.0, f32::max);
|
||||
let opacity = (a.opacity + (b.opacity - a.opacity) * u - s.opacity).abs();
|
||||
// Process inks, which colors that look alike can print differently: off their line, or a
|
||||
// change of color model.
|
||||
let process = match (&a.color, &s.color, &b.color) {
|
||||
(Color::Cmyk { c: c0, m: m0, y: y0, k: k0 }, Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c1, m: m1, y: y1, k: k1 }) => {
|
||||
[(c0, c, c1), (m0, m, m1), (y0, y, y1), (k0, k, k1)].iter().map(|(p, q, r)| (*p + (*r - *p) * u - *q).abs()).fold(0.0, f32::max)
|
||||
}
|
||||
_ if a.color.model() == s.color.model() && s.color.model() == b.color.model() => 0.0,
|
||||
_ => 1.0,
|
||||
};
|
||||
let color = color.max(process);
|
||||
// Separations: a change of swatch link, or of tint or process plates off their line.
|
||||
let ink = if s.swatch != a.swatch || s.swatch != b.swatch {
|
||||
1.0
|
||||
} else {
|
||||
let tint = (a.tint + (b.tint - a.tint) * u - s.tint).abs();
|
||||
let plates = match (a.plates, s.plates, b.plates) {
|
||||
(None, None, None) => 0.0,
|
||||
(Some(pa), Some(ps), Some(pb)) => (0..4).map(|k| (pa[k] + (pb[k] - pa[k]) * u - ps[k]).abs()).fold(0.0, f32::max),
|
||||
_ => 1.0,
|
||||
};
|
||||
tint.max(plates)
|
||||
};
|
||||
// Leaving it out merges two spans, and an off-center midpoint shapes one of them.
|
||||
let shaped = if [a.midpoint, s.midpoint].iter().any(|m| (m - 0.5).abs() > 1e-3) { 1.0 } else { 0.0 };
|
||||
// Non-negative, so the bits order as the numbers do (NaN counts as 0).
|
||||
(color.max(opacity).max(ink) + shaped).max(0.0).to_bits()
|
||||
};
|
||||
// The stops still kept on either side of each stop, and each stop's latest cost entry.
|
||||
let mut prev: Vec<usize> = (0..n).map(|i| i.saturating_sub(1)).collect();
|
||||
let mut next: Vec<usize> = (1..=n).collect();
|
||||
let mut gone = vec![false; n];
|
||||
let mut version = vec![0u32; n];
|
||||
let mut heap: BinaryHeap<Reverse<(u32, usize, u32)>> = (1..n - 1).map(|i| Reverse((cost(&one[i - 1], &one[i], &one[i + 1]), i, 0))).collect();
|
||||
let mut left = n;
|
||||
while left > budget {
|
||||
let Some(Reverse((_, i, v))) = heap.pop() else { break };
|
||||
if gone[i] || v != version[i] {
|
||||
continue;
|
||||
}
|
||||
gone[i] = true;
|
||||
left -= 1;
|
||||
let (a, b) = (prev[i], next[i]);
|
||||
next[a] = b;
|
||||
prev[b] = a;
|
||||
for j in [a, b] {
|
||||
if j != 0 && j != n - 1 {
|
||||
version[j] += 1;
|
||||
heap.push(Reverse((cost(&one[prev[j]], &one[j], &one[next[j]]), j, version[j])));
|
||||
}
|
||||
}
|
||||
}
|
||||
one.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| !gone[*i])
|
||||
.map(|(i, s)| if next[i] == i + 1 { s } else { GradientStop { midpoint: 0.5, ..s } })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A run mirrored: the stops in reverse, each midpoint measured from the other side.
|
||||
fn mirror(run: &[GradientStop]) -> Vec<GradientStop> {
|
||||
let mut g = Gradient::new(GradientKind::Linear, run.to_vec());
|
||||
g.reverse();
|
||||
g.stops
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,520 @@
|
||||
use kurbo::Vec2;
|
||||
|
||||
use super::*;
|
||||
use crate::gradient::{GradientPaint, MAX_REPEATS};
|
||||
use crate::{Color, GradientMethod};
|
||||
|
||||
fn spread(kind: GradientKind, spread: GradientSpread, repeats: u32) -> Gradient {
|
||||
Gradient { spread, repeats, ..Gradient::new(kind, Gradient::default().stops) }
|
||||
}
|
||||
|
||||
fn black_white() -> Vec<GradientStop> {
|
||||
let mut a = GradientStop::new(0.0, Color::BLACK);
|
||||
a.midpoint = 0.3;
|
||||
vec![a, GradientStop::new(1.0, Color::WHITE)]
|
||||
}
|
||||
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-9
|
||||
}
|
||||
|
||||
/// Repeat wraps the parameter, `repeats` times along the vector and on past both ends; Reflect
|
||||
/// runs every other run backwards; Pad leaves it to the stops to clamp; a freeform gradient has
|
||||
/// no ends to spread past.
|
||||
#[test]
|
||||
fn spread_maps_the_parameter_to_a_place_along_the_stops() {
|
||||
let repeat = spread(GradientKind::Linear, GradientSpread::Repeat, 3);
|
||||
for (t, want) in [(0.0, 0.0), (0.1, 0.3), (0.5, 0.5), (1.0 / 3.0 + 0.1, 0.3), (1.1, 0.3), (-0.1, 0.7)] {
|
||||
assert!(close(repeat.spread_param(t), want), "repeat {t}: {}", repeat.spread_param(t));
|
||||
}
|
||||
let reflect = spread(GradientKind::Radial, GradientSpread::Reflect, 3);
|
||||
for (t, want) in [(0.0, 0.0), (0.1, 0.3), (1.0 / 3.0 + 0.1, 0.7), (2.0 / 3.0 + 0.1, 0.3), (1.0, 1.0), (-0.1, 0.3)] {
|
||||
assert!(close(reflect.spread_param(t), want), "reflect {t}: {}", reflect.spread_param(t));
|
||||
}
|
||||
let pad = spread(GradientKind::Linear, GradientSpread::Pad, 3);
|
||||
assert_eq!((pad.spread_param(1.7), pad.spread_param(-0.2)), (1.7, -0.2));
|
||||
let free = spread(GradientKind::Freeform, GradientSpread::Repeat, 3);
|
||||
assert_eq!(free.spread_param(0.7), 0.7);
|
||||
assert!(!free.is_spread() && !pad.is_spread() && repeat.is_spread());
|
||||
assert!(repeat.spread_param(f64::NAN).is_nan());
|
||||
// A count out of range (set in code) counts as the nearest one in range.
|
||||
assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 0).repeat_count(), 1);
|
||||
assert_eq!(spread(GradientKind::Linear, GradientSpread::Repeat, 5000).repeat_count(), MAX_REPEATS);
|
||||
}
|
||||
|
||||
/// The native format writes the spread and count only when they are not Pad and 1, reads a file
|
||||
/// without them as Pad and 1, and reads an unknown spread or a count out of range as the nearest
|
||||
/// one it can hold.
|
||||
#[test]
|
||||
fn the_file_keeps_the_spread_and_reads_bad_values_leniently() {
|
||||
let plain = serde_json::to_value(Gradient::default()).unwrap();
|
||||
assert!(plain.get("spread").is_none() && plain.get("repeats").is_none(), "{plain}");
|
||||
let g = spread(GradientKind::Conic, GradientSpread::Reflect, 4);
|
||||
let v = serde_json::to_value(&g).unwrap();
|
||||
assert_eq!((v["spread"].as_str(), v["repeats"].as_u64()), (Some("Reflect"), Some(4)));
|
||||
assert_eq!(serde_json::from_value::<Gradient>(v).unwrap(), g);
|
||||
let read = |spread: serde_json::Value, repeats: serde_json::Value| {
|
||||
let mut v = serde_json::to_value(Gradient::default()).unwrap();
|
||||
v["spread"] = spread;
|
||||
v["repeats"] = repeats;
|
||||
let g: Gradient = serde_json::from_value(v).unwrap();
|
||||
(g.spread, g.repeats)
|
||||
};
|
||||
assert_eq!(read("Repeat".into(), 3.4.into()), (GradientSpread::Repeat, 3));
|
||||
assert_eq!(read("Spiral".into(), (-5).into()), (GradientSpread::Pad, 1));
|
||||
assert_eq!(read(7.into(), 1e12.into()), (GradientSpread::Pad, MAX_REPEATS));
|
||||
assert_eq!(read(serde_json::Value::Null, "many".into()), (GradientSpread::Pad, 1));
|
||||
let missing: Gradient = serde_json::from_value(serde_json::json!({"kind": "Linear", "stops": []})).unwrap();
|
||||
assert_eq!((missing.spread, missing.repeats), (GradientSpread::Pad, 1));
|
||||
}
|
||||
|
||||
/// One run's placement: a level of the period is the gradient's level times the count, for
|
||||
/// linear, diamond and off-center radial gradients; a conic keeps its placement.
|
||||
#[test]
|
||||
fn a_period_holds_one_run_of_the_stops() {
|
||||
let p = Point::new(72.0, 61.0);
|
||||
let linear = GradientGeom { start: Point::new(10.0, 20.0), end: Point::new(60.0, 40.0), aspect: 1.0, focal: None };
|
||||
let radial = GradientGeom { start: Point::new(50.0, 50.0), end: Point::new(60.0, 50.0), aspect: 0.6, focal: Some(Point::new(55.0, 52.0)) };
|
||||
let diamond = GradientGeom { end: Point::new(58.0, 56.0), focal: None, ..radial };
|
||||
for (kind, geom) in [(GradientKind::Linear, linear), (GradientKind::Radial, radial), (GradientKind::Diamond, diamond)] {
|
||||
let period = geom.period(kind, 4);
|
||||
assert!(close(period.param_at(kind, p), 4.0 * geom.param_at(kind, p)), "{kind:?}");
|
||||
assert_eq!(period.focal, geom.focal, "{kind:?}");
|
||||
}
|
||||
assert_eq!(radial.period(GradientKind::Conic, 4), radial);
|
||||
assert_eq!(linear.period(GradientKind::Linear, 0), linear, "a count of 0 counts as 1");
|
||||
}
|
||||
|
||||
/// The stops repeated over the area: as many runs as its corners reach, each in place.
|
||||
#[test]
|
||||
fn a_linear_gradient_pads_with_its_stops_repeated_over_the_area() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(20.0, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(-5.0, 0.0, 25.0, 10.0)).unwrap();
|
||||
assert!(!p.capped);
|
||||
// Runs of 10 from -10 to 30: four of them.
|
||||
assert_eq!((p.geom.start, p.geom.end), (Point::new(-10.0, 0.0), Point::new(30.0, 0.0)));
|
||||
let offsets: Vec<f32> = p.gradient.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0]);
|
||||
assert!(p.gradient.stops.iter().step_by(2).all(|s| s.color == Color::BLACK && (s.midpoint - 0.3).abs() < 1e-6));
|
||||
assert_eq!((p.gradient.spread, p.gradient.repeats), (GradientSpread::Pad, 1));
|
||||
// Every point gets the color the gradient gives it.
|
||||
for x in [-4.0, 1.0, 7.5, 13.0, 24.0] {
|
||||
let q = Point::new(x, 5.0);
|
||||
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Linear, q)) as f32).0;
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0;
|
||||
assert!(want.to_rgb().iter().zip(got.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-4), "{x}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflect_mirrors_every_other_run_and_its_midpoints() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 20.0, 10.0)).unwrap();
|
||||
let colors: Vec<Color> = p.gradient.stops.iter().map(|s| s.color).collect();
|
||||
assert_eq!(colors, [Color::BLACK, Color::WHITE, Color::WHITE, Color::BLACK]);
|
||||
// Black → white with the midpoint at 0.3 mirrors to white → black with it at 0.7.
|
||||
assert!((p.gradient.stops[2].midpoint - 0.7).abs() < 1e-6, "{:?}", p.gradient.stops);
|
||||
}
|
||||
|
||||
/// A gradient mixed around the hue wheel that reflects: a mirrored run turns the wheel back the
|
||||
/// way it came, so every point keeps its color when the runs are written out as a gradient that
|
||||
/// pads, unrolled along the vector, or as one cycle, with a repeating one's too.
|
||||
#[test]
|
||||
fn reflected_and_repeated_hue_turns_keep_every_color() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
|
||||
let stops = || {
|
||||
let mut red = GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0));
|
||||
red.midpoint = 0.3;
|
||||
vec![red, GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))]
|
||||
};
|
||||
let near = |a: Color, b: Color, what: &str| {
|
||||
assert!(a.to_rgb().iter().zip(b.to_rgb()).all(|(x, y)| (x - y).abs() < 1.0 / 255.0), "{what}: {a:?} vs {b:?}");
|
||||
};
|
||||
for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] {
|
||||
for spread in [GradientSpread::Reflect, GradientSpread::Repeat] {
|
||||
let g = Gradient { method, spread, repeats: 2, ..Gradient::new(GradientKind::Linear, stops()) };
|
||||
let p = g.padded_over(&geom, Rect::new(-10.0, 0.0, 20.0, 10.0)).unwrap();
|
||||
assert_eq!((p.gradient.spread, p.gradient.repeats), (GradientSpread::Pad, 1));
|
||||
for k in 0..300 {
|
||||
let q = Point::new(-10.0 + f64::from(k) * 0.1 + 0.013, 5.0);
|
||||
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Linear, q)) as f32).0;
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0;
|
||||
near(want, got, &format!("{method:?} {spread:?} padded at {}", q.x));
|
||||
}
|
||||
let unrolled = g.unrolled();
|
||||
let (cycle, runs) = g.cycle().unwrap();
|
||||
for k in 0..=200 {
|
||||
let t = (k as f32 + 0.37) / 201.0;
|
||||
let want = g.sample(g.spread_param(f64::from(t)) as f32).0;
|
||||
near(want, unrolled.sample(t).0, &format!("{method:?} {spread:?} unrolled at {t}"));
|
||||
// One cycle covers `runs` of the two runs between 0 and 1.
|
||||
let along = t * runs as f32 / 2.0;
|
||||
let want = g.sample(g.spread_param(f64::from(along)) as f32).0;
|
||||
near(want, cycle.sample(t).0, &format!("{method:?} {spread:?} cycle at {t}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_inside_a_run_hold_their_colors_to_its_ends() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None };
|
||||
let stops = vec![GradientStop::new(0.25, Color::BLACK), GradientStop::new(0.75, Color::WHITE)];
|
||||
let g = Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Linear, stops) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 20.0, 10.0)).unwrap();
|
||||
let offsets: Vec<f32> = p.gradient.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.0, 0.125, 0.375, 0.5, 0.5, 0.625, 0.875, 1.0]);
|
||||
}
|
||||
|
||||
/// An off-center radial grows about its focal point, a diamond about its center; every point
|
||||
/// keeps its color.
|
||||
#[test]
|
||||
fn radial_and_diamond_gradients_pad_in_rings_from_their_first_level() {
|
||||
let c = Point::new(50.0, 50.0);
|
||||
let radial = GradientGeom { start: c, end: Point::new(60.0, 50.0), aspect: 1.0, focal: Some(Point::new(55.0, 50.0)) };
|
||||
let diamond = GradientGeom { focal: None, ..radial };
|
||||
for (kind, geom) in [(GradientKind::Radial, radial), (GradientKind::Diamond, diamond)] {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 2, ..Gradient::new(kind, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 100.0, 100.0)).unwrap();
|
||||
assert!(p.gradient.stops.len() / 2 >= 10, "{kind:?}: {}", p.gradient.stops.len());
|
||||
assert_eq!(p.geom.focal, geom.focal);
|
||||
for q in [Point::new(72.0, 61.0), Point::new(10.0, 95.0), Point::new(52.0, 49.0)] {
|
||||
let want = g.sample(g.spread_param(geom.param_at(kind, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 1e-4), "{kind:?} {q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A run of the stops far too short for the area is written with at most so many runs, and pads
|
||||
/// past them; a gradient of many stops is written with every run the area needs, each run
|
||||
/// without the stops that change its colors least, within so many stops; a conic, a padding
|
||||
/// gradient and one without stops have nothing to pad.
|
||||
#[test]
|
||||
fn far_repeats_are_capped_and_many_stops_are_sampled() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.01, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap();
|
||||
assert!(p.capped);
|
||||
assert_eq!(p.gradient.stops.len(), 2 * MAX_SPREAD_RUNS);
|
||||
let many: Vec<GradientStop> = (0..=4000).map(|i| GradientStop::new(i as f32 / 4000.0, Color::gray(i as f32 / 4000.0))).collect();
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 50, ..Gradient::new(GradientKind::Linear, many) };
|
||||
let wide = GradientGeom { end: Point::new(100.0, 0.0), ..geom };
|
||||
let p = g.padded_over(&wide, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap();
|
||||
assert!(!p.capped && p.runs == 50 && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{} {}", p.runs, p.gradient.stops.len());
|
||||
for x in [0.7, 33.3, 66.1, 99.5] {
|
||||
let q = Point::new(x, 0.5);
|
||||
let want = g.sample(g.spread_param(wide.param_at(GradientKind::Linear, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{x}: {want:?} vs {got:?}");
|
||||
}
|
||||
assert!(g.unrolled().stops.len() <= MAX_SPREAD_STOPS);
|
||||
assert!(p.gradient.padded_over(&p.geom, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none(), "it pads");
|
||||
assert!(spread(GradientKind::Conic, GradientSpread::Repeat, 3).padded_over(&wide, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none());
|
||||
let empty = Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Linear, vec![]) };
|
||||
assert!(empty.padded_over(&wide, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none());
|
||||
}
|
||||
|
||||
/// The runs written are the ones the area shows: a radial or diamond centered a thousand runs
|
||||
/// from the area writes the hundred it crosses, not the first 256 from the center; a linear
|
||||
/// gradient over an area of 1,100 runs far before its start, capped, keeps the runs nearest it.
|
||||
/// Every point checked gets the color the gradient gives it.
|
||||
#[test]
|
||||
fn the_runs_written_cover_a_distant_area() {
|
||||
let centered = GradientGeom { start: Point::new(0.0, 50.0), end: Point::new(1.0, 50.0), aspect: 1.0, focal: None };
|
||||
let before = GradientGeom { start: Point::new(5000.0, 0.0), end: Point::new(5001.0, 0.0), aspect: 1.0, focal: None };
|
||||
for (kind, geom, area) in [
|
||||
(GradientKind::Radial, centered, Rect::new(1000.0, 0.0, 1100.0, 100.0)),
|
||||
(GradientKind::Diamond, centered, Rect::new(1000.0, 0.0, 1100.0, 100.0)),
|
||||
(GradientKind::Linear, before, Rect::new(0.0, 0.0, 1100.0, 100.0)),
|
||||
] {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(kind, black_white()) };
|
||||
let p = g.padded_over(&geom, area).unwrap();
|
||||
assert_eq!(p.capped, kind == GradientKind::Linear, "{kind:?}");
|
||||
assert!(p.gradient.stops.len() <= MAX_SPREAD_STOPS);
|
||||
for q in [Point::new(1000.5, 0.5), Point::new(1050.25, 50.0), Point::new(1099.5, 99.5), Point::new(1010.75, 90.0)] {
|
||||
let want = g.sample(g.spread_param(geom.param_at(kind, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{kind:?} {q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tiny radial centered just outside the area, beside a side between any evenly spaced
|
||||
/// samples of it: the runs written start from the area's true innermost level.
|
||||
#[test]
|
||||
fn the_innermost_level_is_found_between_samples() {
|
||||
let c = Point::new(-0.0005, 7.8125);
|
||||
let geom = GradientGeom { start: c, end: c + Vec2::new(0.001, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Radial, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 1000.0, 1000.0)).unwrap();
|
||||
for q in [Point::new(0.05, 7.8125), Point::new(0.1, 7.9)] {
|
||||
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Radial, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Radial, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An area four billion units wide whose long side passes 50 runs from a tiny radial or diamond's
|
||||
/// center: the runs written start from that side's true innermost level, so the runs beside it
|
||||
/// keep their colors.
|
||||
#[test]
|
||||
fn the_innermost_level_is_found_along_a_very_long_side() {
|
||||
let area = Rect::new(-1.3e9, 0.0, 2.9e9, 1.0);
|
||||
for x in [0.3, 12345.678, -7777.25, 98765.4321] {
|
||||
let c = Point::new(x, -0.00005);
|
||||
let run = GradientGeom { start: c, end: c + Vec2::new(1e-6, 0.0), aspect: 1.0, focal: None };
|
||||
let off_center = GradientGeom { focal: Some(c + Vec2::new(0.5e-6, 0.0)), ..run };
|
||||
for (kind, geom) in [(GradientKind::Diamond, run), (GradientKind::Radial, run), (GradientKind::Radial, off_center)] {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(kind, black_white()) };
|
||||
let p = g.padded_over(&geom, area).unwrap();
|
||||
assert!(p.capped, "{kind:?}");
|
||||
for q in [Point::new(x, 1e-5), Point::new(x + 2e-5, 2e-5), Point::new(x - 1e-5, 0.0001)] {
|
||||
let level = geom.param_at(kind, q);
|
||||
assert!((40.0..200.0).contains(&level), "{kind:?} {q:?}: level {level}");
|
||||
let want = g.sample(g.spread_param(level) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(kind, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{kind:?} {q:?}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a billion levels from a radial's center are past what the stops' offsets can tell apart:
|
||||
/// the gradient is written capped, its stops still apart and in order.
|
||||
#[test]
|
||||
fn runs_too_far_from_the_center_are_capped() {
|
||||
let c = Point::new(0.0, 0.0);
|
||||
let geom = GradientGeom { start: c, end: c + Vec2::new(1e-6, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Radial, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(1000.0, 0.0, 1000.0001, 0.0001)).unwrap();
|
||||
assert!(p.capped);
|
||||
assert!(p.gradient.stops.windows(2).all(|w| w[0].offset <= w[1].offset), "in order");
|
||||
let distinct = p.gradient.stops.windows(2).filter(|w| w[1].offset > w[0].offset).count();
|
||||
assert!(distinct * 2 + 2 >= p.gradient.stops.len(), "the runs stay apart: {distinct} of {}", p.gradient.stops.len());
|
||||
}
|
||||
|
||||
/// A run of 1,000 close stops is written only as far out as their offsets stay apart: around
|
||||
/// level 50,000 it is capped, every stop written apart from the next.
|
||||
#[test]
|
||||
fn close_stops_are_written_only_where_they_stay_apart() {
|
||||
let many: Vec<GradientStop> = (0..=1000).map(|i| GradientStop::new(i as f32 / 1000.0, Color::gray(i as f32 / 1000.0))).collect();
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.001, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 1, ..Gradient::new(GradientKind::Diamond, many) };
|
||||
let p = g.padded_over(&geom, Rect::new(50.0, 0.0, 50.002, 0.002)).unwrap();
|
||||
assert!(p.capped);
|
||||
// Only where one run meets the next do two stops share an offset.
|
||||
let runs = p.gradient.stops.len() / 1001;
|
||||
let shared = p.gradient.stops.windows(2).filter(|w| w[1].offset <= w[0].offset).count();
|
||||
assert!(shared < runs, "{shared} stops share an offset in {runs} runs");
|
||||
// Stops 0.0001234 of a run apart are written out to level 123, on whole runs: an area within
|
||||
// it gets the gradient's colors, Reflect's mirrored runs included.
|
||||
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(0.0001234, Color::gray(0.5)), GradientStop::new(1.0, Color::WHITE)];
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 1, ..Gradient::new(GradientKind::Diamond, stops) };
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(1.0, 0.0), aspect: 1.0, focal: None };
|
||||
let p = g.padded_over(&geom, Rect::new(121.0, 0.0, 123.9, 0.2)).unwrap();
|
||||
assert!(p.capped, "past level 123 it pads");
|
||||
for x in [121.3, 121.9, 122.5] {
|
||||
let q = Point::new(x, 0.1);
|
||||
let want = g.sample(g.spread_param(geom.param_at(GradientKind::Diamond, q)) as f32).0.to_rgb();
|
||||
let got = p.gradient.sample(p.geom.param_at(GradientKind::Diamond, q) as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{x}: {want:?} vs {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A piece of a gradient that starts where two runs meet (a gradient along a stroke, sliced at a
|
||||
/// corner there) starts with the new run's first color, not the old run's last.
|
||||
#[test]
|
||||
fn a_piece_starting_at_a_sharp_step_takes_the_color_after_it() {
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, Gradient::default().stops) };
|
||||
let piece = g.unrolled().span(0.5, 1.0);
|
||||
assert_eq!(piece.stops.first().map(|s| s.color), Some(Color::WHITE), "{:?}", piece.stops);
|
||||
assert_eq!(piece.stops.last().map(|s| s.color), Some(Color::BLACK));
|
||||
let before = g.unrolled().span(0.0, 0.5);
|
||||
assert_eq!((before.stops[0].color, before.stops.last().unwrap().color), (Color::WHITE, Color::BLACK));
|
||||
}
|
||||
|
||||
/// An area very far past a very short reflecting vector (a file's numbers) is padded without the
|
||||
/// run count overflowing.
|
||||
#[test]
|
||||
fn a_far_area_pads_without_overflowing() {
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(1e-300, 0.0), aspect: 1.0, focal: None };
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let p = g.padded_over(&geom, Rect::new(1e3, 0.0, 2e3, 1.0));
|
||||
assert!(p.is_none_or(|p| p.gradient.stops.len() <= MAX_SPREAD_STOPS));
|
||||
// Runs of 1e-8: the area's levels lie past 1e19, more than an integer holds.
|
||||
let geom = GradientGeom { end: Point::new(1e-6, 0.0), ..geom };
|
||||
let p = g.padded_over(&geom, Rect::new(1e11, 0.0, 1e11 + 1.0, 1.0)).unwrap();
|
||||
assert!(p.capped && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{} {} {:?}", p.capped, p.gradient.stops.len(), p.geom);
|
||||
}
|
||||
|
||||
/// Unrolled, the stops run `repeats` times between 0 and 1 (every other run mirrored with
|
||||
/// Reflect); one cycle is a run, or a run and its mirror.
|
||||
#[test]
|
||||
fn unrolled_and_cycle_stops() {
|
||||
let g = Gradient { spread: GradientSpread::Reflect, repeats: 3, ..Gradient::new(GradientKind::Linear, black_white()) };
|
||||
let u = g.unrolled();
|
||||
let offsets: Vec<f32> = u.stops.iter().map(|s| (s.offset * 3.0).round()).collect();
|
||||
assert_eq!(offsets, [0.0, 1.0, 1.0, 2.0, 2.0, 3.0]);
|
||||
let colors: Vec<Color> = u.stops.iter().map(|s| s.color).collect();
|
||||
assert_eq!(colors, [Color::BLACK, Color::WHITE, Color::WHITE, Color::BLACK, Color::BLACK, Color::WHITE]);
|
||||
for t in [0.05, 0.4, 0.71, 0.99] {
|
||||
let (a, b) = (g.sample(g.spread_param(t) as f32).0.to_rgb(), u.sample(t as f32).0.to_rgb());
|
||||
assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4), "{t}");
|
||||
}
|
||||
let (cycle, runs) = g.cycle().unwrap();
|
||||
assert_eq!((runs, cycle.stops.len()), (2, 4));
|
||||
let repeat = Gradient { spread: GradientSpread::Repeat, ..g.clone() };
|
||||
assert_eq!(repeat.cycle().unwrap().1, 1);
|
||||
assert!(Gradient::default().cycle().is_none());
|
||||
assert!(matches!(Gradient::default().unrolled(), std::borrow::Cow::Borrowed(_)));
|
||||
}
|
||||
|
||||
/// A gradient of more stops than [`MAX_SPREAD_STOPS`] allows for all its runs keeps every run
|
||||
/// when unrolled, each run without the stops that change its colors least: its last run ends on
|
||||
/// its last color instead of the rest padding with it.
|
||||
#[test]
|
||||
fn unrolled_many_stops_keep_every_run() {
|
||||
let stops: Vec<GradientStop> = (0..200).map(|i| GradientStop::new(i as f32 / 199.0, Color::gray(i as f32 / 199.0))).collect();
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, stops) };
|
||||
let u = g.unrolled();
|
||||
assert!(u.stops.len() <= MAX_SPREAD_STOPS, "{}", u.stops.len());
|
||||
for t in [0.005, 0.5051, 0.9149, 0.9951] {
|
||||
let want = g.sample(g.spread_param(t) as f32).0.to_rgb();
|
||||
let got = u.sample(t as f32).0.to_rgb();
|
||||
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{t}: {want:?} vs {got:?}");
|
||||
}
|
||||
// A padding gradient fitted to fewer stops keeps its ends.
|
||||
let pad = Gradient::new(GradientKind::Linear, g.stops.clone());
|
||||
let fitted = pad.fitted(16);
|
||||
assert_eq!(fitted.stops.len(), 16);
|
||||
for (stop, want) in [(&fitted.stops[0], Color::gray(0.0)), (&fitted.stops[15], Color::gray(1.0))] {
|
||||
assert!(stop.color.to_rgb().iter().zip(want.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-5), "{:?}", stop.color);
|
||||
}
|
||||
assert!(matches!(pad.fitted(500), std::borrow::Cow::Borrowed(_)));
|
||||
}
|
||||
|
||||
/// One run of more stops than the limit (255 inside it, and a copy of each end color at 0 and 1)
|
||||
/// is written within the limit, every run the area needs included.
|
||||
#[test]
|
||||
fn a_run_over_the_stop_limit_is_written_within_it() {
|
||||
let stops: Vec<GradientStop> = (1..=255).map(|i| GradientStop::new(i as f32 / 256.0, Color::gray(i as f32 / 256.0))).collect();
|
||||
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, stops) };
|
||||
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(20.0, 0.0), aspect: 1.0, focal: None };
|
||||
let p = g.padded_within(&geom, Rect::new(0.0, 0.0, 20.0, 1.0), 256).unwrap();
|
||||
assert!(!p.capped && p.runs == 2 && p.gradient.stops.len() <= 256, "{} {} {}", p.capped, p.runs, p.gradient.stops.len());
|
||||
assert!(g.unrolled_within(256).stops.len() <= 256);
|
||||
}
|
||||
|
||||
/// Fitting a run to fewer stops keeps a narrow band between two sharp steps, a stop linked to a
|
||||
/// swatch, and each kept stop's link and tint, where sampling at evenly spaced places would lose
|
||||
/// them.
|
||||
#[test]
|
||||
fn fitting_keeps_sharp_steps_and_swatch_links() {
|
||||
let mut stops: Vec<GradientStop> = (0..300).map(|i| GradientStop::new(i as f32 / 299.0, Color::gray(i as f32 / 299.0))).collect();
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
// A band of red from 0.5003 to 0.5013, with a sharp step at each side.
|
||||
for (offset, color) in [(0.5003, None), (0.5003, Some(red)), (0.5013, Some(red)), (0.5013, None)] {
|
||||
let gray = Color::gray(offset);
|
||||
stops.push(GradientStop::new(offset, color.unwrap_or(gray)));
|
||||
}
|
||||
let spot = GradientStop { swatch: Some("Ink".into()), tint: 0.4, ..GradientStop::new(0.25, Color::gray(0.25)) };
|
||||
stops.push(spot.clone());
|
||||
// Three stops of one ink that look alike but print at different tints.
|
||||
for (offset, tint) in [(0.8, 0.2), (0.81, 0.9), (0.82, 0.2)] {
|
||||
stops.push(GradientStop { swatch: Some("Ink2".into()), tint, ..GradientStop::new(offset, Color::gray(offset)) });
|
||||
}
|
||||
// A span shaped by an off-center midpoint.
|
||||
if let Some(s) = stops.iter_mut().find(|s| (s.offset - 0.6).abs() < 2e-3) {
|
||||
s.midpoint = 0.13;
|
||||
}
|
||||
stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
|
||||
let g = Gradient::new(GradientKind::Linear, stops);
|
||||
let fitted = g.fitted(32);
|
||||
assert!(fitted.stops.len() <= 32, "{}", fitted.stops.len());
|
||||
let red_at = |t: f32| fitted.sample(t).0.to_rgb();
|
||||
assert_eq!(red_at(0.5008), [1.0, 0.0, 0.0], "the band stays");
|
||||
assert!(red_at(0.499)[1] > 0.4 && red_at(0.503)[1] > 0.4, "the band stays narrow");
|
||||
assert!(fitted.stops.iter().any(|s| s.swatch.as_deref() == Some("Ink") && s.tint == 0.4 && s.offset == 0.25), "{:?}", fitted.stops);
|
||||
assert!(fitted.stops.iter().any(|s| s.swatch.as_deref() == Some("Ink2") && s.tint == 0.9), "the tint change stays");
|
||||
assert!(fitted.stops.iter().any(|s| s.midpoint == 0.13), "the shaped span stays");
|
||||
// Of a stop that changes only its ink's tint and one that the colors' line nearly gives, the
|
||||
// first stays. (The stop before an ink starts stays as well: leaving it out would blend the
|
||||
// ink in sooner.)
|
||||
let ink = |offset: f32, tint: f32| GradientStop { swatch: Some("Ink2".into()), tint, ..GradientStop::new(offset, Color::gray(0.5)) };
|
||||
let few = vec![
|
||||
GradientStop::new(0.0, Color::gray(0.0)),
|
||||
GradientStop::new(0.2, Color::gray(0.17)),
|
||||
GradientStop::new(0.3, Color::gray(0.3)),
|
||||
ink(0.4, 0.2),
|
||||
ink(0.5, 0.9),
|
||||
ink(0.6, 0.2),
|
||||
GradientStop::new(1.0, Color::gray(1.0)),
|
||||
];
|
||||
let fitted = Gradient::new(GradientKind::Linear, few).fitted(6).into_owned();
|
||||
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.0, 0.3, 0.4, 0.5, 0.6, 1.0]);
|
||||
// A Perceptual gradient leaves out the stop its own mixing gives, not the one the RGB line
|
||||
// gives.
|
||||
let (blue, yellow, gray) = (Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 1.0, 0.0), Color::rgb(0.5, 0.5, 0.5));
|
||||
let on_curve = GradientMethod::Perceptual.mix(&gray, &yellow, 0.5);
|
||||
let stops = vec![GradientStop::new(0.0, blue), GradientStop::new(0.5, gray), GradientStop::new(0.75, on_curve), GradientStop::new(1.0, yellow)];
|
||||
let perceptual = Gradient { method: GradientMethod::Perceptual, ..Gradient::new(GradientKind::Linear, stops) };
|
||||
let fitted = perceptual.fitted(3).into_owned();
|
||||
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.0, 0.5, 1.0]);
|
||||
// A black of other inks between blacks that look the same prints differently: it stays.
|
||||
let k = |offset: f32| GradientStop::new(offset, Color::Cmyk { c: 1.0, m: 1.0, y: 1.0, k: 1.0 });
|
||||
let rich = GradientStop::new(0.5, Color::Cmyk { c: 0.6, m: 0.4, y: 0.4, k: 1.0 });
|
||||
let blacks = vec![k(0.0), k(0.4), rich, k(0.6), k(1.0)];
|
||||
let fitted = Gradient::new(GradientKind::Linear, blacks).fitted(3).into_owned();
|
||||
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
|
||||
assert_eq!(offsets, [0.0, 0.5, 1.0]);
|
||||
let spread = Gradient { spread: GradientSpread::Repeat, repeats: 4, ..g.clone() };
|
||||
let u = spread.unrolled_within(128);
|
||||
assert_eq!(u.stops.iter().filter(|s| s.swatch.as_deref() == Some("Ink")).count(), 4, "one linked stop a run");
|
||||
}
|
||||
|
||||
/// Pixels (what the canvas draws a diamond, dithered or Perceptual gradient as, and what SVG and
|
||||
/// PDF write as images) repeat with the stops, for each kind.
|
||||
#[test]
|
||||
fn pixels_repeat_and_reflect_for_every_kind() {
|
||||
let b = Rect::new(0.0, 0.0, 40.0, 40.0);
|
||||
let c = Point::new(20.0, 20.0);
|
||||
for kind in [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Diamond] {
|
||||
for sp in [GradientSpread::Repeat, GradientSpread::Reflect] {
|
||||
for method in [GradientMethod::Classic, GradientMethod::Perceptual] {
|
||||
let mut g = GradientPaint::new(Gradient { spread: sp, repeats: 3, method, ..Gradient::new(kind, Gradient::default().stops) });
|
||||
let geom = if kind == GradientKind::Linear {
|
||||
GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(40.0, 10.0), aspect: 1.0, focal: None }
|
||||
} else {
|
||||
GradientGeom { start: c, end: c + Vec2::new(18.0, 4.0), aspect: 0.8, focal: None }
|
||||
};
|
||||
g.geom = Some(geom);
|
||||
let px: Vec<[u8; 4]> = g.pixels(b, b, 40, 40, false, &Color::to_rgb).collect();
|
||||
for (i, got) in px.iter().enumerate().step_by(37) {
|
||||
let p = Point::new((i % 40) as f64 + 0.5, (i / 40) as f64 + 0.5);
|
||||
let t = g.gradient.spread_param(geom.param_at(kind, p));
|
||||
// Not where Repeat jumps from the last stop back to the first.
|
||||
if sp == GradientSpread::Repeat && !(0.03..0.97).contains(&t) {
|
||||
continue;
|
||||
}
|
||||
let want = g.gradient.sample(t as f32).0.to_rgba8(1.0);
|
||||
assert!(got[0].abs_diff(want[0]) <= 2, "{kind:?} {sp:?} {method:?} {p:?}: {got:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A conic gradient's wedges: as many for each time the stops run around as for one turn, at most
|
||||
/// so many.
|
||||
#[test]
|
||||
fn conic_wedges_count_each_run() {
|
||||
let g = spread(GradientKind::Conic, GradientSpread::Repeat, 4);
|
||||
assert_eq!(g.conic_wedge_count(360), 1440);
|
||||
assert_eq!(spread(GradientKind::Conic, GradientSpread::Pad, 4).conic_wedge_count(360), 360);
|
||||
assert_eq!(spread(GradientKind::Conic, GradientSpread::Reflect, MAX_REPEATS).conic_wedge_count(360), crate::gradient::MAX_CONIC_WEDGES);
|
||||
}
|
||||
@@ -514,6 +514,283 @@ fn perceptual_gradients_draw_as_pixels() {
|
||||
}
|
||||
}
|
||||
|
||||
fn two_stops(a: Color, b: Color, method: GradientMethod) -> Gradient {
|
||||
let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)]);
|
||||
g.method = method;
|
||||
g
|
||||
}
|
||||
|
||||
/// The hue methods mix around the hue wheel in one direction: Hue Counterclockwise raises the
|
||||
/// hue angle from each stop to the next and Hue Clockwise lowers it, by the fixed-direction rules
|
||||
/// of <https://www.w3.org/TR/css-color-4/#hue-interpolation> (the angles below are that
|
||||
/// section's own examples), with saturation and brightness changing evenly.
|
||||
#[test]
|
||||
fn hue_methods_turn_one_way_around_the_wheel() {
|
||||
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
let rising = two_stops(red, blue, GradientMethod::HueCounterclockwise);
|
||||
assert_eq!(rising.sample(0.0).0.to_hex(), "#ff0000");
|
||||
assert_eq!(rising.sample(0.25).0.to_hex(), "#ffff00", "60°");
|
||||
assert_eq!(rising.sample(0.5).0.to_hex(), "#00ff00", "120°");
|
||||
assert_eq!(rising.sample(1.0).0.to_hex(), "#0000ff");
|
||||
let falling = two_stops(red, blue, GradientMethod::HueClockwise);
|
||||
assert_eq!(falling.sample(0.0).0.to_hex(), "#ff0000");
|
||||
assert_eq!(falling.sample(0.5).0.to_hex(), "#ff00ff", "300°");
|
||||
assert_eq!(falling.sample(1.0).0.to_hex(), "#0000ff");
|
||||
assert_eq!(two_stops(red, blue, GradientMethod::Classic).sample(0.5).0.to_rgb(), [0.5, 0.0, 0.5], "classic: the RGB mix");
|
||||
// 30° to 190° and to 230°: halfway is 110° and 130° rising, 290° and 310° falling.
|
||||
for (to, up, down) in [(190.0, 110.0, 290.0), (230.0, 130.0, 310.0)] {
|
||||
let (a, b) = (Color::from_hsb(30.0, 0.5, 0.8), Color::from_hsb(to, 0.9, 0.4));
|
||||
for (method, want) in [(GradientMethod::HueCounterclockwise, up), (GradientMethod::HueClockwise, down)] {
|
||||
let [h, s, v] = method.mix(&a, &b, 0.5).to_hsb();
|
||||
assert!((h - want).abs() < 0.05, "{method:?} to {to}: hue {h}, not {want}");
|
||||
assert!((s - 0.7).abs() < 1e-3 && (v - 0.6).abs() < 1e-3, "{method:?}: saturation {s}, brightness {v}");
|
||||
}
|
||||
}
|
||||
// The other way round, each method takes the arc the other took.
|
||||
let back = two_stops(blue, red, GradientMethod::HueClockwise);
|
||||
assert_eq!(back.sample(0.5).0.to_hex(), "#00ff00");
|
||||
// A position that is not a number gives the first color.
|
||||
assert_eq!(hue_mix(&red, &blue, f32::NAN, true).to_hex(), "#ff0000");
|
||||
}
|
||||
|
||||
/// A color without a hue does not turn the wheel: a gray takes the hue of the stop it mixes
|
||||
/// with, black its saturation too, two grays mix as grays, and two stops of one hue keep that
|
||||
/// hue, whichever way the method turns.
|
||||
#[test]
|
||||
fn hue_methods_keep_the_hue_where_a_stop_has_none() {
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
let close = |c: Color, want: [f32; 3], what: &str| {
|
||||
let got = c.to_rgb();
|
||||
assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3), "{what}: {got:?}, not {want:?}");
|
||||
};
|
||||
let green = Color::rgb(0.0, 1.0, 0.0);
|
||||
for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] {
|
||||
close(method.mix(&Color::WHITE, &green, 0.5), [0.5, 1.0, 0.5], "white to green: a light green");
|
||||
close(method.mix(&green, &Color::WHITE, 0.5), [0.5, 1.0, 0.5], "green to white: a light green");
|
||||
close(method.mix(&Color::rgb(0.5, 0.5, 0.5), &green, 0.5), [0.375, 0.75, 0.375], "gray to green");
|
||||
close(method.mix(&Color::BLACK, &green, 0.5), [0.0, 0.5, 0.0], "black to green: a dark green, not a gray green");
|
||||
close(method.mix(&green, &Color::BLACK, 0.25), [0.0, 0.75, 0.0], "green to black");
|
||||
close(method.mix(&Color::BLACK, &Color::WHITE, 0.5), [0.5, 0.5, 0.5], "black to white: gray");
|
||||
close(method.mix(&Color::BLACK, &Color::BLACK, 0.5), [0.0, 0.0, 0.0], "black to black");
|
||||
let dark = Color::rgb(0.5, 0.0, 0.0);
|
||||
close(method.mix(&red, &dark, 0.5), [0.75, 0.0, 0.0], "one hue: a red between the two");
|
||||
close(method.mix(&red, &red, 0.5), [1.0, 0.0, 0.0], "one color stays");
|
||||
// One hue with saturation and brightness both changing: the hue stays, and the color is
|
||||
// the even mix of saturation and brightness, which is not Classic's RGB mix.
|
||||
let pink = Color::rgb(1.0, 0.8, 0.8);
|
||||
close(method.mix(&dark, &pink, 0.5), [0.75, 0.3, 0.3], "dark red to pink");
|
||||
assert!((Color::lerp(&dark, &pink, 0.5).to_rgb()[1] - 0.4).abs() < 1e-3, "classic differs");
|
||||
// A color whose RGB numbers are under half a color level apart has no hue of its own: a
|
||||
// near gray leaning blue takes green's hue rather than turning from blue.
|
||||
let near_gray = Color::rgb(0.5, 0.5, 0.5 + 0.3 / 255.0);
|
||||
let [h, _, _] = method.mix(&near_gray, &green, 0.5).to_hsb();
|
||||
assert!((h - 120.0).abs() < 0.5, "{method:?}: near gray to green passes hue {h}");
|
||||
// One a whole color level apart has its hue (240°) and turns from it.
|
||||
let bluish = Color::rgb(128.0 / 255.0, 128.0 / 255.0, 129.0 / 255.0);
|
||||
let [h, _, _] = method.mix(&bluish, &green, 0.5).to_hsb();
|
||||
let want = if method == GradientMethod::HueClockwise { 180.0 } else { 0.0 };
|
||||
assert!(((h - want + 180.0).rem_euclid(360.0) - 180.0).abs() < 0.5, "{method:?}: bluish gray to green passes hue {h}, not {want}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Hues that differ only by rounding are one hue: a color and a tint or shade of it, whose
|
||||
/// computed hue angles differ in their last digits, mix without turning the wheel, with either
|
||||
/// method, and a stop added to a ramp leaves the ramp's colors as they were. Hues a whole color
|
||||
/// level apart still turn.
|
||||
#[test]
|
||||
fn hue_methods_take_hues_within_half_a_color_level_as_one() {
|
||||
let level = |n: u8| f32::from(n) / 255.0;
|
||||
let rgb8 = |r: u8, g: u8, b: u8| Color::rgb(level(r), level(g), level(b));
|
||||
let methods = [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise];
|
||||
// Colors against their 50% tint toward white and a shade at 40% brightness. At least one
|
||||
// pair's computed hues differ, or the test checks nothing.
|
||||
let colors = [rgb8(60, 253, 230), rgb8(241, 194, 107), rgb8(68, 32, 130), rgb8(13, 200, 77), rgb8(250, 3, 201), rgb8(90, 91, 200)];
|
||||
let mut uneven = 0;
|
||||
for c in colors {
|
||||
let [h, s, v] = c.to_hsb();
|
||||
let tint = Color::lerp(&c, &Color::WHITE, 0.5);
|
||||
let shade = Color::from_hsb(h, s, v * 0.4);
|
||||
for other in [tint, shade] {
|
||||
let [h1, _, _] = other.to_hsb();
|
||||
assert!((h1 - h).abs() < 0.01, "{c:?} and {other:?} are one hue: {h} and {h1}");
|
||||
uneven += usize::from(h1 != h);
|
||||
for method in methods {
|
||||
for (a, b) in [(c, other), (other, c)] {
|
||||
for k in 0..=20 {
|
||||
let [hm, _, _] = method.mix(&a, &b, k as f32 / 20.0).to_hsb();
|
||||
let off = (hm - h + 180.0).rem_euclid(360.0) - 180.0;
|
||||
assert!(off.abs() < 0.5, "{method:?} {a:?} → {b:?} at {k}/20: hue {hm}, not {h}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(uneven > 0, "no pair's hues differ by rounding");
|
||||
// Across 0°: 359.99° and 0.01° are one hue too.
|
||||
for method in methods {
|
||||
let [h, _, _] = method.mix(&Color::from_hsb(359.99, 1.0, 1.0), &Color::from_hsb(0.01, 1.0, 1.0), 0.5).to_hsb();
|
||||
assert!(!(1.0..=359.0).contains(&h), "{method:?} across 0°: {h}");
|
||||
}
|
||||
// A stop added to a ramp samples the ramp's color there, and the ramp keeps its colors:
|
||||
// white to red, a color to its tint, and a turn from red to blue.
|
||||
let ramps = [
|
||||
(Color::WHITE, rgb8(255, 0, 0)),
|
||||
(rgb8(60, 253, 230), Color::lerp(&rgb8(60, 253, 230), &Color::WHITE, 0.5)),
|
||||
(rgb8(255, 0, 0), rgb8(0, 0, 255)),
|
||||
];
|
||||
for method in methods {
|
||||
for (a, b) in ramps {
|
||||
let g = two_stops(a, b, method);
|
||||
for at in [0.21, 0.5, 0.83] {
|
||||
let (stops, i) = insert_stop(&g, at);
|
||||
assert_eq!((stops.len(), i), (3, 1));
|
||||
let with = Gradient { stops, ..g.clone() };
|
||||
for k in 0..=200 {
|
||||
let t = k as f32 / 200.0;
|
||||
let (was, now) = (g.sample(t).0.to_rgb(), with.sample(t).0.to_rgb());
|
||||
let off = was.iter().zip(now).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
|
||||
assert!(off < 1.0 / 255.0, "{method:?} {a:?} → {b:?}, a stop at {at}: {was:?} became {now:?} at {t}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// One color level of hue is a hue of its own: red to a red one level toward yellow turns
|
||||
// nearly the whole wheel one way and stays put the other.
|
||||
let (red, next) = (rgb8(255, 0, 0), rgb8(255, 1, 0));
|
||||
let [h, _, _] = GradientMethod::HueClockwise.mix(&red, &next, 0.5).to_hsb();
|
||||
assert!((h - 180.0).abs() < 1.0, "the long way: {h}");
|
||||
let [h, _, _] = GradientMethod::HueCounterclockwise.mix(&red, &next, 0.5).to_hsb();
|
||||
assert!(h < 1.0, "the short way: {h}");
|
||||
}
|
||||
|
||||
/// Renderers mix linearly between stops: a hue segment becomes stops on its way around the
|
||||
/// wheel, close enough that the linear ramp between them stays within half a color level of it,
|
||||
/// through the midpoint and with the opacity changing evenly.
|
||||
#[test]
|
||||
fn hue_segments_expand_into_stops_on_the_curve() {
|
||||
let pairs = [
|
||||
(Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)),
|
||||
(Color::rgb(1.0, 0.0, 0.0), Color::rgb(1.0, 0.02, 0.0)),
|
||||
(Color::from_hsb(30.0, 0.5, 0.8), Color::from_hsb(190.0, 0.9, 0.4)),
|
||||
(Color::cmyk(0.0, 0.9, 0.9, 0.0), Color::WHITE),
|
||||
(Color::BLACK, Color::rgb(0.0, 1.0, 0.0)),
|
||||
];
|
||||
for method in [GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] {
|
||||
for (a, b) in pairs {
|
||||
let mut g = two_stops(a, b, method);
|
||||
g.stops[0].midpoint = 0.3;
|
||||
g.stops[1].opacity = 0.5;
|
||||
let ex: Vec<_> = g.expanded().collect();
|
||||
assert!((3..=600).contains(&ex.len()), "{method:?} {a:?} → {b:?}: {} stops", ex.len());
|
||||
assert!(ex.windows(2).all(|w| w[0].0 < w[1].0), "in order");
|
||||
assert!(ex.iter().any(|s| s.3 == Some(0.3) && (s.0 - 0.3).abs() < 1e-6), "a stop stands for the midpoint");
|
||||
let ramp = Ramp::new(&g, &Color::to_rgb);
|
||||
for k in 0..=4000 {
|
||||
let t = k as f32 / 4000.0;
|
||||
let (c, o) = g.sample(t);
|
||||
let [r, gr, bl] = c.to_rgb();
|
||||
let off = [r, gr, bl, o].iter().zip(ramp.at(t)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
|
||||
assert!(off < 0.5 / 255.0, "{method:?} {a:?} → {b:?} at {t}: {off}");
|
||||
}
|
||||
assert_eq!(g.sample_keep_model(0.4), g.sample(0.4), "one mix");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reversing a gradient gives the same ramp the other way round: a hue method turns the other
|
||||
/// way with the stops, so every color keeps its place mirrored, and reversing twice gives the
|
||||
/// gradient back. Classic and Perceptual keep their method. A backward span and the curve as a
|
||||
/// Classic gradient hold the same colors.
|
||||
#[test]
|
||||
fn reversing_a_hue_gradient_keeps_its_colors_mirrored() {
|
||||
let near = |a: Color, b: Color, what: &str| {
|
||||
assert!(a.to_rgb().iter().zip(b.to_rgb()).all(|(x, y)| (x - y).abs() < 1.0 / 255.0), "{what}: {a:?} vs {b:?}");
|
||||
};
|
||||
for (method, other) in
|
||||
[(GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise), (GradientMethod::HueCounterclockwise, GradientMethod::HueClockwise)]
|
||||
{
|
||||
let mut g = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![
|
||||
GradientStop { midpoint: 0.3, ..GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)) },
|
||||
GradientStop { opacity: 0.5, ..GradientStop::new(0.6, Color::rgb(0.0, 0.0, 1.0)) },
|
||||
GradientStop::new(1.0, Color::rgb(0.9, 0.8, 0.1)),
|
||||
],
|
||||
);
|
||||
g.method = method;
|
||||
let mut back = g.clone();
|
||||
back.reverse();
|
||||
assert_eq!(back.method, other);
|
||||
let (span, curve) = (g.span(1.0, 0.0), g.as_classic_curve());
|
||||
assert!(span.method.is_classic() && curve.method.is_classic());
|
||||
assert!(curve.stops.len() > g.stops.len() && curve.stops.iter().all(|s| s.swatch.is_none() && s.midpoint == 0.5));
|
||||
for k in 0..=400 {
|
||||
let t = k as f32 / 400.0;
|
||||
let (want, opacity) = g.sample(1.0 - t);
|
||||
near(want, back.sample(t).0, &format!("{method:?} reversed at {t}"));
|
||||
assert!((opacity - back.sample(t).1).abs() < 1e-4, "{method:?} opacity at {t}");
|
||||
near(want, span.sample(t).0, &format!("{method:?} backward span at {t}"));
|
||||
near(g.sample(t).0, curve.sample(t).0, &format!("{method:?} curve at {t}"));
|
||||
}
|
||||
back.reverse();
|
||||
assert_eq!(back.method, method);
|
||||
assert_eq!(back.stops.len(), g.stops.len());
|
||||
}
|
||||
for method in [GradientMethod::Classic, GradientMethod::Perceptual] {
|
||||
assert_eq!(method.mirrored(), method);
|
||||
let mut g = blue_yellow(method);
|
||||
g.reverse();
|
||||
assert_eq!(g.method, method);
|
||||
}
|
||||
}
|
||||
|
||||
/// The hue methods are written by name, read back, and parsed from their param names; their
|
||||
/// gradients draw as pixels in SVG and PDF, and are not mixes of the stops' inks.
|
||||
#[test]
|
||||
fn hue_methods_save_parse_and_draw_as_pixels() {
|
||||
for (method, name, id) in [
|
||||
(GradientMethod::HueClockwise, "HueClockwise", "hue-clockwise"),
|
||||
(GradientMethod::HueCounterclockwise, "HueCounterclockwise", "hue-counterclockwise"),
|
||||
] {
|
||||
let g = two_stops(Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::cmyk(1.0, 1.0, 0.0, 0.0), method);
|
||||
let v = serde_json::to_value(&g).unwrap();
|
||||
assert_eq!(v["method"], name);
|
||||
assert_eq!(serde_json::from_value::<Gradient>(v).unwrap(), g);
|
||||
assert_eq!(method.id(), id);
|
||||
for written in [id.to_string(), id.to_uppercase(), id.replace('-', " "), id.replace('-', "_"), name.to_string(), method.label().to_string()] {
|
||||
assert_eq!(GradientMethod::parse(&written), Some(method), "{written}");
|
||||
}
|
||||
assert!(method.is_hue() && !method.is_classic());
|
||||
let paint = GradientPaint::new(g.clone());
|
||||
assert!(paint.draws_as_pixels(true) && paint.draws_as_pixels(false));
|
||||
assert!(g.ink_mixes().is_none(), "not mixes of the stops' inks");
|
||||
assert!(
|
||||
paint.ink_pixels(Rect::new(0.0, 0.0, 10.0, 10.0), Rect::new(0.0, 0.0, 10.0, 10.0), 4, 4, true).is_none(),
|
||||
"an RGB image, not an ink image"
|
||||
);
|
||||
}
|
||||
assert!(!GradientMethod::Perceptual.is_hue() && !GradientMethod::Classic.is_hue());
|
||||
for (id, method) in [("classic", GradientMethod::Classic), ("perceptual", GradientMethod::Perceptual)] {
|
||||
assert_eq!(method.id(), id);
|
||||
assert_eq!(GradientMethod::parse(id), Some(method));
|
||||
}
|
||||
for bad in [
|
||||
"hue",
|
||||
"clockwise",
|
||||
"hue-",
|
||||
"",
|
||||
"hue clockwise wise",
|
||||
"c-l-a-s-s-i-c",
|
||||
"per ceptual",
|
||||
"hue--clockwise",
|
||||
"hue-clock_wise",
|
||||
" classic",
|
||||
"hue- clockwise",
|
||||
] {
|
||||
assert_eq!(GradientMethod::parse(bad), None, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Perceptual gradient of an ink's tints as tints: its stops keep their tints, and each tint on
|
||||
/// the curve has the lightness of the color mixed there, so the tints between the stops are not
|
||||
/// a straight line.
|
||||
@@ -697,3 +974,360 @@ fn ink_pixels_stop_at_the_ink_mixes_limit() {
|
||||
assert!(GradientPaint::new(perceptual).ink_pixels(b, b, 2, 1, false).is_none());
|
||||
assert!(GradientPaint::new(classic).ink_pixels(b, b, 2, 1, false).is_some());
|
||||
}
|
||||
|
||||
/// A conic placed at `center` with its vector `dx` long to the right and aspect `aspect`.
|
||||
fn conic_at(center: Point, dx: f64, aspect: f64) -> GradientGeom {
|
||||
GradientGeom { start: center, end: center + Vec2::new(dx, 0.0), aspect, focal: None }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_conic_turns_clockwise_on_the_page_from_its_vector() {
|
||||
// The page's y runs down: a quarter turn clockwise from a vector pointing right is straight
|
||||
// below the center.
|
||||
let g = conic_at(Point::new(100.0, 100.0), 50.0, 1.0);
|
||||
let t = |x: f64, y: f64| g.param_at(GradientKind::Conic, Point::new(x, y));
|
||||
assert!(t(200.0, 100.0).abs() < 1e-12);
|
||||
assert!((t(100.0, 130.0) - 0.25).abs() < 1e-12);
|
||||
assert!((t(10.0, 100.0) - 0.5).abs() < 1e-12);
|
||||
assert!((t(100.0, 3.0) - 0.75).abs() < 1e-12);
|
||||
// Either side of the seam: the start of the ramp just below the vector, its end just above.
|
||||
assert!(t(200.0, 100.01) < 1e-3);
|
||||
let before = t(200.0, 99.99);
|
||||
assert!(before > 0.999 && before <= 1.0, "{before}");
|
||||
// A flatter extent ellipse turns faster near the vector's line: half as tall, the point 1/8
|
||||
// of a turn around is half as far below it.
|
||||
let squashed = conic_at(Point::new(100.0, 100.0), 50.0, 0.5);
|
||||
let p = Point::new(150.0, 125.0);
|
||||
assert!((squashed.param_at(GradientKind::Conic, p) - 0.125).abs() < 1e-12);
|
||||
assert!(g.param_at(GradientKind::Conic, p) < 0.1);
|
||||
// Mirrored (a negative aspect), it turns counterclockwise.
|
||||
let mirrored = conic_at(Point::new(100.0, 100.0), 50.0, -1.0);
|
||||
assert!(mirrored.is_mirrored() && !g.is_mirrored());
|
||||
assert!((mirrored.param_at(GradientKind::Conic, Point::new(100.0, 70.0)) - 0.25).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_conic_follows_moves_turns_scales_and_mirrors() {
|
||||
let c = Point::new(10.0, 20.0);
|
||||
let g0 = conic_at(c, 30.0, 1.0);
|
||||
let probes = [c + Vec2::new(5.0, 7.0), c + Vec2::new(-9.0, 2.0), c + Vec2::new(3.0, -11.0)];
|
||||
for a in [
|
||||
Affine::rotate(0.7),
|
||||
Affine::scale(2.5),
|
||||
Affine::translate((4.0, -9.0)) * Affine::rotate(-2.0),
|
||||
Affine::FLIP_X,
|
||||
Affine::FLIP_Y * Affine::rotate(1.1),
|
||||
Affine::scale_non_uniform(2.0, 0.5),
|
||||
] {
|
||||
let mut g = g0;
|
||||
g.transform(a, GradientKind::Conic);
|
||||
assert!(g.start.distance(a * c) < 1e-9, "{a:?}");
|
||||
for p in probes {
|
||||
let (want, got) = (g0.param_at(GradientKind::Conic, p), g.param_at(GradientKind::Conic, a * p));
|
||||
assert!((want - got).abs() < 1e-9, "{a:?} at {p:?}: {want} vs {got}");
|
||||
}
|
||||
}
|
||||
// A mirror and a mirror back: the same sweep.
|
||||
let mut g = g0;
|
||||
g.transform(Affine::FLIP_X, GradientKind::Conic);
|
||||
assert!(g.is_mirrored());
|
||||
g.transform(Affine::FLIP_X, GradientKind::Conic);
|
||||
assert!(!g.is_mirrored() && (g.aspect - 1.0).abs() < 1e-12);
|
||||
// A conic without a vector, or with a flat extent, turns the other way under a mirror too.
|
||||
for flat in [conic_at(c, 0.0, 1.0), conic_at(c, 30.0, 0.0)] {
|
||||
let mut g = flat;
|
||||
g.transform(Affine::FLIP_Y, GradientKind::Conic);
|
||||
assert!(g.is_mirrored(), "{g:?}");
|
||||
g.transform(Affine::rotate(0.3), GradientKind::Conic);
|
||||
assert!(g.is_mirrored(), "{g:?}");
|
||||
g.transform(Affine::FLIP_X, GradientKind::Conic);
|
||||
assert!(!g.is_mirrored(), "{g:?}");
|
||||
}
|
||||
// Under a shear the seam stays where the vector maps.
|
||||
let shear = Affine::new([1.0, 0.0, 0.6, 1.0, 0.0, 0.0]);
|
||||
let mut g = g0;
|
||||
g.transform(shear, GradientKind::Conic);
|
||||
let on_seam = shear * (c + Vec2::new(20.0, 0.0));
|
||||
assert!(g.param_at(GradientKind::Conic, on_seam) < 1e-9, "{g:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conic_kind_names_and_fit() {
|
||||
for s in ["conic", "Conic", "angle", "CONICAL"] {
|
||||
assert_eq!(GradientKind::parse(s), Some(GradientKind::Conic), "{s}");
|
||||
}
|
||||
assert_eq!(GradientKind::parse("spiral"), None);
|
||||
assert_eq!(GradientKind::Conic.label(), "Conic");
|
||||
assert!(GradientKind::Conic.is_centered() && GradientKind::Radial.is_centered() && !GradientKind::Linear.is_centered());
|
||||
let fit = GradientGeom::fit(GradientKind::Conic, Rect::new(0.0, 0.0, 200.0, 100.0), 90.0);
|
||||
assert_eq!(fit.start, Point::new(100.0, 50.0));
|
||||
assert!(fit.end.distance(Point::new(100.0, -50.0)) < 1e-9);
|
||||
}
|
||||
|
||||
/// Is `p` inside polygon `poly` (non-zero winding)?
|
||||
fn inside(poly: &[Point], p: Point) -> bool {
|
||||
let mut w = 0i32;
|
||||
for (i, &a) in poly.iter().enumerate() {
|
||||
let c = poly[(i + 1) % poly.len()];
|
||||
let cross = (c - a).cross(p - a);
|
||||
if a.y <= p.y && c.y > p.y && cross > 0.0 {
|
||||
w += 1;
|
||||
} else if a.y > p.y && c.y <= p.y && cross < 0.0 {
|
||||
w -= 1;
|
||||
}
|
||||
}
|
||||
w != 0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conic_wedges_cover_the_box_and_meet_at_the_seam() {
|
||||
let b = Rect::new(0.0, 0.0, 200.0, 100.0);
|
||||
let g = conic_at(Point::new(60.0, 40.0), 30.0, 0.5);
|
||||
let wedges = g.conic_wedges(b, 36, false);
|
||||
assert_eq!(wedges.len(), 36);
|
||||
// Each point of the box lies in the wedge whose share of the turn holds it.
|
||||
for (x, y) in [(1.0, 1.0), (199.0, 99.0), (150.0, 30.0), (10.0, 90.0), (61.0, 39.0), (59.0, 41.0)] {
|
||||
let p = Point::new(x, y);
|
||||
let t = g.param_at(GradientKind::Conic, p);
|
||||
let k = ((t * 36.0).floor() as usize).min(35);
|
||||
assert!(inside(&wedges[k].0, p), "({x}, {y}) at {t} is not in wedge {k}");
|
||||
assert!((wedges[k].1 - (k as f64 + 0.5) / 36.0).abs() < 1e-12);
|
||||
}
|
||||
// Overlapping wedges run on from their own start to the seam.
|
||||
let over = g.conic_wedges(b, 36, true);
|
||||
let frame = g.unit_frame().unwrap();
|
||||
let on = |turn: f64| frame * Point::new(0.5 * (turn * std::f64::consts::TAU).cos(), 0.5 * (turn * std::f64::consts::TAU).sin());
|
||||
assert!(inside(&over[0].0, on(0.5)) && inside(&over[0].0, on(35.9 / 36.0)));
|
||||
assert!(inside(&over[20].0, on(35.9 / 36.0)) && !inside(&over[20].0, on(19.9 / 36.0)));
|
||||
// The count is kept to what a file can hold.
|
||||
assert_eq!(g.conic_wedges(b, 0, false).len(), 1);
|
||||
assert_eq!(g.conic_wedges(b, usize::MAX, false).len(), MAX_CONIC_WEDGES);
|
||||
}
|
||||
|
||||
/// A conic whose extent can't be drawn (a vector without length, an aspect of 0, or numbers out
|
||||
/// of range, as a file can hold them) sweeps from the right about its start, or the origin; the
|
||||
/// parameter, the frame and the wedges stay finite.
|
||||
#[test]
|
||||
fn a_conic_with_no_extent_or_bad_numbers_still_sweeps() {
|
||||
let c = Point::new(50.0, 50.0);
|
||||
for g in [
|
||||
conic_at(c, 0.0, 1.0),
|
||||
conic_at(c, 30.0, 0.0),
|
||||
conic_at(c, 30.0, f64::NAN),
|
||||
conic_at(c, 30.0, f64::INFINITY),
|
||||
conic_at(c, f64::INFINITY, 1.0),
|
||||
GradientGeom { end: Point::new(f64::NAN, 3.0), ..conic_at(c, 30.0, 1.0) },
|
||||
] {
|
||||
assert!(g.conic_frame().as_coeffs().iter().all(|v| v.is_finite()), "{g:?}");
|
||||
let t = |x: f64, y: f64| g.param_at(GradientKind::Conic, Point::new(x, y));
|
||||
assert!(t(90.0, 50.0).abs() < 1e-12, "{g:?}");
|
||||
assert!((t(50.0, 90.0) - 0.25).abs() < 1e-12, "{g:?}");
|
||||
let wedges = g.conic_wedges(Rect::new(0.0, 0.0, 100.0, 100.0), 4, false);
|
||||
assert!(wedges.iter().flat_map(|(pts, _)| pts).all(|p| p.is_finite()), "{g:?}");
|
||||
}
|
||||
// A flat extent keeps the vector's direction and the sign of its aspect.
|
||||
let down = GradientGeom { end: Point::new(50.0, 80.0), ..conic_at(c, 30.0, 0.0) };
|
||||
assert!(down.param_at(GradientKind::Conic, Point::new(50.0, 90.0)).abs() < 1e-12);
|
||||
assert!((down.param_at(GradientKind::Conic, Point::new(10.0, 50.0)) - 0.25).abs() < 1e-12);
|
||||
for g in [conic_at(c, 0.0, -1.0), conic_at(c, 30.0, -0.0), conic_at(c, 30.0, f64::NEG_INFINITY)] {
|
||||
assert!(g.is_mirrored(), "{g:?}");
|
||||
assert!((g.param_at(GradientKind::Conic, Point::new(50.0, 10.0)) - 0.25).abs() < 1e-12, "{g:?}");
|
||||
}
|
||||
let lost = GradientGeom { start: Point::new(f64::NAN, 0.0), ..conic_at(c, 30.0, 1.0) };
|
||||
assert_eq!(lost.conic_frame(), Affine::IDENTITY);
|
||||
for p in [Point::new(3.0, 4.0), Point::new(f64::NAN, 1.0), Point::new(f64::INFINITY, 0.0)] {
|
||||
let t = lost.param_at(GradientKind::Conic, p);
|
||||
assert!((0.0..=1.0).contains(&t), "{t}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A conic's pixels (what SVG and PDF draw a dithered or Perceptual one as) follow the sweep,
|
||||
/// with one stop as well as many.
|
||||
#[test]
|
||||
fn conic_pixels_follow_the_sweep() {
|
||||
let b = Rect::new(0.0, 0.0, 4.0, 4.0);
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Conic, Gradient::default().stops));
|
||||
g.geom = Some(conic_at(Point::new(2.0, 2.0), 1.0, 1.0));
|
||||
let px: Vec<[u8; 4]> = g.pixels(b, b, 4, 4, true, &Color::to_rgb).collect();
|
||||
// Below right of the center, early in the sweep: light. Above right, late: dark.
|
||||
assert!(px[3 * 4 + 3][0] > 180 && px[3][0] < 75, "{px:?}");
|
||||
let one = GradientPaint { gradient: Gradient::new(GradientKind::Conic, vec![GradientStop::new(0.3, Color::rgb(1.0, 0.0, 0.0))]), ..g.clone() };
|
||||
assert!(one.pixels(b, b, 4, 4, true, &Color::to_rgb).all(|p| p == [255, 0, 0, 255]));
|
||||
let many = (0..=1000).map(|i| GradientStop::new(i as f32 / 1000.0, Color::gray((i % 2) as f32))).collect();
|
||||
let many = GradientPaint { gradient: Gradient::new(GradientKind::Conic, many), ..g };
|
||||
assert_eq!(many.pixels(b, b, 4, 4, true, &Color::to_rgb).count(), 16);
|
||||
}
|
||||
|
||||
/// A diamond placed at `center` with its vector `dx` long to the right and aspect `aspect`.
|
||||
fn diamond_at(center: Point, dx: f64, aspect: f64) -> GradientGeom {
|
||||
GradientGeom { start: center, end: center + Vec2::new(dx, 0.0), aspect, focal: None }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_diamond_runs_from_its_center_out_to_a_square_with_a_corner_at_the_end_of_its_vector() {
|
||||
let g = diamond_at(Point::new(100.0, 100.0), 50.0, 1.0);
|
||||
let t = |x: f64, y: f64| g.param_at(GradientKind::Diamond, Point::new(x, y));
|
||||
assert!(t(100.0, 100.0).abs() < 1e-12);
|
||||
// The square's corners: at the end of the vector and a quarter turn on from it each way.
|
||||
for (x, y) in [(150.0, 100.0), (100.0, 150.0), (50.0, 100.0), (100.0, 50.0)] {
|
||||
assert!((t(x, y) - 1.0).abs() < 1e-12, "({x}, {y})");
|
||||
}
|
||||
// Halfway along an edge, and halfway out along a diagonal (the middle of the edge's half size).
|
||||
assert!((t(125.0, 125.0) - 1.0).abs() < 1e-12);
|
||||
assert!((t(112.5, 87.5) - 0.5).abs() < 1e-12);
|
||||
// Past the square: more than 1 (the last stop pads on).
|
||||
assert!((t(200.0, 200.0) - 4.0).abs() < 1e-12);
|
||||
// The aspect stretches the square across the vector into a rhombus.
|
||||
let tall = diamond_at(Point::new(100.0, 100.0), 50.0, 2.0);
|
||||
assert!((tall.param_at(GradientKind::Diamond, Point::new(100.0, 200.0)) - 1.0).abs() < 1e-12);
|
||||
assert!((tall.param_at(GradientKind::Diamond, Point::new(150.0, 100.0)) - 1.0).abs() < 1e-12);
|
||||
// Turned: the corner follows the vector.
|
||||
let turned = GradientGeom { end: Point::new(130.0, 140.0), ..g };
|
||||
assert!((turned.param_at(GradientKind::Diamond, Point::new(130.0, 140.0)) - 1.0).abs() < 1e-12);
|
||||
assert!((turned.param_at(GradientKind::Diamond, Point::new(115.0, 120.0)) - 0.5).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diamond_kind_names_and_fit() {
|
||||
for s in ["diamond", "Diamond", "DIAMOND"] {
|
||||
assert_eq!(GradientKind::parse(s), Some(GradientKind::Diamond), "{s}");
|
||||
}
|
||||
assert_eq!(GradientKind::Diamond.label(), "Diamond");
|
||||
assert!(GradientKind::Diamond.is_centered());
|
||||
assert!(GradientKind::ALL.contains(&GradientKind::Diamond));
|
||||
// Level: the square's edges pass through the box's corners, so it covers the box exactly.
|
||||
let b = Rect::new(0.0, 0.0, 200.0, 100.0);
|
||||
let fit = GradientGeom::fit(GradientKind::Diamond, b, 0.0);
|
||||
assert_eq!(fit.start, Point::new(100.0, 50.0));
|
||||
assert!(fit.end.distance(Point::new(250.0, 50.0)) < 1e-9, "{fit:?}");
|
||||
for c in [Point::new(0.0, 0.0), Point::new(200.0, 0.0), Point::new(200.0, 100.0), Point::new(0.0, 100.0)] {
|
||||
assert!((fit.param_at(GradientKind::Diamond, c) - 1.0).abs() < 1e-9, "{c:?}");
|
||||
}
|
||||
// At any angle the square covers the box and runs through its farthest corner, on a square
|
||||
// box too.
|
||||
for b in [b, Rect::new(0.0, 0.0, 100.0, 100.0)] {
|
||||
for angle in [30.0, 45.0, 90.0, -120.0] {
|
||||
let fit = GradientGeom::fit(GradientKind::Diamond, b, angle);
|
||||
let levels = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)]
|
||||
.map(|c| fit.param_at(GradientKind::Diamond, c));
|
||||
assert!(levels.iter().all(|&t| t <= 1.0 + 1e-9), "{angle}: {levels:?}");
|
||||
assert!(levels.iter().any(|&t| (t - 1.0).abs() < 1e-9), "{angle}: {levels:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_diamond_follows_moves_turns_scales_and_mirrors() {
|
||||
let c = Point::new(10.0, 20.0);
|
||||
let g0 = diamond_at(c, 30.0, 0.5);
|
||||
let probes = [c + Vec2::new(5.0, 7.0), c + Vec2::new(-9.0, 2.0), c + Vec2::new(3.0, -11.0), c + Vec2::new(-20.0, -4.0)];
|
||||
for a in [
|
||||
Affine::rotate(0.7),
|
||||
Affine::scale(2.5),
|
||||
Affine::translate((4.0, -9.0)) * Affine::rotate(-2.0),
|
||||
Affine::FLIP_X,
|
||||
Affine::FLIP_Y * Affine::rotate(1.1),
|
||||
// Along and across the vector.
|
||||
Affine::scale_non_uniform(2.0, 0.5),
|
||||
Affine::scale_non_uniform(-3.0, 0.25),
|
||||
] {
|
||||
let mut g = g0;
|
||||
g.transform(a, GradientKind::Diamond);
|
||||
assert!(g.start.distance(a * c) < 1e-9, "{a:?}");
|
||||
// A mirror changes nothing a diamond shows: its aspect stays a size.
|
||||
assert!(g.aspect > 0.0, "{a:?}: {g:?}");
|
||||
for p in probes {
|
||||
let (want, got) = (g0.param_at(GradientKind::Diamond, p), g.param_at(GradientKind::Diamond, a * p));
|
||||
assert!((want - got).abs() < 1e-9, "{a:?} at {p:?}: {want} vs {got}");
|
||||
}
|
||||
}
|
||||
// Under a shear the corner stays where the vector maps.
|
||||
let shear = Affine::new([1.0, 0.0, 0.6, 1.0, 0.0, 0.0]);
|
||||
let mut g = g0;
|
||||
g.transform(shear, GradientKind::Diamond);
|
||||
assert!((g.param_at(GradientKind::Diamond, shear * (c + Vec2::new(30.0, 0.0))) - 1.0).abs() < 1e-9, "{g:?}");
|
||||
// Out-of-range numbers: a finite aspect after any transform.
|
||||
for bad in [diamond_at(c, 30.0, f64::NAN), diamond_at(c, f64::INFINITY, 1.0), diamond_at(c, 0.0, 1.0)] {
|
||||
let mut g = bad;
|
||||
g.transform(Affine::rotate(0.4), GradientKind::Diamond);
|
||||
assert!(g.aspect.is_finite(), "{g:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A diamond without a frame (no vector, a flat or a not-finite extent) has no inside: every
|
||||
/// point is past its edge and takes the last stop. Points that aren't numbers do too.
|
||||
#[test]
|
||||
fn a_diamond_with_no_extent_or_bad_numbers_is_its_last_stop() {
|
||||
let c = Point::new(50.0, 50.0);
|
||||
for g in [
|
||||
diamond_at(c, 0.0, 1.0),
|
||||
diamond_at(c, 30.0, 0.0),
|
||||
diamond_at(c, 30.0, f64::NAN),
|
||||
diamond_at(c, f64::INFINITY, 1.0),
|
||||
GradientGeom { start: Point::new(f64::NAN, 0.0), ..diamond_at(c, 30.0, 1.0) },
|
||||
] {
|
||||
assert!(g.diamond_frame().is_none(), "{g:?}");
|
||||
assert!(g.diamond_quadrants(Rect::new(0.0, 0.0, 100.0, 100.0)).is_none(), "{g:?}");
|
||||
assert_eq!(g.param_at(GradientKind::Diamond, Point::new(60.0, 40.0)), 1.0, "{g:?}");
|
||||
}
|
||||
let g = diamond_at(c, 30.0, 1.0);
|
||||
assert_eq!(g.param_at(GradientKind::Diamond, Point::new(f64::NAN, 1.0)), 1.0);
|
||||
assert!(g.param_at(GradientKind::Diamond, Point::new(f64::INFINITY, 1.0)) >= 1.0);
|
||||
}
|
||||
|
||||
/// The four linear gradients a format without diamond gradients gets, drawn in order, equal the
|
||||
/// diamond everywhere, and each edge drawn lies on the quadrant drawn before it.
|
||||
#[test]
|
||||
fn diamond_quadrants_are_linear_gradients_that_equal_the_diamond() {
|
||||
let b = Rect::new(0.0, 0.0, 200.0, 100.0);
|
||||
let probes: Vec<Point> = (0..=20).flat_map(|i| (0..=10).map(move |j| Point::new(i as f64 * 10.0 + 0.3, j as f64 * 10.0 + 0.7))).collect();
|
||||
// Squashed and turned, stretched twice as tall as wide, and stretched by a shear.
|
||||
let mut turned = diamond_at(Point::new(60.0, 40.0), 30.0, 0.5);
|
||||
turned.transform(Affine::rotate_about(0.4, Point::new(60.0, 40.0)), GradientKind::Diamond);
|
||||
let mut sheared = diamond_at(Point::new(90.0, 50.0), 25.0, 1.0);
|
||||
sheared.transform(Affine::new([2.0, 0.0, 0.7, 1.0, -60.0, 0.0]), GradientKind::Diamond);
|
||||
for g in [turned, diamond_at(Point::new(100.0, 50.0), 20.0, 2.0), sheared] {
|
||||
let quadrants = g.diamond_quadrants(b).expect("a frame");
|
||||
for p in &probes {
|
||||
// The last quadrant drawn that holds the point paints it.
|
||||
let Some((_, linear)) = quadrants.iter().rev().find(|(poly, _)| inside(poly, *p)) else { panic!("{p:?} is in no quadrant") };
|
||||
let (want, got) = (g.param_at(GradientKind::Diamond, *p), linear.param_at(GradientKind::Linear, *p));
|
||||
assert!((want - got).abs() < 1e-9, "{g:?} at {p:?}: {want} vs {got}");
|
||||
}
|
||||
}
|
||||
let g = turned;
|
||||
let quadrants = g.diamond_quadrants(b).expect("a frame");
|
||||
// Next to each edge of a quadrant drawn later, on either side, the quadrant drawn before it
|
||||
// lies underneath (the first quadrant's edges are covered by the second and the last).
|
||||
let frame = g.diamond_frame().expect("a frame");
|
||||
for (unit, under) in [
|
||||
// The second quadrant's first edge, on the first.
|
||||
(Point::new(0.01, 0.5), 0),
|
||||
(Point::new(-0.01, 0.5), 0),
|
||||
// The third's, on the second.
|
||||
(Point::new(-0.5, 0.01), 1),
|
||||
(Point::new(-0.5, -0.01), 1),
|
||||
// The last's two, on the third and on the first.
|
||||
(Point::new(-0.01, -0.5), 2),
|
||||
(Point::new(0.01, -0.5), 2),
|
||||
(Point::new(0.5, -0.01), 0),
|
||||
(Point::new(0.5, 0.01), 0),
|
||||
] {
|
||||
assert!(inside(&quadrants[under].0, frame * unit), "{unit:?} lies on quadrant {under}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A diamond's pixels (what SVG and PDF draw a dithered or Perceptual one as, and what the canvas
|
||||
/// draws) follow the squares.
|
||||
#[test]
|
||||
fn diamond_pixels_follow_the_squares() {
|
||||
let b = Rect::new(0.0, 0.0, 5.0, 5.0);
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Diamond, Gradient::default().stops));
|
||||
g.geom = Some(diamond_at(Point::new(2.5, 2.5), 2.5, 1.0));
|
||||
let px: Vec<[u8; 4]> = g.pixels(b, b, 5, 5, false, &Color::to_rgb).collect();
|
||||
// White at the center, black in the corners, and the same on each side of it.
|
||||
assert!(px[2 * 5 + 2][0] > 200 && px[0][0] < 10 && px[24][0] < 10, "{px:?}");
|
||||
assert_eq!(px[2 * 5 + 1], px[2 * 5 + 3]);
|
||||
assert_eq!(px[5 + 2], px[3 * 5 + 2]);
|
||||
assert_eq!(px[2 * 5 + 1], px[5 + 2]);
|
||||
}
|
||||
@@ -16,7 +16,7 @@ pub mod swatch;
|
||||
|
||||
pub use blend::BlendMode;
|
||||
pub use freeform::{Freeform, FreeformMode, FreeformPoint};
|
||||
pub use gradient::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientStop};
|
||||
pub use gradient::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientSpread, GradientStop};
|
||||
pub use libraries::SwatchLibrary;
|
||||
pub use swatch::{Swatch, SwatchGroup, default_swatches};
|
||||
|
||||
@@ -102,12 +102,13 @@ impl Color {
|
||||
pub fn to_lab(&self) -> cms::Lab {
|
||||
cms::active().lab(self)
|
||||
}
|
||||
/// Colour-managed CMYK in the working CMYK space with `intent` (see [`Color::to_cmyk`] for the
|
||||
/// profile-free formula).
|
||||
/// Color-managed CMYK in the active CMYK space (the front document's assigned CMYK profile, else
|
||||
/// the working CMYK space) with `intent` (see [`Color::to_cmyk`] for the profile-free formula).
|
||||
pub fn to_cmyk_managed(&self, intent: cms::Intent) -> [f32; 4] {
|
||||
cms::active().to_cmyk(self, intent)
|
||||
}
|
||||
/// Gamut warning: true when this colour can't be reproduced in the working CMYK space.
|
||||
/// Gamut warning: true when this color can't be reproduced in the active CMYK space (the front
|
||||
/// document's assigned CMYK profile, else the working CMYK space).
|
||||
pub fn out_of_gamut(&self) -> bool {
|
||||
cms::active().out_of_gamut(self)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::sync::{Arc, OnceLock};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint, Swatch, SwatchGroup};
|
||||
use crate::{Color, Gradient, GradientKind, GradientMethod, GradientPaint, GradientStop, Paint, Swatch, SwatchGroup};
|
||||
|
||||
/// A library: its name, its ungrouped swatches and its colour groups.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
@@ -72,6 +72,8 @@ pub const GRADIENT_LIBRARIES: &[BuiltinLibrary] = &[
|
||||
lib!("spectrum-gradients", "Spectrum Gradients", spectrum_gradients),
|
||||
lib!("sky-gradients", "Sky Gradients", sky_gradients),
|
||||
lib!("neutral-gradients", "Neutral Gradients", neutral_gradients),
|
||||
lib!("organic-fades", "Organic Fades", organic_fades),
|
||||
lib!("holographic", "Holographic", holographic),
|
||||
lib!("duotone-gradients", "Duotone Gradients", duotone_gradients),
|
||||
lib!("radial-glows", "Radial Glows", radial_glows),
|
||||
];
|
||||
@@ -179,6 +181,14 @@ pub(crate) fn gradient(name: &str, kind: GradientKind, stops: &[(f32, Color, f32
|
||||
Swatch { name: name.into(), paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(kind, stops)))), global: false, spot: false }
|
||||
}
|
||||
|
||||
/// A gradient swatch mixed by `method` through `stops` of (offset, color, opacity, midpoint).
|
||||
fn gradient_with(name: &str, kind: GradientKind, method: GradientMethod, stops: &[(f32, Color, f32, f32)]) -> Swatch {
|
||||
let stops =
|
||||
stops.iter().map(|&(offset, color, opacity, midpoint)| GradientStop { opacity, midpoint, ..GradientStop::new(offset, color) }).collect();
|
||||
let gradient = Gradient { method, ..Gradient::new(kind, stops) };
|
||||
Swatch { name: name.into(), paint: Paint::Gradient(Box::new(GradientPaint::new(gradient))), global: false, spot: false }
|
||||
}
|
||||
|
||||
/// `n` steps of OKLCH lightness from `l0` to `l1`, chroma `c(t)` and hue `h(t)` (`t` in 0..=1),
|
||||
/// named "`name` 1"…
|
||||
fn ramp(name: &str, n: usize, (l0, l1): (f64, f64), c: impl Fn(f64) -> f64, h: impl Fn(f64) -> f64) -> SwatchGroup {
|
||||
@@ -387,6 +397,197 @@ fn radial_glows() -> (Vec<Swatch>, Vec<SwatchGroup>) {
|
||||
(s, vec![])
|
||||
}
|
||||
|
||||
/// A stop of [`organic_fades`]: offset, OKLCH `(l, c, h°)`, opacity and midpoint.
|
||||
type FadeStop = (f32, (f64, f64, f64), f32, f32);
|
||||
|
||||
/// Soft fades through a few unevenly spaced stops with off-center midpoints, mixed perceptually,
|
||||
/// that thin out to transparent: at the end of the linear ones and at the edge of the radial ones.
|
||||
fn organic_fades() -> (Vec<Swatch>, Vec<SwatchGroup>) {
|
||||
use GradientKind::{Linear, Radial};
|
||||
let fades: [(&str, GradientKind, &[FadeStop]); 15] = [
|
||||
(
|
||||
"Mist",
|
||||
Linear,
|
||||
&[
|
||||
(0.0, (0.94, 0.012, 240.0), 1.0, 0.38),
|
||||
(0.35, (0.86, 0.03, 235.0), 0.85, 0.62),
|
||||
(0.7, (0.8, 0.035, 230.0), 0.4, 0.45),
|
||||
(1.0, (0.78, 0.035, 230.0), 0.0, 0.5),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Petal",
|
||||
Linear,
|
||||
&[
|
||||
(0.0, (0.82, 0.09, 350.0), 1.0, 0.42),
|
||||
(0.28, (0.88, 0.07, 10.0), 0.9, 0.66),
|
||||
(0.64, (0.93, 0.04, 30.0), 0.45, 0.35),
|
||||
(1.0, (0.95, 0.03, 40.0), 0.0, 0.5),
|
||||
],
|
||||
),
|
||||
("Fern", Linear, &[(0.0, (0.52, 0.1, 145.0), 1.0, 0.6), (0.4, (0.68, 0.11, 135.0), 0.75, 0.4), (1.0, (0.85, 0.08, 120.0), 0.0, 0.5)]),
|
||||
(
|
||||
"Smoke",
|
||||
Linear,
|
||||
&[
|
||||
(0.0, (0.35, 0.01, 260.0), 1.0, 0.3),
|
||||
(0.22, (0.48, 0.012, 255.0), 0.8, 0.58),
|
||||
(0.58, (0.62, 0.01, 250.0), 0.35, 0.7),
|
||||
(1.0, (0.72, 0.008, 250.0), 0.0, 0.5),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Honey",
|
||||
Linear,
|
||||
&[
|
||||
(0.0, (0.72, 0.15, 70.0), 1.0, 0.55),
|
||||
(0.3, (0.8, 0.14, 80.0), 0.9, 0.35),
|
||||
(0.75, (0.9, 0.09, 90.0), 0.3, 0.6),
|
||||
(1.0, (0.95, 0.05, 95.0), 0.0, 0.5),
|
||||
],
|
||||
),
|
||||
("Seafoam", Linear, &[(0.0, (0.7, 0.09, 175.0), 1.0, 0.45), (0.45, (0.84, 0.07, 170.0), 0.6, 0.65), (1.0, (0.95, 0.03, 165.0), 0.0, 0.5)]),
|
||||
(
|
||||
"Lavender",
|
||||
Linear,
|
||||
&[
|
||||
(0.0, (0.62, 0.12, 300.0), 1.0, 0.36),
|
||||
(0.3, (0.72, 0.1, 295.0), 0.85, 0.55),
|
||||
(0.55, (0.82, 0.07, 290.0), 0.5, 0.68),
|
||||
(0.82, (0.9, 0.04, 285.0), 0.15, 0.4),
|
||||
(1.0, (0.93, 0.03, 285.0), 0.0, 0.5),
|
||||
],
|
||||
),
|
||||
("Driftwood", Linear, &[(0.0, (0.55, 0.04, 60.0), 1.0, 0.64), (0.38, (0.68, 0.035, 70.0), 0.7, 0.42), (1.0, (0.84, 0.025, 80.0), 0.0, 0.5)]),
|
||||
(
|
||||
"Ink Wash",
|
||||
Linear,
|
||||
&[
|
||||
(0.0, (0.25, 0.05, 265.0), 1.0, 0.28),
|
||||
(0.18, (0.35, 0.06, 262.0), 0.9, 0.6),
|
||||
(0.5, (0.5, 0.05, 258.0), 0.45, 0.72),
|
||||
(1.0, (0.65, 0.04, 255.0), 0.0, 0.5),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Tide",
|
||||
Linear,
|
||||
&[
|
||||
(0.0, (0.45, 0.1, 230.0), 1.0, 0.4),
|
||||
(0.26, (0.6, 0.1, 215.0), 0.8, 0.62),
|
||||
(0.72, (0.76, 0.08, 200.0), 0.35, 0.44),
|
||||
(1.0, (0.88, 0.05, 195.0), 0.0, 0.5),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Bloom",
|
||||
Radial,
|
||||
&[
|
||||
(0.0, (0.92, 0.05, 40.0), 1.0, 0.4),
|
||||
(0.22, (0.8, 0.12, 20.0), 0.95, 0.6),
|
||||
(0.6, (0.7, 0.14, 355.0), 0.4, 0.35),
|
||||
(1.0, (0.66, 0.13, 345.0), 0.0, 0.5),
|
||||
],
|
||||
),
|
||||
("Dew", Radial, &[(0.0, (0.97, 0.01, 200.0), 1.0, 0.3), (0.3, (0.88, 0.05, 195.0), 0.7, 0.58), (1.0, (0.8, 0.06, 190.0), 0.0, 0.5)]),
|
||||
(
|
||||
"Pollen",
|
||||
Radial,
|
||||
&[
|
||||
(0.0, (0.96, 0.08, 100.0), 1.0, 0.45),
|
||||
(0.18, (0.9, 0.15, 95.0), 1.0, 0.65),
|
||||
(0.55, (0.82, 0.16, 85.0), 0.5, 0.4),
|
||||
(1.0, (0.76, 0.15, 75.0), 0.0, 0.5),
|
||||
],
|
||||
),
|
||||
// A ring: clear at the center, then a band that fades out to the edge.
|
||||
(
|
||||
"Halo",
|
||||
Radial,
|
||||
&[
|
||||
(0.0, (0.98, 0.005, 90.0), 0.0, 0.6),
|
||||
(0.42, (0.95, 0.02, 85.0), 0.0, 0.35),
|
||||
(0.62, (0.92, 0.04, 80.0), 1.0, 0.55),
|
||||
(1.0, (0.88, 0.05, 75.0), 0.0, 0.5),
|
||||
],
|
||||
),
|
||||
(
|
||||
"Lichen",
|
||||
Radial,
|
||||
&[
|
||||
(0.0, (0.8, 0.07, 120.0), 1.0, 0.58),
|
||||
(0.35, (0.7, 0.08, 130.0), 0.75, 0.4),
|
||||
(0.74, (0.6, 0.07, 140.0), 0.25, 0.62),
|
||||
(1.0, (0.55, 0.06, 145.0), 0.0, 0.5),
|
||||
],
|
||||
),
|
||||
];
|
||||
let s = fades
|
||||
.iter()
|
||||
.map(|&(name, kind, stops)| {
|
||||
let stops: Vec<(f32, Color, f32, f32)> = stops.iter().map(|&(at, (l, c, h), opacity, mid)| (at, oklch(l, c, h), opacity, mid)).collect();
|
||||
gradient_with(name, kind, GradientMethod::Perceptual, &stops)
|
||||
})
|
||||
.collect();
|
||||
(s, vec![])
|
||||
}
|
||||
|
||||
/// The stops of a [`holographic`] look: offset, opacity and midpoint toward the next stop.
|
||||
type Bands = [(f32, f32, f32)];
|
||||
|
||||
/// Foil: six opaque linear bands, a narrow bright one among them, with off-center midpoints.
|
||||
const FOIL: &Bands = &[(0.0, 1.0, 0.37), (0.13, 1.0, 0.64), (0.34, 1.0, 0.28), (0.48, 1.0, 0.68), (0.71, 1.0, 0.42), (1.0, 1.0, 0.5)];
|
||||
|
||||
/// Glow: five radial rings from a bright center out to a clear edge.
|
||||
const GLOW: &Bands = &[(0.0, 0.95, 0.4), (0.12, 1.0, 0.58), (0.31, 0.72, 0.34), (0.58, 0.3, 0.62), (1.0, 0.0, 0.5)];
|
||||
|
||||
/// A [`holographic`] look: name, kind, stops and the OKLCH color of each stop in order.
|
||||
type Look = (&'static str, GradientKind, &'static Bands, Anchors);
|
||||
|
||||
/// Iridescent looks mixed perceptually: linear foils of narrow pastel and pearl bands, and radial
|
||||
/// glows that fade out to a clear edge. Each color is one stop of [`FOIL`] or [`GLOW`] in order.
|
||||
fn holographic() -> (Vec<Swatch>, Vec<SwatchGroup>) {
|
||||
use GradientKind::{Linear, Radial};
|
||||
// Pale pearl, pastel and deep-violet OKLCH `(l, c, h°)` anchors.
|
||||
const PEARL: (f64, f64, f64) = (0.97, 0.01, 90.0);
|
||||
const SILVER: (f64, f64, f64) = (0.86, 0.015, 255.0);
|
||||
const BLUSH: (f64, f64, f64) = (0.82, 0.055, 340.0);
|
||||
const VIOLET: (f64, f64, f64) = (0.72, 0.1, 310.0);
|
||||
const BLUE: (f64, f64, f64) = (0.73, 0.09, 255.0);
|
||||
const CYAN: (f64, f64, f64) = (0.79, 0.09, 210.0);
|
||||
const MINT: (f64, f64, f64) = (0.82, 0.08, 165.0);
|
||||
const LIME: (f64, f64, f64) = (0.86, 0.085, 125.0);
|
||||
const GOLD: (f64, f64, f64) = (0.89, 0.08, 85.0);
|
||||
const AMBER: (f64, f64, f64) = (0.82, 0.1, 55.0);
|
||||
const CORAL: (f64, f64, f64) = (0.78, 0.09, 25.0);
|
||||
const DEEP_VIOLET: (f64, f64, f64) = (0.42, 0.04, 275.0);
|
||||
let looks: [Look; 14] = [
|
||||
("Prism Veil", Linear, FOIL, &[SILVER, BLUSH, PEARL, CYAN, VIOLET, SILVER]),
|
||||
("Opal Ribbon", Linear, FOIL, &[PEARL, MINT, BLUSH, PEARL, BLUE, SILVER]),
|
||||
("Pearl Flash", Linear, FOIL, &[SILVER, VIOLET, PEARL, GOLD, CYAN, PEARL]),
|
||||
("Aurora Foil", Linear, FOIL, &[BLUE, MINT, PEARL, BLUSH, CYAN, SILVER]),
|
||||
("Iris Sheen", Linear, FOIL, &[BLUSH, VIOLET, PEARL, CYAN, MINT, SILVER]),
|
||||
("Frost Spectrum", Linear, FOIL, &[CYAN, BLUE, PEARL, MINT, BLUSH, SILVER]),
|
||||
("Silver Tide", Linear, FOIL, &[SILVER, CYAN, PEARL, VIOLET, BLUE, SILVER]),
|
||||
("Rose Quartz Gleam", Radial, GLOW, &[PEARL, BLUSH, CORAL, VIOLET, BLUSH]),
|
||||
("Moonstone Shift", Radial, GLOW, &[PEARL, CYAN, MINT, BLUE, SILVER]),
|
||||
("Violet Edge", Radial, GLOW, &[PEARL, VIOLET, BLUSH, BLUE, DEEP_VIOLET]),
|
||||
("Mint Halo", Radial, GLOW, &[PEARL, MINT, CYAN, LIME, MINT]),
|
||||
("Amber Corona", Radial, GLOW, &[PEARL, GOLD, AMBER, CORAL, AMBER]),
|
||||
("Polar Glint", Radial, GLOW, &[PEARL, CYAN, BLUE, VIOLET, BLUE]),
|
||||
("Pastel Orbit", Radial, GLOW, &[PEARL, BLUSH, MINT, CYAN, VIOLET]),
|
||||
];
|
||||
let s = looks
|
||||
.iter()
|
||||
.map(|&(name, kind, bands, colors)| {
|
||||
let stops: Vec<(f32, Color, f32, f32)> =
|
||||
bands.iter().zip(colors).map(|(&(at, opacity, mid), &(l, c, h))| (at, oklch(l, c, h), opacity, mid)).collect();
|
||||
gradient_with(name, kind, GradientMethod::Perceptual, &stops)
|
||||
})
|
||||
.collect();
|
||||
(s, vec![])
|
||||
}
|
||||
|
||||
/// The sequential scales of [`perceptual`]: name and anchors of rising lightness.
|
||||
const SEQUENTIAL: [(&str, Anchors); 5] = [
|
||||
("Ember", &[(0.22, 0.10, 300.0), (0.55, 0.18, 30.0), (0.93, 0.15, 100.0)]),
|
||||
@@ -532,6 +733,99 @@ mod tests {
|
||||
let st = &g.gradient.stops;
|
||||
assert!(st.len() >= 2 && st.windows(2).all(|w| w[0].offset <= w[1].offset), "{}", s.name);
|
||||
assert!(st.iter().all(|s| (0.0..=1.0).contains(&s.offset) && (0.0..=1.0).contains(&s.opacity)));
|
||||
assert!(st.iter().all(|s| (0.01..=0.99).contains(&s.midpoint)), "{}: a midpoint out of range", s.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn organic_fades_are_perceptual_multi_stop_fades_to_transparent() {
|
||||
let lib = builtin_library("organic-fades").unwrap();
|
||||
assert_eq!(GRADIENT_LIBRARIES.iter().map(|b| b.name).position(|n| n == "Organic Fades"), Some(3), "after Neutral Gradients");
|
||||
assert!(lib.groups.is_empty() && (12..=16).contains(&lib.len()), "{} swatches", lib.len());
|
||||
let radial = lib.iter().filter(|s| matches!(&s.paint, Paint::Gradient(g) if g.gradient.kind == GradientKind::Radial)).count();
|
||||
assert!(radial >= 3 && radial * 2 <= lib.len(), "{radial} radial of {}", lib.len());
|
||||
for s in lib.iter() {
|
||||
let Paint::Gradient(g) = &s.paint else { panic!("{} is a gradient", s.name) };
|
||||
let (g, n) = (&g.gradient, &s.name);
|
||||
assert_eq!(g.method, GradientMethod::Perceptual, "{n}");
|
||||
assert!((3..=5).contains(&g.stops.len()), "{n}: {} stops", g.stops.len());
|
||||
assert!(g.stops.windows(2).all(|w| w[0].offset < w[1].offset), "{n}: rising offsets");
|
||||
assert_eq!((g.stops[0].offset, g.stops[g.stops.len() - 1].offset), (0.0, 1.0), "{n}");
|
||||
// Unevenly spaced: some gap differs from an even step.
|
||||
let even = 1.0 / (g.stops.len() - 1) as f32;
|
||||
assert!(g.stops.windows(2).any(|w| (w[1].offset - w[0].offset - even).abs() > 0.02), "{n}: uneven stops");
|
||||
// Every segment's midpoint is off center and within the Gradient panel's 13 to 87%.
|
||||
let segments = &g.stops[..g.stops.len() - 1];
|
||||
assert!(segments.iter().all(|st| (st.midpoint - 0.5).abs() > 0.02 && (0.13..=0.87).contains(&st.midpoint)), "{n}: midpoints");
|
||||
// Fully opaque somewhere, and clear at the end (the edge of a radial one).
|
||||
assert!(g.stops.iter().any(|st| st.opacity == 1.0), "{n}: an opaque stop");
|
||||
assert_eq!(g.stops[g.stops.len() - 1].opacity, 0.0, "{n}: clear at the end");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holographic_holds_seven_opaque_foils_and_seven_glows_to_a_clear_edge() {
|
||||
let lib = builtin_library("holographic").unwrap();
|
||||
let order: Vec<&str> = GRADIENT_LIBRARIES.iter().map(|b| b.name).collect();
|
||||
assert_eq!(order.iter().position(|n| *n == "Holographic"), Some(4), "after Organic Fades: {order:?}");
|
||||
assert!(lib.groups.is_empty());
|
||||
assert_eq!(lib.len(), 14);
|
||||
// No name another built-in gradient has, in any case.
|
||||
let mut others = std::collections::HashSet::new();
|
||||
for other in builtins().filter(|b| b.id != "holographic").map(|b| builtin_library(b.id).unwrap()) {
|
||||
others.extend(other.iter().filter(|s| matches!(s.paint, Paint::Gradient(_))).map(|s| s.name.to_lowercase()));
|
||||
}
|
||||
assert!(lib.iter().all(|s| !others.contains(&s.name.to_lowercase())), "a name another library has");
|
||||
let (mut foils, mut glows) = (0, 0);
|
||||
for s in lib.iter() {
|
||||
let Paint::Gradient(g) = &s.paint else { panic!("{} is a gradient", s.name) };
|
||||
let (g, n) = (&g.gradient, &s.name);
|
||||
assert_eq!(g.method, GradientMethod::Perceptual, "{n}");
|
||||
let bands = match &g.kind {
|
||||
GradientKind::Linear => {
|
||||
foils += 1;
|
||||
FOIL
|
||||
}
|
||||
GradientKind::Radial => {
|
||||
glows += 1;
|
||||
GLOW
|
||||
}
|
||||
kind => panic!("{n}: {kind:?}"),
|
||||
};
|
||||
// Every stop takes its band's offset, opacity and midpoint, and none is dropped.
|
||||
let shape: Vec<(f32, f32, f32)> = g.stops.iter().map(|st| (st.offset, st.opacity, st.midpoint)).collect();
|
||||
assert_eq!(shape, bands, "{n}");
|
||||
assert!(g.stops.iter().all(|st| matches!(st.color, Color::Rgb { .. })), "{n}");
|
||||
}
|
||||
assert_eq!((foils, glows), (7, 7));
|
||||
// Foils are opaque; a glow is clear at the edge.
|
||||
assert!(FOIL.iter().all(|&(_, opacity, _)| opacity == 1.0));
|
||||
assert_eq!(GLOW.last().map(|b| b.1), Some(0.0));
|
||||
// Every segment's midpoint is off center and within the Gradient panel's 13 to 87%.
|
||||
for bands in [FOIL, GLOW] {
|
||||
assert!(bands[..bands.len() - 1].iter().all(|&(_, _, m)| (m - 0.5).abs() > 0.02 && (0.13..=0.87).contains(&m)));
|
||||
assert!(bands.windows(2).all(|w| w[0].0 < w[1].0) && bands[0].0 == 0.0 && bands[bands.len() - 1].0 == 1.0);
|
||||
}
|
||||
// Sampled colors: Prism Veil's bright band is the pearl anchor, and Violet Edge ends in deep violet.
|
||||
let stop = |name: &str, i: usize| match &lib.swatch(name).unwrap().paint {
|
||||
Paint::Gradient(g) => g.gradient.stops[i].color,
|
||||
_ => panic!("{name} is a gradient"),
|
||||
};
|
||||
assert_eq!(stop("Prism Veil", 2), oklch(0.97, 0.01, 90.0));
|
||||
assert_eq!(stop("Violet Edge", 4), oklch(0.42, 0.04, 275.0));
|
||||
let [l, ..] = to_oklab(&stop("Violet Edge", 4));
|
||||
assert!(l < 0.5 && to_oklab(&stop("Prism Veil", 2))[0] > 0.95, "{l}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_other_libraries_keep_classic_mixing_and_centered_midpoints() {
|
||||
for b in builtins().filter(|b| !["organic-fades", "holographic"].contains(&b.id)) {
|
||||
for s in builtin_library(b.id).unwrap().iter() {
|
||||
if let Paint::Gradient(g) = &s.paint {
|
||||
assert_eq!(g.gradient.method, GradientMethod::Classic, "{}", s.name);
|
||||
assert!(g.gradient.stops.iter().all(|st| st.midpoint == 0.5), "{}", s.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,10 +189,41 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
|
||||
let value = match &w.paint {
|
||||
Paint::Solid { color, .. } => css_color(color, 1.0),
|
||||
Paint::Gradient(g) if g.gradient.kind != GradientKind::Freeform => {
|
||||
// A mirrored conic turns counterclockwise, and CSS only turns clockwise: its stops
|
||||
// are written mirrored about the seam instead.
|
||||
let mirrored = g.gradient.kind == GradientKind::Conic && g.geom.is_some_and(|geom| geom.is_mirrored());
|
||||
let stop = |s: &crate::GradientStop| {
|
||||
let at = if mirrored { 1.0 - s.offset } else { s.offset };
|
||||
format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
|
||||
};
|
||||
// Stops that repeat or reflect run that many times across the box.
|
||||
let unrolled = g.gradient.unrolled();
|
||||
let stops: Vec<String> =
|
||||
g.gradient.stops.iter().map(|s| format!("{} {}%", css_color(&s.color, s.opacity), s.offset * 100.0)).collect();
|
||||
if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() };
|
||||
match g.gradient.kind {
|
||||
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
|
||||
// CSS sweeps clockwise from straight up; the angle is counted counterclockwise
|
||||
// from the right.
|
||||
GradientKind::Conic => {
|
||||
format!("conic-gradient(from {}deg, {})", (90.0 - g.angle).rem_euclid(360.0).round(), stops.join(", "))
|
||||
}
|
||||
// CSS has no diamond gradient: four layers, each a quarter of the box with
|
||||
// the stops running from the center out to its corner at a diagonal angle,
|
||||
// make the diamond its fit gives a box of any shape: the level at a point
|
||||
// is its distance from the center along both axes over the box's
|
||||
// half-width plus half-height
|
||||
// (https://www.w3.org/TR/css-images-3/#linear-gradients). Turned by an angle
|
||||
// that is not a multiple of 90 degrees, its corners leave the box's axes,
|
||||
// and a circle stands in for it, as for a radial swatch.
|
||||
GradientKind::Diamond if (1e-9..90.0 - 1e-9).contains(&g.angle.rem_euclid(90.0)) => {
|
||||
format!("radial-gradient(circle, {})", stops.join(", "))
|
||||
}
|
||||
GradientKind::Diamond => {
|
||||
let stops = stops.join(", ");
|
||||
[("top left", 315), ("top right", 45), ("bottom right", 135), ("bottom left", 225)]
|
||||
.map(|(corner, deg)| format!("linear-gradient({deg}deg, {stops}) {corner} / 50% 50% no-repeat"))
|
||||
.join(", ")
|
||||
}
|
||||
_ => format!("linear-gradient({}deg, {})", (90.0 - g.angle).rem_euclid(360.0).round(), stops.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,6 +166,75 @@ fn css_escapes_names_and_writes_gradients() {
|
||||
assert!(read(&text, "x").is_err(), "CSS is written only");
|
||||
}
|
||||
|
||||
/// A conic gradient swatch is a CSS conic gradient starting where its angle points (CSS turns
|
||||
/// clockwise from straight up); a mirrored one, which turns counterclockwise, has its stops mirrored
|
||||
/// about the seam so each color lies on the same side.
|
||||
#[test]
|
||||
fn css_writes_conic_gradient_swatches() {
|
||||
let one = |name: &str, g: GradientPaint| SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch { name: name.into(), paint: Paint::Gradient(Box::new(g)), global: false, spot: false }],
|
||||
groups: vec![],
|
||||
};
|
||||
let mut conic = GradientPaint::new(Gradient { kind: GradientKind::Conic, ..Gradient::default() });
|
||||
conic.angle = 90.0;
|
||||
let text = written(&one("Sweep", conic.clone()), PaletteFormat::Css);
|
||||
assert!(text.contains("--sweep: conic-gradient(from 0deg, #ffffff 0%, #000000 100%);"), "{text}");
|
||||
conic.gradient.stops[0].offset = 0.2;
|
||||
conic.geom = Some(crate::GradientGeom { start: kurbo::Point::ZERO, end: kurbo::Point::new(0.0, -10.0), aspect: -1.0, focal: None });
|
||||
let text = written(&one("Back", conic), PaletteFormat::Css);
|
||||
assert!(text.contains("--back: conic-gradient(from 0deg, #000000 0%, #ffffff 80%);"), "{text}");
|
||||
}
|
||||
|
||||
/// A diamond gradient swatch (CSS has none) is four layered linear gradients, one a quarter of the
|
||||
/// box running from the center out to its corner, for the `background` shorthand.
|
||||
#[test]
|
||||
fn css_writes_diamond_gradient_swatches_as_four_corner_layers() {
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch {
|
||||
name: "Gem".into(),
|
||||
paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient { kind: GradientKind::Diamond, ..Gradient::default() }))),
|
||||
global: false,
|
||||
spot: false,
|
||||
}],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
// Diagonal angles, not `to <corner>`: on a box that isn't square, `to <corner>` would turn
|
||||
// each layer's lines to run through the quarter's other two corners.
|
||||
let layer = |corner: &str, deg: u32| format!("linear-gradient({deg}deg, #ffffff 0%, #000000 100%) {corner} / 50% 50% no-repeat");
|
||||
let want =
|
||||
format!("--gem: {}, {}, {}, {};", layer("top left", 315), layer("top right", 45), layer("bottom right", 135), layer("bottom left", 225));
|
||||
assert!(text.contains(&want), "{text}");
|
||||
// CSS's gradient line for a diagonal angle on a quarter box w × h is (w + h) / √2 long and
|
||||
// starts at the quarter's corner at the box's center: the level at a point x, y from the
|
||||
// center is (|x| + |y|) / (w + h), the level the diamond fitted to the whole box has there.
|
||||
let (w, h) = (100.0f64, 50.0f64);
|
||||
let length = (w + h) / std::f64::consts::SQRT_2;
|
||||
let fit = crate::GradientGeom::fit(GradientKind::Diamond, kurbo::Rect::new(-w, -h, w, h), 0.0);
|
||||
for (x, y) in [(0.0, -50.0), (-100.0, 0.0), (-30.0, -20.0), (-100.0, -50.0)] {
|
||||
// The top-left quarter's layer runs toward (-1, -1).
|
||||
let css = (-x - y) / std::f64::consts::SQRT_2 / length;
|
||||
let model = fit.param_at(GradientKind::Diamond, kurbo::Point::new(x, y));
|
||||
assert!((css - model).abs() < 1e-9, "({x}, {y}): {css} vs {model}");
|
||||
}
|
||||
// Turned a quarter or a half turn, it is the same diamond; turned 30 degrees, a circle stands
|
||||
// in for it.
|
||||
let turned = |angle: f64| {
|
||||
let mut gp = GradientPaint::new(Gradient { kind: GradientKind::Diamond, ..Gradient::default() });
|
||||
gp.angle = angle;
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch { name: "Gem".into(), paint: Paint::Gradient(Box::new(gp)), global: false, spot: false }],
|
||||
groups: vec![],
|
||||
};
|
||||
written(&lib, PaletteFormat::Css)
|
||||
};
|
||||
assert!(turned(90.0).contains(&want) && turned(-180.0).contains(&want), "{}", turned(90.0));
|
||||
assert!(turned(30.0).contains("--gem: radial-gradient(circle, #ffffff 0%, #000000 100%);"), "{}", turned(30.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn css_preserves_fractional_gradient_stop_positions() {
|
||||
for kind in [GradientKind::Linear, GradientKind::Radial] {
|
||||
@@ -192,6 +261,29 @@ fn css_preserves_fractional_gradient_stop_positions() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient swatch that repeats or reflects has its stops written that many times across the
|
||||
/// box, every other run backwards for Reflect.
|
||||
#[test]
|
||||
fn css_writes_spread_gradient_swatches_with_their_stops_repeated() {
|
||||
for (spread, want) in [
|
||||
(crate::GradientSpread::Repeat, "#ffffff 0%, #000000 50%, #ffffff 50%, #000000 100%"),
|
||||
(crate::GradientSpread::Reflect, "#ffffff 0%, #000000 50%, #000000 50%, #ffffff 100%"),
|
||||
] {
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: vec![Swatch {
|
||||
name: "Bands".into(),
|
||||
paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient { spread, repeats: 2, ..Gradient::default() }))),
|
||||
global: false,
|
||||
spot: false,
|
||||
}],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
assert!(text.contains(&format!("--bands: linear-gradient(90deg, {want});")), "{spread:?}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holds_counts_the_swatches_each_format_writes() {
|
||||
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
|
||||
|
||||
@@ -485,6 +485,194 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec<Vec<usize>> {
|
||||
rows
|
||||
}
|
||||
|
||||
/// The distinct colors [`theme_palette`] clusters, at most.
|
||||
const THEME_CANDIDATES: usize = 4096;
|
||||
|
||||
/// The color palette of the weighted colors `samples` (color, weight), for Recolor Artwork's Color
|
||||
/// Theme Picker: at most `n` colors. The same color given twice counts once with both weights,
|
||||
/// and past [`THEME_CANDIDATES`] distinct colors, colors close in Lab merge into the heaviest of
|
||||
/// them first.
|
||||
/// The colors are grouped as [`cluster`] groups them, each group shows its heaviest color (a color
|
||||
/// of `samples`, in its own model; on a tie the one given first), and the heaviest group comes
|
||||
/// first (on a tie the group whose first color was given first). Samples without a positive,
|
||||
/// finite weight are left out, so no samples give no colors.
|
||||
pub fn theme_palette(samples: &[(Color, f32)], n: usize) -> Vec<Color> {
|
||||
let mut index: std::collections::HashMap<ColorKey, usize> = std::collections::HashMap::new();
|
||||
let mut colors: Vec<Color> = vec![];
|
||||
let mut weights: Vec<f32> = vec![];
|
||||
for (c, w) in samples {
|
||||
if !(w.is_finite() && *w > 0.0) {
|
||||
continue;
|
||||
}
|
||||
let i = *index.entry(ColorKey::of(c)).or_insert_with(|| {
|
||||
colors.push(*c);
|
||||
weights.push(0.0);
|
||||
colors.len() - 1
|
||||
});
|
||||
weights[i] += w;
|
||||
}
|
||||
if colors.is_empty() || n == 0 {
|
||||
return vec![];
|
||||
}
|
||||
// At most THEME_CANDIDATES colors are clustered: past that, colors in the same cube of Lab
|
||||
// space merge into the heaviest of them, the cubes doubling in size until few enough remain.
|
||||
if colors.len() > THEME_CANDIDATES {
|
||||
let labs: Vec<[f32; 3]> = colors
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let l = c.to_lab();
|
||||
[l.l, l.a, l.b]
|
||||
})
|
||||
.collect();
|
||||
let mut side = 2.0f32;
|
||||
loop {
|
||||
let mut cube: std::collections::HashMap<[i32; 3], usize> = std::collections::HashMap::new();
|
||||
let (mut top, mut sum): (Vec<usize>, Vec<f32>) = (vec![], vec![]);
|
||||
for (i, lab) in labs.iter().enumerate() {
|
||||
let k = lab.map(|v| (v / side).floor() as i32);
|
||||
match cube.get(&k) {
|
||||
Some(&j) => {
|
||||
sum[j] += weights[i];
|
||||
if weights[i] > weights[top[j]] {
|
||||
top[j] = i;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
cube.insert(k, top.len());
|
||||
top.push(i);
|
||||
sum.push(weights[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if top.len() <= THEME_CANDIDATES {
|
||||
colors = top.iter().map(|&i| colors[i]).collect();
|
||||
weights = sum;
|
||||
break;
|
||||
}
|
||||
side *= 2.0;
|
||||
}
|
||||
}
|
||||
let mut groups: Vec<(f32, usize, Color)> = cluster(&colors, &weights, n)
|
||||
.into_iter()
|
||||
.filter_map(|g| {
|
||||
let total: f32 = g.iter().map(|&i| weights[i]).sum();
|
||||
let top = g.iter().copied().fold(None::<usize>, |best, i| match best {
|
||||
Some(b) if weights[b] >= weights[i] => Some(b),
|
||||
_ => Some(i),
|
||||
})?;
|
||||
Some((total, *g.first()?, colors[top]))
|
||||
})
|
||||
.collect();
|
||||
groups.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
|
||||
groups.into_iter().map(|g| g.2).collect()
|
||||
}
|
||||
|
||||
/// Colors that [`weigh`] moves from one row to another as one: a color they are shown by, how
|
||||
/// often the art uses them and the row they are in. A fixed unit (such as the color a row is
|
||||
/// shown by) stays in its row.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct WeighUnit {
|
||||
pub color: Color,
|
||||
pub uses: f64,
|
||||
pub row: usize,
|
||||
pub fixed: bool,
|
||||
}
|
||||
|
||||
/// The unit-by-row comparisons one [`weigh`] makes, at most.
|
||||
const WEIGH_WORK: usize = 50_000_000;
|
||||
|
||||
/// The uses of `u` that count: a positive finite number, else 0.
|
||||
fn unit_uses(u: &WeighUnit) -> f64 {
|
||||
if u.uses.is_finite() && u.uses > 0.0 { u.uses } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Each row's share of the uses of `units`, in percent (0 for every row when nothing is used).
|
||||
/// Units whose row is past `rows`, or whose uses are not a positive finite number, count nothing.
|
||||
pub fn row_shares(units: &[WeighUnit], rows: usize) -> Vec<f64> {
|
||||
let mut sums = vec![0.0; rows];
|
||||
for u in units {
|
||||
if let Some(s) = sums.get_mut(u.row) {
|
||||
*s += unit_uses(u);
|
||||
}
|
||||
}
|
||||
let total: f64 = sums.iter().sum();
|
||||
if total <= 0.0 {
|
||||
return vec![0.0; rows];
|
||||
}
|
||||
sums.iter().map(|s| s / total * 100.0).collect()
|
||||
}
|
||||
|
||||
/// For Recolor Artwork's Prominent Colors (our own rule): the row each of `units` goes to so that
|
||||
/// each row's share of the uses comes as near its share of `weights` as whole units allow. One
|
||||
/// unit moves at a time, while a move brings the rows' shares nearer their weights (the sum of
|
||||
/// every row's distance from its weight falls); of those moves, the one taken is the unit nearest
|
||||
/// in Lab (CIEDE2000) to the color of the row it goes to (`anchors`), compared with the row it
|
||||
/// leaves; on a tie, the move that brings the shares nearest. Fixed units, units in a row past
|
||||
/// `anchors` and units used no times stay where they are. Weights that are negative or not finite
|
||||
/// count as 0; when no weight is positive, every unit stays. The moves stop after
|
||||
/// [`WEIGH_WORK`] comparisons of a unit with a row, and when the movable units times the rows pass
|
||||
/// it, every unit stays.
|
||||
pub fn weigh(units: &[WeighUnit], anchors: &[Color], weights: &[f64]) -> Vec<usize> {
|
||||
let mut row: Vec<usize> = units.iter().map(|u| u.row).collect();
|
||||
let n = anchors.len();
|
||||
let given = |r: usize| weights.get(r).copied().filter(|x| x.is_finite() && *x > 0.0).unwrap_or(0.0);
|
||||
// Scaled by the largest weight first, so the sum stays finite.
|
||||
let top = (0..n).map(given).fold(0.0, f64::max);
|
||||
let w = |r: usize| if top > 0.0 { given(r) / top } else { 0.0 };
|
||||
let sum_w: f64 = (0..n).map(w).sum();
|
||||
let movable: Vec<usize> = (0..units.len()).filter(|&i| !units[i].fixed && units[i].row < n && unit_uses(&units[i]) > 0.0).collect();
|
||||
let per_pass = movable.len().saturating_mul(n);
|
||||
if sum_w <= 0.0 || n < 2 || movable.is_empty() || per_pass > WEIGH_WORK {
|
||||
return row;
|
||||
}
|
||||
let mut sums = vec![0.0; n];
|
||||
for u in units.iter().filter(|u| u.row < n) {
|
||||
sums[u.row] += unit_uses(u);
|
||||
}
|
||||
let total: f64 = sums.iter().sum();
|
||||
let target: Vec<f64> = (0..n).map(|r| w(r) / sum_w * total).collect();
|
||||
let anchor_labs: Vec<Lab> = anchors.iter().map(|c| c.to_lab()).collect();
|
||||
// Each movable unit's distance to each row's color.
|
||||
let dist: Vec<Vec<f32>> = movable
|
||||
.iter()
|
||||
.map(|&i| {
|
||||
let l = units[i].color.to_lab();
|
||||
anchor_labs.iter().map(|a| delta_e2000(*a, l)).collect()
|
||||
})
|
||||
.collect();
|
||||
// A move must bring the shares nearer by more than rounding.
|
||||
let eps = total * 1e-9;
|
||||
for _ in 0..WEIGH_WORK / per_pass {
|
||||
let mut best: Option<(f32, f64, usize, usize)> = None;
|
||||
for (m, &i) in movable.iter().enumerate() {
|
||||
let (a, x) = (row[i], unit_uses(&units[i]));
|
||||
let before_a = (sums[a] - target[a]).abs();
|
||||
let after_a = (sums[a] - x - target[a]).abs();
|
||||
for b in (0..n).filter(|&b| b != a) {
|
||||
let gain = before_a + (sums[b] - target[b]).abs() - after_a - (sums[b] + x - target[b]).abs();
|
||||
if gain <= eps {
|
||||
continue;
|
||||
}
|
||||
let cost = dist[m][b] - dist[m][a];
|
||||
let better = match best {
|
||||
None => true,
|
||||
Some((c, g, ..)) => cost < c || (cost == c && gain > g),
|
||||
};
|
||||
if better {
|
||||
best = Some((cost, gain, m, b));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((_, _, m, b)) = best else { break };
|
||||
let i = movable[m];
|
||||
let x = unit_uses(&units[i]);
|
||||
sums[row[i]] -= x;
|
||||
sums[b] += x;
|
||||
row[i] = b;
|
||||
}
|
||||
row
|
||||
}
|
||||
|
||||
/// A set of colours to snap to (Limit to Library), with their Lab values cached.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Palette(Vec<(Color, Lab)>);
|
||||
@@ -691,6 +879,39 @@ mod tests {
|
||||
assert!(cluster(&[], &[], 3).is_empty());
|
||||
}
|
||||
|
||||
/// The Color Theme Picker's palette: similar colors merge, each group shows its heaviest
|
||||
/// color in its own model, and the heaviest group comes first.
|
||||
#[test]
|
||||
fn theme_palette_takes_the_heaviest_color_of_each_group_heaviest_first() {
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
let pink = Color::rgb(1.0, 0.2, 0.2);
|
||||
let blue = Color::cmyk(1.0, 0.8, 0.0, 0.0);
|
||||
let navy = Color::cmyk(1.0, 0.9, 0.0, 0.3);
|
||||
let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 2.5), (red, 0.5)];
|
||||
// Blue and navy weigh 4.5, and so do red (3 + 0.5, its two samples add up) and pink.
|
||||
assert_eq!(theme_palette(&samples, 2), vec![red, navy], "a tie: the group given first");
|
||||
let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 1.0)];
|
||||
assert_eq!(theme_palette(&samples, 2), vec![red, blue], "heaviest group first, its heaviest color");
|
||||
assert_eq!(theme_palette(&samples, 9).len(), 4, "never more colors than given");
|
||||
assert_eq!(theme_palette(&samples, 1), vec![red]);
|
||||
assert!(theme_palette(&samples, 0).is_empty());
|
||||
assert!(theme_palette(&[(red, 0.0), (blue, f32::NAN), (pink, -1.0)], 3).is_empty(), "no weight, no colors");
|
||||
assert!(theme_palette(&[], 3).is_empty());
|
||||
}
|
||||
|
||||
/// Past 4,096 distinct colors, close colors merge before clustering: the palette still keeps
|
||||
/// a heavy color apart from thousands of light ones.
|
||||
#[test]
|
||||
fn theme_palette_merges_close_colors_past_its_candidate_limit() {
|
||||
let mut samples: Vec<(Color, f32)> = (0..20_000).map(|i| (Color::rgb(0.0, 0.0, 0.3 + 0.7 * i as f32 / 20_000.0), 0.001)).collect();
|
||||
samples.extend((0..20_000).map(|i| (Color::rgb(1.0, 0.8 * i as f32 / 20_000.0, 0.0), 0.0001)));
|
||||
samples.push((Color::rgb(0.0, 1.0, 0.0), 50.0));
|
||||
let p = theme_palette(&samples, 3);
|
||||
assert_eq!(p.len(), 3);
|
||||
assert_eq!(p[0], Color::rgb(0.0, 1.0, 0.0), "the heavy green first, exactly as given");
|
||||
assert!(p[1].to_hsb()[0] > 180.0 && p[2].to_hsb()[0] < 90.0, "then the blues, then the reds and oranges: {p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hue_shift_with_own_model_puts_every_colour_of_the_row_in_the_new_model() {
|
||||
let to = Color::cmyk(0.0, 1.0, 1.0, 0.0);
|
||||
@@ -796,4 +1017,55 @@ mod tests {
|
||||
assert!(matches!(Rng::new(3).saturation_brightness(Color::lab(50.0, 40.0, 20.0)), Color::Lab { .. }));
|
||||
assert_eq!(Rng::new(3).saturation_brightness(Color::gray(0.4)).to_hsb()[1], 0.0, "greys stay grey");
|
||||
}
|
||||
|
||||
fn unit(color: Color, uses: f64, row: usize, fixed: bool) -> WeighUnit {
|
||||
WeighUnit { color, uses, row, fixed }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_shares_are_percent_of_the_uses() {
|
||||
let units = [unit(Color::rgb(1.0, 0.0, 0.0), 3.0, 0, true), unit(Color::rgb(0.0, 0.0, 1.0), 1.0, 1, true), unit(Color::WHITE, 5.0, 4, false)];
|
||||
assert_eq!(row_shares(&units, 2), vec![75.0, 25.0]);
|
||||
assert_eq!(row_shares(&[], 2), vec![0.0, 0.0]);
|
||||
assert_eq!(row_shares(&[unit(Color::WHITE, f64::NAN, 0, false)], 1), vec![0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_moves_the_nearest_colors_toward_the_weights() {
|
||||
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
let units = [
|
||||
unit(red, 1.0, 0, true),
|
||||
unit(Color::rgb(0.9, 0.1, 0.3), 1.0, 0, false),
|
||||
unit(Color::rgb(0.5, 0.0, 0.8), 1.0, 0, false),
|
||||
unit(blue, 1.0, 1, true),
|
||||
];
|
||||
// Equal weights: the reddish purple, nearer blue than the red-pink is, moves.
|
||||
assert_eq!(weigh(&units, &[red, blue], &[1.0, 1.0]), vec![0, 0, 1, 1]);
|
||||
// Most of the weight on blue: both movable colors go, the row's own color stays.
|
||||
assert_eq!(weigh(&units, &[red, blue], &[0.0, 1.0]), vec![0, 1, 1, 1]);
|
||||
// Weights already met, or none positive: nothing moves.
|
||||
assert_eq!(weigh(&units, &[red, blue], &[3.0, 1.0]), vec![0, 0, 0, 1]);
|
||||
assert_eq!(weigh(&units, &[red, blue], &[0.0, f64::NAN]), vec![0, 0, 0, 1]);
|
||||
assert_eq!(weigh(&units, &[red, blue], &[1e308, 1e308]), vec![0, 0, 1, 1], "huge weights act as equal ones");
|
||||
assert_eq!(weigh(&units, &[red], &[1.0]), vec![0, 0, 0, 1], "a row past the anchors keeps its units");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_takes_whole_units_and_stops_when_no_move_helps() {
|
||||
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
// A heavy unit: moving it would overshoot by more than staying misses.
|
||||
let units = [unit(red, 1.0, 0, true), unit(Color::rgb(0.8, 0.0, 0.2), 10.0, 0, false), unit(blue, 10.0, 1, true)];
|
||||
assert_eq!(weigh(&units, &[red, blue], &[1.0, 1.4]), vec![0, 0, 1]);
|
||||
assert_eq!(weigh(&units, &[red, blue], &[1.0, 20.0]), vec![0, 1, 1]);
|
||||
// Many units: the result still follows the weights.
|
||||
let many: Vec<WeighUnit> = (0..400).map(|i| unit(Color::rgb(i as f32 / 400.0, 0.2, 1.0 - i as f32 / 400.0), 1.0, 0, i == 0)).collect();
|
||||
let rows = weigh(&many, &[Color::rgb(0.0, 0.2, 1.0), Color::rgb(1.0, 0.2, 0.0)], &[1.0, 3.0]);
|
||||
assert_eq!(rows.iter().filter(|r| **r == 1).count(), 300);
|
||||
assert!(rows[399] == 1 && rows[1] == 0, "the reddest colors go to the red row");
|
||||
// Past the work limit (8,000 units by 7,000 rows) nothing moves.
|
||||
let units: Vec<WeighUnit> = (0..8_000).map(|i| unit(Color::WHITE, 1.0, 0, i == 0)).collect();
|
||||
let anchors = vec![Color::BLACK; 7_000];
|
||||
let weights = vec![1.0; 7_000];
|
||||
assert!(weigh(&units, &anchors, &weights).iter().all(|r| *r == 0));
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ mod stroke_style;
|
||||
|
||||
pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds};
|
||||
pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile};
|
||||
pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
|
||||
pub use stroke_style::{ArrowAlign, Arrowhead, CustomArrowhead, Dash, LineCap, LineJoin, StrokeAlign};
|
||||
|
||||
/// One entry of the appearance stack.
|
||||
// A stroke takes 328 bytes and a fill 104; an appearance holds a few of each.
|
||||
@@ -444,13 +444,14 @@ impl Appearance {
|
||||
}
|
||||
}
|
||||
/// Map placed gradients through a warp, given its local affine approximation at a point (taken
|
||||
/// at each gradient's centre: the start of a radial, the middle of a linear vector). Freeform
|
||||
/// points each follow the warp at their own position.
|
||||
/// at each gradient's center: the start of a radial, conic or diamond, the middle of a linear
|
||||
/// vector).
|
||||
/// Freeform points each follow the warp at their own position.
|
||||
pub fn warp_gradients(&mut self, near: &dyn Fn(vectorcraft_geom::Point) -> vectorcraft_geom::Affine) {
|
||||
for g in self.gradients_mut() {
|
||||
let freeform = g.freeform.take();
|
||||
if let Some(geom) = g.geom {
|
||||
let c = if g.gradient.kind == vectorcraft_color::GradientKind::Radial { geom.start } else { geom.start.midpoint(geom.end) };
|
||||
let c = if g.gradient.kind.is_centered() { geom.start } else { geom.start.midpoint(geom.end) };
|
||||
g.transform(near(c));
|
||||
}
|
||||
g.freeform = freeform.map(|mut f| {
|
||||
|
||||
@@ -193,8 +193,10 @@ impl StrokeLayer {
|
||||
/// How far the start (`end == false`) or end arrowhead can reach from its end point (0
|
||||
/// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap.
|
||||
pub fn head_reach(&self, end: bool) -> f64 {
|
||||
let head = if end { self.end_arrow } else { self.start_arrow };
|
||||
head.map_or(0.0, |k| k.reach() * self.arrow_weight(end) + self.width / 2.0)
|
||||
let head = if end { &self.end_arrow } else { &self.start_arrow };
|
||||
// A custom head can paint in front of its tip, which Extend puts past the end point.
|
||||
let reach = |k: &Arrowhead| if self.arrow_align == ArrowAlign::Extend { k.reach().max(k.length()) } else { k.reach() };
|
||||
head.as_ref().map_or(0.0, |k| reach(k) * self.arrow_weight(end) + self.width / 2.0)
|
||||
}
|
||||
/// How far the arrowheads can reach from the path's end points (0 without heads).
|
||||
pub fn arrow_reach(&self) -> f64 {
|
||||
|
||||
@@ -26,11 +26,16 @@ impl WidthProfile {
|
||||
pub fn at(&self, t: f64) -> (f64, f64) {
|
||||
Self::at_points(&self.points, t)
|
||||
}
|
||||
/// [`Self::at`] of a profile's points (a preset's or a saved profile's). Each side runs through
|
||||
/// its points on a monotone cubic curve (Fritsch–Carlson): it flows through a width point
|
||||
/// without a kink, turns flat at a point wider or narrower than both neighbours, and never
|
||||
/// goes past either point of the span it is in (#5714). Points on one straight line stay on
|
||||
/// it. A step (two points at one position, [`Self::around`]) ends the curve on each side of it.
|
||||
/// [`Self::at`] of a profile's points (a preset's or a saved profile's).
|
||||
///
|
||||
/// Each side runs through its points on a cubic Hermite curve, its slope at each one the
|
||||
/// weighted harmonic mean of the secants either side (Fritsch–Carlson). That is C1 continuous
|
||||
/// and monotone between points, so it never overshoots them, a point eases into its neighbours
|
||||
/// instead of making a corner, and moving one reshapes the curve as far as its neighbours'
|
||||
/// neighbours (their slopes depend on it). The ends of a run use the one-sided PCHIP slope
|
||||
/// from its first two secants, or the secant when it has only two points, so a two-point
|
||||
/// profile stays a straight taper and the lens is a parabola. Two points at one `t` are still
|
||||
/// a step: each run either side ends independently at it.
|
||||
pub fn at_points(p: &[(f64, f64, f64)], t: f64) -> (f64, f64) {
|
||||
if p.is_empty() {
|
||||
return (1.0, 1.0);
|
||||
@@ -71,9 +76,10 @@ impl WidthProfile {
|
||||
// Two swells between narrow necks.
|
||||
ProfilePreset { id: "wave", label: "Wave", points: &[(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)] },
|
||||
];
|
||||
/// The widest the stroke gets, as a multiple of its weight, 1 for a profile without points. Each
|
||||
/// side stays between the widths of the two points of each span ([`Self::at_points`]), but the
|
||||
/// two sides needn't peak together, so a span counts its wider left and its wider right.
|
||||
/// The widest the stroke gets, as a multiple of its weight, 1 for a profile without points.
|
||||
/// Each side's smooth curve stays between the widths of the two points of each span
|
||||
/// ([`Self::at_points`]), but the two sides needn't peak together, so a span counts its wider
|
||||
/// left and its wider right.
|
||||
pub fn widest(&self) -> f64 {
|
||||
let p = &self.points;
|
||||
if p.is_empty() {
|
||||
@@ -196,6 +202,13 @@ impl AngleProfile {
|
||||
if v.is_finite() { vectorcraft_geom::normalize_deg(v) } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The angle at `t` (0..1) as [`Self::at`] reads it, but in the samples' own running degrees,
|
||||
/// so the whole turns the curve makes along the stroke are kept; 0 without any samples.
|
||||
pub fn unwrapped_at(&self, t: f64) -> f64 {
|
||||
let v = interpolated(&self.points, t).unwrap_or(0.0);
|
||||
if v.is_finite() { v } else { 0.0 }
|
||||
}
|
||||
|
||||
/// A profile from (position, degrees) samples in order along the stroke: non-finite ones are
|
||||
/// dropped, each sample is joined to the one before it the shorter way round, and the curve is
|
||||
/// simplified to within 1° and kept to [`PressureProfile::MAX_POINTS`]. `None` without a sample.
|
||||
@@ -249,11 +262,27 @@ impl AngleProfile {
|
||||
/// How close two width points' positions are to make a step ([`WidthProfile::around`]).
|
||||
const STEP: f64 = 1e-7;
|
||||
|
||||
/// The one-sided three-point PCHIP slope at the start of a run, from the first two secants.
|
||||
/// A sign change caps the slope, and a slope that turns back on the first secant is flattened.
|
||||
/// Runs of only two points use their secant instead (see [`tangent`]).
|
||||
fn end_slope(h0: f64, h1: f64, d0: f64, d1: f64) -> f64 {
|
||||
let m = ((2.0 * h0 + h1) * d0 - h0 * d1) / (h0 + h1);
|
||||
if !m.is_finite() || m * d0 <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
if d0 * d1 < 0.0 {
|
||||
return if d0 > 0.0 { m.min(3.0 * d0) } else { m.max(3.0 * d0) };
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// The slope of one side (`v` reads it from a point) of width profile `p` at its point `j`, in
|
||||
/// width per unit of position: Fritsch–Carlson's choice for a monotone cubic curve. It is 0 where
|
||||
/// the point is wider or narrower than both neighbours, the weighted harmonic mean of the slopes
|
||||
/// of the spans on either side elsewhere (never more than three times either, so no span
|
||||
/// overshoots its points), and the span's own slope at an end of the profile or beside a step.
|
||||
/// the point is wider or narrower than both neighbours, and the weighted harmonic mean of the
|
||||
/// slopes of the spans on either side elsewhere (never more than three times either, so no span
|
||||
/// overshoots its points). The ends of a run take the one-sided three-point PCHIP slope, or their
|
||||
/// secant when the run has only two points; a step ends the run on each side, so the points either
|
||||
/// side of it do not see across it.
|
||||
fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f64 {
|
||||
let Some(q) = p.get(j) else { return 0.0 };
|
||||
let before = j.checked_sub(1).and_then(|k| p.get(k)).filter(|a| q.0 - a.0 > STEP);
|
||||
@@ -268,8 +297,18 @@ fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f
|
||||
let (h0, h1) = (q.0 - a.0, b.0 - q.0);
|
||||
3.0 * (h0 + h1) / ((2.0 * h1 + h0) / d0 + (h1 + 2.0 * h0) / d1)
|
||||
}
|
||||
(Some(a), None) => slope(a, q),
|
||||
(None, Some(b)) => slope(q, b),
|
||||
// The end of a run: its previous two points set a one-sided three-point slope, or its
|
||||
// secant when the run has only two points (the point before `a` is on the other side of a
|
||||
// step, or does not exist).
|
||||
(Some(a), None) => {
|
||||
let Some(prev) = j.checked_sub(2).and_then(|k| p.get(k)).filter(|z| a.0 - z.0 > STEP) else { return slope(a, q) };
|
||||
end_slope(q.0 - a.0, a.0 - prev.0, slope(a, q), slope(prev, a))
|
||||
}
|
||||
// The start of a run, symmetrically.
|
||||
(None, Some(b)) => {
|
||||
let Some(next) = p.get(j + 2).filter(|z| z.0 - b.0 > STEP) else { return slope(q, b) };
|
||||
end_slope(b.0 - q.0, next.0 - b.0, slope(q, b), slope(b, next))
|
||||
}
|
||||
(None, None) => 0.0,
|
||||
}
|
||||
}
|
||||
@@ -424,12 +463,12 @@ mod tests {
|
||||
#[test]
|
||||
fn widths_run_smoothly_through_width_points() {
|
||||
// A swell in the middle: flat at its widest, and a quarter of the way along above the
|
||||
// straight ramp from 1 to 3 (2).
|
||||
// straight ramp from 1 to 3 (2) because the end eases out of the first point.
|
||||
let swell = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 2.0), (1.0, 1.0, 1.0)] };
|
||||
let (before, after) = slopes(&swell, 0.5);
|
||||
assert!(before.abs() < 1e-4 && after.abs() < 1e-4, "{before} {after}");
|
||||
let (l, r) = swell.at(0.25);
|
||||
assert!((l - 2.25).abs() < 1e-12 && (r - 1.625).abs() < 1e-12, "{l} {r}");
|
||||
assert!((l - 2.5).abs() < 1e-12 && (r - 1.75).abs() < 1e-12, "{l} {r}");
|
||||
// Rising on both sides of a point: the slope is the same either side of it.
|
||||
let rise = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.3, 1.0, 1.0), (1.0, 4.0, 4.0)] };
|
||||
let (before, after) = slopes(&rise, 0.3);
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::{PathData, Rect};
|
||||
|
||||
use super::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
@@ -53,8 +57,74 @@ impl Dash {
|
||||
/// (the open arrow's arms are cut square a little behind the box).
|
||||
const HEAD_REACH: f64 = 4.6;
|
||||
|
||||
/// An arrowhead the user drew (Stroke panel menu › Edit Arrowheads…), carried with its art so a
|
||||
/// document that uses it draws it wherever it opens.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(from = "CustomArrowheadData")]
|
||||
pub struct CustomArrowhead {
|
||||
/// The name the arrowhead menus show (the symbol's name in the arrowheads file).
|
||||
pub name: String,
|
||||
/// The filled outline (non-zero rule) in head units: x from the tip (0) back along the line, y
|
||||
/// across it, positive to the right of the direction the head points. A head is 4 units wide,
|
||||
/// as the built-in heads are, and a unit is the head's weight.
|
||||
pub path: PathData,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CustomArrowheadData {
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
path: PathData,
|
||||
}
|
||||
|
||||
impl From<CustomArrowheadData> for CustomArrowhead {
|
||||
fn from(d: CustomArrowheadData) -> Self {
|
||||
CustomArrowhead::new(d.name, d.path)
|
||||
}
|
||||
}
|
||||
|
||||
impl CustomArrowhead {
|
||||
/// The most anchors a custom head's outline may have, and the most subpaths.
|
||||
pub const MAX_ANCHORS: usize = 4096;
|
||||
/// How far from the tip a custom head's outline may reach, in head units.
|
||||
pub const MAX_UNITS: f64 = 64.0;
|
||||
|
||||
/// Head `name` with outline `path` (in head units). An outline with more than
|
||||
/// [`Self::MAX_ANCHORS`] anchors or subpaths, a point that is not finite, or a point farther
|
||||
/// than [`Self::MAX_UNITS`] from the tip is dropped: the head then draws nothing.
|
||||
pub fn new(name: String, path: PathData) -> Self {
|
||||
let path = if Self::fits(&path) { path } else { PathData::default() };
|
||||
CustomArrowhead { name, path }
|
||||
}
|
||||
/// Whether outline `path` has at most [`Self::MAX_ANCHORS`] anchors and as many subpaths, with
|
||||
/// finite points within [`Self::MAX_UNITS`] only.
|
||||
pub fn fits(path: &PathData) -> bool {
|
||||
let anchors = path.subpaths.iter().map(|s| s.anchors.len()).sum::<usize>();
|
||||
let near = |p: vectorcraft_geom::Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= Self::MAX_UNITS && p.y.abs() <= Self::MAX_UNITS;
|
||||
anchors <= Self::MAX_ANCHORS
|
||||
&& path.subpaths.len() <= Self::MAX_ANCHORS
|
||||
&& path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| near(a.p) && near(a.h_in) && near(a.h_out))
|
||||
}
|
||||
fn bounds(&self) -> Option<Rect> {
|
||||
self.path.control_bounds()
|
||||
}
|
||||
/// How far any part of the head can be from its tip, in head units.
|
||||
pub fn reach(&self) -> f64 {
|
||||
self.bounds().map_or(0.0, |b| b.x0.hypot(b.y0).max(b.x1.hypot(b.y0)).max(b.x0.hypot(b.y1)).max(b.x1.hypot(b.y1)))
|
||||
}
|
||||
/// How far the head spreads either side of its line, in head units.
|
||||
pub fn half_width(&self) -> f64 {
|
||||
self.bounds().map_or(0.0, |b| b.y0.abs().max(b.y1.abs()))
|
||||
}
|
||||
/// Where the stroke ends under the head, in head units back from the tip: halfway along the
|
||||
/// head's length.
|
||||
pub fn stop(&self) -> f64 {
|
||||
self.bounds().map_or(0.0, |b| b.x1.max(0.0) / 2.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Arrowhead {
|
||||
Triangle,
|
||||
TriangleOpen,
|
||||
@@ -102,6 +172,8 @@ pub enum Arrowhead {
|
||||
/// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as
|
||||
/// the other heads.
|
||||
LineArrow,
|
||||
/// A head the user drew, with its art.
|
||||
Custom(Arc<CustomArrowhead>),
|
||||
}
|
||||
|
||||
impl Arrowhead {
|
||||
@@ -151,23 +223,43 @@ impl Arrowhead {
|
||||
];
|
||||
|
||||
/// How far any part of the head can be from its tip, in units of its weight.
|
||||
pub fn reach(self) -> f64 {
|
||||
pub fn reach(&self) -> f64 {
|
||||
match self {
|
||||
// Its farthest corners are 4 + ½√2 back and 4 − ½√2 out.
|
||||
Arrowhead::LineArrow => 5.75,
|
||||
Arrowhead::Custom(c) => c.reach(),
|
||||
_ => HEAD_REACH,
|
||||
}
|
||||
}
|
||||
/// How far the head spreads either side of its line, in units of its weight.
|
||||
pub fn half_width(self) -> f64 {
|
||||
pub fn half_width(&self) -> f64 {
|
||||
match self {
|
||||
Arrowhead::LineArrow => 4.0,
|
||||
Arrowhead::Custom(c) => c.half_width(),
|
||||
_ => 2.0,
|
||||
}
|
||||
}
|
||||
/// How far past its end point a head placed with [`ArrowAlign::Extend`] can paint, in units of
|
||||
/// its weight: the built-in heads' length, or a custom head's reach past its tip, which sits
|
||||
/// [`CustomArrowhead::stop`] past the end point.
|
||||
pub fn length(&self) -> f64 {
|
||||
match self {
|
||||
Arrowhead::Custom(c) => c.stop() + c.reach(),
|
||||
_ => 4.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The name the arrowhead menus show.
|
||||
pub fn label(self) -> &'static str {
|
||||
/// The name the arrowhead menus show: [`Self::label`], or a custom head's own name.
|
||||
pub fn name(&self) -> &str {
|
||||
match self {
|
||||
Arrowhead::Custom(c) => &c.name,
|
||||
_ => self.label(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The name the arrowhead menus show for a built-in head ("Custom" for a custom one, whose
|
||||
/// own name is [`Self::name`]).
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
Arrowhead::Triangle => "Triangle",
|
||||
Arrowhead::TriangleOpen => "Triangle (open)",
|
||||
@@ -210,6 +302,7 @@ impl Arrowhead {
|
||||
Arrowhead::TriangleBar => "Triangle to Bar",
|
||||
Arrowhead::Oval => "Oval",
|
||||
Arrowhead::LineArrow => "Line Arrow",
|
||||
Arrowhead::Custom(_) => "Custom",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,12 +197,85 @@ fn strokes_without_pressure_round_trip_unchanged() {
|
||||
fn profile_interp() {
|
||||
let p = WidthProfile::lens();
|
||||
assert_eq!(p.at(0.5), (1.0, 1.0));
|
||||
// Half way up the lens the width curves above the straight ramp (0.5), flattening into its
|
||||
// widest point (#5714).
|
||||
assert_eq!(p.at(0.25), (0.625, 0.625));
|
||||
// The lens is a parabola between its ends, so a quarter of the way along is 0.75: above the
|
||||
// 0.5 a straight taper would give.
|
||||
assert_eq!(p.at(0.25), (0.75, 0.75));
|
||||
assert_eq!(p.at(2.0), (0.0, 0.0));
|
||||
}
|
||||
|
||||
/// The width runs smoothly between points: it passes through them, has one slope either side
|
||||
/// of one, and never overshoots the widths its points set.
|
||||
#[test]
|
||||
fn profile_is_smooth_between_points() {
|
||||
let p = [(0.0, 1.0, 2.0), (0.5, 0.2, 2.0), (1.0, 1.0, 2.0)];
|
||||
assert!((WidthProfile::at_points(&p, 0.5).0 - 0.2).abs() < 1e-12);
|
||||
let slope = |t: f64| (WidthProfile::at_points(&p, t + 1e-6).0 - WidthProfile::at_points(&p, t - 1e-6).0) / 2e-6;
|
||||
// A local minimum at the middle point is flat there, so the two sides agree.
|
||||
assert!(slope(0.5).abs() < 1e-3, "{}", slope(0.5));
|
||||
for k in 0..=100 {
|
||||
let w = WidthProfile::at_points(&p, k as f64 / 100.0).0;
|
||||
assert!((0.2..=1.0).contains(&w), "{w} at {k}");
|
||||
}
|
||||
// The side with no points of its own stays flat.
|
||||
for k in 0..=100 {
|
||||
assert!((WidthProfile::at_points(&p, k as f64 / 100.0).1 - 2.0).abs() < 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
/// A run with only two points takes its secant as both end slopes, so it stays a straight
|
||||
/// taper on each side instead of becoming a smoothstep.
|
||||
#[test]
|
||||
fn profile_two_point_runs_are_linear() {
|
||||
let p = [(0.0, 0.0, 1.0), (1.0, 1.0, 0.0)];
|
||||
for k in 0..=100 {
|
||||
let t = k as f64 / 100.0;
|
||||
let (l, r) = WidthProfile::at_points(&p, t);
|
||||
assert!((l - t).abs() < 1e-12, "left {l} at {t}");
|
||||
assert!((r - (1.0 - t)).abs() < 1e-12, "right {r} at {t}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The lens's one-sided end slopes make it a parabola: at a quarter of the way it is 0.75,
|
||||
/// above the 0.5 a straight line between its points would give.
|
||||
#[test]
|
||||
fn profile_lens_is_convex() {
|
||||
let p = WidthProfile::lens();
|
||||
assert!((p.at(0.25).0 - 0.75).abs() < 1e-12);
|
||||
assert!((p.at(0.75).0 - 0.75).abs() < 1e-12);
|
||||
for k in 1..25 {
|
||||
let t = k as f64 / 100.0;
|
||||
assert!(p.at(t).0 > 2.0 * t, "{} at {t}", p.at(t).0);
|
||||
assert!(p.at(1.0 - t).0 > 2.0 * t, "{} at {}", p.at(1.0 - t).0, 1.0 - t);
|
||||
}
|
||||
}
|
||||
|
||||
/// A step still steps, and the smooth runs either side meet it flat.
|
||||
#[test]
|
||||
fn profile_steps_stay_steps() {
|
||||
let p = [(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 2.0, 2.0), (1.0, 2.0, 2.0)];
|
||||
assert_eq!(WidthProfile::at_points(&p, 0.5), (1.0, 1.0));
|
||||
assert_eq!(WidthProfile::at_points(&p, 0.5 + 1e-6), (2.0, 2.0));
|
||||
assert_eq!(WidthProfile::at_points(&p, 0.5 - 1e-6), (1.0, 1.0));
|
||||
assert_eq!(WidthProfile::at_points(&p, 0.25), (1.0, 1.0));
|
||||
assert_eq!(WidthProfile::at_points(&p, 0.75), (2.0, 2.0));
|
||||
}
|
||||
|
||||
/// Moving a point only reshapes the segments beside it (local influence), not the whole path.
|
||||
#[test]
|
||||
fn profile_points_only_affect_the_curve_around_them() {
|
||||
// A monotone run, so no neighbouring slope is held flat by a local extremum.
|
||||
let a = [(0.0, 0.0, 0.0), (0.25, 0.3, 0.3), (0.5, 0.5, 0.5), (0.75, 0.7, 0.7), (1.0, 1.0, 1.0)];
|
||||
let mut b = a;
|
||||
b[3] = (0.75, 0.9, 0.9);
|
||||
// Moving p[3] changes the slopes at p[2] and p[3], so p[1] and p[4] also shape the
|
||||
// curve: nothing before p[1] may move.
|
||||
for k in 0..=24 {
|
||||
let t = k as f64 / 100.0;
|
||||
assert_eq!(WidthProfile::at_points(&a, t), WidthProfile::at_points(&b, t), "at {t}");
|
||||
}
|
||||
assert_ne!(WidthProfile::at_points(&a, 0.3), WidthProfile::at_points(&b, 0.3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_presets_round_trip_their_ids() {
|
||||
for p in WidthProfile::PRESETS {
|
||||
@@ -264,13 +337,65 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
|
||||
];
|
||||
for name in SAVED {
|
||||
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
|
||||
assert_eq!(serde_json::to_value(a).unwrap(), name);
|
||||
assert_eq!(serde_json::to_value(&a).unwrap(), name);
|
||||
assert_eq!(Arrowhead::ALL.iter().filter(|x| **x == a).count(), 1, "{name} in the menu once");
|
||||
}
|
||||
let labels: std::collections::HashSet<&str> = Arrowhead::ALL.iter().map(|a| a.label()).collect();
|
||||
assert_eq!(labels.len(), Arrowhead::ALL.len(), "labels are distinct");
|
||||
}
|
||||
|
||||
/// A custom head: a triangle from its tip back 3 units, 2 units right and 1 left of its line.
|
||||
fn custom_head() -> Arrowhead {
|
||||
use vectorcraft_geom::{PathData, Point, SubPath};
|
||||
let path = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true));
|
||||
Arrowhead::Custom(std::sync::Arc::new(CustomArrowhead::new("Wedge".into(), path)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_arrowheads_carry_their_art_and_measure_it() {
|
||||
let head = custom_head();
|
||||
assert_eq!((head.name(), head.label()), ("Wedge", "Custom"));
|
||||
assert_eq!(head.reach(), 3.0f64.hypot(2.0));
|
||||
assert_eq!(head.half_width(), 2.0);
|
||||
let Arrowhead::Custom(c) = &head else { panic!("custom") };
|
||||
assert_eq!(c.stop(), 1.5, "the line stops halfway along the head");
|
||||
// Saved with the stroke, art and all, beside the built-in heads' names.
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
|
||||
(st.start_arrow, st.end_arrow) = (Some(Arrowhead::Triangle), Some(head.clone()));
|
||||
let json = serde_json::to_value(&st).unwrap();
|
||||
assert_eq!(json["start_arrow"], "Triangle");
|
||||
assert_eq!(json["end_arrow"]["Custom"]["name"], "Wedge");
|
||||
let back: StrokeLayer = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(back, st);
|
||||
// Extended, the tip sits the stop past the end point; on it, only the reach counts.
|
||||
assert_eq!(head.length(), 1.5 + head.reach());
|
||||
assert_eq!(st.head_reach(true), head.length() * 2.0 + 1.0);
|
||||
st.arrow_align = ArrowAlign::Tip;
|
||||
assert_eq!(st.head_reach(true), head.reach() * 2.0 + 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_arrowheads_out_of_bounds_draw_nothing() {
|
||||
let Arrowhead::Custom(c) = custom_head() else { panic!("custom") };
|
||||
let mut path = c.path.clone();
|
||||
path.subpaths[0].anchors[1] = vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1e9, 0.0));
|
||||
// A file can hold what `new` drops: reading it drops it too.
|
||||
let json = serde_json::to_value(CustomArrowhead { name: "Wedge".into(), path }).unwrap();
|
||||
let far: CustomArrowhead = serde_json::from_value(json).unwrap();
|
||||
assert_eq!((far.name.as_str(), far.path.subpaths.len()), ("Wedge", 0));
|
||||
assert_eq!((far.reach(), far.half_width(), far.stop()), (0.0, 0.0, 0.0));
|
||||
let anchors = vec![vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1.0, 0.0)); CustomArrowhead::MAX_ANCHORS + 1];
|
||||
let many = CustomArrowhead::new("Many".into(), vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::new(anchors, true)));
|
||||
assert!(many.path.subpaths.is_empty(), "too many anchors");
|
||||
// Empty subpaths add no anchors, and still count.
|
||||
let mut hollow = c.path.clone();
|
||||
hollow.subpaths.extend(std::iter::repeat_n(vectorcraft_geom::SubPath::new(vec![], false), CustomArrowhead::MAX_ANCHORS));
|
||||
assert!(!CustomArrowhead::fits(&hollow), "too many subpaths");
|
||||
let json = serde_json::to_value(CustomArrowhead { name: "Hollow".into(), path: hollow }).unwrap();
|
||||
let hollow: CustomArrowhead = serde_json::from_value(json).unwrap();
|
||||
assert!(hollow.path.subpaths.is_empty(), "too many subpaths, read back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_align_defaults_to_extend_and_round_trips() {
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
|
||||
|
||||
+1045
-72
File diff suppressed because it is too large.
Load diff
+270
-45
@@ -3,6 +3,7 @@
|
||||
//! the ruler origin and the objects an edit touches), so a file holding something beyond it could be
|
||||
//! opened but not edited: one object, artboard or guide out there made every move fail.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
@@ -15,7 +16,8 @@ pub struct BeyondCanvas {
|
||||
/// Objects removed whole (a layer or group keeps its children within the canvas).
|
||||
pub objects: usize,
|
||||
pub artboards: usize,
|
||||
/// Guides beyond the canvas, and the artboard guides of the artboards removed.
|
||||
/// Guides beyond the canvas, the artboard guides of the artboards removed, and the layer
|
||||
/// guides of the layers removed.
|
||||
pub guides: usize,
|
||||
/// The ruler origin was beyond the canvas and is back at the origin.
|
||||
pub ruler_origin: bool,
|
||||
@@ -71,27 +73,41 @@ fn clipping(n: &Node) -> Option<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `n`, or any object in it, reach beyond the canvas? A container is looked into object by
|
||||
/// object: its own bounds leave out a layer's hidden objects and, when it clips, all but its
|
||||
/// clipping path.
|
||||
fn reaches_beyond(n: &Node) -> bool {
|
||||
match clipping(n) {
|
||||
None => beyond(n),
|
||||
Some(_) => n.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c))),
|
||||
/// The objects of a layer or group that a walk picked, by index in order, each with what was
|
||||
/// picked inside it (nothing for an object that is not a container).
|
||||
#[derive(Debug, Default)]
|
||||
struct Picked(Vec<(usize, Picked)>);
|
||||
|
||||
/// What in `n` reaches beyond the canvas, by `far`, or `None` when nothing does. A container is
|
||||
/// looked into object by object: its own bounds leave out a layer's hidden objects and, when it
|
||||
/// clips, all but its clipping path. Each object is measured once, and the objects a clipping
|
||||
/// path beyond the canvas clips are not measured: they go with it (see [`clips_beyond`]).
|
||||
fn reach(n: &Node, far: &impl Fn(&Node) -> bool) -> Option<Picked> {
|
||||
let Some(clip) = clipping(n) else { return far(n).then(Picked::default) };
|
||||
let mut inner = Vec::new();
|
||||
for (i, c) in n.children().into_iter().flatten().enumerate() {
|
||||
if let Some(p) = reach(c, far) {
|
||||
inner.push((i, p));
|
||||
if clip && i == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
(!inner.is_empty()).then_some(Picked(inner))
|
||||
}
|
||||
|
||||
/// Does `n` clip by a path that reaches beyond the canvas? Then the path and the objects it clips
|
||||
/// go together, so no other object becomes the clipping path.
|
||||
fn clips_beyond(n: &Node) -> bool {
|
||||
clipping(n) == Some(true) && n.children().and_then(|c| c.first()).is_some_and(|c| reaches_beyond(c))
|
||||
/// Does `n`, whose objects beyond the canvas are `found`, clip by a path that reaches beyond it?
|
||||
/// Then the path and the objects it clips go together, so no other object becomes the clipping
|
||||
/// path.
|
||||
fn clips_beyond(n: &Node, found: &Picked) -> bool {
|
||||
clipping(n) == Some(true) && found.0.first().is_some_and(|(i, _)| *i == 0)
|
||||
}
|
||||
|
||||
/// Add the ids of `n` and the layers in it, if it is a layer, to `layers`: their layer guides go
|
||||
/// with them.
|
||||
fn layers_in(n: &Node, layers: &mut Vec<NodeId>) {
|
||||
fn layers_in(n: &Node, layers: &mut BTreeSet<NodeId>) {
|
||||
if matches!(n.kind, NodeKind::Layer { .. }) {
|
||||
layers.push(n.id);
|
||||
layers.insert(n.id);
|
||||
}
|
||||
if clipping(n).is_some() {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
@@ -100,44 +116,82 @@ fn layers_in(n: &Node, layers: &mut Vec<NodeId>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the objects in `node` that reach beyond the canvas: a layer or group keeps those of its
|
||||
/// objects within it, unless its clipping path reaches beyond (see [`clips_beyond`]); anything
|
||||
/// else goes whole. Only containers holding such an object are copied. Recursion follows the
|
||||
/// nesting, which [`Document::limit_depth`] bounds. The layers removed are added to `layers`.
|
||||
fn drop_children_beyond(node: &mut Arc<Node>, dropped: &mut usize, layers: &mut Vec<NodeId>) {
|
||||
if !node.children().is_some_and(|c| c.iter().any(|c| reaches_beyond(c))) {
|
||||
return;
|
||||
/// How many ruler guides the layers in `n` hold, if it is a layer or group.
|
||||
fn guides_in(n: &Node) -> usize {
|
||||
match clipping(n) {
|
||||
None => 0,
|
||||
Some(_) => n.children().into_iter().flatten().map(|c| if c.is_ruler_guide() { 1 } else { guides_in(c) }).sum(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the objects in `node` that reach beyond the canvas, which [`reach`] `found`: a layer or
|
||||
/// group keeps those of its objects within it, unless its clipping path reaches beyond (see
|
||||
/// [`clips_beyond`]); anything else goes whole. Only containers holding such an object are
|
||||
/// copied, and only those are visited again. Recursion follows the nesting, which
|
||||
/// [`Document::limit_depth`] bounds. The layers removed are added to `layers`, and the ruler
|
||||
/// guides they held to `guides`.
|
||||
fn drop_children_beyond(node: &mut Arc<Node>, found: Picked, dropped: &mut usize, layers: &mut BTreeSet<NodeId>, guides: &mut usize) {
|
||||
let Some(children) = Arc::make_mut(node).children_mut() else { return };
|
||||
let mut found = found.0.into_iter().peekable();
|
||||
let mut next = 0;
|
||||
children.retain_mut(|c| {
|
||||
if !reaches_beyond(c) {
|
||||
return true;
|
||||
}
|
||||
if clipping(c).is_some() && !clips_beyond(c) {
|
||||
drop_children_beyond(c, dropped, layers);
|
||||
let at = next;
|
||||
next += 1;
|
||||
let Some((_, inner)) = found.next_if(|(i, _)| *i == at) else { return true };
|
||||
if clipping(c).is_some() && !clips_beyond(c, &inner) {
|
||||
drop_children_beyond(c, inner, dropped, layers, guides);
|
||||
return true;
|
||||
}
|
||||
layers_in(c, layers);
|
||||
*guides += guides_in(c);
|
||||
*dropped += 1;
|
||||
false
|
||||
});
|
||||
}
|
||||
|
||||
/// Is `id` unset, or not one of `ids`? The check takes time logarithmic in the number of ids.
|
||||
fn not_in<T: Ord>(id: Option<T>, ids: &BTreeSet<T>) -> bool {
|
||||
id.is_none_or(|i| !ids.contains(&i))
|
||||
}
|
||||
|
||||
/// Remove the ruler guides of layer `layer` and of its sublayers that `out` picks, adding how many
|
||||
/// to `dropped`. Only layers holding one are copied.
|
||||
/// to `dropped`. `out` looks at each object in the layers once. Only layers holding one are
|
||||
/// copied.
|
||||
fn drop_guides(layer: &mut Arc<Node>, out: &impl Fn(&Node) -> bool, dropped: &mut usize) {
|
||||
fn holds(n: &Node, out: &impl Fn(&Node) -> bool) -> bool {
|
||||
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| out(c) || holds(c, out)))
|
||||
/// The objects of `n`, if it is a layer, that `out` picks (with nothing inside), and its
|
||||
/// sublayers holding one (with what they hold), or `None` when it holds none.
|
||||
fn holds(n: &Node, out: &impl Fn(&Node) -> bool) -> Option<Picked> {
|
||||
if !n.is_layer() {
|
||||
return None;
|
||||
}
|
||||
let inner: Vec<(usize, Picked)> = n
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
.filter_map(|(i, c)| if out(c) { Some((i, Picked::default())) } else { holds(c, out).map(|p| (i, p)) })
|
||||
.collect();
|
||||
(!inner.is_empty()).then_some(Picked(inner))
|
||||
}
|
||||
if !holds(layer, out) {
|
||||
return;
|
||||
fn drop(layer: &mut Arc<Node>, held: Picked, dropped: &mut usize) {
|
||||
let Some(children) = Arc::make_mut(layer).children_mut() else { return };
|
||||
let mut held = held.0.into_iter().peekable();
|
||||
let mut next = 0;
|
||||
children.retain_mut(|c| {
|
||||
let at = next;
|
||||
next += 1;
|
||||
let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true };
|
||||
// A sublayer holds something; an object picked itself has nothing inside.
|
||||
if inner.0.is_empty() {
|
||||
*dropped += 1;
|
||||
return false;
|
||||
}
|
||||
drop(c, inner, dropped);
|
||||
true
|
||||
});
|
||||
}
|
||||
let Some(children) = Arc::make_mut(layer).children_mut() else { return };
|
||||
let before = children.len();
|
||||
children.retain(|c| !out(c));
|
||||
*dropped += before - children.len();
|
||||
for c in children.iter_mut().filter(|c| c.is_layer()) {
|
||||
drop_guides(c, out, dropped);
|
||||
if let Some(held) = holds(layer, out) {
|
||||
drop(layer, held, dropped);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,21 +205,23 @@ impl Document {
|
||||
/// whose artboards were all removed has none left.
|
||||
pub fn drop_beyond_canvas(&mut self) -> BeyondCanvas {
|
||||
let mut gone = BeyondCanvas::default();
|
||||
let mut layers = vec![];
|
||||
let mut layers = BTreeSet::new();
|
||||
for layer in &mut self.layers {
|
||||
if clips_beyond(layer) {
|
||||
let Some(found) = reach(layer, &beyond) else { continue };
|
||||
if clips_beyond(layer, &found) {
|
||||
let layer = Arc::make_mut(layer);
|
||||
if let NodeKind::Layer { children, clip, .. } = &mut layer.kind {
|
||||
for c in children.iter() {
|
||||
layers_in(c, &mut layers);
|
||||
}
|
||||
// The layer's own ruler guides stay; only its art goes.
|
||||
// The layer's own ruler guides stay; only its art goes, with its sublayers' guides.
|
||||
gone.objects += children.iter().filter(|c| !c.is_ruler_guide()).count();
|
||||
gone.guides += children.iter().filter(|c| !c.is_ruler_guide()).map(|c| guides_in(c)).sum::<usize>();
|
||||
children.retain(|c| c.is_ruler_guide());
|
||||
*clip = false;
|
||||
}
|
||||
} else {
|
||||
drop_children_beyond(layer, &mut gone.objects, &mut layers);
|
||||
drop_children_beyond(layer, found, &mut gone.objects, &mut layers, &mut gone.guides);
|
||||
}
|
||||
}
|
||||
if gone.objects > 0 {
|
||||
@@ -180,13 +236,13 @@ impl Document {
|
||||
self.retire_artboard_id(*id);
|
||||
}
|
||||
gone.artboards = removed.len();
|
||||
let removed: BTreeSet<u32> = removed.into_iter().collect();
|
||||
// The saved list, when the guides are not nodes yet ([`Document::guides_into_nodes`]).
|
||||
let guides = self.saved_guides.len();
|
||||
self.saved_guides
|
||||
.retain(|g| in_range(g.pos) && g.artboard.is_none_or(|a| !removed.contains(&a)) && g.layer.is_none_or(|l| !layers.contains(&l)));
|
||||
gone.guides = guides - self.saved_guides.len();
|
||||
self.saved_guides.retain(|g| in_range(g.pos) && not_in(g.artboard, &removed) && not_in(g.layer, &layers));
|
||||
gone.guides += guides - self.saved_guides.len();
|
||||
let out = |n: &Node| match n.kind {
|
||||
NodeKind::RulerGuide { pos, artboard, .. } => !in_range(pos) || artboard.is_some_and(|a| removed.contains(&a)),
|
||||
NodeKind::RulerGuide { pos, artboard, .. } => !in_range(pos) || !not_in(artboard, &removed),
|
||||
_ => false,
|
||||
};
|
||||
for layer in &mut self.layers {
|
||||
@@ -324,6 +380,21 @@ mod tests {
|
||||
let layer = d2.layers[0].id.0;
|
||||
assert_eq!(d2.drop_beyond_canvas().objects, 1);
|
||||
assert_eq!(ids(&d2), [layer, 10]);
|
||||
// The guides of a sublayer emptied out of a top-level layer go with it, counted.
|
||||
let probe = Document::new(1.0, 1.0);
|
||||
let sub = sublayer(&probe, 40, vec![rect(41, 0.0)], false);
|
||||
let mut d3 = doc(vec![rect(10, 1e17), sub]);
|
||||
if let NodeKind::Layer { clip, .. } = &mut Arc::make_mut(&mut d3.layers[0]).kind {
|
||||
*clip = true;
|
||||
}
|
||||
d3.saved_guides =
|
||||
vec![Guide { layer: Some(NodeId(40)), ..Guide::new(false, 5.0) }, Guide { layer: Some(d3.layers[0].id), ..Guide::new(true, 5.0) }];
|
||||
let mut nodes = d3.clone();
|
||||
assert_eq!(nodes.guides_into_nodes(), 2);
|
||||
let gone = d3.drop_beyond_canvas();
|
||||
assert_eq!((gone.objects, gone.guides), (2, 1), "the clipping path, the sublayer and its guide; the layer's own guide stays");
|
||||
assert_eq!(nodes.drop_beyond_canvas(), gone);
|
||||
assert_eq!(nodes.ruler_guides().len(), 1);
|
||||
assert_eq!(d.drop_beyond_canvas(), BeyondCanvas::default());
|
||||
}
|
||||
|
||||
@@ -353,11 +424,165 @@ mod tests {
|
||||
];
|
||||
d.variables.bindings.insert(NodeId(11), ["v".to_string()].into());
|
||||
d.variables.bindings.insert(NodeId(10), ["w".to_string()].into());
|
||||
// The same guides as nodes, as a document has them once read.
|
||||
let mut nodes = d.clone();
|
||||
assert_eq!(nodes.guides_into_nodes(), 2);
|
||||
let gone = d.drop_beyond_canvas();
|
||||
assert_eq!((gone.objects, gone.guides), (2, 1), "the far rectangle, the clipping sublayer and its layer guide");
|
||||
assert_eq!(nodes.drop_beyond_canvas(), gone, "a guide node goes with its sublayer, counted as a saved one is");
|
||||
assert_eq!(nodes.ruler_guides().len(), 1);
|
||||
assert_eq!(d.saved_guides.len(), 1, "the guide of a layer that stays, stays");
|
||||
assert_eq!(d.saved_selections[0].objects, [NodeId(10)]);
|
||||
assert_eq!(d.assets.iter().map(|a| (a.id, a.nodes.clone())).collect::<Vec<_>>(), [(2, vec![NodeId(10)])]);
|
||||
assert_eq!(d.variables.bindings.keys().copied().collect::<Vec<_>>(), [NodeId(10)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_of_many_removed_artboards_and_layers_go_and_the_rest_keep_their_order() {
|
||||
let probe = Document::new(1.0, 1.0);
|
||||
// Sublayers 40 to 43 clip by a path beyond the canvas, so they go whole; 50 stays.
|
||||
let far: Vec<Arc<Node>> = (40..44).map(|id| sublayer(&probe, id, vec![rect(id * 10, 1e17), rect(id * 10 + 1, 0.0)], true)).collect();
|
||||
let near = sublayer(&probe, 50, vec![rect(500, 0.0)], false);
|
||||
let mut d = doc(far.into_iter().chain([near, rect(10, 0.0)]).collect());
|
||||
let kept = d.artboards[0].id;
|
||||
for id in 9..13 {
|
||||
d.artboards.push(Artboard { id, rect: Rect::new(0.0, 1e17, 100.0, 1e17 + 100.0), ..d.artboards[0].clone() });
|
||||
}
|
||||
let top = d.layers[0].id;
|
||||
let guide = |pos: f64, artboard: Option<u32>, layer: Option<NodeId>| Guide { artboard, layer, ..Guide::new(false, pos) };
|
||||
d.saved_guides = vec![
|
||||
guide(1.0, Some(9), None),
|
||||
guide(2.0, None, None),
|
||||
guide(3.0, Some(kept), Some(NodeId(41))),
|
||||
guide(4.0, Some(kept), None),
|
||||
guide(5.0, Some(12), None),
|
||||
guide(6.0, None, Some(NodeId(50))),
|
||||
guide(7.0, None, Some(NodeId(43))),
|
||||
guide(8.0, Some(10), Some(top)),
|
||||
guide(9.0, None, Some(top)),
|
||||
];
|
||||
d.saved_selections = vec![crate::records::SavedSelection { name: "s".into(), objects: vec![NodeId(42), NodeId(10), NodeId(500)] }].into();
|
||||
let mut nodes = d.clone();
|
||||
assert_eq!(nodes.guides_into_nodes(), 9);
|
||||
let gone = d.drop_beyond_canvas();
|
||||
assert_eq!(gone, BeyondCanvas { objects: 4, artboards: 4, guides: 5, ruler_origin: false });
|
||||
assert_eq!(d.artboards.iter().map(|a| a.id).collect::<Vec<_>>(), [kept]);
|
||||
let left: Vec<f64> = d.saved_guides.iter().map(|g| g.pos).collect();
|
||||
assert_eq!(left, [2.0, 4.0, 6.0, 9.0], "the guides that stay keep their order");
|
||||
assert_eq!(d.saved_selections[0].objects, [NodeId(10), NodeId(500)]);
|
||||
assert_eq!(nodes.drop_beyond_canvas(), gone, "guide nodes go as saved guides do");
|
||||
let mut left: Vec<f64> = nodes.ruler_guides().iter().map(|g| g.pos).collect();
|
||||
left.sort_by(f64::total_cmp);
|
||||
assert_eq!(left, [2.0, 4.0, 6.0, 9.0]);
|
||||
assert_eq!(nodes.saved_selections, d.saved_selections);
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// An id that counts how often it is compared.
|
||||
#[derive(Debug)]
|
||||
struct Counted(u32);
|
||||
|
||||
impl Ord for Counted {
|
||||
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||
COMPARISONS.with(|c| c.set(c.get() + 1));
|
||||
self.0.cmp(&other.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for Counted {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Counted {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.cmp(other) == std::cmp::Ordering::Equal
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Counted {}
|
||||
|
||||
#[test]
|
||||
fn a_guide_is_checked_without_scanning_every_removed_id() {
|
||||
let per_guide = |removed: u32| {
|
||||
let ids: BTreeSet<Counted> = (0..removed).map(|i| Counted(i * 2)).collect();
|
||||
COMPARISONS.with(|c| c.set(0));
|
||||
// Guides on removed ids, on ids between them, on ids past them and on none.
|
||||
let guides: Vec<Option<Counted>> = (0..64).map(|i| (i % 4 != 3).then(|| Counted(i * 31 % (removed * 2 + 8)))).collect();
|
||||
let kept = guides.into_iter().filter(|g| not_in(g.as_ref().map(|c| Counted(c.0)), &ids)).count();
|
||||
assert!(kept > 0 && kept < 64);
|
||||
COMPARISONS.with(|c| c.get()) as f64 / 64.0
|
||||
};
|
||||
let small = per_guide(16);
|
||||
let large = per_guide(16_384);
|
||||
// A sorted lookup grows with the depth of the tree; a scan of 16,384 ids compares thousands per guide.
|
||||
assert!(large < small * 32.0 && large < 256.0, "{small} comparisons per guide among 16 ids, {large} among 16,384");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_object_is_measured_once_however_deep_the_nesting() {
|
||||
// 32 groups, each inside the one before and holding an object within the canvas; the
|
||||
// innermost also holds one beyond it. Beside them, a group with nothing beyond and a clip
|
||||
// group whose clipping path reaches beyond.
|
||||
let mut chain = Arc::new(Node::group(NodeId(100), vec![rect(200, 0.0), rect(201, 1e17)]));
|
||||
for depth in 1..32 {
|
||||
chain = Arc::new(Node::group(NodeId(100 + depth), vec![rect(300 + depth, 0.0), chain]));
|
||||
}
|
||||
let still = Arc::new(Node::group(NodeId(400), vec![rect(401, 0.0), rect(402, 5.0)]));
|
||||
let clip = Arc::new(Node::new(NodeId(600), NodeKind::Group { children: vec![rect(601, 1e17), rect(602, 0.0), rect(603, 0.0)], clip: true }));
|
||||
let mut d = doc(vec![chain, Arc::clone(&still), clip]);
|
||||
let mut whole = d.clone();
|
||||
let measured = std::cell::Cell::new(0_usize);
|
||||
let far = |n: &Node| {
|
||||
measured.set(measured.get() + 1);
|
||||
beyond(n)
|
||||
};
|
||||
let layer = &mut d.layers[0];
|
||||
let found = reach(layer, &far).unwrap();
|
||||
assert_eq!(
|
||||
measured.get(),
|
||||
36,
|
||||
"the 33 objects in the groups, the 2 beside them and the clipping path, each measured once; not what the path clips"
|
||||
);
|
||||
assert!(!clips_beyond(layer, &found));
|
||||
let (mut dropped, mut layers, mut guides) = (0, BTreeSet::new(), 0);
|
||||
drop_children_beyond(layer, found, &mut dropped, &mut layers, &mut guides);
|
||||
assert_eq!(measured.get(), 36, "removing measures nothing again");
|
||||
assert_eq!((dropped, layers.len(), guides), (2, 0, 0));
|
||||
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a group with nothing beyond is not copied");
|
||||
assert_eq!(whole.drop_beyond_canvas(), BeyondCanvas { objects: 2, ..Default::default() });
|
||||
assert_eq!(ids(&whole), ids(&d));
|
||||
assert!(!ids(&d).contains(&201) && !ids(&d).contains(&600) && ids(&d).contains(&200) && ids(&d).contains(&331));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_object_is_looked_at_once_when_guides_go_from_nested_layers() {
|
||||
let guide = |id: u64, pos: f64| Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: false, pos, artboard: None }));
|
||||
let probe = Document::new(1.0, 1.0);
|
||||
// 32 sublayers, each inside the one before, each holding a guide within the canvas and one
|
||||
// beyond it. Beside them, a sublayer with nothing to remove.
|
||||
let mut chain = sublayer(&probe, 100, vec![guide(200, 5.0), guide(201, 1e17)], false);
|
||||
for depth in 1..32 {
|
||||
chain = sublayer(&probe, 100 + depth, vec![guide(300 + depth * 2, 5.0), guide(301 + depth * 2, 1e17), chain], false);
|
||||
}
|
||||
let still = sublayer(&probe, 500, vec![guide(501, 5.0), rect(502, 0.0)], false);
|
||||
let mut d = doc(vec![chain, Arc::clone(&still)]);
|
||||
let looked = std::cell::Cell::new(0_usize);
|
||||
let out = |n: &Node| {
|
||||
looked.set(looked.get() + 1);
|
||||
matches!(n.kind, NodeKind::RulerGuide { pos, .. } if !in_range(pos))
|
||||
};
|
||||
let mut dropped = 0;
|
||||
drop_guides(&mut d.layers[0], &out, &mut dropped);
|
||||
assert_eq!(dropped, 32);
|
||||
assert_eq!(looked.get(), 2 + 2 + 31 * 3 + 2, "each object in the layers is looked at once");
|
||||
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with nothing to remove is not copied");
|
||||
let left = d.ruler_guides();
|
||||
assert_eq!(left.len(), 33);
|
||||
assert!(left.iter().all(|g| g.pos == 5.0));
|
||||
}
|
||||
}
|
||||
+219
-30
@@ -133,6 +133,28 @@ pub(crate) fn tiff(bytes: &[u8]) -> Option<(tiff::ColorType, tiff::decoder::Deco
|
||||
Some((d.colortype().ok()?, d))
|
||||
}
|
||||
|
||||
/// The Orientation tag of TIFF `bytes`' first image, of any unsigned type; `None` for other images
|
||||
/// and TIFFs without one. Reads only its header.
|
||||
pub fn tiff_orientation(bytes: &[u8]) -> Option<u16> {
|
||||
let (_, mut d) = tiff(bytes)?;
|
||||
d.find_tag_unsigned::<u16>(tiff::tags::Tag::Orientation).ok().flatten()
|
||||
}
|
||||
|
||||
/// The EXIF orientation of encoded image `bytes` when it turns or flips the pixels; `None` when
|
||||
/// it leaves them as stored, or the image has none. A TIFF the image decoder can't open (one with
|
||||
/// extra samples) has its Orientation tag read from its first image ([`tiff_orientation`]). Reads
|
||||
/// only the image's header and metadata; `None` for an [`oversized_tiff`], which no decoder opens.
|
||||
pub fn exif_orientation(bytes: &[u8]) -> Option<image::metadata::Orientation> {
|
||||
use image::ImageDecoder as _;
|
||||
use image::metadata::Orientation;
|
||||
if oversized_tiff(bytes).is_some() {
|
||||
return None;
|
||||
}
|
||||
let decoded = || image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_decoder().ok()?.orientation().ok();
|
||||
let tagged = || tiff_orientation(bytes).and_then(|v| Orientation::from_exif(u8::try_from(v).ok()?));
|
||||
decoded().or_else(tagged).filter(|o| *o != Orientation::NoTransforms)
|
||||
}
|
||||
|
||||
/// Does the TIFF `d` reads store one plane per channel (PlanarConfiguration 2)?
|
||||
fn planar(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> bool {
|
||||
d.find_tag_unsigned::<u16>(tiff::tags::Tag::PlanarConfiguration).ok().flatten().is_some_and(|p| p != 1)
|
||||
@@ -143,25 +165,181 @@ fn planar(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> bool {
|
||||
/// stores each pixel's samples together or one plane per channel. `None` when they don't decode to
|
||||
/// that many samples, which includes images whose planes together need more than the decoder's
|
||||
/// limit (256 MB of samples).
|
||||
fn read_samples(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
|
||||
pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
|
||||
Some(match read_samples_at_depth(d, n, per)? {
|
||||
Samples::Eight(v) => v,
|
||||
Samples::Sixteen(v) => v.iter().map(|s| (s >> 8) as u8).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Samples of an image, pixel by pixel, at the depth its file stores them.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Samples {
|
||||
Eight(Vec<u8>),
|
||||
Sixteen(Vec<u16>),
|
||||
}
|
||||
|
||||
impl Samples {
|
||||
fn as_slice(&self) -> SampleSlice<'_> {
|
||||
match self {
|
||||
Self::Eight(v) => SampleSlice::Eight(v),
|
||||
Self::Sixteen(v) => SampleSlice::Sixteen(v),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Samples`], borrowed.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum SampleSlice<'a> {
|
||||
Eight(&'a [u8]),
|
||||
Sixteen(&'a [u16]),
|
||||
}
|
||||
|
||||
/// [`read_samples`], keeping 16-bit samples at 16 bits.
|
||||
fn read_samples_at_depth(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Samples> {
|
||||
let mut buf = tiff::decoder::DecodingResult::U8(Vec::new());
|
||||
let layout = d.read_image_to_buffer(&mut buf).ok()?;
|
||||
let data = match buf {
|
||||
tiff::decoder::DecodingResult::U8(v) => v,
|
||||
tiff::decoder::DecodingResult::U16(v) => v.iter().map(|s| (s >> 8) as u8).collect(),
|
||||
_ => return None,
|
||||
};
|
||||
match buf {
|
||||
tiff::decoder::DecodingResult::U8(v) => chunky(v, layout.planes, n, per).map(Samples::Eight),
|
||||
tiff::decoder::DecodingResult::U16(v) => chunky(v, layout.planes, n, per).map(Samples::Sixteen),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `data`, the samples of `n` pixels, `per` to a pixel, stored in `planes` planes, as the samples
|
||||
/// pixel by pixel; `None` when it doesn't hold that many samples or a plane per sample.
|
||||
fn chunky<T: Copy>(data: Vec<T>, planes: usize, n: usize, per: usize) -> Option<Vec<T>> {
|
||||
if Some(data.len()) != n.checked_mul(per) {
|
||||
return None;
|
||||
}
|
||||
if layout.planes <= 1 {
|
||||
if planes <= 1 {
|
||||
return Some(data);
|
||||
}
|
||||
if layout.planes != per {
|
||||
if planes != per {
|
||||
return None;
|
||||
}
|
||||
let planes: Vec<&[u8]> = data.chunks_exact(n).collect();
|
||||
Some((0..n).flat_map(|i| planes.iter().map(move |p| p.get(i).copied().unwrap_or(0))).collect())
|
||||
let planes: Vec<&[T]> = data.chunks_exact(n).collect();
|
||||
Some((0..n).flat_map(|i| planes.iter().filter_map(move |p| p.get(i).copied())).collect())
|
||||
}
|
||||
|
||||
/// The color space an ICC profile's header names (bytes 16 to 19, such as `RGB `, `GRAY` or
|
||||
/// `CMYK`); `None` when `icc` is shorter than a header.
|
||||
pub fn icc_color_space(icc: &[u8]) -> Option<[u8; 4]> {
|
||||
if icc.len() < 128 {
|
||||
return None;
|
||||
}
|
||||
icc.get(16..20)?.try_into().ok()
|
||||
}
|
||||
|
||||
/// The ICC profile of TIFF tag 34675 (ICCProfile) of the image `d` reads; `None` without one.
|
||||
fn tiff_icc(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> Option<Vec<u8>> {
|
||||
d.get_tag_u8_vec(tiff::tags::Tag::IccProfile).ok().filter(|icc| !icc.is_empty())
|
||||
}
|
||||
|
||||
/// The ICC profile of TIFF `bytes`' first image (tag 34675), read with the `tiff` decoder's own
|
||||
/// limits, whatever the size of the image; `None` for other images and TIFFs without one.
|
||||
pub fn tiff_icc_profile(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
let (_, mut d) = tiff(bytes)?;
|
||||
tiff_icc(&mut d)
|
||||
}
|
||||
|
||||
/// The ICC profile of a JPEG, put together from all its numbered `ICC_PROFILE` APP2 segments;
|
||||
/// `None` without one.
|
||||
fn jpeg_icc(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
|
||||
d.decode_headers().ok()?;
|
||||
d.icc_profile().filter(|icc| !icc.is_empty())
|
||||
}
|
||||
|
||||
/// `icc` when it is a profile of CMYK colors, which the samples of a CMYK image are in.
|
||||
fn cmyk_icc(icc: Option<Vec<u8>>) -> Option<Vec<u8>> {
|
||||
icc.filter(|icc| icc_color_space(icc) == Some(*b"CMYK"))
|
||||
}
|
||||
|
||||
/// The CMYK samples of a CMYK image at the depth its file stores them, and its ICC profile.
|
||||
struct CmykSource {
|
||||
width: u32,
|
||||
height: u32,
|
||||
samples: Samples,
|
||||
icc: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// The samples of CMYK TIFF `bytes` (8 or 16 bits), their inks together or one plane per ink, with
|
||||
/// the TIFF's CMYK ICC profile; `None` for other images and ones larger than [`MAX_CMYK_PIXELS`].
|
||||
fn tiff_source(bytes: &[u8]) -> Option<CmykSource> {
|
||||
let (kind, mut d) = tiff(bytes)?;
|
||||
if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) {
|
||||
return None;
|
||||
}
|
||||
let (width, height) = d.dimensions().ok()?;
|
||||
let n = usize::try_from(pixels(width, height)?).ok()?;
|
||||
let icc = cmyk_icc(tiff_icc(&mut d));
|
||||
let samples = read_samples_at_depth(&mut d, n, 4)?;
|
||||
Some(CmykSource { width, height, samples, icc })
|
||||
}
|
||||
|
||||
/// The ink amounts of a four-component JPEG, 8 bits each, with its CMYK ICC profile.
|
||||
fn jpeg_source(bytes: &[u8]) -> Option<CmykSource> {
|
||||
let Inks { width, height, data } = jpeg_inks(bytes)?;
|
||||
Some(CmykSource { width, height, samples: Samples::Eight(data), icc: cmyk_icc(jpeg_icc(bytes)) })
|
||||
}
|
||||
|
||||
/// A Deflate-compressed CMYK TIFF of `width` × `height` pixels of `samples` (inks together, 8 or 16
|
||||
/// bits as they are given), declaring the resolution `ppi` when both of its values are finite and
|
||||
/// above 0, and carrying `icc` as tag 34675 (ICCProfile, of type UNDEFINED); `None` when it can't be
|
||||
/// written.
|
||||
fn write_cmyk_tiff(width: u32, height: u32, samples: SampleSlice<'_>, ppi: Option<(f64, f64)>, icc: Option<&[u8]>) -> Option<Vec<u8>> {
|
||||
use tiff::encoder::colortype::{CMYK8, CMYK16, ColorType};
|
||||
use tiff::encoder::{Compression, ImageEncoder, Rational, TiffEncoder, TiffKind, compression::DeflateLevel};
|
||||
use tiff::tags::{ResolutionUnit, Tag};
|
||||
fn tags<W: std::io::Write + std::io::Seek, C: ColorType, K: TiffKind>(
|
||||
img: &mut ImageEncoder<'_, W, C, K>,
|
||||
ppi: Option<(f64, f64)>,
|
||||
icc: Option<&[u8]>,
|
||||
) -> Option<()> {
|
||||
if let Some((x, y)) = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)) {
|
||||
// Ten-thousandths of a pixel per inch.
|
||||
let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 };
|
||||
img.encoder().write_tag(Tag::XResolution, r(x)).ok()?;
|
||||
img.encoder().write_tag(Tag::YResolution, r(y)).ok()?;
|
||||
img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?;
|
||||
}
|
||||
if let Some(icc) = icc {
|
||||
img.encoder().write_tag(Tag::IccProfile, Undefined(icc)).ok()?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced));
|
||||
match samples {
|
||||
SampleSlice::Eight(data) => {
|
||||
let mut img = enc.new_image::<CMYK8>(width, height).ok()?;
|
||||
tags(&mut img, ppi, icc)?;
|
||||
img.write_data(data).ok()?;
|
||||
}
|
||||
SampleSlice::Sixteen(data) => {
|
||||
let mut img = enc.new_image::<CMYK16>(width, height).ok()?;
|
||||
tags(&mut img, ppi, icc)?;
|
||||
img.write_data(data).ok()?;
|
||||
}
|
||||
}
|
||||
Some(out.into_inner())
|
||||
}
|
||||
|
||||
/// Bytes written as a TIFF field of type UNDEFINED, the type of an embedded ICC profile.
|
||||
struct Undefined<'a>(&'a [u8]);
|
||||
|
||||
impl tiff::encoder::TiffValue for Undefined<'_> {
|
||||
const BYTE_LEN: u8 = 1;
|
||||
const FIELD_TYPE: tiff::tags::Type = tiff::tags::Type::UNDEFINED;
|
||||
|
||||
fn count(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
fn data(&self) -> std::borrow::Cow<'_, [u8]> {
|
||||
std::borrow::Cow::Borrowed(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl ImageBlob {
|
||||
@@ -173,20 +351,8 @@ impl ImageBlob {
|
||||
/// [`ImageBlob::cmyk_tiff`], declaring the resolution `ppi` (horizontal, vertical pixels per
|
||||
/// inch) when it is given and both are finite and above 0.
|
||||
pub fn cmyk_tiff_at(inks: &Inks, ppi: Option<(f64, f64)>) -> Option<Self> {
|
||||
use tiff::encoder::{Compression, Rational, TiffEncoder, colortype::CMYK8, compression::DeflateLevel};
|
||||
use tiff::tags::{ResolutionUnit, Tag};
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced));
|
||||
let mut img = enc.new_image::<CMYK8>(inks.width, inks.height).ok()?;
|
||||
if let Some((x, y)) = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)) {
|
||||
// Ten-thousandths of a pixel per inch.
|
||||
let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 };
|
||||
img.encoder().write_tag(Tag::XResolution, r(x)).ok()?;
|
||||
img.encoder().write_tag(Tag::YResolution, r(y)).ok()?;
|
||||
img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?;
|
||||
}
|
||||
img.write_data(&inks.data).ok()?;
|
||||
Some(Self::new("image/tiff", out.into_inner()))
|
||||
let tiff = write_cmyk_tiff(inks.width, inks.height, SampleSlice::Eight(&inks.data), ppi, None)?;
|
||||
Some(Self::new("image/tiff", tiff))
|
||||
}
|
||||
|
||||
/// Does the image hold CMYK samples (a four-component JPEG or a CMYK TIFF)? Reads only its
|
||||
@@ -309,17 +475,40 @@ fn tiff_inks(bytes: &[u8]) -> Option<Inks> {
|
||||
Inks::new(w, h, read_samples(&mut d, n, 4)?)
|
||||
}
|
||||
|
||||
/// CMYK TIFF `bytes` as Open and Place store them: as they are, or, when they store one plane per
|
||||
/// ink, which the image decoder doesn't read, their ink amounts written again by
|
||||
/// [`ImageBlob::cmyk_tiff_at`] with the resolution `ppi`. `None` for other images and for CMYK
|
||||
/// TIFFs whose inks [`ImageBlob::cmyk`] doesn't read.
|
||||
/// CMYK TIFF `bytes` that no orientation turns ([`turned_cmyk`] stores the others) as Open and
|
||||
/// Place store them: as they are, or, when they store one plane per ink, which the image decoder
|
||||
/// doesn't read, their inks together in a CMYK TIFF with the resolution `ppi`, at the 8 or 16 bits
|
||||
/// the file has, carrying the file's CMYK ICC profile. `None` for other images and for CMYK TIFFs
|
||||
/// whose inks [`ImageBlob::cmyk`] doesn't read.
|
||||
pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option<Vec<u8>> {
|
||||
let inks = tiff_inks(bytes)?;
|
||||
let source = tiff_source(bytes)?;
|
||||
let (_, mut d) = tiff(bytes)?;
|
||||
if !planar(&mut d) {
|
||||
return Some(bytes.to_vec());
|
||||
}
|
||||
ImageBlob::cmyk_tiff_at(&inks, ppi).map(|b| Arc::unwrap_or_clone(b.bytes))
|
||||
write_cmyk_tiff(source.width, source.height, source.samples.as_slice(), ppi, source.icc.as_deref())
|
||||
}
|
||||
|
||||
/// CMYK JPEG or TIFF `bytes` that `orientation` turns or flips, as Open and Place store them: their
|
||||
/// inks turned and written again as a CMYK TIFF with the resolution `ppi` of the turned pixels,
|
||||
/// with the turned width and height. A TIFF keeps its 8 or 16 bits, a JPEG has 8, and both keep
|
||||
/// their CMYK ICC profile (a JPEG's put together from all its APP2 segments). `None` for other
|
||||
/// images and for CMYK images whose inks [`ImageBlob::cmyk`] doesn't read.
|
||||
pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: Option<(f64, f64)>) -> Option<(Vec<u8>, (u32, u32))> {
|
||||
let CmykSource { width, height, samples, icc } = if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_source(bytes) } else { tiff_source(bytes) }?;
|
||||
// Four inks to a pixel, turned as four channels of the same depth are.
|
||||
let mut px = match samples {
|
||||
Samples::Eight(v) => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(width, height, v)?),
|
||||
Samples::Sixteen(v) => image::DynamicImage::ImageRgba16(image::ImageBuffer::from_raw(width, height, v)?),
|
||||
};
|
||||
px.apply_orientation(orientation);
|
||||
let size = (px.width(), px.height());
|
||||
let samples = match px {
|
||||
image::DynamicImage::ImageRgba16(v) => Samples::Sixteen(v.into_raw()),
|
||||
other => Samples::Eight(other.into_rgba8().into_raw()),
|
||||
};
|
||||
let tiff = write_cmyk_tiff(size.0, size.1, samples.as_slice(), ppi, icc.as_deref())?;
|
||||
Some((tiff, size))
|
||||
}
|
||||
|
||||
/// A TIFF whose pixels have samples after their colour, which the image decoder doesn't read at
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
//! Image Tools › Color Mask: colors of an image object that are hidden while its pixels stay as
|
||||
//! they are.
|
||||
//!
|
||||
//! A masked image is an ordinary image ([`NodeKind::Image`]) with a [`ColorMask`] in its extras
|
||||
//! ([`crate::node::NodeExtras::color_mask`]). The record holds the mask's settings and the key of
|
||||
//! the image's pixels with the hidden colors made clear ([`ColorMask::key`]), made by the engine
|
||||
//! from the pixels named by [`ColorMask::from`]. The image's own key keeps naming its own pixels,
|
||||
//! so removing the mask gives them back. While the image's key is [`ColorMask::from`], it is drawn
|
||||
//! and output with the masked pixels ([`Document::shown_image`]); when another key replaced it
|
||||
//! (a link updated, the image cropped), it shows its own pixels until the engine makes the masked
|
||||
//! pixels again.
|
||||
//!
|
||||
//! The concept is that of PDF's color key masking (ISO 32000-1, 8.9.6.4): samples in the chosen
|
||||
//! colors are not painted and what is behind the image shows through. Which colors match, and how
|
||||
//! near ones fade out, are VectorCraft's own rules.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Document, ImageObject, Node, NodeKind};
|
||||
|
||||
/// Where a color mask's colors come from.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum MaskBackground {
|
||||
/// The most common color along the image's edges.
|
||||
#[default]
|
||||
Edges,
|
||||
/// The average of the image's corner pixels that are not clear.
|
||||
Corners,
|
||||
/// The colors in [`ColorMask::colors`].
|
||||
Colors,
|
||||
}
|
||||
|
||||
/// How near a color must be to a masked one.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum MaskMatch {
|
||||
/// The RGB distance, as a percentage of the largest one.
|
||||
#[default]
|
||||
Distance,
|
||||
/// The largest difference on one of red, green and blue, as a percentage of a channel's range.
|
||||
Channels,
|
||||
}
|
||||
|
||||
/// The colors an image object hides (see the module docs).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ColorMask {
|
||||
/// Key into [`Document::images`]: the pixels of [`Self::from`] with the hidden colors made
|
||||
/// clear. Named `key` in the file, so the file keeps those pixels with the document.
|
||||
pub key: String,
|
||||
/// The image's own key when the masked pixels were made.
|
||||
pub from: String,
|
||||
#[serde(default)]
|
||||
pub background: MaskBackground,
|
||||
/// The hidden colors (8-bit RGB) with [`MaskBackground::Colors`].
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub colors: Vec<[u8; 3]>,
|
||||
/// Only the matching pixels that reach in from an edge are hidden. A record without it reads
|
||||
/// as `true`, the command's default.
|
||||
#[serde(default = "default_contiguous")]
|
||||
pub contiguous: bool,
|
||||
#[serde(default, rename = "match")]
|
||||
pub measure: MaskMatch,
|
||||
/// How near a color must be to be hidden, 0 to 100 (see [`MaskMatch`]). A record without it
|
||||
/// reads as 10, the command's default.
|
||||
#[serde(default = "default_percent")]
|
||||
pub tolerance: f64,
|
||||
/// The band past the tolerance over which pixels fade from hidden to shown, 0 to 100. A record
|
||||
/// without it reads as 10, the command's default.
|
||||
#[serde(default = "default_percent")]
|
||||
pub softness: f64,
|
||||
}
|
||||
|
||||
fn default_contiguous() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_percent() -> f64 {
|
||||
10.0
|
||||
}
|
||||
|
||||
impl ColorMask {
|
||||
/// Whether the masked pixels were made from the pixels of `im`.
|
||||
pub fn made_for(&self, im: &ImageObject) -> bool {
|
||||
im.pixels.is_none() && self.from == im.key
|
||||
}
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Image `im` of node `n` as it is drawn and output. With a color mask whose masked pixels were
|
||||
/// made from the image's own pixels and are in this document ([`ColorMask::made_for`]): a copy
|
||||
/// that shows those pixels and links to no file, so an output that refers to a linked file
|
||||
/// writes the masked pixels instead. Otherwise, and for a mask that hides nothing (its masked
|
||||
/// pixels are the image's own), `im` itself.
|
||||
pub fn shown_image<'a>(&self, n: &Node, im: &'a ImageObject) -> Cow<'a, ImageObject> {
|
||||
match n.extras().color_mask.as_deref() {
|
||||
Some(m) if m.key != im.key && m.made_for(im) && self.images.contains_key(&m.key) => {
|
||||
Cow::Owned(ImageObject { key: m.key.clone(), link: None, ..im.clone() })
|
||||
}
|
||||
_ => Cow::Borrowed(im),
|
||||
}
|
||||
}
|
||||
|
||||
/// The color mask of image node `n`, if it has one.
|
||||
pub fn color_mask_of(n: &Node) -> Option<&ColorMask> {
|
||||
matches!(n.kind, NodeKind::Image(_)).then(|| n.extras().color_mask.as_deref()).flatten()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
use super::*;
|
||||
use crate::{ImageBlob, NodeId};
|
||||
|
||||
fn image(key: &str) -> ImageObject {
|
||||
ImageObject { key: key.into(), width: 2, height: 2, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }
|
||||
}
|
||||
|
||||
fn mask(key: &str, from: &str) -> ColorMask {
|
||||
ColorMask {
|
||||
key: key.into(),
|
||||
from: from.into(),
|
||||
background: MaskBackground::Colors,
|
||||
colors: vec![[255, 255, 255]],
|
||||
contiguous: false,
|
||||
measure: MaskMatch::Distance,
|
||||
tolerance: 10.0,
|
||||
softness: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_masked_image_shows_its_masked_pixels_while_they_were_made_from_its_own() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.images.insert("own".into(), ImageBlob::png(vec![1]));
|
||||
d.images.insert("masked".into(), ImageBlob::png(vec![2]));
|
||||
let mut n = Node::new(NodeId(5), NodeKind::Image(Box::new(image("own"))));
|
||||
let NodeKind::Image(im) = &n.kind else { unreachable_kind() };
|
||||
assert_eq!(d.shown_image(&n, im).key, "own", "no mask: its own pixels");
|
||||
n.extras_mut().color_mask = Some(Box::new(mask("masked", "own")));
|
||||
let NodeKind::Image(im) = &n.kind else { unreachable_kind() };
|
||||
assert_eq!(d.shown_image(&n, im).key, "masked");
|
||||
// Linked: the shown copy links to nothing, so outputs write the masked pixels.
|
||||
let mut linked = (**im).clone();
|
||||
linked.link = Some(crate::LinkInfo::new("/a.png"));
|
||||
assert_eq!(d.shown_image(&n, &linked).link, None);
|
||||
// Made from other pixels: its own until they are made again.
|
||||
assert_eq!(d.shown_image(&n, &image("other")).key, "other");
|
||||
// Masked pixels the document doesn't have: its own.
|
||||
n.extras_mut().color_mask = Some(Box::new(mask("gone", "own")));
|
||||
let NodeKind::Image(im) = &n.kind else { unreachable_kind() };
|
||||
assert_eq!(d.shown_image(&n, im).key, "own");
|
||||
// Pixels an image holds itself are drawn as they are.
|
||||
let own = ImageObject { pixels: Some(Arc::new(ImageBlob::png(vec![3]))), ..image("own") };
|
||||
n.extras_mut().color_mask = Some(Box::new(mask("masked", "own")));
|
||||
assert_eq!(d.shown_image(&n, &own).key, "own");
|
||||
// A mask that hides nothing (its masked pixels are the image's own): the image itself, so
|
||||
// a linked image stays linked in outputs.
|
||||
n.extras_mut().color_mask = Some(Box::new(mask("own", "own")));
|
||||
assert_eq!(d.shown_image(&n, &linked).link, linked.link);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mask_saves_and_reads_back_with_its_node() {
|
||||
let mut n = Node::new(NodeId(5), NodeKind::Image(Box::new(image("own"))));
|
||||
n.extras_mut().color_mask = Some(Box::new(mask("masked", "own")));
|
||||
let json = serde_json::to_value(&n).unwrap();
|
||||
assert_eq!(json["color_mask"]["key"], "masked", "the masked pixels' key is a `key` member: {json}");
|
||||
assert_eq!(json["color_mask"]["match"], "distance");
|
||||
let back: Node = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(back, n);
|
||||
// A node without one writes none.
|
||||
let plain = Node::new(NodeId(6), NodeKind::Image(Box::new(image("own"))));
|
||||
assert!(serde_json::to_value(&plain).unwrap().get("color_mask").is_none());
|
||||
}
|
||||
|
||||
/// A record that leaves out settings reads them as the command's defaults: edge color,
|
||||
/// contiguous, distance, tolerance and softness 10.
|
||||
#[test]
|
||||
fn a_record_without_settings_reads_the_defaults() {
|
||||
let m: ColorMask = serde_json::from_value(serde_json::json!({"key": "masked", "from": "own"})).unwrap();
|
||||
assert_eq!(
|
||||
(m.background, m.colors.len(), m.contiguous, m.measure, m.tolerance, m.softness),
|
||||
(MaskBackground::Edges, 0, true, MaskMatch::Distance, 10.0, 10.0)
|
||||
);
|
||||
}
|
||||
|
||||
fn unreachable_kind() -> ! {
|
||||
panic!("an image node")
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,7 @@ impl Document {
|
||||
units_from_file: _,
|
||||
index: _,
|
||||
guide_cache: _,
|
||||
inline_cycles: _,
|
||||
} = self;
|
||||
*version == other.version
|
||||
&& *title == other.title
|
||||
@@ -262,6 +263,7 @@ impl Document {
|
||||
units_from_file: false,
|
||||
index: Default::default(),
|
||||
guide_cache: Default::default(),
|
||||
inline_cycles: Default::default(),
|
||||
};
|
||||
let id = d.alloc_id();
|
||||
d.layers.push(Arc::new(Node::layer(id, "Layer 1", LayerColor::Preset(0))));
|
||||
@@ -286,7 +288,9 @@ impl Document {
|
||||
self.next_id = self.next_id.max(id);
|
||||
}
|
||||
|
||||
/// Ensure `next_id` is above every id in the tree (after deserializing foreign data).
|
||||
/// Ensure `next_id` is above every id in the tree (after deserializing foreign data), then give
|
||||
/// the objects outside the layer tree (opacity-mask art, symbols, graph designs and patterns)
|
||||
/// whose id is missing or already taken a new one, so each stored object has an id of its own.
|
||||
pub fn fix_next_id(&mut self) {
|
||||
// Ids from [`MAX_NEXT_ID`] up (a damaged or hand-made file: #1718) are left out, as is a
|
||||
// counter up there: new ids start under them and never reach them, where counting on from
|
||||
@@ -297,13 +301,12 @@ impl Document {
|
||||
max = max.max(id);
|
||||
}
|
||||
};
|
||||
for l in &self.layers {
|
||||
l.walk(&mut |n| see(n.id.0));
|
||||
}
|
||||
self.visit_stored(|n, _| see(n.id.0));
|
||||
self.slices.iter().for_each(|s| see(s.id.0));
|
||||
self.assets.iter().for_each(|a| see(a.id));
|
||||
let counter = Some(self.next_id).filter(|n| *n <= MAX_NEXT_ID).unwrap_or(0);
|
||||
self.next_id = counter.max(max.saturating_add(1));
|
||||
self.renumber_stored_duplicates();
|
||||
}
|
||||
|
||||
/// Find a node anywhere in the tree.
|
||||
|
||||
@@ -183,8 +183,8 @@ impl Document {
|
||||
self.layers.retain(|l| !l.is_ruler_guide());
|
||||
gone -= self.layers.len();
|
||||
for l in &mut self.layers {
|
||||
if layer_untidy(l) {
|
||||
gone += tidy_layer(Arc::make_mut(l));
|
||||
if let Some(found) = untidy(l, &Node::is_ruler_guide) {
|
||||
gone += tidy_layer(Arc::make_mut(l), found);
|
||||
}
|
||||
}
|
||||
let others = self
|
||||
@@ -198,8 +198,8 @@ impl Document {
|
||||
if root.is_ruler_guide() {
|
||||
*root = Arc::new(Node::group(root.id, vec![]));
|
||||
gone += 1;
|
||||
} else if any_guide(root) {
|
||||
gone += drop_guides_below(Arc::make_mut(root));
|
||||
} else if let Some(found) = guides_below(root, &Node::is_ruler_guide) {
|
||||
gone += drop_guides_below(Arc::make_mut(root), found);
|
||||
}
|
||||
}
|
||||
gone
|
||||
@@ -272,8 +272,8 @@ impl Document {
|
||||
return;
|
||||
}
|
||||
for l in &mut self.layers {
|
||||
if l.holds_ruler_guides() {
|
||||
Arc::make_mut(l).strip_ruler_guides();
|
||||
if let Some(held) = picked_in_layers(l, &Node::is_ruler_guide) {
|
||||
drop_picked(l, held);
|
||||
}
|
||||
}
|
||||
self.saved_guides.extend(guides);
|
||||
@@ -347,16 +347,14 @@ impl Document {
|
||||
/// saved guide whose layer is gone opens. Returns the removed node, without the guides.
|
||||
pub fn remove_edit_layer(&mut self, id: NodeId) -> Result<Arc<Node>, crate::DocError> {
|
||||
let mut layer = self.remove(id)?;
|
||||
if !layer.holds_ruler_guides() {
|
||||
return Ok(layer);
|
||||
}
|
||||
let Some(held) = picked_in_layers(&layer, &Node::is_ruler_guide) else { return Ok(layer) };
|
||||
let mut guides = vec![];
|
||||
layer.walk(&mut |c| {
|
||||
if c.is_ruler_guide() {
|
||||
guides.push(Arc::new(c.clone()));
|
||||
}
|
||||
});
|
||||
Arc::make_mut(&mut layer).strip_ruler_guides();
|
||||
drop_picked(&mut layer, held);
|
||||
let home = self.default_layer().unwrap_or_else(|| self.add_layer(None));
|
||||
self.children_mut(Some(home))?.extend(guides);
|
||||
Ok(layer)
|
||||
@@ -418,21 +416,11 @@ impl Document {
|
||||
if gone.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
fn drop(layer: &mut Arc<Node>, gone: &HashSet<NodeId>) {
|
||||
fn holds(n: &Node, gone: &HashSet<NodeId>) -> bool {
|
||||
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| gone.contains(&c.id) || holds(c, gone)))
|
||||
}
|
||||
if !holds(layer, gone) {
|
||||
return;
|
||||
}
|
||||
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
|
||||
ch.retain(|c| !(c.is_ruler_guide() && gone.contains(&c.id)));
|
||||
for c in ch.iter_mut().filter(|c| c.is_layer()) {
|
||||
drop(c, gone);
|
||||
}
|
||||
}
|
||||
let pick = |n: &Node| n.is_ruler_guide() && gone.contains(&n.id);
|
||||
for l in &mut self.layers {
|
||||
drop(l, &gone);
|
||||
if let Some(held) = picked_in_layers(l, &pick) {
|
||||
drop_picked(l, held);
|
||||
}
|
||||
}
|
||||
sel.guides.retain(|id| !gone.contains(id));
|
||||
if sel.key_guide.is_some_and(|k| gone.contains(&k)) {
|
||||
@@ -444,29 +432,11 @@ impl Document {
|
||||
/// Change the line of every ruler guide on artboard `id` with `f` (whether it is vertical, its
|
||||
/// position).
|
||||
fn edit_artboard_guides(&mut self, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
|
||||
fn visit(layer: &mut Arc<Node>, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
|
||||
fn holds(n: &Node, id: u32) -> bool {
|
||||
n.is_layer()
|
||||
&& n.children().is_some_and(|ch| {
|
||||
ch.iter().any(|c| matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) || holds(c, id))
|
||||
})
|
||||
}
|
||||
if !holds(layer, id) {
|
||||
return;
|
||||
}
|
||||
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
|
||||
for c in ch.iter_mut() {
|
||||
if matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) {
|
||||
if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
|
||||
f(*vertical, pos);
|
||||
}
|
||||
} else if c.is_layer() {
|
||||
visit(c, id, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
let pick = |n: &Node| matches!(n.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id);
|
||||
for l in &mut self.layers {
|
||||
visit(l, id, f);
|
||||
if let Some(held) = picked_in_layers(l, &pick) {
|
||||
edit_picked(l, held, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -503,6 +473,19 @@ impl Document {
|
||||
id
|
||||
}
|
||||
|
||||
/// [`Document::next_artboard_id`] when `top` is the highest id the artboards have (`None`: there
|
||||
/// are none). It reads no artboard unless that id is `u32::MAX`, so a caller that adds many
|
||||
/// artboards and keeps `top` up to date gets each id in constant time.
|
||||
pub fn next_artboard_id_above(&self, top: Option<u32>) -> u32 {
|
||||
match top.unwrap_or(0).max(self.retired_artboard_id.get()).checked_add(1) {
|
||||
Some(id) => {
|
||||
self.retired_artboard_id.raise(id);
|
||||
id
|
||||
}
|
||||
None => self.next_artboard_id(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Record that the artboard with `id` was deleted: no later artboard takes its id.
|
||||
pub fn retire_artboard_id(&self, id: u32) {
|
||||
self.retired_artboard_id.raise(id);
|
||||
@@ -541,6 +524,13 @@ impl Document {
|
||||
t.cached_baselines.clear();
|
||||
t.cached_ink = None;
|
||||
}
|
||||
// Opacity-mask art is stored art too: the copy's gets ids of its own.
|
||||
if let Some(art) = n.extras().mask.as_ref().map(|m| Arc::clone(&m.art)) {
|
||||
let art = Arc::new(self.reid(&art));
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
m.art = art;
|
||||
}
|
||||
}
|
||||
let on_path = n.extras().objects_on_path.is_some();
|
||||
let mut renamed = std::collections::HashMap::new();
|
||||
if let Some(ch) = n.children_mut() {
|
||||
@@ -560,65 +550,172 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `n`, or anything below it (opacity-mask art included), hold a ruler guide?
|
||||
fn any_guide(n: &Node) -> bool {
|
||||
let mut any = false;
|
||||
crate::swatches::walk_with_masks(n, &mut |m| any |= m.is_ruler_guide());
|
||||
any
|
||||
/// What a walk picked in a node: its children by index in order, each with what was picked
|
||||
/// inside it, and what was picked in its opacity-mask art. Empty for a node picked itself.
|
||||
#[derive(Debug, Default)]
|
||||
struct Picked {
|
||||
children: Vec<(usize, Picked)>,
|
||||
mask: Option<Box<Picked>>,
|
||||
}
|
||||
|
||||
/// Remove every ruler guide below `n`, in its members and its opacity-mask art (`n` itself
|
||||
/// stays). Mask art that is a ruler guide becomes an empty group. Returns how many went.
|
||||
fn drop_guides_below(n: &mut Node) -> usize {
|
||||
let mut gone = drop_mask_guides(n);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
let before = ch.len();
|
||||
ch.retain(|c| !c.is_ruler_guide());
|
||||
gone += before - ch.len();
|
||||
for c in ch.iter_mut().filter(|c| any_guide(c)) {
|
||||
gone += drop_guides_below(Arc::make_mut(c));
|
||||
impl Picked {
|
||||
fn is_empty(&self) -> bool {
|
||||
self.children.is_empty() && self.mask.is_none()
|
||||
}
|
||||
|
||||
/// `self`, or `None` when nothing was picked.
|
||||
fn some(self) -> Option<Self> {
|
||||
(!self.is_empty()).then_some(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// The children of `n`, if it is a layer, that `pick` picks (with nothing inside), and its
|
||||
/// sublayers holding one (with what they hold), or `None` when it holds none. `pick` looks at
|
||||
/// each child of the layers once.
|
||||
fn picked_in_layers(n: &Node, pick: &impl Fn(&Node) -> bool) -> Option<Picked> {
|
||||
if !n.is_layer() {
|
||||
return None;
|
||||
}
|
||||
let children = n
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
.filter_map(|(i, c)| if pick(c) { Some((i, Picked::default())) } else { picked_in_layers(c, pick).map(|p| (i, p)) })
|
||||
.collect();
|
||||
Picked { children, mask: None }.some()
|
||||
}
|
||||
|
||||
/// Remove the children of `layer` and of its sublayers that [`picked_in_layers`] picked (`held`).
|
||||
/// Only the layers holding one are copied, and only those are visited.
|
||||
fn drop_picked(layer: &mut Arc<Node>, held: Picked) {
|
||||
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
|
||||
let mut held = held.children.into_iter().peekable();
|
||||
let mut next = 0;
|
||||
ch.retain_mut(|c| {
|
||||
let at = next;
|
||||
next += 1;
|
||||
let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true };
|
||||
// A sublayer holds something; a child picked itself has nothing inside.
|
||||
if inner.is_empty() {
|
||||
return false;
|
||||
}
|
||||
drop_picked(c, inner);
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// Change with `f` (whether it is vertical, its position) the line of each ruler guide of `layer`
|
||||
/// and of its sublayers that [`picked_in_layers`] picked (`held`), in the order they lie in. Only
|
||||
/// the layers holding one, and the guides, are copied, and only those layers are visited.
|
||||
fn edit_picked(layer: &mut Arc<Node>, held: Picked, f: &mut impl FnMut(bool, &mut f64)) {
|
||||
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
|
||||
for (i, inner) in held.children {
|
||||
let Some(c) = ch.get_mut(i) else { continue };
|
||||
if !inner.is_empty() {
|
||||
edit_picked(c, inner, f);
|
||||
} else if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
|
||||
f(*vertical, pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` picked itself when it is a ruler guide by `is_guide`, else the ruler guides below it
|
||||
/// ([`guides_below`]).
|
||||
fn guide_or_below(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
|
||||
if is_guide(n) { Some(Picked::default()) } else { guides_below(n, is_guide) }
|
||||
}
|
||||
|
||||
/// The ruler guides below `n`, by `is_guide`: those among its members and its opacity-mask art
|
||||
/// (each with nothing inside), and the members and mask art holding one further down (with what
|
||||
/// they hold), or `None` when there is none. `is_guide` looks at each node below `n` once, and at
|
||||
/// nothing inside a ruler guide.
|
||||
fn guides_below(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
|
||||
let mask = n.extras().mask.as_deref().and_then(|m| guide_or_below(&m.art, is_guide)).map(Box::new);
|
||||
let children = n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| guide_or_below(c, is_guide).map(|p| (i, p))).collect();
|
||||
Picked { children, mask }.some()
|
||||
}
|
||||
|
||||
/// Remove the ruler guides below `n` that [`guides_below`] `found`, in its members and its
|
||||
/// opacity-mask art (`n` itself stays). Mask art that is a ruler guide becomes an empty group.
|
||||
/// Only the nodes holding one are copied, and only those are visited. Returns how many went.
|
||||
fn drop_guides_below(n: &mut Node, found: Picked) -> usize {
|
||||
let mut gone = drop_mask_guides(n, found.mask);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
let mut found = found.children.into_iter().peekable();
|
||||
let mut next = 0;
|
||||
ch.retain_mut(|c| {
|
||||
let at = next;
|
||||
next += 1;
|
||||
let Some((_, inner)) = found.next_if(|(i, _)| *i == at) else { return true };
|
||||
if inner.is_empty() {
|
||||
gone += 1;
|
||||
return false;
|
||||
}
|
||||
gone += drop_guides_below(Arc::make_mut(c), inner);
|
||||
true
|
||||
});
|
||||
}
|
||||
gone
|
||||
}
|
||||
|
||||
/// Remove every ruler guide in the opacity-mask art of `n`. Mask art that is a ruler guide
|
||||
/// becomes an empty group. Returns how many went.
|
||||
fn drop_mask_guides(n: &mut Node) -> usize {
|
||||
/// Remove the ruler guides `found` in the opacity-mask art of `n` ([`guides_below`]'s mask
|
||||
/// part). Mask art that is a ruler guide becomes an empty group. Returns how many went.
|
||||
fn drop_mask_guides(n: &mut Node, found: Option<Box<Picked>>) -> usize {
|
||||
let Some(found) = found else { return 0 };
|
||||
let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) else { return 0 };
|
||||
if mask.art.is_ruler_guide() {
|
||||
if found.is_empty() {
|
||||
mask.art = Arc::new(Node::group(mask.art.id, vec![]));
|
||||
1
|
||||
} else if any_guide(&mask.art) {
|
||||
drop_guides_below(Arc::make_mut(&mut mask.art))
|
||||
} else {
|
||||
0
|
||||
drop_guides_below(Arc::make_mut(&mut mask.art), *found)
|
||||
}
|
||||
}
|
||||
|
||||
/// Does layer `l` hold a ruler guide out of place: below art, in an object or in mask art, or so
|
||||
/// in one of its sublayers?
|
||||
fn layer_untidy(l: &Node) -> bool {
|
||||
let Some(ch) = l.children() else { return false };
|
||||
let start = Node::guide_run_start(ch);
|
||||
l.extras().mask.as_deref().is_some_and(|m| any_guide(&m.art))
|
||||
|| ch.iter().take(start).any(|c| c.is_ruler_guide() || if c.is_layer() { layer_untidy(c) } else { any_guide(c) })
|
||||
/// The ruler guides, by `is_guide`, that layer `l` holds out of place, or `None` when it holds
|
||||
/// none: those below art (each with nothing inside), those in its mask art and in its objects
|
||||
/// ([`guides_below`]), and its sublayers holding one out of place (with what they hold).
|
||||
/// `is_guide` looks at each node once; the guides at the end of a layer are in place and are
|
||||
/// not looked at.
|
||||
fn untidy(l: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
|
||||
let ch = l.children()?;
|
||||
let mask = l.extras().mask.as_deref().and_then(|m| guide_or_below(&m.art, is_guide)).map(Box::new);
|
||||
let children = ch
|
||||
.iter()
|
||||
.enumerate()
|
||||
.take(Node::guide_run_start(ch))
|
||||
.filter_map(|(i, c)| {
|
||||
let found = if is_guide(c) {
|
||||
Some(Picked::default())
|
||||
} else if c.is_layer() {
|
||||
untidy(c, is_guide)
|
||||
} else {
|
||||
guides_below(c, is_guide)
|
||||
};
|
||||
found.map(|p| (i, p))
|
||||
})
|
||||
.collect();
|
||||
Picked { children, mask }.some()
|
||||
}
|
||||
|
||||
/// [`Document::tidy_ruler_guides`] for layer `l`. Returns how many guides were removed.
|
||||
fn tidy_layer(l: &mut Node) -> usize {
|
||||
let mut gone = drop_mask_guides(l);
|
||||
/// [`Document::tidy_ruler_guides`] for layer `l`, whose guides out of place [`untidy`] `found`.
|
||||
/// Only the nodes holding one are copied, and only those are visited. Returns how many guides
|
||||
/// were removed.
|
||||
fn tidy_layer(l: &mut Node, found: Picked) -> usize {
|
||||
let mut gone = drop_mask_guides(l, found.mask);
|
||||
let Some(ch) = l.children_mut() else { return gone };
|
||||
for c in ch.iter_mut() {
|
||||
if c.is_layer() {
|
||||
if layer_untidy(c) {
|
||||
gone += tidy_layer(Arc::make_mut(c));
|
||||
}
|
||||
} else if !c.is_ruler_guide() && any_guide(c) {
|
||||
gone += drop_guides_below(Arc::make_mut(c));
|
||||
let mut below_art = false;
|
||||
for (i, inner) in found.children {
|
||||
let Some(c) = ch.get_mut(i) else { continue };
|
||||
if inner.is_empty() {
|
||||
below_art = true;
|
||||
} else if c.is_layer() {
|
||||
gone += tidy_layer(Arc::make_mut(c), inner);
|
||||
} else {
|
||||
gone += drop_guides_below(Arc::make_mut(c), inner);
|
||||
}
|
||||
}
|
||||
if ch.iter().take(Node::guide_run_start(ch)).any(|c| c.is_ruler_guide()) {
|
||||
if below_art {
|
||||
let (guides, art): (Vec<_>, Vec<_>) = std::mem::take(ch).into_iter().partition(|c| c.is_ruler_guide());
|
||||
*ch = art;
|
||||
ch.extend(guides);
|
||||
@@ -678,3 +775,286 @@ impl std::fmt::Debug for GuideCache {
|
||||
f.write_str("GuideCache")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Appearance, OpacityMask, Symbol};
|
||||
use std::cell::Cell;
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
/// The sublayers in [`nested`]'s chain: with the top-level layer around them and the objects in
|
||||
/// the innermost, the deepest a document goes ([`crate::MAX_DEPTH`]).
|
||||
const CHAIN: u64 = 30;
|
||||
|
||||
fn rect(id: u64) -> Arc<Node> {
|
||||
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()))
|
||||
}
|
||||
|
||||
fn guide(id: u64, artboard: Option<u32>) -> Arc<Node> {
|
||||
Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: false, pos: id as f64, artboard }))
|
||||
}
|
||||
|
||||
fn group(id: u64, children: Vec<Arc<Node>>) -> Arc<Node> {
|
||||
Arc::new(Node::group(NodeId(id), children))
|
||||
}
|
||||
|
||||
/// `n` with `art` as its opacity-mask art.
|
||||
fn masked(n: Arc<Node>, art: Arc<Node>) -> Arc<Node> {
|
||||
let mut n = (*n).clone();
|
||||
n.extras_mut().mask = Some(Box::new(OpacityMask { art, clip: true, invert: false, disabled: false, linked: true }));
|
||||
Arc::new(n)
|
||||
}
|
||||
|
||||
/// A sublayer like a new document's first layer, holding `children`.
|
||||
fn sublayer(id: u64, children: Vec<Arc<Node>>) -> Arc<Node> {
|
||||
let mut l = (*Document::new(1.0, 1.0).layers[0]).clone();
|
||||
l.id = NodeId(id);
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
Arc::new(l)
|
||||
}
|
||||
|
||||
/// A document whose first layer holds `children`.
|
||||
fn doc(children: Vec<Arc<Node>>) -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
if let Some(ch) = d.layers.first_mut().and_then(|l| Arc::make_mut(l).children_mut()) {
|
||||
*ch = children;
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// The ids of the nodes in the layers, in tree order.
|
||||
fn ids(d: &Document) -> Vec<u64> {
|
||||
fn walk(n: &Node, out: &mut Vec<u64>) {
|
||||
out.push(n.id.0);
|
||||
for c in n.children().into_iter().flatten() {
|
||||
walk(c, out);
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
for l in &d.layers {
|
||||
walk(l, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// [`CHAIN`] sublayers, each inside the one before and holding an object, a canvas guide and a
|
||||
/// guide of artboard 7 (the innermost: object 150, guides 200 and 201). Beside the chain, a
|
||||
/// sublayer with a canvas guide only. Returns the document and that sublayer.
|
||||
fn nested() -> (Document, Arc<Node>) {
|
||||
let mut chain = sublayer(100, vec![rect(150), guide(200, None), guide(201, Some(7))]);
|
||||
for depth in 1..CHAIN {
|
||||
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth * 2, None), guide(301 + depth * 2, Some(7))]);
|
||||
}
|
||||
let still = sublayer(500, vec![rect(502), guide(501, None)]);
|
||||
(doc(vec![chain, Arc::clone(&still)]), still)
|
||||
}
|
||||
|
||||
/// How many children the layers of [`nested`] hold: the first layer's 2, the untouched
|
||||
/// sublayer's 2, the innermost sublayer's 3 and 4 in each sublayer around it.
|
||||
const NESTED_CHILDREN: usize = 2 + 2 + 3 + (CHAIN as usize - 1) * 4;
|
||||
|
||||
fn on_artboard_7(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::RulerGuide { artboard: Some(7), .. })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_guides_looks_at_each_child_of_nested_layers_once() {
|
||||
let (mut d, still) = nested();
|
||||
assert!(!d.clone().limit_depth(), "the chain is as deep as a document goes");
|
||||
let mut deeper = doc(vec![sublayer(999, d.layers[0].children().cloned().unwrap_or_default())]);
|
||||
assert!(deeper.limit_depth(), "a document nested deeper is brought within the cap when it is read");
|
||||
let mut whole = d.clone();
|
||||
let looked = Cell::new(0_usize);
|
||||
let pick = |n: &Node| {
|
||||
looked.set(looked.get() + 1);
|
||||
on_artboard_7(n)
|
||||
};
|
||||
let held = picked_in_layers(&d.layers[0], &pick).unwrap();
|
||||
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
|
||||
drop_picked(&mut d.layers[0], held);
|
||||
assert_eq!(looked.get(), NESTED_CHILDREN, "removing looks at nothing again");
|
||||
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with nothing to remove is not copied");
|
||||
|
||||
// The command's own entry point removes the same guides.
|
||||
let before = whole.clone();
|
||||
let mut sel = Selection::default();
|
||||
sel.set_guides([NodeId(200), NodeId(201), NodeId(501)]);
|
||||
sel.objects.push(NodeId(150));
|
||||
sel.key_guide = Some(NodeId(201));
|
||||
assert_eq!(whole.retain_guides(&mut sel, |g| g.artboard != Some(7)), CHAIN as usize);
|
||||
assert_eq!(ids(&whole), ids(&d));
|
||||
assert_eq!(ids(&whole).len(), ids(&before).len() - CHAIN as usize);
|
||||
assert!(whole.ruler_guides().iter().all(|g| g.artboard.is_none()));
|
||||
assert_eq!(whole.ruler_guides().len(), CHAIN as usize + 1);
|
||||
assert_eq!((sel.objects.as_slice(), sel.guides.as_slice(), sel.key_guide), (&[NodeId(150)][..], &[NodeId(200), NodeId(501)][..], None));
|
||||
assert!(whole.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)));
|
||||
// The document as it was (an undo step's copy) still holds every guide.
|
||||
assert_eq!(before.ruler_guides().len(), CHAIN as usize * 2 + 1);
|
||||
|
||||
// Saving the guides as a list, and removing a layer but not its guides, take the guides
|
||||
// out of the nested layers too.
|
||||
let mut saved = before.clone();
|
||||
saved.guides_to_saved();
|
||||
assert_eq!(saved.saved_guides, before.ruler_guides());
|
||||
assert_eq!(ids(&saved).len(), 1 + CHAIN as usize * 2 + 2);
|
||||
assert!(saved.layers[0].children().is_some_and(|c| !Arc::ptr_eq(&c[1], &still) && c[1].children().is_some_and(|c| c.len() == 1)));
|
||||
let mut edited = before.clone();
|
||||
let chain = edited.remove_edit_layer(NodeId(100 + CHAIN - 1)).unwrap();
|
||||
assert!(!chain.holds_ruler_guides());
|
||||
assert_eq!(edited.ruler_guides().len(), before.ruler_guides().len(), "the removed layer's guides stay in the document");
|
||||
assert_eq!(edited.guides_on(edited.layers[0].id).len(), CHAIN as usize * 2);
|
||||
|
||||
// Keeping every guide changes nothing and copies no layer.
|
||||
let kept = whole.clone();
|
||||
assert_eq!(whole.retain_guides(&mut sel, |_| true), 0);
|
||||
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
|
||||
// Removing every guide leaves the objects.
|
||||
assert_eq!(whole.retain_guides(&mut sel, |_| false), CHAIN as usize + 1);
|
||||
assert!(whole.ruler_guides().is_empty() && sel.guides.is_empty());
|
||||
assert_eq!(ids(&whole).len(), 1 + CHAIN as usize * 2 + 2);
|
||||
assert_eq!(sel.objects, [NodeId(150)]);
|
||||
// A document without layers, and one without guides, have nothing to remove.
|
||||
let mut empty = Document::new(10.0, 10.0);
|
||||
assert_eq!(empty.retain_guides(&mut sel, |_| false), 0);
|
||||
empty.layers.clear();
|
||||
assert_eq!(empty.retain_guides(&mut sel, |_| false), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_artboards_guides_looks_at_each_child_of_nested_layers_once() {
|
||||
let (mut d, still) = nested();
|
||||
let mut whole = d.clone();
|
||||
let looked = Cell::new(0_usize);
|
||||
let pick = |n: &Node| {
|
||||
looked.set(looked.get() + 1);
|
||||
on_artboard_7(n)
|
||||
};
|
||||
let held = picked_in_layers(&d.layers[0], &pick).unwrap();
|
||||
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
|
||||
let mut seen = vec![];
|
||||
edit_picked(&mut d.layers[0], held, &mut |vertical, pos: &mut f64| {
|
||||
seen.push((vertical, *pos));
|
||||
*pos += 9.0;
|
||||
});
|
||||
assert_eq!(looked.get(), NESTED_CHILDREN, "changing looks at nothing again");
|
||||
// A sublayer comes before its layer's own guides, so the innermost guide is changed first.
|
||||
let order: Vec<(bool, f64)> = [201.0].into_iter().chain((1..CHAIN).map(|depth| (301 + depth * 2) as f64)).map(|pos| (false, pos)).collect();
|
||||
assert_eq!(seen, order, "each guide of the artboard is changed once, in the order the guides lie in");
|
||||
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with no guide of the artboard is not copied");
|
||||
|
||||
// The public moves change the same guides by the same amount.
|
||||
let before = whole.clone();
|
||||
whole.move_artboard_guides(7, Vec2::new(5.0, 9.0));
|
||||
assert_eq!(whole, d);
|
||||
assert_eq!(ids(&whole), ids(&before));
|
||||
for g in whole.ruler_guides() {
|
||||
let id = g.id.map_or(0, |id| id.0) as f64;
|
||||
assert_eq!(g.pos, if g.artboard == Some(7) { id + 9.0 } else { id }, "guide {id}");
|
||||
}
|
||||
assert!(whole.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)));
|
||||
assert_eq!(before.ruler_guide(NodeId(201)).map(|g| g.pos), Some(201.0), "the document as it was keeps its guides");
|
||||
whole.map_artboard_guides(7, Affine::scale(2.0));
|
||||
assert_eq!(whole.ruler_guide(NodeId(201)).map(|g| g.pos), Some(420.0));
|
||||
assert_eq!(whole.ruler_guide(NodeId(200)).map(|g| g.pos), Some(200.0), "a canvas guide stays");
|
||||
|
||||
// An artboard without guides, and a document without layers, change nothing and copy no layer.
|
||||
let kept = whole.clone();
|
||||
whole.move_artboard_guides(99, Vec2::new(5.0, 9.0));
|
||||
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
|
||||
let mut empty = Document::new(10.0, 10.0);
|
||||
empty.layers.clear();
|
||||
empty.move_artboard_guides(7, Vec2::new(5.0, 9.0));
|
||||
assert!(empty.layers.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_in_objects_are_found_by_looking_at_each_node_once() {
|
||||
// Groups, each inside the one before and holding an object and a guide. Beside them, an
|
||||
// object whose mask art holds a guide, one whose mask art is a guide, and a group with none.
|
||||
let mut chain = group(100, vec![rect(150), guide(200, None)]);
|
||||
for depth in 1..CHAIN {
|
||||
chain = group(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth, None)]);
|
||||
}
|
||||
let still = group(700, vec![rect(701)]);
|
||||
let root = group(
|
||||
1,
|
||||
vec![chain, masked(rect(800), group(801, vec![guide(802, None), rect(803)])), masked(rect(810), guide(811, None)), Arc::clone(&still)],
|
||||
);
|
||||
let looked = Cell::new(0_usize);
|
||||
let is_guide = |n: &Node| {
|
||||
looked.set(looked.get() + 1);
|
||||
n.is_ruler_guide()
|
||||
};
|
||||
// The chain's groups, objects and guides; a masked object, its mask group and the two in
|
||||
// it; a masked object and its mask guide; the last group and its object.
|
||||
let nodes = CHAIN as usize * 3 + 4 + 2 + 2;
|
||||
let found = guides_below(&root, &is_guide).unwrap();
|
||||
assert_eq!(looked.get(), nodes, "each node below the root is looked at once");
|
||||
let mut cleared = (*root).clone();
|
||||
assert_eq!(drop_guides_below(&mut cleared, found), CHAIN as usize + 2);
|
||||
assert_eq!(looked.get(), nodes, "removing looks at nothing again");
|
||||
assert!(guides_below(&cleared, &Node::is_ruler_guide).is_none());
|
||||
let ch = cleared.children().unwrap();
|
||||
assert!(Arc::ptr_eq(&ch[3], &still), "a group without guides is not copied");
|
||||
assert_eq!(
|
||||
ch[1].extras().mask.as_deref().map(|m| m.art.children().map(|c| c.iter().map(|c| c.id.0).collect::<Vec<_>>())),
|
||||
Some(Some(vec![803]))
|
||||
);
|
||||
assert_eq!(ch[2].extras().mask.as_deref().map(|m| (m.art.id, m.art.children().map(Vec::len))), Some((NodeId(811), Some(0))));
|
||||
|
||||
// Opening a file removes the same guides from an object on a layer and from a symbol's art.
|
||||
let mut d = doc(vec![Arc::clone(&root), guide(900, None)]);
|
||||
d.symbols = vec![Symbol { name: "s".into(), art: Arc::clone(&root), dynamic: false }];
|
||||
assert_eq!(d.tidy_ruler_guides(), (CHAIN as usize + 2) * 2);
|
||||
assert_eq!(d.layers[0].children().map(|c| (*c[0]).clone()), Some(cleared.clone()));
|
||||
assert_eq!(*d.symbols[0].art, cleared);
|
||||
assert_eq!(d.ruler_guides().iter().map(|g| g.id).collect::<Vec<_>>(), [Some(NodeId(900))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_out_of_place_are_found_by_looking_at_each_node_once() {
|
||||
// Sublayers, each inside the one before, with their guides in place; the innermost also
|
||||
// holds a guide below its art. Beside them, a group holding a guide, a sublayer with its
|
||||
// guide in place, and a sublayer whose mask art holds a guide.
|
||||
let mut chain = sublayer(100, vec![guide(200, None), rect(150), guide(201, None)]);
|
||||
for depth in 1..CHAIN {
|
||||
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth, None)]);
|
||||
}
|
||||
let still = sublayer(500, vec![rect(502), guide(501, None)]);
|
||||
let with_mask = masked(sublayer(510, vec![rect(513)]), group(511, vec![guide(512, None)]));
|
||||
let mut d = doc(vec![chain, group(700, vec![rect(701), guide(702, None)]), Arc::clone(&still), with_mask, guide(900, None)]);
|
||||
let mut whole = d.clone();
|
||||
let looked = Cell::new(0_usize);
|
||||
let is_guide = |n: &Node| {
|
||||
looked.set(looked.get() + 1);
|
||||
n.is_ruler_guide()
|
||||
};
|
||||
// Below the guides at the end of each layer: the first layer's 4, the group's 2, the
|
||||
// untouched sublayer's 1, the masked sublayer's mask group, its guide and the object, 2 in
|
||||
// the innermost sublayer and 2 in each sublayer around it.
|
||||
let nodes = 4 + 2 + 1 + 3 + 2 + (CHAIN as usize - 1) * 2;
|
||||
let found = untidy(&d.layers[0], &is_guide).unwrap();
|
||||
assert_eq!(looked.get(), nodes, "each node below the guides in place is looked at once");
|
||||
assert_eq!(tidy_layer(Arc::make_mut(&mut d.layers[0]), found), 2);
|
||||
assert_eq!(looked.get(), nodes, "tidying looks at nothing again");
|
||||
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[2], &still)), "a sublayer with its guides in place is not copied");
|
||||
assert!(untidy(&d.layers[0], &Node::is_ruler_guide).is_none());
|
||||
|
||||
// Opening a file does the same.
|
||||
let before = whole.clone();
|
||||
assert_eq!(whole.tidy_ruler_guides(), 2);
|
||||
assert_eq!(whole, d);
|
||||
let all = ids(&whole);
|
||||
assert!(!all.contains(&702) && all.len() == ids(&before).len() - 1);
|
||||
let innermost = whole.node(NodeId(100)).and_then(|n| n.children()).map(|c| c.iter().map(|c| c.id.0).collect::<Vec<_>>());
|
||||
assert_eq!(innermost, Some(vec![150, 200, 201]), "a guide below art moves up to the other guides");
|
||||
assert!(whole.node(NodeId(510)).is_some_and(|n| n.extras().mask.as_deref().is_some_and(|m| m.art.children().is_some_and(Vec::is_empty))));
|
||||
// A tidy document is left alone, and no layer is copied.
|
||||
let kept = whole.clone();
|
||||
assert_eq!(whole.tidy_ruler_guides(), 0);
|
||||
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1281 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user