mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 19:41:36 -05:00
Merge main into feat/scripts-api-d8b-tracing
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# The DXF writer goldens are compared byte for byte with the writer's output (LF line endings).
|
||||
crates/cad/tests/data/*.dxf -text
|
||||
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1398097510,
|
||||
"producer_workflow_id": 430275079,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_tooling_revision": "main",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"signer_tooling_revision": "main",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
@@ -38,27 +38,32 @@
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 1/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 1/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 2/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 2/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 3/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 3/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 4/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 4/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 5/5 (ubuntu-24.04)",
|
||||
"name": "gate / test 5/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 6/6 (ubuntu-24.04)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
@@ -130,7 +135,15 @@
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
|
||||
@@ -39,11 +39,12 @@ jobs:
|
||||
dev-strip: true
|
||||
# The workspace crates also build without line tables. A panic still names its file and line.
|
||||
dev-debug: "0"
|
||||
# Five legs instead of one: shards 1 to 4 each build and run the tests of their own crates,
|
||||
# and shard 5 runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate (<os>)`
|
||||
# passes only when all five did. On pushes to main, a `cache warm` leg builds what every
|
||||
# shard builds and saves the dependency cache.
|
||||
test-shards: 5
|
||||
# Six legs instead of one: shards 1 and 2 each build vectorcraft-ui-egui's tests and run
|
||||
# half of them, shards 3 to 5 each build and run the tests of their own crates, and shard 6
|
||||
# runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate (<os>)` passes only
|
||||
# when all six did. On pushes to main, a `cache warm` leg builds what every shard builds and
|
||||
# saves the dependency cache.
|
||||
test-shards: 6
|
||||
shard-command: cargo xtask ci shard
|
||||
warm-command: cargo xtask ci warm
|
||||
# The dependency cache also keeps the compiled workspace crates and test executables, so a
|
||||
@@ -89,14 +90,15 @@ jobs:
|
||||
# 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes
|
||||
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
|
||||
# When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run
|
||||
# failed jobs" runs it again beside the re-run leg. The script's 160-minute wait starts when the leg
|
||||
# starts, which is after `gate / select legs` and a free runner, so this job's timeout leaves
|
||||
# 40 minutes for that.
|
||||
# failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a
|
||||
# free runner: the script fails when the leg has not started within 120 minutes, and then waits
|
||||
# up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the
|
||||
# script reports a leg that starts late with its own error before the job times out.
|
||||
cold-cache-clear:
|
||||
name: cold cache clear
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 200
|
||||
timeout-minutes: 290
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
|
||||
@@ -34,12 +34,26 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: main
|
||||
app-name: vectorcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the release environment and export its keys; that environment must
|
||||
# admit nightly-signer alongside release before the first dispatch.
|
||||
|
||||
@@ -22,9 +22,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: main
|
||||
app-name: vectorcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
@@ -32,3 +32,4 @@ jobs:
|
||||
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
|
||||
# #369 and #364).
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
|
||||
|
||||
@@ -7,9 +7,26 @@ on:
|
||||
- "apps/vectorcraft/Cargo.toml"
|
||||
- "apps/vectorcraft/src/printing.rs"
|
||||
- "apps/vectorcraft/src/printing/**"
|
||||
- "crates/ui-egui/Cargo.toml"
|
||||
- "crates/ui-egui/src/print.rs"
|
||||
- "crates/ui-egui/src/tests/printps.rs"
|
||||
- ".github/workflows/print.yml"
|
||||
# A push to main saves the Windows cache entry that pull requests restore.
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "Cargo.toml"
|
||||
- "Cargo.lock"
|
||||
- "apps/vectorcraft/Cargo.toml"
|
||||
- "apps/vectorcraft/src/printing.rs"
|
||||
- "apps/vectorcraft/src/printing/**"
|
||||
- "crates/ui-egui/Cargo.toml"
|
||||
- "crates/ui-egui/src/print.rs"
|
||||
- "crates/ui-egui/src/tests/printps.rs"
|
||||
- ".github/workflows/print.yml"
|
||||
# A weekly run on main saves a fresh entry after a new stable Rust changes the cache key.
|
||||
schedule:
|
||||
- cron: "23 6 * * 1"
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -18,15 +35,14 @@ concurrency:
|
||||
group: print-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
jobs:
|
||||
# Desktop printing on Windows, through the suite's shared gate. Pull requests restore the cache
|
||||
# but never save one; a manual run on main saves the cache they restore.
|
||||
# Desktop printing on Windows, through the suite's shared gate. Pushes to main, the weekly run and
|
||||
# manual runs on main save the cache; pull requests restore it and never save one.
|
||||
windows:
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
os: '["windows-2022"]'
|
||||
# A change to Cargo.lock finds no cache (only main saves one) and builds everything cold:
|
||||
# about 55 minutes for `-p vectorcraft` alone, then the UI crate's tests.
|
||||
# A run that finds no cache builds everything cold, which took 76 to 126 minutes.
|
||||
timeout-minutes: 150
|
||||
# As in ci.yml: test binaries without debug info or symbols, and workspace crates without
|
||||
# line tables. A panic still names its file and line.
|
||||
@@ -36,10 +52,14 @@ jobs:
|
||||
craft-fonts-ref: ""
|
||||
tools: ""
|
||||
targets: ""
|
||||
# A filter that matches nothing still passes, so the printps run fails unless some test ran.
|
||||
# Both test runs select the same two packages, so Cargo resolves features once and the
|
||||
# second run reuses the first run's dependencies. The first runs every test of the app
|
||||
# (`--bin vectorcraft --test it`), the second the UI crate's `tests::printps` tests. A filter
|
||||
# that matches nothing still passes, so the printps run fails unless some test ran.
|
||||
command: |
|
||||
set -o pipefail
|
||||
cargo clippy --locked -p vectorcraft --all-targets -- -D warnings
|
||||
cargo test --locked -p vectorcraft
|
||||
cargo test --locked -p vectorcraft -p vectorcraft-ui-egui --bin vectorcraft --test it
|
||||
log="$RUNNER_TEMP/printps.log"
|
||||
cargo test --locked -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log"
|
||||
cargo test --locked -p vectorcraft -p vectorcraft-ui-egui --lib -- tests::printps | tee "$log"
|
||||
grep -Eq 'test result: ok\. [1-9][0-9]* passed' "$log" || { echo "::error::tests::printps matched no tests"; exit 1; }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
name: SonarCloud
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
@@ -33,7 +33,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
|
||||
**Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay.
|
||||
|
||||
**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=<craft-fonts checkout>` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-<family>.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them.
|
||||
**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=<craft-fonts checkout>` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-<family>.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. Desktop builds with a checkout whose opt-in `fonts/latin-manifest.txt` lists Noto Sans Condensed SemiBold (The Noto Project Authors, SIL Open Font License 1.1, from the [notofonts/latin-greek-cyrillic NotoSans-v2.015 release](https://github.com/notofonts/latin-greek-cyrillic/releases/tag/NotoSans-v2.015)) also embed that face, for document tab titles.
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
|
||||
Generated
+179
-97
@@ -613,6 +613,19 @@ version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "blake3"
|
||||
version = "1.8.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "64c0e36294adc8db531500e3f2b8ec75c4af9177271e9c6d33f93609d56e57cd"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"constant_time_eq",
|
||||
"cpufeatures 0.3.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block"
|
||||
version = "0.1.6"
|
||||
@@ -1106,6 +1119,15 @@ version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
|
||||
|
||||
[[package]]
|
||||
name = "constant_time_eq"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7"
|
||||
dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cookie-factory"
|
||||
version = "0.3.3"
|
||||
@@ -1217,7 +1239,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1258,7 +1280,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-affinity"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1269,7 +1291,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
@@ -1280,7 +1302,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1288,7 +1310,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1313,7 +1335,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
@@ -1331,7 +1353,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1349,7 +1371,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cdr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1358,7 +1380,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1366,7 +1388,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1375,12 +1397,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1400,11 +1422,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-control-protocol",
|
||||
"craft-platform",
|
||||
"getrandom 0.3.4",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
@@ -1412,8 +1433,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde_json",
|
||||
"subtle",
|
||||
]
|
||||
@@ -1421,7 +1443,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1429,7 +1451,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
@@ -1452,10 +1474,26 @@ dependencies = [
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-doc"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"craft-ecproj-format",
|
||||
"craft-pcraft-format",
|
||||
"craft-vectorcraft-format",
|
||||
"flate2",
|
||||
"ruzstd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1463,7 +1501,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1482,7 +1520,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1491,15 +1529,25 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ecproj-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1514,7 +1562,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1533,7 +1581,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -1542,7 +1590,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
@@ -1565,12 +1613,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"gif",
|
||||
]
|
||||
@@ -1578,7 +1626,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
@@ -1586,7 +1634,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1599,7 +1647,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"fixed_decimal",
|
||||
@@ -1627,7 +1675,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1654,7 +1702,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1672,7 +1720,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1680,7 +1728,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jxl"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"brotli-decompressor 5.0.3",
|
||||
"jixel",
|
||||
@@ -1691,7 +1739,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1706,7 +1754,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-layers"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -1720,7 +1768,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1738,7 +1786,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
@@ -1750,7 +1798,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1761,7 +1809,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
@@ -1771,7 +1819,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1784,10 +1832,21 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1799,7 +1858,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"async-io",
|
||||
@@ -1830,7 +1889,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1839,7 +1898,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1863,7 +1922,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -1874,7 +1933,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-eps",
|
||||
"flate2",
|
||||
@@ -1888,7 +1947,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -1899,7 +1958,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -1912,7 +1971,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1931,7 +1990,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -1948,7 +2007,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
@@ -1959,7 +2018,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-xml",
|
||||
@@ -1980,7 +2039,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1992,7 +2051,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-manager",
|
||||
@@ -2017,7 +2076,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2032,7 +2091,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2047,7 +2106,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2057,7 +2116,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2066,7 +2125,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2081,12 +2140,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2100,7 +2159,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -2116,7 +2175,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2154,7 +2213,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2165,7 +2224,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2183,7 +2242,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2204,7 +2263,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2225,7 +2284,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2244,7 +2303,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -2276,7 +2335,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -2287,7 +2346,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wayland"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"raw-window-handle",
|
||||
"wayland-backend",
|
||||
@@ -2297,7 +2356,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2308,7 +2367,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2316,7 +2375,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2348,7 +2407,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2693,7 +2752,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||
[[package]]
|
||||
name = "ecolor"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
@@ -2726,7 +2785,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "eframe"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2761,7 +2820,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -2780,7 +2839,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2799,7 +2858,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-winit"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"accesskit_winit",
|
||||
"arboard",
|
||||
@@ -2824,7 +2883,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"egui",
|
||||
@@ -2838,7 +2897,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -2851,7 +2910,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_kittest"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"dify",
|
||||
"eframe",
|
||||
@@ -2877,7 +2936,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
[[package]]
|
||||
name = "emath"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -2958,7 +3017,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2984,7 +3043,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
@@ -3703,7 +3762,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
@@ -3712,7 +3771,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3730,7 +3789,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3748,12 +3807,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4736,7 +4795,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -4893,7 +4952,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
@@ -8600,6 +8659,7 @@ dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
"vectorcraft-color",
|
||||
@@ -8637,6 +8697,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"craft-cdr",
|
||||
"craft-codepage",
|
||||
"craft-doc",
|
||||
"craft-docpath",
|
||||
"craft-image-codecs",
|
||||
"craft-jxl",
|
||||
@@ -8719,6 +8780,7 @@ dependencies = [
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-effects",
|
||||
"vectorcraft-eps",
|
||||
"vectorcraft-geom 0.24.1",
|
||||
"vectorcraft-metafile",
|
||||
"vectorcraft-pathops 0.24.1",
|
||||
@@ -8875,6 +8937,16 @@ dependencies = [
|
||||
"vectorcraft-text",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-plugin-worker"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"vectorcraft-plugins",
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-plugins"
|
||||
version = "0.24.1"
|
||||
@@ -8891,6 +8963,7 @@ dependencies = [
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-geom 0.24.1",
|
||||
"vectorcraft-js",
|
||||
"vectorcraft-plugins",
|
||||
"wasmi",
|
||||
"wasmparser 0.228.0",
|
||||
"wat",
|
||||
@@ -9020,6 +9093,15 @@ dependencies = [
|
||||
"vectorcraft-pathops 0.24.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-thumbnail-handler"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"png 0.18.1",
|
||||
"windows",
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vectorcraft-tools"
|
||||
version = "0.24.1"
|
||||
@@ -10680,14 +10762,14 @@ dependencies = [
|
||||
[[patch.unused]]
|
||||
name = "egui_demo_lib"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_inspection"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_system_font_provider"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=14c39fed181756be6f357c284354e0ab55b64443#14c39fed181756be6f357c284354e0ab55b64443"
|
||||
|
||||
+50
-48
@@ -11,44 +11,46 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["pcraft-pixels"] }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
|
||||
# the members it imports.
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui
|
||||
# without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes.
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -191,25 +193,25 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
@@ -45,6 +45,8 @@ fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.m
|
||||
Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC and Noto Sans Arabic in the current manifest;
|
||||
web builds BIZ UDPGothic Regular only) under the SIL
|
||||
Open Font License 1.1. Their license texts ship with the release packages as OFL-<family>.txt.
|
||||
Desktop builds with a craft-fonts checkout whose fonts/latin-manifest.txt lists Noto Sans Condensed
|
||||
SemiBold (Copyright 2022 The Noto Project Authors, SIL Open Font License 1.1) also embed that face.
|
||||
|
||||
PDF import decodes CJK text with Adobe's CMap resources (https://github.com/adobe-type-tools/cmap-resources),
|
||||
compiled into the app through the hayro-cmap crate under the BSD 3-Clause License:
|
||||
|
||||
@@ -174,6 +174,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and, with Measurement Labels on, its radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-28: The Three-Point Arc tool joins an arc to the open paths whose ends its ends are placed on, with Join to Open Path Ends (Tool Options, or J while drawing; `shape.threePointArc` `join`), and in direction mode snaps the third point to where the arc carries an open path on, the same way or turned back (Snap Where the Arc Continues a Path, on by default). Headline numbers unchanged.
|
||||
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//! vectorcraft-cli commands
|
||||
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
//! vectorcraft-cli info FILE
|
||||
//! vectorcraft-cli thumbnail [--size 256] IN OUT
|
||||
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
|
||||
//! vectorcraft-cli perf [--paths 50000] [--deep]
|
||||
//! ```
|
||||
@@ -145,6 +146,15 @@ USAGE:
|
||||
read from its preview and why), title, colour mode, units, artboards, object counts by
|
||||
kind, fonts.
|
||||
|
||||
vectorcraft-cli thumbnail [--size N] IN OUT
|
||||
Open IN (any readable format) and write OUT as a PNG of its first artboard (else the art),
|
||||
N pixels on its longer side (1 to 1024, default 256), with a transparent background. Linux
|
||||
file managers run it for .vectorcraft, .drawcraft and .vctemplate files through
|
||||
share/thumbnailers/ai.storyteller.vectorcraft.thumbnailer, and the Windows thumbnail
|
||||
handler (vectorcraft_thumbnail_handler.dll) runs it for Explorer. It exits with an error
|
||||
and writes nothing when IN is larger than 256 MiB, can't be opened, shows nothing, or takes
|
||||
longer than 20 seconds.
|
||||
|
||||
vectorcraft-cli bench FILE [--size WxH] [--iters N]
|
||||
Render FILE (any readable format) fitted to WxH (default 2880x1800) and print ms per frame
|
||||
(warm), multithreaded and single-threaded.
|
||||
@@ -217,6 +227,7 @@ fn main() -> ExitCode {
|
||||
Some("commands") => commands(),
|
||||
Some("convert") => convert(&args[1..]),
|
||||
Some("info") => info(&args[1..]),
|
||||
Some("thumbnail") => thumbnail(&args[1..]),
|
||||
Some("bench") => bench(&args[1..]),
|
||||
Some("perf") => perf::run(&args[1..]),
|
||||
Some("-h" | "--help" | "help") | None => help(),
|
||||
@@ -521,6 +532,83 @@ fn info(args: &[String]) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Largest file `thumbnail` opens, in bytes on disk.
|
||||
const THUMBNAIL_MAX_FILE: u64 = 256 << 20;
|
||||
/// Largest `--size` of `thumbnail`: the thumbnail standard's largest size, xx-large.
|
||||
const THUMBNAIL_MAX_SIZE: u32 = 1024;
|
||||
/// `--size` when it isn't given: the thumbnail standard's large size.
|
||||
const THUMBNAIL_DEFAULT_SIZE: u32 = 256;
|
||||
/// Longest `thumbnail` runs before it exits without writing OUT.
|
||||
const THUMBNAIL_TIME: std::time::Duration = std::time::Duration::from_secs(20);
|
||||
|
||||
/// `thumbnail`: the PNG a Linux file manager shows for a document, run through the
|
||||
/// `.thumbnailer` entry in `packaging/linux`
|
||||
/// (<https://specifications.freedesktop.org/thumbnail-spec/latest/creation.html>), and the
|
||||
/// picture the Windows thumbnail handler (`apps/vectorcraft-thumbnail-handler`) gives Explorer.
|
||||
fn thumbnail(args: &[String]) -> Result<(), String> {
|
||||
if help_requested(args, &["--size", "-s"]) {
|
||||
return help();
|
||||
}
|
||||
let mut files = vec![];
|
||||
let mut size = THUMBNAIL_DEFAULT_SIZE;
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--size" | "-s" => {
|
||||
size = it
|
||||
.next()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.filter(|n| (1..=THUMBNAIL_MAX_SIZE).contains(n))
|
||||
.ok_or_else(|| format!("--size needs a number of pixels from 1 to {THUMBNAIL_MAX_SIZE}"))?;
|
||||
}
|
||||
other if other.starts_with('-') => return Err(format!("unknown thumbnail option `{other}`")),
|
||||
f => files.push(f),
|
||||
}
|
||||
}
|
||||
let [input, output] = <[&str; 2]>::try_from(files).map_err(|_| "thumbnail needs IN and OUT")?;
|
||||
// The process ends when the time is up, wherever the work is: OUT is written whole or not at all.
|
||||
std::thread::spawn(|| {
|
||||
std::thread::sleep(THUMBNAIL_TIME);
|
||||
eprintln!("vectorcraft-cli: thumbnail: took longer than {} seconds", THUMBNAIL_TIME.as_secs());
|
||||
std::process::exit(1);
|
||||
});
|
||||
let len = std::fs::metadata(input).map_err(|e| format!("{input}: {e}"))?.len();
|
||||
if len > THUMBNAIL_MAX_FILE {
|
||||
return Err(format!("{input}: larger than {} MiB", THUMBNAIL_MAX_FILE >> 20));
|
||||
}
|
||||
// Opened as the app opens it: the fonts it carries, its type measured, its linked files read.
|
||||
let mut h = Headless::new();
|
||||
h.call("app.open", json!({"path": input})).map_err(|e| format!("{input}: {e}"))?;
|
||||
let doc = &h.session.doc().map_err(|e| e.to_string())?.doc;
|
||||
// A picture without a visible pixel is an error, and the file manager keeps the file's icon.
|
||||
let img = vectorcraft_render::encode::first_artboard(doc, size)
|
||||
.filter(|img| img.pixels.as_chunks::<4>().0.iter().any(|px| px[3] != 0))
|
||||
.ok_or_else(|| format!("{input}: the document shows nothing"))?;
|
||||
let png = img.to_png().map_err(|e| format!("{input}: {e}"))?;
|
||||
write_whole(Path::new(output), &png, |tmp, out| std::fs::rename(tmp, out)).map_err(|e| format!("{output}: {e}"))
|
||||
}
|
||||
|
||||
/// Writes `bytes` to a temporary file beside `out` and moves it over `out` with `rename`. When the
|
||||
/// temporary file can't be written or `rename` fails, this returns the error, removes the temporary
|
||||
/// file and leaves `out` unchanged; it never copies into `out`.
|
||||
fn write_whole(out: &Path, bytes: &[u8], rename: impl FnOnce(&Path, &Path) -> std::io::Result<()>) -> std::io::Result<()> {
|
||||
let name = out.file_name().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a file name"))?;
|
||||
let mut tmp_name = std::ffi::OsString::from(".");
|
||||
tmp_name.push(name);
|
||||
tmp_name.push(format!(".{}.tmp", std::process::id()));
|
||||
let tmp = out.with_file_name(tmp_name);
|
||||
// A file already at `tmp` is not this run's: the error leaves it in place.
|
||||
let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;
|
||||
let written = f.write_all(bytes).and_then(|()| vectorcraft_format::sync_file(&f));
|
||||
drop(f);
|
||||
let written = written.and_then(|()| rename(&tmp, out));
|
||||
if written.is_err() {
|
||||
// Best effort: the temporary file is all there is to clean up.
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
written
|
||||
}
|
||||
|
||||
enum Step {
|
||||
Cmd(String, Value),
|
||||
Export(String),
|
||||
@@ -770,3 +858,41 @@ fn bench(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod write_whole_tests {
|
||||
use super::write_whole;
|
||||
|
||||
#[test]
|
||||
fn a_failed_rename_leaves_out_unchanged_and_no_temporary_file() {
|
||||
let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
|
||||
let out = dir.path().join("out.png");
|
||||
std::fs::write(&out, b"old").unwrap_or_else(|e| panic!("{e}"));
|
||||
let refused = write_whole(&out, b"new picture", |_, _| Err(std::io::Error::other("refused")));
|
||||
assert!(refused.is_err());
|
||||
assert_eq!(std::fs::read(&out).unwrap_or_else(|e| panic!("{e}")), b"old");
|
||||
let names: Vec<_> = std::fs::read_dir(dir.path()).unwrap_or_else(|e| panic!("{e}")).flatten().map(|e| e.file_name()).collect();
|
||||
assert_eq!(names, ["out.png"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_already_at_the_temporary_name_is_kept() {
|
||||
let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
|
||||
let out = dir.path().join("out.png");
|
||||
let tmp = dir.path().join(format!(".out.png.{}.tmp", std::process::id()));
|
||||
std::fs::write(&tmp, b"someone else's").unwrap_or_else(|e| panic!("{e}"));
|
||||
assert!(write_whole(&out, b"new picture", |tmp, out| std::fs::rename(tmp, out)).is_err());
|
||||
assert_eq!(std::fs::read(&tmp).unwrap_or_else(|e| panic!("{e}")), b"someone else's");
|
||||
assert!(!out.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_replaces_out() {
|
||||
let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
|
||||
let out = dir.path().join("out.png");
|
||||
std::fs::write(&out, b"old").unwrap_or_else(|e| panic!("{e}"));
|
||||
write_whole(&out, b"new picture", |tmp, out| std::fs::rename(tmp, out)).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(std::fs::read(&out).unwrap_or_else(|e| panic!("{e}")), b"new picture");
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap_or_else(|e| panic!("{e}")).count(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ mod cli;
|
||||
mod fileio;
|
||||
mod mcp_e2e;
|
||||
mod script;
|
||||
mod thumbnail;
|
||||
|
||||
/// Nextest relocates archived binaries; Cargo's compile-time path still names the build runner.
|
||||
fn bin() -> std::path::PathBuf {
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
//! `thumbnail` and the Linux `.thumbnailer` entry that runs it for file managers.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
const THUMBNAILER: &str = include_str!("../../../../packaging/linux/ai.storyteller.vectorcraft.thumbnailer");
|
||||
const MIME: &str = include_str!("../../../../packaging/linux/ai.storyteller.vectorcraft.mime.xml");
|
||||
const PACKAGE: &str = include_str!("../../../../packaging/linux/package.sh");
|
||||
|
||||
/// Returns a new empty folder in the temp folder, removed with everything in it when the guard drops.
|
||||
fn tmp() -> tempfile::TempDir {
|
||||
tempfile::tempdir().unwrap()
|
||||
}
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
Command::new(crate::bin()).args(args).output().unwrap()
|
||||
}
|
||||
|
||||
/// Saves a `width`×`height` document with a rectangle on its artboard as `name` in `dir` and returns its path.
|
||||
fn document(dir: &Path, name: &str, width: u32, height: u32) -> PathBuf {
|
||||
save(dir, name, width, height, &["--cmd", "shape.rectangle", "--params", r#"{"x":10,"y":10,"width":40,"height":20}"#])
|
||||
}
|
||||
|
||||
/// Saves a new `width`×`height` document as `name` in `dir` after the `run` arguments `steps`.
|
||||
fn save(dir: &Path, name: &str, width: u32, height: u32, steps: &[&str]) -> PathBuf {
|
||||
let path = dir.join(name);
|
||||
let size = format!(r#"{{"width":{width},"height":{height}}}"#);
|
||||
let mut args = vec!["run", "--cmd", "file.new", "--params", &size];
|
||||
args.extend_from_slice(steps);
|
||||
args.extend(["--export", path.to_str().unwrap()]);
|
||||
let out = cli(&args);
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
path
|
||||
}
|
||||
|
||||
/// The width and height in a PNG's IHDR chunk, after checking that it is the 8-bit, non-interlaced
|
||||
/// RGBA a thumbnail must be (<https://specifications.freedesktop.org/thumbnail-spec/latest/creation.html>).
|
||||
fn png_size(png: &[u8]) -> (u32, u32) {
|
||||
assert!(png.starts_with(b"\x89PNG\r\n\x1a\n") && &png[12..16] == b"IHDR", "not a PNG");
|
||||
assert_eq!((png[24], png[25], png[28]), (8, 6, 0), "bit depth, color type (RGBA) and interlacing");
|
||||
let be = |b: &[u8]| u32::from_be_bytes([b[0], b[1], b[2], b[3]]);
|
||||
(be(&png[16..20]), be(&png[20..24]))
|
||||
}
|
||||
|
||||
/// The value of `key` in the entry's `[Thumbnailer Entry]` group.
|
||||
fn entry(key: &str) -> &'static str {
|
||||
assert_eq!(THUMBNAILER.lines().next(), Some("[Thumbnailer Entry]"));
|
||||
THUMBNAILER.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix('=')).unwrap_or_else(|| panic!("no {key} key"))
|
||||
}
|
||||
|
||||
/// The file manager's command for the entry: `Exec` split at spaces, `%s` the size, `%i` the
|
||||
/// input path and `%o` the output path (the codes the thumbnail factories expand).
|
||||
fn exec(size: u32, input: &Path, output: &Path) -> Vec<String> {
|
||||
entry("Exec")
|
||||
.split(' ')
|
||||
.map(|arg| match arg {
|
||||
"%s" => size.to_string(),
|
||||
"%i" => input.to_string_lossy().into_owned(),
|
||||
"%o" => output.to_string_lossy().into_owned(),
|
||||
other => {
|
||||
assert!(!other.contains('%'), "a field code the CLI doesn't take: {other}");
|
||||
other.to_string()
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The entry runs the CLI with the size, the document and the PNG to write, as a file manager
|
||||
/// does: with no environment, and the PNG is the first artboard at that size, drawn by the
|
||||
/// renderer that embeds a native file's preview.
|
||||
#[test]
|
||||
fn the_thumbnailer_entry_writes_the_first_artboard() {
|
||||
let dir = tmp();
|
||||
let doc = document(dir.path(), "wide.vectorcraft", 200, 100);
|
||||
let out = dir.path().join("wide.png");
|
||||
let command = exec(128, &doc, &out);
|
||||
assert_eq!(command[0], entry("TryExec"));
|
||||
assert_eq!(command[0], "vectorcraft-cli");
|
||||
let run = Command::new(crate::bin()).args(&command[1..]).env_clear().output().unwrap();
|
||||
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
|
||||
let png = std::fs::read(&out).unwrap();
|
||||
assert_eq!(png_size(&png), (128, 64));
|
||||
let saved = vectorcraft_format::load(&std::fs::read(&doc).unwrap()).unwrap();
|
||||
assert_eq!(Some(png), vectorcraft_render::encode::first_artboard_png(&saved, 128).unwrap(), "the renderer's picture");
|
||||
}
|
||||
|
||||
/// Each type the entry lists is a native document type the app's MIME package declares, and the
|
||||
/// packages install the entry where the thumbnail factories look.
|
||||
#[test]
|
||||
fn the_thumbnailer_entry_covers_the_native_types() {
|
||||
let types: Vec<&str> = entry("MimeType").split(';').filter(|t| !t.is_empty()).collect();
|
||||
assert_eq!(types, ["application/x-vectorcraft", "application/x-vectorcraft-template"]);
|
||||
for t in types {
|
||||
assert!(MIME.contains(&format!("<mime-type type=\"{t}\">")), "the MIME package doesn't declare {t}");
|
||||
}
|
||||
assert!(
|
||||
PACKAGE.contains(r#"install -Dm644 "$HERE/$APP_ID.thumbnailer" "$STAGE/usr/share/thumbnailers/$APP_ID.thumbnailer""#),
|
||||
"package.sh doesn't install the entry"
|
||||
);
|
||||
}
|
||||
|
||||
/// The size defaults to 256 pixels on the longer side, and a tall artboard is fitted by its height.
|
||||
#[test]
|
||||
fn thumbnail_fits_the_longer_side() {
|
||||
let dir = tmp();
|
||||
let doc = document(dir.path(), "tall.vectorcraft", 100, 400);
|
||||
let out = dir.path().join("tall.png");
|
||||
let run = cli(&["thumbnail", doc.to_str().unwrap(), out.to_str().unwrap()]);
|
||||
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
|
||||
assert_eq!(png_size(&std::fs::read(&out).unwrap()), (64, 256));
|
||||
}
|
||||
|
||||
/// A size outside 1 to 1024 pixels, a missing file name and an unknown option are errors, and no
|
||||
/// PNG is written.
|
||||
#[test]
|
||||
fn thumbnail_refuses_bad_arguments() {
|
||||
let dir = tmp();
|
||||
let doc = document(dir.path(), "args.vectorcraft", 100, 100);
|
||||
let out = dir.path().join("args.png");
|
||||
let (d, o) = (doc.to_str().unwrap(), out.to_str().unwrap());
|
||||
for (args, says) in [
|
||||
(vec!["thumbnail", "--size", "0", d, o], "--size"),
|
||||
(vec!["thumbnail", "--size", "1025", d, o], "--size"),
|
||||
(vec!["thumbnail", "--size", "big", d, o], "--size"),
|
||||
(vec!["thumbnail", "--size"], "--size"),
|
||||
(vec!["thumbnail", d], "IN and OUT"),
|
||||
(vec!["thumbnail", "--quality", "9", d, o], "--quality"),
|
||||
] {
|
||||
let run = cli(&args);
|
||||
assert!(!run.status.success(), "{args:?}");
|
||||
assert!(String::from_utf8_lossy(&run.stderr).contains(says), "{args:?}: {}", String::from_utf8_lossy(&run.stderr));
|
||||
assert!(!out.exists(), "{args:?} wrote a PNG");
|
||||
}
|
||||
}
|
||||
|
||||
/// A file that isn't a document, a damaged one, one larger than the CLI opens, a missing one and
|
||||
/// an empty document get an error and no PNG, so the file manager shows the file's icon.
|
||||
#[test]
|
||||
fn thumbnail_writes_nothing_for_files_it_cannot_read() {
|
||||
let dir = tmp();
|
||||
let text = dir.path().join("notes.vectorcraft");
|
||||
std::fs::write(&text, b"not a document").unwrap();
|
||||
let saved = std::fs::read(document(dir.path(), "whole.vectorcraft", 100, 100)).unwrap();
|
||||
let damaged = dir.path().join("damaged.vectorcraft");
|
||||
std::fs::write(&damaged, &saved[..saved.len() / 2]).unwrap();
|
||||
// Sparse where the file system allows it: its size is checked before anything is read.
|
||||
let large = dir.path().join("large.vectorcraft");
|
||||
std::fs::File::create(&large).unwrap().set_len((256 << 20) + 1).unwrap();
|
||||
let missing = dir.path().join("missing.vectorcraft");
|
||||
let empty = save(dir.path(), "empty.vectorcraft", 100, 100, &[]);
|
||||
for (input, says) in
|
||||
[(&text, None), (&damaged, None), (&large, Some("larger than 256 MiB")), (&missing, None), (&empty, Some("the document shows nothing"))]
|
||||
{
|
||||
let out = dir.path().join("unreadable.png");
|
||||
let run = cli(&["thumbnail", input.to_str().unwrap(), out.to_str().unwrap()]);
|
||||
assert!(!run.status.success(), "{input:?}");
|
||||
let err = String::from_utf8_lossy(&run.stderr);
|
||||
assert!(err.contains(input.to_str().unwrap()), "{input:?}: {err}");
|
||||
assert!(says.is_none_or(|s| err.contains(s)), "{input:?}: {err}");
|
||||
assert!(!out.exists(), "{input:?} wrote a PNG");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "vectorcraft-plugin-worker"
|
||||
description = "The web build's plug-in worker: checks plug-in modules being installed and runs filters off the page"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "vectorcraft-plugin-worker"
|
||||
path = "src/main.rs"
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
vectorcraft-plugins = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["DedicatedWorkerGlobalScope", "MessageEvent"] }
|
||||
@@ -0,0 +1,37 @@
|
||||
//! The web build's plug-in worker ([`vectorcraft_plugins::worker`]). Trunk builds it beside the
|
||||
//! app (`data-type="worker"` in `apps/vectorcraft-web/index.html`), and the page starts one for each
|
||||
//! module it checks and each filter it runs, through the loader Trunk writes for it
|
||||
//! (`vectorcraft-plugin-worker_loader.js`). Each message, both ways, is one `Uint8Array`.
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn main() {
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::prelude::Closure;
|
||||
use web_sys::{DedicatedWorkerGlobalScope, MessageEvent};
|
||||
|
||||
let scope: DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
|
||||
let poster = scope.clone();
|
||||
let post = Rc::new(move |msg: Vec<u8>| {
|
||||
let bytes = js_sys::Uint8Array::from(msg.as_slice());
|
||||
// A message that can't be posted leaves the page waiting, and its time budget ends the run.
|
||||
let _ = poster.post_message_with_transfer(&bytes, &js_sys::Array::of1(&bytes.buffer()));
|
||||
});
|
||||
let worker = Rc::new(RefCell::new(vectorcraft_plugins::worker::Worker::new(post)));
|
||||
let handler = Rc::clone(&worker);
|
||||
let on_message = Closure::<dyn FnMut(MessageEvent)>::new(move |e: MessageEvent| {
|
||||
let msg = js_sys::Uint8Array::new(&e.data()).to_vec();
|
||||
handler.borrow_mut().handle(&msg);
|
||||
});
|
||||
scope.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
|
||||
// The handler lives as long as the worker.
|
||||
on_message.forget();
|
||||
worker.borrow().ready();
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn main() {
|
||||
eprintln!("vectorcraft-plugin-worker only runs in the browser, as the web build's plug-in worker");
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
[package]
|
||||
name = "vectorcraft-thumbnail-handler"
|
||||
description = "Windows Explorer thumbnail handler for VectorCraft documents and templates"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
# A COM server DLL that Explorer loads; on other systems it builds the parts the tests check.
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
# PNG decoding of the picture `vectorcraft-cli thumbnail` writes. MIT OR Apache-2.0.
|
||||
[dependencies]
|
||||
png = "0.18"
|
||||
|
||||
# IThumbnailProvider, IInitializeWithStream, the class factory, DIB sections and the registry.
|
||||
# MIT OR Apache-2.0.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows = { version = "0.62", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_LibraryLoader",
|
||||
"Win32_System_Registry",
|
||||
"Win32_System_SystemServices",
|
||||
"Win32_UI_Shell",
|
||||
"Win32_UI_Shell_PropertiesSystem",
|
||||
] }
|
||||
windows-core = "0.62"
|
||||
@@ -0,0 +1,345 @@
|
||||
//! The COM server: the thumbnail provider, its class factory and the functions the DLL exports
|
||||
//! (`DllGetClassObject`, `DllCanUnloadNow`, `DllRegisterServer` and `DllUnregisterServer`).
|
||||
//!
|
||||
//! COM, GDI and the registry are C APIs with no safe binding, hence the scoped `unsafe_code`
|
||||
//! allowance.
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::io::{self, Read};
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr::null_mut;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
|
||||
|
||||
use windows::Win32::Foundation::{
|
||||
CLASS_E_CLASSNOTAVAILABLE, CLASS_E_NOAGGREGATION, E_FAIL, E_POINTER, ERROR_ALREADY_INITIALIZED, ERROR_FILE_NOT_FOUND, HINSTANCE, HMODULE,
|
||||
S_FALSE, S_OK,
|
||||
};
|
||||
use windows::Win32::Graphics::Gdi::{BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateDIBSection, DIB_RGB_COLORS, DeleteObject, HBITMAP};
|
||||
use windows::Win32::System::Com::{CoTaskMemFree, IClassFactory, IClassFactory_Impl, IStream};
|
||||
use windows::Win32::System::LibraryLoader::GetModuleFileNameW;
|
||||
use windows::Win32::System::Registry::{HKEY_CURRENT_USER, REG_SZ, RRF_RT_REG_SZ, RegDeleteTreeW, RegGetValueW, RegSetKeyValueW};
|
||||
use windows::Win32::System::SystemServices::DLL_PROCESS_ATTACH;
|
||||
use windows::Win32::UI::Shell::PropertiesSystem::{IInitializeWithStream, IInitializeWithStream_Impl};
|
||||
use windows::Win32::UI::Shell::{
|
||||
FOLDERID_LocalAppDataLow, IThumbnailProvider, IThumbnailProvider_Impl, KNOWN_FOLDER_FLAG, SHCNE_ASSOCCHANGED, SHCNF_IDLIST, SHChangeNotify,
|
||||
SHGetKnownFolderPath, WTS_ALPHATYPE, WTSAT_ARGB,
|
||||
};
|
||||
use windows::core::{BOOL, Error, GUID, HRESULT, HSTRING, IUnknown, Interface, PCWSTR, Ref, Result, implement};
|
||||
|
||||
use crate::{CLI, CLSID_VALUE, DEADLINE, Document, MAX_FILE, Picture, RegistryValue};
|
||||
|
||||
/// The handler's class id ([`crate::CLSID`]).
|
||||
const CLASS_ID: GUID = GUID::from_u128(CLSID_VALUE);
|
||||
/// The registry key the values of [`crate::registry_values`] go under.
|
||||
const CLASSES: &str = "Software\\Classes";
|
||||
/// The longest DLL path read, in UTF-16 units (Windows' own limit).
|
||||
const MAX_PATH: usize = 32_767;
|
||||
|
||||
/// The DLL's module handle, from `DllMain`.
|
||||
static MODULE: AtomicPtr<c_void> = AtomicPtr::new(null_mut());
|
||||
/// Providers and class factories alive plus `LockServer` locks held; the DLL can be unloaded at 0.
|
||||
static LIVE: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// The thumbnail provider: Explorer hands it the file's stream, then asks for the picture.
|
||||
#[implement(IInitializeWithStream, IThumbnailProvider)]
|
||||
struct Provider {
|
||||
document: Mutex<Option<Document<StreamReader>>>,
|
||||
}
|
||||
|
||||
impl Provider {
|
||||
fn new() -> Self {
|
||||
LIVE.fetch_add(1, Ordering::SeqCst);
|
||||
Self { document: Mutex::new(None) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Provider {
|
||||
fn drop(&mut self) {
|
||||
LIVE.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl IInitializeWithStream_Impl for Provider_Impl {
|
||||
fn Initialize(&self, stream: Ref<IStream>, _mode: u32) -> Result<()> {
|
||||
let stream = stream.ok()?.clone();
|
||||
let mut slot = self.document.lock().map_err(|_| Error::from(E_FAIL))?;
|
||||
if slot.is_some() {
|
||||
return Err(ERROR_ALREADY_INITIALIZED.to_hresult().into());
|
||||
}
|
||||
*slot = Some(Document::new(StreamReader(stream)));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl IThumbnailProvider_Impl for Provider_Impl {
|
||||
fn GetThumbnail(&self, cx: u32, bitmap: *mut HBITMAP, alpha: *mut WTS_ALPHATYPE) -> Result<()> {
|
||||
if bitmap.is_null() || alpha.is_null() {
|
||||
return Err(E_POINTER.into());
|
||||
}
|
||||
let mut slot = self.document.lock().map_err(|_| Error::from(E_FAIL))?;
|
||||
let document = slot.as_mut().ok_or_else(|| Error::new(E_FAIL, "not initialized"))?;
|
||||
// A panic must not unwind into Explorer's process.
|
||||
let picture = match std::panic::catch_unwind(AssertUnwindSafe(|| thumbnail(document, cx))) {
|
||||
Ok(Ok(picture)) => picture,
|
||||
Ok(Err(e)) => return Err(Error::new(E_FAIL, e)),
|
||||
Err(_) => return Err(Error::new(E_FAIL, "the thumbnail could not be made")),
|
||||
};
|
||||
drop(slot);
|
||||
let made = dib_section(&picture)?;
|
||||
// SAFETY: both pointers were checked for null above, and Explorer passes them writable.
|
||||
unsafe {
|
||||
*bitmap = made;
|
||||
*alpha = WTSAT_ARGB;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The class factory COM asks for the provider.
|
||||
#[implement(IClassFactory)]
|
||||
struct Factory;
|
||||
|
||||
impl Factory {
|
||||
fn new() -> Self {
|
||||
LIVE.fetch_add(1, Ordering::SeqCst);
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Factory {
|
||||
fn drop(&mut self) {
|
||||
LIVE.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl IClassFactory_Impl for Factory_Impl {
|
||||
fn CreateInstance(&self, outer: Ref<IUnknown>, iid: *const GUID, object: *mut *mut c_void) -> Result<()> {
|
||||
if iid.is_null() || object.is_null() {
|
||||
return Err(E_POINTER.into());
|
||||
}
|
||||
// SAFETY: `object` was checked for null above.
|
||||
unsafe { *object = null_mut() };
|
||||
if !outer.is_null() {
|
||||
return Err(CLASS_E_NOAGGREGATION.into());
|
||||
}
|
||||
let provider: IUnknown = Provider::new().into();
|
||||
// SAFETY: both pointers were checked for null above.
|
||||
unsafe { provider.query(iid, object) }.ok()
|
||||
}
|
||||
|
||||
fn LockServer(&self, lock: BOOL) -> Result<()> {
|
||||
if lock.as_bool() {
|
||||
LIVE.fetch_add(1, Ordering::SeqCst);
|
||||
} else {
|
||||
LIVE.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// `IStream` as [`Read`].
|
||||
struct StreamReader(IStream);
|
||||
|
||||
impl Read for StreamReader {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
let len = u32::try_from(buf.len()).unwrap_or(u32::MAX);
|
||||
let mut read = 0u32;
|
||||
// SAFETY: `buf` holds at least `len` writable bytes, and `read` outlives the call.
|
||||
unsafe { self.0.Read(buf.as_mut_ptr().cast(), len, Some(&mut read)) }.ok().map_err(io::Error::other)?;
|
||||
usize::try_from(read).map_err(io::Error::other)
|
||||
}
|
||||
}
|
||||
|
||||
/// The picture of `document`, at most `cx` pixels on its longer side.
|
||||
fn thumbnail(document: &mut Document<StreamReader>, cx: u32) -> std::result::Result<Picture, String> {
|
||||
let size = crate::request_size(cx).ok_or("a thumbnail of 0 pixels")?;
|
||||
let bytes = document.bytes(MAX_FILE).map_err(|e| e.to_string())?;
|
||||
let dll = module_path()?;
|
||||
let cli = PathBuf::from(dll).parent().ok_or("the DLL's folder is unknown")?.join(CLI);
|
||||
let png = crate::render(&cli, bytes, size, &staging_folder(), DEADLINE)?;
|
||||
crate::picture(&png, size)
|
||||
}
|
||||
|
||||
/// Creates the thumbnail staging folder in LocalLow, falling back to the temp folder.
|
||||
fn staging_folder() -> PathBuf {
|
||||
// SAFETY: the folder ID is valid, and no token means the current user.
|
||||
let Ok(folder) = (unsafe { SHGetKnownFolderPath(&FOLDERID_LocalAppDataLow, KNOWN_FOLDER_FLAG(0), None) }) else {
|
||||
return std::env::temp_dir();
|
||||
};
|
||||
// SAFETY: the call returned a NUL-terminated path allocated by COM; copy it before freeing it.
|
||||
let path = unsafe {
|
||||
let path = PathBuf::from(std::ffi::OsString::from_wide(folder.as_wide()));
|
||||
CoTaskMemFree(Some(folder.0.cast()));
|
||||
path
|
||||
};
|
||||
let path = path.join("VectorCraft").join("Thumbnails");
|
||||
if std::fs::create_dir_all(&path).is_ok() { path } else { std::env::temp_dir() }
|
||||
}
|
||||
|
||||
/// `picture` as a top-down 32-bit DIB section.
|
||||
fn dib_section(picture: &Picture) -> Result<HBITMAP> {
|
||||
let bad = || Error::new(E_FAIL, "the picture's size is wrong");
|
||||
let width = i32::try_from(picture.width).map_err(|_| bad())?;
|
||||
let height = i32::try_from(picture.height).map_err(|_| bad())?;
|
||||
let len = usize::try_from(u64::from(picture.width) * u64::from(picture.height) * 4).map_err(|_| bad())?;
|
||||
if picture.bgra.len() != len {
|
||||
return Err(bad());
|
||||
}
|
||||
let info = BITMAPINFO {
|
||||
bmiHeader: BITMAPINFOHEADER {
|
||||
biSize: size_of::<BITMAPINFOHEADER>() as u32,
|
||||
biWidth: width,
|
||||
// A negative height: the rows go from top to bottom.
|
||||
biHeight: -height,
|
||||
biPlanes: 1,
|
||||
biBitCount: 32,
|
||||
biCompression: BI_RGB.0,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let mut bits: *mut c_void = null_mut();
|
||||
// SAFETY: `info` describes a 32-bit picture and `bits` outlives the call.
|
||||
let bitmap = unsafe { CreateDIBSection(None, &info, DIB_RGB_COLORS, &mut bits, None, 0) }?;
|
||||
if bits.is_null() {
|
||||
// SAFETY: `bitmap` was just made and nothing else holds it.
|
||||
unsafe {
|
||||
let _ = DeleteObject(bitmap.into());
|
||||
}
|
||||
return Err(Error::new(E_FAIL, "the bitmap has no pixels"));
|
||||
}
|
||||
// SAFETY: the DIB section holds `width * height * 4` bytes, `len`, and `bgra` holds `len` bytes.
|
||||
unsafe { std::ptr::copy_nonoverlapping(picture.bgra.as_ptr(), bits.cast::<u8>(), len) };
|
||||
Ok(bitmap)
|
||||
}
|
||||
|
||||
/// The path of this DLL.
|
||||
fn module_path() -> std::result::Result<String, String> {
|
||||
let module = HMODULE(MODULE.load(Ordering::SeqCst));
|
||||
if module.0.is_null() {
|
||||
return Err("the DLL's module handle is unknown".into());
|
||||
}
|
||||
let mut buf = vec![0u16; MAX_PATH];
|
||||
// SAFETY: `module` is this DLL's handle, which stays valid while the DLL is loaded.
|
||||
let len = unsafe { GetModuleFileNameW(Some(module), &mut buf) };
|
||||
let path = usize::try_from(len).ok().filter(|&n| n > 0 && n < buf.len()).and_then(|n| buf.get(..n)).ok_or("the DLL's path is unknown")?;
|
||||
String::from_utf16(path).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Writes `value` under `Software\Classes` of the current user.
|
||||
fn set(value: &RegistryValue) -> Result<()> {
|
||||
let key = HSTRING::from(format!("{CLASSES}\\{}", value.key));
|
||||
let name = value.name.map(HSTRING::from);
|
||||
let name = name.as_ref().map_or(PCWSTR::null(), |n| PCWSTR(n.as_ptr()));
|
||||
let data: Vec<u16> = value.data.encode_utf16().chain([0]).collect();
|
||||
let bytes = u32::try_from(data.len() * 2).map_err(|_| Error::from(E_FAIL))?;
|
||||
// SAFETY: `data` holds `bytes` bytes of a NUL-terminated string, and the names outlive the call.
|
||||
unsafe { RegSetKeyValueW(HKEY_CURRENT_USER, &key, name, REG_SZ.0, Some(data.as_ptr().cast()), bytes) }.ok()
|
||||
}
|
||||
|
||||
/// The default value of `key` under `Software\Classes` of the current user, when it is a string.
|
||||
fn default_value(key: &str) -> Option<String> {
|
||||
let key = HSTRING::from(format!("{CLASSES}\\{key}"));
|
||||
let mut buf = [0u16; 128];
|
||||
let mut bytes = u32::try_from(buf.len() * 2).ok()?;
|
||||
// SAFETY: `buf` holds `bytes` writable bytes, and `bytes` outlives the call.
|
||||
unsafe { RegGetValueW(HKEY_CURRENT_USER, &key, PCWSTR::null(), RRF_RT_REG_SZ, None, Some(buf.as_mut_ptr().cast()), Some(&mut bytes)) }
|
||||
.ok()
|
||||
.ok()?;
|
||||
let units = buf.get(..usize::try_from(bytes / 2).ok()?)?;
|
||||
String::from_utf16(units).ok().map(|s| s.trim_end_matches('\0').to_owned())
|
||||
}
|
||||
|
||||
/// Removes `key` under `Software\Classes` of the current user with its subkeys; a key that isn't
|
||||
/// there is no error.
|
||||
fn remove(key: &str) -> Result<()> {
|
||||
let key = HSTRING::from(format!("{CLASSES}\\{key}"));
|
||||
// SAFETY: `key` outlives the call.
|
||||
match unsafe { RegDeleteTreeW(HKEY_CURRENT_USER, &key) } {
|
||||
ERROR_FILE_NOT_FOUND => Ok(()),
|
||||
e => e.ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Tells Explorer that file associations changed, so it asks for thumbnails again.
|
||||
fn associations_changed() {
|
||||
// SAFETY: SHCNE_ASSOCCHANGED takes no items.
|
||||
unsafe { SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, None, None) };
|
||||
}
|
||||
|
||||
/// Registers the handler for the current user ([`crate::registry_values`]).
|
||||
fn register() -> Result<()> {
|
||||
let dll = module_path().map_err(|e| Error::new(E_FAIL, e))?;
|
||||
crate::registry_values(&dll).iter().try_for_each(set)
|
||||
}
|
||||
|
||||
/// Removes the class key and each extension's thumbnail handler key that names this handler.
|
||||
fn unregister() -> Result<()> {
|
||||
for ext in crate::EXTENSIONS {
|
||||
let key = crate::shell_ex_key(ext);
|
||||
if default_value(&key).is_some_and(|v| crate::names_this_handler(&v)) {
|
||||
remove(&key)?;
|
||||
}
|
||||
}
|
||||
remove(&crate::class_key())
|
||||
}
|
||||
|
||||
/// Keeps the DLL's module handle for [`module_path`].
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn DllMain(module: HINSTANCE, reason: u32, _reserved: *mut c_void) -> BOOL {
|
||||
if reason == DLL_PROCESS_ATTACH {
|
||||
MODULE.store(module.0, Ordering::SeqCst);
|
||||
}
|
||||
true.into()
|
||||
}
|
||||
|
||||
/// COM's request for the class factory of class `class`.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `class` and `iid` point to GUIDs and `object` to writable memory for an interface pointer, as
|
||||
/// COM passes them.
|
||||
#[unsafe(no_mangle)]
|
||||
unsafe extern "system" fn DllGetClassObject(class: *const GUID, iid: *const GUID, object: *mut *mut c_void) -> HRESULT {
|
||||
if class.is_null() || iid.is_null() || object.is_null() {
|
||||
return E_POINTER;
|
||||
}
|
||||
// SAFETY: the caller passes valid pointers, checked for null above.
|
||||
unsafe {
|
||||
*object = null_mut();
|
||||
if *class != CLASS_ID {
|
||||
return CLASS_E_CLASSNOTAVAILABLE;
|
||||
}
|
||||
let factory: IClassFactory = Factory::new().into();
|
||||
factory.query(iid, object)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether COM may unload the DLL: no provider or class factory is alive and no lock is held.
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn DllCanUnloadNow() -> HRESULT {
|
||||
if LIVE.load(Ordering::SeqCst) == 0 { S_OK } else { S_FALSE }
|
||||
}
|
||||
|
||||
/// `regsvr32`: registers the handler for the current user.
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn DllRegisterServer() -> HRESULT {
|
||||
let result = register();
|
||||
if result.is_err() {
|
||||
let _ = unregister();
|
||||
}
|
||||
associations_changed();
|
||||
result.map_or_else(|e| e.code(), |()| S_OK)
|
||||
}
|
||||
|
||||
/// `regsvr32 /u`: removes the current user's registration.
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn DllUnregisterServer() -> HRESULT {
|
||||
let result = unregister();
|
||||
associations_changed();
|
||||
result.map_or_else(|e| e.code(), |()| S_OK)
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
//! Windows: the thumbnail handler that Explorer and the file dialogs run for `.vectorcraft`,
|
||||
//! `.drawcraft` and `.vctemplate` files. It is a COM server DLL whose class implements
|
||||
//! `IThumbnailProvider` and `IInitializeWithStream`
|
||||
//! (<https://learn.microsoft.com/windows/win32/shell/thumbnail-providers>,
|
||||
//! <https://learn.microsoft.com/windows/win32/api/thumbcache/nn-thumbcache-ithumbnailprovider>).
|
||||
//!
|
||||
//! Explorer gives the handler the file's bytes as a stream. The handler writes them to a new file
|
||||
//! in `%USERPROFILE%\AppData\LocalLow\VectorCraft\Thumbnails` (falling back to the temp folder),
|
||||
//! runs `vectorcraft-cli thumbnail --size N IN OUT` from the DLL's folder on
|
||||
//! it, and returns the PNG that command writes (the first artboard, else the art, drawn by
|
||||
//! `vectorcraft_render::encode::first_artboard`) as a 32-bit DIB section with alpha. A file larger
|
||||
//! than 256 MiB, a document that can't be opened or shows nothing, and a `vectorcraft-cli` run
|
||||
//! longer than [`DEADLINE`] give Explorer an error, and Explorer shows the file's icon. Rendering
|
||||
//! runs in the `vectorcraft-cli` process, so a file that makes it fail or hang ends that process.
|
||||
//! The handler is not given the file's path (`IInitializeWithStream` is the only initialization
|
||||
//! an isolated handler gets), so a linked image found only relative to the document's folder
|
||||
//! shows the preview saved with it.
|
||||
//!
|
||||
//! `regsvr32 vectorcraft_thumbnail_handler.dll` registers the handler for the current user, and
|
||||
//! `regsvr32 /u` removes it ([`registry_values`]). The COM parts build on Windows only; the parts
|
||||
//! in this file build everywhere and their tests run on every system.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::fs::File;
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[cfg(windows)]
|
||||
mod com;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// The handler's class id: the key under `CLSID`, and the value of each extension's `ShellEx` key.
|
||||
pub const CLSID: &str = "{1971F5DA-D761-4655-AB25-6B3825BD1748}";
|
||||
/// [`CLSID`] as a number, the form COM compares.
|
||||
pub const CLSID_VALUE: u128 = 0x1971_f5da_d761_4655_ab25_6b38_25bd_1748;
|
||||
/// The `ShellEx` subkey that names an extension's thumbnail handler, the interface id of
|
||||
/// `IThumbnailProvider` (<https://learn.microsoft.com/windows/win32/shell/thumbnail-providers>).
|
||||
pub const THUMBNAIL_SHELL_EX: &str = "{e357fccd-a995-4576-b01f-234630154e96}";
|
||||
/// The extensions the handler is registered for: documents, documents under their former
|
||||
/// extension, and templates (the globs of `packaging/linux/ai.storyteller.vectorcraft.mime.xml`).
|
||||
pub const EXTENSIONS: &[&str] = &[".vectorcraft", ".drawcraft", ".vctemplate"];
|
||||
/// The description in the class key.
|
||||
pub const DESCRIPTION: &str = "VectorCraft document thumbnail handler";
|
||||
/// The largest file the handler reads, in bytes, the limit `vectorcraft-cli thumbnail` applies.
|
||||
pub const MAX_FILE: u64 = 256 << 20;
|
||||
/// The largest `--size` `vectorcraft-cli thumbnail` takes. Explorer asks for sizes up to 1024.
|
||||
pub const MAX_SIDE: u32 = 1024;
|
||||
/// The largest PNG the handler reads back, in bytes: an uncompressed 1024 by 1024 RGBA picture
|
||||
/// with room for the chunks around it.
|
||||
pub const MAX_PNG: u64 = 8 << 20;
|
||||
/// How long the handler waits for `vectorcraft-cli` before it ends the process: the command's
|
||||
/// own 20-second limit and 5 seconds to start.
|
||||
pub const DEADLINE: Duration = Duration::from_secs(25);
|
||||
/// How often the handler checks whether `vectorcraft-cli` has exited.
|
||||
const POLL: Duration = Duration::from_millis(10);
|
||||
/// The program the handler runs, in the DLL's folder.
|
||||
pub const CLI: &str = "vectorcraft-cli.exe";
|
||||
|
||||
/// A picture in the layout Explorer takes: rows from top to bottom, 4 bytes per pixel in blue,
|
||||
/// green, red and alpha order, with the colors premultiplied by alpha.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Picture {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub bgra: Vec<u8>,
|
||||
}
|
||||
|
||||
/// One registry value the handler writes, under `Software\Classes` of the current user.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RegistryValue {
|
||||
/// The key, relative to `Software\Classes`.
|
||||
pub key: String,
|
||||
/// The value's name; `None` is the key's default value.
|
||||
pub name: Option<&'static str>,
|
||||
/// The string the value holds.
|
||||
pub data: String,
|
||||
}
|
||||
|
||||
/// The class key, relative to `Software\Classes`.
|
||||
pub fn class_key() -> String {
|
||||
format!("CLSID\\{CLSID}")
|
||||
}
|
||||
|
||||
/// The key that names `extension`'s thumbnail handler, relative to `Software\Classes`.
|
||||
pub fn shell_ex_key(extension: &str) -> String {
|
||||
format!("{extension}\\ShellEx\\{THUMBNAIL_SHELL_EX}")
|
||||
}
|
||||
|
||||
/// The values that register the handler in the DLL at path `dll`: the class with its server and
|
||||
/// threading model, and the class as the thumbnail handler of each of [`EXTENSIONS`], as
|
||||
/// <https://learn.microsoft.com/windows/win32/shell/thumbnail-providers> describes.
|
||||
pub fn registry_values(dll: &str) -> Vec<RegistryValue> {
|
||||
let class = class_key();
|
||||
let server = format!("{class}\\InprocServer32");
|
||||
let mut values = vec![
|
||||
RegistryValue { key: class, name: None, data: DESCRIPTION.into() },
|
||||
RegistryValue { key: server.clone(), name: None, data: dll.into() },
|
||||
RegistryValue { key: server, name: Some("ThreadingModel"), data: "Apartment".into() },
|
||||
];
|
||||
values.extend(EXTENSIONS.iter().map(|ext| RegistryValue { key: shell_ex_key(ext), name: None, data: CLSID.into() }));
|
||||
values
|
||||
}
|
||||
|
||||
/// Whether `value`, the default value of an extension's `ShellEx` key, names this handler: class
|
||||
/// ids are compared without regard to letter case. `regsvr32 /u` removes only such keys.
|
||||
pub fn names_this_handler(value: &str) -> bool {
|
||||
value.trim().eq_ignore_ascii_case(CLSID)
|
||||
}
|
||||
|
||||
/// Reads all of `r` when it holds at most `max` bytes, else returns an error.
|
||||
pub fn read_bounded(r: impl Read, max: u64) -> io::Result<Vec<u8>> {
|
||||
let mut bytes = Vec::new();
|
||||
r.take(max.saturating_add(1)).read_to_end(&mut bytes)?;
|
||||
if u64::try_from(bytes.len()).map_or(true, |n| n > max) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, format!("larger than {max} bytes")));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// The document Explorer passed as a stream. Its bytes are read on the first request and kept, so
|
||||
/// a later request on the same handler, at another size for example, gets the same document.
|
||||
pub struct Document<R> {
|
||||
stream: Option<R>,
|
||||
bytes: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl<R: Read> Document<R> {
|
||||
pub fn new(stream: R) -> Self {
|
||||
Self { stream: Some(stream), bytes: None }
|
||||
}
|
||||
|
||||
/// The document's bytes, read from the stream when it holds at most `max` bytes. When the
|
||||
/// first read fails, this call and every later one return an error.
|
||||
pub fn bytes(&mut self, max: u64) -> io::Result<&[u8]> {
|
||||
if let Some(stream) = self.stream.take() {
|
||||
self.bytes = Some(read_bounded(stream, max)?);
|
||||
}
|
||||
self.bytes.as_deref().ok_or_else(|| io::Error::other("the document's stream could not be read"))
|
||||
}
|
||||
}
|
||||
|
||||
/// The `--size` for Explorer's request of a picture `cx` pixels on its longer side: `cx`, at most
|
||||
/// [`MAX_SIDE`]; `None` for 0.
|
||||
pub fn request_size(cx: u32) -> Option<u32> {
|
||||
(cx > 0).then(|| cx.min(MAX_SIDE))
|
||||
}
|
||||
|
||||
/// The arguments of `vectorcraft-cli` that write the thumbnail of `input` to `output`, `size`
|
||||
/// pixels on its longer side.
|
||||
pub fn arguments(size: u32, input: &Path, output: &Path) -> Vec<OsString> {
|
||||
vec!["thumbnail".into(), "--size".into(), size.to_string().into(), input.into(), output.into()]
|
||||
}
|
||||
|
||||
/// A file the handler made in the temp folder, removed when dropped.
|
||||
struct TempFile(PathBuf);
|
||||
|
||||
impl Drop for TempFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `bytes` to a new file `vectorcraft-thumbnail-<pid>-<n>.vectorcraft` in `dir`, with the
|
||||
/// first `n` whose name no file has.
|
||||
fn write_input(dir: &Path, bytes: &[u8]) -> io::Result<TempFile> {
|
||||
use std::io::Write;
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
loop {
|
||||
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let path = dir.join(format!("vectorcraft-thumbnail-{}-{n}.vectorcraft", std::process::id()));
|
||||
match File::options().write(true).create_new(true).open(&path) {
|
||||
Ok(mut file) => {
|
||||
let temp = TempFile(path);
|
||||
file.write_all(bytes)?;
|
||||
return Ok(temp);
|
||||
}
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `cli thumbnail --size SIZE IN OUT` with `bytes` written to a new file IN in `dir` and
|
||||
/// returns the PNG it writes to OUT, IN's name with `.png`. The process is ended when it runs
|
||||
/// longer than `deadline`. IN and OUT are removed before this returns.
|
||||
pub fn render(cli: &Path, bytes: &[u8], size: u32, dir: &Path, deadline: Duration) -> Result<Vec<u8>, String> {
|
||||
let input = write_input(dir, bytes).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let output = TempFile(input.0.with_extension("png"));
|
||||
let mut command = Command::new(cli);
|
||||
command.args(arguments(size, &input.0, &output.0)).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
|
||||
no_console_window(&mut command);
|
||||
let mut child = command.spawn().map_err(|e| format!("{}: {e}", cli.display()))?;
|
||||
let end = Instant::now() + deadline;
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait().map_err(|e| format!("{}: {e}", cli.display()))? {
|
||||
break status;
|
||||
}
|
||||
if Instant::now() >= end {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(format!("{} ran longer than {} seconds", cli.display(), deadline.as_secs()));
|
||||
}
|
||||
std::thread::sleep(POLL);
|
||||
};
|
||||
if !status.success() {
|
||||
return Err(format!("{} exited with {status}", cli.display()));
|
||||
}
|
||||
let png = File::open(&output.0).and_then(|f| read_bounded(f, MAX_PNG)).map_err(|e| format!("{}: {e}", output.0.display()))?;
|
||||
Ok(png)
|
||||
}
|
||||
|
||||
/// Starts `command` without a console window (`CREATE_NO_WINDOW`,
|
||||
/// <https://learn.microsoft.com/windows/win32/procthread/process-creation-flags>).
|
||||
#[cfg(windows)]
|
||||
fn no_console_window(command: &mut Command) {
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn no_console_window(_: &mut Command) {}
|
||||
|
||||
/// The 8-bit RGBA PNG `png` (what `vectorcraft-cli thumbnail` writes, with straight alpha) as a
|
||||
/// [`Picture`]. An error
|
||||
/// when it can't be decoded, has another pixel format, or is empty or larger than `max_side`
|
||||
/// pixels on a side.
|
||||
pub fn picture(png: &[u8], max_side: u32) -> Result<Picture, String> {
|
||||
let mut reader = png::Decoder::new(io::Cursor::new(png)).read_info().map_err(|e| e.to_string())?;
|
||||
let (width, height) = (reader.info().width, reader.info().height);
|
||||
if width == 0 || height == 0 || width > max_side || height > max_side {
|
||||
return Err(format!("a {width} by {height} picture, not 1 to {max_side} pixels on each side"));
|
||||
}
|
||||
let mut buf = vec![0; reader.output_buffer_size().ok_or("the picture is too large")?];
|
||||
let frame = reader.next_frame(&mut buf).map_err(|e| e.to_string())?;
|
||||
if (frame.color_type, frame.bit_depth) != (png::ColorType::Rgba, png::BitDepth::Eight) {
|
||||
return Err(format!("a {:?} {:?} picture, not 8-bit RGBA", frame.bit_depth, frame.color_type));
|
||||
}
|
||||
let rgba = buf.get(..frame.buffer_size()).ok_or("the picture is cut short")?;
|
||||
let bgra = rgba.as_chunks::<4>().0.iter().flat_map(|&[r, g, b, a]| [premultiply(b, a), premultiply(g, a), premultiply(r, a), a]).collect();
|
||||
Ok(Picture { width, height, bgra })
|
||||
}
|
||||
|
||||
/// Color `c` multiplied by alpha `a`, both 0 to 255, rounded to the nearest value.
|
||||
fn premultiply(c: u8, a: u8) -> u8 {
|
||||
u8::try_from((u16::from(c) * u16::from(a) + 127) / 255).unwrap_or(u8::MAX)
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
use std::path::Path;
|
||||
|
||||
use super::*;
|
||||
|
||||
const MIME: &str = include_str!("../../../packaging/linux/ai.storyteller.vectorcraft.mime.xml");
|
||||
|
||||
/// A PNG of `width`×`height` pixels with `data` as its samples.
|
||||
fn png_of(width: u32, height: u32, color: png::ColorType, data: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut encoder = png::Encoder::new(&mut out, width, height);
|
||||
encoder.set_color(color);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
let mut writer = encoder.write_header().unwrap();
|
||||
writer.write_image_data(data).unwrap();
|
||||
writer.finish().unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
/// An empty folder `vectorcraft-thumbnail-handler-<pid>-<name>` in the temp folder.
|
||||
#[cfg(unix)]
|
||||
fn folder(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-thumbnail-handler-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// The names of the files in `dir`.
|
||||
#[cfg(unix)]
|
||||
fn files_in(dir: &Path) -> Vec<String> {
|
||||
let mut names: Vec<String> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_class_id_string_and_number_are_the_same_id() {
|
||||
let hex = format!("{CLSID_VALUE:032X}");
|
||||
let grouped = format!("{{{}-{}-{}-{}-{}}}", &hex[..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..]);
|
||||
assert_eq!(grouped, CLSID);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registration_names_the_dll_and_the_handler_of_every_extension() {
|
||||
let values = registry_values("C:\\Program Files\\VectorCraft\\vectorcraft_thumbnail_handler.dll");
|
||||
let class = format!("CLSID\\{CLSID}");
|
||||
let server = format!("{class}\\InprocServer32");
|
||||
let want = vec![
|
||||
RegistryValue { key: class, name: None, data: DESCRIPTION.into() },
|
||||
RegistryValue { key: server.clone(), name: None, data: "C:\\Program Files\\VectorCraft\\vectorcraft_thumbnail_handler.dll".into() },
|
||||
RegistryValue { key: server, name: Some("ThreadingModel"), data: "Apartment".into() },
|
||||
RegistryValue { key: format!(".vectorcraft\\ShellEx\\{THUMBNAIL_SHELL_EX}"), name: None, data: CLSID.into() },
|
||||
RegistryValue { key: format!(".drawcraft\\ShellEx\\{THUMBNAIL_SHELL_EX}"), name: None, data: CLSID.into() },
|
||||
RegistryValue { key: format!(".vctemplate\\ShellEx\\{THUMBNAIL_SHELL_EX}"), name: None, data: CLSID.into() },
|
||||
];
|
||||
assert_eq!(values, want);
|
||||
assert_eq!(THUMBNAIL_SHELL_EX.to_ascii_uppercase(), "{E357FCCD-A995-4576-B01F-234630154E96}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_extensions_are_the_globs_of_the_document_and_template_types() {
|
||||
let mut globs = Vec::new();
|
||||
let mut in_type = false;
|
||||
for line in MIME.lines().map(str::trim) {
|
||||
if let Some(rest) = line.strip_prefix("<mime-type type=\"") {
|
||||
in_type = matches!(rest.split('"').next(), Some("application/x-vectorcraft" | "application/x-vectorcraft-template"));
|
||||
} else if in_type && let Some(rest) = line.strip_prefix("<glob pattern=\"*") {
|
||||
globs.push(rest.split('"').next().unwrap().to_owned());
|
||||
}
|
||||
}
|
||||
assert_eq!(globs, EXTENSIONS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_this_class_id_names_this_handler() {
|
||||
assert!(names_this_handler(CLSID));
|
||||
assert!(names_this_handler(&CLSID.to_ascii_lowercase()));
|
||||
assert!(!names_this_handler("{C7657C4A-9F68-40FA-A4DF-96BC08EB3551}"));
|
||||
assert!(!names_this_handler(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_larger_than_the_limit_is_refused() {
|
||||
assert_eq!(read_bounded(&[7u8; 10][..], 10).unwrap(), vec![7; 10]);
|
||||
assert_eq!(read_bounded(&[][..], 10).unwrap(), Vec::<u8>::new());
|
||||
assert_eq!(read_bounded(&[7u8; 11][..], 10).unwrap_err().kind(), io::ErrorKind::InvalidData);
|
||||
assert!(read_bounded(&[7u8; 11][..], u64::MAX).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_request_gets_the_same_document() {
|
||||
let mut document = Document::new(io::Cursor::new(vec![1u8, 2, 3]));
|
||||
assert_eq!(document.bytes(10).unwrap(), [1, 2, 3]);
|
||||
assert_eq!(document.bytes(10).unwrap(), [1, 2, 3]);
|
||||
|
||||
let mut large = Document::new(&[7u8; 11][..]);
|
||||
assert_eq!(large.bytes(10).unwrap_err().kind(), io::ErrorKind::InvalidData);
|
||||
assert!(large.bytes(10).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_size_asked_of_the_command_is_at_most_its_limit() {
|
||||
assert_eq!(request_size(0), None);
|
||||
assert_eq!(request_size(1), Some(1));
|
||||
assert_eq!(request_size(256), Some(256));
|
||||
assert_eq!(request_size(MAX_SIDE), Some(MAX_SIDE));
|
||||
assert_eq!(request_size(2048), Some(MAX_SIDE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_line_is_thumbnail_size_input_output() {
|
||||
let args = arguments(96, Path::new("in.vectorcraft"), Path::new("out.png"));
|
||||
assert_eq!(args, ["thumbnail", "--size", "96", "in.vectorcraft", "out.png"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_rgba_png_becomes_top_down_premultiplied_bgra() {
|
||||
// Two rows: opaque red and half-transparent blue, then 20% white and a clear white pixel.
|
||||
let rgba = [255, 0, 0, 255, 0, 0, 255, 128, 255, 255, 255, 51, 255, 255, 255, 0];
|
||||
let picture = picture(&png_of(2, 2, png::ColorType::Rgba, &rgba), 2).unwrap();
|
||||
assert_eq!((picture.width, picture.height), (2, 2));
|
||||
assert_eq!(picture.bgra, [0, 0, 255, 255, 128, 0, 0, 128, 51, 51, 51, 51, 0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_png_that_is_not_an_rgba_thumbnail_is_refused() {
|
||||
assert!(picture(&png_of(1, 1, png::ColorType::Rgb, &[1, 2, 3]), 8).is_err());
|
||||
assert!(picture(&png_of(3, 1, png::ColorType::Rgba, &[0; 12]), 2).is_err(), "wider than asked");
|
||||
assert!(picture(&png_of(1, 3, png::ColorType::Rgba, &[0; 12]), 2).is_err(), "taller than asked");
|
||||
assert!(picture(b"not a picture", 8).is_err());
|
||||
let png = png_of(2, 2, png::ColorType::Rgba, &[9; 16]);
|
||||
assert!(picture(&png[..png.len() - 20], 8).is_err(), "cut short");
|
||||
}
|
||||
|
||||
/// `render` runs the program with the thumbnail arguments, returns what it writes to OUT, gives
|
||||
/// an error for a failed or overlong run, and leaves no file behind. The stand-ins are shell
|
||||
/// scripts, all written before the first one runs.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn render_runs_the_command_and_removes_its_files() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::time::Duration;
|
||||
let dir = folder("render");
|
||||
let temp = dir.join("temp");
|
||||
std::fs::create_dir(&temp).unwrap();
|
||||
let png = png_of(1, 1, png::ColorType::Rgba, &[1, 2, 3, 4]);
|
||||
std::fs::write(dir.join("picture.png"), &png).unwrap();
|
||||
std::fs::write(dir.join("document"), b"document bytes").unwrap();
|
||||
let script = |name: &str, body: &str| {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
path
|
||||
};
|
||||
let d = dir.display();
|
||||
let writes = script(
|
||||
"writes",
|
||||
&format!(
|
||||
"[ \"$1 $2 $3\" = \"thumbnail --size 64\" ] || exit 4\ncase \"$4\" in *.vectorcraft) ;; *) exit 5 ;; esac\n\
|
||||
cmp -s \"$4\" '{d}/document' || exit 3\ncp '{d}/picture.png' \"$5\""
|
||||
),
|
||||
);
|
||||
let fails = script("fails", "echo broken >&2\nexit 1");
|
||||
let silent = script("silent", "exit 0");
|
||||
let hangs = script("hangs", "exec sleep 30");
|
||||
|
||||
assert_eq!(render(&writes, b"document bytes", 64, &temp, DEADLINE).unwrap(), png);
|
||||
assert!(render(&fails, b"x", 64, &temp, DEADLINE).unwrap_err().contains("exited with"));
|
||||
assert!(render(&silent, b"x", 64, &temp, DEADLINE).is_err(), "no OUT written");
|
||||
assert!(render(&hangs, b"x", 64, &temp, Duration::ZERO).unwrap_err().contains("ran longer than"));
|
||||
assert!(render(&dir.join("missing"), b"x", 64, &temp, DEADLINE).is_err());
|
||||
assert_eq!(files_in(&temp), Vec::<String>::new());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -27,10 +27,10 @@ log = { workspace = true }
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", version = "0.1.0" }
|
||||
|
||||
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", "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"] }
|
||||
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", "Node", "Worker", "MessageEvent", "ErrorEvent", "Performance"] }
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="icons/32/ai.storyteller.vectorcraft.png">
|
||||
<link rel="apple-touch-icon" href="icons/256/ai.storyteller.vectorcraft.png">
|
||||
<link data-trunk rel="rust" data-bin="vectorcraft-web" data-wasm-opt="z" data-weak-refs />
|
||||
<!-- The plug-in worker: checks plug-ins being installed and runs filters off the page (apps/vectorcraft-plugin-worker). -->
|
||||
<link data-trunk rel="rust" href="../vectorcraft-plugin-worker/Cargo.toml" data-bin="vectorcraft-plugin-worker" data-type="worker" data-loader-shim data-wasm-opt="z" />
|
||||
<style>
|
||||
/* iPad: no page scroll, bounce, pinch zoom, text selection or callout; the app takes the gestures. */
|
||||
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #262626;
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//! The hand-off from the browser's input hook to the visible UI pass.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use egui::{DroppedFileHandle, Pos2, RawInput};
|
||||
|
||||
/// CSS pixels from the canvas origin, and whether Shift was held.
|
||||
pub(crate) type DragPosition = (f32, f32, bool);
|
||||
|
||||
pub(crate) struct DropBatch {
|
||||
pub(crate) files: Vec<DroppedFileHandle>,
|
||||
pub(crate) pos: Option<Pos2>,
|
||||
pub(crate) shift: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct FileDrops(Vec<DroppedFileHandle>);
|
||||
|
||||
impl FileDrops {
|
||||
pub(crate) fn capture(&mut self, raw: &mut RawInput) {
|
||||
// The shared router reads dropped files at the start of the pass, before the web UI runs.
|
||||
self.0.append(&mut raw.dropped_files);
|
||||
}
|
||||
|
||||
pub(crate) fn take(&mut self, ctx: &egui::Context, position: &Cell<Option<DragPosition>>) -> Option<DropBatch> {
|
||||
let files = std::mem::take(&mut self.0);
|
||||
if files.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let at = position.take();
|
||||
let z = ctx.zoom_factor();
|
||||
let pos = at.map(|(x, y, _)| egui::pos2(x / z, y / z));
|
||||
let shift = at.is_some_and(|(_, _, shift)| shift);
|
||||
Some(DropBatch { files, pos, shift })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Svg;
|
||||
|
||||
impl egui::DroppedFile for Svg {
|
||||
fn path(&self) -> &Path {
|
||||
Path::new("drawing.svg")
|
||||
}
|
||||
|
||||
fn bytes(&self) -> Result<Vec<u8>, String> {
|
||||
Err("test file has no contents".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn check_handoff(at: Option<DragPosition>, expected_pos: Option<Pos2>, expected_shift: bool) {
|
||||
let ctx = egui::Context::default();
|
||||
let shared_files = Arc::new(AtomicUsize::new(0));
|
||||
ctx.on_begin_pass("observe dropped files before the app UI", {
|
||||
let shared_files = shared_files.clone();
|
||||
Arc::new(move |ui| {
|
||||
shared_files.fetch_add(ui.ctx().input(|input| input.raw.dropped_files.len()), Ordering::Relaxed);
|
||||
})
|
||||
});
|
||||
let mut drops = FileDrops::default();
|
||||
let position = Cell::new(at);
|
||||
let svg = Arc::new(Svg) as DroppedFileHandle;
|
||||
let mut raw = RawInput { dropped_files: vec![svg.clone()], ..Default::default() };
|
||||
|
||||
drops.capture(&mut raw);
|
||||
let mut delivered = Vec::new();
|
||||
ctx.run_ui(raw, |ui| delivered.extend(drops.take(ui.ctx(), &position))).textures_delta.clear();
|
||||
let mut next = RawInput::default();
|
||||
drops.capture(&mut next);
|
||||
ctx.run_ui(next, |ui| delivered.extend(drops.take(ui.ctx(), &position))).textures_delta.clear();
|
||||
|
||||
assert_eq!(shared_files.load(Ordering::Relaxed), 0, "the shared router must not see browser-owned drops");
|
||||
assert_eq!(delivered.len(), 1, "the browser UI must receive exactly one batch");
|
||||
let batch = &delivered[0];
|
||||
assert_eq!(batch.files.len(), 1, "the browser UI must receive exactly one file");
|
||||
assert!(Arc::ptr_eq(&batch.files[0], &svg));
|
||||
assert_eq!((batch.pos, batch.shift), (expected_pos, expected_shift));
|
||||
assert!(position.get().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positioned_browser_drop_reaches_the_web_ui_once() {
|
||||
check_handoff(Some((53.0, 27.0, true)), Some(egui::pos2(53.0, 27.0)), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_browser_drop_without_a_position_reaches_the_web_ui_once() {
|
||||
check_handoff(None, None, false);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@
|
||||
//! - no TCP control server (browsers can't listen on sockets);
|
||||
//! - File → Open uses the browser file picker, through the host's file service (`BrowserFiles`);
|
||||
//! - Save / Export trigger a browser download;
|
||||
//! - plug-ins are checked when installed, and filters run, in Web Workers of their own
|
||||
//! (`plugin_workers`, the `vectorcraft-plugin-worker` build), so a plug-in never runs on the page;
|
||||
//! - 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, the pen's eraser end
|
||||
@@ -20,6 +22,8 @@
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod api;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod file_drops;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod fonts;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
@@ -28,6 +32,8 @@ mod keys;
|
||||
mod locks;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod pencil;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod plugin_workers;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod saved_files;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -53,6 +53,20 @@ pub struct Pointers {
|
||||
/// The pen's pressure and end for the canvas, the source the install reads.
|
||||
// PLAN: named `source`, not `pen`: `pen` is the pressing pen's pointer id above.
|
||||
source: PenSource,
|
||||
/// The pen whose finger wheel is read ([`Pointers::wheel`]).
|
||||
wheel: Option<Wheel>,
|
||||
/// Every reading written into the source, in order.
|
||||
#[cfg(test)]
|
||||
readings: Vec<PointerSample>,
|
||||
}
|
||||
|
||||
/// A pen, by pointer id and the end it is turned to, and whether it has reported a tangential
|
||||
/// pressure other than 0 since it came near.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Wheel {
|
||||
id: i32,
|
||||
eraser: bool,
|
||||
reads: bool,
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -64,6 +78,11 @@ struct Input<'a> {
|
||||
id: i32,
|
||||
button: i16,
|
||||
pressure: f32,
|
||||
/// Pointer Events' `tangentialPressure`, −1..1: an airbrush pen's finger wheel.
|
||||
tangential: f32,
|
||||
/// Whether the event names an element the pointer moved onto (`relatedTarget`): a pen leaving
|
||||
/// one element for another is still in its hover range.
|
||||
entered: bool,
|
||||
modifiers: egui::Modifiers,
|
||||
}
|
||||
|
||||
@@ -90,11 +109,29 @@ impl Pointers {
|
||||
self.source.clone()
|
||||
}
|
||||
|
||||
/// A pen moved or pressed with `pressure`, with the end it last pressed with.
|
||||
fn pen_sample(&self, pressure: f32) {
|
||||
/// A pen pressed, moved or lifted with `pressure` and `wheel`, with the end it last pressed
|
||||
/// with. The source queues each reading, and the runtime pairs the readings with the frame's
|
||||
/// pointer moves, so each move written after its own reading keeps that reading's wheel.
|
||||
fn pen_sample(&mut self, pressure: f32, wheel: Option<f32>) {
|
||||
let mut sample = PointerSample::new(pressure);
|
||||
sample.eraser = self.eraser;
|
||||
sample.wheel = wheel;
|
||||
self.source.set(Some(sample));
|
||||
#[cfg(test)]
|
||||
self.readings.push(sample);
|
||||
}
|
||||
|
||||
/// The finger wheel of pen `id`, turned to the end it last pressed with, for a sample with
|
||||
/// Pointer Events' `tangentialPressure` (−1..1,
|
||||
/// <https://www.w3.org/TR/pointerevents3/#dom-pointerevent-tangentialpressure>): a wheel of
|
||||
/// 0..1, −1 at 0 and 1 at 1, a value past either end clamped. Pointer Events give 0 for a pen
|
||||
/// without a wheel, so 0 reads as none until that pen, with that end, has reported a value
|
||||
/// other than 0 since it came near. A value that is not a number is none.
|
||||
fn wheel(&mut self, id: i32, tangential: f32) -> Option<f32> {
|
||||
let known = self.wheel.is_some_and(|w| w.id == id && w.eraser == self.eraser && w.reads);
|
||||
let reads = known || (tangential.is_finite() && tangential != 0.0);
|
||||
self.wheel = Some(Wheel { id, eraser: self.eraser, reads });
|
||||
(reads && tangential.is_finite()).then(|| (tangential.clamp(-1.0, 1.0) + 1.0) / 2.0)
|
||||
}
|
||||
|
||||
fn touch(&mut self, device: TouchDeviceId, id: i32, phase: TouchPhase, pos: Pos2, force: Option<f32>) {
|
||||
@@ -134,7 +171,10 @@ 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 {
|
||||
///
|
||||
/// `coalesced` holds the positions the pen reported since the last event, each with its
|
||||
/// pressure and tangential pressure, the last one at `pos`.
|
||||
fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32, 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
|
||||
@@ -163,19 +203,24 @@ impl Pointers {
|
||||
if let Some(end) = end {
|
||||
self.eraser = end;
|
||||
}
|
||||
self.pen_sample(e.pressure);
|
||||
let wheel = self.wheel(id, e.tangential);
|
||||
self.pen_sample(e.pressure, wheel);
|
||||
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)) {
|
||||
self.touch(PEN_DEVICE, id, TouchPhase::Move, c.0, Some(c.1));
|
||||
self.events.push(Event::PointerMoved(c.0));
|
||||
// on an iPad), each with its pressure and wheel, so fast strokes keep
|
||||
// their curve.
|
||||
for &(at, pressure, tangential) in coalesced.iter().take(coalesced.len().saturating_sub(1)) {
|
||||
let wheel = self.wheel(id, tangential);
|
||||
self.pen_sample(pressure, wheel);
|
||||
self.touch(PEN_DEVICE, id, TouchPhase::Move, at, Some(pressure));
|
||||
self.events.push(Event::PointerMoved(at));
|
||||
}
|
||||
let wheel = self.wheel(id, e.tangential);
|
||||
self.pen_sample(e.pressure, wheel);
|
||||
self.touch(PEN_DEVICE, id, TouchPhase::Move, pos, force);
|
||||
self.events.push(Event::PointerMoved(pos));
|
||||
}
|
||||
@@ -189,12 +234,19 @@ impl Pointers {
|
||||
}
|
||||
// Pointer Events report no end while a pen hovers: it keeps the end it
|
||||
// last pressed with.
|
||||
self.pen_sample(e.pressure);
|
||||
let wheel = self.wheel(id, e.tangential);
|
||||
self.pen_sample(e.pressure, wheel);
|
||||
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);
|
||||
let (phase, wheel) = if kind == "pointerup" {
|
||||
// Lifted, the pen hovers on and keeps what it read of its wheel.
|
||||
(TouchPhase::End, self.wheel(id, e.tangential))
|
||||
} else {
|
||||
self.wheel = None;
|
||||
(TouchPhase::Cancel, None)
|
||||
};
|
||||
self.pen_sample(0.0, wheel);
|
||||
self.pen = None;
|
||||
self.touch(PEN_DEVICE, id, phase, pos, None);
|
||||
self.release(pos, e.modifiers);
|
||||
@@ -204,6 +256,13 @@ impl Pointers {
|
||||
if kind == "pointerleave" && self.primary.is_none() && on_canvas {
|
||||
self.events.push(Event::PointerGone);
|
||||
}
|
||||
// Left the hover range (a leave onto no element, on the canvas or off it)
|
||||
// or canceled: the pen reads its wheel afresh. Moving onto another element
|
||||
// keeps what it read.
|
||||
let gone = (kind == "pointerleave" && !e.entered && self.pen.is_none()) || kind == "pointercancel";
|
||||
if gone && self.wheel.is_some_and(|w| w.id == id) {
|
||||
self.wheel = None;
|
||||
}
|
||||
return self.pen.is_some();
|
||||
}
|
||||
}
|
||||
@@ -276,7 +335,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement,
|
||||
let z = runner.egui_ctx().zoom_factor();
|
||||
let pos = egui::pos2((e.client_x() as f32 - rect.left() as f32) / z, (e.client_y() as f32 - rect.top() as f32) / z);
|
||||
let at = |x: i32, y: i32| egui::pos2((x as f32 - rect.left() as f32) / z, (y as f32 - rect.top() as f32) / z);
|
||||
let coalesced: Vec<(Pos2, f32)> = if kind == "pointermove"
|
||||
let coalesced: Vec<(Pos2, f32, f32)> = if kind == "pointermove"
|
||||
&& e.pointer_type() == "pen"
|
||||
// Safari before 17 hasn't it, and calling a missing method would abort the app.
|
||||
&& js_sys::Reflect::has(&e, &"getCoalescedEvents".into()).unwrap_or(false)
|
||||
@@ -284,7 +343,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement,
|
||||
e.get_coalesced_events()
|
||||
.iter()
|
||||
.filter_map(|c| c.dyn_into::<web_sys::PointerEvent>().ok())
|
||||
.map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0)))
|
||||
.map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0), c.tangential_pressure()))
|
||||
.collect()
|
||||
} else {
|
||||
vec![]
|
||||
@@ -295,6 +354,8 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement,
|
||||
id: e.pointer_id(),
|
||||
button: e.button(),
|
||||
pressure: e.pressure(),
|
||||
tangential: e.tangential_pressure(),
|
||||
entered: e.related_target().is_some(),
|
||||
// Same semantics as eframe's modifiers_from_mouse_event.
|
||||
modifiers: egui::Modifiers {
|
||||
alt: e.alt_key(),
|
||||
@@ -343,7 +404,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn input(pointer_type: &str, button: i16) -> Input<'_> {
|
||||
Input { pointer_type, id: 7, button, pressure: 0.6, modifiers: egui::Modifiers::default() }
|
||||
Input { pointer_type, id: 7, button, pressure: 0.6, tangential: 0.0, entered: false, modifiers: egui::Modifiers::default() }
|
||||
}
|
||||
|
||||
fn reset() {
|
||||
@@ -505,6 +566,128 @@ mod tests {
|
||||
reset();
|
||||
}
|
||||
|
||||
fn pen_at(button: i16, tangential: f32) -> Input<'static> {
|
||||
Input { pointer_type: "pen", id: 7, button, pressure: 0.6, tangential, entered: false, modifiers: egui::Modifiers::default() }
|
||||
}
|
||||
|
||||
/// The wheels of the readings written since the last call, in order.
|
||||
fn wheels(p: &mut Pointers) -> Vec<Option<f32>> {
|
||||
p.readings.drain(..).map(|s| s.wheel).collect()
|
||||
}
|
||||
|
||||
/// The wheel of the source's latest reading.
|
||||
fn current_wheel(p: &Pointers) -> Option<f32> {
|
||||
p.pen().current().and_then(|s| s.wheel)
|
||||
}
|
||||
|
||||
/// An airbrush pen's finger wheel (Pointer Events' `tangentialPressure`, −1..1) reaches the
|
||||
/// source as 0..1 with each move, once the pen has reported a value other than 0.
|
||||
#[test]
|
||||
fn an_airbrush_wheel_goes_into_the_feed() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
assert!(p.feed("pointerdown", &pen_at(0, 0.0), Pos2::ZERO, &[], true));
|
||||
for t in [0.0, -1.0, 0.5, 0.0, 3.0, f32::NAN, -0.5] {
|
||||
assert!(p.feed("pointermove", &pen_at(-1, t), Pos2::ZERO, &[], true));
|
||||
}
|
||||
assert_eq!(
|
||||
wheels(&mut p),
|
||||
[None, None, Some(0.0), Some(0.75), Some(0.5), Some(1.0), None, Some(0.25)],
|
||||
"none until reported; then 0 is half way, past the ends is clamped and not a number is none"
|
||||
);
|
||||
assert!(p.feed("pointerup", &pen_at(0, 0.0), Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), Some(0.5), "the lift keeps the wheel");
|
||||
reset();
|
||||
}
|
||||
|
||||
/// The positions a fast stroke's event coalesced each get a reading with their own wheel and
|
||||
/// pressure, in order, before their move, and the event's own position comes last with its own.
|
||||
#[test]
|
||||
fn coalesced_moves_keep_their_wheel() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
let (a, b, c) = (Pos2::new(1.0, 2.0), Pos2::new(3.0, 4.0), Pos2::new(5.0, 6.0));
|
||||
assert!(p.feed("pointerdown", &pen_at(0, -1.0), Pos2::ZERO, &[], true));
|
||||
let coalesced = [(a, 0.3, -0.5), (b, 0.4, 0.5), (c, 0.5, 0.75)];
|
||||
assert!(p.feed("pointermove", &pen_at(-1, 1.0), c, &coalesced, true));
|
||||
let moved: Vec<Pos2> = p.take().into_iter().filter_map(|e| if let Event::PointerMoved(at) = e { Some(at) } else { None }).collect();
|
||||
let kept = std::mem::take(&mut p.readings);
|
||||
assert_eq!(moved, [Pos2::ZERO, a, b, c]);
|
||||
assert_eq!(kept.iter().map(|s| s.wheel).collect::<Vec<_>>(), [Some(0.0), Some(0.25), Some(0.75), Some(1.0)]);
|
||||
assert_eq!(kept.iter().map(|s| s.pressure).collect::<Vec<_>>(), [0.6, 0.3, 0.4, 0.6], "each move keeps its pressure too");
|
||||
reset();
|
||||
}
|
||||
|
||||
/// A pen that leaves the hover range, a canceled press, another pen and the other end each
|
||||
/// read the wheel afresh; a lift into hover does not. A mouse or a finger reads no wheel.
|
||||
#[test]
|
||||
fn the_wheel_is_read_afresh_for_each_pen_and_end() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
let feed = p.pen();
|
||||
let learn = |p: &mut Pointers, button: i16| {
|
||||
assert!(p.feed("pointerdown", &pen_at(button, 0.5), Pos2::ZERO, &[], true));
|
||||
assert!(p.feed("pointerup", &pen_at(button, 0.5), Pos2::ZERO, &[], true));
|
||||
};
|
||||
let hover = |p: &mut Pointers, id: i32| {
|
||||
let mut e = pen_at(-1, 0.0);
|
||||
e.id = id;
|
||||
e.pressure = 0.0;
|
||||
assert!(p.feed("pointermove", &e, Pos2::ZERO, &[], true));
|
||||
};
|
||||
learn(&mut p, 0);
|
||||
hover(&mut p, 7);
|
||||
assert_eq!(current_wheel(&p), Some(0.5), "a lift into hover keeps it");
|
||||
p.feed("pointerleave", &pen_at(-1, 0.0), Pos2::ZERO, &[], true);
|
||||
hover(&mut p, 7);
|
||||
assert_eq!(current_wheel(&p), None, "left the hover range");
|
||||
learn(&mut p, 0);
|
||||
assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true));
|
||||
assert!(p.feed("pointercancel", &pen_at(0, 0.5), Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), None, "a canceled press");
|
||||
hover(&mut p, 7);
|
||||
assert_eq!(current_wheel(&p), None, "after a canceled press");
|
||||
learn(&mut p, 0);
|
||||
hover(&mut p, 8);
|
||||
assert_eq!(current_wheel(&p), None, "another pen");
|
||||
learn(&mut p, 0);
|
||||
assert!(p.feed("pointerdown", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), None, "the other end");
|
||||
assert!(p.feed("pointerup", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true));
|
||||
p.readings.clear();
|
||||
for (pointer_type, kind) in [("mouse", "pointermove"), ("touch", "pointerdown"), ("touch", "pointermove")] {
|
||||
let mut other = pen_at(0, 0.5);
|
||||
(other.pointer_type, other.id) = (pointer_type, 10);
|
||||
p.feed(kind, &other, Pos2::ZERO, &[], true);
|
||||
assert_eq!(feed.current(), None, "{pointer_type} {kind}");
|
||||
assert!(p.readings.is_empty(), "{pointer_type} {kind}");
|
||||
}
|
||||
reset();
|
||||
}
|
||||
|
||||
/// A hovering pen that moves off the canvas onto another element and back keeps what it read
|
||||
/// of its wheel; one that leaves the hover range off the canvas reads it afresh.
|
||||
#[test]
|
||||
fn the_wheel_survives_crossing_the_canvas_edge() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true));
|
||||
assert!(p.feed("pointerup", &pen_at(0, 0.5), Pos2::ZERO, &[], true));
|
||||
let mut hover = pen_at(-1, 0.0);
|
||||
hover.pressure = 0.0;
|
||||
let mut onto = pen_at(-1, 0.0);
|
||||
(onto.pressure, onto.entered) = (0.0, true);
|
||||
p.feed("pointerleave", &onto, Pos2::ZERO, &[], true);
|
||||
assert!(!p.feed("pointermove", &hover, Pos2::ZERO, &[], false));
|
||||
assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), Some(0.5), "moved onto another element and back");
|
||||
p.feed("pointerleave", &onto, Pos2::ZERO, &[], true);
|
||||
p.feed("pointerleave", &hover, Pos2::ZERO, &[], false);
|
||||
assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), None, "left the hover range off the canvas");
|
||||
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]
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! The plug-in workers ([`vectorcraft_ui_egui::plugin_runs::Workers`]): each one a Web Worker that
|
||||
//! runs `vectorcraft-plugin-worker`, which Trunk builds beside the app (`index.html`), started from
|
||||
//! the loader file Trunk writes for it next to `index.html`.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use vectorcraft_ui_egui::plugin_runs::{SharedInbox, WorkerLink, Workers};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::prelude::Closure;
|
||||
|
||||
/// The loader Trunk writes for the worker (`data-loader-shim`), beside `index.html`.
|
||||
const LOADER: &str = "vectorcraft-plugin-worker_loader.js";
|
||||
|
||||
/// Starts the workers; each message or failure asks for a frame, which reads it.
|
||||
pub(crate) struct PageWorkers {
|
||||
pub(crate) ctx: egui::Context,
|
||||
}
|
||||
|
||||
/// One worker and its message and error handlers.
|
||||
struct PageWorker {
|
||||
worker: web_sys::Worker,
|
||||
_on_message: Closure<dyn FnMut(web_sys::MessageEvent)>,
|
||||
_on_error: Closure<dyn FnMut(web_sys::Event)>,
|
||||
}
|
||||
|
||||
/// The text of a browser error value.
|
||||
fn js_err(e: wasm_bindgen::JsValue) -> String {
|
||||
e.as_string().unwrap_or_else(|| format!("{e:?}"))
|
||||
}
|
||||
|
||||
impl Workers for PageWorkers {
|
||||
fn start(&self, inbox: SharedInbox) -> Result<Box<dyn WorkerLink>, String> {
|
||||
let document = web_sys::window().and_then(|w| w.document()).ok_or_else(|| "no document".to_string())?;
|
||||
let base = document.base_uri().map_err(js_err)?.ok_or_else(|| "no document".to_string())?;
|
||||
let url = web_sys::Url::new_with_base(LOADER, &base).map_err(js_err)?.href();
|
||||
let worker = web_sys::Worker::new(&url).map_err(js_err)?;
|
||||
let (to, ctx) = (Rc::clone(&inbox), self.ctx.clone());
|
||||
let on_message = Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |e: web_sys::MessageEvent| {
|
||||
to.borrow_mut().push(&js_sys::Uint8Array::new(&e.data()).to_vec());
|
||||
ctx.request_repaint();
|
||||
});
|
||||
let ctx = self.ctx.clone();
|
||||
// A worker that fails to load, panics or posts a message that can't be read.
|
||||
let on_error = Closure::<dyn FnMut(web_sys::Event)>::new(move |e: web_sys::Event| {
|
||||
let why = e.dyn_ref::<web_sys::ErrorEvent>().map_or_else(|| e.type_(), web_sys::ErrorEvent::message);
|
||||
inbox.borrow_mut().fail(why);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
worker.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
|
||||
worker.set_onerror(Some(on_error.as_ref().unchecked_ref()));
|
||||
worker.set_onmessageerror(Some(on_error.as_ref().unchecked_ref()));
|
||||
Ok(Box::new(PageWorker { worker, _on_message: on_message, _on_error: on_error }))
|
||||
}
|
||||
|
||||
fn now_ms(&self) -> f64 {
|
||||
web_sys::window().and_then(|w| w.performance()).map_or(0.0, |p| p.now())
|
||||
}
|
||||
}
|
||||
|
||||
impl WorkerLink for PageWorker {
|
||||
fn post(&mut self, msg: Vec<u8>) -> Result<(), String> {
|
||||
let bytes = js_sys::Uint8Array::from(msg.as_slice());
|
||||
self.worker.post_message_with_transfer(&bytes, &js_sys::Array::of1(&bytes.buffer())).map_err(js_err)
|
||||
}
|
||||
|
||||
fn terminate(&mut self) {
|
||||
self.worker.set_onmessage(None);
|
||||
self.worker.set_onerror(None);
|
||||
self.worker.set_onmessageerror(None);
|
||||
self.worker.terminate();
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
|
||||
use vectorcraft_ui_egui::{Services, VectorcraftApp};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
use crate::file_drops::{DragPosition, DropBatch, FileDrops};
|
||||
use crate::locks::WebLocks;
|
||||
use crate::pencil::SharedPointers;
|
||||
|
||||
@@ -39,7 +40,7 @@ struct OpenInboxes {
|
||||
|
||||
/// Where the pointer was over the canvas during the last file drag (CSS px from its top-left) and
|
||||
/// whether Shift was held: where dropped files land.
|
||||
type DragPos = Rc<Cell<Option<(f32, f32, bool)>>>;
|
||||
type DragPos = Rc<Cell<Option<DragPosition>>>;
|
||||
|
||||
/// A picture or file pasted into the page, read and waiting for the next frame with the modifiers
|
||||
/// held at the paste, and the context to wake for it (the current runner's).
|
||||
@@ -156,7 +157,7 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
|
||||
.jobs(Arc::new(InlineJobs))
|
||||
.files(Arc::new(files))
|
||||
.install(ctx);
|
||||
let services = services(host.inbox.clone(), host.place_inbox.clone(), host.locks.clone());
|
||||
let services = services(host.inbox.clone(), host.place_inbox.clone(), host.locks.clone(), ctx.clone());
|
||||
let mut app = match taken.borrow_mut().take() {
|
||||
Some(mut app) => {
|
||||
// The old services asked the old context for frames.
|
||||
@@ -176,7 +177,7 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
|
||||
}
|
||||
};
|
||||
app.adopt_context(ctx);
|
||||
Ok(Box::new(WebShell { app: Some(app), host, canvas: page, loss }))
|
||||
Ok(Box::new(WebShell { app: Some(app), host, canvas: page, loss, dropped: FileDrops::default() }))
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
@@ -376,6 +377,7 @@ struct WebShell {
|
||||
host: Host,
|
||||
canvas: web_sys::HtmlCanvasElement,
|
||||
loss: GraphicsLoss,
|
||||
dropped: FileDrops,
|
||||
}
|
||||
|
||||
impl WebShell {
|
||||
@@ -410,9 +412,9 @@ impl eframe::App for WebShell {
|
||||
embed::logic(ctx, || app.close_decision());
|
||||
}
|
||||
|
||||
/// Forward host-gathered pointer events into this frame's raw input, then let the app apply its
|
||||
/// shared input hook before egui runs.
|
||||
/// Gather browser drops and forward host pointer events before egui runs.
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
self.dropped.capture(raw);
|
||||
raw.events.extend(self.host.pointers.borrow_mut().take());
|
||||
if let Some(app) = &mut self.app {
|
||||
app.raw_input(ctx, raw);
|
||||
@@ -425,18 +427,13 @@ impl eframe::App for WebShell {
|
||||
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.
|
||||
// Deliver host input in a visible UI pass. Hidden tabs only run `logic`.
|
||||
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 {
|
||||
if let Some(DropBatch { files, pos, shift }) = self.dropped.take(&ctx, &self.host.drag) {
|
||||
for f in files {
|
||||
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, app.drop_spot(pos), shift);
|
||||
let (inbox, place_inbox, repaint) = (self.host.inbox.dropped.clone(), self.host.place_inbox.clone(), ctx.clone());
|
||||
@@ -461,8 +458,10 @@ impl eframe::App for WebShell {
|
||||
}
|
||||
}
|
||||
|
||||
fn services(inbox: OpenInboxes, place_inbox: PlaceInbox, locks: Option<WebLocks>) -> Services {
|
||||
fn services(inbox: OpenInboxes, place_inbox: PlaceInbox, locks: Option<WebLocks>, ctx: egui::Context) -> Services {
|
||||
Services {
|
||||
// Plug-ins are checked and filters run in workers of their own, off the page.
|
||||
plugin_workers: vectorcraft_ui_egui::plugin_runs::workers(Box::new(crate::plugin_workers::PageWorkers { ctx })),
|
||||
// A download that couldn't be started fails the save or export it is for (#1693).
|
||||
download: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes).inspect_err(|e| log::error!("download of {name} failed: {e}")))),
|
||||
inbox: Some(inbox.dropped),
|
||||
|
||||
@@ -69,7 +69,7 @@ vectorcraft-render = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2 = "0.6"
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSpace", "NSControl", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSpace", "NSControl", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSView", "NSWindow"] }
|
||||
# Files opened from Finder and the Dock (src/open_documents.rs) and pasted bitmaps (src/clipboard.rs); both already come with winit.
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] }
|
||||
block2 = "0.6"
|
||||
|
||||
@@ -243,14 +243,3 @@ pub(crate) fn open_files(app: &mut VectorcraftApp, files: Vec<String>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,11 +7,17 @@
|
||||
//! fails in a Flatpak sandbox (`XCURSOR_PATH` unset, no cursor theme in the runtime) and where the
|
||||
//! `default` theme is a dangling symlink; the desktop's own setting names a theme that loads.
|
||||
//!
|
||||
//! Where no cursor theme can be found at all (KDE or sway without gsettings), the env fix does
|
||||
//! nothing: [`shell_caps`] leaves out [`Caps::SYSTEM_CURSOR`], and the framework keeps the system
|
||||
//! pointer and paints no tool cursor beside it (#5311).
|
||||
//!
|
||||
//! This reads the desktop's cursor theme and size and sets what the user left unset, once, before
|
||||
//! any thread starts and before the window opens.
|
||||
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
|
||||
use craft::host::target::Caps;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Where a Flatpak sandbox mounts the host's cursor themes (user and system).
|
||||
const FLATPAK_HOST_ICONS: [&str; 2] = ["/run/host/user-share/icons", "/run/host/share/icons"];
|
||||
@@ -48,6 +54,74 @@ pub fn plan(var: impl Fn(&str) -> Option<OsString>, host_icons: &[&str], desktop
|
||||
out
|
||||
}
|
||||
|
||||
/// Xcursor's default search path when `XCURSOR_PATH` is unset (relative entries are in `$HOME`).
|
||||
const DEFAULT_ICON_DIRS: [&str; 5] = ["~/.local/share/icons", "~/.icons", "/usr/share/icons", "/usr/share/pixmaps", "/usr/X11R6/lib/X11/icons"];
|
||||
|
||||
/// The themes `index.theme` lists after `Inherits=`.
|
||||
fn inherits(index: &str) -> Vec<String> {
|
||||
index
|
||||
.lines()
|
||||
.find_map(|l| l.trim().strip_prefix("Inherits="))
|
||||
.map(|v| v.split([',', ';']).map(|t| t.trim().to_owned()).filter(|t| !t.is_empty()).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Can Xcursor load a pointer for the environment's theme (`XCURSOR_THEME`, else `default`)? It does
|
||||
/// when the theme, or one it inherits from, has a `default` or `left_ptr` cursor file in a folder of
|
||||
/// `XCURSOR_PATH` (else Xcursor's default folders). `read` returns a file's text, `exists` tells
|
||||
/// whether a file is there.
|
||||
pub fn theme_usable(
|
||||
var: impl Fn(&str) -> Option<OsString>,
|
||||
home: Option<&Path>,
|
||||
read: impl Fn(&Path) -> Option<String>,
|
||||
exists: impl Fn(&Path) -> bool,
|
||||
) -> bool {
|
||||
let dirs: Vec<PathBuf> = match var("XCURSOR_PATH").filter(|v| !v.is_empty()) {
|
||||
Some(v) => std::env::split_paths(&v).collect(),
|
||||
None => DEFAULT_ICON_DIRS
|
||||
.iter()
|
||||
.filter_map(|d| match d.strip_prefix("~/") {
|
||||
Some(rest) => home.map(|h| h.join(rest)),
|
||||
None => Some(PathBuf::from(d)),
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let first = var("XCURSOR_THEME").and_then(|v| v.into_string().ok()).filter(|t| !t.is_empty()).unwrap_or_else(|| "default".into());
|
||||
let mut todo = vec![first];
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
while let Some(theme) = todo.pop() {
|
||||
// Bounded: themes inherit in short chains, and a cycle must end.
|
||||
if seen.contains(&theme) || seen.len() >= 16 {
|
||||
continue;
|
||||
}
|
||||
for dir in &dirs {
|
||||
let base = dir.join(&theme);
|
||||
if ["default", "left_ptr"].iter().any(|c| exists(&base.join("cursors").join(c))) {
|
||||
return true;
|
||||
}
|
||||
if let Some(index) = read(&base.join("index.theme")) {
|
||||
todo.extend(inherits(&index));
|
||||
}
|
||||
}
|
||||
seen.push(theme);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// On this machine, after [`apply`]: is there no cursor theme Xcursor can load? Then winit never
|
||||
/// sets a pointer, and a hidden system pointer does not come back (#2450).
|
||||
pub fn theme_missing() -> bool {
|
||||
let home = std::env::var_os("HOME").filter(|h| !h.is_empty()).map(PathBuf::from);
|
||||
!theme_usable(|n| std::env::var_os(n), home.as_deref(), |p| std::fs::read_to_string(p).ok(), |p| p.exists())
|
||||
}
|
||||
|
||||
/// The shell's capabilities `caps`, without [`Caps::SYSTEM_CURSOR`] when the window opens on
|
||||
/// Wayland and `theme_missing` finds no cursor theme. The framework then keeps the system pointer
|
||||
/// and paints no tool cursor beside it (#5311). `theme_missing` runs only on Wayland.
|
||||
pub fn shell_caps(caps: Caps, wayland: bool, theme_missing: impl FnOnce() -> bool) -> Caps {
|
||||
if wayland && theme_missing() { caps.difference(Caps::SYSTEM_CURSOR) } else { caps }
|
||||
}
|
||||
|
||||
/// The value of a `gsettings get` line: `'Adwaita'` becomes `Adwaita`, `24` stays `24`.
|
||||
fn gsettings_value(output: &str) -> &str {
|
||||
output.trim().trim_matches('\'')
|
||||
@@ -113,6 +187,43 @@ mod tests {
|
||||
assert!(plan(env(&[("WAYLAND_DISPLAY", "wayland-0")]), &[], odd).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_theme_is_usable_directly_or_through_inherits_and_missing_otherwise() {
|
||||
let files = ["/i/Bibata/cursors/left_ptr", "/i/Breeze/index.theme", "/i/Loop/index.theme"];
|
||||
// Compared as paths, so the joins match on Windows too, where they use `\`.
|
||||
let exists = |p: &Path| files.iter().any(|f| Path::new(f) == p);
|
||||
let read = |p: &Path| {
|
||||
if p == Path::new("/i/Breeze/index.theme") {
|
||||
Some("[Icon Theme]\nInherits=Other, Bibata\n".to_owned())
|
||||
} else if p == Path::new("/i/Loop/index.theme") {
|
||||
Some("Inherits=Loop\n".to_owned())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let with = |theme: &'static str| {
|
||||
move |n: &str| (n == "XCURSOR_PATH").then(|| OsString::from("/i")).or((n == "XCURSOR_THEME").then(|| OsString::from(theme)))
|
||||
};
|
||||
assert!(theme_usable(with("Bibata"), None, read, exists));
|
||||
assert!(theme_usable(with("Breeze"), None, read, exists));
|
||||
// No such theme, a theme without cursors, an inheritance loop: nothing to load.
|
||||
assert!(!theme_usable(with("Nope"), None, read, exists));
|
||||
assert!(!theme_usable(with("Loop"), None, read, exists));
|
||||
// Unset: Xcursor's default folders and the `default` theme.
|
||||
assert!(!theme_usable(|_| None, Some(Path::new("/home/u")), read, exists));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_cursor_theme_on_wayland_the_system_pointer_stays_alone() {
|
||||
let native = Caps::native(craft::host::target::Os::Linux);
|
||||
assert!(native.contains(Caps::SYSTEM_CURSOR));
|
||||
let without = shell_caps(native, true, || true);
|
||||
assert!(!without.contains(Caps::SYSTEM_CURSOR), "Wayland with no cursor theme: no painted cursor beside the system pointer");
|
||||
assert_eq!(without.union(Caps::SYSTEM_CURSOR), native, "only the system cursor is left out");
|
||||
assert_eq!(shell_caps(native, true, || false), native, "Wayland with a theme");
|
||||
assert_eq!(shell_caps(native, false, || panic!("the theme is looked up only on Wayland")), native, "X11 and XWayland");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gsettings_output_is_unquoted() {
|
||||
assert_eq!(gsettings_value("'Adwaita'\n"), "Adwaita");
|
||||
|
||||
@@ -629,6 +629,15 @@ struct StartFile {
|
||||
record: StartRecord,
|
||||
}
|
||||
|
||||
impl Drop for StartFile {
|
||||
/// Frees the lock when the start releases the file. A child process that any thread starts holds
|
||||
/// a copy of the file's handle until it runs its program, and the lock is only freed by closing
|
||||
/// every copy or by unlocking.
|
||||
fn drop(&mut self) {
|
||||
let _ = self.file.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
impl StartFile {
|
||||
/// Open `dir`'s [`START_FILE`], with the record the last start left in it (`None` when there is
|
||||
/// none or it can't be read). `Ok(None)` when another copy of the app holds it.
|
||||
|
||||
@@ -613,9 +613,7 @@ fn a_normal_exit_or_another_failure_does_not_restart() {
|
||||
assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into()));
|
||||
}
|
||||
|
||||
/// A log folder of its own for each test, and the guard that keeps other tests from starting a
|
||||
/// program while it runs: the test releases the start file's lock and takes it again, and a child
|
||||
/// starting meanwhile would keep it held (`crate::no_spawns`).
|
||||
/// A log folder of its own for each test.
|
||||
struct TestDir(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
@@ -632,10 +630,23 @@ impl AsRef<std::path::Path> for TestDir {
|
||||
}
|
||||
}
|
||||
|
||||
fn start_dir(tag: &str) -> (TestDir, std::sync::RwLockReadGuard<'static, ()>) {
|
||||
let spawns = crate::no_spawns();
|
||||
let dir = tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap();
|
||||
(TestDir(dir), spawns)
|
||||
fn start_dir(tag: &str) -> TestDir {
|
||||
TestDir(tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap())
|
||||
}
|
||||
|
||||
/// A start that ends frees the start file even while another handle to it is open, as a child
|
||||
/// process that is starting holds one: the next start reads the file instead of taking it for
|
||||
/// another copy of the app that is starting.
|
||||
#[test]
|
||||
fn an_ended_start_frees_the_start_file_while_a_copy_of_its_handle_is_open() {
|
||||
let dir = start_dir("copy");
|
||||
let starting = Startup::default();
|
||||
starting.track(&dir, None, false);
|
||||
let copy = starting.start.lock().unwrap().as_ref().map(|start| start.file.try_clone().unwrap());
|
||||
assert!(copy.is_some(), "the start holds the file");
|
||||
starting.ended();
|
||||
assert!(StartFile::open(&dir).unwrap().is_some(), "an ended start frees the start file");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
/// What a start in `dir` leaves out; it then ends without crashing.
|
||||
@@ -661,7 +672,7 @@ fn issue_2243() -> Vec<Candidate> {
|
||||
/// it, without a status-bar note.
|
||||
#[test]
|
||||
fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
|
||||
let (dir, _spawns) = start_dir("crash");
|
||||
let dir = start_dir("crash");
|
||||
let c = issue_2243();
|
||||
let first = Startup::default();
|
||||
assert_eq!(first.track(&dir, None, false), LeftOut::default());
|
||||
@@ -691,7 +702,7 @@ fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
|
||||
/// 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, _spawns) = start_dir("shown");
|
||||
let dir = start_dir("shown");
|
||||
let c = issue_2243();
|
||||
for end in [Startup::presented as fn(&Startup), Startup::ended] {
|
||||
let first = Startup::default();
|
||||
@@ -714,7 +725,7 @@ fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
|
||||
/// macOS, where wgpu has none.
|
||||
#[test]
|
||||
fn a_crash_while_listing_lists_opengl_alone() {
|
||||
let (dir, _spawns) = start_dir("listing");
|
||||
let dir = start_dir("listing");
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
drop(first);
|
||||
@@ -740,7 +751,7 @@ fn a_crash_while_listing_lists_opengl_alone() {
|
||||
/// 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, _spawns) = start_dir("explicit");
|
||||
let dir = start_dir("explicit");
|
||||
let c = issue_2243();
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
@@ -760,7 +771,7 @@ fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
|
||||
/// are ignored: the start goes on with nothing left out.
|
||||
#[test]
|
||||
fn a_damaged_or_unreadable_start_file_is_ignored() {
|
||||
let (dir, _spawns) = start_dir("damaged");
|
||||
let dir = start_dir("damaged");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let damaged: [&[u8]; 9] = [
|
||||
b"",
|
||||
|
||||
@@ -124,10 +124,13 @@ pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: O
|
||||
/// The arguments a child of this process starts with: a nightly launch hands its profile on, so the
|
||||
/// child opens the same private profile instead of being refused ("Open VectorCraft Nightly…"), and
|
||||
/// `--` keeps a file whose name starts with '-' a file. Stable's child arguments are unchanged.
|
||||
/// Only `single_instance` starts a child, and macOS does not build it.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn child_args(files: &[String]) -> Vec<OsString> {
|
||||
child_args_for(current(), files)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn child_args_for(profile: &Profile, files: &[String]) -> Vec<OsString> {
|
||||
let mut args: Vec<OsString> = match profile {
|
||||
Profile::Stable => Vec::new(),
|
||||
@@ -245,12 +248,14 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[test]
|
||||
fn a_stable_child_gets_the_file_delimiter_only() {
|
||||
let child = child_args_for(&Profile::Stable, &["a file.svg".to_string(), "--looks-like-a-flag".to_string()]);
|
||||
assert_eq!(child, args(&["--", "a file.svg", "--looks-like-a-flag"]));
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[test]
|
||||
fn a_nightly_child_inherits_the_selected_profile() {
|
||||
let root = PathBuf::from(absolute());
|
||||
|
||||
@@ -667,6 +667,11 @@ fn main() -> std::process::ExitCode {
|
||||
// framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and
|
||||
// Preferences › User Interface › System Title Bar.
|
||||
let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() };
|
||||
// On Wayland with no cursor theme, the system pointer stays and no tool cursor is painted
|
||||
// beside it (#2450, #5311).
|
||||
let wayland = !forced_to_x11 && Backend::from_env() == Backend::Wayland;
|
||||
let caps = cursor_theme::shell_caps(shell_info.caps, wayland, cursor_theme::theme_missing);
|
||||
let shell_info = shell_info.caps(caps);
|
||||
let titlebar_pref =
|
||||
if engine_pref("systemTitleBar").and_then(|v| v.as_bool()).unwrap_or(false) { TitleBarPref::System } else { TitleBarPref::Integrated };
|
||||
let decision = decide_for(Prefix::new("VECTORCRAFT"), shell_info.backend, titlebar_pref);
|
||||
@@ -1034,19 +1039,5 @@ fn main() -> std::process::ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests only: while a test starts another program, the child briefly holds a copy of every file
|
||||
/// this process has open, until it runs that program. A file lock held through such a copy outlives
|
||||
/// its own handle, so a GPU start test that released the start file and opened it again found it
|
||||
/// still locked, as if another copy of the app were running, and failed. A test that starts a
|
||||
/// program holds its write side; a test that depends on the start file's lock holds [`no_spawns`].
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
static CHILD_SPAWN: std::sync::RwLock<()> = std::sync::RwLock::new(());
|
||||
|
||||
/// Held by a test that releases a locked file and opens it again (see [`CHILD_SPAWN`]).
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
fn no_spawns() -> std::sync::RwLockReadGuard<'static, ()> {
|
||||
CHILD_SPAWN.read().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
mod tests;
|
||||
|
||||
@@ -16,12 +16,38 @@ static SESSION: Mutex<Option<Session>> = Mutex::new(None);
|
||||
static NOTICE_SHOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
pub struct Session {
|
||||
_lease: File,
|
||||
_lease: Lease,
|
||||
path: PathBuf,
|
||||
own_record: Vec<u8>,
|
||||
previous_unclean: bool,
|
||||
}
|
||||
|
||||
/// The profile's [`LEASE`], open and locked.
|
||||
struct Lease(File);
|
||||
|
||||
impl Lease {
|
||||
/// Lock `root`'s [`LEASE`]: `None` when another window of the same profile holds it.
|
||||
fn take(root: &Path) -> io::Result<Option<Self>> {
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => Ok(Some(Self(lease))),
|
||||
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Lease {
|
||||
/// Frees the lease when the session ends, or when a session could not be started after the lock
|
||||
/// was taken. A child process that any thread starts holds a copy of the lease's handle until it
|
||||
/// runs its program, and the lock is only freed by closing every copy or by unlocking.
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
fn regular_or_missing(path: &Path) -> io::Result<bool> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
|
||||
@@ -73,14 +99,13 @@ impl Session {
|
||||
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
|
||||
}
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => return Err(error),
|
||||
}
|
||||
let Some(lease) = Lease::take(root)? else { return Ok(None) };
|
||||
Self::record(lease, root, version, commit).map(Some)
|
||||
}
|
||||
|
||||
/// Write this launch's record while `lease` is held. On an error `lease` is dropped, which
|
||||
/// unlocks it.
|
||||
fn record(lease: Lease, root: &Path, version: &str, commit: Option<&str>) -> io::Result<Self> {
|
||||
let path = root.join(RECORD);
|
||||
let previous_unclean = regular_or_missing(&path)?;
|
||||
let own_record = serde_json::to_vec(&serde_json::json!({
|
||||
@@ -90,7 +115,7 @@ impl Session {
|
||||
"commit": commit.filter(|value| !value.is_empty()),
|
||||
}))?;
|
||||
atomic_write_no_follow(&path, &own_record)?;
|
||||
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
|
||||
Ok(Self { _lease: lease, path, own_record, previous_unclean })
|
||||
}
|
||||
|
||||
pub fn previous_unclean(&self) -> bool {
|
||||
@@ -258,6 +283,54 @@ mod tests {
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a controlled return clears its record");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ended_session_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
let first = Session::begin(Some(&fixture.0), "first", None).unwrap().unwrap();
|
||||
// A child process that is starting holds such a copy.
|
||||
let first_copy = first._lease.0.try_clone().unwrap();
|
||||
first.complete().unwrap();
|
||||
let second = Session::begin(Some(&fixture.0), "second", None).unwrap();
|
||||
assert!(second.is_some(), "a completed session frees the lease");
|
||||
let second_copy = second.as_ref().map(|session| session._lease.0.try_clone().unwrap());
|
||||
drop(second);
|
||||
assert!(Session::begin(Some(&fixture.0), "third", None).unwrap().is_some(), "a dropped session frees the lease");
|
||||
drop((first_copy, second_copy));
|
||||
}
|
||||
|
||||
/// `root`'s lease, locked as [`Session::begin`] locks it, and a copy of its handle such as a
|
||||
/// child process that is starting holds.
|
||||
fn locked_with_a_copy(root: &Path) -> (Lease, File) {
|
||||
let lease = Lease::take(root).unwrap().unwrap();
|
||||
let copy = lease.0.try_clone().unwrap();
|
||||
(lease, copy)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_cannot_check_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
std::fs::create_dir(fixture.0.join(RECORD)).unwrap();
|
||||
let (lease, copy) = locked_with_a_copy(&fixture.0);
|
||||
assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "a folder is not a record");
|
||||
std::fs::remove_dir(fixture.0.join(RECORD)).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to check its record frees the lease");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_cannot_write_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
// A folder at the temporary file's name makes the write fail after the record was checked.
|
||||
let temporary = fixture.0.join(format!(".{RECORD}.{}.tmp", std::process::id()));
|
||||
std::fs::create_dir(&temporary).unwrap();
|
||||
let (lease, copy) = locked_with_a_copy(&fixture.0);
|
||||
assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "the record cannot be written");
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
std::fs::remove_dir(&temporary).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to write its record frees the lease");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_never_removes_an_unknown_changed_record() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
@@ -145,6 +145,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_font_scans_read_the_fonts_folder_next_to_the_settings() {
|
||||
// No test installs a launch's root in this process, so the settings folder stays the same here.
|
||||
assert_eq!(profile::data_root(), None, "a test installed a launch's root beside the others");
|
||||
install_fonts();
|
||||
let fonts = prefs_dir().map(|dir| dir.join("Fonts"));
|
||||
assert!(fonts.is_some(), "a home folder to keep the settings in");
|
||||
|
||||
@@ -457,10 +457,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the process-wide root: the one test that may, since a `OnceLock` is set once per
|
||||
/// process (nextest gives every test its own).
|
||||
/// Runs the test `name` of this module again in a child process of the test binary → whether
|
||||
/// this is that child. For a test that installs the process-wide root, which every test running
|
||||
/// beside it would then read as the settings folder.
|
||||
fn in_own_process(name: &str) -> bool {
|
||||
const CHILD: &str = "VECTORCRAFT_TEST_OWN_PROCESS";
|
||||
if std::env::var_os(CHILD).is_some() {
|
||||
return true;
|
||||
}
|
||||
// The test's path without the crate's name: the desktop app and `vectorcraft-cli` both build this file.
|
||||
let module = module_path!().split_once("::").map_or(module_path!(), |(_, path)| path);
|
||||
let path = format!("{module}::{name}");
|
||||
let output =
|
||||
std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact", &path, "--nocapture"]).env(CHILD, "1").output().unwrap();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
|
||||
"{path} failed in its own process:\n{stdout}\n{}",
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
false
|
||||
}
|
||||
|
||||
/// Installs the process-wide root, which a `OnceLock` holds once per process, so the test runs in
|
||||
/// a process of its own.
|
||||
#[test]
|
||||
fn the_installed_root_is_used_once_and_must_be_absolute() {
|
||||
if !in_own_process("the_installed_root_is_used_once_and_must_be_absolute") {
|
||||
return;
|
||||
}
|
||||
let dir = temp("installed-root");
|
||||
assert!(install_data_root(PathBuf::from("relative/root")).is_err(), "a relative root is refused");
|
||||
install_data_root(dir.to_path_buf()).unwrap();
|
||||
|
||||
@@ -175,7 +175,16 @@ fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>,
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
let target = chosen.join(name);
|
||||
match std::fs::symlink_metadata(&target) {
|
||||
Ok(metadata) if !metadata.is_dir() => {
|
||||
return Err(format!("the nightly {label} must be a directory inside its selected profile"));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
|
||||
}
|
||||
let child = canonical_future(&target)?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
@@ -192,11 +201,86 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() && !folder_only {
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(all(windows, feature = "wgpu"))]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT) || info.dwFileAttributes.has(co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(all(windows, not(feature = "wgpu")))]
|
||||
{
|
||||
use std::os::windows::fs::MetadataExt as _;
|
||||
const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
|
||||
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
|
||||
if metadata.file_attributes() & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const PROFILE_FOLDERS: [&str; 18] = [
|
||||
"Data Recovery",
|
||||
"Fonts",
|
||||
"logs",
|
||||
"Launch",
|
||||
"Color Profiles",
|
||||
"Plug-ins",
|
||||
"Scripts",
|
||||
"Startup Scripts",
|
||||
"Metadata Templates",
|
||||
"New Document Profiles",
|
||||
"Proof Setups",
|
||||
"Script Data",
|
||||
"PDF Presets",
|
||||
"Swatches",
|
||||
"Graphic Styles",
|
||||
"Symbols",
|
||||
"Brushes",
|
||||
"Libraries",
|
||||
];
|
||||
|
||||
/// Recognise the shared portable data namespace in both the supplied and the resolved path. Up to
|
||||
/// the chosen folder itself, a marker only counts beside a VectorCraft executable, so an unrelated
|
||||
/// `portable.txt` higher up (in a user folder or at a drive root) does not refuse the profile.
|
||||
@@ -557,6 +641,31 @@ mod tests {
|
||||
assert!(result.unwrap_err().contains("not writable"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in PLATFORMS {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data");
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_platform_case_rules_are_the_file_systems_ones() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Invalid roots must exit before desktop initialization on every platform, including a CI
|
||||
/// machine with no display. A regression must fail rather than hang with a window open.
|
||||
@@ -7,9 +6,14 @@ fn rejects(args: &[&str], message: &str) {
|
||||
rejects_with_env(args, &[], message);
|
||||
}
|
||||
|
||||
/// Runs the desktop binary without a display, so on Linux a regression exits with a display
|
||||
/// error, which the exact stderr check rejects, instead of opening a window.
|
||||
fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) {
|
||||
let mut child = Command::new(crate::bin())
|
||||
let child = Command::new(crate::bin())
|
||||
.args(args)
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WAYLAND_SOCKET")
|
||||
.env_remove("VECTORCRAFT_CONTROL_PORT")
|
||||
.env_remove("VECTORCRAFT_AUTOMATION_READ_ROOT")
|
||||
.env_remove("VECTORCRAFT_AUTOMATION_WRITE_ROOT")
|
||||
@@ -20,21 +24,7 @@ fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) {
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
// Long enough for the binary to start on a loaded machine (the workspace's other tests run
|
||||
// meanwhile), short enough to catch a desktop that started instead of exiting.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let timed_out = loop {
|
||||
if child.try_wait().unwrap().is_some() {
|
||||
break false;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
child.kill().unwrap();
|
||||
break true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
let out = child.wait_with_output().unwrap();
|
||||
assert!(!timed_out, "{args:?}: desktop started or did not exit promptly");
|
||||
let out = crate::exit_output(child, &format!("{args:?}: the desktop started instead of exiting"));
|
||||
assert!(!out.status.success(), "{args:?}");
|
||||
assert!(out.stdout.is_empty(), "{args:?}: {:?}", out.stdout);
|
||||
// Exact stderr excludes unrelated startup warnings or display errors that could otherwise
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
//! `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};
|
||||
|
||||
/// 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(crate::bin())
|
||||
let child = Command::new(crate::bin())
|
||||
.args(args)
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
@@ -22,28 +19,7 @@ fn run(args: &[&str], env: &[(&str, &str)]) -> Output {
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.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
|
||||
crate::exit_output(child, &format!("{args:?}: the app started instead of printing its usage"))
|
||||
}
|
||||
|
||||
fn prints_usage(args: &[&str], env: &[(&str, &str)]) {
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::io::Read;
|
||||
use std::process::{Child, Output};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
mod automation_args;
|
||||
mod help;
|
||||
|
||||
@@ -12,3 +17,70 @@ fn bin() -> std::path::PathBuf {
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft").into())
|
||||
}
|
||||
|
||||
/// Waits for `child`, spawned with piped stdout and stderr, to exit and returns its output. 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: the test then fails with `started`.
|
||||
fn exit_output(child: Child, started: &str) -> Output {
|
||||
exit_output_by(child, started, Instant::now() + Duration::from_secs(120))
|
||||
}
|
||||
|
||||
/// [`exit_output`] with the deadline given. A binary that has exited by the deadline passes even
|
||||
/// when its output arrives after it; the output then has 10 seconds more to arrive.
|
||||
fn exit_output_by(mut child: Child, started: &str, deadline: Instant) -> Output {
|
||||
let stdout = read_to_end(child.stdout.take().unwrap());
|
||||
let stderr = read_to_end(child.stderr.take().unwrap());
|
||||
let (mut out, mut err) = (None, None);
|
||||
if !receive([(&stdout, &mut out), (&stderr, &mut err)], deadline) && child.try_wait().unwrap().is_none() {
|
||||
child.kill().unwrap();
|
||||
child.wait().unwrap();
|
||||
panic!("{started}");
|
||||
}
|
||||
receive([(&stdout, &mut out), (&stderr, &mut err)], Instant::now() + Duration::from_secs(10));
|
||||
let (Some(stdout), Some(stderr)) = (out, err) else {
|
||||
panic!("{started}: the binary exited, but its output pipes stayed open");
|
||||
};
|
||||
Output { status: child.wait().unwrap(), stdout, stderr }
|
||||
}
|
||||
|
||||
/// A pipe's reader and the slot that holds its output once it arrives.
|
||||
type Pipe<'a> = (&'a mpsc::Receiver<Vec<u8>>, &'a mut Option<Vec<u8>>);
|
||||
|
||||
/// Fills each empty slot from its reader, waiting until `until` at the latest. Returns whether
|
||||
/// every slot is filled.
|
||||
fn receive(pipes: [Pipe<'_>; 2], until: Instant) -> bool {
|
||||
let mut filled = true;
|
||||
for (rx, slot) in pipes {
|
||||
if slot.is_none() {
|
||||
*slot = rx.recv_timeout(until.saturating_duration_since(Instant::now())).ok();
|
||||
}
|
||||
filled &= slot.is_some();
|
||||
}
|
||||
filled
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
/// A binary that exits before the deadline passes even when a process it started keeps its
|
||||
/// output pipes open past the deadline.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn exit_output_accepts_an_exit_whose_output_arrives_after_the_deadline() {
|
||||
use std::process::{Command, Stdio};
|
||||
let mut child =
|
||||
Command::new("sh").args(["-c", "sleep 1 & exit 0"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
// `sh` has exited; the `sleep` it started still holds both pipes for about a second.
|
||||
child.wait().unwrap();
|
||||
let out = exit_output_by(child, "an exited binary was reported as running", Instant::now());
|
||||
assert!(out.status.success());
|
||||
assert!(out.stdout.is_empty() && out.stderr.is_empty());
|
||||
}
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 235 KiB After Width: | Height: | Size: 122 KiB |
+131
-16
@@ -121,14 +121,125 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) {
|
||||
/// and a copy's size, spacing, scatter and rotation stay as they were without hue jitter.
|
||||
const HUE_JITTER_SALT: u64 = 0x6875_655f_6a69_7474;
|
||||
|
||||
/// Turn the hue of each of `copies` (a scatter brush's copies, in order along the path) by its
|
||||
/// own amount between −`amount` and `amount` degrees, drawn from `seed` (the stroke's
|
||||
/// [`crate::track::seed_of`]).
|
||||
pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) {
|
||||
let mut rng = crate::track::Rng::new(seed ^ HUE_JITTER_SALT);
|
||||
/// Mixed into a stroke's seed for its saturation jitter, so its amounts do not follow the hue
|
||||
/// jitter's and the hue jitter's amounts stay as they were without it.
|
||||
const SATURATION_JITTER_SALT: u64 = 0x7361_745f_6a69_7474;
|
||||
|
||||
/// Mixed into a stroke's seed for its brightness jitter, so its amounts follow neither the hue
|
||||
/// jitter's nor the saturation jitter's, and theirs stay as they were without it.
|
||||
const BRIGHTNESS_JITTER_SALT: u64 = 0x6272_695f_6a69_7474;
|
||||
|
||||
/// Recolor each of `copies` (a scatter brush's copies, in order along the path) with `adjust`,
|
||||
/// given that copy's own amount between −`amount` and `amount`, drawn from `seed` (the stroke's
|
||||
/// [`crate::track::seed_of`]) mixed with `salt`. `adjust` gives `None` for a color it leaves as it
|
||||
/// is.
|
||||
fn jitter_copies(copies: &mut [Node], amount: f64, seed: u64, salt: u64, adjust: fn(&Color, f32) -> Option<Color>) {
|
||||
let mut rng = crate::track::Rng::new(seed ^ salt);
|
||||
for n in copies {
|
||||
let turn = rng.range(-amount, amount) as f32;
|
||||
turn_hues(n, turn);
|
||||
let by = rng.range(-amount, amount) as f32;
|
||||
recolor_solids(n, &|c| adjust(c, by));
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn the hue of each of `copies` by its own amount between −`amount` and `amount` degrees (see
|
||||
/// [`jitter_copies`]).
|
||||
pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) {
|
||||
jitter_copies(copies, amount, seed, HUE_JITTER_SALT, turned);
|
||||
}
|
||||
|
||||
/// Move the saturation of each of `copies` by its own amount between −`amount` and `amount`
|
||||
/// percentage points (see [`jitter_copies`]).
|
||||
pub(crate) fn jitter_saturations(copies: &mut [Node], amount: f64, seed: u64) {
|
||||
jitter_copies(copies, amount, seed, SATURATION_JITTER_SALT, saturated);
|
||||
}
|
||||
|
||||
/// Move the brightness of each of `copies` by its own amount between −`amount` and `amount`
|
||||
/// percentage points (see [`jitter_copies`]).
|
||||
pub(crate) fn jitter_brightnesses(copies: &mut [Node], amount: f64, seed: u64) {
|
||||
jitter_copies(copies, amount, seed, BRIGHTNESS_JITTER_SALT, brightened);
|
||||
}
|
||||
|
||||
/// `c` with its brightness moved by `points` percentage points, worked out on its own components
|
||||
/// so its hue and saturation stay: RGB in HSB of its values, Gray by taking that much ink off or
|
||||
/// adding it, CMYK by changing its K over the brightness its C, M and Y leave (C, M and Y change
|
||||
/// only to go brighter than they show with no K), Lab by moving its lightness by `points` units
|
||||
/// with a and b kept. The result stays between black and full brightness. White, black and grays
|
||||
/// move too. `None` when the brightness stays as it is.
|
||||
fn brightened(c: &Color, points: f32) -> Option<Color> {
|
||||
if !points.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let by = points / 100.0;
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => {
|
||||
let [h, s, v] = vectorcraft_color::rgb_to_hsb([r, g, b]);
|
||||
let to = (v + by).clamp(0.0, 1.0);
|
||||
(to != v).then(|| {
|
||||
let [r, g, b] = vectorcraft_color::hsb_to_rgb([h, s, to]);
|
||||
Color::rgb(r, g, b)
|
||||
})
|
||||
}
|
||||
Color::Gray { k } => {
|
||||
let to = (k - by).clamp(0.0, 1.0);
|
||||
(to != k).then_some(Color::gray(to))
|
||||
}
|
||||
Color::Cmyk { c, m, y, k } => {
|
||||
// `v` is the brightness C, M and Y leave; with its K the color shows `v` × (1 − K).
|
||||
let [h, s, v] = vectorcraft_color::rgb_to_hsb([1.0 - c, 1.0 - m, 1.0 - y]);
|
||||
let shown = v * (1.0 - k);
|
||||
let to = (shown + by).clamp(0.0, 1.0);
|
||||
if to == shown {
|
||||
None
|
||||
} else if to <= v {
|
||||
// v > 0 here: to < shown would need shown > 0, and to > shown leaves to > 0.
|
||||
Some(Color::cmyk(c, m, y, (1.0 - to / v).clamp(0.0, 1.0)))
|
||||
} else {
|
||||
let [r, g, b] = vectorcraft_color::hsb_to_rgb([h, s, to]);
|
||||
Some(Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, 0.0))
|
||||
}
|
||||
}
|
||||
Color::Lab { l, a, b } => {
|
||||
let to = (l + points).clamp(0.0, 100.0);
|
||||
(to != l).then_some(Color::lab(to, a, b))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest a or b a Lab color takes.
|
||||
const LAB_AB_MAX: f64 = 127.0;
|
||||
|
||||
/// `c` with its saturation moved by `points` percentage points, worked out on its own components
|
||||
/// so its hue and brightness stay: RGB in HSB of its values, CMYK over C, M and Y with K kept, Lab
|
||||
/// by moving its chroma (the length of a and b) by `points` with its lightness and hue angle kept.
|
||||
/// The result stays between no saturation and full. `None` for a color without a hue (white,
|
||||
/// black and grays, which have no saturation to move) and for one whose saturation stays as it is
|
||||
/// (already at the end it would move past), so such a color keeps its swatch link.
|
||||
fn saturated(c: &Color, points: f32) -> Option<Color> {
|
||||
if !points.is_finite() || vectorcraft_color::recolor::Neutral::of(c).is_some() {
|
||||
return None;
|
||||
}
|
||||
let by = points / 100.0;
|
||||
let move_by = |v: [f32; 3]| {
|
||||
let [h, s, b] = vectorcraft_color::rgb_to_hsb(v);
|
||||
let to = (s + by).clamp(0.0, 1.0);
|
||||
(s > 0.0 && to != s).then(|| vectorcraft_color::hsb_to_rgb([h, to, b]))
|
||||
};
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => move_by([r, g, b]).map(|[r, g, b]| Color::rgb(r, g, b)),
|
||||
Color::Cmyk { c, m, y, k } => move_by([1.0 - c, 1.0 - m, 1.0 - y]).map(|[r, g, b]| Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, k)),
|
||||
Color::Gray { .. } => None,
|
||||
Color::Lab { l, a, b } => {
|
||||
let (a, b) = (f64::from(a), f64::from(b));
|
||||
let chroma = a.hypot(b);
|
||||
if chroma <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
// A longer chroma is cut back along the same hue angle until a and b fit; one that
|
||||
// already reaches past that does not grow.
|
||||
let fit = (LAB_AB_MAX / a.abs().max(b.abs())).max(1.0);
|
||||
let scale = ((chroma + f64::from(points)).max(0.0) / chroma).min(fit);
|
||||
(scale != 1.0).then(|| Color::lab(l, (a * scale) as f32, (b * scale) as f32))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,32 +267,36 @@ fn turned(c: &Color, degrees: f32) -> Option<Color> {
|
||||
}
|
||||
}
|
||||
|
||||
fn turn_paint(p: &mut Paint, degrees: f32) {
|
||||
/// Replace a solid paint's color with what `adjust` gives for it, dropping its swatch link. A
|
||||
/// color that comes back unchanged (an amount too small to move its components) keeps the paint
|
||||
/// and its link.
|
||||
fn recolor_paint(p: &mut Paint, adjust: &dyn Fn(&Color) -> Option<Color>) {
|
||||
if let Paint::Solid { color, .. } = p
|
||||
&& let Some(c) = turned(color, degrees)
|
||||
&& let Some(c) = adjust(color)
|
||||
&& c != *color
|
||||
{
|
||||
*p = Paint::solid(c);
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn the hue of the solid fills and strokes under `n`, its type's characters included. A
|
||||
/// Recolor the solid fills and strokes under `n` with `adjust`, its type's characters included. A
|
||||
/// mask's colors are its values, so they stay.
|
||||
fn turn_hues(n: &mut Node, degrees: f32) {
|
||||
fn recolor_solids(n: &mut Node, adjust: &dyn Fn(&Color) -> Option<Color>) {
|
||||
for it in &mut n.appearance.items {
|
||||
match it {
|
||||
AppearanceItem::Fill(f) => turn_paint(&mut f.paint, degrees),
|
||||
AppearanceItem::Stroke(s) => turn_paint(&mut s.paint, degrees),
|
||||
AppearanceItem::Fill(f) => recolor_paint(&mut f.paint, adjust),
|
||||
AppearanceItem::Stroke(s) => recolor_paint(&mut s.paint, adjust),
|
||||
}
|
||||
}
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
for r in &mut t.runs {
|
||||
turn_paint(&mut r.style.fill, degrees);
|
||||
turn_paint(&mut r.style.stroke, degrees);
|
||||
recolor_paint(&mut r.style.fill, adjust);
|
||||
recolor_paint(&mut r.style.stroke, adjust);
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
turn_hues(Arc::make_mut(c), degrees);
|
||||
recolor_solids(Arc::make_mut(c), adjust);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,6 +173,8 @@ pub fn defaults() -> &'static [Brush] {
|
||||
rotation_relative_to_path: false,
|
||||
colorization: Colorization::Tints,
|
||||
hue_jitter: 0.0,
|
||||
saturation_jitter: 0.0,
|
||||
brightness_jitter: 0.0,
|
||||
modes: None,
|
||||
}),
|
||||
},
|
||||
@@ -187,6 +189,8 @@ pub fn defaults() -> &'static [Brush] {
|
||||
rotation_relative_to_path: true,
|
||||
colorization: Colorization::None,
|
||||
hue_jitter: 0.0,
|
||||
saturation_jitter: 0.0,
|
||||
brightness_jitter: 0.0,
|
||||
modes: None,
|
||||
}),
|
||||
},
|
||||
|
||||
+86
-9
@@ -324,6 +324,22 @@ pub struct Scatter {
|
||||
/// 0 (brushes saved before there was hue jitter) leaves the colors as they are.
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub hue_jitter: f64,
|
||||
/// Saturation jitter in percent, 0 to 100: each copy moves the saturation of the solid colors it
|
||||
/// draws, after the colorization and the hue jitter, by its own amount between
|
||||
/// −`saturation_jitter` and `saturation_jitter` percentage points, keeping their hue and
|
||||
/// brightness. The stroke's path and the brush name fix the amounts, so a stroke draws the same
|
||||
/// colors every time. 0 (brushes saved before there was saturation jitter) leaves the colors as
|
||||
/// they are.
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub saturation_jitter: f64,
|
||||
/// Brightness jitter in percent, 0 to 100: each copy moves the brightness of the solid colors
|
||||
/// it draws, after the colorization and the hue and saturation jitter, by its own amount
|
||||
/// between −`brightness_jitter` and `brightness_jitter` percentage points, keeping their hue
|
||||
/// and saturation. White, black and grays move too. The stroke's path and the brush name fix
|
||||
/// the amounts, so a stroke draws the same colors every time. 0 (brushes saved before there
|
||||
/// was brightness jitter) leaves the colors as they are.
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub brightness_jitter: f64,
|
||||
/// How size, spacing, scatter and rotation vary between their two values: Fixed takes the
|
||||
/// first, Random any value between them, Pressure the first at the lightest pen pressure and
|
||||
/// the second at the heaviest, Tilt the first with the pen lying flat and the second upright,
|
||||
@@ -346,6 +362,8 @@ impl Default for Scatter {
|
||||
rotation_relative_to_path: false,
|
||||
colorization: Colorization::None,
|
||||
hue_jitter: 0.0,
|
||||
saturation_jitter: 0.0,
|
||||
brightness_jitter: 0.0,
|
||||
modes: None,
|
||||
}
|
||||
}
|
||||
@@ -356,6 +374,10 @@ impl Scatter {
|
||||
pub const RANGES: [(f64, f64); 4] = [(1.0, 10000.0), (1.0, 10000.0), (-1000.0, 1000.0), (-180.0, 180.0)];
|
||||
/// The range of [`Scatter::hue_jitter`] (°).
|
||||
pub const HUE_JITTER_RANGE: (f64, f64) = (0.0, 180.0);
|
||||
/// The range of [`Scatter::saturation_jitter`] (%).
|
||||
pub const SATURATION_JITTER_RANGE: (f64, f64) = (0.0, 100.0);
|
||||
/// The range of [`Scatter::brightness_jitter`] (%).
|
||||
pub const BRIGHTNESS_JITTER_RANGE: (f64, f64) = (0.0, 100.0);
|
||||
|
||||
/// Size, spacing, scatter and rotation, each as its (first, second) values.
|
||||
pub fn values(&self) -> [(f64, f64); 4] {
|
||||
@@ -549,6 +571,15 @@ pub struct PatternBrush {
|
||||
pub end_swatch: Option<String>,
|
||||
/// Scale in percent.
|
||||
pub scale: f64,
|
||||
/// How the scale varies along a stroke: `None` (Fixed) always `scale`; a mode that follows the
|
||||
/// pen goes from `scale` to [`Self::scale_max`] over the ranges [`Variation`] gives, as an Art
|
||||
/// brush's width does ([`ArtBrush::width_mode`]).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub scale_mode: Option<Variation>,
|
||||
/// The second scale (%) of a mode that follows the pen: at the heaviest pressure, upright, at
|
||||
/// 180° or at the wheel's far end (`scale` without one).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub scale_max: Option<f64>,
|
||||
/// Space between tiles in percent of the tile width.
|
||||
pub spacing: f64,
|
||||
pub fit: PatternFit,
|
||||
@@ -561,6 +592,15 @@ impl PatternBrush {
|
||||
/// The ranges of the scale and of the spacing (%).
|
||||
pub const SCALE_RANGE: (f64, f64) = (1.0, 10000.0);
|
||||
pub const SPACING_RANGE: (f64, f64) = (0.0, 10000.0);
|
||||
|
||||
/// The scales (%) where the pen reads 0 and 1 for the scale's mode (the lightest and the
|
||||
/// heaviest pressure, for Pressure): `scale` for both unless the scale follows the pen.
|
||||
pub fn scale_range(&self) -> (f64, f64) {
|
||||
match self.scale_mode {
|
||||
Some(m) if m.follows_pen() => (self.scale, self.scale_max.unwrap_or(self.scale)),
|
||||
_ => (self.scale, self.scale),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PatternBrush {
|
||||
@@ -584,6 +624,8 @@ impl Default for PatternBrush {
|
||||
end_frame: None,
|
||||
end_swatch: None,
|
||||
scale: 100.0,
|
||||
scale_mode: None,
|
||||
scale_max: None,
|
||||
spacing: 0.0,
|
||||
fit: PatternFit::Stretch,
|
||||
flip_along: false,
|
||||
@@ -750,6 +792,8 @@ impl Brush {
|
||||
s.scatter = within_pair(s.scatter, scatter, 0.0);
|
||||
s.rotation = within_pair(s.rotation, rotation, 0.0);
|
||||
s.hue_jitter = within(s.hue_jitter, Scatter::HUE_JITTER_RANGE, 0.0);
|
||||
s.saturation_jitter = within(s.saturation_jitter, Scatter::SATURATION_JITTER_RANGE, 0.0);
|
||||
s.brightness_jitter = within(s.brightness_jitter, Scatter::BRIGHTNESS_JITTER_RANGE, 0.0);
|
||||
s.colorization.sanitize();
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
@@ -767,6 +811,11 @@ impl Brush {
|
||||
}
|
||||
BrushKind::Pattern(p) => {
|
||||
p.scale = within(p.scale, PatternBrush::SCALE_RANGE, 100.0);
|
||||
// The scale follows the pen (its pressure, tilt, bearing, rotation or wheel) or stays fixed.
|
||||
if !p.scale_mode.is_some_and(Variation::follows_pen) {
|
||||
p.scale_mode = None;
|
||||
}
|
||||
p.scale_max = p.scale_max.map(|s| within(s, PatternBrush::SCALE_RANGE, p.scale));
|
||||
p.spacing = within(p.spacing, PatternBrush::SPACING_RANGE, 0.0);
|
||||
for frame in [&mut p.side_frame, &mut p.outer_corner_frame, &mut p.inner_corner_frame, &mut p.start_frame, &mut p.end_frame] {
|
||||
if frame.is_some_and(|f| !valid_tile_frame(f)) {
|
||||
@@ -801,6 +850,9 @@ struct ScatterOptions {
|
||||
modes: Option<[Variation; 4]>,
|
||||
rotation_relative_to_path: bool,
|
||||
colorization: Colorization,
|
||||
hue_jitter: f64,
|
||||
saturation_jitter: f64,
|
||||
brightness_jitter: f64,
|
||||
}
|
||||
|
||||
/// The Art brush fields a stroke can set for itself.
|
||||
@@ -819,6 +871,8 @@ struct ArtOptions {
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct PatternOptions {
|
||||
scale: f64,
|
||||
scale_mode: Option<Variation>,
|
||||
scale_max: Option<f64>,
|
||||
spacing: f64,
|
||||
fit: PatternFit,
|
||||
flip_along: bool,
|
||||
@@ -833,9 +887,20 @@ impl BrushKind {
|
||||
pub fn stroke_option_keys(&self) -> &'static [&'static str] {
|
||||
match self {
|
||||
BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"],
|
||||
BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"],
|
||||
BrushKind::Scatter(_) => &[
|
||||
"size",
|
||||
"spacing",
|
||||
"scatter",
|
||||
"rotation",
|
||||
"modes",
|
||||
"rotation_relative_to_path",
|
||||
"colorization",
|
||||
"hue_jitter",
|
||||
"saturation_jitter",
|
||||
"brightness_jitter",
|
||||
],
|
||||
BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"],
|
||||
BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"],
|
||||
BrushKind::Pattern(_) => &["scale", "scale_mode", "scale_max", "spacing", "fit", "flip_along", "flip_across", "colorization"],
|
||||
BrushKind::Bristle(_) => &[],
|
||||
}
|
||||
}
|
||||
@@ -858,6 +923,9 @@ impl BrushKind {
|
||||
modes: s.modes,
|
||||
rotation_relative_to_path: s.rotation_relative_to_path,
|
||||
colorization: s.colorization,
|
||||
hue_jitter: s.hue_jitter,
|
||||
saturation_jitter: s.saturation_jitter,
|
||||
brightness_jitter: s.brightness_jitter,
|
||||
}),
|
||||
BrushKind::Art(a) => serde_json::to_value(ArtOptions {
|
||||
width: a.width,
|
||||
@@ -870,6 +938,8 @@ impl BrushKind {
|
||||
}),
|
||||
BrushKind::Pattern(p) => serde_json::to_value(PatternOptions {
|
||||
scale: p.scale,
|
||||
scale_mode: p.scale_mode,
|
||||
scale_max: p.scale_max,
|
||||
spacing: p.spacing,
|
||||
fit: p.fit,
|
||||
flip_along: p.flip_along,
|
||||
@@ -890,6 +960,7 @@ impl BrushKind {
|
||||
let o: ScatterOptions = serde_json::from_value(v)?;
|
||||
(s.size, s.spacing, s.scatter, s.rotation, s.modes) = (o.size, o.spacing, o.scatter, o.rotation, o.modes);
|
||||
(s.rotation_relative_to_path, s.colorization) = (o.rotation_relative_to_path, o.colorization);
|
||||
(s.hue_jitter, s.saturation_jitter, s.brightness_jitter) = (o.hue_jitter, o.saturation_jitter, o.brightness_jitter);
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
let o: ArtOptions = serde_json::from_value(v)?;
|
||||
@@ -898,8 +969,8 @@ impl BrushKind {
|
||||
}
|
||||
BrushKind::Pattern(p) => {
|
||||
let o: PatternOptions = serde_json::from_value(v)?;
|
||||
(p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) =
|
||||
(o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization);
|
||||
(p.scale, p.scale_mode, p.scale_max, p.spacing) = (o.scale, o.scale_mode, o.scale_max, o.spacing);
|
||||
(p.fit, p.flip_along, p.flip_across, p.colorization) = (o.fit, o.flip_along, o.flip_across, o.colorization);
|
||||
}
|
||||
BrushKind::Bristle(_) => {}
|
||||
}
|
||||
@@ -1123,17 +1194,23 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
|
||||
BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name),
|
||||
BrushKind::Art(a) => warp::art(a, bp, w, stroke),
|
||||
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name),
|
||||
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
|
||||
BrushKind::Pattern(p) => warp::pattern(p, bp, w, stroke),
|
||||
};
|
||||
let colorization = brush.kind.colorization();
|
||||
for n in &mut out {
|
||||
colorize(n, colorization, &stroke.paint);
|
||||
}
|
||||
// One piece per copy, in the order the copies run along the path.
|
||||
if let BrushKind::Scatter(s) = &brush.kind
|
||||
&& s.hue_jitter > 0.0
|
||||
{
|
||||
colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name));
|
||||
if let BrushKind::Scatter(s) = &brush.kind {
|
||||
if s.hue_jitter > 0.0 {
|
||||
colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name));
|
||||
}
|
||||
if s.saturation_jitter > 0.0 {
|
||||
colorize::jitter_saturations(&mut out, s.saturation_jitter, track::seed_of(bp, &brush.name));
|
||||
}
|
||||
if s.brightness_jitter > 0.0 {
|
||||
colorize::jitter_brightnesses(&mut out, s.brightness_jitter, track::seed_of(bp, &brush.name));
|
||||
}
|
||||
}
|
||||
leave_out_brushed(doc, &mut out, &mut Known::new());
|
||||
out
|
||||
|
||||
@@ -1249,6 +1249,380 @@ fn hue_jitter_turns_type_every_colorization_and_linked_colors() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke's own hue, saturation and brightness jitter replace the brush's, as its other scatter
|
||||
/// settings do, and are kept within their ranges.
|
||||
#[test]
|
||||
fn a_strokes_own_jitter_replaces_the_brushs() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
let pink = Color::rgb(0.8, 0.4, 0.4);
|
||||
let b = sat_jittered(pink, Colorization::None, 0.0, 0.0);
|
||||
let own =
|
||||
stroke_pieces(&doc, &b, &path, &with_options(serde_json::json!({"hue_jitter": 30.0, "saturation_jitter": 40.0, "brightness_jitter": 20.0})));
|
||||
let brushed = stroke_pieces(&doc, &bri_jittered(sat_jittered(pink, Colorization::None, 30.0, 40.0), 20.0), &path, &stroke(1.0));
|
||||
assert_eq!(fill_colors(&own), fill_colors(&brushed));
|
||||
assert!(fill_colors(&own).iter().any(|c| *c != pink));
|
||||
// The brightness is part of what the stroke's own options give.
|
||||
let without = stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 30.0, 40.0), &path, &stroke(1.0));
|
||||
assert_ne!(fill_colors(&own), fill_colors(&without));
|
||||
for (key, given, kept) in [("saturation_jitter", 500.0, 100.0), ("brightness_jitter", 500.0, 100.0)] {
|
||||
let options = serde_json::Map::from_iter([(key.to_string(), serde_json::json!(given))]);
|
||||
assert_eq!(b.stroke_options_that_differ(&options).unwrap(), serde_json::Map::from_iter([(key.to_string(), serde_json::json!(kept))]));
|
||||
}
|
||||
// A stroke that sets 0 on a jittered brush draws the art's own color.
|
||||
let still =
|
||||
stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 40.0), &path, &with_options(serde_json::json!({"saturation_jitter": 0.0})));
|
||||
assert!(!still.is_empty() && fill_colors(&still).iter().all(|c| *c == pink));
|
||||
}
|
||||
|
||||
/// A scatter brush of rectangles filled `fill`, with `colorization`, `hue_jitter` and
|
||||
/// `saturation_jitter`.
|
||||
fn sat_jittered(fill: Color, colorization: Colorization, hue_jitter: f64, saturation_jitter: f64) -> Brush {
|
||||
let mut b = jittered(fill, colorization, hue_jitter);
|
||||
if let BrushKind::Scatter(s) = &mut b.kind {
|
||||
s.saturation_jitter = saturation_jitter;
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// The HSB of an RGB color's own values.
|
||||
fn rgb_hsb(c: &Color) -> [f32; 3] {
|
||||
let Color::Rgb { r, g, b } = *c else { panic!("not RGB: {c:?}") };
|
||||
vectorcraft_color::rgb_to_hsb([r, g, b])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saturation_jitter_moves_each_copy_the_same_every_time() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
// A red at 50% saturation and 80% brightness.
|
||||
let pink = Color::rgb(0.8, 0.4, 0.4);
|
||||
let b = sat_jittered(pink, Colorization::None, 0.0, 40.0);
|
||||
let out = stroke_pieces(&doc, &b, &path, &stroke(1.0));
|
||||
assert_eq!(out.len(), 20);
|
||||
assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors");
|
||||
let colors = fill_colors(&out);
|
||||
let hsb: Vec<[f32; 3]> = colors.iter().map(rgb_hsb).collect();
|
||||
// Each copy's saturation is within 40 points of 50%; its hue and brightness stay.
|
||||
assert!(hsb.iter().all(|[h, s, v]| hue_gap(*h, 0.0) < 1e-3 && (s - 0.5).abs() <= 0.4001 && near(f64::from(*v), 0.8, 1e-4)), "{hsb:?}");
|
||||
assert!(hsb.iter().any(|[_, s, _]| *s > 0.55) && hsb.iter().any(|[_, s, _]| *s < 0.45), "the copies move both ways: {hsb:?}");
|
||||
let distinct: std::collections::HashSet<String> = colors.iter().map(Color::to_hex).collect();
|
||||
assert!(distinct.len() > 10, "each copy moves by its own amount: {distinct:?}");
|
||||
// The copies stay where they were, at their size and angle.
|
||||
let plain = stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 0.0), &path, &stroke(1.0));
|
||||
let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::<Vec<_>>();
|
||||
assert_eq!(boxes(&out), boxes(&plain));
|
||||
// Another path draws other amounts.
|
||||
let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0)));
|
||||
assert_ne!(other, colors);
|
||||
// At 100 the copies reach gray or full saturation and go no further.
|
||||
let full: Vec<f32> = fill_colors(&stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 100.0), &path, &stroke(1.0)))
|
||||
.iter()
|
||||
.map(|c| rgb_hsb(c)[1])
|
||||
.collect();
|
||||
assert!(full.iter().all(|s| (0.0..=1.0).contains(s)), "{full:?}");
|
||||
assert!(full.iter().any(|s| *s < 1e-6) && full.iter().any(|s| *s > 1.0 - 1e-6), "{full:?}");
|
||||
// Saturation jitter leaves the hue jitter's amounts as they were.
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
let hue_only = fill_colors(&stroke_pieces(&doc, &sat_jittered(red, Colorization::None, 90.0, 0.0), &path, &stroke(1.0)));
|
||||
let both = fill_colors(&stroke_pieces(&doc, &sat_jittered(red, Colorization::None, 90.0, 50.0), &path, &stroke(1.0)));
|
||||
assert_eq!(both.len(), hue_only.len());
|
||||
assert_ne!(both, hue_only);
|
||||
for (b, h) in both.iter().zip(&hue_only) {
|
||||
assert!(hue_gap(rgb_hsb(b)[0], rgb_hsb(h)[0]) < 0.01, "{b:?} from {h:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saturation_jitter_of_zero_changes_nothing() {
|
||||
let pink = Color::rgb(0.8, 0.4, 0.4);
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &sat_jittered(pink, Colorization::None, 0.0, 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0));
|
||||
assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == pink));
|
||||
// A brush without saturation jitter is saved as before, and one saved before reads as 0.
|
||||
let v = serde_json::to_value(sat_jittered(pink, Colorization::None, 0.0, 0.0)).unwrap();
|
||||
assert!(v.get("saturation_jitter").is_none(), "{v}");
|
||||
let mut old = serde_json::to_value(sat_jittered(pink, Colorization::None, 0.0, 25.0)).unwrap();
|
||||
assert_eq!(old.as_object_mut().unwrap().remove("saturation_jitter"), Some(serde_json::json!(25.0)));
|
||||
let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.saturation_jitter, 0.0, "a brush saved without the key reads as 0");
|
||||
let mut with = v.clone();
|
||||
with["saturation_jitter"] = serde_json::json!(25.0);
|
||||
let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.saturation_jitter, 25.0);
|
||||
// Values outside 0..100 are clamped.
|
||||
for (given, kept) in [(250.0, 100.0), (-5.0, 0.0)] {
|
||||
let mut v = v.clone();
|
||||
v["saturation_jitter"] = serde_json::json!(given);
|
||||
let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.saturation_jitter, kept, "{given}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saturation_jitter_moves_after_the_colorization_in_each_model() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
// Tints: black art takes the blue stroke color, whose saturation then moves.
|
||||
let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
|
||||
let hsb: Vec<[f32; 3]> =
|
||||
fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::BLACK, Colorization::Tints, 0.0, 30.0), &path, &blue)).iter().map(rgb_hsb).collect();
|
||||
assert!(!hsb.is_empty() && hsb.iter().all(|[h, s, _]| hue_gap(*h, 240.0) < 1e-3 && *s >= 0.6999), "{hsb:?}");
|
||||
assert!(hsb.iter().any(|[_, s, _]| *s < 0.97), "{hsb:?}");
|
||||
// Black, white and grays have no saturation to move, in every model.
|
||||
for key in
|
||||
[Color::rgb(0.5, 0.5, 0.5), Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 0.0, 0.0, 0.5), Color::gray(0.4), Color::lab(60.0, 0.0, 0.0)]
|
||||
{
|
||||
let key = StrokeLayer::new(Paint::solid(key), 1.0);
|
||||
let moved = stroke_pieces(&doc, &sat_jittered(Color::BLACK, Colorization::Tints, 0.0, 100.0), &path, &key);
|
||||
let still = stroke_pieces(&doc, &sat_jittered(Color::BLACK, Colorization::Tints, 0.0, 0.0), &path, &key);
|
||||
assert_eq!(fill_colors(&moved), fill_colors(&still), "{key:?}");
|
||||
}
|
||||
// A process color stays a process color with its K kept, moved over its C, M and Y.
|
||||
let cmyk = fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::cmyk(0.0, 0.6, 0.6, 0.25), Colorization::None, 0.0, 30.0), &path, &stroke(1.0)));
|
||||
assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 0.6, 0.6, 0.25)), "{cmyk:?}");
|
||||
for c in &cmyk {
|
||||
let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") };
|
||||
// No cyan, as before, and magenta equal to yellow: the hue stays; the ink is within 30 points.
|
||||
assert!(k == 0.25 && near(f64::from(c), 0.0, 1e-5) && near(f64::from(m), f64::from(y), 1e-5), "{c} {m} {y} {k}");
|
||||
assert!((m - 0.6).abs() <= 0.3001, "{m}");
|
||||
}
|
||||
// A Lab color keeps its lightness and hue angle; its chroma moves within 20 of its 50.
|
||||
let lab = fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::lab(50.0, 40.0, 30.0), Colorization::None, 0.0, 20.0), &path, &stroke(1.0)));
|
||||
assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}");
|
||||
for c in &lab {
|
||||
let Color::Lab { l, a, b } = *c else { panic!("not Lab: {c:?}") };
|
||||
let chroma = f64::from(a.hypot(b));
|
||||
assert!(l == 50.0 && (chroma - 50.0).abs() <= 20.001 && near(f64::from(b.atan2(a)), 30f64.atan2(40.0), 1e-4), "{c:?}");
|
||||
}
|
||||
// A chroma that grows stops where a and b reach their largest.
|
||||
let vivid = fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::lab(50.0, 120.0, 0.0), Colorization::None, 0.0, 100.0), &path, &stroke(1.0)));
|
||||
assert!(vivid.iter().all(|c| matches!(*c, Color::Lab { a, b, .. } if (0.0..=127.0001).contains(&a) && b.abs() < 1e-4)), "{vivid:?}");
|
||||
assert!(vivid.iter().any(|c| matches!(*c, Color::Lab { a, .. } if a > 126.999)), "{vivid:?}");
|
||||
}
|
||||
|
||||
/// Saturation jitter moves type's characters and a color linked to a swatch (which loses the
|
||||
/// link); a pattern paint stays.
|
||||
#[test]
|
||||
fn saturation_jitter_moves_type_and_linked_colors() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let typed = |saturation_jitter| Brush {
|
||||
name: "s".into(),
|
||||
kind: BrushKind::Scatter(Scatter { art: type_art(red.clone(), red.clone()), saturation_jitter, ..Default::default() }),
|
||||
};
|
||||
let still = run_paints(&stroke_pieces(&doc, &typed(0.0), &path, &stroke(1.0)));
|
||||
let moved = run_paints(&stroke_pieces(&doc, &typed(60.0), &path, &stroke(1.0)));
|
||||
assert!(!still.is_empty() && still.iter().all(|p| *p == (red.clone(), red.clone())), "{still:?}");
|
||||
assert_eq!(moved.len(), still.len());
|
||||
assert!(moved.iter().any(|p| *p != (red.clone(), red.clone())), "the characters move: {moved:?}");
|
||||
assert!(moved.iter().all(|(f, s)| f == s), "a copy's character fill and stroke move by the same amount: {moved:?}");
|
||||
let linked = Paint::Solid { color: Color::rgb(0.8, 0.4, 0.4), swatch: Some("Rose".into()), tint: 1.0 };
|
||||
let pattern = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY };
|
||||
let mut art = rect_art(10.0, 4.0);
|
||||
art.appearance.set_fill(linked.clone());
|
||||
art.appearance.set_stroke(pattern.clone());
|
||||
let b = |saturation_jitter| Brush {
|
||||
name: "s".into(),
|
||||
kind: BrushKind::Scatter(Scatter { art: art.clone(), saturation_jitter, ..Default::default() }),
|
||||
};
|
||||
let moved = stroke_pieces(&doc, &b(50.0), &path, &stroke(1.0));
|
||||
assert!(!moved.is_empty());
|
||||
assert!(moved.iter().any(|n| n.appearance.fill_paint().color() != Some(Color::rgb(0.8, 0.4, 0.4))), "the linked color moves");
|
||||
for n in &moved {
|
||||
assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint());
|
||||
assert_eq!(n.appearance.stroke().map(|s| &s.paint), Some(&pattern));
|
||||
}
|
||||
}
|
||||
|
||||
/// `b` (a scatter brush) with `brightness_jitter`.
|
||||
fn bri_jittered(mut b: Brush, brightness_jitter: f64) -> Brush {
|
||||
if let BrushKind::Scatter(s) = &mut b.kind {
|
||||
s.brightness_jitter = brightness_jitter;
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brightness_jitter_moves_each_copy_the_same_every_time() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
// A red at 50% saturation and 80% brightness.
|
||||
let pink = Color::rgb(0.8, 0.4, 0.4);
|
||||
let b = bri_jittered(sat_jittered(pink, Colorization::None, 0.0, 0.0), 15.0);
|
||||
let out = stroke_pieces(&doc, &b, &path, &stroke(1.0));
|
||||
assert_eq!(out.len(), 20);
|
||||
assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors");
|
||||
let colors = fill_colors(&out);
|
||||
let hsb: Vec<[f32; 3]> = colors.iter().map(rgb_hsb).collect();
|
||||
// Each copy's brightness is within 15 points of 80%; its hue and saturation stay.
|
||||
assert!(hsb.iter().all(|[h, s, v]| hue_gap(*h, 0.0) < 1e-3 && near(f64::from(*s), 0.5, 1e-4) && (v - 0.8).abs() <= 0.1501), "{hsb:?}");
|
||||
assert!(hsb.iter().any(|[_, _, v]| *v > 0.85) && hsb.iter().any(|[_, _, v]| *v < 0.75), "the copies move both ways: {hsb:?}");
|
||||
let distinct: std::collections::HashSet<String> = colors.iter().map(Color::to_hex).collect();
|
||||
assert!(distinct.len() > 10, "each copy moves by its own amount: {distinct:?}");
|
||||
// The copies stay where they were, at their size and angle.
|
||||
let plain = stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 0.0), &path, &stroke(1.0));
|
||||
let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::<Vec<_>>();
|
||||
assert_eq!(boxes(&out), boxes(&plain));
|
||||
// Another path draws other amounts.
|
||||
let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0)));
|
||||
assert_ne!(other, colors);
|
||||
// At 100 the copies reach black or full brightness and go no further.
|
||||
let full: Vec<f32> =
|
||||
fill_colors(&stroke_pieces(&doc, &bri_jittered(sat_jittered(pink, Colorization::None, 0.0, 0.0), 100.0), &path, &stroke(1.0)))
|
||||
.iter()
|
||||
.map(|c| rgb_hsb(c)[2])
|
||||
.collect();
|
||||
assert!(full.iter().all(|v| (0.0..=1.0).contains(v)), "{full:?}");
|
||||
assert!(full.iter().any(|v| *v < 1e-6) && full.iter().any(|v| *v > 1.0 - 1e-6), "{full:?}");
|
||||
// Brightness jitter leaves the hue and saturation jitter's amounts as they were.
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
let hue_sat = fill_colors(&stroke_pieces(&doc, &sat_jittered(red, Colorization::None, 90.0, 50.0), &path, &stroke(1.0)));
|
||||
let all = fill_colors(&stroke_pieces(&doc, &bri_jittered(sat_jittered(red, Colorization::None, 90.0, 50.0), 30.0), &path, &stroke(1.0)));
|
||||
assert_eq!(all.len(), hue_sat.len());
|
||||
assert_ne!(all, hue_sat);
|
||||
for (a, h) in all.iter().zip(&hue_sat) {
|
||||
let ([ha, sa, _], [hh, sh, _]) = (rgb_hsb(a), rgb_hsb(h));
|
||||
assert!(hue_gap(ha, hh) < 0.01 && (sa - sh).abs() < 1e-4, "{a:?} from {h:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brightness_jitter_of_zero_changes_nothing() {
|
||||
let pink = Color::rgb(0.8, 0.4, 0.4);
|
||||
let plain = sat_jittered(pink, Colorization::None, 0.0, 0.0);
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &bri_jittered(plain.clone(), 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0));
|
||||
assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == pink));
|
||||
// A brush without brightness jitter is saved as before, and one saved before reads as 0.
|
||||
let v = serde_json::to_value(&plain).unwrap();
|
||||
assert!(v.get("brightness_jitter").is_none(), "{v}");
|
||||
let mut old = serde_json::to_value(bri_jittered(plain.clone(), 25.0)).unwrap();
|
||||
assert_eq!(old.as_object_mut().unwrap().remove("brightness_jitter"), Some(serde_json::json!(25.0)));
|
||||
let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.brightness_jitter, 0.0, "a brush saved without the key reads as 0");
|
||||
let mut with = v.clone();
|
||||
with["brightness_jitter"] = serde_json::json!(25.0);
|
||||
let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.brightness_jitter, 25.0);
|
||||
// Values outside 0..100 are clamped.
|
||||
for (given, kept) in [(250.0, 100.0), (-5.0, 0.0)] {
|
||||
let mut v = v.clone();
|
||||
v["brightness_jitter"] = serde_json::json!(given);
|
||||
let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.brightness_jitter, kept, "{given}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brightness_jitter_moves_after_the_colorization_in_each_model() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
let jittered_fills = |art: Color, colorization: Colorization, amount: f64, key: &StrokeLayer| {
|
||||
fill_colors(&stroke_pieces(&doc, &bri_jittered(sat_jittered(art, colorization, 0.0, 0.0), amount), &path, key))
|
||||
};
|
||||
// Tints: black art takes the blue stroke color, whose brightness then moves.
|
||||
let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
|
||||
let hsb: Vec<[f32; 3]> = jittered_fills(Color::BLACK, Colorization::Tints, 30.0, &blue).iter().map(rgb_hsb).collect();
|
||||
assert!(!hsb.is_empty() && hsb.iter().all(|[h, s, v]| hue_gap(*h, 240.0) < 1e-3 && near(f64::from(*s), 1.0, 1e-4) && *v >= 0.6999), "{hsb:?}");
|
||||
assert!(hsb.iter().any(|[_, _, v]| *v < 0.97), "{hsb:?}");
|
||||
// White, black and grays move too, and stay neutral. RGB white gets darker.
|
||||
let white: Vec<[f32; 3]> = jittered_fills(Color::WHITE, Colorization::None, 30.0, &stroke(1.0)).iter().map(rgb_hsb).collect();
|
||||
assert!(white.iter().all(|[_, s, v]| *s == 0.0 && *v >= 0.6999) && white.iter().any(|[_, _, v]| *v < 0.95), "{white:?}");
|
||||
// A gray's ink moves within 20 points of its 40%.
|
||||
let gray = StrokeLayer::new(Paint::solid(Color::gray(0.4)), 1.0);
|
||||
let grays = jittered_fills(Color::BLACK, Colorization::Tints, 20.0, &gray);
|
||||
assert!(grays.iter().all(|c| matches!(*c, Color::Gray { k } if (k - 0.4).abs() <= 0.2001)), "{grays:?}");
|
||||
assert!(grays.iter().any(|c| *c != Color::gray(0.4)), "{grays:?}");
|
||||
// Black ink alone stays black ink alone, lighter by its K.
|
||||
let k_only = jittered_fills(Color::cmyk(0.0, 0.0, 0.0, 1.0), Colorization::None, 30.0, &stroke(1.0));
|
||||
assert!(k_only.iter().all(|c| matches!(*c, Color::Cmyk { c, m, y, k } if c == 0.0 && m == 0.0 && y == 0.0 && k >= 0.6999)), "{k_only:?}");
|
||||
assert!(k_only.iter().any(|c| matches!(*c, Color::Cmyk { k, .. } if k < 0.97)), "{k_only:?}");
|
||||
// A process color with room in its K moves by its K and keeps its C, M and Y.
|
||||
let cmyk = jittered_fills(Color::cmyk(0.0, 0.6, 0.6, 0.25), Colorization::None, 20.0, &stroke(1.0));
|
||||
assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 0.6, 0.6, 0.25)), "{cmyk:?}");
|
||||
for c in &cmyk {
|
||||
let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") };
|
||||
assert!(c == 0.0 && m == 0.6 && y == 0.6 && (k - 0.25).abs() <= 0.2001, "{c} {m} {y} {k}");
|
||||
}
|
||||
// One brighter than its C, M and Y show with no K loses its K and takes less ink, its hue and
|
||||
// saturation kept (full magenta and yellow, cyan the brightness).
|
||||
let deep = jittered_fills(Color::cmyk(0.4, 1.0, 1.0, 0.0), Colorization::None, 30.0, &stroke(1.0));
|
||||
let mut ways = (false, false);
|
||||
for c in &deep {
|
||||
let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") };
|
||||
assert!(near(f64::from(m), 1.0, 1e-5) && near(f64::from(y), 1.0, 1e-5), "{c} {m} {y} {k}");
|
||||
if k > 0.0 {
|
||||
assert!(c == 0.4 && k <= 0.5001, "darker: {c} {k}");
|
||||
ways.0 = true;
|
||||
} else {
|
||||
assert!((0.0999..=0.4).contains(&c), "brighter: {c}");
|
||||
ways.1 |= c < 0.4;
|
||||
}
|
||||
}
|
||||
assert!(ways.0 && ways.1, "the copies move both ways: {deep:?}");
|
||||
// A Lab color keeps its a and b; its lightness moves within 20 of its 50.
|
||||
let lab = jittered_fills(Color::lab(50.0, 40.0, 30.0), Colorization::None, 20.0, &stroke(1.0));
|
||||
assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}");
|
||||
assert!(lab.iter().all(|c| matches!(*c, Color::Lab { l, a, b } if a == 40.0 && b == 30.0 && (l - 50.0).abs() <= 20.001)), "{lab:?}");
|
||||
}
|
||||
|
||||
/// A swatch-linked color already at the end a copy's saturation or brightness moves toward stays as
|
||||
/// it is and keeps its link; the copies that move it lose the link.
|
||||
#[test]
|
||||
fn jitter_at_a_limit_keeps_the_swatch_link() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
// Full red (full saturation and brightness), full magenta and yellow ink, and a Lab red whose a
|
||||
// is at its largest: saturation that grows and brightness that grows leave them as they are.
|
||||
for (color, saturation_jitter, brightness_jitter) in [
|
||||
(Color::rgb(1.0, 0.0, 0.0), 50.0, 0.0),
|
||||
(Color::cmyk(0.0, 1.0, 1.0, 0.0), 50.0, 0.0),
|
||||
(Color::lab(50.0, 127.0, 0.0), 50.0, 0.0),
|
||||
(Color::rgb(1.0, 0.0, 0.0), 0.0, 50.0),
|
||||
(Color::lab(100.0, 20.0, 10.0), 0.0, 50.0),
|
||||
] {
|
||||
let linked = Paint::Solid { color, swatch: Some("Spot".into()), tint: 1.0 };
|
||||
let mut art = rect_art(10.0, 4.0);
|
||||
art.appearance.set_fill(linked.clone());
|
||||
let mut s = Scatter { art, saturation_jitter, ..Default::default() };
|
||||
s.brightness_jitter = brightness_jitter;
|
||||
let out = stroke_pieces(&doc, &Brush { name: "s".into(), kind: BrushKind::Scatter(s) }, &path, &stroke(1.0));
|
||||
let (mut kept, mut moved) = (0, 0);
|
||||
for n in &out {
|
||||
match n.appearance.fill_paint() {
|
||||
p if p == linked => kept += 1,
|
||||
Paint::Solid { color: c, swatch: None, .. } if c != color => moved += 1,
|
||||
p => panic!("{color:?}: {p:?}"),
|
||||
}
|
||||
}
|
||||
assert!(kept > 0 && moved > 0, "{color:?}: {kept} kept, {moved} moved");
|
||||
}
|
||||
}
|
||||
|
||||
/// A hue or saturation jitter too small to move a Lab color's components gives each copy the color
|
||||
/// it had, and the copies keep the swatch link.
|
||||
#[test]
|
||||
fn jitter_too_small_to_change_a_color_keeps_the_swatch_link() {
|
||||
let linked = Paint::Solid { color: Color::lab(50.0, 64.0, 0.0), swatch: Some("Spot".into()), tint: 1.0 };
|
||||
// 1e-50 degrees turns a and b by less than an f32 holds; 1e-6 points scales the chroma by
|
||||
// 1 + 1.6e-8, which rounds back to the same f32 components.
|
||||
type Jitter = fn(&mut [Node], f64, u64);
|
||||
let jitters: [(&str, Jitter, f64); 2] = [("hue", crate::colorize::jitter_hues, 1e-50), ("saturation", crate::colorize::jitter_saturations, 1e-6)];
|
||||
for (name, jitter, amount) in jitters {
|
||||
let mut copies: Vec<Node> = (0..8)
|
||||
.map(|_| {
|
||||
let mut art = rect_art(10.0, 4.0);
|
||||
art.appearance.set_fill(linked.clone());
|
||||
art
|
||||
})
|
||||
.collect();
|
||||
jitter(&mut copies, amount, 7);
|
||||
for n in &copies {
|
||||
assert_eq!(n.appearance.fill_paint(), linked, "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its
|
||||
/// swatch links.
|
||||
#[test]
|
||||
@@ -2031,6 +2405,374 @@ fn art_brush_width_follows_tilt_bearing_and_rotation() {
|
||||
assert_eq!(modes, [Some(Variation::Tilt), Some(Variation::Bearing), Some(Variation::Rotation), None]);
|
||||
}
|
||||
|
||||
/// A pattern brush with `scale`, `scale_mode` and `scale_max`, its 10 × 4 pt side tile on `fit`.
|
||||
fn scaled_pattern(fit: PatternFit, corners: bool, scale: f64, mode: Option<Variation>, max: Option<f64>) -> Brush {
|
||||
let mut b = pattern_brush(fit, corners);
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
(p.scale, p.scale_mode, p.scale_max) = (scale, mode, max);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// The bounds of each piece, left to right.
|
||||
fn piece_spans(out: &[Node]) -> Vec<Rect> {
|
||||
let mut spans: Vec<Rect> = out.iter().filter_map(Node::geometric_bounds).collect();
|
||||
spans.sort_by(|a, b| a.x0.total_cmp(&b.x0));
|
||||
spans
|
||||
}
|
||||
|
||||
/// Pattern Brush Options: with Scale on Pressure the tiles go from Scale at the lightest pen
|
||||
/// pressure to the second scale at the heaviest, taller and longer along the stroke where the pen
|
||||
/// pressed harder, and each Fit still fits them to the path.
|
||||
#[test]
|
||||
fn pattern_brush_scale_follows_the_pressure() {
|
||||
let bp = line(0.0, 0.0, 200.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 tall tiles at 50 %: 1 pt either side at the lightest; at 300 %: 6 pt at the heaviest.
|
||||
let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, 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, 199.0, 200.0), 6.0, 0.2), "{}", half_width(&out, 199.0, 200.0));
|
||||
assert!(near(half_width(&out, 99.0, 101.0), 3.5, 0.2), "{}", half_width(&out, 99.0, 101.0));
|
||||
// Stretch to Fit fills the path, and the tiles grow longer along it.
|
||||
let spans = piece_spans(&out);
|
||||
assert!(near(bounds(&out).x0, 0.0, 1e-6) && near(bounds(&out).x1, 200.0, 1e-6), "{:?}", bounds(&out));
|
||||
assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{spans:?}");
|
||||
assert!(spans.last().unwrap().width() > 4.0 * spans[0].width(), "{spans:?}");
|
||||
// The stroke weight scales it.
|
||||
let out =
|
||||
draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &StrokeLayer { width: 2.0, ..ramp.clone() });
|
||||
assert!(near(half_width(&out, 199.0, 200.0), 12.0, 0.4), "{}", half_width(&out, 199.0, 200.0));
|
||||
// Without recorded pressure, half way between the two scales.
|
||||
let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &stroke(1.0));
|
||||
assert!(near(bounds(&out).height(), 7.0, 1e-6), "{:?}", bounds(&out));
|
||||
// With an even pressure, Add Space with spacing places as many tiles as the one scale that
|
||||
// pressure gives: the spacing counts when the tiles are counted again.
|
||||
let even = pressed(vec![(0.0, 0.5), (1.0, 0.5)]);
|
||||
let spaced = |mode: Option<Variation>, max: Option<f64>| {
|
||||
let mut b = scaled_pattern(PatternFit::AddSpace, false, if max.is_some() { 50.0 } else { 100.0 }, mode, max);
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
p.spacing = 100.0;
|
||||
}
|
||||
piece_spans(&draw(&b, &even)).len()
|
||||
};
|
||||
assert_eq!(spaced(Some(Variation::Pressure), Some(150.0)), spaced(None, None));
|
||||
// With spacing, Stretch to Fit still fills the path and Approximate Path still centers the
|
||||
// tiles, with the gaps between them counted and none after the last.
|
||||
for fit in [PatternFit::Stretch, PatternFit::Approximate] {
|
||||
let mut b = scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
p.spacing = 50.0;
|
||||
}
|
||||
let spans = piece_spans(&draw(&b, &ramp));
|
||||
let (first, last) = (spans[0], spans[spans.len() - 1]);
|
||||
assert!(spans.len() > 1 && near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{fit:?}: {spans:?}");
|
||||
if fit == PatternFit::Stretch {
|
||||
assert!(near(first.x0, 0.0, 1e-6) && near(last.x1, 200.0, 1e-6), "{spans:?}");
|
||||
}
|
||||
}
|
||||
// Add Space to Fit keeps the tiles apart within the path; Approximate Path centers them on it.
|
||||
for fit in [PatternFit::AddSpace, PatternFit::Approximate] {
|
||||
let out = draw(&scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp);
|
||||
let spans = piece_spans(&out);
|
||||
assert!(spans.len() > 1 && spans.windows(2).all(|w| w[1].x0 >= w[0].x1 - 1e-6), "{fit:?}: {spans:?}");
|
||||
assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{fit:?}: {spans:?}");
|
||||
let (first, last) = (spans[0], spans[spans.len() - 1]);
|
||||
if fit == PatternFit::AddSpace {
|
||||
assert!(first.x0 >= -1e-6 && last.x1 <= 200.0 + 1e-6, "{spans:?}");
|
||||
} else {
|
||||
assert!(near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{spans:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pattern Brush Options: Scale on Tilt, Bearing, Rotation or Stylus Wheel reads only its own
|
||||
/// input, half way without it; Fixed, a mode without a second scale and equal scales draw as a
|
||||
/// brush without the setting does.
|
||||
#[test]
|
||||
fn pattern_brush_scale_follows_tilt_bearing_rotation_and_the_wheel() {
|
||||
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 brush = |mode: Variation| scaled_pattern(PatternFit::Stretch, false, 50.0, Some(mode), Some(300.0));
|
||||
let wheel = |v: f64| StrokeLayer { wheel: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, v), (1.0, v)] }), ..stroke(1.0) };
|
||||
// 4 pt tiles: 2 pt tall at 50 %, 12 pt at 300 %.
|
||||
for (mode, st, height) in [
|
||||
(Variation::Tilt, posed(Some(0.0), None, None), 12.0),
|
||||
(Variation::Tilt, posed(Some(1.0), None, None), 2.0),
|
||||
(Variation::Bearing, posed(Some(0.5), Some(90.0), None), 9.5),
|
||||
(Variation::Rotation, posed(None, None, Some(-90.0)), 4.5),
|
||||
(Variation::StylusWheel, wheel(1.0), 12.0),
|
||||
(Variation::StylusWheel, wheel(0.0), 2.0),
|
||||
// Without its own input, half way.
|
||||
(Variation::Tilt, posed(None, Some(90.0), Some(90.0)), 7.0),
|
||||
(Variation::Bearing, posed(Some(0.0), None, Some(90.0)), 7.0),
|
||||
(Variation::Rotation, posed(Some(0.0), Some(90.0), None), 7.0),
|
||||
(Variation::StylusWheel, pressed(vec![(0.0, 1.0), (1.0, 1.0)]), 7.0),
|
||||
(Variation::Pressure, posed(Some(0.0), Some(90.0), Some(90.0)), 7.0),
|
||||
] {
|
||||
let h = bounds(&draw(&brush(mode), &st)).height();
|
||||
assert!(near(h, height, 1e-6), "{mode:?}: {h}");
|
||||
}
|
||||
// Fixed, a mode without a second scale, and a second scale equal to the first draw what the
|
||||
// brush draws without them.
|
||||
let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]);
|
||||
let plain = draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &ramp);
|
||||
for (mode, max) in [(None, Some(300.0)), (Some(Variation::Pressure), None), (Some(Variation::Pressure), Some(50.0))] {
|
||||
assert_eq!(draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, mode, max), &ramp), plain, "{mode:?} {max:?}");
|
||||
}
|
||||
let saved = serde_json::to_value(scaled_pattern(PatternFit::Stretch, false, 50.0, None, None)).unwrap();
|
||||
assert!(saved.get("scale_mode").is_none() && saved.get("scale_max").is_none(), "{saved}");
|
||||
// A mode the scale does not take is read as Fixed, and the second scale is kept within range.
|
||||
let lib = parse_library(&serde_json::json!([
|
||||
{"name": "a", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "random", "scale_max": 1e308},
|
||||
{"name": "b", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "stylusWheel", "scale_max": 0.0},
|
||||
]));
|
||||
let [BrushKind::Pattern(a), BrushKind::Pattern(b)] = [&lib[0].kind, &lib[1].kind] else { panic!("{lib:?}") };
|
||||
assert_eq!((a.scale_mode, a.scale_max, b.scale_mode, b.scale_max), (None, Some(10000.0), Some(Variation::StylusWheel), Some(1.0)));
|
||||
// A stroke sets its own mode and second scale.
|
||||
let mut own = serde_json::Map::new();
|
||||
own.insert("scale_mode".into(), serde_json::json!("pressure"));
|
||||
own.insert("scale_max".into(), serde_json::json!(300.0));
|
||||
let edited = scaled_pattern(PatternFit::Stretch, false, 100.0, None, None).with_stroke_options(&own).unwrap();
|
||||
assert!(matches!(&edited.kind, BrushKind::Pattern(p) if p.scale_range() == (100.0, 300.0)), "{edited:?}");
|
||||
}
|
||||
|
||||
/// A pattern brush whose scale follows the pen keeps its start, end and corner tiles at the scale
|
||||
/// where they are, on open and closed paths, and stays finite at the ends of the scale's range.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_places_start_end_and_corner_tiles() {
|
||||
let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]);
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
// Start and end tiles, 6 × 4 pt: the start tile at the light end is smaller than the end tile.
|
||||
let mut ends = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
if let BrushKind::Pattern(p) = &mut ends.kind {
|
||||
(p.start, p.end) = (Some(rect_art(6.0, 4.0)), Some(rect_art(6.0, 4.0)));
|
||||
}
|
||||
let out = stroke_pieces(&doc, &ends, &line(0.0, 0.0, 200.0, 0.0), &ramp);
|
||||
let (start, end) = (out[0].geometric_bounds().unwrap(), out[1].geometric_bounds().unwrap());
|
||||
assert!(near(start.x0, 0.0, 1e-6) && near(end.x1, 200.0, 1e-6), "{start:?} {end:?}");
|
||||
assert!(start.width() < 3.5 && end.width() > 17.0 && start.height() < end.height() / 4.0, "{start:?} {end:?}");
|
||||
// A closed rectangle with corner tiles, on each Fit, and the scale's range at its ends.
|
||||
let mut rect = BezPath::new();
|
||||
rect.move_to((0.0, 0.0));
|
||||
rect.line_to((100.0, 0.0));
|
||||
rect.line_to((100.0, 60.0));
|
||||
rect.line_to((0.0, 60.0));
|
||||
rect.close_path();
|
||||
for fit in [PatternFit::Stretch, PatternFit::AddSpace, PatternFit::Approximate] {
|
||||
for (scale, max) in [(50.0, 300.0), (1.0, 10000.0), (10000.0, 1.0)] {
|
||||
for bp in [&rect, &line(0.0, 0.0, 3.0, 0.0)] {
|
||||
let b = scaled_pattern(fit, true, scale, Some(Variation::Pressure), Some(max));
|
||||
let out = stroke_pieces(&doc, &b, bp, &ramp);
|
||||
assert!(!out.is_empty(), "{fit:?} {scale} {max}");
|
||||
let r = bounds(&out);
|
||||
assert!([r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()), "{fit:?} {scale} {max}: {r:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// On the rectangle the corner tiles grow with the pressure: the first corner's tile is smaller
|
||||
// than the last one's.
|
||||
let b = scaled_pattern(PatternFit::Stretch, true, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
let out = stroke_pieces(&doc, &b, &rect, &ramp);
|
||||
let fixed = stroke_pieces(&doc, &scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &rect, &ramp);
|
||||
assert_ne!(out, fixed);
|
||||
let corner = |n: &Node| n.geometric_bounds().map_or(0.0, |r| r.width().max(r.height()));
|
||||
let corners: Vec<f64> = out.iter().take(4).map(corner).collect();
|
||||
assert!(corners[0] < corners[3], "{corners:?}");
|
||||
// The side tiles start half the corner tile beside them away from the corner: 1.5 pt from the
|
||||
// first corner, where the 6 pt corner tile is drawn at 50 %, not half the largest corner tile.
|
||||
let first_side = out.get(4).and_then(Node::geometric_bounds);
|
||||
assert!(first_side.is_some_and(|r| near(r.x0, 1.5, 1e-3)), "{first_side:?}");
|
||||
}
|
||||
|
||||
/// A start or end tile whose scale follows the pen is placed where it is as long as the scale at
|
||||
/// its middle, even when the scale rises again further along and the tile would not fit at the
|
||||
/// whole run's length.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_fits_start_and_end_tiles_where_the_scale_falls_back() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let bp = line(0.0, 0.0, 100.0, 0.0);
|
||||
// From 100 % to 10000 %: 300 % from 5 to 20 pt, 10000 % from 50 pt on; mirrored for the end.
|
||||
let q = 2.0 / 99.0;
|
||||
for (start, points, span) in [
|
||||
(true, vec![(0.0, 0.0), (0.05, q), (0.2, q), (0.5, 1.0), (1.0, 1.0)], (0.0, 18.0)),
|
||||
(false, vec![(0.0, 1.0), (0.5, 1.0), (0.8, q), (0.95, q), (1.0, 0.0)], (82.0, 100.0)),
|
||||
] {
|
||||
let mut b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(10000.0));
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
let tile = Some(rect_art(6.0, 4.0));
|
||||
(p.start, p.end) = if start { (tile, None) } else { (None, tile) };
|
||||
}
|
||||
// The 6 pt tile at 300 %: 18 pt long, its middle where the scale is 300 %.
|
||||
let out = stroke_pieces(&doc, &b, &bp, &pressed(points));
|
||||
let r = out.first().and_then(Node::geometric_bounds);
|
||||
assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}");
|
||||
}
|
||||
// 400 % at the start, 100 % from 15 to 20 pt, 400 % from 40 pt on, mirrored for the end: a 30 pt
|
||||
// tile at 100 % fits at its middle, although at the scale at its first length's middle it is as
|
||||
// long as that length.
|
||||
for (start, points, span) in [
|
||||
(true, vec![(0.0, 1.0), (0.15, 0.0), (0.2, 0.0), (0.4, 1.0), (1.0, 1.0)], (0.0, 30.0)),
|
||||
(false, vec![(0.0, 1.0), (0.6, 1.0), (0.8, 0.0), (0.85, 0.0), (1.0, 1.0)], (70.0, 100.0)),
|
||||
] {
|
||||
let mut b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(400.0));
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
let tile = Some(rect_art(30.0, 4.0));
|
||||
(p.start, p.end) = if start { (tile, None) } else { (None, tile) };
|
||||
}
|
||||
let out = stroke_pieces(&doc, &b, &bp, &pressed(points));
|
||||
let r = out.first().and_then(Node::geometric_bounds);
|
||||
assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// How far from y = 0 the outlines under `nodes` reach where they cross the vertical line at `x`.
|
||||
fn reach_at(nodes: &[Node], x: f64) -> f64 {
|
||||
let mut reach = 0.0f64;
|
||||
for n in nodes {
|
||||
n.walk(&mut |c| {
|
||||
for sp in c.path_data().into_iter().flat_map(|p| &p.subpaths) {
|
||||
for i in 0..sp.segment_count() {
|
||||
let s = sp.segment(i);
|
||||
let (a, b, c, d) = (s.p0.x, s.p1.x, s.p2.x, s.p3.x);
|
||||
let roots = kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (c - 2.0 * b + a), d - 3.0 * c + 3.0 * b - a);
|
||||
for t in roots.into_iter().filter(|t| (-1e-9..=1.0 + 1e-9).contains(t)) {
|
||||
reach = reach.max(kurbo::ParamCurve::eval(&s, t.clamp(0.0, 1.0)).y.abs());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
reach
|
||||
}
|
||||
|
||||
/// A pattern tile whose scale follows the pen is as tall as the scale at a short peak of the
|
||||
/// pressure, even where the peak falls between the positions the bent outline is checked at.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_keeps_a_short_peak() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(300.0));
|
||||
// One 10 × 4 pt tile on a 10 pt path: 100 % (2 pt either side) but for a peak at 2.2 pt, where
|
||||
// the scale reaches 300 % (6 pt either side).
|
||||
let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]);
|
||||
let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 10.0, 0.0), &peak);
|
||||
// At the peak 300 %, half way up it 200 %, and 100 % on either side of it.
|
||||
for (x, want) in [(2.2, 6.0), (2.15, 4.0), (2.25, 4.0), (1.0, 2.0), (2.05, 2.0), (2.4, 2.0), (8.0, 2.0)] {
|
||||
assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x));
|
||||
}
|
||||
}
|
||||
|
||||
/// An art brush whose width follows the pen is as wide as the pen gives at a short peak of the
|
||||
/// pressure, even where the peak falls between the positions the bent outline is checked at.
|
||||
#[test]
|
||||
fn art_brush_width_from_the_pen_keeps_a_short_peak() {
|
||||
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) = (100.0, Some(Variation::Pressure), Some(300.0));
|
||||
}
|
||||
// 4 pt art on a 100 pt path: 2 pt either side but for a peak at 22 pt, where it is 6 pt.
|
||||
let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]);
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 100.0, 0.0), &peak);
|
||||
for (x, want) in [(22.0, 6.0), (21.5, 4.0), (22.5, 4.0), (10.0, 2.0), (20.5, 2.0), (24.0, 2.0), (80.0, 2.0)] {
|
||||
assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x));
|
||||
}
|
||||
}
|
||||
|
||||
/// A pen recording sampled many times along a straight ramp draws as many anchors as the ramp's
|
||||
/// two ends do: samples that leave the scale on the same straight course are not split at.
|
||||
#[test]
|
||||
fn pen_samples_on_a_straight_ramp_add_no_anchors() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let bp = line(0.0, 0.0, 1000.0, 0.0);
|
||||
let ramp = |n: usize| pressed((0..=n).map(|i| (i as f64 / n as f64, i as f64 / n as f64)).collect());
|
||||
let anchors = |out: &[Node]| {
|
||||
let mut count = 0;
|
||||
for n in out {
|
||||
n.walk(&mut |c| count += c.path_data().map_or(0, |p| p.subpaths.iter().map(|s| s.anchors.len()).sum::<usize>()));
|
||||
}
|
||||
count
|
||||
};
|
||||
let pattern = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
let mut art = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut art.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (50.0, Some(Variation::Pressure), Some(300.0));
|
||||
}
|
||||
for b in [&pattern, &art] {
|
||||
let (few, many) = (stroke_pieces(&doc, b, &bp, &ramp(1)), stroke_pieces(&doc, b, &bp, &ramp(2000)));
|
||||
assert_eq!(anchors(&many), anchors(&few), "{}", b.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// On a closed path, a tile that Approximate Path starts before the path's start takes the scale
|
||||
/// recorded at the end of the stroke there, where the tile is drawn.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_wraps_before_a_closed_paths_start() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let b = scaled_pattern(PatternFit::Approximate, false, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
// Light over the first 90 % of the stroke, heavy at its end.
|
||||
let st = pressed(vec![(0.0, 0.0), (0.9, 0.0), (1.0, 1.0)]);
|
||||
let mut before = 0;
|
||||
for r in (100..=120).map(f64::from) {
|
||||
// A circle of radius `r` as 720 sides, from (r, 0) on towards +y.
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((r, 0.0));
|
||||
for i in 1..720 {
|
||||
let a = std::f64::consts::TAU * f64::from(i) / 720.0;
|
||||
bp.line_to((r * a.cos(), r * a.sin()));
|
||||
}
|
||||
bp.close_path();
|
||||
let out = stroke_pieces(&doc, &b, &bp, &st);
|
||||
let Some(first) = out.first().and_then(Node::geometric_bounds) else { panic!("{r}: no tiles") };
|
||||
if first.y0 < -0.5 {
|
||||
// The 4 pt tall tile is 2 pt tall at the light 50 % and nearly 12 pt at the heavy end.
|
||||
before += 1;
|
||||
assert!(first.x1 > r + 3.0, "{r}: {first:?}");
|
||||
}
|
||||
}
|
||||
assert!(before > 0, "no first tile starts before the path's start");
|
||||
}
|
||||
|
||||
/// On a closed path, a tile over the path's start follows the scale on both sides of the start,
|
||||
/// even when the scale is the same at the tile's ends, its middle and every pen sample within it.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_changes_where_a_closed_path_wraps_round() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let mut b = scaled_pattern(PatternFit::Approximate, false, 100.0, Some(Variation::Pressure), Some(300.0));
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
p.side = rect_art(54.0, 4.0);
|
||||
}
|
||||
// A closed path 256 pt long without corners, from (0, 0) along +x: its sides in each quarter
|
||||
// turn, and the same turned three more times.
|
||||
let quarter = [(28.0, 0.0), (12.0, 5.0), (4.0, 3.0), (3.0, 4.0), (5.0, 12.0)];
|
||||
let mut bp = BezPath::new();
|
||||
let mut at = (0.0, 0.0);
|
||||
bp.move_to(at);
|
||||
for turn in 0..4 {
|
||||
for &(x, y) in &quarter {
|
||||
let (dx, dy) = match turn {
|
||||
0 => (x, y),
|
||||
1 => (-y, x),
|
||||
2 => (-x, -y),
|
||||
_ => (y, -x),
|
||||
};
|
||||
at = (at.0 + dx, at.1 + dy);
|
||||
if at != (0.0, 0.0) {
|
||||
bp.line_to(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
bp.close_path();
|
||||
// 100 % up to 4 pt before the end, rising to 300 % at the end. Approximate Path places five
|
||||
// 54 pt tiles, the first from 7 pt before the start: at 100 % at both its ends, its middle and
|
||||
// the samples at 4 pt before the start and at the start, but larger from 4 pt before it.
|
||||
let st = pressed(vec![(0.0, 0.0), (252.0 / 256.0, 0.0), (1.0, 1.0)]);
|
||||
let out = stroke_pieces(&doc, &b, &bp, &st);
|
||||
let Some(first) = out.first().and_then(Node::geometric_bounds) else { panic!("no tiles") };
|
||||
// The 4 pt tall tile is 2 pt either side of the path at 100 %, and 5 pt at 1 pt before the
|
||||
// start, where the scale is 250 %.
|
||||
assert!(first.y0 < -3.5, "{first:?}");
|
||||
}
|
||||
|
||||
/// Definitions from files and commands are kept within their ranges.
|
||||
#[test]
|
||||
fn sanitize_keeps_values_within_their_ranges() {
|
||||
|
||||
+435
-40
@@ -40,23 +40,32 @@ const MASK_STEPS: usize = 32;
|
||||
/// through the bend to within [`fit_tol`] of `doc_tol`, the flattening tolerance in document
|
||||
/// space, so the art keeps its curves (#3926). Where that cannot be done in no more anchors than
|
||||
/// chords would take, the path is flattened with `flat_tol` (art space) and subdivided so no chord
|
||||
/// is longer than `max_du` along x, as it always was. Stroke widths scale by `width_scale`.
|
||||
/// Text, images and symbol instances can't bend and are dropped. The art of a linked opacity mask
|
||||
/// bends with the object it masks.
|
||||
pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, doc_tol: f64, width_scale: f64) -> Option<Node> {
|
||||
/// is longer than `max_du` along x, as it always was. Both routes also split the art where it
|
||||
/// crosses each of `breaks` (art x, in order), so a turn of the map there is not stepped over.
|
||||
/// Stroke widths scale by `width_scale`. Text, images and symbol instances can't bend and are
|
||||
/// dropped. The art of a linked opacity mask bends with the object it masks.
|
||||
pub(crate) fn warp_node(
|
||||
n: &Node,
|
||||
f: &dyn Fn(Point) -> Point,
|
||||
flat_tol: f64,
|
||||
max_du: f64,
|
||||
doc_tol: f64,
|
||||
width_scale: f64,
|
||||
breaks: &[f64],
|
||||
) -> Option<Node> {
|
||||
let mut out = n.clone();
|
||||
out.appearance.scale_strokes(width_scale);
|
||||
match &mut out.kind {
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
*live = None;
|
||||
*path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol));
|
||||
*path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol), breaks);
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } => {
|
||||
let kids: Vec<Arc<Node>> =
|
||||
children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale)).map(Arc::new).collect();
|
||||
children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale, breaks)).map(Arc::new).collect();
|
||||
if kids.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -64,7 +73,7 @@ pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale));
|
||||
map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale, breaks));
|
||||
Some(out)
|
||||
}
|
||||
|
||||
@@ -80,12 +89,13 @@ fn map_mask(n: &mut Node, map: impl FnOnce(&Node) -> Option<Node>) {
|
||||
}
|
||||
|
||||
/// Each subpath of `p` through `f`: fitted cubics when they take no more anchors than the chords
|
||||
/// would, else the chords. Points `f` cannot place (not finite) are left out of the chords.
|
||||
fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64) -> PathData {
|
||||
/// would, else the chords, both split at `breaks` ([`warp_node`]). Points `f` cannot place (not
|
||||
/// finite) are left out of the chords.
|
||||
fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64, breaks: &[f64]) -> PathData {
|
||||
let mut subs = vec![];
|
||||
for sp in &p.subpaths {
|
||||
let Some(dense) = densified(sp, flat_tol, max_du) else { continue };
|
||||
if let Some(fit) = fitted(sp, f, fit_tol, dense.len()) {
|
||||
let Some(dense) = densified(sp, flat_tol, max_du, breaks) else { continue };
|
||||
if let Some(fit) = fitted(sp, f, fit_tol, dense.len(), breaks) {
|
||||
subs.push(fit);
|
||||
continue;
|
||||
}
|
||||
@@ -98,8 +108,9 @@ fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f6
|
||||
}
|
||||
|
||||
/// `sp` flattened with `flat_tol` and its chords subdivided so none is longer than `max_du` along
|
||||
/// x, in art space: the points the chord route maps. `None` below two points.
|
||||
fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
|
||||
/// x, in art space, with a point where a chord crosses each of `breaks` (art x, in order): the
|
||||
/// points the chord route maps. `None` below two points.
|
||||
fn densified(sp: &SubPath, flat_tol: f64, max_du: f64, breaks: &[f64]) -> Option<Vec<Point>> {
|
||||
let mut bp = BezPath::new();
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
let mut pts = vec![];
|
||||
@@ -118,16 +129,57 @@ fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
|
||||
let mut dense = vec![*pts.first()?];
|
||||
for (i, (&a, &b)) in pts.iter().zip(pts.iter().cycle().skip(1)).take(segs).enumerate() {
|
||||
let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB);
|
||||
// The breaks the chord crosses, as parameters along it in order, go in among the even ones.
|
||||
let mut cuts: Vec<f64> = crossed(breaks, a.x, b.x).iter().map(|&x| (x - a.x) / (b.x - a.x)).collect();
|
||||
cuts.sort_by(f64::total_cmp);
|
||||
let mut cuts = cuts.into_iter().peekable();
|
||||
for j in 1..=k {
|
||||
let even = j as f64 / k as f64;
|
||||
while let Some(t) = cuts.next_if(|&t| t < even) {
|
||||
dense.push(a.lerp(b, t));
|
||||
}
|
||||
if sp.closed && i == segs - 1 && j == k {
|
||||
break;
|
||||
}
|
||||
dense.push(a.lerp(b, j as f64 / k as f64));
|
||||
dense.push(a.lerp(b, even));
|
||||
}
|
||||
}
|
||||
Some(dense)
|
||||
}
|
||||
|
||||
/// The values of `breaks` (in order) strictly between `a` and `b`, either way round.
|
||||
fn crossed(breaks: &[f64], a: f64, b: f64) -> &[f64] {
|
||||
let (lo, hi) = (a.min(b), a.max(b));
|
||||
let from = breaks.partition_point(|&x| x <= lo);
|
||||
let to = from + breaks[from..].partition_point(|&x| x < hi);
|
||||
&breaks[from..to]
|
||||
}
|
||||
|
||||
/// The parameters of `c` (in order, strictly between its ends) where its x is one of `breaks`;
|
||||
/// `line` when `c` is a line with its handles at thirds, whose x runs evenly.
|
||||
fn crossings(c: &CubicBez, line: bool, breaks: &[f64]) -> Vec<f64> {
|
||||
let xs = [c.p0.x, c.p1.x, c.p2.x, c.p3.x];
|
||||
let (lo, hi) = xs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &x| (lo.min(x), hi.max(x)));
|
||||
let inside = crossed(breaks, lo, hi);
|
||||
if inside.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let [a, b, cc, d] = xs;
|
||||
let mut ts: Vec<f64> = vec![];
|
||||
for &x in inside {
|
||||
if line {
|
||||
ts.push((x - a) / (d - a));
|
||||
} else {
|
||||
ts.extend(kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (cc - 2.0 * b + a), d - 3.0 * cc + 3.0 * b - a));
|
||||
}
|
||||
}
|
||||
// Pieces are no shorter than the step the fit reads their ends' directions over.
|
||||
ts.retain(|t| t.is_finite() && *t > FIT_DT && *t < 1.0 - FIT_DT);
|
||||
ts.sort_by(f64::total_cmp);
|
||||
ts.dedup_by(|t, prev| *t - *prev <= FIT_DT);
|
||||
ts
|
||||
}
|
||||
|
||||
/// Times an art segment is halved at most while looking for cubics that fit it.
|
||||
const FIT_DEPTH: u32 = 12;
|
||||
/// Parameter step of the finite differences that stand in for the bend's derivative.
|
||||
@@ -156,7 +208,10 @@ fn fit_tol(doc_tol: f64) -> f64 {
|
||||
/// bend at the same parameters, so the distance measured is never less than the true one. The
|
||||
/// halving is our own rather than kurbo's `fit_to_bezpath`, which halves until the floats run out
|
||||
/// on a map that never fits; the depth and the anchor count bound this one.
|
||||
fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Option<SubPath> {
|
||||
///
|
||||
/// A segment is first split where its x crosses one of `breaks` (art x, in order), so a turn of
|
||||
/// the map there lands on an anchor rather than between the checked positions.
|
||||
fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize, breaks: &[f64]) -> Option<SubPath> {
|
||||
if !(tol.is_finite() && tol > 0.0) {
|
||||
return None;
|
||||
}
|
||||
@@ -174,7 +229,11 @@ fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Op
|
||||
// A line's handles sit on its ends, which stalls its parameter there; thirds keep it even.
|
||||
let c = if line { 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 };
|
||||
let at = |t: f64| Some(f(c.eval(t))).filter(|q| q.is_finite());
|
||||
fit_into(&at, (0.0, 1.0), line, tol, FIT_DEPTH, &mut bp, &mut room)?;
|
||||
let mut t0 = 0.0;
|
||||
for t1 in crossings(&c, line, breaks).into_iter().chain([1.0]) {
|
||||
fit_into(&at, (t0, t1), line, tol, FIT_DEPTH, &mut bp, &mut room)?;
|
||||
t0 = t1;
|
||||
}
|
||||
}
|
||||
if sp.closed {
|
||||
bp.close_path();
|
||||
@@ -316,6 +375,16 @@ impl AlongMap {
|
||||
fn max_scale(&self) -> f64 {
|
||||
(0..3).map(|i| self.slope(i).abs()).fold(1e-6, f64::max)
|
||||
}
|
||||
|
||||
/// The art x (offset from the art's left edge) that [`AlongMap::at`] takes to arc length `s`,
|
||||
/// when a piece with width spans it.
|
||||
fn x_at(&self, s: f64) -> Option<f64> {
|
||||
(0..3).find_map(|i| {
|
||||
let ((x0, x1), (s0, s1)) = ((self.xs[i], self.xs[i + 1]), (self.ss[i], self.ss[i + 1]));
|
||||
let spans = x1 - x0 > 1e-12 && (s1 - s0).abs() > 1e-12 && s0.min(s1) <= s && s <= s0.max(s1);
|
||||
spans.then(|| x0 + (s - s0) / (s1 - s0) * (x1 - x0))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The affine that reproduces `f` over `b` to within `tol`, if one does.
|
||||
@@ -414,12 +483,14 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option<N
|
||||
{
|
||||
return affine_node(art, a, cross.abs());
|
||||
}
|
||||
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs())
|
||||
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * 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> {
|
||||
/// of each object in the art take the factor at the middle of the object. `marks` are the arc
|
||||
/// lengths (in order) of the recorded pen samples `widen` runs in a straight line between; the art
|
||||
/// is split where `widen` turns at one by more than the bent outline's tolerance ([`pen_breaks`]).
|
||||
fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64, marks: &[f64]) -> Option<Node> {
|
||||
let cy = b.center().y;
|
||||
let x0 = b.x0;
|
||||
let f = move |p: Point| {
|
||||
@@ -430,7 +501,45 @@ fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, wid
|
||||
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(), flat_tol * scale, cross.abs())
|
||||
// A change of `dw` in `widen` moves the art's top and bottom edges `dw × reach` across.
|
||||
let reach = b.height() / 2.0 * cross.abs();
|
||||
let mut breaks: Vec<f64> =
|
||||
pen_breaks(marks, along.span(), widen, fit_tol(flat_tol * scale) / reach).into_iter().filter_map(|s| along.x_at(s)).map(|x| x + x0).collect();
|
||||
breaks.sort_by(f64::total_cmp);
|
||||
breaks.dedup();
|
||||
warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs(), &breaks)
|
||||
}
|
||||
|
||||
/// The arc lengths among `marks` (in order) strictly within `(s0, s1)` at which the art is split:
|
||||
/// those where `widen` is more than `tol` from the straight line between the ones kept on either
|
||||
/// side (the span's ends to begin with), chosen by splitting at the farthest one until every
|
||||
/// sample left out is within `tol` of that line. `widen` runs straight between samples, so it
|
||||
/// is then within `tol` of the line between kept samples all along, and samples on a straight
|
||||
/// course add no splits.
|
||||
fn pen_breaks(marks: &[f64], (s0, s1): (f64, f64), widen: &dyn Fn(f64) -> f64, tol: f64) -> Vec<f64> {
|
||||
if !(s1 > s0 && tol > 0.0) {
|
||||
return vec![];
|
||||
}
|
||||
let inside = {
|
||||
let from = marks.partition_point(|&s| s <= s0);
|
||||
&marks[from..from + marks[from..].partition_point(|&s| s < s1)]
|
||||
};
|
||||
if inside.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let pts: Vec<(f64, f64)> = std::iter::once(s0).chain(inside.iter().copied()).chain([s1]).map(|s| (s, widen(s))).collect();
|
||||
let mut keep = vec![false; pts.len()];
|
||||
let mut spans = vec![(0, pts.len() - 1)];
|
||||
while let Some((i, j)) = spans.pop() {
|
||||
let ((sa, wa), (sb, wb)) = (pts[i], pts[j]);
|
||||
let off = |&(s, w): &(f64, f64)| (w - if sb > sa { wa + (wb - wa) * (s - sa) / (sb - sa) } else { wa }).abs();
|
||||
let far = (i + 1..j).map(|k| (k, off(&pts[k]))).filter(|&(_, d)| d > tol).max_by(|a, b| a.1.total_cmp(&b.1));
|
||||
if let Some((k, _)) = far {
|
||||
keep[k] = true;
|
||||
spans.extend([(i, k), (k, j)]);
|
||||
}
|
||||
}
|
||||
pts.iter().zip(keep).filter(|&(_, k)| k).map(|(p, _)| p.0).collect()
|
||||
}
|
||||
|
||||
/// `n` with the strokes of it and of everything inside it scaled by `factor` of the object they
|
||||
@@ -465,8 +574,17 @@ fn art_runs(t: &Track) -> Vec<(f64, f64)> {
|
||||
bounds.windows(2).map(|w| (w[0], w[1])).collect()
|
||||
}
|
||||
|
||||
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1.
|
||||
fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, Rect), cross: f64, widen: &dyn Fn(f64) -> f64) -> Option<Node> {
|
||||
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1 (`marks`
|
||||
/// as [`bend_widened`] takes them).
|
||||
fn art_on_run(
|
||||
t: &Track,
|
||||
(s0, s1): (f64, f64),
|
||||
a: &ArtBrush,
|
||||
(art, b): (&Node, Rect),
|
||||
cross: f64,
|
||||
widen: &dyn Fn(f64) -> f64,
|
||||
marks: &[f64],
|
||||
) -> Option<Node> {
|
||||
let l = s1 - s0;
|
||||
if l <= 1e-9 {
|
||||
return None;
|
||||
@@ -489,7 +607,7 @@ fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, R
|
||||
}
|
||||
}
|
||||
};
|
||||
bend_widened(t, art, b, along, cross, widen)
|
||||
bend_widened(t, art, b, along, cross, widen, marks)
|
||||
}
|
||||
|
||||
/// An art brush's art along `bp`. With a width that follows the pen (its pressure, tilt, bearing
|
||||
@@ -515,9 +633,13 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer)
|
||||
let p = a.width_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5);
|
||||
(light + (heavy - light) * p) / width
|
||||
};
|
||||
let marks = match a.width_mode {
|
||||
Some(m) if light != heavy && width > 0.0 => pen_marks(stroke, m, l),
|
||||
_ => vec![],
|
||||
};
|
||||
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, &widen) {
|
||||
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen, &marks) {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
@@ -649,6 +771,253 @@ fn tile_on(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, cross: f64) -> Opti
|
||||
bend(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), cross)
|
||||
}
|
||||
|
||||
/// A tile placed on [s0, s1] of the track, `k(s)` across at arc length `s` when the scale varies
|
||||
/// (`marks`: the arc lengths of the recorded pen samples in order, between which the scale runs
|
||||
/// in a straight line), else `k` at the middle of the span across all of it ([`tile_on`]), as it
|
||||
/// is too when the scale is the same at both ends of the span, at every sample within it and, at
|
||||
/// a closed track's start within it, on both sides of the start.
|
||||
fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64) -> f64, marks: Option<&[f64]>) -> Option<Node> {
|
||||
let mid = k((s0 + s1) / 2.0);
|
||||
// Only the samples within the span are looked at.
|
||||
let within = |marks: &[f64]| {
|
||||
let from = marks.partition_point(|&s| s <= s0);
|
||||
let to = from + marks[from..].partition_point(|&s| s < s1);
|
||||
marks[from..to].iter().all(|&s| k(s) == mid)
|
||||
};
|
||||
// A closed track's scale goes from the one at its end to the one at its start where it wraps
|
||||
// round, so a span over its start (or a track's length before or after it) takes both.
|
||||
let l = t.len();
|
||||
let seam = t.closed && l > 0.0 && (s0 / l).ceil() <= (s1 / l).floor();
|
||||
let ends = || !seam || (k(0.0) == mid && k(l) == mid);
|
||||
let even = |marks: &[f64]| k(s0) == mid && k(s1) == mid && within(marks) && ends();
|
||||
if mid <= 0.0 || marks.is_none_or(even) {
|
||||
return tile_on(t, tile, s0, s1, mid);
|
||||
}
|
||||
bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid, marks.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The most side tiles a run of a pattern brush places.
|
||||
const MAX_TILES: usize = 20000;
|
||||
|
||||
/// How many times a pattern brush whose scale varies measures its side tiles again where the fit
|
||||
/// puts them.
|
||||
const REFITS: usize = 3;
|
||||
|
||||
/// How many times a pattern brush whose scale varies halves the range a start or end tile's
|
||||
/// length lies in.
|
||||
const END_SOLVE_STEPS: usize = 48;
|
||||
|
||||
/// How many evenly spaced lengths a pattern brush whose scale varies tries for a start or end
|
||||
/// tile before it halves the range the tile's length lies in.
|
||||
const END_SCAN_STEPS: usize = 64;
|
||||
|
||||
/// The side tiles of a pattern brush on a run `avail` long from `a` when the scale varies along
|
||||
/// it: each tile's length and the gap after it, as `natural` gives them at the tile's start, and
|
||||
/// how many tiles fit whole and what fraction of the next one fits after them. The tiles include
|
||||
/// that next one when there is room for part of it.
|
||||
fn varied_tiles(a: f64, avail: f64, natural: &dyn Fn(f64) -> (f64, f64)) -> (Vec<(f64, f64)>, f64) {
|
||||
let mut tiles = vec![];
|
||||
let mut pos = 0.0;
|
||||
while tiles.len() < MAX_TILES {
|
||||
let (w, g) = natural(a + pos);
|
||||
if !(w > 1e-9 && w.is_finite() && g.is_finite() && g >= 0.0) {
|
||||
break;
|
||||
}
|
||||
tiles.push((w, g));
|
||||
if pos + w > avail {
|
||||
let whole = (tiles.len() - 1) as f64;
|
||||
return (tiles, whole + ((avail - pos + g) / (w + g)).clamp(0.0, 1.0));
|
||||
}
|
||||
pos += w + g;
|
||||
}
|
||||
let whole = tiles.len() as f64;
|
||||
(tiles, whole)
|
||||
}
|
||||
|
||||
/// The size factor of a pattern brush's tiles at `weight` where its scale's pen input is `p`
|
||||
/// (0 at the first scale, 1 at the second).
|
||||
fn pattern_scale_at(pb: &PatternBrush, weight: f64, p: f64) -> f64 {
|
||||
let (light, heavy) = pb.scale_range();
|
||||
weight * (light + (heavy - light) * p).max(1.0) / 100.0
|
||||
}
|
||||
|
||||
/// A pattern brush's size factor on `stroke` at `weight`, and whether it varies along the stroke.
|
||||
/// A stroke with no recording of the input the scale follows is drawn at one scale, the one that
|
||||
/// input's missing value gives.
|
||||
fn pattern_scale(pb: &PatternBrush, weight: f64, stroke: &StrokeLayer) -> (f64, bool) {
|
||||
let (light, heavy) = pb.scale_range();
|
||||
match pb.scale_mode {
|
||||
Some(m) if light != heavy && pen_recorded(stroke, m) => (weight * pb.scale.max(1.0) / 100.0, true),
|
||||
Some(m) if light != heavy => (pattern_scale_at(pb, weight, PenAt::of(stroke, 0.0).control(m).unwrap_or(0.5)), false),
|
||||
_ => (weight * pb.scale.max(1.0) / 100.0, false),
|
||||
}
|
||||
}
|
||||
|
||||
/// The length of a start or end tile `width` wide at its art's size, at the scale `k_mid(w)` at
|
||||
/// the middle of the tile when it is `w` long: the shortest length that is as long as the scale at
|
||||
/// its own middle. The scale can rise and fall along the stroke, so the lengths up to `room` are
|
||||
/// tried in order (evenly spaced ones, and `breaks`, the lengths whose middle falls on a recorded
|
||||
/// pen sample), and the range between the last one the tile is too long for and the first one it
|
||||
/// fits is halved. A tile that fits at no length up to `room` gets the length it needs at `room`,
|
||||
/// longer than `room`. `breaks` is `None` when the scale is the same along the whole track, and
|
||||
/// the tile then takes its length at that scale.
|
||||
fn end_tile_length(width: f64, room: f64, k_mid: &dyn Fn(f64) -> f64, breaks: Option<&[f64]>) -> f64 {
|
||||
let length = |w: f64| width * k_mid(w);
|
||||
let first = length(0.0);
|
||||
let Some(breaks) = breaks.filter(|_| !room.is_nan() && room > 0.0) else {
|
||||
return first;
|
||||
};
|
||||
let mut tries: Vec<f64> = (1..=END_SCAN_STEPS).map(|i| room * i as f64 / END_SCAN_STEPS as f64).collect();
|
||||
tries.extend(breaks.iter().copied().filter(|&w| w > 0.0 && w < room));
|
||||
tries.sort_by(f64::total_cmp);
|
||||
let Some(i) = tries.iter().position(|&w| length(w) <= w) else {
|
||||
return length(room);
|
||||
};
|
||||
let (mut short, mut long) = (if i == 0 { 0.0 } else { tries[i - 1] }, tries[i]);
|
||||
for _ in 0..END_SOLVE_STEPS {
|
||||
let mid = (short + long) / 2.0;
|
||||
if length(mid) > mid {
|
||||
short = mid;
|
||||
} else {
|
||||
long = mid;
|
||||
}
|
||||
}
|
||||
long
|
||||
}
|
||||
|
||||
/// Where along a track `l` long `stroke` recorded the pen input `mode` follows: each sample at its
|
||||
/// arc length, and again a track's length before and after it, for tiles of a closed track that
|
||||
/// wrap round, in order.
|
||||
fn pen_marks(stroke: &StrokeLayer, mode: Variation, l: f64) -> Vec<f64> {
|
||||
let points = match mode {
|
||||
Variation::Fixed | Variation::Random => None,
|
||||
Variation::Pressure => stroke.pressure.as_ref().map(|p| &p.points),
|
||||
Variation::Tilt => stroke.tilt.as_ref().map(|p| &p.points),
|
||||
Variation::Bearing => stroke.bearing.as_ref().map(|p| &p.points),
|
||||
Variation::Rotation => stroke.rotation.as_ref().map(|p| &p.points),
|
||||
Variation::StylusWheel => stroke.wheel.as_ref().map(|p| &p.points),
|
||||
};
|
||||
let mut marks: Vec<f64> = points.into_iter().flatten().flat_map(|&(f, _)| [f * l - l, f * l, f * l + l]).collect();
|
||||
marks.sort_by(f64::total_cmp);
|
||||
marks
|
||||
}
|
||||
|
||||
/// Whether `stroke` recorded the pen input `mode` follows.
|
||||
fn pen_recorded(stroke: &StrokeLayer, mode: Variation) -> bool {
|
||||
match mode {
|
||||
Variation::Fixed | Variation::Random => false,
|
||||
Variation::Pressure => stroke.pressure.is_some(),
|
||||
Variation::Tilt => stroke.tilt.is_some(),
|
||||
Variation::Bearing => stroke.bearing.is_some(),
|
||||
Variation::Rotation => stroke.rotation.is_some(),
|
||||
Variation::StylusWheel => stroke.wheel.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Leaves out or adds tiles at the end of `tiles` (each a length and the gap after it) once they
|
||||
/// have been measured again: with `add_space` as many as fit in `avail` with the gaps between
|
||||
/// them, at least one, otherwise the count whose lengths and gaps between them come nearest to
|
||||
/// `avail`. An added tile is
|
||||
/// `natural(s)` long at `s` from the run's start.
|
||||
fn recount(tiles: &mut Vec<(f64, f64)>, avail: f64, add_space: bool, natural: &dyn Fn(f64) -> (f64, f64)) {
|
||||
let mut length: f64 = tiles.iter().map(|t| t.0).sum();
|
||||
let mut gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum());
|
||||
// How much of the run the tiles and the spacing between them take.
|
||||
let run = |length: f64, gaps: f64| length + gaps;
|
||||
while let [.., (_, before), (w, _)] = tiles.as_slice() {
|
||||
let (w, before) = (*w, *before);
|
||||
let (now, without) = (run(length, gaps), run(length - w, gaps - before));
|
||||
let drop = if add_space { now > avail } else { (without - avail).abs() < (now - avail).abs() };
|
||||
if !drop {
|
||||
break;
|
||||
}
|
||||
tiles.pop();
|
||||
length -= w;
|
||||
gaps -= before;
|
||||
}
|
||||
while tiles.len() < MAX_TILES {
|
||||
let last_gap = tiles.last().map_or(0.0, |t| t.1);
|
||||
let now = run(length, gaps);
|
||||
let (w, g) = natural(run(length, gaps + last_gap));
|
||||
if w.is_nan() || w <= 1e-9 {
|
||||
break;
|
||||
}
|
||||
let with = run(length + w, gaps + last_gap);
|
||||
let add = if add_space { with <= avail } else { (with - avail).abs() < (now - avail).abs() };
|
||||
if !add {
|
||||
break;
|
||||
}
|
||||
tiles.push((w, g));
|
||||
length += w;
|
||||
gaps += last_gap;
|
||||
}
|
||||
}
|
||||
|
||||
/// A pattern brush's side tiles on the run `avail` long from `a` of `t` (`marks` as
|
||||
/// [`tile_scaled`] takes them), at the scale `k(s)` at
|
||||
/// arc length `s` ([`varied_tiles`]), fitted as `pb.fit` says: Stretch scales the lengths and gaps
|
||||
/// to fill the run, Add Space keeps the lengths and shares out what is left between the tiles
|
||||
/// (around a lone tile), and Approximate keeps both and centers the tiles on the run.
|
||||
fn varied_side_tiles(
|
||||
out: &mut Budget,
|
||||
t: &Track,
|
||||
pb: &PatternBrush,
|
||||
side: &(Node, Rect),
|
||||
(a, avail): (f64, f64),
|
||||
k: &dyn Fn(f64) -> f64,
|
||||
marks: &[f64],
|
||||
) {
|
||||
let tw = side.1.width();
|
||||
// Each side tile and the gap after it as long as the scale at the tile's middle.
|
||||
let natural = |s: f64| {
|
||||
let w = tw * k(s + tw * k(s) / 2.0);
|
||||
(w, w * pb.spacing.max(0.0) / 100.0)
|
||||
};
|
||||
let (tiles, count) = varied_tiles(a, avail, &natural);
|
||||
let n = match pb.fit {
|
||||
PatternFit::AddSpace => count.floor(),
|
||||
PatternFit::Stretch | PatternFit::Approximate => count.round(),
|
||||
}
|
||||
.max(1.0) as usize;
|
||||
let mut tiles = tiles[..n.min(tiles.len())].to_vec();
|
||||
// How far the fit stretches the tiles and gaps, where the first tile starts, and the space
|
||||
// between tiles when the fit sets it.
|
||||
let fitted = |tiles: &[(f64, f64)]| {
|
||||
let length: f64 = tiles.iter().map(|t| t.0).sum();
|
||||
// The gaps between the tiles: after every tile but the last.
|
||||
let gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum());
|
||||
match pb.fit {
|
||||
PatternFit::Stretch => (avail / (length + gaps), 0.0, None),
|
||||
PatternFit::AddSpace if tiles.len() > 1 => (1.0, 0.0, Some(((avail - length) / (tiles.len() - 1) as f64).max(0.0))),
|
||||
PatternFit::AddSpace => (1.0, (avail - tiles.first().map_or(0.0, |t| t.0)) / 2.0, None),
|
||||
PatternFit::Approximate => (1.0, (avail - length - gaps) / 2.0, None),
|
||||
}
|
||||
};
|
||||
// The fit moves the tiles from where they were measured, so each is measured again at the
|
||||
// middle of where the fit puts it, and the fit worked out again, a few times over.
|
||||
for _ in 0..REFITS {
|
||||
let (stretch, lead, space) = fitted(&tiles);
|
||||
let mut s0 = a + lead;
|
||||
for tile in &mut tiles {
|
||||
let placed = tile.0 * stretch;
|
||||
let w = tw * k(s0 + placed / 2.0);
|
||||
s0 += placed + space.unwrap_or(tile.1 * stretch);
|
||||
*tile = (w, w * pb.spacing.max(0.0) / 100.0);
|
||||
}
|
||||
recount(&mut tiles, avail, pb.fit == PatternFit::AddSpace, &|s| natural(a + s));
|
||||
}
|
||||
let (stretch, lead, space) = fitted(&tiles);
|
||||
let mut s0 = a + lead;
|
||||
for &(w, g) in &tiles {
|
||||
let w = w * stretch;
|
||||
out.take(tile_scaled(t, side, s0, s0 + w, k, Some(marks)));
|
||||
if out.full() {
|
||||
break;
|
||||
}
|
||||
s0 += w + space.unwrap_or(g * stretch);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a pattern brush draws at a corner: corner tile art (oriented, with its bounds), or what
|
||||
/// [`CornerSource`] gives.
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -719,7 +1088,7 @@ fn auto_corner(t: &Track, i: usize, source: CornerSource, side: &(Node, Rect), k
|
||||
}
|
||||
let s = if tw > 1e-9 { len / tw } else { 1.0 };
|
||||
let max_du = MAX_SEG / (2.0 * k * s.max(1.0));
|
||||
let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k);
|
||||
let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k, &[]);
|
||||
// Art point → (distance along from the left edge, stretched to `len`, and offset across).
|
||||
let along = move |q: Point| {
|
||||
let (x, y) = local(q);
|
||||
@@ -803,10 +1172,15 @@ fn masked(n: Node, quad: &[Point], p: Point, towards: Vec2) -> Option<Node> {
|
||||
Some(Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(mask), Arc::new(n)], clip: true }))
|
||||
}
|
||||
|
||||
pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node> {
|
||||
/// A pattern brush's tiles along `bp`. With a scale that follows the pen (its pressure, tilt,
|
||||
/// bearing, rotation or wheel), the tiles are as tall as what `stroke` recorded at each point gives
|
||||
/// (half way without a recording), each tile and the gap after it as long as the scale at its
|
||||
/// middle, and each corner tile at the scale at its corner.
|
||||
pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) -> Vec<Node> {
|
||||
let orient = |n: &Node, frame| oriented_tile(n, frame, pb.flip_along, pb.flip_across);
|
||||
let Some(side) = orient(&pb.side, pb.side_frame) else { return vec![] };
|
||||
let k = weight * pb.scale.max(1.0) / 100.0;
|
||||
let scale_at = |p: f64| pattern_scale_at(pb, weight, p);
|
||||
let (k, varies) = pattern_scale(pb, weight, stroke);
|
||||
let outer = pb.outer_corner.as_ref().and_then(|n| orient(n, pb.outer_corner_frame));
|
||||
let inner = pb.inner_corner.as_ref().and_then(|n| orient(n, pb.inner_corner_frame));
|
||||
let start = pb.start.as_ref().and_then(|n| orient(n, pb.start_frame));
|
||||
@@ -825,6 +1199,17 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
if l <= 1e-9 {
|
||||
continue;
|
||||
}
|
||||
// The scale at arc length `s` of the track; on a closed track a point before its start or
|
||||
// past its end wraps round as `Track::frame` places it (its end itself keeps the scale at
|
||||
// the end), and on an open track a point past either end takes the scale at that end.
|
||||
let ks = |s: f64| {
|
||||
if !varies {
|
||||
return k;
|
||||
}
|
||||
let at = if t.closed && !(0.0..=l).contains(&s) { s.rem_euclid(l) } else { s.clamp(0.0, l) };
|
||||
scale_at(pb.scale_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5))
|
||||
};
|
||||
let marks = pb.scale_mode.filter(|_| varies).map(|m| pen_marks(stroke, m, l));
|
||||
let corners = t.corner_positions();
|
||||
// Corner tiles, centred on the corner and turned to the bisector. The path on each side of
|
||||
// a corner is shortened by `trims` (`None`: half the widest corner tile art).
|
||||
@@ -848,17 +1233,18 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
};
|
||||
before.min(after)
|
||||
};
|
||||
for (ci, &(i, _)) in corners.iter().enumerate() {
|
||||
for (ci, &(i, at)) in corners.iter().enumerate() {
|
||||
if out.full() {
|
||||
break;
|
||||
}
|
||||
let kc = ks(at);
|
||||
let (a, b) = t.in_out(i);
|
||||
// Turning towards the left normal puts the tile's +y side on the inside.
|
||||
let tile = if a.cross(b) > 0.0 { inner_tile.or(outer.as_ref().map(Corner::Art)) } else { outer_tile.or(inner.as_ref().map(Corner::Art)) };
|
||||
let (art, bb) = match tile {
|
||||
Some(Corner::Art(tile)) => tile,
|
||||
Some(Corner::Source(source)) => {
|
||||
let (pieces, trim) = auto_corner(&t, i, source, &side, k, room(ci));
|
||||
let (pieces, trim) = auto_corner(&t, i, source, &side, kc, room(ci));
|
||||
for n in pieces {
|
||||
out.take(Some(n));
|
||||
}
|
||||
@@ -870,8 +1256,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
continue;
|
||||
}
|
||||
};
|
||||
trims.push(None);
|
||||
corner_half = corner_half.max(bb.width() * k / 2.0);
|
||||
// With a scale that varies, each corner's tile is its own size, so the path beside it
|
||||
// is shortened by half of that tile.
|
||||
trims.push(varies.then_some(bb.width() * kc / 2.0));
|
||||
corner_half = corner_half.max(bb.width() * kc / 2.0);
|
||||
// Inner and outer corner art is the corner that joins a side tile on its right to one
|
||||
// below it, so its arms point along +x and +y (as the flips leave them). The tile is
|
||||
// turned so that the line halving its arms lies on the line halving the sides at the
|
||||
@@ -881,7 +1269,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
let arms = Vec2::new(if pb.flip_along { -1.0 } else { 1.0 }, if pb.flip_across { -1.0 } else { 1.0 });
|
||||
let sides = b - a;
|
||||
let angle = sides.y.atan2(sides.x) - arms.y.atan2(arms.x);
|
||||
let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(k) * Affine::translate(-bb.center().to_vec2());
|
||||
let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(kc) * Affine::translate(-bb.center().to_vec2());
|
||||
let mut n = art.clone();
|
||||
n.transform(xf, true);
|
||||
out.take(Some(n));
|
||||
@@ -914,9 +1302,11 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
&& ri == 0
|
||||
&& let Some(st) = &start
|
||||
{
|
||||
let w = st.1.width() * k;
|
||||
// As long as the scale at its middle.
|
||||
let breaks: Option<Vec<f64>> = marks.as_ref().map(|m| m.iter().map(|&m| 2.0 * (m - a)).collect());
|
||||
let w = end_tile_length(st.1.width(), b - a, &|w| ks(a + w / 2.0), breaks.as_deref());
|
||||
if b - a > w {
|
||||
out.take(tile_on(&t, st, a, a + w, k));
|
||||
out.take(tile_scaled(&t, st, a, a + w, &ks, marks.as_deref()));
|
||||
a += w;
|
||||
}
|
||||
}
|
||||
@@ -924,9 +1314,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
&& ri + 1 == nruns
|
||||
&& let Some(en) = &end
|
||||
{
|
||||
let w = en.1.width() * k;
|
||||
let breaks: Option<Vec<f64>> = marks.as_ref().map(|m| m.iter().map(|&m| 2.0 * (b - m)).collect());
|
||||
let w = end_tile_length(en.1.width(), b - a, &|w| ks(b - w / 2.0), breaks.as_deref());
|
||||
if b - a > w {
|
||||
out.take(tile_on(&t, en, b - w, b, k));
|
||||
out.take(tile_scaled(&t, en, b - w, b, &ks, marks.as_deref()));
|
||||
b -= w;
|
||||
}
|
||||
}
|
||||
@@ -934,6 +1325,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
if avail <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
if let Some(marks) = &marks {
|
||||
varied_side_tiles(&mut out, &t, pb, &side, (a, avail), &ks, marks);
|
||||
continue;
|
||||
}
|
||||
let unit = tw + gap;
|
||||
match pb.fit {
|
||||
PatternFit::Stretch => {
|
||||
@@ -1120,7 +1515,7 @@ mod tests {
|
||||
let f = |p: Point| t.map(along.at(p.x - x0), p.y - cy);
|
||||
let tol = tolerance(b.height().max(b.width()));
|
||||
let exact = traced(art, &f, 1000);
|
||||
let chords: Vec<Point> = densified(art, tol, MAX_SEG).expect("the tile flattens").into_iter().map(f).collect();
|
||||
let chords: Vec<Point> = densified(art, tol, MAX_SEG, &[]).expect("the tile flattens").into_iter().map(f).collect();
|
||||
let curves = traced(sp, &|p| p, 200);
|
||||
let (e_curves, e_chords) = (apart(&curves, &exact), apart(&chords, &exact));
|
||||
// Checked at eight points a piece, so a little room between them.
|
||||
@@ -1146,7 +1541,7 @@ mod tests {
|
||||
let allowed: usize = path
|
||||
.subpaths
|
||||
.iter()
|
||||
.filter_map(|sp| densified(sp, 0.25, 1.5))
|
||||
.filter_map(|sp| densified(sp, 0.25, 1.5, &[]))
|
||||
.map(|dense| 1 + (FIT_CHECKS + 3) * (2 * dense.len() + FIT_DEPTH as usize + 1) + dense.len())
|
||||
.sum();
|
||||
let finite = |n: &Node| match &n.kind {
|
||||
@@ -1168,7 +1563,7 @@ mod tests {
|
||||
calls.set(calls.get() + 1);
|
||||
if calls.get() > allowed { Point::new(f64::NAN, f64::NAN) } else { f(p) }
|
||||
};
|
||||
let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0);
|
||||
let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0, &[]);
|
||||
assert!(calls.get() <= allowed, "map {i} was called {} times, {allowed} allowed", calls.get());
|
||||
match (i, &out) {
|
||||
(3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"),
|
||||
@@ -1218,7 +1613,7 @@ mod tests {
|
||||
let mask = out.extras().mask.as_ref().expect("the mask is kept");
|
||||
assert_eq!(*mask.art, stroked(1), "{name} run: an unlinked mask stays where it was");
|
||||
|
||||
let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5).expect("the art is drawn");
|
||||
let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5, &[]).expect("the art is drawn");
|
||||
let mask = out.extras().mask.as_ref().expect("the mask is kept");
|
||||
assert_eq!(mask.art.kind, out.kind, "{name} run, widened: the mask's art bends with the art");
|
||||
assert_eq!(mask.art.appearance, out.appearance, "{name} run, widened: the mask's strokes narrow with the art's");
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
use std::cell::Cell;
|
||||
|
||||
thread_local! {
|
||||
static USED: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
pub(crate) fn initial_used() -> u64 {
|
||||
USED.with(Cell::get)
|
||||
}
|
||||
|
||||
pub(crate) fn with_used<T>(used: u64, action: impl FnOnce() -> T) -> T {
|
||||
struct Reset<'a>(&'a Cell<u64>, u64);
|
||||
impl Drop for Reset<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.set(self.1);
|
||||
}
|
||||
}
|
||||
USED.with(|value| {
|
||||
let _reset = Reset(value, value.replace(used));
|
||||
action()
|
||||
})
|
||||
}
|
||||
@@ -588,6 +588,9 @@ impl<'a> Walk<'a> {
|
||||
clip_tests: 0,
|
||||
warnings: vec![],
|
||||
nest: 0,
|
||||
#[cfg(test)]
|
||||
symbol_nodes: crate::expansion_test::initial_used(),
|
||||
#[cfg(not(test))]
|
||||
symbol_nodes: 0,
|
||||
generated: 0,
|
||||
scratch: None,
|
||||
@@ -740,7 +743,6 @@ impl<'a> Walk<'a> {
|
||||
}
|
||||
Some(None) => {}
|
||||
None => {
|
||||
self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
self.warn(SYMBOLS_LEFT_OUT);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -870,6 +870,31 @@ fn symbols_nested_too_deep_are_left_out_with_a_warning() {
|
||||
assert_eq!(text(&out), "IN;PU;SP0;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_symbol_keeps_the_budget_for_a_later_fitting_symbol() {
|
||||
let mut d = doc_with(|_| vec![]);
|
||||
let leaf = stroked(&mut d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK);
|
||||
let big = Node::group(d.alloc_id(), vec![Arc::new(leaf.clone()), Arc::new(leaf.clone())]);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "big".into(), art: Arc::new(big) });
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "small".into(), art: Arc::new(leaf) });
|
||||
let mut first = None;
|
||||
for name in ["big", "small"] {
|
||||
let id = d.alloc_id();
|
||||
first.get_or_insert(id);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap();
|
||||
}
|
||||
let mut expected = d.clone();
|
||||
expected.remove(first.unwrap()).unwrap();
|
||||
crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1, || {
|
||||
let actual = plot(&d, &opts(&d));
|
||||
let control = plot(&expected, &opts(&expected));
|
||||
assert!(actual.warnings.iter().any(|w| w == SYMBOLS_LEFT_OUT), "{:?}", actual.warnings);
|
||||
assert_ne!(text(&control), "IN;PU;SP0;");
|
||||
assert_eq!(text(&actual), text(&control), "HP-GL keeps the later fitting instance");
|
||||
});
|
||||
}
|
||||
|
||||
/// A symbol instance stained by its fill draws in the stained color.
|
||||
#[test]
|
||||
fn a_stained_symbol_instance_takes_its_stain() {
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
|
||||
|
||||
mod aci;
|
||||
#[cfg(test)]
|
||||
mod expansion_test;
|
||||
pub mod hpgl;
|
||||
pub mod import;
|
||||
mod scene;
|
||||
|
||||
@@ -561,8 +561,10 @@ impl<'a> Scene<'a> {
|
||||
extents: None,
|
||||
opacity: 1.0,
|
||||
nest: 0,
|
||||
// Tests spend all but a million of it up front.
|
||||
symbol_nodes: if cfg!(test) { vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000 } else { 0 },
|
||||
#[cfg(test)]
|
||||
symbol_nodes: crate::expansion_test::initial_used(),
|
||||
#[cfg(not(test))]
|
||||
symbol_nodes: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -711,7 +713,6 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
Some(None) => {}
|
||||
None => {
|
||||
self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
self.warn(SYMBOLS_LEFT_OUT);
|
||||
}
|
||||
}
|
||||
|
||||
+26
-1
@@ -1503,11 +1503,36 @@ fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() {
|
||||
let art = Node::group(d.alloc_id(), children);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(art) });
|
||||
}
|
||||
let out = export(&d, &opts(&d)).unwrap();
|
||||
let out = crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000, || export(&d, &opts(&d)).unwrap());
|
||||
assert!(entities(&out).is_empty());
|
||||
assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_symbol_keeps_the_budget_for_a_later_fitting_symbol() {
|
||||
let mut d = doc_with(|_| vec![]);
|
||||
let leaf = path(&mut d, shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 40.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
|
||||
let big = Node::group(d.alloc_id(), vec![Arc::new(leaf.clone()), Arc::new(leaf.clone())]);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "big".into(), art: Arc::new(big) });
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "small".into(), art: Arc::new(leaf) });
|
||||
let mut first = None;
|
||||
for name in ["big", "small"] {
|
||||
let id = d.alloc_id();
|
||||
first.get_or_insert(id);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap();
|
||||
}
|
||||
let mut expected = d.clone();
|
||||
expected.remove(first.unwrap()).unwrap();
|
||||
crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1, || {
|
||||
let actual = export(&d, &opts(&d)).unwrap();
|
||||
let control = export(&expected, &opts(&expected)).unwrap();
|
||||
assert!(actual.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", actual.warnings);
|
||||
assert!(!entities(&control).is_empty());
|
||||
assert_eq!(kinds(&actual), kinds(&control), "DXF keeps the later fitting instance");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_bytes_match_shared_writer_goldens() {
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -0,0 +1,601 @@
|
||||
//! Color text in the forms CSS Color 4 defines: hex colors with or without an alpha
|
||||
//! (<https://www.w3.org/TR/css-color-4/#hex-notation>), `rgb()` and `rgba()`
|
||||
//! (<https://www.w3.org/TR/css-color-4/#rgb-functions>), `hsl()` and `hsla()`
|
||||
//! (<https://www.w3.org/TR/css-color-4/#the-hsl-notation>) and `oklch()`
|
||||
//! (<https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch>). The functions take the
|
||||
//! space-separated form with an optional `/ alpha`, and `rgb()`, `rgba()`, `hsl()` and `hsla()` also
|
||||
//! take the comma-separated legacy form (<https://www.w3.org/TR/css-color-4/#legacy-color-syntax>).
|
||||
//! Hues take the angle units of CSS Values 4 (<https://www.w3.org/TR/css-values-4/#angles>). A hex
|
||||
//! color may leave out its `#`. [`format`] writes a color in these forms.
|
||||
//!
|
||||
//! The module reads a subset of CSS. A function's arguments are literal numbers, percentages,
|
||||
//! angles and `none`. A parenthesis inside the arguments makes the text invalid, so `calc()`,
|
||||
//! `var()`, `color-mix()`, relative color syntax and every other nested function are refused, as are
|
||||
//! named colors and the other color spaces and functions (`hwb()`, `lab()`, `oklab()`, `color()`).
|
||||
|
||||
use crate::oklab::{self, CHROMA_FULL};
|
||||
|
||||
/// The most characters a color text may have, spaces around it not counted.
|
||||
pub const MAX_CHARS: usize = 48;
|
||||
|
||||
/// The space a parsed color's red, green and blue are in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Space {
|
||||
/// The numbers as written: a hex color, `rgb()` or `hsl()`.
|
||||
Srgb,
|
||||
/// sRGB converted from `oklch()`.
|
||||
Oklch,
|
||||
}
|
||||
|
||||
/// A color read from CSS text.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct CssColor {
|
||||
/// Red, green and blue from 0 to 1.
|
||||
pub rgb: [f32; 3],
|
||||
/// The alpha from 0 to 1, when the text gives one (CSS reads a missing alpha as 1).
|
||||
pub alpha: Option<f32>,
|
||||
pub space: Space,
|
||||
}
|
||||
|
||||
/// The color `text` gives, or `None` when it is not one of the module's forms or has more than
|
||||
/// [`MAX_CHARS`] characters. Values are clamped where CSS clamps them when it parses them: red, green
|
||||
/// and blue to 0..=255 (0..=100 %), alpha to 0..=1, a negative HSL saturation to 0, OKLCH lightness
|
||||
/// to 0..=1 and chroma to 0 or more. `none` reads as 0, as CSS reads a missing component when it
|
||||
/// converts a color. Spaces, tabs, line breaks and form feeds may surround the text and its
|
||||
/// arguments; other whitespace is not CSS whitespace and makes the text invalid. An `hsl()` color whose red, green or
|
||||
/// blue falls outside 0..=1 has that channel clipped, and an `oklch()` color outside sRGB keeps its
|
||||
/// lightness and hue and takes the largest chroma that fits ([`oklab::from_oklch`]); CSS maps such
|
||||
/// colors into the gamut by its own rules instead. An `hsl()` color whose saturation and lightness
|
||||
/// are so large that a channel overflows to an infinity is refused.
|
||||
pub fn parse(text: &str) -> Option<CssColor> {
|
||||
let text = css_trim(text);
|
||||
if text.chars().nth(MAX_CHARS).is_some() {
|
||||
return None;
|
||||
}
|
||||
match text.find('(') {
|
||||
None => hex(text),
|
||||
Some(open) => {
|
||||
// CSS allows no space between a function's name and its `(`.
|
||||
let name = text.get(..open)?.to_ascii_lowercase();
|
||||
let args = text.get(open + 1..)?.strip_suffix(')')?;
|
||||
if args.contains(['(', ')']) {
|
||||
return None;
|
||||
}
|
||||
match name.as_str() {
|
||||
"rgb" | "rgba" => rgb(args),
|
||||
"hsl" | "hsla" => hsl(args),
|
||||
"oklch" => oklch(args),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `s` without the CSS whitespace (spaces, tabs, line breaks and form feeds, which CSS reads as line
|
||||
/// breaks) around it (<https://www.w3.org/TR/css-syntax-3/#whitespace>,
|
||||
/// <https://www.w3.org/TR/css-syntax-3/#input-preprocessing>).
|
||||
fn css_trim(s: &str) -> &str {
|
||||
s.trim_matches(|c: char| c.is_ascii_whitespace())
|
||||
}
|
||||
|
||||
/// `#rrggbb` of red, green and blue from 0 to 1, each rounded to the nearest of 256 steps.
|
||||
pub fn hex_of(rgb: [f32; 3]) -> String {
|
||||
let [r, g, b] = rgb.map(byte);
|
||||
format!("#{r:02x}{g:02x}{b:02x}")
|
||||
}
|
||||
|
||||
/// `v` (0 to 1) as one of 256 steps.
|
||||
fn byte(v: f32) -> u8 {
|
||||
(v.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}
|
||||
|
||||
/// The forms [`format`] writes a color in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Notation {
|
||||
/// `#rrggbb`.
|
||||
Hex,
|
||||
/// `#rrggbbaa`, `ff` for a color without an alpha.
|
||||
HexAlpha,
|
||||
/// `rgb(51 102 153)`.
|
||||
Rgb,
|
||||
/// `hsl(210 50% 40%)`.
|
||||
Hsl,
|
||||
/// `oklch(49.93% 0.0987 250.43)`.
|
||||
Oklch,
|
||||
}
|
||||
|
||||
/// `rgb` (red, green and blue from 0 to 1) and the alpha `alpha` (0 to 1) as text of `notation`
|
||||
/// that [`parse`] reads back to the same `#rrggbb`. Each channel is first rounded to the nearest of
|
||||
/// 256 steps, as [`hex_of`] rounds it. `rgb()`, `hsl()` and `oklch()` use the space-separated form
|
||||
/// and add the alpha as a percentage after a `/` when it rounds to less than 100 %; `hsl()` and
|
||||
/// `oklch()` give their numbers to two places (chroma to four), without trailing zeros, and
|
||||
/// `oklch()` takes one or two more places where fewer would read back to other bytes. The hue of a
|
||||
/// gray is 0. [`Notation::Hex`] leaves the alpha out.
|
||||
pub fn format(rgb: [f32; 3], alpha: Option<f32>, notation: Notation) -> String {
|
||||
// A NaN alpha reads as none.
|
||||
let alpha = alpha.filter(|a| !a.is_nan());
|
||||
let bytes = rgb.map(byte);
|
||||
let units = bytes.map(|v| f64::from(v) / 255.0);
|
||||
let [r, g, b] = bytes;
|
||||
match notation {
|
||||
Notation::Hex => hex_of(rgb),
|
||||
Notation::HexAlpha => format!("{}{:02x}", hex_of(rgb), byte(alpha.unwrap_or(1.0))),
|
||||
Notation::Rgb => format!("rgb({r} {g} {b}{})", alpha_part(alpha)),
|
||||
Notation::Hsl => {
|
||||
let [h, s, l] = rgb_to_hsl(units);
|
||||
format!("hsl({} {}% {}%{})", hue_text(h), number(s * 100.0, 2), number(l * 100.0, 2), alpha_part(alpha))
|
||||
}
|
||||
Notation::Oklch => {
|
||||
let lch = oklab::to_oklch(units.map(|v| v as f32));
|
||||
// The fewest places that read back to the same bytes, from two (four for chroma).
|
||||
let fits = |p: i32| oklch_rounded(lch, p).filter(|&[l, c, h]| oklab::from_oklch(l, c, h).0.map(byte) == bytes);
|
||||
let (p, [l, c, h]) = (0..3).find_map(|extra| fits(extra).map(|v| (extra, v))).unwrap_or((2, oklch_rounded(lch, 2).unwrap_or(lch)));
|
||||
let places = |base: i32| usize::try_from(base + p).unwrap_or(2);
|
||||
let c = number(c, places(4));
|
||||
// A chroma that rounds to 0 is a gray, whose hue is 0.
|
||||
let h = if c == "0" { "0".to_string() } else { hue_text_to(h, places(2)) };
|
||||
format!("oklch({}% {c} {h}{})", number(l * 100.0, places(2)), alpha_part(alpha))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// OKLCH `lch` rounded as [`format`] writes it with `extra` more places than two for the
|
||||
/// lightness percentage and the hue and four for the chroma, or `None` when no chroma at or under
|
||||
/// the rounded one within [`OKLCH_CHROMA_STEPS`] steps lies inside sRGB. A color on the edge of
|
||||
/// sRGB can round to a point just outside it, where [`parse`] would lower the chroma to the edge at
|
||||
/// the rounded lightness and hue; the chroma is lowered a step at a time instead.
|
||||
fn oklch_rounded([l, c, h]: [f64; 3], extra: i32) -> Option<[f64; 3]> {
|
||||
let (l, h) = (rounded(l, 4 + extra), rounded(h, 2 + extra));
|
||||
let step = 10f64.powi(-(4 + extra));
|
||||
let mut c = rounded(c, 4 + extra);
|
||||
for _ in 0..OKLCH_CHROMA_STEPS {
|
||||
if c <= 0.0 || oklab::in_srgb(oklab::oklch_to_srgb(l, c, h)) {
|
||||
return Some([l, c.max(0.0), h]);
|
||||
}
|
||||
c = rounded(c - step, 4 + extra);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The most steps [`oklch_rounded`] lowers a chroma by to bring it inside sRGB.
|
||||
const OKLCH_CHROMA_STEPS: usize = 50;
|
||||
|
||||
/// `v` rounded to `places` decimal places.
|
||||
fn rounded(v: f64, places: i32) -> f64 {
|
||||
let f = 10f64.powi(places);
|
||||
(v * f).round() / f
|
||||
}
|
||||
|
||||
/// ` / 50%` for an alpha that rounds to less than 100 %, else nothing.
|
||||
fn alpha_part(alpha: Option<f32>) -> String {
|
||||
let percent = number(f64::from(alpha.unwrap_or(1.0).clamp(0.0, 1.0)) * 100.0, 2);
|
||||
if percent == "100" { String::new() } else { format!(" / {percent}%") }
|
||||
}
|
||||
|
||||
/// A hue in degrees to two places, 360 written as 0.
|
||||
fn hue_text(h: f64) -> String {
|
||||
hue_text_to(h, 2)
|
||||
}
|
||||
|
||||
/// A hue in degrees to `places` places, 360 written as 0.
|
||||
fn hue_text_to(h: f64, places: usize) -> String {
|
||||
let text = number(h, places);
|
||||
if text == "360" { "0".to_string() } else { text }
|
||||
}
|
||||
|
||||
/// `v` to `places` decimal places, without trailing zeros or a sign on zero.
|
||||
fn number(v: f64, places: usize) -> String {
|
||||
let text = format!("{v:.places$}");
|
||||
let text = if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.') } else { text.as_str() };
|
||||
if text == "-0" { "0".to_string() } else { text.to_string() }
|
||||
}
|
||||
|
||||
/// Hue in degrees (0 to 360), saturation and lightness (0 to 1) of `rgb`, by CSS Color 4's
|
||||
/// rgbToHsl (<https://www.w3.org/TR/css-color-4/#rgb-to-hsl>); the hue of a gray is 0.
|
||||
fn rgb_to_hsl([r, g, b]: [f64; 3]) -> [f64; 3] {
|
||||
let (max, min) = (r.max(g).max(b), r.min(g).min(b));
|
||||
let (d, l) = (max - min, (max + min) / 2.0);
|
||||
if d == 0.0 {
|
||||
return [0.0, 0.0, l];
|
||||
}
|
||||
let s = if l == 0.0 || l == 1.0 { 0.0 } else { (max - l) / l.min(1.0 - l) };
|
||||
let h = if max == r {
|
||||
(g - b) / d + if g < b { 6.0 } else { 0.0 }
|
||||
} else if max == g {
|
||||
(b - r) / d + 2.0
|
||||
} else {
|
||||
(r - g) / d + 4.0
|
||||
};
|
||||
[h * 60.0, s, l]
|
||||
}
|
||||
|
||||
/// A hex color of 3, 4, 6 or 8 digits, with or without `#`.
|
||||
fn hex(text: &str) -> Option<CssColor> {
|
||||
let digits = text.strip_prefix('#').unwrap_or(text);
|
||||
if !digits.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let nibbles: Vec<u8> = digits.bytes().filter_map(|b| (b as char).to_digit(16)).map(|d| d as u8).collect();
|
||||
let values: Vec<u8> = match nibbles.len() {
|
||||
3 | 4 => nibbles.iter().map(|n| n * 17).collect(),
|
||||
6 | 8 => nibbles.chunks(2).map(|p| p.iter().fold(0, |v, n| v * 16 + n)).collect(),
|
||||
_ => return None,
|
||||
};
|
||||
let unit = |i: usize| values.get(i).map(|v| f32::from(*v) / 255.0);
|
||||
Some(CssColor { rgb: [unit(0)?, unit(1)?, unit(2)?], alpha: unit(3), space: Space::Srgb })
|
||||
}
|
||||
|
||||
/// One argument of a color function.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Arg {
|
||||
Number(f64),
|
||||
Percent(f64),
|
||||
/// An angle, in degrees.
|
||||
Angle(f64),
|
||||
None,
|
||||
}
|
||||
|
||||
/// The arguments of a color function, `args` being the text inside its parentheses: the three
|
||||
/// components and the alpha, if any, and whether they were separated by commas (the legacy form).
|
||||
fn split(args: &str, legacy_allowed: bool) -> Option<([Arg; 3], Option<Arg>, bool)> {
|
||||
let (parts, alpha, legacy): (Vec<&str>, Option<&str>, bool) = if args.contains(',') {
|
||||
if !legacy_allowed || args.contains('/') {
|
||||
return None;
|
||||
}
|
||||
let mut parts: Vec<&str> = args.split(',').map(css_trim).collect();
|
||||
let alpha = if parts.len() == 4 { parts.pop() } else { None };
|
||||
(parts, alpha, true)
|
||||
} else {
|
||||
let mut halves = args.split('/');
|
||||
let colors = halves.next().unwrap_or_default();
|
||||
let alpha = halves.next();
|
||||
if halves.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
(colors.split_ascii_whitespace().collect(), alpha.map(css_trim), false)
|
||||
};
|
||||
let [a, b, c] = parts.as_slice() else { return None };
|
||||
let one = |s: &str| {
|
||||
let arg = arg(s)?;
|
||||
// The legacy form has no `none`.
|
||||
(!(legacy && arg == Arg::None)).then_some(arg)
|
||||
};
|
||||
let alpha = match alpha {
|
||||
Some(s) => Some(one(s)?),
|
||||
None => None,
|
||||
};
|
||||
Some(([one(a)?, one(b)?, one(c)?], alpha, legacy))
|
||||
}
|
||||
|
||||
/// One argument: `none`, a number, a percentage or an angle (`deg`, `grad`, `rad`, `turn`), with no
|
||||
/// spaces inside it.
|
||||
fn arg(s: &str) -> Option<Arg> {
|
||||
if s.eq_ignore_ascii_case("none") {
|
||||
return Some(Arg::None);
|
||||
}
|
||||
let end = number_end(s)?;
|
||||
let n: f64 = s.get(..end)?.parse().ok().filter(|n: &f64| n.is_finite())?;
|
||||
let unit = s.get(end..)?.to_ascii_lowercase();
|
||||
let arg = match unit.as_str() {
|
||||
"" => Arg::Number(n),
|
||||
"%" => Arg::Percent(n),
|
||||
"deg" => Arg::Angle(n),
|
||||
"grad" => Arg::Angle(n * 0.9),
|
||||
"rad" => Arg::Angle(n.to_degrees()),
|
||||
"turn" => Arg::Angle(n * 360.0),
|
||||
_ => return None,
|
||||
};
|
||||
match arg {
|
||||
Arg::Angle(a) if !a.is_finite() => None,
|
||||
_ => Some(arg),
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte length of the CSS number at the start of `s`: an optional sign, digits with an
|
||||
/// optional fraction (at least one digit, and digits after a `.`), and an optional exponent.
|
||||
fn number_end(s: &str) -> Option<usize> {
|
||||
let b = s.as_bytes();
|
||||
let digits = |from: usize| b.get(from..).map_or(0, |rest| rest.iter().take_while(|c| c.is_ascii_digit()).count());
|
||||
let mut i = usize::from(matches!(b.first(), Some(b'+' | b'-')));
|
||||
let whole = digits(i);
|
||||
i += whole;
|
||||
let mut fraction = 0;
|
||||
if b.get(i) == Some(&b'.') {
|
||||
fraction = digits(i + 1);
|
||||
if fraction == 0 {
|
||||
return None;
|
||||
}
|
||||
i += 1 + fraction;
|
||||
}
|
||||
if whole + fraction == 0 {
|
||||
return None;
|
||||
}
|
||||
if matches!(b.get(i), Some(b'e' | b'E')) {
|
||||
let sign = usize::from(matches!(b.get(i + 1), Some(b'+' | b'-')));
|
||||
let exp = digits(i + 1 + sign);
|
||||
if exp > 0 {
|
||||
i += 1 + sign + exp;
|
||||
}
|
||||
}
|
||||
Some(i)
|
||||
}
|
||||
|
||||
/// The alpha argument from 0 to 1.
|
||||
fn alpha(a: Option<Arg>) -> Option<Option<f32>> {
|
||||
let v = match a {
|
||||
None => return Some(None),
|
||||
Some(Arg::Number(n)) => n,
|
||||
Some(Arg::Percent(p)) => p / 100.0,
|
||||
Some(Arg::None) => 0.0,
|
||||
Some(Arg::Angle(_)) => return None,
|
||||
};
|
||||
Some(Some(v.clamp(0.0, 1.0) as f32))
|
||||
}
|
||||
|
||||
/// A hue argument in degrees from 0 to 360.
|
||||
fn hue(a: Arg) -> Option<f64> {
|
||||
match a {
|
||||
Arg::Number(d) | Arg::Angle(d) => Some(d.rem_euclid(360.0)).filter(|d| d.is_finite()),
|
||||
Arg::None => Some(0.0),
|
||||
Arg::Percent(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn rgb(args: &str) -> Option<CssColor> {
|
||||
let (comps, a, legacy) = split(args, true)?;
|
||||
let percents = comps.iter().filter(|c| matches!(c, Arg::Percent(_))).count();
|
||||
if legacy && percents != 0 && percents != 3 {
|
||||
return None;
|
||||
}
|
||||
let unit = |c: Arg| match c {
|
||||
Arg::Number(n) => Some(n / 255.0),
|
||||
Arg::Percent(p) => Some(p / 100.0),
|
||||
Arg::None => Some(0.0),
|
||||
Arg::Angle(_) => None,
|
||||
};
|
||||
let [r, g, b] = comps;
|
||||
let rgb = [unit(r)?, unit(g)?, unit(b)?].map(|v| v.clamp(0.0, 1.0) as f32);
|
||||
Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Srgb })
|
||||
}
|
||||
|
||||
fn hsl(args: &str) -> Option<CssColor> {
|
||||
let (comps, a, legacy) = split(args, true)?;
|
||||
let [h, s, l] = comps;
|
||||
let percent = |c: Arg| match c {
|
||||
Arg::Percent(v) => Some(v),
|
||||
Arg::Number(v) if !legacy => Some(v),
|
||||
Arg::None => Some(0.0),
|
||||
_ => None,
|
||||
};
|
||||
// CSS clamps a negative saturation to 0 and nothing else.
|
||||
let (h, s, l) = (hue(h)?, percent(s)?.max(0.0) / 100.0, percent(l)? / 100.0);
|
||||
// CSS Color 4's hslToRgb (https://www.w3.org/TR/css-color-4/#hsl-to-rgb); a channel outside
|
||||
// 0..=1 is clipped.
|
||||
let f = |n: f64| {
|
||||
let k = (n + h / 30.0) % 12.0;
|
||||
let amount = s * l.min(1.0 - l);
|
||||
l - amount * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0)
|
||||
};
|
||||
// Huge saturation and lightness values overflow to an infinity or NaN, which is refused.
|
||||
let rgb = [f(0.0), f(8.0), f(4.0)];
|
||||
if rgb.iter().any(|v| !v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let rgb = rgb.map(|v| v.clamp(0.0, 1.0) as f32);
|
||||
Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Srgb })
|
||||
}
|
||||
|
||||
fn oklch(args: &str) -> Option<CssColor> {
|
||||
let (comps, a, _) = split(args, false)?;
|
||||
let [l, c, h] = comps;
|
||||
let l = match l {
|
||||
Arg::Number(v) => v,
|
||||
Arg::Percent(p) => p / 100.0,
|
||||
Arg::None => 0.0,
|
||||
Arg::Angle(_) => return None,
|
||||
};
|
||||
let c = match c {
|
||||
Arg::Number(v) => v,
|
||||
Arg::Percent(p) => p / 100.0 * CHROMA_FULL,
|
||||
Arg::None => 0.0,
|
||||
Arg::Angle(_) => return None,
|
||||
};
|
||||
let (rgb, _) = oklab::from_oklch(l.clamp(0.0, 1.0), c.max(0.0), hue(h)?);
|
||||
Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Oklch })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use proptest::prelude::*;
|
||||
|
||||
fn bytes(text: &str) -> ([u8; 3], Option<u8>) {
|
||||
let c = parse(text).unwrap_or_else(|| panic!("{text} should parse"));
|
||||
(c.rgb.map(byte), c.alpha.map(|a| (a * 255.0).round() as u8))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_colors_take_three_four_six_or_eight_digits_with_or_without_the_hash() {
|
||||
assert_eq!(bytes("#336699"), ([0x33, 0x66, 0x99], None));
|
||||
assert_eq!(bytes("33669980"), ([0x33, 0x66, 0x99], Some(0x80)));
|
||||
assert_eq!(bytes("#369"), ([0x33, 0x66, 0x99], None));
|
||||
assert_eq!(bytes("#3698"), ([0x33, 0x66, 0x99], Some(0x88)));
|
||||
assert_eq!(bytes(" #AbCdEf "), ([0xab, 0xcd, 0xef], None));
|
||||
for bad in ["", "#", "#12", "#12345", "#1234567", "#123456789", "#ggg", "##123", "#+12", "#12 3", "123"] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rgb_reads_the_modern_and_the_legacy_forms() {
|
||||
assert_eq!(bytes("rgb(51 102 153)"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("rgb(51 102 153 / 50%)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("RGBA(51 102 153/0.5)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("rgb(20% 40% 60%)"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("rgb(20% 102 none)"), ([51, 102, 0], None), "the modern form mixes numbers and percentages");
|
||||
assert_eq!(bytes("rgb(51, 102, 153)"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("rgba(51,102,153,.5)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("rgb(51, 102, 153, 50%)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("rgb(300 -20 1e2)"), ([255, 0, 100], None), "components are clamped");
|
||||
assert_eq!(bytes("rgb(0 0 0 / 2)"), ([0, 0, 0], Some(255)), "the alpha is clamped");
|
||||
assert_eq!(bytes("rgb(0 0 0 / none)"), ([0, 0, 0], Some(0)));
|
||||
for bad in [
|
||||
"rgb(51, 102%, 153)",
|
||||
"rgb(51, 102, none)",
|
||||
"rgb(51 102)",
|
||||
"rgb(51 102 153 0.5)",
|
||||
"rgb(51, 102 153)",
|
||||
"rgb(51, 102, 153 / 0.5)",
|
||||
"rgb(51 102 153 / 0.5 / 1)",
|
||||
"rgb(51 102 153deg)",
|
||||
"rgb(1. 2 3)",
|
||||
"rgb(1e999 0 0)",
|
||||
"rgb(51 102 153",
|
||||
"rgb(51 102 153))",
|
||||
"rgb(51 102 153) x",
|
||||
"rgb(calc(1) 2 3)",
|
||||
"rgb(,,)",
|
||||
"rgb (1 2 3)",
|
||||
"rgb()",
|
||||
"rgbx(1 2 3)",
|
||||
] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_spaces_tabs_and_line_breaks_are_whitespace() {
|
||||
assert_eq!(bytes("\t rgb(51,\n102 ,\t153)\r\n"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("rgb(51 102 153 /\t0.5 )"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("\u{c}#336699\u{c}"), ([51, 102, 153], None), "CSS reads a form feed as a line break");
|
||||
assert_eq!(bytes("rgb(51\u{c}102\u{c}153)"), ([51, 102, 153], None));
|
||||
for bad in ["rgb(51,\u{a0}102,153)", "rgb(51,102,153\u{3000})", "\u{a0}#336699", "#336699\u{2003}", "rgb(0 0 0 /\u{a0}1)", "\u{b}#336699"] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hsl_reads_hues_in_every_angle_unit() {
|
||||
assert_eq!(bytes("hsl(210 50% 40%)"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("hsl(210deg 50 40 / 25%)"), ([51, 102, 153], Some(64)));
|
||||
assert_eq!(bytes("hsla(210, 50%, 40%, 0.5)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("hsl(-150 50% 40%)"), ([51, 102, 153], None), "a hue is normalized");
|
||||
assert_eq!(bytes("hsl(0.5turn 100% 50%)"), ([0, 255, 255], None));
|
||||
assert_eq!(bytes("hsl(200grad 100% 50%)"), ([0, 255, 255], None));
|
||||
assert_eq!(bytes("hsl(3.14159265rad 100% 50%)"), ([0, 255, 255], None));
|
||||
assert_eq!(bytes("hsl(120 -20% 50%)"), ([128, 128, 128], None), "a negative saturation is 0");
|
||||
assert_eq!(bytes("hsl(15 150% 50%)"), ([255, 32, 0], None), "a saturation over 100 % is kept and the channels are clipped");
|
||||
assert_eq!(bytes("hsl(0 50% 150%)"), ([255, 255, 255], None));
|
||||
assert_eq!(bytes("hsl(none 0% 100%)"), ([255, 255, 255], None));
|
||||
for bad in
|
||||
["hsl(210, 50, 40)", "hsl(210% 50% 40%)", "hsl(210 50% 40% 1)", "hsl(210deg, 50%, none)", "hsl(1e999deg 0% 0%)", "hsl(1e306turn 0% 0%)"]
|
||||
{
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
// Saturation and lightness this large overflow to an infinity or NaN.
|
||||
for bad in ["hsl(90 1e308% 1e308%)", "hsl(90 1e308 -1e308)"] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oklch_converts_through_srgb_and_has_no_legacy_form() {
|
||||
let c = parse("oklch(62.8% 0.2577 29.23)").unwrap();
|
||||
assert_eq!((c.rgb.map(byte), c.alpha, c.space), ([255, 0, 0], None, Space::Oklch));
|
||||
let c = parse("oklch(0.628 64.4% 29.23 / 0.5)").unwrap();
|
||||
assert_eq!((c.rgb.map(byte), c.alpha), ([255, 0, 0], Some(0.5)));
|
||||
assert_eq!(parse("oklch(1 0 0)").map(|c| c.rgb.map(byte)), Some([255, 255, 255]));
|
||||
assert_eq!(parse("oklch(2 -1 none)").map(|c| c.rgb.map(byte)), Some([255, 255, 255]), "L and C are clamped");
|
||||
let wide = parse("oklch(0.7 0.4 150)").unwrap();
|
||||
assert!(wide.rgb.iter().all(|v| (0.0..=1.0).contains(v)), "a color outside sRGB is brought inside: {:?}", wide.rgb);
|
||||
let huge = parse("oklch(0.5 1e308 30)").unwrap();
|
||||
assert!(huge.rgb.iter().all(|v| (0.0..=1.0).contains(v)), "a huge chroma is brought inside: {:?}", huge.rgb);
|
||||
for bad in ["oklch(0.6, 0.1, 30)", "oklch(0.6 0.1 30% )", "oklch(0.6deg 0.1 30)", "oklch(0.6 0.1)"] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_longer_than_the_limit_is_refused() {
|
||||
let at_limit = format!("rgb(51 102 153{})", " ".repeat(MAX_CHARS - 15));
|
||||
assert_eq!(at_limit.chars().count(), MAX_CHARS);
|
||||
assert!(parse(&at_limit).is_some());
|
||||
let over = format!("rgb(51 102 153{})", " ".repeat(MAX_CHARS - 14));
|
||||
assert_eq!(parse(&over), None);
|
||||
assert_eq!(parse(&format!(" {at_limit} ")).map(|c| c.rgb.map(byte)), Some([51, 102, 153]), "spaces around it are not counted");
|
||||
assert_eq!(parse(&"(".repeat(100_000)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_of_rounds_each_component() {
|
||||
assert_eq!(hex_of([0.2, 0.4, 0.6]), "#336699");
|
||||
assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_writes_each_notation_with_the_alpha_where_it_belongs() {
|
||||
let rgb = [0.2, 0.4, 0.6];
|
||||
let half = Some(0.5);
|
||||
assert_eq!(format(rgb, half, Notation::Hex), "#336699");
|
||||
assert_eq!(format(rgb, half, Notation::HexAlpha), "#33669980");
|
||||
assert_eq!(format(rgb, None, Notation::HexAlpha), "#336699ff");
|
||||
assert_eq!(format(rgb, Some(1.0), Notation::HexAlpha), "#336699ff");
|
||||
assert_eq!(format(rgb, half, Notation::Rgb), "rgb(51 102 153 / 50%)");
|
||||
assert_eq!(format(rgb, None, Notation::Rgb), "rgb(51 102 153)");
|
||||
assert_eq!(format(rgb, Some(0.99999), Notation::Rgb), "rgb(51 102 153)", "an alpha that rounds to 100 % is left out");
|
||||
assert_eq!(format(rgb, Some(0.125), Notation::Hsl), "hsl(210 50% 40% / 12.5%)");
|
||||
assert_eq!(format(rgb, None, Notation::Oklch), "oklch(49.93% 0.0987 250.43)");
|
||||
assert_eq!(format([0.5; 3], None, Notation::Hsl), "hsl(0 0% 50.2%)");
|
||||
assert_eq!(format([1.0; 3], None, Notation::Oklch), "oklch(100% 0 0)");
|
||||
assert_eq!(format([0.0; 3], Some(0.0), Notation::Oklch), "oklch(0% 0 0 / 0%)");
|
||||
assert_eq!(format([1.0, 0.0, 0.0], None, Notation::Hsl), "hsl(0 100% 50%)");
|
||||
assert_eq!(format([-1.0, 2.0, f32::NAN], Some(f32::NAN), Notation::Rgb), "rgb(0 255 0)");
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn random_text_never_panics(text in "\\PC{0,60}") {
|
||||
// `contains` is false for NaN, so these also check that every channel is finite.
|
||||
if let Some(c) = parse(&text) {
|
||||
prop_assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v)));
|
||||
prop_assert!(c.alpha.is_none_or(|a| (0.0..=1.0).contains(&a)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_shaped_text_never_panics(
|
||||
name in "(rgb|rgba|hsl|hsla|oklch|RGB)",
|
||||
args in "[-+0-9.eE%a-z ,/]{0,40}",
|
||||
) {
|
||||
if let Some(c) = parse(&format!("{name}({args})")) {
|
||||
prop_assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eight_digit_hex_round_trips(r: u8, g: u8, b: u8, a: u8) {
|
||||
let c = parse(&format!("#{r:02x}{g:02x}{b:02x}{a:02x}")).unwrap();
|
||||
prop_assert_eq!(c.rgb.map(byte), [r, g, b]);
|
||||
prop_assert_eq!(c.alpha.map(|v| (v * 255.0).round() as u8), Some(a));
|
||||
prop_assert_eq!(hex_of(c.rgb), format!("#{r:02x}{g:02x}{b:02x}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_notation_reads_back_to_the_same_color(r: u8, g: u8, b: u8, a: u8) {
|
||||
let rgb = [r, g, b].map(|v| f32::from(v) / 255.0);
|
||||
let alpha = f32::from(a) / 255.0;
|
||||
for notation in [Notation::Hex, Notation::HexAlpha, Notation::Rgb, Notation::Hsl, Notation::Oklch] {
|
||||
let text = format(rgb, Some(alpha), notation);
|
||||
let c = parse(&text).unwrap_or_else(|| panic!("{text} should parse"));
|
||||
prop_assert_eq!(hex_of(c.rgb), hex_of(rgb), "{}", text);
|
||||
let read = c.alpha.unwrap_or(1.0);
|
||||
match notation {
|
||||
Notation::Hex => prop_assert_eq!(c.alpha, None),
|
||||
Notation::HexAlpha => prop_assert_eq!(byte(read), a),
|
||||
// A percentage to two places, left out when it rounds to 100.
|
||||
_ => prop_assert!((read - alpha).abs() <= 0.00006, "{} gives {}", text, read),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
pub mod blend;
|
||||
pub mod cms;
|
||||
pub mod css;
|
||||
pub mod freeform;
|
||||
pub mod gradient;
|
||||
pub mod harmony;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! the relative luminance of display sRGB with the 0.04045 threshold, the ratio
|
||||
//! (L1 + 0.05) / (L2 + 0.05) from 1 to 21, and the minimum ratios of success criteria 1.4.3
|
||||
//! (Contrast (Minimum), AA), 1.4.6 (Contrast (Enhanced), AAA) and 1.4.11 (Non-text Contrast, AA).
|
||||
//! [`closest_passing`] finds the color of the same hue nearest in lightness that meets a minimum.
|
||||
|
||||
/// What the content in front is, which sets the ratio it needs.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -87,6 +88,82 @@ pub fn ratio_text(ratio: f64) -> String {
|
||||
format!("{:.2}:1", (r * 100.0).floor() / 100.0)
|
||||
}
|
||||
|
||||
/// The lightnesses [`closest_passing`] tests on each side before it narrows down the first that
|
||||
/// passes.
|
||||
const LIGHTNESS_SAMPLES: usize = 16;
|
||||
/// The halvings [`closest_passing`] makes of the lightness step, which leave it within 1e-9.
|
||||
const LIGHTNESS_STEPS: usize = 32;
|
||||
/// The golden-section steps [`closest_passing`] takes to find the highest ratio between samples,
|
||||
/// which leave it within 1e-7 of the step.
|
||||
const PEAK_STEPS: usize = 32;
|
||||
/// Where between `lo` and `hi` `f` is highest, by golden-section search, which finds the top of a
|
||||
/// single peak between them. `f` is called 34 times.
|
||||
pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 {
|
||||
let g = (5f64.sqrt() - 1.0) / 2.0;
|
||||
let (mut a, mut b) = (hi - g * (hi - lo), lo + g * (hi - lo));
|
||||
let (mut fa, mut fb) = (f(a), f(b));
|
||||
for _ in 0..PEAK_STEPS {
|
||||
if fa < fb {
|
||||
(lo, a, fa) = (a, b, fb);
|
||||
b = lo + g * (hi - lo);
|
||||
fb = f(b);
|
||||
} else {
|
||||
(hi, b, fb) = (b, a, fa);
|
||||
a = hi - g * (hi - lo);
|
||||
fa = f(a);
|
||||
}
|
||||
}
|
||||
if fa > fb { a } else { b }
|
||||
}
|
||||
|
||||
/// The display sRGB color closest to `srgb` whose `ratio` is at least `minimum`: the same OKLCH hue
|
||||
/// (<https://bottosson.github.io/posts/oklab/>) with the lightness raised or lowered, whichever
|
||||
/// takes the smaller step, and the chroma lowered where sRGB cannot show it, to the largest chroma
|
||||
/// below it that fits ([`crate::oklab::from_oklch`]). Each side is tested at
|
||||
/// 16 even steps up to white or black, and the step before the first that passes is narrowed down.
|
||||
/// When no step passes, the highest ratio between the neighbors of the highest step is looked for,
|
||||
/// so a color that passes only in a narrow band between white and black (as under a Difference
|
||||
/// blend) is found too. `srgb` itself when it passes, and None when nothing passes. The work is
|
||||
/// bounded: at most 167 colors are tested. The answer is the nearest passing color when the colors
|
||||
/// that pass on each side form one stretch up to white or black, as for a plain contrast ratio.
|
||||
/// When `ratio` lets colors pass in more than one stretch, a stretch that lies between two tested
|
||||
/// steps before the first passing one is missed, and a farther color can be returned.
|
||||
pub fn closest_passing(srgb: [f32; 3], minimum: f64, ratio: &dyn Fn([f32; 3]) -> f64) -> Option<[f32; 3]> {
|
||||
let passes = |c: [f32; 3]| ratio(c) >= minimum;
|
||||
let srgb = srgb.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
|
||||
if passes(srgb) {
|
||||
return Some(srgb);
|
||||
}
|
||||
let [l, c, h] = crate::oklab::to_oklch(srgb);
|
||||
let mut best: Option<(f64, [f32; 3])> = None;
|
||||
for end in [1.0, 0.0] {
|
||||
let at = |t: f64| crate::oklab::from_oklch(l + (end - l) * t, c, h).0;
|
||||
let step = |k: usize| k as f64 / LIGHTNESS_SAMPLES as f64;
|
||||
let ratios: Vec<f64> = (1..=LIGHTNESS_SAMPLES).map(|k| ratio(at(step(k)))).collect();
|
||||
// `lo` fails and `hi` passes, the step before the first sample that passes.
|
||||
let found = match ratios.iter().position(|r| *r >= minimum) {
|
||||
Some(i) => Some((step(i), step(i + 1))),
|
||||
None => {
|
||||
// Every sample fails: look for a higher ratio around the highest one.
|
||||
let top = ratios.iter().enumerate().fold((0, f64::NEG_INFINITY), |m, (i, r)| if *r > m.1 { (i, *r) } else { m }).0;
|
||||
let (lo, hi) = (step(top), step((top + 2).min(LIGHTNESS_SAMPLES)));
|
||||
let peak = peak_between(lo, hi, &|t| ratio(at(t)));
|
||||
passes(at(peak)).then_some((lo, peak))
|
||||
}
|
||||
};
|
||||
let Some((mut lo, mut hi)) = found else { continue };
|
||||
for _ in 0..LIGHTNESS_STEPS {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if passes(at(mid)) { hi = mid } else { lo = mid }
|
||||
}
|
||||
let step = (end - l).abs() * hi;
|
||||
if best.is_none_or(|(d, _)| step < d) {
|
||||
best = Some((step, at(hi)));
|
||||
}
|
||||
}
|
||||
best.map(|(_, c)| c)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -137,6 +214,80 @@ mod tests {
|
||||
assert_eq!(Category::parse("NormalText"), None);
|
||||
}
|
||||
|
||||
fn hue(srgb: [f32; 3]) -> f64 {
|
||||
let [_, a, b] = crate::libraries::srgb_to_oklab(srgb);
|
||||
b.atan2(a).to_degrees()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_closest_passing_color_keeps_the_hue_and_just_passes() {
|
||||
let (fg, bg) = (hex("fdc96e"), hex("355f78"));
|
||||
let fix = closest_passing(fg, 4.5, &|c| contrast_ratio(c, bg)).unwrap();
|
||||
let r = contrast_ratio(fix, bg);
|
||||
assert!((4.5..4.501).contains(&r), "{r}");
|
||||
assert!((hue(fix) - hue(fg)).abs() < 1.0, "{} {}", hue(fix), hue(fg));
|
||||
// A color lighter than the background gets lighter.
|
||||
assert!(relative_luminance(fix) > relative_luminance(fg));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_closest_passing_gray_on_white_is_a_darker_gray() {
|
||||
let white = [1.0; 3];
|
||||
let fix = closest_passing(hex("777777"), 4.5, &|c| contrast_ratio(c, white)).unwrap();
|
||||
let r = contrast_ratio(fix, white);
|
||||
assert!((4.5..4.501).contains(&r), "{r}");
|
||||
assert!((fix[0] - fix[1]).abs() < 1e-4 && (fix[1] - fix[2]).abs() < 1e-4, "{fix:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_that_passes_only_between_white_and_black_is_found() {
|
||||
// White drawn with Difference over mid gray: white and black both draw mid gray (1:1), and
|
||||
// mid gray draws black, 5.3:1.
|
||||
let gray = [0.5; 3];
|
||||
let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
|
||||
let fix = closest_passing([1.0; 3], 4.5, &|c| contrast_ratio(difference(c), gray)).unwrap();
|
||||
let r = contrast_ratio(difference(fix), gray);
|
||||
assert!((4.5..4.51).contains(&r), "{fix:?}: {r}");
|
||||
assert!(fix[0] > 0.5, "the nearest side of mid gray from white: {fix:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_narrow_band_between_the_samples_is_found() {
|
||||
// Over #5A5A5A only colors within a few hundredths of it draw dark enough with Difference
|
||||
// for 3:1 (black reaches 3.04:1), and no even step from white lands there.
|
||||
let gray = hex("5a5a5a");
|
||||
let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
|
||||
let ratio = |c: [f32; 3]| contrast_ratio(difference(c), gray);
|
||||
let fix = closest_passing([1.0; 3], 3.0, &ratio).unwrap();
|
||||
let r = ratio(fix);
|
||||
assert!((3.0..3.01).contains(&r), "{fix:?}: {r}");
|
||||
}
|
||||
|
||||
/// Just below blue's lightness the chromas sRGB holds at blue's hue come in two stretches, so a
|
||||
/// blue that needs a little more contrast keeps nearly all of its chroma.
|
||||
#[test]
|
||||
fn a_blue_that_darkens_a_little_keeps_its_chroma() {
|
||||
let gray = hex("b8b8b8");
|
||||
let ratio = |c: [f32; 3]| contrast_ratio(c, gray);
|
||||
let blue = [0.0, 0.0, 1.0];
|
||||
assert!(ratio(blue) < 4.5, "{}", ratio(blue));
|
||||
let fix = closest_passing(blue, 4.5, &ratio).unwrap();
|
||||
let ([_, c, h], [_, blue_c, blue_h]) = (crate::oklab::to_oklch(fix), crate::oklab::to_oklch(blue));
|
||||
assert!(ratio(fix) >= 4.5 && (h - blue_h).abs() < 1.0, "{fix:?}");
|
||||
assert!(c > blue_c - 0.02, "{fix:?}: chroma {c}, blue's {blue_c}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_passing_color_is_its_own_closest_and_nothing_passing_is_none() {
|
||||
let white = [1.0; 3];
|
||||
assert_eq!(closest_passing([0.0; 3], 7.0, &|c| contrast_ratio(c, white)), Some([0.0; 3]));
|
||||
assert_eq!(closest_passing(hex("808080"), 4.5, &|_| 1.0), None);
|
||||
// Mid gray: AAA for normal text needs 7:1, which neither white nor black reaches.
|
||||
let mid = hex("777777");
|
||||
assert_eq!(closest_passing(mid, 7.0, &|c| contrast_ratio(c, mid)), None);
|
||||
assert_eq!(closest_passing([f32::NAN; 3], 4.5, &|c| contrast_ratio(c, white)).map(|c| c.map(|v| v.is_finite())), Some([true; 3]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_opaque_black_over_white_is_mid_gray() {
|
||||
assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]);
|
||||
|
||||
@@ -28,6 +28,8 @@ tiff = { workspace = true }
|
||||
craft-stream-codecs = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
# The hash of a generated art object's art, which its file holds (`generated`).
|
||||
sha2 = { version = "0.10", default-features = false }
|
||||
thiserror = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
|
||||
|
||||
@@ -192,14 +192,18 @@ pub enum Arrowhead {
|
||||
/// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as
|
||||
/// the other heads.
|
||||
LineArrow,
|
||||
/// A slender filled head, a little over half as wide as it is long, whose sides bend in
|
||||
/// halfway back, with a V-shaped notch in its back: the arrow of mathematical diagrams.
|
||||
NotchedArrow,
|
||||
/// A head the user drew, with its art.
|
||||
Custom(Arc<CustomArrowhead>),
|
||||
}
|
||||
|
||||
impl Arrowhead {
|
||||
/// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks).
|
||||
pub const ALL: [Arrowhead; 41] = [
|
||||
pub const ALL: [Arrowhead; 42] = [
|
||||
Arrowhead::Arrow,
|
||||
Arrowhead::NotchedArrow,
|
||||
Arrowhead::ArrowOpen,
|
||||
Arrowhead::LineArrow,
|
||||
Arrowhead::Barbed,
|
||||
@@ -322,6 +326,7 @@ impl Arrowhead {
|
||||
Arrowhead::TriangleBar => "Triangle to Bar",
|
||||
Arrowhead::Oval => "Oval",
|
||||
Arrowhead::LineArrow => "Line Arrow",
|
||||
Arrowhead::NotchedArrow => "Notched Arrow",
|
||||
Arrowhead::Custom(_) => "Custom",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -316,7 +316,7 @@ fn profile_presets_round_trip_their_ids() {
|
||||
#[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; 41] = [
|
||||
const SAVED: [&str; 42] = [
|
||||
"Triangle",
|
||||
"TriangleOpen",
|
||||
"Circle",
|
||||
@@ -358,6 +358,7 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
|
||||
"TriangleBar",
|
||||
"Oval",
|
||||
"LineArrow",
|
||||
"NotchedArrow",
|
||||
];
|
||||
for name in SAVED {
|
||||
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
|
||||
|
||||
+109
-13
@@ -394,6 +394,11 @@ pub enum DimensionSource {
|
||||
/// it is vertical. Versions without this source do not open the file.
|
||||
Extent {
|
||||
node: NodeId,
|
||||
/// Placed with Use Preview Bounds on: the points are moved out to the outside of the
|
||||
/// strokes the path paints ([`preview_extents`]), the width or height that W and H show.
|
||||
/// Versions without it measure between the outermost points themselves.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
preview: bool,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -402,7 +407,7 @@ impl DimensionSource {
|
||||
match self {
|
||||
Self::Segment { edge } | Self::Arc { edge } => vec![edge.node],
|
||||
Self::Angle { first, second } => vec![first.node, second.node],
|
||||
Self::Circle { node } | Self::Extent { node } => vec![*node],
|
||||
Self::Circle { node } | Self::Extent { node, .. } => vec![*node],
|
||||
Self::Points { a, b, vertex, free_a, free_b } => [a, b, vertex]
|
||||
.into_iter()
|
||||
.filter_map(|p| p.as_ref().map(|r| r.node))
|
||||
@@ -425,10 +430,18 @@ impl DimensionSource {
|
||||
})
|
||||
}
|
||||
/// Whether a path it measures differs between `before` and `after`, or is in only one of them.
|
||||
/// A node without a path, or missing from both, counts as changed.
|
||||
/// A node without a path, or missing from both, counts as changed. For a dimension of a whole
|
||||
/// path placed with Use Preview Bounds on, so does a change to the strokes the path paints
|
||||
/// ([`stroked_by`]): their appearance, the node they come from, or which arrowheads they draw
|
||||
/// on it, and the path being made into a guide or released from one.
|
||||
pub fn art_changed(&self, before: &Document, after: &Document) -> bool {
|
||||
let strokes = matches!(self, Self::Extent { preview: true, .. });
|
||||
self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) {
|
||||
(Some(old), Some(new)) => old.path_data().is_none() || (!std::ptr::eq(old, new) && old.path_data() != new.path_data()),
|
||||
(Some(old), Some(new)) => {
|
||||
old.path_data().is_none()
|
||||
|| (!std::ptr::eq(old, new) && old.path_data() != new.path_data())
|
||||
|| (strokes && (old.is_guide() != new.is_guide() || stroked_by(before, id) != stroked_by(after, id)))
|
||||
}
|
||||
_ => true,
|
||||
})
|
||||
}
|
||||
@@ -845,7 +858,9 @@ impl Dimension {
|
||||
let (a, b) = (self.a.to_vec2().dot(n), self.b.to_vec2().dot(n));
|
||||
let (low, high) = (a.min(b), a.max(b));
|
||||
match (doc, &self.source) {
|
||||
(Some(doc), Some(DimensionSource::Extent { node })) => reach(doc, *node, n).map_or((low, high), |(l, h)| (low.min(l), high.max(h))),
|
||||
(Some(doc), Some(DimensionSource::Extent { node, preview })) => {
|
||||
reach(doc, *node, n, *preview).map_or((low, high), |(l, h)| (low.min(l), high.max(h)))
|
||||
}
|
||||
_ => (low, high),
|
||||
}
|
||||
}
|
||||
@@ -891,8 +906,8 @@ impl Dimension {
|
||||
};
|
||||
}
|
||||
next.orientation = orientation;
|
||||
if let Some(DimensionSource::Extent { node }) = &next.source {
|
||||
(next.a, next.b) = extent(doc, *node, orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?;
|
||||
if let Some(DimensionSource::Extent { node, preview }) = &next.source {
|
||||
(next.a, next.b) = extent(doc, *node, orientation == Orientation::Vertical, *preview).ok_or("Measured path no longer exists")?;
|
||||
}
|
||||
// Along the new normal, relative to the new first point, so that the result is the offset.
|
||||
let n = next.normal();
|
||||
@@ -1020,8 +1035,8 @@ impl Dimension {
|
||||
let (center, radius) = arc(doc, edge).ok_or("Choose a circle or a perfect arc")?;
|
||||
self.set_radial(center, radius);
|
||||
}
|
||||
Some(DimensionSource::Extent { node }) => {
|
||||
let (a, b) = extent(doc, *node, self.orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?;
|
||||
Some(DimensionSource::Extent { node, preview }) => {
|
||||
let (a, b) = extent(doc, *node, self.orientation == Orientation::Vertical, *preview).ok_or("Measured path no longer exists")?;
|
||||
self.a = a;
|
||||
self.b = b;
|
||||
self.length = self.measured();
|
||||
@@ -1176,14 +1191,86 @@ fn same_extents(before: &Document, after: &Document, id: NodeId) -> bool {
|
||||
}
|
||||
|
||||
/// [`extents`] along one axis: the leftmost and the rightmost points, or with `vertical` the
|
||||
/// topmost and the bottommost.
|
||||
pub fn extent(doc: &Document, id: NodeId, vertical: bool) -> Option<(Point, Point)> {
|
||||
extents(doc, id).map(|ends| ends[usize::from(vertical)])
|
||||
/// topmost and the bottommost. With `preview`, the points of [`preview_extents`].
|
||||
pub fn extent(doc: &Document, id: NodeId, vertical: bool, preview: bool) -> Option<(Point, Point)> {
|
||||
let ends = if preview { preview_extents(doc, id) } else { extents(doc, id) };
|
||||
ends.map(|ends| ends[usize::from(vertical)])
|
||||
}
|
||||
|
||||
/// [`extents`] moved out to the box the path paints, its strokes included ([`painted_box`]), as Use
|
||||
/// Preview Bounds measures it: the leftmost and the rightmost points move out to that box's left
|
||||
/// and right sides at the same height, and the topmost and the bottommost to its top and bottom at
|
||||
/// the same place across. A path that paints no stroke keeps the points of [`extents`]. None for a
|
||||
/// node without a path or without segments.
|
||||
pub fn preview_extents(doc: &Document, id: NodeId) -> Option<[(Point, Point); 2]> {
|
||||
let [(left, right), (top, bottom)] = extents(doc, id)?;
|
||||
let Some(b) = painted_box(doc, id) else { return Some([(left, right), (top, bottom)]) };
|
||||
Some([
|
||||
(Point::new(left.x.min(b.x0), left.y), Point::new(right.x.max(b.x1), right.y)),
|
||||
(Point::new(top.x, top.y.min(b.y0)), Point::new(bottom.x, bottom.y.max(b.y1))),
|
||||
])
|
||||
}
|
||||
|
||||
/// The node whose strokes a path paints with: the compound path that holds it, or the path itself.
|
||||
fn painter(doc: &Document, id: NodeId) -> Option<&crate::Node> {
|
||||
let n = doc.node(id)?;
|
||||
match doc.parent_of(id).and_then(|p| doc.node(p)) {
|
||||
Some(c) if matches!(c.kind, crate::NodeKind::Compound { .. }) => Some(c),
|
||||
_ => Some(n),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the strokes a path paints with depend on, besides its own shape: the node they come from
|
||||
/// ([`painter`]), its appearance, and which arrowheads they draw on the path ([`heads_on`]).
|
||||
fn stroked_by(doc: &Document, id: NodeId) -> Option<(NodeId, &crate::Appearance, (bool, bool))> {
|
||||
painter(doc, id).map(|p| (p.id, &*p.appearance, heads_on(p, id)))
|
||||
}
|
||||
|
||||
/// The box a path paints, its strokes included, measured along its own shape as
|
||||
/// [`crate::Node::visual_bounds`] measures a path: a member of a compound path is stroked with the
|
||||
/// compound path's strokes, with only the arrowheads the compound path paints on it. None for a
|
||||
/// node without a path or without anything drawn, and for a path made into a guide, which paints
|
||||
/// no strokes.
|
||||
fn painted_box(doc: &Document, id: NodeId) -> Option<vectorcraft_geom::Rect> {
|
||||
let n = doc.node(id)?;
|
||||
if n.is_guide() {
|
||||
return None;
|
||||
}
|
||||
let path = n.path_data()?;
|
||||
let painter = painter(doc, id)?;
|
||||
let a = &painter.appearance;
|
||||
// A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath.
|
||||
let dots = a.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square));
|
||||
let b = path.drawn_bounds(dots).or_else(|| n.geometric_bounds())?;
|
||||
let (start, end) = heads_on(painter, id);
|
||||
let mut shape = None;
|
||||
Some(a.stroked_bounds_by(b, |s| {
|
||||
let bp = shape.get_or_insert_with(|| n.stroke_path().unwrap_or_default());
|
||||
if (s.start_arrow.is_some() && !start) || (s.end_arrow.is_some() && !end) {
|
||||
let mut s = s.clone();
|
||||
s.start_arrow = s.start_arrow.filter(|_| start);
|
||||
s.end_arrow = s.end_arrow.filter(|_| end);
|
||||
s.bounds_on(bp, b)
|
||||
} else {
|
||||
s.bounds_on(bp, b)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
/// Whether the start and the end arrowheads of `painter`'s strokes can be drawn on its member
|
||||
/// `id`. A compound path's strokes put the start head on its first subpath and the end head on its
|
||||
/// last, so a member gets the start head only when it holds the first subpath with anchors and
|
||||
/// the end head only when it holds the last one. A path that is its own painter gets both.
|
||||
fn heads_on(painter: &crate::Node, id: NodeId) -> (bool, bool) {
|
||||
let Some(members) = painter.children().filter(|_| painter.id != id) else { return (true, true) };
|
||||
let drawn = |c: &&std::sync::Arc<crate::Node>| c.path_data().is_some_and(|p| p.subpaths.iter().any(|sp| !sp.anchors.is_empty()));
|
||||
(members.iter().find(drawn).is_some_and(|c| c.id == id), members.iter().rfind(drawn).is_some_and(|c| c.id == id))
|
||||
}
|
||||
|
||||
/// How far a path's outline reaches along the unit direction `u`: the lowest and the highest
|
||||
/// `p · u` over the points of its segments. None for a node without a path or without segments.
|
||||
pub fn reach(doc: &Document, id: NodeId, u: Vec2) -> Option<(f64, f64)> {
|
||||
/// `p · u` over the points of its segments, and with `preview` over the corners of the box it
|
||||
/// paints too ([`painted_box`]). None for a node without a path or without segments.
|
||||
pub fn reach(doc: &Document, id: NodeId, u: Vec2, preview: bool) -> Option<(f64, f64)> {
|
||||
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveExtrema};
|
||||
let path = doc.node(id)?.path_data()?;
|
||||
// Turns `u` onto the x axis, so the turned curve's extrema include those along `u`.
|
||||
@@ -1204,6 +1291,15 @@ pub fn reach(doc: &Document, id: NodeId, u: Vec2) -> Option<(f64, f64)> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if preview
|
||||
&& let Some((low, high)) = span.as_mut()
|
||||
&& let Some(b) = painted_box(doc, id)
|
||||
{
|
||||
for corner in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)] {
|
||||
let v = corner.to_vec2().dot(u);
|
||||
(*low, *high) = (low.min(v), high.max(v));
|
||||
}
|
||||
}
|
||||
span
|
||||
}
|
||||
|
||||
|
||||
@@ -314,8 +314,14 @@ impl Document {
|
||||
self.renumber_stored_duplicates();
|
||||
}
|
||||
|
||||
/// Find a node anywhere in the tree.
|
||||
/// Find a node anywhere in the tree. With the lookup cache built, the node comes from the place the cache has for
|
||||
/// it, read once and without copying its index path; otherwise, and when that place no longer holds it, as
|
||||
/// [`Document::index_path`] finds it.
|
||||
pub fn node(&self, id: NodeId) -> Option<&Node> {
|
||||
if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id)) {
|
||||
crate::id_index::note_path_lookup();
|
||||
return Some(n);
|
||||
}
|
||||
self.index_path(id).and_then(|p| self.node_at(&p))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,597 @@
|
||||
//! Generated art objects: a group whose children a generator plug-in drew from its parameters
|
||||
//! (`plugin.generate`). The group keeps the plug-in's id and name, the parameters it was drawn with
|
||||
//! and the transform its art has had since, so `plugin.editGenerated` can run the plug-in again and
|
||||
//! replace the art. Its children are ordinary objects for every renderer and exporter, so the art
|
||||
//! draws, prints and exports whether or not the plug-in is installed.
|
||||
//!
|
||||
//! A file holds the fields beside a SHA-256 of the art as it was written ([`art_hash`]). Reading
|
||||
//! never runs a plug-in. A field that can't be read (an id that is not a plug-in id, parameters
|
||||
//! that are not an object or are past [`MAX_PARAMS_BYTES`], a transform that is not one) marks the
|
||||
//! object [`State::Damaged`], and art that doesn't match the hash marks it [`State::Changed`]: the
|
||||
//! art stays as it was read either way. A damaged object is saved with `damaged: true`, so it stays
|
||||
//! damaged when the file is opened again.
|
||||
//!
|
||||
//! A generated art object inside another one's art (anywhere in its children or their opacity
|
||||
//! masks) is written and read as plain art: its settings are left out of the file, and a file that
|
||||
//! has them there anyway loses them when it is read, its outer object marked [`State::Changed`]
|
||||
//! without hashing. So each object's art is written and hashed once, whatever the nesting.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::{Map, Value};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
use crate::Effect;
|
||||
use crate::node::{Node, NodeKind, Scaling};
|
||||
|
||||
/// Most bytes a generated art object's parameters take, written as JSON.
|
||||
pub const MAX_PARAMS_BYTES: usize = 64 << 10;
|
||||
|
||||
/// Most bytes the art of a generated art object takes when a generator draws it, written as JSON.
|
||||
pub const MAX_ART_BYTES: usize = 16 << 20;
|
||||
|
||||
/// Longest plug-in id, in bytes, as plug-in manifests limit it.
|
||||
pub const MAX_ID: usize = 64;
|
||||
|
||||
/// Longest plug-in name kept, in characters, as plug-in manifests limit it.
|
||||
pub const MAX_NAME: usize = 64;
|
||||
|
||||
/// How the fields of a generated art object were read.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum State {
|
||||
/// Made in this session, or read with every field and the art's hash intact.
|
||||
#[default]
|
||||
Intact,
|
||||
/// A field could not be read: the plug-in id is not one, or the parameters or the transform
|
||||
/// are not usable. The art can't be drawn again.
|
||||
Damaged,
|
||||
/// The fields were read, but the art doesn't match the hash the file gave for it.
|
||||
Changed,
|
||||
}
|
||||
|
||||
/// The settings of a generated art object ([`crate::NodeExtras::generated`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct GeneratedArt {
|
||||
/// The id of the plug-in that drew it.
|
||||
pub plugin: String,
|
||||
/// The plug-in's name when it drew it, to name the plug-in while it is not installed.
|
||||
pub name: String,
|
||||
/// The plug-in's parameters it was drawn with, each one given.
|
||||
pub params: Map<String, Value>,
|
||||
/// The transform its art has had since it was drawn (moves, scales, rotations, reflections
|
||||
/// and shears).
|
||||
pub transform: Affine,
|
||||
/// What its art's stroke weights and dashes have been scaled by since it was drawn (the
|
||||
/// transforms made with Scale Strokes & Effects on).
|
||||
pub stroke_scale: f64,
|
||||
/// What its art's effect distances have been scaled by since it was drawn.
|
||||
pub effect_scale: f64,
|
||||
/// The transform its art's pattern tiles have had since it was drawn (the transforms made with
|
||||
/// Transform Patterns on).
|
||||
pub pattern_transform: Affine,
|
||||
/// How it was read; not written to files.
|
||||
pub state: State,
|
||||
}
|
||||
|
||||
impl GeneratedArt {
|
||||
/// The settings of art drawn by plug-in `plugin` (named `name`) with `params`, not transformed
|
||||
/// since.
|
||||
pub fn new(plugin: &str, name: &str, params: Map<String, Value>) -> Self {
|
||||
Self {
|
||||
plugin: plugin.into(),
|
||||
name: name.chars().take(MAX_NAME).collect(),
|
||||
params,
|
||||
transform: Affine::IDENTITY,
|
||||
stroke_scale: 1.0,
|
||||
effect_scale: 1.0,
|
||||
pattern_transform: Affine::IDENTITY,
|
||||
state: State::Intact,
|
||||
}
|
||||
}
|
||||
|
||||
/// Its art transformed by `a`, with what `sc` says scales besides its geometry.
|
||||
pub fn transform(&mut self, a: Affine, sc: &Scaling) {
|
||||
self.transform = a * self.transform;
|
||||
if let Some(k) = Scaling::factor(a)
|
||||
&& sc.strokes
|
||||
{
|
||||
self.stroke_scale *= k;
|
||||
if sc.effects.is_some() {
|
||||
self.effect_scale *= k;
|
||||
}
|
||||
}
|
||||
if sc.patterns {
|
||||
self.pattern_transform = a * self.pattern_transform;
|
||||
}
|
||||
}
|
||||
|
||||
/// Places `art`, drawn by the generator as it is drawn untransformed, as the object's art has
|
||||
/// been transformed since it was drawn: its geometry, stroke weights, effect distances and
|
||||
/// pattern tiles. `scale` scales an effect's distance parameters (the effects catalogue's).
|
||||
pub fn place(&self, art: &mut Node, scale: fn(&mut Effect, f64)) {
|
||||
if self.transform != Affine::IDENTITY {
|
||||
art.transform(self.transform, false);
|
||||
}
|
||||
self.restyle(art, scale);
|
||||
}
|
||||
|
||||
/// Scales the strokes and effects of `n` and its descendants, and transforms their pattern
|
||||
/// tiles, as [`Self::place`] says.
|
||||
fn restyle(&self, n: &mut Node, scale: fn(&mut Effect, f64)) {
|
||||
if self.stroke_scale != 1.0 {
|
||||
n.appearance.scale_strokes(self.stroke_scale);
|
||||
}
|
||||
if self.effect_scale != 1.0 {
|
||||
n.appearance.scale_effects(self.effect_scale, scale);
|
||||
}
|
||||
if self.pattern_transform != Affine::IDENTITY {
|
||||
crate::pattern::transform_pattern_paints(n, self.pattern_transform);
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
self.restyle(std::sync::Arc::make_mut(c), scale);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Can its art be drawn again: are its fields intact or only its art changed?
|
||||
pub fn redrawable(&self) -> bool {
|
||||
self.state != State::Damaged
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `id` shaped as a plug-in id: 1 to [`MAX_ID`] characters from `A-Z a-z 0-9 . _ -`?
|
||||
pub fn valid_id(id: &str) -> bool {
|
||||
(1..=MAX_ID).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
|
||||
}
|
||||
|
||||
std::thread_local! {
|
||||
/// Is a generated art object's art being written on this thread ([`Inside`])?
|
||||
static INSIDE: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
/// The bytes [`art_hash`] has hashed on this thread.
|
||||
static HASHED: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// While it lives, objects written on this thread are part of a generated art object's art, and
|
||||
/// the generated art objects among them are written as plain art ([`written`]).
|
||||
pub(crate) struct Inside(bool);
|
||||
|
||||
impl Inside {
|
||||
pub(crate) fn enter() -> Self {
|
||||
Self(INSIDE.with(|i| i.replace(true)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Inside {
|
||||
fn drop(&mut self) {
|
||||
INSIDE.with(|i| i.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings `g` an object writes: none while a generated art object's art is being written.
|
||||
pub(crate) fn written(g: Option<&GeneratedArt>) -> Option<&GeneratedArt> {
|
||||
g.filter(|_| !INSIDE.with(Cell::get))
|
||||
}
|
||||
|
||||
/// The SHA-256 of `children` written as JSON, in lower-case hexadecimal: what a file holds as the
|
||||
/// hash of a generated art object's art. Generated art objects among them are written as plain
|
||||
/// art.
|
||||
pub fn art_hash(children: &[Arc<Node>]) -> String {
|
||||
use sha2::{Digest, Sha256};
|
||||
let bytes = {
|
||||
let _inside = Inside::enter();
|
||||
serde_json::to_vec(children).unwrap_or_default()
|
||||
};
|
||||
#[cfg(test)]
|
||||
HASHED.with(|h| h.set(h.get() + bytes.len()));
|
||||
Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// The bytes `children` take written as JSON, generated art objects among them as plain art
|
||||
/// ([`MAX_ART_BYTES`]).
|
||||
pub fn art_bytes(children: &[Arc<Node>]) -> usize {
|
||||
let _inside = Inside::enter();
|
||||
serde_json::to_vec(children).map_or(usize::MAX, |b| b.len())
|
||||
}
|
||||
|
||||
/// Drops the settings of the generated art objects in `nodes`, among their descendants and in
|
||||
/// their opacity masks' art, which become plain art; returns whether there were any. It doesn't
|
||||
/// look among the children of such an object, which reading it already made plain art, only at
|
||||
/// its opacity mask's art.
|
||||
fn plain_art(nodes: &mut [Arc<Node>]) -> bool {
|
||||
let mut found = false;
|
||||
for a in nodes {
|
||||
let generated = a.extras().generated.is_some();
|
||||
if !generated && a.children().is_none_or(Vec::is_empty) && a.extras().mask.is_none() {
|
||||
continue;
|
||||
}
|
||||
let n = Arc::make_mut(a);
|
||||
if generated {
|
||||
n.extras_mut().generated = None;
|
||||
found = true;
|
||||
} else if let Some(ch) = n.children_mut() {
|
||||
found |= plain_art(ch);
|
||||
}
|
||||
if n.extras().mask.is_some()
|
||||
&& let Some(m) = n.extras_mut().mask.as_mut()
|
||||
{
|
||||
found |= plain_art(std::slice::from_mut(&mut m.art));
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// How a file holds a generated art object's settings, borrowed from the node.
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct Wire<'a> {
|
||||
plugin: &'a str,
|
||||
name: &'a str,
|
||||
params: &'a Map<String, Value>,
|
||||
#[serde(skip_serializing_if = "is_identity")]
|
||||
transform: &'a Affine,
|
||||
#[serde(rename = "strokeScale", skip_serializing_if = "is_one")]
|
||||
stroke_scale: f64,
|
||||
#[serde(rename = "effectScale", skip_serializing_if = "is_one")]
|
||||
effect_scale: f64,
|
||||
#[serde(rename = "patternTransform", skip_serializing_if = "is_identity")]
|
||||
pattern_transform: &'a Affine,
|
||||
hash: String,
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
damaged: bool,
|
||||
}
|
||||
|
||||
fn is_identity(a: &&Affine) -> bool {
|
||||
**a == Affine::IDENTITY
|
||||
}
|
||||
|
||||
fn is_one(k: &f64) -> bool {
|
||||
*k == 1.0
|
||||
}
|
||||
|
||||
impl<'a> Wire<'a> {
|
||||
/// The settings `g` of node `n`, with the hash of its art.
|
||||
pub(crate) fn of(g: &'a GeneratedArt, n: &Node) -> Self {
|
||||
let hash = art_hash(n.children().map_or(&[][..], Vec::as_slice));
|
||||
Wire {
|
||||
plugin: &g.plugin,
|
||||
name: &g.name,
|
||||
params: &g.params,
|
||||
transform: &g.transform,
|
||||
stroke_scale: g.stroke_scale,
|
||||
effect_scale: g.effect_scale,
|
||||
pattern_transform: &g.pattern_transform,
|
||||
hash,
|
||||
damaged: g.state == State::Damaged,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A saved transform `t` (absent: none): `None` when it is not six finite numbers.
|
||||
fn read_affine(t: Option<Value>) -> Option<Affine> {
|
||||
match t {
|
||||
None => Some(Affine::IDENTITY),
|
||||
Some(t) => serde_json::from_value::<Affine>(t).ok().filter(|a| a.as_coeffs().iter().all(|c| c.is_finite())),
|
||||
}
|
||||
}
|
||||
|
||||
/// A saved scale `k` (absent: 1): `None` when it is not a finite number of 0 or more. A transform
|
||||
/// that flattens the art to a line or a point scales its strokes and effects by 0.
|
||||
fn read_scale(k: Option<Value>) -> Option<f64> {
|
||||
match k {
|
||||
None => Some(1.0),
|
||||
Some(k) => k.as_f64().filter(|k| k.is_finite() && *k >= 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings a file gives (`v`, its `generated` field) for a node of `kind`: `None` for anything
|
||||
/// but a group, else what could be read, marked [`State::Damaged`] or [`State::Changed`] when a
|
||||
/// field or the art's hash doesn't hold up. A field that can't be read is kept empty: an id is
|
||||
/// kept only when it is a plug-in id, a name at most [`MAX_NAME`] characters long. Generated art
|
||||
/// objects in the group's art become plain art ([`plain_art`]), and the art is then not hashed.
|
||||
pub(crate) fn read(v: Value, kind: &mut NodeKind) -> Option<Box<GeneratedArt>> {
|
||||
let NodeKind::Group { children, .. } = kind else { return None };
|
||||
let nested = plain_art(children);
|
||||
let Value::Object(mut o) = v else {
|
||||
return Some(Box::new(GeneratedArt { state: State::Damaged, ..GeneratedArt::new("", "", Map::new()) }));
|
||||
};
|
||||
let mut damaged = !matches!(o.remove("damaged"), None | Some(Value::Bool(false)));
|
||||
let plugin = match o.remove("plugin") {
|
||||
Some(Value::String(id)) if valid_id(&id) => id,
|
||||
_ => {
|
||||
damaged = true;
|
||||
String::new()
|
||||
}
|
||||
};
|
||||
let name: String = match o.remove("name") {
|
||||
Some(Value::String(n)) => n.chars().filter(|c| !c.is_control()).take(MAX_NAME).collect(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let params = match o.remove("params") {
|
||||
Some(Value::Object(p)) if serde_json::to_vec(&p).is_ok_and(|b| b.len() <= MAX_PARAMS_BYTES) => p,
|
||||
_ => {
|
||||
damaged = true;
|
||||
Map::new()
|
||||
}
|
||||
};
|
||||
let mut affine = |key: &str| {
|
||||
read_affine(o.remove(key)).unwrap_or_else(|| {
|
||||
damaged = true;
|
||||
Affine::IDENTITY
|
||||
})
|
||||
};
|
||||
let transform = affine("transform");
|
||||
let pattern_transform = affine("patternTransform");
|
||||
let mut scale = |key: &str| {
|
||||
read_scale(o.remove(key)).unwrap_or_else(|| {
|
||||
damaged = true;
|
||||
1.0
|
||||
})
|
||||
};
|
||||
let stroke_scale = scale("strokeScale");
|
||||
let effect_scale = scale("effectScale");
|
||||
let intact = !nested && matches!(o.get("hash"), Some(Value::String(h)) if *h == art_hash(children));
|
||||
let state = if damaged {
|
||||
State::Damaged
|
||||
} else if intact {
|
||||
State::Intact
|
||||
} else {
|
||||
State::Changed
|
||||
};
|
||||
Some(Box::new(GeneratedArt { plugin, name, params, transform, stroke_scale, effect_scale, pattern_transform, state }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::node::NodeId;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
fn art() -> Node {
|
||||
let square = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Default::default());
|
||||
let mut g = Node::group(NodeId(1), vec![Arc::new(square)]);
|
||||
let mut params = Map::new();
|
||||
params.insert("size".into(), json!(10));
|
||||
g.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", params)));
|
||||
g
|
||||
}
|
||||
|
||||
fn reread(v: &Value) -> Node {
|
||||
serde_json::from_value(v.clone()).unwrap()
|
||||
}
|
||||
|
||||
/// `depth` generated art objects, each the only child of the one around it, the innermost
|
||||
/// [`art`].
|
||||
fn nested(depth: usize) -> Node {
|
||||
let mut n = art();
|
||||
for i in 1..depth {
|
||||
let mut g = Node::group(NodeId(10 + i as u64), vec![Arc::new(n)]);
|
||||
g.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", Map::new())));
|
||||
n = g;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// The bytes [`art_hash`] hashes while `f` runs.
|
||||
fn hashed<T>(f: impl FnOnce() -> T) -> (T, usize) {
|
||||
HASHED.with(|h| h.set(0));
|
||||
let out = f();
|
||||
(out, HASHED.with(Cell::get))
|
||||
}
|
||||
|
||||
/// The generated art objects in `n` and below it, outermost first, as (depth, state).
|
||||
fn generated_in(n: &Node) -> Vec<(usize, State)> {
|
||||
let mut out = vec![];
|
||||
let mut at = Some((n, 0));
|
||||
while let Some((n, d)) = at {
|
||||
if let Some(g) = &n.extras().generated {
|
||||
out.push((d, g.state));
|
||||
}
|
||||
at = n.children().and_then(|c| c.first()).map(|c| (&**c, d + 1));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Generated art objects nested in one another are written with the outermost one's settings
|
||||
/// alone, so writing and reading them hash each object's art once, however deep they nest; a
|
||||
/// file that has settings on the inner ones anyway loses them, without hashing.
|
||||
#[test]
|
||||
fn nested_generated_art_is_written_and_read_with_its_art_hashed_once() {
|
||||
crate::depth::with_deep_stack(|| {
|
||||
for depth in [16, 200] {
|
||||
let n = nested(depth);
|
||||
let (bytes, writing) = hashed(|| serde_json::to_vec(&n).unwrap());
|
||||
assert!(writing <= bytes.len(), "{depth} deep: {writing} bytes hashed to write {}", bytes.len());
|
||||
assert_eq!(String::from_utf8_lossy(&bytes).matches("\"generated\"").count(), 1, "{depth} deep");
|
||||
let v = serde_json::to_value(&n).unwrap();
|
||||
let (back, reading) = hashed(|| reread(&v));
|
||||
assert!(reading <= bytes.len(), "{depth} deep: {reading} bytes hashed to read {}", bytes.len());
|
||||
assert_eq!(generated_in(&back), vec![(0, State::Intact)], "{depth} deep");
|
||||
// Settings on every level, each with a hash: none is hashed, the inner ones are
|
||||
// dropped, and the outermost reads as changed.
|
||||
let mut crafted = v.clone();
|
||||
let settings = v["generated"].clone();
|
||||
let mut at = crafted.pointer_mut("/kind/children/0");
|
||||
while let Some(c) = at {
|
||||
if c.pointer("/kind/children/0").is_some() {
|
||||
c["generated"] = settings.clone();
|
||||
}
|
||||
at = c.pointer_mut("/kind/children/0");
|
||||
}
|
||||
let (crafted_back, reading) = hashed(|| reread(&crafted));
|
||||
assert!(reading <= bytes.len(), "{depth} deep, crafted: {reading} bytes hashed to read {}", bytes.len());
|
||||
assert_eq!(generated_in(&crafted_back), vec![(0, State::Changed)], "{depth} deep, crafted");
|
||||
assert_eq!(crafted_back.children(), back.children(), "{depth} deep, crafted");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A generated art object inside another one's art, whose opacity mask's art is a generated art
|
||||
/// object too, reads as plain art with plain mask art.
|
||||
#[test]
|
||||
fn a_nested_generated_art_objects_mask_art_reads_as_plain_art() {
|
||||
let mut inner = art();
|
||||
inner.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(art(), true)));
|
||||
let mut outer = Node::group(NodeId(20), vec![Arc::new(inner)]);
|
||||
outer.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", Map::new())));
|
||||
let v = serde_json::to_value(&outer).unwrap();
|
||||
assert!(v.pointer("/kind/children/0/generated").is_none() && v.pointer("/kind/children/0/mask/art/generated").is_none());
|
||||
let mut crafted = v.clone();
|
||||
let settings = v["generated"].clone();
|
||||
crafted["kind"]["children"][0]["generated"] = settings.clone();
|
||||
crafted["kind"]["children"][0]["mask"]["art"]["generated"] = settings;
|
||||
let back = reread(&crafted);
|
||||
assert_eq!(back.extras().generated.as_ref().map(|g| g.state), Some(State::Changed));
|
||||
let inner = &back.children().unwrap()[0];
|
||||
assert!(inner.extras().generated.is_none());
|
||||
assert!(inner.extras().mask.as_ref().is_some_and(|m| m.art.extras().generated.is_none()));
|
||||
assert_eq!(back.children(), reread(&v).children());
|
||||
}
|
||||
|
||||
/// A generated art object inside plain groups is still checked against its hash: intact as
|
||||
/// written, changed when its art is tampered with.
|
||||
#[test]
|
||||
fn a_generated_art_object_deep_in_plain_groups_keeps_its_hash_check() {
|
||||
crate::depth::with_deep_stack(|| {
|
||||
let mut n = art();
|
||||
for i in 1..200 {
|
||||
n = Node::group(NodeId(10 + i as u64), vec![Arc::new(n)]);
|
||||
}
|
||||
let v = serde_json::to_value(&n).unwrap();
|
||||
let state = |v: &Value| generated_in(&reread(v)).into_iter().map(|(_, s)| s).collect::<Vec<_>>();
|
||||
assert_eq!(state(&v), vec![State::Intact]);
|
||||
let mut tampered = v.clone();
|
||||
let mut at = tampered.pointer_mut("/kind/children/0");
|
||||
while let Some(c) = at {
|
||||
if c.get("generated").is_some() {
|
||||
c["kind"]["children"][0]["name"] = json!("tampered");
|
||||
break;
|
||||
}
|
||||
at = c.pointer_mut("/kind/children/0");
|
||||
}
|
||||
assert_eq!(state(&tampered), vec![State::Changed]);
|
||||
});
|
||||
}
|
||||
|
||||
/// A generated art object writes its plug-in, name, parameters and the hash of its art, and
|
||||
/// reads back the same, intact.
|
||||
#[test]
|
||||
fn a_generated_art_object_round_trips_with_the_hash_of_its_art() {
|
||||
let g = art();
|
||||
let v = serde_json::to_value(&g).unwrap();
|
||||
let saved = &v["generated"];
|
||||
assert_eq!((&saved["plugin"], &saved["name"], &saved["params"]), (&json!("org.example.gen"), &json!("Squares"), &json!({"size": 10})));
|
||||
assert_eq!(saved["hash"], json!(art_hash(g.children().unwrap())));
|
||||
assert!(saved.get("transform").is_none());
|
||||
let back = reread(&v);
|
||||
assert_eq!(back, g);
|
||||
assert_eq!(back.extras().generated.as_ref().map(|a| a.state), Some(State::Intact));
|
||||
// A moved object keeps its transform.
|
||||
let mut moved = g.clone();
|
||||
moved.transform(Affine::translate((5.0, 0.0)), false);
|
||||
let back = reread(&serde_json::to_value(&moved).unwrap());
|
||||
assert_eq!(back.extras().generated.as_ref().map(|a| (a.transform, a.state)), Some((Affine::translate((5.0, 0.0)), State::Intact)));
|
||||
// A scale with Scale Strokes & Effects and Transform Patterns keeps what it scaled.
|
||||
let mut scaled = g.clone();
|
||||
let sc = Scaling { strokes: true, patterns: true, ..Scaling::default() };
|
||||
scaled.transform(Affine::scale(2.0), sc);
|
||||
scaled.transform(Affine::scale(3.0), false);
|
||||
let back = reread(&serde_json::to_value(&scaled).unwrap());
|
||||
let a = back.extras().generated.as_deref().unwrap();
|
||||
assert_eq!((a.stroke_scale, a.effect_scale, a.pattern_transform, a.state), (2.0, 1.0, Affine::scale(2.0), State::Intact));
|
||||
assert_eq!(a.transform, Affine::scale(6.0));
|
||||
// A transform that flattens it to a point, with Scale Strokes & Effects on, scales its
|
||||
// strokes and effects by 0, and it reads back intact with those scales.
|
||||
let mut flat = g.clone();
|
||||
flat.transform(Affine::new([0.0; 6]), Scaling { strokes: true, effects: Some(|_, _| {}), ..Scaling::default() });
|
||||
let back = reread(&serde_json::to_value(&flat).unwrap());
|
||||
let a = back.extras().generated.as_deref().unwrap();
|
||||
assert_eq!((a.stroke_scale, a.effect_scale, a.state), (0.0, 0.0, State::Intact));
|
||||
}
|
||||
|
||||
/// Art that doesn't match the file's hash, and fields that can't be read, keep the art and say
|
||||
/// how the object was read; a garbled id is never kept.
|
||||
#[test]
|
||||
fn damaged_fields_and_changed_art_keep_the_art() {
|
||||
let g = art();
|
||||
let v = serde_json::to_value(&g).unwrap();
|
||||
let state = |v: &Value| reread(v).extras().generated.as_ref().map(|a| (a.plugin.clone(), a.state));
|
||||
// The art edited, with the hash of the art before.
|
||||
let mut edited = g.clone();
|
||||
if let Some(c) = edited.children_mut().and_then(|c| c.first_mut()) {
|
||||
Arc::make_mut(c).transform(Affine::translate((1.0, 0.0)), false);
|
||||
}
|
||||
let mut changed = serde_json::to_value(&edited).unwrap();
|
||||
changed["generated"]["hash"] = v["generated"]["hash"].clone();
|
||||
assert_eq!(state(&changed), Some(("org.example.gen".into(), State::Changed)));
|
||||
let mut no_hash = v.clone();
|
||||
no_hash["generated"].as_object_mut().unwrap().remove("hash");
|
||||
assert_eq!(state(&no_hash), Some(("org.example.gen".into(), State::Changed)));
|
||||
for (field, bad) in [
|
||||
("plugin", json!("../evil")),
|
||||
("plugin", json!("x".repeat(65))),
|
||||
("plugin", json!("")),
|
||||
("plugin", json!("a\u{0}b")),
|
||||
("plugin", json!(7)),
|
||||
("params", json!([1, 2])),
|
||||
("params", json!({"blob": "x".repeat(MAX_PARAMS_BYTES)})),
|
||||
("transform", json!("sideways")),
|
||||
("transform", Value::Null),
|
||||
("strokeScale", json!(-2.0)),
|
||||
("strokeScale", Value::Null),
|
||||
("strokeScale", json!("big")),
|
||||
("effectScale", json!(-0.5)),
|
||||
("patternTransform", json!([1, 0, 0, 1, 0])),
|
||||
("patternTransform", Value::Null),
|
||||
("effectScale", Value::Null),
|
||||
("damaged", json!(true)),
|
||||
("damaged", json!("no")),
|
||||
] {
|
||||
let mut w = v.clone();
|
||||
w["generated"][field] = bad;
|
||||
let back = reread(&w);
|
||||
let a = back.extras().generated.as_ref().unwrap();
|
||||
assert_eq!(a.state, State::Damaged, "{field}");
|
||||
assert!(a.plugin.is_empty() || a.plugin == "org.example.gen", "{field}: {}", a.plugin);
|
||||
assert_eq!(back.children(), g.children(), "{field}");
|
||||
// Saved again and read back, it stays damaged.
|
||||
let again = reread(&serde_json::to_value(&back).unwrap());
|
||||
assert_eq!(again.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged), "{field} saved again");
|
||||
}
|
||||
// Not an object at all.
|
||||
let mut w = v.clone();
|
||||
w["generated"] = json!("art");
|
||||
assert_eq!(state(&w), Some((String::new(), State::Damaged)));
|
||||
// A null field is read as a field that can't be read, not as an absent one, from a value
|
||||
// and from a file's text; the art stays, and saved again the object stays damaged.
|
||||
let mut w = v.clone();
|
||||
w["generated"] = Value::Null;
|
||||
assert_eq!(state(&w), Some((String::new(), State::Damaged)));
|
||||
let back: Node = serde_json::from_str(&w.to_string()).unwrap();
|
||||
assert_eq!(back.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged));
|
||||
assert_eq!(back.children(), g.children());
|
||||
let again = reread(&serde_json::to_value(&back).unwrap());
|
||||
assert_eq!(again.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged));
|
||||
// On a path the field is dropped, and the path stays as it was.
|
||||
let path = g.children().unwrap()[0].clone();
|
||||
let mut p = serde_json::to_value(&*path).unwrap();
|
||||
p["generated"] = v["generated"].clone();
|
||||
let back = reread(&p);
|
||||
assert!(back.extras().generated.is_none());
|
||||
assert_eq!(back, *path);
|
||||
// A name is cut to its limit and loses control characters.
|
||||
let mut w = v.clone();
|
||||
w["generated"]["name"] = json!(format!("A\u{202e}\n{}", "n".repeat(100)));
|
||||
let back = reread(&w);
|
||||
let name = &back.extras().generated.as_ref().unwrap().name;
|
||||
assert_eq!(name.chars().count(), MAX_NAME);
|
||||
assert!(!name.chars().any(char::is_control));
|
||||
}
|
||||
}
|
||||
+119
-20
@@ -81,6 +81,11 @@ pub struct HitOptions {
|
||||
/// The point hit tests ([`hit_test`], [`hit_test_visible`] and [`hit_test_visible_skipping`])
|
||||
/// hit the art on a layer whose Preview is off as painted, not in outline.
|
||||
pub ignore_layer_preview: bool,
|
||||
/// The selection tools: where a click hits nothing else, a closed path or compound path with
|
||||
/// no fill is hit inside its closed subpaths, the topmost first, as a filled one is. Off with
|
||||
/// [`Self::path_only`] and in outline. Clipping paths and guides are still hit on their
|
||||
/// outline only. [`hit_test`] and [`objects_at`] try every other object first.
|
||||
pub unfilled_interiors: bool,
|
||||
}
|
||||
|
||||
impl Default for HitOptions {
|
||||
@@ -94,6 +99,7 @@ impl Default for HitOptions {
|
||||
clip_outlines: false,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
unfilled_interiors: false,
|
||||
scope: None,
|
||||
}
|
||||
}
|
||||
@@ -417,11 +423,35 @@ impl Drop for DrawnOff {
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Whether a clipping path is being tested ([`InMask`]).
|
||||
static IN_MASK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// While a guard lives, a clipping path is tested: it is not hit inside by its interior alone
|
||||
/// ([`takes_interior`]).
|
||||
struct InMask {
|
||||
was: bool,
|
||||
}
|
||||
|
||||
impl InMask {
|
||||
fn set() -> Self {
|
||||
Self { was: IN_MASK.replace(true) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for InMask {
|
||||
fn drop(&mut self) {
|
||||
IN_MASK.set(self.was);
|
||||
}
|
||||
}
|
||||
|
||||
/// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a
|
||||
/// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to
|
||||
/// the region it clips to.
|
||||
/// the region it clips to. It is also under an [`InMask`] guard.
|
||||
fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
|
||||
let _off = mask.then(DrawnOff::set);
|
||||
let _mask = mask.then(InMask::set);
|
||||
f()
|
||||
}
|
||||
|
||||
@@ -636,17 +666,23 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) {
|
||||
// An envelope in Edit Contents may expose objects *within* a top-level group.
|
||||
// The repeated traversal handles that mixed hierarchy precisely. The objects found
|
||||
// so far lie above the envelope and stay first; the repeated traversal finds the
|
||||
// rest with what is left of the limit of symbol art to walk.
|
||||
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
|
||||
break;
|
||||
// As [`hit_test`] does: the objects hit by what they paint first, then those hit only inside
|
||||
// an unfilled closed path ([`HitOptions::unfilled_interiors`]).
|
||||
let painted = HitOptions { unfilled_interiors: false, ..opt };
|
||||
let interiors = opt.unfilled_interiors && !opt.path_only && !opt.outline;
|
||||
'passes: for pass in [Some(painted), interiors.then_some(opt)].into_iter().flatten() {
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
if !objects_at_layer(layer, p, pass, &symbols, &mut tops, &mut seen) {
|
||||
// An envelope in Edit Contents may expose objects *within* a top-level group.
|
||||
// The repeated traversal handles that mixed hierarchy precisely. The objects found
|
||||
// so far lie above the envelope and stay first; the repeated traversal finds the
|
||||
// rest with what is left of the limit of symbol art to walk.
|
||||
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
|
||||
break 'passes;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them.
|
||||
@@ -980,7 +1016,18 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
|
||||
/// `editable_only` over the objects of layers and sublayers on a locked artboard, and over all of
|
||||
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
|
||||
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
|
||||
/// With [`HitOptions::unfilled_interiors`], a second walk looks inside the unfilled closed paths
|
||||
/// only when the first, without it, hits nothing.
|
||||
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let painted = hit_test_walk(doc, p, HitOptions { unfilled_interiors: false, ..opt }, skip, editable_only);
|
||||
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline {
|
||||
return painted;
|
||||
}
|
||||
hit_test_walk(doc, p, opt, skip, editable_only)
|
||||
}
|
||||
|
||||
/// One walk of [`hit_test_skipping`], with `opt` as given.
|
||||
fn hit_test_walk(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let _walk = ArtWalk::open();
|
||||
let finish = |mut h: Hit| {
|
||||
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
|
||||
@@ -1524,7 +1571,10 @@ fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: &
|
||||
return false;
|
||||
}
|
||||
}
|
||||
hit_order(n, children, p).any(|i| children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept)))
|
||||
hit_order(n, children, p).any(|i| {
|
||||
let _mask = (i == 0 && n.clips()).then(InMask::set);
|
||||
children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept))
|
||||
})
|
||||
}
|
||||
_ => hit_leaf(n, p, opt, symbols).is_some_and(|kind| accept(n.id, kind)),
|
||||
}
|
||||
@@ -1563,6 +1613,15 @@ fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64)
|
||||
let decoration_sq = decoration_reach * decoration_reach;
|
||||
let mut near_decoration = false;
|
||||
for sp in &path.subpaths {
|
||||
// A closed lone anchor has no segment, and a cap can draw a dot on it: the full check
|
||||
// decides a click near it.
|
||||
if sp.closed
|
||||
&& sp.segment_count() == 0
|
||||
&& let Some(a) = sp.anchors.first()
|
||||
&& (a.p - p).hypot2() <= radius_sq.max(decoration_sq)
|
||||
{
|
||||
near_decoration = true;
|
||||
}
|
||||
for i in 0..sp.segment_count() {
|
||||
let c = sp.segment(i);
|
||||
if decoration_reach > 0.0 && !near_decoration && ([c.p0, c.p3].iter().any(|q| (*q - p).hypot2() <= decoration_sq)) {
|
||||
@@ -1613,6 +1672,8 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => {
|
||||
let has_fill = n.appearance.has_visible_fill();
|
||||
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed) && takes_interior(n, opt);
|
||||
let inside = || (interior && fill_contains(&closed_subpaths_at([path], p), *rule, p)).then_some(HitKind::Fill);
|
||||
if opt.outline
|
||||
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
|
||||
{
|
||||
@@ -1647,7 +1708,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
return Some(HitKind::Stroke);
|
||||
}
|
||||
if !near_decoration {
|
||||
return None;
|
||||
return inside();
|
||||
}
|
||||
}
|
||||
let bp = path.to_bezpath();
|
||||
@@ -1657,7 +1718,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) {
|
||||
return Some(HitKind::Fill);
|
||||
}
|
||||
None
|
||||
inside()
|
||||
}
|
||||
NodeKind::Compound { children, rule } => {
|
||||
// Painted strokes follow the whole compound path (alignment, dashes, width profiles):
|
||||
@@ -1675,7 +1736,11 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol {
|
||||
return Some(HitKind::Outline);
|
||||
}
|
||||
(!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill)
|
||||
if n.appearance.has_visible_fill() {
|
||||
return (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill);
|
||||
}
|
||||
let closed = || closed_subpaths_at(children.iter().filter_map(|m| m.path_data()), p);
|
||||
(takes_interior(n, opt) && fill_contains(&closed(), *rule, p)).then_some(HitKind::Fill)
|
||||
}
|
||||
// The type path lies within the bounds: they rule out the rest before it is measured.
|
||||
NodeKind::Text(t) if opt.type_path_only => {
|
||||
@@ -1747,6 +1812,30 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
}
|
||||
}
|
||||
|
||||
/// Is path or compound path `n`, which has no visible fill, hit inside its closed subpaths
|
||||
/// ([`HitOptions::unfilled_interiors`])? Not a clipping path ([`InMask`]) or a guide.
|
||||
fn takes_interior(n: &Node, opt: HitOptions) -> bool {
|
||||
opt.unfilled_interiors
|
||||
&& !opt.outline
|
||||
&& !opt.path_only
|
||||
&& !IN_MASK.get()
|
||||
&& !matches!(n.kind, NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
/// The closed subpaths of `paths` whose control points' box holds `p`, as one path. A path outside
|
||||
/// that box winds zero times round `p`, so this path's fill holds `p` as all the closed subpaths'
|
||||
/// fill does. Open subpaths are left out: they bound no area.
|
||||
fn closed_subpaths_at<'a>(paths: impl IntoIterator<Item = &'a PathData>, p: Point) -> BezPath {
|
||||
let holds = |b: Rect| b.x0 <= p.x && p.x <= b.x1 && b.y0 <= p.y && p.y <= b.y1;
|
||||
let mut bp = BezPath::new();
|
||||
for pd in paths.into_iter().filter(|pd| pd.control_bounds().is_some_and(holds)) {
|
||||
for sp in pd.subpaths.iter().filter(|sp| sp.closed) {
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
}
|
||||
}
|
||||
bp
|
||||
}
|
||||
|
||||
/// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a
|
||||
/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a
|
||||
/// stroke along its shape, a fill inside it except with Selection by Path Only.
|
||||
@@ -2023,13 +2112,23 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
/// (blends, envelopes, repeats) are tested without those effects. `None` when `inst` is not a
|
||||
/// symbol instance or no editable object of its art is under `p`.
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
let _walk = ArtWalk::open();
|
||||
let walk = ArtWalk::open();
|
||||
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
let art = InstanceArt::drawn(doc, inst, outline)?;
|
||||
let symbols = doc.kept_symbol_boxes();
|
||||
let mut path = vec![];
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
let pick = |opt: HitOptions| {
|
||||
let mut path = vec![];
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
};
|
||||
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit.
|
||||
pick(HitOptions { unfilled_interiors: false, ..opt }).or_else(|| {
|
||||
if !opt.unfilled_interiors || opt.path_only || outline {
|
||||
return None;
|
||||
}
|
||||
walk.restart();
|
||||
pick(opt)
|
||||
})
|
||||
}
|
||||
|
||||
/// The walk of a symbol instance's placed art that [`symbol_part_at`] and [`instance_art_hit`] make.
|
||||
|
||||
@@ -38,6 +38,168 @@ fn unfilled_interior_misses() {
|
||||
assert!(hit_test(&d, Point::new(50.5, 25.0), HitOptions::default()).is_some());
|
||||
}
|
||||
|
||||
/// The selection tools' options with unfilled closed paths hit inside.
|
||||
const INTERIORS: HitOptions = HitOptions { unfilled_interiors: true, ..SELECTING };
|
||||
|
||||
/// A path of `points` with a black stroke and no fill, inserted at the top of the first layer.
|
||||
fn stroked(d: &mut Document, points: &[(f64, f64)], closed: bool) -> NodeId {
|
||||
let l = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let pts: Vec<Point> = points.iter().map(|&(x, y)| Point::new(x, y)).collect();
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pts, closed));
|
||||
d.insert(Some(l), 99, Node::path(id, path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
const FRAME: [(f64, f64); 4] = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
|
||||
|
||||
#[test]
|
||||
fn an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let frame = stroked(&mut d, &FRAME, true);
|
||||
let at = |opt: HitOptions| hit_test(&d, Point::new(50.0, 50.0), opt).map(|h| h.leaf);
|
||||
assert_eq!(at(INTERIORS), Some(frame));
|
||||
assert_eq!(at(SELECTING), None, "without the option, the interior misses");
|
||||
assert_eq!(at(HitOptions { path_only: true, ..INTERIORS }), None, "Object Selection by Path Only");
|
||||
assert_eq!(at(HitOptions { outline: true, ..INTERIORS }), None, "Outline view");
|
||||
assert_eq!(objects_at(&d, Point::new(50.0, 50.0), INTERIORS, None), vec![frame]);
|
||||
assert!(objects_at(&d, Point::new(150.0, 50.0), INTERIORS, None).is_empty(), "outside it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_path_is_not_hit_inside() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
stroked(&mut d, &FRAME, false);
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 50.0), INTERIORS), None);
|
||||
}
|
||||
|
||||
/// What a click paints over comes first: an object drawn inside an unfilled frame above it is hit
|
||||
/// where it paints, and the frame elsewhere inside; Select Behind lists the frame after it.
|
||||
#[test]
|
||||
fn art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let dot = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::path(dot, shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), Appearance::default_art())).unwrap();
|
||||
let frame = stroked(&mut d, &FRAME, true);
|
||||
let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(&d, 50.0), Some(dot));
|
||||
assert_eq!(at(&d, 20.0), Some(frame));
|
||||
assert_eq!(objects_at(&d, Point::new(50.0, 50.0), INTERIORS, None), vec![dot, frame]);
|
||||
// The topmost of two unfilled frames is hit inside both.
|
||||
let inner = stroked(&mut d, &[(10.0, 10.0), (90.0, 10.0), (90.0, 90.0), (10.0, 90.0)], true);
|
||||
assert_eq!(at(&d, 20.0), Some(inner));
|
||||
assert_eq!(at(&d, 5.0), Some(frame));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let (id, outer, hole) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let members = vec![ring(outer, Rect::new(0.0, 0.0, 100.0, 100.0)), ring(hole, Rect::new(30.0, 30.0, 70.0, 70.0))];
|
||||
let mut compound = Node::new(id, NodeKind::Compound { children: members, rule: FillRule::EvenOdd });
|
||||
compound.appearance = look().into();
|
||||
d.insert(Some(l), 0, compound).unwrap();
|
||||
let at = |x: f64| hit_test(&d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(15.0), Some(id));
|
||||
assert_eq!(at(50.0), None, "in the hole");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_and_clipping_paths_are_not_hit_inside() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let guide = stroked(&mut d, &FRAME, true);
|
||||
if let Some(NodeKind::Path { guide: g, .. }) = d.node_mut(guide).map(|n| &mut n.kind) {
|
||||
*g = true;
|
||||
}
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 50.0), INTERIORS), None, "a guide");
|
||||
// A clip group whose art covers only part of its unfilled clipping path.
|
||||
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 mask = Node::path(clip, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::None, Paint::None, 0.0));
|
||||
if let NodeKind::Path { clipping, .. } = &mut mask.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let picture = Node::path(art, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 100.0)), Appearance::default_art());
|
||||
d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(mask), Arc::new(picture)], clip: true })).unwrap();
|
||||
let at = |x: f64| hit_test(&d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(25.0), Some(art));
|
||||
assert_eq!(at(75.0), None, "inside the mask where no art paints");
|
||||
assert!(objects_at(&d, Point::new(75.0, 50.0), INTERIORS, None).is_empty());
|
||||
}
|
||||
|
||||
/// A repeat's copies of an unfilled frame are hit inside, and the copies of a clip group's unfilled
|
||||
/// compound clipping path are not.
|
||||
#[test]
|
||||
fn a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks() {
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let kind = crate::pattern::RepeatKind::Grid {
|
||||
h_spacing: 20.0,
|
||||
v_spacing: 20.0,
|
||||
rows: 1,
|
||||
cols: 2,
|
||||
grid_type: crate::pattern::TileType::Grid,
|
||||
flip_rows: false,
|
||||
flip_cols: false,
|
||||
};
|
||||
let repeat = |d: &mut Document, source: Node| {
|
||||
let r = d.alloc_id();
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, Node::new(r, NodeKind::Repeat(crate::pattern::RepeatSpec { kind: kind.clone(), source: vec![Arc::new(source)] })))
|
||||
.unwrap();
|
||||
r
|
||||
};
|
||||
// Copies at 0..40 and 60..100.
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), look());
|
||||
let r = repeat(&mut d, frame);
|
||||
assert_eq!(hit_test(&d, Point::new(80.0, 20.0), INTERIORS).map(|h| h.leaf), Some(r));
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 20.0), INTERIORS), None, "between the copies");
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let members = vec![ring(d.alloc_id(), Rect::new(0.0, 0.0, 40.0, 40.0)), ring(d.alloc_id(), Rect::new(5.0, 5.0, 35.0, 35.0))];
|
||||
let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
mask.appearance = look().into();
|
||||
let picture = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 40.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(picture)]);
|
||||
clip.set_clips(true);
|
||||
let r = repeat(&mut d, clip);
|
||||
assert_eq!(hit_test(&d, Point::new(65.0, 20.0), INTERIORS).map(|h| h.leaf), Some(r), "on the clipped art");
|
||||
assert_eq!(hit_test(&d, Point::new(80.0, 20.0), INTERIORS), None, "inside the mask where no art paints");
|
||||
}
|
||||
|
||||
/// Direct Selection in a dynamic symbol's art picks parts as a click on the document does: what
|
||||
/// paints first, then an unfilled frame inside; an unfilled compound clipping path by its outline.
|
||||
#[test]
|
||||
fn symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), Appearance::default_art());
|
||||
let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look());
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let (mask_id, a, b) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let members = vec![ring(a, Rect::new(150.0, 0.0, 250.0, 100.0)), ring(b, Rect::new(160.0, 10.0, 240.0, 90.0))];
|
||||
let mut mask = Node::new(mask_id, NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
mask.appearance = look().into();
|
||||
let picture = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(150.0, 0.0, 180.0, 100.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(picture)]);
|
||||
clip.set_clips(true);
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(dot), Arc::new(frame), Arc::new(clip)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Framed".into(), art: Arc::new(root) });
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Framed".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
let n = d.node(inst).unwrap();
|
||||
let at = |x: f64| symbol_part_at(&d, n, Point::new(x, 50.0), INTERIORS);
|
||||
assert_eq!(at(50.0), Some(vec![0]), "the dot under the frame");
|
||||
assert_eq!(at(20.0), Some(vec![1]), "inside the frame");
|
||||
assert_eq!(at(220.0), None, "inside the clipping path where no art paints");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_plain_stroke_hits_its_middle_and_curved_end() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
@@ -1464,6 +1626,7 @@ const SELECTING: HitOptions = HitOptions {
|
||||
clip_outlines: true,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
unfilled_interiors: false,
|
||||
scope: None,
|
||||
};
|
||||
|
||||
|
||||
@@ -82,6 +82,7 @@ impl Paths {
|
||||
/// isn't in the table or it, or a node it is in, was removed.
|
||||
pub(crate) fn get(&self, id: &NodeId) -> Option<Option<Vec<usize>>> {
|
||||
let e = (*self.table.ids.get(id)?)?;
|
||||
note_path_copy();
|
||||
let mut path = Vec::new();
|
||||
let mut cur = e;
|
||||
// Each step goes to a parent entry, made before its children: at most `at.len()` steps.
|
||||
@@ -96,6 +97,29 @@ impl Paths {
|
||||
}
|
||||
Some(None)
|
||||
}
|
||||
/// The node with `id` in `layers` at the place the table has for it, found without copying its index path: `None`
|
||||
/// when the table does not have one place for `id`, its path is deeper than [`NODE_IN_DEPTH`], or the node there
|
||||
/// does not have the id (the tree changed). The caller then looks it up as [`crate::Document::index_path`] does.
|
||||
pub(crate) fn node_in<'a>(&self, layers: &'a [Arc<Node>], id: NodeId) -> Option<&'a Node> {
|
||||
let mut cur = (*self.table.ids.get(&id)?)?;
|
||||
let mut steps = [0u32; NODE_IN_DEPTH];
|
||||
let mut depth = 0;
|
||||
loop {
|
||||
let &(parent, i) = self.table.at.get(cur as usize)?;
|
||||
*steps.get_mut(depth)? = self.shifted(parent, i)?;
|
||||
depth += 1;
|
||||
if parent == u32::MAX {
|
||||
break;
|
||||
}
|
||||
cur = parent;
|
||||
}
|
||||
let mut path = steps[..depth].iter().rev();
|
||||
let mut node: &Node = layers.get(*path.next()? as usize)?;
|
||||
for &i in path {
|
||||
node = node.children()?.get(i as usize)?;
|
||||
}
|
||||
(node.id == id).then_some(node)
|
||||
}
|
||||
/// Where the table has `id` as it was built: its parent's entry and its index among its
|
||||
/// siblings then; `None` when the id isn't in the table or appears more than once.
|
||||
pub(crate) fn table_place(&self, id: &NodeId) -> Option<(u32, u32)> {
|
||||
@@ -170,6 +194,25 @@ pub(crate) fn note_path_lookup() {
|
||||
PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// The deepest index path [`Paths::node_in`] follows without copying it.
|
||||
const NODE_IN_DEPTH: usize = 32;
|
||||
|
||||
thread_local! {
|
||||
/// [`path_copies`] of this thread.
|
||||
static PATH_COPIES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many index paths the lookup cache has copied out on this thread, one for each [`crate::Document::index_path`]
|
||||
/// that it answered. [`crate::Document::node`] reads the node from the cache without one.
|
||||
pub fn path_copies() -> u64 {
|
||||
PATH_COPIES.get()
|
||||
}
|
||||
|
||||
/// Adds one to [`path_copies`].
|
||||
fn note_path_copy() {
|
||||
PATH_COPIES.set(PATH_COPIES.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// The cache, shared by clones of a document (each checks every path it uses against its own tree),
|
||||
/// the lookups that missed it, and the nodes removed from the tree since it was built.
|
||||
#[derive(Default)]
|
||||
|
||||
@@ -18,12 +18,13 @@ pub mod decode;
|
||||
pub mod depth;
|
||||
pub mod dimension;
|
||||
pub mod flare;
|
||||
pub mod generated;
|
||||
pub mod graph;
|
||||
mod halftone_radii;
|
||||
pub mod hit;
|
||||
mod id_index;
|
||||
pub mod image_quad;
|
||||
pub use id_index::{path_lookups, tree_walks};
|
||||
pub use id_index::{path_copies, path_lookups, tree_walks};
|
||||
pub mod inks;
|
||||
mod inline;
|
||||
pub mod intertwine;
|
||||
|
||||
+13
-2
@@ -54,8 +54,8 @@ pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation,
|
||||
use blend_spec::{blend_color_shift, blend_ramp};
|
||||
pub use envelope::{
|
||||
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, TypeInk, envelope_bounds, envelope_content_bounds,
|
||||
envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of,
|
||||
envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid,
|
||||
envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_margin_lengths,
|
||||
envelope_of, envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid,
|
||||
};
|
||||
pub use expand::{
|
||||
Hooks, MAX_GENERATED, Outliner, PatternTiles, affine_near, expand_deep, expand_deep_hooks, expand_live, expand_live_hooks, expand_live_with,
|
||||
@@ -975,6 +975,17 @@ mod tests {
|
||||
assert_eq!(margin(&turned, frame).map(|m| (m * 1000.0).round()), before.map(|m| (m * 1000.0).round()));
|
||||
// Margins an `f32` can't hold are none.
|
||||
assert_eq!(envelope_stroke_margin(Rect::new(-5e41, 0.0, 100.0, 100.0), Rect::new(0.0, 0.0, 100.0, 100.0)), None);
|
||||
// A straight line along an axis has margins across it, as shares of its length, and maps
|
||||
// from its box with them; a point has none.
|
||||
let line =
|
||||
Node::path(NodeId(4), vectorcraft_geom::shapes::line(Point::new(10.0, 20.0), Point::new(110.0, 20.0)), crate::Appearance::default_art());
|
||||
let line = [Arc::new(line)];
|
||||
let stroked_line = Rect::new(10.0, 15.0, 110.0, 25.0);
|
||||
let across = envelope_stroke_margin(stroked_line, Rect::new(10.0, 20.0, 110.0, 20.0)).unwrap();
|
||||
assert!(across[0] > 0.0 && across[1] > 0.0 && across[2] == 0.0 && across[3] == 0.0, "{across:?}");
|
||||
let from = src(&line, Affine::IDENTITY, EnvelopeOptions { bounds_margin: across, ..on });
|
||||
assert!((from.y0 - 15.0).abs() + (from.y1 - 25.0).abs() + (from.x0 - 10.0).abs() + (from.x1 - 110.0).abs() < 1e-4, "{from:?}");
|
||||
assert_eq!(envelope_stroke_margin(stroked_line, Rect::new(60.0, 20.0, 60.0, 20.0)), None);
|
||||
|
||||
assert!(serde_json::to_value(EnvelopeOptions::default()).unwrap().get("boundsMargin").is_none());
|
||||
let saved = serde_json::to_value(on).unwrap();
|
||||
|
||||
+164
-31
@@ -95,7 +95,9 @@ pub struct EnvelopeOptions {
|
||||
/// Distort Pattern Fills (with Distort Appearance): pattern tiles bend with the art.
|
||||
pub distort_pattern_fills: bool,
|
||||
/// With Distort Appearance, how far the box the content maps from reaches past its geometric
|
||||
/// bounds at the top, bottom, left and right, as shares of their height and width. An envelope
|
||||
/// bounds at the top, bottom, left and right, as shares of their height and width; when the
|
||||
/// height or width is shorter than 1e-6 pt, the margins along that side are shares of the other side
|
||||
/// ([`envelope_margin_lengths`]). An envelope
|
||||
/// opened from a `.ai` whose saved size includes its strokes has these margins. New envelopes
|
||||
/// have none. Leaving Edit Contents measures them again when the strokes reach differently.
|
||||
#[serde(skip_serializing_if = "crate::skip::is_default")]
|
||||
@@ -140,7 +142,8 @@ impl EnvelopeOptions {
|
||||
if !self.distort_appearance || !self.bounds_margin.iter().all(|m| m.is_finite() && *m >= 0.0) {
|
||||
return r;
|
||||
}
|
||||
let grown = crate::marks::outset(r, [top * r.height(), bottom * r.height(), left * r.width(), right * r.width()]);
|
||||
let Some([v, _, h, _]) = envelope_margin_lengths(r) else { return r };
|
||||
let grown = crate::marks::outset(r, [top * v, bottom * v, left * h, right * h]);
|
||||
if grown.is_finite() { grown } else { r }
|
||||
}
|
||||
}
|
||||
@@ -382,26 +385,53 @@ fn find_type(n: &Node, typed: &mut std::collections::HashSet<usize>) -> bool {
|
||||
/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box. Type
|
||||
/// that draws nothing has its laid-out box with `blank_type_box`, and no box without it.
|
||||
fn content_box(n: &Arc<Node>, stroked: bool, to: Affine, blank_type_box: bool) -> Option<Rect> {
|
||||
let mut typed = std::collections::HashSet::new();
|
||||
find_type(n, &mut typed);
|
||||
let mut typed = Typed::default();
|
||||
find_type(n, &mut typed.holds);
|
||||
content_box_in(n, stroked, to, &typed, blank_type_box)
|
||||
}
|
||||
|
||||
/// [`content_box`], with the addresses of the objects in `n` that hold type ([`find_type`]).
|
||||
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collections::HashSet<usize>, blank_type_box: bool) -> Option<Rect> {
|
||||
// `n` in the axes of `to`.
|
||||
let moved = || {
|
||||
if to == Affine::IDENTITY {
|
||||
return std::borrow::Cow::Borrowed(&**n);
|
||||
}
|
||||
let mut m = (**n).clone();
|
||||
m.transform(to, true);
|
||||
std::borrow::Cow::Owned(m)
|
||||
};
|
||||
let own = |m: &Node| if stroked { m.visual_bounds() } else { m.geometric_bounds() };
|
||||
if !typed.contains(&(Arc::as_ptr(n) as usize)) {
|
||||
return own(&moved());
|
||||
/// The objects in an envelope's contents that hold type ([`find_type`]), by address, and the
|
||||
/// boxes [`content_box_in`] has measured for them with their strokes, so that measuring a
|
||||
/// container's own strokes along its members ([`container_strokes_in`]) does not measure them
|
||||
/// again.
|
||||
#[derive(Default)]
|
||||
struct Typed {
|
||||
holds: std::collections::HashSet<usize>,
|
||||
stroked: std::cell::RefCell<std::collections::HashMap<usize, Option<Rect>>>,
|
||||
}
|
||||
|
||||
/// `n` in the axes of `to`, with its strokes scaled as [`Node::transform`] scales them.
|
||||
fn moved_into(n: &Node, to: Affine) -> std::borrow::Cow<'_, Node> {
|
||||
if to == Affine::IDENTITY {
|
||||
return std::borrow::Cow::Borrowed(n);
|
||||
}
|
||||
let mut m = n.clone();
|
||||
m.transform(to, true);
|
||||
std::borrow::Cow::Owned(m)
|
||||
}
|
||||
|
||||
/// [`content_box`], with the objects in `n` that hold type ([`Typed`]).
|
||||
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &Typed, blank_type_box: bool) -> Option<Rect> {
|
||||
let key = Arc::as_ptr(n) as usize;
|
||||
if !typed.holds.contains(&key) {
|
||||
let m = moved_into(n, to);
|
||||
return if stroked { m.visual_bounds() } else { m.geometric_bounds() };
|
||||
}
|
||||
if !stroked {
|
||||
return typed_box_in(n, false, to, typed, blank_type_box);
|
||||
}
|
||||
if let Some(b) = typed.stroked.borrow().get(&key) {
|
||||
return *b;
|
||||
}
|
||||
let b = typed_box_in(n, true, to, typed, blank_type_box);
|
||||
typed.stroked.borrow_mut().insert(key, b);
|
||||
b
|
||||
}
|
||||
|
||||
/// [`content_box_in`] of `n`, which holds type.
|
||||
fn typed_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &Typed, blank_type_box: bool) -> Option<Rect> {
|
||||
let moved = || moved_into(n, to);
|
||||
let own = |m: &Node| if stroked { m.visual_bounds() } else { m.geometric_bounds() };
|
||||
match &n.kind {
|
||||
NodeKind::Text(t) => {
|
||||
// Type in perspective: its outlines as its projection draws them.
|
||||
@@ -442,11 +472,16 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
|
||||
let members = n.editing_children().iter();
|
||||
if stroked {
|
||||
// The container's own strokes, scaled by `to` as `Node::transform` scales them,
|
||||
// without copying its members.
|
||||
// measured along its members as in `Node::visual_bounds`.
|
||||
let mut own_strokes = Node::new(n.id, NodeKind::Group { children: Vec::new(), clip: false });
|
||||
own_strokes.appearance = n.appearance.clone();
|
||||
own_strokes.transform(to, true);
|
||||
own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed, blank_type_box)))
|
||||
let painted = own_strokes.appearance.painted_strokes().next().is_some();
|
||||
members.fold(None, |acc, c| {
|
||||
let b = content_box_in(c, true, to, typed, blank_type_box);
|
||||
let own = if painted { container_strokes_in(c, &own_strokes.appearance, Some(b), to, typed, blank_type_box) } else { None };
|
||||
vectorcraft_geom::union_opt(vectorcraft_geom::union_opt(acc, b), own)
|
||||
})
|
||||
} else {
|
||||
members
|
||||
.filter(|c| c.visible || !layer)
|
||||
@@ -457,19 +492,66 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`. `None` for
|
||||
/// content with no width or no height, or for margins an `f32` can't hold.
|
||||
pub fn envelope_stroke_margin(stroked: Rect, plain: Rect) -> Option<[f32; 4]> {
|
||||
if plain.width() < 1e-6 || plain.height() < 1e-6 {
|
||||
/// The box the strokes of `appearance`, the appearance of a group or layer that holds `n` scaled
|
||||
/// by `to`, paint along `n` in the axes of `to`, as [`Node::painted_by_container`] measures them;
|
||||
/// `measured` is the box [`content_box_in`] gives `n` with its strokes, when known. Type, alone or
|
||||
/// in a clip group, has that box grown by the farthest the strokes can reach
|
||||
/// ([`crate::Appearance::outset`]); the strokes paint nothing round hidden members and guides.
|
||||
fn container_strokes_in(
|
||||
n: &Arc<Node>,
|
||||
appearance: &crate::Appearance,
|
||||
measured: Option<Option<Rect>>,
|
||||
to: Affine,
|
||||
typed: &Typed,
|
||||
blank_type_box: bool,
|
||||
) -> Option<Rect> {
|
||||
if !n.visible || n.is_guide() {
|
||||
return None;
|
||||
}
|
||||
let margin = [
|
||||
(plain.y0 - stroked.y0) / plain.height(),
|
||||
(stroked.y1 - plain.y1) / plain.height(),
|
||||
(plain.x0 - stroked.x0) / plain.width(),
|
||||
(stroked.x1 - plain.x1) / plain.width(),
|
||||
]
|
||||
.map(|m| m as f32);
|
||||
if !typed.holds.contains(&(Arc::as_ptr(n) as usize)) {
|
||||
if to == Affine::IDENTITY {
|
||||
return n.painted_by_container(appearance, None);
|
||||
}
|
||||
// Moved with its own strokes scaled, as `content_box_in` moves it, for a member measured
|
||||
// by its visual box.
|
||||
let mut m = (**n).clone();
|
||||
m.transform(to, true);
|
||||
return m.painted_by_container(appearance, None);
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { clip: false, .. } | NodeKind::Layer { clip: false, .. } if !n.is_compound_shape() => n
|
||||
.editing_children()
|
||||
.iter()
|
||||
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, container_strokes_in(c, appearance, None, to, typed, blank_type_box))),
|
||||
_ => {
|
||||
let o = appearance.outset();
|
||||
measured.unwrap_or_else(|| content_box_in(n, true, to, typed, blank_type_box)).map(|b| b.inflate(o, o))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lengths the top, bottom, left and right [`EnvelopeOptions::bounds_margin`] of content with
|
||||
/// geometric bounds `plain` are shares of: its height for the top and bottom and its width for the
|
||||
/// left and right. A side shorter than 1e-6 pt takes the other side's length, so a stroked straight
|
||||
/// line along an axis has margins across it. `None` when neither side has a length.
|
||||
pub fn envelope_margin_lengths(plain: Rect) -> Option<[f64; 4]> {
|
||||
let long = |l: f64| l.is_finite() && l >= 1e-6;
|
||||
let (h, w) = match (long(plain.height()), long(plain.width())) {
|
||||
(true, true) => (plain.height(), plain.width()),
|
||||
(false, true) => (plain.width(), plain.width()),
|
||||
(true, false) => (plain.height(), plain.height()),
|
||||
(false, false) => return None,
|
||||
};
|
||||
Some([h, h, w, w])
|
||||
}
|
||||
|
||||
/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`, as shares
|
||||
/// of [`envelope_margin_lengths`]. `None` for content with neither a width nor a height, or for
|
||||
/// margins an `f32` can't hold.
|
||||
pub fn envelope_stroke_margin(stroked: Rect, plain: Rect) -> Option<[f32; 4]> {
|
||||
let [v, _, h, _] = envelope_margin_lengths(plain)?;
|
||||
let margin =
|
||||
[(plain.y0 - stroked.y0) / v, (stroked.y1 - plain.y1) / v, (plain.x0 - stroked.x0) / h, (stroked.x1 - plain.x1) / h].map(|m| m as f32);
|
||||
margin.iter().all(|m| m.is_finite()).then_some(margin)
|
||||
}
|
||||
|
||||
@@ -869,6 +951,57 @@ mod tests {
|
||||
assert!(content_box(&nested, false, Affine::IDENTITY, true).is_some());
|
||||
}
|
||||
|
||||
/// A group of type and a square with its own 10 pt miter-joined stroke reaches 5 pt past the
|
||||
/// square in a scaled frame, as the group moved into the frame does ([`Node::visual_bounds`]),
|
||||
/// not the 50 pt a miter spike could reach. Round a clip group they reach that far past its
|
||||
/// box, with the clipping path's own stroke scaled into the frame, and in nested groups too.
|
||||
#[test]
|
||||
fn a_groups_own_miter_stroke_is_measured_along_its_members_with_type() {
|
||||
let paint = |fill, stroke, w| crate::Appearance::basic(fill, stroke, w);
|
||||
let path = |id, r: Rect| {
|
||||
let square = vectorcraft_geom::shapes::rectangle(r);
|
||||
Arc::new(Node::path(NodeId(id), square, paint(vectorcraft_color::Paint::solid(Color::BLACK), vectorcraft_color::Paint::None, 0.0)))
|
||||
};
|
||||
let text = type_node(1, "Type");
|
||||
let mut group = Node::group(NodeId(2), vec![text, path(3, Rect::new(100.0, 100.0, 200.0, 200.0))]);
|
||||
group.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 10.0).into();
|
||||
assert_eq!(group.appearance.outset(), 50.0, "a 10 pt miter-joined stroke can reach 50 pt");
|
||||
let group = Arc::new(group);
|
||||
let to = Affine::scale(0.5);
|
||||
let mut moved = (*group).clone();
|
||||
moved.transform(to, true);
|
||||
let want = moved.visual_bounds();
|
||||
// The square's lower right corner, 100 pt in the frame, with half the 5 pt scaled stroke.
|
||||
assert_eq!(want.map(|b| (b.x1, b.y1)), Some((102.5, 102.5)));
|
||||
assert_eq!(content_box(&group, true, to, true), want);
|
||||
// A clip group whose clipping path has a 40 pt stroke, which the group's own strokes grow
|
||||
// by their reach, measured with that stroke scaled into the frame.
|
||||
let mut clip = (*path(5, Rect::new(300.0, 300.0, 400.0, 400.0))).clone();
|
||||
clip.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 40.0).into();
|
||||
let clipped =
|
||||
Node::new(NodeId(4), NodeKind::Group { children: vec![Arc::new(clip), path(6, Rect::new(320.0, 320.0, 380.0, 380.0))], clip: true });
|
||||
let mut group = Node::group(NodeId(2), vec![type_node(1, "Type"), Arc::new(clipped)]);
|
||||
group.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 10.0).into();
|
||||
let group = Arc::new(group);
|
||||
let mut moved = (*group).clone();
|
||||
moved.transform(to, true);
|
||||
let want = moved.visual_bounds();
|
||||
// 200 pt in the frame, with half the 20 pt scaled clip stroke and the 25 pt scaled reach.
|
||||
assert_eq!(want.map(|b| (b.x1, b.y1)), Some((235.0, 235.0)));
|
||||
assert_eq!(content_box(&group, true, to, true), want);
|
||||
// Stroked groups of type nested in plain groups, each measured once.
|
||||
let mut nested = group;
|
||||
for i in 0..50 {
|
||||
let plain = Arc::new(Node::group(NodeId(100 + 2 * i), vec![nested]));
|
||||
let mut stroked = Node::group(NodeId(101 + 2 * i), vec![type_node(1, "Type"), plain]);
|
||||
stroked.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 10.0).into();
|
||||
nested = Arc::new(stroked);
|
||||
}
|
||||
let mut moved = (*nested).clone();
|
||||
moved.transform(to, true);
|
||||
assert_eq!(content_box(&nested, true, to, true), moved.visual_bounds());
|
||||
}
|
||||
|
||||
/// A warp envelope of `style` at `bend` with map `version` around a 200×100 rectangle at
|
||||
/// (100, 50).
|
||||
fn warp_node(style: &str, bend: f64, h: f64, version: u32) -> Node {
|
||||
|
||||
@@ -286,6 +286,10 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
.map_or(0, |m| ALLOC + size_of::<crate::color_mask::ColorMask>() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3);
|
||||
b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::<Value>() + json_bytes(t));
|
||||
b += e.flare.as_ref().map_or(0, |f| ALLOC + size_of::<crate::flare::FlareSpec>() + json_bytes(&f.params));
|
||||
b += e
|
||||
.generated
|
||||
.as_ref()
|
||||
.map_or(0, |g| ALLOC + size_of::<crate::generated::GeneratedArt>() + g.plugin.capacity() + g.name.capacity() + map_bytes(&g.params));
|
||||
b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::<PathData>() + path_bytes(a));
|
||||
if e.intertwine_tiers.capacity() > 0 {
|
||||
b += ALLOC + e.intertwine_tiers.capacity() * size_of::<PathData>() + e.intertwine_tiers.iter().map(path_bytes).sum::<usize>();
|
||||
|
||||
@@ -96,6 +96,9 @@ pub struct NodeExtras {
|
||||
/// (top left, top right, bottom right, bottom left in pixel space) stand on the page when they
|
||||
/// do not make a parallelogram, which its transform alone could place ([`crate::image_quad`]).
|
||||
pub image_quad: Option<Box<[Point; 4]>>,
|
||||
/// Generated art object: the generator plug-in and parameters its group's children were drawn
|
||||
/// with (`plugin.generate`); its ordinary group children hold its art ([`crate::generated`]).
|
||||
pub generated: Option<Box<crate::generated::GeneratedArt>>,
|
||||
}
|
||||
|
||||
/// No extras: what [`Node::extras`] gives for a node without any.
|
||||
@@ -129,6 +132,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
|
||||
warp_piece: false,
|
||||
clip_pieces: false,
|
||||
image_quad: None,
|
||||
generated: None,
|
||||
};
|
||||
|
||||
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
|
||||
|
||||
+81
-18
@@ -463,14 +463,76 @@ impl Node {
|
||||
self.visual(Some(symbols))
|
||||
}
|
||||
|
||||
/// The visual box of a group or layer without a clipping path, from the visual boxes of its
|
||||
/// [`Node::editing_children`]: for a walk that measures the members as well.
|
||||
/// A box round a group or layer without a clipping path, from boxes round its
|
||||
/// [`Node::editing_children`], grown by the farthest its own strokes can reach from any path
|
||||
/// ([`Appearance::outset`]): for boxes measured where the members' shapes are not at hand.
|
||||
/// [`Node::visual_of_measured_members`] measures the strokes along the members.
|
||||
pub fn visual_of_members(&self, members: impl Iterator<Item = Option<Rect>>) -> Option<Rect> {
|
||||
// The container's own strokes paint around its members.
|
||||
let o = self.appearance.outset();
|
||||
members.fold(None, vectorcraft_geom::union_opt).map(|b| b.inflate(o, o))
|
||||
}
|
||||
|
||||
/// The visual box of a group or layer without a clipping path, from its
|
||||
/// [`Node::editing_children`] paired with their visual boxes: for a walk that measures the
|
||||
/// members as well. The container's own strokes are measured along the shape of each member
|
||||
/// path and compound path, at any depth in its groups; they paint nothing round images, symbol
|
||||
/// instances, guides and hidden members, and grow the box of any other member by the farthest
|
||||
/// they can reach ([`Appearance::outset`]), measured with `symbols` as in
|
||||
/// [`Node::visual_bounds_with`].
|
||||
pub fn visual_of_measured_members<'a>(
|
||||
&self,
|
||||
members: impl Iterator<Item = (&'a Node, Option<Rect>)>,
|
||||
symbols: Option<&SymbolBoxes>,
|
||||
) -> Option<Rect> {
|
||||
let stroked = self.appearance.painted_strokes().next().is_some();
|
||||
members.fold(None, |acc, (c, b)| {
|
||||
let own = if stroked { c.strokes_of_container(&self.appearance, Some(b), symbols) } else { None };
|
||||
vectorcraft_geom::union_opt(vectorcraft_geom::union_opt(acc, b), own)
|
||||
})
|
||||
}
|
||||
|
||||
/// The box the strokes of `appearance`, the appearance of a group or layer that holds this
|
||||
/// object, paint along it, measured with `symbols` as in [`Node::visual_bounds_with`]: the box
|
||||
/// [`Node::visual_of_measured_members`] takes in for this member besides its own visual box.
|
||||
pub fn painted_by_container(&self, appearance: &Appearance, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
|
||||
appearance.painted_strokes().next()?;
|
||||
self.strokes_of_container(appearance, None, symbols)
|
||||
}
|
||||
|
||||
/// The box the strokes of `appearance`, a container's, paint along this member, whose visual
|
||||
/// box is `measured` when known: along the shape of a path or compound path, as it measures its
|
||||
/// own strokes ([`Appearance::stroked_bounds`]); along the members of a group or layer without
|
||||
/// a clipping path that is not a compound shape; nothing for a hidden member, a guide, an image
|
||||
/// or a symbol instance, which the strokes do not paint; and the member's visual box grown by
|
||||
/// the farthest the strokes can reach ([`Appearance::outset`]) for anything else.
|
||||
fn strokes_of_container(&self, appearance: &Appearance, measured: Option<Option<Rect>>, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
|
||||
if !self.visible || self.is_guide() {
|
||||
return None;
|
||||
}
|
||||
match &self.kind {
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => self.stroked_by(appearance, symbols),
|
||||
NodeKind::Group { clip: false, .. } | NodeKind::Layer { clip: false, .. } if !self.is_compound_shape() => self
|
||||
.editing_children()
|
||||
.iter()
|
||||
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.strokes_of_container(appearance, None, symbols))),
|
||||
NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => None,
|
||||
_ => {
|
||||
let o = appearance.outset();
|
||||
measured.unwrap_or_else(|| self.visual(symbols)).map(|b| b.inflate(o, o))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The visual box of this path or compound path painted with the strokes of `appearance`,
|
||||
/// measured along its shape ([`Appearance::stroked_bounds`]).
|
||||
fn stroked_by(&self, appearance: &Appearance, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
|
||||
// A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath.
|
||||
let dots = appearance.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square));
|
||||
let b = self.drawn(symbols, dots).or_else(|| self.geometric(symbols))?;
|
||||
Some(appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
@@ -485,7 +547,9 @@ impl Node {
|
||||
}
|
||||
}
|
||||
NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.visual(symbols))),
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } => self.visual_of_members(self.editing_children().iter().map(|c| c.visual(symbols))),
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } => {
|
||||
self.visual_of_measured_members(self.editing_children().iter().map(|c| (c.as_ref(), c.visual(symbols))), symbols)
|
||||
}
|
||||
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);
|
||||
@@ -495,12 +559,7 @@ impl Node {
|
||||
let o = crate::live::max_outset(content, symbols);
|
||||
self.geometric(symbols).map(|b| b.inflate(o, o))
|
||||
}
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
|
||||
// A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath.
|
||||
let dots = self.appearance.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square));
|
||||
let b = self.drawn(symbols, dots).or_else(|| self.geometric(symbols))?;
|
||||
Some(self.appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default()))
|
||||
}
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => self.stroked_by(&self.appearance, symbols),
|
||||
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),
|
||||
@@ -552,19 +611,23 @@ impl Node {
|
||||
self.children()?.iter().find(|c| c.id == r.path)?.path_data()
|
||||
}
|
||||
|
||||
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
|
||||
{
|
||||
/// Moves what `a` moves in the node's extras: a dimension's measurement, a flare's center and
|
||||
/// end point, and the place a generator's art is drawn again at, with what `sc` scales.
|
||||
fn transform_extras(&mut self, a: Affine, sc: &Scaling) {
|
||||
let Some(e) = self.extras_if_any() else { return };
|
||||
if let Some(dimension) = &mut e.dimension {
|
||||
dimension.transform(a);
|
||||
}
|
||||
// So does a flare's center and end point.
|
||||
if let Some(e) = self.extras_if_any()
|
||||
&& let Some(flare) = &mut e.flare
|
||||
{
|
||||
if let Some(flare) = &mut e.flare {
|
||||
flare.transform(a);
|
||||
}
|
||||
if let Some(generated) = &mut e.generated {
|
||||
generated.transform(a, sc);
|
||||
}
|
||||
}
|
||||
|
||||
fn transform_scaled(&mut self, a: Affine, sc: &Scaling) {
|
||||
self.transform_extras(a, sc);
|
||||
// The path the objects are attached to, before it is transformed.
|
||||
let on_path_before = self.on_path_data().cloned();
|
||||
// A distorted image's placement nearest its corners, before they are transformed (`None`
|
||||
|
||||
@@ -498,6 +498,31 @@ fn a_lone_anchor_widens_the_visual_box_only_where_its_cap_draws_a_dot() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The dot a round or projecting cap draws for a closed lone anchor reaches half the stroke's
|
||||
/// width round the anchor under every join, miter and bevel joins included, which measure the
|
||||
/// stroke along its segments.
|
||||
#[test]
|
||||
fn a_lone_anchors_dot_reaches_half_the_stroke_width_under_every_join() {
|
||||
use crate::appearance::{LineCap, LineJoin};
|
||||
use vectorcraft_geom::{Point, SubPath};
|
||||
let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
for join in [LineJoin::Miter, LineJoin::Bevel, LineJoin::Round] {
|
||||
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
|
||||
let mut subpaths = square.subpaths.clone();
|
||||
subpaths.push(SubPath::polyline(&[Point::new(30.0, 5.0)], true));
|
||||
let mut p = Node::path(NodeId(2), PathData::new(subpaths), Appearance::default_art());
|
||||
let s = p.appearance.stroke_mut().unwrap();
|
||||
(s.cap, s.join, s.width) = (cap, join, 4.0);
|
||||
let visual = p.visual_bounds().unwrap();
|
||||
if cap == LineCap::Butt {
|
||||
assert!(visual.x1 < 13.0, "{join:?} {cap:?}: the visual box {visual:?} reaches toward a lone anchor that draws nothing");
|
||||
} else {
|
||||
assert!(visual.x1 >= 32.0 - 1e-9 && visual.y1 >= 10.0, "{join:?} {cap:?}: the visual box {visual:?} leaves out the dot's reach");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's box from its members' boxes grows by the group's own strokes, leaves out members
|
||||
/// without a box, and is `None` when none has one.
|
||||
#[test]
|
||||
@@ -512,6 +537,52 @@ fn visual_of_members_unions_the_members_and_grows_by_the_group_stroke() {
|
||||
assert_eq!(g.visual_of_members([].into_iter()), None);
|
||||
}
|
||||
|
||||
/// A group's or layer's own miter-joined stroke is measured along its members' shapes, as a
|
||||
/// path's is: a 10 pt stroke round a square reaches 5 pt past it, not the 50 pt a miter spike
|
||||
/// could reach, through nested groups and in a turned frame too. It paints nothing round a hidden
|
||||
/// member or an image.
|
||||
#[test]
|
||||
fn a_containers_own_miter_stroke_is_measured_along_its_members() {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let path = |id, r: Rect| Arc::new(Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)));
|
||||
let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 10.0);
|
||||
assert_eq!(stroke.outset(), 50.0, "a 10 pt miter-joined stroke can reach 50 pt");
|
||||
let stroked = |mut n: Node| {
|
||||
n.appearance = stroke.clone().into();
|
||||
n
|
||||
};
|
||||
let square = Rect::new(100.0, 100.0, 200.0, 200.0);
|
||||
let around = Some(Rect::new(95.0, 95.0, 205.0, 205.0));
|
||||
assert_eq!(stroked(Node::group(NodeId(1), vec![path(2, square)])).visual_bounds(), around, "a group");
|
||||
let nested = Node::group(NodeId(1), vec![Arc::new(Node::group(NodeId(3), vec![path(2, square)]))]);
|
||||
assert_eq!(stroked(nested.clone()).visual_bounds(), around, "a nested group");
|
||||
// Measured in a turned frame, as a box square to a turned selection is.
|
||||
let turned = stroked(nested).bounds_in(&crate::Document::new(400.0, 400.0).symbol_boxes(), Affine::rotate(std::f64::consts::FRAC_PI_2), true);
|
||||
let want = Rect::new(-205.0, 95.0, -95.0, 205.0);
|
||||
assert!(
|
||||
turned.is_some_and(|b| (b.x0 - want.x0).abs() + (b.y0 - want.y0).abs() + (b.x1 - want.x1).abs() + (b.y1 - want.y1).abs() < 1e-9),
|
||||
"{turned:?}"
|
||||
);
|
||||
let mut layer = Node::layer(NodeId(1), "Layer 1", LayerColor::Preset(0));
|
||||
if let NodeKind::Layer { children, .. } = &mut layer.kind {
|
||||
children.push(path(2, square));
|
||||
}
|
||||
assert_eq!(stroked(layer).visual_bounds(), around, "a layer");
|
||||
let mut hidden = (*path(3, Rect::new(100.0, 300.0, 200.0, 400.0))).clone();
|
||||
hidden.visible = false;
|
||||
let image = ImageObject {
|
||||
key: "k".into(),
|
||||
width: 10,
|
||||
height: 10,
|
||||
xf: Affine::translate((500.0, 100.0)),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let kids = vec![path(2, square), Arc::new(hidden), Arc::new(Node::new(NodeId(4), NodeKind::Image(Box::new(image))))];
|
||||
assert_eq!(stroked(Node::group(NodeId(1), kids)).visual_bounds(), Some(Rect::new(95.0, 95.0, 510.0, 400.0)), "a hidden member and an image");
|
||||
}
|
||||
|
||||
/// 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]
|
||||
|
||||
@@ -18,6 +18,7 @@ impl Serialize for Node {
|
||||
use crate::skip::{is_default, is_one, is_true};
|
||||
use serde::ser::SerializeStruct;
|
||||
let e = self.extras();
|
||||
let generated = crate::generated::written(e.generated.as_deref());
|
||||
// As the derive did: the fields written, then each field written or skipped in order.
|
||||
let skips = [
|
||||
false,
|
||||
@@ -61,6 +62,7 @@ impl Serialize for Node {
|
||||
is_default(&e.warp_piece),
|
||||
is_default(&e.clip_pieces),
|
||||
e.image_quad.is_none(),
|
||||
generated.is_none(),
|
||||
];
|
||||
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
|
||||
let mut skip = skips.into_iter();
|
||||
@@ -87,6 +89,8 @@ impl Serialize for Node {
|
||||
field!("type_outlines", &e.type_outlines);
|
||||
field!("pixelated", &e.pixelated);
|
||||
field!("shaper", &e.shaper);
|
||||
// A generated art object's art, written while this lives, holds plain art only.
|
||||
let _inside = generated.map(|_| crate::generated::Inside::enter());
|
||||
field!("kind", &self.kind);
|
||||
field!("graphic_style", &e.graphic_style);
|
||||
field!("attrs", &e.attrs);
|
||||
@@ -110,6 +114,7 @@ impl Serialize for Node {
|
||||
field!("warp_piece", &e.warp_piece);
|
||||
field!("clip_pieces", &e.clip_pieces);
|
||||
field!("image_quad", &e.image_quad);
|
||||
field!("generated", &generated.map(|g| crate::generated::Wire::of(g, self)));
|
||||
st.end()
|
||||
}
|
||||
}
|
||||
@@ -265,6 +270,14 @@ pub(super) struct NodeWire {
|
||||
clip_pieces: bool,
|
||||
#[serde(default, deserialize_with = "image_corners")]
|
||||
image_quad: Option<Box<[vectorcraft_geom::Point; 4]>>,
|
||||
/// Read as it is and checked against the node's kind and art ([`crate::generated`]).
|
||||
#[serde(default, deserialize_with = "present_value")]
|
||||
generated: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
/// A field's value as a file holds it, a null included: only an absent field is none.
|
||||
fn present_value<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<serde_json::Value>, D::Error> {
|
||||
serde_json::Value::deserialize(d).map(Some)
|
||||
}
|
||||
|
||||
/// A distorted image's corners as a file holds them: a list of exactly four points, else none (the
|
||||
@@ -455,7 +468,7 @@ fn image_corners<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Box<[v
|
||||
}
|
||||
|
||||
impl From<NodeWire> for Node {
|
||||
fn from(w: NodeWire) -> Self {
|
||||
fn from(mut w: NodeWire) -> Self {
|
||||
// Corners an image cannot take are dropped, so a later transform cannot make them its own.
|
||||
let image_quad = match &w.kind {
|
||||
NodeKind::Image(im) => w.image_quad.filter(|q| crate::image_quad::check_for(im, q).is_ok()),
|
||||
@@ -491,6 +504,7 @@ impl From<NodeWire> for Node {
|
||||
warp_piece: w.warp_piece,
|
||||
clip_pieces: w.clip_pieces,
|
||||
image_quad,
|
||||
generated: w.generated.and_then(|g| crate::generated::read(g, &mut w.kind)),
|
||||
};
|
||||
Node {
|
||||
id: w.id,
|
||||
|
||||
@@ -121,10 +121,16 @@ impl Node {
|
||||
pub fn bounds_in(&self, symbols: &SymbolBoxes, a: Affine, visual: bool) -> Option<Rect> {
|
||||
match &self.kind {
|
||||
NodeKind::Group { clip: false, .. } => {
|
||||
let b = self.editing_children().iter().fold(None, |acc, c| union_opt(acc, c.bounds_in(symbols, a, visual)));
|
||||
// The group's own strokes paint around its members (as in `visual_bounds`).
|
||||
let o = if visual { self.appearance.outset() } else { 0.0 };
|
||||
b.map(|b| b.inflate(o, o))
|
||||
// The group's own strokes paint along its members, placed by `a` (as in `visual_bounds`).
|
||||
let stroked = visual && self.appearance.painted_strokes().next().is_some();
|
||||
self.editing_children().iter().fold(None, |acc, c| {
|
||||
let own = stroked.then(|| {
|
||||
let mut placed = (**c).clone();
|
||||
placed.transform(a, false);
|
||||
placed.painted_by_container(&self.appearance, Some(symbols))
|
||||
});
|
||||
union_opt(union_opt(acc, c.bounds_in(symbols, a, visual)), own.flatten())
|
||||
})
|
||||
}
|
||||
NodeKind::Group { children, clip: true } => {
|
||||
let clip = children.first()?;
|
||||
|
||||
@@ -425,9 +425,13 @@ pub fn uses_pattern(n: &Node, name: Option<&str>) -> bool {
|
||||
}
|
||||
|
||||
/// Transform Patterns without Transform Objects: `m` moves the pattern tiles of `n` and of
|
||||
/// everything inside it, and the art stays where it is.
|
||||
/// everything inside it, and the art stays where it is. A generated art object keeps the move, so
|
||||
/// its art drawn again has its tiles moved too.
|
||||
pub fn transform_patterns_only(n: &mut Node, m: Affine) {
|
||||
transform_pattern_paints(n, m);
|
||||
if let Some(g) = n.extras_if_any().and_then(|e| e.generated.as_deref_mut()) {
|
||||
g.pattern_transform = m * g.pattern_transform;
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
transform_patterns_only(Arc::make_mut(c), m);
|
||||
}
|
||||
|
||||
@@ -17,15 +17,16 @@
|
||||
//! other stop there, showing their previews).
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cell::Cell;
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
use vectorcraft_geom::{Affine, PathData, Rect, SubPath};
|
||||
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
|
||||
use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol};
|
||||
use crate::{Appearance, AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol};
|
||||
|
||||
/// A placed document: an artboard of another VectorCraft file, a page of a PDF or `.ai` file, or
|
||||
/// an EPS file's art, shown as one locked object.
|
||||
@@ -123,12 +124,27 @@ impl PlacedDocument {
|
||||
}
|
||||
|
||||
/// The art the object shows, as plain objects with `n`'s id: one group, its resources named
|
||||
/// as [`Document::with_placed_art`] adds them (nothing until that has read it).
|
||||
/// as [`Document::with_placed_art`] adds them (nothing until that has read it). While
|
||||
/// [`Crossed`] is on for this thread, its box crossed from corner to corner instead
|
||||
/// ([`Self::crossed_art`]).
|
||||
pub fn art(&self, n: &Node) -> Vec<Node> {
|
||||
if crossed() {
|
||||
return vec![self.crossed_art(n)];
|
||||
}
|
||||
let prefix = prefix(&self.key);
|
||||
read_cached(self).and_then(|e| self.art_node(n, &e, &prefix)).into_iter().collect()
|
||||
}
|
||||
|
||||
/// The object's box crossed from corner to corner, as one group with `n`'s id: a path of the
|
||||
/// box's outline and its two diagonals with a black 1 pt stroke. Outline mode without Document
|
||||
/// Setup → Show Images in Outline Mode shows the object so, and its effects reshape this art.
|
||||
pub fn crossed_art(&self, n: &Node) -> Node {
|
||||
let q = self.corners();
|
||||
let path = PathData::new(vec![SubPath::polyline(&q, true), SubPath::polyline(&[q[0], q[2]], false), SubPath::polyline(&[q[1], q[3]], false)]);
|
||||
let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
Node::group(n.id, vec![Arc::new(Node::path(art_id(), path, stroke))])
|
||||
}
|
||||
|
||||
/// Read `e`'s art placed as this object `n` shows it (`n`'s id), its resources renamed with
|
||||
/// `prefix`.
|
||||
fn art_node(&self, n: &Node, e: &ReadDocument, prefix: &str) -> Option<Node> {
|
||||
@@ -364,6 +380,28 @@ pub type Loader = fn(&PlacedDocument, &[u8]) -> Option<(Document, Node, Rect)>;
|
||||
|
||||
static LOADER: OnceLock<Loader> = OnceLock::new();
|
||||
|
||||
std::thread_local! {
|
||||
/// Open checks use previews rather than loading placed documents for drawing.
|
||||
static PREVIEWS_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Restores whether only previews are used when an open check ends, including on unwind.
|
||||
struct PreviewsOnly(bool);
|
||||
|
||||
impl Drop for PreviewsOnly {
|
||||
fn drop(&mut self) {
|
||||
PREVIEWS_ONLY.with(|p| p.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Run an open check using placed documents' previews instead of loading their art on this
|
||||
/// thread. Nested checks keep the scope active until the outer check ends. This prevents an
|
||||
/// open check and drawing from recursively loading each other's nested files.
|
||||
pub fn with_previews<T>(check: impl FnOnce() -> T) -> T {
|
||||
let _scope = PreviewsOnly(PREVIEWS_ONLY.with(|p| p.replace(true)));
|
||||
check()
|
||||
}
|
||||
|
||||
/// Register how files are read (the first registration stays).
|
||||
pub fn set_loader(l: Loader) {
|
||||
// Already set: the same loader, registered by another session.
|
||||
@@ -438,8 +476,12 @@ impl Cache {
|
||||
}
|
||||
|
||||
/// `p`'s file (`bytes`) read, from the cache when it was read already: what the renderer draws a
|
||||
/// placed document from. `None` when it can't be read (or no loader is registered).
|
||||
/// placed document from. `None` when it can't be read, no loader is registered, or an open check
|
||||
/// uses [`with_previews`].
|
||||
pub fn read(p: &PlacedDocument, bytes: &Arc<Vec<u8>>) -> Option<Arc<ReadDocument>> {
|
||||
if PREVIEWS_ONLY.with(std::cell::Cell::get) {
|
||||
return None;
|
||||
}
|
||||
if let Some(e) = cache().get(&p.key, false, Some(bytes)) {
|
||||
return Some(e);
|
||||
}
|
||||
@@ -470,6 +512,36 @@ fn read_preview(p: &PlacedDocument, bytes: &Arc<Vec<u8>>) -> Option<Arc<ReadDocu
|
||||
Some(e)
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Whether [`PlacedDocument::art`] gives the crossed box on this thread ([`Crossed`]).
|
||||
static CROSSED: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
|
||||
/// While alive, [`PlacedDocument::art`] on this thread gives each placed document's box crossed
|
||||
/// from corner to corner ([`PlacedDocument::crossed_art`]) when it was made with `true`, and the
|
||||
/// file's art when made with `false`; once dropped, the setting before it applies again. A
|
||||
/// renderer holds one while it draws or measures Outline mode without Document Setup → Show Images
|
||||
/// in Outline Mode, so that effects and live objects make their art from the crossed box.
|
||||
#[must_use]
|
||||
pub struct Crossed(bool);
|
||||
|
||||
impl Crossed {
|
||||
pub fn set(on: bool) -> Self {
|
||||
Self(CROSSED.with(|c| c.replace(on)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Crossed {
|
||||
fn drop(&mut self) {
|
||||
CROSSED.with(|c| c.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether [`PlacedDocument::art`] gives the crossed box on this thread ([`Crossed`]).
|
||||
pub fn crossed() -> bool {
|
||||
CROSSED.with(Cell::get)
|
||||
}
|
||||
|
||||
/// `p`'s file as read already (else its preview's), without reading it.
|
||||
pub fn read_cached(p: &PlacedDocument) -> Option<Arc<ReadDocument>> {
|
||||
let mut c = cache();
|
||||
@@ -692,6 +764,22 @@ mod tests {
|
||||
Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0)))
|
||||
}
|
||||
|
||||
/// Nested open checks skip both new and cached art, and restore ordinary reads afterward.
|
||||
#[test]
|
||||
fn open_checks_leave_placed_documents_for_drawing_afterward() {
|
||||
set_loader(stub_loader);
|
||||
let p = placed("open-check-1");
|
||||
let bytes = Arc::new(b"leaf".to_vec());
|
||||
with_previews(|| assert!(read(&p, &bytes).is_none()));
|
||||
assert!(read(&p, &bytes).is_some());
|
||||
with_previews(|| {
|
||||
assert!(read(&p, &bytes).is_none());
|
||||
with_previews(|| assert!(read(&p, &bytes).is_none()));
|
||||
assert!(read(&p, &bytes).is_none());
|
||||
});
|
||||
assert!(read(&p, &bytes).is_some());
|
||||
}
|
||||
|
||||
/// A color-masked image in a placed document's art keeps its masked pixels under the prefixed
|
||||
/// names its resources get.
|
||||
#[test]
|
||||
|
||||
+108
-13
@@ -291,9 +291,12 @@ impl StrokeLayer {
|
||||
// past them are measured.
|
||||
match self.body_along(&segs, side, out) {
|
||||
Some(body) => out = out.union(body),
|
||||
// A subpath with no length paints at most its caps' dot.
|
||||
// A subpath with no length paints at most its caps' dot. A closed subpath with
|
||||
// no segment, a lone anchor, has its dot at that anchor under a round or
|
||||
// projecting cap.
|
||||
None if !butt => {
|
||||
let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b));
|
||||
let lone = (self.cap != LineCap::Butt).then(|| els[r.start].end_point()).flatten().map(|p| Rect::from_points(p, p));
|
||||
let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)).or(lone);
|
||||
out = dot.map_or(out, |d| out.union(d.inflate(side, side)));
|
||||
}
|
||||
None => {}
|
||||
@@ -353,13 +356,18 @@ impl StrokeLayer {
|
||||
/// wider side of a farther one can paint past the nearest.
|
||||
pub fn hits(&self, bp: &BezPath, rule: FillRule, p: Point, tol: f64) -> bool {
|
||||
let reach = self.reach() + tol;
|
||||
if self.width.is_nan() || self.width <= 0.0 || !bp.bounding_box().inflate(reach, reach).contains(p) {
|
||||
if self.width.is_nan() || self.width <= 0.0 {
|
||||
return false;
|
||||
}
|
||||
let els = bp.elements();
|
||||
// The box of the segments leaves out a closed subpath of one anchor, which has none: away
|
||||
// from the segments only the dot a cap draws for such a subpath can paint.
|
||||
if !bp.bounding_box().inflate(reach, reach).contains(p) {
|
||||
return self.draws_dots() && subpaths(bp).into_iter().any(|(r, closed)| self.dot_contains(bp, rule, (&els[r], closed), p, tol));
|
||||
}
|
||||
if head_ends(self, bp).into_iter().any(|(at, out, end)| self.head_contains(at, out, end, p, tol)) {
|
||||
return true;
|
||||
}
|
||||
let els = bp.elements();
|
||||
// Aligned strokes paint on one side of the path only.
|
||||
let on_side = |region: Option<bool>, d: f64| region.is_none_or(|inside| d <= tol || fill_contains(bp, rule, p) == inside);
|
||||
// Every dash gets the caps, as wide as the stroke where the dash ends: round ones reach as
|
||||
@@ -371,7 +379,13 @@ impl StrokeLayer {
|
||||
LineCap::Square => Some(std::f64::consts::SQRT_2),
|
||||
};
|
||||
for (r, closed) in subpaths(bp) {
|
||||
let segs = drawn(&els[r]);
|
||||
let segs = drawn(&els[r.clone()]);
|
||||
if segs.is_empty() {
|
||||
if self.dot_contains(bp, rule, (&els[r], closed), p, tol) {
|
||||
return true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (half, region) = self.body(closed);
|
||||
let full = half * self.profile_max() * dash_caps.unwrap_or(1.0);
|
||||
// Past a butt cap or a bevel the stroke stops at the segments' corners. A width profile
|
||||
@@ -442,6 +456,32 @@ impl StrokeLayer {
|
||||
false
|
||||
}
|
||||
|
||||
/// Does this stroke draw a dot for a subpath that never leaves its first point? A round or a
|
||||
/// projecting cap draws one on a stroke without a dash pattern or a width profile.
|
||||
fn draws_dots(&self) -> bool {
|
||||
self.cap != LineCap::Butt && self.profile.is_none() && !self.dash.as_ref().is_some_and(Dash::is_dashed)
|
||||
}
|
||||
|
||||
/// Is `p` within `tol` of the dot this stroke draws for the subpath `els` (`closed`: a closed
|
||||
/// one) of `bp`, filled with `rule`, when every point of the subpath is its first point
|
||||
/// ([`Self::draws_dots`])? A round cap draws a disc there and a projecting cap a square along
|
||||
/// the x axis, as wide as the stroke's body ([`StrokeLayer::body`]). Inside and outside
|
||||
/// strokes of a closed subpath paint on their own side of `bp` only.
|
||||
fn dot_contains(&self, bp: &BezPath, rule: FillRule, (els, closed): (&[vectorcraft_geom::PathEl], bool), p: Point, tol: f64) -> bool {
|
||||
if !self.draws_dots() || vectorcraft_geom::kurbo::segments(els.iter().copied()).any(|s| has_length(&s)) {
|
||||
return false;
|
||||
}
|
||||
let Some(at) = els.first().and_then(vectorcraft_geom::PathEl::end_point) else { return false };
|
||||
let (half, region) = self.body(closed);
|
||||
let v = p - at;
|
||||
let d = v.hypot();
|
||||
let on_dot = match self.cap {
|
||||
LineCap::Square => v.x.abs().max(v.y.abs()) <= half + tol,
|
||||
_ => d <= half + tol,
|
||||
};
|
||||
on_dot && region.is_none_or(|inside| d <= tol || fill_contains(bp, rule, p) == inside)
|
||||
}
|
||||
|
||||
/// Does this stroke, where it stops at the corners of its segments ([`Self::stops_at_corners`]),
|
||||
/// paint `p`, which is within `side` (and `tol`) of segment `i` of the subpath `segs`
|
||||
/// (`closed`: a closed one) and nearest to it at `t`? It does when `p` is not past the end of
|
||||
@@ -560,21 +600,40 @@ pub const SLANT_INSTANCES: usize = 4096;
|
||||
impl crate::Node {
|
||||
/// Does a visible stroke of this object, of an object in it or of an object in a symbol
|
||||
/// instance's art from `symbols`, placed by `a`, stop at the corners of a segment at a slant
|
||||
/// ([`Appearance::has_slanted_stroke_corners`])? Past [`SLANT_INSTANCES`] instances it answers
|
||||
/// yes.
|
||||
/// ([`Appearance::has_slanted_stroke_corners`])? The strokes of a group or layer without a
|
||||
/// clipping path count along the paths and compound paths in it, which they paint along
|
||||
/// ([`crate::Node::painted_by_container`]). Past [`SLANT_INSTANCES`] instances it answers yes.
|
||||
pub fn has_slanted_stroke_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool {
|
||||
self.slanted_corners(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES))
|
||||
self.slanted_corners(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES), &[])
|
||||
}
|
||||
|
||||
/// [`Self::has_slanted_stroke_corners`] with `left` instances still to look into.
|
||||
fn slanted_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> bool {
|
||||
/// [`Self::has_slanted_stroke_corners`] with `left` instances still to look into, and the
|
||||
/// appearances of the groups and layers around this object whose strokes paint along it in
|
||||
/// `around`.
|
||||
fn slanted_corners(
|
||||
&self,
|
||||
symbols: &crate::SymbolBoxes,
|
||||
a: vectorcraft_geom::Affine,
|
||||
left: &std::cell::Cell<usize>,
|
||||
around: &[&Appearance],
|
||||
) -> bool {
|
||||
if let crate::NodeKind::SymbolInstance { symbol, xf } = &self.kind {
|
||||
let Some(l) = left.get().checked_sub(1) else { return true };
|
||||
left.set(l);
|
||||
return symbols.measure_art(symbol, |art| art.slanted_corners(symbols, a * *xf, left)).unwrap_or(false);
|
||||
return symbols.measure_art(symbol, |art| art.slanted_corners(symbols, a * *xf, left, &[])).unwrap_or(false);
|
||||
}
|
||||
(self.appearance.has_cornered_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_stroke_corners(&bp, a)))
|
||||
|| self.children().is_some_and(|c| c.iter().any(|c| c.slanted_corners(symbols, a, left)))
|
||||
let slanted = |ap: &Appearance| ap.has_cornered_stroke() && self.stroke_path().is_some_and(|bp| ap.has_slanted_stroke_corners(&bp, a));
|
||||
let shaped = matches!(self.kind, crate::NodeKind::Path { .. } | crate::NodeKind::Compound { .. });
|
||||
if slanted(&self.appearance) || shaped && around.iter().any(|ap| slanted(ap)) {
|
||||
return true;
|
||||
}
|
||||
let plain =
|
||||
matches!(self.kind, crate::NodeKind::Group { clip: false, .. } | crate::NodeKind::Layer { clip: false, .. }) && !self.is_compound_shape();
|
||||
let mut inner: Vec<&Appearance> = if plain { around.to_vec() } else { vec![] };
|
||||
if plain && self.appearance.has_cornered_stroke() {
|
||||
inner.push(&self.appearance);
|
||||
}
|
||||
self.children().is_some_and(|c| c.iter().any(|c| c.slanted_corners(symbols, a, left, &inner)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -998,4 +1057,40 @@ mod tests {
|
||||
assert!(hit::hit_test(&d, Point::new(108.0, 150.0), opt).is_none(), "an unfilled interior");
|
||||
assert_eq!(d.node(id).unwrap().visual_bounds(), Some(Rect::new(90.0, 90.0, 210.0, 210.0)));
|
||||
}
|
||||
|
||||
/// A round cap draws a disc and a projecting cap a square on a subpath that never leaves its
|
||||
/// first point, a closed lone anchor or a line to the same point: a click on it hits the path,
|
||||
/// and one past it misses. A butt cap draws nothing there.
|
||||
#[test]
|
||||
fn clicks_hit_the_dot_of_a_lone_anchor() {
|
||||
let at = Point::new(150.0, 120.0);
|
||||
let mut lone = BezPath::new();
|
||||
lone.move_to(at);
|
||||
lone.close_path();
|
||||
let mut zero = BezPath::new();
|
||||
zero.move_to(at);
|
||||
zero.line_to(at);
|
||||
let (on_edge, corner, past) = (Point::new(154.5, 120.0), Point::new(154.0, 124.0), Point::new(156.0, 120.0));
|
||||
for (name, bp) in [("closed lone anchor", &lone), ("zero-length line", &zero)] {
|
||||
let round = stroke(10.0, |s| s.cap = LineCap::Round);
|
||||
let square = stroke(10.0, |s| s.cap = LineCap::Square);
|
||||
assert!(round.hits(bp, FillRule::NonZero, at, 0.1) && round.hits(bp, FillRule::NonZero, on_edge, 0.1), "{name}: round dot");
|
||||
assert!(!round.hits(bp, FillRule::NonZero, corner, 0.1) && !round.hits(bp, FillRule::NonZero, past, 0.1), "{name}: past the disc");
|
||||
assert!(square.hits(bp, FillRule::NonZero, corner, 0.1), "{name}: the square's corner");
|
||||
assert!(!square.hits(bp, FillRule::NonZero, past, 0.1), "{name}: past the square");
|
||||
assert!(!stroke(10.0, |_| {}).hits(bp, FillRule::NonZero, on_edge, 0.1), "{name}: a butt cap draws no dot");
|
||||
}
|
||||
// In a document: a click on the dot of a closed lone anchor hits the path's stroke, and a
|
||||
// marquee over the anchor selects it.
|
||||
let mut d = Document::new(300.0, 300.0);
|
||||
let (l, id) = (d.layers[0].id, d.alloc_id());
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 10.0);
|
||||
ap.stroke_mut().unwrap().cap = LineCap::Round;
|
||||
d.insert(Some(l), 0, Node::path(id, PathData::from_bezpath(&lone), ap)).unwrap();
|
||||
let opt = hit::HitOptions { tol: 0.5, ..Default::default() };
|
||||
let h = hit::hit_test(&d, Point::new(153.5, 121.0), opt).expect("a click on the dot");
|
||||
assert_eq!((h.leaf, h.kind), (id, hit::HitKind::Stroke));
|
||||
assert!(hit::hit_test(&d, Point::new(157.0, 120.0), opt).is_none(), "past the dot");
|
||||
assert_eq!(hit::marquee(&d, Rect::new(140.0, 110.0, 160.0, 130.0), None, false), vec![id]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,6 +187,48 @@ impl Selection {
|
||||
self.key_anchor = None;
|
||||
}
|
||||
}
|
||||
/// Select `id` itself in place of the selected object around it, keeping the rest of that
|
||||
/// object selected. The outermost selected object that holds `id` (a group, or a compound path
|
||||
/// selected whole) and every selected object between it and `id` leave the selection. In their
|
||||
/// place go, at the outermost one's position, the objects inside them on the way down to `id`,
|
||||
/// level by level: at each level the objects beside the one that holds `id`, and at the last
|
||||
/// level `id` and the objects beside it, each level in stacking order. A Shaper Group's
|
||||
/// original shapes, and objects that are hidden, locked or on a locked artboard
|
||||
/// ([`Document::is_editable`]), are not taken in.
|
||||
///
|
||||
/// When `id` is also selected itself, it keeps its place in the selection.
|
||||
///
|
||||
/// Returns whether the selection changed. It does not change when `id` is not inside a selected
|
||||
/// object, is inside one that is partly selected (anchors or segments), is one of a selected
|
||||
/// Shaper Group's original shapes, or is hidden, locked or on a locked artboard itself.
|
||||
pub fn expand_to(&mut self, doc: &Document, id: NodeId) -> bool {
|
||||
let Some(chain) = doc.ancestry(id) else { return false };
|
||||
let Some(top) = chain.iter().position(|a| self.contains(*a)) else { return false };
|
||||
let holder = chain[top];
|
||||
if self.anchors.contains_key(&holder) || self.segments.contains_key(&holder) {
|
||||
return false;
|
||||
}
|
||||
let editable = doc.editable();
|
||||
let mut members = Vec::new();
|
||||
for pair in chain[top..].windows(2) {
|
||||
let Some(n) = doc.node(pair[0]) else { return false };
|
||||
let originals = usize::from(n.extras().shaper.is_some());
|
||||
let children = n.children().map(Vec::as_slice).unwrap_or_default();
|
||||
if children.iter().take(originals).any(|c| c.id == pair[1]) {
|
||||
return false;
|
||||
}
|
||||
members.extend(children.iter().skip(originals).map(|c| c.id).filter(|c| editable(*c) && (*c == id || *c != pair[1])));
|
||||
}
|
||||
if !members.contains(&id) {
|
||||
return false;
|
||||
}
|
||||
let around: HashSet<NodeId> = chain[top..chain.len() - 1].iter().copied().collect();
|
||||
let at = self.objects.iter().take_while(|o| **o != holder).filter(|o| !around.contains(o)).count();
|
||||
self.remove_all(around);
|
||||
let selected: HashSet<NodeId> = self.objects.iter().copied().collect();
|
||||
self.objects.splice(at..at, members.into_iter().filter(|m| !selected.contains(m)));
|
||||
true
|
||||
}
|
||||
/// [`Self::add`] for each of `ids` in order, going through the selected objects once.
|
||||
pub fn add_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
|
||||
self.each(ids, false);
|
||||
|
||||
@@ -45,6 +45,80 @@ fn remove_all_does_what_removing_each_does() {
|
||||
assert_eq!(none, s);
|
||||
}
|
||||
|
||||
/// `expand_to` selects a member of a selected group in the group's place, beside the group's other
|
||||
/// objects at each level down to it, and leaves a selection it cannot open alone.
|
||||
#[test]
|
||||
fn expand_to_selects_a_member_in_place_of_its_selected_group() {
|
||||
let rect = || vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let l = d.layers[0].id;
|
||||
let [x, g, e, h, b, c, dd] = [(); 7].map(|_| d.alloc_id());
|
||||
let path = |id| Arc::new(Node::path(id, rect(), crate::Appearance::default_art()));
|
||||
let inner = Node::group(h, vec![path(b), path(c)]);
|
||||
let group = Node::group(g, vec![path(e), Arc::new(inner), path(dd)]);
|
||||
d.insert(Some(l), 0, Node::path(x, rect(), crate::Appearance::default_art())).unwrap();
|
||||
d.insert(Some(l), 1, group).unwrap();
|
||||
let mut s = Selection::default();
|
||||
s.set([x, g]);
|
||||
s.key = Some(g);
|
||||
assert!(s.expand_to(&d, b));
|
||||
assert_eq!(s.objects, [x, e, dd, b, c], "the group's objects beside the inner group, then the inner group's");
|
||||
assert_eq!(s.key, None, "the group leaves the selection with its key");
|
||||
assert!(!s.expand_to(&d, b), "a member selected itself with nothing selected around it");
|
||||
assert!(!s.expand_to(&d, x), "an object inside nothing selected");
|
||||
// A member selected beside the group around it keeps its place.
|
||||
let mut with_member = Selection::default();
|
||||
with_member.set([b, g]);
|
||||
assert!(with_member.expand_to(&d, b));
|
||||
assert_eq!(with_member.objects, [b, e, dd, c]);
|
||||
// An inner group selected beside the group leaves the selection too.
|
||||
let mut both = Selection::default();
|
||||
both.set([h, g]);
|
||||
assert!(both.expand_to(&d, b));
|
||||
assert_eq!(both.objects, [e, dd, b, c]);
|
||||
// A group with anchors recorded for it is left as it is.
|
||||
let mut partly = Selection::default();
|
||||
partly.set([g]);
|
||||
partly.anchors.insert(g, BTreeSet::from([(0, 0)]));
|
||||
let before = partly.clone();
|
||||
assert!(!partly.expand_to(&d, b));
|
||||
assert_eq!(partly, before);
|
||||
// A Shaper Group opens to its faces and never to its original shapes.
|
||||
let [shaper, sources, o1, o2, face] = [(); 5].map(|_| d.alloc_id());
|
||||
let mut sources_group = Node::group(sources, vec![path(o1), path(o2)]);
|
||||
sources_group.name = Some(crate::shaper::SOURCES.into());
|
||||
let mut shaper_group = Node::group(shaper, vec![Arc::new(sources_group), path(face)]);
|
||||
shaper_group.extras_mut().shaper = Some(Box::default());
|
||||
d.insert(Some(l), 2, shaper_group).unwrap();
|
||||
let mut shaped = Selection::default();
|
||||
shaped.set([shaper]);
|
||||
let before = shaped.clone();
|
||||
assert!(!shaped.expand_to(&d, o1), "an original shape");
|
||||
assert_eq!(shaped, before);
|
||||
assert!(shaped.expand_to(&d, face));
|
||||
assert_eq!(shaped.objects, [face]);
|
||||
// Hidden and locked objects beside the member stay out of the selection.
|
||||
let [k, shown, hidden, locked, last] = [(); 5].map(|_| d.alloc_id());
|
||||
let mut hidden_path = Node::path(hidden, rect(), crate::Appearance::default_art());
|
||||
hidden_path.visible = false;
|
||||
let mut locked_path = Node::path(locked, rect(), crate::Appearance::default_art());
|
||||
locked_path.locked = true;
|
||||
let kept = Node::group(k, vec![path(shown), Arc::new(hidden_path), Arc::new(locked_path), path(last)]);
|
||||
d.insert(Some(l), 3, kept).unwrap();
|
||||
let mut with_locked = Selection::default();
|
||||
with_locked.set([k]);
|
||||
assert!(with_locked.expand_to(&d, last));
|
||||
assert_eq!(with_locked.objects, [shown, last]);
|
||||
// A locked or hidden member itself does not open the group.
|
||||
for target in [locked, hidden] {
|
||||
let mut s = Selection::default();
|
||||
s.set([k]);
|
||||
let before = s.clone();
|
||||
assert!(!s.expand_to(&d, target), "{target:?}");
|
||||
assert_eq!(s, before);
|
||||
}
|
||||
}
|
||||
|
||||
/// A selection with every field set: objects 1 to 6 with 3 listed twice, anchors, segments, a key,
|
||||
/// a key anchor, a target, slices, guides, a key guide, new art, a symbol part and an on-path member.
|
||||
fn seeded() -> Selection {
|
||||
|
||||
@@ -579,3 +579,32 @@ fn nearest_finder_reads_one_path_per_object() {
|
||||
assert_eq!(path_lookups() - lookups, 0, "lookups by id");
|
||||
assert_eq!(tree_walks() - walks, 0, "walks of the tree");
|
||||
}
|
||||
|
||||
/// `Document::node` reads a node from the lookup cache without copying its index path, in nested groups and after
|
||||
/// objects were removed, and finds what a walk finds: 10,000 objects looked up one at a time copy no path.
|
||||
#[test]
|
||||
fn node_lookups_copy_no_index_path() {
|
||||
let (mut d, ids) = squares(10_000);
|
||||
let layer = d.layers[0].id;
|
||||
let mut nested = vec![];
|
||||
for g in 0..50 {
|
||||
let kids: Vec<Arc<Node>> = (0..4)
|
||||
.map(|_| {
|
||||
let id = d.alloc_id();
|
||||
nested.push(id);
|
||||
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()))
|
||||
})
|
||||
.collect();
|
||||
let (gid, inner) = (d.alloc_id(), d.alloc_id());
|
||||
d.insert(Some(layer), g, Node::group(gid, vec![Arc::new(Node::group(inner, kids))])).unwrap();
|
||||
}
|
||||
d.remove_many(&ids[..100]).unwrap();
|
||||
d.node(layer);
|
||||
let copies = path_copies();
|
||||
let found = ids[100..].iter().chain(&nested).filter(|id| d.node(**id).is_some_and(|n| n.id == **id)).count();
|
||||
assert_eq!(found, ids.len() - 100 + nested.len());
|
||||
assert_eq!(path_copies() - copies, 0, "index paths copied");
|
||||
assert!(ids[..100].iter().all(|id| d.node(*id).is_none()), "removed objects are not found");
|
||||
agree(&d, &ids[..200], "after remove_many");
|
||||
agree(&d, &nested, "nested");
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ pub(crate) fn apply(effects: &[vectorcraft_doc::Effect], path: &PathData, ctx: &
|
||||
if !has_geometry(effects) || path.is_empty() {
|
||||
return (path.clone(), crate::Carry::default());
|
||||
}
|
||||
let b = vectorcraft_geom::Shape::bounding_box(&path.to_bezpath());
|
||||
let b = path.bounds().unwrap_or_default();
|
||||
apply_geometry_carrying(effects, path, b, ctx)
|
||||
}
|
||||
|
||||
|
||||
@@ -58,10 +58,61 @@ pub fn raster_px_range(id: &str, key: &str) -> Option<std::ops::RangeInclusive<f
|
||||
documented_range(id, key, "px")
|
||||
}
|
||||
|
||||
/// The range parameter `key` of effect `id` is documented with, after any number of unit words
|
||||
/// (`key: lo..hi`, `key: unit lo..hi`, `key: screen angle deg lo..hi`) or as the first word of its
|
||||
/// description in parentheses (`key: unit (lo..hi, default)`), and before the rest of that
|
||||
/// description or the next parameter; `None` when its documentation gives none.
|
||||
pub(crate) fn any_documented_range(id: &str, key: &str) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
let doc = catalog_index().get(id)?.params;
|
||||
let starts = |at: usize| starts_key(doc, at);
|
||||
doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| {
|
||||
let rest = doc.get(at + key.len()..)?;
|
||||
let rest = rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?;
|
||||
for word in rest.split_whitespace() {
|
||||
let opens = word.starts_with('(');
|
||||
if let Some((lo, hi)) = word.trim_start_matches('(').split_once("..") {
|
||||
let (lo, hi) = (lo.parse::<f64>().ok()?, hi.trim_end_matches([',', ';', ')', '}']).parse::<f64>().ok()?);
|
||||
return (lo.is_finite() && hi.is_finite() && lo <= hi).then_some(lo..=hi);
|
||||
}
|
||||
if opens {
|
||||
return None;
|
||||
}
|
||||
if word.ends_with([',', '}']) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
/// The choices parameter `key` of effect `id` is documented with (`key: "a"|"b"`, a note in
|
||||
/// parentheses allowed after a choice: `key: "a" (note)|"b"`); `None` when its documentation gives
|
||||
/// fewer than two.
|
||||
pub(crate) fn documented_choices(id: &str, key: &str) -> Option<Vec<&'static str>> {
|
||||
let doc = catalog_index().get(id)?.params;
|
||||
doc.match_indices(key).map(|(at, _)| at).filter(|at| starts_key(doc, *at)).find_map(|at| {
|
||||
let rest = doc.get(at + key.len()..)?;
|
||||
let mut rest = rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?;
|
||||
let mut choices = vec![];
|
||||
while let Some((choice, after)) = rest.strip_prefix('"').and_then(|r| r.split_once('"')) {
|
||||
choices.push(choice);
|
||||
let after = match after.strip_prefix(" (") {
|
||||
Some(note) => note.get(note.find(')')? + 1..)?,
|
||||
None => after,
|
||||
};
|
||||
match after.strip_prefix('|') {
|
||||
Some(next) => rest = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
(choices.len() >= 2).then_some(choices)
|
||||
})
|
||||
}
|
||||
|
||||
/// The range parameter `key` of effect `id` is documented with in `unit` (`key: unit lo..hi`).
|
||||
fn documented_range(id: &str, key: &str, unit: &str) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
let doc = catalog_index().get(id)?.params;
|
||||
let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' ');
|
||||
let starts = |at: usize| starts_key(doc, at);
|
||||
let rest = doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| {
|
||||
let rest = doc.get(at + key.len()..)?;
|
||||
rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?.strip_prefix(unit)?.strip_prefix(' ')
|
||||
@@ -71,6 +122,12 @@ fn documented_range(id: &str, key: &str, unit: &str) -> Option<std::ops::RangeIn
|
||||
(lo.is_finite() && hi.is_finite() && lo <= hi).then_some(lo..=hi)
|
||||
}
|
||||
|
||||
/// Can a parameter name start at byte `at` of parameter documentation `doc`: after `{`, a space or
|
||||
/// a comma?
|
||||
fn starts_key(doc: &str, at: usize) -> bool {
|
||||
doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| matches!(c, '{' | ' ' | ','))
|
||||
}
|
||||
|
||||
/// The distance parameters of effect `id` (none for unknown effects).
|
||||
fn lengths_of(id: &str) -> Lengths {
|
||||
let always = |always| Lengths { always, absolute: &[] };
|
||||
@@ -257,7 +314,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"{corners: [[x,y]×4] (new positions of the bounding-box corners TL, TR, BR, BL in unit box coordinates; identity [[0,0],[1,0],[1,1],[0,1]]; placed gradients move and scale from the object's bounds to its distorted bounds)}",
|
||||
json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}),
|
||||
),
|
||||
g("distort.puckerBloat", "Pucker & Bloat…", DT, "{amount: % (-200 pucker … 200 bloat, default 0)}", json!({"amount": 0.0})),
|
||||
g("distort.puckerBloat", "Pucker & Bloat…", DT, "{amount: % -200..200 (0; -200 puckers, 200 bloats)}", json!({"amount": 0.0})),
|
||||
g(
|
||||
"distort.roughen",
|
||||
"Roughen…",
|
||||
@@ -808,7 +865,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"adjust.temperatureTint",
|
||||
"Temperature/Tint…",
|
||||
ADJUST,
|
||||
"{temperature: -100 (cooler) .. 100 (warmer) (0), tint: -100 (greener) .. 100 (more magenta) (0)} recolours as Brightness/Contrast does",
|
||||
"{temperature: -100..100 (0; -100 cooler, 100 warmer), tint: -100..100 (0; -100 greener, 100 more magenta)} recolours as Brightness/Contrast does",
|
||||
json!({"temperature": 0.0, "tint": 0.0}),
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -462,6 +462,7 @@ fn builds_within(id: &str) -> bool {
|
||||
fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomContext, max: usize) -> PathData {
|
||||
use util::{join, num};
|
||||
if let Some(plugin) = vectorcraft_plugins::effect::plugin_id(id) {
|
||||
crate::params::check_returned_effects();
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item, at: ctx.stage };
|
||||
return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints, ctx.doc).unwrap_or_else(|| path.clone());
|
||||
}
|
||||
|
||||
@@ -350,7 +350,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod
|
||||
fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node {
|
||||
let mut m = src.clone();
|
||||
if let Some((path, rule)) = geometry(src) {
|
||||
let bounds = vectorcraft_geom::Shape::bounding_box(&path.to_bezpath());
|
||||
let bounds = path.bounds().unwrap_or_default();
|
||||
let (g, carry) =
|
||||
crate::apply_geometry_carrying(&n.appearance.effects, &path, bounds, &crate::GeomContext { doc, ..crate::GeomContext::of(n) });
|
||||
m.kind = NodeKind::Path { path: g, rule, live: None, clipping: false, guide: false };
|
||||
|
||||
@@ -1780,6 +1780,44 @@ fn perspective_projects_the_masks_in_a_symbols_art() {
|
||||
assert_eq!(mask, path, "and so is its mask");
|
||||
}
|
||||
|
||||
/// The images in the art of a symbol instance drawn through a projection have their corners where
|
||||
/// the projection takes them, beside a path, in a group and in the art of a linked mask, and an
|
||||
/// image's own linked mask is projected with it.
|
||||
#[test]
|
||||
fn a_projection_puts_the_corners_of_the_images_in_a_symbols_art_where_it_takes_them() {
|
||||
let masked = masked_by(white_square(22), image_node(23), true);
|
||||
let art = Node::group(NodeId(20), vec![Arc::new(image_node(21)), Arc::new(Node::group(NodeId(24), vec![Arc::new(masked)]))]);
|
||||
// An image with a linked mask of its own, whose path has a linked mask too.
|
||||
let inner = masked_by(white_square(32), white_square(33), true);
|
||||
let own = Node::group(NodeId(30), vec![Arc::new(masked_by(image_node(31), inner, true))]);
|
||||
let at = vectorcraft_doc::PerspectiveAttachment { projection: Some([1.0, 0.2, 3.0, 0.1, 1.0, 2.0, 0.01, 0.02, 1.0]), ..Default::default() };
|
||||
let h = at.homography().unwrap();
|
||||
let mut instance = Node::new(NodeId(2), NodeKind::SymbolInstance { symbol: "t".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
instance.extras_mut().perspective = Some(Box::new(at.clone()));
|
||||
let out = crate::reshape::reshape(None, &instance, Some(&own)).unwrap();
|
||||
let mut masks = vec![];
|
||||
out.walk(&mut |c| masks.extend(c.image_corners().and(c.extras().mask.as_deref()).map(|m| m.art.clone())));
|
||||
let [mask] = masks.as_slice() else { panic!("one masked image: {out:?}") };
|
||||
assert!(mask.path_data() != white_square(32).path_data(), "the image's mask is projected");
|
||||
let inner = mask.extras().mask.as_deref().map(|m| m.art.path_data().cloned());
|
||||
assert_eq!(inner, Some(mask.path_data().cloned()), "and so is the mask on that mask's path");
|
||||
let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
instance.extras_mut().perspective = Some(Box::new(at));
|
||||
let out = crate::reshape::reshape(None, &instance, Some(&art)).unwrap();
|
||||
let want = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(|(x, y)| h.apply(vectorcraft_geom::Point::new(x, y)).unwrap());
|
||||
let mut images = vec![];
|
||||
out.walk(&mut |c| {
|
||||
images.extend(c.image_corners());
|
||||
images.extend(c.extras().mask.as_deref().and_then(|m| m.art.image_corners()));
|
||||
});
|
||||
assert_eq!(images.len(), 2, "{out:?}");
|
||||
for q in images {
|
||||
for (got, want) in q.iter().zip(want) {
|
||||
assert!(got.distance(want) < 1e-9, "{q:?} against {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group with `effect` holding `n` vertical then `n` horizontal bars, 2 wide on a 4-unit
|
||||
/// pitch, each crossing every bar of the other direction: n² crossings.
|
||||
fn crossing_bars(n: usize, effect: &str) -> Node {
|
||||
|
||||
@@ -135,6 +135,6 @@ pub use geometry::{
|
||||
#[cfg(test)]
|
||||
pub(crate) use geometry::{MAX_EFFECT_LINES, apply_geometry_within};
|
||||
pub use params::{
|
||||
any_plugin_paints_output, default_params, has_geometry, has_painted_plugin_effect, has_plugin_effect, is_geometry, is_raster, merged_params,
|
||||
new_effect, plugin_revision, scale_effect, upgrade_params,
|
||||
any_plugin_paints_output, check_returned_effect, default_params, has_geometry, has_painted_plugin_effect, has_plugin_effect, is_geometry,
|
||||
is_raster, merged_params, new_effect, plugin_revision, scale_effect, upgrade_params,
|
||||
};
|
||||
|
||||
@@ -139,6 +139,201 @@ pub fn new_effect(id: &str, params: &Value) -> Option<Effect> {
|
||||
Some(Effect { id: id.to_string(), params, visible: true })
|
||||
}
|
||||
|
||||
/// Checks an effect record that a painted live-effect plug-in returns on a piece, or on one of its
|
||||
/// fills or strokes (`row`) ([`vectorcraft_plugins::painted::CheckEffect`]): a built-in effect other
|
||||
/// than a 3D or Pathfinder effect, a raster effect only on a fill or stroke, and parameters that effect takes. A
|
||||
/// parameter is one its defaults or its parameter documentation name, of the type its default has,
|
||||
/// within the range its documentation gives ([`crate::catalog::any_documented_range`]) and one of the
|
||||
/// choices it lists ([`crate::catalog::documented_choices`]); a texture is one as `effect.list`
|
||||
/// gives it, and an SVG filter's XML one drawable filter. A plug-in effect, the plug-in itself
|
||||
/// included, is refused, so the effects a plug-in returns never run a plug-in.
|
||||
pub fn check_returned_effect(e: &Effect, row: bool) -> Result<(), String> {
|
||||
if e.id.starts_with(vectorcraft_plugins::effect::PREFIX) {
|
||||
return Err("plug-in effects are not allowed in returned effects".into());
|
||||
}
|
||||
let Some(info) = catalog_index().get(e.id.as_str()) else {
|
||||
return Err(format!("unknown effect {:?}", e.id));
|
||||
};
|
||||
if is_three_d(&e.id) {
|
||||
return Err("3D effects are not allowed in returned effects".into());
|
||||
}
|
||||
if is_pathfinder(&e.id) {
|
||||
return Err("Pathfinder effects are not allowed in returned effects; a piece is one path, with nothing to combine".into());
|
||||
}
|
||||
if row && !is_raster(&e.id) {
|
||||
return Err(format!("{:?} is not a raster effect; a fill or stroke takes raster effects only", e.id));
|
||||
}
|
||||
let given = match &e.params {
|
||||
Value::Null => return Ok(()),
|
||||
Value::Object(m) => m,
|
||||
_ => return Err("`params` must be an object".into()),
|
||||
};
|
||||
let defaults = info.defaults.as_object();
|
||||
for (key, v) in given {
|
||||
let default = defaults.and_then(|d| d.get(key));
|
||||
if default.is_none() && !documents_key(info.params, key) {
|
||||
return Err(format!("`{key}` is not a parameter of {:?}", e.id));
|
||||
}
|
||||
let kind = |v: &Value| std::mem::discriminant(v);
|
||||
// A `color` is checked as a color, in any form the effect draws ([`is_color`]).
|
||||
let color = key == "color" && default.is_some_and(Value::is_string);
|
||||
// Curves' `points` is also taken as [[x, y], …], as the effect draws it.
|
||||
let curve = e.id == "adjust.curves" && key == "points" && v.is_array();
|
||||
if let Some(d) = default
|
||||
&& !d.is_null()
|
||||
&& !color
|
||||
&& !curve
|
||||
&& kind(d) != kind(v)
|
||||
{
|
||||
return Err(format!("`{key}` must be of the type its default {d} has"));
|
||||
}
|
||||
let range = crate::catalog::any_documented_range(&e.id, key);
|
||||
if let (Some(r), Some(x)) = (range, v.as_f64())
|
||||
&& !r.contains(&x)
|
||||
{
|
||||
return Err(format!("`{key}` must be from {} to {}", r.start(), r.end()));
|
||||
}
|
||||
if let Some(choices) = crate::catalog::documented_choices(&e.id, key)
|
||||
&& !v.as_str().is_some_and(|v| choices.contains(&v))
|
||||
{
|
||||
return Err(format!("`{key}` must be one of \"{}\"", choices.join("\", \"")));
|
||||
}
|
||||
}
|
||||
if let Some(t) = given.get(crate::pixel::TEXTURE_IMAGE)
|
||||
&& t.as_str().is_none_or(|t| crate::pixel::texture(t).is_none())
|
||||
{
|
||||
return Err("`textureImage` must be a texture as effect.list gives it".into());
|
||||
}
|
||||
check_returned_values(&e.id, given)
|
||||
}
|
||||
|
||||
/// The values in `given`, the parameters of built-in effect `id` that a painted live-effect plug-in
|
||||
/// returned, that are checked further: an SVG filter's XML, `scale`, `origin`, `axes` and
|
||||
/// `name`; a Free Distort's four `corners`; Curves' `points` as pairs from 0 to 255; a Transform's whole
|
||||
/// `copies` and `reference`; a Warp's `version`; a `color` the effect can draw; a
|
||||
/// shadow's or glow's blend `mode`; a Levels or Curves `channel`; a Radial
|
||||
/// Blur's center; and the type of each parameter without a default.
|
||||
fn check_returned_values(id: &str, given: &Map<String, Value>) -> Result<(), String> {
|
||||
let number = |key: &str| given.get(key).is_some_and(|v| !v.is_number());
|
||||
let switch = |key: &str| given.get(key).is_some_and(|v| !v.is_boolean());
|
||||
if id == crate::SVG_FILTER {
|
||||
if let Some(xml) = given.get("xml") {
|
||||
crate::svg_filter::check(xml.as_str().ok_or("`xml` must be a string")?)?;
|
||||
}
|
||||
if given.get("scale").is_some_and(|s| !s.as_f64().is_some_and(|k| (0.001..=1000.0).contains(&k))) {
|
||||
return Err("`scale` must be a number from 0.001 to 1000".into());
|
||||
}
|
||||
if given
|
||||
.get("origin")
|
||||
.is_some_and(|o| !o.as_array().is_some_and(|o| o.len() == 2 && o.iter().all(|v| v.as_f64().is_some_and(f64::is_finite))))
|
||||
{
|
||||
return Err("`origin` must be [x, y] in points".into());
|
||||
}
|
||||
if given.get("axes").is_some_and(|a| crate::svg_filter::valid_axes(a).is_none()) {
|
||||
return Err("`axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0".into());
|
||||
}
|
||||
if given.contains_key("name") && !given.contains_key("xml") {
|
||||
return Err("an SVG filter is named by its id: give `xml` with `name`".into());
|
||||
}
|
||||
}
|
||||
let pair = |p: &Value| p.as_array().is_some_and(|p| p.len() == 2 && p.iter().all(|v| v.as_f64().is_some_and(f64::is_finite)));
|
||||
if id == "distort.freeDistort" && given.get("corners").is_some_and(|c| !c.as_array().is_some_and(|c| c.len() == 4 && c.iter().all(pair))) {
|
||||
return Err("`corners` must be four [x, y] pairs of numbers".into());
|
||||
}
|
||||
if id == "adjust.curves" && given.get("points").is_some_and(|p| !is_curve_points(p)) {
|
||||
return Err("`points` must be \"x,y x,y …\" or [[x, y], …] pairs of numbers from 0 to 255".into());
|
||||
}
|
||||
if id == "distort.transform"
|
||||
&& let Some(key) = ["copies", "reference"].into_iter().find(|k| given.get(*k).and_then(Value::as_f64).is_some_and(|x| x.fract() != 0.0))
|
||||
{
|
||||
return Err(format!("`{key}` must be a whole number"));
|
||||
}
|
||||
if id.starts_with("warp.") && given.get("version").is_some_and(|v| crate::warp_version(v).is_none()) {
|
||||
return Err(format!("`version` must be 0 or {}", crate::WARP_NET));
|
||||
}
|
||||
let takes_color = catalog_index().get(id).is_some_and(|info| info.defaults.get("color").is_some_and(Value::is_string));
|
||||
if takes_color && given.get("color").is_some_and(|v| !is_color(v)) {
|
||||
return Err("`color` must be a #rrggbb color, [r, g, b] from 0 to 1 or a color object".into());
|
||||
}
|
||||
let takes_blend_mode = catalog_index().get(id).is_some_and(|info| info.params.contains("mode: blend mode"));
|
||||
if takes_blend_mode && given.get("mode").is_some_and(|v| v.as_str().and_then(crate::raster::named_blend_mode).is_none()) {
|
||||
return Err("`mode` must be a blend mode, such as \"multiply\" or \"screen\"".into());
|
||||
}
|
||||
if matches!(id, "adjust.levels" | "adjust.curves") && given.get("channel").is_some_and(|v| !v.as_str().is_some_and(crate::is_channel)) {
|
||||
return Err(format!("`channel` must be one of {}", crate::CHANNELS.join(", ")));
|
||||
}
|
||||
if id == "blur.radial" {
|
||||
for key in ["centerX", "centerY"] {
|
||||
if given.get(key).is_some_and(|v| !v.as_f64().is_some_and(|x| (0.0..=1.0).contains(&x))) {
|
||||
return Err(format!("`{key}` must be a number from 0 to 1"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let numbers: &[&str] = match id {
|
||||
"stylize.scribble" => &["variation"],
|
||||
"path.outlineStroke" => &["width"],
|
||||
_ => &[],
|
||||
};
|
||||
if let Some(key) = numbers.iter().find(|k| number(k)) {
|
||||
return Err(format!("`{key}` must be a number"));
|
||||
}
|
||||
if id == "blur.gaussian" && switch("linear") {
|
||||
return Err("`linear` must be true or false".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Can Curves read `v` as its `points`: `"x,y x,y …"` (pairs split by whitespace or `;`) or
|
||||
/// `[[x, y], …]`, each number from 0 to 255?
|
||||
fn is_curve_points(v: &Value) -> bool {
|
||||
let level = |x: f64| (0.0..=255.0).contains(&x);
|
||||
match v {
|
||||
Value::String(s) => s
|
||||
.split(|c: char| c.is_whitespace() || c == ';')
|
||||
.filter(|p| !p.is_empty())
|
||||
.all(|p| p.split_once(',').is_some_and(|(x, y)| [x, y].into_iter().all(|n| n.trim().parse::<f64>().is_ok_and(level)))),
|
||||
Value::Array(a) => a.iter().all(|p| p.as_array().is_some_and(|p| p.len() == 2 && p.iter().all(|n| n.as_f64().is_some_and(level)))),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Can an effect read `v` as its `color`: a hex color or name [`Color::from_hex`] reads, `[r, g, b]`
|
||||
/// with three numbers from 0 to 1 first, or a color object with its components from 0 to 1 (a Lab
|
||||
/// color's lightness from 0 to 100, and finite a and b)?
|
||||
///
|
||||
/// [`Color::from_hex`]: vectorcraft_doc::color::Color::from_hex
|
||||
fn is_color(v: &Value) -> bool {
|
||||
use vectorcraft_doc::color::Color;
|
||||
let unit = |x: f32| (0.0..=1.0).contains(&x);
|
||||
match v {
|
||||
Value::String(s) => Color::from_hex(s).is_some(),
|
||||
Value::Array(a) => a.len() >= 3 && a.iter().take(3).all(|c| c.as_f64().is_some_and(|c| (0.0..=1.0).contains(&c))),
|
||||
Value::Object(_) => match serde_json::from_value::<Color>(v.clone()) {
|
||||
Ok(Color::Rgb { r, g, b }) => [r, g, b].into_iter().all(unit),
|
||||
Ok(Color::Cmyk { c, m, y, k }) => [c, m, y, k].into_iter().all(unit),
|
||||
Ok(Color::Gray { k }) => unit(k),
|
||||
Ok(Color::Lab { l, a, b }) => (0.0..=100.0).contains(&l) && a.is_finite() && b.is_finite(),
|
||||
Err(_) => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Does parameter documentation `doc` (`{edgeWidth: pt 1..14 (2), …}`) name parameter `key`?
|
||||
fn documents_key(doc: &str, key: &str) -> bool {
|
||||
doc.match_indices(key).any(|(at, _)| {
|
||||
let before = doc.get(..at).and_then(|s| s.chars().last());
|
||||
let after = doc.get(at + key.len()..).unwrap_or_default();
|
||||
matches!(before, Some('{' | ' ' | ',' | '|')) && (after.starts_with(':') || after.starts_with('?'))
|
||||
})
|
||||
}
|
||||
|
||||
/// Makes [`check_returned_effect`] how this process checks the effect records painted live-effect
|
||||
/// plug-ins return ([`vectorcraft_plugins::painted::set_effect_check`]).
|
||||
pub(crate) fn check_returned_effects() {
|
||||
vectorcraft_plugins::painted::set_effect_check(check_returned_effect);
|
||||
}
|
||||
|
||||
/// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see
|
||||
/// [`EffectInfo::lengths`]), and its sizes in raster pixels ([`crate::raster_px_range`]), which
|
||||
/// keep their share of the object so. A distance left at its default is written out scaled; one
|
||||
|
||||
@@ -435,7 +435,7 @@ fn reshapes(n: &Node) -> bool {
|
||||
fn path_art(n: &Node) -> Option<Node> {
|
||||
let (path, rule) = leaf_geometry(n)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let g = apply_geometry_with(&n.appearance.effects, &path, path.to_bezpath().bounding_box(), &ctx);
|
||||
let g = apply_geometry_with(&n.appearance.effects, &path, path.bounds().unwrap_or_default(), &ctx);
|
||||
let piece = |geometry: PathData, items: Vec<AppearanceItem>| {
|
||||
let mut ap: Appearance = (*n.appearance).clone();
|
||||
ap.items = items;
|
||||
@@ -454,7 +454,7 @@ fn path_art(n: &Node) -> Option<Node> {
|
||||
if own.is_empty() || plain.iter().any(|i| paints(i)) {
|
||||
pieces.push(piece(g.clone(), plain.into_iter().cloned().collect()));
|
||||
}
|
||||
let bounds = g.to_bezpath().bounding_box();
|
||||
let bounds = g.bounds().unwrap_or_default();
|
||||
for item in own {
|
||||
let geometry = apply_geometry_with(item.effects(), &g, bounds, &ctx.item(item));
|
||||
pieces.push(piece(geometry, vec![item.clone()]));
|
||||
|
||||
@@ -365,8 +365,13 @@ impl Rasterize {
|
||||
|
||||
/// Parse a blend mode name (`"multiply"`, `"Screen"`, `"color-burn"`…).
|
||||
pub fn blend_mode(s: &str) -> BlendMode {
|
||||
named_blend_mode(s).unwrap_or(BlendMode::Normal)
|
||||
}
|
||||
|
||||
/// The blend mode `s` names as [`blend_mode`] reads it; `None` when it names none.
|
||||
pub(crate) fn named_blend_mode(s: &str) -> Option<BlendMode> {
|
||||
let key: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();
|
||||
BlendMode::ALL.iter().copied().find(|m| format!("{m:?}").to_ascii_lowercase() == key).unwrap_or(BlendMode::Normal)
|
||||
BlendMode::ALL.iter().copied().find(|m| format!("{m:?}").to_ascii_lowercase() == key)
|
||||
}
|
||||
|
||||
/// An effect's `color` parameter (`"#rrggbb"`, `[r, g, b]` 0..1 or a colour object).
|
||||
|
||||
+246
-43
@@ -20,7 +20,7 @@ use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak};
|
||||
|
||||
use vectorcraft_doc::live::Hooks;
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, ImageObject, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape, shapes};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes};
|
||||
|
||||
use crate::{Budget, GeomContext, OutlineHook, apply_one, is_geometry, merged_params};
|
||||
|
||||
@@ -659,7 +659,7 @@ fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRu
|
||||
for item in c.appearance.items.iter().filter(|i| crate::paints(i)) {
|
||||
let fx = item.effects();
|
||||
let shape = if crate::has_geometry(fx) && !g.elements().is_empty() {
|
||||
crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item))
|
||||
crate::apply_geometry_bez(fx, &g, vectorcraft_geom::path::anchored_curve_bounds(&g).unwrap_or_default(), &ctx.item(item))
|
||||
} else {
|
||||
g.clone()
|
||||
};
|
||||
@@ -1260,7 +1260,7 @@ fn as_art_opts(
|
||||
) -> Option<Node> {
|
||||
if let Some(t) = copied_raster_at(n) {
|
||||
let outlined = |s: &Node| as_art_opts(symbols, paint_doc, s, symbol_art, outline, nodes, apart);
|
||||
return copied_raster_art(paint_doc, n, t, apart, &outlined).map(|art| dressed_keeping_effects(art, n));
|
||||
return copied_raster_art(paint_doc, n, t, (apart, true), &outlined, None).map(|art| dressed_keeping_effects(art, n));
|
||||
}
|
||||
let fx = geometry_effects(n);
|
||||
let mut art = match &n.kind {
|
||||
@@ -1382,13 +1382,26 @@ fn dressed_keeping_effects(mut art: Node, n: &Node) -> Node {
|
||||
/// object of its own ([`copy_leaf`]). Type, an image or a symbol instance becomes its art through
|
||||
/// `outlined` ([`as_art_opts`]) before it is copied: type as its outlines, an image in its frame
|
||||
/// and an instance as its symbol's art, whose members take their own geometry effects first
|
||||
/// ([`crate::group::members_as_drawn`]). `None` when `outlined` gives no art.
|
||||
fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, outlined: &dyn Fn(&Node) -> Option<Node>) -> Option<Node> {
|
||||
/// ([`crate::group::members_as_drawn`]). With `items`, the pieces a path's fills and strokes make
|
||||
/// of it ([`transform_items`]) are made before it is copied; without, its fills and strokes keep
|
||||
/// their effects for their own stage. Given `check`, a budget and a flag, the art keeps to that
|
||||
/// budget in place of [`Budget::EFFECTS`], and the flag is set to `false` when an effect leaves a
|
||||
/// path with its shape or makes fewer copies than it asks for ([`reshape_leaves_checked`]); the
|
||||
/// art is then incomplete. `None` when `outlined` gives no art.
|
||||
fn copied_raster_art(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
t: usize,
|
||||
(apart, items): (bool, bool),
|
||||
outlined: &dyn Fn(&Node) -> Option<Node>,
|
||||
mut check: Option<(Budget, &mut bool)>,
|
||||
) -> Option<Node> {
|
||||
let budget = check.as_ref().map_or(Budget::EFFECTS, |(b, _)| *b);
|
||||
let (before, rest) = n.appearance.effects.split_at(t);
|
||||
let mut source = n.clone();
|
||||
source.appearance.effects = before.to_vec();
|
||||
let piece = match copied_raster_at(&source) {
|
||||
Some(at) => copied_raster_art(doc, &source, at, apart, outlined)?,
|
||||
Some(at) => copied_raster_art(doc, &source, at, (apart, items), outlined, check.as_mut().map(|(b, c)| (*b, &mut **c)))?,
|
||||
None if needs_outline(&source) => {
|
||||
let mut art = outlined(&source)?;
|
||||
if matches!(source.kind, NodeKind::SymbolInstance { .. }) && geometry_effects(&source).is_empty() {
|
||||
@@ -1404,11 +1417,15 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou
|
||||
None => {
|
||||
let mut art = one_piece(&source);
|
||||
let rows = has_copied_row_raster(&source);
|
||||
let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, (apart, rows), doc);
|
||||
let fx = geometry_effects(&source);
|
||||
let carry =
|
||||
reshape_leaves_checked(&mut art, &fx, &source.appearance.effects, budget, (apart, rows), doc, check.as_mut().map(|(_, c)| &mut **c));
|
||||
if apart {
|
||||
hoist_copies(&mut art);
|
||||
}
|
||||
transform_items(&mut art, doc);
|
||||
if items {
|
||||
transform_items(&mut art, doc);
|
||||
}
|
||||
let mut ran = source.appearance.effects.clone();
|
||||
if carry.skipped() {
|
||||
carry.hide_skipped(&mut ran);
|
||||
@@ -1425,8 +1442,13 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou
|
||||
// The raster effects follow the copies below; Scale Strokes & Effects scales the others.
|
||||
let mut scaling = copy_scaling(options);
|
||||
scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64));
|
||||
let max = Budget::EFFECTS.at_least(art_cost(&art));
|
||||
let max = budget.at_least(art_cost(&art));
|
||||
copy_art(&mut art, m, copies, scaling, max);
|
||||
if let Some((_, complete)) = check.as_mut()
|
||||
&& art.children().map_or(0, Vec::len) <= copies
|
||||
{
|
||||
**complete = false;
|
||||
}
|
||||
if let Some(children) = art.children_mut() {
|
||||
// The original is last, and each copy above it is mapped once more by `m`.
|
||||
let step = m.with_translation(vectorcraft_geom::Vec2::ZERO);
|
||||
@@ -1445,7 +1467,8 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou
|
||||
}
|
||||
}
|
||||
let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect();
|
||||
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), doc);
|
||||
let rows = has_copied_row_raster(n);
|
||||
let carry = reshape_leaves_checked(&mut art, &later, &n.appearance.effects, budget, (apart, rows), doc, check.map(|(_, c)| c));
|
||||
let mut ran = n.appearance.effects.clone();
|
||||
if carry.skipped() {
|
||||
carry.hide_skipped(&mut ran);
|
||||
@@ -1493,7 +1516,7 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option<Node>
|
||||
return None;
|
||||
}
|
||||
if let Some(t) = copied_raster_at(n) {
|
||||
return copied_raster_art(doc, n, t, false, &|_| None).map(|art| dressed_keeping_effects(art, n));
|
||||
return copied_raster_art(doc, n, t, (false, true), &|_| None, None).map(|art| dressed_keeping_effects(art, n));
|
||||
}
|
||||
if n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) {
|
||||
// One element: its pieces never knock each other out.
|
||||
@@ -1521,11 +1544,40 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option<Node>
|
||||
/// follow it. The type and live objects in the art of those masks are outlined and evaluated
|
||||
/// first ([`outlined_members`], with the symbols of `doc`).
|
||||
fn project_leaves(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) {
|
||||
project_art(art, h, doc, false);
|
||||
}
|
||||
|
||||
/// [`project_leaves`], the linked opacity mask of `art` itself included when `own`.
|
||||
fn project_art(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>, own: bool) {
|
||||
project_paths(art, h);
|
||||
each_linked_mask_mut(art, false, 0, &mut |m| {
|
||||
each_linked_mask_mut(art, own, 0, &mut |m| {
|
||||
*m = outlined_mask_art(doc, m);
|
||||
project_paths(m, h);
|
||||
project_image_masks(m, h, doc);
|
||||
});
|
||||
project_image_masks(art, h, doc);
|
||||
}
|
||||
|
||||
/// The art of the linked opacity masks of the images under `art` (`art` itself, and in groups and
|
||||
/// layers, as [`project_images`] reaches them) projected through `h` as [`project_leaves`]
|
||||
/// projects art, the linked mask of that art's own root included, so that each mask stays on the
|
||||
/// object it masks. Unlinked masks stay where they are.
|
||||
fn project_image_masks(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) {
|
||||
match &mut art.kind {
|
||||
NodeKind::Image(_) => {
|
||||
if let Some(m) = art.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|m| m.linked) {
|
||||
let a = Arc::make_mut(&mut m.art);
|
||||
*a = outlined_mask_art(doc, a);
|
||||
project_art(a, h, doc, true);
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
for c in children.iter_mut() {
|
||||
project_image_masks(Arc::make_mut(c), h, doc);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `art`, the art of an opacity mask, with type and live objects in it outlined and evaluated
|
||||
@@ -1561,6 +1613,27 @@ fn project_paths(art: &mut Node, h: &vectorcraft_geom::Homography) {
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
project_images(art, h);
|
||||
}
|
||||
|
||||
/// Place the corners of every image under `art` (in groups and layers, as [`for_each_leaf`] reaches
|
||||
/// paths) where the projective map `h` takes them, so that its pixels are drawn in perspective
|
||||
/// between them ([`Node::set_image_corners`]). An image with a corner that `h` sends past its
|
||||
/// horizon keeps its place, as the points of a path there do.
|
||||
fn project_images(n: &mut Node, h: &vectorcraft_geom::Homography) {
|
||||
match &mut n.kind {
|
||||
NodeKind::Image(_) => {
|
||||
if let Some([Some(a), Some(b), Some(c), Some(d)]) = n.image_corners().map(|q| q.map(|p| h.apply(p))) {
|
||||
let _ = n.set_image_corners([a, b, c, d]);
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
for c in children.iter_mut() {
|
||||
project_images(Arc::make_mut(c), h);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The visible geometry effects of `n`'s own effect list, in order.
|
||||
@@ -1625,12 +1698,27 @@ fn hoist_copies(art: &mut Node) {
|
||||
/// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked
|
||||
/// masks keeps its shape under that effect.
|
||||
fn reshape_leaves_apart(
|
||||
art: &mut Node,
|
||||
fx: &[&Effect],
|
||||
owner: &[Effect],
|
||||
budget: Budget,
|
||||
flags: (bool, bool),
|
||||
doc: Option<&Document>,
|
||||
) -> crate::Carry {
|
||||
reshape_leaves_checked(art, fx, owner, budget, flags, doc, None)
|
||||
}
|
||||
|
||||
/// [`reshape_leaves_apart`] that, given `complete`, stops at the first effect that leaves a path in
|
||||
/// the art with its shape or makes fewer copies than it asks for, past `budget` ([`Ran::kept`],
|
||||
/// [`Ran::short`]), and sets `complete` to `false`; the art is then partly reshaped.
|
||||
fn reshape_leaves_checked(
|
||||
art: &mut Node,
|
||||
fx: &[&Effect],
|
||||
owner: &[Effect],
|
||||
budget: Budget,
|
||||
(apart, rows): (bool, bool),
|
||||
doc: Option<&Document>,
|
||||
mut complete: Option<&mut bool>,
|
||||
) -> crate::Carry {
|
||||
let mut whole = crate::Carry::default();
|
||||
if fx.is_empty() {
|
||||
@@ -1668,11 +1756,18 @@ fn reshape_leaves_apart(
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
|
||||
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
|
||||
let step = Step { e, params: ¶ms, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held };
|
||||
let strict = complete.is_some();
|
||||
let step = Step { e, params: ¶ms, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held, strict };
|
||||
// Art with linked masks keeps its shape under an effect that a mask in it could not take
|
||||
// as the art it masks did, so no mask is left apart from its art.
|
||||
let before = masked.then(|| (art.clone(), used));
|
||||
let ran = step.run(art, max, &mut used, copy_whole, Some(&mut warped), false, 0);
|
||||
if (ran.kept || ran.short)
|
||||
&& let Some(complete) = complete.as_deref_mut()
|
||||
{
|
||||
*complete = false;
|
||||
return whole;
|
||||
}
|
||||
if (ran.masks || ran.short)
|
||||
&& let Some((was, cost)) = before
|
||||
{
|
||||
@@ -1704,7 +1799,8 @@ fn reshape_leaves_apart(
|
||||
/// swatches and patterns of painted pieces are looked up in, [`copies_whole`] of the art of
|
||||
/// each linked mask before the first effect, by the id of the object it masks, and whether one of
|
||||
/// the object's effects holds the raster effects in its art back from its Transform effects
|
||||
/// ([`follow_art`]).
|
||||
/// ([`follow_art`]), and whether a Transform effect that makes fewer copies of anything in the art
|
||||
/// than it asks for is reported ([`Ran::short`]) wherever it is (`strict`).
|
||||
struct Step<'a> {
|
||||
e: &'a Effect,
|
||||
params: &'a serde_json::Value,
|
||||
@@ -1716,6 +1812,7 @@ struct Step<'a> {
|
||||
doc: Option<&'a Document>,
|
||||
wholes: &'a HashMap<NodeId, bool>,
|
||||
held: bool,
|
||||
strict: bool,
|
||||
}
|
||||
|
||||
/// What [`Step::run`] did to a piece of art.
|
||||
@@ -1728,7 +1825,8 @@ struct Ran {
|
||||
/// took the effect, or could have ([`Step::reshape_masks`]).
|
||||
masks: bool,
|
||||
/// A Transform effect made fewer copies of a path, image or symbol instance than it asks for
|
||||
/// (past the budget or out of reach), where a linked mask could take a different number.
|
||||
/// (past the budget or out of reach), where a linked mask could take a different number, or
|
||||
/// anywhere in the art for a [`Step`] with `strict`.
|
||||
short: bool,
|
||||
/// How what paints the art as a whole follows the effect, when it does.
|
||||
whole: Option<crate::Carry>,
|
||||
@@ -1840,7 +1938,8 @@ impl Step<'_> {
|
||||
{
|
||||
if !own {
|
||||
*used = copy_art(art, m, copies, copy_scaling(options), max);
|
||||
return Ran { kept: false, took: true, masks: false, short: false, whole: None };
|
||||
let short = self.strict && art.children().is_some_and(|c| c.iter().filter(|c| !c.is_guide()).count() <= copies);
|
||||
return Ran { kept: false, took: true, masks: false, short, whole: None };
|
||||
}
|
||||
// A mask's art: its copies keep to what the rest of the art leaves of `max`, and the
|
||||
// linked mask of the art itself takes them too. That mask's art stays in `used`, as
|
||||
@@ -1861,7 +1960,7 @@ impl Step<'_> {
|
||||
if watch && !own {
|
||||
masked_ids(art, false, &mut covered);
|
||||
}
|
||||
let counts = |id: NodeId| watch && (own || covered.contains(&id));
|
||||
let counts = |id: NodeId| self.strict || (watch && (own || covered.contains(&id)));
|
||||
let mut short = false;
|
||||
let mut took = false;
|
||||
for_each_leaf(art, &mut |leaf| {
|
||||
@@ -1902,7 +2001,7 @@ impl Step<'_> {
|
||||
if options.objects {
|
||||
moved_ids.insert(leaf.id);
|
||||
}
|
||||
short |= counts(leaf.id) && copied(leaf) <= copies;
|
||||
short |= copies > 0 && counts(leaf.id) && copied(leaf) <= copies;
|
||||
} else {
|
||||
kept_ids.insert(leaf.id);
|
||||
}
|
||||
@@ -2517,7 +2616,8 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling
|
||||
/// path or compound path, as one of its object's effects with reference box `bounds`: `leaf`
|
||||
/// becomes a group with its id and name of one object for each piece returned, in order, each with
|
||||
/// the piece's geometry and the leaf's appearance with the piece's fills and strokes in place of
|
||||
/// its own ([`vectorcraft_plugins::painted::appearance`]). The swatches and patterns the pieces
|
||||
/// its own ([`vectorcraft_plugins::painted::appearance`]), and the piece's opacity, blending mode
|
||||
/// and effects ([`dress_piece`]). The swatches and patterns the pieces
|
||||
/// name must be in `doc`, and without one the pieces may name none. Returns what the pieces cost
|
||||
/// ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails, the pieces are
|
||||
/// refused, or they would pass `budget`. A deferred run is listed by `at`.
|
||||
@@ -2531,28 +2631,112 @@ fn paint_leaf(
|
||||
at: Option<vectorcraft_plugins::deferred::Stage>,
|
||||
) -> Option<Budget> {
|
||||
let (path, rule) = leaf_geometry(leaf)?;
|
||||
crate::params::check_returned_effects();
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: None, at };
|
||||
let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?;
|
||||
let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
|
||||
let mut made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
|
||||
if !budget.fits(made) {
|
||||
return None;
|
||||
}
|
||||
let children = pieces
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let mut one = leaf.clone();
|
||||
one.name = None;
|
||||
one.appearance = vectorcraft_plugins::painted::appearance(&leaf.appearance, p).into();
|
||||
set_geometry(&mut one, p.path.clone(), p.rule);
|
||||
Arc::new(one)
|
||||
})
|
||||
.collect();
|
||||
let mut children = Vec::with_capacity(pieces.len());
|
||||
for p in pieces.iter() {
|
||||
let mut one = leaf.clone();
|
||||
one.name = None;
|
||||
one.appearance = vectorcraft_plugins::painted::appearance(&leaf.appearance, p).into();
|
||||
set_geometry(&mut one, p.path.clone(), p.rule);
|
||||
// The pieces' own geometry effects keep to what the pieces before them leave of the budget.
|
||||
made = made.plus(dress_piece(&mut one, &p.look, budget.minus(made), doc)?);
|
||||
children.push(Arc::new(one));
|
||||
}
|
||||
let mut g = Node::group(leaf.id, children);
|
||||
g.name = leaf.name.clone();
|
||||
*leaf = g;
|
||||
Some(made)
|
||||
}
|
||||
|
||||
/// Gives `one`, the object a painted piece becomes, the piece's `look`: its opacity times the
|
||||
/// object's, its blending mode, and its effects after the object's own. The visible geometry effects
|
||||
/// among them, and only those, reshape the piece at once ([`reshape_leaves_checked`], with `doc`), so they run
|
||||
/// before the source's later effects and the effects of its fills and strokes stay for their own
|
||||
/// stage; the object becomes a group with its id around the reshaped piece, carrying its
|
||||
/// transparency and effects. The piece's raster effects stay on it and draw on it, except that when
|
||||
/// they are listed before a Transform effect that makes copies ([`copied_raster_at`]), each copy
|
||||
/// carries its own, moved, turned, reflected and scaled with it ([`copied_raster_art`]). When the object
|
||||
/// has a blending mode other than Normal and the piece gives one, the same one included, the object
|
||||
/// becomes a group with its blending mode around the piece, so both apply. Returns what the reshaped piece costs
|
||||
/// past its own path; `None` when its geometry effects would cost more than `room` past it: they stop at the first
|
||||
/// effect that does not fit, and `one` is then incomplete.
|
||||
pub(crate) fn dress_piece(one: &mut Node, look: &vectorcraft_plugins::painted::Look, room: Budget, doc: Option<&Document>) -> Option<Budget> {
|
||||
use vectorcraft_doc::color::BlendMode;
|
||||
let none = Budget { anchors: 0, lines: 0 };
|
||||
if look.is_empty() {
|
||||
return Some(none);
|
||||
}
|
||||
let outer = look.blend.filter(|_| one.blend != BlendMode::Normal).map(|_| one.blend);
|
||||
if let Some(o) = look.opacity {
|
||||
one.opacity *= o;
|
||||
}
|
||||
if let Some(b) = look.blend {
|
||||
one.blend = b;
|
||||
}
|
||||
// A Transform effect that makes copies, with raster effects listed before it: each copy is an
|
||||
// object of its own carrying those raster effects, as an object's copies are
|
||||
// ([`copied_raster_art`]). The object's own effects paint around all of them, then the piece's
|
||||
// from the Transform effect on.
|
||||
let mut probe = one.clone();
|
||||
probe.appearance.effects = look.effects.clone();
|
||||
let mut extra = none;
|
||||
if let Some(t) = copied_raster_at(&probe) {
|
||||
let before = art_cost(one);
|
||||
let mut complete = true;
|
||||
let art = copied_raster_art(doc, &probe, t, (false, false), &|_| None, Some((room.plus(before), &mut complete)))?;
|
||||
#[cfg(test)]
|
||||
DRESSED.with(|d| d.set(d.get().plus(art_cost(&art))));
|
||||
extra = art_cost(&art).minus(before);
|
||||
if !complete || !room.fits(extra) {
|
||||
return None;
|
||||
}
|
||||
let mut effects = std::mem::take(&mut one.appearance.effects);
|
||||
effects.extend(art.appearance.effects.iter().cloned());
|
||||
let mut art = dressed(art, one);
|
||||
art.appearance.effects = effects;
|
||||
*one = art;
|
||||
} else {
|
||||
let shape: Vec<Effect> = look.effects.iter().filter(|e| e.visible && is_geometry(&e.id)).cloned().collect();
|
||||
// The raster effects before a Transform effect follow it, as an object's do once its
|
||||
// geometry effects are applied ([`crate::raster::without_geometry`]); hidden records stay
|
||||
// as they are.
|
||||
one.appearance.effects.extend(crate::raster::followed(&look.effects).iter().filter(|e| !(e.visible && is_geometry(&e.id))).cloned());
|
||||
if !shape.is_empty() {
|
||||
let before = art_cost(one);
|
||||
let mut art = one_piece(one);
|
||||
let mut complete = true;
|
||||
reshape_leaves_checked(&mut art, &shape.iter().collect::<Vec<_>>(), &shape, room.plus(before), (false, false), doc, Some(&mut complete));
|
||||
#[cfg(test)]
|
||||
DRESSED.with(|d| d.set(d.get().plus(art_cost(&art))));
|
||||
extra = art_cost(&art).minus(before);
|
||||
if !complete || !room.fits(extra) {
|
||||
return None;
|
||||
}
|
||||
let mut art = dressed(art, one);
|
||||
art.appearance.effects = one.appearance.effects.clone();
|
||||
*one = art;
|
||||
}
|
||||
}
|
||||
if let Some(blend) = outer {
|
||||
let mut g = Node::group(one.id, vec![Arc::new(one.clone())]);
|
||||
g.blend = blend;
|
||||
*one = g;
|
||||
}
|
||||
Some(extra)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// What the art [`dress_piece`] has reshaped on this thread has cost, all together.
|
||||
pub(crate) static DRESSED: std::cell::Cell<Budget> = const { std::cell::Cell::new(Budget { anchors: 0, lines: 0 }) };
|
||||
}
|
||||
|
||||
/// What a painted piece with geometry `path` costs: its anchors and lines, plus a share of the
|
||||
/// effects' budget for the object it becomes, so that a budget of [`Budget::EFFECTS`] holds at most
|
||||
/// [`MAX_OBJECTS`](vectorcraft_plugins::objects::MAX_OBJECTS) pieces however small their paths.
|
||||
@@ -2572,7 +2756,8 @@ fn piece_share() -> Budget {
|
||||
/// order. The plug-in is given `appearance`'s fills and strokes and told that it is on item `index`
|
||||
/// of them. A piece that gives fills (on a fill) or strokes (on a stroke) is painted by copies of
|
||||
/// `item` with those paints ([`vectorcraft_plugins::painted::items`]), under the leaf's other fills
|
||||
/// and strokes; one that gives none keeps the leaf's. Returns
|
||||
/// and strokes; one that gives none keeps the leaf's. Each path takes its piece's opacity, blending
|
||||
/// mode and effects ([`dress_piece`]). Returns
|
||||
/// what the paths cost ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails,
|
||||
/// the pieces are refused (a swatch or pattern not in `doc`, or any without one), or they would pass
|
||||
/// `budget`. A deferred run is listed by `at`.
|
||||
@@ -2588,9 +2773,10 @@ fn paint_piece(
|
||||
at: Option<vectorcraft_plugins::deferred::Stage>,
|
||||
) -> Option<Budget> {
|
||||
let (path, rule) = leaf_geometry(leaf)?;
|
||||
crate::params::check_returned_effects();
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(appearance), item: Some(index), at };
|
||||
let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?;
|
||||
let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
|
||||
let mut made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
|
||||
if !budget.fits(made) {
|
||||
return None;
|
||||
}
|
||||
@@ -2613,6 +2799,7 @@ fn paint_piece(
|
||||
let mut one = leaf.clone();
|
||||
one.appearance.items = items;
|
||||
set_geometry(&mut one, p.path.clone(), p.rule);
|
||||
made = made.plus(dress_piece(&mut one, &p.look, budget.minus(made), doc)?);
|
||||
children.push(Arc::new(one));
|
||||
}
|
||||
*leaf = Node::group(leaf.id, children);
|
||||
@@ -2691,7 +2878,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
let Some((path, rule)) = leaf_geometry(leaf) else { return };
|
||||
let original = leaf.clone();
|
||||
let ctx = GeomContext::of(&original);
|
||||
let bounds = path.to_bezpath().bounding_box();
|
||||
let bounds = path.bounds().unwrap_or_default();
|
||||
// A path of the leaf's geometry painted by `items` alone, without the leaf's transparency and
|
||||
// object effects (the group keeps them).
|
||||
let piece = |items: Vec<AppearanceItem>| {
|
||||
@@ -2766,18 +2953,34 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
let it = one.items.pop().unwrap_or(it);
|
||||
let stage = vectorcraft_plugins::deferred::Stage { object: ctx.seed, effect: at, item: Some(i) };
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&original.appearance), item: Some(i), at: Some(stage) };
|
||||
crate::params::check_returned_effects();
|
||||
let painted = vectorcraft_plugins::effect::apply_painted(plugin, ¶ms, &g, tb, rule, paints, doc)
|
||||
.map(|pieces| pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p))).collect::<Vec<_>>())
|
||||
.map(|pieces| {
|
||||
pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p), p.look.clone())).collect::<Vec<_>>()
|
||||
})
|
||||
.filter(|pieces| room.fits(pieces.iter().map(|(p, ..)| piece_cost(p)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus)));
|
||||
// A failed run draws the fill or stroke on the geometry it was given.
|
||||
let returned = painted.unwrap_or_else(|| vec![(g.clone(), rule, vec![it])]);
|
||||
let mut group: Vec<Arc<Node>> = vec![];
|
||||
for (path, rule, items) in returned.into_iter().filter(|(_, _, items)| !items.is_empty()) {
|
||||
*used = used.plus(piece_cost(&path));
|
||||
let mut p = piece(items);
|
||||
set_geometry(&mut p, path, rule);
|
||||
group.push(Arc::new(p));
|
||||
}
|
||||
// The paths the pieces become, with their own geometry effects applied, and what they
|
||||
// cost; `None` as soon as a piece's own geometry effects would pass `room`.
|
||||
let build = |returned: Vec<(PathData, FillRule, Vec<AppearanceItem>, vectorcraft_plugins::painted::Look)>| {
|
||||
let returned: Vec<_> = returned.into_iter().filter(|(_, _, items, _)| !items.is_empty()).collect();
|
||||
let mut made = returned.iter().map(|(path, ..)| piece_cost(path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
|
||||
let mut group: Vec<Arc<Node>> = vec![];
|
||||
for (path, rule, items, look) in returned {
|
||||
let mut p = piece(items);
|
||||
set_geometry(&mut p, path, rule);
|
||||
made = made.plus(dress_piece(&mut p, &look, room.minus(made), doc)?);
|
||||
group.push(Arc::new(p));
|
||||
}
|
||||
Some((group, made))
|
||||
};
|
||||
// A failed run, or pieces whose own geometry effects would pass the budget, draws the
|
||||
// fill or stroke on the geometry it was given, at that geometry's own cost.
|
||||
let (group, made) = painted.and_then(build).unwrap_or_else(|| {
|
||||
let mut p = piece(vec![it]);
|
||||
set_geometry(&mut p, g.clone(), rule);
|
||||
(vec![Arc::new(p)], piece_cost(&g))
|
||||
});
|
||||
*used = used.plus(made);
|
||||
let mut p = Node::group(leaf.id, group);
|
||||
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), true, limit, used, doc);
|
||||
pieces.push(Arc::new(p));
|
||||
|
||||
+324
-25
@@ -1180,8 +1180,11 @@ impl Placed {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most pairs of faces [`local_order`] compares, and the most [`cut_stroke_faces`] compares;
|
||||
/// the pairs they have not reached by then keep the order of their depths.
|
||||
/// The most pairs of faces [`local_order`] compares, together with the steps it takes to break
|
||||
/// rings of them ([`drawn_in_pairs_order`]), and the most pairs [`cut_stroke_faces`] compares. A
|
||||
/// pair not compared by then adds no constraint on the order (the pairs that were compared can
|
||||
/// still move its faces), and once the steps run out the first face left by depth goes next only
|
||||
/// when no face can.
|
||||
const MAX_LOCAL_CHECKS: usize = 4_000_000;
|
||||
|
||||
/// The polygon of `f` and the sign of its turns, when `f` is a face turned toward the viewer other
|
||||
@@ -1412,11 +1415,11 @@ fn half(p: &[Point], values: &[f64], sign: f64) -> Vec<Point> {
|
||||
/// their depths where they overlap: the face nearer the viewer there goes after the other. A fill
|
||||
/// wall and a face of the same shape's covering stroke ([`Paints::Stroke`]) keep their order. Each
|
||||
/// face otherwise keeps its place in `order`, so a fill wall in the gap between two dashes stays
|
||||
/// where its depth puts it. A cycle of such pairs is broken at the face that comes first in `order`.
|
||||
/// where its depth puts it. A cycle of such pairs is broken at one of its own faces
|
||||
/// ([`drawn_in_pairs_order`]).
|
||||
/// A face drawn last (a planar end turned toward the viewer, at depth `f64::MAX`) keeps its place:
|
||||
/// no face moves across it. Otherwise `order` as it is.
|
||||
fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
use std::cmp::Reverse;
|
||||
// The faces of each shape that take part, from left to right for a sweep along x.
|
||||
let mut shapes: Vec<Vec<usize>> = vec![];
|
||||
for (k, f) in faces.iter().enumerate() {
|
||||
@@ -1428,7 +1431,7 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
}
|
||||
shapes[f.member].push(k);
|
||||
}
|
||||
if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) {
|
||||
if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) || u32::try_from(faces.len()).is_err() {
|
||||
return order;
|
||||
}
|
||||
for list in &mut shapes {
|
||||
@@ -1471,9 +1474,9 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
// faces with a polygon and a plane that overlap goes in the order of their depths there.
|
||||
let mut sweep: Vec<usize> = (0..faces.len()).filter(|&k| faces[k].outline.len() >= 3 && faces[k].plane.is_some()).collect();
|
||||
sweep.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0));
|
||||
// For each face, the faces drawn after it, and for each, how many go before it.
|
||||
let mut after: Vec<Vec<usize>> = vec![vec![]; faces.len()];
|
||||
let mut waits = vec![0usize; faces.len()];
|
||||
// Each pair in its order: a face, and a face drawn after it (as `u32`: there are fewer faces
|
||||
// than that, which is checked above).
|
||||
let mut pairs: Vec<(u32, u32)> = vec![];
|
||||
'pairs: for (i, &k) in sweep.iter().enumerate() {
|
||||
let a = &faces[k];
|
||||
for &j in sweep.iter().skip(i + 1).take_while(|&&j| faces[j].bounds.x0 < a.bounds.x1) {
|
||||
@@ -1491,38 +1494,117 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
let Some(a_nearer) = nearer_where_overlapping(a, b) else { continue };
|
||||
a_nearer
|
||||
};
|
||||
let (back, front) = if a_later { (j, k) } else { (k, j) };
|
||||
after[back].push(front);
|
||||
waits[front] += 1;
|
||||
pairs.push(if a_later { (j as u32, k as u32) } else { (k as u32, j as u32) });
|
||||
}
|
||||
}
|
||||
// Each step draws the face that comes first in `order` of those whose faces before are drawn.
|
||||
// Breaking rings has what is left of the limit.
|
||||
let last: Vec<bool> = faces.iter().map(|f| f.depth >= f64::MAX).collect();
|
||||
let mut room = MAX_LOCAL_CHECKS.saturating_sub(checks);
|
||||
drawn_in_pairs_order(order, &position, &last, pairs, &mut room)
|
||||
}
|
||||
|
||||
/// `order` with each face after the faces that go before it: each of `pairs` is a face and a face
|
||||
/// drawn after it, `position` is each face's place in `order`, and `last` says of each face
|
||||
/// whether it is drawn last. Each step draws the face that comes first in `order` of those whose
|
||||
/// faces before are drawn. A face drawn last goes only after every face before it in `order`, so
|
||||
/// a face before it never waits for it or for a face after it: those pairs, with the face drawn
|
||||
/// last itself or with a face that follows it, are drawn the wrong way round.
|
||||
///
|
||||
/// When no face can go next, some of the faces left go before each other in a ring, or wait for a
|
||||
/// face drawn last or one that follows it. The faces that go before the first face left in `order`
|
||||
/// are followed back, among the faces that come before the next face drawn last, to the first
|
||||
/// group found that waits for no other of them ([`RingFinder::behind`]): a ring, or one face. That
|
||||
/// group gives up its face that comes first in `order`. So when the first face left is in the
|
||||
/// group, it goes next, as it would with no ring looked for; when it only waits for the group, a
|
||||
/// face of the group goes instead, and the only other pairs drawn the wrong way round are pairs of
|
||||
/// a ring.
|
||||
///
|
||||
/// Every face and pair looked at takes one from `room`. The search is kept from one stop to the
|
||||
/// next and goes on from where it stopped, and a face that is drawn is dropped from a list the
|
||||
/// next time the list is looked at, so rings of a few faces take a few steps a face whether they
|
||||
/// stand apart, all lie behind one face or lie one behind the other. Two costs are not in
|
||||
/// proportion to the faces. A ring that is still a ring after it gives up a face is walked again
|
||||
/// from the face the search reached it by, so a large ring can cost about its pairs for each face
|
||||
/// it gives up: the square of its faces, even when each waits for few others (3,200 faces with
|
||||
/// four pairs each at random take about 3,000,000 steps). And a face at or
|
||||
/// after the next face drawn last is passed over again each time a face that waits for it is
|
||||
/// looked at. Once `room` runs out the first face left in `order` goes next, ring or not.
|
||||
/// A first face left that waits only for the next face drawn last or faces after it goes next
|
||||
/// with no search, at no cost.
|
||||
///
|
||||
/// An `order` and `position` that do not agree, or a pair of a face that is not in them, give
|
||||
/// `order` back.
|
||||
///
|
||||
/// The pairs come at 8 bytes each and are dropped once the lists of the faces after each face
|
||||
/// are made, 4 bytes a pair; the lists of the faces before each face, as many again, are made
|
||||
/// when a ring is first looked for, a step a pair not taken from `room`, and only when the room
|
||||
/// left is at least a quarter of the pairs: with less, no ring is looked for and the first face
|
||||
/// left goes next. So a solid whose comparing of pairs leaves less than a quarter of its pairs
|
||||
/// of the limit breaks its rings as before rings were looked for.
|
||||
fn drawn_in_pairs_order(order: Vec<usize>, position: &[usize], last: &[bool], pairs: Vec<(u32, u32)>, room: &mut usize) -> Vec<usize> {
|
||||
use std::cmp::Reverse;
|
||||
let n = order.len();
|
||||
// `order` holds each face once when each face's place in it is the place `position` gives.
|
||||
let agree = position.len() == n && last.len() == n && order.iter().enumerate().all(|(at, &k)| position.get(k) == Some(&at));
|
||||
if !agree || u32::try_from(pairs.len()).is_err() || pairs.iter().any(|&(back, front)| back as usize >= n || front as usize >= n) {
|
||||
return order;
|
||||
}
|
||||
// For each face, how many faces not drawn yet go before it, and the faces drawn after it.
|
||||
let mut waits = vec![0usize; n];
|
||||
for &(_, front) in &pairs {
|
||||
waits[front as usize] += 1;
|
||||
}
|
||||
let after = Lists::from_pairs(n, pairs.iter().map(|&(back, front)| (back as usize, front as usize)));
|
||||
drop(pairs);
|
||||
let mut ready: std::collections::BinaryHeap<Reverse<(usize, usize)>> =
|
||||
(0..faces.len()).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect();
|
||||
(0..n).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect();
|
||||
// The faces drawn last, in `order`: each goes only after every face before it in `order`.
|
||||
let last: Vec<usize> = order.iter().copied().filter(|&k| faces[k].depth >= f64::MAX).collect();
|
||||
let lasts: Vec<usize> = order.iter().copied().filter(|&k| last[k]).collect();
|
||||
let mut next_last = 0usize;
|
||||
let mut drawn = vec![false; faces.len()];
|
||||
let mut out = Vec::with_capacity(order.len());
|
||||
let mut drawn = vec![false; n];
|
||||
let mut out = Vec::with_capacity(n);
|
||||
let mut first = 0usize;
|
||||
while out.len() < order.len() {
|
||||
while last.get(next_last).is_some_and(|&k| drawn[k]) {
|
||||
let mut rings: Option<RingFinder> = None;
|
||||
// For each face, how many faces not drawn yet go before it among the first `counted` of
|
||||
// `order`, which keeps up with the next face drawn last.
|
||||
let mut early = vec![0u32; n];
|
||||
let mut counted = 0usize;
|
||||
while out.len() < n {
|
||||
while lasts.get(next_last).is_some_and(|&k| drawn[k]) {
|
||||
next_last += 1;
|
||||
}
|
||||
let limit = last.get(next_last).map_or(usize::MAX, |&k| position[k]);
|
||||
let limit = lasts.get(next_last).map_or(usize::MAX, |&k| position[k]);
|
||||
while counted < limit.min(n) {
|
||||
if let Some(&back) = order.get(counted).filter(|&&back| !drawn[back]) {
|
||||
for &j in after.list(back) {
|
||||
early[j as usize] += 1;
|
||||
}
|
||||
}
|
||||
counted += 1;
|
||||
}
|
||||
let k = match ready.peek() {
|
||||
Some(&Reverse((at, k))) if at < limit => {
|
||||
ready.pop();
|
||||
k
|
||||
}
|
||||
_ => {
|
||||
// A cycle, or the faces left to draw before a face drawn last wait for faces after
|
||||
// it: the first face in `order` not drawn yet goes next.
|
||||
while order.get(first).is_some_and(|&k| drawn[k]) {
|
||||
first += 1;
|
||||
}
|
||||
let Some(&k) = order.get(first) else { break };
|
||||
k
|
||||
let Some(&next) = order.get(first) else { break };
|
||||
// The face drawn last goes in its turn, and so does a face that waits only for it or
|
||||
// faces after it: no face it waits for can go first. Any other face waits for a
|
||||
// face before the face drawn last: the group behind it gives up a face, while there
|
||||
// is room to look for one. The lists of the faces before each face take a step a
|
||||
// pair to make, which is not taken from `room`: they are made only when the room
|
||||
// left is at least a quarter of the pairs, so making them costs no more than four
|
||||
// times the room left.
|
||||
let mut released = None;
|
||||
let room_for_lists = rings.is_some() || room.saturating_mul(4) >= after.faces.len();
|
||||
if *room > 0 && position[next] < limit && early[next] > 0 && room_for_lists {
|
||||
released = rings.get_or_insert_with(|| RingFinder::new(&after)).behind(next, &drawn, position, limit, room);
|
||||
}
|
||||
released.unwrap_or(next)
|
||||
}
|
||||
};
|
||||
if drawn[k] {
|
||||
@@ -1530,8 +1612,13 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
}
|
||||
drawn[k] = true;
|
||||
out.push(k);
|
||||
for &j in &after[k] {
|
||||
let was_counted = position[k] < counted;
|
||||
for &j in after.list(k) {
|
||||
let j = j as usize;
|
||||
waits[j] = waits[j].saturating_sub(1);
|
||||
if was_counted {
|
||||
early[j] = early[j].saturating_sub(1);
|
||||
}
|
||||
if waits[j] == 0 && !drawn[j] {
|
||||
ready.push(Reverse((position[j], j)));
|
||||
}
|
||||
@@ -1540,6 +1627,217 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
out
|
||||
}
|
||||
|
||||
/// A list of faces for each of some faces, all in one array: the faces after each face, or the
|
||||
/// faces before it.
|
||||
struct Lists {
|
||||
/// The list of face `k` is `faces[starts[k]..starts[k + 1]]`.
|
||||
starts: Vec<u32>,
|
||||
faces: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Lists {
|
||||
/// For each of `n` faces, the second faces of the `pairs` it is first in, in the order of
|
||||
/// `pairs`. There are fewer than 2^32 faces and pairs ([`drawn_in_pairs_order`] checks this);
|
||||
/// a pair with a face that is not one of the `n` is left out.
|
||||
fn from_pairs(n: usize, pairs: impl Iterator<Item = (usize, usize)> + Clone) -> Self {
|
||||
let pairs = pairs.filter(move |&(first, second)| first < n && second < n);
|
||||
let mut starts = vec![0u32; n + 1];
|
||||
for (first, _) in pairs.clone() {
|
||||
if let Some(count) = starts.get_mut(first + 1) {
|
||||
*count += 1;
|
||||
}
|
||||
}
|
||||
for k in 1..starts.len() {
|
||||
starts[k] += starts[k - 1];
|
||||
}
|
||||
let mut filled = starts.clone();
|
||||
let mut faces = vec![0u32; starts.last().map_or(0, |&end| end as usize)];
|
||||
for (first, second) in pairs {
|
||||
if let Some(at) = filled.get_mut(first) {
|
||||
if let Some(slot) = faces.get_mut(*at as usize) {
|
||||
*slot = second as u32;
|
||||
}
|
||||
*at += 1;
|
||||
}
|
||||
}
|
||||
Lists { starts, faces }
|
||||
}
|
||||
|
||||
/// The list of face `k`; none for a face that is not one of them.
|
||||
fn list(&self, k: usize) -> &[u32] {
|
||||
let (Some(&start), Some(&end)) = (self.starts.get(k), self.starts.get(k + 1)) else { return &[] };
|
||||
self.faces.get(start as usize..end as usize).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Each list's faces and the face it is the list of, as pairs.
|
||||
fn pairs(&self) -> impl Iterator<Item = (usize, usize)> + Clone + '_ {
|
||||
(0..self.starts.len().saturating_sub(1)).flat_map(move |k| self.list(k).iter().map(move |&j| (k, j as usize)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The entries of the lists of faces before each face that [`RingFinder`] has read, counted
|
||||
/// where they are read, for tests to hold the reading to the room.
|
||||
pub(super) static LIST_ENTRIES_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// No place among the faces reached, in [`RingFinder`].
|
||||
const NONE: usize = usize::MAX;
|
||||
|
||||
/// Finds the ring behind a face for [`drawn_in_pairs_order`], and keeps its search from one stop to
|
||||
/// the next.
|
||||
///
|
||||
/// Every index it holds is in range: the faces of its lists are faces of the pairs
|
||||
/// [`drawn_in_pairs_order`] checked against the number of faces, which is the length of the
|
||||
/// `drawn` and `position` it is given, and the places it keeps are places in its own lists.
|
||||
struct RingFinder {
|
||||
/// For each face, the faces that go before it, lowest first.
|
||||
before: Lists,
|
||||
/// For each face, where its list in `before` now ends: the faces found drawn are dropped
|
||||
/// from it, and those left moved up.
|
||||
ends: Vec<u32>,
|
||||
/// For each face, its place in `reached`; [`NONE`] for a face not reached.
|
||||
marks: Vec<usize>,
|
||||
/// The faces reached, in the order reached. Every one is in a group not completed yet.
|
||||
reached: Vec<usize>,
|
||||
/// For each face reached, the earliest place in `reached` it leads back to.
|
||||
low: Vec<usize>,
|
||||
/// The path from the first face reached to the one being looked at.
|
||||
path: Vec<Step>,
|
||||
/// The `limit` the faces reached were reached under; `None` with none reached yet.
|
||||
limit: Option<usize>,
|
||||
}
|
||||
|
||||
/// A face on the path of [`RingFinder`]: its place in `reached`, and the entry of its list being
|
||||
/// looked at.
|
||||
struct Step {
|
||||
place: usize,
|
||||
entry: usize,
|
||||
}
|
||||
|
||||
impl RingFinder {
|
||||
/// A finder for the faces of `after`, the faces drawn after each face.
|
||||
fn new(after: &Lists) -> Self {
|
||||
let n = after.starts.len() - 1;
|
||||
let before = Lists::from_pairs(n, after.pairs().map(|(back, front)| (front, back)));
|
||||
let ends = before.starts.get(1..).unwrap_or_default().to_vec();
|
||||
RingFinder { before, ends, marks: vec![NONE; n], reached: vec![], low: vec![], path: vec![], limit: None }
|
||||
}
|
||||
|
||||
/// The face to draw next when `start`, the first face not `drawn`, whose `position` is before
|
||||
/// `limit`, waits for a face. Of the faces that are not drawn and come before `limit`, those
|
||||
/// that go before `start` are followed back to the first group found whose faces wait for no
|
||||
/// other such face: a ring of faces that go before each other, or one face. The answer is the
|
||||
/// face of that group with the lowest `position`. Every face and every pair looked at takes
|
||||
/// one from `room`; `None` when it runs out.
|
||||
///
|
||||
/// The faces are followed depth first, each face's faces before it lowest first, and the first
|
||||
/// strongly connected component completed is the group (Tarjan's algorithm, stopped there):
|
||||
/// it leads to no other component. The search is kept, less that group, and the next call
|
||||
/// goes on with it: the faces drawn since are the group's own and faces that waited for
|
||||
/// nothing else, and none of those is in a group with a face still on the path, so what the
|
||||
/// search knows of the faces left still holds. It starts afresh when `limit` moves, which
|
||||
/// brings in faces it passed over.
|
||||
fn behind(&mut self, start: usize, drawn: &[bool], position: &[usize], limit: usize, room: &mut usize) -> Option<usize> {
|
||||
if self.limit != Some(limit) {
|
||||
self.forget(0);
|
||||
self.limit = Some(limit);
|
||||
}
|
||||
// The end of the path may be drawn: faces that only waited for the last group.
|
||||
while let Some(place) = self.path.last().map(|step| step.place).filter(|&place| drawn[self.reached[place]]) {
|
||||
self.forget(place);
|
||||
}
|
||||
if self.reached.first() != Some(&start) {
|
||||
self.forget(0);
|
||||
if !self.reach(start, drawn, room) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
while let Some(step) = self.path.last_mut() {
|
||||
if *room == 0 {
|
||||
return None;
|
||||
}
|
||||
*room -= 1;
|
||||
let place = step.place;
|
||||
let face = self.reached[place];
|
||||
if step.entry < self.ends[face] as usize {
|
||||
let earlier = self.before.faces[step.entry] as usize;
|
||||
if drawn[earlier] || position[earlier] >= limit {
|
||||
step.entry += 1;
|
||||
} else if self.marks[earlier] != NONE {
|
||||
self.low[place] = self.low[place].min(self.marks[earlier]);
|
||||
step.entry += 1;
|
||||
} else {
|
||||
// The entry is passed once the faces behind it are looked at.
|
||||
if !self.reach(earlier, drawn, room) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Every face before this one is looked at: it ends a group when it leads no further
|
||||
// back than itself.
|
||||
let leads = self.low[place];
|
||||
if leads == place {
|
||||
let found = self.reached[place..].iter().copied().min_by_key(|&face| position[face]);
|
||||
// The face before it on the path keeps its entry for this one, to look at what is
|
||||
// left of the group next time.
|
||||
self.forget(place);
|
||||
return found;
|
||||
}
|
||||
self.path.pop();
|
||||
if let Some(parent) = self.path.last_mut() {
|
||||
self.low[parent.place] = self.low[parent.place].min(leads);
|
||||
parent.entry += 1;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Adds `face` to the faces reached and to the end of the path, at the start of its list, with
|
||||
/// the faces now `drawn` dropped from the list: a step from `room` for each face the list held,
|
||||
/// taken before the list is read. `false`, with `room` emptied and nothing read, when the list
|
||||
/// is longer than the room left.
|
||||
fn reach(&mut self, face: usize, drawn: &[bool], room: &mut usize) -> bool {
|
||||
let (start, end) = (self.before.starts[face] as usize, self.ends[face] as usize);
|
||||
let Some(left) = room.checked_sub(end - start) else {
|
||||
*room = 0;
|
||||
return false;
|
||||
};
|
||||
*room = left;
|
||||
let mut kept = start;
|
||||
for entry in start..end {
|
||||
let earlier = self.before.faces[entry];
|
||||
#[cfg(test)]
|
||||
LIST_ENTRIES_READ.with(|read| read.set(read.get() + 1));
|
||||
if !drawn[earlier as usize] {
|
||||
self.before.faces[kept] = earlier;
|
||||
kept += 1;
|
||||
}
|
||||
}
|
||||
// `kept` is no more than the end it replaces.
|
||||
self.ends[face] = kept as u32;
|
||||
let place = self.reached.len();
|
||||
self.marks[face] = place;
|
||||
self.path.push(Step { place, entry: start });
|
||||
self.low.push(place);
|
||||
self.reached.push(face);
|
||||
true
|
||||
}
|
||||
|
||||
/// Takes out the faces reached from `place` on, and their part of the path.
|
||||
fn forget(&mut self, place: usize) {
|
||||
for face in self.reached.drain(place.min(self.reached.len())..) {
|
||||
self.marks[face] = NONE;
|
||||
}
|
||||
self.low.truncate(place);
|
||||
while self.path.last().is_some_and(|step| step.place >= place) {
|
||||
self.path.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether face `a` is nearer the viewer than face `b` where their polygons overlap on the drawing,
|
||||
/// measured at the middle of the overlap. `None` when they do not overlap, when either polygon is
|
||||
/// not convex, or when they are at the same depth there.
|
||||
@@ -1673,7 +1971,8 @@ fn draw_order(faces: &[Placed], sealed: bool) -> Vec<usize> {
|
||||
/// of overlapping faces with a convex polygon and a plane goes in the order of its depths there,
|
||||
/// the face nearer the viewer after the other ([`local_order`]), and each step draws the face that
|
||||
/// comes first in the given order of those whose faces before are drawn, so a face without a plane
|
||||
/// or a convex polygon can also move. Otherwise the order given.
|
||||
/// or a convex polygon can also move. Faces that lie in front of one another in a ring give up one
|
||||
/// of the ring's own faces ([`drawn_in_pairs_order`]). Otherwise the order given.
|
||||
pub(crate) fn surface_order<'a>(faces: impl IntoIterator<Item = (&'a [Point], Option<DepthPlane>, f64)>) -> Vec<usize> {
|
||||
let placed: Vec<Placed> = faces
|
||||
.into_iter()
|
||||
|
||||
@@ -933,10 +933,10 @@ fn local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cycle of overlapping stroke faces is broken at the face that comes first by depth, and a cap
|
||||
/// drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; 2 at
|
||||
/// x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 nearer
|
||||
/// than 0. 3 is the cap.
|
||||
/// A cycle of overlapping stroke faces is broken at its own face that comes first by depth, and a
|
||||
/// cap drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8;
|
||||
/// 2 at x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2
|
||||
/// nearer than 0. 3 is the cap.
|
||||
#[test]
|
||||
fn a_depth_cycle_keeps_the_cap_last() {
|
||||
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
|
||||
@@ -964,6 +964,450 @@ fn a_depth_cycle_keeps_the_cap_last() {
|
||||
assert_eq!(draw_order(&faces, true), [0, 2, 1, 3]);
|
||||
}
|
||||
|
||||
/// A face that lies in front of a face of a cycle, without being part of the cycle, waits for that
|
||||
/// face. 0, 1 and 2 overlap in a cycle (as in `a_depth_cycle_keeps_the_cap_last`); 3, at x 16 to
|
||||
/// 26 and flat at z 2, is nearer than 2 where they overlap, but its center is the farthest of all,
|
||||
/// so it comes first by depth. The cycle is broken at 0, its first face by depth, and 3 follows 2.
|
||||
/// Breaking it at the first face by depth of all the faces left drew 3 first, under 2.
|
||||
#[test]
|
||||
fn a_face_in_front_of_a_cycle_waits_for_it() {
|
||||
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
|
||||
let at = |depth: f64, x: f64, normal: [f64; 3], offset: f64| Placed {
|
||||
depth,
|
||||
side: true,
|
||||
away: false,
|
||||
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
|
||||
member: 0,
|
||||
paints: Paints::Other,
|
||||
outline: square(x),
|
||||
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
|
||||
};
|
||||
let flat = [0.0, 0.0, 1.0];
|
||||
let walls = || [at(1.0, 0.0, flat, 0.0), at(2.0, 4.0, [-1.0, 0.0, 1.0], -8.0), at(3.0, 8.0, flat, 1.0), at(-5.0, 16.0, flat, 2.0)];
|
||||
assert_eq!(draw_order(&walls(), true), [0, 2, 3, 1]);
|
||||
// With the cap of `a_depth_cycle_keeps_the_cap_last` as well, it still goes last.
|
||||
let cap =
|
||||
Placed { depth: f64::MAX, side: false, bounds: Rect::new(0.0, 0.0, 26.0, 10.0), outline: vec![], plane: None, ..at(0.0, 0.0, flat, 0.0) };
|
||||
let capped: Vec<Placed> = walls().into_iter().chain([cap]).collect();
|
||||
assert_eq!(draw_order(&capped, true), [0, 2, 3, 1, 4]);
|
||||
}
|
||||
|
||||
/// `order` with the pairs `before` (each first face drawn before the second) in their own order
|
||||
/// ([`drawn_in_pairs_order`]), within `room` steps of looking for rings, and the steps taken; the
|
||||
/// faces of `last` are drawn last.
|
||||
fn in_pairs_order(order: &[usize], before: &[(usize, usize)], last: &[usize], room: usize) -> (Vec<usize>, usize) {
|
||||
let n = order.len();
|
||||
let mut position = vec![0; n];
|
||||
for (at, &k) in order.iter().enumerate() {
|
||||
position[k] = at;
|
||||
}
|
||||
let last: Vec<bool> = (0..n).map(|k| last.contains(&k)).collect();
|
||||
let mut left = room;
|
||||
let drawn = drawn_in_pairs_order(order.to_vec(), &position, &last, narrow(before), &mut left);
|
||||
(drawn, room - left)
|
||||
}
|
||||
|
||||
/// What [`drawn_in_pairs_order`] is to give with room enough, worked out plainly: at every stop
|
||||
/// the faces behind the first face left are followed afresh, with nothing kept and no face taken
|
||||
/// out of a list.
|
||||
fn in_pairs_order_plainly(order: &[usize], before: &[(usize, usize)], last: &[usize]) -> Vec<usize> {
|
||||
/// The first group completed behind `face`, among the faces `open`: its faces, or `None` while
|
||||
/// its group goes on. `earlier` lists the faces before each face, lowest first.
|
||||
fn group(face: usize, open: &[bool], earlier: &[Vec<usize>], reached: &mut Vec<usize>, low: &mut Vec<usize>) -> Option<Vec<usize>> {
|
||||
let place = reached.len();
|
||||
reached.push(face);
|
||||
low.push(place);
|
||||
for &e in earlier[face].iter().filter(|&&e| open[e]) {
|
||||
match reached.iter().position(|&f| f == e) {
|
||||
Some(at) => low[place] = low[place].min(at),
|
||||
None => {
|
||||
let found = group(e, open, earlier, reached, low);
|
||||
if found.is_some() {
|
||||
return found;
|
||||
}
|
||||
low[place] = low[place].min(low[reached.iter().position(|&f| f == e).unwrap()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
(low[place] == place).then(|| reached[place..].to_vec())
|
||||
}
|
||||
let n = order.len();
|
||||
let mut at = vec![0; n];
|
||||
for (place, &k) in order.iter().enumerate() {
|
||||
at[k] = place;
|
||||
}
|
||||
let mut earlier = vec![vec![]; n];
|
||||
for &(first, then) in before {
|
||||
earlier[then].push(first);
|
||||
}
|
||||
earlier.iter_mut().for_each(|list| list.sort_unstable());
|
||||
let mut drawn = vec![false; n];
|
||||
let mut out: Vec<usize> = vec![];
|
||||
while out.len() < n {
|
||||
let left: Vec<usize> = order.iter().copied().filter(|&k| !drawn[k]).collect();
|
||||
let limit = left.iter().find(|k| last.contains(k)).map_or(usize::MAX, |&k| at[k]);
|
||||
let waits = |k: usize| earlier[k].iter().any(|&e| !drawn[e]);
|
||||
let next = match left.iter().copied().find(|&k| at[k] < limit && !waits(k)) {
|
||||
Some(ready) => ready,
|
||||
None if at[left[0]] >= limit => left[0],
|
||||
None => {
|
||||
let open: Vec<bool> = (0..n).map(|k| !drawn[k] && at[k] < limit).collect();
|
||||
let found = group(left[0], &open, &earlier, &mut vec![], &mut vec![]).unwrap();
|
||||
found.into_iter().min_by_key(|&k| at[k]).unwrap()
|
||||
}
|
||||
};
|
||||
drawn[next] = true;
|
||||
out.push(next);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `pairs` as [`drawn_in_pairs_order`] takes them.
|
||||
fn narrow(pairs: &[(usize, usize)]) -> Vec<(u32, u32)> {
|
||||
pairs.iter().map(|&(first, then)| (first as u32, then as u32)).collect()
|
||||
}
|
||||
|
||||
/// The pairs of `before` that `drawn` draws the wrong way round.
|
||||
fn broken(drawn: &[usize], before: &[(usize, usize)]) -> Vec<(usize, usize)> {
|
||||
let mut at = vec![0; drawn.len()];
|
||||
for (place, &k) in drawn.iter().enumerate() {
|
||||
at[k] = place;
|
||||
}
|
||||
before.iter().copied().filter(|&(first, then)| at[first] > at[then]).collect()
|
||||
}
|
||||
|
||||
/// After a ring's face is released, the faces left are looked at afresh: they may be a smaller
|
||||
/// ring and faces in none. Two rings share face 1: 0 before 1 before 4 before 0, and 1 before 2
|
||||
/// before 3 before 1. By depth the order is 3, 2, 0, 4, 1. The five wait for no other face, so the
|
||||
/// first stop releases 3, the first of them by depth. That leaves the one ring 0, 1, 4 and face
|
||||
/// 2, which only waits for 1: 0 is released, and 2 follows 1. Only pairs of a ring are drawn the
|
||||
/// wrong way round. Taking the first face left by depth at each stop drew 2 before 1 as well.
|
||||
#[test]
|
||||
fn the_faces_left_are_looked_at_afresh_after_each_face_released() {
|
||||
let before = [(0, 1), (1, 4), (4, 0), (1, 2), (2, 3), (3, 1)];
|
||||
let (drawn, _) = in_pairs_order(&[3, 2, 0, 4, 1], &before, &[], usize::MAX);
|
||||
assert_eq!(drawn, [3, 0, 1, 2, 4]);
|
||||
assert_eq!(broken(&drawn, &before), [(4, 0), (2, 3)]);
|
||||
assert_eq!(broken(&in_pairs_order(&[3, 2, 0, 4, 1], &before, &[], 0).0, &before), [(4, 0), (1, 2), (2, 3)]);
|
||||
}
|
||||
|
||||
/// A ring is the one behind the first face left by depth that waits for no face outside it: 0
|
||||
/// comes first by depth and waits for the ring 1, 2, 3, which waits for the ring 4, 5, 6. The far
|
||||
/// ring is broken first (at 4) and drawn, then the near one (at 1), and 0 follows 1; one pair of
|
||||
/// each ring is drawn the wrong way round, and no pair between them. Taking the first face left by
|
||||
/// depth drew 0 first, under 1.
|
||||
#[test]
|
||||
fn the_ring_released_waits_for_no_face_outside_it() {
|
||||
let before = [(1, 0), (1, 2), (2, 3), (3, 1), (4, 1), (4, 5), (5, 6), (6, 4)];
|
||||
let (drawn, _) = in_pairs_order(&[0, 1, 2, 3, 4, 5, 6], &before, &[], usize::MAX);
|
||||
assert_eq!(drawn, [4, 5, 6, 1, 0, 2, 3]);
|
||||
assert_eq!(broken(&drawn, &before), [(3, 1), (6, 4)]);
|
||||
assert_eq!(broken(&in_pairs_order(&[0, 1, 2, 3, 4, 5, 6], &before, &[], 0).0, &before), [(1, 0), (3, 1), (4, 1), (6, 4)]);
|
||||
}
|
||||
|
||||
/// A ring is looked for among the faces that come before the next face drawn last: 1 comes first
|
||||
/// by depth and waits for 4, a face of the ring 2, 3, 4, and for 0, which is drawn last. 0 waits
|
||||
/// for no face, so it is a group of its own behind 1, but no face before it by depth can wait for
|
||||
/// it. The ring gives up 2, and 1 follows 4; the pair of 1 and 0 cannot be kept. Stopping at 0
|
||||
/// drew 1 first, under 4.
|
||||
#[test]
|
||||
fn a_ring_is_looked_for_before_the_next_face_drawn_last() {
|
||||
let before = [(2, 3), (3, 4), (4, 2), (4, 1), (0, 1)];
|
||||
let (drawn, _) = in_pairs_order(&[1, 2, 3, 4, 0], &before, &[0], usize::MAX);
|
||||
assert_eq!(drawn, [2, 3, 4, 1, 0]);
|
||||
assert_eq!(broken(&drawn, &before), [(4, 2), (0, 1)]);
|
||||
assert_eq!(broken(&in_pairs_order(&[1, 2, 3, 4, 0], &before, &[0], 0).0, &before), [(4, 2), (4, 1), (0, 1)]);
|
||||
// A face that waits only for a face after the one drawn last goes before the faces that wait
|
||||
// for it: 0 waits for 1, 1 for 3, and 2 is drawn last.
|
||||
let before = [(1, 0), (3, 1)];
|
||||
assert_eq!(in_pairs_order(&[0, 1, 2, 3], &before, &[2], usize::MAX).0, [1, 0, 2, 3]);
|
||||
assert_eq!(in_pairs_order(&[0, 1, 2, 3], &before, &[2], 0).0, [0, 1, 2, 3]);
|
||||
}
|
||||
|
||||
/// Looking for rings is counted, and past the room given the first face not drawn yet goes next,
|
||||
/// as before rings were looked for: the pairs of `a_face_in_front_of_a_cycle_waits_for_it`. A
|
||||
/// face drawn last keeps every face before it by depth before it, ring or not. An order and
|
||||
/// places in it that do not agree (an order that is not each face once), or a pair of a face that
|
||||
/// is not in them, give the order back.
|
||||
#[test]
|
||||
fn breaking_rings_stops_at_its_room() {
|
||||
let before = [(1, 0), (0, 2), (2, 1), (2, 3)];
|
||||
let order = [3, 0, 1, 2];
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(drawn, [0, 2, 3, 1]);
|
||||
// The faces and pairs behind 3.
|
||||
assert!((4..=16).contains(&steps), "{steps} steps");
|
||||
assert_eq!(in_pairs_order(&order, &before, &[], steps), (vec![0, 2, 3, 1], steps));
|
||||
for room in [0, 1, steps - 1] {
|
||||
let (drawn, taken) = in_pairs_order(&order, &before, &[], room);
|
||||
assert_eq!(drawn, [3, 0, 2, 1], "{room}");
|
||||
assert!(taken <= room, "{room}");
|
||||
}
|
||||
// 0 is drawn last: 3, before it by depth, goes before it, and the ring's other faces after.
|
||||
assert_eq!(in_pairs_order(&order, &before, &[0], usize::MAX).0, [3, 0, 2, 1]);
|
||||
// 2 is drawn last: every other face is before it by depth, so 3 and 1, which wait only for
|
||||
// it, go when they come first of the faces behind the first face left, and 0 follows 1.
|
||||
assert_eq!(in_pairs_order(&order, &before, &[2], usize::MAX).0, [3, 1, 0, 2]);
|
||||
assert_eq!(in_pairs_order(&order, &before, &[2], 0).0, [3, 0, 1, 2]);
|
||||
let mut room = usize::MAX;
|
||||
let position = [1, 2, 3, 0];
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 3], narrow(&before), &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 4], vec![(9, 0)], &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 4], vec![(0, 4)], &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(order[..3].to_vec(), &position, &[false; 4], narrow(&before), &mut room), order[..3]);
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &position[..3], &[false; 4], narrow(&before), &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &[1, 2, 0, 3], &[false; 4], narrow(&before), &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(vec![0, 0, 1, 2], &[0, 2, 3, 0], &[false; 4], narrow(&before), &mut room), [0, 0, 1, 2]);
|
||||
assert_eq!(drawn_in_pairs_order(vec![0, 1, 2, 4], &[0, 1, 2, 3], &[false; 4], narrow(&before), &mut room), [0, 1, 2, 4]);
|
||||
assert_eq!(room, usize::MAX);
|
||||
}
|
||||
|
||||
/// A first face left that waits only for the face drawn last goes next with no search: 1,000
|
||||
/// such faces before a ring cost nothing, and the ring behind them still has its room. Each face
|
||||
/// i < 1,000 waits for 1,004, which is drawn last; 1,000 to 1,003 are the pairs of
|
||||
/// `breaking_rings_stops_at_its_room`, where 1,003 comes first by depth and waits for the ring.
|
||||
#[test]
|
||||
fn a_face_that_waits_only_for_the_face_drawn_last_costs_no_search() {
|
||||
let waiting = 1000usize;
|
||||
let (r, last) = (waiting, waiting + 4);
|
||||
let mut before: Vec<(usize, usize)> = (0..waiting).map(|f| (last, f)).collect();
|
||||
before.extend([(r + 1, r), (r, r + 2), (r + 2, r + 1), (r + 2, r + 3)]);
|
||||
let order: Vec<usize> = (0..waiting).chain([r + 3, r, r + 1, r + 2, last]).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[last], usize::MAX);
|
||||
let expected: Vec<usize> = (0..waiting).chain([r, r + 2, r + 3, r + 1, last]).collect();
|
||||
assert_eq!(drawn, expected);
|
||||
assert!(steps < 20, "{steps} steps");
|
||||
// The room the ring takes is enough, whatever waits before it.
|
||||
assert_eq!(in_pairs_order(&order, &before, &[last], before.len().div_ceil(4).max(steps)).0, expected);
|
||||
}
|
||||
|
||||
/// The lists of the faces before each face are made only when the room left is at least a
|
||||
/// quarter of the pairs: with less, no ring is looked for, however few steps the ring would take.
|
||||
/// A ring of three behind 3,000 faces in a chain (each before the next).
|
||||
#[test]
|
||||
fn the_lists_for_rings_are_made_only_with_room_for_a_quarter_of_the_pairs() {
|
||||
let chain = 3000usize;
|
||||
let r = chain;
|
||||
let mut before: Vec<(usize, usize)> = (0..chain - 1).map(|f| (f, f + 1)).collect();
|
||||
before.extend([(r + 1, r), (r, r + 2), (r + 2, r + 1), (r + 2, r + 3)]);
|
||||
// As in `breaking_rings_stops_at_its_room`: 3 comes first by depth of the four and waits for
|
||||
// the ring.
|
||||
let order: Vec<usize> = (0..chain).chain([r + 3, r, r + 1, r + 2]).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(drawn[chain..], [r, r + 2, r + 3, r + 1]);
|
||||
assert!(steps < 20, "{steps} steps");
|
||||
let quarter = before.len().div_ceil(4);
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], quarter - 1);
|
||||
assert_eq!(drawn[chain..], [r + 3, r, r + 2, r + 1]);
|
||||
assert_eq!(steps, 0);
|
||||
assert_eq!(in_pairs_order(&order, &before, &[], quarter).0[chain..], [r, r + 2, r + 3, r + 1]);
|
||||
}
|
||||
|
||||
/// A list of the faces before a face is read only when the room left holds it: with less, no
|
||||
/// entry of it is read, and the first face left goes next. Face 0 comes first by depth and waits
|
||||
/// for 1, which waits for 2,000 faces after it in `order`, each waiting for 1: a ring of 1 with
|
||||
/// each of them.
|
||||
#[test]
|
||||
fn a_list_longer_than_the_room_left_is_not_read() {
|
||||
let wide = 2000usize;
|
||||
let mut before = vec![(1, 0)];
|
||||
before.extend((2..2 + wide).flat_map(|f| [(f, 1), (1, f)]));
|
||||
let order: Vec<usize> = (0..2 + wide).collect();
|
||||
// Room for the lists (a quarter of the pairs) but not for 1's list, and room for it.
|
||||
// With too little room only 0's one-entry list is read; with room for both, 1's list as well.
|
||||
for (room, want) in [(before.len().div_ceil(4), 1), (wide - 1, 1), (wide + 3, wide + 1)] {
|
||||
super::LIST_ENTRIES_READ.with(|read| read.set(0));
|
||||
let (drawn, taken) = in_pairs_order(&order, &before, &[], room);
|
||||
let read = super::LIST_ENTRIES_READ.with(|read| read.get());
|
||||
assert_eq!(read, want, "room {room}: {read} entries read, {taken} steps");
|
||||
assert!(read <= taken && taken <= room, "room {room}: {read} entries read, {taken} steps");
|
||||
assert_eq!(drawn.len(), order.len());
|
||||
}
|
||||
}
|
||||
|
||||
/// The steps of breaking rings are counted, not timed, and for rings of a few faces they are a
|
||||
/// few a face however the rings lie: apart, each with a face in front of it that comes first by
|
||||
/// depth; all behind one face, itself in a ring whose other faces come first in its list; and one
|
||||
/// behind the other. The search goes on from where it stopped, and a face drawn is dropped from
|
||||
/// a list the next time the list is looked at. A ring that is still a ring after it gives up a
|
||||
/// face is walked again, so a large ring can take about its pairs for each face it gives up, the
|
||||
/// square of its faces even when each waits for few others. With too little room the rings not
|
||||
/// reached are broken at the first face left by depth, as before.
|
||||
#[test]
|
||||
fn breaking_rings_takes_a_few_steps_a_face_but_for_a_ring_of_many_pairs() {
|
||||
// Ring r: faces 4r, 4r + 1 and 4r + 2 in a ring, and 4r + 3 after 4r + 2.
|
||||
let rings = 2000usize;
|
||||
let mut before = vec![];
|
||||
for r in 0..rings {
|
||||
let f = 4 * r;
|
||||
before.extend([(f + 1, f), (f, f + 2), (f + 2, f + 1), (f + 2, f + 3)]);
|
||||
}
|
||||
// By depth: every fourth face first, then the rings.
|
||||
let order: Vec<usize> = (0..rings).map(|r| 4 * r + 3).chain((0..rings).flat_map(|r| [4 * r, 4 * r + 1, 4 * r + 2])).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(broken(&drawn, &before), (0..rings).map(|r| (4 * r + 1, 4 * r)).collect::<Vec<_>>());
|
||||
assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings apart");
|
||||
// With no room the fourth faces go first, under the faces they are in front of.
|
||||
assert_eq!(broken(&in_pairs_order(&order, &before, &[], 0).0, &before).len(), 2 * rings);
|
||||
|
||||
// Face 0, first by depth, is in a ring with 1 and 2, which come first in its list, and after a
|
||||
// face of each ring r: faces 3r + 3, 3r + 4 and 3r + 5.
|
||||
let rings = 3000usize;
|
||||
let mut before = vec![(1, 0), (0, 2), (2, 1)];
|
||||
for r in 0..rings {
|
||||
let f = 3 * r + 3;
|
||||
before.extend([(f, f + 1), (f + 1, f + 2), (f + 2, f), (f, 0)]);
|
||||
}
|
||||
let order: Vec<usize> = (0..3 * rings + 3).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
// One pair of each ring, face 0's among them, and no pair of face 0 with another ring's face.
|
||||
assert_eq!(broken(&drawn, &before), [(1, 0)].into_iter().chain((0..rings).map(|r| (3 * r + 5, 3 * r + 3))).collect::<Vec<_>>());
|
||||
assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings behind one face");
|
||||
// The same with a face drawn last that every ring's first face waits for: it is passed over
|
||||
// each time, and nothing after it in a list is looked at twice for that.
|
||||
let cap = 3 * rings + 3;
|
||||
let capped: Vec<(usize, usize)> = (0..rings).map(|r| (cap, 3 * r + 3)).chain(before.iter().copied()).collect();
|
||||
let order: Vec<usize> = (0..=cap).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &capped, &[cap], usize::MAX);
|
||||
assert_eq!(broken(&drawn, &capped).len(), 2 * rings + 1);
|
||||
assert!(steps <= 5 * order.len(), "{steps} steps for {rings} rings behind one face, before a face drawn last");
|
||||
|
||||
// Ring r: faces 3r, 3r + 1 and 3r + 2, the first after the last face of ring r + 1.
|
||||
let rings = 3000usize;
|
||||
let mut before = vec![];
|
||||
for r in 0..rings {
|
||||
let f = 3 * r;
|
||||
before.extend([(f, f + 1), (f + 1, f + 2), (f + 2, f)]);
|
||||
if r + 1 < rings {
|
||||
before.push((f + 5, f));
|
||||
}
|
||||
}
|
||||
let order: Vec<usize> = (0..3 * rings).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
// One pair of each ring, and no pair between rings.
|
||||
assert_eq!(broken(&drawn, &before).len(), rings);
|
||||
assert!(broken(&drawn, &before).iter().all(|&(first, then)| first / 3 == then / 3));
|
||||
assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings one behind the other");
|
||||
let (short, taken) = in_pairs_order(&order, &before, &[], steps / 2);
|
||||
assert!(broken(&short, &before).len() > rings && taken <= steps / 2, "{} pairs, {taken} steps", broken(&short, &before).len());
|
||||
assert_eq!(short.len(), order.len());
|
||||
|
||||
// One ring: each of 200 faces before the next 99.
|
||||
let faces = 200usize;
|
||||
let before: Vec<(usize, usize)> = (0..faces).flat_map(|f| (1..100).map(move |d| (f, (f + d) % faces))).collect();
|
||||
let order: Vec<usize> = (0..faces).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(drawn, order);
|
||||
// Each face it gives up walks the ring again, so it takes many times its pairs (the cost the
|
||||
// docs name), but no more than about its pairs for each face.
|
||||
assert!(steps < 2 * faces * before.len(), "{steps} steps for a ring of {} pairs", before.len());
|
||||
|
||||
// Pairs at random, about four a face: one large ring and faces around it.
|
||||
let steps_of = |faces: usize| {
|
||||
let mut next = numbers(faces as u64);
|
||||
let before: Vec<(usize, usize)> = (0..2 * faces)
|
||||
.map(|_| ((next() * faces as f64) as usize, (next() * faces as f64) as usize))
|
||||
.filter(|(first, then)| first != then)
|
||||
.collect();
|
||||
let order: Vec<usize> = (0..faces).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(drawn.len(), faces);
|
||||
steps
|
||||
};
|
||||
// No more than the square of the faces.
|
||||
let (few, more) = (steps_of(800), steps_of(1600));
|
||||
assert!(few < 800 * 800 && more < 1600 * 1600, "{few} steps for 800 faces, {more} for 1,600");
|
||||
}
|
||||
|
||||
/// Numbers from 0 to 1 that are the same on every run.
|
||||
fn numbers(mut seed: u64) -> impl FnMut() -> f64 {
|
||||
move || {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
(seed >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
}
|
||||
|
||||
/// A ring gives up its own face that comes first by depth, which draws no more pairs the wrong
|
||||
/// way round than taking the first face left by depth, ring or not, as before: on 6,000 sets of
|
||||
/// pairs at random (4 to 30 faces, sparse and dense, agreeing with the depths mostly or half the
|
||||
/// time, the pairs in any order and some twice, with up to four faces drawn last) none has more, and they have fewer in all. Every face
|
||||
/// is drawn once, a face drawn last follows every face before it by depth, and the order of every
|
||||
/// set is the one that looking afresh at every stop gives. One of them is a
|
||||
/// set where the ring's face that waits for the fewest faces drew 4 pairs wrong against 3.
|
||||
#[test]
|
||||
fn breaking_a_ring_draws_no_more_pairs_wrong_than_the_first_face_by_depth() {
|
||||
let order = [3, 6, 4, 1, 0, 2, 5];
|
||||
let before = [
|
||||
(1, 0),
|
||||
(2, 0),
|
||||
(0, 3),
|
||||
(0, 4),
|
||||
(5, 0),
|
||||
(6, 0),
|
||||
(1, 2),
|
||||
(1, 3),
|
||||
(4, 1),
|
||||
(5, 1),
|
||||
(4, 2),
|
||||
(5, 2),
|
||||
(6, 2),
|
||||
(3, 4),
|
||||
(3, 6),
|
||||
(5, 4),
|
||||
(6, 4),
|
||||
(5, 6),
|
||||
];
|
||||
assert_eq!(broken(&in_pairs_order(&order, &before, &[], 0).0, &before).len(), 3);
|
||||
assert_eq!(broken(&in_pairs_order(&order, &before, &[], usize::MAX).0, &before).len(), 3);
|
||||
|
||||
let mut next = numbers(7023);
|
||||
let (mut with_rings, mut without, mut fewer) = (0usize, 0usize, 0usize);
|
||||
for set in 0..6000 {
|
||||
let n = 4 + (next() * 27.0) as usize;
|
||||
let (dense, agrees) = (0.05 + 0.8 * next() * next(), if set % 2 == 0 { 0.5 } else { 0.85 });
|
||||
// The order by depth: the faces shuffled.
|
||||
let mut order: Vec<usize> = (0..n).collect();
|
||||
for k in (1..n).rev() {
|
||||
order.swap(k, (next() * (k + 1) as f64) as usize);
|
||||
}
|
||||
let mut before = vec![];
|
||||
for a in 0..n {
|
||||
for b in a + 1..n {
|
||||
if next() < dense {
|
||||
before.push(if next() < agrees { (order[a], order[b]) } else { (order[b], order[a]) });
|
||||
}
|
||||
}
|
||||
}
|
||||
// The pairs in any order, and in every fifth set some of them twice.
|
||||
for k in (1..before.len()).rev() {
|
||||
before.swap(k, (next() * (k + 1) as f64) as usize);
|
||||
}
|
||||
if set % 5 == 0 {
|
||||
let again: Vec<(usize, usize)> = before.iter().copied().filter(|_| next() < 0.3).collect();
|
||||
before.extend(again);
|
||||
}
|
||||
// No face drawn last, or up to four.
|
||||
let last: Vec<usize> = (0..set % 5).map(|_| order[(next() * n as f64) as usize]).collect();
|
||||
let (drawn, _) = in_pairs_order(&order, &before, &last, usize::MAX);
|
||||
// Keeping the search from stop to stop gives what looking afresh at every stop gives.
|
||||
assert_eq!(drawn, in_pairs_order_plainly(&order, &before, &last), "set {set}: {order:?} {before:?} {last:?}");
|
||||
let (plainly, _) = in_pairs_order(&order, &before, &last, 0);
|
||||
let mut once = drawn.clone();
|
||||
once.sort_unstable();
|
||||
assert_eq!(once, (0..n).collect::<Vec<_>>(), "set {set}");
|
||||
for &cap in &last {
|
||||
let (at, place) = (order.iter().position(|&f| f == cap).unwrap(), drawn.iter().position(|&f| f == cap).unwrap());
|
||||
assert!(order[..at].iter().all(|f| drawn[..place].contains(f)), "set {set}");
|
||||
}
|
||||
let (rings, plain) = (broken(&drawn, &before).len(), broken(&plainly, &before).len());
|
||||
assert!(rings <= plain, "set {set}: {rings} pairs wrong, {plain} with the first face by depth; {order:?} {before:?} {last:?}");
|
||||
with_rings += rings;
|
||||
without += plain;
|
||||
fewer += usize::from(rings < plain);
|
||||
}
|
||||
assert!(fewer > 500 && with_rings < without, "{with_rings} pairs wrong, {without} with the first face by depth, fewer in {fewer} sets");
|
||||
}
|
||||
|
||||
/// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a
|
||||
/// face of the same shape's stroke drawn before it: the wall then goes just before that face. A
|
||||
/// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an
|
||||
|
||||
@@ -289,6 +289,8 @@ fn local_stop(kind: &Arrowhead) -> Stop {
|
||||
Arrowhead::DoubleSlash => Stop::At(1.05),
|
||||
Arrowhead::DoubleArrow => Stop::At(1.7),
|
||||
Arrowhead::HalfCircle => Stop::At(1.0),
|
||||
// Between the bend in its sides and its notch, where it is wider than the line at 100 %.
|
||||
Arrowhead::NotchedArrow => Stop::At(2.7),
|
||||
Arrowhead::Concave => Stop::At(2.6),
|
||||
Arrowhead::Hexagon => Stop::At(HEX / 2.0),
|
||||
_ => Stop::At(2.0),
|
||||
@@ -395,6 +397,9 @@ fn local(kind: &Arrowhead) -> BezPath {
|
||||
let t = FRAC_1_SQRT_2;
|
||||
poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]);
|
||||
}
|
||||
// Barbs 1.2 out at the back; each side bends in at (2.1, ±0.5), as wide as the line at
|
||||
// 100 %, so the sides are concave; the notch reaches 0.7 into the back.
|
||||
Arrowhead::NotchedArrow => poly(&mut p, &[(0.0, 0.0), (2.1, 0.5), (4.0, 1.2), (3.3, 0.0), (4.0, -1.2), (2.1, -0.5)]),
|
||||
Arrowhead::Custom(c) => p = c.path.to_bezpath(),
|
||||
// The first ten are drawn by `shape`.
|
||||
Arrowhead::Triangle
|
||||
|
||||
@@ -4,20 +4,26 @@
|
||||
|
||||
use kurbo::{BezPath, PathEl, Point, Shape};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{ArrowAlign, Arrowhead, StrokeLayer};
|
||||
use vectorcraft_doc::{ArrowAlign, Arrowhead, LineCap, StrokeLayer};
|
||||
|
||||
use super::stroke_pieces;
|
||||
use super::{line_outline, stroke_pieces};
|
||||
|
||||
/// A 2 pt line along +x ending at (100, 0) with `kind` at its end, tip on the end point: heads
|
||||
/// of weight 2, so 8 long and 8 wide.
|
||||
fn head(kind: Arrowhead) -> super::Arrow {
|
||||
head_and_line(kind, LineCap::Butt).0
|
||||
}
|
||||
|
||||
/// [`head`] and the outline of the line under it, drawn with `cap`.
|
||||
fn head_and_line(kind: Arrowhead, cap: LineCap) -> (super::Arrow, BezPath) {
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
|
||||
st.end_arrow = Some(kind);
|
||||
st.arrow_align = ArrowAlign::Tip;
|
||||
(st.end_arrow, st.arrow_align, st.cap) = (Some(kind), ArrowAlign::Tip, cap);
|
||||
let mut l = BezPath::new();
|
||||
l.move_to((0.0, 0.0));
|
||||
l.line_to((100.0, 0.0));
|
||||
stroke_pieces(&l, &st).heads.remove(0)
|
||||
let mut p = stroke_pieces(&l, &st);
|
||||
let line = line_outline(&p.line, &st, st.width, 1e-3);
|
||||
(p.heads.remove(0), line)
|
||||
}
|
||||
|
||||
/// The outline's closed contours as polygons (curves flattened).
|
||||
@@ -105,6 +111,53 @@ fn the_line_arrow_is_a_right_angle_of_two_arms_as_thick_as_the_line() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_notched_arrow_is_slender_with_concave_sides_and_a_v_notch() {
|
||||
// Weight 2 at 100 %: a local unit (x back from the tip, y across) is 2 pt.
|
||||
let h = head(Arrowhead::NotchedArrow);
|
||||
let at = |x: f64, y: f64| Point::new(100.0 - 2.0 * x, 2.0 * y);
|
||||
// Six corners: the tip, a bend in each side, a barb on each side and the notch between them.
|
||||
let pts: Vec<Point> = contours(&h.outline).concat();
|
||||
let corners = [(0.0, 0.0), (2.1, 0.5), (4.0, 1.2), (3.3, 0.0), (4.0, -1.2), (2.1, -0.5)].map(|(x, y)| at(x, y));
|
||||
assert_eq!(pts.len(), corners.len(), "{pts:?}");
|
||||
for c in corners {
|
||||
assert!(pts.iter().any(|p| p.distance(c) < 1e-9), "corner {c:?} in {pts:?}");
|
||||
}
|
||||
for side in [1.0, -1.0] {
|
||||
// Concave: at the bend, the straight line from the tip to the barb (0.63 out) is outside.
|
||||
assert_eq!(h.outline.winding(at(2.1, side * 0.6)), 0, "side {side}");
|
||||
assert_ne!(h.outline.winding(at(2.1, side * 0.45)), 0, "side {side}");
|
||||
// Slender: 2.4 units across at the barbs, not the 4 of the other arrows.
|
||||
assert_eq!(h.outline.winding(at(3.9, side * 1.2)), 0, "side {side}");
|
||||
assert_ne!(h.outline.winding(at(3.9, side * 1.1)), 0, "side {side}");
|
||||
}
|
||||
// Open in the notch, solid in front of it.
|
||||
assert_eq!(h.outline.winding(at(3.5, 0.0)), 0);
|
||||
assert_ne!(h.outline.winding(at(3.1, 0.0)), 0);
|
||||
// The line stops between the bend and the notch, 2.7 units back from the tip.
|
||||
assert!((h.inset - 5.4).abs() < 1e-9, "inset {}", h.inset);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_line_under_the_notched_arrow_stays_inside_it_in_front_of_the_notch() {
|
||||
// With every cap, no part of the 2 pt line between the notch and the tip shows beside the
|
||||
// head, though the head is barely wider than the line at its bends.
|
||||
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
|
||||
let (h, line) = head_and_line(Arrowhead::NotchedArrow, cap);
|
||||
let mut covered = 0;
|
||||
for i in 0..=132 {
|
||||
for j in -25..=25 {
|
||||
let p = Point::new(100.0 - 6.6 + f64::from(i) * 0.05, f64::from(j) * 0.04);
|
||||
if line.winding(p) != 0 {
|
||||
assert_ne!(h.outline.winding(p), 0, "{cap:?}: the line shows at {p:?}");
|
||||
covered += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(covered > 500, "{cap:?}: the line reaches under the head ({covered} samples)");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_arrows_barb_on_their_own_side() {
|
||||
// Pointing along +x on a y-down page, left is −y.
|
||||
|
||||
@@ -38,6 +38,12 @@ fn check(bp: &BezPath, st: &StrokeLayer, what: &str) {
|
||||
let painted = region.bounding_box();
|
||||
let bounds = st.bounds_on(bp, bp.bounding_box());
|
||||
assert!(bounds.inflate(0.05, 0.05).contains_rect(painted), "{what}: paints {painted:?} outside {bounds:?}");
|
||||
check_clicks(bp, st, ®ion, what);
|
||||
}
|
||||
|
||||
/// Check that points of `region`, what `st` paints along `bp`, hit as [`check`] says.
|
||||
fn check_clicks(bp: &BezPath, st: &StrokeLayer, region: &BezPath, what: &str) {
|
||||
let painted = region.bounding_box();
|
||||
let tol = if st.profile.is_some() { 1.0 } else { 0.25 };
|
||||
// Off the outline's own coordinates, so no sample sits level with a vertex.
|
||||
let (mut x, mut checked) = (painted.x0 + 0.371, 0);
|
||||
@@ -45,7 +51,7 @@ fn check(bp: &BezPath, st: &StrokeLayer, what: &str) {
|
||||
let mut y = painted.y0 + 0.293;
|
||||
while y <= painted.y1 {
|
||||
let p = Point::new(x, y);
|
||||
if fill_contains(®ion, FillRule::EvenOdd, p) {
|
||||
if fill_contains(region, FillRule::EvenOdd, p) {
|
||||
assert!(st.hits(bp, FillRule::NonZero, p, tol), "{what}: painted {p:?} doesn't hit");
|
||||
checked += 1;
|
||||
}
|
||||
@@ -140,6 +146,58 @@ fn custom_heads() -> Vec<Arrowhead> {
|
||||
vec![head("Wedge", &[(0.0, 0.0), (3.0, 2.0), (3.0, -1.0)]), head("Spindle", &[(-10.0, 0.0), (0.0, 2.0), (10.0, 0.0), (0.0, -2.0)])]
|
||||
}
|
||||
|
||||
/// Paths with a subpath that never leaves its first point, which a round or projecting cap draws
|
||||
/// as a dot at (140, 130): a closed lone anchor, a line to the same point, open and closed, and a
|
||||
/// curve with every handle on the point, alone and after a closed triangle.
|
||||
fn dot_paths() -> Vec<BezPath> {
|
||||
let at = Point::new(140.0, 130.0);
|
||||
let mut lone = BezPath::new();
|
||||
lone.move_to(at);
|
||||
lone.close_path();
|
||||
let mut line = BezPath::new();
|
||||
line.move_to(at);
|
||||
line.line_to(at);
|
||||
let mut closed_line = line.clone();
|
||||
closed_line.close_path();
|
||||
let mut curve = BezPath::new();
|
||||
curve.move_to(at);
|
||||
curve.curve_to(at, at, at);
|
||||
curve.close_path();
|
||||
let mut beside = paths()[2].clone();
|
||||
beside.extend(lone.iter());
|
||||
vec![lone, line, closed_line, curve, beside]
|
||||
}
|
||||
|
||||
/// A click on the dot a round or projecting cap draws for a subpath that never leaves its first
|
||||
/// point hits the path, and where no dot is drawn (butt caps, dashes, width profiles, an inside
|
||||
/// stroke of a closed subpath) a click beside the point misses.
|
||||
#[test]
|
||||
fn clicks_hit_the_dot_a_cap_draws_for_a_subpath_with_no_length() {
|
||||
let beside = Point::new(142.0, 130.0);
|
||||
let mut painted = 0;
|
||||
for (pi, bp) in dot_paths().iter().enumerate() {
|
||||
for align in [StrokeAlign::Center, StrokeAlign::Inside, StrokeAlign::Outside] {
|
||||
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
|
||||
for profile in [None, Some(WidthProfile::lens())] {
|
||||
for dash in [None, Some(Dash { pattern: vec![7.0, 4.0], offset: 0.0, align_corners: false })] {
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 6.0);
|
||||
(st.align, st.cap, st.profile, st.dash) = (align, cap, profile.clone(), dash.clone());
|
||||
let what = format!("path {pi} {align:?} {cap:?} profile {} dashed {}", profile.is_some(), dash.is_some());
|
||||
let region = outline_region(&PathData::from_bezpath(bp), FillRule::NonZero, &st).to_bezpath();
|
||||
if !fill_contains(®ion, FillRule::EvenOdd, beside) {
|
||||
assert!(!st.hits(bp, FillRule::NonZero, beside, 0.25), "{what}: a click beside the point hits, where no dot is drawn");
|
||||
continue;
|
||||
}
|
||||
painted += 1;
|
||||
check_clicks(bp, &st, ®ion, &what);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(painted, 22, "dots drawn");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_and_clicks_cover_every_arrowhead() {
|
||||
let bp = &paths()[0];
|
||||
|
||||
@@ -6,6 +6,7 @@ use super::*;
|
||||
|
||||
mod clipfx;
|
||||
mod imageoutline;
|
||||
mod loneanchor;
|
||||
mod painted;
|
||||
mod rasterfollow;
|
||||
mod scale;
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Geometry effects on a path with a lone anchor work from the path's bounds with that anchor
|
||||
//! included ([`PathData::bounds`]), as the selection's box, Align and Transform Each measure the
|
||||
//! path, wherever the effects are applied.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A 10 pt line from the origin and a lone anchor at (100, 50): its bounds are (0, 0) to
|
||||
/// (100, 50), and the line alone measures (0, 0) to (10, 0).
|
||||
fn marked() -> PathData {
|
||||
PathData::new(vec![
|
||||
SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false),
|
||||
SubPath::polyline(&[Point::new(100.0, 50.0)], false),
|
||||
])
|
||||
}
|
||||
|
||||
/// The Transform effect at 200%, about the center of the box it is given.
|
||||
fn scale() -> Effect {
|
||||
fx("distort.transform", json!({"scaleH": 200, "scaleV": 200}))
|
||||
}
|
||||
|
||||
/// `marked` with a 1 pt black stroke, and `scale` on the object (`on_stroke` false) or on its
|
||||
/// stroke.
|
||||
fn node(on_stroke: bool) -> Node {
|
||||
let mut n = Node::path(NodeId(5), marked(), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0));
|
||||
if on_stroke {
|
||||
if let Some(s) = n.appearance.stroke_mut() {
|
||||
s.effects.push(scale());
|
||||
}
|
||||
} else {
|
||||
n.appearance.effects.push(scale());
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// The first point of each subpath of each path under `n`.
|
||||
fn starts(n: &Node, out: &mut Vec<Point>) {
|
||||
if let NodeKind::Path { path, .. } = &n.kind {
|
||||
out.extend(path.subpaths.iter().filter_map(|s| s.anchors.first()).map(|a| a.p));
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
starts(c, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// Does a path under `n` start where the line scaled about (50, 25) starts, (-50, -25), and
|
||||
/// none where the line scaled about its own center (5, 0) starts, (-5, 0)?
|
||||
fn scaled_about_the_bounds(n: &Node) -> bool {
|
||||
let mut pts = vec![];
|
||||
starts(n, &mut pts);
|
||||
let at = |x: f64, y: f64| pts.iter().any(|p| close(p.x, x, 1e-6) && close(p.y, y, 1e-6));
|
||||
assert_eq!(apply_geometry(&[scale()], &marked(), marked().bounds().unwrap()).subpaths[0].anchors[0].p, Point::new(-50.0, -25.0));
|
||||
at(-50.0, -25.0) && !at(-5.0, 0.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_appearance_scales_about_bounds_with_the_lone_anchor() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, node(false)).unwrap();
|
||||
let baked = bake_document(&d).expect("the effect bakes");
|
||||
let layer = &baked.layers[0];
|
||||
assert!(scaled_about_the_bounds(layer), "{layer:?}");
|
||||
}
|
||||
|
||||
/// A stroke's Transform effect with Scale Strokes & Effects on makes the stroke a path of its own
|
||||
/// when the object's own effects are reshaped, its geometry after the stroke's effects before it.
|
||||
#[test]
|
||||
fn a_stroke_effect_scales_about_bounds_with_the_lone_anchor() {
|
||||
let mut n = node(true);
|
||||
n.appearance.effects = vec![fx("distort.transform", json!({}))];
|
||||
if let Some(s) = n.appearance.stroke_mut() {
|
||||
s.effects.push(fx("distort.transform", json!({"strokes": true})));
|
||||
}
|
||||
let art = reshape(None, &n, None).expect("the effects make art");
|
||||
assert!(scaled_about_the_bounds(&art), "{art:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_art_scales_about_bounds_with_the_lone_anchor() {
|
||||
let art = shape_art(None, &node(false), None).expect("the effect makes art");
|
||||
assert!(scaled_about_the_bounds(&art), "{art:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_art_scales_about_bounds_with_the_lone_anchor() {
|
||||
let d = Document::new(200.0, 200.0);
|
||||
let symbols = d.symbol_boxes();
|
||||
for on_stroke in [false, true] {
|
||||
let art = crate::preview::drawn_art(&symbols, &node(on_stroke)).expect("the effect makes art");
|
||||
assert!(scaled_about_the_bounds(&art), "on the stroke {on_stroke}: {art:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_paints_its_art_scaled_about_bounds_with_the_lone_anchor() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
d.symbols.push(Symbol { dynamic: false, name: "s".into(), art: Arc::new(node(true)) });
|
||||
let mut inst = Node::new(NodeId(9), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY });
|
||||
inst.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into();
|
||||
if let Some(s) = inst.appearance.stroke_mut() {
|
||||
s.effects.push(fx("distort.transform", json!({})));
|
||||
}
|
||||
let painted = image_paint(Some(&d), &inst);
|
||||
let pts: Vec<Point> = painted
|
||||
.iter()
|
||||
.filter_map(|(bp, _, _)| match bp.elements().first() {
|
||||
Some(vectorcraft_geom::PathEl::MoveTo(p)) => Some(*p),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(pts.iter().any(|p| close(p.x, -50.0, 1e-6) && close(p.y, -25.0, 1e-6)), "{pts:?}");
|
||||
assert!(!pts.iter().any(|p| close(p.x, -5.0, 1e-6) && close(p.y, 0.0, 1e-6)), "{pts:?}");
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use vectorcraft_plugins::wat as tpl;
|
||||
|
||||
use crate::geometry::Budget;
|
||||
use crate::reshape;
|
||||
use crate::reshape::{HELD_PEAK, PLUGIN_RUNS};
|
||||
use crate::reshape::{DRESSED, HELD_PEAK, PLUGIN_RUNS};
|
||||
|
||||
/// Installs live-effect plug-in `id`, which paints what it returns, replacing one with the same id:
|
||||
/// its effect returns `output` whatever it is given.
|
||||
@@ -268,3 +268,449 @@ fn a_built_in_result_on_the_path_before_it_is_taken_near_the_budget() {
|
||||
let height = |b: Option<Rect>| b.map_or(0.0, |b| b.height());
|
||||
assert!((height(*bounds) - height(tall.bounds())).abs() < 1.0, "{bounds:?} is not {:?} tall", tall.bounds());
|
||||
}
|
||||
|
||||
/// The host takes a built-in effect with parameters it has, of their type and in range, on a piece,
|
||||
/// and a raster effect on a fill or stroke; it refuses a plug-in effect, a 3D effect, a Pathfinder
|
||||
/// effect (a piece is one path, with nothing to combine), an unknown effect or parameter, a value
|
||||
/// of another type or out of range, and a geometry effect on a fill or stroke.
|
||||
#[test]
|
||||
fn returned_effects_are_built_in_effects_with_their_own_parameters() {
|
||||
let e = |id: &str, params: serde_json::Value| Effect { id: id.into(), params, visible: true };
|
||||
let check = crate::check_returned_effect;
|
||||
assert_eq!(check(&e("path.offsetPath", json!({"offset": 4.0})), false), Ok(()));
|
||||
assert_eq!(check(&e("path.offsetPath", serde_json::Value::Null), false), Ok(()));
|
||||
assert_eq!(check(&e("stylize.dropShadow", json!({"x": 2.0})), true), Ok(()));
|
||||
assert_eq!(check(&e("brushStrokes.accentedEdges", json!({"edgeWidth": 14.0})), false), Ok(()));
|
||||
assert_eq!(check(&e("distort.transform", json!({"copies": 1000})), false), Ok(()));
|
||||
// A parameter documented right after a comma has its range checked too.
|
||||
assert_eq!(check(&e("artistic.paintDaubs", json!({"sharpness": 25})), false), Ok(()));
|
||||
// Each documented choice and each end of a documented range passes.
|
||||
for (id, params) in [
|
||||
("distort.roughen", json!({"points": "smooth"})),
|
||||
("distort.roughen", json!({"points": "corner"})),
|
||||
("distort.zigZag", json!({"points": "corner"})),
|
||||
("distort.puckerBloat", json!({"amount": -200})),
|
||||
("distort.puckerBloat", json!({"amount": 200})),
|
||||
("adjust.temperatureTint", json!({"temperature": -100, "tint": 100})),
|
||||
("stylize.dropShadow", json!({"mode": "color-burn"})),
|
||||
("stylize.outerGlow", json!({"mode": "Normal"})),
|
||||
// A `color` is also taken as [r, g, b] 0..1 or a color object, as the effects draw it.
|
||||
("stylize.dropShadow", json!({"color": [1.0, 0.0, 0.0]})),
|
||||
("stylize.dropShadow", json!({"color": [1, 0, 0]})),
|
||||
("stylize.outerGlow", json!({"color": {"model": "gray", "k": 0.5}})),
|
||||
("stylize.innerGlow", json!({"color": {"model": "cmyk", "c": 0, "m": 1, "y": 0, "k": 0}})),
|
||||
("stylize.innerGlow", json!({"color": {"model": "lab", "l": 100, "a": -128, "b": 127}})),
|
||||
// Curves' `points` is also taken as [[x, y], …], and a Transform's whole numbers as such.
|
||||
("adjust.curves", json!({"points": [[0, 255], [255, 0]]})),
|
||||
("adjust.curves", json!({"points": "0,0; 64,32 255,255"})),
|
||||
("distort.transform", json!({"copies": 2, "reference": 0.0})),
|
||||
] {
|
||||
assert_eq!(check(&e(id, params.clone()), false), Ok(()), "{id} {params}");
|
||||
}
|
||||
// Every effect's own defaults pass the check, so each documented range holds its default.
|
||||
for info in crate::effect_catalog().into_iter().filter(|i| !crate::is_three_d(i.id) && !crate::is_pathfinder(i.id)) {
|
||||
assert_eq!(check(&e(info.id, info.defaults.clone()), false), Ok(()), "{}", info.id);
|
||||
}
|
||||
for (effect, row) in [
|
||||
(e("distort.transform", json!({"copies": 1001})), false),
|
||||
(e("path.offsetPath", json!({"offset": null})), false),
|
||||
(e("plugin.test.effects.self", json!({})), false),
|
||||
(e("threeD.extrude", json!({})), false),
|
||||
(e("pathfinder.add", serde_json::Value::Null), false),
|
||||
(e("pathfinder.divide", json!({"precision": 1.0})), false),
|
||||
(e("stylize.nope", json!({})), false),
|
||||
(e("path.offsetPath", json!({"inset": 4.0})), false),
|
||||
(e("path.offsetPath", json!({"offset": "4"})), false),
|
||||
(e("brushStrokes.accentedEdges", json!({"edgeWidth": 15.0})), false),
|
||||
(e("artistic.paintDaubs", json!({"sharpness": 41})), false),
|
||||
(e("path.offsetPath", json!([4.0])), false),
|
||||
(e("path.offsetPath", json!({"offset": 4.0})), true),
|
||||
] {
|
||||
assert!(check(&effect, row).is_err(), "{effect:?} on a fill or stroke: {row}");
|
||||
}
|
||||
let why = check(&e("pathfinder.add", serde_json::Value::Null), false).unwrap_err();
|
||||
assert!(why.contains("Pathfinder effects are not allowed"), "{why}");
|
||||
// The values checked for one effect are refused with the parameter named.
|
||||
for (id, params, key) in [
|
||||
(crate::SVG_FILTER, json!({"axes": [1, 0, 0, 0]}), "axes"),
|
||||
(crate::SVG_FILTER, json!({"scale": 0.0}), "scale"),
|
||||
(crate::SVG_FILTER, json!({"origin": [1.0]}), "origin"),
|
||||
(crate::SVG_FILTER, json!({"name": "f"}), "name"),
|
||||
("warp.arc", json!({"version": 99}), "version"),
|
||||
("stylize.dropShadow", json!({"color": "#zz0000"}), "color"),
|
||||
("stylize.dropShadow", json!({"color": [1.0, "0", 0.0]}), "color"),
|
||||
("stylize.innerGlow", json!({"color": {"model": "rgb"}}), "color"),
|
||||
("stylize.outerGlow", json!({"color": true}), "color"),
|
||||
// Color components are from 0 to 1, Lab's lightness from 0 to 100.
|
||||
("stylize.dropShadow", json!({"color": [2, -1, 0]}), "color"),
|
||||
("stylize.dropShadow", json!({"color": [0.5, 0.5, 1.01]}), "color"),
|
||||
("stylize.outerGlow", json!({"color": {"model": "rgb", "r": 2.0, "g": 0.0, "b": 0.0}}), "color"),
|
||||
("stylize.innerGlow", json!({"color": {"model": "gray", "k": -0.5}}), "color"),
|
||||
("stylize.innerGlow", json!({"color": {"model": "lab", "l": 101, "a": 0, "b": 0}}), "color"),
|
||||
("adjust.curves", json!({"points": [[0, 255], [255]]}), "points"),
|
||||
("adjust.curves", json!({"points": ["0,0", "255,255"]}), "points"),
|
||||
// Curves' points are read as "x,y" or [x, y] pairs, each number from 0 to 255.
|
||||
("adjust.curves", json!({"points": "not-points"}), "points"),
|
||||
("adjust.curves", json!({"points": "0,0 255,-1"}), "points"),
|
||||
("adjust.curves", json!({"points": [[0, 300], [255, 0]]}), "points"),
|
||||
("distort.transform", json!({"copies": 1.5}), "copies"),
|
||||
("distort.transform", json!({"reference": 4.5}), "reference"),
|
||||
("adjust.levels", json!({"channel": "cyan"}), "channel"),
|
||||
("blur.radial", json!({"centerX": 1.5}), "centerX"),
|
||||
("blur.gaussian", json!({"linear": 1}), "linear"),
|
||||
("pixelate.colorHalftone", json!({"channel1": 400.0}), "channel1"),
|
||||
("distort.twist", json!({"angle": 4000.0}), "angle"),
|
||||
("distort.freeDistort", json!({"corners": []}), "corners"),
|
||||
("distort.freeDistort", json!({"corners": [[0, 0], [1, 0], [1, 1], [0]]}), "corners"),
|
||||
("distort.roughen", json!({"points": "invalid"}), "points"),
|
||||
("distort.zigZag", json!({"points": "Corner"}), "points"),
|
||||
("path.offsetPath", json!({"joins": "square"}), "joins"),
|
||||
(crate::RASTERIZE, json!({"colorModel": "cmyk"}), "colorModel"),
|
||||
(crate::CROP_MARKS, json!({"style": 1}), "style"),
|
||||
("distort.puckerBloat", json!({"amount": -201}), "amount"),
|
||||
("distort.puckerBloat", json!({"amount": 201}), "amount"),
|
||||
("adjust.temperatureTint", json!({"temperature": 101}), "temperature"),
|
||||
("adjust.temperatureTint", json!({"tint": -101}), "tint"),
|
||||
("stylize.dropShadow", json!({"mode": "not-a-mode"}), "mode"),
|
||||
("stylize.innerGlow", json!({"mode": "???"}), "mode"),
|
||||
] {
|
||||
let why = check(&e(id, params.clone()), false).expect_err(&format!("{id} {params}"));
|
||||
assert!(why.contains(key), "{id} {params}: {why}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A painted effect on a fill whose piece fits the budget, but whose piece's own Transform copy
|
||||
/// would not fit beside the source: the fill is drawn on the source's path, and nothing is drawn
|
||||
/// where the piece would be.
|
||||
#[test]
|
||||
fn a_piece_s_own_geometry_effects_keep_to_the_budget() {
|
||||
let id = "test.effects.look.budget";
|
||||
let source = drawn_share(0.45, 0.0);
|
||||
let piece = json!({"path": drawn_share(0.3, 2_000.0), "effects": [{"id": "distort.transform", "params": {"copies": 1, "moveH": 10.0}}]});
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"#
|
||||
);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": [piece] }).to_string())).unwrap();
|
||||
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
|
||||
let mut n = Node::path(NodeId(9), source.clone(), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap();
|
||||
n.appearance.items[fill].effects_mut().push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true });
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let mut bounds = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if let Some(b) = c.path_data().and_then(PathData::bounds) {
|
||||
bounds.push(b);
|
||||
}
|
||||
});
|
||||
assert!(!bounds.is_empty() && bounds.iter().all(|b| b.x1 < 2_000.0), "{bounds:?}");
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
}
|
||||
|
||||
/// Where [`many_heavy_pieces`] puts its effect.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum HeavyOn {
|
||||
/// The object's own effects.
|
||||
Object,
|
||||
/// The square's fill, as its only effect.
|
||||
Fill,
|
||||
/// The square's fill, after a painted effect that returns the square.
|
||||
LaterOnFill,
|
||||
}
|
||||
|
||||
/// Ten painted pieces, each drawn with 4% of the effects' budget, each with a Transform effect that
|
||||
/// makes 14 copies of it (60% of the budget per piece), from an effect on a square `on`: they would
|
||||
/// pass the budget together, so the square is drawn as it was. The pieces' own geometry effects keep
|
||||
/// to what the pieces before them left: the art reshaped for them costs less than the budget
|
||||
/// together, and so does the art drawn.
|
||||
fn many_heavy_pieces(on: HeavyOn) {
|
||||
let id = format!("test.effects.look.heavy{on:?}").to_lowercase();
|
||||
let pieces: Vec<_> = (0..10)
|
||||
.map(|k| json!({"path": drawn_share(0.04, 1_000.0 * f64::from(k)), "effects": [{"id": "distort.transform", "params": {"copies": 14, "moveH": 10.0}}]}))
|
||||
.collect();
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"#
|
||||
);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": pieces }).to_string())).unwrap();
|
||||
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
|
||||
let square = shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0));
|
||||
let first = format!("{id}.first");
|
||||
install_painting(&first, &json!({"objects": [{"path": square}]}));
|
||||
let mut n = Node::path(NodeId(9), square.clone(), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let heavy = Effect { id: format!("plugin.{id}"), params: json!({}), visible: true };
|
||||
let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap();
|
||||
match on {
|
||||
HeavyOn::Object => n.appearance.effects.push(heavy),
|
||||
HeavyOn::Fill => n.appearance.items[fill].effects_mut().push(heavy),
|
||||
HeavyOn::LaterOnFill => {
|
||||
n.appearance.items[fill].effects_mut().push(Effect { id: format!("plugin.{first}"), params: json!({}), visible: true });
|
||||
n.appearance.items[fill].effects_mut().push(heavy);
|
||||
}
|
||||
}
|
||||
DRESSED.with(|d| d.set(Budget { anchors: 0, lines: 0 }));
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let dressed = DRESSED.with(std::cell::Cell::get);
|
||||
assert!(Budget::EFFECTS.fits(dressed), "{on:?}: the pieces' own effects made {dressed:?}");
|
||||
let (mut bounds, mut drawn) = (vec![], Budget { anchors: 0, lines: 0 });
|
||||
art.walk(&mut |c| {
|
||||
if let Some(p) = c.path_data() {
|
||||
bounds.push(p.bounds());
|
||||
drawn = drawn.plus(Budget::of(p));
|
||||
}
|
||||
});
|
||||
// On a fill, the fill and the stroke are paths of their own.
|
||||
assert!(!bounds.is_empty() && bounds.iter().all(|b| *b == square.bounds()), "{on:?}: {bounds:?}");
|
||||
assert!(Budget::EFFECTS.fits(drawn), "{on:?}: the art costs {drawn:?}");
|
||||
vectorcraft_plugins::registry::remove(&id);
|
||||
vectorcraft_plugins::registry::remove(&first);
|
||||
}
|
||||
|
||||
/// [`many_heavy_pieces`] from the object's own effect.
|
||||
#[test]
|
||||
fn heavy_pieces_of_an_object_s_effect_stop_within_the_budget() {
|
||||
many_heavy_pieces(HeavyOn::Object);
|
||||
}
|
||||
|
||||
/// [`many_heavy_pieces`] from an effect on a fill.
|
||||
#[test]
|
||||
fn heavy_pieces_of_a_fill_s_effect_stop_within_the_budget() {
|
||||
many_heavy_pieces(HeavyOn::Fill);
|
||||
}
|
||||
|
||||
/// [`many_heavy_pieces`] from a later effect on a fill.
|
||||
#[test]
|
||||
fn heavy_pieces_of_a_later_effect_on_a_fill_stop_within_the_budget() {
|
||||
many_heavy_pieces(HeavyOn::LaterOnFill);
|
||||
}
|
||||
|
||||
/// A piece's own geometry effect reshapes it before the source's later effects run, and those run
|
||||
/// on it once: the square at 120, 40 grown by a 10 pt Offset Path, then moved 100 pt right by the
|
||||
/// source's Transform effect. The piece's opacity and blending mode stay on the path it becomes.
|
||||
#[test]
|
||||
fn later_source_effects_run_after_generated_effects_once() {
|
||||
let id = "test.effects.look.offset";
|
||||
let piece = json!({"path": shapes::rectangle(Rect::new(120.0, 40.0, 140.0, 60.0)), "opacity": 0.5, "blend": "Multiply",
|
||||
"effects": [{"id": "path.offsetPath", "params": {"offset": 10.0}}]});
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"#
|
||||
);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": [piece] }).to_string())).unwrap();
|
||||
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
n.appearance.effects.push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true });
|
||||
n.appearance.effects.push(Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true });
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let (mut paths, mut looks) = (vec![], vec![]);
|
||||
art.walk(&mut |c| {
|
||||
if let Some(p) = c.path_data() {
|
||||
paths.push(p.bounds());
|
||||
}
|
||||
if c.opacity != 1.0 || c.blend != vectorcraft_doc::color::BlendMode::Normal {
|
||||
looks.push((c.opacity, c.blend));
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 1, "{paths:?}");
|
||||
// Once, on the piece and what holds it.
|
||||
assert_eq!(looks, [(0.5, vectorcraft_doc::color::BlendMode::Multiply)]);
|
||||
let b = paths[0].unwrap();
|
||||
assert!((b.x0 - 210.0).abs() < 0.5 && (b.x1 - 250.0).abs() < 0.5 && (b.y0 - 30.0).abs() < 0.5, "{b:?}");
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
}
|
||||
|
||||
/// A piece's look reshapes it by its own geometry effects alone: the Transform effect of the fill
|
||||
/// it carries stays on the fill for its own stage and does not move the piece now.
|
||||
#[test]
|
||||
fn a_piece_s_look_runs_only_its_own_geometry_effects() {
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap();
|
||||
n.appearance.items[fill].effects_mut().push(Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true });
|
||||
let look = vectorcraft_plugins::painted::Look {
|
||||
effects: vec![Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: true }],
|
||||
..Default::default()
|
||||
};
|
||||
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap();
|
||||
let mut paths = vec![];
|
||||
n.walk(&mut |c| {
|
||||
if let Some(b) = c.path_data().and_then(PathData::bounds) {
|
||||
paths.push((b, c.appearance.items.iter().map(|i| i.effects().len()).sum::<usize>()));
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 1, "{paths:?}");
|
||||
let (b, kept) = paths[0];
|
||||
assert!((b.x0 + 10.0).abs() < 0.5 && (b.x1 - 30.0).abs() < 0.5, "{b:?}");
|
||||
assert_eq!(kept, 1, "the fill keeps its Transform effect");
|
||||
}
|
||||
|
||||
/// A piece's blending mode on an object that blends in the same mode keeps both: the object
|
||||
/// becomes a group in its mode around the piece in the piece's.
|
||||
#[test]
|
||||
fn a_piece_s_blending_mode_nests_in_the_object_s_same_mode() {
|
||||
use vectorcraft_doc::color::BlendMode;
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
n.blend = BlendMode::Multiply;
|
||||
let look = vectorcraft_plugins::painted::Look { blend: Some(BlendMode::Multiply), ..Default::default() };
|
||||
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap();
|
||||
let mut blends = vec![];
|
||||
n.walk(&mut |c| blends.push(c.blend));
|
||||
assert_eq!(blends, [BlendMode::Multiply, BlendMode::Multiply]);
|
||||
}
|
||||
|
||||
/// A piece with an opacity, a blending mode and a geometry effect draws them once: the group the
|
||||
/// reshaped piece becomes carries them, and the path inside it draws at full opacity in Normal.
|
||||
#[test]
|
||||
fn a_reshaped_piece_s_opacity_and_blending_mode_apply_once() {
|
||||
use vectorcraft_doc::color::BlendMode;
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let look = vectorcraft_plugins::painted::Look {
|
||||
opacity: Some(0.5),
|
||||
blend: Some(BlendMode::Screen),
|
||||
effects: vec![Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: true }],
|
||||
};
|
||||
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap();
|
||||
let (mut opacity, mut blends) = (1.0f32, vec![]);
|
||||
n.walk(&mut |c| {
|
||||
opacity *= c.opacity;
|
||||
if c.blend != BlendMode::Normal {
|
||||
blends.push(c.blend);
|
||||
}
|
||||
});
|
||||
assert!((opacity - 0.5).abs() < 1e-6, "{opacity}");
|
||||
assert_eq!(blends, [BlendMode::Screen]);
|
||||
}
|
||||
|
||||
/// A piece's raster effect listed before its Transform effect follows the Transform, as an
|
||||
/// object's does: a Drop Shadow before a scale of 200% keeps twice its offset. A hidden record
|
||||
/// stays as it is.
|
||||
#[test]
|
||||
fn a_piece_s_raster_effects_follow_its_transform_effect() {
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let hidden = Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: false };
|
||||
let look = vectorcraft_plugins::painted::Look {
|
||||
effects: vec![
|
||||
Effect { id: "stylize.dropShadow".into(), params: json!({"x": 3.0, "y": 4.0}), visible: true },
|
||||
hidden.clone(),
|
||||
Effect { id: "distort.transform".into(), params: json!({"scaleH": 200, "scaleV": 200}), visible: true },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap();
|
||||
let mut kept = vec![];
|
||||
n.walk(&mut |c| kept.extend(c.appearance.effects.iter().cloned()));
|
||||
let shadow = kept.iter().find(|e| e.id == "stylize.dropShadow").expect("the piece keeps its Drop Shadow");
|
||||
let at = |k: &str| shadow.params.get(k).and_then(serde_json::Value::as_f64).unwrap_or(f64::NAN);
|
||||
assert!((at("x") - 6.0).abs() < 1e-9 && (at("y") - 8.0).abs() < 1e-9, "{shadow:?}");
|
||||
assert_eq!(kept.iter().filter(|e| **e == hidden).count(), 1, "{kept:?}");
|
||||
assert!(kept.iter().all(|e| e.id != "distort.transform"), "{kept:?}");
|
||||
}
|
||||
|
||||
/// A piece's raster effect listed before a Transform effect that makes copies goes on each copy,
|
||||
/// as an object's does: every copy carries its own Drop Shadow, scaled with it, and the art around
|
||||
/// the copies carries none.
|
||||
#[test]
|
||||
fn each_copy_of_a_piece_carries_its_own_raster_effects() {
|
||||
let shadow = Effect { id: "stylize.dropShadow".into(), params: json!({"x": 3.0, "y": 4.0}), visible: true };
|
||||
let copying = Effect { id: "distort.transform".into(), params: json!({"scaleH": 200, "scaleV": 200, "copies": 1}), visible: true };
|
||||
let square =
|
||||
|| Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
// The offsets of the Drop Shadows the nodes under `art` carry, and how many `art` itself
|
||||
// carries.
|
||||
let shadows = |art: &Node| {
|
||||
let offsets = |c: &Node| {
|
||||
c.appearance
|
||||
.effects
|
||||
.iter()
|
||||
.filter(|e| e.id == "stylize.dropShadow")
|
||||
.map(|e| {
|
||||
let at = |k: &str| e.params.get(k).and_then(serde_json::Value::as_f64).unwrap_or(f64::NAN);
|
||||
((at("x") * 1000.0).round() as i64, (at("y") * 1000.0).round() as i64)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let mut inside = vec![];
|
||||
for c in art.children().into_iter().flatten() {
|
||||
c.walk(&mut |d| inside.extend(offsets(d)));
|
||||
}
|
||||
inside.sort_unstable();
|
||||
(inside, offsets(art).len())
|
||||
};
|
||||
let mut object = square();
|
||||
object.appearance.effects = vec![shadow.clone(), copying.clone()];
|
||||
let expected = shadows(&crate::reshape::own_effects_art(None, &object).expect("the object's copies are drawn"));
|
||||
assert_eq!(expected.0.len(), 2, "{expected:?}");
|
||||
assert_eq!(expected.1, 0, "{expected:?}");
|
||||
let mut n = square();
|
||||
let look = vectorcraft_plugins::painted::Look { effects: vec![shadow, copying], ..Default::default() };
|
||||
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).expect("the piece is dressed");
|
||||
assert_eq!(shadows(&n), expected);
|
||||
}
|
||||
|
||||
/// A piece whose copies, each with its own raster effects, would pass the room left to it is
|
||||
/// refused rather than drawn with fewer copies than its Transform effect asks for.
|
||||
#[test]
|
||||
fn a_piece_s_copies_with_raster_effects_keep_to_its_room() {
|
||||
let square = shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0));
|
||||
let mut n = Node::path(NodeId(9), square.clone(), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let look = vectorcraft_plugins::painted::Look {
|
||||
effects: vec![
|
||||
Effect { id: "stylize.dropShadow".into(), params: json!({"x": 3.0, "y": 4.0}), visible: true },
|
||||
Effect { id: "distort.transform".into(), params: json!({"moveH": 30.0, "copies": 5}), visible: true },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
// Room for one more square: not for five.
|
||||
assert!(crate::reshape::dress_piece(&mut n, &look, Budget::of(&square), None).is_none());
|
||||
}
|
||||
|
||||
/// A piece's Transform effect with no copies and Scale Strokes & Effects on moves the piece: no
|
||||
/// copies were asked for, so none are missing.
|
||||
#[test]
|
||||
fn a_piece_s_transform_without_copies_scaling_strokes_moves_it() {
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let look = vectorcraft_plugins::painted::Look {
|
||||
effects: vec![Effect { id: "distort.transform".into(), params: json!({"moveH": 30.0, "copies": 0, "strokes": true}), visible: true }],
|
||||
..Default::default()
|
||||
};
|
||||
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).expect("the piece is dressed");
|
||||
let mut paths = vec![];
|
||||
n.walk(&mut |c| paths.extend(c.path_data().and_then(PathData::bounds)));
|
||||
assert_eq!(paths.len(), 1, "{paths:?}");
|
||||
assert!((paths[0].x0 - 30.0).abs() < 0.5 && (paths[0].x1 - 50.0).abs() < 0.5, "{paths:?}");
|
||||
}
|
||||
|
||||
/// The same on a fill: the plug-in and the Transform effect after it are the fill's. The piece's
|
||||
/// Offset Path runs on it alone, so the plug-in runs once and the square moves once.
|
||||
#[test]
|
||||
fn a_fill_s_later_effects_run_after_its_piece_s_effects_once() {
|
||||
let id = "test.effects.look.rowoffset";
|
||||
let piece = json!({"path": shapes::rectangle(Rect::new(120.0, 40.0, 140.0, 60.0)), "opacity": 0.5,
|
||||
"effects": [{"id": "path.offsetPath", "params": {"offset": 10.0}}]});
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"#
|
||||
);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": [piece] }).to_string())).unwrap();
|
||||
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap();
|
||||
let fx = n.appearance.items[fill].effects_mut();
|
||||
fx.push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true });
|
||||
fx.push(Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true });
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let mut paths = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if let Some(b) = c.path_data().and_then(PathData::bounds)
|
||||
&& c.appearance.items.iter().any(|i| i.is_fill() && crate::paints(i))
|
||||
{
|
||||
paths.push(b);
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 1, "{paths:?}");
|
||||
let b = paths[0];
|
||||
assert!((b.x0 - 210.0).abs() < 0.5 && (b.x1 - 250.0).abs() < 0.5 && (b.y0 - 30.0).abs() < 0.5, "{b:?}");
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
}
|
||||
|
||||
@@ -43,6 +43,8 @@ vectorcraft-metafile = { workspace = true }
|
||||
vectorcraft-plugins = { workspace = true }
|
||||
vectorcraft-affinity = { workspace = true }
|
||||
craft-cdr = { workspace = true }
|
||||
# `.pcraft` documents opened and placed as images (cmd/fileio/pcraftread.rs).
|
||||
craft-doc = { workspace = true }
|
||||
vectorcraft-scriptcheck = { workspace = true }
|
||||
vectorcraft-js = { workspace = true }
|
||||
# The commands' parameter schemas (schemas.rs).
|
||||
@@ -120,8 +122,13 @@ vectorcraft-testkit = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
# A variable font built in code (no font file is committed).
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
# How many times an open reads a PDF.
|
||||
# Holds the installed plug-ins steady while a test counts what a cache keeps.
|
||||
vectorcraft-plugins = { workspace = true, features = ["test-steady"] }
|
||||
# How many times an open reads a PDF, and the work its import takes.
|
||||
vectorcraft-pdf = { workspace = true, features = ["read-count"] }
|
||||
# The work `.ai` blends take to be checked and made live, and how many included EPS open checks
|
||||
# an open performs.
|
||||
vectorcraft-eps = { workspace = true, features = ["work-count"] }
|
||||
# How many times the symbol list is read to find symbols by name, and how many objects are
|
||||
# measured against locked artboards.
|
||||
vectorcraft-doc = { workspace = true, features = ["symbol-read-count", "locked-artboard-count"] }
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user