mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 17:05:55 +01:00
Merge main into feat/native-save-precision
This commit is contained in:
commit
5d5b775e27
1138 files changed
+176049
-145413
No files matched your search
@@ -0,0 +1,3 @@
|
||||
# Minimum cargo-nextest for this repository: GHSA-vc25-qg58-w57c is fixed in 0.9.150 and CI
|
||||
# installs exactly that version, so an older nextest refuses to run (exit 92 REQUIRED_VERSION_NOT_MET).
|
||||
nextest-version = "0.9.150"
|
||||
+24
-4
@@ -10,11 +10,31 @@ updates:
|
||||
interval: "daily"
|
||||
time: "06:00"
|
||||
timezone: "America/New_York"
|
||||
# Consolidate updates into a single PR rather than one PR per crate
|
||||
groups:
|
||||
cargo-dependencies:
|
||||
patterns:
|
||||
- "*"
|
||||
# A dependency that matches several groups goes to the first one it matches, so the
|
||||
# lockstep families are listed before the catch-all cargo-patch group.
|
||||
# Families that must move together; all update types of a family land in one PR.
|
||||
egui-stack: # egui/eframe/winit are [patch.crates-io]'d to storytold forks: expect this PR red on upstream releases until the forks move
|
||||
patterns: ["egui*", "eframe", "epaint*", "ecolor", "emath", "winit", "wgpu*", "naga", "accesskit*"]
|
||||
font-stack:
|
||||
patterns: ["harfrust", "skrifa", "read-fonts", "font-types", "fontique", "parley", "write-fonts", "skera", "ttf-parser"]
|
||||
pdf-render-stack:
|
||||
patterns: ["hayro*", "krilla*", "vello*", "peniko", "kurbo", "resvg", "usvg", "tiny-skia*", "svgtypes"]
|
||||
icu-stack:
|
||||
patterns: ["icu_*", "fixed_decimal"]
|
||||
ml-stack:
|
||||
patterns: ["candle-*", "rten*", "ocrs"]
|
||||
platform-stack:
|
||||
patterns: ["zbus*", "zvariant*", "x11rb*"]
|
||||
apple-stack:
|
||||
patterns: ["objc2*", "block2", "dispatch2"]
|
||||
rustcrypto:
|
||||
patterns: ["aes", "sha1", "sha2", "sha3", "md-5", "hmac", "pbkdf2", "digest", "cipher"]
|
||||
# Everything else: patch bumps only (minor/major of other crates get one PR each).
|
||||
cargo-patch:
|
||||
update-types: ["patch"]
|
||||
patterns: ["*"]
|
||||
open-pull-requests-limit: 10
|
||||
commit-message:
|
||||
prefix: "chore(deps)"
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
# Same craft-fonts commit as release.yml.
|
||||
craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
timeout-minutes: 90
|
||||
packages: >-
|
||||
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev
|
||||
|
||||
@@ -29,5 +29,5 @@ jobs:
|
||||
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
|
||||
with:
|
||||
require-craft-fonts: true
|
||||
craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
run-package-check: true
|
||||
@@ -23,3 +23,27 @@ jobs:
|
||||
uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main
|
||||
with:
|
||||
extra-checks-script: packaging/check-app-specific.sh
|
||||
|
||||
windows-install-policy:
|
||||
timeout-minutes: 10
|
||||
name: Windows installation policy (no app build)
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Install the pinned packaging toolchain
|
||||
shell: pwsh
|
||||
run: |
|
||||
$tools = Join-Path $env:RUNNER_TEMP 'craft-install-policy-wix'
|
||||
dotnet tool install --tool-path $tools wix --version 5.0.2
|
||||
if ($LASTEXITCODE -ne 0) { throw 'WiX installation failed.' }
|
||||
$tools >> $env:GITHUB_PATH
|
||||
$policy = Get-Content -Raw -LiteralPath packaging/windows/install-policy.json | ConvertFrom-Json
|
||||
foreach ($extension in @($policy.extensions)) {
|
||||
& (Join-Path $tools 'wix.exe') extension add -g "WixToolset.$extension.wixext/5.0.2"
|
||||
if ($LASTEXITCODE -ne 0) { throw "WiX extension $extension installation failed." }
|
||||
}
|
||||
- name: Build and check non-executable installer fixtures
|
||||
shell: pwsh
|
||||
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
|
||||
@@ -8,7 +8,7 @@ on:
|
||||
- "apps/vectorcraft/src/printing.rs"
|
||||
- "apps/vectorcraft/src/printing/**"
|
||||
- "crates/ui-egui/src/print.rs"
|
||||
- "crates/ui-egui/src/tests_printps.rs"
|
||||
- "crates/ui-egui/src/tests/printps.rs"
|
||||
- ".github/workflows/print.yml"
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
@@ -32,4 +32,8 @@ jobs:
|
||||
- run: cargo clippy --locked -p vectorcraft --all-targets -- -D warnings
|
||||
- run: cargo test --locked -p vectorcraft
|
||||
- name: Check pending submission and queue refusal feedback
|
||||
run: cargo test --locked -p vectorcraft-ui-egui tests_printps
|
||||
shell: bash
|
||||
# A filter that matches nothing still passes, so fail unless some test ran.
|
||||
run: |
|
||||
cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee printps.log
|
||||
grep -Eq 'test result: ok\. [1-9][0-9]* passed' printps.log || { echo "::error::tests::printps matched no tests"; exit 1; }
|
||||
@@ -68,7 +68,7 @@ jobs:
|
||||
with:
|
||||
app-name: vectorcraft
|
||||
app-title: VectorCraft
|
||||
craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
web-craft-fonts: true
|
||||
version: ${{ inputs.version }}
|
||||
secrets:
|
||||
|
||||
@@ -27,8 +27,10 @@ permissions:
|
||||
|
||||
jobs:
|
||||
windows-arm64:
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main
|
||||
# Immutable supporting workflow revision until the new install contract lands upstream.
|
||||
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f
|
||||
with:
|
||||
app-name: vectorcraft
|
||||
app-dir: VectorCraft
|
||||
install-relative-path: Programs/ArtCraft/VectorCraft
|
||||
install-scope: perUser
|
||||
@@ -14,7 +14,7 @@ on:
|
||||
- "apps/vectorcraft/src/printing.rs"
|
||||
- "apps/vectorcraft/src/printing/**"
|
||||
- "crates/ui-egui/src/print.rs"
|
||||
- "crates/ui-egui/src/tests_printps.rs"
|
||||
- "crates/ui-egui/src/tests/printps.rs"
|
||||
- "packaging/windows/windows7.ps1"
|
||||
- ".github/workflows/windows7.yml"
|
||||
schedule:
|
||||
|
||||
@@ -12,6 +12,8 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `epaint_default_fonts/fonts/egui-icons.ttf` (egui dependency) | John Slegers (emoji-icon-font) | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/egui-icons.txt; original https://github.com/jslegers/emoji-icon-font | MIT (full text in NOTICE) | Small special-icon subset embedded by default_fonts |
|
||||
| `epaint_default_fonts/fonts/emoji-icon-font.ttf` (egui dependency) | John Slegers | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/emoji-icon-font-mit-license.txt; original https://github.com/jslegers/emoji-icon-font | MIT (full text in NOTICE) | Parent face embedded by monochrome_emoji_fonts |
|
||||
| `docs/brand/artcraft-logo-white.png` | ArtCraft team (project owner) | https://getartcraft.com/ | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | Used in README only; not shipped in the app |
|
||||
| `docs/brand/artcraft-logo-white.svg` | ArtCraft team (project owner) | https://getartcraft.com/ | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | Used in README only; not shipped in the app |
|
||||
| `docs/brand/artcraft-logo.png` | ArtCraft team (project owner) | https://getartcraft.com/ | ArtCraft trademark, see docs/brand/LICENSE-brand.txt (not open source) | Used in README only; not shipped in the app |
|
||||
@@ -350,20 +352,20 @@ The shared PDF backend keeps the existing standard-font and CMap features. These
|
||||
|
||||
| Crate / file | Author | Source | Licence | SHA-256 | Use |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) |
|
||||
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
|
||||
| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitDingbats.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitDingbats.pfb | BSD-3-Clause | `845c752392b6c914fb989c75a08b7792b88f542d2499042ef2889f8c814a16ed` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixed.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixed.pfb | BSD-3-Clause | `b6c8fe53f134b8b6d4578cd2d544df4cee9624c4efa8d51a560fb40ea296101b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedBold.pfb | BSD-3-Clause | `f1b7159702973f54fc86254ea38bcf3712b2a736eb3a0995751e9f4bb45ad603` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedBoldItalic.pfb | BSD-3-Clause | `8a000945843bd31add06aee63bf9fd41b7578b4f3242a4b7cd46349ad9d24d4d` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitFixedItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitFixedItalic.pfb | BSD-3-Clause | `5007faf8320fa1fcc08b8894b356ad976f60b992ba29ee5272578bbdebaf3876` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSans.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSans.pfb | BSD-3-Clause | `a02339e95d20db14cbdfc1c6baf359cd36a091d5434925c3a4040f60e1a1af9e` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansBold.pfb | BSD-3-Clause | `7bdfa36de1d5757dcfaf8b8a4be95c6e41c40fa70dbed9d78bf979a7b9959054` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansBoldItalic.pfb | BSD-3-Clause | `555ce45924338e2e4b32821910221ce85da691fd59a9723c4c971a7c5627fc8b` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSansItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSansItalic.pfb | BSD-3-Clause | `7751cbefeda351708dae8c4a88db043411bc39ab2ae2097685da845d4d16f307` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerif.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerif.pfb | BSD-3-Clause | `4f57d2b9d884af8f907bf22df6019b52d86cbf6214fdbd02b1ae05472a543f35` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifBold.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifBold.pfb | BSD-3-Clause | `0bdf4b04e964139818d51eda03d566ba999fc3ba2421b1c6c51f9dc969022e80` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifBoldItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifBoldItalic.pfb | BSD-3-Clause | `a406cac82583bf98175cb62c87ed5e95c45fbb34eece63a10b0a13e793cb2e10` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSerifItalic.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSerifItalic.pfb | BSD-3-Clause | `610ae0687198045c4db5d1a6650fd5e92536631706382eb8b72e38df578d0ae9` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/FoxitSymbol.pfb` | Foxit Software Inc. / PDFium Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/FoxitSymbol.pfb | BSD-3-Clause | `47967d055530e7357088a08403115425643ec2cdfd6201ba8af0fbd7116c1539` | Renders non-embedded standard-14 fonts (pinned hayro-interpret) |
|
||||
| `hayro-interpret 0.7.0 / assets/CGATS001Compat-v2-micro.icc` | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc | CC0-1.0 | `73e1ba37d2bad5bab2a964f40a9eed96209666efc067c3322626214bbef234a0` | Default CMYK colour conversion (pinned hayro-interpret) |
|
||||
| `hayro-cmap 0.1.0 / assets/cmaps.brotli` | Adobe | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-cmap/assets/cmaps.brotli | BSD-3-Clause | `ddf37af521d904d5646c2fc37b2b7e912dc1b56f0d210190b61f598154758e46` | Character-code mapping tables required to read CJK PDFs. Non-visual dependency data; existing embedding unchanged |
|
||||
| `hayro-interpret 0.7.0 / src/font/generated/metrics.rs` | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/hayro-interpret/src/font/generated/metrics.rs | MIT OR Apache-2.0 | `2ec9e608573eda459de1e1d9bda3bb494315e36bee885acc88912a11fe0caa41` | Glyph widths and encodings for non-embedded standard fonts. Non-visual dependency data; existing embedding unchanged |
|
||||
Generated
+1779
-162
File diff suppressed because it is too large.
Load diff
+32
-16
@@ -11,14 +11,15 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "2eca9b3a53a98ac52efed2a27353c6a6927ead10", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d991bf6792f8ade99c51358bf3c1d902c8cd96b5" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "2eca9b3a53a98ac52efed2a27353c6a6927ead10" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false, features = ["interpret", "write"] }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
|
||||
# desktop. The `egui` feature adds `craft_window::decorate`. (craft-libs#217.)
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "1f805378d454dac48b5c214029d254055fdf961b", features = ["egui"] }
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -102,10 +103,10 @@ tiff = "0.11"
|
||||
zune-jpeg = "0.5"
|
||||
|
||||
# ui
|
||||
egui = "0.36"
|
||||
egui_extras = { version = "0.36", default-features = false, features = ["svg"] }
|
||||
eframe = { version = "0.36", default-features = false }
|
||||
egui_kittest = "0.36"
|
||||
egui = "0.37"
|
||||
egui_extras = { version = "0.37", default-features = false, features = ["svg"] }
|
||||
eframe = { version = "0.37", default-features = false }
|
||||
egui_kittest = "0.37"
|
||||
rfd = "0.17"
|
||||
arboard = { version = "3.6", default-features = false }
|
||||
clipboard-win = "5.4"
|
||||
@@ -140,9 +141,24 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "2eca9b3a53a98ac52efed2a27353c6a6927ead10" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "2eca9b3a53a98ac52efed2a27353c6a6927ead10" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "2eca9b3a53a98ac52efed2a27353c6a6927ead10" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "2eca9b3a53a98ac52efed2a27353c6a6927ead10" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "2eca9b3a53a98ac52efed2a27353c6a6927ead10" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "2eca9b3a53a98ac52efed2a27353c6a6927ead10" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
@@ -77,10 +77,10 @@ Shared PDF backend
|
||||
|
||||
The patched hayro-interpret 0.7.0, hayro-syntax 0.7.2, hayro-jbig2 0.3.0, hayro-cmap 0.1.0
|
||||
and hayro-postscript 0.1.0 are fetched from https://github.com/storytold/craft-libs at revision
|
||||
2eca9b3a53a98ac52efed2a27353c6a6927ead10. Their upstream project is
|
||||
92d392cff132eaf53e13afff77f38b5c11b73aa0. Their upstream project is
|
||||
https://github.com/LaurenzV/hayro, licensed MIT OR Apache-2.0. The snapshot retains each
|
||||
crate's upstream licence files. The patch ledger is at
|
||||
https://github.com/storytold/craft-libs/blob/2eca9b3a53a98ac52efed2a27353c6a6927ead10/vendor/README.craft-reader.md.
|
||||
https://github.com/storytold/craft-libs/blob/92d392cff132eaf53e13afff77f38b5c11b73aa0/vendor/README.craft-reader.md.
|
||||
|
||||
Assets already bundled through Hayro's default features retain their licences:
|
||||
- Foxit standard-14 substitutes: Copyright 2014 PDFium Authors. All rights reserved.
|
||||
@@ -123,3 +123,21 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
Bundled egui font icons
|
||||
|
||||
The pinned egui dependency includes egui-icons.ttf, a small subset of John Slegers'
|
||||
emoji-icon-font, through default_fonts. The parent emoji-icon-font.ttf face is
|
||||
included through monochrome_emoji_fonts. Their upstream project is
|
||||
https://github.com/jslegers/emoji-icon-font; both use the same exact copyright
|
||||
and permission notice below.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2014 John Slegers
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -32,10 +32,11 @@ log = { workspace = true }
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winsafe = { version = "0.0.29", default-features = false, features = ["kernel", "psapi"] }
|
||||
|
||||
# DirectWrite's system font collection (the desktop app's src/system_fonts.rs, shared): fonts that
|
||||
# font services such as Adobe Fonts load in place (#579). MIT OR Apache-2.0.
|
||||
# DirectWrite's system font collection and GDI's font list (the desktop app's src/system_fonts.rs,
|
||||
# shared): fonts that font services such as Adobe Fonts load in place (#579, #1258). MIT OR
|
||||
# Apache-2.0.
|
||||
[target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies]
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite"] }
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi"] }
|
||||
|
||||
# CoreText's font manager (the desktop app's src/mac_fonts.rs, shared): fonts that apps and font
|
||||
# managers register from their own folders (#579). Zlib OR Apache-2.0 OR MIT.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
|
||||
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2]
|
||||
//! vectorcraft-cli commands
|
||||
//! vectorcraft-cli convert IN OUT [--scale 2] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
//! vectorcraft-cli convert IN OUT [--scale 2] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
//! vectorcraft-cli info FILE
|
||||
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
|
||||
//! vectorcraft-cli perf [--paths 50000] [--deep]
|
||||
@@ -90,7 +90,7 @@ USAGE:
|
||||
vectorcraft-cli commands
|
||||
Print the command catalogue as JSON.
|
||||
|
||||
vectorcraft-cli convert IN OUT [--scale N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
vectorcraft-cli convert IN OUT [--scale N] [--artboard I | --range R] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
Open IN (any readable format) and export OUT in the format its extension picks (see Writable
|
||||
formats). --scale sizes a raster OUT (pixels per point, default 1); other formats leave it
|
||||
out. --artboard is 0-based, --range 1-based (\"1-3,5\"); a PDF gets every artboard
|
||||
@@ -103,8 +103,11 @@ USAGE:
|
||||
IN left things out (hidden text, art or layers it could not read; the notes say which) unless
|
||||
--replace-lossy is given. --editing-data opens a .ai or an EPS with editing data from its editing copy
|
||||
even where that draws differently from its PDF part or page (which can be older), as long as
|
||||
it can be read. The
|
||||
result has the export's warnings, and importWarnings for what reading IN left out.
|
||||
it can be read. A PDF OUT omits the embedded native document unless --preserve-editing is
|
||||
given (the app's Save As PDF still defaults to keeping it). With --preserve-editing, when the
|
||||
attachment is written the result's warnings say so (it is left out, with its own warning, for
|
||||
--artboard or a --range without every artboard).
|
||||
The result has the export's warnings, and importWarnings for what reading IN left out.
|
||||
--ai-version 7 writes a .ai as the legacy version 7 (layers, groups and type kept; one file
|
||||
per artboard, OUT-<artboard>.ai when there are several; default pdf, PDF-compatible), with
|
||||
--hidden-objects (default layer: a hidden layer above each layer's hidden objects; omit;
|
||||
@@ -274,8 +277,8 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
return help();
|
||||
}
|
||||
let mut files = vec![];
|
||||
let (mut scale, mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data) =
|
||||
(1.0f64, None::<u64>, None::<String>, false, false, false);
|
||||
let (mut scale, mut artboard, mut range, mut outline_text, mut replace_lossy, mut editing_data, mut preserve_editing) =
|
||||
(1.0f64, None::<u64>, None::<String>, false, false, false, false);
|
||||
let mut decimals = None::<u64>;
|
||||
// Legacy `.ai` options, passed on as the export's own (`aiVersion`, `hiddenObjects`,
|
||||
// `transparentImages`); the engine checks their values.
|
||||
@@ -290,6 +293,7 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
"--decimals" => decimals = Some(it.next().and_then(|v| v.parse::<u64>().ok()).ok_or("--decimals needs a number")?),
|
||||
"--replace-lossy" => replace_lossy = true,
|
||||
"--editing-data" => editing_data = true,
|
||||
"--preserve-editing" => preserve_editing = true,
|
||||
"--ai-version" => legacy.push(("aiVersion", it.next().cloned().ok_or("--ai-version needs 7 or pdf")?)),
|
||||
"--hidden-objects" => legacy.push(("hiddenObjects", it.next().cloned().ok_or("--hidden-objects needs layer, omit or visible")?)),
|
||||
"--transparent-images" => legacy.push(("transparentImages", it.next().cloned().ok_or("--transparent-images needs flatten or omit")?)),
|
||||
@@ -319,6 +323,9 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
if let Some(decimals) = decimals {
|
||||
params["decimals"] = json!(decimals);
|
||||
}
|
||||
if vectorcraft_engine::cmd::fileio::format_for_name(&output).is_some_and(|f| f.id == "pdf") {
|
||||
params["preserveEditing"] = json!(preserve_editing);
|
||||
}
|
||||
("document.export", params)
|
||||
};
|
||||
for (key, value) in legacy {
|
||||
@@ -330,6 +337,25 @@ fn convert(args: &[String]) -> Result<(), String> {
|
||||
if let (Some(w), Some(out)) = (opened.get("warnings").filter(|w| w.as_array().is_some_and(|a| !a.is_empty())), r.as_object_mut()) {
|
||||
out.insert("importWarnings".into(), w.clone());
|
||||
}
|
||||
if preserve_editing
|
||||
&& vectorcraft_engine::cmd::fileio::format_for_name(&output).is_some_and(|f| f.id == "pdf")
|
||||
&& let Some(obj) = r.as_object_mut()
|
||||
{
|
||||
// The export leaves the attachment out (with this warning) for --artboard or a --range
|
||||
// without every artboard; otherwise it writes it. Read that from the result, not the file.
|
||||
let skipped = vectorcraft_engine::cmd::fileio::pdf::EDITING_NEEDS_EVERY_ARTBOARD;
|
||||
let embedded = !obj.get("warnings").and_then(Value::as_array).is_some_and(|w| w.iter().any(|w| w.as_str() == Some(skipped)));
|
||||
if embedded {
|
||||
let note = "The PDF embeds the native VectorCraft document as an attachment (preserveEditing).";
|
||||
if let Some(Value::Array(w)) = obj.get_mut("warnings") {
|
||||
if !w.iter().any(|w| w.as_str() == Some(note)) {
|
||||
w.push(json!(note));
|
||||
}
|
||||
} else {
|
||||
obj.insert("warnings".into(), json!([note]));
|
||||
}
|
||||
}
|
||||
}
|
||||
outln!("{r}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -46,6 +46,29 @@ fn info(file: &str) -> Value {
|
||||
serde_json::from_str(&ok(&["info", file])).unwrap()
|
||||
}
|
||||
|
||||
/// #3627: `convert` to PDF omits the embedded native document unless asked.
|
||||
#[test]
|
||||
fn convert_pdf_omits_editing_data_unless_preserve_editing() {
|
||||
let pdf = tmp("flyer.pdf");
|
||||
make(&pdf, 120, 80);
|
||||
let plain = tmp("plain.pdf");
|
||||
ok(&["convert", &pdf, &plain]);
|
||||
let bytes = std::fs::read(&plain).unwrap();
|
||||
assert!(!bytes.windows(b"vectorcraft-editing.vectorcraft".len()).any(|w| w == b"vectorcraft-editing.vectorcraft"));
|
||||
let kept = tmp("kept.pdf");
|
||||
let r: Value = serde_json::from_str(&ok(&["convert", &pdf, &kept, "--preserve-editing"])).unwrap();
|
||||
let bytes = std::fs::read(&kept).unwrap();
|
||||
assert!(bytes.windows(b"vectorcraft-editing.vectorcraft".len()).any(|w| w == b"vectorcraft-editing.vectorcraft"), "{r}");
|
||||
assert!(r["warnings"].as_array().is_some_and(|w| w.iter().any(|w| w.as_str().is_some_and(|s| s.contains("preserveEditing")))), "{r}");
|
||||
// A --range without every artboard leaves the attachment out: no "embeds" note, even when the
|
||||
// output's own name contains the attachment's name.
|
||||
let part = tmp("vectorcraft-editing.vectorcraft.pdf");
|
||||
let r: Value = serde_json::from_str(&ok(&["convert", &pdf, &part, "--preserve-editing", "--range", "2"])).unwrap();
|
||||
let warnings = r["warnings"].as_array().cloned().unwrap_or_default();
|
||||
assert!(warnings.iter().any(|w| w.as_str().is_some_and(|s| s.contains("every artboard"))), "{r}");
|
||||
assert!(!warnings.iter().any(|w| w.as_str().is_some_and(|s| s.contains("preserveEditing"))), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_pdf_to_svg_and_info_on_ai() {
|
||||
let pdf = tmp("in.pdf");
|
||||
|
||||
@@ -29,4 +29,4 @@ wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlInputElement", "KeyboardEvent", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal"] }
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Shortcuts the browser would also act on. Many of the app's Cmd and Ctrl chords are the
|
||||
//! browser's too: the View menu's `Cmd+=`, `Cmd+-` and `Cmd+0` zoom the page, Edit's `Cmd+Z` and
|
||||
//! `Cmd+Shift+Z` undo and redo in the browser (in Safari, Undo Close Tab when the page has nothing
|
||||
//! to undo), `Cmd+[` and `Cmd+]` go back and forward, `Cmd+F` finds. eframe lets them through, so
|
||||
//! the browser acted on them as well. For a press the keymap in effect binds (the user's shortcuts
|
||||
//! included), the page's default action is cancelled; the key still reaches egui, which runs the
|
||||
//! command (or a text field its own undo). A few chords never reach a page at all (Safari's
|
||||
//! `Cmd+L`, Chrome's `Cmd+T`, `Cmd+W` and `Cmd+N`): the browser keeps those.
|
||||
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
/// Whether the browser's own action for a key press is cancelled. `key` is the event's `key` (the
|
||||
/// character typed), `code` its `code` (the key's position), `modifiers` as eframe reports them,
|
||||
/// and `alt_graph` whether AltGr is held.
|
||||
///
|
||||
/// Only Cmd and Ctrl presses: a plain or Shift press types (cancelling it would drop the
|
||||
/// character it types), and so does AltGr, which Windows reports as Ctrl and Alt held. Cut, Copy
|
||||
/// and Paste (with any other modifiers) are left to the browser, whose clipboard events carry
|
||||
/// their text, and Reload too, as eframe leaves them.
|
||||
pub(crate) fn kept_from_browser(key: &str, code: &str, modifiers: Modifiers, alt_graph: bool) -> bool {
|
||||
if !(modifiers.ctrl || modifiers.mac_cmd) || alt_graph {
|
||||
return false;
|
||||
}
|
||||
if matches!(Key::from_name(key).or(Key::from_name(code)), Some(Key::C | Key::V | Key::X | Key::R)) {
|
||||
return false;
|
||||
}
|
||||
vectorcraft_ui_egui::shortcuts::runs_a_shortcut(key, code, modifiers)
|
||||
}
|
||||
|
||||
/// The modifiers of a key event as eframe reports them to egui (its `modifiers_from_kb_event`).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn modifiers(e: &web_sys::KeyboardEvent) -> Modifiers {
|
||||
Modifiers { alt: e.alt_key(), ctrl: e.ctrl_key(), shift: e.shift_key(), mac_cmd: e.meta_key(), command: e.ctrl_key() || e.meta_key() }
|
||||
}
|
||||
|
||||
/// Whether the app has the keyboard for this event: it went to the canvas, or to the text input
|
||||
/// eframe places right after it while a text field has the focus. Elsewhere (the page's body, a
|
||||
/// file input) eframe ignores the key, so the browser keeps it.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn to_the_app(e: &web_sys::KeyboardEvent) -> bool {
|
||||
use wasm_bindgen::JsCast as _;
|
||||
let Some(target) = e.target() else { return false };
|
||||
if target.has_type::<web_sys::HtmlCanvasElement>() {
|
||||
return true;
|
||||
}
|
||||
target
|
||||
.dyn_ref::<web_sys::HtmlInputElement>()
|
||||
.and_then(|input| input.previous_element_sibling())
|
||||
.is_some_and(|before| before.has_type::<web_sys::HtmlCanvasElement>())
|
||||
}
|
||||
|
||||
/// Cancel the page's default action for [`kept_from_browser`] presses, before eframe's listener
|
||||
/// sees the event (it doesn't stop it).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn keep_app_keys() {
|
||||
use wasm_bindgen::JsCast as _;
|
||||
let Some(window) = web_sys::window() else { return };
|
||||
let on_key = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::KeyboardEvent)>::new(|e: web_sys::KeyboardEvent| {
|
||||
// An IME's keys are its own until it commits.
|
||||
if e.is_composing() || !to_the_app(&e) {
|
||||
return;
|
||||
}
|
||||
if kept_from_browser(&e.key(), &e.code(), modifiers(&e), e.get_modifier_state("AltGraph")) {
|
||||
e.prevent_default();
|
||||
}
|
||||
});
|
||||
if let Err(e) = window.add_event_listener_with_callback_and_bool("keydown", on_key.as_ref().unchecked_ref(), true) {
|
||||
log::error!("couldn't follow keydown events: {e:?}");
|
||||
}
|
||||
// The listener lives as long as the page.
|
||||
on_key.forget();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Cmd as egui reports it on this platform: the Command key on macOS, Ctrl elsewhere.
|
||||
fn cmd() -> Modifiers {
|
||||
if cfg!(target_os = "macos") { Modifiers::MAC_CMD | Modifiers::COMMAND } else { Modifiers::CTRL | Modifiers::COMMAND }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_keymaps_chords_are_kept_from_the_browser() {
|
||||
for (key, code, mods) in [
|
||||
("=", "Equal", cmd()),
|
||||
("-", "Minus", cmd()),
|
||||
("0", "Digit0", cmd()),
|
||||
("z", "KeyZ", cmd()),
|
||||
("Z", "KeyZ", cmd() | Modifiers::SHIFT),
|
||||
("[", "BracketLeft", cmd()),
|
||||
] {
|
||||
assert!(kept_from_browser(key, code, mods, false), "{key} ({code}) {mods:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_the_clipboard_and_reload_stay_with_the_browser() {
|
||||
for (key, code, mods) in [
|
||||
// Typing: plain and Shift presses.
|
||||
("z", "KeyZ", Modifiers::NONE),
|
||||
("Z", "KeyZ", Modifiers::SHIFT),
|
||||
("=", "Equal", Modifiers::NONE),
|
||||
// The clipboard's events carry the text; Paste and Match Style is Shift+Cmd+V.
|
||||
("c", "KeyC", cmd()),
|
||||
("x", "KeyX", cmd()),
|
||||
("v", "KeyV", cmd()),
|
||||
("V", "KeyV", cmd() | Modifiers::SHIFT),
|
||||
("r", "KeyR", cmd()),
|
||||
] {
|
||||
assert!(!kept_from_browser(key, code, mods, false), "{key} ({code}) {mods:?}");
|
||||
}
|
||||
// AltGr+Z types ż on a Polish layout, reported as Ctrl and Alt held on Windows.
|
||||
let ctrl_alt = Modifiers::CTRL | Modifiers::COMMAND | Modifiers::ALT;
|
||||
assert!(!kept_from_browser("ż", "KeyZ", ctrl_alt, true));
|
||||
assert!(!kept_from_browser("}", "Digit0", ctrl_alt, true));
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,10 @@
|
||||
//! - Save / Export trigger a browser download;
|
||||
//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox;
|
||||
//! - pen and finger input is read from Pointer Events by `pencil` (Apple Pencil pressure and
|
||||
//! hover, palm rejection, fingers navigate once a pen has been seen).
|
||||
//! hover, palm rejection, fingers navigate once a pen has been seen, the pen's eraser end
|
||||
//! selects the Eraser tool);
|
||||
//! - a Cmd or Ctrl chord the keymap binds runs its command, not the browser's own action as well
|
||||
//! (`Cmd+=` zooms the canvas, not the page; `Cmd+Z` undoes in the document) (`keys`).
|
||||
//!
|
||||
//! URL query flags: `?webgl` forces the WebGL2 backend instead of WebGPU; `?lang=es` (any
|
||||
//! language code) stands in for the browser's languages when the interface language is Automatic.
|
||||
@@ -20,6 +23,8 @@
|
||||
mod api;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod fonts;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod keys;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod locks;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
//! - A pen drives egui's pointer and is a touch contact with the pen's pressure as its force (the
|
||||
//! canvas reads it), so holding it still opens the context menu (egui's long touch). It hovers
|
||||
//! where the pen can (Apple Pencil hover).
|
||||
//! - A press of the pen's eraser end (the eraser button, `button` 5 in Pointer Events) presses
|
||||
//! like the tip, and the pen's samples go into a [`StylusFeed`] with that end, so the canvas
|
||||
//! selects the Eraser tool for the press. A press of the tip turns the pen back.
|
||||
//! - Fingers are touch contacts: two pinch and pan the canvas, and tap to undo or redo. The first
|
||||
//! finger also drives the pointer, so it taps the panels and menus; on the canvas it navigates
|
||||
//! only once a pen has been seen ([`touch::set_source`]), for this page session only.
|
||||
@@ -20,6 +23,7 @@ use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use egui::{Event, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase};
|
||||
use vectorcraft_ui_egui::stylus::{PenSample, StylusFeed};
|
||||
use vectorcraft_ui_egui::touch::{self, Source};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use wasm_bindgen::JsCast as _;
|
||||
@@ -28,8 +32,11 @@ use wasm_bindgen::JsCast as _;
|
||||
const PEN_DEVICE: TouchDeviceId = TouchDeviceId(1);
|
||||
const FINGER_DEVICE: TouchDeviceId = TouchDeviceId(2);
|
||||
|
||||
/// The Pointer Events `button` of a pen's eraser button, which is how a pen's eraser end presses
|
||||
/// (<https://www.w3.org/TR/pointerevents3/#the-button-property>).
|
||||
const ERASER_BUTTON: i16 = 5;
|
||||
|
||||
/// The pen and finger contacts followed, and the egui events they made since the last frame.
|
||||
#[derive(Default)]
|
||||
pub struct Pointers {
|
||||
events: Vec<Event>,
|
||||
/// The pen pressing, by pointer id.
|
||||
@@ -39,6 +46,16 @@ pub struct Pointers {
|
||||
/// The contact driving egui's pointer.
|
||||
primary: Option<i32>,
|
||||
button: Option<PointerButton>,
|
||||
/// The pen last pressed with its eraser end.
|
||||
eraser: bool,
|
||||
/// The pen's pressure and end for the canvas (`Services::stylus`).
|
||||
stylus: StylusFeed,
|
||||
}
|
||||
|
||||
impl Default for Pointers {
|
||||
fn default() -> Self {
|
||||
Self { events: vec![], pen: None, fingers: vec![], primary: None, button: None, eraser: false, stylus: StylusFeed::on_ui_thread() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -71,6 +88,16 @@ impl Pointers {
|
||||
std::mem::take(&mut self.events)
|
||||
}
|
||||
|
||||
/// The feed the pen's samples go into, for `Services::stylus`.
|
||||
pub fn stylus(&self) -> StylusFeed {
|
||||
self.stylus.clone()
|
||||
}
|
||||
|
||||
/// A pen moved or pressed with `pressure`, with the end it last pressed with.
|
||||
fn pen_sample(&self, pressure: f32) {
|
||||
self.stylus.set_sample(Some(PenSample { pressure, eraser: self.eraser }));
|
||||
}
|
||||
|
||||
fn touch(&mut self, device: TouchDeviceId, id: i32, phase: TouchPhase, pos: Pos2, force: Option<f32>) {
|
||||
self.events.push(Event::Touch { device_id: device, id: TouchId::from(id as u64), phase, pos, force });
|
||||
}
|
||||
@@ -110,6 +137,11 @@ impl Pointers {
|
||||
/// Follow one pointer event; `true` if it was the pen's or a finger's (taken from eframe).
|
||||
fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32)], on_canvas: bool) -> bool {
|
||||
let id = e.id;
|
||||
if e.pointer_type != "pen" && self.pen.is_none() && matches!(kind, "pointerdown" | "pointermove") {
|
||||
// Another pointer moved while no pen presses (a palm under a pen pressing is
|
||||
// rejected): the canvas takes no pen pressure or pen end for it.
|
||||
self.stylus.set(None);
|
||||
}
|
||||
match e.pointer_type {
|
||||
"pen" => {
|
||||
let force = Some(e.pressure.clamp(0.0, 1.0));
|
||||
@@ -118,14 +150,27 @@ impl Pointers {
|
||||
if !on_canvas && self.pen.is_none() {
|
||||
return false;
|
||||
}
|
||||
let Some(button) = button(e.button) else { return false };
|
||||
// The eraser end presses like the tip; the tip and the eraser end each
|
||||
// set the end the pen is turned to.
|
||||
let (button, end) = match e.button {
|
||||
ERASER_BUTTON => (PointerButton::Primary, Some(true)),
|
||||
number => match button(number) {
|
||||
Some(button) => (button, (number == 0).then_some(false)),
|
||||
None => return false,
|
||||
},
|
||||
};
|
||||
touch::set_source(Source::Pen);
|
||||
self.cancel_fingers(pos, e.modifiers);
|
||||
if let Some(end) = end {
|
||||
self.eraser = end;
|
||||
}
|
||||
self.pen_sample(e.pressure);
|
||||
self.pen = Some(id);
|
||||
self.touch(PEN_DEVICE, id, TouchPhase::Start, pos, force);
|
||||
self.press(id, pos, button, e.modifiers);
|
||||
}
|
||||
"pointermove" if self.pen == Some(id) => {
|
||||
self.pen_sample(e.pressure);
|
||||
// The positions the pen reported between two events (up to 240 a second
|
||||
// on an iPad), each with its pressure, so fast strokes keep their curve.
|
||||
for c in coalesced.iter().take(coalesced.len().saturating_sub(1)) {
|
||||
@@ -143,10 +188,14 @@ impl Pointers {
|
||||
if !on_canvas {
|
||||
return false;
|
||||
}
|
||||
// Pointer Events report no end while a pen hovers: it keeps the end it
|
||||
// last pressed with.
|
||||
self.pen_sample(e.pressure);
|
||||
self.events.push(Event::PointerMoved(pos));
|
||||
}
|
||||
"pointerup" | "pointercancel" if self.pen == Some(id) => {
|
||||
let phase = if kind == "pointerup" { TouchPhase::End } else { TouchPhase::Cancel };
|
||||
self.pen_sample(0.0);
|
||||
self.pen = None;
|
||||
self.touch(PEN_DEVICE, id, phase, pos, None);
|
||||
self.release(pos, e.modifiers);
|
||||
@@ -388,8 +437,85 @@ mod tests {
|
||||
fn unknown_pen_buttons_are_not_reinterpreted_as_primary() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
assert!(!p.feed("pointerdown", &input("pen", 5), Pos2::ZERO, &[], true));
|
||||
assert!(!p.feed("pointerdown", &input("pen", 6), Pos2::ZERO, &[], true));
|
||||
assert!(p.take().is_empty());
|
||||
assert!(!touch::pen_seen());
|
||||
assert_eq!(p.stylus().eraser(), None);
|
||||
}
|
||||
|
||||
fn presses(p: &mut Pointers) -> Vec<(PointerButton, bool)> {
|
||||
p.take()
|
||||
.into_iter()
|
||||
.filter_map(|e| match e {
|
||||
Event::PointerButton { button, pressed, .. } => Some((button, pressed)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The eraser end presses as Pointer Events' eraser button (`button` 5): a primary press whose
|
||||
/// samples carry the eraser end, kept while the pen hovers, until the tip presses.
|
||||
#[test]
|
||||
fn the_eraser_button_presses_with_the_eraser_end() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
let feed = p.stylus();
|
||||
let pos = Pos2::new(30.0, 40.0);
|
||||
let eraser = input("pen", ERASER_BUTTON);
|
||||
assert!(p.feed("pointerdown", &eraser, pos, &[], true));
|
||||
assert_eq!(presses(&mut p), [(PointerButton::Primary, true)]);
|
||||
assert!(touch::pen_seen());
|
||||
assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(0.6)));
|
||||
assert!(p.feed("pointermove", &input("pen", -1), pos, &[], true));
|
||||
assert_eq!(feed.eraser(), Some(true));
|
||||
assert!(p.feed("pointerup", &eraser, pos, &[], true));
|
||||
assert_eq!(presses(&mut p), [(PointerButton::Primary, false)]);
|
||||
let mut hover = input("pen", -1);
|
||||
hover.pressure = 0.0;
|
||||
assert!(p.feed("pointermove", &hover, pos, &[], true));
|
||||
assert_eq!(feed.eraser(), Some(true), "a hovering pen keeps the end it pressed with");
|
||||
// The barrel button leaves the end as it was.
|
||||
assert!(p.feed("pointerdown", &input("pen", 2), pos, &[], true));
|
||||
assert!(p.feed("pointerup", &input("pen", 2), pos, &[], true));
|
||||
assert_eq!(feed.eraser(), Some(true));
|
||||
assert!(p.feed("pointerdown", &input("pen", 0), pos, &[], true));
|
||||
assert_eq!(feed.eraser(), Some(false), "the tip");
|
||||
reset();
|
||||
}
|
||||
|
||||
/// A mouse or a finger that moves takes the pen out of the feed, so the canvas gives it no
|
||||
/// pen pressure and does not switch tools for it.
|
||||
#[test]
|
||||
fn other_pointers_clear_the_pen_feed() {
|
||||
for (pointer_type, kind) in [("mouse", "pointermove"), ("mouse", "pointerdown"), ("touch", "pointerdown"), ("touch", "pointermove")] {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
let feed = p.stylus();
|
||||
assert!(p.feed("pointerdown", &input("pen", ERASER_BUTTON), Pos2::ZERO, &[], true));
|
||||
assert!(p.feed("pointerup", &input("pen", ERASER_BUTTON), Pos2::ZERO, &[], true));
|
||||
let mut other = input(pointer_type, 0);
|
||||
other.id = 10;
|
||||
p.feed(kind, &other, Pos2::ZERO, &[], true);
|
||||
assert_eq!((feed.eraser(), feed.held()), (None, None), "{pointer_type} {kind}");
|
||||
}
|
||||
reset();
|
||||
}
|
||||
|
||||
/// A palm that lands or moves while the eraser end presses is rejected, and the feed keeps the
|
||||
/// eraser end for the canvas's next frame.
|
||||
#[test]
|
||||
fn a_rejected_palm_keeps_the_pen_end() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
let feed = p.stylus();
|
||||
assert!(p.feed("pointerdown", &input("pen", ERASER_BUTTON), Pos2::ZERO, &[], true));
|
||||
let mut palm = input("touch", 0);
|
||||
palm.id = 10;
|
||||
for (pointer_type, kind) in [("touch", "pointerdown"), ("touch", "pointermove"), ("mouse", "pointermove")] {
|
||||
palm.pointer_type = pointer_type;
|
||||
p.feed(kind, &palm, Pos2::ZERO, &[], true);
|
||||
assert_eq!(feed.eraser(), Some(true), "{pointer_type} {kind}");
|
||||
}
|
||||
reset();
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ use vectorcraft_ui_egui::graphics::GraphicsLoss;
|
||||
use vectorcraft_ui_egui::i18n;
|
||||
use vectorcraft_ui_egui::place::{DropTarget, PlaceArrival, PlaceInbox};
|
||||
use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
|
||||
use vectorcraft_ui_egui::stylus::StylusFeed;
|
||||
use vectorcraft_ui_egui::{Services, VectorcraftApp};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
@@ -81,6 +82,7 @@ pub fn start() {
|
||||
restarts: 0,
|
||||
};
|
||||
track_paste(&host.pasted);
|
||||
crate::keys::keep_app_keys();
|
||||
run(host, canvas, None).await;
|
||||
});
|
||||
}
|
||||
@@ -106,6 +108,7 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
|
||||
canvas,
|
||||
web_options(),
|
||||
Box::new(move |cc| {
|
||||
VectorcraftApp::install_ime_reset_hooks(&cc.egui_ctx);
|
||||
let ctx = &cc.egui_ctx;
|
||||
crate::fonts::spawn_background_fonts(ctx.clone());
|
||||
let loss = GraphicsLoss::default();
|
||||
@@ -116,7 +119,8 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
|
||||
rs.device.set_device_lost_callback(move |reason, msg| loss.report(&ctx, format!("{reason:?}: {msg}")));
|
||||
}
|
||||
host.pasted.borrow_mut().ctx = Some(ctx.clone());
|
||||
let services = services(host.inbox.clone(), host.place_inbox.clone(), ctx.clone(), host.locks.clone());
|
||||
let stylus = host.pointers.borrow().stylus();
|
||||
let services = services(host.inbox.clone(), host.place_inbox.clone(), ctx.clone(), host.locks.clone(), stylus);
|
||||
let app = match taken.borrow_mut().take() {
|
||||
Some(mut app) => {
|
||||
// The old services asked the old context for frames.
|
||||
@@ -365,55 +369,63 @@ impl eframe::App for WebShell {
|
||||
self.restart(&why);
|
||||
}
|
||||
let Some(app) = &mut self.app else { return };
|
||||
let pasted = self.host.pasted.borrow_mut().flavour.take();
|
||||
if let Some((f, held)) = pasted {
|
||||
app.paste_from_host(ctx, f, held);
|
||||
}
|
||||
let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));
|
||||
if !dropped.is_empty() {
|
||||
let at = self.host.drag.take();
|
||||
let z = ctx.zoom_factor();
|
||||
let (pos, shift) = (at.map(|(x, y, _)| egui::pos2(x / z, y / z)), at.is_some_and(|a| a.2));
|
||||
for f in dropped {
|
||||
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
|
||||
let target = app.drop_target(&name, pos, shift);
|
||||
let (inbox, place_inbox, ctx) = (self.host.inbox.clone(), self.host.place_inbox.clone(), ctx.clone());
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match f.bytes_async().await {
|
||||
Ok(bytes) => {
|
||||
match target {
|
||||
DropTarget::Place(d) => {
|
||||
place_inbox.lock().unwrap_or_else(|e| e.into_inner()).push(PlaceArrival { name, bytes, drop: Some(d) })
|
||||
}
|
||||
DropTarget::Open => inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes)),
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
app.logic(ctx);
|
||||
app.tick(ctx);
|
||||
crate::api::poll_replies();
|
||||
app.finish_ime_logic(ctx);
|
||||
}
|
||||
|
||||
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
/// Forward host-gathered pointer events into this frame's raw input, then let the app apply its
|
||||
/// shared input hook before egui runs.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
raw.events.extend(self.host.pointers.borrow_mut().take());
|
||||
if let Some(app) = &mut self.app {
|
||||
app.raw_input_hook(raw);
|
||||
app.raw_input_hook(ctx, raw);
|
||||
}
|
||||
}
|
||||
|
||||
/// Read host paste and drop input once in the UI phase, hand files to the app's drop targets, run
|
||||
/// the app UI, then poll control replies.
|
||||
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
let ctx = ui.ctx().clone();
|
||||
if let Some(app) = &mut self.app {
|
||||
// DOM paste and drop are host input: read them in the UI phase, once per pass, not in
|
||||
// `logic` where a hidden tab replays the last shown frame's input.
|
||||
let pasted = self.host.pasted.borrow_mut().flavour.take();
|
||||
if let Some((f, held)) = pasted {
|
||||
app.paste_from_host(&ctx, f, held);
|
||||
}
|
||||
let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));
|
||||
if !dropped.is_empty() {
|
||||
let at = self.host.drag.take();
|
||||
let z = ctx.zoom_factor();
|
||||
let (pos, shift) = (at.map(|(x, y, _)| egui::pos2(x / z, y / z)), at.is_some_and(|a| a.2));
|
||||
for f in dropped {
|
||||
let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into());
|
||||
let target = app.drop_target(&name, pos, shift);
|
||||
let (inbox, place_inbox, repaint) = (self.host.inbox.clone(), self.host.place_inbox.clone(), ctx.clone());
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
match f.bytes_async().await {
|
||||
Ok(bytes) => {
|
||||
match target {
|
||||
DropTarget::Place(d) => {
|
||||
place_inbox.lock().unwrap_or_else(|e| e.into_inner()).push(PlaceArrival { name, bytes, drop: Some(d) })
|
||||
}
|
||||
DropTarget::Open => inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes)),
|
||||
}
|
||||
repaint.request_repaint();
|
||||
}
|
||||
Err(e) => log::error!("couldn't read dropped file {name}: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
app.ui(ui);
|
||||
}
|
||||
crate::api::poll_replies();
|
||||
}
|
||||
}
|
||||
|
||||
fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context, locks: Option<WebLocks>) -> Services {
|
||||
fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context, locks: Option<WebLocks>, stylus: StylusFeed) -> Services {
|
||||
let open_inbox = inbox.clone();
|
||||
let picked = place_inbox.clone();
|
||||
let place_ctx = ctx.clone();
|
||||
@@ -463,6 +475,8 @@ fn services(inbox: Inbox, place_inbox: PlaceInbox, ctx: egui::Context, locks: Op
|
||||
recovery_store: Some(Arc::new(BrowserStore { locks })),
|
||||
// File → Print: the browser's print dialog.
|
||||
print: Some(Box::new(BrowserPrint)),
|
||||
// The pen's end, from the page's Pointer Events (`crate::pencil`).
|
||||
stylus: Some(stylus),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ vectorcraft-text = { workspace = true }
|
||||
# Shared across the Craft suite: decides who draws the window frame per desktop (compositor vs app)
|
||||
# so VectorCraft matches the rest on Linux. `egui` adds `craft_window::decorate`. See #217.
|
||||
craft-window = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wayland", "x11"] }
|
||||
eframe = { workspace = true, features = ["clipboard", "default_fonts", "wayland", "x11"] }
|
||||
egui = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
@@ -43,23 +43,26 @@ winit = { version = "0.30", default-features = false }
|
||||
craft-print = { workspace = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
clipboard-win = { workspace = true }
|
||||
# Which GPU drives which display (EnumDisplayDevices, src/gpu.rs), so the window is drawn on the
|
||||
# GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over
|
||||
# Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter.
|
||||
winsafe = { version = "0.0.29", default-features = false, features = ["user"], optional = true }
|
||||
|
||||
# DirectWrite's system font collection (src/system_fonts.rs): fonts that font services such as
|
||||
# Adobe Fonts load in place (#579). MIT OR Apache-2.0, already in the build through accesskit.
|
||||
# DirectWrite's system font collection and GDI's font list (src/system_fonts.rs): fonts that font
|
||||
# services such as Adobe Fonts load in place (#579, #1258). MIT OR Apache-2.0, already in the build
|
||||
# through accesskit.
|
||||
# Win32_UI_WindowsAndMessaging has `MSG` and `WM_POINTERDOWN`, which src/windows_stylus.rs uses to
|
||||
# read a pen's barrel button from its pointer messages.
|
||||
# read a pen's barrel button from its pointer messages. Win32_UI_Input_Pointer has
|
||||
# `GetPointerPenInfo`, which it uses to read the pen's pressure and which end of the pen is down.
|
||||
[target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies]
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_UI_WindowsAndMessaging"] }
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# The macOS menu bar (src/mac_menu.rs): Tauri's menu crate, AppKit menus behind a safe API (no GTK
|
||||
# with default features off). Pinned exactly: review the diff before bumping.
|
||||
muda = { version = "=0.21.1", default-features = false }
|
||||
muda = { version = "=0.21.2", default-features = false }
|
||||
objc2 = "0.6"
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "NSApplication", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
|
||||
# Files opened from Finder and the Dock (src/open_documents.rs), pasted bitmaps (src/clipboard.rs) and the control channel's App Nap activity (src/control_server.rs); both already come with winit, muda and rfd.
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
use super::prefs::save_prefs;
|
||||
use super::*;
|
||||
|
||||
/// The parts of [`App::raw_input_hook`] that every window needs, for the OS windows of floating
|
||||
/// panels: a click or Escape that closes the macOS menu bar's open menu, and the pen barrel
|
||||
/// button's secondary click on Windows. The control channel's input and the native menu's keys
|
||||
/// go to the main window only.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) fn native_input_hook(app: &VectorcraftApp) -> Option<vectorcraft_ui_egui::NativeInputHook> {
|
||||
app.services.native_menu.is_some().then(|| std::sync::Arc::new(mac_menu::raw_input_hook) as vectorcraft_ui_egui::NativeInputHook)
|
||||
}
|
||||
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
pub(crate) fn native_input_hook(_: &VectorcraftApp) -> Option<vectorcraft_ui_egui::NativeInputHook> {
|
||||
Some(std::sync::Arc::new(windows_stylus::raw_input_hook))
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", all(windows, not(target_vendor = "win7")))))]
|
||||
pub(crate) fn native_input_hook(_: &VectorcraftApp) -> Option<vectorcraft_ui_egui::NativeInputHook> {
|
||||
None
|
||||
}
|
||||
|
||||
impl eframe::App for App {
|
||||
// Each frame runs unconfined: it is the person at the keyboard's. The app confines what the
|
||||
// control channel asks for, and the frames carrying input it injected, to the automation roots
|
||||
// (`VectorcraftApp::with_automation_roots`), which are in force elsewhere in the process.
|
||||
fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
|
||||
file_access::unconfined(|| self.logic_frame(ctx, frame));
|
||||
self.app.finish_ime_logic(ctx);
|
||||
}
|
||||
/// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the
|
||||
/// app's raw-input hook while the keyboard user is unconfined.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
// winit gives the window its caption back when it changes the window's flags (maximize,
|
||||
// restore, …): take it off again before the frame is laid out (#1758).
|
||||
if let Some(window_frame) = self.window_frame.as_mut() {
|
||||
window_frame();
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
if self.app.services.native_menu.is_some() {
|
||||
mac_menu::raw_input_hook(raw);
|
||||
}
|
||||
// A pen contact with the barrel button held presses the secondary button (Windows Ink).
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
windows_stylus::raw_input_hook(raw);
|
||||
file_access::unconfined(|| self.app.raw_input_hook(ctx, raw));
|
||||
}
|
||||
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let bar = vectorcraft_ui_egui::chrome::APP_BAR_HEIGHT;
|
||||
let inset = mac_window::center_buttons(frame, ui.ctx().zoom_factor(), bar);
|
||||
self.app.titlebar_inset = inset.unwrap_or(mac_window::DEFAULT_INSET);
|
||||
}
|
||||
file_access::unconfined(|| self.app.ui(ui));
|
||||
// Preferences are written when confirmed, not only at exit: a session ended any other way
|
||||
// (the system shutting down, the process ended or crashing) used to lose them (#1747).
|
||||
if self.app.take_prefs_changed() {
|
||||
file_access::unconfined(|| save_prefs(&self.app));
|
||||
}
|
||||
// Not while a file dialog's sheet has the keyboard: its name field's composition would go.
|
||||
#[cfg(target_os = "macos")]
|
||||
if !self.app.file_dialog_open() && self.app.take_ime_discard() {
|
||||
discard_marked_text();
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "windows7"))]
|
||||
fn on_exit(&mut self) {
|
||||
file_access::unconfined(|| save_prefs(&self.app));
|
||||
end_before_teardown(self.frames);
|
||||
}
|
||||
#[cfg(feature = "windows7")]
|
||||
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
|
||||
file_access::unconfined(|| save_prefs(&self.app));
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn logic_frame(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
self.frames = ctx.cumulative_frame_nr();
|
||||
if let Some(why) = self.graphics_loss.take() {
|
||||
// eframe can't give a window a new device: the user saves and starts again.
|
||||
self.graphics_lost = self.app.graphics_lost(&why);
|
||||
self.app.status(if self.graphics_lost {
|
||||
"The graphics device was lost: unsaved changes are kept for Data Recovery. Save your documents and restart VectorCraft"
|
||||
} else {
|
||||
"The graphics device was lost: save your documents and restart VectorCraft"
|
||||
});
|
||||
}
|
||||
if self.graphics_lost && ctx.input(|i| i.viewport().close_requested()) {
|
||||
// The window can't show the Save Changes question: it closes, and the next launch
|
||||
// offers the changes back.
|
||||
vectorcraft_ui_egui::background::wait_all(&mut self.app);
|
||||
return;
|
||||
}
|
||||
// Files from the Finder and the Dock wait while a file dialog is open: what asked for it runs
|
||||
// again on its document when it answers.
|
||||
#[cfg(target_os = "macos")]
|
||||
if !self.app.file_dialog_open() {
|
||||
let files = open_documents::take();
|
||||
if !files.is_empty() {
|
||||
bring_window_forward(ctx);
|
||||
}
|
||||
open_files(&mut self.app, files);
|
||||
}
|
||||
self.app.tick(ctx);
|
||||
if self.pending_maximize {
|
||||
if let Some(w) = &self.winit_window {
|
||||
self.pending_maximize = window::apply_pending_maximize(w, true, &mut self.maximize_tries);
|
||||
} else {
|
||||
self.pending_maximize = false;
|
||||
}
|
||||
}
|
||||
let host_maximized = self.winit_window.as_ref().map(|w| w.is_maximized());
|
||||
window::track(ctx, &mut self.app.ui.window, host_maximized);
|
||||
if self.app.ui.status == "quit" {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On macOS with accessibility, end the process once the app has saved what it keeps on quitting,
|
||||
/// before eframe tears the window down (#661). AccessKit then gives the window's content view back
|
||||
/// its own class, which AppKit's Touch Bar support was observing it under, and AppKit aborts the
|
||||
/// app as it quits on Macs with a Touch Bar. Nothing after the window is needed on a normal quit.
|
||||
/// Not while the window is still starting up (`frames` below [`gpu::STARTUP_FRAMES`]): a graphics
|
||||
/// failure then starts the app again on another adapter (#651).
|
||||
#[allow(unused_variables)]
|
||||
fn end_before_teardown(frames: u64) {
|
||||
#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))]
|
||||
if frames >= gpu::STARTUP_FRAMES {
|
||||
log::info!("quitting");
|
||||
log::logger().flush();
|
||||
std::process::exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Show the window when files are opened from the Finder or the Dock: a minimized window comes back
|
||||
/// out of the Dock and the app takes focus, as a document-based Mac app does (#3769).
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
pub(crate) fn bring_window_forward(ctx: &egui::Context) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
|
||||
}
|
||||
|
||||
/// Open files handed to the app (command line, macOS Finder and Dock) as documents. A file that
|
||||
/// can't be opened is reported to the user and on stderr; the others still open.
|
||||
pub(crate) fn open_files(app: &mut VectorcraftApp, files: Vec<String>) {
|
||||
for f in files {
|
||||
if let Err(e) = vectorcraft_ui_egui::io::open_reporting(app, &f) {
|
||||
eprintln!("vectorcraft: {f}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tell the macOS input method to drop its composition (the Type tool kept the marked text as
|
||||
/// typed). winit's IME toggle only clears its own copy, so the IME would type it again.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn discard_marked_text() {
|
||||
if let Some(mtm) = objc2::MainThreadMarker::new()
|
||||
&& let Some(ic) = objc2_app_kit::NSTextInputContext::currentInputContext(mtm)
|
||||
{
|
||||
ic.discardMarkedText();
|
||||
}
|
||||
}
|
||||
@@ -289,391 +289,4 @@ fn serve_lines_with<R: Read, W: Write>(
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn short_timeouts() -> ConnectionTimeouts {
|
||||
ConnectionTimeouts { idle: Duration::from_millis(150), line: Duration::from_millis(120), write: Duration::from_millis(150) }
|
||||
}
|
||||
|
||||
fn socket_fixture(
|
||||
timeouts: ConnectionTimeouts,
|
||||
handle: impl FnMut(String, Value) -> Option<Value> + Send + 'static,
|
||||
) -> (TcpStream, Receiver<()>, std::thread::JoinHandle<()>) {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (finished, done) = channel();
|
||||
let worker = std::thread::spawn(move || {
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
socket2::SockRef::from(&stream).set_send_buffer_size(4096).unwrap();
|
||||
serve_socket(stream, timeouts, handle);
|
||||
finished.send(()).unwrap();
|
||||
});
|
||||
let client = TcpStream::connect(addr).unwrap();
|
||||
socket2::SockRef::from(&client).set_recv_buffer_size(4096).unwrap();
|
||||
client.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
(client, done, worker)
|
||||
}
|
||||
|
||||
fn expect_socket_deadline(client: TcpStream, done: Receiver<()>, worker: std::thread::JoinHandle<()>) {
|
||||
let stopped = done.recv_timeout(Duration::from_secs(3)).is_ok();
|
||||
// Always unblock the old implementation too, so a failed regression leaves no worker behind.
|
||||
let _ = client.shutdown(std::net::Shutdown::Both);
|
||||
drop(client);
|
||||
worker.join().unwrap();
|
||||
assert!(stopped, "the server retained a stalled connection beyond its transport deadline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_control_socket_releases_its_worker() {
|
||||
let (client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected"));
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
|
||||
/// An idle connection is closed without a line: a client that sends its next request late
|
||||
/// must not find an error waiting where its reply should be.
|
||||
#[test]
|
||||
fn idle_expiry_closes_without_writing_a_line() {
|
||||
let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected"));
|
||||
let mut got = Vec::new();
|
||||
client.read_to_end(&mut got).unwrap();
|
||||
assert_eq!(String::from_utf8_lossy(&got), "", "the app wrote to an idle connection");
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
|
||||
/// A line that stalls is refused in words a client's author can act on, not the system's.
|
||||
#[test]
|
||||
fn stalled_control_line_is_refused_with_the_reason() {
|
||||
let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("incomplete requests must not execute"));
|
||||
client.write_all(b"{\"method\":").unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(client.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(&line).unwrap(),
|
||||
json!({"ok": false, "error": "request line not completed in time; closing the connection"})
|
||||
);
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_control_line_releases_its_worker() {
|
||||
let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("incomplete requests must not execute"));
|
||||
client.write_all(b"{\"method\":").unwrap();
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trickled_control_line_has_an_absolute_deadline() {
|
||||
let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("incomplete requests must not execute"));
|
||||
client.write_all(b"{").unwrap();
|
||||
let mut writer = client.try_clone().unwrap();
|
||||
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let writing = Arc::clone(&stop);
|
||||
let trickle = std::thread::spawn(move || {
|
||||
while !writing.load(Ordering::SeqCst) {
|
||||
if writer.write_all(b" ").is_err() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
});
|
||||
let stopped = done.recv_timeout(Duration::from_secs(3)).is_ok();
|
||||
stop.store(true, Ordering::SeqCst);
|
||||
// Both socket copies belong to this fixture; shutdown cleans up the baseline failure as well.
|
||||
let _ = client.shutdown(std::net::Shutdown::Both);
|
||||
trickle.join().unwrap();
|
||||
worker.join().unwrap();
|
||||
assert!(stopped, "trickled bytes restarted the line's deadline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nonreading_control_peer_cannot_retain_the_writer() {
|
||||
let payload = "x".repeat(2 * 1024 * 1024);
|
||||
let (mut client, done, worker) = socket_fixture(short_timeouts(), move |_, _| Some(json!({"ok": true, "result": payload})));
|
||||
client.write_all(b"{\"method\":\"large\"}\n").unwrap();
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistent_control_requests_get_fresh_transport_deadlines() {
|
||||
let timeouts = ConnectionTimeouts { idle: Duration::from_secs(2), ..short_timeouts() };
|
||||
let (mut client, done, worker) = socket_fixture(timeouts, |_, _| {
|
||||
// Application processing is not transport time; begin the reply budget afterwards.
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
Some(json!({"ok": true}))
|
||||
});
|
||||
let mut reader = BufReader::new(client.try_clone().unwrap());
|
||||
for id in [1, 2] {
|
||||
// The client sends each line in one write. `writeln!` on the socket sends the JSON in many
|
||||
// small writes, and when the machine is busy, a pause of more than the 120 ms line deadline
|
||||
// between two of them closes the connection.
|
||||
client.write_all(format!("{}\n", json!({"id": id, "method": "inspect"})).as_bytes()).unwrap();
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Value>(&line).unwrap(), json!({"id": id, "ok": true}));
|
||||
}
|
||||
client.shutdown(std::net::Shutdown::Write).unwrap();
|
||||
done.recv_timeout(Duration::from_secs(3)).unwrap();
|
||||
worker.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffered_partial_control_line_also_expires() {
|
||||
let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| Some(json!({"ok": true})));
|
||||
client.write_all(b"{\"id\":1,\"method\":\"inspect\"}\n{").unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(client.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["id"], 1);
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timed_out_worker_returns_its_connection_slot() {
|
||||
let open = Arc::new(AtomicUsize::new(0));
|
||||
let held: Vec<_> = (0..MAX_CONNECTIONS - 1).map(|_| acquire_slot(&open).unwrap()).collect();
|
||||
let slot = acquire_slot(&open).unwrap();
|
||||
assert!(acquire_slot(&open).is_none());
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let (tx, _rx) = channel();
|
||||
let worker = spawn_connection(stream, tx, egui::Context::default(), slot, short_timeouts()).unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
while open.load(Ordering::SeqCst) == MAX_CONNECTIONS && start.elapsed() < Duration::from_secs(3) {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
let released = open.load(Ordering::SeqCst) < MAX_CONNECTIONS;
|
||||
// Clean up an old implementation that never returned its slot as well.
|
||||
let _ = client.shutdown(std::net::Shutdown::Both);
|
||||
worker.join().unwrap();
|
||||
assert!(released, "the deadline did not free capacity for the next client");
|
||||
let replacement = acquire_slot(&open).expect("a new client can reserve the freed slot");
|
||||
drop(replacement);
|
||||
drop(held);
|
||||
assert_eq!(open.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
fn run(input: &[u8]) -> (Vec<Value>, Vec<String>) {
|
||||
let mut out = Vec::new();
|
||||
let mut calls = Vec::new();
|
||||
serve_lines(input, &mut out, |m, _p| {
|
||||
calls.push(m);
|
||||
Some(json!({"ok": true, "result": null}))
|
||||
});
|
||||
let replies = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str::<Value>(l).unwrap()).collect();
|
||||
(replies, calls)
|
||||
}
|
||||
|
||||
/// Counts the `write` calls made on it and keeps the bytes they write.
|
||||
#[derive(Default)]
|
||||
struct Writes {
|
||||
calls: usize,
|
||||
bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Write for Writes {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
self.calls += 1;
|
||||
self.bytes.extend_from_slice(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A reply shaped like `document.inspect`'s for a layer of `n` squares in rows of 200.
|
||||
fn inspect_reply(n: u64) -> Value {
|
||||
let paths: Vec<Value> = (0..n)
|
||||
.map(|k| {
|
||||
let (x, y) = ((k % 200) as f64 * 20.0, (k / 200) as f64 * 20.0);
|
||||
json!({"anchors": 4, "bounds": {"height": 10.0, "width": 10.0, "x": x, "y": y}, "closed": true, "fill": "#f4a261",
|
||||
"id": k + 2, "kind": "Path", "locked": false, "name": "<Path>", "stroke": "None", "strokeWidth": 0.0, "visible": true})
|
||||
})
|
||||
.collect();
|
||||
json!({"ok": true, "result": {"layers": [{"children": paths, "id": 1, "kind": "Layer", "name": "Layer 1"}]}})
|
||||
}
|
||||
|
||||
/// #1725: a request its caller gave up before the app took it never runs; one the app took
|
||||
/// first can't be withdrawn, and the timeout says so.
|
||||
#[test]
|
||||
fn a_timed_out_request_is_withdrawn_unless_it_started() {
|
||||
let (waiting, _rx) = ControlRequest::new("engine.execute", json!({}));
|
||||
assert!(timed_out(&waiting.ticket())["error"].as_str().unwrap().contains("will not run"));
|
||||
assert!(!waiting.claim(), "the app skips a withdrawn request");
|
||||
let (running, _rx) = ControlRequest::new("engine.execute", json!({}));
|
||||
assert!(running.claim());
|
||||
assert!(timed_out(&running.ticket())["error"].as_str().unwrap().contains("still running"));
|
||||
assert!(!running.claim(), "a request is taken once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_are_answered_in_order_with_ids() {
|
||||
let (r, calls) = run(b"{\"id\":1,\"method\":\"a\"}\n\n{\"id\":2,\"method\":\"b\",\"params\":{}}\r\n{\"method\":\"c\"}");
|
||||
assert_eq!(calls, ["a", "b", "c"]);
|
||||
assert_eq!(r.len(), 3);
|
||||
assert_eq!(r[0]["id"], 1);
|
||||
assert_eq!(r[1]["id"], 2);
|
||||
assert_eq!(r[2]["id"], Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replies_are_written_in_few_large_writes() {
|
||||
for reply in [json!({"ok": true, "result": null}), inspect_reply(2_000)] {
|
||||
let mut out = Writes::default();
|
||||
let mut once = Some(reply.clone());
|
||||
serve_lines(&b"{\"id\":1,\"method\":\"document.inspect\"}\n"[..], &mut out, |_, _| once.take());
|
||||
let mut want = reply;
|
||||
want["id"] = json!(1);
|
||||
let text = String::from_utf8(out.bytes).unwrap();
|
||||
// The writer receives the bytes that `writeln!(out, "{want}")` writes, in at most one write per 4 KiB.
|
||||
assert_eq!(text, format!("{want}\n"));
|
||||
assert!(out.calls <= text.len().div_ceil(4096), "{} writes for {} bytes", out.calls, text.len());
|
||||
}
|
||||
// A refusal is one write as well.
|
||||
let mut out = Writes::default();
|
||||
serve_lines(&b"hello\n"[..], &mut out, |_, _| None);
|
||||
assert_eq!(out.calls, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_request_closes_before_the_body_runs() {
|
||||
// A browser's cross-origin `fetch` POST: the request line is rejected and the
|
||||
// connection closed, so the JSON body is never executed.
|
||||
let http = b"POST / HTTP/1.1\r\nHost: 127.0.0.1:7979\r\nOrigin: https://attacker.example\r\nContent-Type: text/plain\r\n\r\n\
|
||||
{\"id\":7,\"method\":\"engine.execute\",\"params\":{\"command\":\"file.new\",\"params\":{}}}\n";
|
||||
let (r, calls) = run(http);
|
||||
assert!(calls.is_empty(), "nothing may run: {calls:?}");
|
||||
assert_eq!(r.len(), 1);
|
||||
assert_eq!(r[0]["ok"], false);
|
||||
assert!(r[0]["error"].as_str().unwrap().contains("closing the connection"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_request_json_closes_the_connection() {
|
||||
for junk in [
|
||||
&b"[1,2]\n{\"method\":\"a\"}\n"[..],
|
||||
b"{\"id\":1}\n{\"method\":\"a\"}\n",
|
||||
b"{\"method\":5}\n{\"method\":\"a\"}\n",
|
||||
b"\xff\xfe\n{\"method\":\"a\"}\n",
|
||||
] {
|
||||
let (r, calls) = run(junk);
|
||||
assert!(calls.is_empty(), "{calls:?}");
|
||||
assert_eq!(r.len(), 1);
|
||||
assert_eq!(r[0]["ok"], false);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_before_junk_still_runs() {
|
||||
let (r, calls) = run(b"{\"method\":\"a\"}\nGET / HTTP/1.1\n{\"method\":\"b\"}\n");
|
||||
assert_eq!(calls, ["a"]);
|
||||
assert_eq!(r.len(), 2);
|
||||
assert_eq!(r[1]["ok"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlong_line_is_refused() {
|
||||
// One byte over the limit, then a valid request: neither runs.
|
||||
let mut input = vec![b'x'; MAX_LINE + 1];
|
||||
input.extend_from_slice(b"\n{\"method\":\"a\"}\n");
|
||||
let (r, calls) = run(&input);
|
||||
assert!(calls.is_empty(), "{calls:?}");
|
||||
assert_eq!(r.len(), 1);
|
||||
assert!(r[0]["error"].as_str().unwrap().contains("longer than"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_at_the_limit_is_accepted() {
|
||||
let mut buf = Vec::new();
|
||||
let line = vec![b'a'; 10];
|
||||
let mut input = line.clone();
|
||||
input.push(b'\n');
|
||||
assert_eq!(read_bounded_line(&mut &input[..], &mut buf, 10), Ok(true));
|
||||
assert_eq!(buf, line);
|
||||
assert!(read_bounded_line(&mut &[b'a'; 11][..], &mut buf, 10).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_connection_is_closed_after_junk() {
|
||||
// End to end over a real loopback socket (the transport the app uses).
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (s, _) = listener.accept().unwrap();
|
||||
let read = s.try_clone().unwrap();
|
||||
serve_lines(read, s, |_, _| Some(json!({"ok": true})));
|
||||
});
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n{\"method\":\"y\"}\n").unwrap();
|
||||
let mut text = String::new();
|
||||
c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection
|
||||
server.join().unwrap();
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 2, "{text}");
|
||||
assert!(lines[0].contains("\"id\":7"));
|
||||
assert!(lines[1].contains("closing the connection"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ten_inspect_replies_for_10000_objects_arrive_within_20_s() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let reply = inspect_reply(10_000);
|
||||
let mut want = reply.clone();
|
||||
want["id"] = json!(1);
|
||||
let want = format!("{want}\n");
|
||||
std::thread::spawn(move || {
|
||||
let (s, _) = listener.accept().unwrap();
|
||||
let read = s.try_clone().unwrap();
|
||||
serve_lines(read, s, |_, _| Some(reply.clone()));
|
||||
});
|
||||
// The client sends each request line and reads its reply line through a `BufReader`, as `vectorcraft_mcp::Remote` does.
|
||||
let (tx, rx) = channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
let mut read = BufReader::new(c.try_clone().unwrap());
|
||||
let mut lines = vec![];
|
||||
for _ in 0..10 {
|
||||
c.write_all(b"{\"id\":1,\"method\":\"document.inspect\"}\n").unwrap();
|
||||
let mut line = String::new();
|
||||
read.read_line(&mut line).unwrap();
|
||||
lines.push(line);
|
||||
}
|
||||
tx.send(lines).ok();
|
||||
});
|
||||
let lines = rx.recv_timeout(Duration::from_secs(20)).unwrap_or_else(|_| panic!("ten replies did not arrive within 20 s"));
|
||||
assert!(lines.iter().all(|l| *l == want), "a reply differs from the bytes `writeln!` writes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_connections_are_refused() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (tx, _rx) = channel::<ControlRequest>();
|
||||
std::thread::spawn(move || accept_loop(listener, tx, egui::Context::default()));
|
||||
// Idle connections are accepted in order and held open.
|
||||
let held: Vec<TcpStream> = (0..16).map(|_| TcpStream::connect(addr).unwrap()).collect();
|
||||
let mut extra = TcpStream::connect(addr).unwrap();
|
||||
extra.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(&mut extra).read_line(&mut line).unwrap();
|
||||
assert!(line.contains("too many control connections"), "{line}");
|
||||
drop(held);
|
||||
}
|
||||
|
||||
// A test process is not an app that App Nap applies to, so this checks the activity the
|
||||
// channel asks for; the throttling itself shows only in a running app with its window hidden.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn the_control_channel_keeps_the_app_at_full_priority_on_macos() {
|
||||
use objc2_foundation::NSActivityOptions;
|
||||
let options = activity_options();
|
||||
assert!(options.contains(NSActivityOptions::LatencyCritical), "without it App Nap still lowers the priority to 20");
|
||||
assert!(options.contains(NSActivityOptions::UserInitiatedAllowingIdleSystemSleep));
|
||||
assert!(!options.contains(NSActivityOptions::IdleSystemSleepDisabled), "the channel must not keep the Mac awake");
|
||||
keep_answering();
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,394 @@
|
||||
use super::*;
|
||||
|
||||
fn short_timeouts() -> ConnectionTimeouts {
|
||||
ConnectionTimeouts { idle: Duration::from_millis(150), line: Duration::from_millis(120), write: Duration::from_millis(150) }
|
||||
}
|
||||
|
||||
/// The short line deadline, with idle and reply budgets longer than the tests' 3 s waits. On a
|
||||
/// busy machine either thread can pause for more than 150 ms between connecting and sending, or
|
||||
/// between starting a reply and writing it, and a short budget then closes the connection with no
|
||||
/// reply.
|
||||
fn line_timeouts() -> ConnectionTimeouts {
|
||||
ConnectionTimeouts { idle: Duration::from_secs(10), write: Duration::from_secs(10), ..short_timeouts() }
|
||||
}
|
||||
|
||||
fn socket_fixture(
|
||||
timeouts: ConnectionTimeouts,
|
||||
handle: impl FnMut(String, Value) -> Option<Value> + Send + 'static,
|
||||
) -> (TcpStream, Receiver<()>, std::thread::JoinHandle<()>) {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (finished, done) = channel();
|
||||
let worker = std::thread::spawn(move || {
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
socket2::SockRef::from(&stream).set_send_buffer_size(4096).unwrap();
|
||||
serve_socket(stream, timeouts, handle);
|
||||
finished.send(()).unwrap();
|
||||
});
|
||||
let client = TcpStream::connect(addr).unwrap();
|
||||
socket2::SockRef::from(&client).set_recv_buffer_size(4096).unwrap();
|
||||
client.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
(client, done, worker)
|
||||
}
|
||||
|
||||
fn expect_socket_deadline(client: TcpStream, done: Receiver<()>, worker: std::thread::JoinHandle<()>) {
|
||||
let stopped = done.recv_timeout(Duration::from_secs(3)).is_ok();
|
||||
// Always unblock the old implementation too, so a failed regression leaves no worker behind.
|
||||
let _ = client.shutdown(std::net::Shutdown::Both);
|
||||
drop(client);
|
||||
worker.join().unwrap();
|
||||
assert!(stopped, "the server retained a stalled connection beyond its transport deadline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_control_socket_releases_its_worker() {
|
||||
let (client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected"));
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
|
||||
/// An idle connection is closed without a line: a client that sends its next request late
|
||||
/// must not find an error waiting where its reply should be.
|
||||
#[test]
|
||||
fn idle_expiry_closes_without_writing_a_line() {
|
||||
let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected"));
|
||||
let mut got = Vec::new();
|
||||
client.read_to_end(&mut got).unwrap();
|
||||
assert_eq!(String::from_utf8_lossy(&got), "", "the app wrote to an idle connection");
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
|
||||
/// A line that stalls is refused in words a client's author can act on, not the system's.
|
||||
#[test]
|
||||
fn stalled_control_line_is_refused_with_the_reason() {
|
||||
let (mut client, done, worker) = socket_fixture(line_timeouts(), |_, _| panic!("incomplete requests must not execute"));
|
||||
client.write_all(b"{\"method\":").unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(client.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(&line).unwrap(),
|
||||
json!({"ok": false, "error": "request line not completed in time; closing the connection"})
|
||||
);
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_control_line_releases_its_worker() {
|
||||
let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("incomplete requests must not execute"));
|
||||
client.write_all(b"{\"method\":").unwrap();
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trickled_control_line_has_an_absolute_deadline() {
|
||||
let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("incomplete requests must not execute"));
|
||||
client.write_all(b"{").unwrap();
|
||||
let mut writer = client.try_clone().unwrap();
|
||||
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let writing = Arc::clone(&stop);
|
||||
let trickle = std::thread::spawn(move || {
|
||||
while !writing.load(Ordering::SeqCst) {
|
||||
if writer.write_all(b" ").is_err() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
});
|
||||
let stopped = done.recv_timeout(Duration::from_secs(3)).is_ok();
|
||||
stop.store(true, Ordering::SeqCst);
|
||||
// Both socket copies belong to this fixture; shutdown cleans up the baseline failure as well.
|
||||
let _ = client.shutdown(std::net::Shutdown::Both);
|
||||
trickle.join().unwrap();
|
||||
worker.join().unwrap();
|
||||
assert!(stopped, "trickled bytes restarted the line's deadline");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nonreading_control_peer_cannot_retain_the_writer() {
|
||||
let payload = "x".repeat(2 * 1024 * 1024);
|
||||
let (mut client, done, worker) = socket_fixture(short_timeouts(), move |_, _| Some(json!({"ok": true, "result": payload})));
|
||||
client.write_all(b"{\"method\":\"large\"}\n").unwrap();
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistent_control_requests_get_fresh_transport_deadlines() {
|
||||
let timeouts = ConnectionTimeouts { idle: Duration::from_secs(2), ..short_timeouts() };
|
||||
let (mut client, done, worker) = socket_fixture(timeouts, |_, _| {
|
||||
// Application processing is not transport time; begin the reply budget afterwards.
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
Some(json!({"ok": true}))
|
||||
});
|
||||
let mut reader = BufReader::new(client.try_clone().unwrap());
|
||||
for id in [1, 2] {
|
||||
// The client sends each line in one write. `writeln!` on the socket sends the JSON in many
|
||||
// small writes, and when the machine is busy, a pause of more than the 120 ms line deadline
|
||||
// between two of them closes the connection.
|
||||
client.write_all(format!("{}\n", json!({"id": id, "method": "inspect"})).as_bytes()).unwrap();
|
||||
let mut line = String::new();
|
||||
reader.read_line(&mut line).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Value>(&line).unwrap(), json!({"id": id, "ok": true}));
|
||||
}
|
||||
client.shutdown(std::net::Shutdown::Write).unwrap();
|
||||
done.recv_timeout(Duration::from_secs(3)).unwrap();
|
||||
worker.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffered_partial_control_line_also_expires() {
|
||||
let (mut client, done, worker) = socket_fixture(line_timeouts(), |_, _| Some(json!({"ok": true})));
|
||||
client.write_all(b"{\"id\":1,\"method\":\"inspect\"}\n{").unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(client.try_clone().unwrap()).read_line(&mut line).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["id"], 1);
|
||||
expect_socket_deadline(client, done, worker);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timed_out_worker_returns_its_connection_slot() {
|
||||
let open = Arc::new(AtomicUsize::new(0));
|
||||
let held: Vec<_> = (0..MAX_CONNECTIONS - 1).map(|_| acquire_slot(&open).unwrap()).collect();
|
||||
let slot = acquire_slot(&open).unwrap();
|
||||
assert!(acquire_slot(&open).is_none());
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let (tx, _rx) = channel();
|
||||
let worker = spawn_connection(stream, tx, egui::Context::default(), slot, short_timeouts()).unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
while open.load(Ordering::SeqCst) == MAX_CONNECTIONS && start.elapsed() < Duration::from_secs(3) {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
let released = open.load(Ordering::SeqCst) < MAX_CONNECTIONS;
|
||||
// Clean up an old implementation that never returned its slot as well.
|
||||
let _ = client.shutdown(std::net::Shutdown::Both);
|
||||
worker.join().unwrap();
|
||||
assert!(released, "the deadline did not free capacity for the next client");
|
||||
let replacement = acquire_slot(&open).expect("a new client can reserve the freed slot");
|
||||
drop(replacement);
|
||||
drop(held);
|
||||
assert_eq!(open.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
fn run(input: &[u8]) -> (Vec<Value>, Vec<String>) {
|
||||
let mut out = Vec::new();
|
||||
let mut calls = Vec::new();
|
||||
serve_lines(input, &mut out, |m, _p| {
|
||||
calls.push(m);
|
||||
Some(json!({"ok": true, "result": null}))
|
||||
});
|
||||
let replies = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str::<Value>(l).unwrap()).collect();
|
||||
(replies, calls)
|
||||
}
|
||||
|
||||
/// Counts the `write` calls made on it and keeps the bytes they write.
|
||||
#[derive(Default)]
|
||||
struct Writes {
|
||||
calls: usize,
|
||||
bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Write for Writes {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
self.calls += 1;
|
||||
self.bytes.extend_from_slice(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A reply shaped like `document.inspect`'s for a layer of `n` squares in rows of 200.
|
||||
fn inspect_reply(n: u64) -> Value {
|
||||
let paths: Vec<Value> = (0..n)
|
||||
.map(|k| {
|
||||
let (x, y) = ((k % 200) as f64 * 20.0, (k / 200) as f64 * 20.0);
|
||||
json!({"anchors": 4, "bounds": {"height": 10.0, "width": 10.0, "x": x, "y": y}, "closed": true, "fill": "#f4a261",
|
||||
"id": k + 2, "kind": "Path", "locked": false, "name": "<Path>", "stroke": "None", "strokeWidth": 0.0, "visible": true})
|
||||
})
|
||||
.collect();
|
||||
json!({"ok": true, "result": {"layers": [{"children": paths, "id": 1, "kind": "Layer", "name": "Layer 1"}]}})
|
||||
}
|
||||
|
||||
/// #1725: a request its caller gave up before the app took it never runs; one the app took
|
||||
/// first can't be withdrawn, and the timeout says so.
|
||||
#[test]
|
||||
fn a_timed_out_request_is_withdrawn_unless_it_started() {
|
||||
let (waiting, _rx) = ControlRequest::new("engine.execute", json!({}));
|
||||
assert!(timed_out(&waiting.ticket())["error"].as_str().unwrap().contains("will not run"));
|
||||
assert!(!waiting.claim(), "the app skips a withdrawn request");
|
||||
let (running, _rx) = ControlRequest::new("engine.execute", json!({}));
|
||||
assert!(running.claim());
|
||||
assert!(timed_out(&running.ticket())["error"].as_str().unwrap().contains("still running"));
|
||||
assert!(!running.claim(), "a request is taken once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_are_answered_in_order_with_ids() {
|
||||
let (r, calls) = run(b"{\"id\":1,\"method\":\"a\"}\n\n{\"id\":2,\"method\":\"b\",\"params\":{}}\r\n{\"method\":\"c\"}");
|
||||
assert_eq!(calls, ["a", "b", "c"]);
|
||||
assert_eq!(r.len(), 3);
|
||||
assert_eq!(r[0]["id"], 1);
|
||||
assert_eq!(r[1]["id"], 2);
|
||||
assert_eq!(r[2]["id"], Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replies_are_written_in_few_large_writes() {
|
||||
for reply in [json!({"ok": true, "result": null}), inspect_reply(2_000)] {
|
||||
let mut out = Writes::default();
|
||||
let mut once = Some(reply.clone());
|
||||
serve_lines(&b"{\"id\":1,\"method\":\"document.inspect\"}\n"[..], &mut out, |_, _| once.take());
|
||||
let mut want = reply;
|
||||
want["id"] = json!(1);
|
||||
let text = String::from_utf8(out.bytes).unwrap();
|
||||
// The writer receives the bytes that `writeln!(out, "{want}")` writes, in at most one write per 4 KiB.
|
||||
assert_eq!(text, format!("{want}\n"));
|
||||
assert!(out.calls <= text.len().div_ceil(4096), "{} writes for {} bytes", out.calls, text.len());
|
||||
}
|
||||
// A refusal is one write as well.
|
||||
let mut out = Writes::default();
|
||||
serve_lines(&b"hello\n"[..], &mut out, |_, _| None);
|
||||
assert_eq!(out.calls, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_request_closes_before_the_body_runs() {
|
||||
// A browser's cross-origin `fetch` POST: the request line is rejected and the
|
||||
// connection closed, so the JSON body is never executed.
|
||||
let http = b"POST / HTTP/1.1\r\nHost: 127.0.0.1:7979\r\nOrigin: https://attacker.example\r\nContent-Type: text/plain\r\n\r\n\
|
||||
{\"id\":7,\"method\":\"engine.execute\",\"params\":{\"command\":\"file.new\",\"params\":{}}}\n";
|
||||
let (r, calls) = run(http);
|
||||
assert!(calls.is_empty(), "nothing may run: {calls:?}");
|
||||
assert_eq!(r.len(), 1);
|
||||
assert_eq!(r[0]["ok"], false);
|
||||
assert!(r[0]["error"].as_str().unwrap().contains("closing the connection"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_request_json_closes_the_connection() {
|
||||
for junk in [
|
||||
&b"[1,2]\n{\"method\":\"a\"}\n"[..],
|
||||
b"{\"id\":1}\n{\"method\":\"a\"}\n",
|
||||
b"{\"method\":5}\n{\"method\":\"a\"}\n",
|
||||
b"\xff\xfe\n{\"method\":\"a\"}\n",
|
||||
] {
|
||||
let (r, calls) = run(junk);
|
||||
assert!(calls.is_empty(), "{calls:?}");
|
||||
assert_eq!(r.len(), 1);
|
||||
assert_eq!(r[0]["ok"], false);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_before_junk_still_runs() {
|
||||
let (r, calls) = run(b"{\"method\":\"a\"}\nGET / HTTP/1.1\n{\"method\":\"b\"}\n");
|
||||
assert_eq!(calls, ["a"]);
|
||||
assert_eq!(r.len(), 2);
|
||||
assert_eq!(r[1]["ok"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlong_line_is_refused() {
|
||||
// One byte over the limit, then a valid request: neither runs.
|
||||
let mut input = vec![b'x'; MAX_LINE + 1];
|
||||
input.extend_from_slice(b"\n{\"method\":\"a\"}\n");
|
||||
let (r, calls) = run(&input);
|
||||
assert!(calls.is_empty(), "{calls:?}");
|
||||
assert_eq!(r.len(), 1);
|
||||
assert!(r[0]["error"].as_str().unwrap().contains("longer than"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_at_the_limit_is_accepted() {
|
||||
let mut buf = Vec::new();
|
||||
let line = vec![b'a'; 10];
|
||||
let mut input = line.clone();
|
||||
input.push(b'\n');
|
||||
assert_eq!(read_bounded_line(&mut &input[..], &mut buf, 10), Ok(true));
|
||||
assert_eq!(buf, line);
|
||||
assert!(read_bounded_line(&mut &[b'a'; 11][..], &mut buf, 10).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tcp_connection_is_closed_after_junk() {
|
||||
// End to end over a real loopback socket (the transport the app uses).
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = std::thread::spawn(move || {
|
||||
let (s, _) = listener.accept().unwrap();
|
||||
let read = s.try_clone().unwrap();
|
||||
serve_lines(read, s, |_, _| Some(json!({"ok": true})));
|
||||
});
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
c.write_all(b"{\"id\":7,\"method\":\"x\"}\nhello\n{\"method\":\"y\"}\n").unwrap();
|
||||
let mut text = String::new();
|
||||
c.read_to_string(&mut text).unwrap(); // returns at EOF: the server closed the connection
|
||||
server.join().unwrap();
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 2, "{text}");
|
||||
assert!(lines[0].contains("\"id\":7"));
|
||||
assert!(lines[1].contains("closing the connection"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ten_inspect_replies_for_10000_objects_arrive_within_20_s() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let reply = inspect_reply(10_000);
|
||||
let mut want = reply.clone();
|
||||
want["id"] = json!(1);
|
||||
let want = format!("{want}\n");
|
||||
std::thread::spawn(move || {
|
||||
let (s, _) = listener.accept().unwrap();
|
||||
let read = s.try_clone().unwrap();
|
||||
serve_lines(read, s, |_, _| Some(reply.clone()));
|
||||
});
|
||||
// The client sends each request line and reads its reply line through a `BufReader`, as `vectorcraft_mcp::Remote` does.
|
||||
let (tx, rx) = channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut c = TcpStream::connect(addr).unwrap();
|
||||
let mut read = BufReader::new(c.try_clone().unwrap());
|
||||
let mut lines = vec![];
|
||||
for _ in 0..10 {
|
||||
c.write_all(b"{\"id\":1,\"method\":\"document.inspect\"}\n").unwrap();
|
||||
let mut line = String::new();
|
||||
read.read_line(&mut line).unwrap();
|
||||
lines.push(line);
|
||||
}
|
||||
tx.send(lines).ok();
|
||||
});
|
||||
let lines = rx.recv_timeout(Duration::from_secs(20)).unwrap_or_else(|_| panic!("ten replies did not arrive within 20 s"));
|
||||
assert!(lines.iter().all(|l| *l == want), "a reply differs from the bytes `writeln!` writes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_connections_are_refused() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (tx, _rx) = channel::<ControlRequest>();
|
||||
std::thread::spawn(move || accept_loop(listener, tx, egui::Context::default()));
|
||||
// Idle connections are accepted in order and held open.
|
||||
let held: Vec<TcpStream> = (0..16).map(|_| TcpStream::connect(addr).unwrap()).collect();
|
||||
let mut extra = TcpStream::connect(addr).unwrap();
|
||||
extra.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut line = String::new();
|
||||
BufReader::new(&mut extra).read_line(&mut line).unwrap();
|
||||
assert!(line.contains("too many control connections"), "{line}");
|
||||
drop(held);
|
||||
}
|
||||
|
||||
// A test process is not an app that App Nap applies to, so this checks the activity the
|
||||
// channel asks for; the throttling itself shows only in a running app with its window hidden.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn the_control_channel_keeps_the_app_at_full_priority_on_macos() {
|
||||
use objc2_foundation::NSActivityOptions;
|
||||
let options = activity_options();
|
||||
assert!(options.contains(NSActivityOptions::LatencyCritical), "without it App Nap still lowers the priority to 20");
|
||||
assert!(options.contains(NSActivityOptions::UserInitiatedAllowingIdleSystemSleep));
|
||||
assert!(!options.contains(NSActivityOptions::IdleSystemSleepDisabled), "the channel must not keep the Mac awake");
|
||||
keep_answering();
|
||||
}
|
||||
+1
-750
@@ -878,753 +878,4 @@ fn restart(skip: &str) -> std::io::Result<()> {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn gpu(name: &str, backend: Backend, device_type: DeviceType) -> Candidate {
|
||||
Candidate { key: format!("{backend:?}:{name}"), name: name.into(), backend, device_type, pci: (0, 0), presents: true }
|
||||
}
|
||||
|
||||
/// #1459: a 9048 px wide window (two display scales' ratio past 8192) fits an adapter that
|
||||
/// takes 16384 px textures; an adapter with less than eframe asks for changes nothing.
|
||||
#[test]
|
||||
fn the_surface_may_be_as_large_as_the_adapter_allows() {
|
||||
assert_eq!(surface_limit(8192, 16384), 16384);
|
||||
assert_eq!(surface_limit(8192, 4096), 8192);
|
||||
}
|
||||
|
||||
fn names(c: &[Candidate], order: &[usize]) -> Vec<String> {
|
||||
order.iter().map(|&i| c[i].name.clone()).collect()
|
||||
}
|
||||
|
||||
const NVIDIA_3090: (u32, u32) = (0x10de, 0x2204);
|
||||
const AMD_IGPU: (u32, u32) = (0x1002, 0x164e);
|
||||
const INTEL_IGPU: (u32, u32) = (0x8086, 0xa780);
|
||||
const WARP: (u32, u32) = (0x1414, 0x008c);
|
||||
|
||||
fn pci_gpu(name: &str, backend: Backend, device_type: DeviceType, pci: (u32, u32)) -> Candidate {
|
||||
Candidate { key: key(backend, pci.0, pci.1, name), name: name.into(), backend, device_type, pci, presents: true }
|
||||
}
|
||||
|
||||
fn monitor(pci: (u32, u32)) -> DisplayGpu {
|
||||
DisplayGpu { pci, primary: false }
|
||||
}
|
||||
|
||||
fn primary(pci: (u32, u32)) -> DisplayGpu {
|
||||
DisplayGpu { pci, primary: true }
|
||||
}
|
||||
|
||||
/// The desktop of pdfcraft#378 as wgpu lists it on Windows: a Ryzen's integrated GPU without a
|
||||
/// monitor and an RTX 3090 driving both monitors, each under Vulkan and DX12, then WARP and
|
||||
/// OpenGL (which reports no device id).
|
||||
fn ryzen_desktop() -> Vec<Candidate> {
|
||||
vec![
|
||||
pci_gpu("NVIDIA GeForce RTX 3090", Backend::Vulkan, DeviceType::DiscreteGpu, NVIDIA_3090),
|
||||
pci_gpu("AMD Radeon(TM) Graphics", Backend::Vulkan, DeviceType::IntegratedGpu, AMD_IGPU),
|
||||
pci_gpu("NVIDIA GeForce RTX 3090", Backend::Dx12, DeviceType::DiscreteGpu, NVIDIA_3090),
|
||||
pci_gpu("AMD Radeon(TM) Graphics", Backend::Dx12, DeviceType::IntegratedGpu, AMD_IGPU),
|
||||
pci_gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu, WARP),
|
||||
pci_gpu("NVIDIA GeForce RTX 3090/PCIe/SSE2", Backend::Gl, DeviceType::Other, (NVIDIA_3090.0, 0)),
|
||||
]
|
||||
}
|
||||
|
||||
/// pdfcraft#378: power saving picked the integrated GPU, whose driver reset when Windows had to
|
||||
/// present its frames on the monitors of the NVIDIA card. The GPU that drives the displays now
|
||||
/// comes first, through DX12 (#545); the integrated GPU stays the fallback a restart reaches.
|
||||
#[test]
|
||||
fn a_desktop_draws_on_the_gpu_that_drives_its_monitors() {
|
||||
let c = ryzen_desktop();
|
||||
for displays in [vec![primary(NVIDIA_3090)], vec![monitor(NVIDIA_3090)]] {
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), [2, 0, 3, 1, 5, 4], "{displays:?}");
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &displays, None, None, &[]), [2, 0, 3, 1, 5, 4], "{displays:?}");
|
||||
}
|
||||
// Without the display information the order is power saving's, as before.
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]), [3, 1, 2, 0, 5, 4]);
|
||||
// After the NVIDIA adapters failed, the integrated GPU is next.
|
||||
let skip = vec![c[2].key.clone(), c[0].key.clone()];
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[primary(NVIDIA_3090)], None, None, &skip), [3, 1, 5, 4]);
|
||||
}
|
||||
|
||||
/// A hybrid laptop: the panel (primary) on the integrated GPU, an external monitor on the
|
||||
/// discrete one. Power saving and the display agree, in either enumeration order.
|
||||
#[test]
|
||||
fn a_hybrid_laptop_draws_on_the_integrated_gpu_that_drives_its_panel() {
|
||||
let c = ryzen_desktop();
|
||||
for displays in [vec![primary(AMD_IGPU), monitor(NVIDIA_3090)], vec![monitor(NVIDIA_3090), primary(AMD_IGPU)], vec![primary(AMD_IGPU)]] {
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), [3, 1, 2, 0, 5, 4], "{displays:?}");
|
||||
}
|
||||
// Linux names no primary unless there is a built-in panel: a monitor on each GPU keeps the
|
||||
// system's order among them (Mesa puts the compositor's GPU first), and a GPU without one
|
||||
// comes after both.
|
||||
let linux = vec![
|
||||
pci_gpu("AMD Radeon Graphics (RADV RAPHAEL_MENDOCINO)", Backend::Vulkan, DeviceType::IntegratedGpu, AMD_IGPU),
|
||||
pci_gpu("NVIDIA GeForce RTX 3090", Backend::Vulkan, DeviceType::DiscreteGpu, NVIDIA_3090),
|
||||
pci_gpu("Intel(R) Arc(TM) A380", Backend::Vulkan, DeviceType::DiscreteGpu, INTEL_IGPU),
|
||||
pci_gpu("llvmpipe (LLVM 20.1.8, 256 bits)", Backend::Vulkan, DeviceType::Cpu, (0x10005, 0)),
|
||||
];
|
||||
let both = [monitor(AMD_IGPU), monitor(NVIDIA_3090)];
|
||||
assert_eq!(adapter_order(&linux, PowerPreference::None, &both, None, None, &[]), [0, 1, 2, 3]);
|
||||
assert_eq!(adapter_order(&linux, PowerPreference::None, &[monitor(INTEL_IGPU)], None, None, &[]), [2, 0, 1, 3]);
|
||||
assert_eq!(adapter_order(&linux, PowerPreference::None, &[monitor(NVIDIA_3090), primary(AMD_IGPU)], None, None, &[]), [0, 1, 2, 3]);
|
||||
}
|
||||
|
||||
/// A hybrid laptop whose Wayland compositor runs on the discrete GPU (Hyprland with
|
||||
/// `AQ_DRM_DEVICES` naming it first), as Vulkan lists it there: the integrated GPU drives the
|
||||
/// built-in panel, yet the compositor shows nothing it draws, and reports no error. The GPU the
|
||||
/// compositor draws with comes first; without it, the panel's, as before.
|
||||
#[test]
|
||||
fn the_gpu_the_compositor_draws_with_comes_before_the_panels() {
|
||||
const RTX_3050: (u32, u32) = (0x10de, 0x25ac);
|
||||
const INTEL_RPL: (u32, u32) = (0x8086, 0xa7a8);
|
||||
let mut c = vec![
|
||||
pci_gpu("NVIDIA GeForce RTX 3050 6GB Laptop GPU", Backend::Vulkan, DeviceType::DiscreteGpu, RTX_3050),
|
||||
pci_gpu("Intel(R) Graphics (RPL-P)", Backend::Vulkan, DeviceType::IntegratedGpu, INTEL_RPL),
|
||||
pci_gpu("NVIDIA GeForce RTX 3050 6GB Laptop GPU/PCIe/SSE2", Backend::Gl, DeviceType::Other, (RTX_3050.0, 0)),
|
||||
];
|
||||
c[2].presents = false;
|
||||
let panel = [primary(INTEL_RPL)];
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some(RTX_3050), None, &[]), [0, 1]);
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &panel, None, None, &[]), [1, 0]);
|
||||
// The usual hybrid laptop, with the compositor on the integrated GPU: the panel's GPU.
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &[primary(INTEL_RPL), monitor(RTX_3050)], Some(INTEL_RPL), None, &[]), [1, 0]);
|
||||
// `WGPU_ADAPTER_NAME` still comes first, and a restart after a failure still moves on.
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some(RTX_3050), Some("intel"), &[]), [1, 0]);
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some(RTX_3050), None, &[c[0].key.clone()]), [1]);
|
||||
// A compositor GPU no adapter matches (a virtual one) leaves the displays in charge.
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some((0x1af4, 0x1050)), None, &[]), [1, 0]);
|
||||
}
|
||||
|
||||
/// A Windows desktop with a monitor on each GPU: the window opens on the primary display, so
|
||||
/// its GPU draws, whichever kind it is.
|
||||
#[test]
|
||||
fn the_primary_display_decides_between_gpus_that_both_drive_a_monitor() {
|
||||
let c = ryzen_desktop();
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[monitor(AMD_IGPU), primary(NVIDIA_3090)], None, None, &[]), [2, 0, 3, 1, 5, 4]);
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[primary(AMD_IGPU), monitor(NVIDIA_3090)], None, None, &[]), [3, 1, 2, 0, 5, 4]);
|
||||
// The displays only matter among adapters that can show the window; a GPU driving no
|
||||
// display still loses to one that does.
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[monitor(AMD_IGPU), monitor(INTEL_IGPU)], None, None, &[]), [3, 1, 2, 0, 5, 4]);
|
||||
}
|
||||
|
||||
/// Display GPUs none of the adapters match (another driver's ids, OpenGL's missing device id,
|
||||
/// Metal's zeros) change nothing: power saving's order, the old behaviour.
|
||||
#[test]
|
||||
fn displays_no_adapter_matches_leave_the_power_preference_in_charge() {
|
||||
let c = ryzen_desktop();
|
||||
let low = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]);
|
||||
for displays in [vec![monitor(INTEL_IGPU)], vec![primary((0x8086, 0x1234)), monitor((0x8086, 0x5678))], vec![primary((0, 0))]] {
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), low, "{displays:?}");
|
||||
}
|
||||
assert_eq!(
|
||||
names(&c, &adapter_order(&c, PowerPreference::HighPerformance, &[monitor(INTEL_IGPU)], None, None, &[]))[0],
|
||||
"NVIDIA GeForce RTX 3090"
|
||||
);
|
||||
// The #502 machine's adapters report no ids in these tests: the primary display never matches.
|
||||
let c = issue_502();
|
||||
assert_eq!(
|
||||
adapter_order(&c, PowerPreference::None, &[primary(NVIDIA_3090)], None, None, &[]),
|
||||
adapter_order(&c, PowerPreference::None, &[], None, None, &[])
|
||||
);
|
||||
assert!(adapter_order(&[], PowerPreference::LowPower, &[primary(NVIDIA_3090)], None, None, &[]).is_empty());
|
||||
}
|
||||
|
||||
/// `WGPU_ADAPTER_NAME` and "can't present" still come before the displays.
|
||||
#[test]
|
||||
fn a_named_adapter_comes_before_the_one_driving_the_display() {
|
||||
let mut c = ryzen_desktop();
|
||||
let displays = [primary(NVIDIA_3090)];
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, Some("radeon"), &[]), [3, 1, 2, 0, 5, 4]);
|
||||
c[2].presents = false;
|
||||
c[0].presents = false;
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), [3, 1, 5, 4]);
|
||||
}
|
||||
|
||||
/// A user's own choice (Preferences or `WGPU_POWER_PREF`) is kept as it is; only Automatic
|
||||
/// looks at the displays.
|
||||
#[test]
|
||||
fn only_automatic_considers_which_gpu_drives_the_display() {
|
||||
assert!(automatic(None, None));
|
||||
assert!(automatic(Some("automatic"), None));
|
||||
assert!(automatic(Some("powerSaving"), None));
|
||||
assert!(!automatic(Some("lowPower"), None));
|
||||
assert!(!automatic(Some("highPerformance"), None));
|
||||
assert!(!automatic(None, Some(PowerPreference::None)));
|
||||
assert!(!automatic(Some("automatic"), Some(PowerPreference::LowPower)));
|
||||
assert!(preferred_displays(Some("lowPower"), None).is_empty());
|
||||
assert!(preferred_displays(None, Some(PowerPreference::HighPerformance)).is_empty());
|
||||
// Automatic reports whatever this machine has (nothing on macOS, in CI, or under Remote Desktop).
|
||||
assert_eq!(preferred_displays(None, None), display_gpus());
|
||||
assert_eq!(preferred_compositor(Some("lowPower"), None), None);
|
||||
assert_eq!(preferred_compositor(None, Some(PowerPreference::HighPerformance)), None);
|
||||
assert_eq!(preferred_compositor(None, None), crate::compositor_gpu::compositor_gpu());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pci_ids_come_from_windows_device_ids() {
|
||||
assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_2204&SUBSYS_40421458&REV_A1"), Some(NVIDIA_3090));
|
||||
assert_eq!(pci_ids("PCI\\VEN_1002&DEV_164E&SUBSYS_88771043&REV_C1"), Some(AMD_IGPU));
|
||||
assert_eq!(pci_ids("pci\\ven_1002&dev_164e"), Some(AMD_IGPU));
|
||||
// Remote Desktop and other non-PCI display devices, and malformed ids.
|
||||
assert_eq!(pci_ids("ROOT\\BasicDisplay\\0000"), None);
|
||||
assert_eq!(pci_ids("PCI\\VEN_10DE&SUBSYS_40421458"), None);
|
||||
assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_ZZZZ"), None);
|
||||
assert_eq!(pci_ids("VEN_&DEV_"), None);
|
||||
assert_eq!(pci_ids(""), None);
|
||||
}
|
||||
|
||||
/// Whatever this machine has: every GPU listed is a PCI device, at most one drives the primary
|
||||
/// display, and none is listed twice. (A headless CI runner may list none.)
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_lists_each_gpu_with_a_monitor_once() {
|
||||
let gpus = windows_display_gpus();
|
||||
assert!(gpus.iter().filter(|g| g.primary).count() <= 1, "{gpus:?}");
|
||||
for (i, g) in gpus.iter().enumerate() {
|
||||
assert_ne!(g.pci.0, 0, "{gpus:?}");
|
||||
assert!(!gpus[..i].iter().any(|h| h.pci == g.pci), "{gpus:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internal_panels_are_edp_lvds_and_dsi_connectors() {
|
||||
for name in ["eDP-1", "LVDS-1", "DSI-1"] {
|
||||
assert!(is_internal_panel(name), "{name}");
|
||||
}
|
||||
for name in ["DP-3", "HDMI-A-1", "DVI-D-1", "VGA-1", "Writeback-1", ""] {
|
||||
assert!(!is_internal_panel(name), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A sysfs like a hybrid laptop's with an external monitor: the panel and a disconnected port
|
||||
/// on the integrated GPU (card0), the monitor on the discrete one (card1), and a card without
|
||||
/// PCI ids. Each GPU is listed once, the one with the panel as primary.
|
||||
#[test]
|
||||
fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<()> {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-drm-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let card = |name: &str, (vendor, device): (u32, u32)| -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir.join(name).join("device"))?;
|
||||
std::fs::write(dir.join(name).join("device/vendor"), format!("{vendor:#06x}\n"))?;
|
||||
std::fs::write(dir.join(name).join("device/device"), format!("{device:#06x}\n"))
|
||||
};
|
||||
let connector = |name: &str, status: &str| -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir.join(name))?;
|
||||
std::fs::write(dir.join(name).join("status"), format!("{status}\n"))
|
||||
};
|
||||
card("card0", AMD_IGPU)?;
|
||||
card("card1", NVIDIA_3090)?;
|
||||
std::fs::create_dir_all(dir.join("card2"))?;
|
||||
connector("card0-eDP-1", "connected")?;
|
||||
connector("card0-HDMI-A-1", "disconnected")?;
|
||||
connector("card1-DP-1", "connected")?;
|
||||
connector("card1-DP-2", "connected")?;
|
||||
connector("card2-Virtual-1", "connected")?;
|
||||
std::fs::write(dir.join("renderD128"), "")?;
|
||||
let mut gpus = linux_display_gpus(&dir);
|
||||
gpus.sort_by_key(|g| g.pci);
|
||||
assert_eq!(gpus, [primary(AMD_IGPU), monitor(NVIDIA_3090)]);
|
||||
assert!(linux_display_gpus(&dir.join("no such dir")).is_empty());
|
||||
std::fs::remove_dir_all(&dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_gpus_are_logged_as_pci_ids() {
|
||||
assert_eq!(primary(NVIDIA_3090).to_string(), "10de:2204 (primary)");
|
||||
assert_eq!(monitor(AMD_IGPU).to_string(), "1002:164e");
|
||||
let mut gpus = vec![];
|
||||
add_display_gpu(&mut gpus, NVIDIA_3090, false);
|
||||
add_display_gpu(&mut gpus, NVIDIA_3090, true);
|
||||
add_display_gpu(&mut gpus, AMD_IGPU, false);
|
||||
assert_eq!(gpus, [primary(NVIDIA_3090), monitor(AMD_IGPU)]);
|
||||
}
|
||||
|
||||
/// The machine of #502 as Vulkan lists it with Mesa's device-select layer: the GPU KDE's
|
||||
/// compositor runs on (NVIDIA) first, then the Ryzen's integrated GPU, Mesa's software
|
||||
/// renderer, and OpenGL.
|
||||
fn issue_502() -> Vec<Candidate> {
|
||||
vec![
|
||||
gpu("NVIDIA GeForce RTX 5070", Backend::Vulkan, DeviceType::DiscreteGpu),
|
||||
gpu("AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)", Backend::Vulkan, DeviceType::IntegratedGpu),
|
||||
gpu("llvmpipe (LLVM 20.1.8, 256 bits)", Backend::Vulkan, DeviceType::Cpu),
|
||||
gpu("NVIDIA GeForce RTX 5070/PCIe/SSE2", Backend::Gl, DeviceType::Other),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_keeps_the_systems_order_on_linux_and_saves_power_elsewhere() {
|
||||
let c = issue_502();
|
||||
let order = adapter_order(&c, power_preference(None, None), &[], None, None, &[]);
|
||||
let first = &c[order[0]].name;
|
||||
if cfg!(any(windows, target_os = "macos")) {
|
||||
assert_eq!(first, "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)");
|
||||
} else {
|
||||
// #502: the integrated GPU couldn't show frames to a compositor on the NVIDIA GPU.
|
||||
assert_eq!(first, "NVIDIA GeForce RTX 5070");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_preference_orders_the_adapters_then_falls_back_to_opengl_and_software() {
|
||||
let c = issue_502();
|
||||
let order = |power| names(&c, &adapter_order(&c, power, &[], None, None, &[]));
|
||||
assert_eq!(
|
||||
order(PowerPreference::None),
|
||||
[
|
||||
"NVIDIA GeForce RTX 5070",
|
||||
"AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)",
|
||||
"NVIDIA GeForce RTX 5070/PCIe/SSE2",
|
||||
"llvmpipe (LLVM 20.1.8, 256 bits)"
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
order(PowerPreference::LowPower),
|
||||
[
|
||||
"AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)",
|
||||
"NVIDIA GeForce RTX 5070",
|
||||
"NVIDIA GeForce RTX 5070/PCIe/SSE2",
|
||||
"llvmpipe (LLVM 20.1.8, 256 bits)"
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
order(PowerPreference::HighPerformance),
|
||||
[
|
||||
"NVIDIA GeForce RTX 5070",
|
||||
"AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)",
|
||||
"NVIDIA GeForce RTX 5070/PCIe/SSE2",
|
||||
"llvmpipe (LLVM 20.1.8, 256 bits)"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A restart leaves out the adapter the window failed on, so Power Saving on the machine of
|
||||
/// #502 ends up on the NVIDIA GPU, and once every adapter failed there is nothing to try.
|
||||
/// A dual-GPU Mac reports both GPUs under Metal with no PCI ids (#651): their keys still
|
||||
/// differ, so when the integrated GPU fails, the restart renders on the discrete one.
|
||||
#[test]
|
||||
fn gpus_without_pci_ids_are_told_apart_by_name() {
|
||||
let mac = |name: &str, device_type| Candidate {
|
||||
key: key(Backend::Metal, 0, 0, name),
|
||||
name: name.into(),
|
||||
backend: Backend::Metal,
|
||||
device_type,
|
||||
pci: (0, 0),
|
||||
presents: true,
|
||||
};
|
||||
let c = vec![mac("NVIDIA GeForce GT 750M", DeviceType::DiscreteGpu), mac("Intel Iris Pro Graphics", DeviceType::IntegratedGpu)];
|
||||
assert_eq!((c[0].key.as_str(), c[1].key.as_str()), ("Metal:NVIDIA GeForce GT 750M", "Metal:Intel Iris Pro Graphics"));
|
||||
let first = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]);
|
||||
assert_eq!(names(&c, &first)[0], "Intel Iris Pro Graphics");
|
||||
let skip = parse_skip(&c[first[0]].key);
|
||||
assert_eq!(names(&c, &adapter_order(&c, PowerPreference::LowPower, &[], None, None, &skip)), ["NVIDIA GeForce GT 750M"]);
|
||||
// A comma in a name can't split the list.
|
||||
assert_eq!(parse_skip(&key(Backend::Gl, 0, 0, "Mesa, llvmpipe")), ["Gl:Mesa llvmpipe"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_first_frame_that_never_reaches_the_screen_hangs_its_adapter() {
|
||||
let s = Duration::from_secs;
|
||||
// The second frame began: the first was presented.
|
||||
assert_eq!(first_frame(2, s(60), false), FirstFrame::Shown);
|
||||
// Still drawing (or presenting) the first frame: waited for, then given up on (#964).
|
||||
for frames in [0, 1] {
|
||||
assert_eq!(first_frame(frames, s(3), false), FirstFrame::Wait);
|
||||
assert_eq!(first_frame(frames, FIRST_FRAME_TIMEOUT, false), FirstFrame::Hung);
|
||||
}
|
||||
// A window minimized at the start may not draw again until restored.
|
||||
assert_eq!(first_frame(1, s(60), true), FirstFrame::Shown);
|
||||
// A hung adapter is left out once, like one that failed.
|
||||
let skip = vec!["Dx12:10de:28a0".to_string()];
|
||||
assert_eq!(restart_without(true, 1, Some("Dx12:10de:28a0"), &skip), None);
|
||||
assert_eq!(restart_without(true, 1, Some("Dx12:8086:a7a8"), &skip), Some("Dx12:8086:a7a8"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restart_tries_the_next_adapter() {
|
||||
let c = issue_502();
|
||||
let mut skip = vec![];
|
||||
let mut tried = vec![];
|
||||
while let Some(&i) = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &skip).first() {
|
||||
tried.push(c[i].name.clone());
|
||||
skip.push(c[i].key.clone());
|
||||
}
|
||||
assert_eq!(
|
||||
tried,
|
||||
[
|
||||
"AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)",
|
||||
"NVIDIA GeForce RTX 5070",
|
||||
"NVIDIA GeForce RTX 5070/PCIe/SSE2",
|
||||
"llvmpipe (LLVM 20.1.8, 256 bits)"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapters_that_cannot_present_to_the_window_are_never_tried() {
|
||||
let mut c = issue_502();
|
||||
c[0].presents = false;
|
||||
c[3].presents = false;
|
||||
for power in [PowerPreference::None, PowerPreference::LowPower, PowerPreference::HighPerformance] {
|
||||
let order = adapter_order(&c, power, &[], None, None, &[]);
|
||||
assert!(!order.contains(&0) && !order.contains(&3), "{power:?}: {order:?}");
|
||||
assert_eq!(order.len(), 2);
|
||||
}
|
||||
for p in &mut c {
|
||||
p.presents = false;
|
||||
}
|
||||
assert!(adapter_order(&c, PowerPreference::None, &[], None, None, &[]).is_empty());
|
||||
assert!(adapter_order(&[], PowerPreference::HighPerformance, &[], None, None, &[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wgpu_adapter_name_picks_an_adapter_first_and_the_rest_stay_as_fallbacks() {
|
||||
let c = issue_502();
|
||||
let order = adapter_order(&c, PowerPreference::HighPerformance, &[], None, Some("radv"), &[]);
|
||||
assert_eq!(c[order[0]].name, "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)");
|
||||
assert_eq!(order.len(), 4);
|
||||
// Any case; every match comes before the rest, natively first.
|
||||
let order = adapter_order(&c, PowerPreference::LowPower, &[], None, Some("GeForce"), &[]);
|
||||
assert_eq!(names(&c, &order[..2]), ["NVIDIA GeForce RTX 5070", "NVIDIA GeForce RTX 5070/PCIe/SSE2"]);
|
||||
// An empty name or one nothing matches changes nothing.
|
||||
for named in ["", "no such gpu"] {
|
||||
assert_eq!(
|
||||
adapter_order(&c, PowerPreference::LowPower, &[], None, Some(named), &[]),
|
||||
adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[])
|
||||
);
|
||||
}
|
||||
// A named adapter that failed is left out like any other.
|
||||
let skip = vec![c[1].key.clone()];
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &[], None, Some("radv"), &skip)[0], 0);
|
||||
}
|
||||
|
||||
/// A Windows machine lists every GPU twice (Vulkan and DX12): power saving still takes the
|
||||
/// integrated GPU first, as wgpu's own choice did (#306), each GPU through DX12 first (#545).
|
||||
#[test]
|
||||
fn hybrid_laptop_on_windows_renders_on_the_integrated_gpu_with_power_saving() {
|
||||
let c = vec![
|
||||
gpu("Intel(R) Arc(TM) A370M", Backend::Vulkan, DeviceType::DiscreteGpu),
|
||||
gpu("Intel(R) Iris(R) Xe Graphics", Backend::Vulkan, DeviceType::IntegratedGpu),
|
||||
gpu("Intel(R) Arc(TM) A370M", Backend::Dx12, DeviceType::DiscreteGpu),
|
||||
gpu("Intel(R) Iris(R) Xe Graphics", Backend::Dx12, DeviceType::IntegratedGpu),
|
||||
gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu),
|
||||
];
|
||||
let order = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]);
|
||||
assert_eq!(order, [3, 1, 2, 0, 4]);
|
||||
assert_eq!(adapter_order(&c, PowerPreference::HighPerformance, &[], None, None, &[]), [2, 0, 3, 1, 4]);
|
||||
}
|
||||
|
||||
/// The machine of #545: one Intel GPU, whose Vulkan driver made the window flicker black.
|
||||
/// DX12 comes first whatever the preference; Vulkan stays a fallback, and `WGPU_ADAPTER_NAME`
|
||||
/// or a restart leaving DX12 out still reach it.
|
||||
#[test]
|
||||
fn a_windows_gpu_renders_through_dx12_before_vulkan() {
|
||||
let c = vec![
|
||||
gpu("Intel(R) Graphics", Backend::Vulkan, DeviceType::IntegratedGpu),
|
||||
gpu("Intel(R) Graphics", Backend::Dx12, DeviceType::IntegratedGpu),
|
||||
gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu),
|
||||
gpu("Intel(R) Graphics", Backend::Gl, DeviceType::Other),
|
||||
];
|
||||
for power in [PowerPreference::LowPower, PowerPreference::HighPerformance, PowerPreference::None] {
|
||||
assert_eq!(adapter_order(&c, power, &[], None, None, &[]), [1, 0, 3, 2], "{power:?}");
|
||||
}
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[c[1].key.clone()]), [0, 3, 2], "DX12 failed: Vulkan next");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_never_loads_vulkan_drivers_unless_asked() {
|
||||
let all = Backends::all();
|
||||
let start = backends(all, false);
|
||||
if cfg!(windows) {
|
||||
assert_eq!(start, Backends::DX12 | Backends::GL, "#806");
|
||||
} else {
|
||||
assert_eq!(start, all);
|
||||
}
|
||||
assert_eq!(backends(Backends::VULKAN, true), Backends::VULKAN, "WGPU_BACKEND=vulkan still picks it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn power_preference_follows_the_environment_then_the_preference() {
|
||||
assert_eq!(power_preference(None, None), AUTOMATIC);
|
||||
assert_eq!(power_preference(Some("automatic"), None), AUTOMATIC);
|
||||
assert_eq!(power_preference(Some("lowPower"), None), PowerPreference::LowPower);
|
||||
assert_eq!(power_preference(Some("highPerformance"), None), PowerPreference::HighPerformance);
|
||||
// 0.5.0's default, and values this version doesn't know (a newer or damaged file).
|
||||
for old in ["powerSaving", "turbo", ""] {
|
||||
assert_eq!(power_preference(Some(old), None), AUTOMATIC, "{old}");
|
||||
}
|
||||
// WGPU_POWER_PREF wins over the preference, either way.
|
||||
assert_eq!(power_preference(Some("lowPower"), Some(PowerPreference::HighPerformance)), PowerPreference::HighPerformance);
|
||||
assert_eq!(power_preference(Some("highPerformance"), Some(PowerPreference::LowPower)), PowerPreference::LowPower);
|
||||
assert_eq!(power_preference(Some("lowPower"), Some(PowerPreference::None)), PowerPreference::None);
|
||||
assert_eq!(AUTOMATIC, if cfg!(any(windows, target_os = "macos")) { PowerPreference::LowPower } else { PowerPreference::None });
|
||||
}
|
||||
|
||||
/// The preference the engine saves is the one the app reads back before the window opens.
|
||||
#[test]
|
||||
fn the_saved_engine_preference_is_found() {
|
||||
let mut prefs = vectorcraft_engine::Prefs::default();
|
||||
let saved = prefs.to_json();
|
||||
assert_eq!(saved.get("gpuPreference").and_then(serde_json::Value::as_str), Some("automatic"));
|
||||
for (value, power) in [("lowPower", PowerPreference::LowPower), ("highPerformance", PowerPreference::HighPerformance)] {
|
||||
prefs.gpu_preference = value.into();
|
||||
let saved = prefs.to_json();
|
||||
assert_eq!(power_preference(saved.get("gpuPreference").and_then(serde_json::Value::as_str), None), power);
|
||||
}
|
||||
// Every choice Preferences offer means something here.
|
||||
for (value, _) in vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES {
|
||||
assert!(["automatic", "lowPower", "highPerformance"].contains(value), "{value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skipped_adapters_parse_from_a_comma_separated_list() {
|
||||
assert_eq!(parse_skip("Vulkan:1002:164e, Gl:10de:2f04,,"), ["Vulkan:1002:164e", "Gl:10de:2f04"]);
|
||||
assert!(parse_skip("").is_empty());
|
||||
assert_eq!(key(Backend::Vulkan, 0x1002, 0x164e, "AMD Radeon"), "Vulkan:1002:164e");
|
||||
assert_eq!(key(Backend::Gl, 0x10de, 0x2f04, "NVIDIA"), "Gl:10de:2f04");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panics_in_wgpu_egui_wgpu_and_naga_are_graphics_failures() {
|
||||
for file in [
|
||||
"/home/u/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/egui-wgpu-0.36.2/src/winit.rs",
|
||||
r"C:\Users\u\.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\wgpu-core-30.0.1\src\device\mod.rs",
|
||||
"/rustc/deps/wgpu-hal-30.0.1/src/vulkan/adapter.rs",
|
||||
"naga-30.0.0/src/back/spv/writer.rs",
|
||||
] {
|
||||
assert!(in_graphics_stack(file), "{file}");
|
||||
}
|
||||
for file in [
|
||||
"apps/vectorcraft/src/main.rs",
|
||||
"/home/wgpu/vectorcraft/crates/ui-egui/src/lib.rs",
|
||||
"egui-0.36.2/src/context.rs",
|
||||
"winit-0.30.12/src/x.rs",
|
||||
] {
|
||||
assert!(!in_graphics_stack(file), "{file}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_graphics_failure_while_starting_up_restarts_without_the_adapter() {
|
||||
let amd = Some("Vulkan:1002:164e");
|
||||
assert_eq!(restart_without(true, 0, amd, &[]), amd);
|
||||
assert_eq!(restart_without(true, STARTUP_FRAMES - 1, amd, &[]), amd);
|
||||
// After start-up the adapter has shown frames; a lost window is something else.
|
||||
assert_eq!(restart_without(true, STARTUP_FRAMES, amd, &[]), None);
|
||||
// A bug outside the graphics, or no adapter picked: nothing another adapter would change.
|
||||
assert_eq!(restart_without(false, 0, amd, &[]), None);
|
||||
assert_eq!(restart_without(true, 0, None, &[]), None);
|
||||
// Never the same adapter twice, so restarts end.
|
||||
assert_eq!(restart_without(true, 0, amd, &["Vulkan:1002:164e".into()]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_normal_exit_or_another_failure_does_not_restart() {
|
||||
let startup = Startup::default();
|
||||
assert_eq!(finish(Ok(Ok(())), &startup), Ok(()));
|
||||
// No adapter was picked (none can show the window): the error is returned, nothing restarts.
|
||||
let none =
|
||||
eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no graphics adapter can show the window".into()));
|
||||
assert_eq!(
|
||||
finish(Ok(Err(none)), &startup),
|
||||
Err(format!("WGPU error: Adapter selection failed: no graphics adapter can show the window ({HELP})"))
|
||||
);
|
||||
let _ = startup.adapter.set("Vulkan:1002:164e".into());
|
||||
GRAPHICS_PANIC.store(false, Ordering::Relaxed);
|
||||
assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into()));
|
||||
}
|
||||
|
||||
/// A log folder of its own for each test.
|
||||
fn start_dir(tag: &str) -> std::path::PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("vectorcraft-gpu-start-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
d
|
||||
}
|
||||
|
||||
/// What a start in `dir` leaves out; it then ends without crashing.
|
||||
fn next_start(dir: &std::path::Path, explicit: bool) -> LeftOut {
|
||||
let s = Startup::default();
|
||||
let left_out = s.track(dir, None, explicit);
|
||||
s.ended();
|
||||
left_out
|
||||
}
|
||||
|
||||
/// The machine of #2243: one Intel UHD Graphics 605, listed through DX12 and OpenGL, and
|
||||
/// Windows' software adapter.
|
||||
fn issue_2243() -> Vec<Candidate> {
|
||||
vec![
|
||||
pci_gpu("Intel(R) UHD Graphics 605", Backend::Dx12, DeviceType::IntegratedGpu, (0x8086, 0x3184)),
|
||||
pci_gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu, (0x1414, 0x008c)),
|
||||
pci_gpu("Intel(R) UHD Graphics 605", Backend::Gl, DeviceType::Other, (0x8086, 0)),
|
||||
]
|
||||
}
|
||||
|
||||
/// #2243: the driver ends the process after the adapter was picked, before the first frame.
|
||||
/// The next start leaves that adapter out and draws through OpenGL, and so do the starts after
|
||||
/// it, without a status-bar note.
|
||||
#[test]
|
||||
fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
|
||||
let dir = start_dir("crash");
|
||||
let c = issue_2243();
|
||||
let first = Startup::default();
|
||||
assert_eq!(first.track(&dir, None, false), LeftOut::default());
|
||||
first.picked(&c[0].key, &c[0].name, true);
|
||||
// The process ends here: its file is closed and unlocked, and the start is still recorded.
|
||||
drop(first);
|
||||
|
||||
let second = Startup::default();
|
||||
let left_out = second.track(&dir, Some("automatic"), false);
|
||||
assert_eq!(left_out.adapters, ["Dx12:8086:3184"]);
|
||||
assert_eq!(left_out.crash, Some(Crash::Adapter { key: "Dx12:8086:3184".into(), name: "Intel(R) UHD Graphics 605".into() }));
|
||||
assert!(!left_out.opengl_only);
|
||||
assert_eq!(left_out.backends(Backends::DX12 | Backends::GL), Backends::DX12 | Backends::GL);
|
||||
let order = adapter_order(&c, AUTOMATIC, &[], None, None, &left_out.adapters);
|
||||
assert_eq!(order, [2, 1], "OpenGL on the same GPU before the software adapter");
|
||||
second.picked(&c[2].key, &c[2].name, true);
|
||||
second.presented();
|
||||
|
||||
let third = Startup::default();
|
||||
let left_out = third.track(&dir, None, false);
|
||||
assert_eq!(left_out.adapters, ["Dx12:8086:3184"], "kept");
|
||||
assert_eq!(left_out.crash, None, "the note is shown once");
|
||||
third.ended();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A start whose first frame reached the screen, or that ended without crashing (a normal exit,
|
||||
/// an error, a restart on another adapter), leaves nothing out of the next.
|
||||
#[test]
|
||||
fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
|
||||
let dir = start_dir("shown");
|
||||
let c = issue_2243();
|
||||
for end in [Startup::presented as fn(&Startup), Startup::ended] {
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
first.picked(&c[0].key, &c[0].name, true);
|
||||
end(&first);
|
||||
drop(first);
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
}
|
||||
// So does a start that ended before it picked an adapter.
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
assert!(finish(Ok(Ok(())), &first).is_ok());
|
||||
drop(first);
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The process ended while the adapters were being listed (wgpu's DX12 backend creates a
|
||||
/// device on each GPU to list it): the next starts list OpenGL's adapters alone, except on
|
||||
/// macOS, where wgpu has none.
|
||||
#[test]
|
||||
fn a_crash_while_listing_lists_opengl_alone() {
|
||||
let dir = start_dir("listing");
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
drop(first);
|
||||
let second = Startup::default();
|
||||
let left_out = second.track(&dir, None, false);
|
||||
assert!(left_out.adapters.is_empty());
|
||||
if cfg!(target_os = "macos") {
|
||||
assert_eq!(left_out, LeftOut::default());
|
||||
} else {
|
||||
assert_eq!(left_out.crash, Some(Crash::Listing));
|
||||
assert_eq!(left_out.backends(Backends::DX12 | Backends::GL), Backends::GL);
|
||||
assert_eq!(left_out.backends(Backends::PRIMARY | Backends::GL), Backends::GL);
|
||||
assert_eq!(left_out.backends(Backends::METAL), Backends::METAL, "no OpenGL to fall back to");
|
||||
}
|
||||
// Listing OpenGL alone found nothing that can show the window: the next start lists every
|
||||
// backend again.
|
||||
second.none_left();
|
||||
second.ended();
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` choose for a start whatever crashed before; when that
|
||||
/// start shows its first frame on the adapter that crashed, the adapter counts again.
|
||||
#[test]
|
||||
fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
|
||||
let dir = start_dir("explicit");
|
||||
let c = issue_2243();
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
first.picked(&c[0].key, &c[0].name, true);
|
||||
drop(first);
|
||||
assert_eq!(next_start(&dir, true), LeftOut::default());
|
||||
assert_eq!(next_start(&dir, false).adapters, ["Dx12:8086:3184"], "still left out without them");
|
||||
|
||||
let explicit = Startup::default();
|
||||
explicit.track(&dir, None, true);
|
||||
explicit.picked(&c[0].key, &c[0].name, true);
|
||||
explicit.presented();
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default(), "a new driver shows the window");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A damaged record, a file that can't be opened and one another starting copy of the app holds
|
||||
/// are ignored: the start goes on with nothing left out.
|
||||
#[test]
|
||||
fn a_damaged_or_unreadable_start_file_is_ignored() {
|
||||
let dir = start_dir("damaged");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let damaged: [&[u8]; 9] = [
|
||||
b"",
|
||||
b"{",
|
||||
b"[]",
|
||||
b"null",
|
||||
b"{\"version\":1}",
|
||||
b"{\"starting\":{}}",
|
||||
b"\xef\xbb\xbf\0",
|
||||
b"\xff\xfe{",
|
||||
&[b' '; START_FILE_LIMIT as usize + 1],
|
||||
];
|
||||
for text in damaged {
|
||||
std::fs::write(dir.join(START_FILE), text).unwrap();
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default(), "{:?}", String::from_utf8_lossy(&text[..text.len().min(20)]));
|
||||
}
|
||||
|
||||
// Another copy of the app is starting: this start neither reads nor writes the file.
|
||||
let c = issue_2243();
|
||||
let starting = Startup::default();
|
||||
starting.track(&dir, None, false);
|
||||
starting.picked(&c[0].key, &c[0].name, true);
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
drop(starting);
|
||||
assert_eq!(next_start(&dir, false).adapters, ["Dx12:8086:3184"]);
|
||||
|
||||
// A folder in the file's place.
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join(START_FILE)).unwrap();
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crashes_are_forgotten_in_another_version_or_under_another_preference() {
|
||||
let starting = |key: &str| Starting { adapter: Some(Recorded { key: key.into(), name: "GPU".into() }), native: true };
|
||||
let (mut record, crash) = StartRecord::begin(None, "0.9.0", "automatic");
|
||||
assert_eq!(crash, None);
|
||||
record.starting = Some(starting("Dx12:8086:3184"));
|
||||
let (record, crash) = StartRecord::begin(Some(record), "0.9.0", "automatic");
|
||||
assert_eq!(crash, Some(Crash::Adapter { key: "Dx12:8086:3184".into(), name: "GPU".into() }));
|
||||
assert_eq!(record.left_out(None, false).adapters, ["Dx12:8086:3184"]);
|
||||
// Written and read back.
|
||||
assert_eq!(StartRecord::parse(&record.to_json()), Some(record.clone()));
|
||||
assert!(StartRecord::begin(Some(record.clone()), "0.9.1", "automatic").0.crashed.is_empty());
|
||||
assert!(StartRecord::begin(Some(record.clone()), "0.9.0", "highPerformance").0.crashed.is_empty());
|
||||
assert_eq!(preference_name(None), "automatic");
|
||||
assert_eq!(preference_name(Some("powerSaving")), "automatic");
|
||||
assert_eq!(preference_name(Some("lowPower")), "lowPower");
|
||||
// An adapter is listed once, and the list is bounded.
|
||||
let mut record = record;
|
||||
for n in 0..CRASHED_LIMIT + 4 {
|
||||
for _ in 0..2 {
|
||||
record.starting = Some(starting(&format!("Dx12:10de:{n:04x}")));
|
||||
record = StartRecord::begin(Some(record), "0.9.0", "automatic").0;
|
||||
}
|
||||
}
|
||||
assert_eq!(record.crashed.len(), CRASHED_LIMIT);
|
||||
assert_eq!(record.crashed.last().map(|c| c.key.as_str()), Some("Dx12:10de:0013"));
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,744 @@
|
||||
use super::*;
|
||||
|
||||
fn gpu(name: &str, backend: Backend, device_type: DeviceType) -> Candidate {
|
||||
Candidate { key: format!("{backend:?}:{name}"), name: name.into(), backend, device_type, pci: (0, 0), presents: true }
|
||||
}
|
||||
|
||||
/// #1459: a 9048 px wide window (two display scales' ratio past 8192) fits an adapter that
|
||||
/// takes 16384 px textures; an adapter with less than eframe asks for changes nothing.
|
||||
#[test]
|
||||
fn the_surface_may_be_as_large_as_the_adapter_allows() {
|
||||
assert_eq!(surface_limit(8192, 16384), 16384);
|
||||
assert_eq!(surface_limit(8192, 4096), 8192);
|
||||
}
|
||||
|
||||
fn names(c: &[Candidate], order: &[usize]) -> Vec<String> {
|
||||
order.iter().map(|&i| c[i].name.clone()).collect()
|
||||
}
|
||||
|
||||
const NVIDIA_3090: (u32, u32) = (0x10de, 0x2204);
|
||||
const AMD_IGPU: (u32, u32) = (0x1002, 0x164e);
|
||||
const INTEL_IGPU: (u32, u32) = (0x8086, 0xa780);
|
||||
const WARP: (u32, u32) = (0x1414, 0x008c);
|
||||
|
||||
fn pci_gpu(name: &str, backend: Backend, device_type: DeviceType, pci: (u32, u32)) -> Candidate {
|
||||
Candidate { key: key(backend, pci.0, pci.1, name), name: name.into(), backend, device_type, pci, presents: true }
|
||||
}
|
||||
|
||||
fn monitor(pci: (u32, u32)) -> DisplayGpu {
|
||||
DisplayGpu { pci, primary: false }
|
||||
}
|
||||
|
||||
fn primary(pci: (u32, u32)) -> DisplayGpu {
|
||||
DisplayGpu { pci, primary: true }
|
||||
}
|
||||
|
||||
/// The desktop of pdfcraft#378 as wgpu lists it on Windows: a Ryzen's integrated GPU without a
|
||||
/// monitor and an RTX 3090 driving both monitors, each under Vulkan and DX12, then WARP and
|
||||
/// OpenGL (which reports no device id).
|
||||
fn ryzen_desktop() -> Vec<Candidate> {
|
||||
vec![
|
||||
pci_gpu("NVIDIA GeForce RTX 3090", Backend::Vulkan, DeviceType::DiscreteGpu, NVIDIA_3090),
|
||||
pci_gpu("AMD Radeon(TM) Graphics", Backend::Vulkan, DeviceType::IntegratedGpu, AMD_IGPU),
|
||||
pci_gpu("NVIDIA GeForce RTX 3090", Backend::Dx12, DeviceType::DiscreteGpu, NVIDIA_3090),
|
||||
pci_gpu("AMD Radeon(TM) Graphics", Backend::Dx12, DeviceType::IntegratedGpu, AMD_IGPU),
|
||||
pci_gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu, WARP),
|
||||
pci_gpu("NVIDIA GeForce RTX 3090/PCIe/SSE2", Backend::Gl, DeviceType::Other, (NVIDIA_3090.0, 0)),
|
||||
]
|
||||
}
|
||||
|
||||
/// pdfcraft#378: power saving picked the integrated GPU, whose driver reset when Windows had to
|
||||
/// present its frames on the monitors of the NVIDIA card. The GPU that drives the displays now
|
||||
/// comes first, through DX12 (#545); the integrated GPU stays the fallback a restart reaches.
|
||||
#[test]
|
||||
fn a_desktop_draws_on_the_gpu_that_drives_its_monitors() {
|
||||
let c = ryzen_desktop();
|
||||
for displays in [vec![primary(NVIDIA_3090)], vec![monitor(NVIDIA_3090)]] {
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), [2, 0, 3, 1, 5, 4], "{displays:?}");
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &displays, None, None, &[]), [2, 0, 3, 1, 5, 4], "{displays:?}");
|
||||
}
|
||||
// Without the display information the order is power saving's, as before.
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]), [3, 1, 2, 0, 5, 4]);
|
||||
// After the NVIDIA adapters failed, the integrated GPU is next.
|
||||
let skip = vec![c[2].key.clone(), c[0].key.clone()];
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[primary(NVIDIA_3090)], None, None, &skip), [3, 1, 5, 4]);
|
||||
}
|
||||
|
||||
/// A hybrid laptop: the panel (primary) on the integrated GPU, an external monitor on the
|
||||
/// discrete one. Power saving and the display agree, in either enumeration order.
|
||||
#[test]
|
||||
fn a_hybrid_laptop_draws_on_the_integrated_gpu_that_drives_its_panel() {
|
||||
let c = ryzen_desktop();
|
||||
for displays in [vec![primary(AMD_IGPU), monitor(NVIDIA_3090)], vec![monitor(NVIDIA_3090), primary(AMD_IGPU)], vec![primary(AMD_IGPU)]] {
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), [3, 1, 2, 0, 5, 4], "{displays:?}");
|
||||
}
|
||||
// Linux names no primary unless there is a built-in panel: a monitor on each GPU keeps the
|
||||
// system's order among them (Mesa puts the compositor's GPU first), and a GPU without one
|
||||
// comes after both.
|
||||
let linux = vec![
|
||||
pci_gpu("AMD Radeon Graphics (RADV RAPHAEL_MENDOCINO)", Backend::Vulkan, DeviceType::IntegratedGpu, AMD_IGPU),
|
||||
pci_gpu("NVIDIA GeForce RTX 3090", Backend::Vulkan, DeviceType::DiscreteGpu, NVIDIA_3090),
|
||||
pci_gpu("Intel(R) Arc(TM) A380", Backend::Vulkan, DeviceType::DiscreteGpu, INTEL_IGPU),
|
||||
pci_gpu("llvmpipe (LLVM 20.1.8, 256 bits)", Backend::Vulkan, DeviceType::Cpu, (0x10005, 0)),
|
||||
];
|
||||
let both = [monitor(AMD_IGPU), monitor(NVIDIA_3090)];
|
||||
assert_eq!(adapter_order(&linux, PowerPreference::None, &both, None, None, &[]), [0, 1, 2, 3]);
|
||||
assert_eq!(adapter_order(&linux, PowerPreference::None, &[monitor(INTEL_IGPU)], None, None, &[]), [2, 0, 1, 3]);
|
||||
assert_eq!(adapter_order(&linux, PowerPreference::None, &[monitor(NVIDIA_3090), primary(AMD_IGPU)], None, None, &[]), [0, 1, 2, 3]);
|
||||
}
|
||||
|
||||
/// A hybrid laptop whose Wayland compositor runs on the discrete GPU (Hyprland with
|
||||
/// `AQ_DRM_DEVICES` naming it first), as Vulkan lists it there: the integrated GPU drives the
|
||||
/// built-in panel, yet the compositor shows nothing it draws, and reports no error. The GPU the
|
||||
/// compositor draws with comes first; without it, the panel's, as before.
|
||||
#[test]
|
||||
fn the_gpu_the_compositor_draws_with_comes_before_the_panels() {
|
||||
const RTX_3050: (u32, u32) = (0x10de, 0x25ac);
|
||||
const INTEL_RPL: (u32, u32) = (0x8086, 0xa7a8);
|
||||
let mut c = vec![
|
||||
pci_gpu("NVIDIA GeForce RTX 3050 6GB Laptop GPU", Backend::Vulkan, DeviceType::DiscreteGpu, RTX_3050),
|
||||
pci_gpu("Intel(R) Graphics (RPL-P)", Backend::Vulkan, DeviceType::IntegratedGpu, INTEL_RPL),
|
||||
pci_gpu("NVIDIA GeForce RTX 3050 6GB Laptop GPU/PCIe/SSE2", Backend::Gl, DeviceType::Other, (RTX_3050.0, 0)),
|
||||
];
|
||||
c[2].presents = false;
|
||||
let panel = [primary(INTEL_RPL)];
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some(RTX_3050), None, &[]), [0, 1]);
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &panel, None, None, &[]), [1, 0]);
|
||||
// The usual hybrid laptop, with the compositor on the integrated GPU: the panel's GPU.
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &[primary(INTEL_RPL), monitor(RTX_3050)], Some(INTEL_RPL), None, &[]), [1, 0]);
|
||||
// `WGPU_ADAPTER_NAME` still comes first, and a restart after a failure still moves on.
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some(RTX_3050), Some("intel"), &[]), [1, 0]);
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some(RTX_3050), None, &[c[0].key.clone()]), [1]);
|
||||
// A compositor GPU no adapter matches (a virtual one) leaves the displays in charge.
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &panel, Some((0x1af4, 0x1050)), None, &[]), [1, 0]);
|
||||
}
|
||||
|
||||
/// A Windows desktop with a monitor on each GPU: the window opens on the primary display, so
|
||||
/// its GPU draws, whichever kind it is.
|
||||
#[test]
|
||||
fn the_primary_display_decides_between_gpus_that_both_drive_a_monitor() {
|
||||
let c = ryzen_desktop();
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[monitor(AMD_IGPU), primary(NVIDIA_3090)], None, None, &[]), [2, 0, 3, 1, 5, 4]);
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[primary(AMD_IGPU), monitor(NVIDIA_3090)], None, None, &[]), [3, 1, 2, 0, 5, 4]);
|
||||
// The displays only matter among adapters that can show the window; a GPU driving no
|
||||
// display still loses to one that does.
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[monitor(AMD_IGPU), monitor(INTEL_IGPU)], None, None, &[]), [3, 1, 2, 0, 5, 4]);
|
||||
}
|
||||
|
||||
/// Display GPUs none of the adapters match (another driver's ids, OpenGL's missing device id,
|
||||
/// Metal's zeros) change nothing: power saving's order, the old behaviour.
|
||||
#[test]
|
||||
fn displays_no_adapter_matches_leave_the_power_preference_in_charge() {
|
||||
let c = ryzen_desktop();
|
||||
let low = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]);
|
||||
for displays in [vec![monitor(INTEL_IGPU)], vec![primary((0x8086, 0x1234)), monitor((0x8086, 0x5678))], vec![primary((0, 0))]] {
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), low, "{displays:?}");
|
||||
}
|
||||
assert_eq!(
|
||||
names(&c, &adapter_order(&c, PowerPreference::HighPerformance, &[monitor(INTEL_IGPU)], None, None, &[]))[0],
|
||||
"NVIDIA GeForce RTX 3090"
|
||||
);
|
||||
// The #502 machine's adapters report no ids in these tests: the primary display never matches.
|
||||
let c = issue_502();
|
||||
assert_eq!(
|
||||
adapter_order(&c, PowerPreference::None, &[primary(NVIDIA_3090)], None, None, &[]),
|
||||
adapter_order(&c, PowerPreference::None, &[], None, None, &[])
|
||||
);
|
||||
assert!(adapter_order(&[], PowerPreference::LowPower, &[primary(NVIDIA_3090)], None, None, &[]).is_empty());
|
||||
}
|
||||
|
||||
/// `WGPU_ADAPTER_NAME` and "can't present" still come before the displays.
|
||||
#[test]
|
||||
fn a_named_adapter_comes_before_the_one_driving_the_display() {
|
||||
let mut c = ryzen_desktop();
|
||||
let displays = [primary(NVIDIA_3090)];
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, Some("radeon"), &[]), [3, 1, 2, 0, 5, 4]);
|
||||
c[2].presents = false;
|
||||
c[0].presents = false;
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &displays, None, None, &[]), [3, 1, 5, 4]);
|
||||
}
|
||||
|
||||
/// A user's own choice (Preferences or `WGPU_POWER_PREF`) is kept as it is; only Automatic
|
||||
/// looks at the displays.
|
||||
#[test]
|
||||
fn only_automatic_considers_which_gpu_drives_the_display() {
|
||||
assert!(automatic(None, None));
|
||||
assert!(automatic(Some("automatic"), None));
|
||||
assert!(automatic(Some("powerSaving"), None));
|
||||
assert!(!automatic(Some("lowPower"), None));
|
||||
assert!(!automatic(Some("highPerformance"), None));
|
||||
assert!(!automatic(None, Some(PowerPreference::None)));
|
||||
assert!(!automatic(Some("automatic"), Some(PowerPreference::LowPower)));
|
||||
assert!(preferred_displays(Some("lowPower"), None).is_empty());
|
||||
assert!(preferred_displays(None, Some(PowerPreference::HighPerformance)).is_empty());
|
||||
// Automatic reports whatever this machine has (nothing on macOS, in CI, or under Remote Desktop).
|
||||
assert_eq!(preferred_displays(None, None), display_gpus());
|
||||
assert_eq!(preferred_compositor(Some("lowPower"), None), None);
|
||||
assert_eq!(preferred_compositor(None, Some(PowerPreference::HighPerformance)), None);
|
||||
assert_eq!(preferred_compositor(None, None), crate::compositor_gpu::compositor_gpu());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pci_ids_come_from_windows_device_ids() {
|
||||
assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_2204&SUBSYS_40421458&REV_A1"), Some(NVIDIA_3090));
|
||||
assert_eq!(pci_ids("PCI\\VEN_1002&DEV_164E&SUBSYS_88771043&REV_C1"), Some(AMD_IGPU));
|
||||
assert_eq!(pci_ids("pci\\ven_1002&dev_164e"), Some(AMD_IGPU));
|
||||
// Remote Desktop and other non-PCI display devices, and malformed ids.
|
||||
assert_eq!(pci_ids("ROOT\\BasicDisplay\\0000"), None);
|
||||
assert_eq!(pci_ids("PCI\\VEN_10DE&SUBSYS_40421458"), None);
|
||||
assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_ZZZZ"), None);
|
||||
assert_eq!(pci_ids("VEN_&DEV_"), None);
|
||||
assert_eq!(pci_ids(""), None);
|
||||
}
|
||||
|
||||
/// Whatever this machine has: every GPU listed is a PCI device, at most one drives the primary
|
||||
/// display, and none is listed twice. (A headless CI runner may list none.)
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn windows_lists_each_gpu_with_a_monitor_once() {
|
||||
let gpus = windows_display_gpus();
|
||||
assert!(gpus.iter().filter(|g| g.primary).count() <= 1, "{gpus:?}");
|
||||
for (i, g) in gpus.iter().enumerate() {
|
||||
assert_ne!(g.pci.0, 0, "{gpus:?}");
|
||||
assert!(!gpus[..i].iter().any(|h| h.pci == g.pci), "{gpus:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internal_panels_are_edp_lvds_and_dsi_connectors() {
|
||||
for name in ["eDP-1", "LVDS-1", "DSI-1"] {
|
||||
assert!(is_internal_panel(name), "{name}");
|
||||
}
|
||||
for name in ["DP-3", "HDMI-A-1", "DVI-D-1", "VGA-1", "Writeback-1", ""] {
|
||||
assert!(!is_internal_panel(name), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A sysfs like a hybrid laptop's with an external monitor: the panel and a disconnected port
|
||||
/// on the integrated GPU (card0), the monitor on the discrete one (card1), and a card without
|
||||
/// PCI ids. Each GPU is listed once, the one with the panel as primary.
|
||||
#[test]
|
||||
fn linux_display_gpus_come_from_the_connected_connectors() -> std::io::Result<()> {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-drm-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let card = |name: &str, (vendor, device): (u32, u32)| -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir.join(name).join("device"))?;
|
||||
std::fs::write(dir.join(name).join("device/vendor"), format!("{vendor:#06x}\n"))?;
|
||||
std::fs::write(dir.join(name).join("device/device"), format!("{device:#06x}\n"))
|
||||
};
|
||||
let connector = |name: &str, status: &str| -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(dir.join(name))?;
|
||||
std::fs::write(dir.join(name).join("status"), format!("{status}\n"))
|
||||
};
|
||||
card("card0", AMD_IGPU)?;
|
||||
card("card1", NVIDIA_3090)?;
|
||||
std::fs::create_dir_all(dir.join("card2"))?;
|
||||
connector("card0-eDP-1", "connected")?;
|
||||
connector("card0-HDMI-A-1", "disconnected")?;
|
||||
connector("card1-DP-1", "connected")?;
|
||||
connector("card1-DP-2", "connected")?;
|
||||
connector("card2-Virtual-1", "connected")?;
|
||||
std::fs::write(dir.join("renderD128"), "")?;
|
||||
let mut gpus = linux_display_gpus(&dir);
|
||||
gpus.sort_by_key(|g| g.pci);
|
||||
assert_eq!(gpus, [primary(AMD_IGPU), monitor(NVIDIA_3090)]);
|
||||
assert!(linux_display_gpus(&dir.join("no such dir")).is_empty());
|
||||
std::fs::remove_dir_all(&dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_gpus_are_logged_as_pci_ids() {
|
||||
assert_eq!(primary(NVIDIA_3090).to_string(), "10de:2204 (primary)");
|
||||
assert_eq!(monitor(AMD_IGPU).to_string(), "1002:164e");
|
||||
let mut gpus = vec![];
|
||||
add_display_gpu(&mut gpus, NVIDIA_3090, false);
|
||||
add_display_gpu(&mut gpus, NVIDIA_3090, true);
|
||||
add_display_gpu(&mut gpus, AMD_IGPU, false);
|
||||
assert_eq!(gpus, [primary(NVIDIA_3090), monitor(AMD_IGPU)]);
|
||||
}
|
||||
|
||||
/// The machine of #502 as Vulkan lists it with Mesa's device-select layer: the GPU KDE's
|
||||
/// compositor runs on (NVIDIA) first, then the Ryzen's integrated GPU, Mesa's software
|
||||
/// renderer, and OpenGL.
|
||||
fn issue_502() -> Vec<Candidate> {
|
||||
vec![
|
||||
gpu("NVIDIA GeForce RTX 5070", Backend::Vulkan, DeviceType::DiscreteGpu),
|
||||
gpu("AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)", Backend::Vulkan, DeviceType::IntegratedGpu),
|
||||
gpu("llvmpipe (LLVM 20.1.8, 256 bits)", Backend::Vulkan, DeviceType::Cpu),
|
||||
gpu("NVIDIA GeForce RTX 5070/PCIe/SSE2", Backend::Gl, DeviceType::Other),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_keeps_the_systems_order_on_linux_and_saves_power_elsewhere() {
|
||||
let c = issue_502();
|
||||
let order = adapter_order(&c, power_preference(None, None), &[], None, None, &[]);
|
||||
let first = &c[order[0]].name;
|
||||
if cfg!(any(windows, target_os = "macos")) {
|
||||
assert_eq!(first, "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)");
|
||||
} else {
|
||||
// #502: the integrated GPU couldn't show frames to a compositor on the NVIDIA GPU.
|
||||
assert_eq!(first, "NVIDIA GeForce RTX 5070");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_preference_orders_the_adapters_then_falls_back_to_opengl_and_software() {
|
||||
let c = issue_502();
|
||||
let order = |power| names(&c, &adapter_order(&c, power, &[], None, None, &[]));
|
||||
assert_eq!(
|
||||
order(PowerPreference::None),
|
||||
[
|
||||
"NVIDIA GeForce RTX 5070",
|
||||
"AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)",
|
||||
"NVIDIA GeForce RTX 5070/PCIe/SSE2",
|
||||
"llvmpipe (LLVM 20.1.8, 256 bits)"
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
order(PowerPreference::LowPower),
|
||||
[
|
||||
"AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)",
|
||||
"NVIDIA GeForce RTX 5070",
|
||||
"NVIDIA GeForce RTX 5070/PCIe/SSE2",
|
||||
"llvmpipe (LLVM 20.1.8, 256 bits)"
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
order(PowerPreference::HighPerformance),
|
||||
[
|
||||
"NVIDIA GeForce RTX 5070",
|
||||
"AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)",
|
||||
"NVIDIA GeForce RTX 5070/PCIe/SSE2",
|
||||
"llvmpipe (LLVM 20.1.8, 256 bits)"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A restart leaves out the adapter the window failed on, so Power Saving on the machine of
|
||||
/// #502 ends up on the NVIDIA GPU, and once every adapter failed there is nothing to try.
|
||||
/// A dual-GPU Mac reports both GPUs under Metal with no PCI ids (#651): their keys still
|
||||
/// differ, so when the integrated GPU fails, the restart renders on the discrete one.
|
||||
#[test]
|
||||
fn gpus_without_pci_ids_are_told_apart_by_name() {
|
||||
let mac = |name: &str, device_type| Candidate {
|
||||
key: key(Backend::Metal, 0, 0, name),
|
||||
name: name.into(),
|
||||
backend: Backend::Metal,
|
||||
device_type,
|
||||
pci: (0, 0),
|
||||
presents: true,
|
||||
};
|
||||
let c = vec![mac("NVIDIA GeForce GT 750M", DeviceType::DiscreteGpu), mac("Intel Iris Pro Graphics", DeviceType::IntegratedGpu)];
|
||||
assert_eq!((c[0].key.as_str(), c[1].key.as_str()), ("Metal:NVIDIA GeForce GT 750M", "Metal:Intel Iris Pro Graphics"));
|
||||
let first = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]);
|
||||
assert_eq!(names(&c, &first)[0], "Intel Iris Pro Graphics");
|
||||
let skip = parse_skip(&c[first[0]].key);
|
||||
assert_eq!(names(&c, &adapter_order(&c, PowerPreference::LowPower, &[], None, None, &skip)), ["NVIDIA GeForce GT 750M"]);
|
||||
// A comma in a name can't split the list.
|
||||
assert_eq!(parse_skip(&key(Backend::Gl, 0, 0, "Mesa, llvmpipe")), ["Gl:Mesa llvmpipe"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_first_frame_that_never_reaches_the_screen_hangs_its_adapter() {
|
||||
let s = Duration::from_secs;
|
||||
// The second frame began: the first was presented.
|
||||
assert_eq!(first_frame(2, s(60), false), FirstFrame::Shown);
|
||||
// Still drawing (or presenting) the first frame: waited for, then given up on (#964).
|
||||
for frames in [0, 1] {
|
||||
assert_eq!(first_frame(frames, s(3), false), FirstFrame::Wait);
|
||||
assert_eq!(first_frame(frames, FIRST_FRAME_TIMEOUT, false), FirstFrame::Hung);
|
||||
}
|
||||
// A window minimized at the start may not draw again until restored.
|
||||
assert_eq!(first_frame(1, s(60), true), FirstFrame::Shown);
|
||||
// A hung adapter is left out once, like one that failed.
|
||||
let skip = vec!["Dx12:10de:28a0".to_string()];
|
||||
assert_eq!(restart_without(true, 1, Some("Dx12:10de:28a0"), &skip), None);
|
||||
assert_eq!(restart_without(true, 1, Some("Dx12:8086:a7a8"), &skip), Some("Dx12:8086:a7a8"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restart_tries_the_next_adapter() {
|
||||
let c = issue_502();
|
||||
let mut skip = vec![];
|
||||
let mut tried = vec![];
|
||||
while let Some(&i) = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &skip).first() {
|
||||
tried.push(c[i].name.clone());
|
||||
skip.push(c[i].key.clone());
|
||||
}
|
||||
assert_eq!(
|
||||
tried,
|
||||
[
|
||||
"AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)",
|
||||
"NVIDIA GeForce RTX 5070",
|
||||
"NVIDIA GeForce RTX 5070/PCIe/SSE2",
|
||||
"llvmpipe (LLVM 20.1.8, 256 bits)"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapters_that_cannot_present_to_the_window_are_never_tried() {
|
||||
let mut c = issue_502();
|
||||
c[0].presents = false;
|
||||
c[3].presents = false;
|
||||
for power in [PowerPreference::None, PowerPreference::LowPower, PowerPreference::HighPerformance] {
|
||||
let order = adapter_order(&c, power, &[], None, None, &[]);
|
||||
assert!(!order.contains(&0) && !order.contains(&3), "{power:?}: {order:?}");
|
||||
assert_eq!(order.len(), 2);
|
||||
}
|
||||
for p in &mut c {
|
||||
p.presents = false;
|
||||
}
|
||||
assert!(adapter_order(&c, PowerPreference::None, &[], None, None, &[]).is_empty());
|
||||
assert!(adapter_order(&[], PowerPreference::HighPerformance, &[], None, None, &[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wgpu_adapter_name_picks_an_adapter_first_and_the_rest_stay_as_fallbacks() {
|
||||
let c = issue_502();
|
||||
let order = adapter_order(&c, PowerPreference::HighPerformance, &[], None, Some("radv"), &[]);
|
||||
assert_eq!(c[order[0]].name, "AMD Ryzen 9 7900X (RADV RAPHAEL_MENDOCINO)");
|
||||
assert_eq!(order.len(), 4);
|
||||
// Any case; every match comes before the rest, natively first.
|
||||
let order = adapter_order(&c, PowerPreference::LowPower, &[], None, Some("GeForce"), &[]);
|
||||
assert_eq!(names(&c, &order[..2]), ["NVIDIA GeForce RTX 5070", "NVIDIA GeForce RTX 5070/PCIe/SSE2"]);
|
||||
// An empty name or one nothing matches changes nothing.
|
||||
for named in ["", "no such gpu"] {
|
||||
assert_eq!(
|
||||
adapter_order(&c, PowerPreference::LowPower, &[], None, Some(named), &[]),
|
||||
adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[])
|
||||
);
|
||||
}
|
||||
// A named adapter that failed is left out like any other.
|
||||
let skip = vec![c[1].key.clone()];
|
||||
assert_eq!(adapter_order(&c, PowerPreference::None, &[], None, Some("radv"), &skip)[0], 0);
|
||||
}
|
||||
|
||||
/// A Windows machine lists every GPU twice (Vulkan and DX12): power saving still takes the
|
||||
/// integrated GPU first, as wgpu's own choice did (#306), each GPU through DX12 first (#545).
|
||||
#[test]
|
||||
fn hybrid_laptop_on_windows_renders_on_the_integrated_gpu_with_power_saving() {
|
||||
let c = vec![
|
||||
gpu("Intel(R) Arc(TM) A370M", Backend::Vulkan, DeviceType::DiscreteGpu),
|
||||
gpu("Intel(R) Iris(R) Xe Graphics", Backend::Vulkan, DeviceType::IntegratedGpu),
|
||||
gpu("Intel(R) Arc(TM) A370M", Backend::Dx12, DeviceType::DiscreteGpu),
|
||||
gpu("Intel(R) Iris(R) Xe Graphics", Backend::Dx12, DeviceType::IntegratedGpu),
|
||||
gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu),
|
||||
];
|
||||
let order = adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[]);
|
||||
assert_eq!(order, [3, 1, 2, 0, 4]);
|
||||
assert_eq!(adapter_order(&c, PowerPreference::HighPerformance, &[], None, None, &[]), [2, 0, 3, 1, 4]);
|
||||
}
|
||||
|
||||
/// The machine of #545: one Intel GPU, whose Vulkan driver made the window flicker black.
|
||||
/// DX12 comes first whatever the preference; Vulkan stays a fallback, and `WGPU_ADAPTER_NAME`
|
||||
/// or a restart leaving DX12 out still reach it.
|
||||
#[test]
|
||||
fn a_windows_gpu_renders_through_dx12_before_vulkan() {
|
||||
let c = vec![
|
||||
gpu("Intel(R) Graphics", Backend::Vulkan, DeviceType::IntegratedGpu),
|
||||
gpu("Intel(R) Graphics", Backend::Dx12, DeviceType::IntegratedGpu),
|
||||
gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu),
|
||||
gpu("Intel(R) Graphics", Backend::Gl, DeviceType::Other),
|
||||
];
|
||||
for power in [PowerPreference::LowPower, PowerPreference::HighPerformance, PowerPreference::None] {
|
||||
assert_eq!(adapter_order(&c, power, &[], None, None, &[]), [1, 0, 3, 2], "{power:?}");
|
||||
}
|
||||
assert_eq!(adapter_order(&c, PowerPreference::LowPower, &[], None, None, &[c[1].key.clone()]), [0, 3, 2], "DX12 failed: Vulkan next");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_never_loads_vulkan_drivers_unless_asked() {
|
||||
let all = Backends::all();
|
||||
let start = backends(all, false);
|
||||
if cfg!(windows) {
|
||||
assert_eq!(start, Backends::DX12 | Backends::GL, "#806");
|
||||
} else {
|
||||
assert_eq!(start, all);
|
||||
}
|
||||
assert_eq!(backends(Backends::VULKAN, true), Backends::VULKAN, "WGPU_BACKEND=vulkan still picks it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn power_preference_follows_the_environment_then_the_preference() {
|
||||
assert_eq!(power_preference(None, None), AUTOMATIC);
|
||||
assert_eq!(power_preference(Some("automatic"), None), AUTOMATIC);
|
||||
assert_eq!(power_preference(Some("lowPower"), None), PowerPreference::LowPower);
|
||||
assert_eq!(power_preference(Some("highPerformance"), None), PowerPreference::HighPerformance);
|
||||
// 0.5.0's default, and values this version doesn't know (a newer or damaged file).
|
||||
for old in ["powerSaving", "turbo", ""] {
|
||||
assert_eq!(power_preference(Some(old), None), AUTOMATIC, "{old}");
|
||||
}
|
||||
// WGPU_POWER_PREF wins over the preference, either way.
|
||||
assert_eq!(power_preference(Some("lowPower"), Some(PowerPreference::HighPerformance)), PowerPreference::HighPerformance);
|
||||
assert_eq!(power_preference(Some("highPerformance"), Some(PowerPreference::LowPower)), PowerPreference::LowPower);
|
||||
assert_eq!(power_preference(Some("lowPower"), Some(PowerPreference::None)), PowerPreference::None);
|
||||
assert_eq!(AUTOMATIC, if cfg!(any(windows, target_os = "macos")) { PowerPreference::LowPower } else { PowerPreference::None });
|
||||
}
|
||||
|
||||
/// The preference the engine saves is the one the app reads back before the window opens.
|
||||
#[test]
|
||||
fn the_saved_engine_preference_is_found() {
|
||||
let mut prefs = vectorcraft_engine::Prefs::default();
|
||||
let saved = prefs.to_json();
|
||||
assert_eq!(saved.get("gpuPreference").and_then(serde_json::Value::as_str), Some("automatic"));
|
||||
for (value, power) in [("lowPower", PowerPreference::LowPower), ("highPerformance", PowerPreference::HighPerformance)] {
|
||||
prefs.gpu_preference = value.into();
|
||||
let saved = prefs.to_json();
|
||||
assert_eq!(power_preference(saved.get("gpuPreference").and_then(serde_json::Value::as_str), None), power);
|
||||
}
|
||||
// Every choice Preferences offer means something here.
|
||||
for (value, _) in vectorcraft_engine::cmd::prefscmds::GPU_PREFERENCES {
|
||||
assert!(["automatic", "lowPower", "highPerformance"].contains(value), "{value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skipped_adapters_parse_from_a_comma_separated_list() {
|
||||
assert_eq!(parse_skip("Vulkan:1002:164e, Gl:10de:2f04,,"), ["Vulkan:1002:164e", "Gl:10de:2f04"]);
|
||||
assert!(parse_skip("").is_empty());
|
||||
assert_eq!(key(Backend::Vulkan, 0x1002, 0x164e, "AMD Radeon"), "Vulkan:1002:164e");
|
||||
assert_eq!(key(Backend::Gl, 0x10de, 0x2f04, "NVIDIA"), "Gl:10de:2f04");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panics_in_wgpu_egui_wgpu_and_naga_are_graphics_failures() {
|
||||
for file in [
|
||||
"/home/u/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/egui-wgpu-0.36.2/src/winit.rs",
|
||||
r"C:\Users\u\.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\wgpu-core-30.0.1\src\device\mod.rs",
|
||||
"/rustc/deps/wgpu-hal-30.0.1/src/vulkan/adapter.rs",
|
||||
"naga-30.0.0/src/back/spv/writer.rs",
|
||||
] {
|
||||
assert!(in_graphics_stack(file), "{file}");
|
||||
}
|
||||
for file in
|
||||
["apps/vectorcraft/src/main.rs", "/home/wgpu/vectorcraft/crates/ui-egui/src/lib.rs", "egui-0.36.2/src/context.rs", "winit-0.30.12/src/x.rs"]
|
||||
{
|
||||
assert!(!in_graphics_stack(file), "{file}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_graphics_failure_while_starting_up_restarts_without_the_adapter() {
|
||||
let amd = Some("Vulkan:1002:164e");
|
||||
assert_eq!(restart_without(true, 0, amd, &[]), amd);
|
||||
assert_eq!(restart_without(true, STARTUP_FRAMES - 1, amd, &[]), amd);
|
||||
// After start-up the adapter has shown frames; a lost window is something else.
|
||||
assert_eq!(restart_without(true, STARTUP_FRAMES, amd, &[]), None);
|
||||
// A bug outside the graphics, or no adapter picked: nothing another adapter would change.
|
||||
assert_eq!(restart_without(false, 0, amd, &[]), None);
|
||||
assert_eq!(restart_without(true, 0, None, &[]), None);
|
||||
// Never the same adapter twice, so restarts end.
|
||||
assert_eq!(restart_without(true, 0, amd, &["Vulkan:1002:164e".into()]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_normal_exit_or_another_failure_does_not_restart() {
|
||||
let startup = Startup::default();
|
||||
assert_eq!(finish(Ok(Ok(())), &startup), Ok(()));
|
||||
// No adapter was picked (none can show the window): the error is returned, nothing restarts.
|
||||
let none = eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no graphics adapter can show the window".into()));
|
||||
assert_eq!(
|
||||
finish(Ok(Err(none)), &startup),
|
||||
Err(format!("WGPU error: Adapter selection failed: no graphics adapter can show the window ({HELP})"))
|
||||
);
|
||||
let _ = startup.adapter.set("Vulkan:1002:164e".into());
|
||||
GRAPHICS_PANIC.store(false, Ordering::Relaxed);
|
||||
assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into()));
|
||||
}
|
||||
|
||||
/// A log folder of its own for each test.
|
||||
fn start_dir(tag: &str) -> std::path::PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("vectorcraft-gpu-start-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
d
|
||||
}
|
||||
|
||||
/// What a start in `dir` leaves out; it then ends without crashing.
|
||||
fn next_start(dir: &std::path::Path, explicit: bool) -> LeftOut {
|
||||
let s = Startup::default();
|
||||
let left_out = s.track(dir, None, explicit);
|
||||
s.ended();
|
||||
left_out
|
||||
}
|
||||
|
||||
/// The machine of #2243: one Intel UHD Graphics 605, listed through DX12 and OpenGL, and
|
||||
/// Windows' software adapter.
|
||||
fn issue_2243() -> Vec<Candidate> {
|
||||
vec![
|
||||
pci_gpu("Intel(R) UHD Graphics 605", Backend::Dx12, DeviceType::IntegratedGpu, (0x8086, 0x3184)),
|
||||
pci_gpu("Microsoft Basic Render Driver", Backend::Dx12, DeviceType::Cpu, (0x1414, 0x008c)),
|
||||
pci_gpu("Intel(R) UHD Graphics 605", Backend::Gl, DeviceType::Other, (0x8086, 0)),
|
||||
]
|
||||
}
|
||||
|
||||
/// #2243: the driver ends the process after the adapter was picked, before the first frame.
|
||||
/// The next start leaves that adapter out and draws through OpenGL, and so do the starts after
|
||||
/// it, without a status-bar note.
|
||||
#[test]
|
||||
fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
|
||||
let dir = start_dir("crash");
|
||||
let c = issue_2243();
|
||||
let first = Startup::default();
|
||||
assert_eq!(first.track(&dir, None, false), LeftOut::default());
|
||||
first.picked(&c[0].key, &c[0].name, true);
|
||||
// The process ends here: its file is closed and unlocked, and the start is still recorded.
|
||||
drop(first);
|
||||
|
||||
let second = Startup::default();
|
||||
let left_out = second.track(&dir, Some("automatic"), false);
|
||||
assert_eq!(left_out.adapters, ["Dx12:8086:3184"]);
|
||||
assert_eq!(left_out.crash, Some(Crash::Adapter { key: "Dx12:8086:3184".into(), name: "Intel(R) UHD Graphics 605".into() }));
|
||||
assert!(!left_out.opengl_only);
|
||||
assert_eq!(left_out.backends(Backends::DX12 | Backends::GL), Backends::DX12 | Backends::GL);
|
||||
let order = adapter_order(&c, AUTOMATIC, &[], None, None, &left_out.adapters);
|
||||
assert_eq!(order, [2, 1], "OpenGL on the same GPU before the software adapter");
|
||||
second.picked(&c[2].key, &c[2].name, true);
|
||||
second.presented();
|
||||
|
||||
let third = Startup::default();
|
||||
let left_out = third.track(&dir, None, false);
|
||||
assert_eq!(left_out.adapters, ["Dx12:8086:3184"], "kept");
|
||||
assert_eq!(left_out.crash, None, "the note is shown once");
|
||||
third.ended();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A start whose first frame reached the screen, or that ended without crashing (a normal exit,
|
||||
/// an error, a restart on another adapter), leaves nothing out of the next.
|
||||
#[test]
|
||||
fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
|
||||
let dir = start_dir("shown");
|
||||
let c = issue_2243();
|
||||
for end in [Startup::presented as fn(&Startup), Startup::ended] {
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
first.picked(&c[0].key, &c[0].name, true);
|
||||
end(&first);
|
||||
drop(first);
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
}
|
||||
// So does a start that ended before it picked an adapter.
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
assert!(finish(Ok(Ok(())), &first).is_ok());
|
||||
drop(first);
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The process ended while the adapters were being listed (wgpu's DX12 backend creates a
|
||||
/// device on each GPU to list it): the next starts list OpenGL's adapters alone, except on
|
||||
/// macOS, where wgpu has none.
|
||||
#[test]
|
||||
fn a_crash_while_listing_lists_opengl_alone() {
|
||||
let dir = start_dir("listing");
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
drop(first);
|
||||
let second = Startup::default();
|
||||
let left_out = second.track(&dir, None, false);
|
||||
assert!(left_out.adapters.is_empty());
|
||||
if cfg!(target_os = "macos") {
|
||||
assert_eq!(left_out, LeftOut::default());
|
||||
} else {
|
||||
assert_eq!(left_out.crash, Some(Crash::Listing));
|
||||
assert_eq!(left_out.backends(Backends::DX12 | Backends::GL), Backends::GL);
|
||||
assert_eq!(left_out.backends(Backends::PRIMARY | Backends::GL), Backends::GL);
|
||||
assert_eq!(left_out.backends(Backends::METAL), Backends::METAL, "no OpenGL to fall back to");
|
||||
}
|
||||
// Listing OpenGL alone found nothing that can show the window: the next start lists every
|
||||
// backend again.
|
||||
second.none_left();
|
||||
second.ended();
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` choose for a start whatever crashed before; when that
|
||||
/// start shows its first frame on the adapter that crashed, the adapter counts again.
|
||||
#[test]
|
||||
fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
|
||||
let dir = start_dir("explicit");
|
||||
let c = issue_2243();
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
first.picked(&c[0].key, &c[0].name, true);
|
||||
drop(first);
|
||||
assert_eq!(next_start(&dir, true), LeftOut::default());
|
||||
assert_eq!(next_start(&dir, false).adapters, ["Dx12:8086:3184"], "still left out without them");
|
||||
|
||||
let explicit = Startup::default();
|
||||
explicit.track(&dir, None, true);
|
||||
explicit.picked(&c[0].key, &c[0].name, true);
|
||||
explicit.presented();
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default(), "a new driver shows the window");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A damaged record, a file that can't be opened and one another starting copy of the app holds
|
||||
/// are ignored: the start goes on with nothing left out.
|
||||
#[test]
|
||||
fn a_damaged_or_unreadable_start_file_is_ignored() {
|
||||
let dir = start_dir("damaged");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let damaged: [&[u8]; 9] = [
|
||||
b"",
|
||||
b"{",
|
||||
b"[]",
|
||||
b"null",
|
||||
b"{\"version\":1}",
|
||||
b"{\"starting\":{}}",
|
||||
b"\xef\xbb\xbf\0",
|
||||
b"\xff\xfe{",
|
||||
&[b' '; START_FILE_LIMIT as usize + 1],
|
||||
];
|
||||
for text in damaged {
|
||||
std::fs::write(dir.join(START_FILE), text).unwrap();
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default(), "{:?}", String::from_utf8_lossy(&text[..text.len().min(20)]));
|
||||
}
|
||||
|
||||
// Another copy of the app is starting: this start neither reads nor writes the file.
|
||||
let c = issue_2243();
|
||||
let starting = Startup::default();
|
||||
starting.track(&dir, None, false);
|
||||
starting.picked(&c[0].key, &c[0].name, true);
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
drop(starting);
|
||||
assert_eq!(next_start(&dir, false).adapters, ["Dx12:8086:3184"]);
|
||||
|
||||
// A folder in the file's place.
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join(START_FILE)).unwrap();
|
||||
assert_eq!(next_start(&dir, false), LeftOut::default());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crashes_are_forgotten_in_another_version_or_under_another_preference() {
|
||||
let starting = |key: &str| Starting { adapter: Some(Recorded { key: key.into(), name: "GPU".into() }), native: true };
|
||||
let (mut record, crash) = StartRecord::begin(None, "0.9.0", "automatic");
|
||||
assert_eq!(crash, None);
|
||||
record.starting = Some(starting("Dx12:8086:3184"));
|
||||
let (record, crash) = StartRecord::begin(Some(record), "0.9.0", "automatic");
|
||||
assert_eq!(crash, Some(Crash::Adapter { key: "Dx12:8086:3184".into(), name: "GPU".into() }));
|
||||
assert_eq!(record.left_out(None, false).adapters, ["Dx12:8086:3184"]);
|
||||
// Written and read back.
|
||||
assert_eq!(StartRecord::parse(&record.to_json()), Some(record.clone()));
|
||||
assert!(StartRecord::begin(Some(record.clone()), "0.9.1", "automatic").0.crashed.is_empty());
|
||||
assert!(StartRecord::begin(Some(record.clone()), "0.9.0", "highPerformance").0.crashed.is_empty());
|
||||
assert_eq!(preference_name(None), "automatic");
|
||||
assert_eq!(preference_name(Some("powerSaving")), "automatic");
|
||||
assert_eq!(preference_name(Some("lowPower")), "lowPower");
|
||||
// An adapter is listed once, and the list is bounded.
|
||||
let mut record = record;
|
||||
for n in 0..CRASHED_LIMIT + 4 {
|
||||
for _ in 0..2 {
|
||||
record.starting = Some(starting(&format!("Dx12:10de:{n:04x}")));
|
||||
record = StartRecord::begin(Some(record), "0.9.0", "automatic").0;
|
||||
}
|
||||
}
|
||||
assert_eq!(record.crashed.len(), CRASHED_LIMIT);
|
||||
assert_eq!(record.crashed.last().map(|c| c.key.as_str()), Some("Dx12:10de:0013"));
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
use super::*;
|
||||
|
||||
/// The window file dialogs belong to.
|
||||
pub(crate) type Parent = Option<std::sync::Arc<winit::window::Window>>;
|
||||
|
||||
/// What rfd's blocking and asynchronous file dialogs are both set up with.
|
||||
trait DialogSettings: Sized {
|
||||
fn parent(self, window: &winit::window::Window) -> Self;
|
||||
fn title(self, title: &str) -> Self;
|
||||
fn filter(self, name: &str, exts: &[impl ToString]) -> Self;
|
||||
fn folder(self, folder: &str) -> Self;
|
||||
fn file_name(self, name: &str) -> Self;
|
||||
}
|
||||
|
||||
macro_rules! dialog_settings {
|
||||
($($dialog:ty),*) => {$(
|
||||
impl DialogSettings for $dialog {
|
||||
fn parent(self, window: &winit::window::Window) -> Self {
|
||||
self.set_parent(window)
|
||||
}
|
||||
fn title(self, title: &str) -> Self {
|
||||
self.set_title(title)
|
||||
}
|
||||
fn filter(self, name: &str, exts: &[impl ToString]) -> Self {
|
||||
self.add_filter(name, exts)
|
||||
}
|
||||
fn folder(self, folder: &str) -> Self {
|
||||
self.set_directory(folder)
|
||||
}
|
||||
fn file_name(self, name: &str) -> Self {
|
||||
self.set_file_name(name)
|
||||
}
|
||||
}
|
||||
)*};
|
||||
}
|
||||
|
||||
dialog_settings!(rfd::FileDialog, rfd::AsyncFileDialog);
|
||||
|
||||
/// `d` set up for `request`: its title, file types, folder and suggested name.
|
||||
fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
let pick = match request {
|
||||
PickRequest::Open(pick) | PickRequest::Save(pick) => pick,
|
||||
PickRequest::OpenMany => {
|
||||
return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| {
|
||||
d.filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name), exts)
|
||||
});
|
||||
}
|
||||
PickRequest::Folder => return d,
|
||||
};
|
||||
let d = pick.filters.iter().fold(d, |d, (name, exts)| {
|
||||
d.filter(vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), exts)
|
||||
});
|
||||
let d = match &pick.folder {
|
||||
Some(folder) => d.folder(folder),
|
||||
None => d,
|
||||
};
|
||||
if pick.name.is_empty() { d } else { d.file_name(&pick.name) }
|
||||
}
|
||||
|
||||
/// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the
|
||||
/// window and keeps it in front).
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn file_dialog(request: &PickRequest, parent: &Parent) -> rfd::FileDialog {
|
||||
match parent {
|
||||
Some(w) => dialog_for(rfd::FileDialog::new().parent(w), request),
|
||||
None => dialog_for(rfd::FileDialog::new(), request),
|
||||
}
|
||||
}
|
||||
|
||||
/// Before `request`'s dialog shows: a save dialog's folder (the Templates folder) may not exist yet.
|
||||
fn make_folder(request: &PickRequest) {
|
||||
if let PickRequest::Save(FilePick { folder: Some(folder), .. }) = request {
|
||||
let _ = std::fs::create_dir_all(folder);
|
||||
}
|
||||
}
|
||||
|
||||
/// Show `dialog` for `request` (on the calling thread, until it closes) → the paths picked. On
|
||||
/// Linux and the BSDs a save dialog with two or more file types is the desktop portal's, over
|
||||
/// `parent`, and its answer also names the file type picked ([`portal_save`]); `dialog` shows when
|
||||
/// the portal can't.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[cfg_attr(windows, allow(unused_variables))]
|
||||
fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) -> Vec<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())
|
||||
{
|
||||
return answer;
|
||||
}
|
||||
let paths = match request {
|
||||
PickRequest::Open(_) => dialog.pick_file().into_iter().collect(),
|
||||
PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(),
|
||||
PickRequest::Save(_) => dialog.save_file().into_iter().collect(),
|
||||
PickRequest::Folder => dialog.pick_folder().into_iter().collect(),
|
||||
};
|
||||
paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect()
|
||||
}
|
||||
|
||||
/// Show the dialog for `request` over `parent` now → the paths picked.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn pick_now(request: PickRequest, parent: &Parent) -> Vec<String> {
|
||||
show_dialog(file_dialog(&request, parent), &request, parent)
|
||||
}
|
||||
|
||||
/// macOS shows no dialog in line: its modal loop would run inside winit's event handler, and an
|
||||
/// event winit held back meanwhile aborts the app (#867). Dialogs are sheets there ([`start_pick`]);
|
||||
/// one asked for any other way (a bug: outside a command, a dialog's OK or a button) picks nothing.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn pick_now(request: PickRequest, _parent: &Parent) -> Vec<String> {
|
||||
log::error!("no file dialog shown for {request:?}: macOS shows them as sheets, from commands, dialogs' OK and buttons only");
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// File → Show in Folder: select `path` in Finder / Explorer, or open its folder elsewhere.
|
||||
fn reveal(path: &str) -> Result<(), String> {
|
||||
explorer_safe(path)?;
|
||||
reveal_command(path).spawn().map(|_| ()).map_err(|e| format!("can't show {path}: {e}"))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn reveal_command(path: &str) -> std::process::Command {
|
||||
let mut c = std::process::Command::new("open");
|
||||
c.args(["-R", path]);
|
||||
c
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn reveal_command(path: &str) -> std::process::Command {
|
||||
use std::os::windows::process::CommandExt as _;
|
||||
// Explorer reads `/select,"path"` itself (the usual argument quoting breaks paths with spaces)
|
||||
// and needs backslashes.
|
||||
let mut c = std::process::Command::new("explorer");
|
||||
c.raw_arg(format!("/select,\"{}\"", path.replace('/', "\\")));
|
||||
c
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
fn reveal_command(path: &str) -> std::process::Command {
|
||||
let folder = std::path::Path::new(path).parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(std::path::Path::new("."));
|
||||
let mut c = std::process::Command::new("xdg-open");
|
||||
c.arg(folder);
|
||||
c
|
||||
}
|
||||
|
||||
/// Write a file the safe way: a failed write keeps the old file ([`fileio::write_atomic`]).
|
||||
fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
fileio::write_atomic(std::path::Path::new(path), bytes).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Linux: show the dialog for `request` over `parent` on a thread of its own, answering on the
|
||||
/// receiver. Shown on the UI thread, nothing would answer the compositor meanwhile, which then
|
||||
/// offers to kill the window as not responding (#592).
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Option<std::sync::mpsc::Receiver<Vec<String>>> {
|
||||
let dialog = file_dialog(&request, parent);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let ui = ui.clone();
|
||||
let parent = parent.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("file-dialog".into())
|
||||
.spawn(move || {
|
||||
// The app gone meanwhile has no use for the answer.
|
||||
let _ = tx.send(show_dialog(dialog, &request, &parent));
|
||||
ui.request_repaint();
|
||||
})
|
||||
.ok()?;
|
||||
Some(rx)
|
||||
}
|
||||
|
||||
/// The paths a dialog shown as a sheet picks, once it closes.
|
||||
#[cfg(target_os = "macos")]
|
||||
type SheetAnswer = std::pin::Pin<Box<dyn std::future::Future<Output = Vec<String>> + Send>>;
|
||||
|
||||
/// macOS: show the dialog for `request` as a sheet on `parent`'s window, answering on the receiver
|
||||
/// (#867). Shown in line, the panel ran AppKit's modal event loop inside winit's event handler: an
|
||||
/// event winit had held back meanwhile (one came as a resize of the panel ended) then re-entered
|
||||
/// the handler, and winit's panic there, inside an AppKit callback, aborted the app. The sheet
|
||||
/// returns at once and the window keeps running; a thread of its own waits for the answer.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Option<std::sync::mpsc::Receiver<Vec<String>>> {
|
||||
use winit::raw_window_handle::HasWindowHandle as _;
|
||||
// rfd runs the panel modally after all unless it has the running app's window to hold the
|
||||
// sheet (and from another thread it can't reach the window): no dialog then (`pick_now`).
|
||||
let mtm = objc2::MainThreadMarker::new();
|
||||
let running = mtm.is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isRunning());
|
||||
let Some(window) = parent.as_ref().filter(|w| running && w.window_handle().is_ok()) else {
|
||||
log::error!("no window to show the file dialog on (main thread: {}, running: {running})", mtm.is_some());
|
||||
return None;
|
||||
};
|
||||
// The thread first, so the answer of a sheet once shown always has somewhere to go.
|
||||
let (sheet_tx, sheet_rx) = std::sync::mpsc::channel::<SheetAnswer>();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let ui = ui.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("file-dialog".into())
|
||||
.spawn(move || {
|
||||
if let Ok(answer) = sheet_rx.recv() {
|
||||
// The app gone meanwhile has no use for the answer.
|
||||
let _ = tx.send(pollster::block_on(answer));
|
||||
ui.request_repaint();
|
||||
}
|
||||
})
|
||||
.ok()?;
|
||||
make_folder(&request);
|
||||
// The panel is built and the sheet is begun below, on the main thread (as it must).
|
||||
let dialog = dialog_for(rfd::AsyncFileDialog::new().parent(window), &request);
|
||||
let path = |f: &rfd::FileHandle| f.path().to_string_lossy().to_string();
|
||||
let answer: SheetAnswer = match request {
|
||||
PickRequest::Open(_) => {
|
||||
let picked = dialog.pick_file();
|
||||
Box::pin(async move { picked.await.iter().map(path).collect() })
|
||||
}
|
||||
PickRequest::OpenMany => {
|
||||
let picked = dialog.pick_files();
|
||||
Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() })
|
||||
}
|
||||
// A save panel with two or more named file types is built by `mac_save_format`, which sets
|
||||
// up its Format menu before the sheet begins (#866); rfd shows the others.
|
||||
PickRequest::Save(pick) => match mac_save_format::begin(window, &pick) {
|
||||
// The dialog thread blocks here until the sheet answers.
|
||||
Some(picked) => Box::pin(async move { picked.recv().unwrap_or_default() }),
|
||||
None => {
|
||||
// Nothing is added to the sheet once rfd has begun it: an accessory view set then
|
||||
// made recent macOS versions dismiss the sheet at once (#1800).
|
||||
let picked = dialog.save_file();
|
||||
Box::pin(async move { picked.await.iter().map(path).collect() })
|
||||
}
|
||||
},
|
||||
PickRequest::Folder => {
|
||||
let picked = dialog.pick_folder();
|
||||
Box::pin(async move { picked.await.iter().map(path).collect() })
|
||||
}
|
||||
};
|
||||
// The thread can't be gone: it waits for this. If it were, its receiver answers as cancelled.
|
||||
let _ = sheet_tx.send(answer);
|
||||
Some(rx)
|
||||
}
|
||||
|
||||
/// The host's services; `ui` is woken when a file dialog answers.
|
||||
pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
|
||||
use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle};
|
||||
let wayland = parent.as_ref().and_then(|w| w.window_handle().ok()).is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Wayland(_)));
|
||||
// A window on X11 (XWayland included) reads a tablet pen's pressure itself (#764).
|
||||
#[cfg(target_os = "linux")]
|
||||
let x11 = parent
|
||||
.as_ref()
|
||||
.and_then(|w| w.window_handle().ok())
|
||||
.is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
|
||||
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
|
||||
#[cfg(target_os = "macos")]
|
||||
let sampled_ui = ui.clone();
|
||||
Services {
|
||||
pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())),
|
||||
pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))),
|
||||
pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())),
|
||||
// Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows
|
||||
// dialogs run the window's events while they are open.
|
||||
start_pick: cfg!(unix).then(|| Box::new(move |request: PickRequest| start_pick(request, &p5, &ui)) as vectorcraft_ui_egui::picks::StartPick),
|
||||
dialogs_are_sheets: cfg!(target_os = "macos"),
|
||||
wayland,
|
||||
no_cursor_theme: wayland && cursor_theme::theme_missing(),
|
||||
#[cfg(target_os = "linux")]
|
||||
stylus: if x11 { tablet::start() } else { None },
|
||||
// macOS reads it from AppKit's events (#852).
|
||||
#[cfg(target_os = "macos")]
|
||||
stylus: mac_tablet::start(),
|
||||
// Windows reads it from the pen's pointer messages (`windows_stylus`).
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
stylus: Some(windows_stylus::start()),
|
||||
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
|
||||
write: Some(Box::new(write_file)),
|
||||
exists: Some(Box::new(|p: &str| std::path::Path::new(p).exists())),
|
||||
// Background Save and Export write from a worker thread.
|
||||
write_shared: Some(std::sync::Arc::new(write_file)),
|
||||
// Native saves stream into the file as they are encoded.
|
||||
stream_shared: Some(std::sync::Arc::new(|p: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| {
|
||||
fileio::write_file_with(p, fill).map_err(|e| e.to_string())
|
||||
})),
|
||||
// Every format Copy offers and Paste reads (menu-bar Paste never sees egui's Paste event).
|
||||
system_clipboard: Some(clipboard::system_clipboard()),
|
||||
// Linux checks whether Paste has something to take on a background thread: an X11 clipboard
|
||||
// owner that never answers holds a read for up to 4 s. Windows only asks which formats the
|
||||
// clipboard holds and macOS asks the pasteboard server, so they check in line.
|
||||
clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(clipboard::system_clipboard) as ClipboardProbeFactory),
|
||||
// Help → Discord / website / GitHub, the Discord button, About and Home links.
|
||||
open_url: Some(Box::new(|url: &str| {
|
||||
let _ = webbrowser::open(url);
|
||||
})),
|
||||
reveal: Some(Box::new(reveal)),
|
||||
// Links panel: Edit Original; Package: Show Package. Relink to Folder and Package pick folders.
|
||||
open_file: Some(Box::new(open_file)),
|
||||
pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())),
|
||||
// Sample Color from Screen: the system's color sampler.
|
||||
#[cfg(target_os = "macos")]
|
||||
screen_color: Some(mac_screen_color::sampler(sampled_ui)),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Windows passes `path` to Explorer inside quotes it adds itself, so a path holding a quote (which
|
||||
/// no Windows file name has) is refused rather than split into other arguments.
|
||||
fn explorer_safe(path: &str) -> Result<(), String> {
|
||||
if cfg!(windows) && path.contains('"') { Err(format!("can't open {path}: the path contains a quotation mark")) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// Edit Original, Show Package: open `path` (a file or a folder) in the system's default app for it.
|
||||
fn open_file(path: &str) -> Result<(), String> {
|
||||
explorer_safe(path)?;
|
||||
#[cfg(windows)]
|
||||
let mut c = {
|
||||
use std::os::windows::process::CommandExt as _;
|
||||
let mut c = std::process::Command::new("explorer");
|
||||
c.raw_arg(format!("\"{}\"", path.replace('/', "\\")));
|
||||
c
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
let mut c = std::process::Command::new("open");
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
let mut c = std::process::Command::new("xdg-open");
|
||||
#[cfg(not(windows))]
|
||||
c.arg(path);
|
||||
c.spawn().map(|_| ()).map_err(|e| format!("can't open {path}: {e}"))
|
||||
}
|
||||
@@ -296,309 +296,4 @@ pub fn install() -> Option<&'static AppLogger> {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let d = std::env::temp_dir().join(format!("vectorcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
d
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> String {
|
||||
std::fs::read_to_string(path).expect("read log")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_filter_shows_vectorcraft_info_and_other_crates_warnings() {
|
||||
let f = Filter::parse(DEFAULT_FILTER);
|
||||
assert_eq!(f.level_for("vectorcraft"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("vectorcraft::window"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("vectorcraft_engine::guard"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("vectorcraft_ui_egui::io"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("wgpu_core::device"), LevelFilter::Warn);
|
||||
assert_eq!(f.level_for("naga"), LevelFilter::Warn);
|
||||
assert_eq!(f.max(), LevelFilter::Info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directives_follow_env_logger_and_the_most_specific_one_wins() {
|
||||
let f = Filter::parse("info,wgpu_core=error,vectorcraft_render=trace,vectorcraft_render::tiles=off");
|
||||
assert_eq!(f.level_for("eframe"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("wgpu_core::instance"), LevelFilter::Error);
|
||||
assert_eq!(f.level_for("vectorcraft_render::canvas"), LevelFilter::Trace);
|
||||
assert_eq!(f.level_for("vectorcraft_render::tiles"), LevelFilter::Off);
|
||||
assert_eq!(f.max(), LevelFilter::Trace);
|
||||
// A module name is matched at `::` boundaries, not as a bare prefix.
|
||||
assert_eq!(f.level_for("wgpu_core_extra"), LevelFilter::Info);
|
||||
// A trailing `*` is a prefix.
|
||||
assert_eq!(Filter::parse("vectorcraft*=debug").level_for("vectorcraft_text::shape"), LevelFilter::Debug);
|
||||
assert_eq!(Filter::parse("vectorcraft*=debug").level_for("eframe"), LevelFilter::Error);
|
||||
// A bare target name sets that target to the most verbose level, as env_logger does.
|
||||
assert_eq!(Filter::parse("naga").level_for("naga::front"), LevelFilter::Trace);
|
||||
assert_eq!(Filter::parse("naga").level_for("eframe"), LevelFilter::Error);
|
||||
// Levels are case-insensitive and surrounding blanks are ignored.
|
||||
assert_eq!(Filter::parse(" WARN , vectorcraft = Debug ").level_for("vectorcraft"), LevelFilter::Debug);
|
||||
assert_eq!(Filter::parse(" WARN , vectorcraft = Debug ").level_for("eframe"), LevelFilter::Warn);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_specs_never_panic_and_fall_back_sensibly() {
|
||||
let long = "x".repeat(100_000);
|
||||
let many = "a=info,".repeat(10_000);
|
||||
for spec in [
|
||||
"",
|
||||
",,,",
|
||||
"=",
|
||||
"==",
|
||||
"=debug",
|
||||
"vectorcraft=",
|
||||
"nonsense=loud",
|
||||
"🦀=info",
|
||||
"*",
|
||||
"*=",
|
||||
"=*",
|
||||
"a=b=c",
|
||||
"warn,,vectorcraft=DEBUG",
|
||||
"\0",
|
||||
"é::ü=trace",
|
||||
&long,
|
||||
&many,
|
||||
] {
|
||||
let f = Filter::parse(spec);
|
||||
for target in ["", "vectorcraft", "🦀", "a::b", "*"] {
|
||||
let _ = f.level_for(target);
|
||||
}
|
||||
let _ = f.max();
|
||||
}
|
||||
assert_eq!(Filter::parse("warn,,vectorcraft=DEBUG").level_for("vectorcraft"), LevelFilter::Debug);
|
||||
// An unknown level is skipped: that target keeps the default.
|
||||
assert_eq!(Filter::parse("nonsense=loud").level_for("nonsense"), LevelFilter::Error);
|
||||
assert_eq!(Filter::parse("vectorcraft=").level_for("vectorcraft"), LevelFilter::Error);
|
||||
assert_eq!(Filter::parse("=debug").max(), LevelFilter::Error);
|
||||
assert_eq!(Filter::parse("🦀=info").level_for("🦀::claw"), LevelFilter::Info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timestamps_are_utc_with_milliseconds() {
|
||||
assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_791_446_357_728)), "2026-10-08T07:59:17.728Z");
|
||||
// Leap day, and the day after it.
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_199)), "2024-02-29T23:59:59.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_200)), "2024-03-01T00:00:00.000Z");
|
||||
// 2000 is a leap year (divisible by 400), 2100 is not.
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z");
|
||||
// Before the epoch (a clock set wrong) clamps instead of panicking.
|
||||
assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z");
|
||||
// Past chrono's year range still converts via the 400-year cycle (the old code did too,
|
||||
// through `civil_from_days`): never a silent reset to the epoch. Platform-safe: Windows'
|
||||
// SystemTime can't hold this instant, so it is only checked where it exists.
|
||||
// `u64::MAX / 2` seconds == `i64::MAX` seconds → year 292277026596 (old output).
|
||||
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) {
|
||||
assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z");
|
||||
}
|
||||
// Years past 9999 keep the plain zero-padded year (no `+`).
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z");
|
||||
// 10_000_000_000_000 s is far beyond chrono's range; old output is year 318857.
|
||||
// Windows' SystemTime holds only up to about year 30828, so this is checked where it fits.
|
||||
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) {
|
||||
assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_carries_time_level_thread_target_and_message() {
|
||||
assert_eq!(
|
||||
format_line("2026-10-08T07:59:17.728Z", log::Level::Info, "main", "vectorcraft", "rendering with Mesa (Vulkan, IntegratedGpu)"),
|
||||
"2026-10-08T07:59:17.728Z INFO [main] vectorcraft: rendering with Mesa (Vulkan, IntegratedGpu)\n"
|
||||
);
|
||||
// A multi-line message keeps its lines; the record still ends in one newline.
|
||||
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() {
|
||||
let dir = temp_dir("rotate");
|
||||
for run in 1..=4 {
|
||||
let (path, _file) = rotate(&dir).expect("rotate");
|
||||
assert_eq!(path, dir.join(LOG_FILE));
|
||||
assert_eq!(read(&path), "");
|
||||
std::fs::write(&path, format!("run {run}")).expect("write");
|
||||
}
|
||||
assert_eq!(read(&dir.join(LOG_FILE)), "run 4");
|
||||
assert_eq!(read(&dir.join("vectorcraft.1.log")), "run 3");
|
||||
assert_eq!(read(&dir.join("vectorcraft.2.log")), "run 2");
|
||||
assert!(!dir.join("vectorcraft.3.log").exists(), "only {KEEP} old logs are kept");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() {
|
||||
let dir = temp_dir("blocked");
|
||||
std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp");
|
||||
std::fs::write(&dir, "a file where the directory should be").expect("block");
|
||||
assert!(rotate(&dir).is_err());
|
||||
let _ = std::fs::remove_file(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() {
|
||||
let dir = temp_dir("pending");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
sink.write("early 1\n");
|
||||
sink.write("early 2\n");
|
||||
sink.attach(file);
|
||||
sink.write("late\n");
|
||||
assert_eq!(read(&path), "early 1\nearly 2\nlate\n");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() {
|
||||
let dir = temp_dir("bounded");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
for i in 0..MAX_PENDING + 5 {
|
||||
sink.write(&format!("line {i}\n"));
|
||||
}
|
||||
sink.attach(file);
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), MAX_PENDING);
|
||||
assert!(text.contains("5 earlier log lines were dropped"), "{text}");
|
||||
assert!(text.contains("line 0\n") && !text.contains(&format!("line {MAX_PENDING}\n")));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exactly_a_full_pending_buffer_drops_nothing() {
|
||||
let dir = temp_dir("full");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
for i in 0..MAX_PENDING {
|
||||
sink.write(&format!("line {i}\n"));
|
||||
}
|
||||
sink.attach(file);
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().count(), MAX_PENDING);
|
||||
assert!(!text.contains("dropped"), "{text}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_file_nothing_is_kept_in_memory() {
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
sink.write("early\n");
|
||||
sink.no_file();
|
||||
sink.write("late\n");
|
||||
assert!(sink.pending.is_empty() && sink.dropped == 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_stops_at_its_size_cap_with_one_note() {
|
||||
let dir = temp_dir("cap");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(100);
|
||||
sink.attach(file);
|
||||
for i in 0..50 {
|
||||
sink.write(&format!("line {i:02} with some padding\n"));
|
||||
}
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), 3, "{text}");
|
||||
assert_eq!(text.matches("log file reached").count(), 1, "{text}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_logger_filters_records_and_writes_them_to_the_attached_file() {
|
||||
use log::Log;
|
||||
let dir = temp_dir("logger");
|
||||
let logger = AppLogger::new(Filter::parse(DEFAULT_FILTER), false);
|
||||
let record = |level, target: &'static str, msg: &'static str| {
|
||||
logger.log(&log::Record::builder().level(level).target(target).args(format_args!("{msg}")).build());
|
||||
};
|
||||
record(log::Level::Info, "vectorcraft", "before the settings directory");
|
||||
record(log::Level::Info, "wgpu_core::device", "too chatty");
|
||||
let path = logger.attach_dir(&dir).expect("attach");
|
||||
assert_eq!(path, dir.join(LOG_FILE));
|
||||
record(log::Level::Warn, "wgpu_hal::vulkan", "a real warning");
|
||||
record(log::Level::Error, "vectorcraft_engine::guard", "recovered from a panic: boom");
|
||||
record(log::Level::Debug, "vectorcraft", "below info");
|
||||
let text = read(&path);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 3, "{text}");
|
||||
assert!(lines[0].contains(" INFO [") && lines[0].ends_with("vectorcraft: before the settings directory"), "{text}");
|
||||
assert!(lines[1].ends_with("wgpu_hal::vulkan: a real warning"), "{text}");
|
||||
assert!(lines[2].contains(" ERROR [") && lines[2].ends_with("vectorcraft_engine::guard: recovered from a panic: boom"), "{text}");
|
||||
assert!(logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("vectorcraft_ui_egui").build()));
|
||||
assert!(!logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("naga").build()));
|
||||
// Attaching again rotates: the first log becomes `.1`.
|
||||
logger.attach_dir(&dir).expect("attach again");
|
||||
assert_eq!(read(&dir.join("vectorcraft.1.log")), text);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn records_from_many_threads_are_whole_lines() {
|
||||
use log::Log;
|
||||
let dir = temp_dir("threads");
|
||||
let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false));
|
||||
let path = logger.attach_dir(&dir).expect("attach");
|
||||
let workers: Vec<_> = (0..8)
|
||||
.map(|t| {
|
||||
let l = std::sync::Arc::clone(&logger);
|
||||
std::thread::spawn(move || {
|
||||
for i in 0..100 {
|
||||
l.log(
|
||||
&log::Record::builder().level(log::Level::Info).target("vectorcraft").args(format_args!("thread {t} record {i}")).build(),
|
||||
);
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for w in workers {
|
||||
w.join().expect("worker");
|
||||
}
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().count(), 800);
|
||||
assert!(text.lines().all(|l| l.contains(" vectorcraft: thread ")), "{text}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attaching_to_an_unusable_directory_reports_an_error_and_keeps_logging() {
|
||||
use log::Log;
|
||||
let dir = temp_dir("unusable");
|
||||
std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp");
|
||||
std::fs::write(&dir, "not a directory").expect("block");
|
||||
let logger = AppLogger::new(Filter::parse("info"), false);
|
||||
assert!(logger.attach_dir(&dir).is_err());
|
||||
logger.log(&log::Record::builder().level(log::Level::Error).target("x").args(format_args!("still fine")).build());
|
||||
// Nothing waits in memory for a file that won't come.
|
||||
assert!(logger.sink.lock().expect("sink").pending.is_empty());
|
||||
let _ = std::fs::remove_file(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_poisoned_sink_still_logs() {
|
||||
use log::Log;
|
||||
let dir = temp_dir("poison");
|
||||
let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false));
|
||||
let l = std::sync::Arc::clone(&logger);
|
||||
let _ = std::thread::spawn(move || {
|
||||
let _guard = l.sink.lock().expect("lock");
|
||||
panic!("poison the sink");
|
||||
})
|
||||
.join();
|
||||
assert!(logger.sink.is_poisoned());
|
||||
let path = logger.attach_dir(&dir).expect("attach");
|
||||
logger.log(&log::Record::builder().level(log::Level::Warn).target("vectorcraft").args(format_args!("after the poison")).build());
|
||||
assert!(read(&path).contains("vectorcraft: after the poison"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,302 @@
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
fn temp_dir(tag: &str) -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
let d = std::env::temp_dir().join(format!("vectorcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
d
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> String {
|
||||
std::fs::read_to_string(path).expect("read log")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_filter_shows_vectorcraft_info_and_other_crates_warnings() {
|
||||
let f = Filter::parse(DEFAULT_FILTER);
|
||||
assert_eq!(f.level_for("vectorcraft"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("vectorcraft::window"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("vectorcraft_engine::guard"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("vectorcraft_ui_egui::io"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("wgpu_core::device"), LevelFilter::Warn);
|
||||
assert_eq!(f.level_for("naga"), LevelFilter::Warn);
|
||||
assert_eq!(f.max(), LevelFilter::Info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directives_follow_env_logger_and_the_most_specific_one_wins() {
|
||||
let f = Filter::parse("info,wgpu_core=error,vectorcraft_render=trace,vectorcraft_render::tiles=off");
|
||||
assert_eq!(f.level_for("eframe"), LevelFilter::Info);
|
||||
assert_eq!(f.level_for("wgpu_core::instance"), LevelFilter::Error);
|
||||
assert_eq!(f.level_for("vectorcraft_render::canvas"), LevelFilter::Trace);
|
||||
assert_eq!(f.level_for("vectorcraft_render::tiles"), LevelFilter::Off);
|
||||
assert_eq!(f.max(), LevelFilter::Trace);
|
||||
// A module name is matched at `::` boundaries, not as a bare prefix.
|
||||
assert_eq!(f.level_for("wgpu_core_extra"), LevelFilter::Info);
|
||||
// A trailing `*` is a prefix.
|
||||
assert_eq!(Filter::parse("vectorcraft*=debug").level_for("vectorcraft_text::shape"), LevelFilter::Debug);
|
||||
assert_eq!(Filter::parse("vectorcraft*=debug").level_for("eframe"), LevelFilter::Error);
|
||||
// A bare target name sets that target to the most verbose level, as env_logger does.
|
||||
assert_eq!(Filter::parse("naga").level_for("naga::front"), LevelFilter::Trace);
|
||||
assert_eq!(Filter::parse("naga").level_for("eframe"), LevelFilter::Error);
|
||||
// Levels are case-insensitive and surrounding blanks are ignored.
|
||||
assert_eq!(Filter::parse(" WARN , vectorcraft = Debug ").level_for("vectorcraft"), LevelFilter::Debug);
|
||||
assert_eq!(Filter::parse(" WARN , vectorcraft = Debug ").level_for("eframe"), LevelFilter::Warn);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_specs_never_panic_and_fall_back_sensibly() {
|
||||
let long = "x".repeat(100_000);
|
||||
let many = "a=info,".repeat(10_000);
|
||||
for spec in [
|
||||
"",
|
||||
",,,",
|
||||
"=",
|
||||
"==",
|
||||
"=debug",
|
||||
"vectorcraft=",
|
||||
"nonsense=loud",
|
||||
"🦀=info",
|
||||
"*",
|
||||
"*=",
|
||||
"=*",
|
||||
"a=b=c",
|
||||
"warn,,vectorcraft=DEBUG",
|
||||
"\0",
|
||||
"é::ü=trace",
|
||||
&long,
|
||||
&many,
|
||||
] {
|
||||
let f = Filter::parse(spec);
|
||||
for target in ["", "vectorcraft", "🦀", "a::b", "*"] {
|
||||
let _ = f.level_for(target);
|
||||
}
|
||||
let _ = f.max();
|
||||
}
|
||||
assert_eq!(Filter::parse("warn,,vectorcraft=DEBUG").level_for("vectorcraft"), LevelFilter::Debug);
|
||||
// An unknown level is skipped: that target keeps the default.
|
||||
assert_eq!(Filter::parse("nonsense=loud").level_for("nonsense"), LevelFilter::Error);
|
||||
assert_eq!(Filter::parse("vectorcraft=").level_for("vectorcraft"), LevelFilter::Error);
|
||||
assert_eq!(Filter::parse("=debug").max(), LevelFilter::Error);
|
||||
assert_eq!(Filter::parse("🦀=info").level_for("🦀::claw"), LevelFilter::Info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timestamps_are_utc_with_milliseconds() {
|
||||
assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_791_446_357_728)), "2026-10-08T07:59:17.728Z");
|
||||
// Leap day, and the day after it.
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_199)), "2024-02-29T23:59:59.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_200)), "2024-03-01T00:00:00.000Z");
|
||||
// 2000 is a leap year (divisible by 400), 2100 is not.
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z");
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z");
|
||||
// Before the epoch (a clock set wrong) clamps instead of panicking.
|
||||
assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z");
|
||||
// Past chrono's year range still converts via the 400-year cycle (the old code did too,
|
||||
// through `civil_from_days`): never a silent reset to the epoch. Platform-safe: Windows'
|
||||
// SystemTime can't hold this instant, so it is only checked where it exists.
|
||||
// `u64::MAX / 2` seconds == `i64::MAX` seconds → year 292277026596 (old output).
|
||||
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) {
|
||||
assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z");
|
||||
}
|
||||
// Years past 9999 keep the plain zero-padded year (no `+`).
|
||||
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z");
|
||||
// 10_000_000_000_000 s is far beyond chrono's range; old output is year 318857.
|
||||
// Windows' SystemTime holds only up to about year 30828, so this is checked where it fits.
|
||||
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) {
|
||||
assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_carries_time_level_thread_target_and_message() {
|
||||
assert_eq!(
|
||||
format_line("2026-10-08T07:59:17.728Z", log::Level::Info, "main", "vectorcraft", "rendering with Mesa (Vulkan, IntegratedGpu)"),
|
||||
"2026-10-08T07:59:17.728Z INFO [main] vectorcraft: rendering with Mesa (Vulkan, IntegratedGpu)\n"
|
||||
);
|
||||
// A multi-line message keeps its lines; the record still ends in one newline.
|
||||
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() {
|
||||
let dir = temp_dir("rotate");
|
||||
for run in 1..=4 {
|
||||
let (path, _file) = rotate(&dir).expect("rotate");
|
||||
assert_eq!(path, dir.join(LOG_FILE));
|
||||
assert_eq!(read(&path), "");
|
||||
std::fs::write(&path, format!("run {run}")).expect("write");
|
||||
}
|
||||
assert_eq!(read(&dir.join(LOG_FILE)), "run 4");
|
||||
assert_eq!(read(&dir.join("vectorcraft.1.log")), "run 3");
|
||||
assert_eq!(read(&dir.join("vectorcraft.2.log")), "run 2");
|
||||
assert!(!dir.join("vectorcraft.3.log").exists(), "only {KEEP} old logs are kept");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() {
|
||||
let dir = temp_dir("blocked");
|
||||
std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp");
|
||||
std::fs::write(&dir, "a file where the directory should be").expect("block");
|
||||
assert!(rotate(&dir).is_err());
|
||||
let _ = std::fs::remove_file(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() {
|
||||
let dir = temp_dir("pending");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
sink.write("early 1\n");
|
||||
sink.write("early 2\n");
|
||||
sink.attach(file);
|
||||
sink.write("late\n");
|
||||
assert_eq!(read(&path), "early 1\nearly 2\nlate\n");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() {
|
||||
let dir = temp_dir("bounded");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
for i in 0..MAX_PENDING + 5 {
|
||||
sink.write(&format!("line {i}\n"));
|
||||
}
|
||||
sink.attach(file);
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), MAX_PENDING);
|
||||
assert!(text.contains("5 earlier log lines were dropped"), "{text}");
|
||||
assert!(text.contains("line 0\n") && !text.contains(&format!("line {MAX_PENDING}\n")));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exactly_a_full_pending_buffer_drops_nothing() {
|
||||
let dir = temp_dir("full");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
for i in 0..MAX_PENDING {
|
||||
sink.write(&format!("line {i}\n"));
|
||||
}
|
||||
sink.attach(file);
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().count(), MAX_PENDING);
|
||||
assert!(!text.contains("dropped"), "{text}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_file_nothing_is_kept_in_memory() {
|
||||
let mut sink = Sink::new(MAX_FILE_BYTES);
|
||||
sink.write("early\n");
|
||||
sink.no_file();
|
||||
sink.write("late\n");
|
||||
assert!(sink.pending.is_empty() && sink.dropped == 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_stops_at_its_size_cap_with_one_note() {
|
||||
let dir = temp_dir("cap");
|
||||
let (path, file) = rotate(&dir).expect("rotate");
|
||||
let mut sink = Sink::new(100);
|
||||
sink.attach(file);
|
||||
for i in 0..50 {
|
||||
sink.write(&format!("line {i:02} with some padding\n"));
|
||||
}
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), 3, "{text}");
|
||||
assert_eq!(text.matches("log file reached").count(), 1, "{text}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_logger_filters_records_and_writes_them_to_the_attached_file() {
|
||||
use log::Log;
|
||||
let dir = temp_dir("logger");
|
||||
let logger = AppLogger::new(Filter::parse(DEFAULT_FILTER), false);
|
||||
let record = |level, target: &'static str, msg: &'static str| {
|
||||
logger.log(&log::Record::builder().level(level).target(target).args(format_args!("{msg}")).build());
|
||||
};
|
||||
record(log::Level::Info, "vectorcraft", "before the settings directory");
|
||||
record(log::Level::Info, "wgpu_core::device", "too chatty");
|
||||
let path = logger.attach_dir(&dir).expect("attach");
|
||||
assert_eq!(path, dir.join(LOG_FILE));
|
||||
record(log::Level::Warn, "wgpu_hal::vulkan", "a real warning");
|
||||
record(log::Level::Error, "vectorcraft_engine::guard", "recovered from a panic: boom");
|
||||
record(log::Level::Debug, "vectorcraft", "below info");
|
||||
let text = read(&path);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 3, "{text}");
|
||||
assert!(lines[0].contains(" INFO [") && lines[0].ends_with("vectorcraft: before the settings directory"), "{text}");
|
||||
assert!(lines[1].ends_with("wgpu_hal::vulkan: a real warning"), "{text}");
|
||||
assert!(lines[2].contains(" ERROR [") && lines[2].ends_with("vectorcraft_engine::guard: recovered from a panic: boom"), "{text}");
|
||||
assert!(logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("vectorcraft_ui_egui").build()));
|
||||
assert!(!logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("naga").build()));
|
||||
// Attaching again rotates: the first log becomes `.1`.
|
||||
logger.attach_dir(&dir).expect("attach again");
|
||||
assert_eq!(read(&dir.join("vectorcraft.1.log")), text);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn records_from_many_threads_are_whole_lines() {
|
||||
use log::Log;
|
||||
let dir = temp_dir("threads");
|
||||
let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false));
|
||||
let path = logger.attach_dir(&dir).expect("attach");
|
||||
let workers: Vec<_> = (0..8)
|
||||
.map(|t| {
|
||||
let l = std::sync::Arc::clone(&logger);
|
||||
std::thread::spawn(move || {
|
||||
for i in 0..100 {
|
||||
l.log(&log::Record::builder().level(log::Level::Info).target("vectorcraft").args(format_args!("thread {t} record {i}")).build());
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for w in workers {
|
||||
w.join().expect("worker");
|
||||
}
|
||||
let text = read(&path);
|
||||
assert_eq!(text.lines().count(), 800);
|
||||
assert!(text.lines().all(|l| l.contains(" vectorcraft: thread ")), "{text}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attaching_to_an_unusable_directory_reports_an_error_and_keeps_logging() {
|
||||
use log::Log;
|
||||
let dir = temp_dir("unusable");
|
||||
std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp");
|
||||
std::fs::write(&dir, "not a directory").expect("block");
|
||||
let logger = AppLogger::new(Filter::parse("info"), false);
|
||||
assert!(logger.attach_dir(&dir).is_err());
|
||||
logger.log(&log::Record::builder().level(log::Level::Error).target("x").args(format_args!("still fine")).build());
|
||||
// Nothing waits in memory for a file that won't come.
|
||||
assert!(logger.sink.lock().expect("sink").pending.is_empty());
|
||||
let _ = std::fs::remove_file(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_poisoned_sink_still_logs() {
|
||||
use log::Log;
|
||||
let dir = temp_dir("poison");
|
||||
let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false));
|
||||
let l = std::sync::Arc::clone(&logger);
|
||||
let _ = std::thread::spawn(move || {
|
||||
let _guard = l.sink.lock().expect("lock");
|
||||
panic!("poison the sink");
|
||||
})
|
||||
.join();
|
||||
assert!(logger.sink.is_poisoned());
|
||||
let path = logger.attach_dir(&dir).expect("attach");
|
||||
logger.log(&log::Record::builder().level(log::Level::Warn).target("vectorcraft").args(format_args!("after the poison")).build());
|
||||
assert!(read(&path).contains("vectorcraft: after the poison"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
+40
-978
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,107 @@
|
||||
use super::*;
|
||||
|
||||
/// Where UI preferences live: ~/Library/Application Support/VectorCraft (macOS),
|
||||
/// %APPDATA%\VectorCraft (Windows), $XDG_CONFIG_HOME or ~/.config/vectorcraft (Linux).
|
||||
pub(crate) fn prefs_path() -> Option<std::path::PathBuf> {
|
||||
prefs_dir::prefs_path_for("VectorCraft", "vectorcraft")
|
||||
}
|
||||
|
||||
/// The same place under the project's former name (DrawCraft): read once if there are no
|
||||
/// VectorCraft preferences yet, so settings survive the rename.
|
||||
fn legacy_prefs_path() -> Option<std::path::PathBuf> {
|
||||
prefs_dir::prefs_path_for("DrawCraft", "drawcraft")
|
||||
}
|
||||
|
||||
/// Where the log files live: `logs` in the preferences folder (see `logging`).
|
||||
pub(crate) fn log_dir() -> Option<std::path::PathBuf> {
|
||||
Some(prefs_path()?.parent()?.join("logs"))
|
||||
}
|
||||
|
||||
/// Runs without preferences (`VECTORCRAFT_NO_PREFS`, agents' test runs) neither read nor write them.
|
||||
pub(crate) fn prefs_enabled() -> bool {
|
||||
std::env::var_os("VECTORCRAFT_NO_PREFS").is_none()
|
||||
}
|
||||
|
||||
/// The saved UI preferences, read before the window opens (they hold its size and position).
|
||||
/// A file read only in part, or with layouts converted from an older version, is copied beside
|
||||
/// itself before anything saves over it.
|
||||
pub(crate) fn read_prefs() -> Option<vectorcraft_ui_egui::UiState> {
|
||||
if !prefs_enabled() {
|
||||
return None;
|
||||
}
|
||||
if let Some(p) = prefs_path()
|
||||
&& let Ok(bytes) = std::fs::read(&p)
|
||||
{
|
||||
let read = vectorcraft_ui_egui::UiState::read_preferences(&bytes);
|
||||
if read.as_ref().is_none_or(|read| !read.intact) {
|
||||
keep_prefs_copy(&p, &bytes, "ui.unreadable");
|
||||
}
|
||||
if read.as_ref().is_some_and(|read| read.converted) {
|
||||
keep_prefs_copy(&p, &bytes, "ui.before-layout-migration");
|
||||
}
|
||||
return read.map(|read| read.ui);
|
||||
}
|
||||
let bytes = legacy_prefs_path().and_then(|p| std::fs::read(p).ok())?;
|
||||
decode_saved_prefs(&bytes)
|
||||
}
|
||||
|
||||
/// Saved preferences, with what this version cannot read of their docking data dropped and
|
||||
/// older layouts converted (`vectorcraft_ui_egui::layout_migration`).
|
||||
pub(crate) fn decode_saved_prefs(bytes: &[u8]) -> Option<vectorcraft_ui_egui::UiState> {
|
||||
vectorcraft_ui_egui::UiState::read_preferences(bytes).map(|read| read.ui)
|
||||
}
|
||||
|
||||
/// Set when `ui.json` needed a copy kept ([`keep_prefs_copy`]) and none could be: the file is
|
||||
/// then left as it is rather than overwritten.
|
||||
pub(crate) static KEEP_UI_PREFS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
/// Copy `ui.json` beside it as `<stem>.json` or the first free `<stem>-N.json`, before the next
|
||||
/// save replaces it: `ui.unreadable` when it could not be read in full (a newer VectorCraft may
|
||||
/// have written it), `ui.before-layout-migration` when its layouts were converted.
|
||||
pub(crate) fn keep_prefs_copy(path: &std::path::Path, bytes: &[u8], stem: &str) {
|
||||
use std::io::Write as _;
|
||||
for n in 1..100u32 {
|
||||
let name = if n == 1 { format!("{stem}.json") } else { format!("{stem}-{n}.json") };
|
||||
match std::fs::OpenOptions::new().write(true).create_new(true).open(path.with_file_name(name)) {
|
||||
Ok(mut file) => {
|
||||
if file.write_all(bytes).is_ok() {
|
||||
return;
|
||||
}
|
||||
break;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
KEEP_UI_PREFS.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn load_prefs(app: &mut VectorcraftApp, saved: Option<vectorcraft_ui_egui::UiState>) {
|
||||
if !prefs_enabled() {
|
||||
return;
|
||||
}
|
||||
if let Some(ui) = saved {
|
||||
app.ui = ui.sanitized();
|
||||
}
|
||||
vectorcraft_ui_egui::prefs_dialog::restore(app);
|
||||
}
|
||||
|
||||
pub(crate) fn save_prefs(app: &VectorcraftApp) {
|
||||
if !prefs_enabled() || KEEP_UI_PREFS.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
if let Some(p) = prefs_path() {
|
||||
let _ = std::fs::create_dir_all(p.parent().unwrap_or(std::path::Path::new(".")));
|
||||
if let Ok(bytes) = prefs_bytes(app) {
|
||||
// Preferences are best effort: a failed write keeps the previous file.
|
||||
let _ = fileio::write_atomic(&p, &bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The preferences file's contents: the UI state with the engine preferences.
|
||||
pub(crate) fn prefs_bytes(app: &VectorcraftApp) -> serde_json::Result<Vec<u8>> {
|
||||
let mut ui = app.ui.clone();
|
||||
ui.engine_prefs = app.session.prefs.to_json();
|
||||
serde_json::to_vec_pretty(&ui)
|
||||
}
|
||||
@@ -1,39 +1,56 @@
|
||||
//! Windows: the font files in DirectWrite's system font collection, scanned with the font folders
|
||||
//! (`vectorcraft_text::set_platform_font_files`). The desktop app and `vectorcraft-cli` (exports,
|
||||
//! MCP) both install it; the CLI shares this file.
|
||||
//! Windows: the font files in DirectWrite's system font collection and those of the fonts GDI has
|
||||
//! loaded, scanned with the font folders (`vectorcraft_text::set_platform_font_files`). The desktop
|
||||
//! app and `vectorcraft-cli` (exports, MCP) both install it; the CLI shares this file.
|
||||
//!
|
||||
//! Font services such as Adobe Fonts load their fonts with GDI at run time, from files in their
|
||||
//! own folders, without installing them: the font folders and the registry don't list them. Since
|
||||
//! Windows 10 (version 1607) DirectWrite's system font collection holds them too
|
||||
//! Windows 10 (version 1607) DirectWrite's system font collection is meant to hold them too
|
||||
//! (<https://learn.microsoft.com/windows/win32/directwrite/what-s-new-in-directwrite-for-windows-8-consumer-preview>,
|
||||
//! "Support for Adobe Typekit and other font-service clients"), so VectorCraft lists them as other
|
||||
//! apps do, reading the files in place (#579).
|
||||
//! apps do, reading the files in place (#579). It doesn't always: on some machines the fonts
|
||||
//! Creative Cloud loads are in GDI's font list (Word and the font dialogs show them) but not in
|
||||
//! the collection (#1258). So the families GDI lists that the collection doesn't name are asked
|
||||
//! for one by one: a GDI font selected into a device context gives the DirectWrite font face
|
||||
//! GDI uses (`IDWriteGdiInterop::CreateFontFaceFromHdc`), and that face its files.
|
||||
//!
|
||||
//! DirectWrite is COM, which has no safe API, hence the scoped `unsafe_code` allowance.
|
||||
//! DirectWrite is COM and GDI a C API, neither with a safe API, hence the scoped `unsafe_code`
|
||||
//! allowance.
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use windows::Win32::Foundation::LPARAM;
|
||||
use windows::Win32::Graphics::DirectWrite::{
|
||||
DWRITE_FACTORY_TYPE_SHARED, DWriteCreateFactory, IDWriteFactory3, IDWriteFontSet, IDWriteLocalFontFileLoader,
|
||||
DWRITE_FACTORY_TYPE_SHARED, DWRITE_FONT_PROPERTY_ID_WIN32_FAMILY_NAME, DWriteCreateFactory, IDWriteFactory3, IDWriteFontFile, IDWriteFontSet,
|
||||
IDWriteGdiInterop, IDWriteLocalFontFileLoader, IDWriteStringList,
|
||||
};
|
||||
use windows::Win32::Graphics::Gdi::{
|
||||
CreateCompatibleDC, CreateFontIndirectW, DEFAULT_CHARSET, DeleteDC, DeleteObject, EnumFontFamiliesExW, HDC, HGDIOBJ, LOGFONTW, RASTER_FONTTYPE,
|
||||
SelectObject, TEXTMETRICW,
|
||||
};
|
||||
use windows::core::Interface;
|
||||
|
||||
/// The most fonts read from the collection (a system has a few thousand).
|
||||
const MAX_FONTS: u32 = 1 << 16;
|
||||
/// The most families and faces taken from GDI's font list.
|
||||
const MAX_GDI_FONTS: usize = 1 << 16;
|
||||
/// The most files one font face is made of (one, but for a few Type 1 fonts).
|
||||
const MAX_FACE_FILES: u32 = 8;
|
||||
/// The longest file path taken, in UTF-16 units (Windows' own limit).
|
||||
const MAX_PATH: u32 = 32_767;
|
||||
|
||||
/// Have the font scans read the font files DirectWrite lists.
|
||||
/// Have the font scans read the font files DirectWrite and GDI list.
|
||||
pub fn install() {
|
||||
vectorcraft_text::set_platform_font_files(font_files);
|
||||
}
|
||||
|
||||
/// The local files of the fonts in DirectWrite's system font collection as it is now (fonts
|
||||
/// loaded since the last call included). None before Windows 10, or when DirectWrite fails: the
|
||||
/// font folders and the registry still list the installed fonts.
|
||||
/// loaded since the last call included), with those of the fonts GDI lists that the collection
|
||||
/// leaves out. None before Windows 10, or when DirectWrite fails: the font folders and the
|
||||
/// registry still list the installed fonts.
|
||||
fn font_files() -> Vec<String> {
|
||||
match collection_files() {
|
||||
match listed_files() {
|
||||
Ok(files) => files.into_iter().collect(),
|
||||
Err(e) => {
|
||||
log::debug!("DirectWrite's system fonts aren't listed: {e}");
|
||||
@@ -42,30 +59,48 @@ fn font_files() -> Vec<String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn collection_files() -> windows::core::Result<BTreeSet<String>> {
|
||||
fn listed_files() -> windows::core::Result<BTreeSet<String>> {
|
||||
// SAFETY: plain DirectWrite calls on interfaces it returned, each checked for failure; the
|
||||
// collection is asked to check for fonts loaded since the factory last looked.
|
||||
let set = unsafe {
|
||||
let (factory, set) = unsafe {
|
||||
let factory: IDWriteFactory3 = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)?;
|
||||
let mut collection = None;
|
||||
factory.GetSystemFontCollection(false, &mut collection, true)?;
|
||||
let Some(collection) = collection else { return Ok(BTreeSet::new()) };
|
||||
collection.GetFontSet()?
|
||||
(factory, collection.map(|c| c.GetFontSet()).transpose()?)
|
||||
};
|
||||
let mut files = set.as_ref().map(collection_files).unwrap_or_default();
|
||||
// GDI's own names for the collection's families, the names GDI lists them by.
|
||||
// SAFETY: a list DirectWrite returns, read by `strings`.
|
||||
let named = set.as_ref().and_then(|s| unsafe { s.GetPropertyValues(DWRITE_FONT_PROPERTY_ID_WIN32_FAMILY_NAME) }.ok());
|
||||
let named: BTreeSet<String> = named.as_ref().map(strings).unwrap_or_default().iter().map(|n| n.to_lowercase()).collect();
|
||||
match gdi_files(&factory, &named) {
|
||||
Ok(more) => files.extend(more),
|
||||
Err(e) => log::debug!("GDI's fonts aren't listed: {e}"),
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn collection_files(set: &IDWriteFontSet) -> BTreeSet<String> {
|
||||
// SAFETY: a count of the set's fonts.
|
||||
let count = unsafe { set.GetFontCount() }.min(MAX_FONTS);
|
||||
// Faces of one file (a collection's, a variable font's instances) name it once.
|
||||
Ok((0..count).filter_map(|i| local_path(&set, i)).collect())
|
||||
(0..count).filter_map(|i| local_path(set, i)).collect()
|
||||
}
|
||||
|
||||
/// The path of the file holding font `i` of `set`, when it is a local file (not a downloadable
|
||||
/// font, nor one in memory).
|
||||
fn local_path(set: &IDWriteFontSet, i: u32) -> Option<String> {
|
||||
// SAFETY: `i` is below the set's count; the key DirectWrite hands back stays valid while
|
||||
// `file` (which owns it) lives, and is passed back with its own size; the path buffer is
|
||||
// sized from DirectWrite's answer plus the terminating NUL.
|
||||
// SAFETY: `i` is below the set's count.
|
||||
let file = unsafe { set.GetFontFaceReference(i).ok()?.GetFontFile().ok()? };
|
||||
file_path(&file)
|
||||
}
|
||||
|
||||
/// The path of `file`, when it is a local file.
|
||||
fn file_path(file: &IDWriteFontFile) -> Option<String> {
|
||||
// SAFETY: the key DirectWrite hands back stays valid while `file` (which owns it) lives, and is
|
||||
// passed back with its own size; the path buffer is sized from DirectWrite's answer plus the
|
||||
// terminating NUL.
|
||||
unsafe {
|
||||
let file = set.GetFontFaceReference(i).ok()?.GetFontFile().ok()?;
|
||||
let loader: IDWriteLocalFontFileLoader = file.GetLoader().ok()?.cast().ok()?;
|
||||
let (mut key, mut size) = (std::ptr::null_mut(), 0u32);
|
||||
file.GetReferenceKey(&mut key, &mut size).ok()?;
|
||||
@@ -79,6 +114,159 @@ fn local_path(set: &IDWriteFontSet, i: u32) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The strings of `list`.
|
||||
fn strings(list: &IDWriteStringList) -> Vec<String> {
|
||||
// SAFETY: indices below the list's count; each buffer is sized from DirectWrite's answer plus
|
||||
// the terminating NUL.
|
||||
let count = unsafe { list.GetCount() }.min(MAX_FONTS);
|
||||
(0..count)
|
||||
.filter_map(|i| unsafe {
|
||||
let len = list.GetStringLength(i).ok()?;
|
||||
if len > MAX_PATH {
|
||||
return None;
|
||||
}
|
||||
let mut s = vec![0u16; len as usize + 1];
|
||||
list.GetString(i, &mut s).ok()?;
|
||||
Some(String::from_utf16_lossy(s.get(..len as usize)?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A memory device context, deleted when dropped.
|
||||
struct MemoryDc(HDC);
|
||||
|
||||
impl MemoryDc {
|
||||
fn new() -> windows::core::Result<Self> {
|
||||
// SAFETY: a device context compatible with the screen, owned by the guard.
|
||||
let dc = unsafe { CreateCompatibleDC(None) };
|
||||
if dc.is_invalid() { Err(windows::core::Error::from_thread()) } else { Ok(Self(dc)) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MemoryDc {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the guard's own device context, with its first font back in it.
|
||||
// Failing to delete it leaks a handle, which there's nothing to do about.
|
||||
let _ = unsafe { DeleteDC(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
/// The files of the faces of the font families GDI lists that DirectWrite's collection doesn't
|
||||
/// name (`named`, lower case).
|
||||
fn gdi_files(factory: &IDWriteFactory3, named: &BTreeSet<String>) -> windows::core::Result<BTreeSet<String>> {
|
||||
// SAFETY: a DirectWrite call checked for failure.
|
||||
let interop = unsafe { factory.GetGdiInterop()? };
|
||||
let dc = MemoryDc::new()?;
|
||||
let mut families = BTreeSet::new();
|
||||
enum_fonts(&dc, [0; 32], add_family, &mut families);
|
||||
let mut faces = Vec::new();
|
||||
for family in families.iter().filter(|f| !named.contains(&face_name(f).to_lowercase())) {
|
||||
enum_fonts(&dc, *family, add_face, &mut faces);
|
||||
}
|
||||
// A face listed once for each of its character sets is read once.
|
||||
faces.sort_by_key(face_key);
|
||||
faces.dedup_by_key(|f| face_key(f));
|
||||
// Asking for a face's files takes about a third of a millisecond, and the fonts are looked at
|
||||
// every few seconds (#2576): the faces still listed keep the files they had while those exist.
|
||||
// A face no longer listed is forgotten, so one activated again is asked for anew, and one
|
||||
// whose files couldn't be read (GDI or DirectWrite failed, or it has no local file) is asked
|
||||
// again at the next look.
|
||||
let mut known = KNOWN_FACES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut now = BTreeMap::new();
|
||||
for f in &faces {
|
||||
let key = face_key(f);
|
||||
let files = match known.remove(&key) {
|
||||
Some(files) if !files.is_empty() && files.iter().all(|p| std::path::Path::new(p).is_file()) => files,
|
||||
_ => face_files(&interop, &dc, f),
|
||||
};
|
||||
now.insert(key, files);
|
||||
}
|
||||
*known = now;
|
||||
Ok(known.values().flatten().cloned().collect())
|
||||
}
|
||||
|
||||
/// A GDI face: its name (NUL-padded), weight and whether it's italic.
|
||||
type FaceKey = ([u16; 32], i32, u8);
|
||||
|
||||
fn face_key(f: &LOGFONTW) -> FaceKey {
|
||||
(f.lfFaceName, f.lfWeight, f.lfItalic)
|
||||
}
|
||||
|
||||
/// The files of the faces GDI listed at the last look ([`gdi_files`]).
|
||||
static KNOWN_FACES: Mutex<BTreeMap<FaceKey, Vec<String>>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
/// Have GDI call `add` with `out` for each font of the family named `family` (NUL-padded), or for
|
||||
/// one font of each family when it's empty.
|
||||
fn enum_fonts<T>(
|
||||
dc: &MemoryDc,
|
||||
family: [u16; 32],
|
||||
add: unsafe extern "system" fn(*const LOGFONTW, *const TEXTMETRICW, u32, LPARAM) -> i32,
|
||||
out: &mut T,
|
||||
) {
|
||||
let query = LOGFONTW { lfCharSet: DEFAULT_CHARSET, lfFaceName: family, ..Default::default() };
|
||||
// SAFETY: `add` reads the fonts GDI passes and casts the LPARAM back to the `T` it is, which
|
||||
// outlives the call (GDI calls back before returning). Its answer is the last callback's.
|
||||
let _ = unsafe { EnumFontFamiliesExW(dc.0, &query, Some(add), LPARAM(std::ptr::from_mut(out) as isize), 0) };
|
||||
}
|
||||
|
||||
/// A GDI font list callback adding the font's family name to the `BTreeSet<[u16; 32]>` in `out`.
|
||||
unsafe extern "system" fn add_family(font: *const LOGFONTW, _: *const TEXTMETRICW, kind: u32, out: LPARAM) -> i32 {
|
||||
// SAFETY: GDI passes a valid font, and `out` is the set `enum_fonts` was given.
|
||||
let (Some(font), Some(out)) = (unsafe { font.as_ref() }, unsafe { (out.0 as *mut BTreeSet<[u16; 32]>).as_mut() }) else {
|
||||
return 0;
|
||||
};
|
||||
// Bitmap fonts have no file DirectWrite reads; `@` names are vertical writing's copies.
|
||||
if kind & RASTER_FONTTYPE == 0 && font.lfFaceName.first().is_some_and(|&c| c != 0 && c != u16::from(b'@')) {
|
||||
out.insert(font.lfFaceName);
|
||||
}
|
||||
i32::from(out.len() < MAX_GDI_FONTS)
|
||||
}
|
||||
|
||||
/// A GDI font list callback adding the font to the `Vec<LOGFONTW>` in `out`.
|
||||
unsafe extern "system" fn add_face(font: *const LOGFONTW, _: *const TEXTMETRICW, kind: u32, out: LPARAM) -> i32 {
|
||||
// SAFETY: GDI passes a valid font, and `out` is the list `enum_fonts` was given.
|
||||
let (Some(font), Some(out)) = (unsafe { font.as_ref() }, unsafe { (out.0 as *mut Vec<LOGFONTW>).as_mut() }) else {
|
||||
return 0;
|
||||
};
|
||||
if kind & RASTER_FONTTYPE == 0 {
|
||||
out.push(*font);
|
||||
}
|
||||
i32::from(out.len() < MAX_GDI_FONTS)
|
||||
}
|
||||
|
||||
/// `name`, NUL-padded, as a string.
|
||||
fn face_name(name: &[u16; 32]) -> String {
|
||||
String::from_utf16_lossy(name.split(|&c| c == 0).next().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The local files of the DirectWrite font face GDI uses for `font`.
|
||||
fn face_files(interop: &IDWriteGdiInterop, dc: &MemoryDc, font: &LOGFONTW) -> Vec<String> {
|
||||
// SAFETY: the font is selected into the guard's device context only while DirectWrite reads
|
||||
// it, then the context's own font goes back and the font is deleted; the files array is
|
||||
// sized from DirectWrite's count.
|
||||
unsafe {
|
||||
let gdi_font = CreateFontIndirectW(font);
|
||||
if gdi_font.is_invalid() {
|
||||
return Vec::new();
|
||||
}
|
||||
let first = SelectObject(dc.0, HGDIOBJ::from(gdi_font));
|
||||
let face = interop.CreateFontFaceFromHdc(dc.0);
|
||||
SelectObject(dc.0, first);
|
||||
// Failing to delete it leaks a handle, which there's nothing to do about.
|
||||
let _ = DeleteObject(HGDIOBJ::from(gdi_font));
|
||||
let Ok(face) = face else { return Vec::new() };
|
||||
let mut count = 0;
|
||||
if face.GetFiles(&mut count, None).is_err() || count == 0 || count > MAX_FACE_FILES {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut files = vec![None; count as usize];
|
||||
if face.GetFiles(&mut count, Some(files.as_mut_ptr())).is_err() {
|
||||
return Vec::new();
|
||||
}
|
||||
files.iter().flatten().filter_map(file_path).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// DirectWrite lists the installed fonts, by their files' full paths.
|
||||
@@ -89,4 +277,34 @@ mod tests {
|
||||
let fonts = std::path::Path::new(&std::env::var("WINDIR").unwrap()).join("Fonts").to_string_lossy().to_lowercase();
|
||||
assert!(files.iter().any(|f| f.to_lowercase().starts_with(&fonts)), "{} files, {:?}", files.len(), files.first());
|
||||
}
|
||||
|
||||
/// A font loaded with GDI from a file without an extension outside the font folders, as
|
||||
/// Creative Cloud loads Adobe Fonts, is listed by its file even though DirectWrite's collection
|
||||
/// doesn't hold it (#1258): fonts loaded for one process never are.
|
||||
#[test]
|
||||
fn fonts_only_gdi_has_loaded_are_listed_by_their_files() {
|
||||
use windows::Win32::Graphics::Gdi::{AddFontResourceExW, FR_PRIVATE, RemoveFontResourceExW};
|
||||
let dir = std::env::temp_dir().join(format!("vc-gdi-fonts-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("29457");
|
||||
let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf");
|
||||
let mut data = std::fs::read(source).unwrap();
|
||||
// Renamed (to a name as long) so no installed Source Sans 3 stands in for it.
|
||||
let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
|
||||
for (from, to) in [(utf16("Source Sans 3"), utf16("GdiOnly Sans3")), (b"Source Sans 3".to_vec(), b"GdiOnly Sans3".to_vec())] {
|
||||
let mut i = 0;
|
||||
while let Some(at) = data[i..].windows(from.len()).position(|w| w == from) {
|
||||
data[i + at..i + at + to.len()].copy_from_slice(&to);
|
||||
i += at + to.len();
|
||||
}
|
||||
}
|
||||
std::fs::write(&file, data).unwrap();
|
||||
let path = windows::core::HSTRING::from(file.as_os_str());
|
||||
assert_eq!(unsafe { AddFontResourceExW(&path, FR_PRIVATE, None) }, 1);
|
||||
let files = super::font_files();
|
||||
let _ = unsafe { RemoveFontResourceExW(&path, FR_PRIVATE.0, None) };
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let wanted = file.to_string_lossy().to_lowercase();
|
||||
assert!(files.iter().any(|f| f.to_lowercase() == wanted), "{wanted} not in {} files", files.len());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
use super::*;
|
||||
|
||||
fn ui_state_with_prefs(engine_prefs: serde_json::Value) -> vectorcraft_ui_egui::UiState {
|
||||
vectorcraft_ui_egui::UiState { engine_prefs, ..Default::default() }
|
||||
}
|
||||
|
||||
/// Shortcut overrides an earlier version saved still load: its spellings, `panel:` keys, an
|
||||
/// override that can't fire (#487), an entry for a command this version lacks, and an old set
|
||||
/// name.
|
||||
#[test]
|
||||
fn shortcut_overrides_from_an_earlier_version_load() {
|
||||
use serde_json::json;
|
||||
use vectorcraft_ui_egui::{keymap, shortcut_editor};
|
||||
let mut raw = serde_json::to_value(vectorcraft_ui_egui::UiState::default()).unwrap();
|
||||
raw["shortcut_overrides"] = json!({
|
||||
"tool:pen": "Shift+9",
|
||||
"edit.preferences": "",
|
||||
"panel:layers": "Cmd+Alt+Shift+F7",
|
||||
"tool:groupSelection": "Shift+ShiftLeft",
|
||||
"test.unknown": "Cmd+Alt+Shift+F9",
|
||||
"view.grid": "Cmd+Period",
|
||||
});
|
||||
raw["shortcut_set"] = json!(shortcut_editor::LEGACY_PRESETS[0].0);
|
||||
let ui = decode_saved_prefs(&serde_json::to_vec(&raw).unwrap()).unwrap().sanitized();
|
||||
assert_eq!(ui.shortcut_set, shortcut_editor::LEGACY_PRESETS[0].1);
|
||||
let km = keymap::keymap_with(&ui.shortcut_overrides);
|
||||
let text = |key: &str| keymap::effective_with(&km, key);
|
||||
assert_eq!(text("tool:pen").as_deref(), Some("Shift+9"));
|
||||
assert_eq!(text("edit.preferences"), None);
|
||||
assert_eq!(text("panel:layers").as_deref(), Some("Cmd+Alt+Shift+F7"));
|
||||
assert_eq!(text("tool:groupSelection").as_deref(), shortcut_editor::default_of("tool:groupSelection"), "back on its default");
|
||||
assert_eq!(text("view.grid").as_deref(), Some("Cmd+Period"));
|
||||
let period = keymap::vc_chord("Cmd+.").unwrap();
|
||||
assert_eq!(keymap::lookup(&km, &period).map(|c| c.id), Some("view.grid".to_string()));
|
||||
assert_eq!(text("test.unknown").as_deref(), Some("Cmd+Alt+Shift+F9"), "kept");
|
||||
assert!(km.problems().iter().any(|p| format!("{p:?}") == r#"UnknownCommand { key: "test.unknown" }"#), "reported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_files_unminimizes_and_focuses_the_window() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| bring_window_forward(ui.ctx()));
|
||||
// Nothing paints in the test: drop the font atlas upload egui expects to be applied.
|
||||
out.textures_delta.clear();
|
||||
let cmds = &out.viewport_output[&egui::ViewportId::ROOT].commands;
|
||||
assert!(cmds.contains(&egui::ViewportCommand::Minimized(false)));
|
||||
assert!(cmds.contains(&egui::ViewportCommand::Focus));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_saved_docking_keeps_preferences_and_every_workspace() {
|
||||
use serde_json::json;
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("window.panel.float", json!({"panel":"layers"})).unwrap();
|
||||
app.ui.toolbar = false;
|
||||
app.ui.engine_prefs = json!({"interfaceLanguage":"fr", "uiBrightness":"light"});
|
||||
app.ui.custom_workspaces =
|
||||
vec![vectorcraft_ui_egui::workspaces::capture(&app.ui, "Future"), vectorcraft_ui_egui::workspaces::capture(&app.ui, "Valid")];
|
||||
app.ui.workspace_changes = vec![vectorcraft_ui_egui::workspaces::capture(&app.ui, "Future")];
|
||||
let original = serde_json::to_value(&app.ui).unwrap();
|
||||
let valid_location = original["docking_hidden"]["layers"].clone();
|
||||
assert!(valid_location.is_object());
|
||||
for invalid_layout in [json!({"root":{"FutureNode":{}},"floating":[]}), json!(false)] {
|
||||
for invalid_hidden in [json!({"layers":{"placement":{"FuturePlacement":{}}},"swatches":valid_location}), json!(["malformed"])] {
|
||||
let mut raw = original.clone();
|
||||
raw["docking"] = invalid_layout.clone();
|
||||
raw["docking_hidden"] = invalid_hidden.clone();
|
||||
raw["custom_workspaces"][0]["docking"] = invalid_layout.clone();
|
||||
raw["custom_workspaces"][0]["dockingHidden"] = invalid_hidden.clone();
|
||||
raw["workspace_changes"][0]["docking"] = invalid_layout.clone();
|
||||
raw["workspace_changes"][0]["dockingHidden"] = invalid_hidden.clone();
|
||||
assert!(serde_json::from_value::<vectorcraft_ui_egui::UiState>(raw.clone()).is_err(), "runtime serde stays strict");
|
||||
let loaded = decode_saved_prefs(&serde_json::to_vec(&raw).unwrap()).unwrap();
|
||||
assert_eq!(loaded.engine_prefs, app.ui.engine_prefs);
|
||||
assert!(!loaded.toolbar);
|
||||
assert!(loaded.docking.is_none());
|
||||
assert!(!loaded.docking_hidden.contains_key("layers"));
|
||||
if invalid_hidden.is_object() {
|
||||
assert_eq!(serde_json::to_value(loaded.docking_hidden.get("swatches")).unwrap(), valid_location);
|
||||
} else {
|
||||
assert!(loaded.docking_hidden.is_empty());
|
||||
}
|
||||
assert_eq!(loaded.custom_workspaces.len(), 2);
|
||||
assert_eq!(loaded.custom_workspaces[0].name, "Future");
|
||||
assert!(loaded.custom_workspaces[0].docking.is_none());
|
||||
assert!(!loaded.custom_workspaces[0].docking_hidden.contains_key("layers"));
|
||||
assert_eq!(serde_json::to_value(&loaded.custom_workspaces[1]).unwrap(), original["custom_workspaces"][1]);
|
||||
assert_eq!(loaded.workspace_changes.len(), 1, "a remembered layout is recovered, not the whole file lost");
|
||||
assert!(loaded.workspace_changes[0].docking.is_none());
|
||||
}
|
||||
}
|
||||
let roundtrip = decode_saved_prefs(&serde_json::to_vec(&original).unwrap()).unwrap();
|
||||
assert_eq!(serde_json::to_value(roundtrip).unwrap(), original);
|
||||
assert!(
|
||||
decode_saved_prefs(&serde_json::to_vec(&json!({"toolbar":"invalid"})).unwrap()).is_none(),
|
||||
"unrelated fields retain normal strict parsing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreadable_ui_json_is_kept_beside_it() {
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-ui-prefs-{}-{stamp}", std::process::id()));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let path = dir.join("ui.json");
|
||||
super::keep_prefs_copy(&path, b"{\"docking\": {\"root\": {\"FutureNode\": {}}}}", "ui.unreadable");
|
||||
super::keep_prefs_copy(&path, b"not json", "ui.unreadable");
|
||||
super::keep_prefs_copy(&path, b"{}", "ui.before-layout-migration");
|
||||
let first = std::fs::read(dir.join("ui.unreadable.json")).unwrap();
|
||||
let second = std::fs::read(dir.join("ui.unreadable-2.json")).unwrap();
|
||||
let before = std::fs::read(dir.join("ui.before-layout-migration.json")).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert!(first.starts_with(b"{\"docking\""), "the first copy is not replaced");
|
||||
assert_eq!(second, b"not json");
|
||||
assert_eq!(before, b"{}");
|
||||
assert!(!super::KEEP_UI_PREFS.load(std::sync::atomic::Ordering::Relaxed), "ui.json can be saved once a copy is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_image_trace_preview_setting_is_kept_across_a_restart() {
|
||||
for preview in [false, true] {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.ui.image_trace_preview = preview;
|
||||
let saved = prefs_bytes(&app).unwrap();
|
||||
let loaded = decode_saved_prefs(&saved).unwrap().sanitized();
|
||||
assert_eq!(loaded.image_trace_preview, preview, "Preview {preview} after a restart");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_system_title_bar_preference_keeps_the_window_decorations() {
|
||||
use craft_window::{Frame, Layout};
|
||||
|
||||
// The System Title Bar preference (Preferences › User Interface) is read the same way on
|
||||
// every platform; a missing or unreadable value is `false`.
|
||||
assert!(!super::opted_into_system_title_bar(None), "no preferences: the default");
|
||||
let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false}));
|
||||
assert!(!super::opted_into_system_title_bar(Some(&off)));
|
||||
let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true}));
|
||||
assert!(super::opted_into_system_title_bar(Some(&on)));
|
||||
|
||||
// The suite-wide mapping (Frame + preference -> whether VectorCraft draws its own title
|
||||
// bar). The desktop frame (macOS, Windows, X11, KDE/Wayland, …) always keeps native
|
||||
// decorations; the app frame (GNOME/Wayland, or a `VECTORCRAFT_TITLEBAR` override) draws
|
||||
// our own title bar — unless the user opted into the system title bar, which forces the
|
||||
// native frame back on.
|
||||
let app = Frame::App(Layout::default());
|
||||
let desktop = Frame::Desktop;
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
assert!(super::custom_titlebar_from(&app, false), "GNOME/Wayland: VectorCraft draws its own");
|
||||
assert!(!super::custom_titlebar_from(&app, true), "System Title Bar preference forces native");
|
||||
assert!(!super::custom_titlebar_from(&desktop, false), "KDE/X11/…: keep the compositor's frame");
|
||||
assert!(!super::custom_titlebar_from(&desktop, true));
|
||||
}
|
||||
// macOS and Windows keep today's behavior, independent of the probed frame: the pref still
|
||||
// forces the native frame back on where a custom one would otherwise be drawn.
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
{
|
||||
assert_eq!(super::custom_titlebar_from(&desktop, false), super::CUSTOM_TITLEBAR);
|
||||
assert_eq!(super::custom_titlebar_from(&app, false), super::CUSTOM_TITLEBAR, "the probe does not change macOS/Windows");
|
||||
assert!(!super::custom_titlebar_from(&desktop, true));
|
||||
}
|
||||
|
||||
assert_eq!(super::native_options(false).viewport.decorations, Some(true));
|
||||
assert_eq!(super::native_options(true).viewport.decorations, Some(false));
|
||||
}
|
||||
|
||||
/// The file extensions the macOS bundle declares: its document types and its own exported type.
|
||||
fn plist_extensions(plist: &str) -> Vec<&str> {
|
||||
["<key>CFBundleTypeExtensions</key>", "<key>public.filename-extension</key>"]
|
||||
.iter()
|
||||
.flat_map(|key| plist.split(key).skip(1))
|
||||
.filter_map(|rest| rest.split("</array>").next())
|
||||
.flat_map(|array| array.split("<string>").skip(1))
|
||||
.filter_map(|s| s.split("</string>").next())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Finder offers the app for every file File › Open reads (#295, #354) but those with an
|
||||
/// extension in `UNASSOCIATED_EXTS`, takes over no other app's files, and hands them to the app
|
||||
/// rather than to AppKit's document machinery.
|
||||
#[test]
|
||||
fn the_macos_bundle_opens_every_readable_format() {
|
||||
let plist = include_str!("../../../packaging/macos/Info.plist.in");
|
||||
let declared = plist_extensions(plist);
|
||||
for e in fileio::OPEN_EXTS.iter().filter(|e| !fileio::UNASSOCIATED_EXTS.contains(e)) {
|
||||
assert!(declared.contains(e), "Info.plist.in doesn't declare .{e}");
|
||||
}
|
||||
for e in &declared {
|
||||
assert!(fileio::OPEN_EXTS.contains(e), "Info.plist.in declares .{e}, which the app doesn't open");
|
||||
}
|
||||
assert!(!plist.contains("<key>NSDocumentClass</key>"), "not an NSDocument app: AppKit would refuse the files");
|
||||
let types = plist.matches("<key>CFBundleTypeName</key>").count();
|
||||
assert!(types > 1 && plist.matches("<key>LSHandlerRank</key>").count() == types, "every document type has a rank");
|
||||
assert_eq!(plist.matches("<string>Owner</string>").count(), 2, "only VectorCraft documents and templates are owned");
|
||||
}
|
||||
|
||||
/// The MIME types a Linux desktop gives each extension in `OPEN_EXTS` but `UNASSOCIATED_EXTS`
|
||||
/// (one row per type): shared-mime-info's, or one that `ai.storyteller.vectorcraft.mime.xml`
|
||||
/// declares.
|
||||
const LINUX_TYPES: &[(&str, &str)] = &[
|
||||
("vectorcraft", "application/x-vectorcraft"),
|
||||
("drawcraft", "application/x-vectorcraft"),
|
||||
("svg", "image/svg+xml"),
|
||||
("svgz", "image/svg+xml-compressed"),
|
||||
("pdf", "application/pdf"),
|
||||
("ai", "application/illustrator"), // brand-ok: shared-mime-info's type
|
||||
("ait", "application/x-ai-template"),
|
||||
("png", "image/png"),
|
||||
("jpg", "image/jpeg"),
|
||||
("jpeg", "image/jpeg"),
|
||||
("gif", "image/gif"),
|
||||
("webp", "image/webp"),
|
||||
("tif", "image/tiff"),
|
||||
("tiff", "image/tiff"),
|
||||
("bmp", "image/bmp"),
|
||||
("vctemplate", "application/x-vectorcraft-template"),
|
||||
("dxf", "image/vnd.dxf"),
|
||||
("emf", "image/emf"),
|
||||
("wmf", "image/wmf"),
|
||||
("eps", "image/x-eps"),
|
||||
("af", "application/x-affinity"),
|
||||
("afdesign", "application/x-affinity"),
|
||||
("afpub", "application/x-affinity"),
|
||||
];
|
||||
|
||||
/// The types in `LINUX_TYPES` that shared-mime-info defines. The MIME package declares every
|
||||
/// other one.
|
||||
const LINUX_SHARED_TYPES: &[&str] = &[
|
||||
"image/svg+xml",
|
||||
"image/svg+xml-compressed",
|
||||
"application/pdf",
|
||||
"application/illustrator", // brand-ok: shared-mime-info's type
|
||||
"image/png",
|
||||
"image/jpeg",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
"image/tiff",
|
||||
"image/bmp",
|
||||
"image/vnd.dxf",
|
||||
"image/emf",
|
||||
"image/wmf",
|
||||
"image/x-eps",
|
||||
];
|
||||
|
||||
/// Extensions in `LINUX_TYPES` whose type the MIME package matches by file content and not by a
|
||||
/// glob, with the package's `<magic>` rule for that type (its lines joined, indentation removed).
|
||||
const LINUX_BY_CONTENT: &[(&str, &str)] = &[(
|
||||
"af",
|
||||
// `MAGIC` at offset 0 and `DOCUMENT_KIND` at offset 8 (crates/affinity/src/container.rs).
|
||||
r#"<magic><match type="string" offset="0" value="\x00\xff\x4b\x41"><match type="string" offset="8" value="nsrP"/></match></magic>"#,
|
||||
)];
|
||||
|
||||
/// The desktop entry lists a MIME type for every extension in `OPEN_EXTS` but
|
||||
/// `UNASSOCIATED_EXTS`, and the app's MIME package declares the types shared-mime-info doesn't
|
||||
/// have.
|
||||
#[test]
|
||||
fn the_linux_desktop_entry_opens_every_readable_format() {
|
||||
let desktop = include_str!("../../../packaging/linux/ai.storyteller.vectorcraft.desktop");
|
||||
let mime = include_str!("../../../packaging/linux/ai.storyteller.vectorcraft.mime.xml");
|
||||
let listed: Vec<&str> =
|
||||
desktop.lines().find_map(|l| l.strip_prefix("MimeType=")).unwrap_or_default().split(';').filter(|t| !t.is_empty()).collect();
|
||||
// Each type the MIME package declares, with the extensions of its globs and its `<magic>`
|
||||
// rule (empty when it has none) in the form `LINUX_BY_CONTENT` gives.
|
||||
let declared: Vec<(&str, Vec<&str>, String)> = mime
|
||||
.split("<mime-type type=\"")
|
||||
.skip(1)
|
||||
.map(|block| {
|
||||
let body = block.split("</mime-type>").next().unwrap_or_default();
|
||||
let globs = body.split("<glob pattern=\"*.").skip(1).filter_map(|g| g.split('"').next()).collect();
|
||||
let magic = match (body.find("<magic"), body.find("</magic>")) {
|
||||
(Some(start), Some(end)) => body[start..end + "</magic>".len()].lines().map(str::trim).collect(),
|
||||
_ => String::new(),
|
||||
};
|
||||
(block.split('"').next().unwrap_or_default(), globs, magic)
|
||||
})
|
||||
.collect();
|
||||
let mut associated: Vec<&str> = fileio::OPEN_EXTS.iter().copied().filter(|e| !fileio::UNASSOCIATED_EXTS.contains(e)).collect();
|
||||
let mut typed: Vec<&str> = LINUX_TYPES.iter().map(|(e, _)| *e).collect();
|
||||
associated.sort_unstable();
|
||||
typed.sort_unstable();
|
||||
typed.dedup();
|
||||
assert_eq!(typed, associated, "a MIME type for each extension the packaging associates with the app");
|
||||
for (e, t) in LINUX_TYPES {
|
||||
assert!(listed.contains(t), "the desktop entry doesn't list {t} (.{e})");
|
||||
let package = declared.iter().find(|(name, ..)| name == t);
|
||||
if LINUX_SHARED_TYPES.contains(t) {
|
||||
assert!(package.is_none(), "{t} is shared-mime-info's, and the MIME package declares it again");
|
||||
continue;
|
||||
}
|
||||
let Some((_, globs, magic)) = package else { panic!("the MIME package doesn't declare {t} (.{e})") };
|
||||
if let Some((_, rule)) = LINUX_BY_CONTENT.iter().find(|(content, _)| content == e) {
|
||||
assert!(!globs.contains(e), "{t} matches .{e} files by content only");
|
||||
assert_eq!(magic, rule, "{t}'s magic rule for .{e} files");
|
||||
} else {
|
||||
assert!(globs.contains(e), "{t} has no *.{e} glob");
|
||||
}
|
||||
}
|
||||
for t in &listed {
|
||||
assert!(LINUX_TYPES.iter().any(|(_, known)| known == t), "the desktop entry lists {t}, which the app doesn't open");
|
||||
}
|
||||
for (t, globs, _) in &declared {
|
||||
assert!(listed.contains(t), "the desktop entry doesn't list the declared {t}");
|
||||
for g in globs {
|
||||
assert!(LINUX_TYPES.contains(&(*g, *t)), "{t}'s *.{g} isn't a file the app opens as {t}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
use super::*;
|
||||
|
||||
/// The window, Dock, taskbar and app-switcher icon (`assets/app-icon/`, see its README). macOS gets
|
||||
/// the version with Apple's transparent margin; elsewhere the full-bleed tile. The app ID matches
|
||||
/// `packaging/linux/ai.storyteller.vectorcraft.desktop` so Wayland docks find the launcher icon.
|
||||
fn app_icon() -> egui::IconData {
|
||||
#[cfg(target_os = "macos")]
|
||||
let png: &[u8] = include_bytes!("../../../assets/app-icon/vectorcraft-macos-512.png");
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let png: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.vectorcraft.png");
|
||||
eframe::icon_data::from_png_bytes(png).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Windows shows a window's big icon (`ICON_BIG`) in the taskbar and Alt+Tab; eframe sets only the
|
||||
/// small one (the title bar's), so the taskbar showed a generic icon. Set the big one too.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn set_taskbar_icon(w: &winit::window::Window) {
|
||||
use winit::platform::windows::WindowExtWindows as _;
|
||||
let icon = app_icon();
|
||||
// An icon that can't be made leaves the generic one: nothing else depends on it.
|
||||
if let Ok(i) = winit::window::Icon::from_rgba(icon.rgba, icon.width, icon.height) {
|
||||
w.set_taskbar_icon(Some(i));
|
||||
}
|
||||
}
|
||||
|
||||
/// "name (backend, kind)" of the adapter the window renders with, for Help › About and bug reports.
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub(crate) fn adapter_summary(info: &eframe::wgpu::AdapterInfo) -> String {
|
||||
format!("{} ({:?}, {:?})", info.name.trim(), info.backend, info.device_type)
|
||||
}
|
||||
|
||||
/// Windows and Linux: no OS title bar; the app bar is the title bar (`vectorcraft_ui_egui::titlebar`).
|
||||
/// macOS keeps its traffic lights over the integrated title strip.
|
||||
///
|
||||
/// Used on macOS and Windows (where VectorCraft keeps today's frame regardless of the
|
||||
/// `craft-window` probe) and by the tests; Linux and the BSDs take the decision from the probe.
|
||||
#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))]
|
||||
pub(crate) const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos");
|
||||
|
||||
/// Whether the user asked for the system title bar in Preferences › User Interface › System Title
|
||||
/// Bar. Read from the saved preferences before the window opens; a missing or unreadable value is
|
||||
/// `false` (the default). This preference forces the desktop/native frame back on.
|
||||
pub(crate) fn opted_into_system_title_bar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
|
||||
saved.map(|ui| ui.engine_prefs.get("systemTitleBar").and_then(serde_json::Value::as_bool).unwrap_or(false)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether this start draws its own title bar, given the frame the shared `craft-window` crate
|
||||
/// decided and the user's System Title Bar preference.
|
||||
///
|
||||
/// The suite-wide rule (`craft_window::Choice`) is: the desktop draws the frame
|
||||
/// ([`craft_window::Frame::Desktop`]) on macOS, Windows, X11 and any Wayland compositor with
|
||||
/// server-side decorations (KDE, Sway, Hyprland, COSMIC); the app draws it
|
||||
/// ([`craft_window::Frame::App`]) only where the compositor leaves it to the app (GNOME's Mutter),
|
||||
/// or when `VECTORCRAFT_TITLEBAR` overrides the probe. VectorCraft draws its own title bar exactly
|
||||
/// when `craft-window` says the app owns the frame **and** the user has not opted into the system
|
||||
/// title bar; the preference always forces the native frame back on.
|
||||
///
|
||||
/// macOS and Windows keep today's behavior and are decided by [`CUSTOM_TITLEBAR`] rather than the
|
||||
/// probe: `craft-window` returns `Frame::Desktop` for both (the OS always draws a frame), but
|
||||
/// VectorCraft insets its content under the macOS traffic lights and draws its own caption buttons
|
||||
/// on Windows — an overdraw on an OS-decorated window that is VectorCraft's choice, not
|
||||
/// `craft-window`'s. Only Linux and the BSDs take the decision from the probe.
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
pub(crate) fn custom_titlebar_from(frame: &craft_window::Frame, opted_into_system: bool) -> bool {
|
||||
matches!(frame, craft_window::Frame::App(_)) && !opted_into_system
|
||||
}
|
||||
|
||||
/// macOS and Windows: today's behavior, independent of the `craft-window` probe (see
|
||||
/// [`custom_titlebar_from`]). macOS never draws its own frame (`CUSTOM_TITLEBAR` is `false`);
|
||||
/// Windows draws its own caption unless the user opted into the system title bar.
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_system: bool) -> bool {
|
||||
CUSTOM_TITLEBAR && !opted_into_system
|
||||
}
|
||||
|
||||
/// Whether this start draws its own title bar. Probes the shared `craft-window` crate once (its
|
||||
/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System
|
||||
/// Title Bar preference. Call once at startup, before [`native_options`].
|
||||
///
|
||||
/// On Linux, Preferences › Performance › Linux Display Server › X11 opens the window through
|
||||
/// XWayland (below). A GNOME/Wayland probe would say `Frame::App` there, but the window really runs
|
||||
/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native
|
||||
/// frame, the same as a real X11 session. An explicit `VECTORCRAFT_TITLEBAR` override still wins.
|
||||
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
|
||||
let choice = craft_window::Choice::probe(craft_window::Prefix::new("VECTORCRAFT"));
|
||||
let opted_into_system = opted_into_system_title_bar(saved);
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let pref = saved.and_then(|ui| ui.engine_prefs.get("linuxDisplayServer")).and_then(serde_json::Value::as_str);
|
||||
// `overridden() == None` means the probe decided (no VECTORCRAFT_TITLEBAR). When the window
|
||||
// will actually open on X11 (XWayland) — the user asked for it *and* the X11 libraries are
|
||||
// present, the same two conditions the launch path checks below — that run is effectively
|
||||
// X11, so keep the native frame. If the libraries are missing, startup stays on Wayland, so
|
||||
// the probe's own decision (app-drawn on GNOME) must stand.
|
||||
let forced_to_x11 = xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) && xwayland::x11_libraries_found();
|
||||
if choice.overridden().is_none() && forced_to_x11 {
|
||||
return custom_titlebar_from(&craft_window::Frame::Desktop, opted_into_system);
|
||||
}
|
||||
}
|
||||
custom_titlebar_from(choice.frame(), opted_into_system)
|
||||
}
|
||||
|
||||
pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
|
||||
eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title("VectorCraft")
|
||||
.with_inner_size(window::DEFAULT_SIZE)
|
||||
.with_min_inner_size(window::MIN_SIZE)
|
||||
.with_drag_and_drop(true)
|
||||
.with_decorations(!custom_titlebar)
|
||||
.with_fullsize_content_view(true)
|
||||
.with_titlebar_shown(false)
|
||||
.with_title_shown(false)
|
||||
.with_icon(app_icon())
|
||||
.with_app_id("ai.storyteller.vectorcraft"),
|
||||
#[cfg(feature = "windows7")]
|
||||
renderer: eframe::Renderer::Glow,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -11,10 +11,17 @@
|
||||
//!
|
||||
//! Windows sizes a maximize by the frame its styles describe, so a window maximized while its
|
||||
//! caption is gone is sized without one: its rect covers the whole monitor, taskbar included, and
|
||||
//! the shell reads a caption-less window covering its monitor as a full-screen app (#1977). The
|
||||
//! guard therefore also trims a parked maximize's rect back to the work area plus its own frame,
|
||||
//! clear of the taskbar, as PhotoCraft does (storytold/photocraft#3308). winit pins the client
|
||||
//! area to the work area either way (`WM_NCCALCSIZE`), so the app's pixels do not move.
|
||||
//! the shell reads a caption-less window covering its monitor as a full-screen app (#1977). With
|
||||
//! the taskbar on the top or a side edge, the strip between the window's edge and the client area
|
||||
//! that winit pins to the work area (`WM_NCCALCSIZE`) is drawn as a classic title bar (#3242,
|
||||
//! #3723). The guard therefore also moves a parked maximize's rect back inside the work area on
|
||||
//! every edge, plus its own frame, clear of the taskbar wherever it is, and repaints the window, as
|
||||
//! PhotoCraft does (storytold/photocraft#3308, storytold/photocraft#5237).
|
||||
//!
|
||||
//! An auto-hidden taskbar reserves no work area, so that move leaves a maximize covering the whole
|
||||
//! monitor. In PhotoCraft the taskbar then did not show when the pointer reached its edge
|
||||
//! (storytold/photocraft#4845). On each edge with an auto-hidden taskbar the guard stops the window
|
||||
//! one pixel short of the monitor instead, as PhotoCraft does (storytold/photocraft#6878).
|
||||
|
||||
/// Run once per frame; a no-op once the window is borderless.
|
||||
pub type WindowFrameFn = Box<dyn FnMut()>;
|
||||
@@ -24,7 +31,8 @@ pub use platform::service;
|
||||
#[cfg(all(windows, feature = "wgpu"))]
|
||||
mod platform {
|
||||
use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle};
|
||||
use winsafe::{HWND, HwndPlace, POINT, SIZE, co};
|
||||
use winsafe::prelude::Handle;
|
||||
use winsafe::{AtomStr, HWND, HwndPlace, POINT, SIZE, co};
|
||||
|
||||
/// A guard that keeps the window borderless each frame, or `None` with the system title bar
|
||||
/// (the window is decorated) or when its handle can't be found.
|
||||
@@ -76,12 +84,14 @@ mod platform {
|
||||
HwndPlace::None,
|
||||
POINT::new(),
|
||||
SIZE::new(),
|
||||
co::SWP::FRAMECHANGED | co::SWP::NOMOVE | co::SWP::NOSIZE | co::SWP::NOZORDER | co::SWP::NOACTIVATE,
|
||||
co::SWP::FRAMECHANGED | co::SWP::NOCOPYBITS | co::SWP::NOMOVE | co::SWP::NOSIZE | co::SWP::NOZORDER | co::SWP::NOACTIVATE,
|
||||
);
|
||||
}
|
||||
|
||||
/// [`super::clamped_height`] for this frame's window: trim a maximized window whose rect runs
|
||||
/// under the taskbar back to the work area plus its frame. No-op otherwise.
|
||||
/// [`super::clamped_rect`] for this frame's window: move a maximized window whose rect runs
|
||||
/// under a taskbar on any edge back inside the work area plus its frame, and repaint it. A
|
||||
/// maximized window that covers its whole monitor instead stops one pixel short of each edge
|
||||
/// with an auto-hidden taskbar ([`super::short_of_autohide_taskbars`]). No-op otherwise.
|
||||
fn keep_clear_of_the_taskbar(hwnd: &HWND) {
|
||||
if !hwnd.IsZoomed() {
|
||||
return;
|
||||
@@ -90,17 +100,48 @@ mod platform {
|
||||
return;
|
||||
};
|
||||
let (m, w) = (mi.rcMonitor, mi.rcWork);
|
||||
let Some(height) =
|
||||
super::clamped_height((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom))
|
||||
else {
|
||||
let (rect, monitor, work) = ((r.left, r.top, r.right, r.bottom), (m.left, m.top, m.right, m.bottom), (w.left, w.top, w.right, w.bottom));
|
||||
// The taskbars are looked up (a few `FindWindowEx` calls) only while the window covers its
|
||||
// whole monitor, which it no longer does once trimmed.
|
||||
let Some((left, top, right, bottom)) = super::clamped_rect(rect, monitor, work).or_else(|| {
|
||||
super::covers(rect, monitor).then(|| super::short_of_autohide_taskbars(rect, monitor, work, &taskbar_edges(monitor))).flatten()
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let (Some(width), Some(height)) = (right.checked_sub(left), bottom.checked_sub(top)) else {
|
||||
return;
|
||||
};
|
||||
// The frame moves while winit keeps the client rect on the work area: `NOCOPYBITS` and the
|
||||
// invalidation have the whole window drawn again instead of the old frame's pixels being
|
||||
// copied into the custom title bar.
|
||||
let _ = hwnd.SetWindowPos(
|
||||
HwndPlace::None,
|
||||
POINT::new(),
|
||||
SIZE { cx: r.right - r.left, cy: height },
|
||||
co::SWP::NOMOVE | co::SWP::NOZORDER | co::SWP::NOACTIVATE,
|
||||
POINT { x: left, y: top },
|
||||
SIZE { cx: width, cy: height },
|
||||
co::SWP::FRAMECHANGED | co::SWP::NOCOPYBITS | co::SWP::NOZORDER | co::SWP::NOACTIVATE,
|
||||
);
|
||||
let _ = hwnd.InvalidateRect(None, false);
|
||||
}
|
||||
|
||||
/// The edges of `monitor` that have a taskbar, shown or auto-hidden: the primary monitor's
|
||||
/// `Shell_TrayWnd` window and the other monitors' `Shell_SecondaryTrayWnd` windows.
|
||||
fn taskbar_edges(monitor: super::Rect) -> Vec<super::Edge> {
|
||||
let mut edges = Vec::new();
|
||||
for class in ["Shell_TrayWnd", "Shell_SecondaryTrayWnd"] {
|
||||
let mut after: Option<HWND> = None;
|
||||
// A monitor has at most one taskbar; the bound ends the walk if the shell keeps
|
||||
// returning windows.
|
||||
for _ in 0..64 {
|
||||
let Ok(Some(tray)) = HWND::NULL.FindWindowEx(after.as_ref(), AtomStr::from_str(class), None) else {
|
||||
break;
|
||||
};
|
||||
if let Ok(r) = tray.GetWindowRect() {
|
||||
edges.extend(super::taskbar_edge((r.left, r.top, r.right, r.bottom), monitor));
|
||||
}
|
||||
after = Some(tray);
|
||||
}
|
||||
}
|
||||
edges
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,35 +152,115 @@ mod platform {
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a parked maximize reaches past its monitor on the left, top and right: the resize border
|
||||
/// (about 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not parked but
|
||||
/// being dragged or snapped, and is left alone.
|
||||
/// How far a parked maximize reaches past a monitor or work-area edge: the resize border (about
|
||||
/// 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not parked but being
|
||||
/// dragged or snapped, and is left alone.
|
||||
const FRAME: i32 = 32;
|
||||
|
||||
/// The height to trim a maximize to so its rect stops at the taskbar, or `None` when it already
|
||||
/// does or `rect` (`left, top, right, bottom`, desktop coordinates) is not parked at its maximize
|
||||
/// place. `monitor` is the monitor's full rect and `work` its work area (the monitor less the
|
||||
/// taskbar) in the same coordinates. The parked check is against the full monitor, because that is
|
||||
/// where Windows puts a caption-less maximize; the trim is against the work area. Platform-neutral
|
||||
/// so it is tested everywhere.
|
||||
/// The rect to move a maximize to so it stays inside the work area on every edge, plus the resize
|
||||
/// border it was parked with, or `None` when it already does or `rect` (`left, top, right,
|
||||
/// bottom`, desktop coordinates) is not parked at its maximize place. `monitor` is the monitor's
|
||||
/// full rect and `work` its work area (the monitor less the taskbar) in the same coordinates. The
|
||||
/// border is read from the edges that have no taskbar, and every edge must sit that far outside
|
||||
/// either the monitor (where Windows puts a caption-less maximize) or the work area (where the
|
||||
/// guard puts it), so a rect it already moved is left alone. Platform-neutral so it is tested
|
||||
/// everywhere.
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
fn clamped_height(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<i32> {
|
||||
fn clamped_rect(rect: (i32, i32, i32, i32), monitor: (i32, i32, i32, i32), work: (i32, i32, i32, i32)) -> Option<(i32, i32, i32, i32)> {
|
||||
let (l, t, r, b) = rect;
|
||||
let (ml, mt, mr, _) = monitor;
|
||||
let (_, _, _, wb) = work;
|
||||
let side = ml - l;
|
||||
if !(0..=FRAME).contains(&side) || !(0..=FRAME).contains(&(mt - t)) || !(0..=FRAME).contains(&(r - mr)) {
|
||||
let (ml, mt, mr, mb) = monitor;
|
||||
let (wl, wt, wr, wb) = work;
|
||||
if ml >= mr || mt >= mb || wl < ml || wt < mt || wr > mr || wb > mb || wl >= wr || wt >= wb {
|
||||
return None;
|
||||
}
|
||||
if b <= wb + side {
|
||||
// On an edge with a taskbar, the offsets from the monitor and from the work area can both
|
||||
// look like a border, so only the edges without one are read.
|
||||
let border = [
|
||||
(ml == wl).then(|| ml.checked_sub(l)).flatten(),
|
||||
(mt == wt).then(|| mt.checked_sub(t)).flatten(),
|
||||
(mr == wr).then(|| r.checked_sub(mr)).flatten(),
|
||||
(mb == wb).then(|| b.checked_sub(mb)).flatten(),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|n| (0..=FRAME).contains(n))
|
||||
.min()?;
|
||||
let parked = |monitor: Option<i32>, work: Option<i32>| monitor == Some(border) || work == Some(border);
|
||||
if !parked(ml.checked_sub(l), wl.checked_sub(l))
|
||||
|| !parked(mt.checked_sub(t), wt.checked_sub(t))
|
||||
|| !parked(r.checked_sub(mr), r.checked_sub(wr))
|
||||
|| !parked(b.checked_sub(mb), b.checked_sub(wb))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(wb + side - t)
|
||||
let corrected = (wl.checked_sub(border)?, wt.checked_sub(border)?, wr.checked_add(border)?, wb.checked_add(border)?);
|
||||
(corrected != rect).then_some(corrected)
|
||||
}
|
||||
|
||||
/// A rect in desktop coordinates: `(left, top, right, bottom)`, right and bottom exclusive.
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
type Rect = (i32, i32, i32, i32);
|
||||
|
||||
/// A monitor edge.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
enum Edge {
|
||||
Left,
|
||||
Top,
|
||||
Right,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
/// Whether `rect` reaches every edge of `monitor`, which the shell treats as a full-screen app.
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
fn covers(rect: Rect, monitor: Rect) -> bool {
|
||||
rect.0 <= monitor.0 && rect.1 <= monitor.1 && rect.2 >= monitor.2 && rect.3 >= monitor.3
|
||||
}
|
||||
|
||||
/// The edge of `monitor` that a taskbar with the rect `taskbar` sits on: the edge nearest the
|
||||
/// taskbar's center, or `None` when the taskbar does not overlap the monitor. An auto-hidden
|
||||
/// taskbar is parked mostly past its edge with a sliver left on the monitor, so its center can lie
|
||||
/// outside the monitor.
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
fn taskbar_edge(taskbar: Rect, monitor: Rect) -> Option<Edge> {
|
||||
let (tl, tt, tr, tb) = (i64::from(taskbar.0), i64::from(taskbar.1), i64::from(taskbar.2), i64::from(taskbar.3));
|
||||
let (ml, mt, mr, mb) = (i64::from(monitor.0), i64::from(monitor.1), i64::from(monitor.2), i64::from(monitor.3));
|
||||
if tl >= tr || tt >= tb || ml >= mr || mt >= mb || tr <= ml || tl >= mr || tb <= mt || tt >= mb {
|
||||
return None;
|
||||
}
|
||||
// The center and the distances are doubled, so nothing is rounded.
|
||||
let (cx, cy) = (tl + tr, tt + tb);
|
||||
[(Edge::Left, cx - 2 * ml), (Edge::Top, cy - 2 * mt), (Edge::Right, 2 * mr - cx), (Edge::Bottom, 2 * mb - cy)]
|
||||
.into_iter()
|
||||
.min_by_key(|&(_, distance)| distance)
|
||||
.map(|(edge, _)| edge)
|
||||
}
|
||||
|
||||
/// A maximize that covers its monitor, trimmed to stop one pixel short of the monitor on each of
|
||||
/// the `taskbars` edges where the work area reaches the monitor's edge (the taskbar there is
|
||||
/// auto-hidden). `None` when `rect` does not cover the monitor or nothing is trimmed.
|
||||
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
|
||||
fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: &[Edge]) -> Option<Rect> {
|
||||
if !covers(rect, monitor) {
|
||||
return None;
|
||||
}
|
||||
let (mut l, mut t, mut r, mut b) = rect;
|
||||
for edge in taskbars {
|
||||
match edge {
|
||||
Edge::Left if work.0 == monitor.0 => l = monitor.0.checked_add(1)?,
|
||||
Edge::Top if work.1 == monitor.1 => t = monitor.1.checked_add(1)?,
|
||||
Edge::Right if work.2 == monitor.2 => r = monitor.2.checked_sub(1)?,
|
||||
Edge::Bottom if work.3 == monitor.3 => b = monitor.3.checked_sub(1)?,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let trimmed = (l, t, r, b);
|
||||
(l < r && t < b && trimmed != rect).then_some(trimmed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::clamped_height;
|
||||
use super::{Edge, clamped_rect, short_of_autohide_taskbars, taskbar_edge};
|
||||
|
||||
#[test]
|
||||
fn a_maximize_covering_the_taskbar_is_trimmed_to_the_work_area() {
|
||||
@@ -148,27 +269,97 @@ mod tests {
|
||||
// window was parked with.
|
||||
let monitor = (0, 0, 1920, 1080);
|
||||
let work = (0, 0, 1920, 1046);
|
||||
assert_eq!(clamped_height((-7, -7, 1927, 1087), monitor, work), Some(1046 + 7 - (-7)));
|
||||
assert_eq!(clamped_rect((-7, -7, 1927, 1087), monitor, work), Some((-7, -7, 1927, 1046 + 7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_maximize_already_clear_of_the_taskbar_is_left_alone() {
|
||||
// What Windows sizes a framed maximize to: the work area plus the frame.
|
||||
assert_eq!(clamped_height((-8, -8, 1928, 1054), (0, 0, 1920, 1080), (0, 0, 1920, 1046)), None);
|
||||
assert_eq!(clamped_rect((-8, -8, 1928, 1054), (0, 0, 1920, 1080), (0, 0, 1920, 1046)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_maximize_beside_a_side_taskbar_is_left_alone() {
|
||||
// Taskbar on the left: the work area starts further right, but the monitor's bottom is
|
||||
// still clear, so the rect reaches nothing.
|
||||
assert_eq!(clamped_height((-8, -8, 1928, 1088), (0, 0, 1920, 1080), (48, 0, 1920, 1080)), None);
|
||||
fn a_maximize_stays_clear_of_a_taskbar_on_any_edge() {
|
||||
// A taskbar on the top or a side edge (#3242, #3723): the rect moves inside the work area
|
||||
// there and keeps its frame on the other edges. Once moved, it is left alone.
|
||||
let monitor = (0, 0, 1920, 1080);
|
||||
let rect = (-8, -8, 1928, 1088);
|
||||
for (work, expected) in [
|
||||
((0, 0, 1920, 1046), (-8, -8, 1928, 1054)),
|
||||
((0, 48, 1920, 1080), (-8, 40, 1928, 1088)),
|
||||
((0, 2, 1920, 1080), (-8, -6, 1928, 1088)),
|
||||
((0, 0, 1920, 1078), (-8, -8, 1928, 1086)),
|
||||
((48, 0, 1920, 1080), (40, -8, 1928, 1088)),
|
||||
((0, 0, 1872, 1080), (-8, -8, 1880, 1088)),
|
||||
] {
|
||||
assert_eq!(clamped_rect(rect, monitor, work), Some(expected), "work area {work:?}");
|
||||
assert_eq!(clamped_rect(expected, monitor, work), None, "already moved, work area {work:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_taskbar_is_cleared_on_any_monitor_and_at_any_frame_size() {
|
||||
// A monitor above and left of the primary one, at frame sizes up to the limit.
|
||||
let monitor = (-1920, -1080, 0, 0);
|
||||
let work = (-1920, -1032, 0, 0);
|
||||
for border in [0, 8, 16, 32] {
|
||||
let rect = (-1920 - border, -1080 - border, border, border);
|
||||
let expected = (-1920 - border, -1032 - border, border, border);
|
||||
assert_eq!(clamped_rect(rect, monitor, work), Some(expected), "border {border}");
|
||||
assert_eq!(clamped_rect(expected, monitor, work), None, "border {border}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_maximize_without_a_reserved_taskbar_is_left_alone() {
|
||||
let monitor = (0, 0, 1920, 1080);
|
||||
assert_eq!(clamped_rect((-8, -8, 1928, 1088), monitor, monitor), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_maximize_being_dragged_away_is_left_alone() {
|
||||
let monitor = (0, 0, 1920, 1080);
|
||||
let work = (0, 0, 1920, 1046);
|
||||
assert_eq!(clamped_height((100, 200, 1100, 900), monitor, work), None, "moved");
|
||||
assert_eq!(clamped_height((-500, -7, 1427, 1087), monitor, work), None, "resized");
|
||||
assert_eq!(clamped_rect((100, 200, 1100, 900), monitor, work), None, "moved");
|
||||
assert_eq!(clamped_rect((-500, -7, 1427, 1087), monitor, work), None, "resized");
|
||||
let work = (0, 48, 1920, 1080);
|
||||
assert_eq!(clamped_rect((-500, -8, 1428, 1088), monitor, work), None, "resized under a top taskbar");
|
||||
assert_eq!(clamped_rect((0, 48, 960, 1080), monitor, work), None, "snapped to half the screen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_maximize_stops_a_pixel_short_of_an_auto_hidden_taskbar_edge() {
|
||||
// An auto-hidden taskbar reserves no work area, so the work area is the whole monitor.
|
||||
let monitor = (0, 0, 1920, 1080);
|
||||
let rect = (-8, -8, 1928, 1088);
|
||||
for (edge, expected) in [
|
||||
(Edge::Bottom, (-8, -8, 1928, 1079)),
|
||||
(Edge::Top, (-8, 1, 1928, 1088)),
|
||||
(Edge::Left, (1, -8, 1928, 1088)),
|
||||
(Edge::Right, (-8, -8, 1919, 1088)),
|
||||
] {
|
||||
assert_eq!(short_of_autohide_taskbars(rect, monitor, monitor, &[edge]), Some(expected), "{edge:?}");
|
||||
assert_eq!(short_of_autohide_taskbars(expected, monitor, monitor, &[edge]), None, "already trimmed, {edge:?}");
|
||||
assert_eq!(clamped_rect(expected, monitor, monitor), None, "left alone on the next frame, {edge:?}");
|
||||
}
|
||||
assert_eq!(short_of_autohide_taskbars(rect, monitor, monitor, &[]), None, "no taskbar");
|
||||
// A taskbar that reserves its work area is moved clear of by `clamped_rect` instead.
|
||||
assert_eq!(short_of_autohide_taskbars(rect, monitor, (0, 0, 1920, 1032), &[Edge::Bottom]), None, "shown taskbar");
|
||||
assert_eq!(short_of_autohide_taskbars((0, 0, 960, 1080), monitor, monitor, &[Edge::Bottom]), None, "half-screen");
|
||||
// A monitor above and left of the primary one.
|
||||
let monitor = (-1920, -1080, 0, 0);
|
||||
assert_eq!(short_of_autohide_taskbars((-1928, -1088, 8, 8), monitor, monitor, &[Edge::Top]), Some((-1928, -1079, 8, 8)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_taskbar_sits_on_the_monitor_edge_nearest_its_center() {
|
||||
let monitor = (0, 0, 1920, 1080);
|
||||
assert_eq!(taskbar_edge((0, 1032, 1920, 1080), monitor), Some(Edge::Bottom), "shown");
|
||||
assert_eq!(taskbar_edge((0, 1078, 1920, 1126), monitor), Some(Edge::Bottom), "auto-hidden");
|
||||
assert_eq!(taskbar_edge((0, -46, 1920, 2), monitor), Some(Edge::Top));
|
||||
assert_eq!(taskbar_edge((-60, 0, 2, 1080), monitor), Some(Edge::Left));
|
||||
assert_eq!(taskbar_edge((1918, 0, 1980, 1080), monitor), Some(Edge::Right));
|
||||
assert_eq!(taskbar_edge((1920, 1032, 3840, 1080), monitor), None, "other monitor");
|
||||
assert!(taskbar_edge((i32::MIN, i32::MIN, i32::MAX, i32::MAX), monitor).is_some(), "no overflow");
|
||||
}
|
||||
}
|
||||
@@ -5,30 +5,74 @@
|
||||
//! second-button flag ("analogous to a mouse right button down",
|
||||
//! <https://learn.microsoft.com/en-us/windows/win32/inputmsg/wm-pointerdown>): [`msg_hook`] notes
|
||||
//! it, and [`raw_input_hook`] makes the primary button of that contact the secondary one.
|
||||
//!
|
||||
//! winit also drops which end of the pen is down. For each pointer message of a pen, [`msg_hook`]
|
||||
//! reads the pen's `POINTER_PEN_INFO` and writes its pressure and end into the canvas's pen feed
|
||||
//! ([`start`]): `PEN_FLAG_INVERTED` ("The pen is inverted") or `PEN_FLAG_ERASER` ("The eraser
|
||||
//! button is pressed") is the eraser end
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/pen-flags-constants>). Pointer
|
||||
//! messages also come while the pen hovers, so turning the pen over selects the Eraser tool before
|
||||
//! it touches. A message of another pointer, a pen leaving detection range or the window, or a
|
||||
//! mouse message that Windows did not make from a pen or a touch
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages>)
|
||||
//! clears the feed.
|
||||
#![cfg_attr(not(all(windows, not(target_vendor = "win7"))), allow(dead_code))]
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, TouchId, TouchPhase};
|
||||
use vectorcraft_ui_egui::stylus::{PenSample, StylusFeed};
|
||||
|
||||
/// `POINTER_MESSAGE_FLAG_SECONDBUTTON` (`winuser.h`): in the high word of a pointer message's
|
||||
/// `wParam`, a pen in contact with its barrel button pressed.
|
||||
const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020;
|
||||
/// `POINTER_MESSAGE_FLAG_INRANGE` (`winuser.h`): not set on the message of a pointer that has left
|
||||
/// detection range.
|
||||
const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002;
|
||||
/// At most this many pointer contacts wait for their touch event.
|
||||
const MAX_PENDING: usize = 16;
|
||||
/// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`.
|
||||
const PEN_FLAG_INVERTED: u32 = 0x0002;
|
||||
const PEN_FLAG_ERASER: u32 = 0x0004;
|
||||
/// `PEN_MASK_PRESSURE` (`winuser.h`), in `POINTER_PEN_INFO::penMask`: the pen reports pressure.
|
||||
const PEN_MASK_PRESSURE: u32 = 0x0001;
|
||||
/// `MI_WP_SIGNATURE` and `SIGNATURE_MASK`: the extra information of a mouse message that Windows
|
||||
/// made from a pen or a touch.
|
||||
const MI_WP_SIGNATURE: u32 = 0xFF51_5700;
|
||||
const SIGNATURE_MASK: u32 = 0xFFFF_FF00;
|
||||
/// `WM_MOUSEFIRST` to `WM_MOUSELAST` (`winuser.h`).
|
||||
const MOUSE_MESSAGES: std::ops::RangeInclusive<u32> = 0x0200..=0x020E;
|
||||
/// `WM_POINTERUPDATE`, `WM_POINTERDOWN`, `WM_POINTERUP`, `WM_POINTERENTER` and `WM_POINTERLEAVE`
|
||||
/// (`winuser.h`).
|
||||
const WM_POINTERUPDATE: u32 = 0x0245;
|
||||
const WM_POINTERDOWN: u32 = 0x0246;
|
||||
const WM_POINTERUP: u32 = 0x0247;
|
||||
const WM_POINTERENTER: u32 = 0x0249;
|
||||
const WM_POINTERLEAVE: u32 = 0x024A;
|
||||
|
||||
thread_local! {
|
||||
static STROKES: RefCell<BarrelStrokes> = RefCell::new(BarrelStrokes::default());
|
||||
}
|
||||
|
||||
/// The pen feed [`msg_hook`] writes, once [`start`] has made it.
|
||||
static FEED: OnceLock<StylusFeed> = OnceLock::new();
|
||||
|
||||
/// The canvas's pen feed, which [`msg_hook`] writes on the UI thread before winit handles each
|
||||
/// message, so a press never waits for it.
|
||||
pub fn start() -> StylusFeed {
|
||||
FEED.get_or_init(StylusFeed::on_ui_thread).clone()
|
||||
}
|
||||
|
||||
/// winit's message hook (`EventLoopBuilderExtWindows::with_msg_hook`), which winit calls for each
|
||||
/// message it takes from the thread's queue, before dispatching it: notes each pointer contact's id
|
||||
/// and whether the barrel button was held.
|
||||
/// and whether the barrel button was held, and writes the pen's pressure and end into the feed.
|
||||
/// It never consumes the message.
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
#[allow(unsafe_code)]
|
||||
pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
|
||||
use windows::Win32::UI::WindowsAndMessaging::{MSG, WM_POINTERDOWN};
|
||||
use windows::Win32::UI::Input::Pointer::{GetPointerPenInfo, POINTER_FLAG_INCONTACT, POINTER_PEN_INFO};
|
||||
use windows::Win32::UI::WindowsAndMessaging::{GetMessageExtraInfo, MSG};
|
||||
// SAFETY: winit passes the `MSG` that `PeekMessageW` has just filled, which lives for this
|
||||
// call; `as_ref` gives `None` for a null pointer.
|
||||
let Some(msg) = (unsafe { msg.cast::<MSG>().as_ref() }) else {
|
||||
@@ -41,9 +85,63 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
|
||||
}
|
||||
});
|
||||
}
|
||||
let Some(feed) = FEED.get() else {
|
||||
return false;
|
||||
};
|
||||
let read_pen = || {
|
||||
let mut info = POINTER_PEN_INFO::default();
|
||||
// SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a
|
||||
// pointer that is not a pen.
|
||||
unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?;
|
||||
let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0;
|
||||
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact))
|
||||
};
|
||||
// SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message.
|
||||
let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32);
|
||||
if let Some(sample) = feed_update(msg.message, msg.wParam.0, read_pen, from_mouse) {
|
||||
feed.set_sample(sample);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags`
|
||||
/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen
|
||||
/// in contact that reports none; and the eraser end while it is inverted or its eraser button is
|
||||
/// pressed.
|
||||
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool) -> PenSample {
|
||||
let pressure = match pressure {
|
||||
1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0,
|
||||
_ if in_contact => 1.0,
|
||||
_ => 0.0,
|
||||
};
|
||||
PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0 }
|
||||
}
|
||||
|
||||
/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse,
|
||||
/// not from a pen or a touch.
|
||||
fn is_mouse(extra_info: u32) -> bool {
|
||||
extra_info & SIGNATURE_MASK != MI_WP_SIGNATURE
|
||||
}
|
||||
|
||||
/// What the feed is set to for a message with this `wParam`: `Some(Some(sample))` for a pointer
|
||||
/// message of a pen in range (`read_pen`), `Some(None)` for a pointer message of another pointer,
|
||||
/// a pointer leaving detection range or the window, or a mouse message from a mouse
|
||||
/// (`from_mouse`), and `None` to leave it as it is.
|
||||
fn feed_update(
|
||||
message: u32,
|
||||
wparam: usize,
|
||||
read_pen: impl FnOnce() -> Option<PenSample>,
|
||||
from_mouse: impl FnOnce() -> bool,
|
||||
) -> Option<Option<PenSample>> {
|
||||
match message {
|
||||
WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP if (wparam >> 16) & POINTER_MESSAGE_FLAG_INRANGE == 0 => Some(None),
|
||||
WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP => Some(read_pen()),
|
||||
WM_POINTERLEAVE => Some(None),
|
||||
m if MOUSE_MESSAGES.contains(&m) && from_mouse() => Some(None),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Before egui reads a frame's input: the primary button of a contact that started with the
|
||||
/// barrel button held becomes the secondary button.
|
||||
pub fn raw_input_hook(raw: &mut egui::RawInput) {
|
||||
@@ -287,6 +385,59 @@ mod tests {
|
||||
assert_eq!(buttons(&rewrite(&mut strokes, &events)), [PRIMARY_DOWN]);
|
||||
}
|
||||
|
||||
/// `PEN_FLAG_BARREL` (`winuser.h`).
|
||||
const PEN_FLAG_BARREL: u32 = 0x0001;
|
||||
|
||||
#[test]
|
||||
fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() {
|
||||
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true).eraser;
|
||||
assert!(!eraser(0), "the tip");
|
||||
assert!(!eraser(PEN_FLAG_BARREL), "the barrel button");
|
||||
assert!(eraser(PEN_FLAG_INVERTED), "turned over");
|
||||
assert!(eraser(PEN_FLAG_ERASER), "the eraser button");
|
||||
assert!(eraser(PEN_FLAG_INVERTED | PEN_FLAG_ERASER));
|
||||
assert!(eraser(PEN_FLAG_INVERTED | PEN_FLAG_BARREL));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pens_pressure_is_the_one_winit_gives_its_touch() {
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true).pressure, 0.5);
|
||||
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true).pressure, 1.0);
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false), PenSample { pressure: 0.0, eraser: true }, "hovering");
|
||||
assert_eq!(pen_sample(0, 0, 0, true).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
|
||||
assert_eq!(pen_sample(300, 0, 0, true).pressure, 1.0, "a pressure without the pressure mask is not one");
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true).pressure, 1.0, "as winit, which gives no force for 0");
|
||||
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false).pressure, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mouse_messages_from_a_pen_or_a_touch_are_told_apart() {
|
||||
assert!(is_mouse(0), "a mouse");
|
||||
assert!(!is_mouse(0xFF51_5701), "a pen");
|
||||
assert!(!is_mouse(0xFF51_5780), "a touch");
|
||||
assert!(is_mouse(0xFF51_5600));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pen_messages_set_the_feed_and_other_pointers_clear_it() {
|
||||
let pen = PenSample { pressure: 0.0, eraser: true };
|
||||
// `POINTER_MESSAGE_FLAG_INRANGE` in the high word of `wParam`, pointer 7 in the low word.
|
||||
let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7;
|
||||
let no_mouse = || -> bool { panic!("a pointer message is not a mouse message") };
|
||||
let no_pen = || -> Option<PenSample> { panic!("no pen to read") };
|
||||
for m in [WM_POINTERENTER, WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] {
|
||||
assert_eq!(feed_update(m, in_range, || Some(pen), no_mouse), Some(Some(pen)), "{m:#x}");
|
||||
assert_eq!(feed_update(m, in_range, || None, no_mouse), Some(None), "a touch: {m:#x}");
|
||||
assert_eq!(feed_update(m, 7, no_pen, no_mouse), Some(None), "out of range: {m:#x}");
|
||||
}
|
||||
assert_eq!(feed_update(WM_POINTERLEAVE, in_range, no_pen, no_mouse), Some(None));
|
||||
// WM_MOUSEMOVE and WM_LBUTTONDOWN.
|
||||
assert_eq!(feed_update(0x0200, 0, no_pen, || true), Some(None), "a mouse moved");
|
||||
assert_eq!(feed_update(0x0201, 0, no_pen, || false), None, "made from a pen");
|
||||
// WM_KEYDOWN.
|
||||
assert_eq!(feed_update(0x0100, 0, no_pen, || -> bool { panic!("not a mouse message") }), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contacts_whose_touch_never_arrives_are_bounded() {
|
||||
let mut strokes = BarrelStrokes::default();
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
//! `vectorcraft --help` prints the usage and exits before the app starts (#2110): run from a
|
||||
//! terminal, SSH or an agent's shell it used to open the window (or hang without a display).
|
||||
|
||||
use std::io::Read;
|
||||
use std::process::{Command, Output, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft");
|
||||
|
||||
/// Runs the desktop binary without a display, so a regression fails instead of opening a window.
|
||||
/// Runs the desktop binary without a display and with a control port it cannot parse, so a
|
||||
/// regression exits with that error instead of opening a window.
|
||||
fn run(args: &[&str], env: &[(&str, &str)]) -> Output {
|
||||
let mut child = Command::new(BIN)
|
||||
.args(args)
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WAYLAND_SOCKET")
|
||||
.env_remove("VECTORCRAFT_CONTROL_PORT")
|
||||
.env("VECTORCRAFT_CONTROL_PORT", "not-a-port")
|
||||
.env("VECTORCRAFT_NO_PREFS", "1")
|
||||
.envs(env.iter().copied())
|
||||
.stdin(Stdio::null())
|
||||
@@ -21,15 +24,28 @@ fn run(args: &[&str], env: &[(&str, &str)]) -> Output {
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while child.try_wait().unwrap().is_none() {
|
||||
if Instant::now() >= deadline {
|
||||
child.kill().unwrap();
|
||||
panic!("{args:?}: the app started instead of printing its usage");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
child.wait_with_output().unwrap()
|
||||
// Both pipes end when the binary exits, however long a loaded machine takes to start it. The
|
||||
// deadline only stops a binary that is still running.
|
||||
let deadline = Instant::now() + Duration::from_secs(120);
|
||||
let stdout = read_to_end(child.stdout.take().unwrap());
|
||||
let stderr = read_to_end(child.stderr.take().unwrap());
|
||||
let recv = |rx: &mpsc::Receiver<Vec<u8>>| rx.recv_timeout(deadline.saturating_duration_since(Instant::now()));
|
||||
let (Ok(stdout), Ok(stderr)) = (recv(&stdout), recv(&stderr)) else {
|
||||
child.kill().unwrap();
|
||||
panic!("{args:?}: the app started instead of printing its usage");
|
||||
};
|
||||
Output { status: child.wait().unwrap(), stdout, stderr }
|
||||
}
|
||||
|
||||
/// Reads `pipe` to its end on another thread.
|
||||
fn read_to_end(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver<Vec<u8>> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
let _ = tx.send(buf);
|
||||
});
|
||||
rx
|
||||
}
|
||||
|
||||
fn prints_usage(args: &[&str], env: &[(&str, &str)]) {
|
||||
|
||||
@@ -3,3 +3,6 @@
|
||||
allow-unwrap-in-tests = true
|
||||
allow-expect-in-tests = true
|
||||
allow-panic-in-tests = true
|
||||
disallowed-types = [
|
||||
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
|
||||
]
|
||||
@@ -159,3 +159,13 @@ display_name = "Aditya Sisodiya"
|
||||
real_name = "Angelo Bernardini"
|
||||
display_name = "Angelo Bernardini"
|
||||
sync_github_name = false
|
||||
|
||||
[people.DCaioP]
|
||||
real_name = "Caio Pontes Magalhães"
|
||||
display_name = "Caio Pontes"
|
||||
sync_github_name = false
|
||||
|
||||
[people.xbirks]
|
||||
real_name = "Andrés Ortega Montoya"
|
||||
display_name = "Andrés Ortega Montoya"
|
||||
sync_github_name = false
|
||||
+10
-740
@@ -8,6 +8,16 @@ use crate::paint::{self, Paint, Stroke};
|
||||
use crate::stream::{ObjId, Stream, Tag};
|
||||
use crate::{Archive, Error, Limits, stream};
|
||||
|
||||
mod bounds;
|
||||
mod read;
|
||||
|
||||
pub(crate) use bounds::rect;
|
||||
pub use bounds::{kind_bounds, nodes_bounds};
|
||||
pub(crate) use read::Reader;
|
||||
pub use read::read;
|
||||
#[cfg(test)]
|
||||
pub(crate) use read::read_within;
|
||||
|
||||
/// Affine map `x' = a·x + c·y + e`, `y' = b·x + d·y + f` (kurbo's coefficient order).
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Affine(pub [f64; 6]);
|
||||
@@ -459,743 +469,3 @@ pub struct Document {
|
||||
/// colorimetric intent and black-point compensation in every document checked.
|
||||
pub cmyk_profile: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
const MAX_TREE_DEPTH: usize = 128;
|
||||
/// Total layer nodes imported.
|
||||
const MAX_NODES: usize = 500_000;
|
||||
|
||||
/// Pixels decoded from pixel layers over a whole document (2 GB as RGBA). The archive's limits
|
||||
/// count the bytes extracted from it, and a layer of one flat colour needs none (#1704).
|
||||
const MAX_LAYER_PIXELS: u64 = 512 << 20;
|
||||
|
||||
/// Embedded documents inside embedded documents are followed this deep.
|
||||
const MAX_EMBED_DEPTH: usize = 4;
|
||||
/// Characters of all stories together (a story may be shared by many text layers).
|
||||
const MAX_DOCUMENT_CHARS: usize = 16 << 20;
|
||||
/// Table cells of all tables together (each becomes a text object with its edge lines).
|
||||
const MAX_DOCUMENT_CELLS: usize = 1 << 18;
|
||||
|
||||
/// What a whole read may still use. Shared objects can be linked from many layers, and embedded
|
||||
/// documents are read with what their embedding document left, so linking or embedding the
|
||||
/// same content many times can't multiply the work.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Budget {
|
||||
/// Layer nodes ([`MAX_NODES`] in all).
|
||||
pub(crate) nodes: usize,
|
||||
/// Pixels the pixel layers may decode ([`MAX_LAYER_PIXELS`] in all).
|
||||
pub(crate) pixels: u64,
|
||||
/// Characters of stories ([`MAX_DOCUMENT_CHARS`] in all).
|
||||
pub(crate) chars: usize,
|
||||
/// Table cells ([`MAX_DOCUMENT_CELLS`] in all).
|
||||
pub(crate) cells: usize,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
pub(crate) const FULL: Budget = Budget { nodes: MAX_NODES, pixels: MAX_LAYER_PIXELS, chars: MAX_DOCUMENT_CHARS, cells: MAX_DOCUMENT_CELLS };
|
||||
}
|
||||
|
||||
/// Read a document: archive, `doc.dat` and the model.
|
||||
pub fn read(bytes: &[u8], limits: Limits) -> Result<Document, Error> {
|
||||
read_within(bytes, limits, MAX_LAYER_PIXELS)
|
||||
}
|
||||
|
||||
/// [`read`], its pixel layers holding at most `pixels` pixels together.
|
||||
pub(crate) fn read_within(bytes: &[u8], limits: Limits, pixels: u64) -> Result<Document, Error> {
|
||||
read_at(bytes, limits, &mut Budget { pixels, ..Budget::FULL }, Affine::IDENTITY, 0).document
|
||||
}
|
||||
|
||||
/// A document read by [`read_at`] (or why it couldn't be), with the bytes its archive extracted
|
||||
/// either way.
|
||||
struct ReadAt {
|
||||
document: Result<Document, Error>,
|
||||
extracted: usize,
|
||||
}
|
||||
|
||||
/// Read a document whose spreads are placed by `base` (for embedded documents, nested `depth`
|
||||
/// deep). What it uses is taken from `budget`, also when it fails part of the way.
|
||||
/// The most characters of a layer's name kept.
|
||||
const MAX_NAME_CHARS: usize = 1024;
|
||||
|
||||
fn read_at(bytes: &[u8], limits: Limits, budget: &mut Budget, base: Affine, depth: usize) -> ReadAt {
|
||||
let mut archive = match Archive::open(bytes, limits) {
|
||||
Ok(a) => a,
|
||||
Err(e) => return ReadAt { document: Err(e), extracted: 0 },
|
||||
};
|
||||
let document = read_archive(&mut archive, budget, base, depth);
|
||||
ReadAt { document, extracted: archive.extracted() }
|
||||
}
|
||||
|
||||
fn read_archive(archive: &mut Archive, budget: &mut Budget, base: Affine, depth: usize) -> Result<Document, Error> {
|
||||
let doc = archive.read("doc.dat")?;
|
||||
let s = stream::parse(&doc)?;
|
||||
let mut reader = Reader::new(&s, archive, base, depth);
|
||||
reader.budget = *budget;
|
||||
let document = reader.document();
|
||||
*budget = reader.budget;
|
||||
document
|
||||
}
|
||||
|
||||
pub(crate) struct Reader<'s, 'a, 'b> {
|
||||
pub(crate) s: &'s Stream,
|
||||
pub(crate) archive: &'b mut Archive<'a>,
|
||||
pub(crate) dpi: f64,
|
||||
pub(crate) warnings: BTreeMap<String, usize>,
|
||||
active: HashSet<ObjId>,
|
||||
/// Where the spreads go: the identity, or an embedding document's placement.
|
||||
base: Affine,
|
||||
/// The linear part of `base`, which also scales frame text.
|
||||
pub(crate) type_base: Affine,
|
||||
/// How deep inside embedded documents this one is.
|
||||
depth: usize,
|
||||
/// An embedded document's content, waiting to become its node's children.
|
||||
pending: Option<Vec<Node>>,
|
||||
/// The master spreads, in the order of [`Document::masters`].
|
||||
master_ids: Vec<ObjId>,
|
||||
/// What the rest of the read may use.
|
||||
pub(crate) budget: Budget,
|
||||
}
|
||||
|
||||
impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
pub(crate) fn new(s: &'s Stream, archive: &'b mut Archive<'a>, base: Affine, depth: usize) -> Self {
|
||||
let [a, b, c, d, ..] = base.0;
|
||||
Self {
|
||||
s,
|
||||
archive,
|
||||
dpi: 72.0,
|
||||
warnings: BTreeMap::new(),
|
||||
active: HashSet::new(),
|
||||
base,
|
||||
type_base: Affine([a, b, c, d, 0.0, 0.0]),
|
||||
depth,
|
||||
pending: None,
|
||||
master_ids: Vec::new(),
|
||||
budget: Budget::FULL,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn warn(&mut self, what: impl Into<String>) {
|
||||
*self.warnings.entry(what.into()).or_default() += 1;
|
||||
}
|
||||
|
||||
/// The document.
|
||||
fn document(&mut self) -> Result<Document, Error> {
|
||||
let s = self.s;
|
||||
let root = s.root;
|
||||
self.dpi = s.obj(root, b"UVCn").and_then(|u| s.f64(u, b"UPPI")).filter(|d| *d > 0.0 && *d < 100_000.0).unwrap_or(72.0);
|
||||
let saved_by = s.obj(root, b"NVer").map(|v| {
|
||||
let product = s.str(v, b"Prod").unwrap_or("Affinity");
|
||||
match (s.int(v, b"Majr"), s.int(v, b"Minr"), s.int(v, b"Bild")) {
|
||||
(Some(a), Some(b), Some(c)) => format!("{product} {a}.{b}.{c}"),
|
||||
_ => product.to_string(),
|
||||
}
|
||||
});
|
||||
let doc = s.obj(root, b"DocR").ok_or(Error::Malformed("document has no root node"))?;
|
||||
self.master_ids = s.objs(doc, b"MpCh").into_iter().filter(|m| s.is(*m, b"Sprd")).collect();
|
||||
let mut spreads = Vec::new();
|
||||
for spread in s.objs(doc, b"Chld") {
|
||||
if let Some(sp) = self.spread(doc, spread)? {
|
||||
spreads.push(sp);
|
||||
}
|
||||
}
|
||||
if spreads.is_empty() {
|
||||
return Err(Error::Malformed("document has no pages"));
|
||||
}
|
||||
let mut masters = Vec::new();
|
||||
for master in self.master_ids.clone() {
|
||||
match self.spread(doc, master)? {
|
||||
Some(sp) => masters.push(sp),
|
||||
// Keep the indices of `MasterInstance::master` valid.
|
||||
None => masters.push(Spread {
|
||||
bounds: Rect { x0: 0.0, y0: 0.0, x1: 0.0, y1: 0.0 },
|
||||
pages: Vec::new(),
|
||||
transparent: true,
|
||||
nodes: Vec::new(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
let cmyk_profile = s
|
||||
.obj(root, b"CMYP")
|
||||
.and_then(|p| s.bytes(p, b"Data"))
|
||||
.filter(|b| b.len() <= MAX_PROFILE_BYTES && b.get(16..20) == Some(b"CMYK".as_slice()))
|
||||
.map(<[u8]>::to_vec);
|
||||
let warnings = std::mem::take(&mut self.warnings).into_iter().map(|(w, n)| if n > 1 { format!("{w} ({n}×)") } else { w }).collect();
|
||||
Ok(Document { dpi: self.dpi, spreads, masters, saved_by, warnings, cmyk_profile })
|
||||
}
|
||||
|
||||
/// A spread (`Sprd`) of the document `doc`, or of its master spreads.
|
||||
fn spread(&mut self, doc: ObjId, spread: ObjId) -> Result<Option<Spread>, Error> {
|
||||
let s = self.s;
|
||||
if !s.is(spread, b"Sprd") {
|
||||
self.warn("an unknown kind of page");
|
||||
return Ok(None);
|
||||
}
|
||||
let pages = pages(s, spread);
|
||||
let default_size = s.floats::<2>(doc, b"DfSz").filter(|[w, h]| *w > 0.0 && *h > 0.0).map(|[w, h]| Rect { x0: 0.0, y0: 0.0, x1: w, y1: h });
|
||||
let bounds = s.floats::<4>(spread, b"SprB").map(rect).or_else(|| pages.iter().copied().reduce(union)).or(default_size).unwrap_or(Rect {
|
||||
x0: 0.0,
|
||||
y0: 0.0,
|
||||
x1: 0.0,
|
||||
y1: 0.0,
|
||||
});
|
||||
let transparent = s.bool(spread, b"SprT").unwrap_or(false);
|
||||
let (nodes, mask) = self.children(spread, self.base, 0)?;
|
||||
if mask.is_some() {
|
||||
self.warn("mask layers directly on a page (imported without them)");
|
||||
}
|
||||
Ok(Some(Spread { bounds, pages, transparent, nodes }))
|
||||
}
|
||||
|
||||
/// The children of `parent`, and the mask layer among them that masks the parent (with its
|
||||
/// placement), read later over just what it masks.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn children(&mut self, parent: ObjId, world: Affine, depth: usize) -> Result<(Vec<Node>, Option<(ObjId, Affine)>), Error> {
|
||||
let s = self.s;
|
||||
let mut out = Vec::new();
|
||||
let mut mask = None;
|
||||
for c in s.objs(parent, b"Chld") {
|
||||
if s.is(c, b"MRst") {
|
||||
// A mask layer inside a group or layer masks that container.
|
||||
if s.bool(c, b"Visi") == Some(false) {
|
||||
continue;
|
||||
}
|
||||
let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
|
||||
if mask.is_none() {
|
||||
mask = Some((c, local.then(world)));
|
||||
} else {
|
||||
self.warn("several pixel masks on one layer (only the first is used)");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = self.node(c, world, depth + 1)? {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
Ok((out, mask))
|
||||
}
|
||||
|
||||
fn node(&mut self, id: ObjId, parent: Affine, depth: usize) -> Result<Option<Node>, Error> {
|
||||
let s = self.s;
|
||||
if depth > MAX_TREE_DEPTH {
|
||||
self.warn("layers nested deeper than 128 levels");
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(left) = self.budget.nodes.checked_sub(1) else {
|
||||
return Err(Error::Limit("too many layers"));
|
||||
};
|
||||
self.budget.nodes = left;
|
||||
// A node that contains itself (a shared object linked back into its own subtree).
|
||||
if !self.active.insert(id) {
|
||||
self.warn("a layer that contains itself");
|
||||
return Ok(None);
|
||||
}
|
||||
let local = s.floats::<6>(id, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
|
||||
let world = local.then(parent);
|
||||
let class = s.class(id).unwrap_or(Tag(0));
|
||||
// A layer name is short; a long one is cut, as every visit of a shared object keeps a copy.
|
||||
let name: String = s.str(id, b"Desc").unwrap_or_default().chars().take(MAX_NAME_CHARS).collect();
|
||||
let visible = s.bool(id, b"Visi").unwrap_or(true);
|
||||
let locked = s.bool(id, b"Edtb").is_some_and(|e| !e);
|
||||
let opacity = s.f64(id, b"Opac").map_or(1.0, |o| o.clamp(0.0, 1.0));
|
||||
let blend = match s.enumeration(id, b"Blnd") {
|
||||
None if s.bool(id, b"PasT") != Some(false) && is_container(class) => Blend::PassThrough,
|
||||
None => Blend::Normal,
|
||||
Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| {
|
||||
self.warn("an unknown blend mode (imported as Normal)");
|
||||
Blend::Normal
|
||||
}),
|
||||
};
|
||||
let kind = if !world.is_finite() {
|
||||
self.warn("a layer with an invalid transform");
|
||||
Kind::Unsupported
|
||||
} else {
|
||||
self.kind(id, class, world, parent)?
|
||||
};
|
||||
// This node's embedded content, before its children's `node` calls can take it.
|
||||
let embedded = self.pending.take();
|
||||
// A compound's children are its operands, already merged into its outline.
|
||||
let (mut children, child_mask) = if class == Tag::of(b"Comp") { (Vec::new(), None) } else { self.children(id, world, depth)? };
|
||||
if let Some(embedded) = embedded {
|
||||
children.extend(embedded);
|
||||
}
|
||||
// Pixel masks are read only over what they mask (they can span a whole spread at print
|
||||
// resolution, a gigapixel).
|
||||
let over = mask_extent(&kind, &children);
|
||||
let child_mask = match child_mask {
|
||||
Some((c, at)) => crate::raster::mask(self, c, at, over)?,
|
||||
None => None,
|
||||
};
|
||||
let (mask, attached_mask) = self.attached_masks(id, world, over)?;
|
||||
let pixel_mask = attached_mask.or(child_mask);
|
||||
self.active.remove(&id);
|
||||
let mut node = Node { class, name, visible, locked, opacity, blend, kind, mask, pixel_mask, effects: Vec::new(), children };
|
||||
// Gradient overlays are laid out over the node's bounds, also while it is hidden.
|
||||
let bounds = tree_bounds(&node);
|
||||
node.effects = self.effects(id, world, bounds);
|
||||
Ok(Some(node))
|
||||
}
|
||||
|
||||
fn kind(&mut self, id: ObjId, class: Tag, world: Affine, parent: Affine) -> Result<Kind, Error> {
|
||||
let s = self.s;
|
||||
Ok(match &class.0.to_be_bytes() {
|
||||
b"Scop" => Kind::Layer,
|
||||
b"Grup" => Kind::Group,
|
||||
b"PCrv" | b"ShpN" | b"Comp" | b"SNEN" | b"SNRR" | b"ShRN" => {
|
||||
// Affinity 3.2.3's two-board public fixture marks board shapes with an `aprp`
|
||||
// property object in `phrp`, while older documents use `ABEn`. Ordinary shapes
|
||||
// in that fixture have neither. See the pinned corpus and validation audit.
|
||||
if s.bool(id, b"ABEn") == Some(true) || s.obj(id, b"phrp").is_some_and(|p| s.is(p, b"aprp")) {
|
||||
return Ok(self.artboard(id, world));
|
||||
}
|
||||
let Some((local, even_odd)) = crate::geometry::outline(self, id, class, world) else {
|
||||
self.warn(format!("a {} that could not be read", describe(class)));
|
||||
return Ok(Kind::Unsupported);
|
||||
};
|
||||
let (fills, strokes) = paint::node_paint(self, id, world);
|
||||
Kind::Shape { path: local.transformed(world), fills, strokes, even_odd }
|
||||
}
|
||||
b"TxtT" => match crate::text::table(self, id, world) {
|
||||
Some(t) => Kind::Table(t),
|
||||
None => {
|
||||
self.warn("tables that could not be read");
|
||||
Kind::Unsupported
|
||||
}
|
||||
},
|
||||
b"TxtA" | b"TxtF" | b"TxtC" => match crate::text::read(self, id, world) {
|
||||
Some(t) => Kind::Text(t),
|
||||
None => {
|
||||
self.warn("text whose story could not be read (master-page text, or an unknown layout)");
|
||||
Kind::Unsupported
|
||||
}
|
||||
},
|
||||
b"ImgN" | b"Rstr" => match crate::raster::node_image(self, id, world)? {
|
||||
Some(img) => Kind::Image(img),
|
||||
None => Kind::Unsupported,
|
||||
},
|
||||
b"MPIN" => {
|
||||
// `SLnk` links the instance with the master spread it shows.
|
||||
let linked = s.obj(id, b"SLnk").map(|l| s.objs(l, b"ILOb")).unwrap_or_default();
|
||||
let master = linked.iter().find_map(|o| self.master_ids.iter().position(|m| m == o));
|
||||
let at = |t: &[u8; 4], default: usize| s.int(id, t).and_then(|v| usize::try_from(v).ok()).unwrap_or(default).min(4096);
|
||||
match master {
|
||||
Some(master) => Kind::MasterInstance { master, page: at(b"PgOf", 0), master_page: at(b"MPOf", 0), count: at(b"PgCt", 1) },
|
||||
None => {
|
||||
self.warn("master page instances without their master");
|
||||
Kind::Unsupported
|
||||
}
|
||||
}
|
||||
}
|
||||
b"EmbN" => match self.embedded_document(id, world) {
|
||||
// The embedded document itself, as editable content.
|
||||
Some(nodes) => {
|
||||
self.pending = Some(nodes);
|
||||
Kind::Group
|
||||
}
|
||||
None => match crate::raster::embedded(self, id, world)? {
|
||||
Some(img) => {
|
||||
self.warn("embedded documents and symbols (imported as pictures of them)");
|
||||
Kind::Image(img)
|
||||
}
|
||||
None => {
|
||||
self.warn("embedded documents and symbols without a cached picture");
|
||||
Kind::Unsupported
|
||||
}
|
||||
},
|
||||
},
|
||||
b"FRst" => {
|
||||
// A fill layer paints its whole bitmap area; its gradient lives in page space.
|
||||
let b = s.obj(id, b"Bitm");
|
||||
let size = |t: &[u8; 4]| b.and_then(|b| s.int(b, t)).map(|v| v as f64).filter(|v| *v > 0.0);
|
||||
match (size(b"BmpW"), size(b"BmpH")) {
|
||||
(Some(w), Some(h)) => {
|
||||
let local = Path { subpaths: vec![crate::shapes::rectangle(0.0, 0.0, w, h)] };
|
||||
let fills = paint::fills(self, id, parent, b"BFFl");
|
||||
Kind::Shape { path: local.transformed(world), fills, strokes: Vec::new(), even_odd: false }
|
||||
}
|
||||
_ => {
|
||||
self.warn("fill layers without an area");
|
||||
Kind::Unsupported
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.warn(format!("{} layers", describe(class)));
|
||||
Kind::Unsupported
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The enabled layer effects (`FiEf`) of node `id`. The angle convention was measured on the
|
||||
/// public MIT fx fixture (Patchy): an angle of π/2 with offset 10 shadows 10 below.
|
||||
fn effects(&mut self, id: ObjId, world: Affine, bounds: Option<Rect>) -> Vec<Effect> {
|
||||
let s = self.s;
|
||||
let mut out = Vec::new();
|
||||
for e in s.objs(id, b"FiEf").into_iter().take(64) {
|
||||
if s.bool(e, b"Enab") == Some(false) {
|
||||
continue;
|
||||
}
|
||||
// "Scale with object": lengths follow the node's transform; otherwise they are absolute.
|
||||
let k = if s.bool(e, b"SclO") == Some(true) { world.scale() } else { 1.0 };
|
||||
let len = |t: &[u8; 4]| s.f64(e, t).filter(|v| v.is_finite() && *v >= 0.0 && *v < 1e6).unwrap_or(0.0) * k;
|
||||
let opacity = s.f64(e, b"Opac").filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0);
|
||||
let angle = s.f64(e, b"Angl").filter(|v| v.is_finite()).unwrap_or(0.0);
|
||||
let color = s.obj(e, b"Colr").and_then(|c| crate::paint::color(self, c));
|
||||
let class = s.class(e).map(|c| c.0.to_be_bytes());
|
||||
match (class.as_ref(), color) {
|
||||
(Some(b"Shad"), Some(color)) => out.push(Effect::DropShadow { color, opacity, radius: len(b"Radi"), distance: len(b"Offs"), angle }),
|
||||
(Some(b"InnS"), Some(color)) => out.push(Effect::InnerShadow { color, opacity, radius: len(b"Radi"), distance: len(b"Offs"), angle }),
|
||||
(Some(b"OutG"), Some(color)) => out.push(Effect::OuterGlow { color, opacity, radius: len(b"Radi") }),
|
||||
(Some(b"Strk"), Some(color)) if s.enumeration(e, b"Ftyp").is_none_or(|(t, _)| t == 0) => {
|
||||
let align = s.enumeration(e, b"Alig").map_or(0, |(a, _)| a);
|
||||
out.push(Effect::Outline { color, opacity, width: len(b"Radi"), align });
|
||||
}
|
||||
(Some(b"Strk"), _) => self.warn("gradient outline effects (left out)"),
|
||||
(Some(b"BevE" | b"EmbE"), _) => {
|
||||
// No radius, no bevel (as Affinity draws it).
|
||||
let size = len(b"Radi");
|
||||
if size > 0.0 {
|
||||
let white = crate::paint::Color::Rgb { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
|
||||
let black = crate::paint::Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 1.0 };
|
||||
let highlight = s.obj(e, b"HiCl").and_then(|c| crate::paint::color(self, c)).unwrap_or(white);
|
||||
let shadow = s.obj(e, b"ShCl").and_then(|c| crate::paint::color(self, c)).unwrap_or(black);
|
||||
let shadow_opacity = s.f64(e, b"ShOp").filter(|v| v.is_finite()).unwrap_or(0.75).clamp(0.0, 1.0);
|
||||
let depth = s.f64(e, b"Dept").filter(|v| v.is_finite()).unwrap_or(5.0);
|
||||
let azimuth = s.f64(e, b"Azim").filter(|v| v.is_finite()).unwrap_or(std::f64::consts::FRAC_PI_4 * 3.0);
|
||||
let inner = s.enumeration(e, b"Beve").is_none_or(|(k, _)| k == 0);
|
||||
out.push(Effect::Bevel { size, depth, angle: azimuth, highlight, highlight_opacity: opacity, shadow, shadow_opacity, inner });
|
||||
}
|
||||
}
|
||||
(Some(b"ColO"), Some(color)) => {
|
||||
let blend = self.effect_blend(e);
|
||||
out.push(Effect::ColorOverlay { color, opacity, blend });
|
||||
}
|
||||
(Some(b"GrdO"), _) => {
|
||||
let blend = self.effect_blend(e);
|
||||
// The gradient's unit space spans the node's bounding box from -1 to 1, centred
|
||||
// on it (y down): checked against the stored previews of real documents.
|
||||
let space =
|
||||
bounds.map(|b| Affine([(b.x1 - b.x0) / 2.0, 0.0, 0.0, (b.y1 - b.y0) / 2.0, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0]));
|
||||
match (s.obj(e, b"GrFl"), space) {
|
||||
(Some(fill), Some(space)) => match paint::descriptor(self, fill, space) {
|
||||
Some(Paint::Gradient(gradient)) => out.push(Effect::GradientOverlay { gradient, opacity, blend }),
|
||||
Some(Paint::Solid(color)) => out.push(Effect::ColorOverlay { color, opacity, blend }),
|
||||
_ => {}
|
||||
},
|
||||
// Nothing visible to lay it over.
|
||||
(Some(_), None) => {}
|
||||
(None, _) => self.warn("gradient overlay effects that could not be read (left out)"),
|
||||
}
|
||||
}
|
||||
(Some(b"ColO"), None) => self.warn("colour overlay effects that could not be read (left out)"),
|
||||
(Some(b"Gaus"), _) => self.warn("blur effects (left out)"),
|
||||
_ => self.warn("layer effects of other kinds (left out)"),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A layer effect's blend mode (`BlnM`); unknown modes are Normal (warned).
|
||||
fn effect_blend(&mut self, e: ObjId) -> Blend {
|
||||
match self.s.enumeration(e, b"BlnM") {
|
||||
None => Blend::Normal,
|
||||
Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| {
|
||||
self.warn("an unknown blend mode (imported as Normal)");
|
||||
Blend::Normal
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Vector shapes attached to a node (`AdCh`) mask it: it shows only inside their outlines;
|
||||
/// an attached mask layer is a pixel mask. Adjustments attached the same way are reported.
|
||||
fn attached_masks(&mut self, id: ObjId, world: Affine, over: Option<Rect>) -> Result<(Option<Path>, Option<Image>), Error> {
|
||||
let s = self.s;
|
||||
let attached = s.objs(id, b"AdCh");
|
||||
let mut mask: Option<Path> = None;
|
||||
let mut pixels: Option<Image> = None;
|
||||
for a in attached {
|
||||
let class = s.class(a).unwrap_or(Tag(0));
|
||||
if s.bool(a, b"Visi") == Some(false) {
|
||||
continue;
|
||||
}
|
||||
if class == Tag::of(b"PCrv") || class == Tag::of(b"ShpN") || class == Tag::of(b"Comp") {
|
||||
let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world);
|
||||
if let Some((p, _)) = crate::geometry::outline(self, a, class, local) {
|
||||
mask.get_or_insert_with(Path::default).subpaths.extend(p.transformed(local).subpaths);
|
||||
}
|
||||
} else if class == Tag::of(b"MRst") {
|
||||
let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world);
|
||||
match crate::raster::mask(self, a, local, over)? {
|
||||
Some(m) if pixels.is_none() => pixels = Some(m),
|
||||
Some(_) => self.warn("several pixel masks on one layer (only the first is used)"),
|
||||
None => {}
|
||||
}
|
||||
} else {
|
||||
self.warn(format!("{} layers attached to other layers (imported without them)", describe(class)));
|
||||
}
|
||||
}
|
||||
Ok((mask, pixels))
|
||||
}
|
||||
|
||||
/// The content of an Affinity document embedded in this one (`EmbN` whose `EmbC` entry holds
|
||||
/// `EmDc`, four more bytes and a complete Affinity document): its first spread's nodes,
|
||||
/// placed so the centre of its page, first artboard or content is the node's origin.
|
||||
fn embedded_document(&mut self, id: ObjId, world: Affine) -> Option<Vec<Node>> {
|
||||
let s = self.s;
|
||||
let entry = s.obj(id, b"Bitm").and_then(|b| s.obj(b, b"EmCn")).and_then(|c| s.entry(c, b"EmbC"))?.to_string();
|
||||
if entry.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if self.depth >= MAX_EMBED_DEPTH {
|
||||
self.warn("embedded documents nested more than four deep");
|
||||
return None;
|
||||
}
|
||||
let data = self.archive.read(&entry).ok()?;
|
||||
let inner = data.strip_prefix(b"EmDc").and_then(|d| d.get(4..))?;
|
||||
if !crate::is_affinity(inner) {
|
||||
return None;
|
||||
}
|
||||
// A first reading finds its page and resolution, the second places it.
|
||||
// Both readings are charged to the budget and the archive's limits, also when they fail:
|
||||
// each does the work.
|
||||
let mut budget = self.budget;
|
||||
let probe = read_at(inner, self.archive.remaining(), &mut budget, Affine::IDENTITY, self.depth + 1);
|
||||
self.budget = budget;
|
||||
if self.archive.charge(probe.extracted).is_err() {
|
||||
self.warn("embedded documents beyond the size limit (left out)");
|
||||
return None;
|
||||
}
|
||||
let probe = match probe.document {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
self.warn(format!("embedded documents that could not be read ({e})"));
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let spread = probe.spreads.first()?;
|
||||
// `PBBx` 2 places the content's own bounds (as with a cached picture); otherwise its page.
|
||||
let content = s.obj(id, b"Bitm").and_then(|b| s.enumeration(b, b"PBBx")).is_some_and(|(k, _)| k == 2);
|
||||
let first_board = spread.nodes.iter().find_map(|n| if let Kind::Artboard { rect, .. } = &n.kind { Some(*rect) } else { None });
|
||||
let page = if content { None } else { spread.pages.first().copied().or(first_board) };
|
||||
let page = page.or_else(|| nodes_bounds(&spread.nodes)).unwrap_or(spread.bounds);
|
||||
// Its pixels aren't needed any more: never hold both readings' at once.
|
||||
drop(probe);
|
||||
// Its document pixels are the node's units, whatever either document's resolution.
|
||||
let k = 1.0;
|
||||
let (cx, cy) = ((page.x0 + page.x1) / 2.0, (page.y0 + page.y1) / 2.0);
|
||||
let base = Affine([k, 0.0, 0.0, k, -cx * k, -cy * k]).then(world);
|
||||
if !base.is_finite() {
|
||||
self.warn("embedded documents with an invalid placement");
|
||||
return None;
|
||||
}
|
||||
let mut budget = self.budget;
|
||||
let placed = read_at(inner, self.archive.remaining(), &mut budget, base, self.depth + 1);
|
||||
self.budget = budget;
|
||||
if self.archive.charge(placed.extracted).is_err() {
|
||||
self.warn("embedded documents beyond the size limit (left out)");
|
||||
return None;
|
||||
}
|
||||
let doc = placed.document.ok()?;
|
||||
for w in doc.warnings {
|
||||
self.warn(format!("{w} [in embedded documents]"));
|
||||
}
|
||||
if doc.spreads.len() > 1 {
|
||||
self.warn("embedded documents with several pages (the first is used)");
|
||||
}
|
||||
let mut nodes = doc.spreads.into_iter().next()?.nodes;
|
||||
// Its master page instances count its own masters, which aren't kept: in this document
|
||||
// they would show other masters.
|
||||
fn strip_masters(nodes: &mut [Node], depth: usize) -> bool {
|
||||
let mut found = false;
|
||||
for n in nodes {
|
||||
if matches!(n.kind, Kind::MasterInstance { .. }) {
|
||||
n.kind = Kind::Unsupported;
|
||||
found = true;
|
||||
}
|
||||
if depth < MAX_TREE_DEPTH {
|
||||
found |= strip_masters(&mut n.children, depth + 1);
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
if strip_masters(&mut nodes, 0) {
|
||||
self.warn("master pages of embedded documents (left out)");
|
||||
}
|
||||
Some(nodes)
|
||||
}
|
||||
|
||||
fn artboard(&mut self, id: ObjId, world: Affine) -> Kind {
|
||||
let s = self.s;
|
||||
let Some(b) = s.floats::<4>(id, b"ShpB").map(rect).filter(|b| b.x1 > b.x0 && b.y1 > b.y0) else {
|
||||
self.warn("an artboard without valid bounds (its children are kept without clipping)");
|
||||
return Kind::Unsupported;
|
||||
};
|
||||
let corners =
|
||||
[Point { x: b.x0, y: b.y0 }, Point { x: b.x1, y: b.y0 }, Point { x: b.x1, y: b.y1 }, Point { x: b.x0, y: b.y1 }].map(|p| world.apply(p));
|
||||
let [a, b2, c, d, ..] = world.0;
|
||||
if b2.abs() > 1e-9 || c.abs() > 1e-9 || a <= 0.0 || d <= 0.0 {
|
||||
self.warn("a rotated or flipped artboard (export bounds are its bounding box; artwork keeps its outline)");
|
||||
}
|
||||
let xs = corners.map(|p| p.x);
|
||||
let ys = corners.map(|p| p.y);
|
||||
let rect = Rect {
|
||||
x0: xs.iter().copied().fold(f64::INFINITY, f64::min),
|
||||
y0: ys.iter().copied().fold(f64::INFINITY, f64::min),
|
||||
x1: xs.iter().copied().fold(f64::NEG_INFINITY, f64::max),
|
||||
y1: ys.iter().copied().fold(f64::NEG_INFINITY, f64::max),
|
||||
};
|
||||
if ![rect.x0, rect.y0, rect.x1, rect.y1].iter().all(|v| v.is_finite()) || rect.x1 <= rect.x0 || rect.y1 <= rect.y0 {
|
||||
self.warn("an artboard with an invalid transformed size (its children are kept without clipping)");
|
||||
return Kind::Unsupported;
|
||||
}
|
||||
let class = s.class(id).unwrap_or(Tag::of(b"ShpN"));
|
||||
let (path, even_odd) = crate::geometry::outline(self, id, class, world).unwrap_or_else(|| {
|
||||
self.warn("an artboard whose outline could not be read (clipped to its rectangle)");
|
||||
(Path { subpaths: vec![crate::shapes::rectangle(b.x0, b.y0, b.x1, b.y1)] }, false)
|
||||
});
|
||||
let (background, strokes) = paint::node_paint(self, id, world);
|
||||
Kind::Artboard { rect, path: path.transformed(world), even_odd, background, strokes }
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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.
|
||||
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).
|
||||
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) }
|
||||
}
|
||||
|
||||
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",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
use super::read::MAX_TREE_DEPTH;
|
||||
use super::*;
|
||||
|
||||
/// The bounds of what visible `nodes` draw (control points of outlines, corners of images, frames
|
||||
/// and tables), in document pixels.
|
||||
pub fn nodes_bounds(nodes: &[Node]) -> Option<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",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,605 @@
|
||||
use super::bounds::{describe, is_container, mask_extent, nodes_bounds, pages, rect, tree_bounds, union};
|
||||
use super::*;
|
||||
|
||||
/// Largest embedded colour profile kept (real CMYK profiles are a few megabytes).
|
||||
const MAX_PROFILE_BYTES: usize = 32 << 20;
|
||||
|
||||
/// Deepest layer nesting followed; deeper content is reported, not imported.
|
||||
pub(super) const MAX_TREE_DEPTH: usize = 128;
|
||||
|
||||
/// Total layer nodes imported.
|
||||
const MAX_NODES: usize = 500_000;
|
||||
|
||||
/// Pixels decoded from pixel layers over a whole document (2 GB as RGBA). The archive's limits
|
||||
/// count the bytes extracted from it, and a layer of one flat colour needs none (#1704).
|
||||
const MAX_LAYER_PIXELS: u64 = 512 << 20;
|
||||
|
||||
/// Embedded documents inside embedded documents are followed this deep.
|
||||
const MAX_EMBED_DEPTH: usize = 4;
|
||||
|
||||
/// Characters of all stories together (a story may be shared by many text layers).
|
||||
const MAX_DOCUMENT_CHARS: usize = 16 << 20;
|
||||
|
||||
/// Table cells of all tables together (each becomes a text object with its edge lines).
|
||||
const MAX_DOCUMENT_CELLS: usize = 1 << 18;
|
||||
|
||||
/// What a whole read may still use. Shared objects can be linked from many layers, and embedded
|
||||
/// documents are read with what their embedding document left, so linking or embedding the
|
||||
/// same content many times can't multiply the work.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Budget {
|
||||
/// Layer nodes ([`MAX_NODES`] in all).
|
||||
pub(crate) nodes: usize,
|
||||
/// Pixels the pixel layers may decode ([`MAX_LAYER_PIXELS`] in all).
|
||||
pub(crate) pixels: u64,
|
||||
/// Characters of stories ([`MAX_DOCUMENT_CHARS`] in all).
|
||||
pub(crate) chars: usize,
|
||||
/// Table cells ([`MAX_DOCUMENT_CELLS`] in all).
|
||||
pub(crate) cells: usize,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
pub(crate) const FULL: Budget = Budget { nodes: MAX_NODES, pixels: MAX_LAYER_PIXELS, chars: MAX_DOCUMENT_CHARS, cells: MAX_DOCUMENT_CELLS };
|
||||
}
|
||||
|
||||
/// Read a document: archive, `doc.dat` and the model.
|
||||
pub fn read(bytes: &[u8], limits: Limits) -> Result<Document, Error> {
|
||||
read_within(bytes, limits, MAX_LAYER_PIXELS)
|
||||
}
|
||||
|
||||
/// [`read`], its pixel layers holding at most `pixels` pixels together.
|
||||
pub(crate) fn read_within(bytes: &[u8], limits: Limits, pixels: u64) -> Result<Document, Error> {
|
||||
read_at(bytes, limits, &mut Budget { pixels, ..Budget::FULL }, Affine::IDENTITY, 0).document
|
||||
}
|
||||
|
||||
/// A document read by [`read_at`] (or why it couldn't be), with the bytes its archive extracted
|
||||
/// either way.
|
||||
struct ReadAt {
|
||||
document: Result<Document, Error>,
|
||||
extracted: usize,
|
||||
}
|
||||
|
||||
/// Read a document whose spreads are placed by `base` (for embedded documents, nested `depth`
|
||||
/// deep). What it uses is taken from `budget`, also when it fails part of the way.
|
||||
/// The most characters of a layer's name kept.
|
||||
const MAX_NAME_CHARS: usize = 1024;
|
||||
|
||||
fn read_at(bytes: &[u8], limits: Limits, budget: &mut Budget, base: Affine, depth: usize) -> ReadAt {
|
||||
let mut archive = match Archive::open(bytes, limits) {
|
||||
Ok(a) => a,
|
||||
Err(e) => return ReadAt { document: Err(e), extracted: 0 },
|
||||
};
|
||||
let document = read_archive(&mut archive, budget, base, depth);
|
||||
ReadAt { document, extracted: archive.extracted() }
|
||||
}
|
||||
|
||||
fn read_archive(archive: &mut Archive, budget: &mut Budget, base: Affine, depth: usize) -> Result<Document, Error> {
|
||||
let doc = archive.read("doc.dat")?;
|
||||
let s = stream::parse(&doc)?;
|
||||
let mut reader = Reader::new(&s, archive, base, depth);
|
||||
reader.budget = *budget;
|
||||
let document = reader.document();
|
||||
*budget = reader.budget;
|
||||
document
|
||||
}
|
||||
|
||||
pub(crate) struct Reader<'s, 'a, 'b> {
|
||||
pub(crate) s: &'s Stream,
|
||||
pub(crate) archive: &'b mut Archive<'a>,
|
||||
pub(crate) dpi: f64,
|
||||
pub(crate) warnings: BTreeMap<String, usize>,
|
||||
active: HashSet<ObjId>,
|
||||
/// Where the spreads go: the identity, or an embedding document's placement.
|
||||
base: Affine,
|
||||
/// The linear part of `base`, which also scales frame text.
|
||||
pub(crate) type_base: Affine,
|
||||
/// How deep inside embedded documents this one is.
|
||||
depth: usize,
|
||||
/// An embedded document's content, waiting to become its node's children.
|
||||
pending: Option<Vec<Node>>,
|
||||
/// The master spreads, in the order of [`Document::masters`].
|
||||
master_ids: Vec<ObjId>,
|
||||
/// What the rest of the read may use.
|
||||
pub(crate) budget: Budget,
|
||||
}
|
||||
|
||||
impl<'s, 'a, 'b> Reader<'s, 'a, 'b> {
|
||||
pub(crate) fn new(s: &'s Stream, archive: &'b mut Archive<'a>, base: Affine, depth: usize) -> Self {
|
||||
let [a, b, c, d, ..] = base.0;
|
||||
Self {
|
||||
s,
|
||||
archive,
|
||||
dpi: 72.0,
|
||||
warnings: BTreeMap::new(),
|
||||
active: HashSet::new(),
|
||||
base,
|
||||
type_base: Affine([a, b, c, d, 0.0, 0.0]),
|
||||
depth,
|
||||
pending: None,
|
||||
master_ids: Vec::new(),
|
||||
budget: Budget::FULL,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn warn(&mut self, what: impl Into<String>) {
|
||||
*self.warnings.entry(what.into()).or_default() += 1;
|
||||
}
|
||||
|
||||
/// The document.
|
||||
fn document(&mut self) -> Result<Document, Error> {
|
||||
let s = self.s;
|
||||
let root = s.root;
|
||||
self.dpi = s.obj(root, b"UVCn").and_then(|u| s.f64(u, b"UPPI")).filter(|d| *d > 0.0 && *d < 100_000.0).unwrap_or(72.0);
|
||||
let saved_by = s.obj(root, b"NVer").map(|v| {
|
||||
let product = s.str(v, b"Prod").unwrap_or("Affinity");
|
||||
match (s.int(v, b"Majr"), s.int(v, b"Minr"), s.int(v, b"Bild")) {
|
||||
(Some(a), Some(b), Some(c)) => format!("{product} {a}.{b}.{c}"),
|
||||
_ => product.to_string(),
|
||||
}
|
||||
});
|
||||
let doc = s.obj(root, b"DocR").ok_or(Error::Malformed("document has no root node"))?;
|
||||
self.master_ids = s.objs(doc, b"MpCh").into_iter().filter(|m| s.is(*m, b"Sprd")).collect();
|
||||
let mut spreads = Vec::new();
|
||||
for spread in s.objs(doc, b"Chld") {
|
||||
if let Some(sp) = self.spread(doc, spread)? {
|
||||
spreads.push(sp);
|
||||
}
|
||||
}
|
||||
if spreads.is_empty() {
|
||||
return Err(Error::Malformed("document has no pages"));
|
||||
}
|
||||
let mut masters = Vec::new();
|
||||
for master in self.master_ids.clone() {
|
||||
match self.spread(doc, master)? {
|
||||
Some(sp) => masters.push(sp),
|
||||
// Keep the indices of `MasterInstance::master` valid.
|
||||
None => masters.push(Spread {
|
||||
bounds: Rect { x0: 0.0, y0: 0.0, x1: 0.0, y1: 0.0 },
|
||||
pages: Vec::new(),
|
||||
transparent: true,
|
||||
nodes: Vec::new(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
let cmyk_profile = s
|
||||
.obj(root, b"CMYP")
|
||||
.and_then(|p| s.bytes(p, b"Data"))
|
||||
.filter(|b| b.len() <= MAX_PROFILE_BYTES && b.get(16..20) == Some(b"CMYK".as_slice()))
|
||||
.map(<[u8]>::to_vec);
|
||||
let warnings = std::mem::take(&mut self.warnings).into_iter().map(|(w, n)| if n > 1 { format!("{w} ({n}×)") } else { w }).collect();
|
||||
Ok(Document { dpi: self.dpi, spreads, masters, saved_by, warnings, cmyk_profile })
|
||||
}
|
||||
|
||||
/// A spread (`Sprd`) of the document `doc`, or of its master spreads.
|
||||
fn spread(&mut self, doc: ObjId, spread: ObjId) -> Result<Option<Spread>, Error> {
|
||||
let s = self.s;
|
||||
if !s.is(spread, b"Sprd") {
|
||||
self.warn("an unknown kind of page");
|
||||
return Ok(None);
|
||||
}
|
||||
let pages = pages(s, spread);
|
||||
let default_size = s.floats::<2>(doc, b"DfSz").filter(|[w, h]| *w > 0.0 && *h > 0.0).map(|[w, h]| Rect { x0: 0.0, y0: 0.0, x1: w, y1: h });
|
||||
let bounds = s.floats::<4>(spread, b"SprB").map(rect).or_else(|| pages.iter().copied().reduce(union)).or(default_size).unwrap_or(Rect {
|
||||
x0: 0.0,
|
||||
y0: 0.0,
|
||||
x1: 0.0,
|
||||
y1: 0.0,
|
||||
});
|
||||
let transparent = s.bool(spread, b"SprT").unwrap_or(false);
|
||||
let (nodes, mask) = self.children(spread, self.base, 0)?;
|
||||
if mask.is_some() {
|
||||
self.warn("mask layers directly on a page (imported without them)");
|
||||
}
|
||||
Ok(Some(Spread { bounds, pages, transparent, nodes }))
|
||||
}
|
||||
|
||||
/// The children of `parent`, and the mask layer among them that masks the parent (with its
|
||||
/// placement), read later over just what it masks.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn children(&mut self, parent: ObjId, world: Affine, depth: usize) -> Result<(Vec<Node>, Option<(ObjId, Affine)>), Error> {
|
||||
let s = self.s;
|
||||
let mut out = Vec::new();
|
||||
let mut mask = None;
|
||||
for c in s.objs(parent, b"Chld") {
|
||||
if s.is(c, b"MRst") {
|
||||
// A mask layer inside a group or layer masks that container.
|
||||
if s.bool(c, b"Visi") == Some(false) {
|
||||
continue;
|
||||
}
|
||||
let local = s.floats::<6>(c, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
|
||||
if mask.is_none() {
|
||||
mask = Some((c, local.then(world)));
|
||||
} else {
|
||||
self.warn("several pixel masks on one layer (only the first is used)");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(n) = self.node(c, world, depth + 1)? {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
Ok((out, mask))
|
||||
}
|
||||
|
||||
fn node(&mut self, id: ObjId, parent: Affine, depth: usize) -> Result<Option<Node>, Error> {
|
||||
let s = self.s;
|
||||
if depth > MAX_TREE_DEPTH {
|
||||
self.warn("layers nested deeper than 128 levels");
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(left) = self.budget.nodes.checked_sub(1) else {
|
||||
return Err(Error::Limit("too many layers"));
|
||||
};
|
||||
self.budget.nodes = left;
|
||||
// A node that contains itself (a shared object linked back into its own subtree).
|
||||
if !self.active.insert(id) {
|
||||
self.warn("a layer that contains itself");
|
||||
return Ok(None);
|
||||
}
|
||||
let local = s.floats::<6>(id, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY);
|
||||
let world = local.then(parent);
|
||||
let class = s.class(id).unwrap_or(Tag(0));
|
||||
// A layer name is short; a long one is cut, as every visit of a shared object keeps a copy.
|
||||
let name: String = s.str(id, b"Desc").unwrap_or_default().chars().take(MAX_NAME_CHARS).collect();
|
||||
let visible = s.bool(id, b"Visi").unwrap_or(true);
|
||||
let locked = s.bool(id, b"Edtb").is_some_and(|e| !e);
|
||||
let opacity = s.f64(id, b"Opac").map_or(1.0, |o| o.clamp(0.0, 1.0));
|
||||
let blend = match s.enumeration(id, b"Blnd") {
|
||||
None if s.bool(id, b"PasT") != Some(false) && is_container(class) => Blend::PassThrough,
|
||||
None => Blend::Normal,
|
||||
Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| {
|
||||
self.warn("an unknown blend mode (imported as Normal)");
|
||||
Blend::Normal
|
||||
}),
|
||||
};
|
||||
let kind = if !world.is_finite() {
|
||||
self.warn("a layer with an invalid transform");
|
||||
Kind::Unsupported
|
||||
} else {
|
||||
self.kind(id, class, world, parent)?
|
||||
};
|
||||
// This node's embedded content, before its children's `node` calls can take it.
|
||||
let embedded = self.pending.take();
|
||||
// A compound's children are its operands, already merged into its outline.
|
||||
let (mut children, child_mask) = if class == Tag::of(b"Comp") { (Vec::new(), None) } else { self.children(id, world, depth)? };
|
||||
if let Some(embedded) = embedded {
|
||||
children.extend(embedded);
|
||||
}
|
||||
// Pixel masks are read only over what they mask (they can span a whole spread at print
|
||||
// resolution, a gigapixel).
|
||||
let over = mask_extent(&kind, &children);
|
||||
let child_mask = match child_mask {
|
||||
Some((c, at)) => crate::raster::mask(self, c, at, over)?,
|
||||
None => None,
|
||||
};
|
||||
let (mask, attached_mask) = self.attached_masks(id, world, over)?;
|
||||
let pixel_mask = attached_mask.or(child_mask);
|
||||
self.active.remove(&id);
|
||||
let mut node = Node { class, name, visible, locked, opacity, blend, kind, mask, pixel_mask, effects: Vec::new(), children };
|
||||
// Gradient overlays are laid out over the node's bounds, also while it is hidden.
|
||||
let bounds = tree_bounds(&node);
|
||||
node.effects = self.effects(id, world, bounds);
|
||||
Ok(Some(node))
|
||||
}
|
||||
|
||||
fn kind(&mut self, id: ObjId, class: Tag, world: Affine, parent: Affine) -> Result<Kind, Error> {
|
||||
let s = self.s;
|
||||
Ok(match &class.0.to_be_bytes() {
|
||||
b"Scop" => Kind::Layer,
|
||||
b"Grup" => Kind::Group,
|
||||
b"PCrv" | b"ShpN" | b"Comp" | b"SNEN" | b"SNRR" | b"ShRN" => {
|
||||
// Affinity 3.2.3's two-board public fixture marks board shapes with an `aprp`
|
||||
// property object in `phrp`, while older documents use `ABEn`. Ordinary shapes
|
||||
// in that fixture have neither. See the pinned corpus and validation audit.
|
||||
if s.bool(id, b"ABEn") == Some(true) || s.obj(id, b"phrp").is_some_and(|p| s.is(p, b"aprp")) {
|
||||
return Ok(self.artboard(id, world));
|
||||
}
|
||||
let Some((local, even_odd)) = crate::geometry::outline(self, id, class, world) else {
|
||||
self.warn(format!("a {} that could not be read", describe(class)));
|
||||
return Ok(Kind::Unsupported);
|
||||
};
|
||||
let (fills, strokes) = paint::node_paint(self, id, world);
|
||||
Kind::Shape { path: local.transformed(world), fills, strokes, even_odd }
|
||||
}
|
||||
b"TxtT" => match crate::text::table(self, id, world) {
|
||||
Some(t) => Kind::Table(t),
|
||||
None => {
|
||||
self.warn("tables that could not be read");
|
||||
Kind::Unsupported
|
||||
}
|
||||
},
|
||||
b"TxtA" | b"TxtF" | b"TxtC" => match crate::text::read(self, id, world) {
|
||||
Some(t) => Kind::Text(t),
|
||||
None => {
|
||||
self.warn("text whose story could not be read (master-page text, or an unknown layout)");
|
||||
Kind::Unsupported
|
||||
}
|
||||
},
|
||||
b"ImgN" | b"Rstr" => match crate::raster::node_image(self, id, world)? {
|
||||
Some(img) => Kind::Image(img),
|
||||
None => Kind::Unsupported,
|
||||
},
|
||||
b"MPIN" => {
|
||||
// `SLnk` links the instance with the master spread it shows.
|
||||
let linked = s.obj(id, b"SLnk").map(|l| s.objs(l, b"ILOb")).unwrap_or_default();
|
||||
let master = linked.iter().find_map(|o| self.master_ids.iter().position(|m| m == o));
|
||||
let at = |t: &[u8; 4], default: usize| s.int(id, t).and_then(|v| usize::try_from(v).ok()).unwrap_or(default).min(4096);
|
||||
match master {
|
||||
Some(master) => Kind::MasterInstance { master, page: at(b"PgOf", 0), master_page: at(b"MPOf", 0), count: at(b"PgCt", 1) },
|
||||
None => {
|
||||
self.warn("master page instances without their master");
|
||||
Kind::Unsupported
|
||||
}
|
||||
}
|
||||
}
|
||||
b"EmbN" => match self.embedded_document(id, world) {
|
||||
// The embedded document itself, as editable content.
|
||||
Some(nodes) => {
|
||||
self.pending = Some(nodes);
|
||||
Kind::Group
|
||||
}
|
||||
None => match crate::raster::embedded(self, id, world)? {
|
||||
Some(img) => {
|
||||
self.warn("embedded documents and symbols (imported as pictures of them)");
|
||||
Kind::Image(img)
|
||||
}
|
||||
None => {
|
||||
self.warn("embedded documents and symbols without a cached picture");
|
||||
Kind::Unsupported
|
||||
}
|
||||
},
|
||||
},
|
||||
b"FRst" => {
|
||||
// A fill layer paints its whole bitmap area; its gradient lives in page space.
|
||||
let b = s.obj(id, b"Bitm");
|
||||
let size = |t: &[u8; 4]| b.and_then(|b| s.int(b, t)).map(|v| v as f64).filter(|v| *v > 0.0);
|
||||
match (size(b"BmpW"), size(b"BmpH")) {
|
||||
(Some(w), Some(h)) => {
|
||||
let local = Path { subpaths: vec![crate::shapes::rectangle(0.0, 0.0, w, h)] };
|
||||
let fills = paint::fills(self, id, parent, b"BFFl");
|
||||
Kind::Shape { path: local.transformed(world), fills, strokes: Vec::new(), even_odd: false }
|
||||
}
|
||||
_ => {
|
||||
self.warn("fill layers without an area");
|
||||
Kind::Unsupported
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.warn(format!("{} layers", describe(class)));
|
||||
Kind::Unsupported
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The enabled layer effects (`FiEf`) of node `id`. The angle convention was measured on the
|
||||
/// public MIT fx fixture (Patchy): an angle of π/2 with offset 10 shadows 10 below.
|
||||
fn effects(&mut self, id: ObjId, world: Affine, bounds: Option<Rect>) -> Vec<Effect> {
|
||||
let s = self.s;
|
||||
let mut out = Vec::new();
|
||||
for e in s.objs(id, b"FiEf").into_iter().take(64) {
|
||||
if s.bool(e, b"Enab") == Some(false) {
|
||||
continue;
|
||||
}
|
||||
// "Scale with object": lengths follow the node's transform; otherwise they are absolute.
|
||||
let k = if s.bool(e, b"SclO") == Some(true) { world.scale() } else { 1.0 };
|
||||
let len = |t: &[u8; 4]| s.f64(e, t).filter(|v| v.is_finite() && *v >= 0.0 && *v < 1e6).unwrap_or(0.0) * k;
|
||||
let opacity = s.f64(e, b"Opac").filter(|v| v.is_finite()).unwrap_or(1.0).clamp(0.0, 1.0);
|
||||
let angle = s.f64(e, b"Angl").filter(|v| v.is_finite()).unwrap_or(0.0);
|
||||
let color = s.obj(e, b"Colr").and_then(|c| crate::paint::color(self, c));
|
||||
let class = s.class(e).map(|c| c.0.to_be_bytes());
|
||||
match (class.as_ref(), color) {
|
||||
(Some(b"Shad"), Some(color)) => out.push(Effect::DropShadow { color, opacity, radius: len(b"Radi"), distance: len(b"Offs"), angle }),
|
||||
(Some(b"InnS"), Some(color)) => out.push(Effect::InnerShadow { color, opacity, radius: len(b"Radi"), distance: len(b"Offs"), angle }),
|
||||
(Some(b"OutG"), Some(color)) => out.push(Effect::OuterGlow { color, opacity, radius: len(b"Radi") }),
|
||||
(Some(b"Strk"), Some(color)) if s.enumeration(e, b"Ftyp").is_none_or(|(t, _)| t == 0) => {
|
||||
let align = s.enumeration(e, b"Alig").map_or(0, |(a, _)| a);
|
||||
out.push(Effect::Outline { color, opacity, width: len(b"Radi"), align });
|
||||
}
|
||||
(Some(b"Strk"), _) => self.warn("gradient outline effects (left out)"),
|
||||
(Some(b"BevE" | b"EmbE"), _) => {
|
||||
// No radius, no bevel (as Affinity draws it).
|
||||
let size = len(b"Radi");
|
||||
if size > 0.0 {
|
||||
let white = crate::paint::Color::Rgb { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };
|
||||
let black = crate::paint::Color::Rgb { r: 0.0, g: 0.0, b: 0.0, a: 1.0 };
|
||||
let highlight = s.obj(e, b"HiCl").and_then(|c| crate::paint::color(self, c)).unwrap_or(white);
|
||||
let shadow = s.obj(e, b"ShCl").and_then(|c| crate::paint::color(self, c)).unwrap_or(black);
|
||||
let shadow_opacity = s.f64(e, b"ShOp").filter(|v| v.is_finite()).unwrap_or(0.75).clamp(0.0, 1.0);
|
||||
let depth = s.f64(e, b"Dept").filter(|v| v.is_finite()).unwrap_or(5.0);
|
||||
let azimuth = s.f64(e, b"Azim").filter(|v| v.is_finite()).unwrap_or(std::f64::consts::FRAC_PI_4 * 3.0);
|
||||
let inner = s.enumeration(e, b"Beve").is_none_or(|(k, _)| k == 0);
|
||||
out.push(Effect::Bevel { size, depth, angle: azimuth, highlight, highlight_opacity: opacity, shadow, shadow_opacity, inner });
|
||||
}
|
||||
}
|
||||
(Some(b"ColO"), Some(color)) => {
|
||||
let blend = self.effect_blend(e);
|
||||
out.push(Effect::ColorOverlay { color, opacity, blend });
|
||||
}
|
||||
(Some(b"GrdO"), _) => {
|
||||
let blend = self.effect_blend(e);
|
||||
// The gradient's unit space spans the node's bounding box from -1 to 1, centred
|
||||
// on it (y down): checked against the stored previews of real documents.
|
||||
let space =
|
||||
bounds.map(|b| Affine([(b.x1 - b.x0) / 2.0, 0.0, 0.0, (b.y1 - b.y0) / 2.0, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0]));
|
||||
match (s.obj(e, b"GrFl"), space) {
|
||||
(Some(fill), Some(space)) => match paint::descriptor(self, fill, space) {
|
||||
Some(Paint::Gradient(gradient)) => out.push(Effect::GradientOverlay { gradient, opacity, blend }),
|
||||
Some(Paint::Solid(color)) => out.push(Effect::ColorOverlay { color, opacity, blend }),
|
||||
_ => {}
|
||||
},
|
||||
// Nothing visible to lay it over.
|
||||
(Some(_), None) => {}
|
||||
(None, _) => self.warn("gradient overlay effects that could not be read (left out)"),
|
||||
}
|
||||
}
|
||||
(Some(b"ColO"), None) => self.warn("colour overlay effects that could not be read (left out)"),
|
||||
(Some(b"Gaus"), _) => self.warn("blur effects (left out)"),
|
||||
_ => self.warn("layer effects of other kinds (left out)"),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A layer effect's blend mode (`BlnM`); unknown modes are Normal (warned).
|
||||
fn effect_blend(&mut self, e: ObjId) -> Blend {
|
||||
match self.s.enumeration(e, b"BlnM") {
|
||||
None => Blend::Normal,
|
||||
Some((i, v)) => Blend::from_enum(i, v).unwrap_or_else(|| {
|
||||
self.warn("an unknown blend mode (imported as Normal)");
|
||||
Blend::Normal
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Vector shapes attached to a node (`AdCh`) mask it: it shows only inside their outlines;
|
||||
/// an attached mask layer is a pixel mask. Adjustments attached the same way are reported.
|
||||
fn attached_masks(&mut self, id: ObjId, world: Affine, over: Option<Rect>) -> Result<(Option<Path>, Option<Image>), Error> {
|
||||
let s = self.s;
|
||||
let attached = s.objs(id, b"AdCh");
|
||||
let mut mask: Option<Path> = None;
|
||||
let mut pixels: Option<Image> = None;
|
||||
for a in attached {
|
||||
let class = s.class(a).unwrap_or(Tag(0));
|
||||
if s.bool(a, b"Visi") == Some(false) {
|
||||
continue;
|
||||
}
|
||||
if class == Tag::of(b"PCrv") || class == Tag::of(b"ShpN") || class == Tag::of(b"Comp") {
|
||||
let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world);
|
||||
if let Some((p, _)) = crate::geometry::outline(self, a, class, local) {
|
||||
mask.get_or_insert_with(Path::default).subpaths.extend(p.transformed(local).subpaths);
|
||||
}
|
||||
} else if class == Tag::of(b"MRst") {
|
||||
let local = s.floats::<6>(a, b"Xfrm").map(Affine::from_xfrm).unwrap_or(Affine::IDENTITY).then(world);
|
||||
match crate::raster::mask(self, a, local, over)? {
|
||||
Some(m) if pixels.is_none() => pixels = Some(m),
|
||||
Some(_) => self.warn("several pixel masks on one layer (only the first is used)"),
|
||||
None => {}
|
||||
}
|
||||
} else {
|
||||
self.warn(format!("{} layers attached to other layers (imported without them)", describe(class)));
|
||||
}
|
||||
}
|
||||
Ok((mask, pixels))
|
||||
}
|
||||
|
||||
/// The content of an Affinity document embedded in this one (`EmbN` whose `EmbC` entry holds
|
||||
/// `EmDc`, four more bytes and a complete Affinity document): its first spread's nodes,
|
||||
/// placed so the centre of its page, first artboard or content is the node's origin.
|
||||
fn embedded_document(&mut self, id: ObjId, world: Affine) -> Option<Vec<Node>> {
|
||||
let s = self.s;
|
||||
let entry = s.obj(id, b"Bitm").and_then(|b| s.obj(b, b"EmCn")).and_then(|c| s.entry(c, b"EmbC"))?.to_string();
|
||||
if entry.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if self.depth >= MAX_EMBED_DEPTH {
|
||||
self.warn("embedded documents nested more than four deep");
|
||||
return None;
|
||||
}
|
||||
let data = self.archive.read(&entry).ok()?;
|
||||
let inner = data.strip_prefix(b"EmDc").and_then(|d| d.get(4..))?;
|
||||
if !crate::is_affinity(inner) {
|
||||
return None;
|
||||
}
|
||||
// A first reading finds its page and resolution, the second places it.
|
||||
// Both readings are charged to the budget and the archive's limits, also when they fail:
|
||||
// each does the work.
|
||||
let mut budget = self.budget;
|
||||
let probe = read_at(inner, self.archive.remaining(), &mut budget, Affine::IDENTITY, self.depth + 1);
|
||||
self.budget = budget;
|
||||
if self.archive.charge(probe.extracted).is_err() {
|
||||
self.warn("embedded documents beyond the size limit (left out)");
|
||||
return None;
|
||||
}
|
||||
let probe = match probe.document {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
self.warn(format!("embedded documents that could not be read ({e})"));
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let spread = probe.spreads.first()?;
|
||||
// `PBBx` 2 places the content's own bounds (as with a cached picture); otherwise its page.
|
||||
let content = s.obj(id, b"Bitm").and_then(|b| s.enumeration(b, b"PBBx")).is_some_and(|(k, _)| k == 2);
|
||||
let first_board = spread.nodes.iter().find_map(|n| if let Kind::Artboard { rect, .. } = &n.kind { Some(*rect) } else { None });
|
||||
let page = if content { None } else { spread.pages.first().copied().or(first_board) };
|
||||
let page = page.or_else(|| nodes_bounds(&spread.nodes)).unwrap_or(spread.bounds);
|
||||
// Its pixels aren't needed any more: never hold both readings' at once.
|
||||
drop(probe);
|
||||
// Its document pixels are the node's units, whatever either document's resolution.
|
||||
let k = 1.0;
|
||||
let (cx, cy) = ((page.x0 + page.x1) / 2.0, (page.y0 + page.y1) / 2.0);
|
||||
let base = Affine([k, 0.0, 0.0, k, -cx * k, -cy * k]).then(world);
|
||||
if !base.is_finite() {
|
||||
self.warn("embedded documents with an invalid placement");
|
||||
return None;
|
||||
}
|
||||
let mut budget = self.budget;
|
||||
let placed = read_at(inner, self.archive.remaining(), &mut budget, base, self.depth + 1);
|
||||
self.budget = budget;
|
||||
if self.archive.charge(placed.extracted).is_err() {
|
||||
self.warn("embedded documents beyond the size limit (left out)");
|
||||
return None;
|
||||
}
|
||||
let doc = placed.document.ok()?;
|
||||
for w in doc.warnings {
|
||||
self.warn(format!("{w} [in embedded documents]"));
|
||||
}
|
||||
if doc.spreads.len() > 1 {
|
||||
self.warn("embedded documents with several pages (the first is used)");
|
||||
}
|
||||
let mut nodes = doc.spreads.into_iter().next()?.nodes;
|
||||
// Its master page instances count its own masters, which aren't kept: in this document
|
||||
// they would show other masters.
|
||||
fn strip_masters(nodes: &mut [Node], depth: usize) -> bool {
|
||||
let mut found = false;
|
||||
for n in nodes {
|
||||
if matches!(n.kind, Kind::MasterInstance { .. }) {
|
||||
n.kind = Kind::Unsupported;
|
||||
found = true;
|
||||
}
|
||||
if depth < MAX_TREE_DEPTH {
|
||||
found |= strip_masters(&mut n.children, depth + 1);
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
if strip_masters(&mut nodes, 0) {
|
||||
self.warn("master pages of embedded documents (left out)");
|
||||
}
|
||||
Some(nodes)
|
||||
}
|
||||
|
||||
fn artboard(&mut self, id: ObjId, world: Affine) -> Kind {
|
||||
let s = self.s;
|
||||
let Some(b) = s.floats::<4>(id, b"ShpB").map(rect).filter(|b| b.x1 > b.x0 && b.y1 > b.y0) else {
|
||||
self.warn("an artboard without valid bounds (its children are kept without clipping)");
|
||||
return Kind::Unsupported;
|
||||
};
|
||||
let corners =
|
||||
[Point { x: b.x0, y: b.y0 }, Point { x: b.x1, y: b.y0 }, Point { x: b.x1, y: b.y1 }, Point { x: b.x0, y: b.y1 }].map(|p| world.apply(p));
|
||||
let [a, b2, c, d, ..] = world.0;
|
||||
if b2.abs() > 1e-9 || c.abs() > 1e-9 || a <= 0.0 || d <= 0.0 {
|
||||
self.warn("a rotated or flipped artboard (export bounds are its bounding box; artwork keeps its outline)");
|
||||
}
|
||||
let xs = corners.map(|p| p.x);
|
||||
let ys = corners.map(|p| p.y);
|
||||
let rect = Rect {
|
||||
x0: xs.iter().copied().fold(f64::INFINITY, f64::min),
|
||||
y0: ys.iter().copied().fold(f64::INFINITY, f64::min),
|
||||
x1: xs.iter().copied().fold(f64::NEG_INFINITY, f64::max),
|
||||
y1: ys.iter().copied().fold(f64::NEG_INFINITY, f64::max),
|
||||
};
|
||||
if ![rect.x0, rect.y0, rect.x1, rect.y1].iter().all(|v| v.is_finite()) || rect.x1 <= rect.x0 || rect.y1 <= rect.y0 {
|
||||
self.warn("an artboard with an invalid transformed size (its children are kept without clipping)");
|
||||
return Kind::Unsupported;
|
||||
}
|
||||
let class = s.class(id).unwrap_or(Tag::of(b"ShpN"));
|
||||
let (path, even_odd) = crate::geometry::outline(self, id, class, world).unwrap_or_else(|| {
|
||||
self.warn("an artboard whose outline could not be read (clipped to its rectangle)");
|
||||
(Path { subpaths: vec![crate::shapes::rectangle(b.x0, b.y0, b.x1, b.y1)] }, false)
|
||||
});
|
||||
let (background, strokes) = paint::node_paint(self, id, world);
|
||||
Kind::Artboard { rect, path: path.transformed(world), even_odd, background, strokes }
|
||||
}
|
||||
}
|
||||
@@ -119,7 +119,7 @@ pub fn tint_node(n: &mut Node, color: &Color, amount: f32) {
|
||||
for r in &mut t.runs {
|
||||
for p in [&mut r.style.fill, &mut r.style.stroke] {
|
||||
if let Paint::Solid { color: c, .. } = p {
|
||||
*c = c.lerp(color, amount);
|
||||
*p = Paint::solid(c.lerp(color, amount));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+36
-1
@@ -285,6 +285,13 @@ pub struct ArtBrush {
|
||||
pub scale: ArtScale,
|
||||
/// Width in percent.
|
||||
pub width: f64,
|
||||
/// How the width varies along a stroke: `None` (Fixed) always `width`; Pressure goes from
|
||||
/// `width` at the lightest pen pressure to [`Self::width_max`] at the heaviest.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub width_mode: Option<Variation>,
|
||||
/// The width at the heaviest pen pressure (%), for Pressure (`width` without one).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub width_max: Option<f64>,
|
||||
pub flip_along: bool,
|
||||
pub flip_across: bool,
|
||||
/// When true, art is placed on each run between sharp corners so folds do not overlap.
|
||||
@@ -295,6 +302,15 @@ pub struct ArtBrush {
|
||||
impl ArtBrush {
|
||||
/// The range of the width (%).
|
||||
pub const WIDTH_RANGE: (f64, f64) = (1.0, 1000.0);
|
||||
|
||||
/// The widths (%) at the lightest and the heaviest pen pressure: `width` for both unless the
|
||||
/// width follows the pressure.
|
||||
pub fn width_range(&self) -> (f64, f64) {
|
||||
match self.width_mode {
|
||||
Some(Variation::Pressure) => (self.width, self.width_max.unwrap_or(self.width)),
|
||||
_ => (self.width, self.width),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ArtBrush {
|
||||
@@ -304,6 +320,8 @@ impl Default for ArtBrush {
|
||||
direction: Direction::LeftToRight,
|
||||
scale: ArtScale::Stretch,
|
||||
width: 100.0,
|
||||
width_mode: None,
|
||||
width_max: None,
|
||||
flip_along: false,
|
||||
flip_across: false,
|
||||
overlap: false,
|
||||
@@ -458,6 +476,18 @@ impl Brush {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Brush::art`], to change (relink the resources it uses).
|
||||
pub fn art_mut(&mut self) -> Vec<&mut Node> {
|
||||
match &mut self.kind {
|
||||
BrushKind::Scatter(s) => vec![&mut s.art],
|
||||
BrushKind::Art(a) => vec![&mut a.art],
|
||||
BrushKind::Pattern(p) => std::iter::once(&mut p.side)
|
||||
.chain([&mut p.outer_corner, &mut p.inner_corner, &mut p.start, &mut p.end].into_iter().flatten())
|
||||
.collect(),
|
||||
BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// A brush definition from JSON (a stored library entry or a command's params), its values
|
||||
/// kept within their ranges ([`Brush::sanitize`]). A Hue Shift colorization without a `key`
|
||||
/// takes the color the art's fills and strokes use most (the first of [`art_colors`]), or
|
||||
@@ -508,6 +538,11 @@ impl Brush {
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
a.width = within(a.width, ArtBrush::WIDTH_RANGE, 100.0);
|
||||
// The width follows the pen's pressure or stays fixed.
|
||||
if a.width_mode != Some(Variation::Pressure) {
|
||||
a.width_mode = None;
|
||||
}
|
||||
a.width_max = a.width_max.map(|w| within(w, ArtBrush::WIDTH_RANGE, a.width));
|
||||
if let ArtScale::BetweenGuides { start, end } = &mut a.scale {
|
||||
*start = within(*start, (0.0, 1.0), 0.0);
|
||||
*end = within(*end, (0.0, 1.0), 1.0);
|
||||
@@ -592,7 +627,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
|
||||
let mut out = match &brush.kind {
|
||||
BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name),
|
||||
BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name),
|
||||
BrushKind::Art(a) => warp::art(a, bp, w),
|
||||
BrushKind::Art(a) => warp::art(a, bp, w, stroke.pressure.as_ref()),
|
||||
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke.pressure.as_ref(), &brush.name),
|
||||
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
|
||||
};
|
||||
|
||||
@@ -363,6 +363,12 @@ fn stain_mixes_type_strokes_too() {
|
||||
let mut art = type_art(red.clone(), red);
|
||||
tint_node(&mut art, &blue, 1.0);
|
||||
assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]);
|
||||
// Characters painted with a global swatch lose the link, as a path's paint does: the mixed color
|
||||
// is not the swatch's color.
|
||||
let linked = Paint::Solid { color: Color::rgb(1.0, 0.0, 0.0), swatch: Some("Red".into()), tint: 0.5 };
|
||||
let mut art = type_art(linked.clone(), linked);
|
||||
tint_node(&mut art, &blue, 1.0);
|
||||
assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -579,6 +585,78 @@ fn scatter_values_follow_their_modes() {
|
||||
assert!(serde_json::to_value(&unsaved).unwrap().get("modes").is_none(), "not saved when unset");
|
||||
}
|
||||
|
||||
/// Art Brush Options: with Width on Pressure the art goes from Width at the lightest pen pressure
|
||||
/// to the second width at the heaviest, along the stroke where the pen pressed; Fixed keeps Width.
|
||||
#[test]
|
||||
fn art_brush_width_follows_the_pressure() {
|
||||
let brush = |mode: Option<Variation>, max: Option<f64>| {
|
||||
let mut b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut b.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (50.0, mode, max);
|
||||
}
|
||||
b
|
||||
};
|
||||
let bp = line(0.0, 0.0, 100.0, 0.0);
|
||||
let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st);
|
||||
let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]);
|
||||
// 4 pt art at 50 %: 1 pt either side at the lightest; at 300 %: 6 pt at the heaviest.
|
||||
let out = draw(&brush(Some(Variation::Pressure), Some(300.0)), &ramp);
|
||||
assert!(near(half_width(&out, 0.0, 1.0), 1.0, 0.1), "{}", half_width(&out, 0.0, 1.0));
|
||||
assert!(near(half_width(&out, 99.0, 100.0), 6.0, 0.1), "{}", half_width(&out, 99.0, 100.0));
|
||||
assert!(near(half_width(&out, 49.0, 51.0), 3.5, 0.15), "{}", half_width(&out, 49.0, 51.0));
|
||||
// The stroke weight scales it.
|
||||
let out = draw(&brush(Some(Variation::Pressure), Some(300.0)), &StrokeLayer { width: 2.0, ..ramp.clone() });
|
||||
assert!(near(half_width(&out, 99.0, 100.0), 12.0, 0.2), "{}", half_width(&out, 99.0, 100.0));
|
||||
// Without recorded pressure, half way between the two widths.
|
||||
assert!(near(bounds(&draw(&brush(Some(Variation::Pressure), Some(300.0)), &stroke(1.0))).height(), 7.0, 1e-6));
|
||||
// Fixed (or a definition without a mode) keeps Width, whatever the pressure and the second width.
|
||||
for (mode, max) in [(None, Some(300.0)), (None, None), (Some(Variation::Pressure), None)] {
|
||||
let out = draw(&brush(mode, max), &ramp);
|
||||
assert!(near(bounds(&out).height(), 2.0, 1e-6), "{mode:?} {max:?}: {:?}", bounds(&out));
|
||||
}
|
||||
// A stroke in the art takes the width at the middle of its path: 50 % and 300 % for an even
|
||||
// light and heavy pressure, 175 % without recorded pressure.
|
||||
let mut stroked = brush(Some(Variation::Pressure), Some(300.0));
|
||||
if let BrushKind::Art(a) = &mut stroked.kind {
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((0.0, 0.0));
|
||||
bp.line_to((10.0, 0.0));
|
||||
a.art = Node::path(NodeId(0), vectorcraft_geom::PathData::from_bezpath(&bp), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0));
|
||||
}
|
||||
for (st, want) in [(pressed(vec![(0.0, 0.0), (1.0, 0.0)]), 1.0), (pressed(vec![(0.0, 1.0), (1.0, 1.0)]), 6.0), (stroke(1.0), 3.5)] {
|
||||
let out = draw(&stroked, &st);
|
||||
let w = out.first().and_then(|n| n.appearance.stroke()).map(|s| s.width);
|
||||
assert!(w.is_some_and(|w| near(w, want, 1e-6)), "{want}: {w:?}");
|
||||
}
|
||||
// Stretch Between Guides: an end outside the guides keeps the proportions of the width at its
|
||||
// end of the stroke. A 2 pt marker at the start of 10 × 4 pt art (guides at 20 % and 80 %),
|
||||
// 100 % to 300 % wide: 2 pt long at the lightest pressure, 6 pt at the heaviest.
|
||||
let marker =
|
||||
Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, -1.0, 2.0, 1.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let mut spacer = rect_art(10.0, 4.0);
|
||||
spacer.appearance = Appearance::default().into();
|
||||
let art = Node::group(NodeId(0), vec![std::sync::Arc::new(spacer), std::sync::Arc::new(marker)]);
|
||||
let mut guided = art_brush(art, ArtScale::BetweenGuides { start: 0.2, end: 0.8 });
|
||||
if let BrushKind::Art(a) = &mut guided.kind {
|
||||
(a.width_mode, a.width_max) = (Some(Variation::Pressure), Some(300.0));
|
||||
}
|
||||
for (p, long) in [(0.0, 2.0), (1.0, 6.0)] {
|
||||
let out = draw(&guided, &pressed(vec![(0.0, p), (1.0, p)]));
|
||||
let m = out.first().and_then(|g| g.children()).and_then(|c| c.get(1)).and_then(|m| m.geometric_bounds());
|
||||
assert!(m.is_some_and(|m| near(m.x0, 0.0, 1e-6) && near(m.x1, long, 1e-6)), "{p}: {m:?}");
|
||||
}
|
||||
// A mode the width does not take is read as Fixed, and the second width is kept within range.
|
||||
let lib = parse_library(&serde_json::json!([
|
||||
{"name": "a", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "random", "width_max": 1e308},
|
||||
{"name": "b", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "pressure", "width_max": 0.0},
|
||||
]));
|
||||
let [BrushKind::Art(a), BrushKind::Art(b)] = [&lib[0].kind, &lib[1].kind] else { panic!("{lib:?}") };
|
||||
assert_eq!((a.width_mode, a.width_max, b.width_mode, b.width_max), (None, Some(1000.0), Some(Variation::Pressure), Some(1.0)));
|
||||
// A brush without the new fields is written back without them.
|
||||
let plain = serde_json::to_value(art_brush(rect_art(10.0, 4.0), ArtScale::Stretch)).unwrap();
|
||||
assert!(plain.get("width_mode").is_none() && plain.get("width_max").is_none(), "{plain}");
|
||||
}
|
||||
|
||||
/// Definitions from files and commands are kept within their ranges.
|
||||
#[test]
|
||||
fn sanitize_keeps_values_within_their_ranges() {
|
||||
|
||||
+64
-11
@@ -169,6 +169,33 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option<N
|
||||
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), cross.abs())
|
||||
}
|
||||
|
||||
/// [`bend`], with the cross scale at arc length `s` multiplied by `widen(s)` (0..=1). The strokes
|
||||
/// of each object in the art take the factor at the middle of the object.
|
||||
fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64) -> Option<Node> {
|
||||
let cy = b.center().y;
|
||||
let x0 = b.x0;
|
||||
let f = move |p: Point| {
|
||||
let s = along.at(p.x - x0);
|
||||
t.map(s, (p.y - cy) * cross * widen(s))
|
||||
};
|
||||
let factor = |n: &Node| n.geometric_bounds().map_or(1.0, |r| widen(along.at(r.center().x - x0)));
|
||||
let art = widen_strokes(art, &factor);
|
||||
let scale = along.max_scale().max(cross.abs()).max(1e-6);
|
||||
let flat_tol = tolerance(b.height().max(b.width()) * scale) / scale;
|
||||
warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), cross.abs())
|
||||
}
|
||||
|
||||
/// `n` with the strokes of it and of everything inside it scaled by `factor` of the object they
|
||||
/// belong to.
|
||||
fn widen_strokes(n: &Node, factor: &dyn Fn(&Node) -> f64) -> Node {
|
||||
let mut out = n.clone();
|
||||
out.appearance.scale_strokes(factor(n));
|
||||
if let NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } = &mut out.kind {
|
||||
*children = children.iter().map(|c| Arc::new(widen_strokes(c, factor))).collect();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Arc-length spans to place art on when [`ArtBrush::overlap`] is on: one run between each sharp
|
||||
/// corner (the whole path when it has none).
|
||||
fn art_runs(t: &Track) -> Vec<(f64, f64)> {
|
||||
@@ -189,7 +216,17 @@ fn art_runs(t: &Track) -> Vec<(f64, f64)> {
|
||||
bounds.windows(2).map(|w| (w[0], w[1])).collect()
|
||||
}
|
||||
|
||||
fn art_on_run(a: &ArtBrush, t: &Track, s0: f64, s1: f64, art: &Node, b: Rect, cross: f64) -> Option<Node> {
|
||||
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1, and
|
||||
/// `width` the width (%) there.
|
||||
fn art_on_run(
|
||||
t: &Track,
|
||||
(s0, s1): (f64, f64),
|
||||
a: &ArtBrush,
|
||||
(art, b): (&Node, Rect),
|
||||
cross: f64,
|
||||
width: f64,
|
||||
widen: &dyn Fn(f64) -> f64,
|
||||
) -> Option<Node> {
|
||||
let l = s1 - s0;
|
||||
if l <= 1e-9 {
|
||||
return None;
|
||||
@@ -199,33 +236,49 @@ fn art_on_run(a: &ArtBrush, t: &Track, s0: f64, s1: f64, art: &Node, b: Rect, cr
|
||||
ArtScale::Stretch => (AlongMap::linear(w, s0, s1), cross),
|
||||
ArtScale::Proportional => {
|
||||
let k = l / w;
|
||||
(AlongMap::linear(w, s0, s1), k * a.width / 100.0)
|
||||
(AlongMap::linear(w, s0, s1), k * width / 100.0)
|
||||
}
|
||||
ArtScale::BetweenGuides { start, end } => {
|
||||
let (g0, g1) = (start.clamp(0.0, 1.0) * w, end.clamp(0.0, 1.0) * w);
|
||||
let (g0, g1) = (g0.min(g1), g0.max(g1));
|
||||
let fixed = (g0 + (w - g1)) * cross;
|
||||
// The ends keep the proportions of the width at their end of the run.
|
||||
let (c0, c1) = (cross * widen(s0), cross * widen(s1));
|
||||
let fixed = g0 * c0 + (w - g1) * c1;
|
||||
if fixed >= l || g1 - g0 < 1e-9 {
|
||||
(AlongMap::linear(w, s0, s1), cross)
|
||||
} else {
|
||||
(AlongMap { xs: [0.0, g0, g1, w], ss: [s0, s0 + g0 * cross, s1 - (w - g1) * cross, s1] }, cross)
|
||||
(AlongMap { xs: [0.0, g0, g1, w], ss: [s0, s0 + g0 * c0, s1 - (w - g1) * c1, s1] }, cross)
|
||||
}
|
||||
}
|
||||
};
|
||||
bend(t, art, b, along, cross)
|
||||
bend_widened(t, art, b, along, cross, widen)
|
||||
}
|
||||
|
||||
pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64) -> Vec<Node> {
|
||||
/// 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> {
|
||||
let Some((art, b)) = oriented(&a.art, a.direction, a.flip_along, a.flip_across) else { return vec![] };
|
||||
let cross = weight * a.width / 100.0;
|
||||
let (light, heavy) = a.width_range();
|
||||
let width = light.max(heavy);
|
||||
let cross = weight * width / 100.0;
|
||||
let mut out = vec![];
|
||||
for t in tracks(bp, 0.05) {
|
||||
if t.len() <= 1e-9 {
|
||||
let l = t.len();
|
||||
if l <= 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, t.len())] };
|
||||
for (s0, s1) in runs {
|
||||
if let Some(n) = art_on_run(a, &t, s0, s1, &art, b, cross) {
|
||||
let widen = |s: f64| {
|
||||
if light == heavy || width <= 0.0 {
|
||||
return 1.0;
|
||||
}
|
||||
// A run past the start of a closed track wraps round to it.
|
||||
let at = if s > l { s - l } else { s };
|
||||
let p = pressure.map_or(PressureProfile::MID, |p| p.at(at / l)).clamp(0.0, 1.0);
|
||||
(light + (heavy - light) * p) / width
|
||||
};
|
||||
let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] };
|
||||
for run in runs {
|
||||
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, width, &widen) {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
|
||||
File renamed without changes.
@@ -801,468 +801,4 @@ pub fn dither_noise(x: u32, y: u32, channel: u32) -> f32 {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sample_endpoints_and_mid() {
|
||||
let g = Gradient::default();
|
||||
assert_eq!(g.sample(0.0).0.to_hex(), "#ffffff");
|
||||
assert_eq!(g.sample(1.0).0.to_hex(), "#000000");
|
||||
let mid = g.sample(0.5).0.to_rgb()[0];
|
||||
assert!((mid - 0.5).abs() < 1e-5);
|
||||
}
|
||||
|
||||
/// Sampling increasing positions in one pass gives what sampling each alone does, out-of-order
|
||||
/// and repeated stop offsets included.
|
||||
#[test]
|
||||
fn increasing_samples_match_single_samples() {
|
||||
let stop = |offset: f32, hex: &str, midpoint: f32| GradientStop { midpoint, ..GradientStop::new(offset, Color::from_hex(hex).unwrap()) };
|
||||
let g = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![
|
||||
stop(0.1, "#ff0000", 0.3),
|
||||
stop(0.4, "#00ff00", 0.7),
|
||||
stop(0.4, "#0000ff", 0.5),
|
||||
stop(0.2, "#ffff00", 0.5),
|
||||
stop(0.9, "#000000", 0.5),
|
||||
],
|
||||
);
|
||||
let ts: Vec<f32> = (0..=40).map(|k| k as f32 / 40.0).collect();
|
||||
let one_by_one: Vec<_> = ts.iter().map(|&t| g.sample_with(t, Color::lerp_keep_model)).collect();
|
||||
assert_eq!(g.sample_increasing_with(ts, Color::lerp_keep_model), one_by_one);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midpoint_shifts() {
|
||||
let mut g = Gradient::default();
|
||||
g.stops[0].midpoint = 0.25;
|
||||
// At t = 0.25 we should be half way.
|
||||
assert!((g.sample(0.25).0.to_rgb()[0] - 0.5).abs() < 1e-5);
|
||||
assert_eq!(g.expanded_stops().len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fit_linear_horizontal() {
|
||||
let g = GradientGeom::fit(GradientKind::Linear, Rect::new(0.0, 0.0, 100.0, 50.0), 0.0);
|
||||
assert_eq!(g.start, Point::new(0.0, 25.0));
|
||||
assert_eq!(g.end, Point::new(100.0, 25.0));
|
||||
assert!((g.angle_deg()).abs() < 1e-9);
|
||||
let v = GradientGeom::fit(GradientKind::Linear, Rect::new(0.0, 0.0, 100.0, 50.0), 90.0);
|
||||
assert!((v.angle_deg() - 90.0).abs() < 1e-9);
|
||||
assert!((v.length() - 50.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_stops() {
|
||||
let mut g = Gradient::default();
|
||||
g.reverse();
|
||||
assert_eq!(g.stops[0].color.to_hex(), "#000000");
|
||||
assert_eq!(g.stops[0].offset, 0.0);
|
||||
}
|
||||
|
||||
/// #1007: reversing mirrors off-centre midpoints with their segments, so the ramp is the same
|
||||
/// the other way round.
|
||||
#[test]
|
||||
fn reverse_mirrors_midpoints() {
|
||||
let stop = |offset, hex, midpoint| GradientStop { midpoint, ..GradientStop::new(offset, Color::from_hex(hex).unwrap()) };
|
||||
let two = Gradient::new(GradientKind::Linear, vec![stop(0.0, "#ff0000", 0.2), stop(1.0, "#0000ff", 0.5)]);
|
||||
let three = Gradient::new(GradientKind::Linear, vec![stop(0.0, "#ff0000", 0.2), stop(0.3, "#00ff00", 0.8), stop(1.0, "#0000ff", 0.5)]);
|
||||
for g in [two, three] {
|
||||
let mut r = g.clone();
|
||||
r.reverse();
|
||||
let mids: Vec<f32> = r.stops.iter().map(|s| s.midpoint).collect();
|
||||
let want: Vec<f32> = g.stops.iter().rev().skip(1).map(|s| 1.0 - s.midpoint).chain([0.5]).collect();
|
||||
assert!(mids.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-6), "{mids:?} {want:?}");
|
||||
for i in 0..=20 {
|
||||
let t = i as f32 / 20.0;
|
||||
let ((a, ao), (b, bo)) = (g.sample(t), r.sample(1.0 - t));
|
||||
let same = a.to_rgba8(1.0).iter().zip(b.to_rgba8(1.0)).all(|(x, y)| x.abs_diff(y) <= 1);
|
||||
assert!(same && (ao - bo).abs() < 1e-6, "t {t}: {a:?} vs {b:?}");
|
||||
}
|
||||
r.reverse();
|
||||
let back = r.stops.iter().zip(&g.stops).all(|(a, b)| (a.offset - b.offset).abs() < 1e-6 && (a.midpoint - b.midpoint).abs() < 1e-6);
|
||||
assert!(back, "reversed twice, it is as it was: {:?}", r.stops);
|
||||
}
|
||||
}
|
||||
|
||||
fn close(a: Point, b: Point) -> bool {
|
||||
a.distance(b) < 1e-9
|
||||
}
|
||||
|
||||
fn linear(start: (f64, f64), end: (f64, f64)) -> GradientGeom {
|
||||
GradientGeom { start: start.into(), end: end.into(), aspect: 1.0, focal: None }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_90_gives_vertical_vector() {
|
||||
let mut g = linear((0.0, 0.0), (100.0, 0.0));
|
||||
g.transform(Affine::rotate(std::f64::consts::FRAC_PI_2), GradientKind::Linear);
|
||||
assert!(close(g.start, Point::ZERO) && close(g.end, Point::new(0.0, 100.0)), "{g:?}");
|
||||
assert!((g.angle_deg() + 90.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflect_swaps_start_and_end() {
|
||||
let mut g = linear((0.0, 25.0), (100.0, 25.0));
|
||||
// Reflect across the vertical axis through x = 50.
|
||||
let flip = Affine::translate((50.0, 0.0)) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate((-50.0, 0.0));
|
||||
g.transform(flip, GradientKind::Linear);
|
||||
assert!(close(g.start, Point::new(100.0, 25.0)) && close(g.end, Point::new(0.0, 25.0)), "{g:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_uniform_scale_turns_a_circle_into_an_ellipse() {
|
||||
let mut g = GradientGeom { start: Point::new(10.0, 10.0), end: Point::new(20.0, 10.0), aspect: 1.0, focal: None };
|
||||
g.transform(Affine::scale_non_uniform(2.0, 1.0), GradientKind::Radial);
|
||||
assert!(close(g.start, Point::new(20.0, 10.0)) && close(g.end, Point::new(40.0, 10.0)), "{g:?}");
|
||||
assert!((g.aspect - 0.5).abs() < 1e-9);
|
||||
// A vertical vector keeps its axis: the ellipse is twice as wide as the vector is long.
|
||||
let mut v = GradientGeom { start: Point::ZERO, end: Point::new(0.0, -10.0), aspect: 1.0, focal: None };
|
||||
v.transform(Affine::scale_non_uniform(2.0, 1.0), GradientKind::Radial);
|
||||
assert!(close(v.end, Point::new(0.0, -10.0)) && (v.aspect - 2.0).abs() < 1e-9, "{v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn samples_follow_shear_and_rotation() {
|
||||
let shear = Affine::new([1.0, 0.3, 0.7, 1.2, 15.0, -4.0]) * Affine::rotate(0.4);
|
||||
for kind in [GradientKind::Linear, GradientKind::Radial] {
|
||||
let g = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(80.0, 55.0), aspect: 0.6, focal: None };
|
||||
let mut m = g;
|
||||
m.transform(shear, kind);
|
||||
for p in [Point::new(30.0, 40.0), Point::new(55.0, 70.0), Point::new(90.0, 10.0), Point::new(-20.0, 48.0)] {
|
||||
let (a, b) = (g.param_at(kind, p), m.param_at(kind, shear * p));
|
||||
assert!((a - b).abs() < 1e-9, "{kind:?} at {p:?}: {a} vs {b}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_fit_uses_the_angle_and_param_honours_aspect() {
|
||||
let b = Rect::new(0.0, 0.0, 100.0, 60.0);
|
||||
let g = GradientGeom::fit(GradientKind::Radial, b, 90.0);
|
||||
assert!(close(g.start, Point::new(50.0, 30.0)) && close(g.end, Point::new(50.0, -20.0)), "end above the centre: {g:?}");
|
||||
let e = GradientGeom { start: Point::ZERO, end: Point::new(10.0, 0.0), aspect: 0.5, focal: None };
|
||||
assert!((e.param_at(GradientKind::Radial, Point::new(0.0, 5.0)) - 1.0).abs() < 1e-12);
|
||||
assert!((e.param_at(GradientKind::Radial, Point::new(5.0, 0.0)) - 0.5).abs() < 1e-12);
|
||||
assert!((e.param_at(GradientKind::Linear, Point::new(5.0, 7.0)) - 0.5).abs() < 1e-12);
|
||||
}
|
||||
|
||||
fn g3() -> Gradient {
|
||||
let mut g = Gradient::default();
|
||||
g.stops.insert(1, GradientStop::new(0.5, Color::rgb(1.0, 0.0, 0.0)));
|
||||
g
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_samples_color_and_sorts() {
|
||||
let g = Gradient::default();
|
||||
let (stops, i) = insert_stop(&g, 0.25);
|
||||
assert_eq!(stops.len(), 3);
|
||||
assert_eq!(i, 1);
|
||||
let r = stops[1].color.to_rgb()[0];
|
||||
assert!((r - 0.75).abs() < 1e-4, "sampled {r}");
|
||||
let (stops, i) = insert_stop(&g, 2.0);
|
||||
assert_eq!(i, 2);
|
||||
assert_eq!(stops[2].offset, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_keeps_two() {
|
||||
let g = g3();
|
||||
let v = remove_stop(&g.stops, 1).unwrap();
|
||||
assert_eq!(v.len(), 2);
|
||||
assert!(remove_stop(&v, 0).is_none());
|
||||
assert!(remove_stop(&g.stops, 9).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_reorders_and_tracks_index() {
|
||||
let g = g3();
|
||||
let (v, i) = move_stop(&g.stops, 0, 0.8);
|
||||
assert_eq!(i, 1);
|
||||
assert_eq!(v[1].color.to_hex(), "#ffffff");
|
||||
assert!(v.windows(2).all(|w| w[0].offset <= w[1].offset));
|
||||
let (v, i) = move_stop(&g.stops, 1, -3.0);
|
||||
// Clamped to 0 and placed after the existing stop at 0.
|
||||
assert_eq!((i, v[i].offset, v[i].color.to_hex()), (1, 0.0, "#ff0000".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_copies_the_stop_to_a_new_offset() {
|
||||
let g = g3();
|
||||
let (v, i) = duplicate_stop(&g.stops, 1, 0.9);
|
||||
assert_eq!((v.len(), i, v[i].offset, v[i].color.to_hex()), (4, 2, 0.9, "#ff0000".to_string()));
|
||||
assert_eq!(v[1], g.stops[1], "the original stays");
|
||||
assert_eq!(duplicate_stop(&g.stops, 7, 0.5).0, g.stops);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swap_exchanges_only_the_colours() {
|
||||
let mut g = g3();
|
||||
g.stops[0].opacity = 0.25;
|
||||
let v = swap_stop_colors(&g.stops, 0, 1);
|
||||
assert_eq!((v[0].color.to_hex(), v[1].color.to_hex()), ("#ff0000".to_string(), "#ffffff".to_string()));
|
||||
assert_eq!((v[0].offset, v[0].opacity, v[1].offset, v[1].opacity), (0.0, 0.25, 0.5, 1.0));
|
||||
assert_eq!(swap_stop_colors(&g.stops, 0, 9), g.stops);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midpoint_math() {
|
||||
let g = g3();
|
||||
assert_eq!(midpoint_pos(&g.stops, 0), Some(0.25));
|
||||
assert_eq!(midpoint_pos(&g.stops, 2), None);
|
||||
let m = midpoint_from_pos(&g.stops, 1, 0.6).unwrap();
|
||||
assert!((m - 0.2).abs() < 1e-5);
|
||||
assert_eq!(midpoint_from_pos(&g.stops, 1, 0.51).unwrap(), 0.13);
|
||||
let v = set_midpoint(&g.stops, 0, 0.99);
|
||||
assert_eq!(v[0].midpoint, 0.87);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rebase_keeps_relative_positions() {
|
||||
let mut g = GradientGeom { start: Point::new(110.0, 150.0), end: Point::new(190.0, 120.0), aspect: 0.5, focal: None };
|
||||
g.rebase(Rect::new(100.0, 100.0, 200.0, 200.0), Rect::new(500.0, 0.0, 700.0, 50.0));
|
||||
assert!(close(g.start, Point::new(520.0, 25.0)) && close(g.end, Point::new(680.0, 10.0)) && g.aspect == 0.5, "{g:?}");
|
||||
// A box without height (a horizontal line) keeps the offset from its centre line.
|
||||
let mut h = GradientGeom { start: Point::new(0.0, 12.0), end: Point::new(10.0, 10.0), aspect: 1.0, focal: None };
|
||||
h.rebase(Rect::new(0.0, 10.0, 10.0, 10.0), Rect::new(0.0, 0.0, 20.0, 40.0));
|
||||
assert!(close(h.start, Point::new(0.0, 22.0)) && close(h.end, Point::new(20.0, 20.0)), "{h:?}");
|
||||
// Unplaced paints have nothing to move.
|
||||
let mut p = GradientPaint::new(Gradient::default());
|
||||
p.rebase(Rect::new(0.0, 0.0, 1.0, 1.0), Rect::new(5.0, 5.0, 9.0, 9.0));
|
||||
assert_eq!(p.geom, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pin_fixes_the_fit_once() {
|
||||
let mut p = GradientPaint::new(Gradient::default());
|
||||
p.angle = 90.0;
|
||||
let b = Rect::new(0.0, 0.0, 100.0, 50.0);
|
||||
p.pin(b);
|
||||
assert_eq!(p.geom, Some(GradientGeom::fit(GradientKind::Linear, b, 90.0)));
|
||||
p.pin(Rect::new(0.0, 0.0, 1.0, 1.0));
|
||||
assert_eq!(p.geom, Some(GradientGeom::fit(GradientKind::Linear, b, 90.0)));
|
||||
}
|
||||
|
||||
/// A 100 pt circle at (200, 200) with its focal point 40 pt left of the centre.
|
||||
fn off_centre() -> GradientGeom {
|
||||
let mut g = GradientGeom { start: Point::new(200.0, 200.0), end: Point::new(300.0, 200.0), aspect: 1.0, focal: None };
|
||||
g.set_focal(Some(Point::new(160.0, 200.0)));
|
||||
g
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focal_round_trips_through_serde_and_defaults_to_none() {
|
||||
let g = off_centre();
|
||||
let s = serde_json::to_string(&g).unwrap();
|
||||
assert!(s.contains("\"focal\""), "{s}");
|
||||
assert_eq!(serde_json::from_str::<GradientGeom>(&s).unwrap(), g);
|
||||
// Placements saved before focal points existed load centred, and centred ones write none.
|
||||
let old: GradientGeom = serde_json::from_str(r#"{"start":{"x":0.0,"y":0.0},"end":{"x":1.0,"y":0.0}}"#).unwrap();
|
||||
assert_eq!((old.focal, old.aspect), (None, 1.0));
|
||||
assert!(!serde_json::to_string(&old).unwrap().contains("focal"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focal_follows_transforms_and_rebases() {
|
||||
let mut g = off_centre();
|
||||
let a = Affine::translate((10.0, -5.0)) * Affine::rotate(0.7) * Affine::scale_non_uniform(2.0, 0.5);
|
||||
let f = a * g.focal.unwrap();
|
||||
g.transform(a, GradientKind::Radial);
|
||||
assert!(close(g.focal.unwrap(), f), "{g:?}");
|
||||
// Still at the same parameter: the first stop.
|
||||
assert!(g.param_at(GradientKind::Radial, f).abs() < 1e-9);
|
||||
let mut h = off_centre();
|
||||
h.rebase(Rect::new(100.0, 100.0, 300.0, 300.0), Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
assert!(close(h.focal.unwrap(), Point::new(30.0, 50.0)) && close(h.start, Point::new(50.0, 50.0)), "{h:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn param_runs_from_the_focal_point_to_the_ellipse() {
|
||||
let g = off_centre();
|
||||
let t = |x: f64, y: f64| g.param_at(GradientKind::Radial, Point::new(x, y));
|
||||
assert!(t(160.0, 200.0).abs() < 1e-9);
|
||||
// The extent circle is the last stop all round.
|
||||
for a in [0.0f64, 1.0, 2.5, 4.0] {
|
||||
let p = Point::new(200.0 + 100.0 * a.cos(), 200.0 + 100.0 * a.sin());
|
||||
assert!((g.param_at(GradientKind::Radial, p) - 1.0).abs() < 1e-9, "{a}");
|
||||
}
|
||||
// The centre lies on the level-2/7 circle: centred 2/7 of the way back to the focal point
|
||||
// (0.4 of the radius off), with a radius of 2/7.
|
||||
assert!((t(200.0, 200.0) - 2.0 / 7.0).abs() < 1e-9, "{}", t(200.0, 200.0));
|
||||
assert!(t(180.0, 200.0) < t(220.0, 200.0), "nearer the focal side is earlier");
|
||||
assert_eq!(GradientGeom { focal: None, ..g }.param_at(GradientKind::Radial, Point::new(250.0, 200.0)), 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focal_is_kept_inside_the_ellipse_and_follows_its_reshaping() {
|
||||
let mut g = off_centre();
|
||||
g.set_focal(Some(Point::new(500.0, 200.0)));
|
||||
assert!(close(g.focal.unwrap(), Point::new(299.0, 200.0)), "pulled inside: {g:?}");
|
||||
g.set_focal(Some(Point::new(200.0, 200.0)));
|
||||
assert_eq!(g.focal, None, "on the centre: centred");
|
||||
// A new vector and aspect keep it in its place in the ellipse.
|
||||
let before = off_centre();
|
||||
let mut h = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.0, 50.0), aspect: 0.5, focal: None };
|
||||
h.keep_focal_from(&before);
|
||||
assert!(close(h.focal.unwrap(), Point::new(0.0, -20.0)), "{h:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixels_sample_the_ramp_at_each_cell_centre() {
|
||||
// White → black left to right over a 10 × 2 box, a midpoint at 30% and a half-opaque end.
|
||||
let mut g = GradientPaint::new(Gradient::default());
|
||||
g.gradient.stops[0].midpoint = 0.3;
|
||||
g.gradient.stops[1].opacity = 0.5;
|
||||
let b = Rect::new(0.0, 0.0, 10.0, 2.0);
|
||||
let px: Vec<[u8; 4]> = g.pixels(b, b, 10, 2, true, &Color::to_rgb).collect();
|
||||
assert_eq!(px.len(), 20);
|
||||
let ramp = Ramp::new(&g.gradient, &Color::to_rgb);
|
||||
for (i, p) in px.iter().take(10).enumerate() {
|
||||
let c = ramp.at((i as f32 + 0.5) / 10.0).map(|v| (v * 255.0).round() as u8);
|
||||
assert_eq!(*p, c, "pixel {i}");
|
||||
}
|
||||
assert_eq!(px[3], px[13], "rows alike");
|
||||
// The midpoint stop: grey at 30%; padded past the ends.
|
||||
assert!((ramp.at(0.3)[0] - 0.5).abs() < 0.02, "{:?}", ramp.at(0.3));
|
||||
assert_eq!(ramp.at(-1.0), [1.0, 1.0, 1.0, 1.0]);
|
||||
assert_eq!(ramp.at(2.0), [0.0, 0.0, 0.0, 0.5]);
|
||||
assert_eq!(ramp.at(f32::NAN), [1.0, 1.0, 1.0, 1.0]);
|
||||
}
|
||||
|
||||
fn blue_yellow(method: GradientMethod) -> Gradient {
|
||||
let mut g = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::rgb(1.0, 1.0, 0.0))],
|
||||
);
|
||||
g.method = method;
|
||||
g
|
||||
}
|
||||
|
||||
/// Illustrator 30's Perceptual method mixes colours in a perceptually even way
|
||||
/// (https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/control-perceptual-interpolation-in-gradients.html).
|
||||
/// Here that is OKLab: blue → yellow passes through a light blue-grey, not the flat mid grey
|
||||
/// a display RGB mix gives, and its lightness climbs evenly.
|
||||
#[test]
|
||||
fn perceptual_blue_to_yellow_is_not_the_grey_rgb_mix() {
|
||||
let classic = blue_yellow(GradientMethod::Classic).sample(0.5).0.to_rgb();
|
||||
assert!(classic.iter().all(|v| (v - 0.5).abs() < 1e-5), "classic: the RGB mix {classic:?}");
|
||||
let p = blue_yellow(GradientMethod::Perceptual);
|
||||
let [r, g, b] = p.sample(0.5).0.to_rgb();
|
||||
assert!(b > r + 0.1 && b > g + 0.05, "a blue-grey, not grey: {:?}", [r, g, b]);
|
||||
assert!(r + g + b > 1.5 + 0.2, "lighter than the RGB mix: {:?}", [r, g, b]);
|
||||
let lightness = |t: f32| crate::libraries::to_oklab(&p.sample(t).0)[0];
|
||||
let steps: Vec<f64> = (0..4).map(|k| lightness((k + 1) as f32 / 4.0) - lightness(k as f32 / 4.0)).collect();
|
||||
assert!(steps.iter().all(|d| (d - steps[0]).abs() < 1e-3), "even lightness steps: {steps:?}");
|
||||
// Ends and opacity as before.
|
||||
assert_eq!(p.sample(0.0).0.to_hex(), "#0000ff");
|
||||
assert_eq!(p.sample(1.0).0.to_hex(), "#ffff00");
|
||||
}
|
||||
|
||||
/// Renderers mix linearly between stops: a Perceptual segment becomes stops on the perceptual
|
||||
/// curve (the midpoint diamond among them), more where it bends, close enough that the linear
|
||||
/// ramp between them stays within half a colour level of the curve; a segment that hardly
|
||||
/// bends needs few.
|
||||
#[test]
|
||||
fn perceptual_segments_expand_into_stops_on_the_curve() {
|
||||
let pairs = [
|
||||
(Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 1.0, 0.0)),
|
||||
(Color::BLACK, Color::rgb(1.0, 0.0, 0.0)),
|
||||
(Color::rgb(0.0, 1.0, 0.0), Color::rgb(1.0, 0.0, 1.0)),
|
||||
(Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::WHITE),
|
||||
];
|
||||
for (a, b) in pairs {
|
||||
let mut p = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)]);
|
||||
p.method = GradientMethod::Perceptual;
|
||||
p.stops[0].midpoint = 0.3;
|
||||
p.stops[1].opacity = 0.5;
|
||||
let ex: Vec<_> = p.expanded().collect();
|
||||
assert!((3..=100).contains(&ex.len()), "{a:?} → {b:?}: {} stops", ex.len());
|
||||
assert!(ex.windows(2).all(|w| w[0].0 < w[1].0), "in order");
|
||||
assert_eq!(ex.iter().filter(|s| s.3.is_some()).count(), 1, "one stop stands for the midpoint");
|
||||
assert!(ex.iter().any(|s| s.3 == Some(0.3) && (s.0 - 0.3).abs() < 1e-6));
|
||||
let ramp = Ramp::new(&p, &Color::to_rgb);
|
||||
for k in 0..=2000 {
|
||||
let t = k as f32 / 2000.0;
|
||||
let (c, o) = p.sample(t);
|
||||
let [r, g, b] = c.to_rgb();
|
||||
let off = [r, g, b, o].iter().zip(ramp.at(t)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
|
||||
assert!(off < 0.5 / 255.0, "{a:?} → {b:?} at {t}: {off}");
|
||||
}
|
||||
}
|
||||
let mut flat = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![GradientStop::new(0.0, Color::rgb(0.2, 0.4, 0.6)), GradientStop::new(1.0, Color::rgb(0.25, 0.45, 0.6))],
|
||||
);
|
||||
flat.method = GradientMethod::Perceptual;
|
||||
assert_eq!(flat.expanded().count(), 3, "the ends and the midpoint");
|
||||
}
|
||||
|
||||
/// Classic gradients expand as they always did: their stops, and a stop at each off-centre
|
||||
/// midpoint, sampled in display RGB (so the renderer draws the same pixels as before).
|
||||
#[test]
|
||||
fn classic_gradients_expand_as_before() {
|
||||
let mut g = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![
|
||||
GradientStop { midpoint: 0.2, ..GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)) },
|
||||
GradientStop { opacity: 0.4, ..GradientStop::new(0.45, Color::cmyk(0.1, 0.8, 0.0, 0.2)) },
|
||||
GradientStop { midpoint: 0.87, ..GradientStop::new(0.6, Color::rgb(1.0, 1.0, 0.0)) },
|
||||
GradientStop::new(1.0, Color::gray(0.3)),
|
||||
],
|
||||
);
|
||||
// The expansion gradients had before they had a method.
|
||||
let before: Vec<_> = g
|
||||
.stops
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(i, s)| {
|
||||
let mid = g.stops.get(i + 1).filter(|_| (s.midpoint - 0.5).abs() > 1e-3).map(|n| {
|
||||
let t = s.offset + (n.offset - s.offset) * s.midpoint;
|
||||
let (c, o) = g.sample_with(t, Color::lerp);
|
||||
(t, c, o, Some(s.midpoint))
|
||||
});
|
||||
std::iter::once((s.offset, s.color, s.opacity, None)).chain(mid)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(g.expanded().collect::<Vec<_>>(), before);
|
||||
assert_eq!(before.len(), 6);
|
||||
assert_eq!(g.sample(0.3), g.sample_with(0.3, Color::lerp));
|
||||
assert_eq!(g.sample_keep_model(0.5), g.sample_with(0.5, Color::lerp_keep_model));
|
||||
g.method = GradientMethod::Perceptual;
|
||||
assert_eq!(g.sample_keep_model(0.5), g.sample(0.5), "perceptual: one mix");
|
||||
}
|
||||
|
||||
/// The method is written only when Perceptual, so files from before it (and Classic
|
||||
/// gradients) read as Classic and new Classic files stay as they were.
|
||||
#[test]
|
||||
fn method_is_saved_only_when_perceptual() {
|
||||
let classic = serde_json::to_value(Gradient::default()).unwrap();
|
||||
assert!(classic.get("method").is_none(), "{classic}");
|
||||
let old: Gradient = serde_json::from_value(serde_json::json!({"kind": "Linear", "stops": []})).unwrap();
|
||||
assert_eq!(old.method, GradientMethod::Classic);
|
||||
let p = blue_yellow(GradientMethod::Perceptual);
|
||||
let v = serde_json::to_value(&p).unwrap();
|
||||
assert_eq!(v["method"], "Perceptual");
|
||||
assert_eq!(serde_json::from_value::<Gradient>(v).unwrap(), p);
|
||||
assert_eq!(GradientMethod::parse("perceptual"), Some(GradientMethod::Perceptual));
|
||||
assert_eq!(GradientMethod::parse("CLASSIC"), Some(GradientMethod::Classic));
|
||||
assert_eq!(GradientMethod::parse("smooth"), None);
|
||||
}
|
||||
|
||||
/// SVG and PDF can't mix colours perceptually: a Perceptual gradient is drawn as pixels there,
|
||||
/// as Illustrator rasterises perceptual gradients saved as PDF or SVG, as a fill or a stroke,
|
||||
/// dithered or not.
|
||||
#[test]
|
||||
fn perceptual_gradients_draw_as_pixels() {
|
||||
for fill in [true, false] {
|
||||
assert!(!GradientPaint::new(blue_yellow(GradientMethod::Classic)).draws_as_pixels(fill));
|
||||
assert!(GradientPaint::new(blue_yellow(GradientMethod::Perceptual)).draws_as_pixels(fill));
|
||||
let mut radial = blue_yellow(GradientMethod::Perceptual);
|
||||
radial.kind = GradientKind::Radial;
|
||||
radial.dither = true;
|
||||
assert!(GradientPaint::new(radial).draws_as_pixels(fill));
|
||||
}
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,457 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sample_endpoints_and_mid() {
|
||||
let g = Gradient::default();
|
||||
assert_eq!(g.sample(0.0).0.to_hex(), "#ffffff");
|
||||
assert_eq!(g.sample(1.0).0.to_hex(), "#000000");
|
||||
let mid = g.sample(0.5).0.to_rgb()[0];
|
||||
assert!((mid - 0.5).abs() < 1e-5);
|
||||
}
|
||||
|
||||
/// Sampling increasing positions in one pass gives what sampling each alone does, out-of-order
|
||||
/// and repeated stop offsets included.
|
||||
#[test]
|
||||
fn increasing_samples_match_single_samples() {
|
||||
let stop = |offset: f32, hex: &str, midpoint: f32| GradientStop { midpoint, ..GradientStop::new(offset, Color::from_hex(hex).unwrap()) };
|
||||
let g = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![stop(0.1, "#ff0000", 0.3), stop(0.4, "#00ff00", 0.7), stop(0.4, "#0000ff", 0.5), stop(0.2, "#ffff00", 0.5), stop(0.9, "#000000", 0.5)],
|
||||
);
|
||||
let ts: Vec<f32> = (0..=40).map(|k| k as f32 / 40.0).collect();
|
||||
let one_by_one: Vec<_> = ts.iter().map(|&t| g.sample_with(t, Color::lerp_keep_model)).collect();
|
||||
assert_eq!(g.sample_increasing_with(ts, Color::lerp_keep_model), one_by_one);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midpoint_shifts() {
|
||||
let mut g = Gradient::default();
|
||||
g.stops[0].midpoint = 0.25;
|
||||
// At t = 0.25 we should be half way.
|
||||
assert!((g.sample(0.25).0.to_rgb()[0] - 0.5).abs() < 1e-5);
|
||||
assert_eq!(g.expanded_stops().len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fit_linear_horizontal() {
|
||||
let g = GradientGeom::fit(GradientKind::Linear, Rect::new(0.0, 0.0, 100.0, 50.0), 0.0);
|
||||
assert_eq!(g.start, Point::new(0.0, 25.0));
|
||||
assert_eq!(g.end, Point::new(100.0, 25.0));
|
||||
assert!((g.angle_deg()).abs() < 1e-9);
|
||||
let v = GradientGeom::fit(GradientKind::Linear, Rect::new(0.0, 0.0, 100.0, 50.0), 90.0);
|
||||
assert!((v.angle_deg() - 90.0).abs() < 1e-9);
|
||||
assert!((v.length() - 50.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverse_stops() {
|
||||
let mut g = Gradient::default();
|
||||
g.reverse();
|
||||
assert_eq!(g.stops[0].color.to_hex(), "#000000");
|
||||
assert_eq!(g.stops[0].offset, 0.0);
|
||||
}
|
||||
|
||||
/// #1007: reversing mirrors off-centre midpoints with their segments, so the ramp is the same
|
||||
/// the other way round.
|
||||
#[test]
|
||||
fn reverse_mirrors_midpoints() {
|
||||
let stop = |offset, hex, midpoint| GradientStop { midpoint, ..GradientStop::new(offset, Color::from_hex(hex).unwrap()) };
|
||||
let two = Gradient::new(GradientKind::Linear, vec![stop(0.0, "#ff0000", 0.2), stop(1.0, "#0000ff", 0.5)]);
|
||||
let three = Gradient::new(GradientKind::Linear, vec![stop(0.0, "#ff0000", 0.2), stop(0.3, "#00ff00", 0.8), stop(1.0, "#0000ff", 0.5)]);
|
||||
for g in [two, three] {
|
||||
let mut r = g.clone();
|
||||
r.reverse();
|
||||
let mids: Vec<f32> = r.stops.iter().map(|s| s.midpoint).collect();
|
||||
let want: Vec<f32> = g.stops.iter().rev().skip(1).map(|s| 1.0 - s.midpoint).chain([0.5]).collect();
|
||||
assert!(mids.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-6), "{mids:?} {want:?}");
|
||||
for i in 0..=20 {
|
||||
let t = i as f32 / 20.0;
|
||||
let ((a, ao), (b, bo)) = (g.sample(t), r.sample(1.0 - t));
|
||||
let same = a.to_rgba8(1.0).iter().zip(b.to_rgba8(1.0)).all(|(x, y)| x.abs_diff(y) <= 1);
|
||||
assert!(same && (ao - bo).abs() < 1e-6, "t {t}: {a:?} vs {b:?}");
|
||||
}
|
||||
r.reverse();
|
||||
let back = r.stops.iter().zip(&g.stops).all(|(a, b)| (a.offset - b.offset).abs() < 1e-6 && (a.midpoint - b.midpoint).abs() < 1e-6);
|
||||
assert!(back, "reversed twice, it is as it was: {:?}", r.stops);
|
||||
}
|
||||
}
|
||||
|
||||
fn close(a: Point, b: Point) -> bool {
|
||||
a.distance(b) < 1e-9
|
||||
}
|
||||
|
||||
fn linear(start: (f64, f64), end: (f64, f64)) -> GradientGeom {
|
||||
GradientGeom { start: start.into(), end: end.into(), aspect: 1.0, focal: None }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_90_gives_vertical_vector() {
|
||||
let mut g = linear((0.0, 0.0), (100.0, 0.0));
|
||||
g.transform(Affine::rotate(std::f64::consts::FRAC_PI_2), GradientKind::Linear);
|
||||
assert!(close(g.start, Point::ZERO) && close(g.end, Point::new(0.0, 100.0)), "{g:?}");
|
||||
assert!((g.angle_deg() + 90.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflect_swaps_start_and_end() {
|
||||
let mut g = linear((0.0, 25.0), (100.0, 25.0));
|
||||
// Reflect across the vertical axis through x = 50.
|
||||
let flip = Affine::translate((50.0, 0.0)) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate((-50.0, 0.0));
|
||||
g.transform(flip, GradientKind::Linear);
|
||||
assert!(close(g.start, Point::new(100.0, 25.0)) && close(g.end, Point::new(0.0, 25.0)), "{g:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_uniform_scale_turns_a_circle_into_an_ellipse() {
|
||||
let mut g = GradientGeom { start: Point::new(10.0, 10.0), end: Point::new(20.0, 10.0), aspect: 1.0, focal: None };
|
||||
g.transform(Affine::scale_non_uniform(2.0, 1.0), GradientKind::Radial);
|
||||
assert!(close(g.start, Point::new(20.0, 10.0)) && close(g.end, Point::new(40.0, 10.0)), "{g:?}");
|
||||
assert!((g.aspect - 0.5).abs() < 1e-9);
|
||||
// A vertical vector keeps its axis: the ellipse is twice as wide as the vector is long.
|
||||
let mut v = GradientGeom { start: Point::ZERO, end: Point::new(0.0, -10.0), aspect: 1.0, focal: None };
|
||||
v.transform(Affine::scale_non_uniform(2.0, 1.0), GradientKind::Radial);
|
||||
assert!(close(v.end, Point::new(0.0, -10.0)) && (v.aspect - 2.0).abs() < 1e-9, "{v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn samples_follow_shear_and_rotation() {
|
||||
let shear = Affine::new([1.0, 0.3, 0.7, 1.2, 15.0, -4.0]) * Affine::rotate(0.4);
|
||||
for kind in [GradientKind::Linear, GradientKind::Radial] {
|
||||
let g = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(80.0, 55.0), aspect: 0.6, focal: None };
|
||||
let mut m = g;
|
||||
m.transform(shear, kind);
|
||||
for p in [Point::new(30.0, 40.0), Point::new(55.0, 70.0), Point::new(90.0, 10.0), Point::new(-20.0, 48.0)] {
|
||||
let (a, b) = (g.param_at(kind, p), m.param_at(kind, shear * p));
|
||||
assert!((a - b).abs() < 1e-9, "{kind:?} at {p:?}: {a} vs {b}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_fit_uses_the_angle_and_param_honours_aspect() {
|
||||
let b = Rect::new(0.0, 0.0, 100.0, 60.0);
|
||||
let g = GradientGeom::fit(GradientKind::Radial, b, 90.0);
|
||||
assert!(close(g.start, Point::new(50.0, 30.0)) && close(g.end, Point::new(50.0, -20.0)), "end above the centre: {g:?}");
|
||||
let e = GradientGeom { start: Point::ZERO, end: Point::new(10.0, 0.0), aspect: 0.5, focal: None };
|
||||
assert!((e.param_at(GradientKind::Radial, Point::new(0.0, 5.0)) - 1.0).abs() < 1e-12);
|
||||
assert!((e.param_at(GradientKind::Radial, Point::new(5.0, 0.0)) - 0.5).abs() < 1e-12);
|
||||
assert!((e.param_at(GradientKind::Linear, Point::new(5.0, 7.0)) - 0.5).abs() < 1e-12);
|
||||
}
|
||||
|
||||
fn g3() -> Gradient {
|
||||
let mut g = Gradient::default();
|
||||
g.stops.insert(1, GradientStop::new(0.5, Color::rgb(1.0, 0.0, 0.0)));
|
||||
g
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_samples_color_and_sorts() {
|
||||
let g = Gradient::default();
|
||||
let (stops, i) = insert_stop(&g, 0.25);
|
||||
assert_eq!(stops.len(), 3);
|
||||
assert_eq!(i, 1);
|
||||
let r = stops[1].color.to_rgb()[0];
|
||||
assert!((r - 0.75).abs() < 1e-4, "sampled {r}");
|
||||
let (stops, i) = insert_stop(&g, 2.0);
|
||||
assert_eq!(i, 2);
|
||||
assert_eq!(stops[2].offset, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_keeps_two() {
|
||||
let g = g3();
|
||||
let v = remove_stop(&g.stops, 1).unwrap();
|
||||
assert_eq!(v.len(), 2);
|
||||
assert!(remove_stop(&v, 0).is_none());
|
||||
assert!(remove_stop(&g.stops, 9).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_reorders_and_tracks_index() {
|
||||
let g = g3();
|
||||
let (v, i) = move_stop(&g.stops, 0, 0.8);
|
||||
assert_eq!(i, 1);
|
||||
assert_eq!(v[1].color.to_hex(), "#ffffff");
|
||||
assert!(v.windows(2).all(|w| w[0].offset <= w[1].offset));
|
||||
let (v, i) = move_stop(&g.stops, 1, -3.0);
|
||||
// Clamped to 0 and placed after the existing stop at 0.
|
||||
assert_eq!((i, v[i].offset, v[i].color.to_hex()), (1, 0.0, "#ff0000".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_copies_the_stop_to_a_new_offset() {
|
||||
let g = g3();
|
||||
let (v, i) = duplicate_stop(&g.stops, 1, 0.9);
|
||||
assert_eq!((v.len(), i, v[i].offset, v[i].color.to_hex()), (4, 2, 0.9, "#ff0000".to_string()));
|
||||
assert_eq!(v[1], g.stops[1], "the original stays");
|
||||
assert_eq!(duplicate_stop(&g.stops, 7, 0.5).0, g.stops);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swap_exchanges_only_the_colours() {
|
||||
let mut g = g3();
|
||||
g.stops[0].opacity = 0.25;
|
||||
let v = swap_stop_colors(&g.stops, 0, 1);
|
||||
assert_eq!((v[0].color.to_hex(), v[1].color.to_hex()), ("#ff0000".to_string(), "#ffffff".to_string()));
|
||||
assert_eq!((v[0].offset, v[0].opacity, v[1].offset, v[1].opacity), (0.0, 0.25, 0.5, 1.0));
|
||||
assert_eq!(swap_stop_colors(&g.stops, 0, 9), g.stops);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midpoint_math() {
|
||||
let g = g3();
|
||||
assert_eq!(midpoint_pos(&g.stops, 0), Some(0.25));
|
||||
assert_eq!(midpoint_pos(&g.stops, 2), None);
|
||||
let m = midpoint_from_pos(&g.stops, 1, 0.6).unwrap();
|
||||
assert!((m - 0.2).abs() < 1e-5);
|
||||
assert_eq!(midpoint_from_pos(&g.stops, 1, 0.51).unwrap(), 0.13);
|
||||
let v = set_midpoint(&g.stops, 0, 0.99);
|
||||
assert_eq!(v[0].midpoint, 0.87);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rebase_keeps_relative_positions() {
|
||||
let mut g = GradientGeom { start: Point::new(110.0, 150.0), end: Point::new(190.0, 120.0), aspect: 0.5, focal: None };
|
||||
g.rebase(Rect::new(100.0, 100.0, 200.0, 200.0), Rect::new(500.0, 0.0, 700.0, 50.0));
|
||||
assert!(close(g.start, Point::new(520.0, 25.0)) && close(g.end, Point::new(680.0, 10.0)) && g.aspect == 0.5, "{g:?}");
|
||||
// A box without height (a horizontal line) keeps the offset from its centre line.
|
||||
let mut h = GradientGeom { start: Point::new(0.0, 12.0), end: Point::new(10.0, 10.0), aspect: 1.0, focal: None };
|
||||
h.rebase(Rect::new(0.0, 10.0, 10.0, 10.0), Rect::new(0.0, 0.0, 20.0, 40.0));
|
||||
assert!(close(h.start, Point::new(0.0, 22.0)) && close(h.end, Point::new(20.0, 20.0)), "{h:?}");
|
||||
// Unplaced paints have nothing to move.
|
||||
let mut p = GradientPaint::new(Gradient::default());
|
||||
p.rebase(Rect::new(0.0, 0.0, 1.0, 1.0), Rect::new(5.0, 5.0, 9.0, 9.0));
|
||||
assert_eq!(p.geom, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pin_fixes_the_fit_once() {
|
||||
let mut p = GradientPaint::new(Gradient::default());
|
||||
p.angle = 90.0;
|
||||
let b = Rect::new(0.0, 0.0, 100.0, 50.0);
|
||||
p.pin(b);
|
||||
assert_eq!(p.geom, Some(GradientGeom::fit(GradientKind::Linear, b, 90.0)));
|
||||
p.pin(Rect::new(0.0, 0.0, 1.0, 1.0));
|
||||
assert_eq!(p.geom, Some(GradientGeom::fit(GradientKind::Linear, b, 90.0)));
|
||||
}
|
||||
|
||||
/// A 100 pt circle at (200, 200) with its focal point 40 pt left of the centre.
|
||||
fn off_centre() -> GradientGeom {
|
||||
let mut g = GradientGeom { start: Point::new(200.0, 200.0), end: Point::new(300.0, 200.0), aspect: 1.0, focal: None };
|
||||
g.set_focal(Some(Point::new(160.0, 200.0)));
|
||||
g
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focal_round_trips_through_serde_and_defaults_to_none() {
|
||||
let g = off_centre();
|
||||
let s = serde_json::to_string(&g).unwrap();
|
||||
assert!(s.contains("\"focal\""), "{s}");
|
||||
assert_eq!(serde_json::from_str::<GradientGeom>(&s).unwrap(), g);
|
||||
// Placements saved before focal points existed load centred, and centred ones write none.
|
||||
let old: GradientGeom = serde_json::from_str(r#"{"start":{"x":0.0,"y":0.0},"end":{"x":1.0,"y":0.0}}"#).unwrap();
|
||||
assert_eq!((old.focal, old.aspect), (None, 1.0));
|
||||
assert!(!serde_json::to_string(&old).unwrap().contains("focal"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focal_follows_transforms_and_rebases() {
|
||||
let mut g = off_centre();
|
||||
let a = Affine::translate((10.0, -5.0)) * Affine::rotate(0.7) * Affine::scale_non_uniform(2.0, 0.5);
|
||||
let f = a * g.focal.unwrap();
|
||||
g.transform(a, GradientKind::Radial);
|
||||
assert!(close(g.focal.unwrap(), f), "{g:?}");
|
||||
// Still at the same parameter: the first stop.
|
||||
assert!(g.param_at(GradientKind::Radial, f).abs() < 1e-9);
|
||||
let mut h = off_centre();
|
||||
h.rebase(Rect::new(100.0, 100.0, 300.0, 300.0), Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
assert!(close(h.focal.unwrap(), Point::new(30.0, 50.0)) && close(h.start, Point::new(50.0, 50.0)), "{h:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn param_runs_from_the_focal_point_to_the_ellipse() {
|
||||
let g = off_centre();
|
||||
let t = |x: f64, y: f64| g.param_at(GradientKind::Radial, Point::new(x, y));
|
||||
assert!(t(160.0, 200.0).abs() < 1e-9);
|
||||
// The extent circle is the last stop all round.
|
||||
for a in [0.0f64, 1.0, 2.5, 4.0] {
|
||||
let p = Point::new(200.0 + 100.0 * a.cos(), 200.0 + 100.0 * a.sin());
|
||||
assert!((g.param_at(GradientKind::Radial, p) - 1.0).abs() < 1e-9, "{a}");
|
||||
}
|
||||
// The centre lies on the level-2/7 circle: centred 2/7 of the way back to the focal point
|
||||
// (0.4 of the radius off), with a radius of 2/7.
|
||||
assert!((t(200.0, 200.0) - 2.0 / 7.0).abs() < 1e-9, "{}", t(200.0, 200.0));
|
||||
assert!(t(180.0, 200.0) < t(220.0, 200.0), "nearer the focal side is earlier");
|
||||
assert_eq!(GradientGeom { focal: None, ..g }.param_at(GradientKind::Radial, Point::new(250.0, 200.0)), 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focal_is_kept_inside_the_ellipse_and_follows_its_reshaping() {
|
||||
let mut g = off_centre();
|
||||
g.set_focal(Some(Point::new(500.0, 200.0)));
|
||||
assert!(close(g.focal.unwrap(), Point::new(299.0, 200.0)), "pulled inside: {g:?}");
|
||||
g.set_focal(Some(Point::new(200.0, 200.0)));
|
||||
assert_eq!(g.focal, None, "on the centre: centred");
|
||||
// A new vector and aspect keep it in its place in the ellipse.
|
||||
let before = off_centre();
|
||||
let mut h = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.0, 50.0), aspect: 0.5, focal: None };
|
||||
h.keep_focal_from(&before);
|
||||
assert!(close(h.focal.unwrap(), Point::new(0.0, -20.0)), "{h:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixels_sample_the_ramp_at_each_cell_centre() {
|
||||
// White → black left to right over a 10 × 2 box, a midpoint at 30% and a half-opaque end.
|
||||
let mut g = GradientPaint::new(Gradient::default());
|
||||
g.gradient.stops[0].midpoint = 0.3;
|
||||
g.gradient.stops[1].opacity = 0.5;
|
||||
let b = Rect::new(0.0, 0.0, 10.0, 2.0);
|
||||
let px: Vec<[u8; 4]> = g.pixels(b, b, 10, 2, true, &Color::to_rgb).collect();
|
||||
assert_eq!(px.len(), 20);
|
||||
let ramp = Ramp::new(&g.gradient, &Color::to_rgb);
|
||||
for (i, p) in px.iter().take(10).enumerate() {
|
||||
let c = ramp.at((i as f32 + 0.5) / 10.0).map(|v| (v * 255.0).round() as u8);
|
||||
assert_eq!(*p, c, "pixel {i}");
|
||||
}
|
||||
assert_eq!(px[3], px[13], "rows alike");
|
||||
// The midpoint stop: grey at 30%; padded past the ends.
|
||||
assert!((ramp.at(0.3)[0] - 0.5).abs() < 0.02, "{:?}", ramp.at(0.3));
|
||||
assert_eq!(ramp.at(-1.0), [1.0, 1.0, 1.0, 1.0]);
|
||||
assert_eq!(ramp.at(2.0), [0.0, 0.0, 0.0, 0.5]);
|
||||
assert_eq!(ramp.at(f32::NAN), [1.0, 1.0, 1.0, 1.0]);
|
||||
}
|
||||
|
||||
fn blue_yellow(method: GradientMethod) -> Gradient {
|
||||
let mut g = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::rgb(1.0, 1.0, 0.0))],
|
||||
);
|
||||
g.method = method;
|
||||
g
|
||||
}
|
||||
|
||||
/// Illustrator 30's Perceptual method mixes colours in a perceptually even way
|
||||
/// (https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-gradients/control-perceptual-interpolation-in-gradients.html).
|
||||
/// Here that is OKLab: blue → yellow passes through a light blue-grey, not the flat mid grey
|
||||
/// a display RGB mix gives, and its lightness climbs evenly.
|
||||
#[test]
|
||||
fn perceptual_blue_to_yellow_is_not_the_grey_rgb_mix() {
|
||||
let classic = blue_yellow(GradientMethod::Classic).sample(0.5).0.to_rgb();
|
||||
assert!(classic.iter().all(|v| (v - 0.5).abs() < 1e-5), "classic: the RGB mix {classic:?}");
|
||||
let p = blue_yellow(GradientMethod::Perceptual);
|
||||
let [r, g, b] = p.sample(0.5).0.to_rgb();
|
||||
assert!(b > r + 0.1 && b > g + 0.05, "a blue-grey, not grey: {:?}", [r, g, b]);
|
||||
assert!(r + g + b > 1.5 + 0.2, "lighter than the RGB mix: {:?}", [r, g, b]);
|
||||
let lightness = |t: f32| crate::libraries::to_oklab(&p.sample(t).0)[0];
|
||||
let steps: Vec<f64> = (0..4).map(|k| lightness((k + 1) as f32 / 4.0) - lightness(k as f32 / 4.0)).collect();
|
||||
assert!(steps.iter().all(|d| (d - steps[0]).abs() < 1e-3), "even lightness steps: {steps:?}");
|
||||
// Ends and opacity as before.
|
||||
assert_eq!(p.sample(0.0).0.to_hex(), "#0000ff");
|
||||
assert_eq!(p.sample(1.0).0.to_hex(), "#ffff00");
|
||||
}
|
||||
|
||||
/// Renderers mix linearly between stops: a Perceptual segment becomes stops on the perceptual
|
||||
/// curve (the midpoint diamond among them), more where it bends, close enough that the linear
|
||||
/// ramp between them stays within half a colour level of the curve; a segment that hardly
|
||||
/// bends needs few.
|
||||
#[test]
|
||||
fn perceptual_segments_expand_into_stops_on_the_curve() {
|
||||
let pairs = [
|
||||
(Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 1.0, 0.0)),
|
||||
(Color::BLACK, Color::rgb(1.0, 0.0, 0.0)),
|
||||
(Color::rgb(0.0, 1.0, 0.0), Color::rgb(1.0, 0.0, 1.0)),
|
||||
(Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::WHITE),
|
||||
];
|
||||
for (a, b) in pairs {
|
||||
let mut p = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)]);
|
||||
p.method = GradientMethod::Perceptual;
|
||||
p.stops[0].midpoint = 0.3;
|
||||
p.stops[1].opacity = 0.5;
|
||||
let ex: Vec<_> = p.expanded().collect();
|
||||
assert!((3..=100).contains(&ex.len()), "{a:?} → {b:?}: {} stops", ex.len());
|
||||
assert!(ex.windows(2).all(|w| w[0].0 < w[1].0), "in order");
|
||||
assert_eq!(ex.iter().filter(|s| s.3.is_some()).count(), 1, "one stop stands for the midpoint");
|
||||
assert!(ex.iter().any(|s| s.3 == Some(0.3) && (s.0 - 0.3).abs() < 1e-6));
|
||||
let ramp = Ramp::new(&p, &Color::to_rgb);
|
||||
for k in 0..=2000 {
|
||||
let t = k as f32 / 2000.0;
|
||||
let (c, o) = p.sample(t);
|
||||
let [r, g, b] = c.to_rgb();
|
||||
let off = [r, g, b, o].iter().zip(ramp.at(t)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
|
||||
assert!(off < 0.5 / 255.0, "{a:?} → {b:?} at {t}: {off}");
|
||||
}
|
||||
}
|
||||
let mut flat = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![GradientStop::new(0.0, Color::rgb(0.2, 0.4, 0.6)), GradientStop::new(1.0, Color::rgb(0.25, 0.45, 0.6))],
|
||||
);
|
||||
flat.method = GradientMethod::Perceptual;
|
||||
assert_eq!(flat.expanded().count(), 3, "the ends and the midpoint");
|
||||
}
|
||||
|
||||
/// Classic gradients expand as they always did: their stops, and a stop at each off-centre
|
||||
/// midpoint, sampled in display RGB (so the renderer draws the same pixels as before).
|
||||
#[test]
|
||||
fn classic_gradients_expand_as_before() {
|
||||
let mut g = Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![
|
||||
GradientStop { midpoint: 0.2, ..GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)) },
|
||||
GradientStop { opacity: 0.4, ..GradientStop::new(0.45, Color::cmyk(0.1, 0.8, 0.0, 0.2)) },
|
||||
GradientStop { midpoint: 0.87, ..GradientStop::new(0.6, Color::rgb(1.0, 1.0, 0.0)) },
|
||||
GradientStop::new(1.0, Color::gray(0.3)),
|
||||
],
|
||||
);
|
||||
// The expansion gradients had before they had a method.
|
||||
let before: Vec<_> = g
|
||||
.stops
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(i, s)| {
|
||||
let mid = g.stops.get(i + 1).filter(|_| (s.midpoint - 0.5).abs() > 1e-3).map(|n| {
|
||||
let t = s.offset + (n.offset - s.offset) * s.midpoint;
|
||||
let (c, o) = g.sample_with(t, Color::lerp);
|
||||
(t, c, o, Some(s.midpoint))
|
||||
});
|
||||
std::iter::once((s.offset, s.color, s.opacity, None)).chain(mid)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(g.expanded().collect::<Vec<_>>(), before);
|
||||
assert_eq!(before.len(), 6);
|
||||
assert_eq!(g.sample(0.3), g.sample_with(0.3, Color::lerp));
|
||||
assert_eq!(g.sample_keep_model(0.5), g.sample_with(0.5, Color::lerp_keep_model));
|
||||
g.method = GradientMethod::Perceptual;
|
||||
assert_eq!(g.sample_keep_model(0.5), g.sample(0.5), "perceptual: one mix");
|
||||
}
|
||||
|
||||
/// The method is written only when Perceptual, so files from before it (and Classic
|
||||
/// gradients) read as Classic and new Classic files stay as they were.
|
||||
#[test]
|
||||
fn method_is_saved_only_when_perceptual() {
|
||||
let classic = serde_json::to_value(Gradient::default()).unwrap();
|
||||
assert!(classic.get("method").is_none(), "{classic}");
|
||||
let old: Gradient = serde_json::from_value(serde_json::json!({"kind": "Linear", "stops": []})).unwrap();
|
||||
assert_eq!(old.method, GradientMethod::Classic);
|
||||
let p = blue_yellow(GradientMethod::Perceptual);
|
||||
let v = serde_json::to_value(&p).unwrap();
|
||||
assert_eq!(v["method"], "Perceptual");
|
||||
assert_eq!(serde_json::from_value::<Gradient>(v).unwrap(), p);
|
||||
assert_eq!(GradientMethod::parse("perceptual"), Some(GradientMethod::Perceptual));
|
||||
assert_eq!(GradientMethod::parse("CLASSIC"), Some(GradientMethod::Classic));
|
||||
assert_eq!(GradientMethod::parse("smooth"), None);
|
||||
}
|
||||
|
||||
/// SVG and PDF can't mix colours perceptually: a Perceptual gradient is drawn as pixels there,
|
||||
/// as Illustrator rasterises perceptual gradients saved as PDF or SVG, as a fill or a stroke,
|
||||
/// dithered or not.
|
||||
#[test]
|
||||
fn perceptual_gradients_draw_as_pixels() {
|
||||
for fill in [true, false] {
|
||||
assert!(!GradientPaint::new(blue_yellow(GradientMethod::Classic)).draws_as_pixels(fill));
|
||||
assert!(GradientPaint::new(blue_yellow(GradientMethod::Perceptual)).draws_as_pixels(fill));
|
||||
let mut radial = blue_yellow(GradientMethod::Perceptual);
|
||||
radial.kind = GradientKind::Radial;
|
||||
radial.dither = true;
|
||||
assert!(GradientPaint::new(radial).draws_as_pixels(fill));
|
||||
}
|
||||
}
|
||||
@@ -668,524 +668,4 @@ impl UniqueNames {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Gradient, GradientPaint, GradientStop};
|
||||
use proptest::prelude::*;
|
||||
|
||||
#[test]
|
||||
fn gpl_blank_name_keeps_fallback() {
|
||||
let blank = "GIMP Palette\nName: \nColumns: 0\n#\n 1 2 3\tx\n";
|
||||
assert_eq!(read(blank, "fallback").unwrap().name, "fallback");
|
||||
let named = "GIMP Palette\nName: Warm\n 1 2 3\tx\n";
|
||||
assert_eq!(read(named, "fallback").unwrap().name, "Warm");
|
||||
}
|
||||
|
||||
/// A color book's string: a `u32` count of UTF-16 code units, then the units.
|
||||
fn acb_str(out: &mut Vec<u8>, s: &str) {
|
||||
let units: Vec<u16> = s.encode_utf16().collect();
|
||||
out.extend((units.len() as u32).to_be_bytes());
|
||||
units.iter().for_each(|u| out.extend(u.to_be_bytes()));
|
||||
}
|
||||
|
||||
/// A color book in `space` (0 RGB, 2 CMYK, 7 Lab) with `colors` (name, components) and an
|
||||
/// optional spot/process marker.
|
||||
fn acb(space: u16, colors: &[(&str, &[u8])], marker: &[u8]) -> Vec<u8> {
|
||||
let mut b = b"8BCB".to_vec();
|
||||
b.extend(1u16.to_be_bytes());
|
||||
b.extend(3000u16.to_be_bytes());
|
||||
for s in ["$$$/colorbook/Test/title=Test Book^R", "TEST ", " C", "a book"] {
|
||||
acb_str(&mut b, s);
|
||||
}
|
||||
b.extend((colors.len() as u16).to_be_bytes());
|
||||
b.extend(7u16.to_be_bytes());
|
||||
b.extend(0u16.to_be_bytes());
|
||||
b.extend(space.to_be_bytes());
|
||||
for (name, comps) in colors {
|
||||
acb_str(&mut b, name);
|
||||
b.extend(b"TST001");
|
||||
b.extend(*comps);
|
||||
}
|
||||
b.extend(marker);
|
||||
b
|
||||
}
|
||||
|
||||
/// #831: color books (`.acb`) are read: their colors in RGB, CMYK or Lab, named with the book's
|
||||
/// prefix and suffix, spot unless the book says process; page padding is left out.
|
||||
#[test]
|
||||
fn color_books_are_read() {
|
||||
let lib = read_bytes(&acb(0, &[("185", &[228, 0, 43]), ("", &[0, 0, 0]), ("Red 032", &[239, 51, 64])], b"spflspot"), "fallback").unwrap();
|
||||
assert_eq!(lib.name, "Test Book®");
|
||||
let names: Vec<&str> = lib.swatches.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names, ["TEST 185 C", "TEST Red 032 C"]);
|
||||
assert!(lib.swatches.iter().all(|s| s.spot && s.global));
|
||||
assert_eq!(lib.swatches[0].paint.color(), Some(Color::rgb8(228, 0, 43)));
|
||||
// CMYK ink is stored inverted; a book marked process gives process colors.
|
||||
let lib = read_bytes(&acb(2, &[("Cyan", &[0, 255, 255, 255])], b"spflproc"), "x").unwrap();
|
||||
assert_eq!(lib.swatches[0].paint.color(), Some(Color::cmyk(1.0, 0.0, 0.0, 0.0)));
|
||||
assert!(!lib.swatches[0].spot && !lib.swatches[0].global);
|
||||
// Lab: lightness 0..255 for 0..100, a and b offset by 128; no marker: spot.
|
||||
let lib = read_bytes(&acb(7, &[("Grey", &[255, 128, 128])], b""), "x").unwrap();
|
||||
assert_eq!(lib.swatches[0].paint.color(), Some(Color::lab(100.0, 0.0, 0.0)));
|
||||
assert!(lib.swatches[0].spot);
|
||||
assert!(sniff_bytes(&acb(0, &[], b"")));
|
||||
// Unsupported versions and color spaces, and short files, are errors.
|
||||
let mut v2 = acb(0, &[], b"");
|
||||
v2[5] = 2;
|
||||
assert!(read_bytes(&v2, "x").is_err());
|
||||
assert!(read_bytes(&acb(1, &[("x", &[1, 2, 3])], b""), "x").is_err());
|
||||
let full = acb(0, &[("185", &[228, 0, 43])], b"");
|
||||
for cut in 4..full.len() {
|
||||
assert!(read_bytes(&full[..cut], "x").is_err(), "{cut} bytes");
|
||||
}
|
||||
let mut huge = b"8BCB\0\x01\0\x01".to_vec();
|
||||
huge.extend(u32::MAX.to_be_bytes());
|
||||
assert!(read_bytes(&huge, "x").is_err(), "a string longer than the file");
|
||||
}
|
||||
|
||||
fn sample() -> SwatchLibrary {
|
||||
let grad = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![
|
||||
GradientStop { midpoint: 0.4, ..GradientStop::new(0.0, Color::cmyk(0.1, 0.2, 0.3, 0.0)) },
|
||||
GradientStop { opacity: 0.5, ..GradientStop::new(1.0, Color::rgb8(255, 0, 0)) },
|
||||
],
|
||||
))));
|
||||
SwatchLibrary {
|
||||
name: "Brand */ Colours".into(),
|
||||
swatches: vec![
|
||||
Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(1.0, 0.5, 0.0, 0.2)), global: true, spot: true },
|
||||
Swatch { name: "Fade".into(), paint: grad, global: false, spot: false },
|
||||
Swatch { name: "Tiles".into(), paint: Paint::Pattern { pattern: "Dots".into(), xf: Default::default() }, global: false, spot: false },
|
||||
],
|
||||
groups: vec![SwatchGroup {
|
||||
name: "Neutrals".into(),
|
||||
swatches: vec![
|
||||
Swatch { name: "R=255 G=0 B=0".into(), paint: Paint::solid(Color::rgb8(255, 0, 0)), global: false, spot: false },
|
||||
Swatch { name: "Mist".into(), paint: Paint::solid(Color::gray(0.25)), global: true, spot: false },
|
||||
],
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
/// `lib` written as text format `f`.
|
||||
fn written(lib: &SwatchLibrary, f: PaletteFormat) -> String {
|
||||
String::from_utf8(write(lib, f).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_round_trip_keeps_cmyk_spot_and_groups() {
|
||||
let lib = sample();
|
||||
let text = written(&lib, PaletteFormat::Native);
|
||||
assert!(sniff(&text));
|
||||
let back = read(&text, "fallback").unwrap();
|
||||
let mut expected = lib.clone();
|
||||
expected.swatches.retain(|w| !matches!(w.paint, Paint::Pattern { .. }));
|
||||
assert_eq!(back, expected, "everything but the pattern comes back exactly");
|
||||
assert!(back.swatches[0].spot && back.swatches[0].global);
|
||||
assert_eq!(back.swatches[0].paint.color(), Some(Color::cmyk(1.0, 0.5, 0.0, 0.2)));
|
||||
assert!(read("{\"format\": \"other\", \"version\": 1, \"name\": \"x\"}", "x").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpl_writes_rgb_with_group_headers_and_reads_comments_and_headers() {
|
||||
let text = written(&sample(), PaletteFormat::Gpl);
|
||||
assert!(text.starts_with("GIMP Palette\nName: Brand */ Colours\n"));
|
||||
assert!(text.contains("# Group: Neutrals\n255 0 0\tR=255 G=0 B=0\n"), "{text}");
|
||||
assert!(!text.contains("Fade") && !text.contains("Tiles"), "only solid colours");
|
||||
let back = read(&text, "x").unwrap();
|
||||
assert_eq!(back.name, "Brand */ Colours");
|
||||
assert_eq!(back.swatches.len(), 1);
|
||||
assert_eq!(back.groups[0].swatches[1].paint.color(), Some(Color::rgb8(191, 191, 191)), "grey as 8-bit RGB");
|
||||
// Another tool's palette: comments, a Columns header, blank lines, unnamed and repeated names.
|
||||
let other = "GIMP Palette\r\nName: Sunset\r\nColumns: 4\r\n# a comment\r\n\r\n 0 128 255\tSky Blue\r\n10 20 30\r\n0 0 0 Black\r\n1 1 1 Black\r\nbad line\r\n";
|
||||
let lib = read(other, "file").unwrap();
|
||||
assert_eq!(lib.name, "Sunset");
|
||||
let names: Vec<&str> = lib.swatches.iter().map(|w| w.name.as_str()).collect();
|
||||
assert_eq!(names, ["Sky Blue", "R=10 G=20 B=30", "Black", "Black 2"]);
|
||||
assert_eq!(lib.swatches[0].paint.color(), Some(Color::rgb8(0, 128, 255)));
|
||||
assert_eq!(read("GIMP Palette\n1 2 3 x\n", "Fallback").unwrap().name, "Fallback");
|
||||
// Colors and groups share names; an unnamed group is "Color Group".
|
||||
let lib = read("GIMP Palette\n0 0 0 Black\n# Group: Black\n1 1 1 Black\n# Group:\n", "x").unwrap();
|
||||
let groups: Vec<(&str, Vec<&str>)> =
|
||||
lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect();
|
||||
assert_eq!(groups, [("Black 2", vec!["Black 3"]), ("Color Group", vec![])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn css_escapes_names_and_writes_gradients() {
|
||||
assert_eq!(css_property("Sky Blue"), "--sky-blue");
|
||||
assert_eq!(css_property("R=255 G=0 B=0"), "--r\\=255-g\\=0-b\\=0");
|
||||
assert_eq!(css_property("#FF00CC"), "--\\#ff00cc");
|
||||
assert_eq!(css_property("Café 50%"), "--café-50\\%");
|
||||
assert_eq!(css_property(" "), "--swatch");
|
||||
let text = written(&sample(), PaletteFormat::Css);
|
||||
assert!(text.starts_with("/* Brand * / Colours */\n:root {\n"), "{text}");
|
||||
assert!(text.contains(" --ink: #"), "{text}");
|
||||
assert!(text.contains("; /* spot */"));
|
||||
assert!(text.contains(" --fade: linear-gradient(90deg, #"), "{text}");
|
||||
assert!(text.contains("#ff000080 100%)"), "half-transparent stop: {text}");
|
||||
assert!(text.contains(" /* Neutrals */\n --r\\=255-g\\=0-b\\=0: #ff0000;\n"));
|
||||
assert!(!text.contains("tiles"));
|
||||
// Names that collide once escaped are numbered.
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: ["Red", "red"].map(|n| Swatch { name: n.into(), paint: Paint::solid(Color::BLACK), global: false, spot: false }).to_vec(),
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
assert!(text.contains("--red: #000000;") && text.contains("--red-2: #000000;"));
|
||||
assert!(read(&text, "x").is_err(), "CSS is written only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn css_preserves_fractional_gradient_stop_positions() {
|
||||
for kind in [GradientKind::Linear, GradientKind::Radial] {
|
||||
let lib = SwatchLibrary {
|
||||
name: "Positions".into(),
|
||||
swatches: vec![Swatch {
|
||||
name: "Ramp".into(),
|
||||
paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
|
||||
kind,
|
||||
vec![
|
||||
GradientStop::new(0.0, Color::BLACK),
|
||||
GradientStop::new(0.125, Color::rgb8(255, 0, 0)),
|
||||
GradientStop::new(0.12890625, Color::WHITE),
|
||||
GradientStop::new(1.0, Color::rgb8(0, 0, 255)),
|
||||
],
|
||||
)))),
|
||||
global: false,
|
||||
spot: false,
|
||||
}],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
assert!(text.contains("#000000 0%, #ff0000 12.5%, #ffffff 12.890625%, #0000ff 100%"), "{kind:?}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holds_counts_the_swatches_each_format_writes() {
|
||||
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
|
||||
let mut lib = sample();
|
||||
let Paint::Gradient(mut mesh) = lib.swatches[1].paint.clone() else { panic!("Fade is a gradient") };
|
||||
mesh.gradient.kind = GradientKind::Freeform;
|
||||
lib.swatches.push(Swatch { name: "Mesh".into(), paint: Paint::Gradient(mesh), global: false, spot: false });
|
||||
lib.swatches.push(Swatch { name: "[None]".into(), paint: Paint::None, global: false, spot: false });
|
||||
let held = |f: PaletteFormat| lib.iter().filter(|w| f.holds(&w.paint)).count();
|
||||
assert_eq!(PaletteFormat::ALL.map(held), [5, 3, 3, 4], "vcswatches, gpl, ase, css");
|
||||
for f in [PaletteFormat::Native, PaletteFormat::Gpl, PaletteFormat::Ase] {
|
||||
assert_eq!(read_bytes(&write(&lib, f).unwrap(), "x").unwrap().len(), held(f), "{f:?}");
|
||||
}
|
||||
let css = written(&lib, PaletteFormat::Css);
|
||||
assert_eq!(css.lines().filter(|l| l.starts_with(" --")).count(), held(PaletteFormat::Css), "one property each: {css}");
|
||||
}
|
||||
|
||||
/// A swatch exchange file of `blocks` (type, body).
|
||||
fn ase(blocks: &[(u16, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut out = b"ASEF\0\x01\0\0".to_vec();
|
||||
out.extend((blocks.len() as u32).to_be_bytes());
|
||||
for (kind, body) in blocks {
|
||||
out.extend(kind.to_be_bytes());
|
||||
out.extend((body.len() as u32).to_be_bytes());
|
||||
out.extend(body);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A name as `.ase` stores it.
|
||||
fn ase_name(name: &str) -> Vec<u8> {
|
||||
let units: Vec<u16> = name.encode_utf16().chain([0]).collect();
|
||||
let mut out = (units.len() as u16).to_be_bytes().to_vec();
|
||||
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
|
||||
out
|
||||
}
|
||||
|
||||
/// A color block: name, model, components and color type.
|
||||
fn ase_color(name: &str, model: &[u8; 4], values: &[f32], kind: u16) -> (u16, Vec<u8>) {
|
||||
let mut body = ase_name(name);
|
||||
body.extend(model);
|
||||
body.extend(values.iter().flat_map(|v| v.to_be_bytes()));
|
||||
body.extend(kind.to_be_bytes());
|
||||
(ASE_COLOR, body)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_reads_color_models_kinds_and_groups() {
|
||||
let bytes = ase(&[
|
||||
ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0),
|
||||
ase_color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1),
|
||||
(ASE_GROUP_START, ase_name("Neutrals")),
|
||||
ase_color("Mist", b"Gray", &[0.75], 2),
|
||||
ase_color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2),
|
||||
(ASE_GROUP_END, vec![]),
|
||||
ase_color("Paper", b"RGB ", &[1.0, 1.0, 1.0], 2),
|
||||
]);
|
||||
assert!(sniff_bytes(&bytes));
|
||||
let sw = |name: &str, color, global, spot| Swatch { name: name.into(), paint: Paint::solid(color), global, spot };
|
||||
let expected = SwatchLibrary {
|
||||
name: "Brand".into(),
|
||||
swatches: vec![
|
||||
sw("Sky", Color::rgb(0.0, 0.5, 1.0), true, false),
|
||||
sw("Ink", Color::cmyk(1.0, 0.5, 0.0, 0.2), true, true),
|
||||
sw("Paper", Color::WHITE, false, false),
|
||||
],
|
||||
groups: vec![SwatchGroup {
|
||||
name: "Neutrals".into(),
|
||||
swatches: vec![sw("Mist", Color::gray(0.25), false, false), sw("Clay", Color::lab(50.0, 20.0, -30.0), false, false)],
|
||||
}],
|
||||
};
|
||||
assert_eq!(read_bytes(&bytes, "Brand").unwrap(), expected, "named after the file; 0 global, 1 spot, 2 process");
|
||||
// A lightness above 1 is L* itself.
|
||||
let deep = read_bytes(&ase(&[ase_color("Deep", b"LAB ", &[53.0, 20.0, -30.0], 2)]), "x").unwrap();
|
||||
assert_eq!(deep.swatches[0].paint.color(), Some(Color::lab(53.0, 20.0, -30.0)));
|
||||
// Text libraries read through the same call, also when they aren't valid UTF-8.
|
||||
assert!(sniff_bytes(b"GIMP Palette\n1 2 3 x\n") && !sniff_bytes(b"ASE") && !sniff_bytes(&[0xff, 0xfe, 0]));
|
||||
assert_eq!(read_bytes(b"GIMP Palette\n1 2 3 x\n", "F").unwrap().swatches.len(), 1);
|
||||
let latin1 = b"GIMP Palette\n1 2 3 Caf\xe9\n";
|
||||
assert!(sniff_bytes(latin1));
|
||||
assert_eq!(read_bytes(latin1, "F").unwrap().swatches.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_names_unnamed_and_repeated_entries_and_skips_other_blocks() {
|
||||
let mut untyped = ase_color("Plain", b"RGB ", &[0.2, 0.4, 0.6], 2);
|
||||
untyped.1.truncate(untyped.1.len() - 2);
|
||||
let bytes = ase(&[
|
||||
ase_color("Café 🎨", b"RGB ", &[1.0, 0.0, 0.0], 2),
|
||||
ase_color("", b"CMYK", &[0.1, 0.2, 0.3, 0.0], 2),
|
||||
ase_color(" Red ", b"RGB ", &[2.0, -1.0, f32::NAN], 0),
|
||||
ase_color("Red", b"Gray", &[0.0], 2),
|
||||
untyped,
|
||||
ase_color("Hue", b"HSB ", &[0.1, 0.2, 0.3], 2),
|
||||
(0x0042, vec![1, 2, 3]),
|
||||
(ASE_GROUP_END, vec![]),
|
||||
(ASE_GROUP_START, ase_name("")),
|
||||
(ASE_GROUP_START, ase_name("Red")),
|
||||
ase_color("Red", b"Gray", &[1.0], 2),
|
||||
]);
|
||||
let lib = read_bytes(&bytes, "x").unwrap();
|
||||
let names: Vec<&str> = lib.swatches.iter().map(|w| w.name.as_str()).collect();
|
||||
assert_eq!(names, ["Café 🎨", "C=10 M=20 Y=30 K=0", "Red", "Red 2", "Plain"], "an HSB color and an unknown block are skipped");
|
||||
assert_eq!(lib.swatches[2].paint.color(), Some(Color::rgb(1.0, 0.0, 0.0)), "clamped, NaN read as 0");
|
||||
assert!(lib.swatches[2].global && !lib.swatches[4].global, "without a color type: process");
|
||||
// A group start ends the open group, and groups and colors share names.
|
||||
let groups: Vec<(&str, Vec<&str>)> =
|
||||
lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect();
|
||||
assert_eq!(groups, [("Color Group", vec![]), ("Red 3", vec!["Red 4"])]);
|
||||
assert_eq!(lib.groups[1].swatches[0].paint.color(), Some(Color::gray(0.0)), "gray level 1 is white");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_ase_files_are_errors() {
|
||||
let good = ase(&[(ASE_GROUP_START, ase_name("G")), ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0)]);
|
||||
assert_eq!(read_bytes(&good, "x").unwrap().len(), 1);
|
||||
for n in ASE_SIGNATURE.len()..good.len() {
|
||||
assert!(read_bytes(&good[..n], "x").is_err(), "cut at {n}");
|
||||
}
|
||||
let mut v2 = good.clone();
|
||||
v2[5] = 2;
|
||||
assert!(read_bytes(&v2, "x").unwrap_err().contains("2.0"), "version 2.0");
|
||||
// Too many colors, or too many groups (empty group starts take 6 bytes each).
|
||||
let colors: Vec<(u16, Vec<u8>)> = (0..=ASE_MAX_ENTRIES).map(|_| ase_color("Gray", b"Gray", &[0.5], 2)).collect();
|
||||
assert!(read_bytes(&ase(&colors), "x").unwrap_err().contains("more than"));
|
||||
let groups: Vec<(u16, Vec<u8>)> = (0..=ASE_MAX_ENTRIES).map(|_| (ASE_GROUP_START, vec![])).collect();
|
||||
assert!(read_bytes(&ase(&groups), "x").unwrap_err().contains("more than"));
|
||||
assert_eq!(read_bytes(&ase(&groups[1..]), "x").unwrap().groups.len(), ASE_MAX_ENTRIES, "up to the limit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_writes_each_model_kind_and_group() {
|
||||
let sw = |name: &str, color, global, spot| Swatch { name: name.into(), paint: Paint::solid(color), global, spot };
|
||||
let tint = Swatch {
|
||||
name: "Ink 40%".into(),
|
||||
paint: Paint::Solid { color: Color::cmyk(0.4, 0.2, 0.0, 0.08), swatch: Some("Ink".into()), tint: 0.4 },
|
||||
global: false,
|
||||
spot: false,
|
||||
};
|
||||
// `sample()` holds the spot color Ink, the gradient Fade, the pattern Tiles and the group Neutrals.
|
||||
let mut lib = sample();
|
||||
lib.swatches.insert(0, sw("Sky", Color::rgb(0.0, 0.5, 1.0), true, false));
|
||||
lib.swatches.push(tint);
|
||||
lib.groups[0].swatches = vec![sw("Mist", Color::gray(0.25), false, false), sw("Clay", Color::lab(50.0, 20.0, -30.0), false, false)];
|
||||
lib.groups.push(SwatchGroup { name: "Empty".into(), swatches: vec![] });
|
||||
let bytes = write(&lib, PaletteFormat::Ase).unwrap();
|
||||
let expected = ase(&[
|
||||
ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0),
|
||||
ase_color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1),
|
||||
ase_color("Ink 40%", b"CMYK", &[0.4, 0.2, 0.0, 0.08], 2),
|
||||
(ASE_GROUP_START, ase_name("Neutrals")),
|
||||
ase_color("Mist", b"Gray", &[0.75], 2),
|
||||
ase_color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2),
|
||||
(ASE_GROUP_END, vec![]),
|
||||
(ASE_GROUP_START, ase_name("Empty")),
|
||||
(ASE_GROUP_END, vec![]),
|
||||
]);
|
||||
assert_eq!(bytes, expected, "no gradient or pattern; the tint as the process color it shows");
|
||||
let back = read_bytes(&bytes, "Brand").unwrap();
|
||||
assert_eq!((back.len(), back.groups.len()), (5, 2), "the empty group stays");
|
||||
assert_eq!(PaletteFormat::parse(".ASE"), Some(PaletteFormat::Ase));
|
||||
assert!(PaletteFormat::Ase.readable() && PaletteFormat::Ase.binary() && !PaletteFormat::Gpl.binary());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_names_lose_nul_and_stop_at_the_reader_limit() {
|
||||
let names = ["Re\0d".to_string(), "é".repeat(1030), format!("a{}", "🎨".repeat(600))];
|
||||
let swatches = names.iter().map(|n| Swatch { name: n.clone(), paint: Paint::solid(Color::BLACK), global: false, spot: false }).collect();
|
||||
let lib = SwatchLibrary { name: "x".into(), swatches, groups: vec![] };
|
||||
let back = read_bytes(&write(&lib, PaletteFormat::Ase).unwrap(), "x").unwrap();
|
||||
let got: Vec<&str> = back.swatches.iter().map(|w| w.name.as_str()).collect();
|
||||
// At most 1024 UTF-16 code units, cut between characters: "a" and 511 two-unit emoji.
|
||||
assert_eq!(got, ["Red".to_string(), "é".repeat(1024), format!("a{}", "🎨".repeat(511))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_clamps_components_and_writes_non_finite_ones_as_zero() {
|
||||
let sw = |name: &str, color| Swatch { name: name.into(), paint: Paint::solid(color), global: false, spot: false };
|
||||
let swatches = vec![
|
||||
sw("Lab", Color::lab(100.5, 300.0, -300.0)),
|
||||
sw("Rgb", Color::rgb(2.0, -1.0, f32::NAN)),
|
||||
sw("Cmyk", Color::cmyk(1.5, 0.0, 0.0, f32::INFINITY)),
|
||||
sw("Gray", Color::gray(1.5)),
|
||||
];
|
||||
let bytes = write(&SwatchLibrary { name: "x".into(), swatches, groups: vec![] }, PaletteFormat::Ase).unwrap();
|
||||
let expected = ase(&[
|
||||
ase_color("Lab", b"LAB ", &[1.0, 127.0, -128.0], 2),
|
||||
ase_color("Rgb", b"RGB ", &[1.0, 0.0, 0.0], 2),
|
||||
ase_color("Cmyk", b"CMYK", &[1.0, 0.0, 0.0, 0.0], 2),
|
||||
ase_color("Gray", b"Gray", &[0.0], 2),
|
||||
]);
|
||||
assert_eq!(bytes, expected, "clamped to the ranges .ase holds, a component that isn't finite as 0");
|
||||
// Lightness 100.5 is written as 1, which reads back as L* 100.
|
||||
let back = read_bytes(&bytes, "x").unwrap();
|
||||
assert_eq!(back.swatches[0].paint.color(), Some(Color::lab(100.0, 127.0, -128.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_write_refuses_more_entries_than_the_reader_takes() {
|
||||
let gray = |i: usize| Swatch { name: format!("G{i}"), paint: Paint::solid(Color::gray(0.5)), global: false, spot: false };
|
||||
// The limit counts colors and groups: a group and `ASE_MAX_ENTRIES - 1` colors reach it.
|
||||
let mut lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: (1..ASE_MAX_ENTRIES).map(gray).collect(),
|
||||
groups: vec![SwatchGroup { name: "Group".into(), swatches: vec![] }],
|
||||
};
|
||||
let back = read_bytes(&write(&lib, PaletteFormat::Ase).unwrap(), "x").unwrap();
|
||||
assert_eq!((back.len(), back.groups.len()), (ASE_MAX_ENTRIES - 1, 1));
|
||||
lib.swatches.push(gray(0));
|
||||
let e = write(&lib, PaletteFormat::Ase).unwrap_err();
|
||||
assert!(e.contains("reads at most 100000 colors and groups from a swatch exchange file, and this library has 100001"), "{e}");
|
||||
// A gradient is left out and is not counted.
|
||||
lib.swatches.last_mut().unwrap().paint = sample().swatches[1].paint.clone();
|
||||
assert!(write(&lib, PaletteFormat::Ase).is_ok());
|
||||
}
|
||||
|
||||
/// A color in one of the four models, in the ranges `.ase` holds.
|
||||
fn arb_color() -> impl Strategy<Value = Color> {
|
||||
let unit = || 0.0f32..=1.0;
|
||||
prop_oneof![
|
||||
(unit(), unit(), unit()).prop_map(|(r, g, b)| Color::rgb(r, g, b)),
|
||||
(unit(), unit(), unit(), unit()).prop_map(|(c, m, y, k)| Color::cmyk(c, m, y, k)),
|
||||
unit().prop_map(Color::gray),
|
||||
(0.0f32..=100.0, -128.0f32..=127.0, -128.0f32..=127.0).prop_map(|(l, a, b)| Color::lab(l, a, b)),
|
||||
]
|
||||
}
|
||||
|
||||
/// A swatch's paint with its global and spot flags: a solid color with any flags, a tint swatch
|
||||
/// (both flags off) or a gradient.
|
||||
fn arb_paint() -> impl Strategy<Value = (Paint, bool, bool)> {
|
||||
prop_oneof![
|
||||
4 => (arb_color(), any::<bool>(), any::<bool>()).prop_map(|(c, global, spot)| (Paint::solid(c), global, spot)),
|
||||
1 => arb_color().prop_map(|c| (Paint::Solid { color: c, swatch: Some("Base".into()), tint: 0.4 }, false, false)),
|
||||
1 => Just((sample().swatches[1].paint.clone(), false, false)),
|
||||
]
|
||||
}
|
||||
|
||||
/// Ungrouped swatches and color groups. A name is a number and up to 12 characters of any script
|
||||
/// but NUL, trimmed, so swatches and groups have unique names, as in a document.
|
||||
fn arb_library() -> impl Strategy<Value = SwatchLibrary> {
|
||||
let swatches = || prop::collection::vec((arb_paint(), "[^\\x00]{0,12}"), 0..12);
|
||||
(swatches(), prop::collection::vec(("[^\\x00]{0,12}", swatches()), 0..4)).prop_map(|(loose, groups)| {
|
||||
let mut n = 0;
|
||||
let mut name = |prefix: &str, base: &str| {
|
||||
n += 1;
|
||||
format!("{prefix}{n} {base}").trim().to_string()
|
||||
};
|
||||
let mut lib = SwatchLibrary { name: "Fuzz".into(), ..Default::default() };
|
||||
for ((paint, global, spot), base) in loose {
|
||||
lib.swatches.push(Swatch { name: name("", &base), paint, global, spot });
|
||||
}
|
||||
for (base, list) in groups {
|
||||
let mut g = SwatchGroup { name: name("G", &base), swatches: vec![] };
|
||||
for ((paint, global, spot), base) in list {
|
||||
g.swatches.push(Swatch { name: name("", &base), paint, global, spot });
|
||||
}
|
||||
lib.groups.push(g);
|
||||
}
|
||||
lib
|
||||
})
|
||||
}
|
||||
|
||||
/// Are `got` and `want` in the same model, with every component within 1e-4? Lab lightness and
|
||||
/// gray read back within `f32` rounding.
|
||||
fn close(got: Color, want: Color) -> bool {
|
||||
let near = |a: f32, b: f32| (a - b).abs() < 1e-4;
|
||||
match (got, want) {
|
||||
(Color::Rgb { r, g, b }, Color::Rgb { r: r2, g: g2, b: b2 }) => near(r, r2) && near(g, g2) && near(b, b2),
|
||||
(Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => near(c, c2) && near(m, m2) && near(y, y2) && near(k, k2),
|
||||
(Color::Gray { k }, Color::Gray { k: k2 }) => near(k, k2),
|
||||
(Color::Lab { l, a, b }, Color::Lab { l: l2, a: a2, b: b2 }) => near(l, l2) && near(a, a2) && near(b, b2),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The swatches of `list` as an `.ase` file reads them back: solid colors only, unlinked, spot
|
||||
/// colors global.
|
||||
fn ase_expected(list: &[Swatch]) -> Vec<Swatch> {
|
||||
list.iter()
|
||||
.filter_map(|w| Some(Swatch { name: w.name.clone(), paint: Paint::solid(w.paint.color()?), global: w.global || w.spot, spot: w.spot }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Do swatches `got` have the names, flags and unlinked colors (within 1e-4) of `want`?
|
||||
fn same_swatches(got: &[Swatch], want: &[Swatch]) -> bool {
|
||||
got.len() == want.len()
|
||||
&& got.iter().zip(want).all(|(g, w)| {
|
||||
let color = match (&g.paint, w.paint.color()) {
|
||||
(Paint::Solid { color, swatch: None, .. }, Some(c)) => close(*color, c),
|
||||
_ => false,
|
||||
};
|
||||
g.name == w.name && g.global == w.global && g.spot == w.spot && color
|
||||
})
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { failure_persistence: None, ..ProptestConfig::default() })]
|
||||
|
||||
/// A written `.ase` file reads back as the library's solid colors in their own model, with
|
||||
/// their names, kinds and color groups.
|
||||
#[test]
|
||||
fn ase_round_trip_keeps_models_kinds_and_groups(lib in arb_library()) {
|
||||
let bytes = write(&lib, PaletteFormat::Ase).unwrap();
|
||||
prop_assert!(sniff_bytes(&bytes));
|
||||
let back = read_bytes(&bytes, &lib.name).unwrap();
|
||||
prop_assert_eq!(&back.name, &lib.name);
|
||||
prop_assert!(same_swatches(&back.swatches, &ase_expected(&lib.swatches)), "{:?}", back.swatches);
|
||||
prop_assert_eq!(back.groups.len(), lib.groups.len());
|
||||
for (g, want) in back.groups.iter().zip(&lib.groups) {
|
||||
prop_assert_eq!(&g.name, &want.name);
|
||||
prop_assert!(same_swatches(&g.swatches, &ase_expected(&want.swatches)), "{}: {:?}", g.name, g.swatches);
|
||||
}
|
||||
}
|
||||
|
||||
/// A written `.vcswatches`, `.gpl` or `.ase` file reads back with as many swatches as
|
||||
/// [`PaletteFormat::holds`] counts.
|
||||
#[test]
|
||||
fn written_files_read_back_with_the_swatches_holds_counts(lib in arb_library()) {
|
||||
for f in [PaletteFormat::Native, PaletteFormat::Gpl, PaletteFormat::Ase] {
|
||||
let back = read_bytes(&write(&lib, f).unwrap(), &lib.name).unwrap();
|
||||
prop_assert_eq!(back.len(), lib.iter().filter(|w| f.holds(&w.paint)).count(), "{:?}", f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,517 @@
|
||||
use super::*;
|
||||
use crate::{Gradient, GradientPaint, GradientStop};
|
||||
use proptest::prelude::*;
|
||||
|
||||
#[test]
|
||||
fn gpl_blank_name_keeps_fallback() {
|
||||
let blank = "GIMP Palette\nName: \nColumns: 0\n#\n 1 2 3\tx\n";
|
||||
assert_eq!(read(blank, "fallback").unwrap().name, "fallback");
|
||||
let named = "GIMP Palette\nName: Warm\n 1 2 3\tx\n";
|
||||
assert_eq!(read(named, "fallback").unwrap().name, "Warm");
|
||||
}
|
||||
|
||||
/// A color book's string: a `u32` count of UTF-16 code units, then the units.
|
||||
fn acb_str(out: &mut Vec<u8>, s: &str) {
|
||||
let units: Vec<u16> = s.encode_utf16().collect();
|
||||
out.extend((units.len() as u32).to_be_bytes());
|
||||
units.iter().for_each(|u| out.extend(u.to_be_bytes()));
|
||||
}
|
||||
|
||||
/// A color book in `space` (0 RGB, 2 CMYK, 7 Lab) with `colors` (name, components) and an
|
||||
/// optional spot/process marker.
|
||||
fn acb(space: u16, colors: &[(&str, &[u8])], marker: &[u8]) -> Vec<u8> {
|
||||
let mut b = b"8BCB".to_vec();
|
||||
b.extend(1u16.to_be_bytes());
|
||||
b.extend(3000u16.to_be_bytes());
|
||||
for s in ["$$$/colorbook/Test/title=Test Book^R", "TEST ", " C", "a book"] {
|
||||
acb_str(&mut b, s);
|
||||
}
|
||||
b.extend((colors.len() as u16).to_be_bytes());
|
||||
b.extend(7u16.to_be_bytes());
|
||||
b.extend(0u16.to_be_bytes());
|
||||
b.extend(space.to_be_bytes());
|
||||
for (name, comps) in colors {
|
||||
acb_str(&mut b, name);
|
||||
b.extend(b"TST001");
|
||||
b.extend(*comps);
|
||||
}
|
||||
b.extend(marker);
|
||||
b
|
||||
}
|
||||
|
||||
/// #831: color books (`.acb`) are read: their colors in RGB, CMYK or Lab, named with the book's
|
||||
/// prefix and suffix, spot unless the book says process; page padding is left out.
|
||||
#[test]
|
||||
fn color_books_are_read() {
|
||||
let lib = read_bytes(&acb(0, &[("185", &[228, 0, 43]), ("", &[0, 0, 0]), ("Red 032", &[239, 51, 64])], b"spflspot"), "fallback").unwrap();
|
||||
assert_eq!(lib.name, "Test Book®");
|
||||
let names: Vec<&str> = lib.swatches.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names, ["TEST 185 C", "TEST Red 032 C"]);
|
||||
assert!(lib.swatches.iter().all(|s| s.spot && s.global));
|
||||
assert_eq!(lib.swatches[0].paint.color(), Some(Color::rgb8(228, 0, 43)));
|
||||
// CMYK ink is stored inverted; a book marked process gives process colors.
|
||||
let lib = read_bytes(&acb(2, &[("Cyan", &[0, 255, 255, 255])], b"spflproc"), "x").unwrap();
|
||||
assert_eq!(lib.swatches[0].paint.color(), Some(Color::cmyk(1.0, 0.0, 0.0, 0.0)));
|
||||
assert!(!lib.swatches[0].spot && !lib.swatches[0].global);
|
||||
// Lab: lightness 0..255 for 0..100, a and b offset by 128; no marker: spot.
|
||||
let lib = read_bytes(&acb(7, &[("Grey", &[255, 128, 128])], b""), "x").unwrap();
|
||||
assert_eq!(lib.swatches[0].paint.color(), Some(Color::lab(100.0, 0.0, 0.0)));
|
||||
assert!(lib.swatches[0].spot);
|
||||
assert!(sniff_bytes(&acb(0, &[], b"")));
|
||||
// Unsupported versions and color spaces, and short files, are errors.
|
||||
let mut v2 = acb(0, &[], b"");
|
||||
v2[5] = 2;
|
||||
assert!(read_bytes(&v2, "x").is_err());
|
||||
assert!(read_bytes(&acb(1, &[("x", &[1, 2, 3])], b""), "x").is_err());
|
||||
let full = acb(0, &[("185", &[228, 0, 43])], b"");
|
||||
for cut in 4..full.len() {
|
||||
assert!(read_bytes(&full[..cut], "x").is_err(), "{cut} bytes");
|
||||
}
|
||||
let mut huge = b"8BCB\0\x01\0\x01".to_vec();
|
||||
huge.extend(u32::MAX.to_be_bytes());
|
||||
assert!(read_bytes(&huge, "x").is_err(), "a string longer than the file");
|
||||
}
|
||||
|
||||
fn sample() -> SwatchLibrary {
|
||||
let grad = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
|
||||
GradientKind::Linear,
|
||||
vec![
|
||||
GradientStop { midpoint: 0.4, ..GradientStop::new(0.0, Color::cmyk(0.1, 0.2, 0.3, 0.0)) },
|
||||
GradientStop { opacity: 0.5, ..GradientStop::new(1.0, Color::rgb8(255, 0, 0)) },
|
||||
],
|
||||
))));
|
||||
SwatchLibrary {
|
||||
name: "Brand */ Colours".into(),
|
||||
swatches: vec![
|
||||
Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(1.0, 0.5, 0.0, 0.2)), global: true, spot: true },
|
||||
Swatch { name: "Fade".into(), paint: grad, global: false, spot: false },
|
||||
Swatch { name: "Tiles".into(), paint: Paint::Pattern { pattern: "Dots".into(), xf: Default::default() }, global: false, spot: false },
|
||||
],
|
||||
groups: vec![SwatchGroup {
|
||||
name: "Neutrals".into(),
|
||||
swatches: vec![
|
||||
Swatch { name: "R=255 G=0 B=0".into(), paint: Paint::solid(Color::rgb8(255, 0, 0)), global: false, spot: false },
|
||||
Swatch { name: "Mist".into(), paint: Paint::solid(Color::gray(0.25)), global: true, spot: false },
|
||||
],
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
/// `lib` written as text format `f`.
|
||||
fn written(lib: &SwatchLibrary, f: PaletteFormat) -> String {
|
||||
String::from_utf8(write(lib, f).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_round_trip_keeps_cmyk_spot_and_groups() {
|
||||
let lib = sample();
|
||||
let text = written(&lib, PaletteFormat::Native);
|
||||
assert!(sniff(&text));
|
||||
let back = read(&text, "fallback").unwrap();
|
||||
let mut expected = lib.clone();
|
||||
expected.swatches.retain(|w| !matches!(w.paint, Paint::Pattern { .. }));
|
||||
assert_eq!(back, expected, "everything but the pattern comes back exactly");
|
||||
assert!(back.swatches[0].spot && back.swatches[0].global);
|
||||
assert_eq!(back.swatches[0].paint.color(), Some(Color::cmyk(1.0, 0.5, 0.0, 0.2)));
|
||||
assert!(read("{\"format\": \"other\", \"version\": 1, \"name\": \"x\"}", "x").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpl_writes_rgb_with_group_headers_and_reads_comments_and_headers() {
|
||||
let text = written(&sample(), PaletteFormat::Gpl);
|
||||
assert!(text.starts_with("GIMP Palette\nName: Brand */ Colours\n"));
|
||||
assert!(text.contains("# Group: Neutrals\n255 0 0\tR=255 G=0 B=0\n"), "{text}");
|
||||
assert!(!text.contains("Fade") && !text.contains("Tiles"), "only solid colours");
|
||||
let back = read(&text, "x").unwrap();
|
||||
assert_eq!(back.name, "Brand */ Colours");
|
||||
assert_eq!(back.swatches.len(), 1);
|
||||
assert_eq!(back.groups[0].swatches[1].paint.color(), Some(Color::rgb8(191, 191, 191)), "grey as 8-bit RGB");
|
||||
// Another tool's palette: comments, a Columns header, blank lines, unnamed and repeated names.
|
||||
let other = "GIMP Palette\r\nName: Sunset\r\nColumns: 4\r\n# a comment\r\n\r\n 0 128 255\tSky Blue\r\n10 20 30\r\n0 0 0 Black\r\n1 1 1 Black\r\nbad line\r\n";
|
||||
let lib = read(other, "file").unwrap();
|
||||
assert_eq!(lib.name, "Sunset");
|
||||
let names: Vec<&str> = lib.swatches.iter().map(|w| w.name.as_str()).collect();
|
||||
assert_eq!(names, ["Sky Blue", "R=10 G=20 B=30", "Black", "Black 2"]);
|
||||
assert_eq!(lib.swatches[0].paint.color(), Some(Color::rgb8(0, 128, 255)));
|
||||
assert_eq!(read("GIMP Palette\n1 2 3 x\n", "Fallback").unwrap().name, "Fallback");
|
||||
// Colors and groups share names; an unnamed group is "Color Group".
|
||||
let lib = read("GIMP Palette\n0 0 0 Black\n# Group: Black\n1 1 1 Black\n# Group:\n", "x").unwrap();
|
||||
let groups: Vec<(&str, Vec<&str>)> = lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect();
|
||||
assert_eq!(groups, [("Black 2", vec!["Black 3"]), ("Color Group", vec![])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn css_escapes_names_and_writes_gradients() {
|
||||
assert_eq!(css_property("Sky Blue"), "--sky-blue");
|
||||
assert_eq!(css_property("R=255 G=0 B=0"), "--r\\=255-g\\=0-b\\=0");
|
||||
assert_eq!(css_property("#FF00CC"), "--\\#ff00cc");
|
||||
assert_eq!(css_property("Café 50%"), "--café-50\\%");
|
||||
assert_eq!(css_property(" "), "--swatch");
|
||||
let text = written(&sample(), PaletteFormat::Css);
|
||||
assert!(text.starts_with("/* Brand * / Colours */\n:root {\n"), "{text}");
|
||||
assert!(text.contains(" --ink: #"), "{text}");
|
||||
assert!(text.contains("; /* spot */"));
|
||||
assert!(text.contains(" --fade: linear-gradient(90deg, #"), "{text}");
|
||||
assert!(text.contains("#ff000080 100%)"), "half-transparent stop: {text}");
|
||||
assert!(text.contains(" /* Neutrals */\n --r\\=255-g\\=0-b\\=0: #ff0000;\n"));
|
||||
assert!(!text.contains("tiles"));
|
||||
// Names that collide once escaped are numbered.
|
||||
let lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: ["Red", "red"].map(|n| Swatch { name: n.into(), paint: Paint::solid(Color::BLACK), global: false, spot: false }).to_vec(),
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
assert!(text.contains("--red: #000000;") && text.contains("--red-2: #000000;"));
|
||||
assert!(read(&text, "x").is_err(), "CSS is written only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn css_preserves_fractional_gradient_stop_positions() {
|
||||
for kind in [GradientKind::Linear, GradientKind::Radial] {
|
||||
let lib = SwatchLibrary {
|
||||
name: "Positions".into(),
|
||||
swatches: vec![Swatch {
|
||||
name: "Ramp".into(),
|
||||
paint: Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
|
||||
kind,
|
||||
vec![
|
||||
GradientStop::new(0.0, Color::BLACK),
|
||||
GradientStop::new(0.125, Color::rgb8(255, 0, 0)),
|
||||
GradientStop::new(0.12890625, Color::WHITE),
|
||||
GradientStop::new(1.0, Color::rgb8(0, 0, 255)),
|
||||
],
|
||||
)))),
|
||||
global: false,
|
||||
spot: false,
|
||||
}],
|
||||
groups: vec![],
|
||||
};
|
||||
let text = written(&lib, PaletteFormat::Css);
|
||||
assert!(text.contains("#000000 0%, #ff0000 12.5%, #ffffff 12.890625%, #0000ff 100%"), "{kind:?}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holds_counts_the_swatches_each_format_writes() {
|
||||
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
|
||||
let mut lib = sample();
|
||||
let Paint::Gradient(mut mesh) = lib.swatches[1].paint.clone() else { panic!("Fade is a gradient") };
|
||||
mesh.gradient.kind = GradientKind::Freeform;
|
||||
lib.swatches.push(Swatch { name: "Mesh".into(), paint: Paint::Gradient(mesh), global: false, spot: false });
|
||||
lib.swatches.push(Swatch { name: "[None]".into(), paint: Paint::None, global: false, spot: false });
|
||||
let held = |f: PaletteFormat| lib.iter().filter(|w| f.holds(&w.paint)).count();
|
||||
assert_eq!(PaletteFormat::ALL.map(held), [5, 3, 3, 4], "vcswatches, gpl, ase, css");
|
||||
for f in [PaletteFormat::Native, PaletteFormat::Gpl, PaletteFormat::Ase] {
|
||||
assert_eq!(read_bytes(&write(&lib, f).unwrap(), "x").unwrap().len(), held(f), "{f:?}");
|
||||
}
|
||||
let css = written(&lib, PaletteFormat::Css);
|
||||
assert_eq!(css.lines().filter(|l| l.starts_with(" --")).count(), held(PaletteFormat::Css), "one property each: {css}");
|
||||
}
|
||||
|
||||
/// A swatch exchange file of `blocks` (type, body).
|
||||
fn ase(blocks: &[(u16, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut out = b"ASEF\0\x01\0\0".to_vec();
|
||||
out.extend((blocks.len() as u32).to_be_bytes());
|
||||
for (kind, body) in blocks {
|
||||
out.extend(kind.to_be_bytes());
|
||||
out.extend((body.len() as u32).to_be_bytes());
|
||||
out.extend(body);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A name as `.ase` stores it.
|
||||
fn ase_name(name: &str) -> Vec<u8> {
|
||||
let units: Vec<u16> = name.encode_utf16().chain([0]).collect();
|
||||
let mut out = (units.len() as u16).to_be_bytes().to_vec();
|
||||
out.extend(units.iter().flat_map(|u| u.to_be_bytes()));
|
||||
out
|
||||
}
|
||||
|
||||
/// A color block: name, model, components and color type.
|
||||
fn ase_color(name: &str, model: &[u8; 4], values: &[f32], kind: u16) -> (u16, Vec<u8>) {
|
||||
let mut body = ase_name(name);
|
||||
body.extend(model);
|
||||
body.extend(values.iter().flat_map(|v| v.to_be_bytes()));
|
||||
body.extend(kind.to_be_bytes());
|
||||
(ASE_COLOR, body)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_reads_color_models_kinds_and_groups() {
|
||||
let bytes = ase(&[
|
||||
ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0),
|
||||
ase_color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1),
|
||||
(ASE_GROUP_START, ase_name("Neutrals")),
|
||||
ase_color("Mist", b"Gray", &[0.75], 2),
|
||||
ase_color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2),
|
||||
(ASE_GROUP_END, vec![]),
|
||||
ase_color("Paper", b"RGB ", &[1.0, 1.0, 1.0], 2),
|
||||
]);
|
||||
assert!(sniff_bytes(&bytes));
|
||||
let sw = |name: &str, color, global, spot| Swatch { name: name.into(), paint: Paint::solid(color), global, spot };
|
||||
let expected = SwatchLibrary {
|
||||
name: "Brand".into(),
|
||||
swatches: vec![
|
||||
sw("Sky", Color::rgb(0.0, 0.5, 1.0), true, false),
|
||||
sw("Ink", Color::cmyk(1.0, 0.5, 0.0, 0.2), true, true),
|
||||
sw("Paper", Color::WHITE, false, false),
|
||||
],
|
||||
groups: vec![SwatchGroup {
|
||||
name: "Neutrals".into(),
|
||||
swatches: vec![sw("Mist", Color::gray(0.25), false, false), sw("Clay", Color::lab(50.0, 20.0, -30.0), false, false)],
|
||||
}],
|
||||
};
|
||||
assert_eq!(read_bytes(&bytes, "Brand").unwrap(), expected, "named after the file; 0 global, 1 spot, 2 process");
|
||||
// A lightness above 1 is L* itself.
|
||||
let deep = read_bytes(&ase(&[ase_color("Deep", b"LAB ", &[53.0, 20.0, -30.0], 2)]), "x").unwrap();
|
||||
assert_eq!(deep.swatches[0].paint.color(), Some(Color::lab(53.0, 20.0, -30.0)));
|
||||
// Text libraries read through the same call, also when they aren't valid UTF-8.
|
||||
assert!(sniff_bytes(b"GIMP Palette\n1 2 3 x\n") && !sniff_bytes(b"ASE") && !sniff_bytes(&[0xff, 0xfe, 0]));
|
||||
assert_eq!(read_bytes(b"GIMP Palette\n1 2 3 x\n", "F").unwrap().swatches.len(), 1);
|
||||
let latin1 = b"GIMP Palette\n1 2 3 Caf\xe9\n";
|
||||
assert!(sniff_bytes(latin1));
|
||||
assert_eq!(read_bytes(latin1, "F").unwrap().swatches.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_names_unnamed_and_repeated_entries_and_skips_other_blocks() {
|
||||
let mut untyped = ase_color("Plain", b"RGB ", &[0.2, 0.4, 0.6], 2);
|
||||
untyped.1.truncate(untyped.1.len() - 2);
|
||||
let bytes = ase(&[
|
||||
ase_color("Café 🎨", b"RGB ", &[1.0, 0.0, 0.0], 2),
|
||||
ase_color("", b"CMYK", &[0.1, 0.2, 0.3, 0.0], 2),
|
||||
ase_color(" Red ", b"RGB ", &[2.0, -1.0, f32::NAN], 0),
|
||||
ase_color("Red", b"Gray", &[0.0], 2),
|
||||
untyped,
|
||||
ase_color("Hue", b"HSB ", &[0.1, 0.2, 0.3], 2),
|
||||
(0x0042, vec![1, 2, 3]),
|
||||
(ASE_GROUP_END, vec![]),
|
||||
(ASE_GROUP_START, ase_name("")),
|
||||
(ASE_GROUP_START, ase_name("Red")),
|
||||
ase_color("Red", b"Gray", &[1.0], 2),
|
||||
]);
|
||||
let lib = read_bytes(&bytes, "x").unwrap();
|
||||
let names: Vec<&str> = lib.swatches.iter().map(|w| w.name.as_str()).collect();
|
||||
assert_eq!(names, ["Café 🎨", "C=10 M=20 Y=30 K=0", "Red", "Red 2", "Plain"], "an HSB color and an unknown block are skipped");
|
||||
assert_eq!(lib.swatches[2].paint.color(), Some(Color::rgb(1.0, 0.0, 0.0)), "clamped, NaN read as 0");
|
||||
assert!(lib.swatches[2].global && !lib.swatches[4].global, "without a color type: process");
|
||||
// A group start ends the open group, and groups and colors share names.
|
||||
let groups: Vec<(&str, Vec<&str>)> = lib.groups.iter().map(|g| (g.name.as_str(), g.swatches.iter().map(|w| w.name.as_str()).collect())).collect();
|
||||
assert_eq!(groups, [("Color Group", vec![]), ("Red 3", vec!["Red 4"])]);
|
||||
assert_eq!(lib.groups[1].swatches[0].paint.color(), Some(Color::gray(0.0)), "gray level 1 is white");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_ase_files_are_errors() {
|
||||
let good = ase(&[(ASE_GROUP_START, ase_name("G")), ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0)]);
|
||||
assert_eq!(read_bytes(&good, "x").unwrap().len(), 1);
|
||||
for n in ASE_SIGNATURE.len()..good.len() {
|
||||
assert!(read_bytes(&good[..n], "x").is_err(), "cut at {n}");
|
||||
}
|
||||
let mut v2 = good.clone();
|
||||
v2[5] = 2;
|
||||
assert!(read_bytes(&v2, "x").unwrap_err().contains("2.0"), "version 2.0");
|
||||
// Too many colors, or too many groups (empty group starts take 6 bytes each).
|
||||
let colors: Vec<(u16, Vec<u8>)> = (0..=ASE_MAX_ENTRIES).map(|_| ase_color("Gray", b"Gray", &[0.5], 2)).collect();
|
||||
assert!(read_bytes(&ase(&colors), "x").unwrap_err().contains("more than"));
|
||||
let groups: Vec<(u16, Vec<u8>)> = (0..=ASE_MAX_ENTRIES).map(|_| (ASE_GROUP_START, vec![])).collect();
|
||||
assert!(read_bytes(&ase(&groups), "x").unwrap_err().contains("more than"));
|
||||
assert_eq!(read_bytes(&ase(&groups[1..]), "x").unwrap().groups.len(), ASE_MAX_ENTRIES, "up to the limit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_writes_each_model_kind_and_group() {
|
||||
let sw = |name: &str, color, global, spot| Swatch { name: name.into(), paint: Paint::solid(color), global, spot };
|
||||
let tint = Swatch {
|
||||
name: "Ink 40%".into(),
|
||||
paint: Paint::Solid { color: Color::cmyk(0.4, 0.2, 0.0, 0.08), swatch: Some("Ink".into()), tint: 0.4 },
|
||||
global: false,
|
||||
spot: false,
|
||||
};
|
||||
// `sample()` holds the spot color Ink, the gradient Fade, the pattern Tiles and the group Neutrals.
|
||||
let mut lib = sample();
|
||||
lib.swatches.insert(0, sw("Sky", Color::rgb(0.0, 0.5, 1.0), true, false));
|
||||
lib.swatches.push(tint);
|
||||
lib.groups[0].swatches = vec![sw("Mist", Color::gray(0.25), false, false), sw("Clay", Color::lab(50.0, 20.0, -30.0), false, false)];
|
||||
lib.groups.push(SwatchGroup { name: "Empty".into(), swatches: vec![] });
|
||||
let bytes = write(&lib, PaletteFormat::Ase).unwrap();
|
||||
let expected = ase(&[
|
||||
ase_color("Sky", b"RGB ", &[0.0, 0.5, 1.0], 0),
|
||||
ase_color("Ink", b"CMYK", &[1.0, 0.5, 0.0, 0.2], 1),
|
||||
ase_color("Ink 40%", b"CMYK", &[0.4, 0.2, 0.0, 0.08], 2),
|
||||
(ASE_GROUP_START, ase_name("Neutrals")),
|
||||
ase_color("Mist", b"Gray", &[0.75], 2),
|
||||
ase_color("Clay", b"LAB ", &[0.5, 20.0, -30.0], 2),
|
||||
(ASE_GROUP_END, vec![]),
|
||||
(ASE_GROUP_START, ase_name("Empty")),
|
||||
(ASE_GROUP_END, vec![]),
|
||||
]);
|
||||
assert_eq!(bytes, expected, "no gradient or pattern; the tint as the process color it shows");
|
||||
let back = read_bytes(&bytes, "Brand").unwrap();
|
||||
assert_eq!((back.len(), back.groups.len()), (5, 2), "the empty group stays");
|
||||
assert_eq!(PaletteFormat::parse(".ASE"), Some(PaletteFormat::Ase));
|
||||
assert!(PaletteFormat::Ase.readable() && PaletteFormat::Ase.binary() && !PaletteFormat::Gpl.binary());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_names_lose_nul_and_stop_at_the_reader_limit() {
|
||||
let names = ["Re\0d".to_string(), "é".repeat(1030), format!("a{}", "🎨".repeat(600))];
|
||||
let swatches = names.iter().map(|n| Swatch { name: n.clone(), paint: Paint::solid(Color::BLACK), global: false, spot: false }).collect();
|
||||
let lib = SwatchLibrary { name: "x".into(), swatches, groups: vec![] };
|
||||
let back = read_bytes(&write(&lib, PaletteFormat::Ase).unwrap(), "x").unwrap();
|
||||
let got: Vec<&str> = back.swatches.iter().map(|w| w.name.as_str()).collect();
|
||||
// At most 1024 UTF-16 code units, cut between characters: "a" and 511 two-unit emoji.
|
||||
assert_eq!(got, ["Red".to_string(), "é".repeat(1024), format!("a{}", "🎨".repeat(511))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_clamps_components_and_writes_non_finite_ones_as_zero() {
|
||||
let sw = |name: &str, color| Swatch { name: name.into(), paint: Paint::solid(color), global: false, spot: false };
|
||||
let swatches = vec![
|
||||
sw("Lab", Color::lab(100.5, 300.0, -300.0)),
|
||||
sw("Rgb", Color::rgb(2.0, -1.0, f32::NAN)),
|
||||
sw("Cmyk", Color::cmyk(1.5, 0.0, 0.0, f32::INFINITY)),
|
||||
sw("Gray", Color::gray(1.5)),
|
||||
];
|
||||
let bytes = write(&SwatchLibrary { name: "x".into(), swatches, groups: vec![] }, PaletteFormat::Ase).unwrap();
|
||||
let expected = ase(&[
|
||||
ase_color("Lab", b"LAB ", &[1.0, 127.0, -128.0], 2),
|
||||
ase_color("Rgb", b"RGB ", &[1.0, 0.0, 0.0], 2),
|
||||
ase_color("Cmyk", b"CMYK", &[1.0, 0.0, 0.0, 0.0], 2),
|
||||
ase_color("Gray", b"Gray", &[0.0], 2),
|
||||
]);
|
||||
assert_eq!(bytes, expected, "clamped to the ranges .ase holds, a component that isn't finite as 0");
|
||||
// Lightness 100.5 is written as 1, which reads back as L* 100.
|
||||
let back = read_bytes(&bytes, "x").unwrap();
|
||||
assert_eq!(back.swatches[0].paint.color(), Some(Color::lab(100.0, 127.0, -128.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ase_write_refuses_more_entries_than_the_reader_takes() {
|
||||
let gray = |i: usize| Swatch { name: format!("G{i}"), paint: Paint::solid(Color::gray(0.5)), global: false, spot: false };
|
||||
// The limit counts colors and groups: a group and `ASE_MAX_ENTRIES - 1` colors reach it.
|
||||
let mut lib = SwatchLibrary {
|
||||
name: "x".into(),
|
||||
swatches: (1..ASE_MAX_ENTRIES).map(gray).collect(),
|
||||
groups: vec![SwatchGroup { name: "Group".into(), swatches: vec![] }],
|
||||
};
|
||||
let back = read_bytes(&write(&lib, PaletteFormat::Ase).unwrap(), "x").unwrap();
|
||||
assert_eq!((back.len(), back.groups.len()), (ASE_MAX_ENTRIES - 1, 1));
|
||||
lib.swatches.push(gray(0));
|
||||
let e = write(&lib, PaletteFormat::Ase).unwrap_err();
|
||||
assert!(e.contains("reads at most 100000 colors and groups from a swatch exchange file, and this library has 100001"), "{e}");
|
||||
// A gradient is left out and is not counted.
|
||||
lib.swatches.last_mut().unwrap().paint = sample().swatches[1].paint.clone();
|
||||
assert!(write(&lib, PaletteFormat::Ase).is_ok());
|
||||
}
|
||||
|
||||
/// A color in one of the four models, in the ranges `.ase` holds.
|
||||
fn arb_color() -> impl Strategy<Value = Color> {
|
||||
let unit = || 0.0f32..=1.0;
|
||||
prop_oneof![
|
||||
(unit(), unit(), unit()).prop_map(|(r, g, b)| Color::rgb(r, g, b)),
|
||||
(unit(), unit(), unit(), unit()).prop_map(|(c, m, y, k)| Color::cmyk(c, m, y, k)),
|
||||
unit().prop_map(Color::gray),
|
||||
(0.0f32..=100.0, -128.0f32..=127.0, -128.0f32..=127.0).prop_map(|(l, a, b)| Color::lab(l, a, b)),
|
||||
]
|
||||
}
|
||||
|
||||
/// A swatch's paint with its global and spot flags: a solid color with any flags, a tint swatch
|
||||
/// (both flags off) or a gradient.
|
||||
fn arb_paint() -> impl Strategy<Value = (Paint, bool, bool)> {
|
||||
prop_oneof![
|
||||
4 => (arb_color(), any::<bool>(), any::<bool>()).prop_map(|(c, global, spot)| (Paint::solid(c), global, spot)),
|
||||
1 => arb_color().prop_map(|c| (Paint::Solid { color: c, swatch: Some("Base".into()), tint: 0.4 }, false, false)),
|
||||
1 => Just((sample().swatches[1].paint.clone(), false, false)),
|
||||
]
|
||||
}
|
||||
|
||||
/// Ungrouped swatches and color groups. A name is a number and up to 12 characters of any script
|
||||
/// but NUL, trimmed, so swatches and groups have unique names, as in a document.
|
||||
fn arb_library() -> impl Strategy<Value = SwatchLibrary> {
|
||||
let swatches = || prop::collection::vec((arb_paint(), "[^\\x00]{0,12}"), 0..12);
|
||||
(swatches(), prop::collection::vec(("[^\\x00]{0,12}", swatches()), 0..4)).prop_map(|(loose, groups)| {
|
||||
let mut n = 0;
|
||||
let mut name = |prefix: &str, base: &str| {
|
||||
n += 1;
|
||||
format!("{prefix}{n} {base}").trim().to_string()
|
||||
};
|
||||
let mut lib = SwatchLibrary { name: "Fuzz".into(), ..Default::default() };
|
||||
for ((paint, global, spot), base) in loose {
|
||||
lib.swatches.push(Swatch { name: name("", &base), paint, global, spot });
|
||||
}
|
||||
for (base, list) in groups {
|
||||
let mut g = SwatchGroup { name: name("G", &base), swatches: vec![] };
|
||||
for ((paint, global, spot), base) in list {
|
||||
g.swatches.push(Swatch { name: name("", &base), paint, global, spot });
|
||||
}
|
||||
lib.groups.push(g);
|
||||
}
|
||||
lib
|
||||
})
|
||||
}
|
||||
|
||||
/// Are `got` and `want` in the same model, with every component within 1e-4? Lab lightness and
|
||||
/// gray read back within `f32` rounding.
|
||||
fn close(got: Color, want: Color) -> bool {
|
||||
let near = |a: f32, b: f32| (a - b).abs() < 1e-4;
|
||||
match (got, want) {
|
||||
(Color::Rgb { r, g, b }, Color::Rgb { r: r2, g: g2, b: b2 }) => near(r, r2) && near(g, g2) && near(b, b2),
|
||||
(Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => near(c, c2) && near(m, m2) && near(y, y2) && near(k, k2),
|
||||
(Color::Gray { k }, Color::Gray { k: k2 }) => near(k, k2),
|
||||
(Color::Lab { l, a, b }, Color::Lab { l: l2, a: a2, b: b2 }) => near(l, l2) && near(a, a2) && near(b, b2),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The swatches of `list` as an `.ase` file reads them back: solid colors only, unlinked, spot
|
||||
/// colors global.
|
||||
fn ase_expected(list: &[Swatch]) -> Vec<Swatch> {
|
||||
list.iter()
|
||||
.filter_map(|w| Some(Swatch { name: w.name.clone(), paint: Paint::solid(w.paint.color()?), global: w.global || w.spot, spot: w.spot }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Do swatches `got` have the names, flags and unlinked colors (within 1e-4) of `want`?
|
||||
fn same_swatches(got: &[Swatch], want: &[Swatch]) -> bool {
|
||||
got.len() == want.len()
|
||||
&& got.iter().zip(want).all(|(g, w)| {
|
||||
let color = match (&g.paint, w.paint.color()) {
|
||||
(Paint::Solid { color, swatch: None, .. }, Some(c)) => close(*color, c),
|
||||
_ => false,
|
||||
};
|
||||
g.name == w.name && g.global == w.global && g.spot == w.spot && color
|
||||
})
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { failure_persistence: None, ..ProptestConfig::default() })]
|
||||
|
||||
/// A written `.ase` file reads back as the library's solid colors in their own model, with
|
||||
/// their names, kinds and color groups.
|
||||
#[test]
|
||||
fn ase_round_trip_keeps_models_kinds_and_groups(lib in arb_library()) {
|
||||
let bytes = write(&lib, PaletteFormat::Ase).unwrap();
|
||||
prop_assert!(sniff_bytes(&bytes));
|
||||
let back = read_bytes(&bytes, &lib.name).unwrap();
|
||||
prop_assert_eq!(&back.name, &lib.name);
|
||||
prop_assert!(same_swatches(&back.swatches, &ase_expected(&lib.swatches)), "{:?}", back.swatches);
|
||||
prop_assert_eq!(back.groups.len(), lib.groups.len());
|
||||
for (g, want) in back.groups.iter().zip(&lib.groups) {
|
||||
prop_assert_eq!(&g.name, &want.name);
|
||||
prop_assert!(same_swatches(&g.swatches, &ase_expected(&want.swatches)), "{}: {:?}", g.name, g.swatches);
|
||||
}
|
||||
}
|
||||
|
||||
/// A written `.vcswatches`, `.gpl` or `.ase` file reads back with as many swatches as
|
||||
/// [`PaletteFormat::holds`] counts.
|
||||
#[test]
|
||||
fn written_files_read_back_with_the_swatches_holds_counts(lib in arb_library()) {
|
||||
for f in [PaletteFormat::Native, PaletteFormat::Gpl, PaletteFormat::Ase] {
|
||||
let back = read_bytes(&write(&lib, f).unwrap(), &lib.name).unwrap();
|
||||
prop_assert_eq!(back.len(), lib.iter().filter(|w| f.holds(&w.paint)).count(), "{:?}", f);
|
||||
}
|
||||
}
|
||||
}
|
||||
+93
-951
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,240 @@
|
||||
use super::profile::{PressureProfile, WidthProfile};
|
||||
use super::stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
|
||||
use super::*;
|
||||
|
||||
/// A live effect in an appearance stack. Parameters are interpreted by `vectorcraft-effects`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Effect {
|
||||
/// Stable id, e.g. `stylize.dropShadow`, `distort.roughen`, `path.offsetPath`, `warp.arc`.
|
||||
pub id: String,
|
||||
#[serde(default)]
|
||||
pub params: serde_json::Value,
|
||||
#[serde(default = "yes")]
|
||||
pub visible: bool,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn one() -> f32 {
|
||||
1.0
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FillLayer {
|
||||
pub paint: Paint,
|
||||
#[serde(default = "one", skip_serializing_if = "crate::skip::is_one")]
|
||||
pub opacity: f32,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub blend: BlendMode,
|
||||
#[serde(default = "yes", skip_serializing_if = "crate::skip::is_true")]
|
||||
pub visible: bool,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub effects: Vec<Effect>,
|
||||
/// Overprint Fill: on press the fill's inks print over the inks below instead of knocking
|
||||
/// them out (Overprint Preview and Separations Preview show it).
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub overprint: bool,
|
||||
}
|
||||
|
||||
impl FillLayer {
|
||||
pub fn new(paint: Paint) -> Self {
|
||||
Self { paint, opacity: 1.0, blend: BlendMode::Normal, visible: true, effects: vec![], overprint: false }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct StrokeLayer {
|
||||
pub paint: Paint,
|
||||
/// Weight in points.
|
||||
pub width: f64,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub cap: LineCap,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub join: LineJoin,
|
||||
#[serde(default = "ten", skip_serializing_if = "is_ten")]
|
||||
pub miter_limit: f64,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub align: StrokeAlign,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub dash: Option<Dash>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub start_arrow: Option<Arrowhead>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub end_arrow: Option<Arrowhead>,
|
||||
/// Arrowhead scale in percent (start, end).
|
||||
#[serde(default = "hundreds", skip_serializing_if = "is_hundreds")]
|
||||
pub arrow_scale: (f64, f64),
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub profile: Option<WidthProfile>,
|
||||
/// Brush applied to the stroke (by brush name).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub brush: Option<String>,
|
||||
#[serde(default = "one", skip_serializing_if = "crate::skip::is_one")]
|
||||
pub opacity: f32,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub blend: BlendMode,
|
||||
#[serde(default = "yes", skip_serializing_if = "crate::skip::is_true")]
|
||||
pub visible: bool,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub effects: Vec<Effect>,
|
||||
/// Arrowhead placement at both ends.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub arrow_align: ArrowAlign,
|
||||
/// Overprint Stroke (see [`FillLayer::overprint`]).
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub overprint: bool,
|
||||
/// How a gradient paint maps onto the stroke (within, along or across it).
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub gradient_mode: StrokeGradientMode,
|
||||
/// The pen pressure the stroke was drawn with (Paintbrush with a tablet): pressure-sensitive
|
||||
/// brushes vary with it. It belongs to this path's shape, so appearances copied to other
|
||||
/// art leave it behind ([`Appearance::without_pressure`]).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub pressure: Option<PressureProfile>,
|
||||
}
|
||||
|
||||
/// How a gradient on a stroke is laid out (the Gradient panel's Stroke buttons). Saved by variant
|
||||
/// name: new modes are appended, never renamed.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum StrokeGradientMode {
|
||||
/// Placed on the page like a fill's gradient and seen through the stroke.
|
||||
#[default]
|
||||
Within,
|
||||
/// From the start of each subpath to its end, following the path.
|
||||
Along,
|
||||
/// From the stroke's left edge to its right edge (left of the path's direction), all along it.
|
||||
Across,
|
||||
}
|
||||
|
||||
impl StrokeGradientMode {
|
||||
pub const ALL: [StrokeGradientMode; 3] = [StrokeGradientMode::Within, StrokeGradientMode::Along, StrokeGradientMode::Across];
|
||||
/// The name commands use (`within`, `along`, `across`).
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
StrokeGradientMode::Within => "within",
|
||||
StrokeGradientMode::Along => "along",
|
||||
StrokeGradientMode::Across => "across",
|
||||
}
|
||||
}
|
||||
/// Parse a mode name (any case).
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|m| m.name().eq_ignore_ascii_case(s))
|
||||
}
|
||||
}
|
||||
|
||||
/// How far any arrowhead reaches from its tip, in units of its weight (the open arrow's arms are
|
||||
/// cut square a little behind its 4 × 4 box).
|
||||
pub(crate) const HEAD_REACH: f64 = 4.6;
|
||||
|
||||
fn ten() -> f64 {
|
||||
10.0
|
||||
}
|
||||
|
||||
fn hundreds() -> (f64, f64) {
|
||||
(100.0, 100.0)
|
||||
}
|
||||
|
||||
fn is_ten(v: &f64) -> bool {
|
||||
*v == 10.0
|
||||
}
|
||||
|
||||
fn is_hundreds(v: &(f64, f64)) -> bool {
|
||||
*v == (100.0, 100.0)
|
||||
}
|
||||
|
||||
impl StrokeLayer {
|
||||
pub fn new(paint: Paint, width: f64) -> Self {
|
||||
Self {
|
||||
paint,
|
||||
width,
|
||||
cap: LineCap::Butt,
|
||||
join: LineJoin::Miter,
|
||||
miter_limit: 10.0,
|
||||
align: StrokeAlign::Center,
|
||||
dash: None,
|
||||
start_arrow: None,
|
||||
end_arrow: None,
|
||||
arrow_scale: (100.0, 100.0),
|
||||
profile: None,
|
||||
brush: None,
|
||||
opacity: 1.0,
|
||||
blend: BlendMode::Normal,
|
||||
visible: true,
|
||||
effects: vec![],
|
||||
arrow_align: ArrowAlign::Extend,
|
||||
overprint: false,
|
||||
gradient_mode: StrokeGradientMode::Within,
|
||||
pressure: None,
|
||||
}
|
||||
}
|
||||
/// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least
|
||||
/// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide.
|
||||
pub fn arrow_weight(&self, end: bool) -> f64 {
|
||||
let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 };
|
||||
(self.width * pct / 100.0).max(0.25)
|
||||
}
|
||||
/// How far the start (`end == false`) or end arrowhead can reach from its end point (0
|
||||
/// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap.
|
||||
pub fn head_reach(&self, end: bool) -> f64 {
|
||||
let head = if end { self.end_arrow } else { self.start_arrow };
|
||||
head.map_or(0.0, |_| HEAD_REACH * self.arrow_weight(end) + self.width / 2.0)
|
||||
}
|
||||
/// How far the arrowheads can reach from the path's end points (0 without heads).
|
||||
pub fn arrow_reach(&self) -> f64 {
|
||||
self.head_reach(false).max(self.head_reach(true))
|
||||
}
|
||||
/// The widest the width profile makes the stroke, as a factor of its weight (1 without one).
|
||||
pub fn profile_max(&self) -> f64 {
|
||||
self.profile.as_ref().and_then(|p| p.points.iter().map(|&(_, l, r)| l.max(r)).reduce(f64::max)).unwrap_or(1.0).max(0.0)
|
||||
}
|
||||
/// The stroke's body across a path that is `closed` or open: how far it reaches from the path
|
||||
/// at full width (half the weight centred; the whole weight on one side when aligned inside or
|
||||
/// outside a closed path, which open paths ignore), and for aligned strokes which side it
|
||||
/// paints (`Some(true)`: inside).
|
||||
pub fn body(&self, closed: bool) -> (f64, Option<bool>) {
|
||||
match self.align {
|
||||
StrokeAlign::Outside if closed => (self.width, Some(false)),
|
||||
StrokeAlign::Inside if closed => (self.width, Some(true)),
|
||||
_ => (self.width / 2.0, None),
|
||||
}
|
||||
}
|
||||
/// How far the body paints outside a path that is `closed` or open, at the profile's widest.
|
||||
pub fn side_reach(&self, closed: bool) -> f64 {
|
||||
match self.body(closed) {
|
||||
(_, Some(true)) => 0.0,
|
||||
(half, _) => half * self.profile_max(),
|
||||
}
|
||||
}
|
||||
/// The farthest this stroke can paint from any path: its body, miter spikes up to the miter
|
||||
/// limit, projecting caps' corners and the arrowheads ([`Appearance::outset`]).
|
||||
pub fn reach(&self) -> f64 {
|
||||
let side = self.side_reach(true).max(self.side_reach(false));
|
||||
let miter = if self.join == LineJoin::Miter { self.miter_limit.max(1.0) } else { 1.0 };
|
||||
let cap = if self.cap == LineCap::Square { std::f64::consts::SQRT_2 } else { 1.0 };
|
||||
(side * miter.max(cap)).max(self.arrow_reach())
|
||||
}
|
||||
/// The box an unplaced gradient on this stroke fits to (see [`stroke_paint_bounds`]).
|
||||
pub fn paint_bounds(&self, geometric: vectorcraft_geom::Rect) -> vectorcraft_geom::Rect {
|
||||
stroke_paint_bounds(geometric, self.width)
|
||||
}
|
||||
/// The gradient this stroke lays along or across its path: its linear or radial gradient
|
||||
/// paint when [`Self::gradient_mode`] isn't Within (freeform gradients always paint within).
|
||||
pub fn path_gradient(&self) -> Option<&vectorcraft_color::GradientPaint> {
|
||||
match &self.paint {
|
||||
Paint::Gradient(g)
|
||||
if self.gradient_mode != StrokeGradientMode::Within && g.gradient.kind != vectorcraft_color::GradientKind::Freeform =>
|
||||
{
|
||||
Some(g)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The box an unplaced gradient on a stroke of `width` fits to: the geometric bounds grown by half
|
||||
/// the weight (object strokes and type strokes alike, on screen and in exports).
|
||||
pub fn stroke_paint_bounds(geometric: vectorcraft_geom::Rect, width: f64) -> vectorcraft_geom::Rect {
|
||||
geometric.inflate(width / 2.0, width / 2.0)
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
use super::*;
|
||||
|
||||
/// Variable-width profile: (position 0..1 along the path, left width factor, right width factor),
|
||||
/// in order along the path. Two points at the same position make a discontinuous point: the
|
||||
/// first is the width just before it, the second the width just after it (a step).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct WidthProfile {
|
||||
pub points: Vec<(f64, f64, f64)>,
|
||||
}
|
||||
|
||||
/// A built-in width profile (the Stroke panel's Profile list).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ProfilePreset {
|
||||
/// Stable id used by `stroke.set {profile}`.
|
||||
pub id: &'static str,
|
||||
/// Menu label.
|
||||
pub label: &'static str,
|
||||
/// (t, left, right) width points.
|
||||
pub points: &'static [(f64, f64, f64)],
|
||||
}
|
||||
|
||||
impl WidthProfile {
|
||||
/// (left, right) width factors at `t`, linear between points.
|
||||
pub fn at(&self, t: f64) -> (f64, f64) {
|
||||
Self::at_points(&self.points, t)
|
||||
}
|
||||
/// [`Self::at`] of a profile's points (a preset's or a saved profile's).
|
||||
pub fn at_points(p: &[(f64, f64, f64)], t: f64) -> (f64, f64) {
|
||||
if p.is_empty() {
|
||||
return (1.0, 1.0);
|
||||
}
|
||||
if t <= p[0].0 {
|
||||
return (p[0].1, p[0].2);
|
||||
}
|
||||
for w in p.windows(2) {
|
||||
if t <= w[1].0 {
|
||||
let u = (t - w[0].0) / (w[1].0 - w[0].0).max(1e-9);
|
||||
return (w[0].1 + (w[1].1 - w[0].1) * u, w[0].2 + (w[1].2 - w[0].2) * u);
|
||||
}
|
||||
}
|
||||
p.last().map_or((1.0, 1.0), |l| (l.1, l.2))
|
||||
}
|
||||
/// The built-in profiles, in menu order. "uniform" is the plain stroke (no profile).
|
||||
pub const PRESETS: [ProfilePreset; 7] = [
|
||||
ProfilePreset { id: "uniform", label: "Uniform", points: &[(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)] },
|
||||
ProfilePreset { id: "lens", label: "Lens", points: &[(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)] },
|
||||
ProfilePreset { id: "taperStart", label: "Taper Start", points: &[(0.0, 0.0, 0.0), (1.0, 1.0, 1.0)] },
|
||||
ProfilePreset { id: "taperEnd", label: "Taper End", points: &[(0.0, 1.0, 1.0), (1.0, 0.0, 0.0)] },
|
||||
// Full width at both ends, pinched to a quarter in the middle.
|
||||
ProfilePreset { id: "pinch", label: "Pinch", points: &[(0.0, 1.0, 1.0), (0.5, 0.25, 0.25), (1.0, 1.0, 1.0)] },
|
||||
// A round head a fifth of the way along, then a long taper to the end.
|
||||
ProfilePreset { id: "teardrop", label: "Teardrop", points: &[(0.0, 0.0, 0.0), (0.2, 1.0, 1.0), (1.0, 0.0, 0.0)] },
|
||||
// Two swells between narrow necks.
|
||||
ProfilePreset { id: "wave", label: "Wave", points: &[(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)] },
|
||||
];
|
||||
/// The built-in profile with this id.
|
||||
pub fn preset(id: &str) -> Option<Self> {
|
||||
Self::PRESETS.iter().find(|p| p.id == id).map(|p| Self { points: p.points.to_vec() })
|
||||
}
|
||||
/// The id of the built-in profile these points match, if any.
|
||||
pub fn preset_id(&self) -> Option<&'static str> {
|
||||
Self::PRESETS.iter().find(|p| p.points == self.points.as_slice()).map(|p| p.id)
|
||||
}
|
||||
/// The id of a stroke's profile: "uniform" without one, "custom" when it matches no preset.
|
||||
pub fn id_of(p: Option<&Self>) -> &'static str {
|
||||
p.map_or(Some("uniform"), Self::preset_id).unwrap_or("custom")
|
||||
}
|
||||
/// The lens profile (thin ends, full width in the middle).
|
||||
pub fn lens() -> Self {
|
||||
Self::preset("lens").unwrap_or_default()
|
||||
}
|
||||
pub fn taper_end() -> Self {
|
||||
Self::preset("taperEnd").unwrap_or_default()
|
||||
}
|
||||
pub fn taper_start() -> Self {
|
||||
Self::preset("taperStart").unwrap_or_default()
|
||||
}
|
||||
/// The (left, right) factors just before and just after `t`: they differ only at a
|
||||
/// discontinuous point (two points at `t`, within `1e-7`).
|
||||
pub fn around(&self, t: f64) -> ((f64, f64), (f64, f64)) {
|
||||
let p = &self.points;
|
||||
if let Some(i) = p.iter().position(|q| (q.0 - t).abs() <= 1e-7) {
|
||||
let j = i + p[i..].iter().take_while(|q| (q.0 - p[i].0).abs() <= 1e-9).count() - 1;
|
||||
if j > i {
|
||||
return ((p[i].1, p[i].2), (p[j].1, p[j].2));
|
||||
}
|
||||
}
|
||||
let v = self.at(t);
|
||||
(v, v)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pen pressure recorded along a stroke (the Paintbrush with a graphics tablet): (position 0..1
|
||||
/// along the path, pressure 0..1) samples in order, positions measured as a [`WidthProfile`]'s
|
||||
/// are. Calligraphic brushes with Pressure variation read it; everything else ignores it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PressureProfile {
|
||||
pub points: Vec<(f64, f64)>,
|
||||
}
|
||||
|
||||
impl PressureProfile {
|
||||
/// The pressure of a stroke drawn without one (a mouse, or a path the brush was applied to):
|
||||
/// half way, so a Pressure brush draws its own value there.
|
||||
pub const MID: f64 = 0.5;
|
||||
/// The most samples a stroke keeps (after simplifying them).
|
||||
pub const MAX_POINTS: usize = 512;
|
||||
/// How far (in pressure) simplifying may move the recorded curve.
|
||||
const TOLERANCE: f64 = 0.01;
|
||||
|
||||
/// The pressure at `t` (0..1), linear between samples; [`Self::MID`] without any.
|
||||
pub fn at(&self, t: f64) -> f64 {
|
||||
let p = &self.points;
|
||||
let (Some(first), Some(last)) = (p.first(), p.last()) else { return Self::MID };
|
||||
// (Positions go forward; a profile read from a file is searched as if they do, in log time.)
|
||||
let v = if t <= first.0 {
|
||||
first.1
|
||||
} else {
|
||||
let i = p.partition_point(|q| q.0 < t);
|
||||
match (i.checked_sub(1).and_then(|j| p.get(j)), p.get(i)) {
|
||||
(Some(a), Some(b)) => a.1 + (b.1 - a.1) * ((t - a.0) / (b.0 - a.0).max(1e-9)).clamp(0.0, 1.0),
|
||||
_ => last.1,
|
||||
}
|
||||
};
|
||||
if v.is_finite() { v.clamp(0.0, 1.0) } else { Self::MID }
|
||||
}
|
||||
|
||||
/// A profile from (position, pressure) samples in order along the stroke: values are clamped
|
||||
/// into 0..1 (non-finite ones dropped), the curve is simplified to within 1 % and kept to
|
||||
/// [`Self::MAX_POINTS`]. `None` without a sample.
|
||||
pub fn from_samples(samples: impl IntoIterator<Item = (f64, f64)>) -> Option<Self> {
|
||||
let pts: Vec<(f64, f64)> =
|
||||
samples.into_iter().filter(|(t, p)| t.is_finite() && p.is_finite()).map(|(t, p)| (t.clamp(0.0, 1.0), p.clamp(0.0, 1.0))).collect();
|
||||
if pts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Simplifying is quadratic at worst: a huge stroke is thinned evenly first.
|
||||
let mut pts = thin(pts, 16 * Self::MAX_POINTS);
|
||||
// Positions only ever go forward.
|
||||
let mut prev = 0.0;
|
||||
for p in &mut pts {
|
||||
p.0 = p.0.max(prev);
|
||||
prev = p.0;
|
||||
}
|
||||
let keep = simplify_1d(&pts, Self::TOLERANCE);
|
||||
let pts = thin(pts.iter().zip(keep).filter(|(_, k)| *k).map(|(p, _)| *p).collect(), Self::MAX_POINTS);
|
||||
let round = |v: f64| (v * 1e4).round() / 1e4;
|
||||
Some(Self { points: pts.into_iter().map(|(t, p)| (round(t), round(p))).collect() })
|
||||
}
|
||||
|
||||
/// The pressure of a path `old_len` long (`old`; None: drawn without pressure) continued at its
|
||||
/// end by a stroke `added_len` long (`added`). None when neither has pressure.
|
||||
pub fn extended(old: Option<&Self>, old_len: f64, added: Option<&Self>, added_len: f64) -> Option<Self> {
|
||||
if old.is_none() && added.is_none() {
|
||||
return None;
|
||||
}
|
||||
let (old_len, added_len) = (old_len.max(0.0), added_len.max(0.0));
|
||||
let total = old_len + added_len;
|
||||
if !total.is_finite() || total <= 1e-9 {
|
||||
return old.or(added).cloned();
|
||||
}
|
||||
let flat = Self { points: vec![(0.0, Self::MID), (1.0, Self::MID)] };
|
||||
let (old, added) = (old.unwrap_or(&flat), added.unwrap_or(&flat));
|
||||
let o = old_len / total;
|
||||
let old_pts = old.points.iter().map(|&(t, p)| (t * o, p));
|
||||
Self::from_samples(old_pts.chain(added.points.iter().map(|&(u, p)| (o + u * (1.0 - o), p))))
|
||||
}
|
||||
|
||||
/// The pressure of the path reversed.
|
||||
pub fn reversed(&self) -> Self {
|
||||
Self { points: self.points.iter().rev().map(|&(t, p)| (1.0 - t, p)).collect() }
|
||||
}
|
||||
|
||||
/// A light–heavy–light stroke, for previews of pressure-sensitive brushes.
|
||||
pub fn sample() -> Self {
|
||||
Self { points: vec![(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)] }
|
||||
}
|
||||
}
|
||||
|
||||
/// At most `max` of `pts`, evenly spread (the ends kept).
|
||||
fn thin(pts: Vec<(f64, f64)>, max: usize) -> Vec<(f64, f64)> {
|
||||
let n = pts.len();
|
||||
if n <= max || max < 2 {
|
||||
return pts;
|
||||
}
|
||||
(0..max).filter_map(|i| pts.get(i * (n - 1) / (max - 1)).copied()).collect()
|
||||
}
|
||||
|
||||
/// Douglas–Peucker over a function sampled at `pts`: which samples to keep so the polyline through
|
||||
/// them stays within `tol` (vertically) of every sample. The ends are always kept.
|
||||
fn simplify_1d(pts: &[(f64, f64)], tol: f64) -> Vec<bool> {
|
||||
let mut keep = vec![false; pts.len()];
|
||||
let Some(last) = pts.len().checked_sub(1) else { return keep };
|
||||
for i in [0, last] {
|
||||
if let Some(k) = keep.get_mut(i) {
|
||||
*k = true;
|
||||
}
|
||||
}
|
||||
let mut stack = vec![(0, last)];
|
||||
while let Some((i, j)) = stack.pop() {
|
||||
let (Some(&a), Some(&b)) = (pts.get(i), pts.get(j)) else { continue };
|
||||
let line = |t: f64| if b.0 - a.0 > 1e-12 { a.1 + (b.1 - a.1) * (t - a.0) / (b.0 - a.0) } else { (a.1 + b.1) / 2.0 };
|
||||
let far = (i + 1..j).filter_map(|k| pts.get(k).map(|q| (k, (q.1 - line(q.0)).abs()))).max_by(|x, y| x.1.total_cmp(&y.1));
|
||||
if let Some((k, d)) = far
|
||||
&& d > tol
|
||||
{
|
||||
if let Some(f) = keep.get_mut(k) {
|
||||
*f = true;
|
||||
}
|
||||
stack.push((i, k));
|
||||
stack.push((k, j));
|
||||
}
|
||||
}
|
||||
keep
|
||||
}
|
||||
|
||||
/// A width profile saved to the Profile list under a name (Add to Profiles), kept with the
|
||||
/// preferences.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SavedProfile {
|
||||
pub name: String,
|
||||
pub profile: WidthProfile,
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum LineCap {
|
||||
#[default]
|
||||
Butt,
|
||||
Round,
|
||||
Square,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum LineJoin {
|
||||
#[default]
|
||||
Miter,
|
||||
Round,
|
||||
Bevel,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum StrokeAlign {
|
||||
#[default]
|
||||
Center,
|
||||
Inside,
|
||||
Outside,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Dash {
|
||||
/// Dash, gap, dash, gap… (up to 6 values in the Stroke panel).
|
||||
pub pattern: Vec<f64>,
|
||||
#[serde(default)]
|
||||
pub offset: f64,
|
||||
/// "Aligns dashes to corners and path ends, adjusting lengths to fit".
|
||||
#[serde(default)]
|
||||
pub align_corners: bool,
|
||||
}
|
||||
|
||||
impl Dash {
|
||||
/// Whether the pattern draws dashes. As in PDF (`d` operator) and SVG (`stroke-dasharray`), a
|
||||
/// pattern with a negative or non-finite value, or whose values are all zero, is invalid and the
|
||||
/// stroke is drawn solid.
|
||||
pub fn is_dashed(&self) -> bool {
|
||||
self.pattern.iter().all(|v| v.is_finite() && *v >= 0.0) && self.pattern.iter().any(|v| *v > 0.0)
|
||||
}
|
||||
/// Scale the dash and gap lengths and the offset by `s`.
|
||||
pub fn scale(&mut self, s: f64) {
|
||||
self.pattern.iter_mut().for_each(|v| *v *= s);
|
||||
self.offset *= s;
|
||||
}
|
||||
}
|
||||
|
||||
/// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum Arrowhead {
|
||||
Triangle,
|
||||
TriangleOpen,
|
||||
Circle,
|
||||
CircleOpen,
|
||||
Square,
|
||||
SquareOpen,
|
||||
Bar,
|
||||
Diamond,
|
||||
Arrow,
|
||||
ArrowOpen,
|
||||
Barbed,
|
||||
/// One barb, on the left of the direction the head points.
|
||||
HalfArrowLeft,
|
||||
/// One barb, on the right of the direction the head points.
|
||||
HalfArrowRight,
|
||||
Concave,
|
||||
DoubleBar,
|
||||
Feather,
|
||||
DotOnBar,
|
||||
Chevron,
|
||||
DoubleArrow,
|
||||
Target,
|
||||
Star,
|
||||
Cross,
|
||||
Plus,
|
||||
Hexagon,
|
||||
HexagonOpen,
|
||||
Tag,
|
||||
TagOpen,
|
||||
HalfCircle,
|
||||
Drop,
|
||||
Slash,
|
||||
DoubleSlash,
|
||||
DiamondOpen,
|
||||
TriangleReverse,
|
||||
Swallowtail,
|
||||
Bracket,
|
||||
Fork,
|
||||
Leaf,
|
||||
Kite,
|
||||
TriangleBar,
|
||||
Oval,
|
||||
}
|
||||
|
||||
impl Arrowhead {
|
||||
/// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks).
|
||||
pub const ALL: [Arrowhead; 40] = [
|
||||
Arrowhead::Arrow,
|
||||
Arrowhead::ArrowOpen,
|
||||
Arrowhead::Barbed,
|
||||
Arrowhead::Concave,
|
||||
Arrowhead::DoubleArrow,
|
||||
Arrowhead::HalfArrowLeft,
|
||||
Arrowhead::HalfArrowRight,
|
||||
Arrowhead::Chevron,
|
||||
Arrowhead::Feather,
|
||||
Arrowhead::Swallowtail,
|
||||
Arrowhead::Triangle,
|
||||
Arrowhead::TriangleOpen,
|
||||
Arrowhead::TriangleReverse,
|
||||
Arrowhead::TriangleBar,
|
||||
Arrowhead::Kite,
|
||||
Arrowhead::Leaf,
|
||||
Arrowhead::Drop,
|
||||
Arrowhead::Circle,
|
||||
Arrowhead::CircleOpen,
|
||||
Arrowhead::HalfCircle,
|
||||
Arrowhead::Oval,
|
||||
Arrowhead::Target,
|
||||
Arrowhead::Square,
|
||||
Arrowhead::SquareOpen,
|
||||
Arrowhead::Tag,
|
||||
Arrowhead::TagOpen,
|
||||
Arrowhead::Diamond,
|
||||
Arrowhead::DiamondOpen,
|
||||
Arrowhead::Hexagon,
|
||||
Arrowhead::HexagonOpen,
|
||||
Arrowhead::Star,
|
||||
Arrowhead::Cross,
|
||||
Arrowhead::Plus,
|
||||
Arrowhead::Bar,
|
||||
Arrowhead::DoubleBar,
|
||||
Arrowhead::DotOnBar,
|
||||
Arrowhead::Slash,
|
||||
Arrowhead::DoubleSlash,
|
||||
Arrowhead::Bracket,
|
||||
Arrowhead::Fork,
|
||||
];
|
||||
|
||||
/// The name the arrowhead menus show.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Arrowhead::Triangle => "Triangle",
|
||||
Arrowhead::TriangleOpen => "Triangle (open)",
|
||||
Arrowhead::Circle => "Circle",
|
||||
Arrowhead::CircleOpen => "Circle (open)",
|
||||
Arrowhead::Square => "Square",
|
||||
Arrowhead::SquareOpen => "Square (open)",
|
||||
Arrowhead::Bar => "Bar",
|
||||
Arrowhead::Diamond => "Diamond",
|
||||
Arrowhead::Arrow => "Arrow",
|
||||
Arrowhead::ArrowOpen => "Arrow (open)",
|
||||
Arrowhead::Barbed => "Barbed",
|
||||
Arrowhead::HalfArrowLeft => "Half Arrow (left)",
|
||||
Arrowhead::HalfArrowRight => "Half Arrow (right)",
|
||||
Arrowhead::Concave => "Concave",
|
||||
Arrowhead::DoubleBar => "Double Bar",
|
||||
Arrowhead::Feather => "Feather",
|
||||
Arrowhead::DotOnBar => "Dot on Bar",
|
||||
Arrowhead::Chevron => "Chevron",
|
||||
Arrowhead::DoubleArrow => "Double Arrow",
|
||||
Arrowhead::Target => "Target",
|
||||
Arrowhead::Star => "Star",
|
||||
Arrowhead::Cross => "Cross",
|
||||
Arrowhead::Plus => "Plus",
|
||||
Arrowhead::Hexagon => "Hexagon",
|
||||
Arrowhead::HexagonOpen => "Hexagon (open)",
|
||||
Arrowhead::Tag => "Tag",
|
||||
Arrowhead::TagOpen => "Tag (open)",
|
||||
Arrowhead::HalfCircle => "Half Circle",
|
||||
Arrowhead::Drop => "Drop",
|
||||
Arrowhead::Slash => "Slash",
|
||||
Arrowhead::DoubleSlash => "Double Slash",
|
||||
Arrowhead::DiamondOpen => "Diamond (open)",
|
||||
Arrowhead::TriangleReverse => "Reverse Triangle",
|
||||
Arrowhead::Swallowtail => "Swallowtail",
|
||||
Arrowhead::Bracket => "Bracket",
|
||||
Arrowhead::Fork => "Fork",
|
||||
Arrowhead::Leaf => "Leaf",
|
||||
Arrowhead::Kite => "Kite",
|
||||
Arrowhead::TriangleBar => "Triangle to Bar",
|
||||
Arrowhead::Oval => "Oval",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where an arrowhead sits relative to the end of its path. In both modes the stroke stops under
|
||||
/// the head, so the line never shows through a hollow head or past its tip.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum ArrowAlign {
|
||||
/// The tip extends past the end point (the path keeps its length).
|
||||
#[default]
|
||||
Extend,
|
||||
/// The tip sits on the end point (the stroke is shortened by the head).
|
||||
Tip,
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hidden_attributes_show_again() {
|
||||
let mut a = Appearance::default_art();
|
||||
assert!(!a.has_hidden() && !a.show_all());
|
||||
a.stroke_mut().unwrap().visible = false;
|
||||
a.items[0].effects_mut().push(Effect { id: "distort.roughen".into(), params: serde_json::Value::Null, visible: false });
|
||||
assert!(a.has_hidden());
|
||||
assert!(a.show_all());
|
||||
assert!(!a.has_hidden() && a.items.iter().all(AppearanceItem::visible) && a.items[0].effects()[0].visible);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic_appearance() {
|
||||
let a = Appearance::default_art();
|
||||
assert!(a.is_basic());
|
||||
assert_eq!(a.fill_paint(), Paint::solid(Color::WHITE));
|
||||
assert_eq!(a.stroke_width(), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rebase_moves_fills_by_the_box_and_strokes_by_their_inflated_box() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientPaint};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
let placed = |x: f64| {
|
||||
let mut g = GradientPaint::new(Gradient::default());
|
||||
g.geom = Some(GradientGeom { start: Point::new(x, 0.0), end: Point::new(x + 10.0, 0.0), aspect: 1.0, focal: None });
|
||||
Paint::Gradient(Box::new(g))
|
||||
};
|
||||
let mut a = Appearance::basic(placed(0.0), placed(-5.0), 10.0);
|
||||
a.rebase_gradients(Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(100.0, 0.0, 300.0, 100.0));
|
||||
let start = |p: Paint| match p {
|
||||
Paint::Gradient(g) => g.geom.unwrap().start,
|
||||
_ => panic!("a gradient"),
|
||||
};
|
||||
// The fill's start stays on the left edge; the stroke's on its inflated box's (−5 → 95).
|
||||
assert_eq!((start(a.fill_paint()), start(a.stroke_paint())), (Point::new(100.0, 0.0), Point::new(95.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn items_by_index() {
|
||||
let mut a = Appearance::default_art();
|
||||
a.items.push(AppearanceItem::Fill(FillLayer::new(Paint::None)));
|
||||
// [Fill white, Stroke black, Fill none]
|
||||
assert_eq!(a.fill_at(None).unwrap().paint, Paint::None);
|
||||
assert_eq!(a.fill_at(Some(0)).unwrap().paint, Paint::solid(Color::WHITE));
|
||||
assert!(a.fill_at(Some(1)).is_none() && a.stroke_at(Some(0)).is_none() && a.fill_at(Some(9)).is_none());
|
||||
assert_eq!(a.item_of_kind(Some(1), false), Some(1));
|
||||
assert_eq!(a.item_of_kind(Some(1), true), None);
|
||||
assert_eq!(a.fill_for(Some(1)).unwrap().paint, Paint::None);
|
||||
assert!(a.set_fill_at(Some(0), Paint::solid(Color::BLACK)));
|
||||
assert!(!a.set_stroke_at(Some(0), Paint::None));
|
||||
assert_eq!(a.fill_at(Some(0)).unwrap().paint, Paint::solid(Color::BLACK));
|
||||
a.effects_mut(Some(1)).unwrap().push(Effect { id: "distort.roughen".into(), params: serde_json::Value::Null, visible: true });
|
||||
assert_eq!(a.effects_at(Some(1)).unwrap().len(), 1);
|
||||
assert!(a.effects_at(None).unwrap().is_empty() && a.effects_mut(Some(3)).is_none());
|
||||
assert_eq!((a.items[1].kind_name(), a.items[2].kind_name()), ("stroke", "fill"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic_means_one_plain_fill_and_stroke() {
|
||||
let stroke = || AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 1.0));
|
||||
let mut a = Appearance { items: vec![stroke(), stroke()], ..Appearance::default() };
|
||||
assert!(!a.is_basic(), "two strokes");
|
||||
a.items.pop();
|
||||
assert!(a.is_basic() && Appearance::default().is_basic());
|
||||
let mut b = Appearance::default_art();
|
||||
b.stroke_mut().unwrap().visible = false;
|
||||
assert!(!b.is_basic(), "a hidden stroke");
|
||||
let mut c = Appearance::default_art();
|
||||
c.fill_mut().unwrap().opacity = 0.5;
|
||||
assert!(!c.is_basic(), "fill opacity");
|
||||
let mut d = Appearance::default_art();
|
||||
d.items.push(AppearanceItem::Fill(FillLayer::new(Paint::None)));
|
||||
assert!(!d.is_basic(), "two fills");
|
||||
let mut e = Appearance::default_art();
|
||||
e.effects.push(Effect { id: "distort.roughen".into(), params: serde_json::Value::Null, visible: true });
|
||||
assert!(!e.is_basic(), "an effect");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_creates_missing() {
|
||||
let mut a = Appearance::default();
|
||||
a.set_fill(Paint::solid(Color::BLACK));
|
||||
a.set_stroke(Paint::solid(Color::WHITE));
|
||||
assert_eq!(a.items.len(), 2);
|
||||
assert!(matches!(a.items[0], AppearanceItem::Fill(_)));
|
||||
}
|
||||
|
||||
/// #852: pen pressure is kept simplified along the stroke and read back by position.
|
||||
#[test]
|
||||
fn pressure_profile_samples_simplify_and_interpolate() {
|
||||
// A steady ramp keeps only its ends; a bump keeps its peak.
|
||||
let ramp = PressureProfile::from_samples((0..=100).map(|i| (i as f64 / 100.0, i as f64 / 100.0))).unwrap();
|
||||
assert_eq!(ramp.points, vec![(0.0, 0.0), (1.0, 1.0)]);
|
||||
assert!((ramp.at(0.25) - 0.25).abs() < 1e-9);
|
||||
let bump = PressureProfile::from_samples([(0.0, 0.2), (0.3, 0.2), (0.5, 0.9), (0.7, 0.2), (1.0, 0.2)]).unwrap();
|
||||
assert!(bump.points.contains(&(0.5, 0.9)) && (bump.at(0.4) - 0.55).abs() < 1e-9, "{bump:?}");
|
||||
// Junk is clamped or dropped; positions never go back; nothing at all is no profile.
|
||||
let junk = PressureProfile::from_samples([(f64::NAN, 0.5), (0.5, 7.0), (0.2, -1.0), (2.0, f64::INFINITY)]).unwrap();
|
||||
assert_eq!(junk.points, vec![(0.5, 1.0), (0.5, 0.0)]);
|
||||
assert!(PressureProfile::from_samples([(f64::NAN, 0.5)]).is_none());
|
||||
assert_eq!(PressureProfile::default().at(0.3), PressureProfile::MID);
|
||||
// A long noisy stroke stays bounded.
|
||||
let noisy = PressureProfile::from_samples((0..1_000_000).map(|i| (i as f64 / 1e6, (i % 2) as f64))).unwrap();
|
||||
assert!(noisy.points.len() <= PressureProfile::MAX_POINTS);
|
||||
// Out-of-order points (a hand-edited file) still read within 0..1.
|
||||
let odd = PressureProfile { points: vec![(1.0, 5.0), (0.0, -3.0)] };
|
||||
assert!((0.0..=1.0).contains(&odd.at(0.5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pressure_profile_extends_and_reverses() {
|
||||
let old = PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] };
|
||||
let added = PressureProfile { points: vec![(0.0, 1.0), (1.0, 0.0)] };
|
||||
// A 30 pt path continued by 10 pt: its ramp fills the first three quarters.
|
||||
let joined = PressureProfile::extended(Some(&old), 30.0, Some(&added), 10.0).unwrap();
|
||||
assert!((joined.at(0.75) - 1.0).abs() < 1e-9 && (joined.at(0.375) - 0.5).abs() < 1e-9 && joined.at(1.0) == 0.0, "{joined:?}");
|
||||
// A side without pressure is half way.
|
||||
let half = PressureProfile::extended(None, 10.0, Some(&added), 10.0).unwrap();
|
||||
assert_eq!(half.at(0.25), PressureProfile::MID);
|
||||
assert!(PressureProfile::extended(None, 10.0, None, 10.0).is_none());
|
||||
assert_eq!(PressureProfile::extended(Some(&old), 0.0, None, f64::NAN), Some(old.clone()));
|
||||
assert_eq!(old.reversed().points, vec![(0.0, 1.0), (1.0, 0.0)]);
|
||||
}
|
||||
|
||||
/// Strokes saved before pen pressure load as they were, and are written without it.
|
||||
#[test]
|
||||
fn strokes_without_pressure_round_trip_unchanged() {
|
||||
let json = serde_json::to_value(StrokeLayer::new(Paint::None, 2.0)).unwrap();
|
||||
assert!(json.get("pressure").is_none());
|
||||
let st: StrokeLayer = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(st.pressure, None);
|
||||
let pressed = StrokeLayer { pressure: Some(PressureProfile::sample()), ..st };
|
||||
let back: StrokeLayer = serde_json::from_value(serde_json::to_value(&pressed).unwrap()).unwrap();
|
||||
assert_eq!(back, pressed);
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0);
|
||||
ap.stroke_mut().unwrap().pressure = Some(PressureProfile::sample());
|
||||
assert_eq!(ap.without_pressure().stroke().unwrap().pressure, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_interp() {
|
||||
let p = WidthProfile::lens();
|
||||
assert_eq!(p.at(0.5), (1.0, 1.0));
|
||||
assert_eq!(p.at(0.25), (0.5, 0.5));
|
||||
assert_eq!(p.at(2.0), (0.0, 0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_presets_round_trip_their_ids() {
|
||||
for p in WidthProfile::PRESETS {
|
||||
let prof = WidthProfile::preset(p.id).unwrap();
|
||||
assert_eq!(prof.preset_id(), Some(p.id));
|
||||
assert_eq!(WidthProfile::id_of(Some(&prof)), p.id);
|
||||
}
|
||||
assert_eq!(WidthProfile::id_of(None), "uniform");
|
||||
assert_eq!(WidthProfile::id_of(Some(&WidthProfile { points: vec![(0.0, 0.3, 0.3)] })), "custom");
|
||||
assert!(WidthProfile::preset("nope").is_none());
|
||||
assert_eq!(WidthProfile::lens().points, vec![(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
|
||||
// Saved files store these names: they may only ever be appended to.
|
||||
const SAVED: [&str; 40] = [
|
||||
"Triangle",
|
||||
"TriangleOpen",
|
||||
"Circle",
|
||||
"CircleOpen",
|
||||
"Square",
|
||||
"SquareOpen",
|
||||
"Bar",
|
||||
"Diamond",
|
||||
"Arrow",
|
||||
"ArrowOpen",
|
||||
"Barbed",
|
||||
"HalfArrowLeft",
|
||||
"HalfArrowRight",
|
||||
"Concave",
|
||||
"DoubleBar",
|
||||
"Feather",
|
||||
"DotOnBar",
|
||||
"Chevron",
|
||||
"DoubleArrow",
|
||||
"Target",
|
||||
"Star",
|
||||
"Cross",
|
||||
"Plus",
|
||||
"Hexagon",
|
||||
"HexagonOpen",
|
||||
"Tag",
|
||||
"TagOpen",
|
||||
"HalfCircle",
|
||||
"Drop",
|
||||
"Slash",
|
||||
"DoubleSlash",
|
||||
"DiamondOpen",
|
||||
"TriangleReverse",
|
||||
"Swallowtail",
|
||||
"Bracket",
|
||||
"Fork",
|
||||
"Leaf",
|
||||
"Kite",
|
||||
"TriangleBar",
|
||||
"Oval",
|
||||
];
|
||||
for name in SAVED {
|
||||
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
|
||||
assert_eq!(serde_json::to_value(a).unwrap(), name);
|
||||
assert_eq!(Arrowhead::ALL.iter().filter(|x| **x == a).count(), 1, "{name} in the menu once");
|
||||
}
|
||||
let labels: std::collections::HashSet<&str> = Arrowhead::ALL.iter().map(|a| a.label()).collect();
|
||||
assert_eq!(labels.len(), Arrowhead::ALL.len(), "labels are distinct");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_align_defaults_to_extend_and_round_trips() {
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
|
||||
assert_eq!(st.arrow_align, ArrowAlign::Extend);
|
||||
// The default is not written, so older readers see the same JSON as before.
|
||||
assert!(!serde_json::to_string(&st).unwrap().contains("arrow_align"));
|
||||
let old: StrokeLayer = serde_json::from_str(r#"{"paint":{"type":"none"},"width":2.0}"#).unwrap();
|
||||
assert_eq!(old.arrow_align, ArrowAlign::Extend);
|
||||
st.arrow_align = ArrowAlign::Tip;
|
||||
let back: StrokeLayer = serde_json::from_str(&serde_json::to_string(&st).unwrap()).unwrap();
|
||||
assert_eq!(back, st);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outset_covers_arrowheads() {
|
||||
let mut a = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 4.0);
|
||||
a.stroke_mut().unwrap().join = LineJoin::Round;
|
||||
assert_eq!(a.outset(), 2.0);
|
||||
let st = a.stroke_mut().unwrap();
|
||||
st.end_arrow = Some(Arrowhead::Triangle);
|
||||
st.arrow_scale = (100.0, 200.0);
|
||||
assert_eq!(st.arrow_weight(false), 4.0);
|
||||
assert_eq!(st.arrow_weight(true), 8.0);
|
||||
assert_eq!((st.head_reach(false), st.head_reach(true)), (0.0, HEAD_REACH * 8.0 + 2.0));
|
||||
// A 32 pt head whose tip sits up to its length (plus the cap) past the end point.
|
||||
assert_eq!(a.outset(), HEAD_REACH * 8.0 + 2.0);
|
||||
a.stroke_mut().unwrap().width = 0.01;
|
||||
assert_eq!(a.stroke().unwrap().arrow_weight(true), 0.25, "heads keep a minimum size");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outset_depends_on_align() {
|
||||
let mut a = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 10.0);
|
||||
a.stroke_mut().unwrap().join = LineJoin::Round;
|
||||
assert_eq!(a.outset(), 5.0);
|
||||
a.stroke_mut().unwrap().align = StrokeAlign::Outside;
|
||||
assert_eq!(a.outset(), 10.0);
|
||||
// Open paths stroke inside-aligned strokes centred.
|
||||
a.stroke_mut().unwrap().align = StrokeAlign::Inside;
|
||||
assert_eq!(a.outset(), 5.0);
|
||||
assert_eq!((a.stroke().unwrap().side_reach(true), a.stroke().unwrap().body(true)), (0.0, (10.0, Some(true))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outset_covers_miter_spikes_projecting_caps_and_profile_maxima() {
|
||||
let mut a = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
|
||||
// Miter joins can spike out to the limit × half the weight.
|
||||
assert_eq!(a.outset(), 10.0);
|
||||
let st = a.stroke_mut().unwrap();
|
||||
st.join = LineJoin::Bevel;
|
||||
st.cap = LineCap::Square;
|
||||
assert!((a.outset() - std::f64::consts::SQRT_2).abs() < 1e-12, "a projecting cap's corner");
|
||||
let st = a.stroke_mut().unwrap();
|
||||
st.cap = LineCap::Round;
|
||||
st.profile = Some(WidthProfile { points: vec![(0.0, 0.5, 2.5), (1.0, 1.0, 1.0)] });
|
||||
assert_eq!(st.profile_max(), 2.5);
|
||||
assert_eq!(a.outset(), 2.5);
|
||||
a.stroke_mut().unwrap().paint = Paint::None;
|
||||
assert_eq!(a.outset(), 0.0, "an unpainted stroke");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contents_slot_follows_item_edits_and_round_trips() {
|
||||
let fill = || AppearanceItem::Fill(FillLayer::new(Paint::None));
|
||||
let mut a = Appearance { items: vec![fill(), fill(), fill()], ..Appearance::default() };
|
||||
assert_eq!((a.contents_at(), a.split_contents().1.len()), (0, 3), "all items above by default");
|
||||
a.set_contents_at(1);
|
||||
assert!(!a.is_basic());
|
||||
// [0 | 1 2]: removing below shifts the slot, removing above doesn't.
|
||||
a.remove_item(2);
|
||||
assert_eq!(a.contents_at(), 1);
|
||||
a.remove_item(0);
|
||||
assert_eq!((a.contents_at(), a.contents_index), (0, None));
|
||||
// Inserting next to the slot joins the item below it.
|
||||
a.items.push(fill());
|
||||
a.set_contents_at(1); // [0 | 1]
|
||||
a.insert_item(1, fill());
|
||||
assert_eq!(a.contents_at(), 2);
|
||||
a.insert_item(3, fill()); // [0 1 | 2 3]
|
||||
assert_eq!(a.contents_at(), 2);
|
||||
// Moves keep their side when landing next to the slot, cross it otherwise.
|
||||
assert_eq!(a.move_item(3, 2), Some(2));
|
||||
assert_eq!(a.contents_at(), 2, "stays above");
|
||||
a.move_item(3, 0);
|
||||
assert_eq!(a.contents_at(), 3, "crossed below");
|
||||
a.move_item(0, 3);
|
||||
assert_eq!(a.contents_at(), 2, "crossed above");
|
||||
assert_eq!(a.move_item(9, 0), None);
|
||||
// Saved only when set; older files load with every item above.
|
||||
let json = serde_json::to_string(&a).unwrap();
|
||||
assert!(json.contains("\"contents_index\":2"));
|
||||
assert_eq!(serde_json::from_str::<Appearance>(&json).unwrap(), a);
|
||||
let old: Appearance = serde_json::from_str(r#"{"items":[]}"#).unwrap();
|
||||
assert_eq!(old.contents_index, None);
|
||||
assert!(!serde_json::to_string(&Appearance::default_art()).unwrap().contains("contents_index"));
|
||||
}
|
||||
|
||||
/// The issue's case (#4174): two circles with different fills, the same stroke and the same
|
||||
/// effect share the stroke and the effect, not the fills; a shared stroke at another place in one
|
||||
/// stack maps to its own index there; nothing shared shares nothing; equal stacks share all.
|
||||
#[test]
|
||||
fn mixed_appearances_share_their_equal_rows() {
|
||||
let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 11.0));
|
||||
let fill = |c: Color| AppearanceItem::Fill(FillLayer::new(Paint::solid(c)));
|
||||
let feather = Effect { id: "stylize.feather".into(), params: serde_json::json!({"radius": 5}), visible: true };
|
||||
let a = Appearance { items: vec![fill(Color::rgb(1.0, 1.0, 0.0)), stroke.clone()], effects: vec![feather.clone()], ..Appearance::default() };
|
||||
let b = Appearance { items: vec![fill(Color::rgb(1.0, 0.0, 0.0)), stroke.clone()], effects: vec![feather.clone()], ..Appearance::default() };
|
||||
let shared = SharedStack::of(&[&a, &b]);
|
||||
assert_eq!(shared.items, vec![vec![1, 1]], "the stroke, not the fills");
|
||||
assert_eq!(shared.effects, vec![vec![0, 0]]);
|
||||
// The stroke under an extra fill in the second object.
|
||||
let c =
|
||||
Appearance { items: vec![fill(Color::BLACK), fill(Color::WHITE), stroke.clone()], effects: vec![feather.clone()], ..Appearance::default() };
|
||||
let shared = SharedStack::of(&[&a, &c]);
|
||||
assert_eq!(shared.items, vec![vec![1, 2]]);
|
||||
assert_eq!(shared.item_in(1, 1), Some(2));
|
||||
assert_eq!(shared.item_in(0, 1), None);
|
||||
// Nothing alike.
|
||||
let d = Appearance { items: vec![fill(Color::WHITE)], ..Appearance::default() };
|
||||
let none = SharedStack::of(&[&a, &d]);
|
||||
assert!(none.items.is_empty() && none.effects.is_empty());
|
||||
// Equal stacks share everything, each row where it is.
|
||||
assert_eq!(SharedStack::of(&[&a, &a.clone(), &a.clone()]).items, vec![vec![0, 0, 0], vec![1, 1, 1]]);
|
||||
}
|
||||
|
||||
/// Matches keep their stacking order: two equal rows in the opposite order match once.
|
||||
#[test]
|
||||
fn aligned_rows_never_cross() {
|
||||
assert_eq!(align(&[1, 2], &[2, 1], |a, b| a == b).iter().filter(|m| m.is_some()).count(), 1);
|
||||
assert_eq!(align(&[1, 2, 3], &[9, 1, 3], |a, b| a == b), vec![Some(1), None, Some(2)]);
|
||||
assert_eq!(align::<i32>(&[], &[1], |a, b| a == b), Vec::<Option<usize>>::new());
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Artboard {
|
||||
pub id: u32,
|
||||
pub name: String,
|
||||
/// Artboard rectangle in document points.
|
||||
pub rect: Rect,
|
||||
/// Locked (the Artboards panel's lock column): the Artboard tool and the artboard commands
|
||||
/// don't move, resize or delete it, Rearrange leaves it where it is, and the art on it can't be
|
||||
/// selected or edited ([`Document::on_locked_artboard`]), except new art while it stays
|
||||
/// selected ([`Document::new_art`]).
|
||||
#[serde(default, skip_serializing_if = "skip::is_default")]
|
||||
pub locked: bool,
|
||||
/// Show Center Mark (Artboard Options): the canvas draws a mark at the artboard's center.
|
||||
/// Exports and print leave it out. Always written, as before it could be set.
|
||||
#[serde(default)]
|
||||
pub show_center_mark: bool,
|
||||
/// Show Cross Hairs (Artboard Options): the canvas draws a line from the middle of each side
|
||||
/// through the center. Exports and print leave them out. Always written, as before it could
|
||||
/// be set.
|
||||
#[serde(default)]
|
||||
pub show_cross_hairs: bool,
|
||||
/// Show Video Safe Areas (Artboard Options): the canvas draws the artboard's action-safe and
|
||||
/// title-safe areas ([`Artboard::video_safe_areas`]). Exports and print leave them out. Written
|
||||
/// only when on, so a document that never shows them saves as before.
|
||||
#[serde(default, skip_serializing_if = "skip::is_default")]
|
||||
pub show_video_safe_areas: bool,
|
||||
/// Video Ruler Pixel Aspect Ratio (Artboard Options): the width of one video pixel over its
|
||||
/// height, which View › Rulers › Show Video Rulers counts the artboard in: a pixel is this many
|
||||
/// points wide and one point tall. 1 (square pixels) unless set, and written only when it isn't
|
||||
/// 1; always within [`VIDEO_PIXEL_ASPECT_RANGE`]: the commands refuse others, and a file's is
|
||||
/// brought into it as it opens.
|
||||
#[serde(default = "square_pixels", deserialize_with = "pixel_aspect_within_range", skip_serializing_if = "is_square_pixels")]
|
||||
pub video_ruler_pixel_aspect_ratio: f64,
|
||||
/// Background color (Properties › Artboards › Fill, Artboard Options). The canvas draws the
|
||||
/// artboard's paper in it, multiplied with the Simulate Colored Paper color while that is on;
|
||||
/// without one the paper is white, or the Simulate Colored Paper color. Exports and print leave
|
||||
/// it out.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub color: Option<vectorcraft_color::Color>,
|
||||
}
|
||||
|
||||
/// The Video Ruler Pixel Aspect Ratios an artboard takes (Artboard Options): from a pixel ten times
|
||||
/// as tall as it is wide to one ten times as wide as it is tall, which holds the anamorphic and
|
||||
/// standard-definition ratios video uses (0.9, 1.2, 1.33, 2) with room to spare.
|
||||
pub const VIDEO_PIXEL_ASPECT_RANGE: std::ops::RangeInclusive<f64> = 0.1..=10.0;
|
||||
|
||||
/// How far in from each edge of an artboard the video safe areas lie, as a share of its width
|
||||
/// (left and right) and of its height (top and bottom): the action-safe area 3.5% and the
|
||||
/// title-safe (graphics-safe) area 5%, as EBU R 95 sets them for 16:9 television
|
||||
/// (https://tech.ebu.ch/docs/r/r095.pdf, note 5).
|
||||
pub const VIDEO_SAFE_INSETS: [f64; 2] = [0.035, 0.05];
|
||||
|
||||
fn square_pixels() -> f64 {
|
||||
1.0
|
||||
}
|
||||
|
||||
fn is_square_pixels(v: &f64) -> bool {
|
||||
*v == 1.0
|
||||
}
|
||||
|
||||
/// A file's Video Ruler Pixel Aspect Ratio, brought into [`VIDEO_PIXEL_ASPECT_RANGE`]: one that
|
||||
/// isn't a number (NaN, infinite) reads as square pixels.
|
||||
fn pixel_aspect_within_range<'de, D: serde::Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
|
||||
let v = f64::deserialize(d)?;
|
||||
let (lo, hi) = (*VIDEO_PIXEL_ASPECT_RANGE.start(), *VIDEO_PIXEL_ASPECT_RANGE.end());
|
||||
Ok(if v.is_finite() { v.clamp(lo, hi) } else { 1.0 })
|
||||
}
|
||||
|
||||
impl Artboard {
|
||||
/// The action-safe and the title-safe area of the artboard, in that order, each inset from its
|
||||
/// edges by the share of [`VIDEO_SAFE_INSETS`] (Show Video Safe Areas).
|
||||
pub fn video_safe_areas(&self) -> [Rect; 2] {
|
||||
let r = self.rect;
|
||||
VIDEO_SAFE_INSETS.map(|k| r.inflate(-k * r.width(), -k * r.height()))
|
||||
}
|
||||
}
|
||||
|
||||
/// A document's locked artboards ([`Document::locked_artboards`]).
|
||||
pub struct LockedArtboards<'a> {
|
||||
pub(crate) rects: Vec<Rect>,
|
||||
pub(crate) symbols: SymbolBoxes<'a>,
|
||||
/// The new art, which isn't on them ([`Document::new_art`]).
|
||||
pub(crate) new_art: Arc<std::collections::HashSet<NodeId>>,
|
||||
/// The objects of pattern editing mode's layer ([`Document::pattern_edit`]), which are on no
|
||||
/// artboard.
|
||||
pub(crate) pattern_art: std::collections::HashSet<NodeId>,
|
||||
/// What [`LockedArtboards::overlaps`] found for each object it measured: the members of a
|
||||
/// group are each answered with one measurement of the group.
|
||||
pub(crate) held: std::cell::RefCell<std::collections::HashMap<NodeId, bool>>,
|
||||
}
|
||||
|
||||
impl LockedArtboards<'_> {
|
||||
/// No artboard is locked.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.rects.is_empty()
|
||||
}
|
||||
/// Is `n`, an object of a layer or sublayer, on a locked artboard: shown, not a guide, and its
|
||||
/// visual bounds (with its strokes, a symbol instance by its art) overlapping the artboard? An
|
||||
/// object counts for every artboard it overlaps, as Fit to Artwork Bounds counts it. A layer or
|
||||
/// sublayer is on none, nor is the art of pattern editing mode ([`Document::pattern_edit`]) or
|
||||
/// new art while it stays selected ([`Document::new_art`]).
|
||||
pub fn holds(&self, n: &Node) -> bool {
|
||||
!self.new_art.contains(&n.id) && self.overlaps(n)
|
||||
}
|
||||
/// [`LockedArtboards::holds`] for new art too: is `n` on a locked artboard, whether or not it
|
||||
/// is new art?
|
||||
pub fn overlaps(&self, n: &Node) -> bool {
|
||||
if self.rects.is_empty()
|
||||
|| !n.visible
|
||||
|| n.is_layer()
|
||||
|| matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
|| self.pattern_art.contains(&n.id)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Some(held) = self.held.borrow().get(&n.id) {
|
||||
return *held;
|
||||
}
|
||||
let held =
|
||||
n.visual_bounds_with(&self.symbols).is_some_and(|b| self.rects.iter().any(|r| b.x0 < r.x1 && b.x1 > r.x0 && b.y0 < r.y1 && b.y1 > r.y0));
|
||||
self.held.borrow_mut().insert(n.id, held);
|
||||
held
|
||||
}
|
||||
/// Is node `id` on a locked artboard: is the object of a layer or sublayer that holds it (`id`
|
||||
/// itself when it is one, a group counting as one object) on one ([`LockedArtboards::holds`])?
|
||||
pub fn holds_id(&self, id: NodeId) -> bool {
|
||||
!self.rects.is_empty() && self.symbols.document().layer_object(id).is_some_and(|n| self.holds(n))
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Document::retired_artboard_id`]: not document content, so two documents are equal whatever it
|
||||
/// holds. A clone shares the value with the document it was cloned from.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RetiredArtboardId(pub(crate) Arc<std::sync::atomic::AtomicU32>);
|
||||
|
||||
impl RetiredArtboardId {
|
||||
pub fn get(&self) -> u32 {
|
||||
self.0.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
/// Raise the value to `id` when `id` is higher.
|
||||
pub fn raise(&self, id: u32) {
|
||||
self.0.fetch_max(id, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for RetiredArtboardId {
|
||||
fn eq(&self, _: &Self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,786 @@
|
||||
use super::artboard::{Artboard, LockedArtboards};
|
||||
use super::graphic_style::default_graphic_styles;
|
||||
use super::guides::{GridPrefs, RulerMode};
|
||||
use super::limits::{DocError, FORMAT_VERSION, MAX_COORD, MAX_NEXT_ID};
|
||||
use super::units::{ColorMode, Unit};
|
||||
use super::*;
|
||||
|
||||
impl Document {
|
||||
/// Is everything but the layers the same in `other`, as the next version of the document after
|
||||
/// an edit of its art? The id counter and the id index are left out, and art outside the layers
|
||||
/// (symbols, patterns, graph designs) compares by identity, which an edit keeps for what it
|
||||
/// doesn't change: quick for every frame of an animation.
|
||||
pub fn same_outside_layers(&self, other: &Self) -> bool {
|
||||
let same_art = |a: &[Arc<Node>], b: &[Arc<Node>]| a.len() == b.len() && a.iter().zip(b).all(|(a, b)| Arc::ptr_eq(a, b));
|
||||
let same_pattern = |a: &PatternDef, b: &PatternDef| {
|
||||
same_art(&a.art, &b.art) && PatternDef { art: Vec::new(), ..a.clone() } == PatternDef { art: Vec::new(), ..b.clone() }
|
||||
};
|
||||
let Self {
|
||||
version,
|
||||
title,
|
||||
template,
|
||||
units,
|
||||
ruler_origin,
|
||||
rulers,
|
||||
artboard_ruler_origins,
|
||||
color_mode,
|
||||
artboards,
|
||||
layers: _,
|
||||
swatches,
|
||||
swatch_groups,
|
||||
graphic_styles,
|
||||
char_styles,
|
||||
para_styles,
|
||||
text_threads,
|
||||
symbols,
|
||||
graph_designs,
|
||||
guides,
|
||||
views,
|
||||
saved_selections,
|
||||
variables,
|
||||
grid,
|
||||
raster_effects_ppi,
|
||||
images,
|
||||
patterns,
|
||||
pattern_edit,
|
||||
mask_edit,
|
||||
next_id: _,
|
||||
unknown,
|
||||
page_isolate,
|
||||
page_knockout,
|
||||
spot_use_lab,
|
||||
setup,
|
||||
paste_remembers_layers,
|
||||
metadata,
|
||||
raster_effects,
|
||||
last_view,
|
||||
transparency_grid,
|
||||
layers_open,
|
||||
color_profiles,
|
||||
export_settings,
|
||||
extra,
|
||||
slices,
|
||||
slices_clip_to_artboard,
|
||||
print_setup,
|
||||
assets,
|
||||
svg_scripts,
|
||||
puppet,
|
||||
new_art,
|
||||
dimensions,
|
||||
retired_artboard_id: _,
|
||||
index: _,
|
||||
} = self;
|
||||
*version == other.version
|
||||
&& *title == other.title
|
||||
&& *template == other.template
|
||||
&& *units == other.units
|
||||
&& *ruler_origin == other.ruler_origin
|
||||
&& *rulers == other.rulers
|
||||
&& *artboard_ruler_origins == other.artboard_ruler_origins
|
||||
&& *color_mode == other.color_mode
|
||||
&& *artboards == other.artboards
|
||||
&& *swatches == other.swatches
|
||||
&& *swatch_groups == other.swatch_groups
|
||||
&& *graphic_styles == other.graphic_styles
|
||||
&& *char_styles == other.char_styles
|
||||
&& *para_styles == other.para_styles
|
||||
&& *text_threads == other.text_threads
|
||||
&& symbols.len() == other.symbols.len()
|
||||
&& symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
&& graph_designs.len() == other.graph_designs.len()
|
||||
&& graph_designs.iter().zip(&other.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
&& *guides == other.guides
|
||||
&& *views == other.views
|
||||
&& *saved_selections == other.saved_selections
|
||||
&& *variables == other.variables
|
||||
&& *grid == other.grid
|
||||
&& *raster_effects_ppi == other.raster_effects_ppi
|
||||
&& *images == other.images
|
||||
&& patterns.len() == other.patterns.len()
|
||||
&& patterns.iter().zip(&other.patterns).all(|(a, b)| same_pattern(a, b))
|
||||
&& match (pattern_edit, &other.pattern_edit) {
|
||||
(Some(a), Some(b)) => {
|
||||
a.pattern == b.pattern
|
||||
&& a.layer == b.layer
|
||||
&& match (&a.original, &b.original) {
|
||||
(Some(a), Some(b)) => same_pattern(a, b),
|
||||
(a, b) => a.is_none() && b.is_none(),
|
||||
}
|
||||
}
|
||||
(a, b) => a.is_none() && b.is_none(),
|
||||
}
|
||||
&& *mask_edit == other.mask_edit
|
||||
&& *unknown == other.unknown
|
||||
&& *page_isolate == other.page_isolate
|
||||
&& *page_knockout == other.page_knockout
|
||||
&& *spot_use_lab == other.spot_use_lab
|
||||
&& *setup == other.setup
|
||||
&& *paste_remembers_layers == other.paste_remembers_layers
|
||||
&& *metadata == other.metadata
|
||||
&& *raster_effects == other.raster_effects
|
||||
&& *last_view == other.last_view
|
||||
&& *transparency_grid == other.transparency_grid
|
||||
&& *layers_open == other.layers_open
|
||||
&& *color_profiles == other.color_profiles
|
||||
&& *export_settings == other.export_settings
|
||||
&& *extra == other.extra
|
||||
&& *slices == other.slices
|
||||
&& *slices_clip_to_artboard == other.slices_clip_to_artboard
|
||||
&& *print_setup == other.print_setup
|
||||
&& *assets == other.assets
|
||||
&& *svg_scripts == other.svg_scripts
|
||||
&& match (puppet, &other.puppet) {
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
|
||||
(a, b) => a.is_none() && b.is_none(),
|
||||
}
|
||||
&& *new_art == other.new_art
|
||||
&& *dimensions == other.dimensions
|
||||
}
|
||||
|
||||
/// Document Raster Effects Settings › Resolution in ppi, 1 to 2400 (72 when the stored value
|
||||
/// isn't a number).
|
||||
pub fn raster_ppi(&self) -> f64 {
|
||||
Some(self.raster_effects_ppi).filter(|v| v.is_finite()).unwrap_or(72.0).clamp(1.0, 2400.0)
|
||||
}
|
||||
|
||||
/// The ruler zero point, or zero on both axes when either stored coordinate is invalid.
|
||||
/// Rulers, coordinate fields and guide snapping use the same supported range.
|
||||
pub fn ruler_origin_or_zero(&self) -> Point {
|
||||
let origin = self.ruler_origin;
|
||||
if origin.is_finite() && origin.x.abs() <= MAX_COORD && origin.y.abs() <= MAX_COORD { origin } else { Point::ZERO }
|
||||
}
|
||||
|
||||
/// Where the rulers measure from with artboard `index` active: [`Self::ruler_origin_or_zero`]
|
||||
/// with global rulers; with artboard rulers that artboard's top-left corner moved by its own
|
||||
/// offset (the first artboard's when `index` is out of range, the global zero point when the
|
||||
/// document has no artboard or the result is out of the supported range).
|
||||
pub fn ruler_origin_for(&self, index: usize) -> Point {
|
||||
if self.rulers == RulerMode::Global {
|
||||
return self.ruler_origin_or_zero();
|
||||
}
|
||||
let Some(ab) = self.artboards.get(index).or_else(|| self.artboards.first()) else { return self.ruler_origin_or_zero() };
|
||||
let corner = Point::new(ab.rect.x0, ab.rect.y0);
|
||||
let offset = self.artboard_ruler_origins.get(&ab.id).copied().unwrap_or(Vec2::ZERO);
|
||||
let origin = corner + offset;
|
||||
if origin.is_finite() && origin.x.abs() <= MAX_COORD && origin.y.abs() <= MAX_COORD {
|
||||
origin
|
||||
} else if corner.is_finite() && corner.x.abs() <= MAX_COORD && corner.y.abs() <= MAX_COORD {
|
||||
corner
|
||||
} else {
|
||||
Point::ZERO
|
||||
}
|
||||
}
|
||||
|
||||
/// A new RGB document with one artboard of `size` and one layer ("Layer 1").
|
||||
pub fn new(width: f64, height: f64) -> Self {
|
||||
Self::new_with_mode(width, height, ColorMode::Rgb)
|
||||
}
|
||||
|
||||
/// [`Document::new`] in colour `mode`, with that mode's default swatches.
|
||||
pub fn new_with_mode(width: f64, height: f64, mode: ColorMode) -> Self {
|
||||
let (swatches, swatch_groups) = vectorcraft_color::default_swatches(mode.model());
|
||||
let mut d = Self {
|
||||
version: FORMAT_VERSION,
|
||||
title: "Untitled-1".into(),
|
||||
template: false,
|
||||
units: Unit::Points,
|
||||
ruler_origin: Point::ZERO,
|
||||
rulers: RulerMode::Artboard,
|
||||
artboard_ruler_origins: BTreeMap::new(),
|
||||
color_mode: mode,
|
||||
artboards: vec![Artboard {
|
||||
id: 1,
|
||||
name: "Artboard 1".into(),
|
||||
rect: Rect::new(0.0, 0.0, width, height),
|
||||
locked: false,
|
||||
show_center_mark: false,
|
||||
show_cross_hairs: false,
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
}],
|
||||
layers: vec![],
|
||||
swatches: swatches.into(),
|
||||
swatch_groups: swatch_groups.into(),
|
||||
graphic_styles: default_graphic_styles().into(),
|
||||
char_styles: Default::default(),
|
||||
para_styles: Default::default(),
|
||||
text_threads: vec![],
|
||||
symbols: vec![],
|
||||
graph_designs: vec![],
|
||||
guides: vec![],
|
||||
views: vec![],
|
||||
saved_selections: Default::default(),
|
||||
variables: Default::default(),
|
||||
grid: GridPrefs::default(),
|
||||
raster_effects_ppi: 72.0,
|
||||
images: BTreeMap::new(),
|
||||
patterns: vec![],
|
||||
pattern_edit: None,
|
||||
mask_edit: None,
|
||||
next_id: 1,
|
||||
unknown: Default::default(),
|
||||
page_isolate: false,
|
||||
page_knockout: false,
|
||||
spot_use_lab: true,
|
||||
setup: DocSetup::default(),
|
||||
paste_remembers_layers: false,
|
||||
metadata: DocMetadata::default(),
|
||||
raster_effects: RasterEffectsSettings::default(),
|
||||
last_view: None,
|
||||
transparency_grid: false,
|
||||
layers_open: None,
|
||||
color_profiles: ColorProfiles::default(),
|
||||
export_settings: Default::default(),
|
||||
extra: Default::default(),
|
||||
slices: vec![],
|
||||
slices_clip_to_artboard: true,
|
||||
print_setup: None,
|
||||
assets: vec![],
|
||||
svg_scripts: vec![],
|
||||
puppet: None,
|
||||
new_art: Default::default(),
|
||||
dimensions: false,
|
||||
retired_artboard_id: Default::default(),
|
||||
index: Default::default(),
|
||||
};
|
||||
let id = d.alloc_id();
|
||||
d.layers.push(Arc::new(Node::layer(id, "Layer 1", LayerColor::Preset(0))));
|
||||
d
|
||||
}
|
||||
|
||||
/// Allocate a fresh node id.
|
||||
pub fn alloc_id(&mut self) -> NodeId {
|
||||
let id = NodeId(self.next_id);
|
||||
// Never reached from a counter [`Self::fix_next_id`] has seen (it stays under
|
||||
// [`MAX_NEXT_ID`]); saturating so that no counter can overflow.
|
||||
self.next_id = self.next_id.saturating_add(1);
|
||||
id
|
||||
}
|
||||
|
||||
pub fn peek_next_id(&self) -> u64 {
|
||||
self.next_id
|
||||
}
|
||||
|
||||
/// Ensure `next_id` is above every id in the tree (after deserializing foreign data).
|
||||
pub fn fix_next_id(&mut self) {
|
||||
// Ids from [`MAX_NEXT_ID`] up (a damaged or hand-made file: #1718) are left out, as is a
|
||||
// counter up there: new ids start under them and never reach them, where counting on from
|
||||
// the largest would run out and hand out ids the document already uses.
|
||||
let mut max = 0;
|
||||
let mut see = |id: u64| {
|
||||
if id < MAX_NEXT_ID {
|
||||
max = max.max(id);
|
||||
}
|
||||
};
|
||||
for l in &self.layers {
|
||||
l.walk(&mut |n| see(n.id.0));
|
||||
}
|
||||
self.slices.iter().for_each(|s| see(s.id.0));
|
||||
self.assets.iter().for_each(|a| see(a.id));
|
||||
let counter = Some(self.next_id).filter(|n| *n <= MAX_NEXT_ID).unwrap_or(0);
|
||||
self.next_id = counter.max(max.saturating_add(1));
|
||||
}
|
||||
|
||||
/// Find a node anywhere in the tree.
|
||||
pub fn node(&self, id: NodeId) -> Option<&Node> {
|
||||
self.index_path(id).and_then(|p| self.node_at(&p))
|
||||
}
|
||||
|
||||
/// [`Document::node`] without building the lookup cache when there is none: for a look at a
|
||||
/// document kept in the undo history ([`Document::drop_lookup_cache`]).
|
||||
pub fn node_uncached(&self, id: NodeId) -> Option<&Node> {
|
||||
match self.index.is_built() {
|
||||
true => self.node(id),
|
||||
false => self.walk_index_path(id).and_then(|p| self.node_at(&p)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Let go of the lookup cache ([`id_index`]), as a document kept in the undo history does: a
|
||||
/// table per step would add up. Lookups still work; the first one builds the cache again.
|
||||
pub fn drop_lookup_cache(&self) {
|
||||
self.index.clear();
|
||||
}
|
||||
|
||||
/// Whether the lookup cache ([`id_index`]) is built (see [`Document::drop_lookup_cache`]).
|
||||
pub fn has_lookup_cache(&self) -> bool {
|
||||
self.index.is_built()
|
||||
}
|
||||
|
||||
/// Index path from the top-level layer list to `id` (e.g. `[0, 3, 1]`): the first place in
|
||||
/// tree order where `id` appears.
|
||||
pub fn index_path(&self, id: NodeId) -> Option<Vec<usize>> {
|
||||
// The cached path, while the node there still has the id ([`id_index`]).
|
||||
let cached = self.index.get();
|
||||
match cached.as_ref().and_then(|m| m.get(&id)) {
|
||||
Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == id) => return Some(p),
|
||||
Some(None) => return self.walk_index_path(id),
|
||||
_ => {}
|
||||
}
|
||||
// A stale path (the tree changed), an id the cache doesn't have (deleted or added since),
|
||||
// or no cache yet: walk, and rebuild now and then.
|
||||
let found = self.walk_index_path(id);
|
||||
let stale = cached.as_ref().is_some_and(|m| m.contains_key(&id));
|
||||
if cached.is_none() || ((stale || found.is_some()) && self.index.missed()) {
|
||||
self.index.rebuild(&self.layers);
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// [`Document::index_path`] by walking the tree.
|
||||
pub(crate) fn walk_index_path(&self, id: NodeId) -> Option<Vec<usize>> {
|
||||
fn find(nodes: &[Arc<Node>], id: NodeId, path: &mut Vec<usize>) -> bool {
|
||||
for (i, n) in nodes.iter().enumerate() {
|
||||
path.push(i);
|
||||
if n.id == id {
|
||||
return true;
|
||||
}
|
||||
if let Some(ch) = n.children()
|
||||
&& find(ch, id, path)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
false
|
||||
}
|
||||
let mut p = vec![];
|
||||
find(&self.layers, id, &mut p).then_some(p)
|
||||
}
|
||||
|
||||
/// [`Document::index_path`] of every id in `ids` that is in the tree, in one walk of it: an
|
||||
/// edit of many objects looks them all up for the cost of one search instead of one each. Like
|
||||
/// `index_path`, an id that appears twice maps to its first place in tree order.
|
||||
pub fn index_paths(&self, ids: impl IntoIterator<Item = NodeId>) -> std::collections::HashMap<NodeId, Vec<usize>> {
|
||||
use std::collections::{HashMap, HashSet};
|
||||
fn walk(nodes: &[Arc<Node>], want: &HashSet<NodeId>, path: &mut Vec<usize>, out: &mut HashMap<NodeId, Vec<usize>>) -> bool {
|
||||
for (i, n) in nodes.iter().enumerate() {
|
||||
path.push(i);
|
||||
if want.contains(&n.id) && !out.contains_key(&n.id) {
|
||||
out.insert(n.id, path.clone());
|
||||
if out.len() == want.len() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children()
|
||||
&& walk(ch, want, path, out)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
false
|
||||
}
|
||||
let mut want: HashSet<NodeId> = ids.into_iter().collect();
|
||||
let mut out = HashMap::with_capacity(want.len());
|
||||
// Cached paths that still check out ([`id_index`]); the rest take one walk. For a good
|
||||
// share of the document, one walk is quicker than checking each cached path.
|
||||
if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) {
|
||||
want.retain(|id| match cache.get(id) {
|
||||
Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => {
|
||||
out.insert(*id, p);
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
if !want.is_empty() {
|
||||
let mut rest = HashMap::with_capacity(want.len());
|
||||
walk(&self.layers, &want, &mut Vec::new(), &mut rest);
|
||||
out.extend(rest);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The node at index path `path` (as [`Document::index_path`] gives it).
|
||||
pub fn node_at(&self, path: &[usize]) -> Option<&Node> {
|
||||
let (first, rest) = path.split_first()?;
|
||||
let mut cur: &Node = self.layers.get(*first)?;
|
||||
for &i in rest {
|
||||
cur = cur.children()?.get(i)?;
|
||||
}
|
||||
Some(cur)
|
||||
}
|
||||
|
||||
/// Mutable access to the node at index path `path`; clones the Arc path (copy-on-write), as
|
||||
/// [`Document::node_mut`] does.
|
||||
pub fn node_mut_at(&mut self, path: &[usize]) -> Option<&mut Node> {
|
||||
let (first, rest) = path.split_first()?;
|
||||
let mut cur: &mut Arc<Node> = self.layers.get_mut(*first)?;
|
||||
for &i in rest {
|
||||
cur = Arc::make_mut(cur).children_mut()?.get_mut(i)?;
|
||||
}
|
||||
Some(Arc::make_mut(cur))
|
||||
}
|
||||
|
||||
/// [`Document::ancestry`] of the node at index path `path`.
|
||||
pub fn ancestry_at(&self, path: &[usize]) -> Option<Vec<NodeId>> {
|
||||
let mut out = Vec::with_capacity(path.len());
|
||||
let mut nodes = &self.layers;
|
||||
for &i in path {
|
||||
let n = nodes.get(i)?;
|
||||
out.push(n.id);
|
||||
if let Some(ch) = n.children() {
|
||||
nodes = ch;
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Ids from the top-level layer down to `id` inclusive.
|
||||
pub fn ancestry(&self, id: NodeId) -> Option<Vec<NodeId>> {
|
||||
let path = self.index_path(id)?;
|
||||
let mut out = Vec::with_capacity(path.len());
|
||||
let mut nodes = &self.layers;
|
||||
for &i in &path {
|
||||
let n = &nodes[i];
|
||||
out.push(n.id);
|
||||
if let Some(ch) = n.children() {
|
||||
nodes = ch;
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
pub fn parent_of(&self, id: NodeId) -> Option<NodeId> {
|
||||
let a = self.ancestry(id)?;
|
||||
(a.len() >= 2).then(|| a[a.len() - 2])
|
||||
}
|
||||
|
||||
/// The top-level layer that contains `id`.
|
||||
pub fn layer_of(&self, id: NodeId) -> Option<NodeId> {
|
||||
self.ancestry(id).and_then(|a| a.first().copied())
|
||||
}
|
||||
|
||||
/// Mutable access to a node; clones the Arc path (copy-on-write).
|
||||
pub fn node_mut(&mut self, id: NodeId) -> Option<&mut Node> {
|
||||
let path = self.index_path(id)?;
|
||||
let mut cur: &mut Arc<Node> = &mut self.layers[path[0]];
|
||||
for &i in &path[1..] {
|
||||
cur = &mut Arc::make_mut(cur).children_mut()?[i];
|
||||
}
|
||||
Some(Arc::make_mut(cur))
|
||||
}
|
||||
|
||||
/// Children list of a container (or the top-level layer list for `None`).
|
||||
pub fn children_mut(&mut self, parent: Option<NodeId>) -> Result<&mut Vec<Arc<Node>>, DocError> {
|
||||
match parent {
|
||||
None => Ok(&mut self.layers),
|
||||
Some(p) => self.node_mut(p).ok_or(DocError::NoNode(p))?.children_mut().ok_or(DocError::NotContainer(p)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn children(&self, parent: Option<NodeId>) -> Option<&Vec<Arc<Node>>> {
|
||||
match parent {
|
||||
None => Some(&self.layers),
|
||||
Some(p) => self.node(p)?.children(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top).
|
||||
pub fn insert(&mut self, parent: Option<NodeId>, index: usize, node: Node) -> Result<NodeId, DocError> {
|
||||
let id = node.id;
|
||||
let ch = self.children_mut(parent)?;
|
||||
let i = index.min(ch.len());
|
||||
ch.insert(i, Arc::new(node));
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Remove a node and return it.
|
||||
pub fn remove(&mut self, id: NodeId) -> Result<Arc<Node>, DocError> {
|
||||
let parent = self.parent_of(id);
|
||||
let path = self.index_path(id).ok_or(DocError::NoNode(id))?;
|
||||
let idx = *path.last().ok_or(DocError::NoNode(id))?;
|
||||
let ch = self.children_mut(parent)?;
|
||||
if idx >= ch.len() {
|
||||
return Err(DocError::NoNode(id));
|
||||
}
|
||||
Ok(ch.remove(idx))
|
||||
}
|
||||
|
||||
/// Move a node to `parent` at `index` (index measured after removal).
|
||||
pub fn move_node(&mut self, id: NodeId, parent: Option<NodeId>, index: usize) -> Result<(), DocError> {
|
||||
if let Some(p) = parent
|
||||
&& self.ancestry(p).is_some_and(|a| a.contains(&id))
|
||||
{
|
||||
return Err(DocError::Invalid("cannot move an object into itself".into()));
|
||||
}
|
||||
let n = self.remove(id)?;
|
||||
let ch = self.children_mut(parent)?;
|
||||
let i = index.min(ch.len());
|
||||
ch.insert(i, n);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Position of `id` within its parent: (parent, index, sibling count).
|
||||
pub fn position(&self, id: NodeId) -> Option<(Option<NodeId>, usize, usize)> {
|
||||
let parent = self.parent_of(id);
|
||||
let idx = *self.index_path(id)?.last()?;
|
||||
let n = self.children(parent)?.len();
|
||||
Some((parent, idx, n))
|
||||
}
|
||||
|
||||
/// Remove the nodes `ids` names and return them in the order of `ids`, in one pass over the
|
||||
/// children of each parent. Each id is listed once and none lies inside another listed node, as
|
||||
/// in a list of top-level objects. For an id that is not in the tree, is listed twice or lies
|
||||
/// inside another listed node, it fails with `NoNode` and leaves the document as it was.
|
||||
pub fn remove_many(&mut self, ids: &[NodeId]) -> Result<Vec<Arc<Node>>, DocError> {
|
||||
let places = self.places(ids)?;
|
||||
let removed = self.take(places, ids.len())?;
|
||||
self.index.clear();
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
/// Remove the nodes `ids` names, as [`Document::remove_many`] does, and put the node that `make`
|
||||
/// builds from them (in the order of `ids`) in the parent of the last of them, at that node's
|
||||
/// index less the number of listed nodes below it there. Returns the new node's id.
|
||||
pub fn wrap(&mut self, ids: &[NodeId], make: impl FnOnce(Vec<Arc<Node>>) -> Node) -> Result<NodeId, DocError> {
|
||||
let places = self.places(ids)?;
|
||||
let last = ids.len().checked_sub(1);
|
||||
let found = places.iter().find_map(|(up, kids)| kids.iter().find(|(_, k)| Some(*k) == last).map(|(i, _)| (up.clone(), *i)));
|
||||
let Some((up, i)) = found else { return Err(DocError::Invalid("nothing to wrap".into())) };
|
||||
// The parent and each node it is in move down by the listed nodes before them.
|
||||
let below = |parent: &[usize], index: usize| places.get(parent).map_or(0, |kids| kids.partition_point(|(j, _)| *j < index));
|
||||
let to: Vec<usize> = up.iter().enumerate().map(|(l, &j)| j.saturating_sub(below(&up[..l], j))).collect();
|
||||
let at = i.saturating_sub(below(&up, i));
|
||||
let node = make(self.take(places, ids.len())?);
|
||||
let id = node.id;
|
||||
let children = self.children_at(&to).ok_or_else(|| DocError::Invalid("the container of the listed objects is gone".into()))?;
|
||||
let at = at.min(children.len());
|
||||
children.insert(at, Arc::new(node));
|
||||
self.index.clear();
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Put each list of nodes in `items` directly above its anchor (`replace`: in its place), in
|
||||
/// list order, in one pass over the children of each parent. Each anchor is listed once and none
|
||||
/// lies inside another. For an anchor that is not in the tree, is listed twice or lies inside
|
||||
/// another listed anchor, it fails with `NoNode` and leaves the document as it was.
|
||||
pub fn insert_beside(&mut self, items: Vec<(NodeId, Vec<Node>)>, replace: bool) -> Result<(), DocError> {
|
||||
let anchors: Vec<NodeId> = items.iter().map(|(id, _)| *id).collect();
|
||||
let places = self.places(&anchors)?;
|
||||
let mut lists: Vec<Vec<Node>> = items.into_iter().map(|(_, nodes)| nodes).collect();
|
||||
self.edit_children(places, |k, anchor, children| {
|
||||
if !replace {
|
||||
children.push(anchor);
|
||||
}
|
||||
let nodes = lists.get_mut(k).map(std::mem::take).unwrap_or_default();
|
||||
children.extend(nodes.into_iter().map(Arc::new));
|
||||
})?;
|
||||
self.index.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Where each of `ids` is ([`Places`]). Fails with `NoNode` for an id that is not in the tree,
|
||||
/// is listed twice or lies inside another listed node.
|
||||
fn places(&self, ids: &[NodeId]) -> Result<Places, DocError> {
|
||||
let paths = self.index_paths(ids.iter().copied());
|
||||
let mut places = Places::new();
|
||||
for (k, id) in ids.iter().enumerate() {
|
||||
let (&i, up) = paths.get(id).and_then(|p| p.split_last()).ok_or(DocError::NoNode(*id))?;
|
||||
match places.get_mut(up) {
|
||||
Some(kids) => kids.push((i, k)),
|
||||
None => {
|
||||
places.insert(up.to_vec(), vec![(i, k)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
for kids in places.values_mut() {
|
||||
kids.sort_unstable();
|
||||
}
|
||||
// An id listed twice has one path, so its parent lists the same child twice. A listed node
|
||||
// lies inside another when its parent's path, or a part of it from the top, is the path of a
|
||||
// listed node.
|
||||
let twice = places.values().flat_map(|kids| kids.windows(2)).find(|w| w[0].0 == w[1].0).map(|w| w[1].1);
|
||||
let listed = |path: &[usize]| {
|
||||
path.split_last().is_some_and(|(i, up)| places.get(up).is_some_and(|kids| kids.binary_search_by_key(i, |(j, _)| *j).is_ok()))
|
||||
};
|
||||
let nested = places.iter().find(|(up, _)| (1..=up.len()).any(|l| listed(&up[..l])));
|
||||
let inner = nested.and_then(|(_, kids)| kids.first()).map(|(_, k)| *k);
|
||||
if let Some(id) = twice.or(inner).and_then(|k| ids.get(k)) {
|
||||
return Err(DocError::NoNode(*id));
|
||||
}
|
||||
Ok(places)
|
||||
}
|
||||
|
||||
/// Take the nodes `places` lists out of their parents and return them in the order of the list,
|
||||
/// which is `len` long.
|
||||
fn take(&mut self, places: Places, len: usize) -> Result<Vec<Arc<Node>>, DocError> {
|
||||
let mut taken = vec![None; len];
|
||||
self.edit_children(places, |k, node, _| {
|
||||
if let Some(t) = taken.get_mut(k) {
|
||||
*t = Some(node);
|
||||
}
|
||||
})?;
|
||||
Ok(taken.into_iter().flatten().collect())
|
||||
}
|
||||
|
||||
/// Rebuild the children of each parent in `places` once, the parents later in tree order
|
||||
/// first. `each` gets each listed child, its place in the list and the parent's new children,
|
||||
/// onto which it pushes what takes the child's place.
|
||||
fn edit_children(&mut self, places: Places, mut each: impl FnMut(usize, Arc<Node>, &mut Vec<Arc<Node>>)) -> Result<(), DocError> {
|
||||
for (up, kids) in places.into_iter().rev() {
|
||||
let children = self.children_at(&up).ok_or_else(|| DocError::Invalid("a container of the listed objects is gone".into()))?;
|
||||
let old = std::mem::take(children);
|
||||
children.reserve(old.len());
|
||||
let mut kids = kids.into_iter().peekable();
|
||||
for (i, node) in old.into_iter().enumerate() {
|
||||
match kids.next_if(|(j, _)| *j == i) {
|
||||
Some((_, k)) => each(k, node, children),
|
||||
None => children.push(node),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The children of the node at index path `path`, or the top-level layers for an empty path.
|
||||
fn children_at(&mut self, path: &[usize]) -> Option<&mut Vec<Arc<Node>>> {
|
||||
match path {
|
||||
[] => Some(&mut self.layers),
|
||||
_ => self.node_mut_at(path)?.children_mut(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Default target layer: the topmost visible, unlocked layer.
|
||||
pub fn default_layer(&self) -> Option<NodeId> {
|
||||
self.layers.iter().rev().find(|l| l.visible && !l.locked).or(self.layers.last()).map(|l| l.id)
|
||||
}
|
||||
|
||||
/// Add a new top-level layer above all others.
|
||||
pub fn add_layer(&mut self, name: Option<&str>) -> NodeId {
|
||||
let id = self.alloc_id();
|
||||
let n = self.layers.len();
|
||||
let name = name.map(str::to_string).unwrap_or_else(|| self.next_layer_name());
|
||||
self.layers.push(Arc::new(Node::layer(id, &name, LayerColor::Preset((n % LAYER_COLORS.len()) as u8))));
|
||||
id
|
||||
}
|
||||
|
||||
/// The default name of a new layer or sublayer, "Layer N". Layers and sublayers share the
|
||||
/// numbering: it starts after the number of layers there are and skips any layer's name.
|
||||
pub fn next_layer_name(&self) -> String {
|
||||
let (mut count, mut taken) = (0, std::collections::HashSet::new());
|
||||
self.walk(|n| {
|
||||
if n.is_layer() {
|
||||
count += 1;
|
||||
taken.extend(n.name.as_deref());
|
||||
}
|
||||
});
|
||||
(count + 1..).map(|i| format!("Layer {i}")).find(|name| !taken.contains(name.as_str())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Visit every node depth first in paint order (bottom to top).
|
||||
pub fn walk<'a>(&'a self, mut f: impl FnMut(&'a Node)) {
|
||||
for l in &self.layers {
|
||||
l.walk(&mut f);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn node_count(&self) -> usize {
|
||||
self.layers.iter().map(|l| l.count()).sum()
|
||||
}
|
||||
|
||||
/// Is the node (and every ancestor) visible and unlocked, and not on a locked artboard
|
||||
/// ([`Document::on_locked_artboard`])?
|
||||
pub fn is_editable(&self, id: NodeId) -> bool {
|
||||
self.is_editable_with(&self.locked_artboards(), id)
|
||||
}
|
||||
|
||||
/// [`Document::is_editable`] with the locked artboards `locks` of this document, measured
|
||||
/// once for many ids.
|
||||
pub fn is_editable_with(&self, locks: &LockedArtboards, id: NodeId) -> bool {
|
||||
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| n.visible && !n.locked))) && !locks.holds_id(id)
|
||||
}
|
||||
|
||||
/// [`Document::is_editable`] for many ids: the art on the locked artboards is measured once
|
||||
/// for all of them, a group once for all its members.
|
||||
pub fn editable(&self) -> impl Fn(NodeId) -> bool + '_ {
|
||||
let locks = self.locked_artboards();
|
||||
move |id| self.is_editable_with(&locks, id)
|
||||
}
|
||||
|
||||
/// The locked artboards, for asking which art is on them ([`LockedArtboards::holds`]).
|
||||
pub fn locked_artboards(&self) -> LockedArtboards<'_> {
|
||||
self.locked_artboards_except(usize::MAX)
|
||||
}
|
||||
|
||||
/// [`Document::locked_artboards`] leaving out artboard `index`.
|
||||
pub fn locked_artboards_except(&self, index: usize) -> LockedArtboards<'_> {
|
||||
// Art flush with an edge from outside can overlap it by a rounding error, as in
|
||||
// `art_bounds_on` (#1295).
|
||||
let rects: Vec<Rect> =
|
||||
self.artboards.iter().enumerate().filter(|(i, a)| a.locked && *i != index).map(|(_, a)| a.rect.inflate(-1e-6, -1e-6)).collect();
|
||||
// The objects of pattern editing mode's layer, a sublayer's objects included.
|
||||
fn objects(n: &Node, out: &mut std::collections::HashSet<NodeId>) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if c.is_layer() {
|
||||
objects(c, out);
|
||||
} else {
|
||||
out.insert(c.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut pattern_art = std::collections::HashSet::new();
|
||||
if let Some(layer) = self.pattern_edit.as_ref().filter(|_| !rects.is_empty()).and_then(|e| self.layers.iter().find(|l| l.id == e.layer)) {
|
||||
objects(layer, &mut pattern_art);
|
||||
}
|
||||
LockedArtboards { rects, symbols: self.symbol_boxes(), new_art: self.new_art.get(), pattern_art, held: Default::default() }
|
||||
}
|
||||
|
||||
/// Is `id` on a locked artboard ([`LockedArtboards::holds_id`])? A layer or sublayer is on none.
|
||||
pub fn on_locked_artboard(&self, id: NodeId) -> bool {
|
||||
self.locked_artboards().holds_id(id)
|
||||
}
|
||||
|
||||
/// The object of a layer or sublayer that holds node `id`: `id` itself when it is one, else
|
||||
/// the group or other object around it right inside a layer. None for a layer or sublayer.
|
||||
pub fn layer_object(&self, id: NodeId) -> Option<&Node> {
|
||||
self.layer_object_at(&self.index_path(id)?)
|
||||
}
|
||||
|
||||
/// [`Document::layer_object`] for the node at index path `path`.
|
||||
pub fn layer_object_at(&self, path: &[usize]) -> Option<&Node> {
|
||||
// Down the path to the first node that isn't a layer.
|
||||
let mut nodes = &self.layers;
|
||||
for &i in path {
|
||||
let n = nodes.get(i)?;
|
||||
if !n.is_layer() {
|
||||
return Some(n.as_ref());
|
||||
}
|
||||
nodes = n.children()?;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn is_visible(&self, id: NodeId) -> bool {
|
||||
self.ancestry(id).is_some_and(|a| a.iter().all(|i| self.node(*i).is_some_and(|n| n.visible)))
|
||||
}
|
||||
|
||||
/// The innermost layer or sublayer containing `id` (`id` itself when it is a layer).
|
||||
pub fn layer_containing(&self, id: NodeId) -> Option<NodeId> {
|
||||
let a = self.ancestry(id)?;
|
||||
a.iter().rev().copied().find(|i| self.node(*i).is_some_and(Node::is_layer))
|
||||
}
|
||||
|
||||
/// Every art object the Selection tool can reach (Select All): the visible, unlocked objects
|
||||
/// of the visible, unlocked, non-template layers, looking through sublayers (bottom first),
|
||||
/// except those on a locked artboard.
|
||||
pub fn selectable_art(&self) -> Vec<NodeId> {
|
||||
let locks = self.locked_artboards();
|
||||
self.layers
|
||||
.iter()
|
||||
.filter(|l| l.visible && !l.locked && !l.is_template())
|
||||
.flat_map(|l| l.layer_art(true))
|
||||
.filter(|id| locks.is_empty() || !self.node(*id).is_some_and(|n| locks.holds(n)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Colour of the innermost layer or sublayer containing `id` (selection highlight colour).
|
||||
pub fn layer_color(&self, id: NodeId) -> [u8; 3] {
|
||||
let l = self.layer_containing(id).and_then(|l| self.node(l));
|
||||
match l.map(|n| &n.kind) {
|
||||
Some(NodeKind::Layer { color, .. }) => color.rgb(),
|
||||
_ => LAYER_COLORS[0].1,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
use super::graphic_style::GraphicStyle;
|
||||
use super::limits::MAX_NEXT_ID;
|
||||
use super::records::{ImageBlob, SavedSelection, SavedView};
|
||||
use super::*;
|
||||
|
||||
impl Document {
|
||||
/// The pixels image `im` shows: its own ([`ImageObject::pixels`]) or this document's.
|
||||
pub fn image_blob<'a>(&'a self, im: &'a ImageObject) -> Option<&'a ImageBlob> {
|
||||
im.pixels.as_deref().or_else(|| self.images.get(&im.key))
|
||||
}
|
||||
|
||||
/// Take the pixels the images in `n` (its opacity masks' art included) hold themselves (art
|
||||
/// made outside a document) into [`Self::images`]: under the image's key, or a free one when
|
||||
/// the key shows other pixels.
|
||||
pub fn adopt_pixels(&mut self, n: &mut Node) {
|
||||
// Only what holds such pixels is copied out of the art it shares.
|
||||
fn holds(n: &Node) -> bool {
|
||||
matches!(&n.kind, NodeKind::Image(im) if im.pixels.is_some())
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| holds(&m.art))
|
||||
|| n.children().into_iter().flatten().any(|c| holds(c))
|
||||
}
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
self.adopt_image_pixels(im);
|
||||
}
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut())
|
||||
&& holds(&m.art)
|
||||
{
|
||||
self.adopt_pixels(Arc::make_mut(&mut m.art));
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
if holds(c) {
|
||||
self.adopt_pixels(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn adopt_image_pixels(&mut self, im: &mut ImageObject) {
|
||||
let Some(blob) = im.pixels.take() else { return };
|
||||
let mut key = im.key.clone();
|
||||
let mut i = 1;
|
||||
while self.images.get(&key).is_some_and(|b| b.bytes != blob.bytes) {
|
||||
i += 1;
|
||||
key = format!("{}-{i}", im.key);
|
||||
}
|
||||
self.images.entry(key.clone()).or_insert_with(|| (*blob).clone());
|
||||
im.key = key;
|
||||
}
|
||||
|
||||
/// Saved selections as a file gives them, made safe to list and recall: at most
|
||||
/// [`SavedSelection::MAX`], each with a clean, unique name and naming objects this document
|
||||
/// has, each once. (An id it doesn't have would select whatever object takes that id later.)
|
||||
pub fn tidy_saved_selections(&mut self) {
|
||||
if self.saved_selections.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
self.walk(|n| {
|
||||
ids.insert(n.id);
|
||||
});
|
||||
let mut kept: Vec<SavedSelection> = vec![];
|
||||
for s in std::mem::take(&mut self.saved_selections) {
|
||||
if kept.len() >= SavedSelection::MAX {
|
||||
break;
|
||||
}
|
||||
let Some(name) = SavedSelection::clean_name(&s.name) else { continue };
|
||||
if kept.iter().any(|k| k.name == name) {
|
||||
continue;
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let objects = s.objects.into_iter().filter(|id| ids.contains(id) && seen.insert(*id)).collect();
|
||||
kept.push(SavedSelection { name, objects });
|
||||
}
|
||||
self.saved_selections = kept.into();
|
||||
}
|
||||
|
||||
/// Saved views as a file gives them, made safe to list and go to: at most [`SavedView::MAX`],
|
||||
/// each with a clean, unique name, a finite centre and a finite, positive zoom (a rotation
|
||||
/// that isn't finite becomes 0°).
|
||||
pub fn tidy_views(&mut self) {
|
||||
if self.views.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut kept: Vec<SavedView> = vec![];
|
||||
for v in std::mem::take(&mut self.views) {
|
||||
if kept.len() >= SavedView::MAX {
|
||||
break;
|
||||
}
|
||||
let Some(name) = SavedView::clean_name(&v.name) else { continue };
|
||||
if !v.is_usable() || kept.iter().any(|k| k.name == name) {
|
||||
continue;
|
||||
}
|
||||
let rotation = if v.rotation.is_finite() { v.rotation } else { 0.0 };
|
||||
kept.push(SavedView { name, rotation, ..v });
|
||||
}
|
||||
self.views = kept;
|
||||
}
|
||||
|
||||
/// Leave opacity-mask editing: drop the temporary editing layer, a working copy of art the
|
||||
/// mask already holds (the engine syncs it after every edit).
|
||||
pub fn drop_edit_modes(&mut self) {
|
||||
if let Some(me) = self.mask_edit.take() {
|
||||
self.layers.retain(|l| l.id != me.layer);
|
||||
}
|
||||
}
|
||||
|
||||
/// The document as saved and exported: without the opacity-mask editing layer. Borrowed when
|
||||
/// no mask is being edited. (Pattern editing is saved: its tile layer holds unapplied edits.)
|
||||
pub fn without_edit_modes(&self) -> std::borrow::Cow<'_, Document> {
|
||||
if self.mask_edit.is_none() {
|
||||
return std::borrow::Cow::Borrowed(self);
|
||||
}
|
||||
let mut d = self.clone();
|
||||
d.drop_edit_modes();
|
||||
std::borrow::Cow::Owned(d)
|
||||
}
|
||||
|
||||
/// Round every path's anchors and handles to `decimals` decimal places: path objects (with
|
||||
/// Live Corners' uncut outlines), blend spines, envelopes' top-object outlines and Intertwine
|
||||
/// areas, in the layers, symbol definitions, graph designs, pattern swatches (the one being
|
||||
/// edited included), opacity masks and the brushes kept as foreign data. Colors, transforms,
|
||||
/// opacity, live shapes' own sizes, meshes and type (its frames and paths included) are left
|
||||
/// as they are.
|
||||
pub fn round_geometry(&mut self, decimals: u8) {
|
||||
let scale = 10f64.powi(i32::from(decimals));
|
||||
let round = |v: f64| {
|
||||
let r = (v * scale).round() / scale;
|
||||
if !r.is_finite() {
|
||||
v
|
||||
} else if r == 0.0 {
|
||||
// `-0.0` is written as `0.0`.
|
||||
0.0
|
||||
} else {
|
||||
r
|
||||
}
|
||||
};
|
||||
let round_path = |path: &mut vectorcraft_geom::PathData| {
|
||||
for a in path.subpaths.iter_mut().flat_map(|s| s.anchors.iter_mut()) {
|
||||
for p in [&mut a.p, &mut a.h_in, &mut a.h_out] {
|
||||
*p = Point::new(round(p.x), round(p.y));
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut fix = |n: &mut Node| {
|
||||
match &mut n.kind {
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
round_path(path);
|
||||
// Live Corners' uncut outline.
|
||||
if let Some(LiveShape::Path { base, .. }) = live.as_deref_mut() {
|
||||
round_path(base);
|
||||
}
|
||||
}
|
||||
NodeKind::Blend { spec, .. } => {
|
||||
if let Some(spine) = &mut spec.spine {
|
||||
round_path(spine);
|
||||
}
|
||||
}
|
||||
NodeKind::Envelope { kind, .. } => {
|
||||
if let EnvelopeKind::TopObject { path } = kind.as_mut() {
|
||||
round_path(path);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(area) = n.extras_if_any().and_then(|e| e.intertwine.as_deref_mut()) {
|
||||
round_path(area);
|
||||
}
|
||||
};
|
||||
let roots = self
|
||||
.layers
|
||||
.iter_mut()
|
||||
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
|
||||
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
|
||||
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
|
||||
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
|
||||
for root in roots {
|
||||
placed_document::each_mut(Arc::make_mut(root), &mut fix);
|
||||
}
|
||||
if self.unknown.contains_key("brushes")
|
||||
&& let Some(brushes) = self.unknown.get_mut("brushes")
|
||||
{
|
||||
round_json_paths(brushes, &round);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Round with `round` the anchors of the paths in `v`, nodes in their file form kept as JSON: every
|
||||
/// `{"subpaths": [{"anchors": [{"p", "in", "out"}]}]}` outside type (`{"type": "text"}`), as
|
||||
/// [`Document::round_geometry`] rounds the nodes it holds.
|
||||
fn round_json_paths(v: &mut serde_json::Value, round: &impl Fn(f64) -> f64) {
|
||||
use serde_json::Value;
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
if o.get("type").and_then(Value::as_str) == Some("text") {
|
||||
return;
|
||||
}
|
||||
if let Some(subpaths) = o.get_mut("subpaths").and_then(Value::as_array_mut) {
|
||||
let anchors = subpaths.iter_mut().filter_map(|s| s.get_mut("anchors").and_then(Value::as_array_mut)).flatten();
|
||||
for a in anchors.filter_map(Value::as_object_mut) {
|
||||
let points = a.iter_mut().filter(|(k, _)| matches!(k.as_str(), "p" | "in" | "out")).filter_map(|(_, v)| v.as_array_mut());
|
||||
for xy in points {
|
||||
for n in xy.iter_mut().filter(|n| n.is_f64()) {
|
||||
if let Some(r) = n.as_f64().and_then(|x| serde_json::Number::from_f64(round(x))) {
|
||||
*n = Value::Number(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for c in o.values_mut() {
|
||||
round_json_paths(c, round);
|
||||
}
|
||||
}
|
||||
Value::Array(a) => {
|
||||
for c in a {
|
||||
round_json_paths(c, round);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Graphic styles.
|
||||
impl Document {
|
||||
/// Index of the graphic style named `name`.
|
||||
pub fn graphic_style_index(&self, name: &str) -> Option<usize> {
|
||||
self.graphic_styles.iter().position(|g| g.name == name)
|
||||
}
|
||||
|
||||
/// The graphic style named `name`.
|
||||
pub fn graphic_style(&self, name: &str) -> Option<&GraphicStyle> {
|
||||
self.graphic_styles.iter().find(|g| g.name == name)
|
||||
}
|
||||
|
||||
/// The graphic style with id `id` (0 never matches).
|
||||
pub fn graphic_style_by_id(&self, id: u32) -> Option<&GraphicStyle> {
|
||||
self.graphic_styles.iter().find(|g| g.id != 0 && g.id == id)
|
||||
}
|
||||
|
||||
/// An id no graphic style has.
|
||||
pub fn next_graphic_style_id(&self) -> u32 {
|
||||
free_id(self.graphic_styles.iter().map(|g| g.id))
|
||||
}
|
||||
|
||||
/// The id of graphic style `index`, assigning one if it has none yet.
|
||||
pub fn graphic_style_id(&mut self, index: usize) -> u32 {
|
||||
if self.graphic_styles[index].id == 0 {
|
||||
self.graphic_styles[index].id = self.next_graphic_style_id();
|
||||
}
|
||||
self.graphic_styles[index].id
|
||||
}
|
||||
|
||||
/// The default name of a new graphic style: the first free "Graphic Style N", N counting on
|
||||
/// from the number of styles.
|
||||
pub fn new_graphic_style_name(&self) -> String {
|
||||
(self.graphic_styles.len() + 1..).map(|i| format!("Graphic Style {i}")).find(|n| self.graphic_style(n).is_none()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `base`, or the first free "`base` N" (N from 2) when a symbol already has that name.
|
||||
pub fn unique_symbol_name(&self, base: &str) -> String {
|
||||
let taken = |n: &str| self.symbols.iter().any(|s| s.name == n);
|
||||
if !taken(base) {
|
||||
return base.to_string();
|
||||
}
|
||||
(2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| base.to_string())
|
||||
}
|
||||
|
||||
/// Symbol Options › Registration for `name` (default: centre).
|
||||
pub fn symbol_registration(&self, name: &str) -> SymbolRegistration {
|
||||
self.unknown
|
||||
.get(SYMBOL_REGISTRATION)
|
||||
.and_then(|m| m.get(name))
|
||||
.and_then(|v| v.as_u64())
|
||||
.and_then(SymbolRegistration::from_u64)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Set or clear (when centre) the registration point stored for `name`.
|
||||
pub fn set_symbol_registration(&mut self, name: &str, reg: SymbolRegistration) {
|
||||
let m = self.unknown.entry(SYMBOL_REGISTRATION.to_string()).or_insert_with(|| serde_json::json!({}));
|
||||
let Some(o) = m.as_object_mut() else { return };
|
||||
if reg.is_center() {
|
||||
o.remove(name);
|
||||
if o.is_empty() {
|
||||
self.unknown.remove(SYMBOL_REGISTRATION);
|
||||
}
|
||||
} else {
|
||||
o.insert(name.into(), serde_json::json!(reg.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the stored registration when a symbol is renamed.
|
||||
pub fn rename_symbol_registration(&mut self, from: &str, to: &str) {
|
||||
if from == to {
|
||||
return;
|
||||
}
|
||||
let reg = self.symbol_registration(from);
|
||||
self.set_symbol_registration(from, SymbolRegistration::CENTER);
|
||||
self.set_symbol_registration(to, reg);
|
||||
}
|
||||
|
||||
/// Symbol Options › Export Type for `name` (default: Movie Clip).
|
||||
pub fn symbol_export_type(&self, name: &str) -> SymbolExportType {
|
||||
self.unknown.get(SYMBOL_EXPORT_TYPE).and_then(|m| m.get(name)).and_then(SymbolExportType::from_value).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Set or clear (when Movie Clip, the default) the export type stored for `name`.
|
||||
pub fn set_symbol_export_type(&mut self, name: &str, kind: SymbolExportType) {
|
||||
if kind.is_default() {
|
||||
self.clear_symbol_export_type(name);
|
||||
return;
|
||||
}
|
||||
let m = self.unknown.entry(SYMBOL_EXPORT_TYPE.to_string()).or_insert_with(|| serde_json::json!({}));
|
||||
let Some(o) = m.as_object_mut() else { return };
|
||||
o.insert(name.into(), serde_json::json!(kind.id()));
|
||||
}
|
||||
|
||||
/// Drop any stored export type for `name` (Movie Clip default).
|
||||
pub fn clear_symbol_export_type(&mut self, name: &str) {
|
||||
let Some(m) = self.unknown.get_mut(SYMBOL_EXPORT_TYPE) else { return };
|
||||
let Some(o) = m.as_object_mut() else { return };
|
||||
o.remove(name);
|
||||
if o.is_empty() {
|
||||
self.unknown.remove(SYMBOL_EXPORT_TYPE);
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the stored export type when a symbol is renamed.
|
||||
pub fn rename_symbol_export_type(&mut self, from: &str, to: &str) {
|
||||
if from == to {
|
||||
return;
|
||||
}
|
||||
let kind = self.symbol_export_type(from);
|
||||
self.clear_symbol_export_type(from);
|
||||
self.set_symbol_export_type(to, kind);
|
||||
}
|
||||
|
||||
/// Symbol Options › 9-slice guides for `name`: `None` when 9-slice scaling is off (default).
|
||||
pub fn symbol_nine_slice(&self, name: &str) -> Option<SymbolNineSlice> {
|
||||
self.unknown.get(SYMBOL_NINE_SLICE).and_then(|m| m.get(name)).and_then(SymbolNineSlice::from_value)
|
||||
}
|
||||
|
||||
/// Turn 9-slice scaling on with `guides`, or off with `None`, for `name`.
|
||||
pub fn set_symbol_nine_slice(&mut self, name: &str, guides: Option<SymbolNineSlice>) {
|
||||
let Some(g) = guides else {
|
||||
let Some(o) = self.unknown.get_mut(SYMBOL_NINE_SLICE).and_then(|m| m.as_object_mut()) else { return };
|
||||
o.remove(name);
|
||||
if o.is_empty() {
|
||||
self.unknown.remove(SYMBOL_NINE_SLICE);
|
||||
}
|
||||
return;
|
||||
};
|
||||
let m = self.unknown.entry(SYMBOL_NINE_SLICE.to_string()).or_insert_with(|| serde_json::json!({}));
|
||||
if let Some(o) = m.as_object_mut() {
|
||||
o.insert(name.into(), g.to_value());
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the stored 9-slice guides when a symbol is renamed.
|
||||
pub fn rename_symbol_nine_slice(&mut self, from: &str, to: &str) {
|
||||
if from == to {
|
||||
return;
|
||||
}
|
||||
let g = self.symbol_nine_slice(from);
|
||||
self.set_symbol_nine_slice(from, None);
|
||||
self.set_symbol_nine_slice(to, g);
|
||||
}
|
||||
}
|
||||
|
||||
/// An id (never 0) none of `used` has: one past the largest, or, when that is the largest there
|
||||
/// is (a damaged file), the smallest one free.
|
||||
pub(crate) fn free_id(used: impl Iterator<Item = u32>) -> u32 {
|
||||
let mut used: Vec<u32> = used.collect();
|
||||
if let Some(next) = used.iter().max().copied().unwrap_or(0).checked_add(1) {
|
||||
return next;
|
||||
}
|
||||
used.sort_unstable();
|
||||
used.dedup();
|
||||
// Ids 1, 2, 3… as far as they are all taken: the first that isn't follows them.
|
||||
let taken = used.iter().filter(|&&id| id != 0).zip(1u32..).take_while(|&(&id, n)| id == n).count();
|
||||
u32::try_from(taken).map_or(u32::MAX, |n| n.saturating_add(1))
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Make the next id allocated at least `next`: ids handed out outside the layer tree (such
|
||||
/// as an importer's opacity mask and pattern art), which [`Document::fix_next_id`] doesn't see.
|
||||
pub fn reserve_ids(&mut self, next: u64) {
|
||||
self.next_id = self.next_id.max(next.min(MAX_NEXT_ID));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
use super::document_ext::free_id;
|
||||
use super::guides::Guide;
|
||||
use super::*;
|
||||
|
||||
impl Document {
|
||||
/// Union of the geometric bounds of `ids` (their visual bounds when `visual`), with symbol
|
||||
/// instances measured by their art ([`Node::geometric_bounds_with`]).
|
||||
pub fn bounds_of(&self, ids: &[NodeId], visual: bool) -> Option<Rect> {
|
||||
let symbols = self.symbol_boxes();
|
||||
ids.iter().filter_map(|id| self.node(*id)).fold(None, |acc, n| {
|
||||
vectorcraft_geom::union_opt(acc, if visual { n.visual_bounds_with(&symbols) } else { n.geometric_bounds_with(&symbols) })
|
||||
})
|
||||
}
|
||||
|
||||
/// Visual bounds of all art, with symbol instances measured by their art.
|
||||
pub fn art_bounds(&self) -> Option<Rect> {
|
||||
let symbols = self.symbol_boxes();
|
||||
self.layers.iter().fold(None, |acc, l| vectorcraft_geom::union_opt(acc, l.visual_bounds_with(&symbols)))
|
||||
}
|
||||
|
||||
/// Artboard index containing point `p` (topmost = last), its edges included
|
||||
/// ([`Document::artboard_holding`]).
|
||||
pub fn artboard_at(&self, p: Point) -> Option<usize> {
|
||||
self.artboard_holding(p, true)
|
||||
}
|
||||
|
||||
/// Index of the artboard that holds point `p`: the first (the last when `topmost`) that holds it
|
||||
/// inside or on its left or top edge, else the first (the last) that holds it by
|
||||
/// [`artboard_holds`]: on its right or bottom edge, or within a millionth of a point outside an
|
||||
/// edge. On an edge two artboards share, the artboard to the right of it or below it holds the
|
||||
/// point, except at the end of the edge that lies on that artboard's bottom or right edge, such
|
||||
/// as the point where both artboards' bottom edges meet; there the first (the last) holds it.
|
||||
pub fn artboard_holding(&self, p: Point, topmost: bool) -> Option<usize> {
|
||||
let pick = |on: &dyn Fn(Rect) -> bool| {
|
||||
let on = |i: &usize| self.artboards.get(*i).is_some_and(|a| on(a.rect));
|
||||
let mut all = 0..self.artboards.len();
|
||||
if topmost { all.rfind(on) } else { all.find(on) }
|
||||
};
|
||||
pick(&|r| r.contains(p)).or_else(|| pick(&|r| artboard_holds(r, p)))
|
||||
}
|
||||
|
||||
/// The art that moves with an artboard at `rect`: top-level objects (children of layers and
|
||||
/// sublayers) lying entirely inside it, with symbol instances measured by their art. Locked and
|
||||
/// hidden objects and layers stay put unless `locked_and_hidden` (Selection & Anchor Display ›
|
||||
/// Move Locked and Hidden Artwork with Artboard).
|
||||
pub fn art_on_artboard(&self, rect: Rect, locked_and_hidden: bool) -> Vec<NodeId> {
|
||||
// Art drawn flush with the artboard can end up a rounding error outside it (a background
|
||||
// 3e-14 pt past the top edge, #1295): a millionth of a point is far below anything visible.
|
||||
let rect = rect.inflate(1e-6, 1e-6);
|
||||
fn collect(n: &Node, s: &SymbolBoxes, rect: Rect, all: bool, out: &mut Vec<NodeId>) {
|
||||
for c in n.children().into_iter().flatten().filter(|c| c.rides_with_artboard(all)) {
|
||||
if c.is_layer() {
|
||||
collect(c, s, rect, all, out);
|
||||
} else if let Some(b) = c.geometric_bounds_with(s)
|
||||
// Inside it, edges included: art flush with the right or bottom edge is on it too
|
||||
// (`Rect::contains` leaves those out, #890).
|
||||
&& b.x0 >= rect.x0
|
||||
&& b.y0 >= rect.y0
|
||||
&& b.x1 <= rect.x1
|
||||
&& b.y1 <= rect.y1
|
||||
{
|
||||
out.push(c.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let symbols = self.symbol_boxes();
|
||||
let mut art = vec![];
|
||||
for l in self.layers.iter().filter(|l| l.rides_with_artboard(locked_and_hidden)) {
|
||||
collect(l, &symbols, rect, locked_and_hidden, &mut art);
|
||||
}
|
||||
art
|
||||
}
|
||||
|
||||
/// Does any artwork lie on `rect` (an artboard)? Artwork is any object under the layers,
|
||||
/// hidden and locked ones and those on template layers included, whose visual bounds (symbol
|
||||
/// instances measured by their art) meet `rect`; touching its edge counts. A group (not a clip
|
||||
/// group) counts by its members, so one whose members sit on two other artboards leaves the one
|
||||
/// between them empty. A clip group or clipping layer counts by its members inside its clip (and
|
||||
/// by its clipping path where that paints). Guides (paths made into guides too) aren't artwork
|
||||
/// (Delete Empty Artboards).
|
||||
pub fn artboard_has_art(&self, rect: Rect) -> bool {
|
||||
// As in `art_on_artboard`: a millionth of a point covers rounding at the edges.
|
||||
let rect = rect.inflate(1e-6, 1e-6);
|
||||
fn meets(b: Option<Rect>, r: Rect) -> bool {
|
||||
b.is_some_and(|b| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1)
|
||||
}
|
||||
fn has(c: &Node, s: &SymbolBoxes, rect: Rect) -> bool {
|
||||
match &c.kind {
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
|
||||
let Some((clip, rest)) = children.split_first() else { return false };
|
||||
let paint = clip.clip_paint();
|
||||
if (paint.fill.is_some() || paint.stroke.is_some()) && meets(clip.visual_bounds_with(s), rect) {
|
||||
return true;
|
||||
}
|
||||
// The members show only inside the clip's box.
|
||||
let Some(b) = c.visual_bounds_with(s).filter(|b| meets(Some(*b), rect)) else { return false };
|
||||
let inside = Rect::new(b.x0.max(rect.x0), b.y0.max(rect.y0), b.x1.min(rect.x1), b.y1.min(rect.y1));
|
||||
rest.iter().any(|m| has(m, s, inside))
|
||||
}
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().any(|m| has(m, s, rect)),
|
||||
NodeKind::Path { guide: true, .. } => false,
|
||||
_ => meets(c.visual_bounds_with(s), rect),
|
||||
}
|
||||
}
|
||||
let symbols = self.symbol_boxes();
|
||||
self.layers.iter().any(|l| has(l, &symbols, rect))
|
||||
}
|
||||
|
||||
/// The art that moves, scales or is cut with artboard `index`: [`Document::art_on_artboard`]
|
||||
/// without the objects on another locked artboard, which stay unless `locked_and_hidden`, as
|
||||
/// locked art does.
|
||||
pub fn art_moving_with(&self, index: usize, locked_and_hidden: bool) -> Vec<NodeId> {
|
||||
let Some(rect) = self.artboards.get(index).map(|a| a.rect) else { return vec![] };
|
||||
let mut art = self.art_on_artboard(rect, locked_and_hidden);
|
||||
let locks = self.locked_artboards_except(index);
|
||||
if !locked_and_hidden && !locks.is_empty() {
|
||||
art.retain(|id| !self.node(*id).is_some_and(|n| locks.holds(n)));
|
||||
}
|
||||
art
|
||||
}
|
||||
|
||||
/// Where ruler guide `g` runs along its line (the y range of a vertical guide): across its
|
||||
/// artboard for an artboard guide, None (the whole canvas) for a canvas guide or one whose
|
||||
/// artboard is gone.
|
||||
pub fn guide_span(&self, g: &Guide) -> Option<(f64, f64)> {
|
||||
let r = self.artboards.iter().find(|a| Some(a.id) == g.artboard)?.rect;
|
||||
Some(if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) })
|
||||
}
|
||||
|
||||
/// The layer (or sublayer) ruler guide `g` is on, if it is on one this document has.
|
||||
fn guide_layer(&self, g: &Guide) -> Option<NodeId> {
|
||||
g.layer.filter(|l| self.node(*l).is_some_and(Node::is_layer))
|
||||
}
|
||||
|
||||
/// Is ruler guide `g` shown: on no layer, or on a layer that (with the layers around it) is
|
||||
/// visible? A guide whose layer is gone shows as one on no layer.
|
||||
pub fn guide_shown(&self, g: &Guide) -> bool {
|
||||
self.guide_layer(g).is_none_or(|l| self.is_visible(l))
|
||||
}
|
||||
|
||||
/// Can ruler guide `g` be picked, moved and deleted: shown, and its layer unlocked?
|
||||
pub fn guide_editable(&self, g: &Guide) -> bool {
|
||||
self.guide_layer(g).is_none_or(|l| self.is_editable(l))
|
||||
}
|
||||
|
||||
/// Put the ruler guides on no layer this document has (from files saved before guides had
|
||||
/// layers, or of layers merged into `layer`) on layer `layer`. Returns how many.
|
||||
pub fn rehome_guides(&mut self, layer: NodeId) -> usize {
|
||||
let lost: Vec<bool> = self.guides.iter().map(|g| self.guide_layer(g).is_none()).collect();
|
||||
let mut n = 0;
|
||||
for (g, lost) in self.guides.iter_mut().zip(lost) {
|
||||
if lost {
|
||||
g.layer = Some(layer);
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Put the ruler guides on no layer (from files saved before guides had layers), or on one that
|
||||
/// is gone, on the top visible, unlocked layer ([`Self::default_layer`]). Returns how many.
|
||||
pub fn adopt_guides(&mut self) -> usize {
|
||||
self.default_layer().map_or(0, |home| self.rehome_guides(home))
|
||||
}
|
||||
|
||||
/// Delete the ruler guides whose layer was deleted (they go with it), keeping `sel`'s guides in
|
||||
/// step. Guides on no layer stay. Returns how many went.
|
||||
pub fn drop_guides_of_deleted_layers(&mut self, sel: &mut Selection) -> usize {
|
||||
let gone: Vec<bool> = self.guides.iter().map(|g| g.layer.is_some() && self.guide_layer(g).is_none()).collect();
|
||||
self.retain_guides(sel, |i, _| !gone.get(i).copied().unwrap_or(false))
|
||||
}
|
||||
|
||||
/// Copy the ruler guides of layer `from` and of its sublayers onto their copies in `copy` (made
|
||||
/// from `from` by [`Self::reid`]: the same tree with fresh ids), as duplicating a layer copies
|
||||
/// the objects on it. Returns how many.
|
||||
pub fn copy_layer_guides(&mut self, from: &Node, copy: &Node) -> usize {
|
||||
let layers = |n: &Node| {
|
||||
let mut out = vec![];
|
||||
n.walk(&mut |c| {
|
||||
if c.is_layer() {
|
||||
out.push(c.id);
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let pairs: Vec<(NodeId, NodeId)> = layers(from).into_iter().zip(layers(copy)).collect();
|
||||
let copies: Vec<Guide> = self
|
||||
.guides
|
||||
.iter()
|
||||
.filter_map(|g| {
|
||||
let to = pairs.iter().find(|(a, _)| Some(*a) == g.layer)?.1;
|
||||
Some(Guide { layer: Some(to), ..g.clone() })
|
||||
})
|
||||
.collect();
|
||||
let n = copies.len();
|
||||
self.guides.extend(copies);
|
||||
n
|
||||
}
|
||||
|
||||
/// The ruler guides on layer `layer` (not its sublayers'), by index.
|
||||
pub fn guides_on(&self, layer: NodeId) -> impl Iterator<Item = (usize, &Guide)> + '_ {
|
||||
self.guides.iter().enumerate().filter(move |(_, g)| g.layer == Some(layer))
|
||||
}
|
||||
|
||||
/// Does ruler guide `g` run past `p` (up to `tol` beyond its ends)?
|
||||
pub fn guide_passes(&self, g: &Guide, p: Point, tol: f64) -> bool {
|
||||
let along = if g.vertical { p.y } else { p.x };
|
||||
self.guide_span(g).is_none_or(|(a, b)| along >= a - tol && along <= b + tol)
|
||||
}
|
||||
|
||||
/// Keep the ruler guides `keep` accepts (by index), the selected ones left keeping their
|
||||
/// place among the rest (the selected art stays selected). Returns how many went.
|
||||
pub fn retain_guides(&mut self, sel: &mut Selection, keep: impl Fn(usize, &Guide) -> bool) -> usize {
|
||||
let kept: Vec<bool> = self.guides.iter().enumerate().map(|(i, g)| keep(i, g)).collect();
|
||||
// Where each kept guide ends up.
|
||||
let (mut to, mut n) = (Vec::with_capacity(kept.len()), 0);
|
||||
for k in &kept {
|
||||
to.push(k.then_some(n));
|
||||
n += usize::from(*k);
|
||||
}
|
||||
sel.guides = sel.guides.iter().filter_map(|i| to.get(*i).copied().flatten()).collect();
|
||||
sel.key_guide = sel.key_guide.and_then(|i| to.get(i).copied().flatten());
|
||||
let before = self.guides.len();
|
||||
let mut flags = kept.into_iter();
|
||||
self.guides.retain(|_| flags.next().unwrap_or(true));
|
||||
before - self.guides.len()
|
||||
}
|
||||
|
||||
/// Move the guides of artboard `id` by `d` (along with their artboard).
|
||||
pub fn move_artboard_guides(&mut self, id: u32, d: Vec2) {
|
||||
for g in self.guides.iter_mut().filter(|g| g.artboard == Some(id)) {
|
||||
*g = g.moved(d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Map the guides of artboard `id` through `xf`, an axis-aligned scale and move (Scale Artwork
|
||||
/// with Artboard).
|
||||
pub fn map_artboard_guides(&mut self, id: u32, xf: Affine) {
|
||||
for g in self.guides.iter_mut().filter(|g| g.artboard == Some(id)) {
|
||||
g.pos = if g.vertical { (xf * Point::new(g.pos, 0.0)).x } else { (xf * Point::new(0.0, g.pos)).y };
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy the guides of artboard `from` onto artboard `to`, `d` away (with a copy of their
|
||||
/// artboard).
|
||||
pub fn copy_artboard_guides(&mut self, from: u32, to: u32, d: Vec2) {
|
||||
let copies: Vec<Guide> =
|
||||
self.guides.iter().filter(|g| g.artboard == Some(from)).map(|g| Guide { artboard: Some(to), ..g.moved(d) }).collect();
|
||||
self.guides.extend(copies);
|
||||
}
|
||||
|
||||
/// An id for a new artboard: one no artboard has, above the ids given out before and the ids of
|
||||
/// the artboards deleted from the document ([`Document::retired_artboard_id`]). The id counts
|
||||
/// as given out, so an artboard made after an undo does not take the id of one the undo took
|
||||
/// away.
|
||||
pub fn next_artboard_id(&self) -> u32 {
|
||||
let id = free_id(self.artboards.iter().map(|a| a.id).chain([self.retired_artboard_id.get()]));
|
||||
self.retired_artboard_id.raise(id);
|
||||
id
|
||||
}
|
||||
|
||||
/// Record that the artboard with `id` was deleted: no later artboard takes its id.
|
||||
pub fn retire_artboard_id(&self, id: u32) {
|
||||
self.retired_artboard_id.raise(id);
|
||||
}
|
||||
|
||||
pub fn pattern(&self, name: &str) -> Option<&PatternDef> {
|
||||
self.patterns.iter().find(|p| p.name == name)
|
||||
}
|
||||
|
||||
pub fn pattern_mut(&mut self, name: &str) -> Option<&mut PatternDef> {
|
||||
self.patterns.iter_mut().find(|p| p.name == name)
|
||||
}
|
||||
|
||||
/// Deep-clone `node` with fresh ids for it and all descendants, its images' own pixels taken
|
||||
/// in ([`Self::adopt_pixels`]).
|
||||
pub fn reid(&mut self, node: &Node) -> Node {
|
||||
let mut n = node.clone();
|
||||
n.id = self.alloc_id();
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
self.adopt_image_pixels(im);
|
||||
}
|
||||
// A copied annotation must never bind its source ids to unrelated art in a different
|
||||
// document. Keep the measured geometry; new measurements can be linked after pasting.
|
||||
if let Some(e) = n.extras_if_any()
|
||||
&& let Some(dimension) = &mut e.dimension
|
||||
{
|
||||
dimension.source = None;
|
||||
}
|
||||
// A copy of a threaded frame is in no thread, so its first paragraph starts in it and its
|
||||
// layout caches are dropped. A caller that keeps the copy as an object fills them again.
|
||||
if let NodeKind::Text(t) = &mut n.kind
|
||||
&& t.first_para_continues
|
||||
{
|
||||
t.first_para_continues = false;
|
||||
t.cached_bounds = None;
|
||||
t.cached_baselines.clear();
|
||||
}
|
||||
let mut renamed = std::collections::HashMap::new();
|
||||
if let Some(ch) = n.children_mut() {
|
||||
let old: Vec<Arc<Node>> = std::mem::take(ch);
|
||||
*ch = old.iter().map(|c| Arc::new(self.reid(c))).collect();
|
||||
renamed.extend(old.iter().zip(ch.iter()).map(|(o, c)| (o.id, c.id)));
|
||||
}
|
||||
// An Objects on Path group names its path and its objects by id: the copy names the copies.
|
||||
if let Some(e) = n.extras_if_any()
|
||||
&& let Some(on_path) = &mut e.objects_on_path
|
||||
{
|
||||
on_path.rename(&renamed);
|
||||
}
|
||||
n
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
use super::*;
|
||||
|
||||
/// A named graphic style (Graphic Styles panel): an appearance plus the object's transparency.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct GraphicStyle {
|
||||
pub name: String,
|
||||
pub appearance: Appearance,
|
||||
/// Stable id linked objects refer to ([`Node::graphic_style`]); 0 until first needed (styles
|
||||
/// from older files get one when an object is first linked to them).
|
||||
#[serde(default, skip_serializing_if = "skip::is_default")]
|
||||
pub id: u32,
|
||||
#[serde(default = "one", skip_serializing_if = "skip::is_one")]
|
||||
pub opacity: f32,
|
||||
#[serde(default, skip_serializing_if = "skip::is_default")]
|
||||
pub blend: vectorcraft_color::BlendMode,
|
||||
#[serde(default, skip_serializing_if = "skip::is_default")]
|
||||
pub isolate: bool,
|
||||
#[serde(default, skip_serializing_if = "skip::is_default")]
|
||||
pub knockout: Knockout,
|
||||
/// Placed gradients are stored relative to the unit box (0, 0)–(1, 1), so applying the style
|
||||
/// places them on each object's own bounds. Styles saved before this kept document
|
||||
/// coordinates (false).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub unit_box: bool,
|
||||
}
|
||||
|
||||
fn one() -> f32 {
|
||||
1.0
|
||||
}
|
||||
|
||||
/// The name of the style new documents list first (Sort by Name keeps it first).
|
||||
pub const DEFAULT_GRAPHIC_STYLE: &str = "Default Graphic Style";
|
||||
|
||||
impl GraphicStyle {
|
||||
/// The box a style's placed gradients are stored relative to.
|
||||
pub const UNIT_BOX: Rect = Rect::new(0.0, 0.0, 1.0, 1.0);
|
||||
|
||||
/// A style with `appearance` (its placed gradients, if any, in unit-box space) and default
|
||||
/// transparency (no id yet).
|
||||
pub fn new(name: impl Into<String>, appearance: Appearance) -> Self {
|
||||
Self {
|
||||
name: name.into(),
|
||||
appearance,
|
||||
id: 0,
|
||||
opacity: 1.0,
|
||||
blend: Default::default(),
|
||||
isolate: false,
|
||||
knockout: Knockout::Neutral,
|
||||
unit_box: true,
|
||||
}
|
||||
}
|
||||
/// A style capturing `n`'s transparency and `appearance` (in unit-box space).
|
||||
pub fn of(name: impl Into<String>, appearance: Appearance, n: &Node) -> Self {
|
||||
Self { opacity: n.opacity, blend: n.blend, isolate: n.isolate, knockout: n.knockout, ..Self::new(name, appearance) }
|
||||
}
|
||||
/// The style's appearance as object `n` takes it: placed gradients stored in unit-box space
|
||||
/// land at the same place relative to `n`'s geometric bounds.
|
||||
pub fn appearance_on(&self, n: &Node) -> std::borrow::Cow<'_, Appearance> {
|
||||
let placed = self.unit_box && self.appearance.has_placed_gradient();
|
||||
match n.geometric_bounds().filter(|_| placed) {
|
||||
Some(b) => {
|
||||
let mut ap = self.appearance.clone();
|
||||
ap.rebase_gradients(Self::UNIT_BOX, b);
|
||||
std::borrow::Cow::Owned(ap)
|
||||
}
|
||||
None => std::borrow::Cow::Borrowed(&self.appearance),
|
||||
}
|
||||
}
|
||||
/// Give `n` this style's transparency.
|
||||
pub fn apply_transparency(&self, n: &mut Node) {
|
||||
(n.opacity, n.blend, n.isolate, n.knockout) = (self.opacity, self.blend, self.isolate, self.knockout);
|
||||
}
|
||||
/// Does `n` have this style's transparency?
|
||||
pub fn transparency_matches(&self, n: &Node) -> bool {
|
||||
(n.opacity, n.blend, n.isolate, n.knockout) == (self.opacity, self.blend, self.isolate, self.knockout)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn default_graphic_styles() -> Vec<GraphicStyle> {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let solid = |hex| Paint::solid(Color::from_hex(hex).unwrap_or(Color::BLACK));
|
||||
[
|
||||
GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, Appearance::default_art()),
|
||||
GraphicStyle::new("Black Outline", Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)),
|
||||
GraphicStyle::new("Heavy Ink", Appearance::basic(solid("#1b1464"), Paint::solid(Color::BLACK), 4.0)),
|
||||
GraphicStyle::new("Sunshine", Appearance::basic(solid("#fbb03b"), solid("#f15a24"), 2.0)),
|
||||
]
|
||||
.into_iter()
|
||||
.zip(1..)
|
||||
.map(|(g, id)| GraphicStyle { id, ..g })
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Guide {
|
||||
/// true = vertical guide at `pos` (x), false = horizontal at `pos` (y).
|
||||
pub vertical: bool,
|
||||
pub pos: f64,
|
||||
/// An artboard guide: the [`Artboard::id`] it belongs to. It runs across that artboard only
|
||||
/// and moves, is copied and is deleted with it. None: a canvas guide, across the whole canvas.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub artboard: Option<u32>,
|
||||
/// The layer (or sublayer) it is on: it shows, hides and locks with that layer and is listed
|
||||
/// in it in the Layers panel, and goes when the layer is deleted. None: on no layer (guides
|
||||
/// from before guides had layers, and from files that don't say), always there.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub layer: Option<NodeId>,
|
||||
}
|
||||
|
||||
impl Guide {
|
||||
/// A canvas guide.
|
||||
pub fn new(vertical: bool, pos: f64) -> Self {
|
||||
Self { vertical, pos, artboard: None, layer: None }
|
||||
}
|
||||
|
||||
/// Moved by `d` (a vertical guide across, a horizontal one down).
|
||||
pub fn moved(&self, d: Vec2) -> Self {
|
||||
Self { pos: self.pos + if self.vertical { d.x } else { d.y }, ..self.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct GridPrefs {
|
||||
pub spacing: f64,
|
||||
pub subdivisions: u32,
|
||||
}
|
||||
|
||||
impl Default for GridPrefs {
|
||||
fn default() -> Self {
|
||||
Self { spacing: 72.0, subdivisions: 8 }
|
||||
}
|
||||
}
|
||||
|
||||
/// What the rulers measure from (View › Rulers): the active artboard's origin, the default of a
|
||||
/// new document, or one origin for the whole document.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum RulerMode {
|
||||
#[default]
|
||||
Artboard,
|
||||
Global,
|
||||
}
|
||||
|
||||
impl RulerMode {
|
||||
/// The mode of a document saved before the choice existed: global, as its rulers measured.
|
||||
pub fn legacy() -> Self {
|
||||
Self::Global
|
||||
}
|
||||
}
|
||||
+1
-840
@@ -731,843 +731,4 @@ fn marquee_in_clip(clip: &Node, r: Rect) -> Option<Rect> {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Appearance, Node};
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
#[test]
|
||||
fn hits_topmost() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let a = d.alloc_id();
|
||||
d.insert(Some(l), 9, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
let b = d.alloc_id();
|
||||
d.insert(Some(l), 9, Node::path(b, shapes::rectangle(Rect::new(25.0, 25.0, 75.0, 75.0)), Appearance::default_art())).unwrap();
|
||||
let h = hit_test(&d, Point::new(30.0, 30.0), HitOptions::default()).unwrap();
|
||||
assert_eq!(h.leaf, b);
|
||||
assert_eq!(h.kind, HitKind::Fill);
|
||||
let h = hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).unwrap();
|
||||
assert_eq!(h.leaf, a);
|
||||
assert!(hit_test(&d, Point::new(150.0, 150.0), HitOptions::default()).is_none());
|
||||
// Outline mode: interior misses.
|
||||
assert!(hit_test(&d, Point::new(10.0, 10.0), HitOptions { outline: true, ..Default::default() }).is_none());
|
||||
assert!(hit_test(&d, Point::new(0.5, 10.0), HitOptions { outline: true, ..Default::default() }).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unfilled_interior_misses() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let a = d.alloc_id();
|
||||
d.insert(
|
||||
Some(l),
|
||||
9,
|
||||
Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(hit_test(&d, Point::new(25.0, 25.0), HitOptions::default()).is_none());
|
||||
assert!(hit_test(&d, Point::new(50.5, 25.0), HitOptions::default()).is_some());
|
||||
}
|
||||
|
||||
/// #1103: a marquee drawn over a background picks what is on it, not the background, whose
|
||||
/// outline it doesn't touch.
|
||||
#[test]
|
||||
fn a_marquee_inside_a_background_leaves_the_background() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (back, small) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::path(back, shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default_art())).unwrap();
|
||||
d.insert(Some(l), 1, Node::path(small, shapes::rectangle(Rect::new(50.0, 50.0, 60.0, 60.0)), Appearance::default_art())).unwrap();
|
||||
assert_eq!(marquee(&d, Rect::new(40.0, 40.0, 70.0, 70.0), None, false), vec![small]);
|
||||
// Reaching the background's edge takes it too.
|
||||
assert_eq!(marquee(&d, Rect::new(-5.0, 40.0, 70.0, 70.0), None, false), vec![back, small]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_top_object() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let a = d.alloc_id();
|
||||
let g = d.alloc_id();
|
||||
let p = Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art());
|
||||
d.insert(Some(l), 0, Node::group(g, vec![Arc::new(p)])).unwrap();
|
||||
let h = hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).unwrap();
|
||||
assert_eq!(h.leaf, a);
|
||||
assert_eq!(h.top_object(None), g);
|
||||
assert_eq!(h.top_object(Some(g)), a);
|
||||
assert_eq!(marquee(&d, Rect::new(-5.0, -5.0, 5.0, 5.0), None, false), vec![g]);
|
||||
assert_eq!(marquee(&d, Rect::new(-5.0, -5.0, 5.0, 5.0), None, true), vec![a]);
|
||||
assert!(marquee(&d, Rect::new(100.0, 100.0, 105.0, 105.0), None, false).is_empty());
|
||||
}
|
||||
|
||||
/// The art of a 200 pt wide rectangle clipped to its left half (0..100 × 0..100): the mask and
|
||||
/// the art, in that order.
|
||||
fn half_clipped(d: &mut Document) -> (Node, Node) {
|
||||
let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default());
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), Appearance::default_art());
|
||||
(mask, art)
|
||||
}
|
||||
|
||||
/// #2345: a marquee touches a clip group only where its art shows. Over the clipped-away
|
||||
/// half alone it selects nothing, and around a rectangle drawn beside the group's mask it
|
||||
/// takes that rectangle alone; reaching into the mask takes the group. The same holds for
|
||||
/// Group Selection's leaves and in isolation mode.
|
||||
#[test]
|
||||
fn a_marquee_leaves_a_clip_group_by_its_clipped_away_art() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = half_clipped(&mut d);
|
||||
let (g, art_id, beside) = (d.alloc_id(), art.id, d.alloc_id());
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
d.insert(Some(l), 1, Node::path(beside, shapes::rectangle(Rect::new(150.0, 80.0, 190.0, 130.0)), Appearance::default_art())).unwrap();
|
||||
// This marquee crosses only the hidden art's top and right edges.
|
||||
let hidden = Rect::new(150.0, -10.0, 210.0, 50.0);
|
||||
assert!(marquee(&d, hidden, None, false).is_empty());
|
||||
assert!(marquee(&d, hidden, None, true).is_empty());
|
||||
assert!(marquee(&d, hidden, Some(g), false).is_empty());
|
||||
assert!(marquee(&d, hidden, Some(art_id), false).is_empty());
|
||||
// This marquee surrounds the rectangle beside and crosses the hidden art's bottom edge.
|
||||
assert_eq!(marquee(&d, Rect::new(140.0, 70.0, 195.0, 140.0), None, false), vec![beside]);
|
||||
// This marquee crosses the shown half's top edge and goes on into the hidden half.
|
||||
let shown = Rect::new(50.0, -10.0, 160.0, 10.0);
|
||||
assert_eq!(marquee(&d, shown, None, false), vec![g]);
|
||||
assert!(marquee(&d, shown, None, true).contains(&art_id));
|
||||
assert_eq!(marquee(&d, shown, Some(g), false).len(), 2, "the mask and the art");
|
||||
}
|
||||
|
||||
/// #2345: in the corner of a diamond mask's box, outside the diamond, a marquee over the
|
||||
/// clipped art's corner leaves the clip group. An open mask clips to its area closed by a
|
||||
/// straight line, and a marquee across that line takes the art it reaches inside.
|
||||
#[test]
|
||||
fn a_marquee_must_meet_the_clipping_path_itself() {
|
||||
// A clip group of a mask through `pts` (closed or open) over the art `art`.
|
||||
let clipped = |pts: &[(f64, f64)], closed: bool, art: Rect| {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut mask = vectorcraft_geom::BezPath::new();
|
||||
mask.move_to(pts[0]);
|
||||
for &p in &pts[1..] {
|
||||
mask.line_to(p);
|
||||
}
|
||||
if closed {
|
||||
mask.close_path();
|
||||
}
|
||||
let mask = Node::path(d.alloc_id(), vectorcraft_geom::PathData::from_bezpath(&mask), Appearance::default());
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(art), Appearance::default_art());
|
||||
let g = d.alloc_id();
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
(d, g)
|
||||
};
|
||||
let (d, g) = clipped(&[(50.0, 0.0), (100.0, 50.0), (50.0, 100.0), (0.0, 50.0)], true, Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
assert!(marquee(&d, Rect::new(-10.0, -10.0, 10.0, 10.0), None, false).is_empty());
|
||||
assert_eq!(marquee(&d, Rect::new(-10.0, 40.0, 10.0, 60.0), None, false), vec![g], "over the diamond's left point");
|
||||
// The mask is the triangle above the line from (0, 0) to (100, 100), and the art lies inside it.
|
||||
let (d, g) = clipped(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false, Rect::new(55.0, 40.0, 70.0, 50.0));
|
||||
assert_eq!(marquee(&d, Rect::new(40.0, 45.0, 60.0, 70.0), None, false), vec![g]);
|
||||
}
|
||||
|
||||
/// #2345: the objects of a layer or sublayer with a clipping mask are touched only where the
|
||||
/// mask shows them, as in a clip group.
|
||||
#[test]
|
||||
fn a_marquee_leaves_art_a_layer_clips_away() {
|
||||
for sublayer in [false, true] {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let beside = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::path(beside, shapes::rectangle(Rect::new(150.0, 80.0, 190.0, 130.0)), Appearance::default_art())).unwrap();
|
||||
let masked = d.alloc_id();
|
||||
let mut layer = Node::layer(masked, "Masked", crate::LayerColor::Preset(2));
|
||||
layer.set_clips(true);
|
||||
d.insert(sublayer.then_some(l), 9, layer).unwrap();
|
||||
let (mask, art) = half_clipped(&mut d);
|
||||
let (mask_id, art_id) = (mask.id, art.id);
|
||||
d.insert(Some(masked), 0, mask).unwrap();
|
||||
d.insert(Some(masked), 1, art).unwrap();
|
||||
assert!(marquee(&d, Rect::new(150.0, -10.0, 210.0, 50.0), None, false).is_empty(), "sublayer: {sublayer}");
|
||||
assert_eq!(marquee(&d, Rect::new(140.0, 70.0, 195.0, 140.0), None, false), vec![beside], "sublayer: {sublayer}");
|
||||
assert_eq!(marquee(&d, Rect::new(50.0, -10.0, 160.0, 10.0), None, false), vec![mask_id, art_id], "sublayer: {sublayer}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A marquee touches a Shaper Group only by the art it shows, as clicks do ([`may_hit`]): over
|
||||
/// the original shape of a face the group erased it selects nothing, with Group Selection's
|
||||
/// leaves too, and over a face it shows it takes the group. With the original shapes isolated
|
||||
/// (Construction mode) it takes the original shape it reaches.
|
||||
#[test]
|
||||
fn a_marquee_leaves_a_shaper_group_by_its_original_shapes() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
// Two original squares, 0..100 and 50..150; the group shows only the first one's face.
|
||||
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0));
|
||||
let a = Node::path(d.alloc_id(), square(0.0), Appearance::default_art());
|
||||
let b = Node::path(d.alloc_id(), square(50.0), Appearance::default_art());
|
||||
let b_id = b.id;
|
||||
let mut sources = Node::group(d.alloc_id(), vec![Arc::new(a), Arc::new(b)]);
|
||||
sources.name = Some(crate::shaper::SOURCES.into());
|
||||
sources.opacity = 0.0;
|
||||
let sources_id = sources.id;
|
||||
let mut face = Node::path(d.alloc_id(), square(0.0), Appearance::default_art());
|
||||
face.name = Some(format!("{}0", crate::shaper::FILL_PREFIX));
|
||||
let face_id = face.id;
|
||||
let g = d.alloc_id();
|
||||
let mut group = Node::group(g, vec![Arc::new(sources), Arc::new(face)]);
|
||||
group.extras_mut().shaper = Some(Box::default());
|
||||
d.insert(Some(l), 0, group).unwrap();
|
||||
// This marquee crosses only the right edge of the second square, whose face is erased.
|
||||
let erased = Rect::new(140.0, 40.0, 160.0, 60.0);
|
||||
assert!(hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).is_none(), "a click there misses");
|
||||
assert!(marquee(&d, erased, None, false).is_empty());
|
||||
assert!(marquee(&d, erased, None, true).is_empty());
|
||||
assert!(marquee(&d, erased, Some(g), false).is_empty());
|
||||
// This marquee crosses the shown face's left edge.
|
||||
let shown = Rect::new(-10.0, 40.0, 10.0, 60.0);
|
||||
assert_eq!(marquee(&d, shown, None, false), vec![g]);
|
||||
assert_eq!(marquee(&d, shown, None, true), vec![face_id]);
|
||||
assert_eq!(marquee(&d, shown, Some(g), false), vec![face_id]);
|
||||
// Construction mode: the original shapes are the objects.
|
||||
assert_eq!(marquee(&d, erased, Some(sources_id), false), vec![b_id]);
|
||||
}
|
||||
|
||||
/// A marquee touches an Intertwine group by its members, as it touches a plain group (#1103) and
|
||||
/// as clicks do: in the gap between two members, or inside one member's fill, it selects nothing.
|
||||
/// Across a member's edge it selects the group, and with the leaves that Direct and Group
|
||||
/// Selection take, or in isolation mode, it selects the member.
|
||||
#[test]
|
||||
fn a_marquee_meets_an_intertwine_group_by_its_members() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
// Two squares, 0..100 and 150..250, with a gap between them inside the group's box.
|
||||
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0));
|
||||
let mut a = Node::path(d.alloc_id(), square(0.0), Appearance::default_art());
|
||||
a.extras_mut().intertwine = Some(Box::new(shapes::rectangle(Rect::new(50.0, 0.0, 100.0, 100.0))));
|
||||
let b = Node::path(d.alloc_id(), square(150.0), Appearance::default_art());
|
||||
let (a_id, g) = (a.id, d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::new(g, NodeKind::Intertwine { children: vec![Arc::new(a), Arc::new(b)] })).unwrap();
|
||||
let gap = Rect::new(110.0, 40.0, 140.0, 60.0);
|
||||
assert!(hit_test(&d, gap.center(), HitOptions::default()).is_none(), "a click in the gap misses");
|
||||
assert!(marquee(&d, gap, None, false).is_empty());
|
||||
assert!(marquee(&d, gap, None, true).is_empty());
|
||||
assert!(marquee(&d, gap, Some(g), false).is_empty());
|
||||
assert!(marquee(&d, Rect::new(20.0, 20.0, 40.0, 40.0), None, false).is_empty(), "inside a member's fill");
|
||||
// This marquee crosses the first square's left edge.
|
||||
let edge = Rect::new(-10.0, 40.0, 10.0, 60.0);
|
||||
assert_eq!(marquee(&d, edge, None, false), vec![g]);
|
||||
assert_eq!(marquee(&d, edge, None, true), vec![a_id]);
|
||||
assert_eq!(marquee(&d, edge, Some(g), false), vec![a_id]);
|
||||
}
|
||||
|
||||
/// A marquee touches a repeat by the copies it draws, as clicks do: between two copies of a
|
||||
/// grid repeat it selects nothing, and across a copy's edge it takes the repeat.
|
||||
#[test]
|
||||
fn a_marquee_meets_a_repeat_by_its_copies() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let source = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art());
|
||||
// Copies at 0..20, 40..60 and 80..100.
|
||||
let kind = crate::pattern::RepeatKind::Grid {
|
||||
h_spacing: 20.0,
|
||||
v_spacing: 20.0,
|
||||
rows: 1,
|
||||
cols: 3,
|
||||
grid_type: crate::pattern::TileType::Grid,
|
||||
flip_rows: false,
|
||||
flip_cols: false,
|
||||
};
|
||||
let r = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(r, NodeKind::Repeat(crate::pattern::RepeatSpec { kind, source: vec![Arc::new(source)] }))).unwrap();
|
||||
let gap = Rect::new(25.0, 5.0, 35.0, 15.0);
|
||||
assert!(hit_test(&d, gap.center(), HitOptions::default()).is_none(), "a click between copies misses");
|
||||
assert!(marquee(&d, gap, None, false).is_empty());
|
||||
assert!(marquee(&d, gap, None, true).is_empty());
|
||||
assert_eq!(marquee(&d, Rect::new(35.0, 5.0, 45.0, 15.0), None, false), vec![r], "across the second copy's left edge");
|
||||
assert_eq!(marquee(&d, Rect::new(35.0, 5.0, 45.0, 15.0), None, true), vec![r]);
|
||||
}
|
||||
|
||||
/// A blend and an envelope are clicked anywhere in their box, and a marquee touches them there
|
||||
/// too: inside the box, away from every key object's and the content's outline, it takes them.
|
||||
#[test]
|
||||
fn a_marquee_meets_blends_and_envelopes_by_their_box() {
|
||||
let mut d = Document::new(300.0, 300.0);
|
||||
let l = d.layers[0].id;
|
||||
let square = |id, x: f64, y: f64| Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), Appearance::default_art()));
|
||||
let blend = d.alloc_id();
|
||||
let keys = vec![square(d.alloc_id(), 0.0, 0.0), square(d.alloc_id(), 100.0, 0.0)];
|
||||
d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Default::default() })).unwrap();
|
||||
let envelope = d.alloc_id();
|
||||
let content = vec![Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 150.0, 100.0, 250.0)), Appearance::default_art()))];
|
||||
let e = Node::new(
|
||||
envelope,
|
||||
NodeKind::Envelope {
|
||||
content,
|
||||
kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true }),
|
||||
fidelity: 100.0,
|
||||
editing: false,
|
||||
options: Default::default(),
|
||||
frame: Box::new(vectorcraft_geom::Affine::IDENTITY),
|
||||
},
|
||||
);
|
||||
d.insert(Some(l), 1, e).unwrap();
|
||||
for (r, id) in [(Rect::new(50.0, 5.0, 60.0, 15.0), blend), (Rect::new(40.0, 190.0, 60.0, 210.0), envelope)] {
|
||||
assert_eq!(hit_test(&d, r.center(), HitOptions::default()).map(|h| h.leaf), Some(id));
|
||||
assert_eq!(marquee(&d, r, None, false), vec![id]);
|
||||
assert_eq!(marquee(&d, r, None, true), vec![id]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A rectangle (40, 40)–(140, 140) clipping a filled 200 × 200 square drawn over its edges, in a
|
||||
/// clip group (or, `layer`, as the first layer's clipping mask): the group (or the layer), the
|
||||
/// clipping path and the art.
|
||||
fn masked_square(layer: bool) -> (Document, NodeId, NodeId, NodeId) {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (g, clip, art) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let mut path = Node::path(clip, shapes::rectangle(Rect::new(40.0, 40.0, 140.0, 140.0)), Appearance::basic(Paint::None, Paint::None, 0.0));
|
||||
if let NodeKind::Path { clipping, .. } = &mut path.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let picture = Node::path(art, shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default_art());
|
||||
if layer {
|
||||
d.insert(Some(l), 0, path).unwrap();
|
||||
d.insert(Some(l), 1, picture).unwrap();
|
||||
d.node_mut(l).unwrap().set_clips(true);
|
||||
(d, l, clip, art)
|
||||
} else {
|
||||
d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(path), Arc::new(picture)], clip: true })).unwrap();
|
||||
(d, g, clip, art)
|
||||
}
|
||||
}
|
||||
|
||||
const SELECTING: HitOptions =
|
||||
HitOptions { tol: 3.0, outline: false, path_only: false, type_path_only: false, skip_guides: false, clip_outlines: true, scope: None };
|
||||
|
||||
/// For the selection tools a clip group's clipping path is hit on its outline, within the
|
||||
/// tolerance, before the art it clips and just outside it too; inside, the art is hit.
|
||||
#[test]
|
||||
fn a_clipping_path_is_hit_on_its_outline_before_its_art() {
|
||||
let (d, g, clip, art) = masked_square(false);
|
||||
for (x, y) in [(140.0, 90.0), (141.5, 90.0), (138.5, 90.0), (90.0, 40.0)] {
|
||||
let h = hit_test(&d, Point::new(x, y), SELECTING).unwrap();
|
||||
assert_eq!((h.leaf, h.kind, h.top_object(None)), (clip, HitKind::Outline, g), "at {x}, {y}");
|
||||
}
|
||||
let h = hit_test(&d, Point::new(90.0, 90.0), SELECTING).unwrap();
|
||||
assert_eq!((h.leaf, h.top_object(None)), (art, g));
|
||||
// Beyond the tolerance outside it, the clipped art is not there to hit.
|
||||
assert!(hit_test(&d, Point::new(150.0, 90.0), SELECTING).is_none());
|
||||
}
|
||||
|
||||
/// Without `clip_outlines` (the tools that act on what is drawn) and for read-only sampling
|
||||
/// (the eyedropper), the art is hit on the mask's edge, as before: the clipping path paints
|
||||
/// nothing there.
|
||||
#[test]
|
||||
fn only_the_selection_tools_hit_a_clipping_path_on_its_outline() {
|
||||
let (d, _, clip, art) = masked_square(false);
|
||||
let p = Point::new(138.5, 90.0);
|
||||
assert_eq!(hit_test(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art));
|
||||
assert_eq!(hit_test_visible(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art));
|
||||
assert_eq!(hit_test_visible(&d, p, SELECTING).map(|h| h.leaf), Some(art));
|
||||
assert_eq!(hit_test(&d, p, SELECTING).map(|h| h.leaf), Some(clip));
|
||||
// A hidden or locked clipping path is passed over.
|
||||
for change in [|n: &mut Node| n.visible = false, |n: &mut Node| n.locked = true] {
|
||||
let mut d = d.clone();
|
||||
change(d.node_mut(clip).unwrap());
|
||||
assert_ne!(hit_test(&d, p, SELECTING).map(|h| h.leaf), Some(clip));
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer's clipping mask is hit on its outline too, and Select Behind lists what the
|
||||
/// repeated hit test finds: the mask on and just outside its edge, then the art inside it;
|
||||
/// well inside, the art alone (the mask paints nothing there).
|
||||
#[test]
|
||||
fn select_behind_takes_a_layer_masks_outline_first() {
|
||||
let (d, _, clip, art) = masked_square(true);
|
||||
for (x, want) in [(140.0, vec![clip]), (141.5, vec![clip]), (138.5, vec![clip, art]), (90.0, vec![art])] {
|
||||
let p = Point::new(x, 90.0);
|
||||
assert_eq!(objects_at(&d, p, SELECTING, None), want, "x = {x}");
|
||||
assert_eq!(objects_at_repeated(&d, p, SELECTING, None), want, "x = {x}");
|
||||
}
|
||||
// Without clip_outlines, as before.
|
||||
assert_eq!(objects_at(&d, Point::new(138.5, 90.0), HitOptions::default(), None), vec![art, clip]);
|
||||
}
|
||||
|
||||
/// Art in a sublayer is an object of its own: a click or a marquee takes it, not the
|
||||
/// sublayer; hidden, locked and template sublayers block both.
|
||||
#[test]
|
||||
fn sublayers_are_not_objects() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let sub = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::layer(sub, "Sub", crate::LayerColor::Preset(2))).unwrap();
|
||||
let inner = d.alloc_id();
|
||||
d.insert(Some(sub), 0, Node::layer(inner, "Inner", crate::LayerColor::Preset(3))).unwrap();
|
||||
let a = d.alloc_id();
|
||||
d.insert(Some(inner), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
let g = d.alloc_id();
|
||||
let b = d.alloc_id();
|
||||
let pb = Node::path(b, shapes::rectangle(Rect::new(100.0, 0.0, 150.0, 50.0)), Appearance::default_art());
|
||||
d.insert(Some(sub), 9, Node::group(g, vec![Arc::new(pb)])).unwrap();
|
||||
let h = hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).unwrap();
|
||||
assert_eq!((h.leaf, h.top_object(None), h.layers), (a, a, 3));
|
||||
let h = hit_test(&d, Point::new(110.0, 10.0), HitOptions::default()).unwrap();
|
||||
assert_eq!((h.top_object(None), h.top_object(Some(g))), (g, b));
|
||||
let all = Rect::new(-5.0, -5.0, 200.0, 200.0);
|
||||
assert_eq!(marquee(&d, all, None, false), vec![a, g]);
|
||||
assert_eq!(d.layer_containing(a), Some(inner));
|
||||
assert_eq!(d.layer_color(a), crate::LayerColor::Preset(3).rgb(), "the sublayer's own colour");
|
||||
assert_eq!(d.selectable_art(), vec![a, g]);
|
||||
for f in [
|
||||
|n: &mut Node| n.visible = false,
|
||||
|n: &mut Node| n.locked = true,
|
||||
|n: &mut Node| {
|
||||
if let NodeKind::Layer { template, .. } = &mut n.kind {
|
||||
*template = true;
|
||||
}
|
||||
},
|
||||
] {
|
||||
let mut d2 = d.clone();
|
||||
f(d2.node_mut(inner).unwrap());
|
||||
assert!(hit_test(&d2, Point::new(10.0, 10.0), HitOptions::default()).is_none());
|
||||
assert_eq!(marquee(&d2, all, None, false), vec![g]);
|
||||
assert_eq!(d2.selectable_art(), vec![g]);
|
||||
}
|
||||
// A sublayer whose Preview is off is clicked in outline: its fill no longer hits.
|
||||
if let NodeKind::Layer { preview, .. } = &mut d.node_mut(inner).unwrap().kind {
|
||||
*preview = false;
|
||||
}
|
||||
assert!(hit_test(&d, Point::new(25.0, 25.0), HitOptions::default()).is_none());
|
||||
assert!(hit_test(&d, Point::new(0.5, 25.0), HitOptions::default()).is_some());
|
||||
}
|
||||
|
||||
/// Object Selection by Path Only: a filled path or compound path hits on its outline only.
|
||||
#[test]
|
||||
fn path_only_leaves_out_fills() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (a, c) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
let inner = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 0.0, 150.0, 50.0)), Appearance::default());
|
||||
let mut compound = Node::new(c, NodeKind::Compound { children: vec![Arc::new(inner)], rule: vectorcraft_geom::FillRule::NonZero });
|
||||
compound.appearance = Appearance::default_art().into();
|
||||
d.insert(Some(l), 9, compound).unwrap();
|
||||
let path_only = HitOptions { path_only: true, ..Default::default() };
|
||||
for (id, inside, edge) in [(a, Point::new(25.0, 25.0), Point::new(0.5, 25.0)), (c, Point::new(125.0, 25.0), Point::new(100.5, 25.0))] {
|
||||
assert_eq!(hit_test(&d, inside, HitOptions::default()).map(|h| h.leaf), Some(id), "the fill hits");
|
||||
assert!(hit_test(&d, inside, path_only).is_none(), "path only: the fill of {id:?} doesn't hit");
|
||||
assert_eq!(hit_test(&d, edge, path_only).map(|h| h.leaf), Some(id), "path only: the outline does");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3291: with Object Selection by Path Only, a placed image is picked on its frame's edge, so
|
||||
/// a path under it can be picked through it.
|
||||
#[test]
|
||||
fn path_only_picks_paths_through_images() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (path, image) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::path(path, shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default_art())).unwrap();
|
||||
// 100×50 pixels, scaled to 100×100 and moved to (10, 10): over the whole path.
|
||||
let xf = vectorcraft_geom::Affine::translate((10.0, 10.0)) * vectorcraft_geom::Affine::scale_non_uniform(1.0, 2.0);
|
||||
let im = crate::ImageObject { key: "k".into(), width: 100, height: 50, xf, link: None, placement: Default::default(), pixels: None };
|
||||
d.insert(Some(l), 1, Node::new(image, NodeKind::Image(Box::new(im)))).unwrap();
|
||||
let path_only = HitOptions { path_only: true, ..Default::default() };
|
||||
let hit = |p: Point, opt| hit_test(&d, p, opt).map(|h| h.leaf);
|
||||
let (path_edge, inside, image_edge) = (Point::new(20.5, 40.0), Point::new(80.0, 80.0), Point::new(80.0, 109.5));
|
||||
assert_eq!(hit(path_edge, HitOptions::default()), Some(image), "the image covers the path");
|
||||
assert_eq!(hit(inside, HitOptions::default()), Some(image));
|
||||
assert_eq!(hit(path_edge, path_only), Some(path), "path only: the path through the image");
|
||||
assert_eq!(hit(inside, path_only), None, "path only: not inside the image");
|
||||
assert_eq!(hit(image_edge, path_only), Some(image), "path only: the image's frame");
|
||||
}
|
||||
|
||||
/// Type Object Selection by Path Only: point type is picked on its baseline, area type on its
|
||||
/// frame and type on a path on its path, no longer anywhere in its bounds.
|
||||
#[test]
|
||||
fn type_path_only_picks_type_on_its_path() {
|
||||
use crate::{CharStyle, TextKind, TextObject};
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut add = |t: TextObject| {
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(l), 9, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
|
||||
id
|
||||
};
|
||||
// Point type at (10, 100), 20 pt: its glyphs rise above the baseline, its layout is 60 wide.
|
||||
let mut point = TextObject::point(Point::new(10.0, 100.0), "Hello", CharStyle { size: 20.0, ..CharStyle::default() });
|
||||
point.cached_bounds = Some(Rect::new(0.0, -16.0, 60.0, 4.0));
|
||||
let point = add(point);
|
||||
let mut area = TextObject::point(Point::new(200.0, 200.0), "Area", CharStyle::default());
|
||||
area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)) };
|
||||
let area = add(area);
|
||||
let mut on_path = TextObject::point(Point::new(10.0, 300.0), "Path", CharStyle::default());
|
||||
on_path.kind = TextKind::OnPath { path: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 40.0)), start: 0.0, end: None };
|
||||
let on_path = add(on_path);
|
||||
let path_only = HitOptions { type_path_only: true, ..Default::default() };
|
||||
let hit = |p: Point, opt: HitOptions| hit_test(&d, p, opt).map(|h| (h.leaf, h.kind));
|
||||
// Off: anywhere in the bounds.
|
||||
assert_eq!(hit(Point::new(40.0, 90.0), HitOptions::default()), Some((point, HitKind::Bounds)));
|
||||
assert_eq!(hit(Point::new(250.0, 225.0), HitOptions::default()), Some((area, HitKind::Bounds)));
|
||||
assert_eq!(hit(Point::new(60.0, 320.0), HitOptions::default()), Some((on_path, HitKind::Bounds)));
|
||||
// On: the glyphs and the inside of the frame or path no longer pick the type.
|
||||
assert_eq!(hit(Point::new(40.0, 90.0), path_only), None, "point type: among its glyphs");
|
||||
assert_eq!(hit(Point::new(250.0, 225.0), path_only), None, "area type: inside its frame");
|
||||
assert_eq!(hit(Point::new(60.0, 320.0), path_only), None, "type on a path: inside its path");
|
||||
// The baseline (within the tolerance, across the layout's width), frame and path do.
|
||||
assert_eq!(hit(Point::new(40.0, 101.5), path_only), Some((point, HitKind::Outline)), "point type: its baseline");
|
||||
assert_eq!(hit(Point::new(75.0, 100.0), path_only), None, "point type: past the end of its layout");
|
||||
assert_eq!(hit(Point::new(250.0, 200.5), path_only), Some((area, HitKind::Outline)), "area type: its frame");
|
||||
assert_eq!(hit(Point::new(60.0, 339.5), path_only), Some((on_path, HitKind::Outline)), "type on a path: its path");
|
||||
}
|
||||
|
||||
/// Type Object Selection by Path Only with the layout's baselines: every line's for point type,
|
||||
/// area type's besides its frame, a vertical column's centre line, and type in perspective
|
||||
/// where it is drawn.
|
||||
#[test]
|
||||
fn type_path_only_picks_every_baseline() {
|
||||
use crate::{CharStyle, PerspectiveAttachment, TextKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, Homography};
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut add = |t: TextObject, perspective: Option<Affine>| {
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
n.extras_mut().perspective = perspective.map(|a| {
|
||||
Box::new(PerspectiveAttachment { projection: Some(Homography::from_affine(a).to_array()), ..PerspectiveAttachment::new("left", 0.0) })
|
||||
});
|
||||
let id = n.id;
|
||||
d.insert(Some(l), 9, n).unwrap();
|
||||
id
|
||||
};
|
||||
let style = CharStyle { size: 20.0, ..CharStyle::default() };
|
||||
// Two lines of point type at (10, 100), 24 pt apart.
|
||||
let mut point = TextObject::point(
|
||||
Point::new(10.0, 100.0),
|
||||
"Hello
|
||||
world",
|
||||
style.clone(),
|
||||
);
|
||||
point.cached_bounds = Some(Rect::new(0.0, -16.0, 60.0, 28.0));
|
||||
point.cached_baselines = vec![(Point::ZERO, Point::new(60.0, 0.0)), (Point::new(0.0, 24.0), Point::new(50.0, 24.0))];
|
||||
let point = add(point, None);
|
||||
// Area type: a line inside its frame.
|
||||
let mut area = TextObject::point(Point::new(200.0, 50.0), "Area", style.clone());
|
||||
area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)) };
|
||||
area.cached_baselines = vec![(Point::new(0.0, 16.0), Point::new(40.0, 16.0))];
|
||||
let area = add(area, None);
|
||||
// Vertical point type at (300, 200) with no baselines cached: down its first column.
|
||||
let mut vertical = TextObject::point(Point::new(300.0, 200.0), "Tate", style.clone());
|
||||
vertical.vertical = true;
|
||||
vertical.cached_bounds = Some(Rect::new(-10.0, 0.0, 10.0, 80.0));
|
||||
let vertical = add(vertical, None);
|
||||
// Point type drawn 100 to the right of where it is laid out.
|
||||
let mut moved = TextObject::point(Point::new(10.0, 350.0), "Moved", style);
|
||||
moved.cached_bounds = Some(Rect::new(0.0, -16.0, 60.0, 4.0));
|
||||
let moved = add(moved, Some(Affine::translate((100.0, 0.0))));
|
||||
let path_only = HitOptions { type_path_only: true, ..Default::default() };
|
||||
let hit = |p: Point| hit_test(&d, p, path_only).map(|h| h.leaf);
|
||||
assert_eq!(hit(Point::new(40.0, 100.0)), Some(point), "the first line's baseline");
|
||||
assert_eq!(hit(Point::new(40.0, 125.0)), Some(point), "the second line's");
|
||||
assert_eq!(hit(Point::new(40.0, 112.0)), None, "between the lines");
|
||||
assert_eq!(hit(Point::new(65.0, 124.0)), None, "past the end of the shorter second line");
|
||||
assert_eq!(hit(Point::new(220.0, 66.0)), Some(area), "area type: a line's baseline");
|
||||
assert_eq!(hit(Point::new(220.0, 80.0)), None, "area type: inside the frame, off the baselines");
|
||||
assert_eq!(hit(Point::new(299.0, 260.0)), Some(vertical), "vertical type: down the column");
|
||||
assert_eq!(hit(Point::new(306.0, 260.0)), None, "vertical type: beside it");
|
||||
assert_eq!(hit(Point::new(140.0, 351.0)), Some(moved), "in perspective: where it is drawn");
|
||||
assert_eq!(hit(Point::new(40.0, 351.0)), None, "in perspective: not where it is laid out");
|
||||
}
|
||||
|
||||
/// `objects_at`: every object under the point, topmost first; a group counts once.
|
||||
#[test]
|
||||
fn objects_at_lists_the_stack() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let rect =
|
||||
|d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art());
|
||||
let a = rect(&mut d, 0.0);
|
||||
let (b, c) = (rect(&mut d, 10.0), rect(&mut d, 20.0));
|
||||
let (a_id, b_id, c_id, g) = (a.id, b.id, c.id, d.alloc_id());
|
||||
d.insert(Some(l), 0, a).unwrap();
|
||||
d.insert(Some(l), 9, Node::group(g, vec![Arc::new(b), Arc::new(c)])).unwrap();
|
||||
let far = rect(&mut d, 120.0);
|
||||
d.insert(Some(l), 9, far).unwrap();
|
||||
let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope);
|
||||
assert_eq!(at(30.0, None), vec![g, a_id]);
|
||||
assert_eq!(at(30.0, Some(g)), [c_id, b_id], "isolated: the group's own objects");
|
||||
// Isolated, the art around the group is locked: clicks pass through it (#833).
|
||||
assert!(at(5.0, Some(g)).is_empty());
|
||||
assert!(at(130.0, Some(g)).is_empty());
|
||||
assert!(hit_test(&d, Point::new(5.0, 25.0), HitOptions { scope: Some(g), ..HitOptions::default() }).is_none());
|
||||
assert_eq!(at(5.0, None), vec![a_id]);
|
||||
assert!(at(90.0, None).is_empty());
|
||||
}
|
||||
|
||||
/// Many overlapping paths: Select Behind must list each exactly once, front to back.
|
||||
/// This is quadratic with repeated full-document hit tests, but linear in tree size with
|
||||
/// the per-object walk.
|
||||
#[test]
|
||||
fn objects_at_large_overlapping_stack() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let layer = d.layers[0].id;
|
||||
let mut ids = Vec::new();
|
||||
for _ in 0..256 {
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
ids.push(id);
|
||||
}
|
||||
ids.reverse();
|
||||
assert_eq!(objects_at(&d, Point::new(25.0, 25.0), HitOptions::default(), None), ids);
|
||||
}
|
||||
|
||||
/// Match the original skip-and-retest algorithm for normal groups, sublayers, clipping,
|
||||
/// invisibility, and path/outline-only settings.
|
||||
#[test]
|
||||
fn objects_at_one_pass_matches_repeated_hits() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let layer = d.layers[0].id;
|
||||
let add = |d: &mut Document, parent, bounds| {
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(parent), usize::MAX, Node::path(id, shapes::rectangle(bounds), Appearance::default_art())).unwrap();
|
||||
id
|
||||
};
|
||||
add(&mut d, layer, Rect::new(0.0, 0.0, 60.0, 60.0));
|
||||
let sub = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sublayer", crate::LayerColor::Preset(2))).unwrap();
|
||||
add(&mut d, sub, Rect::new(0.0, 0.0, 60.0, 60.0));
|
||||
let group = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::group(group, Vec::new())).unwrap();
|
||||
add(&mut d, group, Rect::new(0.0, 0.0, 60.0, 60.0));
|
||||
add(&mut d, group, Rect::new(5.0, 5.0, 60.0, 60.0));
|
||||
let clip = d.alloc_id();
|
||||
let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(5.0, 5.0, 45.0, 45.0)), Appearance::default_art());
|
||||
let content = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 80.0, 80.0)), Appearance::default_art());
|
||||
let mut clipping = Node::group(clip, vec![Arc::new(mask), Arc::new(content)]);
|
||||
clipping.set_clips(true);
|
||||
d.insert(Some(layer), usize::MAX, clipping).unwrap();
|
||||
for (point, opt) in [
|
||||
(Point::new(25.0, 25.0), HitOptions::default()),
|
||||
(Point::new(3.0, 25.0), HitOptions::default()),
|
||||
(Point::new(25.0, 25.0), HitOptions { outline: true, ..Default::default() }),
|
||||
(Point::new(6.0, 25.0), HitOptions { path_only: true, ..Default::default() }),
|
||||
(Point::new(100.0, 100.0), HitOptions::default()),
|
||||
] {
|
||||
assert_eq!(objects_at(&d, point, opt, None), objects_at_repeated(&d, point, opt, None), "point={point:?}, opt={opt:?}");
|
||||
}
|
||||
if let NodeKind::Layer { preview, .. } = &mut d.node_mut(sub).unwrap().kind {
|
||||
*preview = false;
|
||||
}
|
||||
let p = Point::new(25.0, 25.0);
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None));
|
||||
d.node_mut(group).unwrap().locked = true;
|
||||
assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None));
|
||||
}
|
||||
|
||||
/// Documents built at random (nested groups, sublayers, clipping groups, compound paths, blends
|
||||
/// of nothing, hidden and locked objects, outline layers): Select Behind lists the same objects
|
||||
/// in the same order as the hit test repeated over what is left.
|
||||
#[test]
|
||||
fn objects_at_matches_repeated_hits_on_random_documents() {
|
||||
let mut seed = 0x9e37_79b9_u32;
|
||||
let mut next = move |n: u32| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
seed % n
|
||||
};
|
||||
fn fill(d: &mut Document, parent: NodeId, depth: u32, next: &mut impl FnMut(u32) -> u32) {
|
||||
for _ in 0..2 + next(4) {
|
||||
let id = d.alloc_id();
|
||||
let (x, y) = (f64::from(next(60)), f64::from(next(60)));
|
||||
let rect = Rect::new(x, y, x + 10.0 + f64::from(next(50)), y + 10.0 + f64::from(next(50)));
|
||||
let appearance = if next(4) == 0 { Appearance::default() } else { Appearance::default_art() };
|
||||
let mut n = match next(if depth < 3 { 8 } else { 4 }) {
|
||||
4 | 5 => Node::group(id, Vec::new()),
|
||||
6 => Node::layer(id, "Sublayer", crate::LayerColor::Preset(2)),
|
||||
7 => {
|
||||
let mut g = Node::group(id, Vec::new());
|
||||
g.set_clips(true);
|
||||
g
|
||||
}
|
||||
_ => Node::path(id, shapes::rectangle(rect), appearance),
|
||||
};
|
||||
n.visible = next(8) != 0;
|
||||
n.locked = next(8) == 0;
|
||||
if let NodeKind::Layer { preview, .. } = &mut n.kind {
|
||||
*preview = next(3) != 0;
|
||||
}
|
||||
let container = n.is_container();
|
||||
// A sublayer belongs in a layer; in a group it is a group like another to the hit test.
|
||||
d.insert(Some(parent), usize::MAX, n).unwrap();
|
||||
if container {
|
||||
fill(d, id, depth + 1, next);
|
||||
}
|
||||
}
|
||||
}
|
||||
for round in 0..200 {
|
||||
let mut d = Document::new(120.0, 120.0);
|
||||
let layer = d.layers[0].id;
|
||||
fill(&mut d, layer, 0, &mut next);
|
||||
// A clipping mask on the layer, or on a sublayer, now and then.
|
||||
let sublayers: Vec<NodeId> = d.layers[0].children().into_iter().flatten().filter(|n| n.is_layer()).map(|n| n.id).collect();
|
||||
for id in std::iter::once(layer).chain(sublayers) {
|
||||
if next(3) == 0 {
|
||||
d.node_mut(id).unwrap().set_clips(true);
|
||||
}
|
||||
}
|
||||
for _ in 0..12 {
|
||||
let p = Point::new(f64::from(next(120)), f64::from(next(120)));
|
||||
let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() };
|
||||
assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None), "round {round}, {p:?}, {opt:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Select Behind finds a symbol instance by its symbol's art, as a click does: art from
|
||||
/// (100, 60) to (140, 80), outside the 20 × 20 square around the origin, drawn where it lies by
|
||||
/// one instance and 100 pt lower by an instance in a group.
|
||||
#[test]
|
||||
fn objects_at_finds_symbol_instances_by_their_art() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 60.0, 140.0, 80.0)), Appearance::default_art());
|
||||
d.symbols.push(crate::Symbol { name: "Far".into(), art: Arc::new(art) });
|
||||
let (layer, top, inner, group) = (d.layers[0].id, d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let instance =
|
||||
|id, dy: f64| Node::new(id, NodeKind::SymbolInstance { symbol: "Far".into(), xf: vectorcraft_geom::Affine::translate((0.0, dy)) });
|
||||
d.insert(Some(layer), 0, instance(top, 0.0)).unwrap();
|
||||
d.insert(Some(layer), 1, Node::group(group, vec![Arc::new(instance(inner, 100.0))])).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
for (x, y, want) in [(120.0, 70.0, vec![top]), (120.0, 170.0, vec![group]), (0.0, 0.0, vec![]), (0.0, 100.0, vec![])] {
|
||||
let p = Point::new(x, y);
|
||||
assert_eq!(objects_at(&d, p, opt, None), want, "{p:?}");
|
||||
assert_eq!(objects_at_repeated(&d, p, opt, None), want, "{p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Edit Contents can expose descendants of a top-level group: preserve the original
|
||||
/// selection order by falling back to the general hit traversal.
|
||||
#[test]
|
||||
fn objects_at_edit_contents_uses_general_order() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let layer = d.layers[0].id;
|
||||
let inner = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art()));
|
||||
let (a, b) = (d.alloc_id(), d.alloc_id());
|
||||
let e = Node::new(
|
||||
d.alloc_id(),
|
||||
NodeKind::Envelope {
|
||||
content: vec![inner(a), inner(b)],
|
||||
kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true }),
|
||||
fidelity: 100.0,
|
||||
editing: true,
|
||||
options: Default::default(),
|
||||
frame: Box::new(vectorcraft_geom::Affine::IDENTITY),
|
||||
},
|
||||
);
|
||||
d.insert(Some(layer), usize::MAX, e).unwrap();
|
||||
let p = Point::new(25.0, 25.0);
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None));
|
||||
assert_eq!(objects_at(&d, p, opt, None), vec![b, a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_skip() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let a = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
d.node_mut(a).unwrap().locked = true;
|
||||
assert!(hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).is_none());
|
||||
d.node_mut(a).unwrap().locked = false;
|
||||
d.node_mut(l).unwrap().visible = false;
|
||||
assert!(hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).is_none());
|
||||
}
|
||||
|
||||
/// Insert `n` locked at the top of `parent`.
|
||||
fn insert_locked(d: &mut Document, parent: NodeId, mut n: Node) -> NodeId {
|
||||
let id = n.id;
|
||||
n.locked = true;
|
||||
d.insert(Some(parent), usize::MAX, n).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// `locked_objects_at`: the locked objects under the point, topmost first. A locked group is
|
||||
/// listed rather than its contents, and a locked object in an unlocked group is listed itself.
|
||||
/// Hidden objects, locked layers and the art outside an isolated group are left out.
|
||||
#[test]
|
||||
fn locked_objects_at_lists_the_locked_stack() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let rect =
|
||||
|d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art());
|
||||
let (a, b) = (rect(&mut d, 0.0), rect(&mut d, 10.0));
|
||||
let (a, b) = (insert_locked(&mut d, l, a), insert_locked(&mut d, l, b));
|
||||
let (mut inner, locked_group) = (rect(&mut d, 20.0), d.alloc_id());
|
||||
inner.locked = true;
|
||||
let inner_id = inner.id;
|
||||
let mut g = Node::group(locked_group, vec![Arc::new(inner)]);
|
||||
g.locked = true;
|
||||
d.insert(Some(l), usize::MAX, g).unwrap();
|
||||
let open_group = d.alloc_id();
|
||||
let mut child = rect(&mut d, 25.0);
|
||||
child.locked = true;
|
||||
let child_id = child.id;
|
||||
let free = rect(&mut d, 25.0);
|
||||
d.insert(Some(l), usize::MAX, Node::group(open_group, vec![Arc::new(child), Arc::new(free)])).unwrap();
|
||||
let at = |d: &Document, x: f64, scope| locked_objects_at(d, Point::new(x, 25.0), HitOptions { scope, ..HitOptions::default() });
|
||||
assert_eq!(at(&d, 30.0, None), [child_id, locked_group, b, a]);
|
||||
assert!(!at(&d, 30.0, None).contains(&inner_id), "the locked group stands for what it holds");
|
||||
assert_eq!(at(&d, 5.0, None), [a]);
|
||||
assert!(at(&d, 150.0, None).is_empty());
|
||||
// Isolated, only the group's own objects are looked at.
|
||||
assert_eq!(at(&d, 30.0, Some(open_group)), [child_id]);
|
||||
// A hidden object is left out, and nothing on a locked or hidden layer is listed.
|
||||
d.node_mut(b).unwrap().visible = false;
|
||||
assert_eq!(at(&d, 30.0, None), [child_id, locked_group, a]);
|
||||
d.node_mut(l).unwrap().locked = true;
|
||||
assert!(at(&d, 30.0, None).is_empty());
|
||||
d.node_mut(l).unwrap().locked = false;
|
||||
d.node_mut(l).unwrap().visible = false;
|
||||
assert!(at(&d, 30.0, None).is_empty());
|
||||
}
|
||||
|
||||
/// `locked_objects_at` lists at most `MAX_LOCKED_AT` objects, the topmost ones.
|
||||
#[test]
|
||||
fn locked_objects_at_stops_at_its_limit() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let l = d.layers[0].id;
|
||||
let ids: Vec<NodeId> = (0..MAX_LOCKED_AT + 5)
|
||||
.map(|_| {
|
||||
let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art());
|
||||
insert_locked(&mut d, l, n)
|
||||
})
|
||||
.collect();
|
||||
let found = locked_objects_at(&d, Point::new(25.0, 25.0), HitOptions::default());
|
||||
assert_eq!(found, ids.iter().rev().take(MAX_LOCKED_AT).copied().collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visible_sampling_reads_locked_art_and_layers_but_excludes_hidden_art() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let a = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
let p = Point::new(10.0, 10.0);
|
||||
for lock in [a, l] {
|
||||
d.node_mut(lock).unwrap().locked = true;
|
||||
assert!(hit_test(&d, p, HitOptions::default()).is_none());
|
||||
assert_eq!(hit_test_visible(&d, p, HitOptions::default()).unwrap().leaf, a);
|
||||
assert!(d.node(lock).unwrap().locked);
|
||||
d.node_mut(lock).unwrap().locked = false;
|
||||
}
|
||||
d.node_mut(a).unwrap().visible = false;
|
||||
assert!(hit_test_visible(&d, p, HitOptions::default()).is_none());
|
||||
d.node_mut(a).unwrap().visible = true;
|
||||
d.node_mut(l).unwrap().visible = false;
|
||||
assert!(hit_test_visible(&d, p, HitOptions::default()).is_none());
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,835 @@
|
||||
use super::*;
|
||||
use crate::{Appearance, Node};
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
#[test]
|
||||
fn hits_topmost() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let a = d.alloc_id();
|
||||
d.insert(Some(l), 9, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
let b = d.alloc_id();
|
||||
d.insert(Some(l), 9, Node::path(b, shapes::rectangle(Rect::new(25.0, 25.0, 75.0, 75.0)), Appearance::default_art())).unwrap();
|
||||
let h = hit_test(&d, Point::new(30.0, 30.0), HitOptions::default()).unwrap();
|
||||
assert_eq!(h.leaf, b);
|
||||
assert_eq!(h.kind, HitKind::Fill);
|
||||
let h = hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).unwrap();
|
||||
assert_eq!(h.leaf, a);
|
||||
assert!(hit_test(&d, Point::new(150.0, 150.0), HitOptions::default()).is_none());
|
||||
// Outline mode: interior misses.
|
||||
assert!(hit_test(&d, Point::new(10.0, 10.0), HitOptions { outline: true, ..Default::default() }).is_none());
|
||||
assert!(hit_test(&d, Point::new(0.5, 10.0), HitOptions { outline: true, ..Default::default() }).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unfilled_interior_misses() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let a = d.alloc_id();
|
||||
d.insert(
|
||||
Some(l),
|
||||
9,
|
||||
Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(hit_test(&d, Point::new(25.0, 25.0), HitOptions::default()).is_none());
|
||||
assert!(hit_test(&d, Point::new(50.5, 25.0), HitOptions::default()).is_some());
|
||||
}
|
||||
|
||||
/// #1103: a marquee drawn over a background picks what is on it, not the background, whose
|
||||
/// outline it doesn't touch.
|
||||
#[test]
|
||||
fn a_marquee_inside_a_background_leaves_the_background() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (back, small) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::path(back, shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default_art())).unwrap();
|
||||
d.insert(Some(l), 1, Node::path(small, shapes::rectangle(Rect::new(50.0, 50.0, 60.0, 60.0)), Appearance::default_art())).unwrap();
|
||||
assert_eq!(marquee(&d, Rect::new(40.0, 40.0, 70.0, 70.0), None, false), vec![small]);
|
||||
// Reaching the background's edge takes it too.
|
||||
assert_eq!(marquee(&d, Rect::new(-5.0, 40.0, 70.0, 70.0), None, false), vec![back, small]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_top_object() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let a = d.alloc_id();
|
||||
let g = d.alloc_id();
|
||||
let p = Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art());
|
||||
d.insert(Some(l), 0, Node::group(g, vec![Arc::new(p)])).unwrap();
|
||||
let h = hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).unwrap();
|
||||
assert_eq!(h.leaf, a);
|
||||
assert_eq!(h.top_object(None), g);
|
||||
assert_eq!(h.top_object(Some(g)), a);
|
||||
assert_eq!(marquee(&d, Rect::new(-5.0, -5.0, 5.0, 5.0), None, false), vec![g]);
|
||||
assert_eq!(marquee(&d, Rect::new(-5.0, -5.0, 5.0, 5.0), None, true), vec![a]);
|
||||
assert!(marquee(&d, Rect::new(100.0, 100.0, 105.0, 105.0), None, false).is_empty());
|
||||
}
|
||||
|
||||
/// The art of a 200 pt wide rectangle clipped to its left half (0..100 × 0..100): the mask and
|
||||
/// the art, in that order.
|
||||
fn half_clipped(d: &mut Document) -> (Node, Node) {
|
||||
let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default());
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), Appearance::default_art());
|
||||
(mask, art)
|
||||
}
|
||||
|
||||
/// #2345: a marquee touches a clip group only where its art shows. Over the clipped-away
|
||||
/// half alone it selects nothing, and around a rectangle drawn beside the group's mask it
|
||||
/// takes that rectangle alone; reaching into the mask takes the group. The same holds for
|
||||
/// Group Selection's leaves and in isolation mode.
|
||||
#[test]
|
||||
fn a_marquee_leaves_a_clip_group_by_its_clipped_away_art() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = half_clipped(&mut d);
|
||||
let (g, art_id, beside) = (d.alloc_id(), art.id, d.alloc_id());
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
d.insert(Some(l), 1, Node::path(beside, shapes::rectangle(Rect::new(150.0, 80.0, 190.0, 130.0)), Appearance::default_art())).unwrap();
|
||||
// This marquee crosses only the hidden art's top and right edges.
|
||||
let hidden = Rect::new(150.0, -10.0, 210.0, 50.0);
|
||||
assert!(marquee(&d, hidden, None, false).is_empty());
|
||||
assert!(marquee(&d, hidden, None, true).is_empty());
|
||||
assert!(marquee(&d, hidden, Some(g), false).is_empty());
|
||||
assert!(marquee(&d, hidden, Some(art_id), false).is_empty());
|
||||
// This marquee surrounds the rectangle beside and crosses the hidden art's bottom edge.
|
||||
assert_eq!(marquee(&d, Rect::new(140.0, 70.0, 195.0, 140.0), None, false), vec![beside]);
|
||||
// This marquee crosses the shown half's top edge and goes on into the hidden half.
|
||||
let shown = Rect::new(50.0, -10.0, 160.0, 10.0);
|
||||
assert_eq!(marquee(&d, shown, None, false), vec![g]);
|
||||
assert!(marquee(&d, shown, None, true).contains(&art_id));
|
||||
assert_eq!(marquee(&d, shown, Some(g), false).len(), 2, "the mask and the art");
|
||||
}
|
||||
|
||||
/// #2345: in the corner of a diamond mask's box, outside the diamond, a marquee over the
|
||||
/// clipped art's corner leaves the clip group. An open mask clips to its area closed by a
|
||||
/// straight line, and a marquee across that line takes the art it reaches inside.
|
||||
#[test]
|
||||
fn a_marquee_must_meet_the_clipping_path_itself() {
|
||||
// A clip group of a mask through `pts` (closed or open) over the art `art`.
|
||||
let clipped = |pts: &[(f64, f64)], closed: bool, art: Rect| {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut mask = vectorcraft_geom::BezPath::new();
|
||||
mask.move_to(pts[0]);
|
||||
for &p in &pts[1..] {
|
||||
mask.line_to(p);
|
||||
}
|
||||
if closed {
|
||||
mask.close_path();
|
||||
}
|
||||
let mask = Node::path(d.alloc_id(), vectorcraft_geom::PathData::from_bezpath(&mask), Appearance::default());
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(art), Appearance::default_art());
|
||||
let g = d.alloc_id();
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
(d, g)
|
||||
};
|
||||
let (d, g) = clipped(&[(50.0, 0.0), (100.0, 50.0), (50.0, 100.0), (0.0, 50.0)], true, Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
assert!(marquee(&d, Rect::new(-10.0, -10.0, 10.0, 10.0), None, false).is_empty());
|
||||
assert_eq!(marquee(&d, Rect::new(-10.0, 40.0, 10.0, 60.0), None, false), vec![g], "over the diamond's left point");
|
||||
// The mask is the triangle above the line from (0, 0) to (100, 100), and the art lies inside it.
|
||||
let (d, g) = clipped(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0)], false, Rect::new(55.0, 40.0, 70.0, 50.0));
|
||||
assert_eq!(marquee(&d, Rect::new(40.0, 45.0, 60.0, 70.0), None, false), vec![g]);
|
||||
}
|
||||
|
||||
/// #2345: the objects of a layer or sublayer with a clipping mask are touched only where the
|
||||
/// mask shows them, as in a clip group.
|
||||
#[test]
|
||||
fn a_marquee_leaves_art_a_layer_clips_away() {
|
||||
for sublayer in [false, true] {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let beside = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::path(beside, shapes::rectangle(Rect::new(150.0, 80.0, 190.0, 130.0)), Appearance::default_art())).unwrap();
|
||||
let masked = d.alloc_id();
|
||||
let mut layer = Node::layer(masked, "Masked", crate::LayerColor::Preset(2));
|
||||
layer.set_clips(true);
|
||||
d.insert(sublayer.then_some(l), 9, layer).unwrap();
|
||||
let (mask, art) = half_clipped(&mut d);
|
||||
let (mask_id, art_id) = (mask.id, art.id);
|
||||
d.insert(Some(masked), 0, mask).unwrap();
|
||||
d.insert(Some(masked), 1, art).unwrap();
|
||||
assert!(marquee(&d, Rect::new(150.0, -10.0, 210.0, 50.0), None, false).is_empty(), "sublayer: {sublayer}");
|
||||
assert_eq!(marquee(&d, Rect::new(140.0, 70.0, 195.0, 140.0), None, false), vec![beside], "sublayer: {sublayer}");
|
||||
assert_eq!(marquee(&d, Rect::new(50.0, -10.0, 160.0, 10.0), None, false), vec![mask_id, art_id], "sublayer: {sublayer}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A marquee touches a Shaper Group only by the art it shows, as clicks do ([`may_hit`]): over
|
||||
/// the original shape of a face the group erased it selects nothing, with Group Selection's
|
||||
/// leaves too, and over a face it shows it takes the group. With the original shapes isolated
|
||||
/// (Construction mode) it takes the original shape it reaches.
|
||||
#[test]
|
||||
fn a_marquee_leaves_a_shaper_group_by_its_original_shapes() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
// Two original squares, 0..100 and 50..150; the group shows only the first one's face.
|
||||
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0));
|
||||
let a = Node::path(d.alloc_id(), square(0.0), Appearance::default_art());
|
||||
let b = Node::path(d.alloc_id(), square(50.0), Appearance::default_art());
|
||||
let b_id = b.id;
|
||||
let mut sources = Node::group(d.alloc_id(), vec![Arc::new(a), Arc::new(b)]);
|
||||
sources.name = Some(crate::shaper::SOURCES.into());
|
||||
sources.opacity = 0.0;
|
||||
let sources_id = sources.id;
|
||||
let mut face = Node::path(d.alloc_id(), square(0.0), Appearance::default_art());
|
||||
face.name = Some(format!("{}0", crate::shaper::FILL_PREFIX));
|
||||
let face_id = face.id;
|
||||
let g = d.alloc_id();
|
||||
let mut group = Node::group(g, vec![Arc::new(sources), Arc::new(face)]);
|
||||
group.extras_mut().shaper = Some(Box::default());
|
||||
d.insert(Some(l), 0, group).unwrap();
|
||||
// This marquee crosses only the right edge of the second square, whose face is erased.
|
||||
let erased = Rect::new(140.0, 40.0, 160.0, 60.0);
|
||||
assert!(hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).is_none(), "a click there misses");
|
||||
assert!(marquee(&d, erased, None, false).is_empty());
|
||||
assert!(marquee(&d, erased, None, true).is_empty());
|
||||
assert!(marquee(&d, erased, Some(g), false).is_empty());
|
||||
// This marquee crosses the shown face's left edge.
|
||||
let shown = Rect::new(-10.0, 40.0, 10.0, 60.0);
|
||||
assert_eq!(marquee(&d, shown, None, false), vec![g]);
|
||||
assert_eq!(marquee(&d, shown, None, true), vec![face_id]);
|
||||
assert_eq!(marquee(&d, shown, Some(g), false), vec![face_id]);
|
||||
// Construction mode: the original shapes are the objects.
|
||||
assert_eq!(marquee(&d, erased, Some(sources_id), false), vec![b_id]);
|
||||
}
|
||||
|
||||
/// A marquee touches an Intertwine group by its members, as it touches a plain group (#1103) and
|
||||
/// as clicks do: in the gap between two members, or inside one member's fill, it selects nothing.
|
||||
/// Across a member's edge it selects the group, and with the leaves that Direct and Group
|
||||
/// Selection take, or in isolation mode, it selects the member.
|
||||
#[test]
|
||||
fn a_marquee_meets_an_intertwine_group_by_its_members() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
// Two squares, 0..100 and 150..250, with a gap between them inside the group's box.
|
||||
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 100.0, 100.0));
|
||||
let mut a = Node::path(d.alloc_id(), square(0.0), Appearance::default_art());
|
||||
a.extras_mut().intertwine = Some(Box::new(shapes::rectangle(Rect::new(50.0, 0.0, 100.0, 100.0))));
|
||||
let b = Node::path(d.alloc_id(), square(150.0), Appearance::default_art());
|
||||
let (a_id, g) = (a.id, d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::new(g, NodeKind::Intertwine { children: vec![Arc::new(a), Arc::new(b)] })).unwrap();
|
||||
let gap = Rect::new(110.0, 40.0, 140.0, 60.0);
|
||||
assert!(hit_test(&d, gap.center(), HitOptions::default()).is_none(), "a click in the gap misses");
|
||||
assert!(marquee(&d, gap, None, false).is_empty());
|
||||
assert!(marquee(&d, gap, None, true).is_empty());
|
||||
assert!(marquee(&d, gap, Some(g), false).is_empty());
|
||||
assert!(marquee(&d, Rect::new(20.0, 20.0, 40.0, 40.0), None, false).is_empty(), "inside a member's fill");
|
||||
// This marquee crosses the first square's left edge.
|
||||
let edge = Rect::new(-10.0, 40.0, 10.0, 60.0);
|
||||
assert_eq!(marquee(&d, edge, None, false), vec![g]);
|
||||
assert_eq!(marquee(&d, edge, None, true), vec![a_id]);
|
||||
assert_eq!(marquee(&d, edge, Some(g), false), vec![a_id]);
|
||||
}
|
||||
|
||||
/// A marquee touches a repeat by the copies it draws, as clicks do: between two copies of a
|
||||
/// grid repeat it selects nothing, and across a copy's edge it takes the repeat.
|
||||
#[test]
|
||||
fn a_marquee_meets_a_repeat_by_its_copies() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let source = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art());
|
||||
// Copies at 0..20, 40..60 and 80..100.
|
||||
let kind = crate::pattern::RepeatKind::Grid {
|
||||
h_spacing: 20.0,
|
||||
v_spacing: 20.0,
|
||||
rows: 1,
|
||||
cols: 3,
|
||||
grid_type: crate::pattern::TileType::Grid,
|
||||
flip_rows: false,
|
||||
flip_cols: false,
|
||||
};
|
||||
let r = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(r, NodeKind::Repeat(crate::pattern::RepeatSpec { kind, source: vec![Arc::new(source)] }))).unwrap();
|
||||
let gap = Rect::new(25.0, 5.0, 35.0, 15.0);
|
||||
assert!(hit_test(&d, gap.center(), HitOptions::default()).is_none(), "a click between copies misses");
|
||||
assert!(marquee(&d, gap, None, false).is_empty());
|
||||
assert!(marquee(&d, gap, None, true).is_empty());
|
||||
assert_eq!(marquee(&d, Rect::new(35.0, 5.0, 45.0, 15.0), None, false), vec![r], "across the second copy's left edge");
|
||||
assert_eq!(marquee(&d, Rect::new(35.0, 5.0, 45.0, 15.0), None, true), vec![r]);
|
||||
}
|
||||
|
||||
/// A blend and an envelope are clicked anywhere in their box, and a marquee touches them there
|
||||
/// too: inside the box, away from every key object's and the content's outline, it takes them.
|
||||
#[test]
|
||||
fn a_marquee_meets_blends_and_envelopes_by_their_box() {
|
||||
let mut d = Document::new(300.0, 300.0);
|
||||
let l = d.layers[0].id;
|
||||
let square = |id, x: f64, y: f64| Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), Appearance::default_art()));
|
||||
let blend = d.alloc_id();
|
||||
let keys = vec![square(d.alloc_id(), 0.0, 0.0), square(d.alloc_id(), 100.0, 0.0)];
|
||||
d.insert(Some(l), 0, Node::new(blend, NodeKind::Blend { children: keys, spec: Default::default() })).unwrap();
|
||||
let envelope = d.alloc_id();
|
||||
let content = vec![Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 150.0, 100.0, 250.0)), Appearance::default_art()))];
|
||||
let e = Node::new(
|
||||
envelope,
|
||||
NodeKind::Envelope {
|
||||
content,
|
||||
kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true }),
|
||||
fidelity: 100.0,
|
||||
editing: false,
|
||||
options: Default::default(),
|
||||
frame: Box::new(vectorcraft_geom::Affine::IDENTITY),
|
||||
},
|
||||
);
|
||||
d.insert(Some(l), 1, e).unwrap();
|
||||
for (r, id) in [(Rect::new(50.0, 5.0, 60.0, 15.0), blend), (Rect::new(40.0, 190.0, 60.0, 210.0), envelope)] {
|
||||
assert_eq!(hit_test(&d, r.center(), HitOptions::default()).map(|h| h.leaf), Some(id));
|
||||
assert_eq!(marquee(&d, r, None, false), vec![id]);
|
||||
assert_eq!(marquee(&d, r, None, true), vec![id]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A rectangle (40, 40)–(140, 140) clipping a filled 200 × 200 square drawn over its edges, in a
|
||||
/// clip group (or, `layer`, as the first layer's clipping mask): the group (or the layer), the
|
||||
/// clipping path and the art.
|
||||
fn masked_square(layer: bool) -> (Document, NodeId, NodeId, NodeId) {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (g, clip, art) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let mut path = Node::path(clip, shapes::rectangle(Rect::new(40.0, 40.0, 140.0, 140.0)), Appearance::basic(Paint::None, Paint::None, 0.0));
|
||||
if let NodeKind::Path { clipping, .. } = &mut path.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let picture = Node::path(art, shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default_art());
|
||||
if layer {
|
||||
d.insert(Some(l), 0, path).unwrap();
|
||||
d.insert(Some(l), 1, picture).unwrap();
|
||||
d.node_mut(l).unwrap().set_clips(true);
|
||||
(d, l, clip, art)
|
||||
} else {
|
||||
d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(path), Arc::new(picture)], clip: true })).unwrap();
|
||||
(d, g, clip, art)
|
||||
}
|
||||
}
|
||||
|
||||
const SELECTING: HitOptions =
|
||||
HitOptions { tol: 3.0, outline: false, path_only: false, type_path_only: false, skip_guides: false, clip_outlines: true, scope: None };
|
||||
|
||||
/// For the selection tools a clip group's clipping path is hit on its outline, within the
|
||||
/// tolerance, before the art it clips and just outside it too; inside, the art is hit.
|
||||
#[test]
|
||||
fn a_clipping_path_is_hit_on_its_outline_before_its_art() {
|
||||
let (d, g, clip, art) = masked_square(false);
|
||||
for (x, y) in [(140.0, 90.0), (141.5, 90.0), (138.5, 90.0), (90.0, 40.0)] {
|
||||
let h = hit_test(&d, Point::new(x, y), SELECTING).unwrap();
|
||||
assert_eq!((h.leaf, h.kind, h.top_object(None)), (clip, HitKind::Outline, g), "at {x}, {y}");
|
||||
}
|
||||
let h = hit_test(&d, Point::new(90.0, 90.0), SELECTING).unwrap();
|
||||
assert_eq!((h.leaf, h.top_object(None)), (art, g));
|
||||
// Beyond the tolerance outside it, the clipped art is not there to hit.
|
||||
assert!(hit_test(&d, Point::new(150.0, 90.0), SELECTING).is_none());
|
||||
}
|
||||
|
||||
/// Without `clip_outlines` (the tools that act on what is drawn) and for read-only sampling
|
||||
/// (the eyedropper), the art is hit on the mask's edge, as before: the clipping path paints
|
||||
/// nothing there.
|
||||
#[test]
|
||||
fn only_the_selection_tools_hit_a_clipping_path_on_its_outline() {
|
||||
let (d, _, clip, art) = masked_square(false);
|
||||
let p = Point::new(138.5, 90.0);
|
||||
assert_eq!(hit_test(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art));
|
||||
assert_eq!(hit_test_visible(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art));
|
||||
assert_eq!(hit_test_visible(&d, p, SELECTING).map(|h| h.leaf), Some(art));
|
||||
assert_eq!(hit_test(&d, p, SELECTING).map(|h| h.leaf), Some(clip));
|
||||
// A hidden or locked clipping path is passed over.
|
||||
for change in [|n: &mut Node| n.visible = false, |n: &mut Node| n.locked = true] {
|
||||
let mut d = d.clone();
|
||||
change(d.node_mut(clip).unwrap());
|
||||
assert_ne!(hit_test(&d, p, SELECTING).map(|h| h.leaf), Some(clip));
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer's clipping mask is hit on its outline too, and Select Behind lists what the
|
||||
/// repeated hit test finds: the mask on and just outside its edge, then the art inside it;
|
||||
/// well inside, the art alone (the mask paints nothing there).
|
||||
#[test]
|
||||
fn select_behind_takes_a_layer_masks_outline_first() {
|
||||
let (d, _, clip, art) = masked_square(true);
|
||||
for (x, want) in [(140.0, vec![clip]), (141.5, vec![clip]), (138.5, vec![clip, art]), (90.0, vec![art])] {
|
||||
let p = Point::new(x, 90.0);
|
||||
assert_eq!(objects_at(&d, p, SELECTING, None), want, "x = {x}");
|
||||
assert_eq!(objects_at_repeated(&d, p, SELECTING, None), want, "x = {x}");
|
||||
}
|
||||
// Without clip_outlines, as before.
|
||||
assert_eq!(objects_at(&d, Point::new(138.5, 90.0), HitOptions::default(), None), vec![art, clip]);
|
||||
}
|
||||
|
||||
/// Art in a sublayer is an object of its own: a click or a marquee takes it, not the
|
||||
/// sublayer; hidden, locked and template sublayers block both.
|
||||
#[test]
|
||||
fn sublayers_are_not_objects() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let sub = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::layer(sub, "Sub", crate::LayerColor::Preset(2))).unwrap();
|
||||
let inner = d.alloc_id();
|
||||
d.insert(Some(sub), 0, Node::layer(inner, "Inner", crate::LayerColor::Preset(3))).unwrap();
|
||||
let a = d.alloc_id();
|
||||
d.insert(Some(inner), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
let g = d.alloc_id();
|
||||
let b = d.alloc_id();
|
||||
let pb = Node::path(b, shapes::rectangle(Rect::new(100.0, 0.0, 150.0, 50.0)), Appearance::default_art());
|
||||
d.insert(Some(sub), 9, Node::group(g, vec![Arc::new(pb)])).unwrap();
|
||||
let h = hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).unwrap();
|
||||
assert_eq!((h.leaf, h.top_object(None), h.layers), (a, a, 3));
|
||||
let h = hit_test(&d, Point::new(110.0, 10.0), HitOptions::default()).unwrap();
|
||||
assert_eq!((h.top_object(None), h.top_object(Some(g))), (g, b));
|
||||
let all = Rect::new(-5.0, -5.0, 200.0, 200.0);
|
||||
assert_eq!(marquee(&d, all, None, false), vec![a, g]);
|
||||
assert_eq!(d.layer_containing(a), Some(inner));
|
||||
assert_eq!(d.layer_color(a), crate::LayerColor::Preset(3).rgb(), "the sublayer's own colour");
|
||||
assert_eq!(d.selectable_art(), vec![a, g]);
|
||||
for f in [
|
||||
|n: &mut Node| n.visible = false,
|
||||
|n: &mut Node| n.locked = true,
|
||||
|n: &mut Node| {
|
||||
if let NodeKind::Layer { template, .. } = &mut n.kind {
|
||||
*template = true;
|
||||
}
|
||||
},
|
||||
] {
|
||||
let mut d2 = d.clone();
|
||||
f(d2.node_mut(inner).unwrap());
|
||||
assert!(hit_test(&d2, Point::new(10.0, 10.0), HitOptions::default()).is_none());
|
||||
assert_eq!(marquee(&d2, all, None, false), vec![g]);
|
||||
assert_eq!(d2.selectable_art(), vec![g]);
|
||||
}
|
||||
// A sublayer whose Preview is off is clicked in outline: its fill no longer hits.
|
||||
if let NodeKind::Layer { preview, .. } = &mut d.node_mut(inner).unwrap().kind {
|
||||
*preview = false;
|
||||
}
|
||||
assert!(hit_test(&d, Point::new(25.0, 25.0), HitOptions::default()).is_none());
|
||||
assert!(hit_test(&d, Point::new(0.5, 25.0), HitOptions::default()).is_some());
|
||||
}
|
||||
|
||||
/// Object Selection by Path Only: a filled path or compound path hits on its outline only.
|
||||
#[test]
|
||||
fn path_only_leaves_out_fills() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (a, c) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
let inner = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 0.0, 150.0, 50.0)), Appearance::default());
|
||||
let mut compound = Node::new(c, NodeKind::Compound { children: vec![Arc::new(inner)], rule: vectorcraft_geom::FillRule::NonZero });
|
||||
compound.appearance = Appearance::default_art().into();
|
||||
d.insert(Some(l), 9, compound).unwrap();
|
||||
let path_only = HitOptions { path_only: true, ..Default::default() };
|
||||
for (id, inside, edge) in [(a, Point::new(25.0, 25.0), Point::new(0.5, 25.0)), (c, Point::new(125.0, 25.0), Point::new(100.5, 25.0))] {
|
||||
assert_eq!(hit_test(&d, inside, HitOptions::default()).map(|h| h.leaf), Some(id), "the fill hits");
|
||||
assert!(hit_test(&d, inside, path_only).is_none(), "path only: the fill of {id:?} doesn't hit");
|
||||
assert_eq!(hit_test(&d, edge, path_only).map(|h| h.leaf), Some(id), "path only: the outline does");
|
||||
}
|
||||
}
|
||||
|
||||
/// #3291: with Object Selection by Path Only, a placed image is picked on its frame's edge, so
|
||||
/// a path under it can be picked through it.
|
||||
#[test]
|
||||
fn path_only_picks_paths_through_images() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (path, image) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(l), 0, Node::path(path, shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default_art())).unwrap();
|
||||
// 100×50 pixels, scaled to 100×100 and moved to (10, 10): over the whole path.
|
||||
let xf = vectorcraft_geom::Affine::translate((10.0, 10.0)) * vectorcraft_geom::Affine::scale_non_uniform(1.0, 2.0);
|
||||
let im = crate::ImageObject { key: "k".into(), width: 100, height: 50, xf, link: None, placement: Default::default(), pixels: None };
|
||||
d.insert(Some(l), 1, Node::new(image, NodeKind::Image(Box::new(im)))).unwrap();
|
||||
let path_only = HitOptions { path_only: true, ..Default::default() };
|
||||
let hit = |p: Point, opt| hit_test(&d, p, opt).map(|h| h.leaf);
|
||||
let (path_edge, inside, image_edge) = (Point::new(20.5, 40.0), Point::new(80.0, 80.0), Point::new(80.0, 109.5));
|
||||
assert_eq!(hit(path_edge, HitOptions::default()), Some(image), "the image covers the path");
|
||||
assert_eq!(hit(inside, HitOptions::default()), Some(image));
|
||||
assert_eq!(hit(path_edge, path_only), Some(path), "path only: the path through the image");
|
||||
assert_eq!(hit(inside, path_only), None, "path only: not inside the image");
|
||||
assert_eq!(hit(image_edge, path_only), Some(image), "path only: the image's frame");
|
||||
}
|
||||
|
||||
/// Type Object Selection by Path Only: point type is picked on its baseline, area type on its
|
||||
/// frame and type on a path on its path, no longer anywhere in its bounds.
|
||||
#[test]
|
||||
fn type_path_only_picks_type_on_its_path() {
|
||||
use crate::{CharStyle, TextKind, TextObject};
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut add = |t: TextObject| {
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(l), 9, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
|
||||
id
|
||||
};
|
||||
// Point type at (10, 100), 20 pt: its glyphs rise above the baseline, its layout is 60 wide.
|
||||
let mut point = TextObject::point(Point::new(10.0, 100.0), "Hello", CharStyle { size: 20.0, ..CharStyle::default() });
|
||||
point.cached_bounds = Some(Rect::new(0.0, -16.0, 60.0, 4.0));
|
||||
let point = add(point);
|
||||
let mut area = TextObject::point(Point::new(200.0, 200.0), "Area", CharStyle::default());
|
||||
area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)) };
|
||||
let area = add(area);
|
||||
let mut on_path = TextObject::point(Point::new(10.0, 300.0), "Path", CharStyle::default());
|
||||
on_path.kind = TextKind::OnPath { path: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 40.0)), start: 0.0, end: None };
|
||||
let on_path = add(on_path);
|
||||
let path_only = HitOptions { type_path_only: true, ..Default::default() };
|
||||
let hit = |p: Point, opt: HitOptions| hit_test(&d, p, opt).map(|h| (h.leaf, h.kind));
|
||||
// Off: anywhere in the bounds.
|
||||
assert_eq!(hit(Point::new(40.0, 90.0), HitOptions::default()), Some((point, HitKind::Bounds)));
|
||||
assert_eq!(hit(Point::new(250.0, 225.0), HitOptions::default()), Some((area, HitKind::Bounds)));
|
||||
assert_eq!(hit(Point::new(60.0, 320.0), HitOptions::default()), Some((on_path, HitKind::Bounds)));
|
||||
// On: the glyphs and the inside of the frame or path no longer pick the type.
|
||||
assert_eq!(hit(Point::new(40.0, 90.0), path_only), None, "point type: among its glyphs");
|
||||
assert_eq!(hit(Point::new(250.0, 225.0), path_only), None, "area type: inside its frame");
|
||||
assert_eq!(hit(Point::new(60.0, 320.0), path_only), None, "type on a path: inside its path");
|
||||
// The baseline (within the tolerance, across the layout's width), frame and path do.
|
||||
assert_eq!(hit(Point::new(40.0, 101.5), path_only), Some((point, HitKind::Outline)), "point type: its baseline");
|
||||
assert_eq!(hit(Point::new(75.0, 100.0), path_only), None, "point type: past the end of its layout");
|
||||
assert_eq!(hit(Point::new(250.0, 200.5), path_only), Some((area, HitKind::Outline)), "area type: its frame");
|
||||
assert_eq!(hit(Point::new(60.0, 339.5), path_only), Some((on_path, HitKind::Outline)), "type on a path: its path");
|
||||
}
|
||||
|
||||
/// Type Object Selection by Path Only with the layout's baselines: every line's for point type,
|
||||
/// area type's besides its frame, a vertical column's centre line, and type in perspective
|
||||
/// where it is drawn.
|
||||
#[test]
|
||||
fn type_path_only_picks_every_baseline() {
|
||||
use crate::{CharStyle, PerspectiveAttachment, TextKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, Homography};
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut add = |t: TextObject, perspective: Option<Affine>| {
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
n.extras_mut().perspective = perspective.map(|a| {
|
||||
Box::new(PerspectiveAttachment { projection: Some(Homography::from_affine(a).to_array()), ..PerspectiveAttachment::new("left", 0.0) })
|
||||
});
|
||||
let id = n.id;
|
||||
d.insert(Some(l), 9, n).unwrap();
|
||||
id
|
||||
};
|
||||
let style = CharStyle { size: 20.0, ..CharStyle::default() };
|
||||
// Two lines of point type at (10, 100), 24 pt apart.
|
||||
let mut point = TextObject::point(
|
||||
Point::new(10.0, 100.0),
|
||||
"Hello
|
||||
world",
|
||||
style.clone(),
|
||||
);
|
||||
point.cached_bounds = Some(Rect::new(0.0, -16.0, 60.0, 28.0));
|
||||
point.cached_baselines = vec![(Point::ZERO, Point::new(60.0, 0.0)), (Point::new(0.0, 24.0), Point::new(50.0, 24.0))];
|
||||
let point = add(point, None);
|
||||
// Area type: a line inside its frame.
|
||||
let mut area = TextObject::point(Point::new(200.0, 50.0), "Area", style.clone());
|
||||
area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)) };
|
||||
area.cached_baselines = vec![(Point::new(0.0, 16.0), Point::new(40.0, 16.0))];
|
||||
let area = add(area, None);
|
||||
// Vertical point type at (300, 200) with no baselines cached: down its first column.
|
||||
let mut vertical = TextObject::point(Point::new(300.0, 200.0), "Tate", style.clone());
|
||||
vertical.vertical = true;
|
||||
vertical.cached_bounds = Some(Rect::new(-10.0, 0.0, 10.0, 80.0));
|
||||
let vertical = add(vertical, None);
|
||||
// Point type drawn 100 to the right of where it is laid out.
|
||||
let mut moved = TextObject::point(Point::new(10.0, 350.0), "Moved", style);
|
||||
moved.cached_bounds = Some(Rect::new(0.0, -16.0, 60.0, 4.0));
|
||||
let moved = add(moved, Some(Affine::translate((100.0, 0.0))));
|
||||
let path_only = HitOptions { type_path_only: true, ..Default::default() };
|
||||
let hit = |p: Point| hit_test(&d, p, path_only).map(|h| h.leaf);
|
||||
assert_eq!(hit(Point::new(40.0, 100.0)), Some(point), "the first line's baseline");
|
||||
assert_eq!(hit(Point::new(40.0, 125.0)), Some(point), "the second line's");
|
||||
assert_eq!(hit(Point::new(40.0, 112.0)), None, "between the lines");
|
||||
assert_eq!(hit(Point::new(65.0, 124.0)), None, "past the end of the shorter second line");
|
||||
assert_eq!(hit(Point::new(220.0, 66.0)), Some(area), "area type: a line's baseline");
|
||||
assert_eq!(hit(Point::new(220.0, 80.0)), None, "area type: inside the frame, off the baselines");
|
||||
assert_eq!(hit(Point::new(299.0, 260.0)), Some(vertical), "vertical type: down the column");
|
||||
assert_eq!(hit(Point::new(306.0, 260.0)), None, "vertical type: beside it");
|
||||
assert_eq!(hit(Point::new(140.0, 351.0)), Some(moved), "in perspective: where it is drawn");
|
||||
assert_eq!(hit(Point::new(40.0, 351.0)), None, "in perspective: not where it is laid out");
|
||||
}
|
||||
|
||||
/// `objects_at`: every object under the point, topmost first; a group counts once.
|
||||
#[test]
|
||||
fn objects_at_lists_the_stack() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let rect = |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art());
|
||||
let a = rect(&mut d, 0.0);
|
||||
let (b, c) = (rect(&mut d, 10.0), rect(&mut d, 20.0));
|
||||
let (a_id, b_id, c_id, g) = (a.id, b.id, c.id, d.alloc_id());
|
||||
d.insert(Some(l), 0, a).unwrap();
|
||||
d.insert(Some(l), 9, Node::group(g, vec![Arc::new(b), Arc::new(c)])).unwrap();
|
||||
let far = rect(&mut d, 120.0);
|
||||
d.insert(Some(l), 9, far).unwrap();
|
||||
let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope);
|
||||
assert_eq!(at(30.0, None), vec![g, a_id]);
|
||||
assert_eq!(at(30.0, Some(g)), [c_id, b_id], "isolated: the group's own objects");
|
||||
// Isolated, the art around the group is locked: clicks pass through it (#833).
|
||||
assert!(at(5.0, Some(g)).is_empty());
|
||||
assert!(at(130.0, Some(g)).is_empty());
|
||||
assert!(hit_test(&d, Point::new(5.0, 25.0), HitOptions { scope: Some(g), ..HitOptions::default() }).is_none());
|
||||
assert_eq!(at(5.0, None), vec![a_id]);
|
||||
assert!(at(90.0, None).is_empty());
|
||||
}
|
||||
|
||||
/// Many overlapping paths: Select Behind must list each exactly once, front to back.
|
||||
/// This is quadratic with repeated full-document hit tests, but linear in tree size with
|
||||
/// the per-object walk.
|
||||
#[test]
|
||||
fn objects_at_large_overlapping_stack() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let layer = d.layers[0].id;
|
||||
let mut ids = Vec::new();
|
||||
for _ in 0..256 {
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
ids.push(id);
|
||||
}
|
||||
ids.reverse();
|
||||
assert_eq!(objects_at(&d, Point::new(25.0, 25.0), HitOptions::default(), None), ids);
|
||||
}
|
||||
|
||||
/// Match the original skip-and-retest algorithm for normal groups, sublayers, clipping,
|
||||
/// invisibility, and path/outline-only settings.
|
||||
#[test]
|
||||
fn objects_at_one_pass_matches_repeated_hits() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let layer = d.layers[0].id;
|
||||
let add = |d: &mut Document, parent, bounds| {
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(parent), usize::MAX, Node::path(id, shapes::rectangle(bounds), Appearance::default_art())).unwrap();
|
||||
id
|
||||
};
|
||||
add(&mut d, layer, Rect::new(0.0, 0.0, 60.0, 60.0));
|
||||
let sub = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sublayer", crate::LayerColor::Preset(2))).unwrap();
|
||||
add(&mut d, sub, Rect::new(0.0, 0.0, 60.0, 60.0));
|
||||
let group = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::group(group, Vec::new())).unwrap();
|
||||
add(&mut d, group, Rect::new(0.0, 0.0, 60.0, 60.0));
|
||||
add(&mut d, group, Rect::new(5.0, 5.0, 60.0, 60.0));
|
||||
let clip = d.alloc_id();
|
||||
let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(5.0, 5.0, 45.0, 45.0)), Appearance::default_art());
|
||||
let content = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 80.0, 80.0)), Appearance::default_art());
|
||||
let mut clipping = Node::group(clip, vec![Arc::new(mask), Arc::new(content)]);
|
||||
clipping.set_clips(true);
|
||||
d.insert(Some(layer), usize::MAX, clipping).unwrap();
|
||||
for (point, opt) in [
|
||||
(Point::new(25.0, 25.0), HitOptions::default()),
|
||||
(Point::new(3.0, 25.0), HitOptions::default()),
|
||||
(Point::new(25.0, 25.0), HitOptions { outline: true, ..Default::default() }),
|
||||
(Point::new(6.0, 25.0), HitOptions { path_only: true, ..Default::default() }),
|
||||
(Point::new(100.0, 100.0), HitOptions::default()),
|
||||
] {
|
||||
assert_eq!(objects_at(&d, point, opt, None), objects_at_repeated(&d, point, opt, None), "point={point:?}, opt={opt:?}");
|
||||
}
|
||||
if let NodeKind::Layer { preview, .. } = &mut d.node_mut(sub).unwrap().kind {
|
||||
*preview = false;
|
||||
}
|
||||
let p = Point::new(25.0, 25.0);
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None));
|
||||
d.node_mut(group).unwrap().locked = true;
|
||||
assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None));
|
||||
}
|
||||
|
||||
/// Documents built at random (nested groups, sublayers, clipping groups, compound paths, blends
|
||||
/// of nothing, hidden and locked objects, outline layers): Select Behind lists the same objects
|
||||
/// in the same order as the hit test repeated over what is left.
|
||||
#[test]
|
||||
fn objects_at_matches_repeated_hits_on_random_documents() {
|
||||
let mut seed = 0x9e37_79b9_u32;
|
||||
let mut next = move |n: u32| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 17;
|
||||
seed ^= seed << 5;
|
||||
seed % n
|
||||
};
|
||||
fn fill(d: &mut Document, parent: NodeId, depth: u32, next: &mut impl FnMut(u32) -> u32) {
|
||||
for _ in 0..2 + next(4) {
|
||||
let id = d.alloc_id();
|
||||
let (x, y) = (f64::from(next(60)), f64::from(next(60)));
|
||||
let rect = Rect::new(x, y, x + 10.0 + f64::from(next(50)), y + 10.0 + f64::from(next(50)));
|
||||
let appearance = if next(4) == 0 { Appearance::default() } else { Appearance::default_art() };
|
||||
let mut n = match next(if depth < 3 { 8 } else { 4 }) {
|
||||
4 | 5 => Node::group(id, Vec::new()),
|
||||
6 => Node::layer(id, "Sublayer", crate::LayerColor::Preset(2)),
|
||||
7 => {
|
||||
let mut g = Node::group(id, Vec::new());
|
||||
g.set_clips(true);
|
||||
g
|
||||
}
|
||||
_ => Node::path(id, shapes::rectangle(rect), appearance),
|
||||
};
|
||||
n.visible = next(8) != 0;
|
||||
n.locked = next(8) == 0;
|
||||
if let NodeKind::Layer { preview, .. } = &mut n.kind {
|
||||
*preview = next(3) != 0;
|
||||
}
|
||||
let container = n.is_container();
|
||||
// A sublayer belongs in a layer; in a group it is a group like another to the hit test.
|
||||
d.insert(Some(parent), usize::MAX, n).unwrap();
|
||||
if container {
|
||||
fill(d, id, depth + 1, next);
|
||||
}
|
||||
}
|
||||
}
|
||||
for round in 0..200 {
|
||||
let mut d = Document::new(120.0, 120.0);
|
||||
let layer = d.layers[0].id;
|
||||
fill(&mut d, layer, 0, &mut next);
|
||||
// A clipping mask on the layer, or on a sublayer, now and then.
|
||||
let sublayers: Vec<NodeId> = d.layers[0].children().into_iter().flatten().filter(|n| n.is_layer()).map(|n| n.id).collect();
|
||||
for id in std::iter::once(layer).chain(sublayers) {
|
||||
if next(3) == 0 {
|
||||
d.node_mut(id).unwrap().set_clips(true);
|
||||
}
|
||||
}
|
||||
for _ in 0..12 {
|
||||
let p = Point::new(f64::from(next(120)), f64::from(next(120)));
|
||||
let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() };
|
||||
assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None), "round {round}, {p:?}, {opt:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Select Behind finds a symbol instance by its symbol's art, as a click does: art from
|
||||
/// (100, 60) to (140, 80), outside the 20 × 20 square around the origin, drawn where it lies by
|
||||
/// one instance and 100 pt lower by an instance in a group.
|
||||
#[test]
|
||||
fn objects_at_finds_symbol_instances_by_their_art() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 60.0, 140.0, 80.0)), Appearance::default_art());
|
||||
d.symbols.push(crate::Symbol { name: "Far".into(), art: Arc::new(art) });
|
||||
let (layer, top, inner, group) = (d.layers[0].id, d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let instance = |id, dy: f64| Node::new(id, NodeKind::SymbolInstance { symbol: "Far".into(), xf: vectorcraft_geom::Affine::translate((0.0, dy)) });
|
||||
d.insert(Some(layer), 0, instance(top, 0.0)).unwrap();
|
||||
d.insert(Some(layer), 1, Node::group(group, vec![Arc::new(instance(inner, 100.0))])).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
for (x, y, want) in [(120.0, 70.0, vec![top]), (120.0, 170.0, vec![group]), (0.0, 0.0, vec![]), (0.0, 100.0, vec![])] {
|
||||
let p = Point::new(x, y);
|
||||
assert_eq!(objects_at(&d, p, opt, None), want, "{p:?}");
|
||||
assert_eq!(objects_at_repeated(&d, p, opt, None), want, "{p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Edit Contents can expose descendants of a top-level group: preserve the original
|
||||
/// selection order by falling back to the general hit traversal.
|
||||
#[test]
|
||||
fn objects_at_edit_contents_uses_general_order() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let layer = d.layers[0].id;
|
||||
let inner = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art()));
|
||||
let (a, b) = (d.alloc_id(), d.alloc_id());
|
||||
let e = Node::new(
|
||||
d.alloc_id(),
|
||||
NodeKind::Envelope {
|
||||
content: vec![inner(a), inner(b)],
|
||||
kind: Box::new(crate::live::EnvelopeKind::Warp { style: "arc".to_string(), bend: 0.0, h: 0.0, v: 0.0, horizontal: true }),
|
||||
fidelity: 100.0,
|
||||
editing: true,
|
||||
options: Default::default(),
|
||||
frame: Box::new(vectorcraft_geom::Affine::IDENTITY),
|
||||
},
|
||||
);
|
||||
d.insert(Some(layer), usize::MAX, e).unwrap();
|
||||
let p = Point::new(25.0, 25.0);
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None));
|
||||
assert_eq!(objects_at(&d, p, opt, None), vec![b, a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_skip() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let a = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
d.node_mut(a).unwrap().locked = true;
|
||||
assert!(hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).is_none());
|
||||
d.node_mut(a).unwrap().locked = false;
|
||||
d.node_mut(l).unwrap().visible = false;
|
||||
assert!(hit_test(&d, Point::new(10.0, 10.0), HitOptions::default()).is_none());
|
||||
}
|
||||
|
||||
/// Insert `n` locked at the top of `parent`.
|
||||
fn insert_locked(d: &mut Document, parent: NodeId, mut n: Node) -> NodeId {
|
||||
let id = n.id;
|
||||
n.locked = true;
|
||||
d.insert(Some(parent), usize::MAX, n).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// `locked_objects_at`: the locked objects under the point, topmost first. A locked group is
|
||||
/// listed rather than its contents, and a locked object in an unlocked group is listed itself.
|
||||
/// Hidden objects, locked layers and the art outside an isolated group are left out.
|
||||
#[test]
|
||||
fn locked_objects_at_lists_the_locked_stack() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let rect = |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art());
|
||||
let (a, b) = (rect(&mut d, 0.0), rect(&mut d, 10.0));
|
||||
let (a, b) = (insert_locked(&mut d, l, a), insert_locked(&mut d, l, b));
|
||||
let (mut inner, locked_group) = (rect(&mut d, 20.0), d.alloc_id());
|
||||
inner.locked = true;
|
||||
let inner_id = inner.id;
|
||||
let mut g = Node::group(locked_group, vec![Arc::new(inner)]);
|
||||
g.locked = true;
|
||||
d.insert(Some(l), usize::MAX, g).unwrap();
|
||||
let open_group = d.alloc_id();
|
||||
let mut child = rect(&mut d, 25.0);
|
||||
child.locked = true;
|
||||
let child_id = child.id;
|
||||
let free = rect(&mut d, 25.0);
|
||||
d.insert(Some(l), usize::MAX, Node::group(open_group, vec![Arc::new(child), Arc::new(free)])).unwrap();
|
||||
let at = |d: &Document, x: f64, scope| locked_objects_at(d, Point::new(x, 25.0), HitOptions { scope, ..HitOptions::default() });
|
||||
assert_eq!(at(&d, 30.0, None), [child_id, locked_group, b, a]);
|
||||
assert!(!at(&d, 30.0, None).contains(&inner_id), "the locked group stands for what it holds");
|
||||
assert_eq!(at(&d, 5.0, None), [a]);
|
||||
assert!(at(&d, 150.0, None).is_empty());
|
||||
// Isolated, only the group's own objects are looked at.
|
||||
assert_eq!(at(&d, 30.0, Some(open_group)), [child_id]);
|
||||
// A hidden object is left out, and nothing on a locked or hidden layer is listed.
|
||||
d.node_mut(b).unwrap().visible = false;
|
||||
assert_eq!(at(&d, 30.0, None), [child_id, locked_group, a]);
|
||||
d.node_mut(l).unwrap().locked = true;
|
||||
assert!(at(&d, 30.0, None).is_empty());
|
||||
d.node_mut(l).unwrap().locked = false;
|
||||
d.node_mut(l).unwrap().visible = false;
|
||||
assert!(at(&d, 30.0, None).is_empty());
|
||||
}
|
||||
|
||||
/// `locked_objects_at` lists at most `MAX_LOCKED_AT` objects, the topmost ones.
|
||||
#[test]
|
||||
fn locked_objects_at_stops_at_its_limit() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let l = d.layers[0].id;
|
||||
let ids: Vec<NodeId> = (0..MAX_LOCKED_AT + 5)
|
||||
.map(|_| {
|
||||
let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art());
|
||||
insert_locked(&mut d, l, n)
|
||||
})
|
||||
.collect();
|
||||
let found = locked_objects_at(&d, Point::new(25.0, 25.0), HitOptions::default());
|
||||
assert_eq!(found, ids.iter().rev().take(MAX_LOCKED_AT).copied().collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visible_sampling_reads_locked_art_and_layers_but_excludes_hidden_art() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let a = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
let p = Point::new(10.0, 10.0);
|
||||
for lock in [a, l] {
|
||||
d.node_mut(lock).unwrap().locked = true;
|
||||
assert!(hit_test(&d, p, HitOptions::default()).is_none());
|
||||
assert_eq!(hit_test_visible(&d, p, HitOptions::default()).unwrap().leaf, a);
|
||||
assert!(d.node(lock).unwrap().locked);
|
||||
d.node_mut(lock).unwrap().locked = false;
|
||||
}
|
||||
d.node_mut(a).unwrap().visible = false;
|
||||
assert!(hit_test_visible(&d, p, HitOptions::default()).is_none());
|
||||
d.node_mut(a).unwrap().visible = true;
|
||||
d.node_mut(l).unwrap().visible = false;
|
||||
assert!(hit_test_visible(&d, p, HitOptions::default()).is_none());
|
||||
}
|
||||
@@ -20,8 +20,9 @@ use std::sync::{Arc, RwLock};
|
||||
|
||||
use crate::{Node, NodeId};
|
||||
|
||||
/// Hasher for node ids: one multiply. Ids are small counters, not attacker-chosen keys, and the
|
||||
/// default SipHash dominated the cost of building the cache.
|
||||
/// Hasher for node ids: one multiply, by a number chosen at random once per run (a document's ids
|
||||
/// are its author's, and a fixed multiplier lets them be picked to collide). The default SipHash
|
||||
/// dominated the cost of building the cache.
|
||||
#[derive(Default)]
|
||||
pub struct IdHasher(u64);
|
||||
|
||||
@@ -32,13 +33,19 @@ impl Hasher for IdHasher {
|
||||
}
|
||||
}
|
||||
fn write_u64(&mut self, v: u64) {
|
||||
self.0 = (self.0 ^ v).wrapping_mul(0x9e37_79b9_7f4a_7c15);
|
||||
self.0 = (self.0 ^ v).wrapping_mul(multiplier());
|
||||
}
|
||||
fn finish(&self) -> u64 {
|
||||
self.0 ^ (self.0 >> 29)
|
||||
}
|
||||
}
|
||||
|
||||
/// The odd multiplier of [`IdHasher`], random per run.
|
||||
fn multiplier() -> u64 {
|
||||
static KEY: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
|
||||
*KEY.get_or_init(|| std::hash::BuildHasher::hash_one(&std::hash::RandomState::new(), 0x9e37_79b9_7f4a_7c15_u64) | 1)
|
||||
}
|
||||
|
||||
/// A map keyed by node id with [`IdHasher`].
|
||||
pub type IdMap<V> = HashMap<NodeId, V, BuildHasherDefault<IdHasher>>;
|
||||
/// Where each node is: its parent's entry (`u32::MAX` for a top-level layer) and its index among
|
||||
|
||||
+22
-2520
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,20 @@
|
||||
use super::*;
|
||||
|
||||
/// Coordinates beyond this many points exceed the supported document range.
|
||||
pub const MAX_COORD: f64 = 4.0e6;
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||
pub enum DocError {
|
||||
#[error("no such object {0}")]
|
||||
NoNode(NodeId),
|
||||
#[error("object {0} cannot have children")]
|
||||
NotContainer(NodeId),
|
||||
#[error("{0}")]
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
pub const FORMAT_VERSION: u32 = 1;
|
||||
|
||||
/// Node, slice and asset ids are handed out below this: no document gets near it by counting, so
|
||||
/// larger ids in a file are damage (or made by hand) and the counter never follows them (#1718).
|
||||
pub(crate) const MAX_NEXT_ID: u64 = 1 << 62;
|
||||
+49
-1
@@ -139,7 +139,17 @@ fn proxy_png(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
if w.max(h) <= PROXY_SIZE {
|
||||
return None;
|
||||
}
|
||||
let small = image::load_from_memory(bytes).ok()?.thumbnail(PROXY_SIZE, PROXY_SIZE);
|
||||
// The proxy decodes within the project's raster cap, counted as RGBA like every other
|
||||
// decode path (#3597): the header alone decides whether the pixels could ever fit, and the
|
||||
// decoder gets the same budget instead of image's own default.
|
||||
if u64::from(w) * u64::from(h) > crate::MAX_RASTER_ALLOC / 4 {
|
||||
return None;
|
||||
}
|
||||
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(crate::MAX_RASTER_ALLOC);
|
||||
reader.limits(limits);
|
||||
let small = reader.decode().ok()?.thumbnail(PROXY_SIZE, PROXY_SIZE);
|
||||
let mut png = Vec::new();
|
||||
small.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
Some(png)
|
||||
@@ -432,6 +442,44 @@ mod tests {
|
||||
assert!(ImageBlob::new("image/png", vec![1, 2, 3]).with_proxy().proxy.is_none(), "undecodable");
|
||||
}
|
||||
|
||||
/// PNG CRC-32 (the same polynomial ZIP uses), so a hand-written header is one a decoder accepts.
|
||||
fn crc32(data: &[u8]) -> u32 {
|
||||
let mut crc = !0u32;
|
||||
for &b in data {
|
||||
crc ^= u32::from(b);
|
||||
for _ in 0..8 {
|
||||
crc = (crc >> 1) ^ (0xEDB8_8320 & u32::from(crc & 1 != 0).wrapping_neg());
|
||||
}
|
||||
}
|
||||
!crc
|
||||
}
|
||||
|
||||
/// A PNG header and nothing else, declaring `w` × `h` 8-bit gray pixels.
|
||||
fn png_header_declaring(w: u32, h: u32) -> Vec<u8> {
|
||||
let mut out = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
|
||||
let mut chunk = Vec::new();
|
||||
chunk.extend(b"IHDR");
|
||||
chunk.extend(w.to_be_bytes());
|
||||
chunk.extend(h.to_be_bytes());
|
||||
chunk.extend([8, 0, 0, 0, 0]);
|
||||
let crc = crc32(&chunk);
|
||||
out.extend(13u32.to_be_bytes());
|
||||
out.extend(&chunk);
|
||||
out.extend(crc.to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// A linked image past the raster cap gets no proxy: the header alone decides (#3597).
|
||||
#[test]
|
||||
fn an_image_past_the_raster_cap_gets_no_proxy() {
|
||||
// 65536 × 65536 gray pixels are 4 GiB as RGBA, past the 2 GiB cap on every target.
|
||||
let huge = png_header_declaring(1 << 16, 1 << 16);
|
||||
assert!(proxy_png(&huge).is_none());
|
||||
// A header within the cap but with no image data decodes to no preview, as before.
|
||||
let truncated = png_header_declaring(600, 300);
|
||||
assert!(proxy_png(&truncated).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_blobs_no_embedded_image_shows_are_linked_only() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
|
||||
+22
-1924
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,157 @@
|
||||
use super::*;
|
||||
|
||||
// =====================================================================================
|
||||
// Data
|
||||
// =====================================================================================
|
||||
|
||||
/// Blend Options → Spacing.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum BlendSpacing {
|
||||
/// Step count chosen from the colour difference (or the distance when colours match).
|
||||
#[default]
|
||||
SmoothColor,
|
||||
/// Specified number of steps between each pair of key objects (1–1000).
|
||||
Steps(u32),
|
||||
/// Specified distance (pt) between the steps.
|
||||
Distance(f64),
|
||||
}
|
||||
|
||||
/// Blend Options → Orientation.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum BlendOrientation {
|
||||
#[default]
|
||||
AlignToPage,
|
||||
AlignToPath,
|
||||
}
|
||||
|
||||
/// Distribution of blend steps, as offered by the Blend panel's Type menu.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum BlendEaseType {
|
||||
#[default]
|
||||
In,
|
||||
Out,
|
||||
InOut,
|
||||
OutIn,
|
||||
}
|
||||
|
||||
impl BlendEaseType {
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::In => "easeIn",
|
||||
Self::Out => "easeOut",
|
||||
Self::InOut => "easeInOut",
|
||||
Self::OutIn => "easeOutIn",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Blend panel Type and Ramp. Ramp is a fraction from 0 (even) to 1.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct BlendEase {
|
||||
#[serde(default)]
|
||||
pub kind: BlendEaseType,
|
||||
#[serde(default, deserialize_with = "blend_ramp")]
|
||||
pub ramp: f64,
|
||||
}
|
||||
|
||||
impl BlendEase {
|
||||
pub fn is_linear(&self) -> bool {
|
||||
self.ramp <= 0.0
|
||||
}
|
||||
|
||||
/// Only the default Type and Ramp can be omitted without losing a chosen Type at Ramp 0.
|
||||
pub fn is_default(&self) -> bool {
|
||||
self.kind == BlendEaseType::In && self.ramp == 0.0
|
||||
}
|
||||
|
||||
/// A monotone polynomial distribution, blended with even spacing by Ramp. Public help
|
||||
/// describes the four distributions, not their numeric curves; these curves are original.
|
||||
pub fn apply(&self, u: f64) -> f64 {
|
||||
let u = if u.is_finite() { u.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let r = if self.ramp.is_finite() { self.ramp.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let eased = match self.kind {
|
||||
BlendEaseType::In => u * u,
|
||||
BlendEaseType::Out => u * (2.0 - u),
|
||||
BlendEaseType::InOut => u * u * (3.0 - 2.0 * u),
|
||||
BlendEaseType::OutIn if u < 0.5 => 2.0 * u * (1.0 - u),
|
||||
BlendEaseType::OutIn => 0.5 + 2.0 * (u - 0.5) * (u - 0.5),
|
||||
};
|
||||
u + r * (eased - u)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct BlendSpec {
|
||||
#[serde(default)]
|
||||
pub spacing: BlendSpacing,
|
||||
#[serde(default)]
|
||||
pub orientation: BlendOrientation,
|
||||
/// Acceleration of the steps' shapes and positions along the spine between two keys.
|
||||
#[serde(default, skip_serializing_if = "BlendEase::is_default")]
|
||||
pub ease: BlendEase,
|
||||
/// Independent color acceleration. -100..100, with 0 preserving the even color ramp.
|
||||
#[serde(default, rename = "colorShift", skip_serializing_if = "is_zero", deserialize_with = "blend_color_shift")]
|
||||
pub color_shift: f64,
|
||||
/// Replaced spine. `None` = the straight lines between the key objects' centres.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub spine: Option<PathData>,
|
||||
/// The anchor of the spine's first subpath each key object sits on (a spine edited on the
|
||||
/// canvas: moving a key moves its anchor and the other way round). Empty: the keys spread
|
||||
/// evenly along the spine by arc length (Replace Spine).
|
||||
#[serde(default, rename = "keyAnchors", skip_serializing_if = "Vec::is_empty")]
|
||||
pub key_anchors: Vec<u32>,
|
||||
/// Per key object, the anchor of its first subpath the blend starts from (Blend tool clicks
|
||||
/// on anchor points); `None`: chosen so closed shapes don't twist.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub starts: Vec<Option<u32>>,
|
||||
}
|
||||
|
||||
impl BlendSpec {
|
||||
/// The start anchor of key `i` (see [`Self::starts`]).
|
||||
pub fn start(&self, i: usize) -> Option<usize> {
|
||||
self.starts.get(i).copied().flatten().map(|a| a as usize)
|
||||
}
|
||||
}
|
||||
|
||||
/// Blend Options set with no blend selected: what new blends start with.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct BlendDefaults {
|
||||
#[serde(default)]
|
||||
pub spacing: BlendSpacing,
|
||||
#[serde(default)]
|
||||
pub orientation: BlendOrientation,
|
||||
}
|
||||
|
||||
/// Reading a native file never fails over one bad blend number: out-of-range values clamp,
|
||||
/// and anything that is not a finite number (NaN, null, text) becomes the default. The
|
||||
/// commands still refuse such input (`ease_param`).
|
||||
fn blend_number<'de, D: serde::Deserializer<'de>>(d: D, min: f64, max: f64) -> Result<f64, D::Error> {
|
||||
let v = serde_json::Value::deserialize(d)?;
|
||||
Ok(v.as_f64().filter(|n| n.is_finite()).map_or(0.0, |n| n.clamp(min, max)))
|
||||
}
|
||||
|
||||
pub(super) fn blend_ramp<'de, D: serde::Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
|
||||
blend_number(d, 0.0, 1.0)
|
||||
}
|
||||
|
||||
pub(super) fn blend_color_shift<'de, D: serde::Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
|
||||
blend_number(d, -100.0, 100.0)
|
||||
}
|
||||
|
||||
/// Whether an optional stored color shift has its unchanged default.
|
||||
fn is_zero(v: &f64) -> bool {
|
||||
*v == 0.0
|
||||
}
|
||||
|
||||
impl BlendSpec {
|
||||
/// Shift the color transition independently of shape placement. The exponential curve is
|
||||
/// original; the documented behavior specifies the direction, not numeric sample values.
|
||||
pub fn color_position(&self, u: f64) -> f64 {
|
||||
let u = if u.is_finite() { u.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let shift = if self.color_shift.is_finite() { self.color_shift.clamp(-100.0, 100.0) } else { 0.0 };
|
||||
if shift == 0.0 { u } else { u.powf(2.0f64.powf(shift / 50.0)) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
use super::expand::{Hooks, Outliner, Warper, map_node};
|
||||
use super::mesh::{GradientMesh, MeshPoint, grid_len, grid_points, nodes_bounds, surface_of};
|
||||
use super::*;
|
||||
|
||||
/// How an envelope distorts its content.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum EnvelopeKind {
|
||||
/// One of the 15 warp styles (`arc`, `arcLower`, … — see [`WarpStyle::from_id`]); bend and
|
||||
/// distortions in percent (-100..100).
|
||||
Warp {
|
||||
style: String,
|
||||
#[serde(default)]
|
||||
bend: f64,
|
||||
#[serde(default)]
|
||||
h: f64,
|
||||
#[serde(default)]
|
||||
v: f64,
|
||||
#[serde(default = "yes")]
|
||||
horizontal: bool,
|
||||
},
|
||||
/// A `(rows+1)×(cols+1)` grid of points (row-major) the content's bounding box maps onto.
|
||||
Mesh {
|
||||
rows: u32,
|
||||
cols: u32,
|
||||
points: Vec<Point>,
|
||||
/// Each point's bezier handles (offsets, see [`H_RIGHT`] …), row-major like `points`.
|
||||
/// Empty: the smooth (Catmull-Rom) mesh through the points, as before handles existed;
|
||||
/// editing the mesh's points or handles on the canvas fills them in.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
handles: Vec<[Vec2; 4]>,
|
||||
},
|
||||
/// The content's bounding box maps onto the outline of this path.
|
||||
TopObject { path: PathData },
|
||||
}
|
||||
|
||||
/// Envelope Options → Preserve Shape Using: how a distorted raster keeps the envelope's shape.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PreserveShape {
|
||||
#[default]
|
||||
ClippingMask,
|
||||
Transparency,
|
||||
}
|
||||
|
||||
impl PreserveShape {
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::ClippingMask => "clippingMask",
|
||||
Self::Transparency => "transparency",
|
||||
}
|
||||
}
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
match s {
|
||||
"clippingMask" => Some(Self::ClippingMask),
|
||||
"transparency" => Some(Self::Transparency),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Envelope Options besides Fidelity. `Default` is what envelopes saved before these options
|
||||
/// existed do (their appearance applies after the distortion); new envelopes start from
|
||||
/// [`EnvelopeOptions::NEW`], as in the reference app.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct EnvelopeOptions {
|
||||
/// Rasters: Anti-Alias.
|
||||
pub anti_alias: bool,
|
||||
/// Rasters: Preserve Shape Using.
|
||||
pub preserve_shape: PreserveShape,
|
||||
/// Distort Appearance: strokes and live effects are applied before the distortion, so they
|
||||
/// bend with the art (off: they apply to the distorted paths).
|
||||
pub distort_appearance: bool,
|
||||
/// Distort Linear Gradients (with Distort Appearance): placed gradients bend with the art.
|
||||
pub distort_linear_gradients: bool,
|
||||
/// Distort Pattern Fills (with Distort Appearance): pattern tiles bend with the art.
|
||||
pub distort_pattern_fills: bool,
|
||||
}
|
||||
|
||||
impl Default for EnvelopeOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
anti_alias: true,
|
||||
preserve_shape: PreserveShape::ClippingMask,
|
||||
distort_appearance: false,
|
||||
distort_linear_gradients: false,
|
||||
distort_pattern_fills: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EnvelopeOptions {
|
||||
/// The options a new envelope gets (the reference app's defaults).
|
||||
pub const NEW: Self = Self {
|
||||
anti_alias: true,
|
||||
preserve_shape: PreserveShape::ClippingMask,
|
||||
distort_appearance: true,
|
||||
distort_linear_gradients: false,
|
||||
distort_pattern_fills: false,
|
||||
};
|
||||
/// Do gradients bend with the art?
|
||||
pub fn gradients(&self) -> bool {
|
||||
self.distort_appearance && self.distort_linear_gradients
|
||||
}
|
||||
/// Do pattern tiles bend with the art?
|
||||
pub fn patterns(&self) -> bool {
|
||||
self.distort_appearance && self.distort_pattern_fills
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle slots of a [`MeshPoint`]: towards the next column, previous column, next row, previous row.
|
||||
pub const H_RIGHT: usize = 0;
|
||||
|
||||
pub const H_LEFT: usize = 1;
|
||||
|
||||
pub const H_DOWN: usize = 2;
|
||||
|
||||
pub const H_UP: usize = 3;
|
||||
|
||||
/// The envelope's point map for content whose bounding box is `src` (page axes).
|
||||
pub fn envelope_mapper<'a>(kind: &'a EnvelopeKind, src: Rect) -> Box<dyn Fn(Point) -> Point + 'a> {
|
||||
let s = surface_of(kind, src, Affine::IDENTITY);
|
||||
let (w, h) = (src.width().max(1e-9), src.height().max(1e-9));
|
||||
Box::new(move |q: Point| s((q.x - src.x0) / w, (q.y - src.y0) / h))
|
||||
}
|
||||
|
||||
/// Catmull-Rom tangents of a `(rows+1)×(cols+1)` point grid (row-major) as mesh handles, a third
|
||||
/// of the tangent towards each neighbour (past the borders the grid goes on straight): the curves
|
||||
/// an envelope mesh without handles of its own runs along between its points.
|
||||
pub fn smooth_handles(rows: u32, cols: u32, points: &[Point]) -> Vec<[Vec2; 4]> {
|
||||
let (rows, cols) = (rows as usize, cols as usize);
|
||||
let at = |r: usize, c: usize| points.get(r * (cols + 1) + c).copied().unwrap_or_default();
|
||||
let tangent = |prev: Option<Point>, p: Point, next: Option<Point>| match (prev, next) {
|
||||
(Some(a), Some(b)) => (b - a) / 2.0,
|
||||
(None, Some(b)) => b - p,
|
||||
(Some(a), None) => p - a,
|
||||
(None, None) => Vec2::ZERO,
|
||||
};
|
||||
let mut out = Vec::with_capacity(points.len());
|
||||
for r in 0..=rows {
|
||||
for c in 0..=cols {
|
||||
let p = at(r, c);
|
||||
let du = tangent(c.checked_sub(1).map(|c| at(r, c)), p, (c < cols).then(|| at(r, c + 1))) / 3.0;
|
||||
let dv = tangent(r.checked_sub(1).map(|r| at(r, c)), p, (r < rows).then(|| at(r + 1, c))) / 3.0;
|
||||
// Handles pointing out of the grid are unused: they stay at the point.
|
||||
let keep = |inside: bool, d: Vec2| if inside { d } else { Vec2::ZERO };
|
||||
let mut h = [Vec2::ZERO; 4];
|
||||
(h[H_RIGHT], h[H_LEFT], h[H_DOWN], h[H_UP]) = (keep(c < cols, du), keep(c > 0, -du), keep(r < rows, dv), keep(r > 0, -dv));
|
||||
out.push(h);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A mesh envelope's grid (`rows`×`cols` patches, `points` and their `handles`; without handles
|
||||
/// the smooth ones, see [`smooth_handles`]) as a gradient mesh with black points: what the
|
||||
/// canvas draws and the Mesh tool and Direct Selection edit. `None` for a malformed grid.
|
||||
pub fn envelope_grid(rows: u32, cols: u32, points: &[Point], handles: &[[Vec2; 4]]) -> Option<GradientMesh> {
|
||||
if rows == 0 || cols == 0 || grid_len(rows, cols) != Some(points.len()) {
|
||||
return None;
|
||||
}
|
||||
let smooth;
|
||||
let handles = if handles.len() == points.len() {
|
||||
handles
|
||||
} else {
|
||||
smooth = smooth_handles(rows, cols, points);
|
||||
&smooth
|
||||
};
|
||||
let points = points.iter().zip(handles).map(|(p, h)| MeshPoint { p: *p, color: Color::BLACK, opacity: 1.0, handles: *h }).collect();
|
||||
Some(GradientMesh { rows, cols, points })
|
||||
}
|
||||
|
||||
/// The point of mesh `m` at (u, v) over the whole mesh (each patch an equal share; past the edges
|
||||
/// the outer patches go on).
|
||||
pub(super) fn mesh_at(m: &GradientMesh, u: f64, v: f64) -> Point {
|
||||
let (rows, cols) = (m.rows.max(1) as i64, m.cols.max(1) as i64);
|
||||
let (su, sv) = (u * cols as f64, v * rows as f64);
|
||||
let (c, r) = ((su.floor() as i64).clamp(0, cols - 1), (sv.floor() as i64).clamp(0, rows - 1));
|
||||
m.eval(r as usize, c as usize, su - c as f64, sv - r as f64)
|
||||
}
|
||||
|
||||
/// The envelope `id` is, or the innermost one it sits in.
|
||||
pub fn envelope_of(doc: &crate::Document, id: NodeId) -> Option<&Node> {
|
||||
doc.ancestry(id)?.into_iter().rev().find_map(|a| doc.node(a).filter(|n| matches!(n.kind, NodeKind::Envelope { .. })))
|
||||
}
|
||||
|
||||
/// What a selected envelope shows on the canvas: its mesh lines (a warp's surface on a 4×4 grid,
|
||||
/// a mesh envelope's own grid) or its top object's outline, and for a mesh envelope the grid to
|
||||
/// edit (its points and handles).
|
||||
pub fn envelope_overlay(n: &Node) -> Option<(PathData, Option<GradientMesh>)> {
|
||||
let NodeKind::Envelope { kind, .. } = &n.kind else { return None };
|
||||
match &**kind {
|
||||
EnvelopeKind::Mesh { rows, cols, points, handles } => {
|
||||
let grid = envelope_grid(*rows, *cols, points, handles)?;
|
||||
Some((grid.lines(), Some(grid)))
|
||||
}
|
||||
EnvelopeKind::Warp { .. } => Some((EnvelopeMap::of(n)?.surface_mesh(4, 4, Color::BLACK).lines(), None)),
|
||||
EnvelopeKind::TopObject { path } => Some((path.clone(), None)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame an envelope keeps after transform `m` (its frame so far composed with the
|
||||
/// transform): identity when its axes stay square to the page, unflipped, since evaluating on
|
||||
/// the page axes gives the same result then.
|
||||
pub fn envelope_frame(m: Affine) -> Affine {
|
||||
let [a, b, c, d, _, _] = m.as_coeffs();
|
||||
if b.abs() < 1e-12 && c.abs() < 1e-12 && a > 0.0 && d > 0.0 { Affine::IDENTITY } else { m }
|
||||
}
|
||||
|
||||
/// An envelope's point map: content placed in the envelope's own frame maps, by its bounds there,
|
||||
/// onto the unit square and from there onto the envelope's surface ([`surface_of`]).
|
||||
pub struct EnvelopeMap<'a> {
|
||||
src: Rect,
|
||||
frame: Affine,
|
||||
to_frame: Affine,
|
||||
surface: Box<dyn Fn(f64, f64) -> Point + 'a>,
|
||||
}
|
||||
|
||||
impl<'a> EnvelopeMap<'a> {
|
||||
/// The map of an envelope of `kind` around `content` with `frame`. `None` when the content
|
||||
/// has no bounds.
|
||||
pub fn new(content: &[Arc<Node>], kind: &'a EnvelopeKind, frame: Affine) -> Option<Self> {
|
||||
let frame = if frame.is_finite() && frame.determinant().abs() > 1e-12 { frame } else { Affine::IDENTITY };
|
||||
let to_frame = frame.inverse();
|
||||
let src = if frame == Affine::IDENTITY {
|
||||
nodes_bounds(content)?
|
||||
} else {
|
||||
content.iter().try_fold(None, |acc, c| {
|
||||
let mut m = (**c).clone();
|
||||
m.transform(to_frame, false);
|
||||
Some(vectorcraft_geom::union_opt(acc, m.geometric_bounds()))
|
||||
})??
|
||||
};
|
||||
Some(Self { src, frame, to_frame, surface: surface_of(kind, src, frame) })
|
||||
}
|
||||
|
||||
/// The map of envelope node `n` (`None` for other nodes).
|
||||
pub fn of(n: &'a Node) -> Option<Self> {
|
||||
match &n.kind {
|
||||
NodeKind::Envelope { content, kind, frame, .. } => Self::new(content, kind, **frame),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The content's bounds in the envelope's frame.
|
||||
pub fn src(&self) -> Rect {
|
||||
self.src
|
||||
}
|
||||
|
||||
/// The surface point at (u, v) ∈ [0,1]².
|
||||
pub fn at(&self, u: f64, v: f64) -> Point {
|
||||
(self.surface)(u, v)
|
||||
}
|
||||
|
||||
/// Where the envelope puts document point `p`.
|
||||
pub fn map(&self, p: Point) -> Point {
|
||||
let q = self.to_frame * p;
|
||||
let (w, h) = (self.src.width().max(1e-9), self.src.height().max(1e-9));
|
||||
self.at((q.x - self.src.x0) / w, (q.y - self.src.y0) / h)
|
||||
}
|
||||
|
||||
/// A flat `(rows+1)×(cols+1)` grid over the content, in the envelope's frame (row-major).
|
||||
pub fn grid(&self, rows: u32, cols: u32) -> Vec<Point> {
|
||||
grid_points(self.src, rows, cols).into_iter().map(|p| self.frame * p).collect()
|
||||
}
|
||||
|
||||
/// The surface sampled on a `rows`×`cols` grid as a mesh whose handles follow it and whose
|
||||
/// points are `color`: Release gives it back as the envelope's shape, Reset with Mesh starts
|
||||
/// from it.
|
||||
pub fn surface_mesh(&self, rows: u32, cols: u32, color: Color) -> GradientMesh {
|
||||
GradientMesh::from_surface(rows, cols, &|u, v| self.at(u, v), &|_, _| color)
|
||||
}
|
||||
|
||||
/// The surface's bounds (sampled; a mesh's points and a top object's path bound it exactly).
|
||||
fn bounds(&self) -> Option<Rect> {
|
||||
const N: usize = 16;
|
||||
let mut r: Option<Rect> = None;
|
||||
for j in 0..=N {
|
||||
for i in 0..=N {
|
||||
let q = self.at(i as f64 / N as f64, j as f64 / N as f64);
|
||||
r = Some(r.map_or(Rect::from_points(q, q), |r| r.union_pt(q)));
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate an envelope of `kind` around `content` on the page axes with the options envelopes
|
||||
/// had before Envelope Options (see [`expand_live_hooks`] for an envelope node).
|
||||
pub fn envelope_expand(content: &[Arc<Node>], kind: &EnvelopeKind, fidelity: f64, outline: Outliner) -> Vec<Node> {
|
||||
expand_envelope(content, kind, fidelity, EnvelopeOptions::default(), Affine::IDENTITY, outline.into())
|
||||
}
|
||||
|
||||
/// An envelope's content pushed through its map: Fidelity sets how finely curves are cut (and
|
||||
/// into how many pieces images are), the options what bends with the art.
|
||||
pub(super) fn expand_envelope(
|
||||
content: &[Arc<Node>],
|
||||
kind: &EnvelopeKind,
|
||||
fidelity: f64,
|
||||
options: EnvelopeOptions,
|
||||
frame: Affine,
|
||||
hooks: Hooks,
|
||||
) -> Vec<Node> {
|
||||
let Some(map) = EnvelopeMap::new(content, kind, frame) else { return content.iter().map(|c| (**c).clone()).collect() };
|
||||
let src = map.src();
|
||||
let fid = if fidelity.is_finite() { fidelity.clamp(0.0, 100.0) / 100.0 } else { 0.5 };
|
||||
let f = |p: Point| map.map(p);
|
||||
let w = Warper {
|
||||
f: &f,
|
||||
piece: src.width().hypot(src.height()).max(1e-6) / (8.0 + fid * 56.0),
|
||||
eps: (src.width().max(src.height()) * 0.05).max(0.5),
|
||||
cells: (4.0 + fid * 12.0).round() as usize,
|
||||
hooks,
|
||||
options,
|
||||
depth: 0,
|
||||
};
|
||||
content.iter().map(|c| map_node(c, &w)).collect()
|
||||
}
|
||||
|
||||
/// Envelope bounds: a mesh's points, a top object's path, the warp's surface (sampled).
|
||||
pub fn envelope_bounds(content: &[Arc<Node>], kind: &EnvelopeKind, frame: Affine) -> Option<Rect> {
|
||||
match kind {
|
||||
EnvelopeKind::Mesh { rows, cols, points, handles } if !handles.is_empty() => envelope_grid(*rows, *cols, points, handles)?.outline().bounds(),
|
||||
EnvelopeKind::Mesh { points, .. } => {
|
||||
let first = *points.first()?;
|
||||
Some(points.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)))
|
||||
}
|
||||
EnvelopeKind::TopObject { path } => path.bounds(),
|
||||
EnvelopeKind::Warp { .. } => EnvelopeMap::new(content, kind, frame)?.bounds(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
use super::envelope::{EnvelopeOptions, expand_envelope};
|
||||
use super::mesh::GradientMesh;
|
||||
use super::warp::map_nonlinear;
|
||||
use super::*;
|
||||
|
||||
/// Optional hook that converts nodes the pure evaluation can't map (text) to outlines.
|
||||
pub type Outliner<'a> = Option<&'a dyn Fn(&Node) -> Option<Node>>;
|
||||
|
||||
/// Distort Pattern Fills: the tiles pattern swatch `name` painted with placement `xf` lays over
|
||||
/// `region` (see [`crate::PatternDef::instances_in`]); `None` without such a swatch.
|
||||
pub type PatternTiles<'a> = &'a dyn Fn(&str, Affine, Rect) -> Option<Vec<Node>>;
|
||||
|
||||
/// What live evaluation asks of the crates above this one (`vectorcraft-effects` supplies them).
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct Hooks<'a> {
|
||||
/// Type as its glyph outlines, a symbol instance as its art (see [`Outliner`]).
|
||||
pub outline: Outliner<'a>,
|
||||
/// Distort Appearance: a path's strokes and geometry effects baked into filled art (`None`
|
||||
/// when it has none to bake).
|
||||
pub appearance: Outliner<'a>,
|
||||
/// Distort Pattern Fills: the tiles a pattern fill lays (see [`PatternTiles`]).
|
||||
pub pattern: Option<PatternTiles<'a>>,
|
||||
/// The document whose symbols' art counts toward the instance budget of a Repeat of their
|
||||
/// instances ([`crate::RepeatSpec::expand`]).
|
||||
pub symbols: Option<&'a crate::Document>,
|
||||
}
|
||||
|
||||
impl<'a> From<Outliner<'a>> for Hooks<'a> {
|
||||
fn from(outline: Outliner<'a>) -> Self {
|
||||
Self { outline, ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The affine map that best matches `f` near `p` (finite differences with step `eps`).
|
||||
pub fn affine_near(f: &dyn Fn(Point) -> Point, p: Point, eps: f64) -> Affine {
|
||||
let o = f(p);
|
||||
let ex = (f(p + Vec2::new(eps, 0.0)) - f(p - Vec2::new(eps, 0.0))) / (2.0 * eps);
|
||||
let ey = (f(p + Vec2::new(0.0, eps)) - f(p - Vec2::new(0.0, eps))) / (2.0 * eps);
|
||||
let lin = Affine::new([ex.x, ex.y, ey.x, ey.y, 0.0, 0.0]);
|
||||
Affine::translate(o.to_vec2()) * lin * Affine::translate(-p.to_vec2())
|
||||
}
|
||||
|
||||
/// How deep hooks may nest art inside art (symbols in symbols, envelopes in envelopes) before
|
||||
/// the rest is left as it is: a file can make a symbol contain itself.
|
||||
const MAX_HOOK_DEPTH: u32 = 16;
|
||||
|
||||
/// How an envelope pushes art through its point map.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Warper<'a> {
|
||||
pub(super) f: &'a dyn Fn(Point) -> Point,
|
||||
/// Longest piece a segment is cut into before mapping.
|
||||
pub(super) piece: f64,
|
||||
/// Finite-difference step for the local affine maps gradients follow.
|
||||
pub(super) eps: f64,
|
||||
/// Rows and columns of the pieces an image is cut into.
|
||||
pub(super) cells: usize,
|
||||
pub(super) hooks: Hooks<'a>,
|
||||
pub(super) options: EnvelopeOptions,
|
||||
/// How many hooks the art being mapped came through.
|
||||
pub(super) depth: u32,
|
||||
}
|
||||
|
||||
impl Warper<'_> {
|
||||
/// This warper one hook deeper (`None` past [`MAX_HOOK_DEPTH`]).
|
||||
fn deeper(&self) -> Option<Self> {
|
||||
(self.depth < MAX_HOOK_DEPTH).then_some(Self { depth: self.depth + 1, ..*self })
|
||||
}
|
||||
}
|
||||
|
||||
/// `to` (art standing in for `from`: its outlines, its art) with `from`'s name, transparency,
|
||||
/// opacity mask and effects.
|
||||
fn carry_look(from: &Node, mut to: Node) -> Node {
|
||||
to.name = from.name.clone();
|
||||
to.opacity = from.opacity;
|
||||
to.blend = from.blend;
|
||||
to.isolate = from.isolate;
|
||||
to.knockout = from.knockout;
|
||||
to.knockout_shape = from.knockout_shape;
|
||||
to.extras_mut().mask = from.extras().mask.clone();
|
||||
to.appearance.effects = from.appearance.effects.clone();
|
||||
to
|
||||
}
|
||||
|
||||
pub(super) fn map_node(n: &Node, w: &Warper) -> Node {
|
||||
let deeper = w.deeper();
|
||||
// Distort Appearance: strokes and geometry effects bend with the art.
|
||||
if w.options.distort_appearance
|
||||
&& let Some(d) = &deeper
|
||||
&& let Some(o) = w.hooks.appearance.and_then(|h| h(n))
|
||||
{
|
||||
return map_node(&o, d);
|
||||
}
|
||||
// Distort Pattern Fills: the tiles bend with the art (not the patterns inside them).
|
||||
if w.options.patterns()
|
||||
&& let Some(d) = &deeper
|
||||
&& let Some(o) = w.hooks.pattern.and_then(|p| pattern_art(n, p))
|
||||
{
|
||||
let inner = Warper { options: EnvelopeOptions { distort_pattern_fills: false, ..d.options }, ..*d };
|
||||
return map_node(&o, &inner);
|
||||
}
|
||||
let mut out = n.clone();
|
||||
// Distort Linear Gradients: the gradient vectors follow the warp where they sit.
|
||||
if w.options.gradients()
|
||||
&& let Some(b) = n.geometric_bounds()
|
||||
{
|
||||
out.appearance.warp_linear_gradients(b, &|p| affine_near(w.f, p, w.eps));
|
||||
}
|
||||
if let Some(m) = out.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
m.art = Arc::new(map_node(&m.art, w));
|
||||
}
|
||||
match &mut out.kind {
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
*path = map_nonlinear(path, w.piece, w.f);
|
||||
*live = None;
|
||||
}
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => {
|
||||
for c in children.iter_mut() {
|
||||
*c = Arc::new(map_node(c, w));
|
||||
}
|
||||
}
|
||||
NodeKind::Mesh(m) => m.map(w.f),
|
||||
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => {
|
||||
if let Some(d) = &deeper {
|
||||
return map_node(&expanded_group_hooks(n, w.hooks), d);
|
||||
}
|
||||
}
|
||||
NodeKind::Text(_) | NodeKind::SymbolInstance { .. } => {
|
||||
if let Some(d) = &deeper
|
||||
&& let Some(o) = w.hooks.outline.and_then(|h| h(n))
|
||||
{
|
||||
return map_node(&carry_look(n, o), d);
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
let im = im.clone();
|
||||
return warp_image(&out, &im, w);
|
||||
}
|
||||
// Its art is plain, so it warps at this depth.
|
||||
NodeKind::PlacedDocument(_) => return map_node(&expanded_group_hooks(n, w.hooks), w),
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The affine map taking triangle `s` to triangle `d` (`None` when `s` is degenerate).
|
||||
fn affine_between(s: [Point; 3], d: [Point; 3]) -> Option<Affine> {
|
||||
let basis = |p: [Point; 3]| Affine::new([p[1].x - p[0].x, p[1].y - p[0].y, p[2].x - p[0].x, p[2].y - p[0].y, p[0].x, p[0].y]);
|
||||
let bs = basis(s);
|
||||
if bs.determinant().abs() < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
let a = basis(d) * bs.inverse();
|
||||
a.is_finite().then_some(a)
|
||||
}
|
||||
|
||||
/// Image `n` (`im`) pushed through the warp as a raster mesh warp: its frame cut into
|
||||
/// `w.cells`² cells of two triangles, each a clip group showing the image under the affine map
|
||||
/// that takes the triangle where the warp takes its corners. Each piece reaches a little past its
|
||||
/// edges (at most half a point) so neighbours overlap and no seams show.
|
||||
fn warp_image(n: &Node, im: &ImageObject, w: &Warper) -> Node {
|
||||
let k = w.cells.max(1);
|
||||
// Two triangles a cell, three objects each; an image an inner envelope already cut into
|
||||
// pieces is cut again here, so the pieces count against [`MAX_GENERATED`]. Past it, the image
|
||||
// is left out.
|
||||
if !Generating::charge(k.saturating_mul(k).saturating_mul(6)) {
|
||||
let mut g = n.clone();
|
||||
g.kind = NodeKind::Group { children: vec![], clip: false };
|
||||
return g;
|
||||
}
|
||||
let (pw, ph) = (im.width as f64, im.height as f64);
|
||||
let at = |i: usize, j: usize| Point::new(pw * i as f64 / k as f64, ph * j as f64 / k as f64);
|
||||
let mut pieces = Vec::with_capacity(2 * k * k);
|
||||
for j in 0..k {
|
||||
for i in 0..k {
|
||||
let s = [at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)];
|
||||
let d = s.map(|p| (w.f)(im.xf * p));
|
||||
for t in [[0, 1, 2], [0, 2, 3]] {
|
||||
let (st, dt) = (t.map(|v| s[v]), t.map(|v| d[v]));
|
||||
let Some(xf) = affine_between(st, dt) else { continue };
|
||||
let c = Point::new((dt[0].x + dt[1].x + dt[2].x) / 3.0, (dt[0].y + dt[1].y + dt[2].y) / 3.0);
|
||||
let grow = (dt[0].distance(dt[1]).max(dt[1].distance(dt[2])) * 0.02).min(0.5);
|
||||
let tri: Vec<Point> = dt
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let v = *p - c;
|
||||
let len = v.hypot();
|
||||
if len > 1e-12 { *p + v * (grow / len) } else { *p }
|
||||
})
|
||||
.collect();
|
||||
let mut clip = Node::path(n.id, PathData::single(SubPath::polyline(&tri, true)), Appearance::default());
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() })));
|
||||
pieces.push(Arc::new(Node::new(n.id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image)], clip: true })));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut g = n.clone();
|
||||
g.kind = NodeKind::Group { children: pieces, clip: false };
|
||||
g
|
||||
}
|
||||
|
||||
/// Distort Pattern Fills: path or compound path `n` with each visible pattern fill turned into the
|
||||
/// tiles it paints in a clip group shaped like `n` (with the fill's opacity and blend mode), its
|
||||
/// other fills and strokes on copies of it, in paint order, under `n`'s transparency. `None`
|
||||
/// without a pattern fill whose definition `pattern` finds.
|
||||
fn pattern_art(n: &Node, tiles: PatternTiles) -> Option<Node> {
|
||||
let (path, rule, _) = crate::blend::node_path(n)?;
|
||||
let pattern_fill = |i: &AppearanceItem| matches!(i, AppearanceItem::Fill(f) if f.visible && matches!(f.paint, Paint::Pattern { .. }));
|
||||
if !n.appearance.items.iter().any(pattern_fill) {
|
||||
return None;
|
||||
}
|
||||
let bounds = path.bounds()?;
|
||||
let def = |i: &AppearanceItem| match i {
|
||||
AppearanceItem::Fill(f) if f.visible => match &f.paint {
|
||||
Paint::Pattern { pattern: name, xf } => tiles(name, *xf, bounds).map(|t| (t, f.opacity, f.blend)),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
let plain = |items: Vec<AppearanceItem>| {
|
||||
let mut p = Node {
|
||||
appearance: Appearance { items, ..Default::default() }.into(),
|
||||
opacity: 1.0,
|
||||
blend: Default::default(),
|
||||
isolate: false,
|
||||
knockout: Default::default(),
|
||||
knockout_shape: false,
|
||||
name: None,
|
||||
..n.clone()
|
||||
};
|
||||
p.extras_mut().mask = None;
|
||||
Arc::new(p)
|
||||
};
|
||||
let mut pieces = vec![];
|
||||
let mut rest = vec![];
|
||||
for i in &n.appearance.items {
|
||||
let Some((tiles, opacity, blend)) = def(i) else {
|
||||
rest.push(i.clone());
|
||||
continue;
|
||||
};
|
||||
if !rest.is_empty() {
|
||||
pieces.push(plain(std::mem::take(&mut rest)));
|
||||
}
|
||||
let mut clip = Node::path(n.id, path.clone(), Appearance::default());
|
||||
if let NodeKind::Path { clipping, rule: r, .. } = &mut clip.kind {
|
||||
(*clipping, *r) = (true, rule);
|
||||
}
|
||||
let children = std::iter::once(clip).chain(tiles).map(Arc::new).collect();
|
||||
let mut g = Node::new(n.id, NodeKind::Group { children, clip: true });
|
||||
g.opacity = opacity;
|
||||
g.blend = blend;
|
||||
pieces.push(Arc::new(g));
|
||||
}
|
||||
if !rest.is_empty() {
|
||||
pieces.push(plain(rest));
|
||||
}
|
||||
Some(Node {
|
||||
kind: NodeKind::Group { children: pieces, clip: false },
|
||||
appearance: Appearance { effects: n.appearance.effects.clone(), ..Default::default() }.into(),
|
||||
..n.clone()
|
||||
})
|
||||
}
|
||||
|
||||
// =====================================================================================
|
||||
// Expansion
|
||||
// =====================================================================================
|
||||
|
||||
/// Is this one of the live kinds?
|
||||
pub fn is_live(n: &Node) -> bool {
|
||||
matches!(
|
||||
n.kind,
|
||||
NodeKind::Blend { .. }
|
||||
| NodeKind::Envelope { .. }
|
||||
| NodeKind::Mesh(_)
|
||||
| NodeKind::Repeat(_)
|
||||
| NodeKind::PlacedDocument(_)
|
||||
| NodeKind::Intertwine { .. }
|
||||
)
|
||||
}
|
||||
|
||||
/// Mesh tessellation as filled quad paths (no stroke), `n`×`n` per patch.
|
||||
pub fn mesh_quad_nodes(m: &GradientMesh, n: usize) -> Vec<Node> {
|
||||
m.quads(n)
|
||||
.into_iter()
|
||||
.map(|q| {
|
||||
let mut ap = Appearance::default();
|
||||
let mut fl = FillLayer::new(Paint::solid(q.color));
|
||||
fl.opacity = q.opacity;
|
||||
ap.items.push(AppearanceItem::Fill(fl));
|
||||
Node::path(NodeId(0), PathData::single(SubPath::polyline(&q.pts, true)), ap)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One level of evaluation of a live object (non-live nodes return themselves). Blend steps and
|
||||
/// envelope results may still contain live objects (e.g. a blend of two meshes).
|
||||
pub fn expand_live(n: &Node) -> Vec<Node> {
|
||||
expand_live_with(n, None)
|
||||
}
|
||||
|
||||
pub fn expand_live_with(n: &Node, outline: Outliner) -> Vec<Node> {
|
||||
expand_live_hooks(n, outline.into())
|
||||
}
|
||||
|
||||
/// [`expand_live_with`] with everything an envelope can ask of the crates above (see [`Hooks`]).
|
||||
pub fn expand_live_hooks(n: &Node, hooks: Hooks) -> Vec<Node> {
|
||||
let _generating = Generating::enter();
|
||||
match &n.kind {
|
||||
NodeKind::Blend { children, spec } => blend_expand(children, spec),
|
||||
NodeKind::Envelope { content, kind, fidelity, options, frame, .. } => expand_envelope(content, kind, *fidelity, *options, **frame, hooks),
|
||||
NodeKind::Mesh(m) => mesh_quad_nodes(m, 8),
|
||||
NodeKind::Repeat(r) => r.expand(hooks.symbols),
|
||||
NodeKind::PlacedDocument(p) => p.art(n),
|
||||
NodeKind::Intertwine { children } => crate::intertwine::expand(children),
|
||||
_ => vec![n.clone()],
|
||||
}
|
||||
}
|
||||
|
||||
/// A live object evaluated into a plain group (keeping the object's id, name and transparency).
|
||||
pub fn expanded_group(n: &Node, outline: Outliner) -> Node {
|
||||
expanded_group_hooks(n, outline.into())
|
||||
}
|
||||
|
||||
/// [`expanded_group`] with [`Hooks`].
|
||||
pub fn expanded_group_hooks(n: &Node, hooks: Hooks) -> Node {
|
||||
let _generating = Generating::enter();
|
||||
let children = expand_live_hooks(n, hooks).into_iter().map(Arc::new).collect();
|
||||
let mut g = Node::new(n.id, NodeKind::Group { children, clip: false });
|
||||
g.name = n.name.clone();
|
||||
g.visible = n.visible;
|
||||
g.locked = n.locked;
|
||||
g.opacity = n.opacity;
|
||||
g.blend = n.blend;
|
||||
g.isolate = n.isolate;
|
||||
g.knockout = n.knockout;
|
||||
// Knocking out opaque blend steps changes nothing: don't make the outputs work for it.
|
||||
if matches!(n.kind, NodeKind::Blend { .. }) && g.knockout == crate::Knockout::On && !crate::blend::knockout_shows(&g) {
|
||||
g.knockout = crate::Knockout::Off;
|
||||
}
|
||||
g.knockout_shape = n.knockout_shape;
|
||||
g.extras_mut().mask = n.extras().mask.clone();
|
||||
g
|
||||
}
|
||||
|
||||
/// Recursively replace every live object in `n` by plain geometry (for exporters).
|
||||
pub fn expand_deep(n: &Node, outline: Outliner) -> Node {
|
||||
expand_deep_hooks(n, outline.into())
|
||||
}
|
||||
|
||||
/// [`expand_deep`] with [`Hooks`]. The objects live art makes here count against one
|
||||
/// [`MAX_GENERATED`] ([`Generating`]): blends of blends kept their inner blends live, and each
|
||||
/// copy expanded on its own, so step counts capped one by one multiplied. Past it, live art
|
||||
/// expands to nothing.
|
||||
pub fn expand_deep_hooks(n: &Node, hooks: Hooks) -> Node {
|
||||
let _generating = Generating::enter();
|
||||
let mut out = if is_live(n) {
|
||||
let g = expanded_group_hooks(n, hooks);
|
||||
if !Generating::charge(g.count()) {
|
||||
return Node::new(n.id, NodeKind::Group { children: vec![], clip: false });
|
||||
}
|
||||
g
|
||||
} else {
|
||||
n.clone()
|
||||
};
|
||||
if let Some(ch) = out.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
if subtree_has_live(c) {
|
||||
*c = Arc::new(expand_deep_hooks(c, hooks));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Most objects one evaluation of live art (an expansion, an envelope's mapping and everything
|
||||
/// inside them) may make.
|
||||
pub const MAX_GENERATED: usize = 4_000_000;
|
||||
|
||||
std::thread_local! {
|
||||
/// What is left of [`MAX_GENERATED`] for the evaluation running on this thread; `None` outside
|
||||
/// one.
|
||||
static GENERATED_LEFT: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
|
||||
}
|
||||
|
||||
/// The outermost live evaluation on this thread: it starts [`GENERATED_LEFT`] and ends it.
|
||||
struct Generating(bool);
|
||||
|
||||
impl Generating {
|
||||
fn enter() -> Self {
|
||||
let outermost = GENERATED_LEFT.get().is_none();
|
||||
if outermost {
|
||||
GENERATED_LEFT.set(Some(MAX_GENERATED));
|
||||
}
|
||||
Self(outermost)
|
||||
}
|
||||
|
||||
/// Spend `n` objects; `false` (and nothing left) when there aren't that many.
|
||||
fn charge(n: usize) -> bool {
|
||||
match GENERATED_LEFT.get() {
|
||||
None => true,
|
||||
Some(left) => {
|
||||
GENERATED_LEFT.set(Some(left.saturating_sub(n)));
|
||||
n <= left
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Generating {
|
||||
fn drop(&mut self) {
|
||||
if self.0 {
|
||||
GENERATED_LEFT.set(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `n` or any descendant need live evaluation?
|
||||
pub fn subtree_has_live(n: &Node) -> bool {
|
||||
let mut any = false;
|
||||
n.walk(&mut |c| any |= is_live(c));
|
||||
any
|
||||
}
|
||||
|
||||
/// Largest stroke outset in a subtree (for visual bounds of envelopes). With `symbols`, the
|
||||
/// outsets in the art of the symbols its instances show count too
|
||||
/// ([`crate::symbols::ArtBox::reach`]), grown by [`crate::SymbolBoxes::brush_pad`]. In boxes made
|
||||
/// by [`crate::SymbolBoxes::without_art_strokes`], the outsets in the art do not count, and the pad
|
||||
/// does.
|
||||
pub(crate) fn max_outset(nodes: &[Arc<Node>], symbols: Option<&crate::SymbolBoxes>) -> f64 {
|
||||
let mut o = 0.0f64;
|
||||
for n in nodes {
|
||||
n.walk(&mut |c| {
|
||||
o = o.max(c.appearance.outset());
|
||||
if let (Some(s), NodeKind::SymbolInstance { symbol, .. }) = (symbols, &c.kind)
|
||||
&& let Some(art) = s.art(symbol)
|
||||
{
|
||||
let reach = if s.art_strokes() { art.reach } else { 0.0 };
|
||||
o = o.max(reach + s.brush_pad(symbol));
|
||||
}
|
||||
});
|
||||
}
|
||||
o
|
||||
}
|
||||
@@ -0,0 +1,761 @@
|
||||
use super::envelope::{EnvelopeKind, H_DOWN, H_LEFT, H_RIGHT, H_UP, envelope_grid, mesh_at};
|
||||
use super::warp::{WarpStyle, flatten_subpath, resample, warp_point};
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MeshPoint {
|
||||
pub p: Point,
|
||||
pub color: Color,
|
||||
#[serde(default = "one")]
|
||||
pub opacity: f32,
|
||||
/// Tangent handles as offsets from `p` (see [`H_RIGHT`] …).
|
||||
#[serde(default)]
|
||||
pub handles: [Vec2; 4],
|
||||
}
|
||||
|
||||
/// A gradient mesh: `(rows+1)×(cols+1)` points, row-major.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct GradientMesh {
|
||||
pub rows: u32,
|
||||
pub cols: u32,
|
||||
pub points: Vec<MeshPoint>,
|
||||
}
|
||||
|
||||
/// One tessellated piece of a mesh: a small quad, its colour at the centre, and its colour and
|
||||
/// opacity at each corner (in `pts` order), which a renderer shades between so neighbouring quads
|
||||
/// meet without a step.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MeshQuad {
|
||||
pub pts: [Point; 4],
|
||||
pub color: Color,
|
||||
pub opacity: f32,
|
||||
pub corners: [(Color, f32); 4],
|
||||
}
|
||||
|
||||
/// Create Gradient Mesh → Appearance.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum MeshAppearance {
|
||||
#[default]
|
||||
Flat,
|
||||
ToCenter,
|
||||
ToEdge,
|
||||
}
|
||||
|
||||
impl MeshAppearance {
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
match s.to_ascii_lowercase().as_str() {
|
||||
"flat" => Some(Self::Flat),
|
||||
"center" | "tocenter" | "to center" => Some(Self::ToCenter),
|
||||
"edge" | "toedge" | "to edge" => Some(Self::ToEdge),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Default envelope fidelity.
|
||||
pub fn default_fidelity() -> f64 {
|
||||
fifty()
|
||||
}
|
||||
|
||||
const SIDE: usize = 65;
|
||||
|
||||
/// Four boundary curves (top TL→TR, right TR→BR, bottom BL→BR, left TL→BL), each resampled to
|
||||
/// [`SIDE`] points, from the outline of a closed path split at the points nearest its bounding
|
||||
/// box corners.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Coons {
|
||||
top: Vec<Point>,
|
||||
right: Vec<Point>,
|
||||
bottom: Vec<Point>,
|
||||
left: Vec<Point>,
|
||||
}
|
||||
|
||||
impl Coons {
|
||||
/// A rectangle.
|
||||
pub fn rect(r: Rect) -> Self {
|
||||
let line = |a: Point, b: Point| (0..SIDE).map(|i| a.lerp(b, i as f64 / (SIDE - 1) as f64)).collect::<Vec<_>>();
|
||||
let (tl, tr, br, bl) = (Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1));
|
||||
Self { top: line(tl, tr), right: line(tr, br), bottom: line(bl, br), left: line(tl, bl) }
|
||||
}
|
||||
|
||||
pub fn from_path(path: &PathData) -> Option<Self> {
|
||||
// The largest subpath is the outline.
|
||||
let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?;
|
||||
let r = path.bounds()?;
|
||||
let tol = (r.width() + r.height()).max(1e-6) / 2000.0;
|
||||
let mut poly = flatten_subpath(sp, tol);
|
||||
if poly.len() > 1
|
||||
&& let (Some(a), Some(b)) = (poly.first(), poly.last())
|
||||
&& a.distance(*b) < 1e-9
|
||||
{
|
||||
poly.pop();
|
||||
}
|
||||
if poly.len() < 3 {
|
||||
return Some(Self::rect(r));
|
||||
}
|
||||
// Orient clockwise in y-down (TL → TR → BR → BL).
|
||||
let area: f64 = (0..poly.len())
|
||||
.map(|i| {
|
||||
let (p, q) = (poly[i], poly[(i + 1) % poly.len()]);
|
||||
p.x * q.y - q.x * p.y
|
||||
})
|
||||
.sum();
|
||||
if area < 0.0 {
|
||||
poly.reverse();
|
||||
}
|
||||
let nearest = |c: Point| (0..poly.len()).min_by(|i, j| poly[*i].distance_squared(c).total_cmp(&poly[*j].distance_squared(c))).unwrap_or(0);
|
||||
let tl = nearest(Point::new(r.x0, r.y0));
|
||||
let tr = nearest(Point::new(r.x1, r.y0));
|
||||
let br = nearest(Point::new(r.x1, r.y1));
|
||||
let bl = nearest(Point::new(r.x0, r.y1));
|
||||
let n = poly.len();
|
||||
let arc = |i: usize, j: usize| -> Vec<Point> {
|
||||
let mut v = vec![poly[i]];
|
||||
let mut k = i;
|
||||
while k != j {
|
||||
k = (k + 1) % n;
|
||||
v.push(poly[k]);
|
||||
}
|
||||
v
|
||||
};
|
||||
let top = resample(&arc(tl, tr), SIDE);
|
||||
let right = resample(&arc(tr, br), SIDE);
|
||||
let mut bottom = resample(&arc(br, bl), SIDE);
|
||||
bottom.reverse();
|
||||
let mut left = resample(&arc(bl, tl), SIDE);
|
||||
left.reverse();
|
||||
Some(Self { top, right, bottom, left })
|
||||
}
|
||||
|
||||
/// The point at `u` along a side; past its ends the end segments go on straight (art an
|
||||
/// envelope bends can reach past the content's box: outlined strokes).
|
||||
fn sample(side: &[Point], u: f64) -> Point {
|
||||
let s = u * (side.len() - 1) as f64;
|
||||
let i = (s.floor().max(0.0) as usize).min(side.len() - 2);
|
||||
side[i].lerp(side[i + 1], s - i as f64)
|
||||
}
|
||||
|
||||
/// The surface point at (u, v) ∈ [0,1]².
|
||||
pub fn eval(&self, u: f64, v: f64) -> Point {
|
||||
let (t, b, l, r) = (Self::sample(&self.top, u), Self::sample(&self.bottom, u), Self::sample(&self.left, v), Self::sample(&self.right, v));
|
||||
let (p00, p10, p01, p11) = (self.top[0], self.top[SIDE - 1], self.bottom[0], self.bottom[SIDE - 1]);
|
||||
let c = (1.0 - v) * t.to_vec2() + v * b.to_vec2() + (1.0 - u) * l.to_vec2() + u * r.to_vec2()
|
||||
- ((1.0 - u) * (1.0 - v) * p00.to_vec2() + u * (1.0 - v) * p10.to_vec2() + (1.0 - u) * v * p01.to_vec2() + u * v * p11.to_vec2());
|
||||
c.to_point()
|
||||
}
|
||||
|
||||
/// The four corners TL, TR, BR, BL.
|
||||
pub fn corners(&self) -> [Point; 4] {
|
||||
[self.top[0], self.top[SIDE - 1], self.bottom[SIDE - 1], self.bottom[0]]
|
||||
}
|
||||
}
|
||||
|
||||
// =====================================================================================
|
||||
// Gradient meshes
|
||||
// =====================================================================================
|
||||
|
||||
/// `0, 1/n, …, 1` for `n` (clamped to 1..=200) even steps.
|
||||
fn even_steps(n: u32) -> Vec<f64> {
|
||||
let n = n.clamp(1, 200);
|
||||
(0..=n).map(|i| i as f64 / n as f64).collect()
|
||||
}
|
||||
|
||||
/// The number of points of a `(rows+1)×(cols+1)` grid, `None` past `usize`: counts come from
|
||||
/// files, and u32::MAX rows and columns (65,535 on 32-bit targets) would wrap to an empty grid.
|
||||
pub(super) fn grid_len(rows: u32, cols: u32) -> Option<usize> {
|
||||
(rows as usize).checked_add(1)?.checked_mul((cols as usize).checked_add(1)?)
|
||||
}
|
||||
|
||||
impl GradientMesh {
|
||||
pub fn idx(&self, r: usize, c: usize) -> usize {
|
||||
r * (self.cols as usize + 1) + c
|
||||
}
|
||||
pub fn is_valid(&self) -> bool {
|
||||
self.rows >= 1 && self.cols >= 1 && grid_len(self.rows, self.cols) == Some(self.points.len())
|
||||
}
|
||||
|
||||
/// A 1×1 mesh from its four corners (bottom-left, top-left, top-right, bottom-right in u/v
|
||||
/// order: row 0 is v = 0, columns follow u), each with its handles ([`H_RIGHT`] …).
|
||||
fn patch(corners: [(Point, [Vec2; 4], Color); 4]) -> Self {
|
||||
let point = |(p, handles, color): (Point, [Vec2; 4], Color)| MeshPoint { p, color, opacity: 1.0, handles };
|
||||
let [a, b, c, d] = corners;
|
||||
Self { rows: 1, cols: 1, points: vec![point(a), point(d), point(b), point(c)] }
|
||||
}
|
||||
|
||||
/// A 1×1 mesh from a Coons patch's twelve boundary points (in the order PDF and PostScript
|
||||
/// shadings list them: v runs cp0 → cp3 along cp1 and cp2, u runs cp0 → cp9 along cp11 and
|
||||
/// cp10) and its corner colours (at cp0, cp3, cp6, cp9); `None` if a point isn't finite.
|
||||
pub fn coons(cp: &[Point; 12], colors: [Color; 4]) -> Option<Self> {
|
||||
if !cp.iter().all(|p| p.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let h = |a: usize, b: usize| cp[b] - cp[a];
|
||||
let handles = |right: Vec2, left: Vec2, down: Vec2, up: Vec2| {
|
||||
let mut h = [Vec2::ZERO; 4];
|
||||
(h[H_RIGHT], h[H_LEFT], h[H_DOWN], h[H_UP]) = (right, left, down, up);
|
||||
h
|
||||
};
|
||||
let [c0, c1, c2, c3] = colors;
|
||||
Some(Self::patch([
|
||||
(cp[0], handles(h(0, 11), Vec2::ZERO, h(0, 1), Vec2::ZERO), c0),
|
||||
(cp[3], handles(h(3, 4), Vec2::ZERO, Vec2::ZERO, h(3, 2)), c1),
|
||||
(cp[6], handles(Vec2::ZERO, h(6, 5), Vec2::ZERO, h(6, 7)), c2),
|
||||
(cp[9], handles(Vec2::ZERO, h(9, 10), h(9, 8), Vec2::ZERO), c3),
|
||||
]))
|
||||
}
|
||||
|
||||
/// A 1×1 mesh of a Gouraud-shaded triangle (a patch with two corners together); `None` if a
|
||||
/// point isn't finite.
|
||||
pub fn triangle(corners: [(Point, Color); 3]) -> Option<Self> {
|
||||
if !corners.iter().all(|(p, _)| p.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let [a, b, c] = corners.map(|(p, color)| (p, [Vec2::ZERO; 4], color));
|
||||
Some(Self::patch([a, b, c, c]))
|
||||
}
|
||||
|
||||
/// A mesh over surface `s` (u, v ∈ [0,1]) with handles from its partial derivatives.
|
||||
pub fn from_surface(rows: u32, cols: u32, s: &dyn Fn(f64, f64) -> Point, color: &dyn Fn(f64, f64) -> Color) -> Self {
|
||||
let (us, vs) = (even_steps(cols), even_steps(rows));
|
||||
Self::from_grid(&us, &vs, s, &|r, c, _| (color(us[c], vs[r]), 1.0))
|
||||
}
|
||||
|
||||
/// A mesh over surface `s` (u, v ∈ [0,1]) whose column lines sit at `us` and row lines at `vs`
|
||||
/// (ascending, at least two each; equal neighbours make a patch of no width, a sharp colour
|
||||
/// change), with handles from its partial derivatives. `color(row, col, point)` gives each
|
||||
/// point its colour and opacity.
|
||||
pub fn from_grid(us: &[f64], vs: &[f64], s: &dyn Fn(f64, f64) -> Point, color: &dyn Fn(usize, usize, Point) -> (Color, f32)) -> Self {
|
||||
let (rows, cols) = (vs.len().saturating_sub(1), us.len().saturating_sub(1));
|
||||
let eps = 1e-3;
|
||||
let mut points = Vec::with_capacity(us.len() * vs.len());
|
||||
for (r, &v) in vs.iter().enumerate() {
|
||||
for (c, &u) in us.iter().enumerate() {
|
||||
let p = s(u, v);
|
||||
let d_u = (s((u + eps).min(1.0), v) - s((u - eps).max(0.0), v)) / ((u + eps).min(1.0) - (u - eps).max(0.0));
|
||||
let d_v = (s(u, (v + eps).min(1.0)) - s(u, (v - eps).max(0.0))) / ((v + eps).min(1.0) - (v - eps).max(0.0));
|
||||
// A third of the way to the neighbouring line along the tangent; outward handles on
|
||||
// the border are unused, so they stay at the point.
|
||||
let h = |d: Vec2, from: f64, to: Option<&f64>| to.map_or(Vec2::ZERO, |to| d * ((to - from) / 3.0));
|
||||
let handles = [
|
||||
h(d_u, u, us.get(c + 1)),
|
||||
h(d_u, u, c.checked_sub(1).map(|i| &us[i])),
|
||||
h(d_v, v, vs.get(r + 1)),
|
||||
h(d_v, v, r.checked_sub(1).map(|i| &vs[i])),
|
||||
];
|
||||
let (color, opacity) = color(r, c, p);
|
||||
points.push(MeshPoint { p, color, opacity, handles });
|
||||
}
|
||||
}
|
||||
Self { rows: rows as u32, cols: cols as u32, points }
|
||||
}
|
||||
|
||||
/// Create Gradient Mesh for a path: the outline split at its corners, coloured per `appearance`.
|
||||
pub fn for_path(path: &PathData, rows: u32, cols: u32, base: Color, appearance: MeshAppearance, highlight: f64) -> Option<Self> {
|
||||
let mut m = Self::for_path_with(path, rows, cols, &|_| (base, 1.0))?;
|
||||
m.highlight(appearance, highlight);
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// Create Gradient Mesh for a path: the outline split at its corners, each point taking the
|
||||
/// colour and opacity `color_at` gives at its position (a gradient fill's, say).
|
||||
pub fn for_path_with(path: &PathData, rows: u32, cols: u32, color_at: &dyn Fn(Point) -> (Color, f32)) -> Option<Self> {
|
||||
let coons = Coons::from_path(path)?;
|
||||
Some(Self::from_grid(&even_steps(cols), &even_steps(rows), &|u, v| coons.eval(u, v), &|_, _, p| color_at(p)))
|
||||
}
|
||||
|
||||
/// Create Gradient Mesh → Appearance: lighten the points towards white, to the centre or to
|
||||
/// the edges, by at most `highlight` %.
|
||||
pub fn highlight(&mut self, appearance: MeshAppearance, highlight: f64) {
|
||||
let h = (highlight / 100.0).clamp(0.0, 1.0) as f32;
|
||||
let (rows, cols) = (self.rows as usize, self.cols as usize);
|
||||
for r in 0..=rows {
|
||||
for c in 0..=cols {
|
||||
let (u, v) = (c as f64 / cols as f64, r as f64 / rows as f64);
|
||||
let d = ((u - 0.5).abs().max((v - 0.5).abs()) * 2.0) as f32; // 0 centre … 1 edge
|
||||
let w = match appearance {
|
||||
MeshAppearance::Flat => 0.0,
|
||||
MeshAppearance::ToCenter => (1.0 - d) * h,
|
||||
MeshAppearance::ToEdge => d * h,
|
||||
};
|
||||
if w > 0.0 {
|
||||
let i = self.idx(r, c);
|
||||
self.points[i].color = lerp_color(&self.points[i].color, &Color::WHITE, w);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Horizontal edge from (r, c) to (r, c+1).
|
||||
pub fn edge_u(&self, r: usize, c: usize) -> CubicBez {
|
||||
let (a, b) = (&self.points[self.idx(r, c)], &self.points[self.idx(r, c + 1)]);
|
||||
CubicBez::new(a.p, a.p + a.handles[H_RIGHT], b.p + b.handles[H_LEFT], b.p)
|
||||
}
|
||||
/// Vertical edge from (r, c) to (r+1, c).
|
||||
pub fn edge_v(&self, r: usize, c: usize) -> CubicBez {
|
||||
let (a, b) = (&self.points[self.idx(r, c)], &self.points[self.idx(r + 1, c)]);
|
||||
CubicBez::new(a.p, a.p + a.handles[H_DOWN], b.p + b.handles[H_UP], b.p)
|
||||
}
|
||||
|
||||
/// Coons patch point of patch (r, c) at local (u, v).
|
||||
pub fn eval(&self, r: usize, c: usize, u: f64, v: f64) -> Point {
|
||||
let (t, b) = (self.edge_u(r, c).eval(u), self.edge_u(r + 1, c).eval(u));
|
||||
let (l, rr) = (self.edge_v(r, c).eval(v), self.edge_v(r, c + 1).eval(v));
|
||||
let p00 = self.points[self.idx(r, c)].p.to_vec2();
|
||||
let p10 = self.points[self.idx(r, c + 1)].p.to_vec2();
|
||||
let p01 = self.points[self.idx(r + 1, c)].p.to_vec2();
|
||||
let p11 = self.points[self.idx(r + 1, c + 1)].p.to_vec2();
|
||||
((1.0 - v) * t.to_vec2() + v * b.to_vec2() + (1.0 - u) * l.to_vec2() + u * rr.to_vec2()
|
||||
- ((1.0 - u) * (1.0 - v) * p00 + u * (1.0 - v) * p10 + (1.0 - u) * v * p01 + u * v * p11))
|
||||
.to_point()
|
||||
}
|
||||
|
||||
/// Bilinear colour and opacity of patch (r, c) at local (u, v). Corners all in CMYK (or all
|
||||
/// grey) mix in that space, as a PDF shading mixes in its own colour space: the inks come out
|
||||
/// exact, and a CMYK document separates no colour to draw them. Other corners mix in RGB.
|
||||
pub fn color_at(&self, r: usize, c: usize, u: f64, v: f64) -> (Color, f32) {
|
||||
let q =
|
||||
[&self.points[self.idx(r, c)], &self.points[self.idx(r, c + 1)], &self.points[self.idx(r + 1, c)], &self.points[self.idx(r + 1, c + 1)]];
|
||||
let w = [(1.0 - u) * (1.0 - v), u * (1.0 - v), (1.0 - u) * v, u * v];
|
||||
let op = q.iter().zip(w).map(|(p, w)| p.opacity * w as f32).sum();
|
||||
let cmyk: Option<Vec<[f32; 4]>> =
|
||||
q.iter().map(|p| if let Color::Cmyk { c, m, y, k } = p.color { Some([c, m, y, k]) } else { None }).collect();
|
||||
if let Some(inks) = cmyk {
|
||||
let mut mix = [0.0f32; 4];
|
||||
for (ink, w) in inks.iter().zip(w) {
|
||||
for (m, x) in mix.iter_mut().zip(ink) {
|
||||
*m += x * w as f32;
|
||||
}
|
||||
}
|
||||
let [c, m, y, k] = mix;
|
||||
return (Color::Cmyk { c, m, y, k }, op);
|
||||
}
|
||||
let grey: Option<Vec<f32>> = q.iter().map(|p| if let Color::Gray { k } = p.color { Some(k) } else { None }).collect();
|
||||
if let Some(ks) = grey {
|
||||
return (Color::Gray { k: ks.iter().zip(w).map(|(k, w)| k * w as f32).sum() }, op);
|
||||
}
|
||||
let mut rgb = [0.0f32; 3];
|
||||
for (p, w) in q.iter().zip(w) {
|
||||
for (ch, x) in rgb.iter_mut().zip(p.color.to_rgb()) {
|
||||
*ch += x * w as f32;
|
||||
}
|
||||
}
|
||||
(Color::rgb(rgb[0], rgb[1], rgb[2]), op)
|
||||
}
|
||||
|
||||
/// Tessellate into `n`×`n` quads per patch, each coloured at its centre and its corners.
|
||||
pub fn quads(&self, n: usize) -> Vec<MeshQuad> {
|
||||
if !self.is_valid() {
|
||||
return vec![];
|
||||
}
|
||||
let n = n.clamp(1, 64);
|
||||
let mut out = Vec::with_capacity(self.rows as usize * self.cols as usize * n * n);
|
||||
let mut grid = vec![Point::ZERO; (n + 1) * (n + 1)];
|
||||
let mut colors = vec![(Color::default(), 0.0f32); (n + 1) * (n + 1)];
|
||||
for r in 0..self.rows as usize {
|
||||
for c in 0..self.cols as usize {
|
||||
for j in 0..=n {
|
||||
for i in 0..=n {
|
||||
let (u, v) = (i as f64 / n as f64, j as f64 / n as f64);
|
||||
grid[j * (n + 1) + i] = self.eval(r, c, u, v);
|
||||
colors[j * (n + 1) + i] = self.color_at(r, c, u, v);
|
||||
}
|
||||
}
|
||||
for j in 0..n {
|
||||
for i in 0..n {
|
||||
let (color, opacity) = self.color_at(r, c, (i as f64 + 0.5) / n as f64, (j as f64 + 0.5) / n as f64);
|
||||
let g = |a: usize, b: usize| grid[b * (n + 1) + a];
|
||||
let k = |a: usize, b: usize| colors[b * (n + 1) + a];
|
||||
out.push(MeshQuad {
|
||||
pts: [g(i, j), g(i + 1, j), g(i + 1, j + 1), g(i, j + 1)],
|
||||
color,
|
||||
opacity,
|
||||
corners: [k(i, j), k(i + 1, j), k(i + 1, j + 1), k(i, j + 1)],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The mesh's outer boundary as a closed path.
|
||||
pub fn outline(&self) -> PathData {
|
||||
if !self.is_valid() {
|
||||
return PathData::default();
|
||||
}
|
||||
let (rows, cols) = (self.rows as usize, self.cols as usize);
|
||||
let mut segs: Vec<CubicBez> = vec![];
|
||||
for c in 0..cols {
|
||||
segs.push(self.edge_u(0, c));
|
||||
}
|
||||
for r in 0..rows {
|
||||
segs.push(self.edge_v(r, cols));
|
||||
}
|
||||
for c in (0..cols).rev() {
|
||||
let e = self.edge_u(rows, c);
|
||||
segs.push(CubicBez::new(e.p3, e.p2, e.p1, e.p0));
|
||||
}
|
||||
for r in (0..rows).rev() {
|
||||
let e = self.edge_v(r, 0);
|
||||
segs.push(CubicBez::new(e.p3, e.p2, e.p1, e.p0));
|
||||
}
|
||||
let mut anchors: Vec<Anchor> = Vec::with_capacity(segs.len());
|
||||
for (i, s) in segs.iter().enumerate() {
|
||||
let prev = &segs[(i + segs.len() - 1) % segs.len()];
|
||||
anchors.push(Anchor::with_handles(s.p0, prev.p2, s.p1));
|
||||
}
|
||||
PathData::single(SubPath::new(anchors, true))
|
||||
}
|
||||
|
||||
/// Mesh lines (all row and column edges) as open paths, for outline view and editing overlays.
|
||||
pub fn lines(&self) -> PathData {
|
||||
if !self.is_valid() {
|
||||
return PathData::default();
|
||||
}
|
||||
let (rows, cols) = (self.rows as usize, self.cols as usize);
|
||||
let mut subs = vec![];
|
||||
let cub = |e: CubicBez| SubPath::new(vec![Anchor::with_handles(e.p0, e.p0, e.p1), Anchor::with_handles(e.p3, e.p2, e.p3)], false);
|
||||
for r in 0..=rows {
|
||||
for c in 0..cols {
|
||||
subs.push(cub(self.edge_u(r, c)));
|
||||
}
|
||||
}
|
||||
for c in 0..=cols {
|
||||
for r in 0..rows {
|
||||
subs.push(cub(self.edge_v(r, c)));
|
||||
}
|
||||
}
|
||||
PathData::new(subs)
|
||||
}
|
||||
|
||||
/// Control bounds (points and handles).
|
||||
pub fn bounds(&self) -> Option<Rect> {
|
||||
let mut it = self.points.iter().flat_map(|p| std::iter::once(p.p).chain(p.handles.iter().map(move |h| p.p + *h)));
|
||||
let first = it.next()?;
|
||||
Some(it.fold(Rect::from_points(first, first), |r, q| r.union_pt(q)))
|
||||
}
|
||||
|
||||
pub fn transform(&mut self, a: Affine) {
|
||||
let lin = Affine::new({
|
||||
let c = a.as_coeffs();
|
||||
[c[0], c[1], c[2], c[3], 0.0, 0.0]
|
||||
});
|
||||
for p in &mut self.points {
|
||||
p.p = a * p.p;
|
||||
for h in &mut p.handles {
|
||||
*h = (lin * h.to_point()).to_vec2();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Map points (and handle ends) through a non-linear function.
|
||||
pub fn map(&mut self, f: &dyn Fn(Point) -> Point) {
|
||||
for p in &mut self.points {
|
||||
let q = f(p.p);
|
||||
for h in &mut p.handles {
|
||||
*h = f(p.p + *h) - q;
|
||||
}
|
||||
p.p = q;
|
||||
}
|
||||
}
|
||||
|
||||
/// Which patch and local (u, v) contains `p` (sampled search; `None` outside the mesh).
|
||||
pub fn locate(&self, p: Point) -> Option<(usize, usize, f64, f64)> {
|
||||
if !self.is_valid() {
|
||||
return None;
|
||||
}
|
||||
let bp = self.outline().to_bezpath();
|
||||
if bp.winding(p) == 0 {
|
||||
return None;
|
||||
}
|
||||
const N: usize = 16;
|
||||
let mut best = (f64::INFINITY, 0, 0, 0.0, 0.0);
|
||||
for r in 0..self.rows as usize {
|
||||
for c in 0..self.cols as usize {
|
||||
for j in 0..=N {
|
||||
for i in 0..=N {
|
||||
let (u, v) = (i as f64 / N as f64, j as f64 / N as f64);
|
||||
let d = self.eval(r, c, u, v).distance_squared(p);
|
||||
if d < best.0 {
|
||||
best = (d, r, c, u, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Refine with a few Newton-free local searches.
|
||||
let (_, r, c, mut u, mut v) = best;
|
||||
let mut step = 0.5 / N as f64;
|
||||
for _ in 0..12 {
|
||||
let mut improved = false;
|
||||
for (du, dv) in [(step, 0.0), (-step, 0.0), (0.0, step), (0.0, -step)] {
|
||||
let (nu, nv) = ((u + du).clamp(0.0, 1.0), (v + dv).clamp(0.0, 1.0));
|
||||
if self.eval(r, c, nu, nv).distance_squared(p) < self.eval(r, c, u, v).distance_squared(p) {
|
||||
u = nu;
|
||||
v = nv;
|
||||
improved = true;
|
||||
}
|
||||
}
|
||||
if !improved {
|
||||
step /= 2.0;
|
||||
}
|
||||
}
|
||||
Some((r, c, u, v))
|
||||
}
|
||||
|
||||
/// Index of the mesh point within `tol` of `p`.
|
||||
pub fn point_near(&self, p: Point, tol: f64) -> Option<usize> {
|
||||
self.points
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, q)| q.p.distance(p) <= tol)
|
||||
.min_by(|a, b| a.1.p.distance(p).total_cmp(&b.1.p.distance(p)))
|
||||
.map(|(i, _)| i)
|
||||
}
|
||||
|
||||
fn surface_du(&self, r: usize, c: usize, u: f64, v: f64) -> Vec2 {
|
||||
let e = 1e-3;
|
||||
let (a, b) = ((u - e).max(0.0), (u + e).min(1.0));
|
||||
(self.eval(r, c, b, v) - self.eval(r, c, a, v)) / (b - a)
|
||||
}
|
||||
fn surface_dv(&self, r: usize, c: usize, u: f64, v: f64) -> Vec2 {
|
||||
let e = 1e-3;
|
||||
let (a, b) = ((v - e).max(0.0), (v + e).min(1.0));
|
||||
(self.eval(r, c, u, b) - self.eval(r, c, u, a)) / (b - a)
|
||||
}
|
||||
|
||||
/// Insert a mesh row through patch row `r` at local `v`.
|
||||
pub fn insert_row(&mut self, r: usize, v: f64) {
|
||||
let cols = self.cols as usize;
|
||||
let v = v.clamp(0.01, 0.99);
|
||||
let mut row = Vec::with_capacity(cols + 1);
|
||||
// Split the vertical edges.
|
||||
let mut ups = vec![];
|
||||
for c in 0..=cols {
|
||||
let e = self.edge_v(r, c);
|
||||
let (l, rr) = (e.subsegment(0.0..v), e.subsegment(v..1.0));
|
||||
ups.push((l.p1 - l.p0, rr.p2 - rr.p3));
|
||||
let pc = c.min(cols - 1);
|
||||
let u = if c == cols { 1.0 } else { 0.0 };
|
||||
let (color, opacity) = self.color_at(r, pc, u, v);
|
||||
// Horizontal handles: isocurve derivatives on either side.
|
||||
let right = if c < cols { self.surface_du(r, c, 0.0, v) / (3.0) } else { Vec2::ZERO };
|
||||
let left = if c > 0 { -self.surface_du(r, c - 1, 1.0, v) / 3.0 } else { Vec2::ZERO };
|
||||
row.push(MeshPoint { p: l.p3, color, opacity, handles: [right, left, rr.p1 - rr.p0, l.p2 - l.p3] });
|
||||
}
|
||||
for (c, (down, up)) in ups.into_iter().enumerate() {
|
||||
let i0 = self.idx(r, c);
|
||||
let i1 = self.idx(r + 1, c);
|
||||
self.points[i0].handles[H_DOWN] = down;
|
||||
self.points[i1].handles[H_UP] = up;
|
||||
}
|
||||
let at = self.idx(r + 1, 0);
|
||||
self.points.splice(at..at, row);
|
||||
self.rows += 1;
|
||||
}
|
||||
|
||||
/// Insert a mesh column through patch column `c` at local `u`.
|
||||
pub fn insert_col(&mut self, c: usize, u: f64) {
|
||||
let rows = self.rows as usize;
|
||||
let u = u.clamp(0.01, 0.99);
|
||||
let mut col = Vec::with_capacity(rows + 1);
|
||||
for r in 0..=rows {
|
||||
let e = self.edge_u(r, c);
|
||||
let (l, rr) = (e.subsegment(0.0..u), e.subsegment(u..1.0));
|
||||
let pr = r.min(rows - 1);
|
||||
let v = if r == rows { 1.0 } else { 0.0 };
|
||||
let (color, opacity) = self.color_at(pr, c, u, v);
|
||||
let down = if r < rows { self.surface_dv(r, c, u, 0.0) / 3.0 } else { Vec2::ZERO };
|
||||
let up = if r > 0 { -self.surface_dv(r - 1, c, u, 1.0) / 3.0 } else { Vec2::ZERO };
|
||||
col.push((MeshPoint { p: l.p3, color, opacity, handles: [rr.p1 - rr.p0, l.p2 - l.p3, down, up] }, l.p1 - l.p0, rr.p2 - rr.p3));
|
||||
}
|
||||
let cols = self.cols as usize;
|
||||
let mut pts = Vec::with_capacity((rows + 1) * (cols + 2));
|
||||
for (r, (mp, right, left)) in col.into_iter().enumerate() {
|
||||
for cc in 0..=cols {
|
||||
let mut q = self.points[r * (cols + 1) + cc].clone();
|
||||
if cc == c {
|
||||
q.handles[H_RIGHT] = right;
|
||||
}
|
||||
if cc == c + 1 {
|
||||
q.handles[H_LEFT] = left;
|
||||
}
|
||||
pts.push(q);
|
||||
if cc == c {
|
||||
pts.push(mp.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.points = pts;
|
||||
self.cols += 1;
|
||||
}
|
||||
|
||||
/// Mesh tool click: add a row and a column through `p` (inside the mesh). Returns the new point index.
|
||||
pub fn add_lines_at(&mut self, p: Point) -> Option<usize> {
|
||||
let (r, c, u, v) = self.locate(p)?;
|
||||
let mut rr = r;
|
||||
let mut cc = c;
|
||||
let row_new = v > 0.02 && v < 0.98;
|
||||
let col_new = u > 0.02 && u < 0.98;
|
||||
if row_new {
|
||||
self.insert_row(r, v);
|
||||
rr = r + 1;
|
||||
} else if v >= 0.98 {
|
||||
rr = r + 1;
|
||||
}
|
||||
if col_new {
|
||||
self.insert_col(c, u);
|
||||
cc = c + 1;
|
||||
} else if u >= 0.98 {
|
||||
cc = c + 1;
|
||||
}
|
||||
Some(self.idx(rr, cc))
|
||||
}
|
||||
|
||||
/// Mesh tool Alt-click: delete the mesh lines through point `index` (interior lines only).
|
||||
pub fn remove_point_lines(&mut self, index: usize) -> bool {
|
||||
// A mesh from a file may not have the points its rows and columns need: it is indexed below.
|
||||
if !self.is_valid() || index >= self.points.len() {
|
||||
return false;
|
||||
}
|
||||
let w = self.cols as usize + 1;
|
||||
let (r, c) = (index / w, index % w);
|
||||
let mut changed = false;
|
||||
if r > 0 && r < self.rows as usize {
|
||||
// Merge the edges above and below: keep the outer handles.
|
||||
for cc in 0..w {
|
||||
let above = self.idx(r - 1, cc);
|
||||
let below = self.idx(r + 1, cc);
|
||||
let mid = self.idx(r, cc);
|
||||
let (pa, pm, pb) = (self.points[above].p, self.points[mid].p, self.points[below].p);
|
||||
let _ = pm;
|
||||
self.points[above].handles[H_DOWN] = (pb - pa) / 3.0;
|
||||
self.points[below].handles[H_UP] = (pa - pb) / 3.0;
|
||||
}
|
||||
self.points.drain(r * w..(r + 1) * w);
|
||||
self.rows -= 1;
|
||||
changed = true;
|
||||
}
|
||||
let w = self.cols as usize + 1;
|
||||
if c > 0 && c < self.cols as usize {
|
||||
let rows = self.rows as usize;
|
||||
for rr in 0..=rows {
|
||||
let (l, rt) = (rr * w + c - 1, rr * w + c + 1);
|
||||
let (pl, pr) = (self.points[l].p, self.points[rt].p);
|
||||
self.points[l].handles[H_RIGHT] = (pr - pl) / 3.0;
|
||||
self.points[rt].handles[H_LEFT] = (pl - pr) / 3.0;
|
||||
}
|
||||
let mut k = 0;
|
||||
self.points.retain(|_| {
|
||||
let keep = k % w != c;
|
||||
k += 1;
|
||||
keep
|
||||
});
|
||||
self.cols -= 1;
|
||||
changed = true;
|
||||
}
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
// =====================================================================================
|
||||
// Envelopes
|
||||
// =====================================================================================
|
||||
|
||||
/// Union of the geometric bounds of `nodes`.
|
||||
pub fn nodes_bounds(nodes: &[Arc<Node>]) -> Option<Rect> {
|
||||
nodes.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric_bounds()))
|
||||
}
|
||||
|
||||
/// A `(rows+1)×(cols+1)` grid over `r` (row-major).
|
||||
pub fn grid_points(r: Rect, rows: u32, cols: u32) -> Vec<Point> {
|
||||
let mut v = Vec::with_capacity(((rows + 1) * (cols + 1)) as usize);
|
||||
for i in 0..=rows {
|
||||
for j in 0..=cols {
|
||||
v.push(Point::new(r.x0 + r.width() * j as f64 / cols.max(1) as f64, r.y0 + r.height() * i as f64 / rows.max(1) as f64));
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn catmull(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: f64) -> Vec2 {
|
||||
let t2 = t * t;
|
||||
let t3 = t2 * t;
|
||||
0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3)
|
||||
}
|
||||
|
||||
/// Point map from the unit square onto a point grid (tensor-product Catmull-Rom; linear
|
||||
/// extrapolation at the borders so an undistorted grid is the identity, also past the square).
|
||||
pub(super) fn grid_eval(rows: usize, cols: usize, pts: &[Point], u: f64, v: f64) -> Point {
|
||||
let at = |r: i64, c: i64| -> Vec2 {
|
||||
let rr = r.clamp(0, rows as i64);
|
||||
let cc = c.clamp(0, cols as i64);
|
||||
let base = pts[rr as usize * (cols + 1) + cc as usize].to_vec2();
|
||||
// Linear extrapolation outside the grid.
|
||||
let er = r - rr;
|
||||
let ec = c - cc;
|
||||
let mut p = base;
|
||||
if er != 0 && rows >= 1 {
|
||||
let inner = (rr - er.signum()).clamp(0, rows as i64);
|
||||
p += (base - pts[inner as usize * (cols + 1) + cc as usize].to_vec2()) * er.abs() as f64;
|
||||
}
|
||||
if ec != 0 && cols >= 1 {
|
||||
let inner = (cc - ec.signum()).clamp(0, cols as i64);
|
||||
p += (base - pts[rr as usize * (cols + 1) + inner as usize].to_vec2()) * ec.abs() as f64;
|
||||
}
|
||||
p
|
||||
};
|
||||
// Past the grid's edges the outer patches go on (art can reach past the content's box).
|
||||
let (su, sv) = (u * cols as f64, v * rows as f64);
|
||||
let (ci, ri) = ((su.floor() as i64).clamp(0, cols as i64 - 1), (sv.floor() as i64).clamp(0, rows as i64 - 1));
|
||||
let (fu, fv) = (su - ci as f64, sv - ri as f64);
|
||||
let mut rowsv = [Vec2::ZERO; 4];
|
||||
for (k, rv) in rowsv.iter_mut().enumerate() {
|
||||
let r = ri - 1 + k as i64;
|
||||
*rv = catmull(at(r, ci - 1), at(r, ci), at(r, ci + 1), at(r, ci + 2), fu);
|
||||
}
|
||||
catmull(rowsv[0], rowsv[1], rowsv[2], rowsv[3], fv).to_point()
|
||||
}
|
||||
|
||||
/// The surface (u, v ∈ [0,1]) an envelope of `kind` maps content onto, for content whose bounds in
|
||||
/// the envelope's own `frame` (its axes → the document) are `src`: a warp bends along the frame's
|
||||
/// axes; a mesh's points and a top object's path are in the document already.
|
||||
pub(super) fn surface_of<'a>(kind: &'a EnvelopeKind, src: Rect, frame: Affine) -> Box<dyn Fn(f64, f64) -> Point + 'a> {
|
||||
let flat = move |u: f64, v: f64| frame * Point::new(src.x0 + u * src.width(), src.y0 + v * src.height());
|
||||
match kind {
|
||||
EnvelopeKind::Warp { style, bend, h: dh, v: dv, horizontal } => {
|
||||
let st = WarpStyle::from_id(style).unwrap_or(WarpStyle::Arc);
|
||||
let b = bend.clamp(-100.0, 100.0) / 100.0;
|
||||
let (dh, dv) = (dh.clamp(-100.0, 100.0) / 100.0, dv.clamp(-100.0, 100.0) / 100.0);
|
||||
let c = src.center();
|
||||
let (hw, hh) = (src.width() / 2.0, src.height() / 2.0);
|
||||
let horizontal = *horizontal;
|
||||
Box::new(move |u: f64, v: f64| {
|
||||
let (x, y) = (2.0 * u - 1.0, 2.0 * v - 1.0);
|
||||
let (x2, y2) = if horizontal {
|
||||
warp_point(st, b, dh, dv, hh / hw.max(1e-9), x, y)
|
||||
} else {
|
||||
let (a, b2) = warp_point(st, b, dh, dv, hw / hh.max(1e-9), y, x);
|
||||
(b2, a)
|
||||
};
|
||||
frame * Point::new(c.x + x2 * hw, c.y + y2 * hh)
|
||||
})
|
||||
}
|
||||
EnvelopeKind::Mesh { rows, cols, points, handles } => {
|
||||
if !handles.is_empty()
|
||||
&& let Some(m) = envelope_grid(*rows, *cols, points, handles)
|
||||
{
|
||||
return Box::new(move |u: f64, v: f64| mesh_at(&m, u, v));
|
||||
}
|
||||
if *rows == 0 || *cols == 0 || grid_len(*rows, *cols) != Some(points.len()) {
|
||||
return Box::new(flat);
|
||||
}
|
||||
let (rows, cols) = (*rows as usize, *cols as usize);
|
||||
Box::new(move |u: f64, v: f64| grid_eval(rows, cols, points, u, v))
|
||||
}
|
||||
EnvelopeKind::TopObject { path } => match Coons::from_path(path) {
|
||||
Some(co) => Box::new(move |u: f64, v: f64| co.eval(u, v)),
|
||||
None => Box::new(flat),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
use super::*;
|
||||
|
||||
// =====================================================================================
|
||||
// Warp maps (shared with vectorcraft-effects' Warp effects)
|
||||
// =====================================================================================
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum WarpStyle {
|
||||
Arc,
|
||||
ArcLower,
|
||||
ArcUpper,
|
||||
Arch,
|
||||
Bulge,
|
||||
ShellLower,
|
||||
ShellUpper,
|
||||
Flag,
|
||||
Wave,
|
||||
Fish,
|
||||
Rise,
|
||||
Fisheye,
|
||||
Inflate,
|
||||
Squeeze,
|
||||
Twist,
|
||||
}
|
||||
|
||||
impl WarpStyle {
|
||||
/// From the id suffix (`arc`, `arcLower`, …).
|
||||
pub fn from_id(s: &str) -> Option<Self> {
|
||||
use WarpStyle::*;
|
||||
Some(match s {
|
||||
"arc" => Arc,
|
||||
"arcLower" => ArcLower,
|
||||
"arcUpper" => ArcUpper,
|
||||
"arch" => Arch,
|
||||
"bulge" => Bulge,
|
||||
"shellLower" => ShellLower,
|
||||
"shellUpper" => ShellUpper,
|
||||
"flag" => Flag,
|
||||
"wave" => Wave,
|
||||
"fish" => Fish,
|
||||
"rise" => Rise,
|
||||
"fisheye" => Fisheye,
|
||||
"inflate" => Inflate,
|
||||
"squeeze" => Squeeze,
|
||||
"twist" => Twist,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The warp map on normalised coordinates: `b` = bend (-1..1), `dh`/`dv` = distortion (-1..1);
|
||||
/// `aspect` is the box's half-height over its half-width along the warp (Arc bends in real
|
||||
/// proportions).
|
||||
pub fn warp_point(style: WarpStyle, b: f64, dh: f64, dv: f64, aspect: f64, x: f64, y: f64) -> (f64, f64) {
|
||||
use WarpStyle::*;
|
||||
let t = (y + 1.0) / 2.0; // 0 at top, 1 at bottom
|
||||
let par = 1.0 - x * x; // parabola: 1 at centre, 0 at sides
|
||||
let (mut x2, mut y2) = match style {
|
||||
Arc => {
|
||||
if b.abs() < 1e-6 {
|
||||
(x, y)
|
||||
} else {
|
||||
// Bend the centre line into a circular arc of equal length (sweep = |b|·180°), in
|
||||
// the box's real proportions (lengths in half-widths, so y counts `aspect` each):
|
||||
// the edges are concentric arcs, and one that would pass the centre stops there
|
||||
// instead of folding over (#1578).
|
||||
let k = if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 };
|
||||
let sweep = b.abs() * PI;
|
||||
let r0 = 2.0 / sweep;
|
||||
let yy = if b > 0.0 { y } else { -y } * k;
|
||||
let a = x / r0;
|
||||
let r = (r0 - yy).max(0.0);
|
||||
let (s, c) = a.sin_cos();
|
||||
let (nx, ny) = (r * s, (r0 - r * c) / k);
|
||||
(nx, if b > 0.0 { ny } else { -ny })
|
||||
}
|
||||
}
|
||||
ArcLower => (x, y + b * par * t),
|
||||
ArcUpper => (x, y - b * par * (1.0 - t)),
|
||||
Arch => (x, y - b * par),
|
||||
Bulge => (x, y + b * par * y),
|
||||
ShellLower => (x * (1.0 - 0.5 * b * (1.0 - t)), y + b * par * t),
|
||||
ShellUpper => (x * (1.0 - 0.5 * b * t), y - b * par * (1.0 - t)),
|
||||
Flag => (x, y + 0.5 * b * (PI * x).sin()),
|
||||
Wave => (x + 0.1 * b * (PI * y).sin(), y + 0.3 * b * (2.0 * PI * x).sin() * (0.5 + 0.5 * t)),
|
||||
Fish => (x, y * (1.0 + 0.5 * b * (0.75 * PI * (x + 1.0)).sin())),
|
||||
Rise => (x, y - b * ((x + 1.0) / 2.0).powi(2) * 2.0 + b),
|
||||
Fisheye => {
|
||||
let r2 = x * x + y * y;
|
||||
let s = if r2 < 1.0 { 1.0 + 0.5 * b * (1.0 - r2) } else { 1.0 };
|
||||
(x * s, y * s)
|
||||
}
|
||||
Inflate => (x * (1.0 + 0.5 * b * (1.0 - y * y)), y * (1.0 + 0.5 * b * par)),
|
||||
Squeeze => (x * (1.0 - 0.5 * b * (1.0 - y * y)), y * (1.0 + 0.3 * b * par)),
|
||||
Twist => {
|
||||
let r = (x * x + y * y).sqrt();
|
||||
let a = -b * PI * 0.5 * (1.0 - r / std::f64::consts::SQRT_2).max(0.0);
|
||||
let (s, c) = a.sin_cos();
|
||||
(x * c - y * s, x * s + y * c)
|
||||
}
|
||||
};
|
||||
// Perspective-like distortion: horizontal narrows one side, vertical one end.
|
||||
if dh != 0.0 {
|
||||
y2 *= (1.0 + dh * x2 * 0.5).max(0.0);
|
||||
}
|
||||
if dv != 0.0 {
|
||||
x2 *= (1.0 + dv * y2 * 0.5).max(0.0);
|
||||
}
|
||||
(x2, y2)
|
||||
}
|
||||
|
||||
/// Segment as a cubic; straight lines get handles at 1/3 and 2/3 so a non-linear map bends them.
|
||||
fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez {
|
||||
let c = sp.segment(i);
|
||||
if sp.segment_is_line(i) { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c }
|
||||
}
|
||||
|
||||
fn poly_len(c: &CubicBez) -> f64 {
|
||||
c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3)
|
||||
}
|
||||
|
||||
/// Running length along a polyline: `0, |p0p1|, |p0p1| + |p1p2|, …` (one entry per point).
|
||||
fn cumulative_lengths(pts: &[Point]) -> Vec<f64> {
|
||||
let mut total = 0.0;
|
||||
let mut cum = Vec::with_capacity(pts.len());
|
||||
cum.push(0.0);
|
||||
for w in pts.windows(2) {
|
||||
total += w[0].distance(w[1]);
|
||||
cum.push(total);
|
||||
}
|
||||
cum
|
||||
}
|
||||
|
||||
/// Most pieces [`map_nonlinear`] splits one segment into.
|
||||
const MAX_PIECES: usize = 64;
|
||||
|
||||
/// How many pieces of about `piece` a segment of length `len` is split into: one to `most`.
|
||||
pub fn pieces(len: f64, piece: f64, most: usize) -> usize {
|
||||
((len / piece).ceil() as usize).clamp(1, most.max(1))
|
||||
}
|
||||
|
||||
/// The piece length to split segments of lengths `lens` with ([`pieces`], at most `most` each) so
|
||||
/// that the pieces past each segment's first number at most `room`: `piece` when they already do,
|
||||
/// longer pieces otherwise. A segment of `n` pieces adds `n - 1 ≤ len / piece` points to a path,
|
||||
/// so pieces of the total length over `room` fit; with no room every segment stays one piece.
|
||||
pub fn fit_piece(lens: &[f64], piece: f64, most: usize, room: usize) -> f64 {
|
||||
let added = lens.iter().map(|&len| pieces(len, piece, most) - 1).fold(0, usize::saturating_add);
|
||||
if added <= room {
|
||||
return piece;
|
||||
}
|
||||
if room == 0 {
|
||||
return f64::INFINITY;
|
||||
}
|
||||
// A NaN length is always one piece.
|
||||
piece.max(lens.iter().filter(|len| !len.is_nan()).sum::<f64>() / room as f64)
|
||||
}
|
||||
|
||||
/// Map every point of `path` through the non-linear function `f`. Segments are split into pieces
|
||||
/// no longer than about `max_piece` (up to 64 per segment) and their control points mapped, which
|
||||
/// approximates the image curve to O(h²). Closedness and subpath structure are preserved.
|
||||
pub fn map_nonlinear(path: &PathData, max_piece: f64, f: impl Fn(Point) -> Point) -> PathData {
|
||||
map_nonlinear_within(path, max_piece, usize::MAX, f)
|
||||
}
|
||||
|
||||
/// [`map_nonlinear`] whose result has at most `max` anchors, or `path`'s count when that is more:
|
||||
/// where pieces of `max_piece` would make more, the pieces grow until they don't ([`fit_piece`]),
|
||||
/// a coarser approximation of the image curve. Geometry effects map within their anchor budget.
|
||||
pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData {
|
||||
let mut max_piece = max_piece.max(1e-3);
|
||||
// Each segment adds one anchor per piece past its first.
|
||||
let room = max.saturating_sub(path.anchor_count());
|
||||
let segs = path.subpaths.iter().map(SubPath::segment_count).fold(0, usize::saturating_add);
|
||||
if segs.saturating_mul(MAX_PIECES - 1) > room {
|
||||
let lens: Vec<f64> = path.subpaths.iter().flat_map(|sp| (0..sp.segment_count()).map(|i| poly_len(&seg_cubic(sp, i)))).collect();
|
||||
max_piece = fit_piece(&lens, max_piece, MAX_PIECES, room);
|
||||
}
|
||||
let mut subs = Vec::with_capacity(path.subpaths.len());
|
||||
for sp in &path.subpaths {
|
||||
let n = sp.anchors.len();
|
||||
if n == 0 {
|
||||
continue;
|
||||
}
|
||||
let segs = sp.segment_count();
|
||||
let mut res: Vec<Anchor> = Vec::new();
|
||||
let mut pending_in: Option<Point> = None;
|
||||
for i in 0..n {
|
||||
let a = &sp.anchors[i];
|
||||
let h_in = pending_in.take().unwrap_or_else(|| f(a.h_in));
|
||||
res.push(Anchor { p: f(a.p), h_in, h_out: f(a.h_out), kind: a.kind });
|
||||
if i < segs {
|
||||
let c = seg_cubic(sp, i);
|
||||
let k = pieces(poly_len(&c), max_piece, MAX_PIECES);
|
||||
for j in 0..k {
|
||||
let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64));
|
||||
if let Some(last) = res.last_mut() {
|
||||
last.h_out = f(sub.p1);
|
||||
}
|
||||
if j + 1 < k {
|
||||
res.push(Anchor { p: f(sub.p3), h_in: f(sub.p2), h_out: f(sub.p3), kind: Default::default() });
|
||||
} else {
|
||||
pending_in = Some(f(sub.p2));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(h) = pending_in
|
||||
&& sp.closed
|
||||
&& let Some(first) = res.first_mut()
|
||||
{
|
||||
first.h_in = h;
|
||||
}
|
||||
let anchors = res.into_iter().map(|a| Anchor::with_handles(a.p, a.h_in, a.h_out)).collect();
|
||||
subs.push(SubPath::new(anchors, sp.closed));
|
||||
}
|
||||
PathData::new(subs)
|
||||
}
|
||||
|
||||
// =====================================================================================
|
||||
// Coons patches from outlines
|
||||
// =====================================================================================
|
||||
|
||||
pub(super) fn flatten_subpath(sp: &SubPath, tol: f64) -> Vec<Point> {
|
||||
let mut bp = BezPath::new();
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
let mut pts: Vec<Point> = Vec::new();
|
||||
vectorcraft_geom::kurbo::flatten(bp.iter(), tol, |el| match el {
|
||||
vectorcraft_geom::PathEl::MoveTo(p) | vectorcraft_geom::PathEl::LineTo(p) if pts.last().is_none_or(|q| q.distance(p) > 1e-9) => pts.push(p),
|
||||
_ => {}
|
||||
});
|
||||
pts
|
||||
}
|
||||
|
||||
pub(super) fn resample(poly: &[Point], m: usize) -> Vec<Point> {
|
||||
if poly.is_empty() {
|
||||
return vec![Point::ZERO; m];
|
||||
}
|
||||
if poly.len() == 1 {
|
||||
return vec![poly[0]; m];
|
||||
}
|
||||
let cum = cumulative_lengths(poly);
|
||||
let total = cum.last().copied().unwrap_or(0.0);
|
||||
let mut out = Vec::with_capacity(m);
|
||||
let mut i = 0;
|
||||
for k in 0..m {
|
||||
let s = if m > 1 { total * k as f64 / (m - 1) as f64 } else { 0.0 };
|
||||
while i + 2 < cum.len() && cum[i + 1] < s {
|
||||
i += 1;
|
||||
}
|
||||
let seg = (cum[i + 1] - cum[i]).max(1e-12);
|
||||
out.push(poly[i].lerp(poly[i + 1], ((s - cum[i]) / seg).clamp(0.0, 1.0)));
|
||||
}
|
||||
out
|
||||
}
|
||||
+18
-2548
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,133 @@
|
||||
use super::kind::NodeKind;
|
||||
use super::live_shape::LiveShape;
|
||||
use super::*;
|
||||
|
||||
/// Window → Attributes: an object's settings that don't change how it prints.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ObjectAttributes {
|
||||
/// Show Center / Don't Show Center (`None`: the object kind's default, [`Node::shows_center`]).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub show_center: Option<bool>,
|
||||
/// Image Map: the clickable area the URL covers in web output.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub image_map: ImageMap,
|
||||
/// URL the object links to (SVG `<a href>`; empty: none).
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub url: String,
|
||||
/// The note shown in the Attributes panel.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub note: String,
|
||||
/// The object's own data, in order: SVG's `data-*` attributes (`data-pivot="100,180"` is
|
||||
/// `("pivot", "100,180")`), kept from import to export (`object.setProps {data}`).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub data: Vec<(String, String)>,
|
||||
/// Window › SVG Interactivity: the JavaScript each event runs, in the panel's order
|
||||
/// (`("onclick", "alert(1)")`, one entry per event of [`SVG_EVENTS`]). SVG export writes them as
|
||||
/// the element's event attributes; nothing in VectorCraft runs them.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub events: Vec<(String, String)>,
|
||||
/// Attributes in other applications' XML namespaces, in order, kept from SVG import to SVG
|
||||
/// export: what another tool notes on an object (a plotter's pen, a cutter's passes) survives
|
||||
/// a round trip through VectorCraft. Nothing in VectorCraft reads them. They are the object's,
|
||||
/// as `data` is, so copies, duplicates and pastes keep them and a deleted object takes them
|
||||
/// with it.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub foreign: Vec<ForeignAttribute>,
|
||||
}
|
||||
|
||||
/// An attribute in another application's XML namespace: `plotter:pen="2"` with `xmlns:plotter=
|
||||
/// "https://example.org/plotter"` is `{ns: "https://example.org/plotter", prefix: "plotter", name:
|
||||
/// "pen", value: "2"}`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ForeignAttribute {
|
||||
/// The namespace's URI, which names it.
|
||||
pub ns: String,
|
||||
/// The prefix the file gave the namespace, which export reuses where it can.
|
||||
pub prefix: String,
|
||||
/// The attribute's local name.
|
||||
pub name: String,
|
||||
/// The attribute's value, as the file had it.
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
/// The events the SVG Interactivity panel attaches JavaScript to, by the names of the SVG event
|
||||
/// attributes that run it.
|
||||
pub const SVG_EVENTS: [&str; 19] = [
|
||||
"onfocusin",
|
||||
"onfocusout",
|
||||
"onactivate",
|
||||
"onmousedown",
|
||||
"onmouseup",
|
||||
"onclick",
|
||||
"onmouseover",
|
||||
"onmousemove",
|
||||
"onmouseout",
|
||||
"onkeydown",
|
||||
"onkeypress",
|
||||
"onkeyup",
|
||||
"onload",
|
||||
"onerror",
|
||||
"onabort",
|
||||
"onunload",
|
||||
"onzoom",
|
||||
"onresize",
|
||||
"onscroll",
|
||||
];
|
||||
|
||||
/// The most JavaScript files a document links (`Document::svg_scripts`): SVG import keeps the
|
||||
/// first ones and warns about the rest, and `svgInteractivity.addFile` refuses another.
|
||||
pub const MAX_SVG_SCRIPTS: usize = 64;
|
||||
|
||||
/// The Attributes panel's Image Map shapes.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ImageMap {
|
||||
#[default]
|
||||
None,
|
||||
Rectangle,
|
||||
Polygon,
|
||||
}
|
||||
|
||||
impl ImageMap {
|
||||
pub const ALL: [ImageMap; 3] = [ImageMap::None, ImageMap::Rectangle, ImageMap::Polygon];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
ImageMap::None => "None",
|
||||
ImageMap::Rectangle => "Rectangle",
|
||||
ImageMap::Polygon => "Polygon",
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a label or serialized name, ignoring case.
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|m| m.label().eq_ignore_ascii_case(s))
|
||||
}
|
||||
}
|
||||
|
||||
impl Node {
|
||||
/// The URL this object links to, if any.
|
||||
pub fn url(&self) -> Option<&str> {
|
||||
self.extras().attrs.as_deref().map(|a| a.url.as_str()).filter(|u| !u.is_empty())
|
||||
}
|
||||
|
||||
/// Whether the canvas shows this object's centre point when it is selected: as set in the
|
||||
/// Attributes panel, else [`Self::shows_center_by_default`].
|
||||
pub fn shows_center(&self) -> bool {
|
||||
self.extras().attrs.as_deref().and_then(|a| a.show_center).unwrap_or_else(|| self.shows_center_by_default())
|
||||
}
|
||||
|
||||
/// Shapes drawn with the shape tools (live rectangles, ellipses and polygons) show their centre.
|
||||
pub fn shows_center_by_default(&self) -> bool {
|
||||
matches!(&self.kind, NodeKind::Path { live: Some(l), .. } if !matches!(**l, LiveShape::Line { .. } | LiveShape::Path { .. }))
|
||||
}
|
||||
|
||||
/// Change this object's attributes with `f`; all-default attributes are dropped.
|
||||
pub fn edit_attrs<R>(&mut self, f: impl FnOnce(&mut ObjectAttributes) -> R) -> R {
|
||||
let mut a = self.extras_mut().attrs.take().unwrap_or_default();
|
||||
let r = f(&mut a);
|
||||
self.extras_mut().attrs = (*a != ObjectAttributes::default()).then_some(a);
|
||||
r
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
use super::kind::NodeKind;
|
||||
use super::*;
|
||||
|
||||
/// Unites filled regions (each under its own fill rule) into one path filled non-zero. Booleans
|
||||
/// live above this crate (`vectorcraft-pathops`), so callers supply it.
|
||||
pub type Uniter<'a> = &'a dyn Fn(&[(BezPath, FillRule)]) -> BezPath;
|
||||
|
||||
impl Node {
|
||||
/// The filled regions this object clips to as the clipping path of a clip group, in document
|
||||
/// space, each with its fill rule: a path, a compound path (with its holes), an image's frame,
|
||||
/// text outlined by `text` (glyph outlines need the font engine, above this crate), the visible
|
||||
/// members of a group (their union) and the clipping path of a nested clip group. Live objects
|
||||
/// are evaluated first. Guides and symbol instances add nothing.
|
||||
pub fn clip_shapes(&self, text: Outliner) -> Vec<(BezPath, FillRule)> {
|
||||
let mut out = vec![];
|
||||
self.push_clip_shapes(text, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn push_clip_shapes(&self, text: Outliner, out: &mut Vec<(BezPath, FillRule)>) {
|
||||
match &self.kind {
|
||||
NodeKind::Path { guide: true, .. } | NodeKind::SymbolInstance { .. } => {}
|
||||
NodeKind::Path { path, rule, .. } => out.push((path.to_bezpath(), *rule)),
|
||||
NodeKind::Compound { children, rule } => {
|
||||
let mut bp = BezPath::new();
|
||||
for p in children.iter().filter_map(|c| c.path_data()) {
|
||||
bp.extend(p.to_bezpath());
|
||||
}
|
||||
out.push((bp, *rule));
|
||||
}
|
||||
NodeKind::Group { children, clip: true } => {
|
||||
if let Some(c) = children.first() {
|
||||
c.push_clip_shapes(text, out);
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
for c in children.iter().skip(usize::from(self.extras().shaper.is_some())).filter(|c| c.visible) {
|
||||
c.push_clip_shapes(text, out);
|
||||
}
|
||||
}
|
||||
NodeKind::Text(_) => {
|
||||
if let Some(o) = text.and_then(|f| f(self)) {
|
||||
o.push_clip_shapes(None, out);
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
|
||||
out.push((frame.to_bezpath(), FillRule::NonZero));
|
||||
}
|
||||
NodeKind::PlacedDocument(p) => {
|
||||
let frame = shapes::rectangle(p.natural()).transformed(p.xf);
|
||||
out.push((frame.to_bezpath(), FillRule::NonZero));
|
||||
}
|
||||
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => {
|
||||
crate::live::expand_deep(self, text).push_clip_shapes(text, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The region this object clips to as one path and fill rule ([`Self::clip_shapes`]), shared
|
||||
/// by the renderer and the SVG and PDF writers so every output clips alike. One shape keeps its
|
||||
/// own rule; several are united by `unite` (filled non-zero). `None` when there is nothing to
|
||||
/// clip by: the clipped art is then hidden.
|
||||
pub fn clip_outline(&self, text: Outliner, unite: Uniter) -> Option<(BezPath, FillRule)> {
|
||||
let mut shapes = self.clip_shapes(text);
|
||||
match shapes.len() {
|
||||
0 => None,
|
||||
1 => shapes.pop(),
|
||||
_ => Some((unite(&shapes), FillRule::NonZero)),
|
||||
}
|
||||
}
|
||||
|
||||
/// What this object paints as the clipping path of a clip group, shared by the renderer and
|
||||
/// the SVG and PDF writers: its fills, painted behind the clipped art, and its strokes, painted
|
||||
/// over it (unclipped). Each part is this object keeping only those appearance items (type:
|
||||
/// also only its characters' fills or strokes); `None` where it paints nothing, as right after
|
||||
/// Make Clipping Mask. Only paths, compound paths and type paint as clipping paths.
|
||||
pub fn clip_paint(&self) -> ClipPaint {
|
||||
use crate::appearance::AppearanceItem;
|
||||
let runs = match &self.kind {
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => None,
|
||||
NodeKind::Text(t) => Some(&t.runs),
|
||||
_ => return ClipPaint::default(),
|
||||
};
|
||||
let paints = |fill: bool| {
|
||||
let item = |i: &AppearanceItem| match i {
|
||||
AppearanceItem::Fill(f) => fill && f.visible && !f.paint.is_none(),
|
||||
AppearanceItem::Stroke(s) => !fill && s.visible && !s.paint.is_none() && s.width > 0.0,
|
||||
};
|
||||
let run = |r: &crate::text::TextRun| if fill { !r.style.fill.is_none() } else { !r.style.stroke.is_none() && r.style.stroke_width > 0.0 };
|
||||
self.appearance.items.iter().any(item) || runs.is_some_and(|rs| rs.iter().any(run))
|
||||
};
|
||||
let part = |fill: bool| {
|
||||
paints(fill).then(|| {
|
||||
let mut n = self.clone();
|
||||
for i in (0..n.appearance.items.len()).rev() {
|
||||
if matches!(n.appearance.items[i], AppearanceItem::Fill(_)) != fill {
|
||||
n.appearance.remove_item(i);
|
||||
}
|
||||
}
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
for r in &mut t.runs {
|
||||
*(if fill { &mut r.style.stroke } else { &mut r.style.fill }) = vectorcraft_color::Paint::None;
|
||||
}
|
||||
}
|
||||
n
|
||||
})
|
||||
};
|
||||
ClipPaint { fill: part(true), stroke: part(false) }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a clipping path paints ([`Node::clip_paint`]).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ClipPaint {
|
||||
/// The clipping path with only its fills: painted behind the clipped art (inside the clip).
|
||||
pub fill: Option<Node>,
|
||||
/// The clipping path with only its strokes: painted over the clipped art, not clipped.
|
||||
pub stroke: Option<Node>,
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
use super::attributes::ObjectAttributes;
|
||||
use super::kind::NodeKind;
|
||||
use super::live_shape::LiveShape;
|
||||
use super::opacity::OpacityMask;
|
||||
use super::*;
|
||||
|
||||
/// The parts of a [`Node`] that few objects have: kept out of line, so that the nodes without
|
||||
/// them stay small ([`Node::extras`]).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct NodeExtras {
|
||||
/// Opacity mask (Transparency panel). Its art lives here, outside the layer tree.
|
||||
pub mask: Option<Box<OpacityMask>>,
|
||||
/// Image Trace object: `{preset, params, view?}` it was traced with (the Image Trace panel shows
|
||||
/// them; `view` is its [`crate::TraceView`] id, absent for the tracing result).
|
||||
pub trace: Option<Box<serde_json::Value>>,
|
||||
/// Object → Text Wrap: area type below this object (in the same layer) flows around it.
|
||||
pub wrap: Option<crate::text::TextWrap>,
|
||||
/// Graph object: the group's children are generated from this spec (Object → Graph).
|
||||
pub graph: Option<Box<crate::graph::GraphSpec>>,
|
||||
/// Index of the graph series this generated group belongs to. Axes, the legend and other
|
||||
/// children leave it unset, so a series named "Legend" or "Axes" is not mistaken for them.
|
||||
pub series_index: Option<u32>,
|
||||
/// The group holds the glyph outlines of type. Geometry effects that reshape it move and scale
|
||||
/// the placed gradients in it with the outlines.
|
||||
pub type_outlines: bool,
|
||||
/// Editable Shaper composition; the original art is retained in its source child.
|
||||
pub shaper: Option<Box<crate::shaper::ShaperSpec>>,
|
||||
/// The [`crate::GraphicStyle::id`] last applied to this object. It stays linked while it keeps
|
||||
/// that style's look: editing its appearance or transparency breaks the link.
|
||||
pub graphic_style: Option<u32>,
|
||||
/// Attributes panel: centre point display, image map, URL and note (`None`: all defaults).
|
||||
pub attrs: Option<Box<ObjectAttributes>>,
|
||||
/// Object → Slice → Make: the object is an object slice (its slice follows its bounds) with
|
||||
/// these options.
|
||||
pub slice: Option<Box<crate::SliceOptions>>,
|
||||
/// Object › Perspective: the perspective grid plane the object is attached to.
|
||||
pub perspective: Option<Box<crate::PerspectiveAttachment>>,
|
||||
/// Dimension object: the live measurement it draws; its ordinary group children hold its
|
||||
/// exportable appearance (Object › Dimensions, the Dimension tool).
|
||||
pub dimension: Option<Box<crate::dimension::Dimension>>,
|
||||
/// Object › Intertwine: as a member of an Intertwine group, the area (document coordinates,
|
||||
/// filled non-zero) where this object is drawn over the group's other members.
|
||||
pub intertwine: Option<Box<PathData>>,
|
||||
/// Live Paint group: its Gap Options (Object › Live Paint › Gap Options; `None`: the defaults).
|
||||
pub live_paint_gaps: Option<Box<crate::live_paint::GapOptions>>,
|
||||
/// Object › Objects on Path: the group's path and the objects attached to it (see
|
||||
/// [`crate::objects_on_path`]).
|
||||
pub objects_on_path: Option<Box<crate::objects_on_path::ObjectsOnPath>>,
|
||||
}
|
||||
|
||||
/// No extras: what [`Node::extras`] gives for a node without any.
|
||||
pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
mask: None,
|
||||
trace: None,
|
||||
wrap: None,
|
||||
graph: None,
|
||||
series_index: None,
|
||||
type_outlines: false,
|
||||
shaper: None,
|
||||
graphic_style: None,
|
||||
attrs: None,
|
||||
slice: None,
|
||||
perspective: None,
|
||||
dimension: None,
|
||||
intertwine: None,
|
||||
live_paint_gaps: None,
|
||||
objects_on_path: None,
|
||||
};
|
||||
|
||||
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
|
||||
/// none.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Extras(pub(crate) Option<Box<NodeExtras>>);
|
||||
|
||||
impl Extras {
|
||||
fn get(&self) -> &NodeExtras {
|
||||
self.0.as_deref().unwrap_or(&NO_EXTRAS)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Extras {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (&self.0, &other.0) {
|
||||
(Some(a), Some(b)) => a == b,
|
||||
_ => self.get() == other.get(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Node {
|
||||
/// The rarely set parts of this node (all unset when it has none).
|
||||
#[inline]
|
||||
pub fn extras(&self) -> &NodeExtras {
|
||||
self.extras.get()
|
||||
}
|
||||
|
||||
/// The rarely set parts of this node, to change: when the change is done (the guard dropped),
|
||||
/// extras that were set are allocated and extras left all unset are let go. Setting one to
|
||||
/// `None` on a node without extras allocates nothing.
|
||||
#[inline]
|
||||
pub fn extras_mut(&mut self) -> ExtrasMut<'_> {
|
||||
ExtrasMut { slot: &mut self.extras.0, local: NodeExtras::default() }
|
||||
}
|
||||
|
||||
/// The rarely set parts of this node, if it has any: to change what is there in place.
|
||||
#[inline]
|
||||
pub fn extras_if_any(&mut self) -> Option<&mut NodeExtras> {
|
||||
self.extras.0.as_deref_mut()
|
||||
}
|
||||
|
||||
/// The live shape of a path object, if it is one.
|
||||
pub fn live_shape(&self) -> Option<&LiveShape> {
|
||||
match &self.kind {
|
||||
NodeKind::Path { live, .. } => live.as_deref(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The live shape of a path object, if it is one, to change.
|
||||
pub fn live_shape_mut(&mut self) -> Option<&mut LiveShape> {
|
||||
match &mut self.kind {
|
||||
NodeKind::Path { live, .. } => live.as_deref_mut(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// This node with opacity mask `mask` (or none).
|
||||
pub fn with_mask(mut self, mask: Option<Box<OpacityMask>>) -> Self {
|
||||
self.extras_mut().mask = mask;
|
||||
self
|
||||
}
|
||||
|
||||
/// The extras, if this node has them allocated (for [`crate::mem`]'s estimate).
|
||||
pub(crate) fn extras_box(&self) -> Option<&NodeExtras> {
|
||||
self.extras.0.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Node::extras_mut`]: the node's extras while they change.
|
||||
pub struct ExtrasMut<'a> {
|
||||
slot: &'a mut Option<Box<NodeExtras>>,
|
||||
/// Stands for the extras of a node without any, boxed into it when dropped if one was set.
|
||||
local: NodeExtras,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for ExtrasMut<'_> {
|
||||
type Target = NodeExtras;
|
||||
fn deref(&self) -> &NodeExtras {
|
||||
self.slot.as_deref().unwrap_or(&self.local)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::DerefMut for ExtrasMut<'_> {
|
||||
fn deref_mut(&mut self) -> &mut NodeExtras {
|
||||
match self.slot.as_deref_mut() {
|
||||
Some(e) => e,
|
||||
None => &mut self.local,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ExtrasMut<'_> {
|
||||
fn drop(&mut self) {
|
||||
match self.slot.as_deref() {
|
||||
Some(e) if *e == NO_EXTRAS => *self.slot = None,
|
||||
Some(_) => {}
|
||||
None if self.local != NO_EXTRAS => *self.slot = Some(Box::new(std::mem::take(&mut self.local))),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use super::*;
|
||||
|
||||
/// Stable per-document object id. Never reused.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct NodeId(pub u64);
|
||||
|
||||
impl std::fmt::Display for NodeId {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "#{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Layer colours used for selection highlighting (index into [`LAYER_COLORS`]) or a custom RGB.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum LayerColor {
|
||||
Preset(u8),
|
||||
Custom([u8; 3]),
|
||||
}
|
||||
|
||||
/// Layer highlight colours, assigned in sequence to new layers. First is Illustrator-like light blue.
|
||||
pub const LAYER_COLORS: [(&str, [u8; 3]); 27] = [
|
||||
("Light Blue", [0x4f, 0x80, 0xff]),
|
||||
("Red", [0xff, 0x4f, 0x4f]),
|
||||
("Green", [0x4f, 0xff, 0x4f]),
|
||||
("Blue", [0x4f, 0x4f, 0xff]),
|
||||
("Yellow", [0xff, 0xff, 0x4f]),
|
||||
("Magenta", [0xff, 0x4f, 0xff]),
|
||||
("Cyan", [0x4f, 0xff, 0xff]),
|
||||
("Gray", [0x80, 0x80, 0x80]),
|
||||
("Black", [0x00, 0x00, 0x00]),
|
||||
("Orange", [0xff, 0x66, 0x00]),
|
||||
("Dark Green", [0x00, 0x80, 0x00]),
|
||||
("Teal", [0x00, 0x80, 0x80]),
|
||||
("Tan", [0xcc, 0x99, 0x66]),
|
||||
("Brown", [0x99, 0x33, 0x00]),
|
||||
("Violet", [0x99, 0x33, 0xff]),
|
||||
("Gold", [0xff, 0x99, 0x00]),
|
||||
("Dark Blue", [0x00, 0x00, 0x80]),
|
||||
("Pink", [0xff, 0x99, 0xcc]),
|
||||
("Lavender", [0x99, 0x99, 0xff]),
|
||||
("Brick Red", [0x99, 0x00, 0x00]),
|
||||
("Olive Green", [0x66, 0x66, 0x00]),
|
||||
("Peach", [0xff, 0x99, 0x99]),
|
||||
("Burgundy", [0x99, 0x00, 0x33]),
|
||||
("Grass Green", [0x99, 0xcc, 0x00]),
|
||||
("Ochre", [0x99, 0x66, 0x00]),
|
||||
("Purple", [0x66, 0x00, 0x99]),
|
||||
("Light Gray", [0xbb, 0xbb, 0xbb]),
|
||||
];
|
||||
|
||||
impl LayerColor {
|
||||
pub fn rgb(self) -> [u8; 3] {
|
||||
match self {
|
||||
LayerColor::Preset(i) => LAYER_COLORS[i as usize % LAYER_COLORS.len()].1,
|
||||
LayerColor::Custom(c) => c,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
use super::ids::LayerColor;
|
||||
use super::live_shape::LiveShape;
|
||||
use super::*;
|
||||
|
||||
/// Embedded or linked raster image.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ImageObject {
|
||||
/// Key into [`crate::Document::images`].
|
||||
pub key: String,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Maps pixel space (0..w, 0..h) into the document.
|
||||
pub xf: Affine,
|
||||
/// The file a linked image shows (File → Place with Link); `None`: embedded. Files saved
|
||||
/// before links had details hold just the path.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::links::de_link")]
|
||||
pub link: Option<crate::LinkInfo>,
|
||||
/// Links panel → Placement Options: how a file read again takes this image's place.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub placement: crate::links::PlacementOptions,
|
||||
/// The pixels of an image in art made outside a document (type's outlines, a glyph's art),
|
||||
/// which has no [`crate::Document::images`] to keep them in. A document takes them in
|
||||
/// ([`crate::Document::adopt_pixels`]): no image in one holds its own.
|
||||
#[serde(skip)]
|
||||
pub pixels: Option<Arc<crate::ImageBlob>>,
|
||||
}
|
||||
|
||||
/// Written with its `type` first, then its fields (an internally tagged enum); read by
|
||||
/// [`kind_de`], which takes the fields straight from the file when `type` comes first.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(tag = "type", rename_all = "lowercase")]
|
||||
pub enum NodeKind {
|
||||
/// A top-level layer or sublayer.
|
||||
Layer {
|
||||
color: LayerColor,
|
||||
#[serde(default)]
|
||||
template: bool,
|
||||
#[serde(default = "yes")]
|
||||
printable: bool,
|
||||
children: Vec<Arc<Node>>,
|
||||
/// Layer clipping mask: the first (bottom-most) child clips the others, as in a clip group.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
clip: bool,
|
||||
/// Layer Options → Preview: off, the layer's art is drawn (and clicked) in outline on screen
|
||||
/// (Ctrl-click its eye in the Layers panel).
|
||||
#[serde(default = "yes", skip_serializing_if = "crate::skip::is_true")]
|
||||
preview: bool,
|
||||
/// Layer Options → Dim Images to: on screen, images on the layer show faded to this
|
||||
/// percentage (0–100); `None`: not dimmed.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
dim_images: Option<u8>,
|
||||
},
|
||||
/// A group. With `clip`, the first (bottom-most) child is the clipping path.
|
||||
Group {
|
||||
children: Vec<Arc<Node>>,
|
||||
#[serde(default)]
|
||||
clip: bool,
|
||||
},
|
||||
Path {
|
||||
path: PathData,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
rule: FillRule,
|
||||
/// Boxed: few paths are live shapes, and the shape is larger than the rest of the variant.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
live: Option<Box<LiveShape>>,
|
||||
/// This path acts as a clipping path inside a clip group.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
clipping: bool,
|
||||
/// Guide (non-printing) path.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
guide: bool,
|
||||
},
|
||||
/// Compound path: children are paths painted as one with the compound's appearance.
|
||||
Compound {
|
||||
children: Vec<Arc<Node>>,
|
||||
#[serde(default)]
|
||||
rule: FillRule,
|
||||
},
|
||||
Text(Box<TextObject>),
|
||||
/// Boxed, as the other large kinds: a node is as large as its largest kind.
|
||||
Image(Box<ImageObject>),
|
||||
SymbolInstance {
|
||||
symbol: String,
|
||||
xf: Affine,
|
||||
},
|
||||
/// Live blend: the key objects (paint order) plus spacing/orientation/spine; the intermediate
|
||||
/// steps are evaluated on demand (`live::blend_expand`).
|
||||
Blend {
|
||||
children: Vec<Arc<Node>>,
|
||||
#[serde(default)]
|
||||
spec: Box<BlendSpec>,
|
||||
},
|
||||
/// Live envelope distortion of `content`.
|
||||
Envelope {
|
||||
content: Vec<Arc<Node>>,
|
||||
kind: Box<EnvelopeKind>,
|
||||
/// Envelope Options → Fidelity (0–100).
|
||||
#[serde(default = "crate::live::default_fidelity")]
|
||||
fidelity: f64,
|
||||
/// Edit Contents mode (the content, not the envelope, is edited).
|
||||
#[serde(default)]
|
||||
editing: bool,
|
||||
/// Envelope Options besides Fidelity.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
options: crate::live::EnvelopeOptions,
|
||||
/// The envelope's own axes (→ the document): the transforms it took since it was made that
|
||||
/// the page axes can't stand for (rotation, shear, reflection). The content maps from its
|
||||
/// bounds in this frame, and a warp bends along it.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
frame: Box<Affine>,
|
||||
},
|
||||
/// Gradient mesh.
|
||||
Mesh(GradientMesh),
|
||||
/// Live Repeat (radial / grid / mirror) of source art.
|
||||
Repeat(RepeatSpec),
|
||||
/// A placed document: an artboard of another VectorCraft file, or a page of a PDF or `.ai`
|
||||
/// file, linked and locked (see [`crate::placed_document`]).
|
||||
PlacedDocument(Box<crate::placed_document::PlacedDocument>),
|
||||
/// Object › Intertwine: the objects keep their own stacking order, except where one of them
|
||||
/// is drawn over the others: the area [`NodeExtras::intertwine`] of that member (see
|
||||
/// [`crate::intertwine`]).
|
||||
Intertwine {
|
||||
children: Vec<Arc<Node>>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Reading a [`NodeKind`]. Derived, an internally tagged enum buffers each kind (with every
|
||||
/// object inside a group, again at each level of nesting) before reading it, since `type` may come
|
||||
/// anywhere among its fields. Files have it first (it is written first): then the kind is read
|
||||
/// straight from the file. Otherwise (hand-written files, values whose keys are sorted) the
|
||||
/// fields before `type` are buffered, and only those.
|
||||
mod kind_de {
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::de::value::{MapAccessDeserializer, StringDeserializer};
|
||||
use serde::de::{self, DeserializeSeed, Deserializer, EnumAccess, IntoDeserializer, MapAccess, VariantAccess, Visitor};
|
||||
use serde::{Deserialize, forward_to_deserialize_any};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData};
|
||||
|
||||
use super::{LayerColor, LiveShape, Node, NodeKind, yes};
|
||||
use crate::live::{BlendSpec, EnvelopeKind, GradientMesh};
|
||||
use crate::pattern::RepeatSpec;
|
||||
use crate::text::TextObject;
|
||||
|
||||
/// The kinds and their fields as [`NodeKind`] has them, with the defaults its field attributes
|
||||
/// note (the compiler checks that every field is here), read externally tagged: the kind from
|
||||
/// `type`, its fields from the rest of the object ([`Tagged`]).
|
||||
#[derive(Deserialize)]
|
||||
#[serde(remote = "NodeKind", rename_all = "lowercase")]
|
||||
enum KindDef {
|
||||
Layer {
|
||||
color: LayerColor,
|
||||
#[serde(default)]
|
||||
template: bool,
|
||||
#[serde(default = "yes")]
|
||||
printable: bool,
|
||||
children: Vec<Arc<Node>>,
|
||||
#[serde(default)]
|
||||
clip: bool,
|
||||
#[serde(default = "yes")]
|
||||
preview: bool,
|
||||
#[serde(default)]
|
||||
dim_images: Option<u8>,
|
||||
},
|
||||
Group {
|
||||
children: Vec<Arc<Node>>,
|
||||
#[serde(default)]
|
||||
clip: bool,
|
||||
},
|
||||
Path {
|
||||
path: PathData,
|
||||
#[serde(default)]
|
||||
rule: FillRule,
|
||||
#[serde(default)]
|
||||
live: Option<Box<LiveShape>>,
|
||||
#[serde(default)]
|
||||
clipping: bool,
|
||||
#[serde(default)]
|
||||
guide: bool,
|
||||
},
|
||||
Compound {
|
||||
children: Vec<Arc<Node>>,
|
||||
#[serde(default)]
|
||||
rule: FillRule,
|
||||
},
|
||||
Text(Box<TextObject>),
|
||||
Image(Box<super::ImageObject>),
|
||||
SymbolInstance {
|
||||
symbol: String,
|
||||
xf: Affine,
|
||||
},
|
||||
Blend {
|
||||
children: Vec<Arc<Node>>,
|
||||
#[serde(default)]
|
||||
spec: Box<BlendSpec>,
|
||||
},
|
||||
Envelope {
|
||||
content: Vec<Arc<Node>>,
|
||||
kind: Box<EnvelopeKind>,
|
||||
#[serde(default = "crate::live::default_fidelity")]
|
||||
fidelity: f64,
|
||||
#[serde(default)]
|
||||
editing: bool,
|
||||
#[serde(default)]
|
||||
options: crate::live::EnvelopeOptions,
|
||||
#[serde(default)]
|
||||
frame: Box<Affine>,
|
||||
},
|
||||
Mesh(GradientMesh),
|
||||
Repeat(RepeatSpec),
|
||||
PlacedDocument(Box<crate::placed_document::PlacedDocument>),
|
||||
Intertwine {
|
||||
children: Vec<Arc<Node>>,
|
||||
},
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for NodeKind {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
d.deserialize_map(KindVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
struct KindVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for KindVisitor {
|
||||
type Value = NodeKind;
|
||||
|
||||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("an object kind (a map with `type`)")
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<NodeKind, A::Error> {
|
||||
let mut before = vec![];
|
||||
while let Some(key) = map.next_key::<String>()? {
|
||||
if key == "type" {
|
||||
let tag: String = map.next_value()?;
|
||||
return KindDef::deserialize(Tagged { tag, map: Buffered { before: before.into_iter(), value: None, map } });
|
||||
}
|
||||
before.push((key, map.next_value::<serde_json::Value>()?));
|
||||
}
|
||||
Err(de::Error::missing_field("type"))
|
||||
}
|
||||
}
|
||||
|
||||
/// The fields read before `type` (buffered), then the rest of the object.
|
||||
struct Buffered<A> {
|
||||
before: std::vec::IntoIter<(String, serde_json::Value)>,
|
||||
value: Option<serde_json::Value>,
|
||||
map: A,
|
||||
}
|
||||
|
||||
impl<'de, A: MapAccess<'de>> MapAccess<'de> for Buffered<A> {
|
||||
type Error = A::Error;
|
||||
|
||||
fn next_key_seed<K: DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>, A::Error> {
|
||||
match self.before.next() {
|
||||
Some((key, value)) => {
|
||||
self.value = Some(value);
|
||||
seed.deserialize(StringDeserializer::<A::Error>::new(key)).map(Some)
|
||||
}
|
||||
None => self.map.next_key_seed(seed),
|
||||
}
|
||||
}
|
||||
|
||||
fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, A::Error> {
|
||||
match self.value.take() {
|
||||
Some(value) => seed.deserialize(value).map_err(de::Error::custom),
|
||||
None => self.map.next_value_seed(seed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An object whose `type` was read: the kind is `tag`, its fields are the rest of `map`.
|
||||
struct Tagged<A> {
|
||||
tag: String,
|
||||
map: A,
|
||||
}
|
||||
|
||||
impl<'de, A: MapAccess<'de>> Deserializer<'de> for Tagged<A> {
|
||||
type Error = A::Error;
|
||||
|
||||
fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, A::Error> {
|
||||
visitor.visit_enum(self)
|
||||
}
|
||||
|
||||
forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
|
||||
option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum
|
||||
identifier ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, A: MapAccess<'de>> EnumAccess<'de> for Tagged<A> {
|
||||
type Error = A::Error;
|
||||
type Variant = Fields<A>;
|
||||
|
||||
fn variant_seed<V: DeserializeSeed<'de>>(self, seed: V) -> Result<(V::Value, Fields<A>), A::Error> {
|
||||
let kind = seed.deserialize(self.tag.into_deserializer())?;
|
||||
Ok((kind, Fields(self.map)))
|
||||
}
|
||||
}
|
||||
|
||||
/// A kind's fields: the rest of the object.
|
||||
struct Fields<A>(A);
|
||||
|
||||
impl<'de, A: MapAccess<'de>> VariantAccess<'de> for Fields<A> {
|
||||
type Error = A::Error;
|
||||
|
||||
fn unit_variant(self) -> Result<(), A::Error> {
|
||||
Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"an object kind with fields"))
|
||||
}
|
||||
|
||||
fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value, A::Error> {
|
||||
seed.deserialize(MapAccessDeserializer::new(self.0))
|
||||
}
|
||||
|
||||
fn tuple_variant<V: Visitor<'de>>(self, _: usize, _: V) -> Result<V::Value, A::Error> {
|
||||
Err(de::Error::invalid_type(de::Unexpected::TupleVariant, &"an object kind with fields"))
|
||||
}
|
||||
|
||||
fn struct_variant<V: Visitor<'de>>(self, _: &'static [&'static str], visitor: V) -> Result<V::Value, A::Error> {
|
||||
visitor.visit_map(self.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
use super::*;
|
||||
|
||||
/// Live shape parameters (Illustrator's "Live Shapes"). The node's path is regenerated from these
|
||||
/// while the shape stays live; editing anchors directly converts it to a plain path.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "shape", rename_all = "lowercase")]
|
||||
pub enum LiveShape {
|
||||
Rectangle {
|
||||
/// Untransformed width/height. Transforms fold their scale into these (see
|
||||
/// [`LiveShape::transform`]), so they are document lengths unless `xf` shears.
|
||||
w: f64,
|
||||
h: f64,
|
||||
/// Corner radii: top-left, top-right, bottom-right, bottom-left. In the same units as
|
||||
/// `w`/`h`: the corners are circular arcs in the document whenever `xf` doesn't scale.
|
||||
radii: [f64; 4],
|
||||
/// Corner kinds, in the same order (Live Corners' corner types).
|
||||
#[serde(default, skip_serializing_if = "all_round")]
|
||||
kinds: [CornerKind; 4],
|
||||
/// When true, `radii` are fractions in 0..1 of each corner's largest possible radius.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
radii_relative: bool,
|
||||
/// Maps the untransformed shape (origin at its top-left) into the document. A rotation
|
||||
/// or reflection plus a move, unless a shear (or a file saved before transforms folded
|
||||
/// their scale into `w`/`h`) put more in it.
|
||||
xf: Affine,
|
||||
},
|
||||
Ellipse {
|
||||
w: f64,
|
||||
h: f64,
|
||||
/// Pie start/end angles in degrees (0/360 = full ellipse).
|
||||
pie: (f64, f64),
|
||||
xf: Affine,
|
||||
},
|
||||
Polygon {
|
||||
radius: f64,
|
||||
/// 3–1000, as [`LiveShape::set_sides`] gives it; a file's count is clamped when read.
|
||||
#[serde(deserialize_with = "de_sides")]
|
||||
sides: u32,
|
||||
xf: Affine,
|
||||
/// Corner radii in document units, by vertex from the first one clockwise (none: sharp).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
radii: Vec<f64>,
|
||||
/// Corner kinds, in the same order (none: round).
|
||||
#[serde(default, skip_serializing_if = "all_round")]
|
||||
kinds: Vec<CornerKind>,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
radii_relative: bool,
|
||||
},
|
||||
Line {
|
||||
a: Point,
|
||||
b: Point,
|
||||
},
|
||||
/// Any other path whose corners Live Corners cut (a star, a pen path): it keeps its uncut
|
||||
/// outline so the corners stay editable. Without a cut corner it is a plain path again.
|
||||
Path {
|
||||
/// The path with its corners uncut, in the document.
|
||||
base: PathData,
|
||||
/// Corner radii in document units, by anchor index of `base` (counting every subpath's
|
||||
/// anchors in order; missing: sharp).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
radii: Vec<f64>,
|
||||
/// Corner kinds, in the same order (missing: round).
|
||||
#[serde(default, skip_serializing_if = "all_round")]
|
||||
kinds: Vec<CornerKind>,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
radii_relative: bool,
|
||||
},
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
impl LiveShape {
|
||||
pub fn radii_relative(&self) -> bool {
|
||||
match self {
|
||||
LiveShape::Rectangle { radii_relative, .. } | LiveShape::Polygon { radii_relative, .. } | LiveShape::Path { radii_relative, .. } => {
|
||||
*radii_relative
|
||||
}
|
||||
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => false,
|
||||
}
|
||||
}
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
LiveShape::Rectangle { radii, .. } if radii.iter().any(|r| *r > 0.0) => "Rounded Rectangle",
|
||||
LiveShape::Rectangle { .. } => "Rectangle",
|
||||
LiveShape::Ellipse { .. } => "Ellipse",
|
||||
LiveShape::Polygon { .. } => "Polygon",
|
||||
LiveShape::Line { .. } => "Line",
|
||||
LiveShape::Path { .. } => "Path",
|
||||
}
|
||||
}
|
||||
/// Regenerate the path.
|
||||
pub fn to_path(&self) -> PathData {
|
||||
match self {
|
||||
LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } => {
|
||||
let base = shapes::rectangle(Rect::new(0.0, 0.0, *w, *h));
|
||||
let resolved = crate::corners::resolve_stored_radii(&base, radii, *radii_relative);
|
||||
let radii = std::array::from_fn(|i| resolved.get(i).copied().unwrap_or(0.0));
|
||||
shapes::rectangle_with_corners(Rect::new(0.0, 0.0, *w, *h), radii, *kinds).transformed(*xf)
|
||||
}
|
||||
LiveShape::Ellipse { w, h, pie, xf } => shapes::ellipse_pie(Rect::new(0.0, 0.0, *w, *h), pie.0, pie.1).transformed(*xf),
|
||||
LiveShape::Polygon { radii, kinds, radii_relative, .. } => {
|
||||
let outline = self.polygon_outline();
|
||||
let radii = crate::corners::resolve_stored_radii(&outline, radii, *radii_relative);
|
||||
cut_corners(&outline, &radii, kinds).0
|
||||
}
|
||||
LiveShape::Line { a, b } => shapes::line(*a, *b),
|
||||
LiveShape::Path { base, radii, kinds, radii_relative } => {
|
||||
let radii = crate::corners::resolve_stored_radii(base, radii, *radii_relative);
|
||||
cut_corners(base, &radii, kinds).0
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A polygon's outline with its corners uncut, in the document (empty for other shapes).
|
||||
pub fn polygon_outline(&self) -> PathData {
|
||||
match self {
|
||||
LiveShape::Polygon { radius, sides, xf, .. } => shapes::polygon(Point::ZERO, *radius, *sides, 0.0).transformed(*xf),
|
||||
_ => PathData::default(),
|
||||
}
|
||||
}
|
||||
/// Give a polygon `n` sides (3–1000). Its corners keep the radius and kind they shared; else
|
||||
/// the corners past the old last one are sharp.
|
||||
pub fn set_sides(&mut self, n: u64) {
|
||||
let LiveShape::Polygon { sides, radii, kinds, .. } = self else { return };
|
||||
*sides = n.clamp(3, 1000) as u32;
|
||||
fn spread<T: Copy + PartialEq + Default>(v: &mut Vec<T>, n: usize) {
|
||||
match v.first().copied() {
|
||||
Some(x) if v.iter().all(|y| *y == x) => *v = vec![x; n],
|
||||
Some(_) => v.resize(n, T::default()),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
spread(radii, *sides as usize);
|
||||
spread(kinds, *sides as usize);
|
||||
}
|
||||
/// A polygon's radius in the document, centre to vertex: its own radius by the mean scale of
|
||||
/// `xf` (exact while its sides are equal). None for other shapes.
|
||||
pub fn polygon_radius(&self) -> Option<f64> {
|
||||
let LiveShape::Polygon { radius, xf, .. } = self else { return None };
|
||||
Some(radius * xf.determinant().abs().sqrt())
|
||||
}
|
||||
/// A polygon's angle: the counterclockwise degrees in [0, 360) its first vertex is turned by
|
||||
/// from straight up (the Rotate field's sense). None for other shapes.
|
||||
pub fn polygon_angle(&self) -> Option<f64> {
|
||||
let LiveShape::Polygon { .. } = self else { return None };
|
||||
// No −0° or 360° from rounding: a polygon drawn upright reads 0°.
|
||||
let a = (-self.angle_deg()).rem_euclid(360.0);
|
||||
Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 })
|
||||
}
|
||||
/// Whether a polygon's sides are all as long: `xf` scales it evenly and doesn't shear it. True
|
||||
/// for other shapes.
|
||||
pub fn polygon_sides_equal(&self) -> bool {
|
||||
let LiveShape::Polygon { xf, .. } = self else { return true };
|
||||
let [a, b, c, d, _, _] = xf.as_coeffs();
|
||||
let (sx, sy) = (a.hypot(b), c.hypot(d));
|
||||
(sx - sy).abs() <= 1e-9 * sx.max(sy) && (a * c + b * d).abs() <= 1e-9 * sx * sy
|
||||
}
|
||||
/// Give a polygon the document radius `r` (centre to vertex, see [`LiveShape::polygon_radius`]).
|
||||
pub fn set_polygon_radius(&mut self, r: f64) {
|
||||
let LiveShape::Polygon { radius, xf, .. } = self else { return };
|
||||
let k = xf.determinant().abs().sqrt();
|
||||
if k > 1e-12 && r.is_finite() {
|
||||
*radius = r.max(0.0) / k;
|
||||
}
|
||||
}
|
||||
/// The document radius that makes a polygon's sides `side` long (with its sides equal).
|
||||
pub fn polygon_radius_for_side(&self, side: f64) -> Option<f64> {
|
||||
let LiveShape::Polygon { sides, .. } = self else { return None };
|
||||
Some(side / (2.0 * (std::f64::consts::PI / f64::from((*sides).max(3))).sin()))
|
||||
}
|
||||
/// Turn a polygon about its centre to `angle` (degrees, as [`LiveShape::polygon_angle`]).
|
||||
pub fn set_polygon_angle(&mut self, angle: f64) {
|
||||
let Some(now) = self.polygon_angle() else { return };
|
||||
if let LiveShape::Polygon { xf, .. } = self
|
||||
&& angle.is_finite()
|
||||
{
|
||||
let centre = *xf * Point::ZERO;
|
||||
*xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf;
|
||||
}
|
||||
}
|
||||
/// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from
|
||||
/// `xf`, keeping its centre, angle, reflection and [`LiveShape::polygon_radius`].
|
||||
pub fn make_sides_equal(&mut self) {
|
||||
let Some(r) = self.polygon_radius() else { return };
|
||||
let LiveShape::Polygon { radius, xf, .. } = self else { return };
|
||||
let [a, b, _, _, e, f] = xf.as_coeffs();
|
||||
let flip = if xf.determinant() < 0.0 { Affine::FLIP_Y } else { Affine::IDENTITY };
|
||||
*xf = Affine::translate((e, f)) * Affine::rotate(b.atan2(a)) * flip;
|
||||
*radius = r;
|
||||
}
|
||||
/// Apply `a` to the shape. True when the shape is no longer `a` applied to the old path, so
|
||||
/// the caller must regenerate the path with [`LiveShape::to_path`].
|
||||
///
|
||||
/// A rectangle keeps round corners whatever its proportions: when `a` scales it along its own
|
||||
/// sides (any rotation or reflection, no shear), the scale goes into `w`/`h` and `xf` keeps
|
||||
/// only the rotation, reflection and position. The radii scale by the mean scale (the square
|
||||
/// root of the determinant), which [`LiveShape::keep_corners`] undoes for Scale Corners off.
|
||||
/// A shear can't keep circular corners: `xf` takes it, as do moves (so files saved with a
|
||||
/// scale in `xf` keep their exact geometry until they're next transformed). A polygon's or a
|
||||
/// path's corner radii are document lengths: they scale by the mean scale and the corners are
|
||||
/// cut again, circular whatever `a` does.
|
||||
pub fn transform(&mut self, a: Affine) -> bool {
|
||||
match self {
|
||||
LiveShape::Rectangle { xf, .. } => {
|
||||
*xf = a * *xf;
|
||||
!moves_only(a) && self.fold_scale()
|
||||
}
|
||||
LiveShape::Ellipse { xf, .. } => {
|
||||
*xf = a * *xf;
|
||||
false
|
||||
}
|
||||
LiveShape::Polygon { xf, radii, radii_relative, .. } => {
|
||||
*xf = a * *xf;
|
||||
scale_radii(radii, a, *radii_relative)
|
||||
}
|
||||
LiveShape::Path { base, radii, radii_relative, .. } => {
|
||||
base.transform(a);
|
||||
scale_radii(radii, a, *radii_relative)
|
||||
}
|
||||
LiveShape::Line { a: p, b } => {
|
||||
*p = a * *p;
|
||||
*b = a * *b;
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Move the scale of a rectangle's `xf` into `w`/`h` (and its radii, by the mean scale), so
|
||||
/// `xf` keeps only a rotation or reflection plus a move and the corners are circular in the
|
||||
/// document. False (and nothing changes) when there is no scale to move, when `xf` shears or
|
||||
/// isn't finite, and for other shapes. Files saved before transforms did this (#291) carry an
|
||||
/// uneven scale in `xf`: their corners are elliptical until this runs.
|
||||
pub fn fold_scale(&mut self) -> bool {
|
||||
let LiveShape::Rectangle { w, h, radii, radii_relative, xf, .. } = self else { return false };
|
||||
let [m0, m1, m2, m3, m4, m5] = xf.as_coeffs();
|
||||
let (sx, sy) = (m0.hypot(m1), m2.hypot(m3));
|
||||
let orthogonal = sx > 1e-12 && sy > 1e-12 && (m0 * m2 + m1 * m3).abs() <= 1e-9 * sx * sy;
|
||||
let finite = xf.as_coeffs().iter().all(|c| c.is_finite()) && w.is_finite() && h.is_finite();
|
||||
let unscaled = (sx - 1.0).abs() < 1e-12 && (sy - 1.0).abs() < 1e-12;
|
||||
if !orthogonal || !finite || unscaled {
|
||||
return false;
|
||||
}
|
||||
let k = (sx * sy).sqrt();
|
||||
if !*radii_relative {
|
||||
radii.iter_mut().for_each(|r| *r *= k);
|
||||
}
|
||||
*w *= sx;
|
||||
*h *= sy;
|
||||
*xf = Affine::new([m0 / sx, m1 / sx, m2 / sy, m3 / sy, m4, m5]);
|
||||
true
|
||||
}
|
||||
/// This shape with [`LiveShape::fold_scale`] applied: a rectangle's size and radii in document
|
||||
/// units (what Live Corners show and edit).
|
||||
pub fn folded(&self) -> Self {
|
||||
let mut s = self.clone();
|
||||
s.fold_scale();
|
||||
s
|
||||
}
|
||||
/// Divide live corner radii by `k`, the mean scale of a transform just applied, so the corners
|
||||
/// keep their size (Scale Corners off). False when nothing changed.
|
||||
pub fn keep_corners(&mut self, k: f64) -> bool {
|
||||
let relative = self.radii_relative();
|
||||
let radii: &mut [f64] = match self {
|
||||
LiveShape::Rectangle { radii, .. } => radii,
|
||||
LiveShape::Polygon { radii, .. } | LiveShape::Path { radii, .. } => radii,
|
||||
LiveShape::Ellipse { .. } | LiveShape::Line { .. } => return false,
|
||||
};
|
||||
if relative || !radii.iter().any(|r| *r > 0.0) || k <= 1e-12 {
|
||||
return false;
|
||||
}
|
||||
radii.iter_mut().for_each(|r| *r /= k);
|
||||
true
|
||||
}
|
||||
/// Rotation angle of the live shape in degrees, clockwise on the page (y points down).
|
||||
pub fn angle_deg(&self) -> f64 {
|
||||
match self {
|
||||
LiveShape::Rectangle { xf, .. } | LiveShape::Ellipse { xf, .. } | LiveShape::Polygon { xf, .. } => {
|
||||
let c = xf.as_coeffs();
|
||||
c[1].atan2(c[0]).to_degrees()
|
||||
}
|
||||
LiveShape::Line { a, b } => (b.y - a.y).atan2(b.x - a.x).to_degrees(),
|
||||
LiveShape::Path { .. } => 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn all_round(kinds: &[CornerKind]) -> bool {
|
||||
kinds.iter().all(|k| *k == CornerKind::Round)
|
||||
}
|
||||
|
||||
/// A polygon's side count read from a file, clamped as the commands clamp it: the outline and its
|
||||
/// corner lists hold one entry per side, so a huge count would allocate gigabytes.
|
||||
fn de_sides<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
|
||||
u32::deserialize(d).map(|n| n.clamp(3, 1000))
|
||||
}
|
||||
|
||||
/// Whether `a` only moves (no rotation, scale, shear or reflection).
|
||||
pub(super) fn moves_only(a: Affine) -> bool {
|
||||
let [a0, a1, a2, a3, _, _] = a.as_coeffs();
|
||||
(a0 - 1.0).abs() < 1e-12 && a1.abs() < 1e-12 && a2.abs() < 1e-12 && (a3 - 1.0).abs() < 1e-12
|
||||
}
|
||||
|
||||
/// Scale corner radii in document units by the mean scale of `a`, applied to their path. True
|
||||
/// when the path must be cut again: some corner is cut and `a` does more than move it (an
|
||||
/// uneven scale would otherwise make the cuts elliptical).
|
||||
fn scale_radii(radii: &mut [f64], a: Affine, relative: bool) -> bool {
|
||||
if relative || moves_only(a) || !radii.iter().any(|r| *r > 0.0) {
|
||||
return false;
|
||||
}
|
||||
let k = a.determinant().abs().sqrt();
|
||||
radii.iter_mut().for_each(|r| *r *= k);
|
||||
true
|
||||
}
|
||||
|
||||
/// What a transform scales besides geometry, by its mean scale (the square root of its
|
||||
/// determinant). `Scaling::default()` (and `false`) scales nothing else; `true` scales stroke
|
||||
/// weights and dashes only. Transforms the user asks for take theirs from Scale Strokes & Effects
|
||||
/// and Scale Corners.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Scaling {
|
||||
/// Stroke weights, dash lengths and dash offsets scale.
|
||||
pub strokes: bool,
|
||||
/// With `strokes`: scales an effect's distance parameters (the effects catalogue's).
|
||||
pub effects: Option<fn(&mut crate::Effect, f64)>,
|
||||
/// Type keeps its character strokes' weight (they otherwise scale with the type).
|
||||
pub keep_type_strokes: bool,
|
||||
/// Live corner radii keep their size.
|
||||
pub keep_corners: bool,
|
||||
/// Pattern fills and strokes move with the art (Transform Patterns; General › Transform
|
||||
/// Pattern Tiles is its default): their tiles transform too, instead of staying put.
|
||||
pub patterns: bool,
|
||||
}
|
||||
|
||||
impl Scaling {
|
||||
/// The mean scale of `a` when it scales (isn't 1): what strokes, effects and corners scale by.
|
||||
pub fn factor(a: Affine) -> Option<f64> {
|
||||
let k = a.determinant().abs().sqrt();
|
||||
((k - 1.0).abs() > 1e-9).then_some(k)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bool> for Scaling {
|
||||
fn from(strokes: bool) -> Self {
|
||||
Self { strokes, ..Self::default() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
use super::kind::NodeKind;
|
||||
use super::*;
|
||||
|
||||
/// Opacity mask: the luminance of the mask art sets the object's opacity (white = opaque).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct OpacityMask {
|
||||
/// Mask art in document coordinates.
|
||||
pub art: Arc<Node>,
|
||||
/// Clip: outside the mask art is hidden. Off: outside the mask art stays visible.
|
||||
#[serde(default = "yes")]
|
||||
pub clip: bool,
|
||||
/// Invert the mask's luminance.
|
||||
#[serde(default)]
|
||||
pub invert: bool,
|
||||
/// Disabled masks are kept but not applied.
|
||||
#[serde(default)]
|
||||
pub disabled: bool,
|
||||
/// Linked masks move with the object.
|
||||
#[serde(default = "yes")]
|
||||
pub linked: bool,
|
||||
}
|
||||
|
||||
impl OpacityMask {
|
||||
pub fn new(art: Node, clip: bool) -> Self {
|
||||
Self { art: Arc::new(art), clip, invert: false, disabled: false, linked: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// Every paint of `n` (and its children) white, opacities kept: an alpha mask's art as an opacity
|
||||
/// mask's, whose luminance over the black outside the art is then the art's alpha.
|
||||
pub fn whiten(n: &mut Node) {
|
||||
let white = |p: &mut Paint| match p {
|
||||
Paint::Solid { color, swatch, tint } => {
|
||||
(*color, *swatch, *tint) = (Color::WHITE, None, 1.0);
|
||||
}
|
||||
Paint::Gradient(g) => {
|
||||
for s in &mut g.gradient.stops {
|
||||
(s.color, s.swatch, s.tint) = (Color::WHITE, None, 1.0);
|
||||
}
|
||||
}
|
||||
Paint::None | Paint::Pattern { .. } => {}
|
||||
};
|
||||
for item in &mut n.appearance.items {
|
||||
white(item.paint_mut());
|
||||
}
|
||||
match &mut n.kind {
|
||||
NodeKind::Mesh(m) => m.points.iter_mut().for_each(|p| p.color = Color::WHITE),
|
||||
NodeKind::Text(t) => t.runs.iter_mut().for_each(|r| {
|
||||
white(&mut r.style.fill);
|
||||
white(&mut r.style.stroke);
|
||||
}),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch {
|
||||
whiten(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Knockout Group state of a container (the Transparency panel's three-state checkbox). In a
|
||||
/// knockout group each child composites against the group's backdrop, so it hides the children
|
||||
/// below it instead of showing them through its transparency. Neutral passes the enclosing
|
||||
/// group's setting through to the children. Files from before the three states stored a bool:
|
||||
/// `true` loads as On, `false` as Neutral.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum Knockout {
|
||||
#[default]
|
||||
Neutral,
|
||||
Off,
|
||||
On,
|
||||
}
|
||||
|
||||
impl Knockout {
|
||||
pub const ALL: [Knockout; 3] = [Knockout::Neutral, Knockout::Off, Knockout::On];
|
||||
|
||||
/// Name in files and command parameters.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Knockout::Neutral => "neutral",
|
||||
Knockout::Off => "off",
|
||||
Knockout::On => "on",
|
||||
}
|
||||
}
|
||||
/// A name ([`Self::label`], any case) or a bool as older files and commands wrote it.
|
||||
pub fn from_value(v: &serde_json::Value) -> Option<Self> {
|
||||
match v {
|
||||
serde_json::Value::Bool(b) => Some(Self::from(*b)),
|
||||
serde_json::Value::String(s) => Self::ALL.into_iter().find(|k| k.label().eq_ignore_ascii_case(s.trim())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// The state a click on the checkbox moves to: on → neutral → off → on.
|
||||
pub fn cycle(self) -> Self {
|
||||
match self {
|
||||
Knockout::On => Knockout::Neutral,
|
||||
Knockout::Neutral => Knockout::Off,
|
||||
Knockout::Off => Knockout::On,
|
||||
}
|
||||
}
|
||||
/// Whether children of a group with this state knock each other out, inside a group (or page)
|
||||
/// where that is `enclosing`.
|
||||
pub fn resolve(self, enclosing: bool) -> bool {
|
||||
match self {
|
||||
Knockout::Neutral => enclosing,
|
||||
Knockout::Off => false,
|
||||
Knockout::On => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bool> for Knockout {
|
||||
fn from(b: bool) -> Self {
|
||||
if b { Knockout::On } else { Knockout::Neutral }
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Knockout {
|
||||
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(self.label())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Knockout {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let v = serde_json::Value::deserialize(d)?;
|
||||
Self::from_value(&v).ok_or_else(|| serde::de::Error::custom(format!("invalid knockout {v}")))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,712 @@
|
||||
use super::extras::Extras;
|
||||
use super::ids::{LayerColor, NodeId};
|
||||
use super::kind::NodeKind;
|
||||
use super::live_shape::{Scaling, moves_only};
|
||||
use super::opacity::Knockout;
|
||||
use super::*;
|
||||
|
||||
impl Node {
|
||||
pub fn new(id: NodeId, kind: NodeKind) -> Self {
|
||||
Self {
|
||||
id,
|
||||
name: None,
|
||||
visible: true,
|
||||
locked: false,
|
||||
opacity: 1.0,
|
||||
blend: BlendMode::Normal,
|
||||
isolate: false,
|
||||
knockout: Knockout::Neutral,
|
||||
knockout_shape: false,
|
||||
appearance: Appearance::default().into(),
|
||||
kind,
|
||||
bbox_angle: 0.0,
|
||||
extras: Extras::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn path(id: NodeId, path: PathData, appearance: Appearance) -> Self {
|
||||
let mut n = Self::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false });
|
||||
n.appearance = appearance.into();
|
||||
n
|
||||
}
|
||||
|
||||
pub fn group(id: NodeId, children: Vec<Arc<Node>>) -> Self {
|
||||
Self::new(id, NodeKind::Group { children, clip: false })
|
||||
}
|
||||
|
||||
pub fn layer(id: NodeId, name: &str, color: LayerColor) -> Self {
|
||||
let mut n = Self::new(
|
||||
id,
|
||||
NodeKind::Layer { color, template: false, printable: true, children: vec![], clip: false, preview: true, dim_images: None },
|
||||
);
|
||||
n.name = Some(name.to_string());
|
||||
n
|
||||
}
|
||||
|
||||
pub fn children(&self) -> Option<&Vec<Arc<Node>>> {
|
||||
match &self.kind {
|
||||
NodeKind::Layer { children, .. }
|
||||
| NodeKind::Group { children, .. }
|
||||
| NodeKind::Compound { children, .. }
|
||||
| NodeKind::Blend { children, .. }
|
||||
| NodeKind::Envelope { content: children, .. }
|
||||
| NodeKind::Repeat(RepeatSpec { source: children, .. })
|
||||
| NodeKind::Intertwine { children } => Some(children),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn children_mut(&mut self) -> Option<&mut Vec<Arc<Node>>> {
|
||||
match &mut self.kind {
|
||||
NodeKind::Layer { children, .. }
|
||||
| NodeKind::Group { children, .. }
|
||||
| NodeKind::Compound { children, .. }
|
||||
| NodeKind::Blend { children, .. }
|
||||
| NodeKind::Envelope { content: children, .. }
|
||||
| NodeKind::Repeat(RepeatSpec { source: children, .. })
|
||||
| NodeKind::Intertwine { children } => Some(children),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Does this object or layer move with its artboard? Locked and hidden ones only with
|
||||
/// `locked_and_hidden` (Selection & Anchor Display › Move Locked and Hidden Artwork with
|
||||
/// Artboard).
|
||||
pub fn rides_with_artboard(&self, locked_and_hidden: bool) -> bool {
|
||||
locked_and_hidden || (!self.locked && self.visible)
|
||||
}
|
||||
|
||||
pub fn is_layer(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::Layer { .. })
|
||||
}
|
||||
|
||||
/// A template layer (Layer Options → Template).
|
||||
pub fn is_template(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::Layer { template: true, .. })
|
||||
}
|
||||
|
||||
/// The art objects of this container: its children, looking through sublayers, which are not
|
||||
/// objects (bottom first). With `editable`, only the visible, unlocked objects in visible,
|
||||
/// unlocked, non-template sublayers.
|
||||
pub fn layer_art(&self, editable: bool) -> Vec<NodeId> {
|
||||
fn visit(n: &Node, editable: bool, out: &mut Vec<NodeId>) {
|
||||
for c in n.children().into_iter().flatten() {
|
||||
if editable && (!c.visible || c.locked || c.is_template()) {
|
||||
continue;
|
||||
}
|
||||
if c.is_layer() {
|
||||
visit(c, editable, out);
|
||||
} else {
|
||||
out.push(c.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
visit(self, editable, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
pub fn is_container(&self) -> bool {
|
||||
self.children().is_some()
|
||||
}
|
||||
|
||||
/// Full opacity, Normal blending, no isolation, knockout or opacity mask (the Layers panel
|
||||
/// fills an object's target circle otherwise).
|
||||
pub fn has_default_transparency(&self) -> bool {
|
||||
self.opacity >= 1.0
|
||||
&& self.blend == BlendMode::Normal
|
||||
&& !self.isolate
|
||||
&& self.knockout == Knockout::Neutral
|
||||
&& !self.knockout_shape
|
||||
&& self.extras().mask.is_none()
|
||||
}
|
||||
|
||||
/// Kind name as the Layers panel / Properties panel shows it.
|
||||
pub fn kind_label(&self) -> &'static str {
|
||||
match &self.kind {
|
||||
NodeKind::Layer { .. } => "Layer",
|
||||
NodeKind::Group { clip: true, .. } => "Clip Group",
|
||||
NodeKind::Group { .. } if self.extras().objects_on_path.is_some() => "Objects on Path",
|
||||
NodeKind::Group { .. } => "Group",
|
||||
NodeKind::Path { live: Some(l), .. } => l.label(),
|
||||
NodeKind::Path { guide: true, .. } => "Guide",
|
||||
NodeKind::Path { .. } => "Path",
|
||||
NodeKind::Compound { .. } => "Compound Path",
|
||||
NodeKind::Text(_) => "Type",
|
||||
NodeKind::Image(_) => "Image",
|
||||
NodeKind::SymbolInstance { .. } => "Symbol",
|
||||
NodeKind::Blend { .. } => "Blend",
|
||||
NodeKind::Envelope { .. } => "Envelope",
|
||||
NodeKind::Mesh(_) => "Mesh",
|
||||
NodeKind::Repeat(r) => r.kind.label(),
|
||||
NodeKind::PlacedDocument(_) => "Placed Document",
|
||||
NodeKind::Intertwine { .. } => "Intertwine",
|
||||
}
|
||||
}
|
||||
|
||||
/// Name shown in the Layers panel: explicit name or `<Kind>`.
|
||||
pub fn display_name(&self) -> String {
|
||||
if let Some(n) = &self.name {
|
||||
return n.clone();
|
||||
}
|
||||
match &self.kind {
|
||||
NodeKind::Text(t) => {
|
||||
let s: String = t.plain_text().chars().take(32).collect();
|
||||
if s.is_empty() { "<Text>".into() } else { s }
|
||||
}
|
||||
_ => format!("<{}>", self.kind_label()),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::display_name`], or its XML id when Preferences › Units › Identify Objects By is XML ID.
|
||||
pub fn identify_label(&self, xml_id: bool) -> String {
|
||||
let name = self.display_name();
|
||||
if xml_id { crate::xml_id::from_object_name(&name) } else { name }
|
||||
}
|
||||
|
||||
/// Path data for path nodes.
|
||||
pub fn path_data(&self) -> Option<&PathData> {
|
||||
match &self.kind {
|
||||
NodeKind::Path { path, .. } => Some(path),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn path_data_mut(&mut self) -> Option<&mut PathData> {
|
||||
match &mut self.kind {
|
||||
NodeKind::Path { path, .. } => Some(path),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The path a path's or compound path's own strokes follow (a compound's members' together).
|
||||
pub fn stroke_path(&self) -> Option<vectorcraft_geom::BezPath> {
|
||||
match &self.kind {
|
||||
NodeKind::Path { path, .. } => Some(path.to_bezpath()),
|
||||
NodeKind::Compound { children, .. } => {
|
||||
let mut bp = vectorcraft_geom::BezPath::new();
|
||||
children.iter().filter_map(|c| c.path_data()).for_each(|pd| bp.extend(pd.to_bezpath()));
|
||||
Some(bp)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A quick box round everything the object can paint, for culling clicks: paths and compound
|
||||
/// paths grow their geometric bounds by the farthest their strokes can reach from any path
|
||||
/// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in
|
||||
/// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers
|
||||
/// without a clipping mask and Intertwine groups take in their members' boxes, grown by their
|
||||
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`].
|
||||
pub fn reach_bounds(&self) -> Option<Rect> {
|
||||
self.reach(None)
|
||||
}
|
||||
|
||||
/// [`Node::reach_bounds`] with symbol instances measured by their symbol's art box from
|
||||
/// `symbols`. An instance that only moves its art is measured as the art's visual box moved,
|
||||
/// and any other instance is measured as its geometric box ([`Node::geometric_bounds_with`])
|
||||
/// grown by the farthest a stroke in the art can reach.
|
||||
pub fn reach_bounds_with(&self, symbols: &SymbolBoxes) -> Option<Rect> {
|
||||
symbols.quickly(|| self.reach(Some(symbols)))
|
||||
}
|
||||
|
||||
/// The box of [`Node::reach_bounds`], or of [`Node::reach_bounds_with`] when `symbols` is given.
|
||||
pub(crate) fn reach(&self, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
|
||||
match &self.kind {
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
|
||||
let o = self.appearance.outset();
|
||||
self.geometric(symbols).map(|b| b.inflate(o, o))
|
||||
}
|
||||
// The members' reach, grown by the container's own strokes.
|
||||
NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => {
|
||||
let o = self.appearance.outset();
|
||||
children
|
||||
.iter()
|
||||
.skip(usize::from(self.extras().shaper.is_some()))
|
||||
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols)))
|
||||
.map(|b| b.inflate(o, o))
|
||||
}
|
||||
NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))),
|
||||
// The frame and each shape the image's own fills and strokes paint, a stroke's grown by
|
||||
// the farthest it can reach from its shape.
|
||||
NodeKind::Image(_) => crate::hit::image_paint(self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| {
|
||||
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
|
||||
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
|
||||
}),
|
||||
_ => self.visual(symbols),
|
||||
}
|
||||
}
|
||||
|
||||
/// Geometric bounds (no stroke), recursively. Clip groups are bounded by their clip path. A
|
||||
/// symbol instance is measured as its transform applied to the 20 × 20 square around the origin
|
||||
/// that symbols made in the app keep their art in ([`Node::geometric_bounds_with`] measures
|
||||
/// its art).
|
||||
pub fn geometric_bounds(&self) -> Option<Rect> {
|
||||
self.geometric(None)
|
||||
}
|
||||
|
||||
/// [`Node::geometric_bounds`] with each symbol instance measured as its transform applied to
|
||||
/// its symbol's art box from `symbols`. An instance is measured as the square when its symbol
|
||||
/// is missing, when its symbol or a symbol nested in its art holds an instance of itself, and
|
||||
/// when symbols nest 32 deep in its art.
|
||||
pub fn geometric_bounds_with(&self, symbols: &SymbolBoxes) -> Option<Rect> {
|
||||
self.geometric(Some(symbols))
|
||||
}
|
||||
|
||||
/// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a
|
||||
/// hidden bitmap for re-tracing/release; only source-image views measure that bitmap.
|
||||
pub fn editing_children(&self) -> &[Arc<Node>] {
|
||||
let children = self.children().map(Vec::as_slice).unwrap_or_default();
|
||||
let trace_source = self.extras().trace.is_some()
|
||||
&& !self.trace_view().shows_source()
|
||||
&& children.first().is_some_and(|n| !n.visible && matches!(n.kind, NodeKind::Image(_)));
|
||||
let skip = usize::from(self.extras().shaper.is_some() || trace_source);
|
||||
children.get(skip..).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The box of [`Node::geometric_bounds`], or of [`Node::geometric_bounds_with`] when `symbols`
|
||||
/// is given.
|
||||
pub(crate) fn geometric(&self, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
|
||||
let union = |nodes: &[Arc<Node>]| nodes.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric(symbols)));
|
||||
match &self.kind {
|
||||
NodeKind::Path { path, .. } => path.bounds(),
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
|
||||
children.first().and_then(|c| c.geometric(symbols))
|
||||
}
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. } => self
|
||||
.editing_children()
|
||||
.iter()
|
||||
.filter(|c| c.visible || !matches!(self.kind, NodeKind::Layer { .. }))
|
||||
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric(symbols))),
|
||||
NodeKind::Text(t) => self.projected(t.bounds()),
|
||||
NodeKind::Image(im) => Some(im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, im.width as f64, im.height as f64))),
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let art = symbols.and_then(|s| s.art(symbol)).map_or(SYMBOL_SQUARE, |a| a.geometric);
|
||||
self.projected(Some(xf.transform_rect_bbox(art)))
|
||||
}
|
||||
NodeKind::Blend { children, spec } => vectorcraft_geom::union_opt(union(children), spec.spine.as_ref().and_then(|s| s.bounds())),
|
||||
NodeKind::Envelope { content, kind, frame, .. } => crate::live::envelope_bounds(content, kind, **frame),
|
||||
NodeKind::Mesh(m) => m.bounds(),
|
||||
// Each copy is measured where the repeat draws it: `RepeatSpec::transforms` lays the
|
||||
// copies out by the source's bounds measured without the document.
|
||||
NodeKind::Repeat(r) => r.copies_bounds(union(&r.source)?, symbols.map(|s| s.document())),
|
||||
NodeKind::PlacedDocument(p) => Some(p.bounds()),
|
||||
// The members drawn over the others are drawn where they are.
|
||||
NodeKind::Intertwine { children } => union(children),
|
||||
}
|
||||
}
|
||||
|
||||
/// Visual bounds: what the object paints, its strokes included (paths and compound paths
|
||||
/// measure theirs along their own shape, see [`Appearance::stroked_bounds`]). An image is
|
||||
/// measured by its frame. A symbol instance is measured as in [`Node::geometric_bounds`],
|
||||
/// grown by its own strokes' reach ([`Node::visual_bounds_with`] measures its art).
|
||||
pub fn visual_bounds(&self) -> Option<Rect> {
|
||||
self.visual(None)
|
||||
}
|
||||
|
||||
/// [`Node::visual_bounds`] with symbol instances measured by their symbol's art from
|
||||
/// `symbols`, the strokes in it included. An instance that only moves its art is measured as
|
||||
/// the art's visual box moved. Any other instance is measured as its art transformed by it with
|
||||
/// the strokes at their own weight, as the renderer draws it, and never smaller than its
|
||||
/// geometric box ([`Node::geometric_bounds_with`]). Instances inside symbol art are measured as
|
||||
/// in [`Node::reach_bounds_with`]. In boxes made by [`SymbolBoxes::with_brush_art`], the box of
|
||||
/// an instance whose art holds brushed strokes grows by as far as their brush art can paint. In
|
||||
/// boxes made by [`SymbolBoxes::without_art_strokes`], an instance is measured as its art's
|
||||
/// geometric box placed by its transform, grown by its own strokes.
|
||||
pub fn visual_bounds_with(&self, symbols: &SymbolBoxes) -> Option<Rect> {
|
||||
self.visual(Some(symbols))
|
||||
}
|
||||
|
||||
/// The box of [`Node::visual_bounds`], or of [`Node::visual_bounds_with`] when `symbols` is
|
||||
/// given.
|
||||
pub(crate) fn visual(&self, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
|
||||
match &self.kind {
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
|
||||
// A clipping path that paints (see `clip_paint`) strokes over the clip edge.
|
||||
let clip = children.first()?;
|
||||
if matches!(clip.kind, NodeKind::Path { .. } | NodeKind::Compound { .. } | NodeKind::Text(_)) {
|
||||
clip.visual(symbols)
|
||||
} else {
|
||||
clip.geometric(symbols)
|
||||
}
|
||||
}
|
||||
NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols))),
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } => {
|
||||
// The container's own strokes paint around its members.
|
||||
let o = self.appearance.outset();
|
||||
self.editing_children().iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols))).map(|b| b.inflate(o, o))
|
||||
}
|
||||
NodeKind::Blend { children, spec } => {
|
||||
let b = children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols)));
|
||||
let o = crate::live::max_outset(children, symbols);
|
||||
vectorcraft_geom::union_opt(b, spec.spine.as_ref().and_then(|s| s.bounds()).map(|r| r.inflate(o, o)))
|
||||
}
|
||||
NodeKind::Envelope { content, .. } | NodeKind::Repeat(RepeatSpec { source: content, .. }) => {
|
||||
let o = crate::live::max_outset(content, symbols);
|
||||
self.geometric(symbols).map(|b| b.inflate(o, o))
|
||||
}
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
|
||||
let b = self.geometric(symbols)?;
|
||||
Some(self.appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default()))
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let b = match symbols.and_then(|s| Some((s, s.art(symbol)?))) {
|
||||
Some((s, art)) if !s.art_strokes() => xf.transform_rect_bbox(art.geometric),
|
||||
Some((_, art)) if moves_only(*xf) => xf.transform_rect_bbox(art.visual),
|
||||
Some((s, art)) => {
|
||||
let placed = xf.transform_rect_bbox(art.geometric);
|
||||
match s.placed_visual(symbol, *xf) {
|
||||
Some(v) => v.union(placed),
|
||||
None => placed.inflate(art.reach, art.reach),
|
||||
}
|
||||
}
|
||||
None => xf.transform_rect_bbox(SYMBOL_SQUARE),
|
||||
};
|
||||
let o = self.appearance.outset() + symbols.map_or(0.0, |s| s.brush_pad(symbol));
|
||||
self.projected(Some(b)).map(|b| b.inflate(o, o))
|
||||
}
|
||||
NodeKind::Text(t) => {
|
||||
// The characters' strokes paint around the glyphs.
|
||||
let o = self.appearance.outset().max(t.char_stroke_outset());
|
||||
self.geometric(symbols).map(|b| b.inflate(o, o))
|
||||
}
|
||||
// An image is measured by its frame, without its own fills and strokes.
|
||||
NodeKind::Image(_) => self.geometric(symbols),
|
||||
_ => {
|
||||
let o = self.appearance.outset();
|
||||
self.geometric(symbols).map(|b| b.inflate(o, o))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply an affine transform to the geometry (and gradients) of this node and its descendants.
|
||||
/// `scaling` says what else scales by the transform's mean scale (a bool: stroke weights
|
||||
/// only, see [`Scaling`]).
|
||||
pub fn transform(&mut self, a: Affine, scaling: impl Into<Scaling>) {
|
||||
self.transform_scaled(a, &scaling.into());
|
||||
}
|
||||
|
||||
fn transform_scaled(&mut self, a: Affine, sc: &Scaling) {
|
||||
// A dimension's measurement moves with it.
|
||||
if let Some(e) = self.extras_if_any()
|
||||
&& let Some(dimension) = &mut e.dimension
|
||||
{
|
||||
dimension.transform(a);
|
||||
}
|
||||
// The frames of the objects attached to a path move with them.
|
||||
if let Some(e) = self.extras_if_any()
|
||||
&& let Some(on_path) = &mut e.objects_on_path
|
||||
{
|
||||
on_path.transform(a);
|
||||
}
|
||||
if !self.is_layer() {
|
||||
self.bbox_angle = crate::orient::transformed_angle(self.bbox_angle, a);
|
||||
}
|
||||
// Type and symbols in perspective keep looking the same, moved by `a`.
|
||||
self.transform_projection(a);
|
||||
// Refitting an unplaced gradient only reproduces moves and uniform scales.
|
||||
if !keeps_gradient_fit(a) {
|
||||
self.pin_gradients();
|
||||
}
|
||||
let k = Scaling::factor(a);
|
||||
if let Some(k) = k
|
||||
&& sc.strokes
|
||||
{
|
||||
self.appearance.scale_strokes(k);
|
||||
if let Some(f) = sc.effects {
|
||||
self.appearance.scale_effects(k, f);
|
||||
}
|
||||
}
|
||||
// Only through `DerefMut` when there is something to change: the appearance is shared
|
||||
// copy-on-write (`Shared`), and a move must not copy what it leaves as it is.
|
||||
if self.appearance.gradients().next().is_some() {
|
||||
self.appearance.transform_gradients(a);
|
||||
}
|
||||
if sc.patterns {
|
||||
crate::pattern::transform_pattern_paints(self, a);
|
||||
}
|
||||
match &mut self.kind {
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
path.transform(a);
|
||||
if let Some(l) = live {
|
||||
// A rectangle scaled unevenly keeps circular corners: its path is regenerated.
|
||||
let reshaped = l.transform(a);
|
||||
let kept = sc.keep_corners && k.is_some_and(|k| l.keep_corners(k));
|
||||
if reshaped || kept {
|
||||
*path = l.to_path();
|
||||
}
|
||||
}
|
||||
}
|
||||
NodeKind::Layer { children, .. }
|
||||
| NodeKind::Group { children, .. }
|
||||
| NodeKind::Compound { children, .. }
|
||||
| NodeKind::Intertwine { children } => {
|
||||
for c in children.iter_mut() {
|
||||
Arc::make_mut(c).transform_scaled(a, sc);
|
||||
}
|
||||
}
|
||||
NodeKind::Text(t) => {
|
||||
t.transform(a);
|
||||
// Character strokes scale with the type: undo that when strokes keep their weight.
|
||||
if sc.keep_type_strokes
|
||||
&& let Some(k) = k.filter(|k| *k > 1e-12)
|
||||
{
|
||||
t.scale_char_strokes(1.0 / k);
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => im.xf = a * im.xf,
|
||||
NodeKind::PlacedDocument(p) => p.xf = a * p.xf,
|
||||
NodeKind::SymbolInstance { xf, .. } => *xf = a * *xf,
|
||||
NodeKind::Blend { children, spec } => {
|
||||
for c in children.iter_mut() {
|
||||
Arc::make_mut(c).transform_scaled(a, sc);
|
||||
}
|
||||
if let Some(s) = &mut spec.spine {
|
||||
s.transform(a);
|
||||
}
|
||||
}
|
||||
NodeKind::Envelope { content, kind, frame, .. } => {
|
||||
for c in content.iter_mut() {
|
||||
Arc::make_mut(c).transform_scaled(a, sc);
|
||||
}
|
||||
**frame = crate::live::envelope_frame(a * **frame);
|
||||
match &mut **kind {
|
||||
EnvelopeKind::Mesh { points, handles, .. } => {
|
||||
for p in points.iter_mut() {
|
||||
*p = a * *p;
|
||||
}
|
||||
// Handles are offsets: they take the linear part.
|
||||
let [m0, m1, m2, m3, _, _] = a.as_coeffs();
|
||||
let lin = Affine::new([m0, m1, m2, m3, 0.0, 0.0]);
|
||||
for h in handles.iter_mut().flatten() {
|
||||
*h = (lin * h.to_point()).to_vec2();
|
||||
}
|
||||
}
|
||||
EnvelopeKind::TopObject { path } => path.transform(a),
|
||||
EnvelopeKind::Warp { .. } => {}
|
||||
}
|
||||
}
|
||||
NodeKind::Mesh(m) => m.transform(a),
|
||||
NodeKind::Repeat(r) => r.transform(a, *sc),
|
||||
}
|
||||
if let Some(m) = self.extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
&& m.linked
|
||||
{
|
||||
Arc::make_mut(&mut m.art).transform_scaled(a, sc);
|
||||
}
|
||||
// The area where an Intertwine member is drawn over the others moves with it.
|
||||
if let Some(area) = self.extras_if_any().and_then(|e| e.intertwine.as_mut()) {
|
||||
area.transform(a);
|
||||
}
|
||||
}
|
||||
|
||||
/// Visit this node and all descendants depth first (paint order).
|
||||
pub fn walk<'a>(&'a self, f: &mut impl FnMut(&'a Node)) {
|
||||
f(self);
|
||||
if let Some(ch) = self.children() {
|
||||
for c in ch {
|
||||
c.walk(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Count of nodes in this subtree.
|
||||
pub fn count(&self) -> usize {
|
||||
let mut n = 0;
|
||||
self.walk(&mut |_| n += 1);
|
||||
n
|
||||
}
|
||||
|
||||
/// [`Self::count`], with the art of the opacity masks in the subtree (and theirs): what copying
|
||||
/// and transforming the subtree makes, as [`Self::walk`] doesn't go into masks.
|
||||
pub fn count_with_masks(&self) -> usize {
|
||||
let mut n = 0;
|
||||
self.walk(&mut |c| {
|
||||
n += 1;
|
||||
if let Some(m) = &c.extras().mask {
|
||||
n += m.art.count_with_masks();
|
||||
}
|
||||
});
|
||||
n
|
||||
}
|
||||
|
||||
/// Fix this node's unplaced gradients to their fit on its current bounds (before a transform
|
||||
/// or warp that refitting wouldn't reproduce). Descendants pin their own when transformed.
|
||||
pub fn pin_gradients(&mut self) {
|
||||
if self.appearance.has_unplaced_gradient()
|
||||
&& let Some(b) = self.geometric_bounds()
|
||||
{
|
||||
self.appearance.pin_gradients(b);
|
||||
}
|
||||
}
|
||||
|
||||
/// The paint behind the Fill (or Stroke) proxy, the map from its space to the document and
|
||||
/// the box (in that space) an unplaced gradient fits. `item` (the Appearance panel's active
|
||||
/// item) stands in for the topmost fill or stroke when it is of the proxy's kind. Otherwise
|
||||
/// type objects paint their runs (the first run speaks for all) in text space, fitted to the
|
||||
/// layout bounds; everything else paints its fill or stroke in the document, fitted to the
|
||||
/// geometric bounds. Strokes fit the box grown by half their weight.
|
||||
pub fn proxy_paint(&self, stroke: bool, item: Option<usize>) -> Option<(&vectorcraft_color::Paint, Affine, Rect)> {
|
||||
let item = self.appearance.item_of_kind(item, !stroke);
|
||||
if item.is_none()
|
||||
&& let NodeKind::Text(t) = &self.kind
|
||||
{
|
||||
let st = &t.runs.first()?.style;
|
||||
let b = t.local_bounds();
|
||||
return Some(if stroke { (&st.stroke, t.xf, crate::appearance::stroke_paint_bounds(b, st.stroke_width)) } else { (&st.fill, t.xf, b) });
|
||||
}
|
||||
// An object without bounds (an empty path) still shows its paints, fitted to an empty box.
|
||||
let b = self.geometric_bounds().unwrap_or(Rect::ZERO);
|
||||
if stroke {
|
||||
self.appearance.stroke_at(item).map(|s| (&s.paint, Affine::IDENTITY, s.paint_bounds(b)))
|
||||
} else {
|
||||
self.appearance.fill_at(item).map(|f| (&f.paint, Affine::IDENTITY, b))
|
||||
}
|
||||
}
|
||||
|
||||
/// The gradient behind the Fill (or Stroke) proxy and its placement in document coordinates
|
||||
/// (see [`Node::proxy_paint`]): what the gradient annotator shows and edits.
|
||||
pub fn proxy_gradient(&self, stroke: bool, item: Option<usize>) -> Option<(&vectorcraft_color::GradientPaint, vectorcraft_color::GradientGeom)> {
|
||||
let (paint, to_doc, b) = self.proxy_paint(stroke, item)?;
|
||||
let vectorcraft_color::Paint::Gradient(g) = paint else { return None };
|
||||
let mut geom = g.resolve(b);
|
||||
if to_doc != Affine::IDENTITY {
|
||||
geom.transform(to_doc, g.gradient.kind);
|
||||
}
|
||||
Some((g, geom))
|
||||
}
|
||||
|
||||
/// The freeform gradient behind the Fill (or Stroke) proxy, its points in document coordinates
|
||||
/// (the automatic ones while unplaced), and the length its spreads are fractions of there
|
||||
/// (see [`Node::proxy_paint`]): what the Gradient tool's freeform annotator shows and edits.
|
||||
pub fn proxy_freeform(&self, stroke: bool, item: Option<usize>) -> Option<(vectorcraft_color::Freeform, f64)> {
|
||||
let (paint, to_doc, b) = self.proxy_paint(stroke, item)?;
|
||||
let vectorcraft_color::Paint::Gradient(g) = paint else { return None };
|
||||
if g.gradient.kind != vectorcraft_color::GradientKind::Freeform {
|
||||
return None;
|
||||
}
|
||||
let mut f = g.freeform_on(b).into_owned();
|
||||
let mut scale = vectorcraft_color::freeform::spread_scale(b);
|
||||
if to_doc != Affine::IDENTITY {
|
||||
f.transform(to_doc);
|
||||
scale *= to_doc.determinant().abs().sqrt();
|
||||
}
|
||||
Some((f, scale))
|
||||
}
|
||||
}
|
||||
|
||||
impl Node {
|
||||
/// Whether the children of this group or layer knock each other out, inside a group (or page)
|
||||
/// where that is `enclosing`.
|
||||
pub fn knocks_out(&self, enclosing: bool) -> bool {
|
||||
matches!(self.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && self.knockout.resolve(enclosing)
|
||||
}
|
||||
|
||||
/// A plain group or layer that is neutral to knockout and has no transparency or appearance
|
||||
/// of its own: inside a knockout group its children composite as the group's own children.
|
||||
pub fn passes_knockout_through(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { template: false, clip: false, .. })
|
||||
&& self.has_default_transparency()
|
||||
&& self.appearance.items.is_empty()
|
||||
&& self.appearance.effects.is_empty()
|
||||
}
|
||||
|
||||
/// The visible elements of a knockout group made of `children` (bottom first): neutral plain
|
||||
/// groups ([`Self::passes_knockout_through`]) contribute their children instead of themselves.
|
||||
pub fn knockout_elements(children: &[Arc<Node>]) -> Vec<&Arc<Node>> {
|
||||
fn push<'a>(children: &'a [Arc<Node>], out: &mut Vec<&'a Arc<Node>>) {
|
||||
for c in children.iter().filter(|c| c.visible) {
|
||||
match c.children() {
|
||||
Some(ch) if c.passes_knockout_through() => push(ch, out),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::with_capacity(children.len());
|
||||
push(children, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether this is a clip group or a layer with a clipping mask: its first child clips the rest.
|
||||
pub fn clips(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::Group { clip: true, .. } | NodeKind::Layer { clip: true, .. })
|
||||
}
|
||||
|
||||
/// Make this group or layer clip its children by its first child, or stop it.
|
||||
pub fn set_clips(&mut self, on: bool) {
|
||||
if let NodeKind::Group { clip, .. } | NodeKind::Layer { clip, .. } = &mut self.kind {
|
||||
*clip = on;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether blending inside this object reaches the art below it unless the object isolates
|
||||
/// it: a blend mode other than Normal on a child (or, in a leaf, on a fill or stroke),
|
||||
/// directly or through children that don't isolate their own blending.
|
||||
pub fn blends_through(&self) -> bool {
|
||||
self.blends_through_with(&mut |c| c.blends_through())
|
||||
}
|
||||
|
||||
/// [`Self::blends_through`], with `inner` answering it for the children (e.g. from a cache).
|
||||
pub fn blends_through_with(&self, inner: &mut dyn FnMut(&Arc<Node>) -> bool) -> bool {
|
||||
match self.children() {
|
||||
Some(ch) if !matches!(self.kind, NodeKind::Compound { .. }) => Self::children_blend(ch, inner),
|
||||
_ => self.appearance.items.iter().any(|i| i.visible() && i.blend() != BlendMode::Normal),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::blends_through`] of a group made of `children` (`inner` answers it for each child).
|
||||
pub fn children_blend(children: &[Arc<Node>], inner: &mut dyn FnMut(&Arc<Node>) -> bool) -> bool {
|
||||
children.iter().any(|c| c.visible && (c.blend != BlendMode::Normal || (!c.isolate && inner(c))))
|
||||
}
|
||||
}
|
||||
|
||||
impl Node {
|
||||
/// The Appearance panel's row for what this object's own fills and strokes paint around:
|
||||
/// "Contents" for a group or layer (its members) and for an image (its pixels), "Characters"
|
||||
/// for type; `None` for objects whose fills and strokes paint their own geometry.
|
||||
pub fn contents_label(&self) -> Option<&'static str> {
|
||||
match self.kind {
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Image(_) => Some("Contents"),
|
||||
NodeKind::Text(_) => Some("Characters"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Node {
|
||||
/// Whether this object shows any transparency, itself or anything inside it: object, fill or
|
||||
/// stroke opacity below 100%, a blend mode, an opacity mask, effects or transparent gradient
|
||||
/// stops. Hidden objects show none.
|
||||
pub fn shows_transparency(&self) -> bool {
|
||||
use vectorcraft_color::Paint;
|
||||
let see_through = |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity < 1.0));
|
||||
let effects = |fx: &[crate::Effect]| fx.iter().any(|e| e.visible);
|
||||
self.visible
|
||||
&& (self.opacity < 1.0
|
||||
|| self.blend != BlendMode::Normal
|
||||
|| self.extras().mask.as_ref().is_some_and(|m| !m.disabled)
|
||||
|| effects(&self.appearance.effects)
|
||||
|| self
|
||||
.appearance
|
||||
.items
|
||||
.iter()
|
||||
.any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects())))
|
||||
|| self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency())))
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)?
|
||||
fn keeps_gradient_fit(a: Affine) -> bool {
|
||||
let [m0, m1, m2, m3, _, _] = a.as_coeffs();
|
||||
let eps = 1e-12 * m0.abs().max(1.0);
|
||||
m0 > 0.0 && m1.abs() <= eps && m2.abs() <= eps && (m0 - m3).abs() <= eps
|
||||
}
|
||||
|
||||
impl Node {
|
||||
/// Whether a document point lies in this object's filled regions ([`Node::clip_shapes`]; true
|
||||
/// everywhere for objects without them, such as type, whose boxes stand in).
|
||||
pub fn contains_fn(&self) -> impl Fn(Point) -> bool + use<> {
|
||||
let shapes = self.clip_shapes(None);
|
||||
move |p| shapes.is_empty() || shapes.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
use super::*;
|
||||
|
||||
/// A node writes its rarely set parts among the others, in the file's field order, and reads
|
||||
/// them back into its extras; a node without any keeps none.
|
||||
#[test]
|
||||
fn extras_are_written_flat_in_order() {
|
||||
let mut n = Node::path(NodeId(7), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art());
|
||||
n.name = Some("n".into());
|
||||
n.knockout_shape = true;
|
||||
n.bbox_angle = 30.0;
|
||||
{
|
||||
let mut e = n.extras_mut();
|
||||
e.mask = Some(Box::new(OpacityMask::new(Node::group(NodeId(8), vec![]), true)));
|
||||
e.trace = Some(Box::new(serde_json::json!({"preset": "p"})));
|
||||
e.series_index = Some(2);
|
||||
e.type_outlines = true;
|
||||
e.graphic_style = Some(3);
|
||||
e.attrs = Some(Box::default());
|
||||
e.slice = Some(Box::default());
|
||||
e.perspective = Some(Box::new(crate::PerspectiveAttachment::new("left", 1.0)));
|
||||
e.live_paint_gaps = Some(Box::default());
|
||||
}
|
||||
/// The top-level keys of a JSON object, in the order written.
|
||||
struct Keys(Vec<String>);
|
||||
impl<'de> Deserialize<'de> for Keys {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
struct V;
|
||||
impl<'de> serde::de::Visitor<'de> for V {
|
||||
type Value = Keys;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("an object")
|
||||
}
|
||||
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut a: A) -> Result<Keys, A::Error> {
|
||||
let mut out = vec![];
|
||||
while let Some(k) = a.next_key::<String>()? {
|
||||
a.next_value::<serde::de::IgnoredAny>()?;
|
||||
out.push(k);
|
||||
}
|
||||
Ok(Keys(out))
|
||||
}
|
||||
}
|
||||
d.deserialize_map(V)
|
||||
}
|
||||
}
|
||||
let text = serde_json::to_string(&n).unwrap();
|
||||
let keys = serde_json::from_str::<Keys>(&text).unwrap().0;
|
||||
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
let order = [
|
||||
"id",
|
||||
"name",
|
||||
"knockout_shape",
|
||||
"appearance",
|
||||
"mask",
|
||||
"trace",
|
||||
"series_index",
|
||||
"type_outlines",
|
||||
"kind",
|
||||
"graphic_style",
|
||||
"attrs",
|
||||
"slice",
|
||||
"bbox_angle",
|
||||
"perspective",
|
||||
"live_paint_gaps",
|
||||
];
|
||||
assert_eq!(keys, order);
|
||||
assert_eq!(serde_json::from_value::<Node>(v).unwrap(), n);
|
||||
let plain = Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 2.0)), Appearance::default_art());
|
||||
let back: Node = serde_json::from_value(serde_json::to_value(&plain).unwrap()).unwrap();
|
||||
assert!(back.extras_box().is_none());
|
||||
// Clearing the last extra lets them go; clearing one a node doesn't have allocates none.
|
||||
n.extras_mut().mask = None;
|
||||
assert!(n.extras_box().is_some());
|
||||
*n.extras_mut() = NodeExtras::default();
|
||||
assert!(n.extras_box().is_none());
|
||||
n.extras_mut().mask = None;
|
||||
assert!(n.extras_box().is_none());
|
||||
assert_eq!(n.extras(), &NodeExtras::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rect_live_shape_roundtrip() {
|
||||
let l = LiveShape::Rectangle {
|
||||
w: 10.0,
|
||||
h: 20.0,
|
||||
radii: [0.0; 4],
|
||||
kinds: Default::default(),
|
||||
radii_relative: false,
|
||||
xf: Affine::translate((5.0, 5.0)),
|
||||
};
|
||||
assert_eq!(l.to_path().bounds(), Some(Rect::new(5.0, 5.0, 15.0, 25.0)));
|
||||
assert_eq!(l.label(), "Rectangle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_kinds_save_only_when_some_corner_isnt_round() {
|
||||
let mut l = LiveShape::Rectangle {
|
||||
w: 100.0,
|
||||
h: 50.0,
|
||||
radii: [0.0, 10.0, 0.0, 0.0],
|
||||
kinds: Default::default(),
|
||||
radii_relative: false,
|
||||
xf: Affine::IDENTITY,
|
||||
};
|
||||
// Older files read as round.
|
||||
let json = serde_json::to_value(&l).unwrap();
|
||||
assert!(json.get("kinds").is_none(), "{json}");
|
||||
assert_eq!(serde_json::from_value::<LiveShape>(json).unwrap(), l);
|
||||
if let LiveShape::Rectangle { kinds, .. } = &mut l {
|
||||
kinds[1] = CornerKind::Chamfer;
|
||||
}
|
||||
let json = serde_json::to_value(&l).unwrap();
|
||||
assert_eq!(json["kinds"], serde_json::json!(["round", "chamfer", "round", "round"]));
|
||||
assert_eq!(serde_json::from_value::<LiveShape>(json).unwrap(), l);
|
||||
// Polygons saved before Live Corners cut theirs read as sharp; a live path round-trips.
|
||||
let p: LiveShape = serde_json::from_value(serde_json::json!({"shape": "polygon", "radius": 10.0, "sides": 5, "xf": [1, 0, 0, 1, 0, 0]})).unwrap();
|
||||
assert_eq!(p, LiveShape::Polygon { radius: 10.0, sides: 5, xf: Affine::IDENTITY, radii: vec![], kinds: vec![], radii_relative: false });
|
||||
let star = shapes::star(Point::new(0.0, 0.0), 20.0, 10.0, 5, 0.0);
|
||||
let path = LiveShape::Path { base: star, radii: vec![2.0; 10], kinds: vec![], radii_relative: false };
|
||||
let json = serde_json::to_value(&path).unwrap();
|
||||
assert_eq!((json["shape"].as_str(), json.get("kinds")), (Some("path"), None));
|
||||
assert_eq!(serde_json::from_value::<LiveShape>(json).unwrap(), path);
|
||||
assert_eq!(path.label(), "Path");
|
||||
}
|
||||
|
||||
/// A polygon read from a file has 3 to 1000 sides, as the commands give it: selecting one
|
||||
/// with four billion made its outline and corner lists allocate tens of gigabytes.
|
||||
#[test]
|
||||
fn a_polygon_from_a_file_has_3_to_1000_sides() {
|
||||
let read = |sides: u32| {
|
||||
let json = serde_json::json!({"shape": "polygon", "radius": 10.0, "sides": sides, "xf": [1, 0, 0, 1, 0, 0]});
|
||||
serde_json::from_value::<LiveShape>(json).unwrap()
|
||||
};
|
||||
let sides_of = |l: &LiveShape| match l {
|
||||
LiveShape::Polygon { sides, .. } => *sides,
|
||||
_ => panic!("not a polygon: {l:?}"),
|
||||
};
|
||||
let huge = read(4_000_000_000);
|
||||
assert_eq!([0, 5, 1000].map(|n| sides_of(&read(n))), [3, 5, 1000]);
|
||||
assert_eq!(sides_of(&huge), 1000);
|
||||
assert_eq!(huge.polygon_outline().anchor_count(), 1000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() {
|
||||
let close = |a: f64, b: f64| (a - b).abs() < 1e-9;
|
||||
// A hexagon of radius 10 at (50, 50), drawn 2× and turned 30° clockwise on the page.
|
||||
let xf = Affine::translate((50.0, 50.0)) * Affine::rotate(30f64.to_radians()) * Affine::scale(2.0);
|
||||
let mut p = LiveShape::Polygon { radius: 10.0, sides: 6, xf, radii: vec![], kinds: vec![], radii_relative: false };
|
||||
assert!(close(p.polygon_radius().unwrap(), 20.0) && close(p.polygon_angle().unwrap(), 330.0) && p.polygon_sides_equal());
|
||||
p.set_polygon_angle(45.0);
|
||||
assert!(close(p.polygon_angle().unwrap(), 45.0));
|
||||
let centre = p.to_path().bounds().unwrap().center();
|
||||
assert!(close(centre.x, 50.0) && close(centre.y, 50.0), "turned about its centre: {centre:?}");
|
||||
p.set_polygon_radius(30.0);
|
||||
assert!(close(p.polygon_radius().unwrap(), 30.0));
|
||||
// A hexagon's side is as long as its radius.
|
||||
assert!(close(p.polygon_radius_for_side(12.0).unwrap(), 12.0));
|
||||
// Stretched, its sides differ; Make Sides Equal keeps its centre, angle and mean radius.
|
||||
p.transform(Affine::scale_non_uniform(2.0, 1.0));
|
||||
assert!(!p.polygon_sides_equal());
|
||||
let (r, a) = (p.polygon_radius().unwrap(), p.polygon_angle().unwrap());
|
||||
p.make_sides_equal();
|
||||
assert!(p.polygon_sides_equal() && close(p.polygon_radius().unwrap(), r) && close(p.polygon_angle().unwrap(), a));
|
||||
let LiveShape::Polygon { xf, .. } = &p else { panic!("polygon") };
|
||||
assert_eq!(*xf * Point::ZERO, Point::new(100.0, 50.0));
|
||||
// Other shapes have none of it.
|
||||
let e = LiveShape::Ellipse { w: 1.0, h: 1.0, pie: (0.0, 360.0), xf: Affine::IDENTITY };
|
||||
assert_eq!((e.polygon_radius(), e.polygon_angle()), (None, None));
|
||||
}
|
||||
|
||||
/// A node holding a live rectangle (`w` × `h`, all radii `r`, placed by `xf`) and its path.
|
||||
fn live_rect(w: f64, h: f64, r: f64, xf: Affine) -> Node {
|
||||
let live = LiveShape::Rectangle { w, h, radii: [r; 4], kinds: Default::default(), radii_relative: false, xf };
|
||||
let mut n = Node::path(NodeId(1), live.to_path(), Appearance::default_art());
|
||||
if let NodeKind::Path { live: slot, .. } = &mut n.kind {
|
||||
*slot = Some(Box::new(live));
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn live_of(n: &Node) -> (f64, f64, [f64; 4], Affine) {
|
||||
let NodeKind::Path { live: Some(l), .. } = &n.kind else { panic!("not a live shape") };
|
||||
let LiveShape::Rectangle { w, h, radii, xf, .. } = &**l else { panic!("not a live rectangle") };
|
||||
(*w, *h, *radii, *xf)
|
||||
}
|
||||
|
||||
fn near(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-9
|
||||
}
|
||||
|
||||
fn near_xf(a: Affine, b: Affine) -> bool {
|
||||
a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| near(*x, y))
|
||||
}
|
||||
|
||||
/// Size and radius of a live rectangle, within rounding.
|
||||
fn assert_live(n: &Node, w: f64, h: f64, r: f64) {
|
||||
let (lw, lh, radii, _) = live_of(n);
|
||||
assert!(near(lw, w) && near(lh, h) && radii.iter().all(|x| near(*x, r)), "{lw} × {lh} r {radii:?}, want {w} × {h} r {r}");
|
||||
}
|
||||
|
||||
/// Each corner arc of a rounded rectangle's path, mapped by `back` (to undo a rotation),
|
||||
/// spans `r` along x and y: the corner is a circular arc of radius `r`.
|
||||
fn assert_round_corners(n: &Node, back: Affine, r: f64) {
|
||||
let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") };
|
||||
let a: Vec<Point> = path.subpaths[0].anchors.iter().map(|a| back * a.p).collect();
|
||||
assert_eq!(a.len(), 8, "a rounded rectangle");
|
||||
// Anchors 1→2, 3→4, 5→6 and 7→0 are the arcs.
|
||||
for (i, j) in [(1, 2), (3, 4), (5, 6), (7, 0)] {
|
||||
let (x, y) = ((a[j].x - a[i].x).abs(), (a[j].y - a[i].y).abs());
|
||||
assert!(near(x, r) && near(y, r), "corner spans {x} × {y}, want {r} × {r}");
|
||||
}
|
||||
}
|
||||
|
||||
const KEEP_CORNERS: Scaling = Scaling { strokes: false, effects: None, keep_type_strokes: false, keep_corners: true, patterns: false };
|
||||
|
||||
#[test]
|
||||
fn uneven_scales_keep_live_corners_circular() {
|
||||
// A 100 pt rounded square at (10, 10) stretched to 300 × 100 (#291).
|
||||
let mut n = live_rect(100.0, 100.0, 20.0, Affine::translate((10.0, 10.0)));
|
||||
let stretch = Affine::translate((10.0, 10.0)) * Affine::scale_non_uniform(3.0, 1.0) * Affine::translate((-10.0, -10.0));
|
||||
n.transform(stretch, KEEP_CORNERS);
|
||||
assert_live(&n, 300.0, 100.0, 20.0);
|
||||
assert!(near_xf(live_of(&n).3, Affine::translate((10.0, 10.0))), "the scale went into the size");
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!(near(b.x0, 10.0) && near(b.y0, 10.0) && near(b.x1, 310.0) && near(b.y1, 110.0), "{b:?}");
|
||||
assert_round_corners(&n, Affine::IDENTITY, 20.0);
|
||||
// Scale Corners on: the radius scales by the mean scale, still circular.
|
||||
let mut n = live_rect(100.0, 100.0, 20.0, Affine::IDENTITY);
|
||||
n.transform(Affine::scale_non_uniform(4.0, 1.0), Scaling::default());
|
||||
assert_live(&n, 400.0, 100.0, 40.0);
|
||||
assert_round_corners(&n, Affine::IDENTITY, 40.0);
|
||||
// Squashed below the radius, the short sides are fully round; stretched back, it returns.
|
||||
n.transform(Affine::scale_non_uniform(1.0, 0.5), KEEP_CORNERS);
|
||||
assert_round_corners(&n, Affine::IDENTITY, 25.0);
|
||||
n.transform(Affine::scale_non_uniform(1.0, 2.0), KEEP_CORNERS);
|
||||
assert_round_corners(&n, Affine::IDENTITY, 40.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotated_and_reflected_live_rectangles_scale_along_their_own_sides() {
|
||||
let place = Affine::translate((200.0, 100.0)) * Affine::rotate(30f64.to_radians());
|
||||
let mut n = live_rect(100.0, 50.0, 10.0, place);
|
||||
// Stretched along its own width, as a bounding-box drag of a rotated shape does.
|
||||
n.transform(place * Affine::scale_non_uniform(2.0, 1.0) * place.inverse(), KEEP_CORNERS);
|
||||
assert_live(&n, 200.0, 50.0, 10.0);
|
||||
assert!(near_xf(live_of(&n).3, place));
|
||||
assert_round_corners(&n, place.inverse(), 10.0);
|
||||
// A reflection stays in `xf`; the corners stay as they were.
|
||||
n.transform(Affine::scale_non_uniform(-1.0, 1.0), KEEP_CORNERS);
|
||||
assert_live(&n, 200.0, 50.0, 10.0);
|
||||
let xf = live_of(&n).3;
|
||||
assert!(near(xf.determinant(), -1.0));
|
||||
assert_round_corners(&n, xf.inverse(), 10.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shears_and_moves_keep_the_old_transform() {
|
||||
// Scaling a rotated rectangle along the page axes shears it: `xf` takes it all, as before.
|
||||
let rot = Affine::rotate(30f64.to_radians());
|
||||
let mut n = live_rect(100.0, 50.0, 10.0, rot);
|
||||
let before = n.clone();
|
||||
let a = Affine::scale_non_uniform(2.0, 1.0);
|
||||
n.transform(a, Scaling::default());
|
||||
assert_eq!(live_of(&n), (100.0, 50.0, [10.0; 4], a * rot));
|
||||
let (NodeKind::Path { path, .. }, NodeKind::Path { path: old, .. }) = (&n.kind, &before.kind) else { panic!() };
|
||||
assert_eq!(*path, old.transformed(a));
|
||||
// A file saved with an uneven scale in `xf` keeps its exact geometry when moved...
|
||||
let legacy = Affine::translate((5.0, 5.0)) * Affine::scale_non_uniform(2.0, 1.0);
|
||||
let mut n = live_rect(100.0, 100.0, 20.0, legacy);
|
||||
n.transform(Affine::translate((10.0, 0.0)), KEEP_CORNERS);
|
||||
assert_eq!(live_of(&n), (100.0, 100.0, [20.0; 4], Affine::translate((10.0, 0.0)) * legacy));
|
||||
// ...and once scaled, has document units and circular corners of its mean radius.
|
||||
n.transform(Affine::scale(2.0), Scaling::default());
|
||||
assert_live(&n, 400.0, 200.0, 20.0 * 2f64.sqrt() * 2.0);
|
||||
assert!(near(live_of(&n).3.determinant(), 1.0));
|
||||
assert_round_corners(&n, Affine::IDENTITY, 20.0 * 2f64.sqrt() * 2.0);
|
||||
}
|
||||
|
||||
/// A rectangle saved with an uneven scale in `xf` (before #291) has elliptical corners; Live
|
||||
/// Corners see and edit it in document units, with circular corners (#442).
|
||||
#[test]
|
||||
fn a_scale_left_in_the_transform_folds_into_the_size() {
|
||||
let legacy = Affine::translate((5.0, 5.0)) * Affine::scale_non_uniform(4.0, 1.0);
|
||||
let n = live_rect(50.0, 80.0, 20.0, legacy);
|
||||
let NodeKind::Path { live: Some(live), .. } = &n.kind else { panic!("not live") };
|
||||
let folded = live.folded();
|
||||
assert_eq!(live_of(&n).3, legacy, "folded() leaves the shape alone");
|
||||
let LiveShape::Rectangle { w, h, radii, xf, .. } = &folded else { panic!("not a rectangle") };
|
||||
// Drawn 200 × 80 with 80 × 20 corners; folded, the corners are circles of the mean radius.
|
||||
assert!(near(*w, 200.0) && near(*h, 80.0) && radii.iter().all(|r| near(*r, 40.0)), "{w} × {h} r {radii:?}");
|
||||
assert!(near_xf(*xf, Affine::translate((5.0, 5.0))));
|
||||
let (a, b) = (folded.to_path().bounds().unwrap(), live.to_path().bounds().unwrap());
|
||||
assert!(near(a.x0, b.x0) && near(a.y0, b.y0) && near(a.x1, b.x1) && near(a.y1, b.y1), "same place and size: {a:?} {b:?}");
|
||||
let corners = crate::LiveCorners::of(&n).unwrap();
|
||||
assert_eq!(corners.style(&corners.all()).0, Some(40.0), "the radius in document units");
|
||||
// Nothing to fold: a moved, rotated or reflected rectangle and a sheared one stay as they are.
|
||||
let place = Affine::translate((5.0, 5.0)) * Affine::rotate(0.5) * Affine::scale_non_uniform(-1.0, 1.0);
|
||||
let shear = Affine::new([1.0, 0.0, 0.5, 1.0, 0.0, 0.0]);
|
||||
for xf in [place, shear] {
|
||||
let mut l = live_rect(100.0, 160.0, 20.0, xf);
|
||||
let NodeKind::Path { live: Some(live), .. } = &mut l.kind else { panic!("not live") };
|
||||
assert!(!live.fold_scale());
|
||||
assert_eq!(live_of(&l), (100.0, 160.0, [20.0; 4], xf));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_transparency() {
|
||||
let p = || Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
assert!(p().has_default_transparency());
|
||||
let tweaks: [fn(&mut Node); 7] = [
|
||||
|n| n.opacity = 0.5,
|
||||
|n| n.blend = BlendMode::Multiply,
|
||||
|n| n.isolate = true,
|
||||
|n| n.knockout = Knockout::On,
|
||||
|n| n.knockout = Knockout::Off,
|
||||
|n| n.knockout_shape = true,
|
||||
|n| n.extras_mut().mask = Some(Box::new(OpacityMask::new(n.clone(), true))),
|
||||
];
|
||||
for tweak in tweaks {
|
||||
let mut n = p();
|
||||
tweak(&mut n);
|
||||
assert!(!n.has_default_transparency(), "{n:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_group_recurses() {
|
||||
let p = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
let mut g = Node::group(NodeId(1), vec![Arc::new(p)]);
|
||||
g.transform(Affine::scale(2.0), true);
|
||||
assert_eq!(g.geometric_bounds(), Some(Rect::new(0.0, 0.0, 20.0, 20.0)));
|
||||
let child = &g.children().unwrap()[0];
|
||||
assert_eq!(child.appearance.stroke_width(), 2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unplaced_gradients_pin_only_when_a_refit_would_differ() {
|
||||
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, Paint};
|
||||
let grad = || Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
|
||||
let fresh = || Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), Appearance::basic(grad(), grad(), 2.0));
|
||||
let geoms = |n: &Node| match (n.appearance.fill_paint(), n.appearance.stroke_paint()) {
|
||||
(Paint::Gradient(f), Paint::Gradient(s)) => (f.geom, s.geom),
|
||||
_ => panic!("gradient fill and stroke"),
|
||||
};
|
||||
let mut n = fresh();
|
||||
n.transform(Affine::translate((10.0, 5.0)) * Affine::scale(2.0), true);
|
||||
assert_eq!(geoms(&n), (None, None), "moves and uniform scales keep refitting");
|
||||
let mut n = fresh();
|
||||
n.transform(Affine::rotate(std::f64::consts::FRAC_PI_2), false);
|
||||
let (f, s) = geoms(&n);
|
||||
// Fitted on the old bounds (strokes on the stroke-inflated box), then rotated: vertical.
|
||||
let mut want = GradientGeom::fit(GradientKind::Linear, Rect::new(0.0, 0.0, 100.0, 50.0), 0.0);
|
||||
want.transform(Affine::rotate(std::f64::consts::FRAC_PI_2), GradientKind::Linear);
|
||||
let f = f.unwrap();
|
||||
assert!(f.start.distance(want.start) < 1e-9 && f.end.distance(want.end) < 1e-9, "{f:?}");
|
||||
assert!((s.unwrap().length() - 102.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_names() {
|
||||
let p = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
assert_eq!(p.display_name(), "<Path>");
|
||||
let l = Node::layer(NodeId(1), "Layer 1", LayerColor::Preset(0));
|
||||
assert_eq!(l.display_name(), "Layer 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_bounds_include_stroke() {
|
||||
let mut p = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
p.appearance.stroke_mut().unwrap().join = crate::appearance::LineJoin::Round;
|
||||
assert_eq!(p.visual_bounds(), Some(Rect::new(-0.5, -0.5, 10.5, 10.5)));
|
||||
}
|
||||
|
||||
/// Type's visual bounds grow by how far its character strokes paint past the glyphs: half the
|
||||
/// weight centred, the whole weight outside, nothing inside; scaled with the type.
|
||||
#[test]
|
||||
fn type_visual_bounds_grow_with_the_character_stroke() {
|
||||
use crate::appearance::StrokeAlign;
|
||||
use crate::text::{CharStyle, TextObject};
|
||||
let style = CharStyle { stroke: vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), stroke_width: 4.0, ..Default::default() };
|
||||
let mut t = TextObject::point(vectorcraft_geom::Point::new(0.0, 0.0), "Ab", style);
|
||||
t.xf = Affine::scale(2.0) * t.xf;
|
||||
let node = |t: &TextObject| Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone())));
|
||||
let g = node(&t).geometric_bounds().unwrap();
|
||||
for (align, grow) in [(StrokeAlign::Center, 4.0), (StrokeAlign::Outside, 8.0), (StrokeAlign::Inside, 0.0)] {
|
||||
t.runs[0].style.stroke_align = align;
|
||||
assert_eq!(node(&t).visual_bounds(), Some(g.inflate(grow, grow)), "{align:?}");
|
||||
}
|
||||
t.runs[0].style.stroke = vectorcraft_color::Paint::None;
|
||||
assert_eq!(node(&t).visual_bounds(), Some(g), "no stroke, no growth");
|
||||
}
|
||||
|
||||
/// A group holding a path, a compound, an image and a nested group, as a file writes it.
|
||||
fn nested_group() -> Node {
|
||||
let path = |id| Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
let image = ImageObject { key: "k".into(), width: 2, height: 3, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
|
||||
let inner = Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(path(6))], clip: true });
|
||||
let compound = Node::new(NodeId(3), NodeKind::Compound { children: vec![Arc::new(path(4))], rule: FillRule::EvenOdd });
|
||||
let kids = vec![Arc::new(path(2)), Arc::new(compound), Arc::new(Node::new(NodeId(7), NodeKind::Image(Box::new(image)))), Arc::new(inner)];
|
||||
Node::new(NodeId(1), NodeKind::Group { children: kids, clip: false })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kinds_read_back_with_type_first_or_anywhere() {
|
||||
let n = nested_group();
|
||||
let json = serde_json::to_string(&n).unwrap();
|
||||
assert!(json.contains(r#""kind":{"type":"group","children":["#), "written with `type` first: {json}");
|
||||
assert_eq!(serde_json::from_str::<Node>(&json).unwrap(), n);
|
||||
// Through a JSON value, whose keys are sorted: `type` comes after `children`.
|
||||
let v = serde_json::to_value(&n).unwrap();
|
||||
assert_eq!(serde_json::from_value::<Node>(v.clone()).unwrap(), n);
|
||||
assert_eq!(serde_json::from_str::<Node>(&v.to_string()).unwrap(), n);
|
||||
// `type` last, in the middle, and keys a newer version added (ignored, as before).
|
||||
let kind = r#"{"children":[],"x":{"deep":[1,2]},"clip":true,"type":"group"}"#;
|
||||
assert_eq!(serde_json::from_str::<NodeKind>(kind).unwrap(), NodeKind::Group { children: vec![], clip: true });
|
||||
let kind = r#"{"symbol":"S","type":"symbolinstance","later":1,"xf":[1,0,0,1,5,6]}"#;
|
||||
assert_eq!(serde_json::from_str::<NodeKind>(kind).unwrap(), NodeKind::SymbolInstance { symbol: "S".into(), xf: Affine::translate((5.0, 6.0)) });
|
||||
let kind = r#"{"width":2,"type":"image","key":"k","height":3,"xf":[1,0,0,1,0,0]}"#;
|
||||
assert!(matches!(serde_json::from_str::<NodeKind>(kind).unwrap(), NodeKind::Image(i) if i.key == "k" && i.height == 3));
|
||||
// Defaults as before.
|
||||
let NodeKind::Layer { printable, preview, template, .. } =
|
||||
serde_json::from_str(r#"{"type":"layer","color":{"Preset":0},"children":[]}"#).unwrap()
|
||||
else {
|
||||
panic!("a layer")
|
||||
};
|
||||
assert!(printable && preview && !template);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_kinds_are_errors() {
|
||||
for bad in [r#"{"children":[]}"#, r#"{"type":"nothing"}"#, r#"{"type":"group"}"#, r#"{"type":3,"children":[]}"#, r#"[]"#, r#""group""#] {
|
||||
assert!(serde_json::from_str::<NodeKind>(bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
use super::attributes::ObjectAttributes;
|
||||
use super::extras::{Extras, NO_EXTRAS, NodeExtras};
|
||||
use super::ids::NodeId;
|
||||
use super::kind::NodeKind;
|
||||
use super::opacity::{Knockout, OpacityMask};
|
||||
use super::*;
|
||||
|
||||
/// How a [`Node`] is written: the flat field list of the file format, in its order, borrowed from
|
||||
/// the node and its extras (nothing is copied). The node reads back through `NodeWire`.
|
||||
impl Serialize for Node {
|
||||
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
use crate::skip::{is_default, is_one, is_true};
|
||||
use serde::ser::SerializeStruct;
|
||||
let e = self.extras();
|
||||
// As the derive did: the fields written, then each field written or skipped in order.
|
||||
let skips = [
|
||||
false,
|
||||
self.name.is_none(),
|
||||
is_true(&self.visible),
|
||||
is_default(&self.locked),
|
||||
is_one(&self.opacity),
|
||||
is_default(&self.blend),
|
||||
is_default(&self.isolate),
|
||||
is_default(&self.knockout),
|
||||
is_default(&self.knockout_shape),
|
||||
is_default(&self.appearance),
|
||||
e.mask.is_none(),
|
||||
e.trace.is_none(),
|
||||
e.wrap.is_none(),
|
||||
e.graph.is_none(),
|
||||
e.series_index.is_none(),
|
||||
is_default(&e.type_outlines),
|
||||
e.shaper.is_none(),
|
||||
false,
|
||||
e.graphic_style.is_none(),
|
||||
e.attrs.is_none(),
|
||||
e.slice.is_none(),
|
||||
is_default(&self.bbox_angle),
|
||||
e.perspective.is_none(),
|
||||
e.dimension.is_none(),
|
||||
e.intertwine.is_none(),
|
||||
e.live_paint_gaps.is_none(),
|
||||
e.objects_on_path.is_none(),
|
||||
];
|
||||
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
|
||||
let mut skip = skips.into_iter();
|
||||
macro_rules! field {
|
||||
($name:literal, $v:expr) => {
|
||||
if skip.next().unwrap_or(false) {
|
||||
st.skip_field($name)?;
|
||||
} else {
|
||||
st.serialize_field($name, $v)?;
|
||||
}
|
||||
};
|
||||
}
|
||||
field!("id", &self.id);
|
||||
field!("name", &self.name);
|
||||
field!("visible", &self.visible);
|
||||
field!("locked", &self.locked);
|
||||
field!("opacity", &self.opacity);
|
||||
field!("blend", &self.blend);
|
||||
field!("isolate", &self.isolate);
|
||||
field!("knockout", &self.knockout);
|
||||
field!("knockout_shape", &self.knockout_shape);
|
||||
field!("appearance", &self.appearance);
|
||||
field!("mask", &e.mask);
|
||||
field!("trace", &e.trace);
|
||||
field!("wrap", &e.wrap);
|
||||
field!("graph", &e.graph);
|
||||
field!("series_index", &e.series_index);
|
||||
field!("type_outlines", &e.type_outlines);
|
||||
field!("shaper", &e.shaper);
|
||||
field!("kind", &self.kind);
|
||||
field!("graphic_style", &e.graphic_style);
|
||||
field!("attrs", &e.attrs);
|
||||
field!("slice", &e.slice);
|
||||
field!("bbox_angle", &self.bbox_angle);
|
||||
field!("perspective", &e.perspective);
|
||||
field!("dimension", &e.dimension);
|
||||
field!("intertwine", &e.intertwine);
|
||||
field!("live_paint_gaps", &e.live_paint_gaps);
|
||||
field!("objects_on_path", &e.objects_on_path);
|
||||
st.end()
|
||||
}
|
||||
}
|
||||
|
||||
/// How a [`Node`] is read: the flat field list of the file format. Fields move into the node
|
||||
/// (and its extras, allocated only when one is set) without a copy of what they own.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename = "Node")]
|
||||
pub(super) struct NodeWire {
|
||||
id: NodeId,
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
#[serde(default = "yes")]
|
||||
visible: bool,
|
||||
#[serde(default)]
|
||||
locked: bool,
|
||||
#[serde(default = "one")]
|
||||
opacity: f32,
|
||||
#[serde(default)]
|
||||
blend: BlendMode,
|
||||
#[serde(default)]
|
||||
isolate: bool,
|
||||
#[serde(default)]
|
||||
knockout: Knockout,
|
||||
#[serde(default)]
|
||||
knockout_shape: bool,
|
||||
#[serde(default)]
|
||||
appearance: crate::Shared<Appearance>,
|
||||
#[serde(default)]
|
||||
mask: Option<Box<OpacityMask>>,
|
||||
#[serde(default)]
|
||||
trace: Option<Box<serde_json::Value>>,
|
||||
#[serde(default)]
|
||||
wrap: Option<crate::text::TextWrap>,
|
||||
#[serde(default)]
|
||||
graph: Option<Box<crate::graph::GraphSpec>>,
|
||||
#[serde(default)]
|
||||
series_index: Option<u32>,
|
||||
#[serde(default)]
|
||||
type_outlines: bool,
|
||||
#[serde(default)]
|
||||
shaper: Option<Box<crate::shaper::ShaperSpec>>,
|
||||
kind: NodeKind,
|
||||
#[serde(default)]
|
||||
graphic_style: Option<u32>,
|
||||
#[serde(default)]
|
||||
attrs: Option<Box<ObjectAttributes>>,
|
||||
#[serde(default)]
|
||||
slice: Option<Box<crate::SliceOptions>>,
|
||||
#[serde(default)]
|
||||
bbox_angle: f64,
|
||||
#[serde(default)]
|
||||
perspective: Option<Box<crate::PerspectiveAttachment>>,
|
||||
#[serde(default)]
|
||||
dimension: Option<Box<crate::dimension::Dimension>>,
|
||||
#[serde(default)]
|
||||
intertwine: Option<Box<PathData>>,
|
||||
#[serde(default)]
|
||||
live_paint_gaps: Option<Box<crate::live_paint::GapOptions>>,
|
||||
#[serde(default)]
|
||||
objects_on_path: Option<Box<crate::objects_on_path::ObjectsOnPath>>,
|
||||
}
|
||||
|
||||
impl From<NodeWire> for Node {
|
||||
fn from(w: NodeWire) -> Self {
|
||||
let extras = NodeExtras {
|
||||
mask: w.mask,
|
||||
trace: w.trace,
|
||||
wrap: w.wrap,
|
||||
graph: w.graph,
|
||||
series_index: w.series_index,
|
||||
type_outlines: w.type_outlines,
|
||||
shaper: w.shaper,
|
||||
graphic_style: w.graphic_style,
|
||||
attrs: w.attrs,
|
||||
slice: w.slice,
|
||||
perspective: w.perspective,
|
||||
dimension: w.dimension,
|
||||
intertwine: w.intertwine,
|
||||
live_paint_gaps: w.live_paint_gaps,
|
||||
objects_on_path: w.objects_on_path,
|
||||
};
|
||||
Node {
|
||||
id: w.id,
|
||||
name: w.name,
|
||||
visible: w.visible,
|
||||
locked: w.locked,
|
||||
opacity: w.opacity,
|
||||
blend: w.blend,
|
||||
isolate: w.isolate,
|
||||
knockout: w.knockout,
|
||||
knockout_shape: w.knockout_shape,
|
||||
appearance: w.appearance,
|
||||
kind: w.kind,
|
||||
bbox_angle: w.bbox_angle,
|
||||
extras: Extras((extras != NO_EXTRAS).then(|| Box::new(extras))),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -142,8 +142,10 @@ impl Document {
|
||||
let ids: Vec<NodeId> = list.as_array().into_iter().flatten().filter_map(|v| v.as_u64()).map(NodeId).collect();
|
||||
// The old list marked spot-linked blacks too (so the spot names don't matter).
|
||||
let op = OverprintBlack { spot: true, ..Default::default() };
|
||||
for id in ids {
|
||||
if let Some(n) = self.node_mut(id) {
|
||||
// One walk of the tree finds them all (a missing id costs a walk each, and a list can repeat it).
|
||||
let paths = self.index_paths(ids);
|
||||
for path in paths.values() {
|
||||
if let Some(n) = self.node_mut_at(path) {
|
||||
op.apply(n, &[]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -632,7 +632,12 @@ impl RepeatSpec {
|
||||
/// Where the instances go, counting toward the budget the Repeats in the art of the symbols
|
||||
/// of `doc` that instances in the source show (none without a document).
|
||||
pub fn transforms(&self, doc: Option<&Document>) -> Vec<Affine> {
|
||||
let mut v = repeat_transforms(&self.kind, self.source_bounds());
|
||||
self.transforms_from(doc, self.source_bounds())
|
||||
}
|
||||
/// [`Self::transforms`] with the source's bounds (as [`Self::source_bounds`] measures them)
|
||||
/// already at hand: measuring them again, at every level of nested Repeats, doubles the work.
|
||||
fn transforms_from(&self, doc: Option<&Document>, bounds: Option<Rect>) -> Vec<Affine> {
|
||||
let mut v = repeat_transforms(&self.kind, bounds);
|
||||
// Each instance draws the Repeats in the source again, so nested ones multiply (a 500 × 500
|
||||
// grid of one is 62.5 billion instances): keep the first that fit the budget.
|
||||
v.truncate(self.kept(NestedCount::new(doc).nodes(&self.source)));
|
||||
@@ -681,7 +686,9 @@ impl RepeatSpec {
|
||||
/// The bounds of all instances of a source measuring `source`, each placed by its transform
|
||||
/// ([`Self::transforms`] for `doc`).
|
||||
pub(crate) fn copies_bounds(&self, source: Rect, doc: Option<&Document>) -> Option<Rect> {
|
||||
self.transforms(doc).into_iter().fold(None, |acc, m| vectorcraft_geom::union_opt(acc, Some(m.transform_rect_bbox(source))))
|
||||
// Without a document the source's bounds are the ones `source` is: not measured twice.
|
||||
let transforms = if doc.is_none() { self.transforms_from(None, Some(source)) } else { self.transforms(doc) };
|
||||
transforms.into_iter().fold(None, |acc, m| vectorcraft_geom::union_opt(acc, Some(m.transform_rect_bbox(source))))
|
||||
}
|
||||
/// Apply a document transform (source + arrangement parameters).
|
||||
pub fn transform(&mut self, a: Affine, scaling: impl Into<crate::node::Scaling>) {
|
||||
|
||||
@@ -17,6 +17,7 @@ pub fn parse_range(s: &str, count: usize) -> Result<Vec<usize>, String> {
|
||||
.ok_or_else(|| format!("range `{s}`: `{t}` is not a number from 1 to {count}"))
|
||||
};
|
||||
let mut out = vec![];
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) {
|
||||
let (a, b) = match part.replace('\u{2013}', "-").split_once('-') {
|
||||
Some((a, b)) if a.trim().is_empty() && b.trim().is_empty() => return Err(format!("range `{s}`: `{part}` names no number")),
|
||||
@@ -30,7 +31,7 @@ pub fn parse_range(s: &str, count: usize) -> Result<Vec<usize>, String> {
|
||||
return Err(format!("range `{s}`: `{part}` runs backwards"));
|
||||
}
|
||||
for i in a - 1..b {
|
||||
if !out.contains(&i) {
|
||||
if seen.insert(i) {
|
||||
out.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
use super::*;
|
||||
|
||||
/// New art on a locked artboard ([`Document::new_art`]). Setting it changes the document in
|
||||
/// place, so a selection change that sets it doesn't replace the document.
|
||||
#[derive(Default)]
|
||||
pub struct NewArtIds(pub(crate) std::sync::RwLock<Arc<std::collections::HashSet<NodeId>>>);
|
||||
|
||||
impl NewArtIds {
|
||||
/// The objects.
|
||||
pub fn get(&self) -> Arc<std::collections::HashSet<NodeId>> {
|
||||
self.0.read().map(|g| g.clone()).unwrap_or_default()
|
||||
}
|
||||
/// Make `ids` the objects.
|
||||
pub fn set(&self, ids: Arc<std::collections::HashSet<NodeId>>) {
|
||||
if let Ok(mut g) = self.0.write() {
|
||||
*g = ids;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for NewArtIds {
|
||||
fn clone(&self) -> Self {
|
||||
NewArtIds(std::sync::RwLock::new(self.get()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Editing state, not document content: two documents are equal whatever new art they name.
|
||||
impl PartialEq for NewArtIds {
|
||||
fn eq(&self, _: &Self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for NewArtIds {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple("NewArtIds").field(&self.get()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Opacity-mask editing mode: `object`'s mask art lives on the temporary `layer` while editing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MaskEdit {
|
||||
pub object: NodeId,
|
||||
pub layer: NodeId,
|
||||
}
|
||||
|
||||
/// A saved view (View → New View…): zoom, centre and rotation, listed at the bottom of the View menu.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SavedView {
|
||||
pub name: String,
|
||||
pub center: Point,
|
||||
pub zoom: f64,
|
||||
#[serde(default)]
|
||||
pub rotation: f64,
|
||||
}
|
||||
|
||||
impl SavedView {
|
||||
/// Most views a document keeps (the View menu lists every one).
|
||||
pub const MAX: usize = 25;
|
||||
/// Longest name, in characters.
|
||||
pub const MAX_NAME: usize = 255;
|
||||
|
||||
/// `name` trimmed and cut to [`Self::MAX_NAME`] characters (`None` when blank).
|
||||
pub fn clean_name(name: &str) -> Option<String> {
|
||||
let name: String = name.trim().chars().take(Self::MAX_NAME).collect();
|
||||
(!name.is_empty()).then_some(name)
|
||||
}
|
||||
|
||||
/// The first "View N" none of `saved` is named.
|
||||
pub fn default_name(saved: &[SavedView]) -> String {
|
||||
(1..=saved.len() + 1).map(|i| format!("View {i}")).find(|n| !saved.iter().any(|x| &x.name == n)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Can the canvas show this view: a finite centre and a finite, positive zoom.
|
||||
pub fn is_usable(&self) -> bool {
|
||||
self.center.x.is_finite() && self.center.y.is_finite() && self.zoom.is_finite() && self.zoom > 0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// A saved selection (Select → Save Selection…): the objects that were selected, listed by name at
|
||||
/// the bottom of the Select menu.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SavedSelection {
|
||||
pub name: String,
|
||||
pub objects: Vec<NodeId>,
|
||||
}
|
||||
|
||||
impl SavedSelection {
|
||||
/// Most saved selections a document keeps (the Select menu lists every one).
|
||||
pub const MAX: usize = 25;
|
||||
/// Longest name, in characters.
|
||||
pub const MAX_NAME: usize = 255;
|
||||
|
||||
/// `name` trimmed and cut to [`Self::MAX_NAME`] characters (`None` when blank).
|
||||
pub fn clean_name(name: &str) -> Option<String> {
|
||||
let name: String = name.trim().chars().take(Self::MAX_NAME).collect();
|
||||
(!name.is_empty()).then_some(name)
|
||||
}
|
||||
|
||||
/// The first "Selection N" none of `saved` is named.
|
||||
pub fn default_name(saved: &[SavedSelection]) -> String {
|
||||
(1..=saved.len() + 1).map(|i| format!("Selection {i}")).find(|n| !saved.iter().any(|x| &x.name == n)).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A symbol definition.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Symbol {
|
||||
pub name: String,
|
||||
pub art: Arc<Node>,
|
||||
}
|
||||
|
||||
/// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ImageBlob {
|
||||
pub mime: String,
|
||||
#[serde(skip)]
|
||||
pub bytes: Arc<Vec<u8>>,
|
||||
/// A linked image's low-resolution preview (PNG, see [`links`]): what a save writes when only
|
||||
/// linked images show this blob, and what `bytes` hold while the linked file can't be read.
|
||||
#[serde(skip)]
|
||||
pub proxy: Option<Arc<Vec<u8>>>,
|
||||
}
|
||||
@@ -212,7 +212,8 @@ pub struct DocSetup {
|
||||
pub bleed: [f64; 4],
|
||||
/// Show Images in Outline Mode.
|
||||
pub outline_images: bool,
|
||||
/// Highlight text whose font is missing (drawn in a substitute font).
|
||||
/// The Highlight Substituted Fonts value older builds kept in Document Setup. Files keep it as
|
||||
/// they were saved; the screen follows Preferences › Type › Highlight Substituted Fonts.
|
||||
pub highlight_substituted_fonts: bool,
|
||||
/// Highlight glyphs the font lacks (drawn from a fallback font).
|
||||
pub highlight_substituted_glyphs: bool,
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
pub fn is_default<T: Default + PartialEq>(v: &T) -> bool {
|
||||
*v == T::default()
|
||||
}
|
||||
pub fn is_true(v: &bool) -> bool {
|
||||
*v
|
||||
}
|
||||
pub fn is_one(v: &f32) -> bool {
|
||||
*v == 1.0
|
||||
}
|
||||
pub fn is_empty_vec<T>(v: &[T]) -> bool {
|
||||
v.is_empty()
|
||||
}
|
||||
pub fn is_empty_map(v: &serde_json::Map<String, serde_json::Value>) -> bool {
|
||||
v.is_empty()
|
||||
}
|
||||
@@ -274,6 +274,10 @@ pub fn auto_slices(region: Rect, cut: &[Rect]) -> Vec<Rect> {
|
||||
return vec![];
|
||||
}
|
||||
let inside: Vec<Rect> = cut.iter().map(|r| region.intersect(*r)).filter(|r| valid_rect(*r)).collect();
|
||||
// Every band scans every cut: past a bound the layout is refused, not truncated.
|
||||
if inside.len() > MAX_AUTO_CUTS {
|
||||
return vec![];
|
||||
}
|
||||
let mut ys: Vec<f64> = inside.iter().flat_map(|r| [r.y0, r.y1]).chain([region.y0, region.y1]).collect();
|
||||
ys.sort_by(f64::total_cmp);
|
||||
ys.dedup_by(|a, b| (*a - *b).abs() <= EPS);
|
||||
@@ -298,6 +302,9 @@ pub fn auto_slices(region: Rect, cut: &[Rect]) -> Vec<Rect> {
|
||||
// Spans continuing an open slice extend it; the others close.
|
||||
let mut next = Vec::with_capacity(free.len());
|
||||
for (a, b) in free {
|
||||
if done.len() + open.len() + next.len() >= MAX_AUTO_SLICES {
|
||||
break;
|
||||
}
|
||||
match open.iter().position(|r: &Rect| (r.x0 - a).abs() <= EPS && (r.x1 - b).abs() <= EPS) {
|
||||
Some(i) => {
|
||||
let mut r = open.swap_remove(i);
|
||||
@@ -309,7 +316,18 @@ pub fn auto_slices(region: Rect, cut: &[Rect]) -> Vec<Rect> {
|
||||
}
|
||||
done.append(&mut open);
|
||||
open = next;
|
||||
// Crossing strips make a cell of every crossing: the layout stops, short, past a bound.
|
||||
if done.len() + open.len() >= MAX_AUTO_SLICES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
done.append(&mut open);
|
||||
done.truncate(MAX_AUTO_SLICES);
|
||||
done
|
||||
}
|
||||
|
||||
/// The most slices automatic layout makes.
|
||||
const MAX_AUTO_SLICES: usize = 10_000;
|
||||
|
||||
/// The most cut rectangles automatic layout works through.
|
||||
const MAX_AUTO_CUTS: usize = 2_000;
|
||||
@@ -0,0 +1,418 @@
|
||||
use super::*;
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
mod lookups;
|
||||
mod slices;
|
||||
mod units;
|
||||
|
||||
/// Zooming in on an inch ruler divided the inch into tenths (#2827). Its steps below an inch
|
||||
/// are binary fractions now, and the minor ticks between them stay binary too; every other
|
||||
/// unit is still read in tenths.
|
||||
#[test]
|
||||
fn an_inch_ruler_steps_in_binary_fractions() {
|
||||
let step = |u: Unit, zoom: f64| u.ruler_step(zoom);
|
||||
// Every inch step at or below an inch is 1/2^k, never a tenth or a fifth.
|
||||
for zoom in [1.0, 2.0, 5.0, 7.5, 10.0, 20.0, 40.0, 100.0, 400.0] {
|
||||
let s = step(Unit::Inches, zoom);
|
||||
if s <= 1.0 {
|
||||
let k = s.recip();
|
||||
assert_eq!(k, k.round(), "{s} at zoom {zoom} is 1/k for a whole k");
|
||||
assert!((k.round() as u64).is_power_of_two(), "{s} at zoom {zoom} is 1/2^k");
|
||||
}
|
||||
// A label step always leaves at least 50 px, which is what the ladder is picked for.
|
||||
assert!(s * Unit::Inches.points() * zoom >= 50.0, "zoom {zoom}");
|
||||
}
|
||||
// The steps the report named: tenths became quarters, eighths and sixteenths.
|
||||
assert_eq!(step(Unit::Inches, 5.0), 0.25);
|
||||
assert_eq!(step(Unit::Inches, 10.0), 0.125);
|
||||
assert_eq!(step(Unit::Inches, 20.0), 0.0625);
|
||||
// An inch and wider is unchanged.
|
||||
assert_eq!(step(Unit::Inches, 1.0), 1.0);
|
||||
// Labelling stops at a sixteenth, as the report says Illustrator's does, so zooming in
|
||||
// further only adds ticks. A label therefore never needs more than the six characters of
|
||||
// "0.0625", which the left ruler has room for when it spells one out a character per line.
|
||||
for zoom in [20.0, 50.0, 100.0, 400.0, 1600.0] {
|
||||
assert_eq!(step(Unit::Inches, zoom), 0.0625, "zoom {zoom}");
|
||||
}
|
||||
// The unlabelled ticks go on down to a hundred and twenty-eighth: the 32nds, 64ths and
|
||||
// 128ths the report expects to appear unlabelled when zoomed in close.
|
||||
assert_eq!(Unit::Inches.ruler_minor(0.0625), 1.0 / 128.0);
|
||||
// The minor ticks: an eighth of the step on an inch ruler, a tenth elsewhere.
|
||||
assert_eq!(Unit::Inches.ruler_minor(0.25), 0.03125);
|
||||
assert_eq!(Unit::Millimeters.ruler_minor(25.0), 2.5);
|
||||
assert_eq!(Unit::Points.ruler_minor(100.0), 10.0);
|
||||
// Other units keep the decimal ladder, so a tenth and a fifth still appear.
|
||||
assert!([0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0].contains(&step(Unit::Millimeters, 5.0)), "{}", step(Unit::Millimeters, 5.0));
|
||||
}
|
||||
|
||||
fn doc_with_rects() -> (Document, NodeId, NodeId) {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
let layer = d.layers[0].id;
|
||||
let a = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(a, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art())).unwrap();
|
||||
let b = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(b, shapes::rectangle(Rect::new(20.0, 0.0, 30.0, 10.0)), Appearance::default_art())).unwrap();
|
||||
(d, a, b)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_document_has_layer_and_artboard() {
|
||||
let d = Document::new(612.0, 792.0);
|
||||
assert_eq!(d.layers.len(), 1);
|
||||
assert_eq!(d.layers[0].display_name(), "Layer 1");
|
||||
assert_eq!(d.artboards[0].rect, Rect::new(0.0, 0.0, 612.0, 792.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_on_artboard_takes_unlocked_objects_wholly_inside() {
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
let wide = Rect::new(-1.0, -1.0, 40.0, 15.0);
|
||||
assert_eq!(d.art_on_artboard(Rect::new(-1.0, -1.0, 15.0, 15.0), false), vec![a]);
|
||||
assert_eq!(d.art_on_artboard(Rect::new(-1.0, -1.0, 25.0, 15.0), false), vec![a], "b only half inside");
|
||||
// Flush with the artboard's edges counts as inside: the right and bottom ones too (#890).
|
||||
for board in [Rect::new(0.0, 0.0, 10.0, 10.0), Rect::new(-5.0, 0.0, 10.0, 15.0), Rect::new(0.0, -5.0, 15.0, 10.0)] {
|
||||
assert_eq!(d.art_on_artboard(board, false), vec![a], "{board:?}");
|
||||
}
|
||||
d.node_mut(a).unwrap().locked = true;
|
||||
assert_eq!(d.art_on_artboard(wide, false), vec![b]);
|
||||
// Move Locked and Hidden Artwork with Artboard (#394): hidden art stays too, unless on.
|
||||
d.node_mut(b).unwrap().visible = false;
|
||||
assert!(d.art_on_artboard(wide, false).is_empty());
|
||||
assert_eq!(d.art_on_artboard(wide, true), vec![a, b]);
|
||||
Arc::make_mut(&mut d.layers[0]).locked = true;
|
||||
assert!(d.art_on_artboard(wide, false).is_empty());
|
||||
assert_eq!(d.art_on_artboard(wide, true), vec![a, b], "a locked layer's art too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_on_artboard_tolerates_roundoff_at_each_edge() {
|
||||
let (d, a, _) = doc_with_rects();
|
||||
let roundoff = 1e-12;
|
||||
for board in [
|
||||
Rect::new(roundoff, 0.0, 10.0, 10.0),
|
||||
Rect::new(0.0, roundoff, 10.0, 10.0),
|
||||
Rect::new(0.0, 0.0, 10.0 - roundoff, 10.0),
|
||||
Rect::new(0.0, 0.0, 10.0, 10.0 - roundoff),
|
||||
] {
|
||||
assert_eq!(d.art_on_artboard(board, false), vec![a], "roundoff at {board:?}");
|
||||
}
|
||||
// A real overhang remains outside.
|
||||
for board in
|
||||
[Rect::new(0.001, 0.0, 10.0, 10.0), Rect::new(0.0, 0.001, 10.0, 10.0), Rect::new(0.0, 0.0, 9.999, 10.0), Rect::new(0.0, 0.0, 10.0, 9.999)]
|
||||
{
|
||||
assert!(d.art_on_artboard(board, false).is_empty(), "overhang at {board:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The art on a locked artboard (each object of a layer whose bounds overlap it, a group as one
|
||||
/// object) can't be edited, and Select All, a click and a marquee pass over it; art flush with
|
||||
/// the artboard from outside isn't on it, a layer is on no artboard, and new art isn't on one.
|
||||
/// Unlocking the artboard gives the art back.
|
||||
#[test]
|
||||
fn art_on_a_locked_artboard_cannot_be_selected_or_edited() {
|
||||
use crate::hit::{HitOptions, hit_test, marquee, objects_at};
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
let layer = d.layers[0].id;
|
||||
d.artboards.push(Artboard {
|
||||
id: 2,
|
||||
name: "Artboard 2".into(),
|
||||
rect: Rect::new(700.0, 0.0, 900.0, 200.0),
|
||||
locked: false,
|
||||
show_center_mark: false,
|
||||
show_cross_hairs: false,
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
});
|
||||
let rect = |d: &mut Document, r: Rect, appearance: Appearance| {
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(id, shapes::rectangle(r), appearance)).unwrap();
|
||||
id
|
||||
};
|
||||
let c = rect(&mut d, Rect::new(710.0, 10.0, 730.0, 30.0), Appearance::default_art());
|
||||
// A group with one member on the artboard and one right of it.
|
||||
let (g, m1, m2) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let members = [(m1, 750.0), (m2, 950.0)]
|
||||
.map(|(id, x)| Arc::new(Node::path(id, shapes::rectangle(Rect::new(x, 50.0, x + 10.0, 60.0)), Appearance::default_art())));
|
||||
d.insert(Some(layer), usize::MAX, Node::group(g, members.to_vec())).unwrap();
|
||||
// Unstroked and flush with the artboard's left edge, from outside.
|
||||
let e = rect(&mut d, Rect::new(680.0, 10.0, 700.0, 30.0), Appearance::default());
|
||||
let opt = HitOptions::default();
|
||||
let top = |d: &Document, x, y| hit_test(d, Point::new(x, y), opt).map(|h| h.top_object(None));
|
||||
let all = Rect::new(-10.0, -10.0, 1000.0, 800.0);
|
||||
assert_eq!(top(&d, 720.0, 20.0), Some(c));
|
||||
d.artboards[1].locked = true;
|
||||
for id in [c, g, m1, m2] {
|
||||
assert!(d.on_locked_artboard(id) && !d.is_editable(id), "{id:?} is on the locked artboard");
|
||||
}
|
||||
for id in [a, b, e, layer] {
|
||||
assert!(!d.on_locked_artboard(id) && d.is_editable(id), "{id:?} isn't");
|
||||
}
|
||||
assert_eq!(d.selectable_art(), [a, b, e]);
|
||||
assert_eq!(top(&d, 720.0, 20.0), None, "a click passes over c");
|
||||
assert_eq!(top(&d, 955.0, 55.0), None, "and over the group's member off the artboard");
|
||||
let isolated = HitOptions { scope: Some(g), ..opt };
|
||||
assert!(hit_test(&d, Point::new(755.0, 55.0), isolated).is_none(), "and inside the group isolated before the lock");
|
||||
assert!(objects_at(&d, Point::new(720.0, 20.0), opt, None).is_empty());
|
||||
assert_eq!(marquee(&d, all, None, false), [a, b, e]);
|
||||
assert_eq!(marquee(&d, all, None, true), [a, b, e], "the Direct Selection tool's marquee too");
|
||||
// Deselected in one pass, with the key object and the anchors.
|
||||
let mut sel = Selection::default();
|
||||
sel.set([a, c]);
|
||||
sel.key = Some(c);
|
||||
sel.anchors.insert(c, [(0, 0)].into());
|
||||
sel.deselect_on_locked_artboards(&d);
|
||||
assert_eq!((sel.objects.clone(), sel.key, sel.anchors.is_empty()), (vec![a], None, true));
|
||||
// A targeted layer stays targeted, with its art off the locked artboard selected.
|
||||
sel.set_target(&d, layer);
|
||||
sel.deselect_on_locked_artboards(&d);
|
||||
assert_eq!((sel.objects.clone(), sel.target), (vec![a, b, e], Some(layer)));
|
||||
// Shift-clicking the layer's target circle removes its art off the locked artboard, and
|
||||
// a second Shift-click adds it again.
|
||||
sel.toggle_target(&d, layer);
|
||||
sel.deselect_on_locked_artboards(&d);
|
||||
assert_eq!((sel.objects.clone(), sel.target), (vec![], None));
|
||||
sel.toggle_target(&d, layer);
|
||||
sel.deselect_on_locked_artboards(&d);
|
||||
assert_eq!(sel.objects, [a, b, e]);
|
||||
// A sublayer with art on both artboards: its art off the locked artboard can still be clicked.
|
||||
let (sub, s1, s2) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(layer), usize::MAX, Node::layer(sub, "Sub", LayerColor::Preset(2))).unwrap();
|
||||
for (id, x, y) in [(s1, 300.0, 300.0), (s2, 800.0, 100.0)] {
|
||||
d.insert(Some(sub), usize::MAX, Node::path(id, shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)), Appearance::default_art())).unwrap();
|
||||
}
|
||||
assert_eq!((top(&d, 305.0, 305.0), top(&d, 805.0, 105.0)), (Some(s1), None));
|
||||
assert!(!d.on_locked_artboard(sub));
|
||||
let mut both = Selection::default();
|
||||
both.set([s1, s2]);
|
||||
both.deselect_on_locked_artboards(&d);
|
||||
assert_eq!(both.objects, [s1]);
|
||||
// New art on it is editable and can be clicked while it is new art.
|
||||
d.new_art.set(Arc::new([c].into()));
|
||||
assert!(!d.on_locked_artboard(c) && d.is_editable(c), "new art");
|
||||
assert_eq!(top(&d, 720.0, 20.0), Some(c));
|
||||
d.new_art.set(Default::default());
|
||||
d.artboards[1].locked = false;
|
||||
assert_eq!(d.selectable_art(), [a, b, c, g, e, s1, s2]);
|
||||
assert_eq!(top(&d, 955.0, 55.0), Some(g));
|
||||
assert_eq!(marquee(&d, all, None, false), [a, b, c, g, e, s1, s2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_on_artboard_measures_a_symbol_instance_by_its_art() {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
d.symbols.push(Symbol { name: "Box".into(), art: Arc::new(art) });
|
||||
let (layer, id) = (d.layers[0].id, d.alloc_id());
|
||||
d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Box".into(), xf: Affine::translate((2.0, 2.0)) })).unwrap();
|
||||
// The art, (2, 2) to (12, 12), lies inside; the 20 × 20 square, (-8, -8) to (12, 12), doesn't.
|
||||
assert_eq!(d.art_on_artboard(Rect::new(0.0, 0.0, 15.0, 15.0), false), vec![id]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artboard_at_counts_the_right_and_bottom_edges() {
|
||||
// Artboard 0 is (0, 0) to (100, 100), artboard 1 is to its right and artboard 2 below it.
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
for rect in [Rect::new(100.0, 0.0, 200.0, 100.0), Rect::new(0.0, 100.0, 100.0, 200.0)] {
|
||||
let mut a = d.artboards[0].clone();
|
||||
a.rect = rect;
|
||||
d.artboards.push(a);
|
||||
}
|
||||
let held = |d: &Document, x: f64, y: f64| (d.artboard_at(Point::new(x, y)), d.artboard_holding(Point::new(x, y), false));
|
||||
// Each artboard's own right and bottom edges, edges with roundoff, and points beyond them.
|
||||
assert_eq!(held(&d, 200.0, 50.0), (Some(1), Some(1)), "right edge");
|
||||
assert_eq!(held(&d, 150.0, 100.0), (Some(1), Some(1)), "bottom edge");
|
||||
assert_eq!(held(&d, 200.0, 100.0), (Some(1), Some(1)), "bottom right corner");
|
||||
assert_eq!(held(&d, 100.0, 150.0), (Some(2), Some(2)), "right edge");
|
||||
assert_eq!(held(&d, 50.0, 200.0 + 1e-9), (Some(2), Some(2)), "roundoff past the bottom edge");
|
||||
assert_eq!(held(&d, -1e-9, 50.0), (Some(0), Some(0)), "roundoff past the left edge");
|
||||
assert_eq!(held(&d, 200.001, 50.0), (None, None));
|
||||
assert_eq!(held(&d, 50.0, 200.001), (None, None));
|
||||
// On an edge two artboards share, the artboard to the right of it or below it holds the
|
||||
// point, in either list order, except at the end of the edge that lies on that artboard's
|
||||
// bottom or right edge.
|
||||
assert_eq!(held(&d, 100.0, 50.0), (Some(1), Some(1)));
|
||||
assert_eq!(held(&d, 50.0, 100.0), (Some(2), Some(2)));
|
||||
// The bottom edges of artboards 0 and 1 meet at (100, 100), which is also artboard 2's top
|
||||
// right corner: the first holds the point, or the last when `topmost`.
|
||||
assert_eq!(held(&d, 100.0, 100.0), (Some(2), Some(0)), "shared corner");
|
||||
d.artboards.swap(0, 1);
|
||||
assert_eq!(held(&d, 100.0, 50.0), (Some(0), Some(0)));
|
||||
// Where two artboards overlap, the topmost holds the point, or the first one when not
|
||||
// `topmost`.
|
||||
let mut inner = d.artboards[1].clone();
|
||||
inner.rect = Rect::new(10.0, 10.0, 90.0, 90.0);
|
||||
d.artboards.push(inner);
|
||||
assert_eq!(held(&d, 50.0, 50.0), (Some(3), Some(1)));
|
||||
assert_eq!(held(&d, 90.0, 50.0), (Some(1), Some(1)), "inside artboard 1, on the right edge of artboard 3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_and_paths() {
|
||||
let (d, a, b) = doc_with_rects();
|
||||
assert_eq!(d.index_path(b), Some(vec![0, 1]));
|
||||
assert_eq!(d.parent_of(a), Some(d.layers[0].id));
|
||||
assert_eq!(d.layer_of(b), Some(d.layers[0].id));
|
||||
assert!(d.node(NodeId(999)).is_none());
|
||||
assert_eq!(d.node_count(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_on_write_shares_untouched() {
|
||||
let (d, a, b) = doc_with_rects();
|
||||
let mut e = d.clone();
|
||||
e.node_mut(a).unwrap().name = Some("A".into());
|
||||
// b's Arc is shared between both versions; a's is not.
|
||||
let lb = &d.layers[0].children().unwrap()[1];
|
||||
let eb = &e.layers[0].children().unwrap()[1];
|
||||
assert!(Arc::ptr_eq(lb, eb));
|
||||
assert_eq!(d.node(a).unwrap().name, None);
|
||||
assert_eq!(e.node(a).unwrap().name.as_deref(), Some("A"));
|
||||
let _ = b;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_and_remove() {
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
let layer = d.layers[0].id;
|
||||
d.move_node(a, Some(layer), usize::MAX).unwrap();
|
||||
assert_eq!(d.index_path(a), Some(vec![0, 1]));
|
||||
assert_eq!(d.index_path(b), Some(vec![0, 0]));
|
||||
let r = d.remove(a).unwrap();
|
||||
assert_eq!(r.id, a);
|
||||
assert!(d.node(a).is_none());
|
||||
assert!(d.move_node(layer, Some(layer), 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_and_names() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let l2 = d.add_layer(None);
|
||||
assert_eq!(d.node(l2).unwrap().display_name(), "Layer 2");
|
||||
assert_eq!(d.default_layer(), Some(l2));
|
||||
assert_eq!(d.layer_color(l2), LAYER_COLORS[1].1);
|
||||
}
|
||||
|
||||
/// #1718: a file whose ids or counters are at their type's largest value still hands out ids
|
||||
/// nothing in it uses (and never 0), instead of overflowing.
|
||||
#[test]
|
||||
fn exhausted_ids_in_a_file_dont_run_out() {
|
||||
let (d, a, b) = doc_with_rects();
|
||||
let mut v = serde_json::to_value(&d).unwrap();
|
||||
v["next_id"] = serde_json::json!(u64::MAX);
|
||||
// Object `a` gets the largest id there is.
|
||||
fn renumber(v: &mut serde_json::Value, from: u64) {
|
||||
match v {
|
||||
serde_json::Value::Object(o) => {
|
||||
if o.get("id").and_then(serde_json::Value::as_u64) == Some(from) {
|
||||
o.insert("id".into(), serde_json::json!(u64::MAX));
|
||||
}
|
||||
o.values_mut().for_each(|c| renumber(c, from));
|
||||
}
|
||||
serde_json::Value::Array(a) => a.iter_mut().for_each(|c| renumber(c, from)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
renumber(&mut v["layers"], a.0);
|
||||
let mut d: Document = serde_json::from_value(v).unwrap();
|
||||
assert!(d.node(NodeId(u64::MAX)).is_some(), "the file's largest id is kept");
|
||||
d.fix_next_id();
|
||||
let fresh: Vec<NodeId> = (0..3).map(|_| d.alloc_id()).collect();
|
||||
assert!(fresh.iter().all(|id| d.node(*id).is_none() && id.0 > b.0 && id.0 < MAX_NEXT_ID), "{fresh:?}");
|
||||
assert!(fresh[0] != fresh[1] && fresh[1] != fresh[2]);
|
||||
// A counter left at the end by other means stays there rather than wrapping to 0.
|
||||
d.next_id = u64::MAX;
|
||||
assert_eq!((d.alloc_id(), d.peek_next_id()), (NodeId(u64::MAX), u64::MAX));
|
||||
d.reserve_ids(u64::MAX);
|
||||
// Artboards and graphic styles: one past the largest, else the smallest id free.
|
||||
assert_eq!(free_id([1, 2, 7].into_iter()), 8);
|
||||
assert_eq!(free_id([u32::MAX, 0, 1, 2, 4].into_iter()), 3);
|
||||
assert_eq!(free_id([u32::MAX].into_iter()), 1);
|
||||
d.artboards[0].id = u32::MAX;
|
||||
assert_eq!(d.next_artboard_id(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serde_roundtrip() {
|
||||
let (d, _, _) = doc_with_rects();
|
||||
let s = serde_json::to_string(&d).unwrap();
|
||||
let back: Document = serde_json::from_str(&s).unwrap();
|
||||
assert_eq!(back.node_count(), d.node_count());
|
||||
assert_eq!(back.peek_next_id(), d.peek_next_id());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reid_gives_fresh_ids() {
|
||||
let (mut d, a, b) = doc_with_rects();
|
||||
let g = d.alloc_id();
|
||||
let na = (*d.remove(a).unwrap()).clone();
|
||||
let nb = (*d.remove(b).unwrap()).clone();
|
||||
let group = Node::group(g, vec![Arc::new(na), Arc::new(nb)]);
|
||||
let copy = d.reid(&group);
|
||||
assert_ne!(copy.id, g);
|
||||
let ids: Vec<NodeId> = copy.children().unwrap().iter().map(|c| c.id).collect();
|
||||
assert!(!ids.contains(&a) && !ids.contains(&b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setup_round_trips_and_old_files_load() {
|
||||
let (mut d, _, _) = doc_with_rects();
|
||||
// A document without a setup writes no `setup` key (old readers and files stay unchanged).
|
||||
assert!(!serde_json::to_string(&d).unwrap().contains("\"setup\""));
|
||||
d.setup.bleed = [9.0, 9.0, 0.0, 18.0];
|
||||
d.setup.grid_size = GridSize::Large;
|
||||
d.setup.typographers_quotes = false;
|
||||
d.setup.quotes = setup::language_quotes("German").unwrap();
|
||||
d.setup.flattener_preset = Some("High Resolution".into());
|
||||
d.setup.background = Background::White;
|
||||
d.setup.export_text = ExportText::Appearance;
|
||||
let back: Document = serde_json::from_str(&serde_json::to_string(&d).unwrap()).unwrap();
|
||||
assert_eq!(back.setup, d.setup);
|
||||
// Files written before Document Setup existed load with the defaults.
|
||||
let mut v = serde_json::to_value(&d).unwrap();
|
||||
v.as_object_mut().unwrap().remove("setup");
|
||||
let old: Document = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(old.setup, DocSetup::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn char_position_round_trips() {
|
||||
let st =
|
||||
CharStyle { position: CharPosition::Subscript(ScriptMetrics { size: 50.0, position: 20.0 }), small_caps: Some(75.0), ..CharStyle::default() };
|
||||
let v = serde_json::to_value(&st).unwrap();
|
||||
assert_eq!(v["position"], serde_json::json!({"kind": "subscript", "size": 50.0, "position": 20.0}));
|
||||
assert_eq!(serde_json::from_value::<CharStyle>(v).unwrap(), st);
|
||||
let plain = serde_json::to_value(CharStyle::default()).unwrap();
|
||||
assert!(plain.get("position").is_none() && plain.get("small_caps").is_none());
|
||||
let (scale, shift) = CharPosition::Subscript(ScriptMetrics::DEFAULT).scale_shift(10.0);
|
||||
assert!((scale - 0.583).abs() < 1e-9 && (shift + 3.33).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn units() {
|
||||
assert_eq!(Unit::Inches.parse("1"), Some(72.0));
|
||||
assert_eq!(Unit::Points.parse("1in"), Some(72.0));
|
||||
assert_eq!(Unit::Points.parse("10 mm").map(|v| (v * 1000.0).round()), Some(28346.0));
|
||||
assert_eq!(Unit::Points.parse("2p6"), Some(30.0));
|
||||
assert_eq!(Unit::Points.parse("10+5"), Some(15.0));
|
||||
assert_eq!(Unit::Points.parse("100/4"), Some(25.0));
|
||||
assert_eq!(Unit::Points.parse("-5"), Some(-5.0));
|
||||
assert_eq!(Unit::Points.parse("abc"), None);
|
||||
assert_eq!(Unit::Points.format(12.5), "12.5 pt");
|
||||
assert_eq!(Unit::Inches.format(144.0), "2 in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_picas_and_points_sign_applies_to_whole_value() {
|
||||
assert_eq!(Unit::Points.parse("-2p6"), Some(-30.0));
|
||||
assert_eq!(Unit::Points.parse("-0p6"), Some(-6.0));
|
||||
assert_eq!(Unit::Points.parse("-2p"), Some(-24.0));
|
||||
assert_eq!(Unit::Points.parse("2p6"), Some(30.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pica_form_rejects_exponent_notation() {
|
||||
for s in ["1e5p", "infp", "nanp", "infp3", "1p1e2"] {
|
||||
assert_eq!(Unit::Points.parse(s), None, "{s}");
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! with the one-id ones on nested trees with missing and duplicated ids, and the edits of many nodes
|
||||
//! ([`Document::remove_many`], `wrap`, `insert_beside`) leave the tree that `remove`, `insert` and
|
||||
//! `move_node` leave one node at a time.
|
||||
use super::*;
|
||||
use crate::*;
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
/// Layers with paths and groups nested `depth` deep; every 7th id is reused (a damaged file), so
|
||||
File renamed without changes.
@@ -3,7 +3,7 @@
|
||||
|
||||
use proptest::prelude::*;
|
||||
|
||||
use super::Unit;
|
||||
use crate::Unit;
|
||||
|
||||
#[test]
|
||||
fn every_unit_round_trips_through_its_field_text() {
|
||||
@@ -133,7 +133,7 @@ fn a_negative_operand_after_an_operator_is_a_sign() {
|
||||
assert_eq!(Unit::Points.parse("5 - -3"), Some(8.0));
|
||||
assert_eq!(Unit::Points.parse("5+-3"), Some(2.0));
|
||||
assert_eq!(Unit::Points.parse("10-2"), Some(8.0));
|
||||
assert_eq!(super::parse_number("90*-1"), Some(-90.0));
|
||||
assert_eq!(crate::parse_number("90*-1"), Some(-90.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
+17
-2389
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,228 @@
|
||||
use super::para_style::FirstBaseline;
|
||||
use super::*;
|
||||
|
||||
/// Area Type Options "Align" (vertical): where the lines of each row/column sit in it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VerticalAlign {
|
||||
/// Lines start at the top of the cell (the default).
|
||||
#[default]
|
||||
Top,
|
||||
/// The block of lines is centred in the cell.
|
||||
Center,
|
||||
/// The last line's descent touches the cell bottom.
|
||||
Bottom,
|
||||
/// The first line stays at the top, the last one moves to the bottom and the space left over
|
||||
/// is shared equally between the lines (no paragraph spacing limit).
|
||||
Justify,
|
||||
}
|
||||
|
||||
impl VerticalAlign {
|
||||
pub const ALL: [VerticalAlign; 4] = [VerticalAlign::Top, VerticalAlign::Center, VerticalAlign::Bottom, VerticalAlign::Justify];
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
VerticalAlign::Top => "top",
|
||||
VerticalAlign::Center => "center",
|
||||
VerticalAlign::Bottom => "bottom",
|
||||
VerticalAlign::Justify => "justify",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Text Wrap Options of a wrap object (Object → Text Wrap).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct TextWrap {
|
||||
/// Distance kept between the text and the object, in points (Illustrator's default 6 pt).
|
||||
pub offset: f64,
|
||||
/// Invert Wrap: text flows inside the object instead of around it.
|
||||
pub invert: bool,
|
||||
}
|
||||
|
||||
impl Default for TextWrap {
|
||||
fn default() -> Self {
|
||||
Self { offset: 6.0, invert: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// A resolved wrap shape on an area text object: the outline of a wrap object in text space.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct WrapShape {
|
||||
pub path: PathData,
|
||||
#[serde(flatten)]
|
||||
pub wrap: TextWrap,
|
||||
}
|
||||
|
||||
/// Type on a Path effect: how each glyph is oriented on the path (Type → Type on a Path).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PathEffect {
|
||||
/// Glyphs rotate with the path (the default).
|
||||
#[default]
|
||||
Rainbow,
|
||||
/// Vertical edges stay vertical; the baseline follows the path.
|
||||
Skew,
|
||||
/// Horizontal edges stay horizontal; vertical edges are perpendicular to the path.
|
||||
#[serde(rename = "3dRibbon")]
|
||||
Ribbon3d,
|
||||
/// No rotation: the left end of each glyph's baseline sits on the path.
|
||||
StairStep,
|
||||
/// The baseline centre sits on the path and glyphs point away from the path's centre.
|
||||
Gravity,
|
||||
}
|
||||
|
||||
impl PathEffect {
|
||||
pub const ALL: [PathEffect; 5] = [PathEffect::Rainbow, PathEffect::Skew, PathEffect::Ribbon3d, PathEffect::StairStep, PathEffect::Gravity];
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
PathEffect::Rainbow => "rainbow",
|
||||
PathEffect::Skew => "skew",
|
||||
PathEffect::Ribbon3d => "3dRibbon",
|
||||
PathEffect::StairStep => "stairStep",
|
||||
PathEffect::Gravity => "gravity",
|
||||
}
|
||||
}
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
let k = s.to_ascii_lowercase().replace([' ', '-', '_'], "");
|
||||
Self::ALL.into_iter().find(|e| e.id().to_ascii_lowercase() == k || (k == "ribbon3d" && *e == PathEffect::Ribbon3d))
|
||||
}
|
||||
}
|
||||
|
||||
/// Type on a Path Options › Align to Path: which height of the type runs along the path.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PathAlign {
|
||||
/// The font's top edge: the type hangs below the path.
|
||||
Ascender,
|
||||
/// The font's bottom edge: the type stands above the path.
|
||||
Descender,
|
||||
/// Halfway between the ascender and the descender.
|
||||
Center,
|
||||
/// The baseline (the default).
|
||||
#[default]
|
||||
Baseline,
|
||||
}
|
||||
|
||||
impl PathAlign {
|
||||
pub const ALL: [PathAlign; 4] = [PathAlign::Ascender, PathAlign::Descender, PathAlign::Center, PathAlign::Baseline];
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
PathAlign::Ascender => "ascender",
|
||||
PathAlign::Descender => "descender",
|
||||
PathAlign::Center => "center",
|
||||
PathAlign::Baseline => "baseline",
|
||||
}
|
||||
}
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|a| a.id().eq_ignore_ascii_case(s.trim()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Area Type Options: rows and columns, gutters, inset and first baseline of area type.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AreaOptions {
|
||||
#[serde(deserialize_with = "de_rows_or_columns")]
|
||||
pub rows: usize,
|
||||
#[serde(deserialize_with = "de_rows_or_columns")]
|
||||
pub columns: usize,
|
||||
/// Gutter between rows/columns in points.
|
||||
pub gutter: f64,
|
||||
/// Inset from the frame edges in points.
|
||||
pub inset: f64,
|
||||
pub first_baseline: FirstBaseline,
|
||||
/// Minimum first-baseline offset in points.
|
||||
pub first_baseline_min: f64,
|
||||
/// Vertical alignment of the lines in each row/column.
|
||||
pub vertical_align: VerticalAlign,
|
||||
/// How the frame and its text fit each other (Auto Size, Shrink Text to Fit).
|
||||
#[serde(skip_serializing_if = "crate::skip::is_default")]
|
||||
pub fit: AreaFit,
|
||||
}
|
||||
|
||||
impl Default for AreaOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
rows: 1,
|
||||
columns: 1,
|
||||
gutter: 18.0,
|
||||
inset: 0.0,
|
||||
first_baseline: FirstBaseline::Ascent,
|
||||
first_baseline_min: 0.0,
|
||||
vertical_align: VerticalAlign::Top,
|
||||
fit: AreaFit::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AreaOptions {
|
||||
/// The most rows, and the most columns, area type can have.
|
||||
pub const MAX_ROWS_COLUMNS: usize = 100;
|
||||
}
|
||||
|
||||
/// [`AreaOptions::rows`] or [`AreaOptions::columns`], read as a `u64` and clamped to
|
||||
/// 1..=[`AreaOptions::MAX_ROWS_COLUMNS`].
|
||||
fn de_rows_or_columns<'de, D: serde::Deserializer<'de>>(d: D) -> Result<usize, D::Error> {
|
||||
let n = usize::try_from(u64::deserialize(d)?).unwrap_or(usize::MAX);
|
||||
Ok(n.clamp(1, AreaOptions::MAX_ROWS_COLUMNS))
|
||||
}
|
||||
|
||||
/// How area type and its frame fit each other. Serialized as `"none"`, `"autoHeight"` or
|
||||
/// `{"shrinkText": {"minPercent": 50}}`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AreaFit {
|
||||
/// The frame keeps its size; text that doesn't fit overflows.
|
||||
#[default]
|
||||
None,
|
||||
/// The frame's height follows the text (Illustrator's Auto Size): resolved by the engine after
|
||||
/// each edit, for rectangular frames of horizontal type in one row.
|
||||
AutoHeight,
|
||||
/// Text that overflows is scaled down (size, leading and baseline shift; not paragraph
|
||||
/// spacing) by the largest factor down to `min_percent` % that makes it fit, at layout time.
|
||||
ShrinkText {
|
||||
#[serde(rename = "minPercent", default = "AreaFit::default_min_percent")]
|
||||
min_percent: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl AreaFit {
|
||||
/// The smallest Shrink Text to Fit percentage allowed.
|
||||
pub const MIN_PERCENT: f64 = 10.0;
|
||||
/// The Shrink Text to Fit percentage new settings start with.
|
||||
pub const DEFAULT_MIN_PERCENT: f64 = 50.0;
|
||||
fn default_min_percent() -> f64 {
|
||||
Self::DEFAULT_MIN_PERCENT
|
||||
}
|
||||
/// Its id: `none`, `autoHeight` or `shrinkText`.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
AreaFit::None => "none",
|
||||
AreaFit::AutoHeight => "autoHeight",
|
||||
AreaFit::ShrinkText { .. } => "shrinkText",
|
||||
}
|
||||
}
|
||||
/// The fit an id names (case, spaces, dashes and underscores ignored), with `min_percent`
|
||||
/// for Shrink Text (clamped to 10..100; a non-finite value gives the default).
|
||||
pub fn parse(id: &str, min_percent: Option<f64>) -> Option<Self> {
|
||||
match id.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str() {
|
||||
"none" | "off" => Some(AreaFit::None),
|
||||
"autoheight" | "autosize" => Some(AreaFit::AutoHeight),
|
||||
"shrinktext" | "shrinktexttofit" | "shrink" => {
|
||||
Some(AreaFit::ShrinkText { min_percent: Self::clamp_percent(min_percent.unwrap_or(Self::DEFAULT_MIN_PERCENT)) })
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// A Shrink Text minimum percentage within 10..100 (the default when not finite).
|
||||
pub fn clamp_percent(p: f64) -> f64 {
|
||||
if p.is_finite() { p.clamp(Self::MIN_PERCENT, 100.0) } else { Self::DEFAULT_MIN_PERCENT }
|
||||
}
|
||||
/// Shrink Text's minimum scale factor (0.1..1), if this is Shrink Text.
|
||||
pub fn min_scale(self) -> Option<f64> {
|
||||
match self {
|
||||
AreaFit::ShrinkText { min_percent } => Some(Self::clamp_percent(min_percent) / 100.0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
use super::para_style::ParaDirection;
|
||||
use super::*;
|
||||
|
||||
/// Character attributes (the Character panel).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CharStyle {
|
||||
pub font_family: String,
|
||||
#[serde(default = "regular")]
|
||||
pub font_style: String,
|
||||
/// Which installed version of the font (its version string) when several versions of the
|
||||
/// family and style are installed and the text was set in one the family and style alone
|
||||
/// wouldn't pick (an imported file's type matched to it); None = the one they pick.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub font_version: Option<String>,
|
||||
/// Variation axis settings of a variable font (Character panel › Variable Font), by axis tag
|
||||
/// (`wght`, `wdth`), in the axis's own units. They replace the named instance's setting of
|
||||
/// each axis they name; the other axes keep the style's settings. Empty: the style as it is.
|
||||
#[serde(default, rename = "fontAxes", skip_serializing_if = "std::collections::BTreeMap::is_empty")]
|
||||
pub font_axes: std::collections::BTreeMap<String, f64>,
|
||||
/// Size in points.
|
||||
pub size: f64,
|
||||
/// Leading in points; None = Auto (120% of size).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub leading: Option<f64>,
|
||||
/// Tracking in 1/1000 em.
|
||||
#[serde(default)]
|
||||
pub tracking: f64,
|
||||
/// Kerning: None = Auto (metrics), Some(v) = manual in 1/1000 em.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub kerning: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub baseline_shift: f64,
|
||||
#[serde(default = "hundred")]
|
||||
pub h_scale: f64,
|
||||
#[serde(default = "hundred")]
|
||||
pub v_scale: f64,
|
||||
#[serde(default)]
|
||||
pub rotation: f64,
|
||||
pub fill: Paint,
|
||||
#[serde(default)]
|
||||
pub stroke: Paint,
|
||||
#[serde(default)]
|
||||
pub stroke_width: f64,
|
||||
#[serde(default)]
|
||||
pub underline: bool,
|
||||
#[serde(default)]
|
||||
pub strikethrough: bool,
|
||||
#[serde(default)]
|
||||
pub all_caps: bool,
|
||||
/// OpenType features that differ from the defaults (OpenType panel), as tags: `"dlig"` turns
|
||||
/// a feature on, `"-liga"` off.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub features: Vec<String>,
|
||||
/// Character style (Character Styles panel) these attributes come from; None = Normal.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub style_name: Option<String>,
|
||||
/// Overprint Fill / Overprint Stroke of these characters (see [`crate::FillLayer::overprint`]).
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub overprint_fill: bool,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub overprint_stroke: bool,
|
||||
/// Cap, join, miter limit and dashes of the character stroke (Stroke panel, with type
|
||||
/// selected); defaults as for object strokes.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub stroke_cap: LineCap,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub stroke_join: LineJoin,
|
||||
#[serde(default = "ten", skip_serializing_if = "is_ten")]
|
||||
pub stroke_miter_limit: f64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub stroke_dash: Option<Dash>,
|
||||
/// Align Stroke of the character stroke (Stroke panel, with type selected): centred on the
|
||||
/// glyph outlines, inside or outside them, as for object strokes; the type stays live.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub stroke_align: StrokeAlign,
|
||||
/// Superscript or subscript (Character panel).
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub position: CharPosition,
|
||||
/// Small Caps (Character panel): lowercase letters drawn as capitals at this percentage of the
|
||||
/// size (Document Setup → Type → Small Caps); None = off.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub small_caps: Option<f64>,
|
||||
/// Character Alignment (Character panel menu): where characters smaller than the largest on
|
||||
/// their line line up with it.
|
||||
#[serde(default, rename = "charAlign", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub char_align: CharAlign,
|
||||
/// Character Direction (Character panel menu, Middle Eastern options): these characters are
|
||||
/// set left to right or right to left inside their paragraph, each stretch of them a Unicode
|
||||
/// bidi embedding (UAX #9 LRE or RLE); None = Default, the direction the bidi algorithm gives
|
||||
/// them.
|
||||
#[serde(default, rename = "charDirection", skip_serializing_if = "Option::is_none")]
|
||||
pub char_direction: Option<ParaDirection>,
|
||||
/// Proportional Metrics (Character panel menu, East Asian options): full-width glyphs take the
|
||||
/// font's own proportional widths, OpenType `palt` (#966); in vertical type upright glyphs take
|
||||
/// its proportional heights, `vpal`.
|
||||
#[serde(default, rename = "proportionalMetrics", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub proportional_metrics: bool,
|
||||
/// Tate-chu-yoko (Character panel menu, East Asian options): in vertical type these characters
|
||||
/// stand side by side across one em of the column. Horizontal type keeps the mark and does not
|
||||
/// move them. Two or three half-width digits do this without the mark.
|
||||
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
|
||||
#[serde(default, rename = "tateChuYoko", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub tate_chu_yoko: bool,
|
||||
/// Digits (Character panel menu, Middle Eastern options): the numeral system the digits of
|
||||
/// these characters are drawn in, whatever digits were typed.
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
pub digits: Digits,
|
||||
/// No Break (Character panel menu): these characters are not broken across lines, including
|
||||
/// at a space or a hyphenation point inside the run. A run longer than the line stays together
|
||||
/// and can overflow it.
|
||||
/// <https://helpx.adobe.com/illustrator/using/hyphenation-line-breaks.html>
|
||||
#[serde(default, rename = "noBreak", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub no_break: bool,
|
||||
}
|
||||
|
||||
/// The numeral system digits are drawn in ([`CharStyle::digits`]): as typed, or every digit of
|
||||
/// the Western, Arabic-Indic and Eastern Arabic-Indic sets drawn in one of them. The text keeps
|
||||
/// the digits that were typed; only the glyphs change (like All Caps).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Digits {
|
||||
/// Each digit as typed.
|
||||
#[default]
|
||||
Default,
|
||||
/// Western digits 0–9 (the digits Arabic typography calls Arabic).
|
||||
Arabic,
|
||||
/// Arabic-Indic digits ٠–٩ (U+0660–U+0669), used in Arabic.
|
||||
Hindi,
|
||||
/// Eastern Arabic-Indic digits ۰–۹ (U+06F0–U+06F9), used in Persian and Urdu.
|
||||
Farsi,
|
||||
}
|
||||
|
||||
impl Digits {
|
||||
/// The digit `c` is drawn as in this numeral system: the same digit in the chosen set, or `c`
|
||||
/// itself when `c` isn't a digit of the Western, Arabic-Indic or Eastern Arabic-Indic set.
|
||||
pub fn map(self, c: char) -> char {
|
||||
let value = match c {
|
||||
'0'..='9' => c as u32 - '0' as u32,
|
||||
'\u{660}'..='\u{669}' => c as u32 - 0x660,
|
||||
'\u{6F0}'..='\u{6F9}' => c as u32 - 0x6F0,
|
||||
_ => return c,
|
||||
};
|
||||
let base = match self {
|
||||
Digits::Default => return c,
|
||||
Digits::Arabic => '0' as u32,
|
||||
Digits::Hindi => 0x660,
|
||||
Digits::Farsi => 0x6F0,
|
||||
};
|
||||
char::from_u32(base + value).unwrap_or(c)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a character smaller than the largest on its line lines up with it: on the Roman
|
||||
/// baseline, at the top (right, in vertical type), centre or bottom (left) of the ideographic
|
||||
/// em boxes, or at the top (right) or bottom (left) of the ideographic character faces (ICF, the
|
||||
/// average box of the ideographs inside the em box: OpenType's `icft` and `icfb` baselines).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum CharAlign {
|
||||
#[default]
|
||||
RomanBaseline,
|
||||
EmBoxTop,
|
||||
EmBoxCenter,
|
||||
EmBoxBottom,
|
||||
IcfTop,
|
||||
IcfBottom,
|
||||
}
|
||||
|
||||
/// Superscript or subscript proportions in percent of the font size (Document Setup → Type).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ScriptMetrics {
|
||||
/// Glyph size.
|
||||
pub size: f64,
|
||||
/// Baseline offset: up for superscript, down for subscript.
|
||||
pub position: f64,
|
||||
}
|
||||
|
||||
impl ScriptMetrics {
|
||||
pub const DEFAULT: Self = Self { size: 58.3, position: 33.3 };
|
||||
/// Returns these proportions with the size kept to 1 to 500% and the position kept to -500 to
|
||||
/// 500%, the ranges `document.setup` takes for `superscript` and `subscript`. A value outside
|
||||
/// its range becomes the nearer end.
|
||||
pub fn in_range(self) -> Self {
|
||||
Self { size: self.size.clamp(1.0, 500.0), position: self.position.clamp(-500.0, 500.0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a small caps size kept to 1 to 200%, the range `document.setup` takes for
|
||||
/// `smallCapsSize`. A size outside it becomes the nearer end.
|
||||
fn small_caps_in_range(size: f64) -> f64 {
|
||||
size.clamp(1.0, 200.0)
|
||||
}
|
||||
|
||||
impl Default for ScriptMetrics {
|
||||
fn default() -> Self {
|
||||
Self::DEFAULT
|
||||
}
|
||||
}
|
||||
|
||||
/// Character position (Character panel Superscript / Subscript). The proportions are the
|
||||
/// document's when the position is applied, and follow later Document Setup changes.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum CharPosition {
|
||||
#[default]
|
||||
Normal,
|
||||
Superscript(ScriptMetrics),
|
||||
Subscript(ScriptMetrics),
|
||||
}
|
||||
|
||||
impl CharPosition {
|
||||
/// Glyph scale and baseline shift (points, positive = up) for text of `size` points.
|
||||
pub fn scale_shift(self, size: f64) -> (f64, f64) {
|
||||
match self {
|
||||
CharPosition::Normal => (1.0, 0.0),
|
||||
CharPosition::Superscript(m) => (m.size / 100.0, m.position / 100.0 * size),
|
||||
CharPosition::Subscript(m) => (m.size / 100.0, -m.position / 100.0 * size),
|
||||
}
|
||||
}
|
||||
/// `normal`, `superscript` or `subscript`.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
CharPosition::Normal => "normal",
|
||||
CharPosition::Superscript(_) => "superscript",
|
||||
CharPosition::Subscript(_) => "subscript",
|
||||
}
|
||||
}
|
||||
/// Returns this position with its proportions kept by [`ScriptMetrics::in_range`].
|
||||
pub fn in_range(self) -> Self {
|
||||
match self {
|
||||
CharPosition::Normal => CharPosition::Normal,
|
||||
CharPosition::Superscript(m) => CharPosition::Superscript(m.in_range()),
|
||||
CharPosition::Subscript(m) => CharPosition::Subscript(m.in_range()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ten() -> f64 {
|
||||
10.0
|
||||
}
|
||||
|
||||
fn is_ten(v: &f64) -> bool {
|
||||
*v == 10.0
|
||||
}
|
||||
|
||||
fn regular() -> String {
|
||||
"Regular".into()
|
||||
}
|
||||
|
||||
fn hundred() -> f64 {
|
||||
100.0
|
||||
}
|
||||
|
||||
pub(super) fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl Default for CharStyle {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
font_family: "Source Sans 3".into(),
|
||||
font_style: "Regular".into(),
|
||||
font_version: None,
|
||||
font_axes: std::collections::BTreeMap::new(),
|
||||
size: 12.0,
|
||||
leading: None,
|
||||
tracking: 0.0,
|
||||
kerning: None,
|
||||
baseline_shift: 0.0,
|
||||
h_scale: 100.0,
|
||||
v_scale: 100.0,
|
||||
rotation: 0.0,
|
||||
fill: Paint::solid(Color::BLACK),
|
||||
stroke: Paint::None,
|
||||
stroke_width: 0.0,
|
||||
underline: false,
|
||||
strikethrough: false,
|
||||
all_caps: false,
|
||||
features: vec![],
|
||||
style_name: None,
|
||||
overprint_fill: false,
|
||||
overprint_stroke: false,
|
||||
stroke_cap: LineCap::Butt,
|
||||
stroke_join: LineJoin::Miter,
|
||||
stroke_miter_limit: 10.0,
|
||||
stroke_dash: None,
|
||||
stroke_align: StrokeAlign::Center,
|
||||
position: CharPosition::Normal,
|
||||
char_align: CharAlign::RomanBaseline,
|
||||
char_direction: None,
|
||||
proportional_metrics: false,
|
||||
tate_chu_yoko: false,
|
||||
small_caps: None,
|
||||
digits: Digits::Default,
|
||||
no_break: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CharStyle {
|
||||
pub fn effective_leading(&self) -> f64 {
|
||||
self.leading.unwrap_or(self.size * 1.2)
|
||||
}
|
||||
/// Keeps the size, leading, baseline shift and horizontal and vertical scales in range: a size
|
||||
/// or scale of 0 or less becomes the default new type takes (12 pt, 100%), a negative leading
|
||||
/// becomes Auto, and a value past [`crate::MAX_COORD`] (a baseline shift past it either way)
|
||||
/// becomes the nearer end. A leading of 0, which legacy `.ai` import stores, stays, and a
|
||||
/// baseline shift that is not a number becomes 0.
|
||||
pub fn keep_dimensions_in_range(&mut self) {
|
||||
let default = Self::default();
|
||||
let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or };
|
||||
self.size = within(self.size, default.size);
|
||||
self.h_scale = within(self.h_scale, default.h_scale);
|
||||
self.v_scale = within(self.v_scale, default.v_scale);
|
||||
self.leading = self.leading.filter(|l| *l >= 0.0).map(|l| l.min(crate::MAX_COORD));
|
||||
self.baseline_shift = if self.baseline_shift.is_nan() { 0.0 } else { self.baseline_shift.clamp(-crate::MAX_COORD, crate::MAX_COORD) };
|
||||
}
|
||||
/// Do the characters draw a stroke (a paint and a positive weight)?
|
||||
pub fn has_stroke(&self) -> bool {
|
||||
!self.stroke.is_none() && self.stroke_width > 0.0
|
||||
}
|
||||
/// The character stroke as a stroke layer (paint, weight, cap, join, miter limit, dashes,
|
||||
/// alignment and overprint), so type strokes share the object strokes' geometry, rendering
|
||||
/// and export.
|
||||
pub fn stroke_layer(&self) -> StrokeLayer {
|
||||
StrokeLayer {
|
||||
overprint: self.overprint_stroke,
|
||||
cap: self.stroke_cap,
|
||||
join: self.stroke_join,
|
||||
miter_limit: self.stroke_miter_limit,
|
||||
dash: self.stroke_dash.clone(),
|
||||
align: self.stroke_align,
|
||||
..StrokeLayer::new(self.stroke.clone(), self.stroke_width)
|
||||
}
|
||||
}
|
||||
/// Take the paint, weight, cap, join, miter limit, dashes and alignment of `st` as the
|
||||
/// character stroke (the options characters have no use for, such as arrowheads and width
|
||||
/// profiles, are dropped).
|
||||
pub fn set_stroke_layer(&mut self, st: &StrokeLayer) {
|
||||
self.stroke = st.paint.clone();
|
||||
self.stroke_width = st.width;
|
||||
self.stroke_cap = st.cap;
|
||||
self.stroke_join = st.join;
|
||||
self.stroke_miter_limit = st.miter_limit;
|
||||
self.stroke_dash = st.dash.clone();
|
||||
self.stroke_align = st.align;
|
||||
}
|
||||
/// How far the character stroke paints past the glyph outlines (text space): half the weight
|
||||
/// centred, the whole weight outside, nothing inside (miter spikes aside).
|
||||
pub fn stroke_outset(&self) -> f64 {
|
||||
if !self.has_stroke() {
|
||||
return 0.0;
|
||||
}
|
||||
match self.stroke_align {
|
||||
StrokeAlign::Center => self.stroke_width / 2.0,
|
||||
StrokeAlign::Outside => self.stroke_width,
|
||||
StrokeAlign::Inside => 0.0,
|
||||
}
|
||||
}
|
||||
/// The character fill as a fill layer, overprinting as the characters do.
|
||||
fn fill_layer(&self) -> FillLayer {
|
||||
FillLayer { overprint: self.overprint_fill, ..FillLayer::new(self.fill.clone()) }
|
||||
}
|
||||
/// The characters' paint as an object appearance (their outlines'): the fill, plus the
|
||||
/// stroke when it draws one, overprinting as the characters do.
|
||||
pub fn appearance(&self) -> Appearance {
|
||||
let mut a = Appearance { items: vec![AppearanceItem::Fill(self.fill_layer())], ..Default::default() };
|
||||
if self.has_stroke() {
|
||||
a.items.push(AppearanceItem::Stroke(self.stroke_layer()));
|
||||
}
|
||||
a
|
||||
}
|
||||
/// The characters' paint as the basic fill and stroke rows (the stroke row even when it has
|
||||
/// no paint): the appearance the Eyedropper and graphic styles take from type.
|
||||
pub fn basic_appearance(&self) -> Appearance {
|
||||
Appearance { items: vec![AppearanceItem::Fill(self.fill_layer()), AppearanceItem::Stroke(self.stroke_layer())], ..Default::default() }
|
||||
}
|
||||
/// Keeps the superscript or subscript proportions in range with [`CharPosition::in_range`] and
|
||||
/// keeps the small caps size to 1 to 200%, the range `document.setup` takes for `smallCapsSize`.
|
||||
pub fn keep_scripts_in_range(&mut self) {
|
||||
self.position = self.position.in_range();
|
||||
self.small_caps = self.small_caps.map(small_caps_in_range);
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Document {
|
||||
/// Keeps the superscript, subscript and small caps proportions to the ranges `document.setup`
|
||||
/// takes ([`CharStyle::keep_scripts_in_range`]) in the type of the layers, symbols, graph
|
||||
/// designs, pattern swatches and the pattern definition that pattern editing's Cancel puts
|
||||
/// back (opacity-mask art included), in graphs' label styles and in the character styles. It
|
||||
/// recurses through the art: call it on a document no deeper than [`crate::depth::MAX_DEPTH`].
|
||||
pub fn keep_scripts_in_range(&mut self) {
|
||||
let mut fix = |n: &mut crate::Node| {
|
||||
if let crate::NodeKind::Text(t) = &mut n.kind {
|
||||
for r in &mut t.runs {
|
||||
r.style.keep_scripts_in_range();
|
||||
}
|
||||
}
|
||||
if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
|
||||
let l = &mut g.label_styles;
|
||||
for st in [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten() {
|
||||
st.keep_scripts_in_range();
|
||||
}
|
||||
}
|
||||
};
|
||||
let roots = self
|
||||
.layers
|
||||
.iter_mut()
|
||||
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
|
||||
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
|
||||
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
|
||||
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
|
||||
for root in roots {
|
||||
crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix);
|
||||
}
|
||||
// Character styles store the attributes they set by their serialized names.
|
||||
for def in self.char_styles.iter_mut() {
|
||||
if let Some(v) = def.attrs.get_mut("position")
|
||||
&& let Ok(p) = serde_json::from_value::<CharPosition>(v.clone())
|
||||
&& p.in_range() != p
|
||||
{
|
||||
*v = serde_json::to_value(p.in_range()).unwrap_or(serde_json::Value::Null);
|
||||
}
|
||||
if let Some(v) = def.attrs.get_mut("small_caps")
|
||||
&& let Some(size) = v.as_f64()
|
||||
&& small_caps_in_range(size) != size
|
||||
{
|
||||
*v = small_caps_in_range(size).into();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1138 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user