mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge main into fix/shape-control-canceled-tool-options-b-verify
This commit is contained in:
commit
ca262510c8
545 files changed
+32909
-3743
No files matched your search
@@ -0,0 +1,35 @@
|
||||
name: Cache prune
|
||||
|
||||
# A pass of the cache prune after every CI attempt on main. ci.yml's `cache prune` job prunes while
|
||||
# a run's jobs save their entries, but "Re-run failed jobs" re-runs only the failed jobs: a re-run
|
||||
# `cache warm` leg saves a new entry, and the prune job, which succeeded in the first attempt, does
|
||||
# not run again. The entry it replaced would stay until the next main run, and with it the cache
|
||||
# would be over its 10 GB budget, where GitHub evicts entries a run still needs. This runs once
|
||||
# after every attempt, re-runs and canceled runs included (craft-common-actions actions/cache-prune).
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [CI]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
cache-prune:
|
||||
name: cache prune
|
||||
# A fork's pull request from a branch named main also matches `branches`.
|
||||
if: github.event.workflow_run.event != 'pull_request'
|
||||
timeout-minutes: 10
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
# A failed pass warns; the next run's prune deletes what it missed.
|
||||
- name: Prune replaced cache entries
|
||||
uses: storytold/craft-common-actions/actions/cache-prune@main
|
||||
continue-on-error: true
|
||||
@@ -1,10 +1,14 @@
|
||||
name: CI
|
||||
|
||||
# Quality gates for every push to main and every pull request (`cargo xtask ci`), through the
|
||||
# suite's shared gate workflow in craft-common-actions.
|
||||
# suite's shared gate workflow in craft-common-actions. Every night the gate runs a cold build:
|
||||
# the safety net for the workspace crates it keeps between runs (`cache-workspace-crates`), and a
|
||||
# fresh start for that cache entry.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
schedule:
|
||||
- cron: "37 3 * * *"
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
@@ -23,7 +27,10 @@ jobs:
|
||||
with:
|
||||
# Same craft-fonts commit as release.yml.
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
timeout-minutes: 90
|
||||
# A cold `cache warm` leg (the nightly run, or any run after a toolchain or lockfile change)
|
||||
# took 90 minutes to reach its last three steps on 2026-11-27 and was canceled there; with
|
||||
# those steps and the save it needs about two hours.
|
||||
timeout-minutes: 150
|
||||
# The gate's test binaries carry no debug info and no symbols (CARGO_PROFILE_TEST_DEBUG=0,
|
||||
# CARGO_PROFILE_TEST_STRIP=symbols), as photocraft's do: linking ~100 test binaries with line
|
||||
# tables ran the hosted runner out of resources, and it stopped mid-link with "received a
|
||||
@@ -39,7 +46,68 @@ jobs:
|
||||
test-shards: 5
|
||||
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
|
||||
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
|
||||
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
|
||||
# `cache-prune` below deletes the one it replaced. The nightly run restores nothing and
|
||||
# builds everything from source.
|
||||
cache-workspace-crates: true
|
||||
cold-build: ${{ github.event_name == 'schedule' }}
|
||||
packages: >-
|
||||
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev
|
||||
libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
|
||||
libgl1-mesa-dev
|
||||
|
||||
# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache
|
||||
# budget. It runs beside the gate and prunes each time the `cache warm` leg finishes saving. A
|
||||
# failed prune warns instead of failing the run, and cache-prune.yml prunes again after every
|
||||
# attempt, re-runs of failed jobs included. `watch-minutes` is longer than the gate's
|
||||
# `timeout-minutes`, so the watch outlasts a cold `cache warm` leg.
|
||||
cache-prune:
|
||||
name: cache prune
|
||||
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 170
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Prune replaced cache entries
|
||||
uses: storytold/craft-common-actions/actions/cache-prune@main
|
||||
continue-on-error: true
|
||||
with:
|
||||
watch: true
|
||||
watch-minutes: 160
|
||||
saving-jobs: |
|
||||
^gate( / cache warm \(.*\))?$
|
||||
|
||||
# The nightly cold run never restores the rolling crates entry, so the old entry is only overlap
|
||||
# while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the
|
||||
# 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.
|
||||
cold-cache-clear:
|
||||
name: cold cache clear
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 200
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Delete the old rolling entries before the save
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: python3 scripts/ci-clear-rolling-cache.py
|
||||
@@ -3,13 +3,14 @@ name: Nightly check
|
||||
# The app-side Nightly pieces, checked without a feed run: the Python suites that read the archive,
|
||||
# plist and signing scripts, the workflow contracts, and (on Windows) the packaging and signing
|
||||
# PowerShell suites. The producer itself is .github/workflows/nightly.yml; the Apple-silicon bundle
|
||||
# is built and verified by nightly-macos.yml behind the `full-ci` label.
|
||||
# is built and verified by nightly-macos.yml behind the `full-ci` label. The same job also runs the
|
||||
# suite for scripts/ci-clear-rolling-cache.py, which ci.yml's nightly cold run calls.
|
||||
on:
|
||||
push:
|
||||
branches: [main, release]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"]
|
||||
pull_request:
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -34,6 +35,8 @@ jobs:
|
||||
persist-credentials: false
|
||||
- name: Run the synthetic suites
|
||||
run: python3 packaging/nightly-tests.py
|
||||
- name: Run the cold cache clear suite
|
||||
run: python3 scripts/ci-clear-rolling-cache-tests.py
|
||||
- name: Parse every nightly shell script
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -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
+219
-106
@@ -1217,7 +1217,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1258,7 +1258,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-affinity"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1269,9 +1269,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
@@ -1279,7 +1280,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1287,7 +1288,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1312,7 +1313,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
@@ -1330,7 +1331,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1348,7 +1349,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cdr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1357,7 +1358,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1365,7 +1366,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1374,12 +1375,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1399,17 +1400,28 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-control-protocol",
|
||||
"craft-platform",
|
||||
"getrandom 0.3.4",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1417,9 +1429,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
"craft-browse",
|
||||
@@ -1442,7 +1455,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1450,7 +1463,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1469,7 +1482,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1481,12 +1494,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1501,7 +1514,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1517,14 +1530,24 @@ dependencies = [
|
||||
"skrifa 0.47.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
"craft-font-catalog",
|
||||
"craft-font-os-windows",
|
||||
"flate2",
|
||||
"log",
|
||||
"ruzstd",
|
||||
@@ -1542,12 +1565,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"gif",
|
||||
]
|
||||
@@ -1555,7 +1578,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
@@ -1563,7 +1586,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1576,7 +1599,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"fixed_decimal",
|
||||
@@ -1604,7 +1627,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1617,7 +1640,7 @@ dependencies = [
|
||||
"hayro-jpeg2000",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"jpeg-encoder 0.7.1",
|
||||
"png 0.18.1",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
@@ -1631,7 +1654,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1649,7 +1672,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1657,7 +1680,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jxl"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"brotli-decompressor 5.0.3",
|
||||
"jixel",
|
||||
@@ -1668,7 +1691,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1683,7 +1706,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-layers"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -1697,7 +1720,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1715,7 +1738,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
@@ -1727,7 +1750,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1738,7 +1761,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
@@ -1748,7 +1771,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1764,7 +1787,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1776,7 +1799,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"async-io",
|
||||
@@ -1807,7 +1830,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1816,7 +1839,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1840,7 +1863,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -1851,7 +1874,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-eps",
|
||||
"flate2",
|
||||
@@ -1865,7 +1888,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -1876,7 +1899,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -1889,7 +1912,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1908,7 +1931,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -1925,7 +1948,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
@@ -1936,7 +1959,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-xml",
|
||||
@@ -1957,7 +1980,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1969,7 +1992,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-manager",
|
||||
@@ -1994,7 +2017,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2009,7 +2032,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2024,7 +2047,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2034,7 +2057,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2043,7 +2066,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2058,12 +2081,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2077,7 +2100,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -2093,7 +2116,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2131,7 +2154,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2142,7 +2165,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2160,7 +2183,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2181,7 +2204,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2202,7 +2225,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2221,13 +2244,15 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"craft-host",
|
||||
"craft-theme",
|
||||
"craft-ui",
|
||||
"dunce",
|
||||
"ed25519-dalek",
|
||||
"egui",
|
||||
"flate2",
|
||||
"image",
|
||||
@@ -2240,6 +2265,7 @@ dependencies = [
|
||||
"sha2 0.10.9",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"toml",
|
||||
"ureq",
|
||||
"verifysign",
|
||||
"winreg",
|
||||
@@ -2250,7 +2276,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -2261,7 +2287,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wayland"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"raw-window-handle",
|
||||
"wayland-backend",
|
||||
@@ -2271,7 +2297,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2282,7 +2308,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2290,7 +2316,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2322,7 +2348,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2424,6 +2450,33 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek"
|
||||
version = "4.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"curve25519-dalek-derive",
|
||||
"digest 0.10.7",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek-derive"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "data-url"
|
||||
version = "0.3.2"
|
||||
@@ -2640,16 +2693,40 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||
[[package]]
|
||||
name = "ecolor"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "2.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
|
||||
dependencies = [
|
||||
"pkcs8",
|
||||
"signature",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-dalek"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"ed25519",
|
||||
"serde",
|
||||
"sha2 0.10.9",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "eframe"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2684,7 +2761,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -2703,7 +2780,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2722,7 +2799,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-winit"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"accesskit_winit",
|
||||
"arboard",
|
||||
@@ -2747,7 +2824,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"egui",
|
||||
@@ -2761,7 +2838,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -2774,7 +2851,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_kittest"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"dify",
|
||||
"eframe",
|
||||
@@ -2800,7 +2877,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
[[package]]
|
||||
name = "emath"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -2881,7 +2958,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2907,7 +2984,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
@@ -3003,6 +3080,12 @@ version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
|
||||
[[package]]
|
||||
name = "filetime"
|
||||
version = "0.2.29"
|
||||
@@ -3620,7 +3703,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
@@ -3629,7 +3712,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3647,7 +3730,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3665,12 +3748,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4411,6 +4494,12 @@ version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f"
|
||||
|
||||
[[package]]
|
||||
name = "jpeg-encoder"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a0370574b86f7eca156b9f298392b5e69a23f8c86f3f865add60bbc2e79467a6"
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.106"
|
||||
@@ -4647,7 +4736,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -4804,7 +4893,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6013,6 +6102,16 @@ dependencies = [
|
||||
"system-deps",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
|
||||
dependencies = [
|
||||
"der",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.34"
|
||||
@@ -6356,6 +6455,9 @@ name = "rand_core"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
||||
dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
@@ -8493,7 +8595,7 @@ dependencies = [
|
||||
"craft-stream-codecs",
|
||||
"flate2",
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
"jpeg-encoder 0.6.1",
|
||||
"kurbo 0.13.1",
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -8617,6 +8719,7 @@ dependencies = [
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-effects",
|
||||
"vectorcraft-eps",
|
||||
"vectorcraft-geom 0.24.1",
|
||||
"vectorcraft-metafile",
|
||||
"vectorcraft-pathops 0.24.1",
|
||||
@@ -8749,7 +8852,7 @@ dependencies = [
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
"jpeg-encoder 0.6.1",
|
||||
"krilla",
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
@@ -8773,6 +8876,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"
|
||||
@@ -8806,7 +8919,7 @@ dependencies = [
|
||||
"craft-tiff",
|
||||
"flate2",
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
"jpeg-encoder 0.6.1",
|
||||
"log",
|
||||
"proptest",
|
||||
"serde_json",
|
||||
@@ -9175,9 +9288,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmi"
|
||||
version = "2.0.0"
|
||||
version = "2.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78693fcdd618e0fc34af59c6b8efa9ac5d58c68df940beff4bedddb6acfe7c27"
|
||||
checksum = "36dcb6cbd722c1575daf8c3063dd7ba1883fcd35b51fcbd377ae4f3371ac4dba"
|
||||
dependencies = [
|
||||
"spin",
|
||||
"wasmi_collections",
|
||||
@@ -9188,27 +9301,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmi_collections"
|
||||
version = "2.0.0"
|
||||
version = "2.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a8be2aa467cf2d29e96ff759472c36eeb44a3c81c67fc9cb76c9a24c519c557"
|
||||
checksum = "b62dc4c1a17f3294aa2b23ac39979e3b38f3ee6afe5673eea76b76902d11103b"
|
||||
dependencies = [
|
||||
"string-interner",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmi_core"
|
||||
version = "2.0.0"
|
||||
version = "2.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69372d5fda3ea3d1e0aa6603c7888110e0187e88ea17cd8fc2e2df0a0e1f37fa"
|
||||
checksum = "c19f6f7fcf32b9e12cebc8fec606fefac71af3d386bae1472e35d620b5471754"
|
||||
dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmi_ir"
|
||||
version = "2.0.0"
|
||||
version = "2.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f17b774caa13c618c7244f1ee51fe23c5e7b8538a471fa46d9949779758aed6"
|
||||
checksum = "14f9c115dfd2397700880a64d14161db3a4da0a11059fac39c6a7935eb8f6b36"
|
||||
dependencies = [
|
||||
"wasmi_core",
|
||||
]
|
||||
@@ -10578,14 +10691,14 @@ dependencies = [
|
||||
[[patch.unused]]
|
||||
name = "egui_demo_lib"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_inspection"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_system_font_provider"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
+48
-48
@@ -11,44 +11,44 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
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" }
|
||||
# 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 = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
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" }
|
||||
# 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 = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# 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 = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
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" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -191,25 +191,25 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
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" }
|
||||
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:
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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 = "b0d422cf0c23baccdaca314b916458a89c0952e0", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", 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;
|
||||
|
||||
@@ -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
|
||||
@@ -28,6 +30,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();
|
||||
}
|
||||
}
|
||||
@@ -156,7 +156,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.
|
||||
@@ -461,8 +461,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();
|
||||
}
|
||||
}
|
||||
+286
-144
@@ -4,10 +4,12 @@
|
||||
//! - Windows: text, SVG, PDF, PNG and an opaque bitmap (for apps that don't read PNG) in one go;
|
||||
//! Paste reads each of them and EPS, a bitmap as PNG, else as the device-independent bitmap that
|
||||
//! screenshots and most apps copy (`CF_DIBV5`, `CF_DIB`; the system makes them of a `CF_BITMAP`).
|
||||
//! - macOS and Linux: one format at a time, the text (a type-only copy's text or the SVG markup),
|
||||
//! else the PNG as a bitmap; Paste reads text and bitmaps, and on macOS the pasteboard's SVG, PDF
|
||||
//! and EPS as vector art (#1499) and its PNG or TIFF as they are, as screenshots copy them (on
|
||||
//! Linux arboard reads no other formats). On Wayland, arboard's data-control
|
||||
//! - macOS: text, SVG, PDF and PNG in one go: arboard writes the text, else the PNG as TIFF, and
|
||||
//! the other formats are added to the same pasteboard item ([`pasteboard_additions`]); Paste
|
||||
//! reads text and bitmaps, the pasteboard's SVG, PDF and EPS as vector art (#1499) and its PNG
|
||||
//! or TIFF as they are, as screenshots copy them.
|
||||
//! - Linux: one format at a time, the text (a type-only copy's text or the SVG markup), else the
|
||||
//! PNG as a bitmap; Paste reads text and bitmaps (arboard reads no other formats). On Wayland, arboard's data-control
|
||||
//! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps
|
||||
//! copied), falling back to X11 where the compositor lacks the protocol, and where there is no
|
||||
//! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection:
|
||||
@@ -137,6 +139,26 @@ fn pasteboard_types(mime: &str) -> &'static [(&'static str, &'static str)] {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pasteboard types and data Copy adds on macOS to the item arboard wrote (the text, else the
|
||||
/// PNG as TIFF), in the order of `flavors` (best first): the SVG, PDF and EPS under the first of
|
||||
/// their [`pasteboard_types`], and the PNG as `public.png`. Text, empty flavours and flavours the
|
||||
/// pasteboard has no type for are left out.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn pasteboard_additions(flavors: &[Flavor]) -> Vec<(&'static str, &[u8])> {
|
||||
flavors
|
||||
.iter()
|
||||
.filter(|f| !f.data.is_empty())
|
||||
.filter_map(|f| {
|
||||
let t = match engine_mime(&f.mime)? {
|
||||
TEXT => return None,
|
||||
PNG => "public.png",
|
||||
mime => pasteboard_types(mime).first()?.0,
|
||||
};
|
||||
Some((t, &f.data[..]))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Most pixels a side of a bitmap another app put on the clipboard (untrusted data).
|
||||
const MAX_SIDE: u32 = 32_768;
|
||||
|
||||
@@ -612,9 +634,46 @@ mod loads {
|
||||
|
||||
/// The longest a read waits for the clipboard's owner to send its data.
|
||||
pub(super) const LOAD_WAIT: Duration = Duration::from_secs(2);
|
||||
/// The longest a paste's bitmap read of arboard's waits for the app that copied, off the UI
|
||||
/// thread: the bitmap's transfer and its PNG decoding happen within the read. A paste waits as
|
||||
/// long, from when it was sent, for a read that got no answer in its wait, the core protocol's
|
||||
/// text read included. Text, file lists and the UI thread's bitmap check wait [`LOAD_WAIT`].
|
||||
pub(super) const IMAGE_WAIT: Duration = Duration::from_secs(10);
|
||||
/// What a read says once its worker has stopped.
|
||||
pub(super) const GONE: &str = "the clipboard's reader stopped";
|
||||
|
||||
/// How long the reads of a [`Loads`] wait for the clipboard's owner.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct Waits {
|
||||
/// A text or file-list read, the UI thread's bitmap check, and dropping an idle `Loads`.
|
||||
pub(super) load: Duration,
|
||||
/// A paste's bitmap read off the UI thread, and a paste's wait for a read that got no
|
||||
/// answer in its wait.
|
||||
pub(super) image: Duration,
|
||||
}
|
||||
|
||||
impl Waits {
|
||||
/// [`LOAD_WAIT`] and [`IMAGE_WAIT`].
|
||||
pub(super) const APP: Self = Self { load: LOAD_WAIT, image: IMAGE_WAIT };
|
||||
/// No limit: each wait ends when its answer comes or its worker stops.
|
||||
#[cfg(test)]
|
||||
pub(super) const UNTIL_ANSWERED: Self = Self { load: Duration::MAX, image: Duration::MAX };
|
||||
}
|
||||
|
||||
/// What is left at `now` of `limit` from `sent`; [`Duration::MAX`] (no limit) when the end is
|
||||
/// past the clock's range.
|
||||
pub(super) fn left(sent: Instant, limit: Duration, now: Instant) -> Duration {
|
||||
sent.checked_add(limit).map_or(Duration::MAX, |end| end.saturating_duration_since(now))
|
||||
}
|
||||
|
||||
/// What comes on `rx` within `wait`; a wait whose end is past the clock's range has no limit.
|
||||
fn recv_within<T>(rx: &mpsc::Receiver<T>, wait: Duration) -> Result<T, mpsc::RecvTimeoutError> {
|
||||
match Instant::now().checked_add(wait) {
|
||||
Some(_) => rx.recv_timeout(wait),
|
||||
None => rx.recv().map_err(mpsc::RecvTimeoutError::from),
|
||||
}
|
||||
}
|
||||
|
||||
/// Requests of type `R` answered with `A` on a worker thread.
|
||||
pub(super) struct Loads<R, A> {
|
||||
/// The worker's requests; the worker stops once this is dropped.
|
||||
@@ -623,6 +682,8 @@ mod loads {
|
||||
done: mpsc::Receiver<()>,
|
||||
/// How long after it was sent dropping `Loads` waits for an unanswered read to end.
|
||||
finish: Duration,
|
||||
/// How long its reads wait.
|
||||
waits: Waits,
|
||||
}
|
||||
|
||||
/// Where requests go to a [`Loads`] worker.
|
||||
@@ -685,18 +746,18 @@ mod loads {
|
||||
}
|
||||
}
|
||||
|
||||
/// When dropping `Loads` stops waiting for its worker: `finish` after the unanswered read
|
||||
/// `pending` was sent (at once if that time has passed), and with no read unanswered
|
||||
/// [`LOAD_WAIT`] from `now` at most (an idle worker ends at once).
|
||||
fn stop_by(pending: Option<Instant>, now: Instant, finish: Duration) -> Instant {
|
||||
pending.map_or(now + LOAD_WAIT, |sent| sent + finish)
|
||||
/// How long, from `now`, dropping `Loads` waits for its worker: until `finish` after the
|
||||
/// unanswered read `pending` was sent (not at all if that time has passed), and with no read
|
||||
/// unanswered `idle` at most (an idle worker ends at once).
|
||||
fn stop_wait(pending: Option<Instant>, now: Instant, finish: Duration, idle: Duration) -> Duration {
|
||||
pending.map_or(idle, |sent| left(sent, finish, now))
|
||||
}
|
||||
|
||||
impl<R: Send + 'static, A: Send + 'static> Loads<R, A> {
|
||||
/// A worker thread named `name` that answers each request with `load`; dropping the result
|
||||
/// waits up to `finish` after an unanswered read was sent for that read to end. None when the
|
||||
/// worker can't start.
|
||||
pub(super) fn spawn(name: &str, finish: Duration, mut load: impl FnMut(R) -> A + Send + 'static) -> Option<Self> {
|
||||
/// A worker thread named `name` that answers each request with `load`, whose reads wait as
|
||||
/// `waits` says; dropping the result waits up to `finish` after an unanswered read was sent
|
||||
/// for that read to end. None when the worker can't start.
|
||||
pub(super) fn spawn(name: &str, finish: Duration, waits: Waits, mut load: impl FnMut(R) -> A + Send + 'static) -> Option<Self> {
|
||||
let (requests, asked) = mpsc::channel::<(R, mpsc::Sender<A>)>();
|
||||
let (alive, done) = mpsc::channel::<()>();
|
||||
let open = Arc::new(AtomicUsize::new(0));
|
||||
@@ -714,7 +775,12 @@ mod loads {
|
||||
drop(alive);
|
||||
};
|
||||
std::thread::Builder::new().name(name.into()).spawn(work).ok()?;
|
||||
Some(Self { line: Arc::new(Line { requests, open, sent: Mutex::default() }), done, finish })
|
||||
Some(Self { line: Arc::new(Line { requests, open, sent: Mutex::default() }), done, finish, waits })
|
||||
}
|
||||
|
||||
/// How long its reads wait.
|
||||
pub(super) fn waits(&self) -> Waits {
|
||||
self.waits
|
||||
}
|
||||
|
||||
/// `request` sent to the worker; its answer comes on the channel returned, for
|
||||
@@ -741,9 +807,10 @@ mod loads {
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer that comes on `answer` ([`Loads::ask`]), or why there is none, after `wait` at most.
|
||||
/// The answer that comes on `answer` ([`Loads::ask`]), or why there is none, after `wait` at most
|
||||
/// ([`Duration::MAX`]: no limit).
|
||||
pub(super) fn wait_for_answer<A>(answer: &mpsc::Receiver<A>, wait: Duration) -> Result<A, String> {
|
||||
match answer.recv_timeout(wait) {
|
||||
match recv_within(answer, wait) {
|
||||
Ok(answer) => Ok(answer),
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => Err(format!("the clipboard's owner didn't send its data within {wait:?}")),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => Err(GONE.into()),
|
||||
@@ -751,16 +818,16 @@ mod loads {
|
||||
}
|
||||
|
||||
impl<R, A> Drop for Loads<R, A> {
|
||||
/// Stops the worker and waits until it has let go of what its `load` holds, until
|
||||
/// [`stop_by`] at most: on X11 the last arboard handle dropped hands what the app copied to
|
||||
/// the clipboard manager, and the app's own handle must be that one.
|
||||
/// Stops the worker and waits until it has let go of what its `load` holds, as long as
|
||||
/// [`stop_wait`] says at most: on X11 the last arboard handle dropped hands what the app
|
||||
/// copied to the clipboard manager, and the app's own handle must be that one.
|
||||
fn drop(&mut self) {
|
||||
// No `Asker` sends after this, and one that holds the line lets go once it has sent.
|
||||
let pending = self.line.close();
|
||||
drop(std::mem::replace(&mut self.line, Line::dead()));
|
||||
let end = stop_by(pending, Instant::now(), self.finish);
|
||||
// Nothing is sent on `done`: this ends when the worker drops `alive`, or at `end`.
|
||||
let _ = self.done.recv_timeout(end.saturating_duration_since(Instant::now()));
|
||||
let wait = stop_wait(pending, Instant::now(), self.finish, self.waits.load);
|
||||
// Nothing is sent on `done`: this ends when the worker drops `alive`, or after `wait`.
|
||||
let _ = recv_within(&self.done, wait);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -770,18 +837,38 @@ mod loads {
|
||||
|
||||
use super::*;
|
||||
|
||||
/// No limit: a wait ends when its answer comes.
|
||||
const UNTIL_ANSWERED: Duration = Duration::MAX;
|
||||
|
||||
#[test]
|
||||
fn a_read_that_answers_in_time_gives_the_text() {
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, |()| "<svg/>".to_string()).unwrap();
|
||||
assert_eq!(loads.get((), Duration::from_secs(5)), Ok("<svg/>".to_string()));
|
||||
assert_eq!(loads.get((), Duration::from_secs(5)), Ok("<svg/>".to_string()));
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| "<svg/>".to_string()).unwrap();
|
||||
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok("<svg/>".to_string()));
|
||||
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok("<svg/>".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wait_with_no_limit_ends_when_its_answer_comes() {
|
||||
let (reply, answer) = mpsc::channel();
|
||||
let late = std::thread::spawn(move || reply.send(7));
|
||||
assert_eq!(wait_for_answer(&answer, UNTIL_ANSWERED), Ok(7));
|
||||
assert_eq!(late.join().ok(), Some(Ok(())));
|
||||
// A worker that stops without answering ends the wait too.
|
||||
let (reply, answer) = mpsc::channel::<u8>();
|
||||
drop(reply);
|
||||
assert_eq!(wait_for_answer(&answer, UNTIL_ANSWERED), Err(GONE.to_string()));
|
||||
// Limits from a read's send: what is left, none once it is over, no limit past the clock.
|
||||
let now = Instant::now();
|
||||
assert_eq!(left(now, Duration::from_secs(10), now + Duration::from_secs(3)), Duration::from_secs(7));
|
||||
assert_eq!(left(now, Duration::from_secs(10), now + Duration::from_secs(20)), Duration::ZERO);
|
||||
assert_eq!(left(now, Duration::MAX, now), Duration::MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_owner_that_never_answers_holds_the_worker_not_the_caller() {
|
||||
let (release, gate) = mpsc::channel::<()>();
|
||||
let mut calls = 0;
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, move |()| {
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |()| {
|
||||
calls += 1;
|
||||
if calls == 1 {
|
||||
// The first owner sends nothing until released.
|
||||
@@ -793,11 +880,11 @@ mod loads {
|
||||
.unwrap();
|
||||
assert!(loads.get((), Duration::ZERO).is_err(), "the first read times out");
|
||||
// While it is unanswered, a read doesn't queue behind it or wait at all.
|
||||
assert!(loads.get((), Duration::from_secs(600)).is_err());
|
||||
assert!(loads.get((), UNTIL_ANSWERED).is_err());
|
||||
release.send(()).unwrap();
|
||||
// Once the late answer is in, it is dropped and a new read is made.
|
||||
let text = loop {
|
||||
match loads.get((), Duration::from_secs(600)) {
|
||||
match loads.get((), UNTIL_ANSWERED) {
|
||||
Ok(text) => break text,
|
||||
Err(why) => {
|
||||
// The late answer isn't in yet.
|
||||
@@ -811,17 +898,17 @@ mod loads {
|
||||
|
||||
#[test]
|
||||
fn a_read_after_the_worker_stops_says_so() {
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, |()| String::new()).unwrap();
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| String::new()).unwrap();
|
||||
// The worker ends when its requests stop: cut them off by hand.
|
||||
drop(std::mem::replace(&mut loads.line, Line::dead()));
|
||||
assert_eq!(loads.get((), Duration::from_millis(50)), Err(GONE.to_string()));
|
||||
assert_eq!(loads.get((), UNTIL_ANSWERED), Err(GONE.to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_threads_reads_stop_with_the_reads() {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, |()| 1).unwrap();
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| 1).unwrap();
|
||||
let asker = loads.asker();
|
||||
assert_eq!(asker.ask(()).and_then(|a| wait_for_answer(&a, Duration::from_secs(600))), Ok(1));
|
||||
assert_eq!(asker.ask(()).and_then(|a| wait_for_answer(&a, UNTIL_ANSWERED)), Ok(1));
|
||||
drop(loads);
|
||||
assert_eq!(asker.ask(()).err(), Some(GONE.to_string()));
|
||||
// Closed while an asker still holds the line: nothing more is sent.
|
||||
@@ -833,7 +920,7 @@ mod loads {
|
||||
#[test]
|
||||
fn an_answer_waited_for_on_another_thread_holds_back_the_next_read() {
|
||||
let (release, gate) = mpsc::channel::<()>();
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, move |n: u32| {
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |n: u32| {
|
||||
if n == 1 {
|
||||
let _ = gate.recv();
|
||||
}
|
||||
@@ -842,20 +929,21 @@ mod loads {
|
||||
.unwrap();
|
||||
let answer = loads.ask(1).unwrap();
|
||||
// The caller doesn't wait: the answer is waited for wherever the channel goes.
|
||||
let waiter = std::thread::spawn(move || wait_for_answer(&answer, Duration::from_secs(600)));
|
||||
let waiter = std::thread::spawn(move || wait_for_answer(&answer, UNTIL_ANSWERED));
|
||||
// Until it comes, a read fails at once instead of queuing behind it.
|
||||
assert!(loads.get(2, Duration::from_secs(600)).is_err());
|
||||
assert!(loads.get(2, UNTIL_ANSWERED).is_err());
|
||||
release.send(()).unwrap();
|
||||
assert_eq!(waiter.join().ok(), Some(Ok(1)));
|
||||
assert_eq!(loads.get(3, Duration::from_secs(600)), Ok(3));
|
||||
assert_eq!(loads.get(3, UNTIL_ANSWERED), Ok(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_the_reads_waits_until_the_worker_lets_go_of_its_clipboard() {
|
||||
let clipboard = Arc::new(());
|
||||
let held = clipboard.clone();
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, move |()| Arc::strong_count(&held)).unwrap();
|
||||
assert_eq!(loads.get((), Duration::from_secs(600)), Ok(2));
|
||||
// With no limit on the idle wait, the drop ends only once the worker has let go.
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |()| Arc::strong_count(&held)).unwrap();
|
||||
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok(2));
|
||||
drop(loads);
|
||||
assert_eq!(Arc::strong_count(&clipboard), 1, "the worker's handle is gone before the app's");
|
||||
}
|
||||
@@ -865,12 +953,12 @@ mod loads {
|
||||
let now = Instant::now();
|
||||
let limit = Duration::from_secs(25);
|
||||
// No read unanswered: the idle worker ends at once, LOAD_WAIT is only the bound.
|
||||
assert_eq!(stop_by(None, now, limit), now + LOAD_WAIT);
|
||||
assert_eq!(stop_wait(None, now, limit, LOAD_WAIT), LOAD_WAIT);
|
||||
// A read sent 2 s ago that timed out: wait for it until 25 s after it was sent.
|
||||
assert_eq!(stop_by(Some(now - Duration::from_secs(2)), now, limit), now + Duration::from_secs(23));
|
||||
assert_eq!(stop_wait(Some(now - Duration::from_secs(2)), now, limit, LOAD_WAIT), Duration::from_secs(23));
|
||||
// Its limit already over, or no limit (data-control, the core protocol): no wait.
|
||||
assert!(stop_by(Some(now - Duration::from_secs(30)), now, limit) <= now);
|
||||
assert_eq!(stop_by(Some(now), now, Duration::ZERO), now);
|
||||
assert_eq!(stop_wait(Some(now - Duration::from_secs(30)), now, limit, LOAD_WAIT), Duration::ZERO);
|
||||
assert_eq!(stop_wait(Some(now), now, Duration::ZERO, LOAD_WAIT), Duration::ZERO);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -885,6 +973,8 @@ mod portable {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
use super::loads::Waits;
|
||||
use super::{
|
||||
BITMAP, ClipboardBackend, ClipboardError, ClipboardImage, ClipboardRead, Flavor, Flavour, LaterFlavor, PNG, TEXT, copied_file, decode_png,
|
||||
engine_mimes, png_flavour, read_flavor, read_image_flavor, read_later_flavor, takes_files,
|
||||
@@ -991,28 +1081,21 @@ mod portable {
|
||||
reads.get(request, wait).unwrap_or_else(|why| Answer::failed(request, why))
|
||||
}
|
||||
|
||||
/// The longest a paste's bitmap read of arboard's waits for the app that copied, off the UI
|
||||
/// thread: the bitmap's transfer and its PNG decoding happen within the read. A paste waits as
|
||||
/// long, from when it was sent, for a read that got no answer in its wait, the core protocol's
|
||||
/// text read included. Text, file lists and the UI thread's bitmap check wait
|
||||
/// [`LOAD_WAIT`](super::loads::LOAD_WAIT).
|
||||
/// How long a read of `request` waits for the app that copied: `waits.image` for a bitmap,
|
||||
/// `waits.load` otherwise.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
const IMAGE_WAIT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// How long a read of `request` waits for the app that copied.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
fn wait_for(request: Request) -> Duration {
|
||||
fn wait_for(waits: Waits, request: Request) -> Duration {
|
||||
match request {
|
||||
Request::Image => IMAGE_WAIT,
|
||||
Request::Text | Request::Files => super::loads::LOAD_WAIT,
|
||||
Request::Image => waits.image,
|
||||
Request::Text | Request::Files => waits.load,
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a paste's read of `request` after a late answer waits at `now`: as long as any read
|
||||
/// of `request`, or until [`IMAGE_WAIT`] after the unanswered read was `sent` when that is later.
|
||||
/// of `request`, or until `waits.image` after the unanswered read was `sent` when that is later.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
fn follow_up_wait(request: Request, sent: Instant, now: Instant) -> Duration {
|
||||
wait_for(request).max((sent + IMAGE_WAIT).saturating_duration_since(now))
|
||||
fn follow_up_wait(waits: Waits, request: Request, sent: Instant, now: Instant) -> Duration {
|
||||
wait_for(waits, request).max(super::loads::left(sent, waits.image, now))
|
||||
}
|
||||
|
||||
/// The longest an X11 read of arboard's lasts while the owner sends nothing: a text read tries
|
||||
@@ -1063,6 +1146,8 @@ mod portable {
|
||||
sent: Instant,
|
||||
/// The worker, for the paste's other reads.
|
||||
reads: super::loads::Asker<Request, Answer>,
|
||||
/// How long the worker's reads wait.
|
||||
waits: Waits,
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
@@ -1078,7 +1163,8 @@ mod portable {
|
||||
}
|
||||
|
||||
/// What a paste of one of `mimes` takes, once this read's answer comes, waiting for it until
|
||||
/// [`IMAGE_WAIT`] after it was sent, as long as a paste's bitmap read waits. Once it comes,
|
||||
/// `waits.image` ([`IMAGE_WAIT`](super::loads::IMAGE_WAIT)) after it was sent, as long as a
|
||||
/// paste's bitmap read waits. Once it comes,
|
||||
/// the same read is made again, since the clipboard may have changed hands meanwhile.
|
||||
/// `None`, so the paste takes the internal clipboard, when that answer doesn't come or the
|
||||
/// new one is what `ours` put on the clipboard. Otherwise the clipboard is read as
|
||||
@@ -1088,12 +1174,12 @@ mod portable {
|
||||
/// names a picture (`adopt_system_clipboard_or_defer` in `vectorcraft-ui-egui`). Those reads
|
||||
/// wait as [`follow_up_wait`] says.
|
||||
fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
let wait = (self.sent + IMAGE_WAIT).saturating_duration_since(Instant::now());
|
||||
let wait = super::loads::left(self.sent, self.waits.image, Instant::now());
|
||||
super::loads::wait_for_answer(&self.answer, wait).ok()?;
|
||||
let fresh = |request: Request| {
|
||||
self.reads
|
||||
.ask(request)
|
||||
.and_then(|a| super::loads::wait_for_answer(&a, follow_up_wait(request, self.sent, Instant::now())))
|
||||
.and_then(|a| super::loads::wait_for_answer(&a, follow_up_wait(self.waits, request, self.sent, Instant::now())))
|
||||
.unwrap_or_else(|why| Answer::failed(request, why))
|
||||
};
|
||||
// The late answer may come from an app that lost the clipboard while it was awaited.
|
||||
@@ -1139,14 +1225,15 @@ mod portable {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
impl Late {
|
||||
/// What a paste of one of `mimes` takes once the answer comes ([`Unanswered::paste`]). The
|
||||
/// core protocol's answer is waited for as long, until [`IMAGE_WAIT`] after its read was
|
||||
/// sent; then the clipboard is read again and pasted as at once, unless it holds the Copy
|
||||
/// made here ([`super::wayland::Unanswered::paste`]).
|
||||
/// core protocol's answer is waited for as long, until
|
||||
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) after its read was sent; then the clipboard is
|
||||
/// read again and pasted as at once, unless it holds the Copy made here
|
||||
/// ([`super::wayland::Unanswered::paste`]).
|
||||
fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
match self {
|
||||
Self::Arboard(unanswered) => unanswered.paste(ours, mimes),
|
||||
#[cfg(target_os = "linux")]
|
||||
Self::Wayland(unanswered) => unanswered.paste(mimes, IMAGE_WAIT),
|
||||
Self::Wayland(unanswered) => unanswered.paste(mimes),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1163,8 +1250,9 @@ mod portable {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
{
|
||||
let mut reader = arboard::Clipboard::new().map_err(|e| e.to_string())?;
|
||||
let reads = super::loads::Loads::spawn("clipboard-read", finish(on_data_control()), move |request| answer(&mut reader, request))
|
||||
.ok_or("the clipboard's reader didn't start")?;
|
||||
let reads =
|
||||
super::loads::Loads::spawn("clipboard-read", finish(on_data_control()), Waits::APP, move |request| answer(&mut reader, request))
|
||||
.ok_or("the clipboard's reader didn't start")?;
|
||||
Ok(Self { reads, unanswered: None, cb })
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))]
|
||||
@@ -1181,13 +1269,13 @@ mod portable {
|
||||
impl<C> Arboard<C> {
|
||||
/// Reads on the worker; the write handle `C` is not used.
|
||||
fn read(&mut self, request: Request) -> Answer {
|
||||
self.read_waiting(request, wait_for(request))
|
||||
self.read_waiting(request, wait_for(self.reads.waits(), request))
|
||||
}
|
||||
|
||||
/// A bitmap read on the worker that waits [`LOAD_WAIT`](super::loads::LOAD_WAIT) at most, for
|
||||
/// a check on the UI thread.
|
||||
fn image_now(&mut self) -> Result<arboard::ImageData<'static>, String> {
|
||||
self.read_waiting(Request::Image, super::loads::LOAD_WAIT).image()
|
||||
self.read_waiting(Request::Image, self.reads.waits().load).image()
|
||||
}
|
||||
|
||||
/// `request` read on the worker, waiting `wait` at most. A read that gets no answer in that
|
||||
@@ -1202,7 +1290,7 @@ mod portable {
|
||||
Ok(answer) => answer,
|
||||
Err(why) => {
|
||||
if why != super::loads::GONE {
|
||||
self.unanswered = Some(Unanswered { request, answer, sent, reads: self.reads.asker() });
|
||||
self.unanswered = Some(Unanswered { request, answer, sent, reads: self.reads.asker(), waits: self.reads.waits() });
|
||||
}
|
||||
Answer::failed(request, why)
|
||||
}
|
||||
@@ -1217,11 +1305,13 @@ mod portable {
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// A bitmap read sent to the worker now; the work returned waits [`IMAGE_WAIT`] at most for
|
||||
/// it, so the caller can wait off the UI thread. Err when the read can't be sent.
|
||||
/// A bitmap read sent to the worker now; the work returned waits
|
||||
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most for it, so the caller can wait off the UI
|
||||
/// thread. Err when the read can't be sent.
|
||||
fn image_later(&mut self) -> Result<ImageWork, String> {
|
||||
let wait = self.reads.waits().image;
|
||||
let answer = self.ask(Request::Image)?;
|
||||
Ok(Box::new(move || super::loads::wait_for_answer(&answer, IMAGE_WAIT).and_then(Answer::image)))
|
||||
Ok(Box::new(move || super::loads::wait_for_answer(&answer, wait).and_then(Answer::image)))
|
||||
}
|
||||
|
||||
/// The read that got no answer in its wait, while its answer has still not come and a paste
|
||||
@@ -1503,12 +1593,12 @@ mod portable {
|
||||
/// Text and copied files are read here, and work that reads arboard's image comes back. On
|
||||
/// the Wayland core protocol the copied files, else the first of `mimes` the clipboard
|
||||
/// offers, is read: text here, file lists, SVG and PNG by the work that comes back, which
|
||||
/// waits [`IMAGE_WAIT`] at most.
|
||||
/// waits [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most.
|
||||
fn read_now_or_later(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
|
||||
let cb = self.cb(Asker::User).ok()?;
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Backend::Wayland(cb) = cb {
|
||||
return cb.read(mimes, IMAGE_WAIT);
|
||||
return cb.read(mimes);
|
||||
}
|
||||
if let Some(f) = copied_file(cb.file_list(), mimes) {
|
||||
return Some(ClipboardRead::Now(f));
|
||||
@@ -1554,7 +1644,8 @@ mod portable {
|
||||
/// arboard takes the text, else the PNG as a bitmap; the Wayland core protocol offers the
|
||||
/// SVG, PNG and text together ([`DataClipboard::copy`](super::wayland::DataClipboard::copy)).
|
||||
/// The index answered is the flavour that went out: the text, else the PNG, and on the
|
||||
/// core protocol the first flavour it offers.
|
||||
/// core protocol the first flavour it offers. On macOS the other flavours are then added
|
||||
/// to the pasteboard item arboard wrote ([`pasteboard_additions`](super::pasteboard_additions)).
|
||||
fn write(&mut self, flavors: &[Flavor]) -> Result<usize, ClipboardError> {
|
||||
let cb = self.cb(Asker::User).map_err(ClipboardError::Other)?;
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -1591,6 +1682,8 @@ mod portable {
|
||||
// What a read got late was on the clipboard before this write.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
cb.forget_unanswered();
|
||||
#[cfg(target_os = "macos")]
|
||||
super::mac::add(&super::pasteboard_additions(flavors));
|
||||
self.ours = ours;
|
||||
Ok(wrote)
|
||||
}
|
||||
@@ -1654,9 +1747,12 @@ mod portable {
|
||||
mod tests {
|
||||
use std::cell::Cell;
|
||||
|
||||
use super::super::loads::Loads;
|
||||
use super::super::loads::{Loads, Waits};
|
||||
use super::*;
|
||||
|
||||
/// No limit: a wait ends when its answer comes.
|
||||
const UNTIL_ANSWERED: Duration = Duration::MAX;
|
||||
|
||||
/// A clock that starts now and moves only when told.
|
||||
struct Clock(Cell<Instant>);
|
||||
|
||||
@@ -1780,27 +1876,27 @@ mod portable {
|
||||
fn reads_return_while_the_clipboard_owner_sends_nothing() {
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
// The app that copied never sends its data until released.
|
||||
let mut reads = Loads::spawn("test", Duration::ZERO, move |request| {
|
||||
let mut reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| {
|
||||
let _ = gate.recv();
|
||||
Answer::failed(request, "late".into())
|
||||
})
|
||||
.unwrap();
|
||||
// Copy's look at the text, Paste's file list and its bitmap: none waits for the owner.
|
||||
assert!(read_within(&mut reads, Request::Text, Duration::ZERO).text().is_err());
|
||||
assert!(read_within(&mut reads, Request::Files, Duration::from_secs(600)).files().is_empty());
|
||||
assert!(read_within(&mut reads, Request::Image, Duration::from_secs(600)).image().is_err());
|
||||
assert!(read_within(&mut reads, Request::Files, UNTIL_ANSWERED).files().is_empty());
|
||||
assert!(read_within(&mut reads, Request::Image, UNTIL_ANSWERED).image().is_err());
|
||||
drop(release);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_read_takes_its_own_answer() {
|
||||
let mut reads = Loads::spawn("test", Duration::ZERO, |request| match request {
|
||||
let mut reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |request| match request {
|
||||
Request::Text => Answer::Text(Ok("<svg/>".into())),
|
||||
Request::Image => Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) })),
|
||||
Request::Files => Answer::Files(vec![PathBuf::from("art.svg")]),
|
||||
})
|
||||
.unwrap();
|
||||
let wait = Duration::from_secs(600);
|
||||
let wait = UNTIL_ANSWERED;
|
||||
assert_eq!(read_within(&mut reads, Request::Text, wait).text(), Ok("<svg/>".to_string()));
|
||||
assert_eq!(read_within(&mut reads, Request::Image, wait).image().map(|i| (i.width, i.height)), Ok((2, 1)));
|
||||
assert_eq!(read_within(&mut reads, Request::Files, wait).files(), [PathBuf::from("art.svg")]);
|
||||
@@ -1847,7 +1943,8 @@ mod portable {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn arboards_reads_run_on_its_reader_and_wait_by_kind() {
|
||||
let reads = Loads::spawn("test", Duration::ZERO, |request| match request {
|
||||
// The reads wait for their answer however long it takes, so the answer decides the result.
|
||||
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |request| match request {
|
||||
Request::Text => Answer::Text(Ok("read on the worker".into())),
|
||||
_ => Answer::failed(request, "not asked".into()),
|
||||
})
|
||||
@@ -1855,15 +1952,18 @@ mod portable {
|
||||
// `()` for writes: a read made through the write handle wouldn't build.
|
||||
let mut cb = Arboard { reads, unanswered: None, cb: () };
|
||||
assert_eq!(cb.read(Request::Text).text(), Ok("read on the worker".to_string()));
|
||||
assert_eq!(wait_for(Request::Text), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(wait_for(Request::Files), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(wait_for(Request::Image), Duration::from_secs(10));
|
||||
let app = Waits::APP;
|
||||
assert_eq!(wait_for(app, Request::Text), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(wait_for(app, Request::Files), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(wait_for(app, Request::Image), Duration::from_secs(10));
|
||||
// A paste's reads after a late answer wait until 10 s after the unanswered read was
|
||||
// sent, and never less than any read of their kind.
|
||||
let sent = Instant::now();
|
||||
assert_eq!(follow_up_wait(Request::Text, sent, sent + Duration::from_secs(3)), Duration::from_secs(7));
|
||||
assert_eq!(follow_up_wait(Request::Files, sent, sent + Duration::from_secs(9)), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(follow_up_wait(Request::Image, sent, sent + Duration::from_secs(20)), IMAGE_WAIT);
|
||||
assert_eq!(follow_up_wait(app, Request::Text, sent, sent + Duration::from_secs(3)), Duration::from_secs(7));
|
||||
assert_eq!(follow_up_wait(app, Request::Files, sent, sent + Duration::from_secs(9)), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(follow_up_wait(app, Request::Image, sent, sent + Duration::from_secs(20)), super::super::loads::IMAGE_WAIT);
|
||||
// With no limit, the follow-up reads have none either.
|
||||
assert_eq!(follow_up_wait(Waits::UNTIL_ANSWERED, Request::Text, sent, sent + Duration::from_secs(20)), Duration::MAX);
|
||||
// X11 waits for an unanswered read when the clipboard closes; data-control doesn't.
|
||||
assert_eq!(finish(false), X11_READ_LIMIT);
|
||||
assert_eq!(finish(true), Duration::ZERO);
|
||||
@@ -1884,7 +1984,7 @@ mod portable {
|
||||
fn a_bitmap_paste_waits_for_the_owner_off_the_ui_thread() {
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
// The app that copied sends its bitmap only when released.
|
||||
let reads = Loads::spawn("test", Duration::ZERO, move |request| match request {
|
||||
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| match request {
|
||||
Request::Image => {
|
||||
let _ = gate.recv();
|
||||
Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) }))
|
||||
@@ -1903,11 +2003,12 @@ mod portable {
|
||||
}
|
||||
|
||||
/// An arboard clipboard whose owner answers each read with `answer` only once the sender
|
||||
/// returned is used or dropped.
|
||||
/// returned is used or dropped. Its reads wait for their answers with no limit: the
|
||||
/// release decides when a paste gets its answer.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
fn slow_owner(answer: impl Fn(Request) -> Answer + Send + 'static) -> (Arboard<()>, std::sync::mpsc::Sender<()>) {
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
let reads = Loads::spawn("test", Duration::ZERO, move |request| {
|
||||
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| {
|
||||
let _ = gate.recv();
|
||||
answer(request)
|
||||
})
|
||||
@@ -2028,10 +2129,10 @@ mod portable {
|
||||
|
||||
/// Core protocol reads of a clipboard offering `types`, whose owner answers each read
|
||||
/// of a text type with `text` and of `image/png` with `png`, only once the sender
|
||||
/// returned is used or dropped.
|
||||
/// returned is used or dropped. The reads wait for their answers with no limit.
|
||||
fn slow_owner(types: &[&str], text: &'static str, png: &'static [u8]) -> (Reads, Arc<Mutex<Seen>>, std::sync::mpsc::Sender<()>) {
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
|
||||
let _ = gate.recv();
|
||||
Ok(if wire == PNG { png.to_vec() } else { text.as_bytes().to_vec() })
|
||||
})
|
||||
@@ -2047,7 +2148,7 @@ mod portable {
|
||||
// in its wait (2 s on the UI thread, none here).
|
||||
assert!(reads.text(Duration::ZERO).is_err());
|
||||
// The paste's own read fails at once while the owner hasn't answered.
|
||||
assert!(reads.text(Duration::from_secs(600)).is_err());
|
||||
assert!(reads.text(UNTIL_ANSWERED).is_err());
|
||||
// A paste of a bitmap alone can't take text: the read stays kept.
|
||||
assert!(reads.unanswered(&[BITMAP]).is_none());
|
||||
let late = Late::Wayland(reads.unanswered(&PASTE_ORDER).expect("the check's read is kept for the paste"));
|
||||
@@ -2083,7 +2184,7 @@ mod portable {
|
||||
// again and takes the new owner's text.
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
let mut texts_read = 0;
|
||||
let loads = Loads::spawn("test", Duration::ZERO, move |_: String| {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |_: String| {
|
||||
let _ = gate.recv();
|
||||
texts_read += 1;
|
||||
Ok(if texts_read == 1 { "old owner" } else { "new owner" }.as_bytes().to_vec())
|
||||
@@ -2149,7 +2250,7 @@ mod wayland {
|
||||
use wayland_client::protocol::wl_seat::{self, WlSeat};
|
||||
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum};
|
||||
|
||||
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer};
|
||||
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, Waits, left, wait_for_answer};
|
||||
use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, takes_files, uri_list_paths};
|
||||
|
||||
/// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK
|
||||
@@ -2445,16 +2546,18 @@ mod wayland {
|
||||
/// The worker, for the reads made once the answer comes.
|
||||
reads: Asker<String, Got>,
|
||||
seen: Arc<Mutex<Seen>>,
|
||||
/// How long the worker's reads wait.
|
||||
waits: Waits,
|
||||
}
|
||||
|
||||
impl Unanswered {
|
||||
/// What a paste of one of `mimes` takes once this read's answer comes, waiting for it until
|
||||
/// `limit` after the read was sent: the clipboard read again as [`pick_pasted`] reads it,
|
||||
/// each read waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may
|
||||
/// have lost the clipboard meanwhile. None when the answer doesn't come or the clipboard holds this
|
||||
/// connection's Copy.
|
||||
pub(super) fn paste(self, mimes: &[&'static str], limit: Duration) -> Option<Flavour> {
|
||||
let left = |now: Instant| (self.sent + limit).saturating_duration_since(now);
|
||||
/// `waits.image` after the read was sent: the clipboard read again as [`pick_pasted`] reads
|
||||
/// it, each read waiting as long, `waits.load` ([`LOAD_WAIT`]) at least, since the app that
|
||||
/// answers late may have lost the clipboard meanwhile. None when the answer doesn't come or
|
||||
/// the clipboard holds this connection's Copy.
|
||||
pub(super) fn paste(self, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
let left = |now: Instant| left(self.sent, self.waits.image, now);
|
||||
let _late = wait_for_answer(&self.answer, left(Instant::now())).ok()?;
|
||||
let offered = {
|
||||
let seen = lock(&self.seen);
|
||||
@@ -2464,7 +2567,7 @@ mod wayland {
|
||||
seen.offered.clone()
|
||||
};
|
||||
pick_pasted(&offered, mimes, |wire| {
|
||||
wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok()
|
||||
wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, self.waits.load.max(left(Instant::now()))).ok()?.ok()
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2491,7 +2594,8 @@ mod wayland {
|
||||
Ok(got) => Ok(flavour(TEXT, got?).map(|f| String::from_utf8_lossy(&f.data).into_owned()).unwrap_or_default()),
|
||||
Err(why) => {
|
||||
if why != GONE {
|
||||
self.unanswered = Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone() });
|
||||
self.unanswered =
|
||||
Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone(), waits: self.loads.waits() });
|
||||
}
|
||||
Err(why)
|
||||
}
|
||||
@@ -2501,12 +2605,13 @@ mod wayland {
|
||||
/// What a paste of one of `mimes` reads: the files a file manager copied, else the first of
|
||||
/// `mimes` the clipboard offers. A file list is asked for here and read, with the files,
|
||||
/// by the work that comes back, which pastes the first file that is art ([`copied`]) and
|
||||
/// else reads `mimes` as [`pick`] does. Text is read here, [`LOAD_WAIT`] at most, and
|
||||
/// pasted unless it is empty; SVG and PNG are asked for here and waited for, `wait` at most,
|
||||
/// by the work that comes back. When that read fails or is empty, the work reads the rest
|
||||
/// of `mimes` as [`pick`] does. Each read the work makes after the first waits until `wait`
|
||||
/// after the first was sent, [`LOAD_WAIT`] at least.
|
||||
pub(super) fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option<ClipboardRead> {
|
||||
/// else reads `mimes` as [`pick`] does. Text is read here, `waits.load` ([`LOAD_WAIT`]) at
|
||||
/// most, and pasted unless it is empty; SVG and PNG are asked for here and waited for,
|
||||
/// `waits.image` at most, by the work that comes back. When that read fails or is empty,
|
||||
/// the work reads the rest of `mimes` as [`pick`] does. Each read the work makes after the
|
||||
/// first waits until `waits.image` after the first was sent, `waits.load` at least.
|
||||
pub(super) fn read(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
|
||||
let Waits { load, image: wait } = self.loads.waits();
|
||||
if takes_files(mimes) {
|
||||
let offered = lock(&self.seen).offered.clone();
|
||||
if let Some(list) = file_list_type(&offered).map(str::to_string) {
|
||||
@@ -2515,7 +2620,7 @@ mod wayland {
|
||||
self.unanswered = None;
|
||||
let (reads, mimes) = (self.loads.asker(), mimes.to_vec());
|
||||
return Some(ClipboardRead::Later(Box::new(move || {
|
||||
let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now()));
|
||||
let left = || load.max(left(sent, wait, Instant::now()));
|
||||
// The list asked for here is read from its answer, every other type anew.
|
||||
let mut first = Some((list, answer));
|
||||
pick_pasted(&offered, &mimes, |wire| {
|
||||
@@ -2531,7 +2636,7 @@ mod wayland {
|
||||
mimes.iter().enumerate().find_map(|(i, &mime)| {
|
||||
let wire = self.wire(mime)?;
|
||||
if mime == TEXT {
|
||||
let text = self.text(LOAD_WAIT).ok().filter(|t| !t.is_empty())?;
|
||||
let text = self.text(load).ok().filter(|t| !t.is_empty())?;
|
||||
return Some(ClipboardRead::Now(Flavour { mime: TEXT, data: text.into_bytes() }));
|
||||
}
|
||||
let sent = Instant::now();
|
||||
@@ -2543,7 +2648,7 @@ mod wayland {
|
||||
return Some(f);
|
||||
}
|
||||
let offered = lock(&seen).offered.clone();
|
||||
let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now()));
|
||||
let left = || load.max(left(sent, wait, Instant::now()));
|
||||
pick(&offered, &rest, |wire| wait_for_answer(&reads.ask(wire.to_string()).ok()?, left()).ok()?.ok())
|
||||
})))
|
||||
})
|
||||
@@ -2809,7 +2914,7 @@ mod wayland {
|
||||
let receiver = Receiver { conn: conn.clone(), objects: objects.clone(), _window: window.clone() };
|
||||
// Dropping doesn't wait for an unanswered read: only arboard's X11 handles hand what the
|
||||
// app copied on when the last one goes.
|
||||
let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, move |wire| receiver.receive(wire))?;
|
||||
let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, Waits::APP, move |wire| receiver.receive(wire))?;
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let (stopped, held) = (stop.clone(), window.clone());
|
||||
let work = move || {
|
||||
@@ -2846,14 +2951,16 @@ mod wayland {
|
||||
self.conn.flush().map_err(|e| format!("couldn't reach the compositor: {e}"))
|
||||
}
|
||||
|
||||
/// The text, waiting [`LOAD_WAIT`] at most ([`Reads::text`]).
|
||||
pub fn text(&mut self) -> Result<String, String> {
|
||||
self.reads.text(LOAD_WAIT)
|
||||
let wait = self.reads.loads.waits().load;
|
||||
self.reads.text(wait)
|
||||
}
|
||||
|
||||
/// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for `wait` at
|
||||
/// most.
|
||||
pub fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option<ClipboardRead> {
|
||||
self.reads.read(mimes, wait)
|
||||
/// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for
|
||||
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most.
|
||||
pub fn read(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
|
||||
self.reads.read(mimes)
|
||||
}
|
||||
|
||||
pub fn has(&self, mimes: &[&'static str]) -> bool {
|
||||
@@ -3022,8 +3129,8 @@ mod wayland {
|
||||
assert_eq!(keyboard_serial(&modifiers(9), None), None);
|
||||
}
|
||||
|
||||
/// A wait no test reaches: the other end of each pipe below either moves data or closes.
|
||||
const LONG: Duration = Duration::from_secs(600);
|
||||
/// No limit ([`idle_until`]): the other end of each pipe below either moves data or closes.
|
||||
const LONG: Duration = Duration::MAX;
|
||||
|
||||
/// A pipe holding `data`, its write end closed when `close`.
|
||||
fn pipe_with(data: &[u8], close: bool) -> (std::io::PipeReader, Option<std::io::PipeWriter>) {
|
||||
@@ -3041,7 +3148,7 @@ mod wayland {
|
||||
assert_eq!(read_capped(pipe_with(&[0u8; 9], true).0, 8, Duration::ZERO), Err("the clipboard's data is larger than 0 MiB".to_string()));
|
||||
// More than a pipe holds, from an app that is still sending.
|
||||
let (from, to) = std::io::pipe().unwrap();
|
||||
assert!(Sends::default().start(to, vec![0u8; (2 << 20) + 1].into()));
|
||||
assert!(Sends { idle: LONG, ..Sends::default() }.start(to, vec![0u8; (2 << 20) + 1].into()));
|
||||
assert_eq!(read_capped(from, 2 << 20, LONG), Err("the clipboard's data is larger than 2 MiB".to_string()));
|
||||
// A pipe that can't be read: the write end.
|
||||
let (_, to) = std::io::pipe().unwrap();
|
||||
@@ -3095,8 +3202,8 @@ mod wayland {
|
||||
|
||||
#[test]
|
||||
fn a_copys_data_is_sent_through_the_pipe_and_closed() {
|
||||
let sends = Sends::default();
|
||||
assert_eq!(sends.idle, IDLE_WAIT);
|
||||
assert_eq!(Sends::default().idle, IDLE_WAIT);
|
||||
let sends = Sends { idle: LONG, ..Sends::default() };
|
||||
let (from, to) = std::io::pipe().unwrap();
|
||||
let data: Arc<[u8]> = vec![7u8; 300_000].into();
|
||||
assert!(sends.start(to, data.clone()));
|
||||
@@ -3146,9 +3253,10 @@ mod wayland {
|
||||
const NOTHING: Held = &[];
|
||||
const UNKNOWN: Held = &[("application/x-other", b"x")];
|
||||
|
||||
/// Reads of a clipboard holding `data`, answered at once.
|
||||
/// Reads of a clipboard holding `data`, answered at once; each read waits for its answer
|
||||
/// with no limit.
|
||||
fn reads_of(data: Held) -> Reads {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
|
||||
data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.to_vec()).ok_or_else(|| "not offered".to_string())
|
||||
})
|
||||
.unwrap();
|
||||
@@ -3159,27 +3267,26 @@ mod wayland {
|
||||
#[test]
|
||||
fn a_picture_or_svg_alone_can_be_pasted_and_is() {
|
||||
use vectorcraft_engine::cmd::clipboard::PASTE_ORDER;
|
||||
let wait = Duration::from_secs(600);
|
||||
for (data, mime) in [(PNG_ONLY, PNG), (SVG_ONLY, SVG)] {
|
||||
let mut reads = reads_of(data);
|
||||
// The paste check enables Paste from the types alone.
|
||||
assert!(reads.has(&PASTE_ORDER));
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("{mime} is read off the UI thread") };
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("{mime} is read off the UI thread") };
|
||||
assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, data[0].1.to_vec())));
|
||||
}
|
||||
let mut reads = reads_of(TEXT_ONLY);
|
||||
assert!(reads.has(&[TEXT]) && !reads.has(&[BITMAP, SVG]));
|
||||
let Some(ClipboardRead::Now(f)) = reads.read(&PASTE_ORDER, wait) else { panic!("text is read at once") };
|
||||
let Some(ClipboardRead::Now(f)) = reads.read(&PASTE_ORDER) else { panic!("text is read at once") };
|
||||
assert_eq!((f.mime, f.data), (TEXT, b"words".to_vec()));
|
||||
// An empty clipboard, or one with no type a paste reads, enables nothing and pastes nothing.
|
||||
for data in [NOTHING, UNKNOWN] {
|
||||
let mut reads = reads_of(data);
|
||||
assert!(!reads.has(&PASTE_ORDER));
|
||||
assert!(reads.read(&PASTE_ORDER, wait).is_none());
|
||||
assert_eq!(reads.text(wait), Ok(String::new()));
|
||||
assert!(reads.read(&PASTE_ORDER).is_none());
|
||||
assert_eq!(reads.text(Duration::MAX), Ok(String::new()));
|
||||
}
|
||||
// Empty text is not pasted.
|
||||
assert!(reads_of(EMPTY_TEXT).read(&[TEXT], wait).is_none());
|
||||
assert!(reads_of(EMPTY_TEXT).read(&[TEXT]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3188,36 +3295,38 @@ mod wayland {
|
||||
const EMPTY_SVG_TEXT: Held = &[(SVG, b""), ("text/plain", b"words"), (PNG, b"\x89PNG")];
|
||||
const EMPTY_SVG_PNG: Held = &[(SVG, b""), (PNG, b"\x89PNG")];
|
||||
const EMPTY_SVG_URL: Held = &[(SVG, b""), ("text/plain", b"https://example.com/art.png"), (PNG, b"\x89PNG")];
|
||||
let wait = Duration::from_secs(600);
|
||||
const EMPTY_PNG: Held = &[(PNG, b"")];
|
||||
for (data, mime, bytes) in
|
||||
[(EMPTY_SVG_TEXT, TEXT, &b"words"[..]), (EMPTY_SVG_PNG, PNG, &b"\x89PNG"[..]), (EMPTY_SVG_URL, PNG, &b"\x89PNG"[..])]
|
||||
{
|
||||
// Held while the work runs, as the clipboard is.
|
||||
let mut reads = reads_of(data);
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the SVG is asked for") };
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("the SVG is asked for") };
|
||||
assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, bytes.to_vec())));
|
||||
}
|
||||
// A failed PNG read, last of all, pastes nothing.
|
||||
let mut reads = reads_of(EMPTY_PNG);
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the PNG is asked for") };
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("the PNG is asked for") };
|
||||
assert!(work().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_that_fails_pastes_nothing() {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, |_: String| Err::<Vec<u8>, _>("the clipboard's data is larger than 64 MiB".to_string()))
|
||||
.unwrap();
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |_: String| {
|
||||
Err::<Vec<u8>, _>("the clipboard's data is larger than 64 MiB".to_string())
|
||||
})
|
||||
.unwrap();
|
||||
let mut reads = Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&[PNG, "text/plain"]))));
|
||||
assert_eq!(reads.text(Duration::from_secs(600)), Err("the clipboard's data is larger than 64 MiB".to_string()));
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP], Duration::from_secs(600)) else { panic!("the PNG is asked for") };
|
||||
assert_eq!(reads.text(Duration::MAX), Err("the clipboard's data is larger than 64 MiB".to_string()));
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP]) else { panic!("the PNG is asked for") };
|
||||
assert!(work().is_none());
|
||||
}
|
||||
|
||||
/// Reads of a clipboard holding `data` by type, answered at once.
|
||||
/// Reads of a clipboard holding `data` by type, answered at once; each read waits for its
|
||||
/// answer with no limit.
|
||||
fn reads_holding(data: Vec<(String, Vec<u8>)>) -> Reads {
|
||||
let types: Vec<String> = data.iter().map(|(t, _)| t.clone()).collect();
|
||||
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
|
||||
data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.clone()).ok_or_else(|| "not offered".to_string())
|
||||
})
|
||||
.unwrap();
|
||||
@@ -3232,7 +3341,7 @@ mod wayland {
|
||||
|
||||
/// What a paste of `mimes` takes from `reads`.
|
||||
fn paste(reads: &mut Reads, mimes: &[&'static str]) -> Option<(&'static str, Vec<u8>)> {
|
||||
match reads.read(mimes, Duration::from_secs(600))? {
|
||||
match reads.read(mimes)? {
|
||||
ClipboardRead::Now(f) => Some((f.mime, f.data)),
|
||||
ClipboardRead::Later(work) => work().map(|f| (f.mime, f.data)),
|
||||
}
|
||||
@@ -3296,15 +3405,29 @@ mod wayland {
|
||||
}
|
||||
|
||||
/// The macOS pasteboard's vector art and bitmaps as they are (arboard reads text, and of the
|
||||
/// pictures TIFF only, decoded).
|
||||
/// pictures TIFF only, decoded), and the formats Copy adds to what arboard wrote.
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac {
|
||||
use objc2::rc::autoreleasepool;
|
||||
use objc2_app_kit::NSPasteboard;
|
||||
use objc2_foundation::{NSArray, NSString};
|
||||
use objc2_foundation::{NSArray, NSData, NSString};
|
||||
|
||||
use super::{Flavour, MAX_BYTES, copy_within, pasteboard_types};
|
||||
|
||||
/// Adds `types` ([`super::pasteboard_additions`]: each pasteboard type with its data) to the
|
||||
/// item arboard just wrote. A type that can't be added is logged, and what arboard wrote still
|
||||
/// carries the copy.
|
||||
pub fn add(types: &[(&str, &[u8])]) {
|
||||
autoreleasepool(|_| {
|
||||
let pasteboard = NSPasteboard::generalPasteboard();
|
||||
for &(t, data) in types {
|
||||
if !pasteboard.setData_forType(Some(&NSData::with_bytes(data)), &NSString::from_str(t)) {
|
||||
log::warn!("clipboard: couldn't add {t}");
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Does the pasteboard hold one of `mimes` ([`pasteboard_types`])? Asks for its types only.
|
||||
pub fn has(mimes: &[&'static str]) -> bool {
|
||||
autoreleasepool(|_| {
|
||||
@@ -3393,6 +3516,25 @@ mod tests {
|
||||
assert!(at(PDF) < at(EPS) && at(EPS) < at(TEXT) && at(TEXT) < at(BITMAP));
|
||||
}
|
||||
|
||||
/// On macOS a Copy puts every format on the pasteboard, not only the text or the picture
|
||||
/// arboard writes (#6310): with On Copy: PDF the PDF goes with the picture, and with Include
|
||||
/// SVG Code the SVG and the PDF go with the markup as text.
|
||||
#[test]
|
||||
fn a_copy_adds_its_other_formats_to_the_pasteboard() {
|
||||
let flavor = |mime: &'static str, data: &[u8]| Flavor::new(mime, data.to_vec());
|
||||
let added = |flavors: &[Flavor]| pasteboard_additions(flavors).into_iter().map(|(t, data)| (t, data.to_vec())).collect::<Vec<_>>();
|
||||
// On Copy: PDF alone: arboard writes the picture, and the PDF is added beside it.
|
||||
let pdf_only = [flavor(PDF, b"%PDF"), flavor(PNG, b"png")];
|
||||
assert_eq!(added(&pdf_only), [("com.adobe.pdf", b"%PDF".to_vec()), ("public.png", b"png".to_vec())]);
|
||||
// Include SVG Code with the PDF: arboard writes the markup as text, and the SVG, PDF and
|
||||
// picture are added in the order Copy offers them.
|
||||
let both = [flavor(TEXT, b"<svg/>"), flavor(SVG, b"<svg/>"), flavor(PDF, b"%PDF"), flavor(PNG, b"png")];
|
||||
let types: Vec<_> = added(&both).into_iter().map(|(t, _)| t).collect();
|
||||
assert_eq!(types, ["public.svg-image", "com.adobe.pdf", "public.png"]);
|
||||
// An empty flavour and a type the pasteboard doesn't carry are left out.
|
||||
assert!(added(&[flavor(PDF, b""), flavor(EMF, b"emf"), flavor("text/html", b"<p>")]).is_empty());
|
||||
}
|
||||
|
||||
/// An .eps file copied in a file manager pastes as EPS.
|
||||
#[test]
|
||||
fn a_copied_eps_file_pastes() {
|
||||
|
||||
@@ -220,11 +220,20 @@ fn report_path(dir: &Path) -> PathBuf {
|
||||
dir.join(format!("{REPORT_PREFIX}{}.txt", std::process::id()))
|
||||
}
|
||||
|
||||
/// A report file this process wrote and holds locked until the interface answers again.
|
||||
/// A report file this process holds locked: the one it wrote, until the interface answers again,
|
||||
/// or a left one while it is read. Dropping it unlocks 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.
|
||||
#[derive(Debug)]
|
||||
pub struct Held {
|
||||
path: PathBuf,
|
||||
_file: File,
|
||||
file: File,
|
||||
}
|
||||
|
||||
impl Drop for Held {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.file.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `text` to this process's report file in `dir` and lock it. Where the file system has no
|
||||
@@ -237,7 +246,7 @@ fn write_report(dir: &Path, text: &str) -> std::io::Result<Held> {
|
||||
log::warn!("the hang report file is written without a lock: {e}");
|
||||
}
|
||||
file.write_all(text.as_bytes())?;
|
||||
Ok(Held { path, _file: file })
|
||||
Ok(Held { path, file })
|
||||
}
|
||||
|
||||
/// Whether a report file whose `try_lock` gave `locked` was abandoned: nobody holds it. A file
|
||||
@@ -253,13 +262,14 @@ fn abandoned(locked: Result<(), std::fs::TryLockError>) -> bool {
|
||||
|
||||
/// The report file at `path`, opened and locked, with its length, when it was abandoned
|
||||
/// ([`abandoned`]) and is not empty (an empty one may be being written).
|
||||
fn open_abandoned(path: &Path) -> Option<(File, u64)> {
|
||||
fn open_abandoned(path: &Path) -> Option<(Held, u64)> {
|
||||
let file = File::options().read(true).write(true).open(path).ok()?;
|
||||
if !abandoned(file.try_lock()) {
|
||||
return None;
|
||||
}
|
||||
let len = file.metadata().map_or(0, |m| m.len());
|
||||
(len > 0).then_some((file, len))
|
||||
let held = Held { path: path.to_path_buf(), file };
|
||||
let len = held.file.metadata().map_or(0, |m| m.len());
|
||||
(len > 0).then_some((held, len))
|
||||
}
|
||||
|
||||
/// The reports that sessions closed while they did not answer left in `dir`, oldest first; `None`
|
||||
@@ -286,20 +296,20 @@ pub fn take_previous(dir: &Path) -> Option<String> {
|
||||
// Newest first: only abandoned reports count toward the limit.
|
||||
let mut texts = Vec::new();
|
||||
for (_, path) in found.into_iter().rev() {
|
||||
let Some((file, len)) = open_abandoned(&path) else { continue };
|
||||
let Some((held, len)) = open_abandoned(&path) else { continue };
|
||||
if texts.len() == MAX_REPORT_FILES {
|
||||
drop(file);
|
||||
drop(held);
|
||||
remove_quietly(&path);
|
||||
continue;
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
let text = if len <= MAX_REPORT_BYTES && (&file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() {
|
||||
let text = if len <= MAX_REPORT_BYTES && (&held.file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() {
|
||||
String::from_utf8_lossy(&bytes).into_owned()
|
||||
} else {
|
||||
format!("The report was larger than {MAX_REPORT_BYTES} bytes and was not read.\n")
|
||||
};
|
||||
// Closed (and unlocked) before it is moved: Windows moves no open file.
|
||||
drop(file);
|
||||
drop(held);
|
||||
if !texts.is_empty() {
|
||||
remove_quietly(&path);
|
||||
} else if let Err(e) = std::fs::rename(&path, dir.join(PREVIOUS_FILE)) {
|
||||
@@ -324,8 +334,8 @@ pub static CLOSING: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Remove `held`'s file, closing it first. → the error message; a file already gone is none.
|
||||
fn remove(held: Held) -> Option<String> {
|
||||
let Held { path, _file: file } = held;
|
||||
drop(file);
|
||||
let path = held.path.clone();
|
||||
drop(held);
|
||||
match std::fs::remove_file(&path) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Some(e.to_string()),
|
||||
_ => None,
|
||||
|
||||
@@ -136,6 +136,17 @@ fn a_stall_writes_the_report_file_and_its_end_removes_it() {
|
||||
assert!(shared.last.lock().unwrap().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_report_frees_its_lock_while_a_copy_of_its_handle_is_open() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let held = write_report(dir.path(), "left\n").unwrap();
|
||||
// A child process that is starting holds such a copy.
|
||||
let copy = held.file.try_clone().unwrap();
|
||||
drop(held);
|
||||
assert_eq!(take_previous(dir.path()).as_deref(), Some("left\n"), "a dropped report is no longer locked");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_normally_removes_the_report_and_writes_no_more() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -46,6 +46,17 @@ const SERVER_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
/// How long a launch waits on the primary: longer than a launch served before it can take.
|
||||
const CLIENT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// How long each side of a hand-over waits on the other.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Timeouts {
|
||||
connect: Duration,
|
||||
server: Duration,
|
||||
client: Duration,
|
||||
}
|
||||
|
||||
/// The waits a launch and the running app use.
|
||||
const TIMEOUTS: Timeouts = Timeouts { connect: CONNECT_TIMEOUT, server: SERVER_TIMEOUT, client: CLIENT_TIMEOUT };
|
||||
|
||||
/// Paths handed over by later launches that the UI hasn't opened yet.
|
||||
static PENDING: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
/// This app while it is the one later launches hand their files to ([`hold`]).
|
||||
@@ -68,25 +79,25 @@ pub fn start(automation: bool, new_instance: bool, safe_mode: bool, files: &[Str
|
||||
return Start::Running(None);
|
||||
}
|
||||
let Some(path) = prefs_dir().map(|dir| dir.join(FILE_NAME)) else { return Start::Running(None) };
|
||||
start_at(&path, new_instance, safe_mode, files)
|
||||
start_at(&path, TIMEOUTS, new_instance, safe_mode, files)
|
||||
}
|
||||
|
||||
/// [`start`] with the endpoint file `path`. A launch with `--new-instance` or `--safe-mode` keeps
|
||||
/// [`start`] with the endpoint file `path` and the waits `timeouts`. A launch with `--new-instance` or `--safe-mode` keeps
|
||||
/// its files and runs as its own app: a running app would open them with its plug-ins loaded. A
|
||||
/// `--safe-mode` launch never becomes the app later launches hand their files to, which would open
|
||||
/// them without plug-ins.
|
||||
fn start_at(path: &Path, new_instance: bool, safe_mode: bool, files: &[String]) -> Start {
|
||||
fn start_at(path: &Path, timeouts: Timeouts, new_instance: bool, safe_mode: bool, files: &[String]) -> Start {
|
||||
if safe_mode {
|
||||
return Start::Running(None);
|
||||
}
|
||||
// With nothing to hand over, the same exchange only asks whether an app is running.
|
||||
let send: &[String] = if new_instance { &[] } else { files };
|
||||
match forward(path, send) {
|
||||
match forward(path, timeouts, send) {
|
||||
Ok(()) if send.is_empty() => Start::Running(None),
|
||||
Ok(()) => Start::Forwarded,
|
||||
Err(e) => {
|
||||
log::debug!("no running VectorCraft to hand files to ({e})");
|
||||
Start::Running(listen(path, queue))
|
||||
Start::Running(listen(path, timeouts, queue))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -195,12 +206,12 @@ fn read_endpoint(path: &Path) -> Option<Endpoint> {
|
||||
|
||||
/// Hand `files` (made absolute against this launch's folder) to the app recorded at `path`; `Ok`
|
||||
/// once it acknowledged them.
|
||||
fn forward(path: &Path, files: &[String]) -> io::Result<()> {
|
||||
fn forward(path: &Path, timeouts: Timeouts, files: &[String]) -> io::Result<()> {
|
||||
let endpoint = read_endpoint(path).ok_or_else(|| invalid("no endpoint file"))?;
|
||||
let files = files.iter().map(|f| std::path::absolute(f).map(|p| p.to_string_lossy().into_owned())).collect::<io::Result<Vec<_>>>()?;
|
||||
let stream = TcpStream::connect_timeout(&(Ipv4Addr::LOCALHOST, endpoint.port).into(), CONNECT_TIMEOUT)?;
|
||||
stream.set_read_timeout(Some(CLIENT_TIMEOUT))?;
|
||||
stream.set_write_timeout(Some(CLIENT_TIMEOUT))?;
|
||||
let stream = TcpStream::connect_timeout(&(Ipv4Addr::LOCALHOST, endpoint.port).into(), timeouts.connect)?;
|
||||
stream.set_read_timeout(Some(timeouts.client))?;
|
||||
stream.set_write_timeout(Some(timeouts.client))?;
|
||||
// The token and the paths go only to a listener that knows the greeting.
|
||||
if !same(read_message(&stream)?.get("hello"), &endpoint.hello) {
|
||||
return Err(invalid("the listener isn't VectorCraft"));
|
||||
@@ -214,11 +225,11 @@ fn forward(path: &Path, files: &[String]) -> io::Result<()> {
|
||||
|
||||
/// Listen for later launches and record this app at `path`; each launch's files go to `deliver`.
|
||||
/// `None` when that fails (logged): the app then runs on its own, as before.
|
||||
fn listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> Option<Primary> {
|
||||
try_listen(path, deliver).inspect_err(|e| log::warn!("files opened while VectorCraft runs will open in another window: {e}")).ok()
|
||||
fn listen(path: &Path, timeouts: Timeouts, deliver: impl Fn(Vec<String>) + Send + 'static) -> Option<Primary> {
|
||||
try_listen(path, timeouts, deliver).inspect_err(|e| log::warn!("files opened while VectorCraft runs will open in another window: {e}")).ok()
|
||||
}
|
||||
|
||||
fn try_listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> io::Result<Primary> {
|
||||
fn try_listen(path: &Path, timeouts: Timeouts, deliver: impl Fn(Vec<String>) + Send + 'static) -> io::Result<Primary> {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
|
||||
let port = listener.local_addr()?.port();
|
||||
let (token, hello) = random_tokens();
|
||||
@@ -227,7 +238,7 @@ fn try_listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> io
|
||||
let primary = Primary { path: path.to_path_buf(), token: token.clone() };
|
||||
std::thread::Builder::new().name("open-files-listener".into()).spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
match stream.and_then(|s| receive(&s, &hello, &token)) {
|
||||
match stream.and_then(|s| receive(&s, timeouts.server, &hello, &token)) {
|
||||
Ok(files) if files.is_empty() => {}
|
||||
Ok(files) => deliver(files),
|
||||
Err(e) => {
|
||||
@@ -241,10 +252,11 @@ fn try_listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> io
|
||||
Ok(primary)
|
||||
}
|
||||
|
||||
/// Serve one launch: greet it, check its token, keep the paths that are existing files.
|
||||
fn receive(stream: &TcpStream, hello: &str, token: &str) -> io::Result<Vec<String>> {
|
||||
stream.set_read_timeout(Some(SERVER_TIMEOUT))?;
|
||||
stream.set_write_timeout(Some(SERVER_TIMEOUT))?;
|
||||
/// Serve one launch, waiting on it at most `timeout`: greet it, check its token, keep the paths
|
||||
/// that are existing files.
|
||||
fn receive(stream: &TcpStream, timeout: Duration, hello: &str, token: &str) -> io::Result<Vec<String>> {
|
||||
stream.set_read_timeout(Some(timeout))?;
|
||||
stream.set_write_timeout(Some(timeout))?;
|
||||
write_message(stream, &json!({ "hello": hello }))?;
|
||||
let message = read_message(stream)?;
|
||||
if !same(message.get("token"), token) {
|
||||
@@ -357,17 +369,38 @@ mod tests {
|
||||
(dir.path().join(FILE_NAME), TestDir(dir), file)
|
||||
}
|
||||
|
||||
/// Stops a test that hangs. A hand-over on a busy machine still ends long before it, so no
|
||||
/// result depends on how long a step takes.
|
||||
const HANG_GUARD: Duration = Duration::from_secs(60);
|
||||
/// The waits both sides get in the tests.
|
||||
const PATIENT: Timeouts = Timeouts { connect: HANG_GUARD, server: HANG_GUARD, client: HANG_GUARD };
|
||||
|
||||
fn primary(path: &Path) -> (Primary, mpsc::Receiver<Vec<String>>) {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let primary = listen(path, move |files| tx.send(files).unwrap()).unwrap();
|
||||
let primary = listen(path, PATIENT, move |files| tx.send(files).unwrap()).unwrap();
|
||||
(primary, rx)
|
||||
}
|
||||
|
||||
/// The next files the app delivered. The app delivers them after it acknowledges the launch,
|
||||
/// so this waits for them.
|
||||
fn delivered(rx: &mpsc::Receiver<Vec<String>>) -> Vec<String> {
|
||||
rx.recv_timeout(HANG_GUARD).unwrap_or_else(|e| panic!("the app delivered no files: {e}"))
|
||||
}
|
||||
|
||||
/// `result` is an error from the other side, not a wait that ran out.
|
||||
fn refused<T>(result: io::Result<T>) -> bool {
|
||||
result.is_err_and(|e| {
|
||||
assert!(!matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut), "a wait ran out instead: {e}");
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
/// Connects as a launch would and sends `message` after the greeting; what came back.
|
||||
fn send_raw(path: &Path, message: &[u8]) -> io::Result<Value> {
|
||||
let endpoint = read_endpoint(path).unwrap();
|
||||
let stream = TcpStream::connect((Ipv4Addr::LOCALHOST, endpoint.port)).unwrap();
|
||||
stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap();
|
||||
stream.set_read_timeout(Some(HANG_GUARD)).unwrap();
|
||||
stream.set_write_timeout(Some(HANG_GUARD)).unwrap();
|
||||
assert!(same(read_message(&stream).unwrap().get("hello"), &endpoint.hello));
|
||||
(&stream).write_all(message)?;
|
||||
read_message(&stream)
|
||||
@@ -378,12 +411,12 @@ mod tests {
|
||||
let (path, dir, file) = folder("forward");
|
||||
let (primary, rx) = primary(&path);
|
||||
let missing = dir.join("missing.svg").to_string_lossy().into_owned();
|
||||
forward(&path, &[file.clone(), missing]).unwrap();
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file), "the missing file is left out");
|
||||
forward(&path, PATIENT, &[file.clone(), missing]).unwrap();
|
||||
assert_eq!(delivered(&rx), std::slice::from_ref(&file), "the missing file is left out");
|
||||
// An empty list only asks whether the app runs: nothing is delivered.
|
||||
forward(&path, &[]).unwrap();
|
||||
forward(&path, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
|
||||
forward(&path, PATIENT, &[]).unwrap();
|
||||
forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(delivered(&rx), [file]);
|
||||
drop(primary);
|
||||
assert!(!path.exists(), "the endpoint file goes with the app");
|
||||
}
|
||||
@@ -393,11 +426,11 @@ mod tests {
|
||||
let (path, _dir, file) = folder("own");
|
||||
let (primary, rx) = primary(&path);
|
||||
for (new_instance, safe_mode) in [(true, false), (false, true)] {
|
||||
let start = start_at(&path, new_instance, safe_mode, std::slice::from_ref(&file));
|
||||
let start = start_at(&path, PATIENT, new_instance, safe_mode, std::slice::from_ref(&file));
|
||||
assert!(matches!(start, Start::Running(None)), "runs as its own app (new instance {new_instance}, Safe Mode {safe_mode})");
|
||||
}
|
||||
assert!(matches!(start_at(&path, false, false, std::slice::from_ref(&file)), Start::Forwarded));
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file));
|
||||
assert!(matches!(start_at(&path, PATIENT, false, false, std::slice::from_ref(&file)), Start::Forwarded));
|
||||
assert_eq!(delivered(&rx), std::slice::from_ref(&file));
|
||||
assert!(rx.try_recv().is_err(), "only the plain launch handed its file over");
|
||||
drop(primary);
|
||||
}
|
||||
@@ -407,10 +440,10 @@ mod tests {
|
||||
let _globals = globals();
|
||||
let (path, _dir, file) = folder("safe-mode-alone");
|
||||
// With no app running, a Safe Mode launch runs without listening.
|
||||
assert!(matches!(start_at(&path, false, true, std::slice::from_ref(&file)), Start::Running(None)));
|
||||
assert!(matches!(start_at(&path, PATIENT, false, true, std::slice::from_ref(&file)), Start::Running(None)));
|
||||
assert!(!path.exists(), "a Safe Mode launch records no endpoint");
|
||||
// A plain launch after it starts its own app and takes later launches' files.
|
||||
let Start::Running(Some(primary)) = start_at(&path, false, false, std::slice::from_ref(&file)) else {
|
||||
let Start::Running(Some(primary)) = start_at(&path, PATIENT, false, false, std::slice::from_ref(&file)) else {
|
||||
panic!("the plain launch runs and listens")
|
||||
};
|
||||
assert!(path.exists());
|
||||
@@ -427,7 +460,7 @@ mod tests {
|
||||
resign();
|
||||
drop(take());
|
||||
let (path, _dir, file) = folder("safe-mode-later");
|
||||
let Start::Running(Some(primary)) = start_at(&path, false, false, &[]) else { panic!("the first launch listens") };
|
||||
let Start::Running(Some(primary)) = start_at(&path, PATIENT, false, false, &[]) else { panic!("the first launch listens") };
|
||||
hold(Some(primary));
|
||||
// A later launch handed its file over while the choice about a stopped plug-in was up.
|
||||
queue(vec![file.clone()]);
|
||||
@@ -460,17 +493,18 @@ mod tests {
|
||||
let (_primary, rx) = primary(&path);
|
||||
let token = read_endpoint(&path).unwrap().token;
|
||||
let wrong = format!("{}\n", json!({ "token": "0".repeat(token.len()), "files": [file] }));
|
||||
assert!(send_raw(&path, wrong.as_bytes()).is_err());
|
||||
assert!(send_raw(&path, b"not json\n").is_err());
|
||||
assert!(send_raw(&path, &vec![b'a'; MAX_MESSAGE as usize + 10]).is_err());
|
||||
assert!(refused(send_raw(&path, wrong.as_bytes())));
|
||||
assert!(refused(send_raw(&path, b"not json\n")));
|
||||
assert!(refused(send_raw(&path, &vec![b'a'; MAX_MESSAGE as usize + 10])));
|
||||
let many = format!("{}\n", json!({ "token": token, "files": vec![file.clone(); MAX_FILES + 1] }));
|
||||
assert!(send_raw(&path, many.as_bytes()).is_err());
|
||||
assert!(refused(send_raw(&path, many.as_bytes())));
|
||||
let relative = format!("{}\n", json!({ "token": token, "files": ["a b.svg", 7] }));
|
||||
assert_eq!(send_raw(&path, relative.as_bytes()).unwrap(), json!({ "ok": true }));
|
||||
assert!(rx.try_recv().is_err(), "nothing was delivered");
|
||||
// The listener still serves a launch with the right token.
|
||||
forward(&path, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
|
||||
// The listener still serves a launch with the right token. It serves launches in turn, so
|
||||
// anything delivered for the messages above would come before this file.
|
||||
forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(delivered(&rx), [file]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -483,27 +517,28 @@ mod tests {
|
||||
let port = gone.local_addr().unwrap().port();
|
||||
write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap();
|
||||
let closed = std::thread::spawn(move || drop(gone.accept()));
|
||||
assert!(forward(&path, std::slice::from_ref(&file)).is_err());
|
||||
assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file))));
|
||||
closed.join().unwrap();
|
||||
// A listener that doesn't know the greeting gets neither the token nor the paths.
|
||||
// A listener that doesn't know the greeting gets neither the token nor the paths: the
|
||||
// launch closes the connection instead.
|
||||
let impostor = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let port = impostor.local_addr().unwrap().port();
|
||||
write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap();
|
||||
let heard = std::thread::spawn(move || {
|
||||
let (stream, _) = impostor.accept().unwrap();
|
||||
write_message(&stream, &json!({ "hello": "x" })).unwrap();
|
||||
stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap();
|
||||
read_message(&stream).ok()
|
||||
stream.set_read_timeout(Some(HANG_GUARD)).unwrap();
|
||||
read_message(&stream)
|
||||
});
|
||||
assert!(forward(&path, std::slice::from_ref(&file)).is_err());
|
||||
assert!(heard.join().unwrap().is_none());
|
||||
assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file))));
|
||||
assert!(refused(heard.join().unwrap()));
|
||||
// Garbage in the file is no endpoint either.
|
||||
fs::write(&path, b"\xff not json").unwrap();
|
||||
assert!(forward(&path, std::slice::from_ref(&file)).is_err());
|
||||
assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file))));
|
||||
// A new primary replaces the stale file.
|
||||
let (_primary, rx) = primary(&path);
|
||||
forward(&path, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
|
||||
forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(delivered(&rx), [file]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -309,7 +309,7 @@ pub struct Scatter {
|
||||
pub art: Node,
|
||||
/// Size range in percent of the art.
|
||||
pub size: (f64, f64),
|
||||
/// Spacing range in percent of the (scaled) art width.
|
||||
/// Spacing range in percent of the (scaled) art width, its strokes included.
|
||||
pub spacing: (f64, f64),
|
||||
/// Perpendicular offset range in percent of the (scaled) art height.
|
||||
pub scatter: (f64, f64),
|
||||
|
||||
@@ -272,6 +272,22 @@ fn scatter_count_and_spacing() {
|
||||
assert_eq!(out.len(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_spaces_stroked_art_by_its_stroked_width() {
|
||||
let art = Node::path(
|
||||
NodeId(0),
|
||||
shapes::rectangle(Rect::new(0.0, -2.0, 10.0, 2.0)),
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0),
|
||||
);
|
||||
let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) };
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 120.0, 0.0), &stroke(1.0));
|
||||
let boxes: Vec<Rect> = out.iter().filter_map(Node::visual_bounds).collect();
|
||||
assert!(boxes.len() > 1, "{boxes:?}");
|
||||
for w in boxes.windows(2) {
|
||||
assert!(near(w[1].x0, w[0].x1, 1e-6), "stroked copies at 100% spacing touch: {boxes:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_is_deterministic_and_randomised() {
|
||||
let b = Brush {
|
||||
|
||||
@@ -540,7 +540,10 @@ fn vary(rng: &mut Rng, (a, b): (f64, f64), mode: Variation, pen: PenAt) -> f64 {
|
||||
|
||||
pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec<Node> {
|
||||
let Some(b) = sc.art.geometric_bounds() else { return vec![] };
|
||||
let (aw, ah) = (b.width().max(1e-3), b.height().max(1e-3));
|
||||
// Copies are spaced by the width of the art with its strokes, so at 100% spacing stroked
|
||||
// copies touch instead of overlapping by the stroke.
|
||||
let aw = sc.art.visual_bounds().unwrap_or(b).width().max(1e-3);
|
||||
let ah = b.height().max(1e-3);
|
||||
let mut rng = Rng::new(seed_of(bp, name));
|
||||
let [size_mode, spacing_mode, scatter_mode, rotation_mode] = sc.modes();
|
||||
let mut out = Budget::default();
|
||||
@@ -1129,11 +1132,23 @@ mod tests {
|
||||
/// Fitting is bounded however badly the map behaves: where it gives points that are not finite
|
||||
/// the tile falls back to chords with those points left out (or to nothing), and where it never
|
||||
/// fits (a map that jumps everywhere) the halving stops at its depth and anchor count. Either
|
||||
/// way the call comes back promptly with finite geometry.
|
||||
/// way the call comes back with finite geometry, having called the map a bounded number of
|
||||
/// times.
|
||||
#[test]
|
||||
fn a_map_that_misbehaves_still_returns_promptly_and_finite() {
|
||||
let b = Rect::new(0.0, -20.0, 40.0, 20.0);
|
||||
let tile = circle_tile(b);
|
||||
// Each piece the fitting tries reads its two ends, the derivatives there and the checks
|
||||
// between them. Fitted pieces are at most the chords, so the halving tries at most twice
|
||||
// as many pieces plus those on the way down to the one that gives up. The chord route
|
||||
// maps each chord point once more.
|
||||
let NodeKind::Path { path, .. } = &tile.kind else { panic!("the tile is a path") };
|
||||
let allowed: usize = path
|
||||
.subpaths
|
||||
.iter()
|
||||
.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 {
|
||||
NodeKind::Path { path, .. } => {
|
||||
path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite())
|
||||
@@ -1147,9 +1162,14 @@ mod tests {
|
||||
&|_| Point::new(f64::NAN, f64::NAN),
|
||||
];
|
||||
for (i, f) in maps.iter().enumerate() {
|
||||
let t0 = std::time::Instant::now();
|
||||
let out = warp_node(&tile, f, 0.25, 1.5, 0.25, 1.0);
|
||||
assert!(t0.elapsed() < std::time::Duration::from_secs(2), "map {i} took {:?}", t0.elapsed());
|
||||
// Past the allowance the map places nothing, so a warp that keeps calling it stops.
|
||||
let calls = std::cell::Cell::new(0usize);
|
||||
let counted = |p: Point| {
|
||||
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);
|
||||
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"),
|
||||
(_, Some(n)) => assert!(finite(n), "map {i} drew non-finite geometry"),
|
||||
|
||||
@@ -708,16 +708,29 @@ fn rgb_color([r, g, b]: [u8; 3]) -> Color {
|
||||
Color::rgb8(r, g, b)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many names [`unique`] tried on this thread (tests).
|
||||
pub(crate) static SYMBOL_NAMES_TRIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Whether `taken` holds `name`, counted as one name tried (tests).
|
||||
fn is_taken(taken: &HashSet<String>, name: &str) -> bool {
|
||||
#[cfg(test)]
|
||||
SYMBOL_NAMES_TRIED.with(|n| n.set(n.get().saturating_add(1)));
|
||||
taken.contains(name)
|
||||
}
|
||||
|
||||
/// `base`, or `base 2`, `base 3`… when taken; `next` remembers where each base left off.
|
||||
fn unique(base: &str, next: &mut HashMap<String, usize>, taken: &HashSet<String>) -> String {
|
||||
if !taken.contains(base) {
|
||||
if !is_taken(taken, base) {
|
||||
return base.to_string();
|
||||
}
|
||||
let i = next.entry(base.to_string()).or_insert(2);
|
||||
loop {
|
||||
let name = format!("{base} {i}");
|
||||
*i += 1;
|
||||
if !taken.contains(&name) {
|
||||
if !is_taken(taken, &name) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,6 +175,32 @@ fn layer(l: model::Layer) -> LayerDef {
|
||||
/// drawings have a few dozen layouts with short names.
|
||||
const MAX_LAYOUT_NAME_BYTES: usize = 4 << 20;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`layouts`] compared two layout names on this thread (tests).
|
||||
pub(crate) static LAYOUT_NAME_COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A paper layout's name as [`layouts`] de-duplicates it (lower case: names differing only in
|
||||
/// ASCII case are one layout).
|
||||
struct LayoutKey(String);
|
||||
|
||||
impl PartialEq for LayoutKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
LAYOUT_NAME_COMPARISONS.with(|n| n.set(n.get().saturating_add(1)));
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for LayoutKey {}
|
||||
|
||||
impl std::hash::Hash for LayoutKey {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.0.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Model space, then each paper layout (its LAYOUT object, in tab order); a file without layout
|
||||
/// objects but with paper-space art has one paper layout.
|
||||
fn layouts(doc: &model::Document<'_>, block_names: &HashMap<u64, &str>) -> Vec<LayoutDef> {
|
||||
@@ -187,7 +213,7 @@ fn layouts(doc: &model::Document<'_>, block_names: &HashMap<u64, &str>) -> Vec<L
|
||||
continue;
|
||||
}
|
||||
let Some(block) = block else { continue };
|
||||
let key = l.name.to_ascii_lowercase();
|
||||
let key = LayoutKey(l.name.to_ascii_lowercase());
|
||||
let cost = l.name.len() + block.len();
|
||||
// A layout past the allowance is skipped alone: a later short one is still offered, and a
|
||||
// skipped one reserves neither its name nor its bytes.
|
||||
|
||||
@@ -743,15 +743,16 @@ fn many_by_block_looks_import_in_linear_time() {
|
||||
inserts.extend([(0, "INSERT"), (2, "Door"), (420, colour), (10, "0"), (20, "0")]);
|
||||
}
|
||||
let text = with_door(by_block, &inserts);
|
||||
let start = std::time::Instant::now();
|
||||
build::SYMBOL_NAMES_TRIED.with(|t| t.set(0));
|
||||
let doc = open(&text, &points()).document;
|
||||
let took = start.elapsed();
|
||||
let tried = build::SYMBOL_NAMES_TRIED.with(std::cell::Cell::get);
|
||||
let mut names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names.len(), n);
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
assert_eq!(names.len(), n, "names stay unique");
|
||||
assert!(took < std::time::Duration::from_secs(4), "import took {took:?}");
|
||||
// Each symbol after the first tries its label and then the next free suffix.
|
||||
assert!(tried < 2 * n, "{tried} names tried for {n} symbols");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1001,7 +1002,7 @@ fn binary_dwg_damaged_and_foreign_files() {
|
||||
// A binary DXF opens as its ASCII form does.
|
||||
let ascii = entities(LINE);
|
||||
let tags = craft_dxf::parse(&ascii).unwrap();
|
||||
let r = open(&craft_dxf::write_binary(&tags, true), &points());
|
||||
let r = open(&craft_dxf::write_binary(&tags, true).unwrap(), &points());
|
||||
assert_eq!(leaves(&r.document).len(), 1);
|
||||
let e = import(b"AC1032\x00\x00\x00", &ImportOptions::default()).unwrap_err();
|
||||
assert!(e.contains("DWG"), "{e}");
|
||||
@@ -1151,12 +1152,13 @@ fn with_layouts(names: &[String]) -> Vec<u8> {
|
||||
|
||||
#[test]
|
||||
fn many_paper_layouts_are_read_in_linear_time() {
|
||||
let names: Vec<String> = (0..100_000).map(|i| format!("L{i}")).collect();
|
||||
let names: Vec<String> = (0..10_000).map(|i| format!("L{i}")).collect();
|
||||
let bytes = with_layouts(&names);
|
||||
let t = std::time::Instant::now();
|
||||
reader::LAYOUT_NAME_COMPARISONS.with(|c| c.set(0));
|
||||
let info = info(&bytes).unwrap();
|
||||
let compared = reader::LAYOUT_NAME_COMPARISONS.with(std::cell::Cell::get);
|
||||
assert_eq!(info.layouts.len(), names.len() + 1);
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5), "layout de-duplication is quadratic: {:?}", t.elapsed());
|
||||
assert!(compared <= names.len(), "layout de-duplication compared {compared} names for {} layouts", names.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+17
-3
@@ -1211,7 +1211,18 @@ pub fn active_settings() -> ColorSettings {
|
||||
|
||||
/// The color-management context of Edit → Color Settings (the working spaces, intent and black
|
||||
/// point compensation), as [`set_active`] last set them, whatever profiles a document is assigned.
|
||||
/// Inside [`with_active`] on this thread: the working settings of the settings it was given.
|
||||
pub fn working() -> Arc<Cms> {
|
||||
if SCOPED_FLAGS.with(Cell::get) & SCOPED_SET != 0
|
||||
&& let Some(c) = SCOPED.with(|s| s.borrow().clone())
|
||||
{
|
||||
return c.working.clone().unwrap_or(c);
|
||||
}
|
||||
installed_working()
|
||||
}
|
||||
|
||||
/// The working settings of the process, as [`set_active`] last set them.
|
||||
fn installed_working() -> Arc<Cms> {
|
||||
if let Some(c) = WORKING.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
|
||||
return c.clone();
|
||||
}
|
||||
@@ -1241,7 +1252,7 @@ pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> {
|
||||
/// is not of its model, leaves the working space. The working settings stay as they are. True when
|
||||
/// the active settings changed.
|
||||
pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool {
|
||||
let working = working();
|
||||
let working = installed_working();
|
||||
let st = document_settings(&working.settings, rgb, cmyk);
|
||||
if st == installed().settings {
|
||||
return false;
|
||||
@@ -1281,7 +1292,7 @@ const DOCUMENT_CONTEXTS: usize = 8;
|
||||
/// loaded gives the working settings.
|
||||
pub fn for_document(rgb: Option<&str>, cmyk: Option<&str>) -> Arc<Cms> {
|
||||
static KEPT: Mutex<Vec<(u64, Arc<Cms>)>> = Mutex::new(Vec::new());
|
||||
let working = working();
|
||||
let working = installed_working();
|
||||
let st = document_settings(&working.settings, rgb, cmyk);
|
||||
let installed = installed();
|
||||
if st == installed.settings {
|
||||
@@ -1308,7 +1319,10 @@ pub fn for_document(rgb: Option<&str>, cmyk: Option<&str>) -> Arc<Cms> {
|
||||
|
||||
/// Run `f` with `cms` as the active settings on this thread ([`active`], [`crate::Color::to_rgb`]
|
||||
/// and the conversions that read them), as when drawing a document other than the front one
|
||||
/// through its own profiles. Other threads, and this thread after `f`, keep the settings they had.
|
||||
/// through its own profiles, and with the working settings `cms` was made from as the working
|
||||
/// settings ([`working`]): the ones [`for_document`] put the document's profiles in place of, else
|
||||
/// `cms` itself. A [`set_active`] while `f` runs, on any thread, does not change either on this
|
||||
/// thread. Other threads, and this thread after `f`, keep the settings they had.
|
||||
pub fn with_active<R>(cms: Arc<Cms>, f: impl FnOnce() -> R) -> R {
|
||||
/// Puts back the settings this thread had before, when `f` returns or unwinds.
|
||||
struct Restore(Option<Arc<Cms>>, u8);
|
||||
|
||||
@@ -519,6 +519,33 @@ fn with_active_puts_settings_in_place_on_this_thread_only() {
|
||||
assert_eq!((rgb.to_rgb(), ink.to_rgb()), before, "the active settings come back after a panic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_active_keeps_its_working_settings_while_another_thread_sets_them() {
|
||||
let before = working_settings();
|
||||
let p3 = Arc::new(Cms::new(&ColorSettings { rgb: DISPLAY_P3.into(), cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap());
|
||||
let (inside, after_other, other) = with_active(p3.clone(), || {
|
||||
let inside = working();
|
||||
// The same settings again, so other tests in this binary see the same values.
|
||||
let again = before.clone();
|
||||
let other = std::thread::spawn(move || {
|
||||
set_active(&again).unwrap();
|
||||
working()
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
(inside, working(), other)
|
||||
});
|
||||
assert!(Arc::ptr_eq(&inside, &p3), "settings made from no others are their own working settings");
|
||||
assert!(Arc::ptr_eq(&after_other, &p3), "a set_active on another thread leaves this thread's working settings");
|
||||
assert!(!Arc::ptr_eq(&other, &p3), "the other thread has the settings it set");
|
||||
assert_eq!(working_settings(), before, "the working settings come back after");
|
||||
// A document's context keeps the working settings it was made from.
|
||||
let doc = for_document(Some(DISPLAY_P3), None);
|
||||
let (active, working) = with_active(doc, || (active_settings(), working_settings()));
|
||||
assert_eq!(active.rgb, DISPLAY_P3, "the document's profile is active");
|
||||
assert_eq!(working, before, "the working RGB space stays the working one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_gets_the_same_context_for_the_same_profiles() {
|
||||
// Other tests load profiles meanwhile, and a load makes the contexts again: try until one pair
|
||||
|
||||
@@ -731,6 +731,152 @@ fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: O
|
||||
tops
|
||||
}
|
||||
|
||||
/// The most hits [`leaves_at`] lists.
|
||||
pub const MAX_LEAVES_AT: usize = 256;
|
||||
|
||||
/// The hits under `p`, topmost first, at most [`MAX_LEAVES_AT`]: one for each object a click with
|
||||
/// Direct Selection picks there (a path, a compound path or an image, also inside a group), each
|
||||
/// found by a hit test ([`hit_test`]) that passes over the ones found before it. In isolation mode
|
||||
/// (`opt.scope`) only what is inside the isolated group or object is hit. Cmd/Ctrl-clicks with the
|
||||
/// Selection tool step through them (Select Behind).
|
||||
pub fn leaves_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<Hit> {
|
||||
let _walk = ArtWalk::open();
|
||||
// A clipping mask, or a group drawn with its own geometry effects, hits by rules the single
|
||||
// traversal leaves to the hit test: the repeated hit test finds the rest, after the hits found
|
||||
// above them, which the art walked for them already counted against.
|
||||
leaves_at_once(doc, p, opt).unwrap_or_else(|above| leaves_at_repeated_after(doc, p, opt, above))
|
||||
}
|
||||
|
||||
/// [`leaves_at`] by repeated hit tests, each passing over the objects found before it.
|
||||
#[cfg(test)]
|
||||
fn leaves_at_repeated(doc: &Document, p: Point, opt: HitOptions) -> Vec<Hit> {
|
||||
leaves_at_repeated_after(doc, p, opt, vec![])
|
||||
}
|
||||
|
||||
/// [`leaves_at`] by repeated hit tests after `hits`, the topmost hits already found.
|
||||
fn leaves_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, mut hits: Vec<Hit>) -> Vec<Hit> {
|
||||
let mut found: HashSet<NodeId> = hits.iter().map(|h| h.leaf).collect();
|
||||
while hits.len() < MAX_LEAVES_AT
|
||||
&& let Some(h) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true)
|
||||
{
|
||||
if !found.insert(h.leaf) {
|
||||
break;
|
||||
}
|
||||
hits.push(h);
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
/// [`leaves_at`] in one traversal of the document, in the order repeated hit tests
|
||||
/// ([`hit_test_skipping`]) find them. `Err` with the hits found above it when a container under
|
||||
/// `p` clips or draws its art with its own geometry effects ([`leaves_in`]).
|
||||
fn leaves_at_once(doc: &Document, p: Point, opt: HitOptions) -> Result<Vec<Hit>, Vec<Hit>> {
|
||||
let finish = |mut h: Hit| {
|
||||
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
|
||||
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
|
||||
h
|
||||
};
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let on_locked = |id: NodeId| {
|
||||
!locks.is_empty() && doc.parent_of(id).and_then(|l| doc.node(l)).is_some_and(Node::is_layer) && doc.node(id).is_some_and(|n| locks.holds(n))
|
||||
};
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
let mut hits = Vec::new();
|
||||
if let Some(scope) = opt.scope
|
||||
&& let Some(isolated) = doc.node(scope)
|
||||
&& let Some(mut chain) = doc.ancestry(scope)
|
||||
{
|
||||
if !doc.is_editable_with(&locks, scope) {
|
||||
return Ok(hits);
|
||||
}
|
||||
let whole = if isolated.is_container() {
|
||||
leaves_in(isolated, p, opt, &symbols, &on_locked, &mut chain, &mut hits)
|
||||
} else {
|
||||
// A single object isolated: only it hits, among its siblings.
|
||||
chain.pop();
|
||||
let Some(parent) = chain.last().and_then(|id| doc.node(*id)) else { return Ok(hits) };
|
||||
leaves_in(parent, p, opt, &symbols, &|id| id != scope || on_locked(id), &mut chain, &mut hits)
|
||||
};
|
||||
let hits = hits.into_iter().map(finish).collect();
|
||||
return if whole { Ok(hits) } else { Err(hits) };
|
||||
}
|
||||
let mut chain = Vec::new();
|
||||
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;
|
||||
}
|
||||
chain.push(layer.id);
|
||||
let opt = if !opt.ignore_layer_preview && previews_off(layer) { HitOptions { outline: true, ..opt } } else { opt };
|
||||
if !leaves_in(layer, p, opt, &symbols, &on_locked, &mut chain, &mut hits) {
|
||||
return Err(hits.into_iter().map(finish).collect());
|
||||
}
|
||||
chain.pop();
|
||||
if hits.len() >= MAX_LEAVES_AT {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(hits.into_iter().map(finish).collect())
|
||||
}
|
||||
|
||||
/// Every editable hit under `p` in `parent`, topmost first, added to `hits` up to
|
||||
/// [`MAX_LEAVES_AT`]: what [`hit_children`] finds first, then what it finds passing over each hit
|
||||
/// found before. `false` when `parent` or a container in it under `p` clips or draws its art with
|
||||
/// its own geometry effects, which [`hit_children`] hits by rules of their own.
|
||||
fn leaves_in(
|
||||
parent: &Node,
|
||||
p: Point,
|
||||
opt: HitOptions,
|
||||
symbols: &SymbolBoxes,
|
||||
skip: &dyn Fn(NodeId) -> bool,
|
||||
chain: &mut Vec<NodeId>,
|
||||
hits: &mut Vec<Hit>,
|
||||
) -> bool {
|
||||
let Some(children) = parent.children() else { return true };
|
||||
if parent.clips() || drawn_art(symbols, parent, opt.outline).is_some() {
|
||||
return false;
|
||||
}
|
||||
for i in hit_order(parent, children, p) {
|
||||
if hits.len() >= MAX_LEAVES_AT {
|
||||
return true;
|
||||
}
|
||||
let Some(c) = children.get(i) else { continue };
|
||||
if !may_hit(parent, i, c, p, opt, symbols, true) || skip(c.id) {
|
||||
continue;
|
||||
}
|
||||
chain.push(c.id);
|
||||
let leaf = |hits: &mut Vec<Hit>, chain: &[NodeId]| {
|
||||
if let Some(kind) = hit_leaf(c, p, opt, symbols) {
|
||||
hits.push(Hit { leaf: c.id, ancestry: chain.to_vec(), kind, contents_of: None, layers: 1 });
|
||||
}
|
||||
};
|
||||
let whole = match &c.kind {
|
||||
NodeKind::Layer { preview: false, .. } if !opt.ignore_layer_preview => {
|
||||
leaves_in(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, hits)
|
||||
}
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } | NodeKind::Envelope { editing: true, .. } => {
|
||||
leaves_in(c, p, opt, symbols, skip, chain, hits)
|
||||
}
|
||||
// A blend's key objects first; its steps hit as the blend.
|
||||
NodeKind::Blend { .. } => {
|
||||
let whole = leaves_in(c, p, opt, symbols, skip, chain, hits);
|
||||
if whole && hits.len() < MAX_LEAVES_AT {
|
||||
leaf(hits, chain);
|
||||
}
|
||||
whole
|
||||
}
|
||||
_ => {
|
||||
leaf(hits, chain);
|
||||
true
|
||||
}
|
||||
};
|
||||
chain.pop();
|
||||
if !whole {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The most objects [`locked_objects_at`] lists.
|
||||
pub const MAX_LOCKED_AT: usize = 20;
|
||||
|
||||
@@ -1417,6 +1563,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)) {
|
||||
|
||||
@@ -1992,10 +1992,58 @@ fn objects_at_matches_repeated_hits_on_random_documents() {
|
||||
let p = Point::new(f64::from(next(120)), f64::from(next(120)));
|
||||
let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() };
|
||||
assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None), "round {round}, {p:?}, {opt:?}");
|
||||
assert_eq!(leaf_chains(leaves_at(&d, p, opt)), leaf_chains(leaves_at_repeated(&d, p, opt)), "leaves: round {round}, {p:?}, {opt:?}");
|
||||
// Isolated in a group of the document, now and then.
|
||||
let groups: Vec<NodeId> =
|
||||
d.layers[0].children().into_iter().flatten().filter(|n| n.is_container() && !n.is_layer()).map(|n| n.id).collect();
|
||||
if let Some(&g) = groups.first().filter(|_| next(3) == 0) {
|
||||
let opt = HitOptions { scope: Some(g), ..opt };
|
||||
assert_eq!(leaf_chains(leaves_at(&d, p, opt)), leaf_chains(leaves_at_repeated(&d, p, opt)), "isolated: round {round}, {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A hit's leaf, ancestry, kind, layer count and edited envelope.
|
||||
type LeafChain = (NodeId, Vec<NodeId>, HitKind, usize, Option<NodeId>);
|
||||
|
||||
/// Each hit's [`LeafChain`], to compare two lists.
|
||||
fn leaf_chains(hits: Vec<Hit>) -> Vec<LeafChain> {
|
||||
hits.into_iter().map(|h| (h.leaf, h.ancestry, h.kind, h.layers, h.contents_of)).collect()
|
||||
}
|
||||
|
||||
/// Select Behind steps through the members of groups one by one, front to back, in one traversal
|
||||
/// for a large stack, as the hit test repeated over what is left finds them.
|
||||
#[test]
|
||||
fn leaves_at_lists_group_members_one_by_one() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let layer = d.layers[0].id;
|
||||
let square = |d: &mut Document| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art());
|
||||
let below = square(&mut d);
|
||||
let below_id = below.id;
|
||||
d.insert(Some(layer), usize::MAX, below).unwrap();
|
||||
let members: Vec<Node> = (0..300).map(|_| square(&mut d)).collect();
|
||||
let mut ids: Vec<NodeId> = members.iter().map(|n| n.id).collect();
|
||||
let g = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap();
|
||||
ids.reverse();
|
||||
ids.push(below_id);
|
||||
let p = Point::new(25.0, 25.0);
|
||||
let hits = leaves_at(&d, p, HitOptions::default());
|
||||
assert_eq!(hits.len(), MAX_LEAVES_AT, "the list stops at its limit");
|
||||
assert_eq!(hits.iter().map(|h| h.leaf).collect::<Vec<_>>(), ids[..MAX_LEAVES_AT], "the group's members, topmost first");
|
||||
assert!(hits.iter().all(|h| h.ancestry.contains(&g)));
|
||||
assert_eq!(leaf_chains(hits), leaf_chains(leaves_at_repeated(&d, p, HitOptions::default())));
|
||||
// Hidden past the limit, the object below the group comes after the members that are left.
|
||||
for id in &ids[3..300] {
|
||||
d.node_mut(*id).unwrap().visible = false;
|
||||
}
|
||||
let shown: Vec<NodeId> = leaves_at(&d, p, HitOptions::default()).iter().map(|h| h.leaf).collect();
|
||||
assert_eq!(shown, [ids[0], ids[1], ids[2], below_id]);
|
||||
let isolated = leaves_at(&d, p, HitOptions { scope: Some(g), ..Default::default() });
|
||||
assert!(!isolated.iter().any(|h| h.leaf == below_id), "isolated: only the group's members");
|
||||
}
|
||||
|
||||
/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the
|
||||
/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times.
|
||||
fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
|
||||
@@ -2322,6 +2370,40 @@ fn select_behind_keeps_one_art_limit_when_it_falls_back() {
|
||||
assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked");
|
||||
}
|
||||
|
||||
/// [`leaves_at`] falls back to repeated hit tests at a clip group, after the hits its single
|
||||
/// traversal found above it: an instance hit by its art, with the limit of symbol art then used
|
||||
/// up, stays in the list.
|
||||
#[test]
|
||||
fn leaves_at_keeps_the_hits_above_a_clip_group_it_falls_back_at() {
|
||||
let p = Point::new(150.0, 50.0);
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
clipped_symbol(&mut d, false);
|
||||
// A clip group at the bottom of the layer, its art under (150, 50).
|
||||
let square = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art()));
|
||||
let (mask, art) = (d.alloc_id(), d.alloc_id());
|
||||
let mut clip_group = Node::group(d.alloc_id(), vec![square(mask), square(art)]);
|
||||
clip_group.set_clips(true);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, clip_group).unwrap();
|
||||
let (mut shown_mask, shown_art) = half_clipped(&mut d);
|
||||
shown_mask.appearance.effects.push(test_move());
|
||||
let mut shown = Node::group(d.alloc_id(), vec![Arc::new(shown_mask), Arc::new(shown_art)]);
|
||||
shown.set_clips(true);
|
||||
group_symbol(&mut d, "Shown", vec![Arc::new(shown)]);
|
||||
let hit = instance_of(&mut d, "Shown");
|
||||
let hit_id = hit.id;
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap();
|
||||
for _ in 0..32 {
|
||||
let inst = instance_of(&mut d, "Clipped");
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
}
|
||||
let (hits, _, arts) = with_art_limit(100, || leaves_at(&d, p, HitOptions::default()));
|
||||
let leaves: Vec<NodeId> = hits.iter().map(|h| h.leaf).collect();
|
||||
assert_eq!(leaves.first(), Some(&hit_id), "hit before the fallback: {leaves:?}");
|
||||
assert!(leaves.contains(&art), "the clipped art after it: {leaves:?}");
|
||||
assert!(arts <= 34, "{arts} instances' art walked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_skip() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
|
||||
+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();
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
@@ -457,19 +460,28 @@ 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.
|
||||
/// 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]> {
|
||||
if plain.width() < 1e-6 || plain.height() < 1e-6 {
|
||||
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);
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
@@ -431,6 +431,17 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// The box of what a path, or the paths of a compound path, draw before the strokes' reach
|
||||
/// ([`PathData::drawn_bounds`]): lone anchors of closed subpaths count only with `dots`. Other
|
||||
/// members of a compound path count by their geometric box. `None` when nothing is drawn.
|
||||
fn drawn(&self, symbols: Option<&SymbolBoxes>, dots: bool) -> Option<Rect> {
|
||||
match &self.kind {
|
||||
NodeKind::Path { path, .. } => path.drawn_bounds(dots),
|
||||
NodeKind::Compound { .. } => self.editing_children().iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.drawn(symbols, dots))),
|
||||
_ => self.geometric(symbols),
|
||||
}
|
||||
}
|
||||
|
||||
/// Visual bounds: what the object paints, its strokes included (paths and compound paths
|
||||
/// measure theirs along their own shape, see [`Appearance::stroked_bounds`]). An image is
|
||||
/// measured by its frame. A symbol instance is measured as in [`Node::geometric_bounds`],
|
||||
@@ -485,7 +496,9 @@ impl Node {
|
||||
self.geometric(symbols).map(|b| b.inflate(o, o))
|
||||
}
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
|
||||
let b = self.geometric(symbols)?;
|
||||
// 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::SymbolInstance { symbol, xf } => {
|
||||
|
||||
@@ -469,6 +469,60 @@ fn visual_bounds_include_stroke() {
|
||||
assert_eq!(p.visual_bounds(), Some(Rect::new(-0.5, -0.5, 10.5, 10.5)));
|
||||
}
|
||||
|
||||
/// A lone anchor 20 points right of a stroked square widens the path's geometric box, and its
|
||||
/// visual box only where the stroke draws it: as the dot of a round or projecting cap on a closed
|
||||
/// subpath. An open lone anchor, or a closed one under a butt cap, draws nothing.
|
||||
#[test]
|
||||
fn a_lone_anchor_widens_the_visual_box_only_where_its_cap_draws_a_dot() {
|
||||
use crate::appearance::LineCap;
|
||||
use vectorcraft_geom::{Point, SubPath};
|
||||
let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let node = |closed: bool, cap: LineCap| {
|
||||
let mut subpaths = square.subpaths.clone();
|
||||
subpaths.push(SubPath::polyline(&[Point::new(30.0, 5.0)], closed));
|
||||
let mut p = Node::path(NodeId(2), PathData::new(subpaths), Appearance::default_art());
|
||||
let s = p.appearance.stroke_mut().unwrap();
|
||||
(s.cap, s.join) = (cap, crate::appearance::LineJoin::Round);
|
||||
p
|
||||
};
|
||||
for closed in [false, true] {
|
||||
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
|
||||
let p = node(closed, cap);
|
||||
let geometric = p.geometric_bounds().unwrap();
|
||||
let visual = p.visual_bounds().unwrap();
|
||||
assert!(geometric.x1 >= 30.0, "{closed} {cap:?}: the geometric box {geometric:?} leaves out the lone anchor");
|
||||
let dot = closed && cap != LineCap::Butt;
|
||||
assert_eq!(visual.x1 > 30.0, dot, "{closed} {cap:?}: the visual box {visual:?}");
|
||||
assert!(dot || visual.x1 < 11.0, "{closed} {cap:?}: the visual box {visual:?} reaches toward the lone anchor");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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]
|
||||
|
||||
@@ -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> {
|
||||
@@ -470,6 +486,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();
|
||||
|
||||
+81
-5
@@ -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
|
||||
@@ -998,4 +1038,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]);
|
||||
}
|
||||
}
|
||||
@@ -291,3 +291,15 @@ fn q_and_ha_suffixes_do_not_take_other_units_suffixes() {
|
||||
// A suffix after math covers the whole expression, as for the other units.
|
||||
assert!((Unit::Points.parse("26/2 q").unwrap() - Unit::Q.to_pt(13.0)).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_area_formats_and_trims_cleanly() {
|
||||
assert_eq!(Unit::Points.format_area(100.0), "100 pt²");
|
||||
assert_eq!(Unit::Inches.format_area(4.5 * 72.0 * 72.0), "4.5 in²");
|
||||
let mm_side = Unit::Millimeters.to_pt(1.0);
|
||||
assert_eq!(Unit::Millimeters.format_area(12.5 * mm_side * mm_side), "12.5 mm²");
|
||||
assert_eq!(Unit::Points.format_area(0.0), "0 pt²");
|
||||
assert_eq!(Unit::Points.format_area(-10.0), "0 pt²");
|
||||
assert_eq!(Unit::Points.format_area(f64::NAN), "0 pt²");
|
||||
assert_eq!(Unit::Points.format_area(f64::INFINITY), "0 pt²");
|
||||
}
|
||||
@@ -166,6 +166,19 @@ impl Unit {
|
||||
pub fn format(self, pt: f64) -> String {
|
||||
format!("{} {}", self.number(pt), self.suffix())
|
||||
}
|
||||
/// Format an area in square points into this unit (e.g. `12.5 mm²`, `4.5 in²`, `100 pt²`).
|
||||
pub fn format_area(self, pt2: f64) -> String {
|
||||
if !pt2.is_finite() || pt2 <= 0.0 {
|
||||
return format!("0 {}²", self.suffix());
|
||||
}
|
||||
let side = self.from_pt(1.0);
|
||||
let val = pt2 * side * side;
|
||||
let decimals = if matches!(self, Unit::Points | Unit::Pixels | Unit::Picas | Unit::Q | Unit::Ha) { 3 } else { 4 };
|
||||
let s = format!("{:.*}", decimals, val);
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
let s = if s == "-0" || s.is_empty() { "0" } else { s };
|
||||
format!("{s} {}²", self.suffix())
|
||||
}
|
||||
/// [`Unit::format`] without the suffix (`12.5`), for narrow fields.
|
||||
pub fn number(self, pt: f64) -> String {
|
||||
// Three decimals for the small units (`595.276 pt`), four for the large ones (`8.2677 in`,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -619,7 +619,12 @@ fn moved_type(n: &Node, moves: &[serde_json::Value]) -> Option<Vec<Node>> {
|
||||
}
|
||||
let (_, all) = glyph_outlines(t);
|
||||
let outline = PathData::from_bezpath(&all).transformed(t.xf);
|
||||
let ink = outline.bounds()?;
|
||||
// A contour of one anchor paints only as the dot of a round or projecting character stroke cap.
|
||||
let dots = t
|
||||
.runs
|
||||
.iter()
|
||||
.any(|r| r.style.appearance().painted_strokes().any(|s| matches!(s.cap, vectorcraft_doc::LineCap::Round | vectorcraft_doc::LineCap::Square)));
|
||||
let ink = outline.drawn_bounds(dots)?;
|
||||
let offsets = transform_offsets(moves, &outline)?;
|
||||
if offsets.len() > MAX_TYPE_COPIES {
|
||||
return None;
|
||||
|
||||
@@ -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}),
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -447,6 +447,12 @@ pub(crate) fn apply_one(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &Geo
|
||||
budget.fits(Budget::of(&out)).then_some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The subpaths the Offset Path effect has offset on this thread.
|
||||
pub(crate) static OFFSET_SUBPATHS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Does geometry effect `id` build within the anchors it is given?
|
||||
fn builds_within(id: &str) -> bool {
|
||||
matches!(id, "distort.freeDistort" | "distort.roughen" | "distort.transform" | "distort.twist" | "distort.zigZag") || id.starts_with("warp.")
|
||||
@@ -456,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());
|
||||
}
|
||||
@@ -472,6 +479,8 @@ fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomCont
|
||||
if off.abs() < 1e-9 {
|
||||
return path.clone();
|
||||
}
|
||||
#[cfg(test)]
|
||||
OFFSET_SUBPATHS.with(|n| n.set(n.get() + path.subpaths.len()));
|
||||
vectorcraft_pathops::offset_path(path, off, join(p, "joins"), num(p, "miterLimit", 4.0).clamp(1.0, 500.0))
|
||||
}
|
||||
// Outline Object returns the geometry unchanged. Type reaches every geometry effect as its
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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).
|
||||
|
||||
+195
-42
@@ -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.
|
||||
@@ -1625,12 +1648,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 +1706,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 +1749,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 +1762,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 +1775,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 +1888,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 +1910,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 +1951,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 +2566,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 +2581,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 +2706,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 +2723,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 +2749,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 +2828,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 +2903,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));
|
||||
|
||||
@@ -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;
|
||||
@@ -1117,10 +1118,10 @@ fn transform_copies_before_offset_path_evaluates_without_ram_spike() {
|
||||
fx("path.offsetPath", json!({"offset": 10.0, "joins": "round"})),
|
||||
];
|
||||
let path = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
let start = std::time::Instant::now();
|
||||
crate::geometry::OFFSET_SUBPATHS.with(|n| n.set(0));
|
||||
let out = apply_geometry(&effects, &path, path.bounds().unwrap());
|
||||
let elapsed = start.elapsed();
|
||||
assert!(elapsed < std::time::Duration::from_secs(2), "elapsed: {:?}", elapsed);
|
||||
// Offset Path offsets the one rectangle, not the 31 overlapping copies.
|
||||
assert_eq!(crate::geometry::OFFSET_SUBPATHS.with(|n| n.get()), path.subpaths.len());
|
||||
assert_eq!(out.subpaths.len(), 31);
|
||||
}
|
||||
|
||||
@@ -1135,10 +1136,10 @@ fn reshape_leaves_within_optimizes_transform_before_terminal_offset_path() {
|
||||
let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 10}));
|
||||
let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"}));
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
crate::geometry::OFFSET_SUBPATHS.with(|n| n.set(0));
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&transform, &offset], Budget::EFFECTS, None);
|
||||
let elapsed = start.elapsed();
|
||||
assert!(elapsed < std::time::Duration::from_secs(2));
|
||||
// Offset Path offsets each leaf's one rectangle, not its 11 copies.
|
||||
assert_eq!(crate::geometry::OFFSET_SUBPATHS.with(|n| n.get()), 5);
|
||||
|
||||
let children = art.children().unwrap();
|
||||
assert_eq!(children.len(), 5);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -120,8 +120,10 @@ 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.
|
||||
# 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.
|
||||
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"] }
|
||||
|
||||
@@ -964,6 +964,8 @@ pub use variablecmds::utf16_order_without_mark;
|
||||
/// file: its size limit, its text, its cells and the data `graph.setData` takes from them.
|
||||
pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
|
||||
|
||||
/// The kind of variable that drives an object's content (`variable.setBinding`).
|
||||
pub(crate) use variablecmds::content_kind;
|
||||
/// The Variables panel's sort (`variable.sort`) and its rows in that order.
|
||||
pub use variablecmds::{VariableSort, VariableSortKey, variable_order};
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fold",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true when the gap is within the larger of tolerance and 0.5% of the distance between the hinge's two ends. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
|
||||
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it; the lowest id wins a tie. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true when the gap is within the larger of tolerance and 0.5% of the distance between the hinge's two ends. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
|
||||
has_doc,
|
||||
fold_command
|
||||
)]
|
||||
|
||||
@@ -4,14 +4,15 @@
|
||||
//! (`vectorcraft_tools::addons::parametric_shape`), which SVG export leaves out.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point};
|
||||
use vectorcraft_doc::{Document, Node, NodeKind, Scaling};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point};
|
||||
use vectorcraft_pathops::addons::pathtools::shapes::{ParametricShape, ShapeKind, recognise};
|
||||
use vectorcraft_render::effects;
|
||||
use vectorcraft_tools::addons::parametric_shape::{CREATE, EDIT, KEY, apply, read, stored, to_json};
|
||||
|
||||
use super::super::super::menucmds::whole_or;
|
||||
use super::super::super::{CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection};
|
||||
use super::super::super::object;
|
||||
use super::super::super::{CommandSpec, bad, check_switches, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection};
|
||||
use crate::{EngineError, MAX_COORD, Result, Session};
|
||||
|
||||
/// The undo step's name and the command's label.
|
||||
@@ -33,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Parametric Shape",
|
||||
[],
|
||||
None,
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; a new center, size or rotation moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with it, and with `strokes` its strokes and effects scale; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
@@ -62,6 +63,25 @@ fn shape_node(n: &mut Node, s: &ParametricShape, path: PathData) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The transform that takes the outline of `old` to the one `new` would have if only their
|
||||
/// center, size and rotation differed: what moves, turns and scales the rest of the object (a
|
||||
/// linked opacity mask, gradients and patterns placed on it) with the new numbers.
|
||||
fn carry(old: &ParametricShape, new: &ParametricShape) -> Option<Affine> {
|
||||
let same = old.center == new.center && old.width == new.width && old.height == new.height && old.rotation == new.rotation;
|
||||
(!same).then(|| new.frame() * Affine::scale_non_uniform(new.width / old.width, new.height / old.height) * old.frame().inverse())
|
||||
}
|
||||
|
||||
/// Path node `n`, shape `old`, becomes shape `new`: the node takes the transform between them
|
||||
/// ([`carry`]) with `sc`, and then the outline and numbers of `new` ([`shape_node`]).
|
||||
fn reshape(n: &mut Node, old: &ParametricShape, new: &ParametricShape, sc: Scaling, cmd: &str) -> Result<()> {
|
||||
let path = outline(new, cmd)?;
|
||||
if let Some(xf) = carry(old, new) {
|
||||
n.transform(xf, sc);
|
||||
}
|
||||
shape_node(n, new, path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The outline of `s`, checked already.
|
||||
fn outline(s: &ParametricShape, cmd: &str) -> Result<PathData> {
|
||||
s.path().ok_or_else(|| bad(cmd, "the shape's numbers are out of range"))
|
||||
@@ -97,6 +117,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "the path is locked or hidden"));
|
||||
}
|
||||
let old = d.node(id).and_then(read).ok_or_else(|| bad(C, "the object is not an editable parametric shape"))?;
|
||||
check_switches(p, &["strokes", "corners", "patterns"], C)?;
|
||||
let reference = match p.get("reference").filter(|v| !v.is_null()) {
|
||||
Some(_) => match whole_or(p, "reference", 4, C)? {
|
||||
i @ 0..=8 => Some(i as usize),
|
||||
@@ -121,17 +142,21 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let path = outline(&shape, C)?;
|
||||
// A new center, size or rotation moves, turns or scales the object as a transform does,
|
||||
// with Scale Strokes & Effects and Transform Patterns from `strokes` and `patterns` or the
|
||||
// preferences.
|
||||
let scales = carry(&old, &shape).is_some_and(|xf| Scaling::factor(xf).is_some());
|
||||
let base = if scales { object::scaling(s, p) } else { Scaling::default() };
|
||||
let sc = Scaling { patterns: object::transform_patterns(s, p, &[id])?, ..base };
|
||||
s.edit(EDIT, |d, sel| {
|
||||
shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, path);
|
||||
reshape(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &old, &shape, sc, C)?;
|
||||
if let Some((i, m, was)) = keep
|
||||
&& let Some(now) = boxed(d, m).map(|(_, b)| b.reference_point(i))
|
||||
&& now != was
|
||||
{
|
||||
let mut moved = shape;
|
||||
moved.center += was - now;
|
||||
let path = outline(&moved, C)?;
|
||||
shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &moved, path);
|
||||
reshape(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, &moved, sc, C)?;
|
||||
}
|
||||
// A shape named by `id` and not selected is not checked after the edit: one the edit
|
||||
// takes past the coordinate limit is an error here, and nothing changes.
|
||||
|
||||
@@ -562,6 +562,50 @@ fn set_keeps_the_reference_point_of_the_bounding_box_in_place() {
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": edge.0, "width": 180, "reference": 2})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_takes_a_linked_mask_and_placed_gradient_with_the_shape() {
|
||||
let mut s = session();
|
||||
let id =
|
||||
id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": "rectangle", "center": [200, 150], "width": 100, "height": 60})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [id.0], "gradient": {"kind": "linear"}})).unwrap();
|
||||
s.execute("paint.setGradientGeom", &json!({"ids": [id.0], "start": [170, 150], "end": [230, 150]})).unwrap();
|
||||
let m = id_of(&s.execute("shape.rectangle", &json!({"x": 160, "y": 130, "width": 40, "height": 40})).unwrap());
|
||||
s.execute("transparency.makeOpacityMask", &json!({"ids": [id.0, m.0]})).unwrap();
|
||||
// Where the mask art and the gradient's vector sit in the shape's own frame: the same before and after.
|
||||
let local = |s: &Session| {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let frame = shape_of(s, id).unwrap();
|
||||
let to_local = vectorcraft_geom::Affine::scale_non_uniform(1.0 / frame.width, 1.0 / frame.height) * frame.frame().inverse();
|
||||
let mask = n.extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap();
|
||||
let vectorcraft_color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("a gradient fill") };
|
||||
let geom = g.geom.unwrap();
|
||||
[to_local * mask.center(), to_local * geom.start, to_local * geom.end]
|
||||
};
|
||||
let was = local(&s);
|
||||
for edit in [
|
||||
json!({"center": [320, 260]}),
|
||||
json!({"width": 180}),
|
||||
json!({"rotation": 90}),
|
||||
json!({"height": 90, "reference": 0}),
|
||||
json!({"count": 6, "kind": "polygon"}),
|
||||
] {
|
||||
let mut p = edit.clone();
|
||||
p["id"] = json!(id.0);
|
||||
s.execute("addon.pathtools.shape.set", &p).unwrap();
|
||||
for (now, then) in local(&s).iter().zip(&was) {
|
||||
assert!(now.distance(*then) < 1e-9, "{edit}: moved off the shape to {now:?} from {then:?}");
|
||||
}
|
||||
}
|
||||
// With Scale Strokes & Effects on, a new size scales the stroke as a transform does; off, it keeps its weight.
|
||||
let weight = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width();
|
||||
s.execute("stroke.set", &json!({"ids": [id.0], "weight": 4})).unwrap();
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 360, "height": 180, "strokes": false})).unwrap();
|
||||
assert!((weight(&s) - 4.0).abs() < 1e-9);
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 720, "height": 360, "strokes": true})).unwrap();
|
||||
assert!(weight(&s) > 4.0 + 1.0, "the stroke scaled with the shape");
|
||||
refuses(&mut s, "addon.pathtools.shape.set", &[json!({"id": id.0, "width": 50, "strokes": "yes"})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_shape_params_are_refused() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -322,35 +322,52 @@ impl ItemTarget {
|
||||
/// targets have. In a target without an equal item, and for any other target, the row stands
|
||||
/// for itself. Every entry is `Some`.
|
||||
pub(crate) fn per_target(self, s: &Session, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
|
||||
let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] };
|
||||
let Some(st) = s.active().filter(|_| ids.len() >= 2) else { return vec![Some(self); ids.len()] };
|
||||
let k = self.anchor(s, ids);
|
||||
let Some(first) = ids.get(k).and_then(|id| st.doc.node(*id)) else { return vec![Some(self); ids.len()] };
|
||||
ids.iter()
|
||||
.enumerate()
|
||||
.map(|(j, id)| match st.doc.node(*id) {
|
||||
self.each_target(s, ids).collect()
|
||||
}
|
||||
|
||||
/// [`ItemTarget::per_target`], one target at a time: a caller that stops at the first answer
|
||||
/// matches only the targets it reads against the anchor's stack.
|
||||
pub(crate) fn each_target<'a>(self, s: &'a Session, ids: &'a [NodeId]) -> impl Iterator<Item = Option<ItemTarget>> + 'a {
|
||||
let anchor = match self {
|
||||
ItemTarget::Item { aligned: true, .. } if ids.len() >= 2 => s.active().and_then(|st| {
|
||||
let k = self.anchor(s, ids);
|
||||
Some((&st.doc, k, ids.get(k).and_then(|id| st.doc.node(*id))?))
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
ids.iter().enumerate().map(move |(j, id)| {
|
||||
let (ItemTarget::Item { index, explicit, .. }, Some((d, k, first))) = (self, anchor) else { return Some(self) };
|
||||
match d.node(*id) {
|
||||
Some(n) if j != k => {
|
||||
let at = SharedStack::of(&[&*first.appearance, &*n.appearance]).item_in(index, 1);
|
||||
let at = shared_stack(&first.appearance, &n.appearance).item_in(index, 1);
|
||||
Some(at.map_or(self, |index| ItemTarget::Item { index, explicit, aligned: true }))
|
||||
}
|
||||
_ => Some(self),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// [`ItemTarget::per_target`], with an explicit aligned item a row of the stack of `of` (see [`design_reference`]),
|
||||
/// which is not among `ids`, when there is one: each target edits the item equal to it there, and a target without
|
||||
/// an equal item is left out (`None`).
|
||||
pub(crate) fn per_target_of(self, s: &Session, of: Option<NodeId>, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
|
||||
let ItemTarget::Item { index, explicit: true, aligned: true } = self else { return self.per_target(s, ids) };
|
||||
let Some(d) = s.active().map(|st| &st.doc) else { return self.per_target(s, ids) };
|
||||
let Some(r) = of.and_then(|of| d.node(of)) else { return self.per_target(s, ids) };
|
||||
ids.iter()
|
||||
.map(|id| {
|
||||
let index = SharedStack::of(&[&*r.appearance, &*d.node(*id)?.appearance]).item_in(index, 1)?;
|
||||
self.each_target_of(s, of, ids).collect()
|
||||
}
|
||||
|
||||
/// [`ItemTarget::per_target_of`], one target at a time (see [`ItemTarget::each_target`]).
|
||||
pub(crate) fn each_target_of<'a>(self, s: &'a Session, of: Option<NodeId>, ids: &'a [NodeId]) -> impl Iterator<Item = Option<ItemTarget>> + 'a {
|
||||
let reference = match self {
|
||||
ItemTarget::Item { index, explicit: true, aligned: true } => s.active().map(|st| &st.doc).and_then(|d| Some((d, d.node(of?)?, index))),
|
||||
_ => None,
|
||||
};
|
||||
let own = reference.is_none().then(|| self.each_target(s, ids));
|
||||
let shared = reference.map(|(d, r, index)| {
|
||||
ids.iter().map(move |id| {
|
||||
let index = shared_stack(&r.appearance, &d.node(*id)?.appearance).item_in(index, 1)?;
|
||||
Some(ItemTarget::Item { index, explicit: true, aligned: true })
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
own.into_iter().flatten().chain(shared.into_iter().flatten())
|
||||
}
|
||||
|
||||
/// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of
|
||||
@@ -392,6 +409,26 @@ impl ItemTarget {
|
||||
}
|
||||
}
|
||||
|
||||
/// The stack that `a` and `b` share ([`SharedStack::of`]), which [`ItemTarget::each_target`] and
|
||||
/// [`ItemTarget::each_target_of`] match each target's rows in.
|
||||
fn shared_stack(a: &Appearance, b: &Appearance) -> SharedStack {
|
||||
#[cfg(test)]
|
||||
STACKS_MATCHED.set(STACKS_MATCHED.get() + 1);
|
||||
SharedStack::of(&[a, b])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// [`stacks_matched`] of this thread.
|
||||
static STACKS_MATCHED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many shared stacks [`shared_stack`] has built on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn stacks_matched() -> u64 {
|
||||
STACKS_MATCHED.get()
|
||||
}
|
||||
|
||||
/// Does `p` say its item and effect indices are rows of the first target's stack (`aligned`),
|
||||
/// which each other target edits where it has them (see [`ItemTarget::per_target`])?
|
||||
pub(crate) fn aligned(p: &Value, cmd: &str) -> Result<bool> {
|
||||
@@ -865,7 +902,7 @@ fn edit_items_writing_then(
|
||||
/// The first of `ids` that [`edit_items`] aimed at `item` with `of` changes, and the item it changes there. Read it
|
||||
/// before the edit: once edited, a row that was equal to a row of the art of `of` no longer is.
|
||||
pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option<NodeId>, ids: &[NodeId]) -> Option<(NodeId, ItemTarget)> {
|
||||
ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
|
||||
ids.iter().zip(item.each_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
|
||||
}
|
||||
|
||||
/// Keep the object rows of the graph labels among `ids` for every label of their kind
|
||||
|
||||
@@ -38,7 +38,7 @@ mod dynamic;
|
||||
mod symbolism;
|
||||
mod symbols;
|
||||
|
||||
pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint};
|
||||
pub(crate) use brushes::{apply_brush, brush_targets, frame_marker, stroke_paint};
|
||||
use brushes::{
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options,
|
||||
brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
|
||||
@@ -766,10 +766,12 @@ pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]): the
|
||||
/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]), and
|
||||
/// the tile such a rectangle at the back of a pattern's art marks (`object.pattern.replaceArt`): the
|
||||
/// rectangle's bounds, when `n` is a path of one closed subpath through the four corners of its
|
||||
/// bounds, without curves, whose fills and strokes paint nothing and that has no other appearance.
|
||||
fn frame_marker(n: &Node) -> Option<vectorcraft_geom::Rect> {
|
||||
/// bounds in order around them (either way), without curves, whose fills and strokes paint nothing
|
||||
/// and that has no other appearance.
|
||||
pub(crate) fn frame_marker(n: &Node) -> Option<vectorcraft_geom::Rect> {
|
||||
let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return None };
|
||||
let unpainted = n.appearance.effects.is_empty()
|
||||
&& n.appearance.items.iter().all(|i| match i {
|
||||
@@ -781,7 +783,9 @@ fn frame_marker(n: &Node) -> Option<vectorcraft_geom::Rect> {
|
||||
let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)];
|
||||
let at_corners = sp.anchors.len() == 4
|
||||
&& sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p)
|
||||
&& corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c));
|
||||
&& corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c))
|
||||
// Each side, the closing one included, joins two corners that share an edge.
|
||||
&& sp.anchors.iter().zip(sp.anchors.iter().cycle().skip(1)).all(|(a, b)| a.p.x == b.p.x || a.p.y == b.p.y);
|
||||
(unpainted && sp.closed && at_corners && r.width() > 1e-9 && r.height() > 1e-9).then_some(r)
|
||||
}
|
||||
|
||||
|
||||
@@ -1601,7 +1601,8 @@ impl Clipboard {
|
||||
/// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's
|
||||
/// filter of its name; one that draws another definition than that filter takes the document's
|
||||
/// filter when pasted back into the document it came from, and elsewhere keeps its own under a
|
||||
/// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone. When that name would
|
||||
/// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone; an
|
||||
/// effect of the document that draws the same definition under a name no filter has gives that name. When that name would
|
||||
/// make the filter too long to draw, the free name is a shorter start of its name ("Shif"), else
|
||||
/// a free letter, digit or other printable ASCII character; the filter's id is always its name. An error when no free name fits.
|
||||
fn filter_links(&self, d: &Document, same_doc: bool) -> Result<BTreeMap<(String, String), (String, String)>> {
|
||||
@@ -1627,6 +1628,8 @@ impl Clipboard {
|
||||
}
|
||||
let mut taken: BTreeSet<String> = d.svg_filters.iter().map(|f| f.name.clone()).chain(found.iter().map(|(n, _)| n.clone())).collect();
|
||||
let mut effects_read = false;
|
||||
// The filter effects of the document, by name and definition.
|
||||
let mut held_effects = BTreeSet::new();
|
||||
let mut links = BTreeMap::new();
|
||||
for (name, xml) in found {
|
||||
let Some(held) = d.svg_filters.iter().find(|f| f.name == name).filter(|f| f.xml != xml.trim()) else { continue };
|
||||
@@ -1640,14 +1643,28 @@ impl Clipboard {
|
||||
effects_read = true;
|
||||
for root in d.art_roots() {
|
||||
node_filter_names(root, &mut taken);
|
||||
node_filters(root, &mut held_effects);
|
||||
}
|
||||
for a in vectorcraft_brush::library(d).iter().flat_map(Brush::art) {
|
||||
node_filter_names(a, &mut taken);
|
||||
node_filters(a, &mut held_effects);
|
||||
}
|
||||
for g in &d.graphic_styles {
|
||||
appearance_filter_names(&g.appearance, &mut taken);
|
||||
appearance_filters(&g.appearance, &mut held_effects);
|
||||
}
|
||||
}
|
||||
// An effect of the document that already draws this filter under a name no filter
|
||||
// of the document has (one pasted or loaded before) gives its name, so pasting or
|
||||
// loading the same filter again adds no other name.
|
||||
let earlier = held_effects.iter().find(|(n, x)| {
|
||||
!d.svg_filters.iter().any(|f| &f.name == n)
|
||||
&& vectorcraft_render::effects::svg_filter::with_id(&xml, n).is_some_and(|drawn| drawn == *x)
|
||||
});
|
||||
if let Some((n, x)) = earlier {
|
||||
links.insert((name, xml), (n.clone(), x.clone()));
|
||||
continue;
|
||||
}
|
||||
// Free names made from the starts of the name, longest first, then free letters and
|
||||
// digits, then other single printable ASCII characters: the first under which the
|
||||
// filter still draws.
|
||||
@@ -1845,6 +1862,8 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
|
||||
let clip = Clipboard::with_used(src, &used, &library, vec![]);
|
||||
let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::<BTreeSet<_>>());
|
||||
let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?;
|
||||
// Graphs in the symbols added draw with the designs `d` kept, as pasted ones do.
|
||||
crate::cmd::graph::redraw_symbols_with_designs(d, &out.added_symbols, &out.kept_designs);
|
||||
let mut placed: Vec<LoadedStyle> = vec![];
|
||||
for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] {
|
||||
for s in list {
|
||||
@@ -1857,6 +1876,35 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
|
||||
Ok(placed)
|
||||
}
|
||||
|
||||
/// Add to `d` the swatches, patterns, symbols and brushes (and what their art uses) that the
|
||||
/// appearance `look` of `src` and the character style attributes `attrs` of `src` paint with, as
|
||||
/// [`import_text_styles`] adds those of loaded styles, and give back `look` and `attrs` relinked to
|
||||
/// them (a resource `d` has under the same name and with the same contents is used; another is
|
||||
/// added under a free name; a global or spot color whose name `d` gives another color is `d`'s;
|
||||
/// an SVG filter whose name `d` gives another filter is renamed).
|
||||
pub(crate) fn import_looks(
|
||||
src: &Document,
|
||||
d: &mut Document,
|
||||
look: &Appearance,
|
||||
attrs: &Map<String, Value>,
|
||||
) -> Result<(Appearance, Map<String, Value>)> {
|
||||
let library = OnceCell::new();
|
||||
let defs = Defs::of(src, &library);
|
||||
let mut used = Used::default();
|
||||
used.follow(&defs, vec![Source::Appearance(look), Source::Attrs(attrs)]);
|
||||
// The look goes on an empty path, so that its SVG filters are renamed where `d` gives their
|
||||
// names other filters, as a pasted object's are.
|
||||
let carrier = Node::path(vectorcraft_doc::NodeId(0), vectorcraft_geom::PathData::default(), look.clone());
|
||||
let clip = Clipboard::with_used(src, &used, &library, vec![carrier]);
|
||||
let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?;
|
||||
// Graphs in the symbols added draw with the designs `d` kept, as pasted ones do.
|
||||
crate::cmd::graph::redraw_symbols_with_designs(d, &out.added_symbols, &out.kept_designs);
|
||||
let (mut look, mut attrs) = (look.clone(), attrs.clone());
|
||||
out.relink.appearance(&mut look);
|
||||
out.relink.attrs(&mut attrs);
|
||||
Ok((look, attrs))
|
||||
}
|
||||
|
||||
/// The resources graph designs `names` of `src` use, through the definitions they lead to.
|
||||
fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used {
|
||||
let mut used = Used::default();
|
||||
|
||||
@@ -593,10 +593,11 @@ fn mode_color(col: &Color, link: proof::Link, bases: &BTreeMap<String, Color>, c
|
||||
/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks,
|
||||
/// effect colors and the series paints and label styles that graphs keep included), symbols,
|
||||
/// graph designs, pattern tiles (the tile that pattern editing's Cancel puts back included),
|
||||
/// graphic styles (their effects included), brushes (their art and a Hue Shift key color) and
|
||||
/// swatches through the color settings (`intent`, default: theirs) → how many colors of the art
|
||||
/// (opacity masks, effect colors and graphs' paints included), symbols, graph designs and pattern
|
||||
/// tiles changed; the colors of graphic styles and brushes convert without being counted. Gray
|
||||
/// graphic styles (their effects included), brushes (their art and a Hue Shift key color),
|
||||
/// character and paragraph styles (their fill and stroke) and swatches through the color settings
|
||||
/// (`intent`, default: theirs) → how many colors of the art (opacity masks, effect colors and
|
||||
/// graphs' paints included), symbols, graph designs and pattern tiles changed; the colors of
|
||||
/// graphic styles, brushes and text styles convert without being counted. Gray
|
||||
/// colors stay Gray (they print on the black plate in either mode); RGB grays are colors like any
|
||||
/// other and separate through the CMYK profile, unless `grays` puts them on the black plate
|
||||
/// ([`mode_converter`]). Lab colors
|
||||
@@ -608,7 +609,10 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
if !convert {
|
||||
return 0;
|
||||
}
|
||||
convert_colors(d, &mode_converter(mode, intent, grays))
|
||||
let conv = mode_converter(mode, intent, grays);
|
||||
let changed = convert_colors(d, &conv);
|
||||
convert_style_colors(d, &conv);
|
||||
changed
|
||||
}
|
||||
|
||||
/// Every color of `d` that [`set_color_mode`] converts, converted with `conv` → how many colors of
|
||||
|
||||
@@ -204,7 +204,7 @@ fn parse_set(v: &Value, font: &str, kanji: &CompositePart, c: &str) -> Result<Cu
|
||||
|
||||
/// Error unless `fonts` can stand together in a document: names unique in any case, none naming
|
||||
/// an installed font, no part set in a composite font, and at most [`COMPOSITE_FONTS_MAX`].
|
||||
fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
|
||||
pub(crate) fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
|
||||
if fonts.len() > COMPOSITE_FONTS_MAX {
|
||||
return Err(bad(c, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
|
||||
}
|
||||
@@ -237,31 +237,53 @@ fn replace(s: &mut Session, label: &str, after: Vec<CompositeFont>) -> Result<()
|
||||
if before == after {
|
||||
return Ok(());
|
||||
}
|
||||
let changed = register(s, &before, &after);
|
||||
let r = s.edit(label, |d, _| set_fonts(d, &after, &changed));
|
||||
sync(s);
|
||||
r
|
||||
}
|
||||
|
||||
/// Before an edit makes `after` the active document's composite fonts (it has `before`), register
|
||||
/// them in the font database and forget the ones taken out → the lowercased names of the fonts that
|
||||
/// change, for [`set_fonts`]. Run [`sync`] after the edit, whether it was made or not.
|
||||
pub(crate) fn register(s: &mut Session, before: &[CompositeFont], after: &[CompositeFont]) -> Vec<String> {
|
||||
let changed: Vec<String> =
|
||||
before.iter().filter(|b| !after.contains(b)).chain(after.iter().filter(|a| !before.contains(a))).map(|f| f.name.to_lowercase()).collect();
|
||||
// A refused or panicked edit leaves the document without the new fonts: `sync` forgets a name
|
||||
// listed here that the document doesn't define.
|
||||
s.composite_names.extend(after.iter().map(|f| f.name.to_lowercase()));
|
||||
let db = FontDb::global();
|
||||
for f in &before {
|
||||
for f in before {
|
||||
if !after.iter().any(|a| CompositeFont::same_name(&a.name, &f.name)) {
|
||||
db.remove_composite_font(&f.name);
|
||||
}
|
||||
}
|
||||
for f in &after {
|
||||
for f in after {
|
||||
db.set_composite_font(f);
|
||||
}
|
||||
let r = s.edit(label, |d, _| {
|
||||
*d.composite_fonts = after.clone();
|
||||
each_text_mut(d, &mut |t| {
|
||||
if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) {
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
sync(s);
|
||||
r
|
||||
changed
|
||||
}
|
||||
|
||||
/// Make `after` the composite fonts of `d`, and measure the type set in a font of `changed` again.
|
||||
pub(crate) fn set_fonts(d: &mut vectorcraft_doc::Document, after: &[CompositeFont], changed: &[String]) -> Result<()> {
|
||||
*d.composite_fonts = after.to_vec();
|
||||
each_text_mut(d, &mut |t| {
|
||||
if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) {
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// `fonts` with `f` in place of the composite font of its name, or added, as Import Composite Fonts
|
||||
/// adds a font.
|
||||
pub(crate) fn with_font(fonts: &[CompositeFont], f: &CompositeFont) -> Vec<CompositeFont> {
|
||||
let mut after = fonts.to_vec();
|
||||
match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) {
|
||||
Some(a) => *a = f.clone(),
|
||||
None => after.push(f.clone()),
|
||||
}
|
||||
after
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -377,10 +399,7 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if apply {
|
||||
let mut after = s.doc()?.doc.composite_fonts.to_vec();
|
||||
for f in &fonts {
|
||||
match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) {
|
||||
Some(a) => *a = f.clone(),
|
||||
None => after.push(f.clone()),
|
||||
}
|
||||
after = with_font(&after, f);
|
||||
}
|
||||
check_set(&after, C)?;
|
||||
replace(s, "Import Composite Fonts", after)?;
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file, format, effectivePpi, memoryBytes, storedBytes}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one; format: a linked image's file format by its extension, else the format of the pixels the document holds, null when unknown; effectivePpi: [x, y] pixels per inch at the size it is placed at, a distorted image measured at its middle, null when it has no area; memoryBytes: for an embedded image width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, else null; storedBytes: for an embedded image the bytes of the encoded image the document holds, else null; a Linked Images row gives the format, the size, the resolution and the file (`PNG; 1200 × 800 px; 150 ppi — /art/photo.png`), an Embedded Images row the format, the size and the memory (`PNG; 1200 × 800 px; estimated memory 3.7 MiB`)), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freef
Line truncated
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), pathArea?: bool (default true; false skips the paths' area pass, as a category other than objects does), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), pathArea: pt² (the paths' total area, compound paths' included, guides left out; null unless the request covers the Objects category (no category, or objects) and pathArea? is not false: the area pass normalizes every closed path's geometry, so a caller showing another category can skip it), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file, format, effectivePpi, memoryBytes, storedBytes}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one; format: a linked image's file format by its extension, else the format of the pixels the document holds, null when unknown; effectivePpi: [x, y] pixels per inch at the size it is placed at, a distorted image measured at its middle, null when it has no area; memoryBytes: for an embedded image width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, else null; storedBytes: for an embedded image the bytes of the encoded image the document holds, else null; a Linked Images row gives the format, the size, the resolution and the file (`PNG; 1200 × 800 px; 150 ppi — /art/photo.png`), an Embedded Images row the format, the size and the memory (`PNG; 1200 × 800 px; estimated memory 3.7 MiB`)), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which obje
Line truncated
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -445,6 +445,12 @@ fn sections(
|
||||
if let Some(at) = rows.iter().position(|(label, _)| label == "Paths") {
|
||||
rows.insert(at + 1, ("Path Length".into(), u.format(info["pathLength"].as_f64().unwrap_or(0.0))));
|
||||
}
|
||||
let area = info["pathArea"].as_f64().unwrap_or(0.0);
|
||||
if area > 0.0
|
||||
&& let Some(at) = rows.iter().position(|(label, _)| label == "Path Length")
|
||||
{
|
||||
rows.insert(at + 1, ("Path Area".into(), u.format_area(area)));
|
||||
}
|
||||
rows
|
||||
}
|
||||
"graphicStyles" => names("graphicStyleNames"),
|
||||
@@ -755,6 +761,38 @@ fn object_paints(d: &Document, spots: &HashSet<&str>, members: &HashSet<*const N
|
||||
used
|
||||
}
|
||||
|
||||
/// Filled area of a path's closed subpaths under its fill rule (holes subtracted; open subpaths left out).
|
||||
fn closed_path_area(path: &vectorcraft_geom::PathData, rule: vectorcraft_geom::FillRule) -> f64 {
|
||||
let closed = vectorcraft_geom::PathData { subpaths: path.subpaths.iter().filter(|s| s.closed).cloned().collect() };
|
||||
if closed.subpaths.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let a = vectorcraft_pathops::area(&closed, rule);
|
||||
if a.is_finite() && a > 0.0 { a } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Recursively collects non-guide subpaths from a node and its descendants for compound path area calculation.
|
||||
fn collect_compound_subpaths(n: &Node, subs: &mut Vec<vectorcraft_geom::SubPath>) {
|
||||
if n.is_guide() {
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, guide: false, .. } => {
|
||||
subs.extend(path.subpaths.clone());
|
||||
}
|
||||
NodeKind::Compound { children, .. } => {
|
||||
for c in children {
|
||||
collect_compound_subpaths(c, subs);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if let Some((pd, _)) = super::pathops::node_path(n) {
|
||||
subs.extend(pd.subpaths);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.info";
|
||||
let category = str_param(p, "category");
|
||||
@@ -782,6 +820,10 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The paths' total length, as Document Info › Objects shows it (the length of a cut line, a
|
||||
// strip of LEDs along the letters, #1958).
|
||||
let mut path_length = 0.0;
|
||||
let mut path_area = 0.0;
|
||||
// The area normalizes every closed path's geometry, so it is worked out only for a request
|
||||
// that covers the Objects category and does not turn it off with `pathArea: false`.
|
||||
let want_area = bool_or(p, "pathArea", true) && category.is_none_or(|c| c == "objects");
|
||||
// Each font with the number of text objects set in it.
|
||||
let mut fonts: BTreeMap<super::fonts::UsedFont, usize> = BTreeMap::new();
|
||||
let mut images: BTreeMap<String, Value> = BTreeMap::new();
|
||||
@@ -830,6 +872,19 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
members.extend(children.iter().map(|c| std::ptr::from_ref(&**c)));
|
||||
}
|
||||
});
|
||||
// The members of the compound paths that the roots contain. Only these leave their area to the compound.
|
||||
let mut compound_members: HashSet<*const Node> = HashSet::new();
|
||||
for (r, _) in roots.iter().filter(|_| want_area) {
|
||||
r.walk(&mut |n| {
|
||||
if let NodeKind::Compound { children, .. } = &n.kind {
|
||||
for c in children {
|
||||
c.walk(&mut |descendant| {
|
||||
compound_members.insert(std::ptr::from_ref(descendant));
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
// Depth first, in paint order, as `Node::walk` visits: each object with whether it and the groups and layers around it
|
||||
// draw. An object that does not draw is still counted, and its members are visited.
|
||||
let mut stack: Vec<(&Node, bool)> = vec![];
|
||||
@@ -849,14 +904,26 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
NodeKind::Group { clip: true, .. } => Some("clipGroups"),
|
||||
NodeKind::Group { .. } => Some("groups"),
|
||||
NodeKind::Path { guide: true, .. } => Some("guides"),
|
||||
NodeKind::Path { path, .. } => {
|
||||
NodeKind::Path { path, rule, .. } => {
|
||||
let l = path.length();
|
||||
if l.is_finite() {
|
||||
path_length += l;
|
||||
}
|
||||
if want_area && !compound_members.contains(&std::ptr::from_ref(n)) {
|
||||
path_area += closed_path_area(path, *rule);
|
||||
}
|
||||
Some("paths")
|
||||
}
|
||||
NodeKind::Compound { .. } => Some("compoundPaths"),
|
||||
NodeKind::Compound { children, rule } => {
|
||||
if want_area && !compound_members.contains(&std::ptr::from_ref(n)) {
|
||||
let mut subs = Vec::new();
|
||||
for c in children {
|
||||
collect_compound_subpaths(c, &mut subs);
|
||||
}
|
||||
path_area += closed_path_area(&vectorcraft_geom::PathData::new(subs), *rule);
|
||||
}
|
||||
Some("compoundPaths")
|
||||
}
|
||||
NodeKind::Text(t) => {
|
||||
count_fonts(&mut fonts, t);
|
||||
Some("textObjects")
|
||||
@@ -972,6 +1039,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"document": document_summary(d),
|
||||
"objects": counts,
|
||||
"pathLength": path_length,
|
||||
"pathArea": want_area.then_some(path_area),
|
||||
"fonts": font_names,
|
||||
"fontUses": font_uses,
|
||||
"fontDetails": font_entries,
|
||||
@@ -1347,6 +1415,115 @@ mod tests {
|
||||
assert_eq!(length(&mut s, json!({"selectionOnly": true})), 0.0);
|
||||
}
|
||||
|
||||
/// Document Info › Objects gives the paths' total area in the document's units: an open line
|
||||
/// counts 0, a closed rectangle encloses its area, and a compound path's holes are subtracted.
|
||||
#[test]
|
||||
fn info_gives_the_paths_total_area() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400, "units": "Points"})).unwrap();
|
||||
let line = s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 72, "y2": 0})).unwrap()["id"].clone();
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 10, "height": 20})).unwrap()["id"].clone();
|
||||
let area = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["pathArea"].as_f64().unwrap();
|
||||
// The rectangle encloses 200 pt²; the open line encloses 0.
|
||||
assert!((area(&mut s, json!({})) - 200.0).abs() < 1e-6);
|
||||
// An open line selected: pathArea is 0, so no "Path Area" row is inserted.
|
||||
s.execute("select.set", &json!({"ids": [line]})).unwrap();
|
||||
assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0);
|
||||
let rows = s.execute("document.info", &json!({"selectionOnly": true, "category": "objects"})).unwrap()["sections"][0]["rows"].clone();
|
||||
assert_eq!(rows, json!([["Paths", "1"], ["Path Length", "72 pt"]]));
|
||||
// The rectangle selected: "Path Area" row follows "Path Length".
|
||||
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
|
||||
assert!((area(&mut s, json!({"selectionOnly": true})) - 200.0).abs() < 1e-6);
|
||||
let rows = s.execute("document.info", &json!({"selectionOnly": true, "category": "objects"})).unwrap()["sections"][0]["rows"].clone();
|
||||
assert_eq!(rows, json!([["Paths", "1"], ["Path Length", "60 pt"], ["Path Area", "200 pt²"]]));
|
||||
// A compound path's pieces are paths: their areas count.
|
||||
let other = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 5, "height": 5})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({"ids": [rect, other]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
assert!((area(&mut s, json!({"selectionOnly": true})) - 225.0).abs() < 1e-6);
|
||||
// A compound path (a 10x10 outer contour with a 6x6 inner hole) subtracts the hole:
|
||||
let mut s2 = Session::new();
|
||||
s2.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points"})).unwrap();
|
||||
let outer = s2.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let inner = s2.execute("shape.rectangle", &json!({"x": 12, "y": 12, "width": 6, "height": 6})).unwrap()["id"].clone();
|
||||
s2.execute("select.set", &json!({"ids": [outer, inner]})).unwrap();
|
||||
let cp1 = s2.execute("object.compoundPath.make", &json!({})).unwrap()["id"].clone();
|
||||
assert!((area(&mut s2, json!({"selectionOnly": true})) - 64.0).abs() < 1e-6);
|
||||
// A nested compound path (cp1 compounded with another disjoint 5x5 rectangle) does not double-count cp1:
|
||||
let extra = s2.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 5, "height": 5})).unwrap()["id"].clone();
|
||||
s2.execute("select.set", &json!({"ids": [cp1, extra]})).unwrap();
|
||||
s2.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
assert!((area(&mut s2, json!({"selectionOnly": true})) - 89.0).abs() < 1e-6);
|
||||
// A guide path is left out.
|
||||
let guide = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(guide)).unwrap().kind {
|
||||
*g = true;
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [guide]})).unwrap();
|
||||
assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0);
|
||||
// A compound path whose members are guides is left out.
|
||||
let g1 = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
let g2 = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(g1)).unwrap().kind {
|
||||
*g = true;
|
||||
}
|
||||
if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(g2)).unwrap().kind {
|
||||
*g = true;
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [g1, g2]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0);
|
||||
// Nothing with no paths, and no area row.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0);
|
||||
}
|
||||
|
||||
/// The area pass normalizes every closed path, so `document.info` leaves it out (`pathArea`
|
||||
/// null) for a request that does not cover the Objects category or turns it off, and still
|
||||
/// gives it for Objects and for every category.
|
||||
#[test]
|
||||
fn info_works_out_the_path_area_only_for_the_objects_category() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap();
|
||||
let area = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["pathArea"].as_f64();
|
||||
assert!(area(&mut s, json!({})).is_some_and(|a| a > 0.0));
|
||||
assert!(area(&mut s, json!({"category": "objects"})).is_some_and(|a| a > 0.0));
|
||||
assert_eq!(area(&mut s, json!({"category": "fonts"})), None);
|
||||
assert_eq!(area(&mut s, json!({"pathArea": false})), None);
|
||||
// Without the area, Objects has no Path Area row and keeps its other rows.
|
||||
let rows = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["sections"][0]["rows"].clone();
|
||||
let without = rows(&mut s, json!({"category": "objects", "pathArea": false}));
|
||||
let with = rows(&mut s, json!({"category": "objects"}));
|
||||
assert!(without.as_array().unwrap().iter().all(|r| r[0] != "Path Area"), "{without}");
|
||||
assert!(with.as_array().unwrap().iter().any(|r| r[0] == "Path Area"), "{with}");
|
||||
assert_eq!(with.as_array().unwrap().len(), without.as_array().unwrap().len() + 1);
|
||||
}
|
||||
|
||||
/// A selection containing both a compound and its member counts the member once; selecting
|
||||
/// only the member still reports that path's area.
|
||||
#[test]
|
||||
fn info_path_area_counts_selected_compound_members_once() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let p = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
let q = s.execute("shape.rectangle", &json!({"x": 30, "y": 30, "width": 5, "height": 5})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({"ids": [p, q]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let st = s.doc_mut().unwrap();
|
||||
let NodeKind::Compound { children, .. } = &st.doc.node(NodeId(compound)).unwrap().kind else { panic!("not a compound path") };
|
||||
let member = children.iter().find(|child| child.id.0 == p).unwrap().id;
|
||||
let area = |s: &mut Session| s.execute("document.info", &json!({"selectionOnly": true})).unwrap()["pathArea"].as_f64().unwrap();
|
||||
let picked = s.execute("select.set", &json!({"ids": [member.0]})).unwrap();
|
||||
assert_eq!(picked["count"], 1);
|
||||
assert!((area(&mut s) - 100.0).abs() < 1e-6);
|
||||
let picked = s.execute("select.set", &json!({"ids": [member.0, compound]})).unwrap();
|
||||
assert_eq!(picked["count"], 2);
|
||||
assert!((area(&mut s) - 125.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// Document Info › Brushes lists the brushes the art's strokes use, each once with its type, and
|
||||
/// leaves out the Brushes panel's brushes no art uses (`panelBrushNames` lists those). With
|
||||
/// Selection Only it lists the brushes the selected objects' strokes use.
|
||||
|
||||
@@ -823,7 +823,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
st.sync_new_art();
|
||||
super::maskedit::follow_history(st, editing);
|
||||
super::symboledit::follow_history(st, editing_symbol.as_ref());
|
||||
leave_isolation_if_gone(st);
|
||||
st.leave_isolation_if_gone();
|
||||
super::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
if let Some((before, _)) = paints {
|
||||
@@ -860,7 +860,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
st.sync_new_art();
|
||||
super::maskedit::follow_history(st, editing);
|
||||
super::symboledit::follow_history(st, editing_symbol.as_ref());
|
||||
leave_isolation_if_gone(st);
|
||||
st.leave_isolation_if_gone();
|
||||
super::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
if let Some((_, after)) = paints {
|
||||
@@ -869,15 +869,6 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "redone": label }))
|
||||
}
|
||||
|
||||
/// After undo or redo, isolation mode ends when the isolated object is no longer in the document,
|
||||
/// such as the clip group Draw Inside made around the isolated object (#3705), rather than naming
|
||||
/// an id a later object may take.
|
||||
fn leave_isolation_if_gone(st: &mut crate::DocState) {
|
||||
if st.isolation.is_some_and(|i| st.doc.node(i).is_none()) {
|
||||
st.isolation = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// History panel › Clear History: removes the steps after the current state and the steps before
|
||||
/// it, and leaves the document as it is. Typing or a drag still in progress is first kept as a
|
||||
/// step, as Undo keeps it, so it is removed with the others and its change stays in the document.
|
||||
@@ -960,8 +951,12 @@ fn shared_selection(selection: vectorcraft_doc::Selection, like: Option<&crate::
|
||||
/// instance as it is. Copy copies the instance whole ([`copy_cut_targets`]).
|
||||
pub(crate) fn selected_roots(s: &Session) -> Result<Vec<NodeId>> {
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
Ok(roots_of(&st.doc, st.selection.in_paint_order(&st.doc)))
|
||||
Ok(selection_roots(s.doc()?))
|
||||
}
|
||||
|
||||
/// [`selected_roots`] of one document's selection.
|
||||
pub(crate) fn selection_roots(st: &crate::DocState) -> Vec<NodeId> {
|
||||
roots_of(&st.doc, st.selection.in_paint_order(&st.doc))
|
||||
}
|
||||
|
||||
/// [`super::brushsym::part_only`] while an object of a dynamic symbol instance's art is selected:
|
||||
@@ -1592,6 +1587,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
for xf in placements {
|
||||
for (k, n) in clip.nodes.iter().enumerate() {
|
||||
let mut c = d.reid(n);
|
||||
// A pasted object never goes in as a clip group's clipping path, so a copied clipping
|
||||
// path comes back as an ordinary path that the path commands work on (#9227).
|
||||
if let NodeKind::Path { clipping, .. } = &mut c.kind {
|
||||
*clipping = false;
|
||||
}
|
||||
// A pasted symbol set packs from the density recorded for it at Copy.
|
||||
d.carry_set_densities(n, &c, &clip.set_densities);
|
||||
imported.apply(&mut c, d);
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
//! - `metafile`: EMF and WMF export, open and place; PICT open and place.
|
||||
//! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, and `.cmx` files with
|
||||
//! 32-bit coordinates, open and place.
|
||||
//! - `cmx`: `.cmx` export (a page for each chosen artboard, a layer for each layer with art on it).
|
||||
//! - `hpgl`: HP-GL export options and plots.
|
||||
//! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no
|
||||
//! built-in format reads).
|
||||
@@ -31,6 +32,7 @@ mod action_batch;
|
||||
mod affinity;
|
||||
mod batch;
|
||||
mod cdr;
|
||||
mod cmx;
|
||||
pub mod dxf;
|
||||
pub mod dxfimport;
|
||||
mod encode;
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
//! `.cmx` exchange files for every path that writes them (`craft_cdr::write_cmx`):
|
||||
//! `document.export {format: cmx}` and Export As. The chosen artboard (default the first) is the
|
||||
//! file's page; with Use Artboards each chosen artboard (default all) is a page of one file. Each
|
||||
//! top-level layer with art over a page is a layer of that page, holding that art as
|
||||
//! [`vectorcraft_metafile::painted_layers`] gives it: fills and strokes in their colors (CMYK, RGB,
|
||||
//! gray, spot colors with their tints and Registration), type as glyph outlines, and gradients and
|
||||
//! patterns as one color. What the file can't hold comes back in the warnings.
|
||||
|
||||
use craft_cdr::Limits;
|
||||
use craft_cdr::model as cd;
|
||||
use kurbo::PathEl;
|
||||
use serde_json::Value;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::{Document, LineCap, LineJoin, StrokeLayer};
|
||||
use vectorcraft_geom::{BezPath, FillRule, Point};
|
||||
use vectorcraft_metafile::Painted;
|
||||
|
||||
use super::super::{Result, bad};
|
||||
use super::{ArtboardPick, Encoded, FormatOption};
|
||||
|
||||
const C: &str = "document.export";
|
||||
|
||||
/// The options `document.formats` lists for CMX.
|
||||
pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS, super::RANGE, super::USE_ARTBOARDS];
|
||||
|
||||
const IMAGES: &str = "placed images are left out of CMX files";
|
||||
const NONZERO: &str = "fills that use the nonzero fill rule are written even-odd: where a shape crosses itself, or parts of it that turn the same way overlap, they may leave holes";
|
||||
const SPLIT: &str = "paths with more than 7,281 points were written as several curves: their fills where their parts overlap, and their strokes where the curves meet, may draw differently";
|
||||
const PAST_PAGE: &str = "art that crosses the edge of a page is written whole, including the part past the edge";
|
||||
const DASHES: &str = "dash and gap lengths were rounded to whole stroke widths, the unit CMX files store them in";
|
||||
const CUT: &str = "filled shapes with a part of more than 7,281 points were written as open pieces of that part, so their fills draw differently";
|
||||
const ZERO_TINTS: &str = "spot colors at a low tint were written in the color they print at that tint, so their ink's color may open changed";
|
||||
const LONG_NAMES: &str = "layer and spot color names longer than 256 characters open again shortened";
|
||||
const UNNAMED_SPOTS: &str = "spot colors without a name were written as process colors";
|
||||
const UNKNOWN_LOOKS: &str = "spot colors whose color is not known were written as black at their tints";
|
||||
const MERGED_LOOKS: &str = "spot colors that share a name but not a color were all written in one of those colors";
|
||||
const LEFT_OUT: &str = "art the file can't hold was left out";
|
||||
const DASH_OFFSETS: &str = "dash offsets are left out: dashes start at the start of each path";
|
||||
const ALIGNED_DASHES: &str = "dashes aligned to corners and path ends are written as plain dashes";
|
||||
const MITER_LIMITS: &str = "miter limits are left out: mitered corners open again with a miter limit of 10";
|
||||
|
||||
/// Encode `doc` as CMX: one file with a page for the chosen artboard (default the first), or with
|
||||
/// `use_artboards` a page for each chosen artboard (default all), in the order they are chosen.
|
||||
pub(super) fn encode(doc: &Document, f: &super::Format, p: &Value, use_artboards: Option<bool>) -> Result<Encoded> {
|
||||
let pick: ArtboardPick = super::encode::options(f, p)?;
|
||||
let n = doc.artboards.len();
|
||||
let boards = match use_artboards {
|
||||
Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()),
|
||||
_ => vec![pick.one(n).map_err(|e| bad(C, e))?],
|
||||
};
|
||||
if boards.is_empty() {
|
||||
return Err(bad(C, "the document has no artboard"));
|
||||
}
|
||||
let rects = boards
|
||||
.iter()
|
||||
.map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?;
|
||||
let mut warnings = Vec::new();
|
||||
let mut note = |w: &str| {
|
||||
if !warnings.iter().any(|x: &String| x == w) {
|
||||
warnings.push(w.to_string());
|
||||
}
|
||||
};
|
||||
let mut pages = Vec::with_capacity(rects.len());
|
||||
for r in &rects {
|
||||
let art = vectorcraft_metafile::painted_layers(doc, *r).map_err(|e| bad(C, e))?;
|
||||
art.warnings.iter().for_each(|w| note(w));
|
||||
if art.images {
|
||||
note(IMAGES);
|
||||
}
|
||||
// The file has no clipping the reader reads, so art is not cut at the page's edge.
|
||||
let edge = r.abs().inflate(PAGE_EDGE_TOLERANCE, PAGE_EDGE_TOLERANCE);
|
||||
// A stroke reaches half its width past its path.
|
||||
let past = |bp: &BezPath, reach: f64| {
|
||||
let b = kurbo::Shape::bounding_box(bp).inflate(reach, reach);
|
||||
!bp.elements().is_empty() && (b.x0 < edge.x0 || b.y0 < edge.y0 || b.x1 > edge.x1 || b.y1 > edge.y1)
|
||||
};
|
||||
if art.layers.iter().flat_map(|(_, p)| p).any(|op| match op {
|
||||
Painted::Fill { path, .. } => past(path, 0.0),
|
||||
Painted::Stroke { path, width, .. } => past(path, width.max(0.0) / 2.0),
|
||||
}) {
|
||||
note(PAST_PAGE);
|
||||
}
|
||||
let page = Page { center: r.abs().center() };
|
||||
// The model lists layers and objects front to back; the document paints them back to front.
|
||||
// A layer with nothing drawn on the page is left out, as the reader leaves out a layer that
|
||||
// holds nothing.
|
||||
let layers = art
|
||||
.layers
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|(name, painted)| (name, page.objects(&art.swatches, painted, &mut note)))
|
||||
.filter(|(_, objects)| !objects.is_empty())
|
||||
.map(|(name, objects)| cd::Layer {
|
||||
name: name.clone(),
|
||||
kind: cd::LayerKind::Drawing,
|
||||
flags: cd::Flags::default(),
|
||||
objects: objects.into_iter().rev().collect(),
|
||||
guides: Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
pages.push(cd::Page { size: Some((r.width().abs(), r.height().abs())), layers });
|
||||
}
|
||||
let drawing = cd::Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: Vec::new() };
|
||||
// The limits `document.open` reads `.cmx` files with, so the file opens whole again.
|
||||
let written = craft_cdr::write_cmx(&drawing, Limits::default()).map_err(|e| bad(C, e.to_string()))?;
|
||||
for (set, w) in [
|
||||
(written.nonzero_fills, NONZERO),
|
||||
(written.split_paths, SPLIT),
|
||||
(written.cut_subpaths, CUT),
|
||||
(written.long_names, LONG_NAMES),
|
||||
(written.zero_tints, ZERO_TINTS),
|
||||
(written.rounded_dashes, DASHES),
|
||||
(written.unnamed_spots, UNNAMED_SPOTS),
|
||||
(written.unknown_looks, UNKNOWN_LOOKS),
|
||||
(written.merged_looks, MERGED_LOOKS),
|
||||
(written.left_out, LEFT_OUT),
|
||||
] {
|
||||
if set {
|
||||
note(w);
|
||||
}
|
||||
}
|
||||
let mut enc = Encoded::one(written.bytes);
|
||||
enc.warnings = warnings;
|
||||
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(&rects)));
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
/// A page's placement: document space (y down) to the page's coordinates (from its center, y up).
|
||||
struct Page {
|
||||
center: Point,
|
||||
}
|
||||
|
||||
impl Page {
|
||||
fn pt(&self, p: Point) -> cd::Pt {
|
||||
cd::Pt { x: p.x - self.center.x, y: self.center.y - p.y }
|
||||
}
|
||||
|
||||
/// `bp` in the page's coordinates. A quadratic segment becomes the cubic that draws it.
|
||||
fn path(&self, bp: &BezPath) -> cd::Path {
|
||||
let mut subpaths: Vec<cd::SubPath> = Vec::new();
|
||||
// The current point and the start of the current subpath, in document space.
|
||||
let (mut last, mut start) = (Point::ZERO, Point::ZERO);
|
||||
for el in bp.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
subpaths.push(cd::SubPath { start: self.pt(p), segments: Vec::new(), closed: false });
|
||||
(last, start) = (p, p);
|
||||
}
|
||||
PathEl::LineTo(p) => {
|
||||
self.segment(&mut subpaths, last, cd::Segment::Line(self.pt(p)));
|
||||
last = p;
|
||||
}
|
||||
PathEl::QuadTo(c, p) => {
|
||||
let (c1, c2) = (last + (c - last) * (2.0 / 3.0), p + (c - p) * (2.0 / 3.0));
|
||||
self.segment(&mut subpaths, last, cd::Segment::Cubic(self.pt(c1), self.pt(c2), self.pt(p)));
|
||||
last = p;
|
||||
}
|
||||
PathEl::CurveTo(c1, c2, p) => {
|
||||
self.segment(&mut subpaths, last, cd::Segment::Cubic(self.pt(c1), self.pt(c2), self.pt(p)));
|
||||
last = p;
|
||||
}
|
||||
PathEl::ClosePath => {
|
||||
if let Some(s) = subpaths.last_mut() {
|
||||
s.closed = true;
|
||||
}
|
||||
last = start;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A subpath of a lone point draws nothing.
|
||||
subpaths.retain(|s| !s.segments.is_empty());
|
||||
cd::Path { subpaths }
|
||||
}
|
||||
|
||||
/// Add `seg` to the open subpath, or to a new one from `from` after a close.
|
||||
fn segment(&self, subpaths: &mut Vec<cd::SubPath>, from: Point, seg: cd::Segment) {
|
||||
match subpaths.last_mut() {
|
||||
Some(s) if !s.closed => s.segments.push(seg),
|
||||
_ => subpaths.push(cd::SubPath { start: self.pt(from), segments: vec![seg], closed: false }),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fills and strokes of one layer as shapes, in paint order. A fill followed by a stroke of
|
||||
/// the same path is one shape with both. A path with no segments draws nothing and is left out.
|
||||
fn objects(&self, swatches: &[Swatch], painted: &[Painted], note: &mut impl FnMut(&str)) -> Vec<cd::Object> {
|
||||
let mut out = Vec::with_capacity(painted.len());
|
||||
let mut i = 0;
|
||||
while let Some(op) = painted.get(i) {
|
||||
i += 1;
|
||||
let shape = match op {
|
||||
Painted::Fill { path, rule, rgb, paint } => {
|
||||
let outline = match painted.get(i) {
|
||||
Some(s @ Painted::Stroke { path: stroked, .. }) if stroked == path => {
|
||||
i += 1;
|
||||
outline(swatches, s, note)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let fill = color(swatches, *rgb, paint.as_ref());
|
||||
let mut shape = cd::Shape::new(cd::Geometry::Path(self.path(path)), cd::Matrix::IDENTITY, Some(fill), outline);
|
||||
shape.nonzero = *rule == FillRule::NonZero;
|
||||
shape
|
||||
}
|
||||
Painted::Stroke { path, .. } => {
|
||||
cd::Shape::new(cd::Geometry::Path(self.path(path)), cd::Matrix::IDENTITY, None, outline(swatches, op, note))
|
||||
}
|
||||
};
|
||||
if matches!(&shape.geometry, cd::Geometry::Path(p) if p.subpaths.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
out.push(cd::Object::Shape(Box::new(shape)));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// How far (points) a path may reach past its page before the export says art crosses the edge.
|
||||
const PAGE_EDGE_TOLERANCE: f64 = 0.01;
|
||||
|
||||
/// The outline of a stroke: its width, color, cap, join and dashes in stroke widths. The file holds
|
||||
/// no miter limit, so a mitered stroke with a limit other than the one a stroke opens with is
|
||||
/// named in the warnings.
|
||||
fn outline(swatches: &[Swatch], p: &Painted, note: &mut impl FnMut(&str)) -> Option<cd::Outline> {
|
||||
let Painted::Stroke { rgb, paint, width, cap, join, miter, dash, .. } = p else { return None };
|
||||
if *join == LineJoin::Miter && *miter != StrokeLayer::new(Paint::None, *width).miter_limit {
|
||||
note(MITER_LIMITS);
|
||||
}
|
||||
let dashes = match dash {
|
||||
Some(d) if *width > 0.0 => {
|
||||
if d.offset != 0.0 {
|
||||
note(DASH_OFFSETS);
|
||||
}
|
||||
if d.align_corners {
|
||||
note(ALIGNED_DASHES);
|
||||
}
|
||||
d.pattern.iter().map(|x| x / width).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
Some(cd::Outline {
|
||||
width: *width,
|
||||
color: color(swatches, *rgb, paint.as_ref()),
|
||||
cap: match cap {
|
||||
LineCap::Butt => cd::Cap::Butt,
|
||||
LineCap::Round => cd::Cap::Round,
|
||||
LineCap::Square => cd::Cap::Square,
|
||||
},
|
||||
join: match join {
|
||||
LineJoin::Miter => cd::Join::Miter,
|
||||
LineJoin::Round => cd::Join::Round,
|
||||
LineJoin::Bevel => cd::Join::Bevel,
|
||||
},
|
||||
dashes,
|
||||
behind_fill: false,
|
||||
scale_with: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The color a fill or stroke is written in: Registration, a spot color at its tint with the look
|
||||
/// of its swatch among `swatches`, or the solid color in its own model (Lab as RGB); `rgb` for the
|
||||
/// one color of a gradient or pattern.
|
||||
fn color(swatches: &[Swatch], rgb: [u8; 3], paint: Option<&Paint>) -> cd::Color {
|
||||
let from_rgb = |[r, g, b]: [u8; 3]| cd::Color::Rgb([r, g, b].map(|v| f32::from(v) / 255.0));
|
||||
let Some(Paint::Solid { color, swatch, tint }) = paint else { return from_rgb(rgb) };
|
||||
if swatch.as_deref() == Some(REGISTRATION) {
|
||||
return cd::Color::Registration;
|
||||
}
|
||||
if let Some(s) = swatch.as_deref().and_then(|name| swatches.iter().find(|s| s.name == name)).filter(|s| s.spot) {
|
||||
let look = s.paint.color().map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
[r, g, b].map(|v| f32::from(v) / 255.0)
|
||||
});
|
||||
return cd::Color::Spot { name: s.name.clone(), tint: tint.clamp(0.0, 1.0), look };
|
||||
}
|
||||
match *color {
|
||||
Color::Rgb { r, g, b } => cd::Color::Rgb([r, g, b]),
|
||||
Color::Cmyk { c, m, y, k } => cd::Color::Cmyk([c, m, y, k]),
|
||||
Color::Gray { k } => cd::Color::Gray(k),
|
||||
Color::Lab { .. } => from_rgb(rgb),
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Serialize Document",
|
||||
[],
|
||||
None,
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)",
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)",
|
||||
has_doc,
|
||||
export::serialize
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), d
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Selection…",
|
||||
["File"],
|
||||
None,
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})",
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|cmx|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})",
|
||||
has_selection,
|
||||
export::export_selection
|
||||
),
|
||||
|
||||
@@ -1069,7 +1069,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
|
||||
}
|
||||
// Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so
|
||||
// themselves: SVG only when it outlines or embeds fonts).
|
||||
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl"))
|
||||
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl" | "cmx"))
|
||||
&& let Some(w) = crate::cmd::fonts::substitution_warning(doc)
|
||||
{
|
||||
enc.warnings.push(w);
|
||||
@@ -1110,7 +1110,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
let doc = &*doc.without_edit_modes();
|
||||
let n = doc.artboards.len();
|
||||
// SVG reads its own `useArtboards` (an SVG option).
|
||||
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(C, p)? } else { None };
|
||||
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None };
|
||||
// `rect`: that area of the page, as if it were the only artboard (the document is not changed).
|
||||
if let Some(rect) = page_rect(f, p)? {
|
||||
let mut q = super::export::without_artboards(p);
|
||||
@@ -1156,6 +1156,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
"emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf),
|
||||
"wmf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Wmf),
|
||||
"hpgl" => return super::hpgl::encode(doc, p, use_artboards),
|
||||
"cmx" => return super::cmx::encode(doc, f, p, use_artboards),
|
||||
"ai" => return super::save::encode_ai(C, f, doc, p),
|
||||
"pdf" => {
|
||||
let (bytes, notes) = super::pdf::encode(C, doc, p)?;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::super::unique_name;
|
||||
use super::{
|
||||
Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, dxf, eps, hpgl, json, metafile, native, pdf, screens, svg, text,
|
||||
Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, cmx, dxf, eps, hpgl, json, metafile, native, pdf, screens, svg, text,
|
||||
unsupported,
|
||||
};
|
||||
|
||||
@@ -553,9 +553,9 @@ pub const FORMATS: &[Format] = &[
|
||||
// them.
|
||||
reader("cdr", "CDR Drawing", &["cdr"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type
|
||||
reader("cdt", "CDR Template", &["cdt"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type
|
||||
// `.cmx` exchange files with 32-bit coordinates, read by `craft-cdr`; exports don't write
|
||||
// them.
|
||||
reader("cmx", "CMX", &["cmx"], "image/x-cmx", false),
|
||||
// `.cmx` exchange files with 32-bit coordinates, read and written by `craft-cdr`: a page for
|
||||
// each chosen artboard, with the art's fills and strokes in their colors.
|
||||
Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS },
|
||||
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images.
|
||||
reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false),
|
||||
];
|
||||
|
||||
@@ -196,7 +196,7 @@ pub(super) fn name_without_device(name: &str) -> String {
|
||||
pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"];
|
||||
|
||||
/// The writable formats a format row can't name.
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 6] = ["template", "txt", "dxf", "emf", "wmf", "hpgl"];
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 7] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx"];
|
||||
|
||||
/// One format row: what to write, at which size, with which suffix, into which sub-folder.
|
||||
struct Row {
|
||||
|
||||
@@ -532,7 +532,8 @@ fn export_extensions_name_every_writable_format() {
|
||||
"wmf",
|
||||
"plt",
|
||||
"tga",
|
||||
"psd"
|
||||
"psd",
|
||||
"cmx"
|
||||
]
|
||||
);
|
||||
for e in exts {
|
||||
@@ -568,7 +569,8 @@ fn formats_query_lists_readers_writers_and_options() {
|
||||
"wmf",
|
||||
"hpgl",
|
||||
"tga",
|
||||
"psd"
|
||||
"psd",
|
||||
"cmx"
|
||||
]
|
||||
);
|
||||
assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string()));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! `.cmx` files: Open and Place, by extension and by content, mapped to artboards, layers, groups,
|
||||
//! paths, solid paint and strokes, with their warnings and refusals.
|
||||
//! paths, solid paint and strokes, with their warnings and refusals; and export, read back.
|
||||
|
||||
use super::*;
|
||||
use craft_cdr::synth_cmx::*;
|
||||
@@ -61,7 +61,7 @@ fn detection_by_content_and_place() {
|
||||
s.execute("file.place", &json!({"name":"art.cmx", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty()));
|
||||
let f = format("cmx").unwrap();
|
||||
assert!(f.read && !f.write);
|
||||
assert!(f.read && f.write);
|
||||
assert!(OPEN_EXTS.contains(&"cmx") && PLACE_EXTS.contains(&"cmx") && UNASSOCIATED_EXTS.contains(&"cmx"));
|
||||
assert!(!SAVE_FORMATS.contains(&"cmx"));
|
||||
}
|
||||
@@ -123,6 +123,183 @@ fn files_that_are_not_read_say_why() {
|
||||
assert!(e.contains("this CMX file can't be read (not a CMX file)"), "{e}");
|
||||
}
|
||||
|
||||
fn b64(v: &serde_json::Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap()
|
||||
}
|
||||
|
||||
/// Two artboards of 200 x 100 pt. The first layer holds a CMYK rectangle with a dashed gray stroke on
|
||||
/// the first; layer "Front" a 40 % tint of spot ink "Gold" on the first and an RGB stroke on the
|
||||
/// second.
|
||||
fn drawn() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2, "colorMode": "cmyk"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Gold", "color": {"model": "cmyk", "c": 0.0, "m": 0.2, "y": 0.8, "k": 0.1}, "spot": true})).unwrap();
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect.x0;
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 40, "height": 30})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": {"model": "cmyk", "c": 0.6, "m": 0.1, "y": 0.0, "k": 0.2}})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": {"model": "gray", "k": 0.5}})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2, "dash": [6, 2]})).unwrap();
|
||||
s.execute("layer.new", &json!({"name": "Front"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Gold", "tint": 40})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": second + 5.0, "y": 5, "width": 10, "height": 10})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#3366cc"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 1})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Every path of a document with its bounds relative to the artboard it is on.
|
||||
fn placed(s: &Session) -> Vec<(Node, vectorcraft_geom::Rect)> {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let mut all = Vec::new();
|
||||
paths(&doc.layers, &mut all);
|
||||
all.into_iter()
|
||||
.map(|n| {
|
||||
let b = doc.bounds_of(&[n.id], false).unwrap();
|
||||
let board = doc.artboards.iter().find(|a| a.rect.contains(b.center())).map_or(vectorcraft_geom::Rect::ZERO, |a| a.rect);
|
||||
(n, b - board.origin().to_vec2())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exported_cmx_file_opens_with_its_pages_layers_colors_and_strokes() {
|
||||
let mut s = drawn();
|
||||
let r = s.execute("document.export", &json!({"format": "cmx", "useArtboards": true})).unwrap();
|
||||
assert_eq!(r["format"], "cmx");
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
let bytes = b64(&r);
|
||||
assert!(craft_cdr::is_cmx(&bytes), "one file holds both pages");
|
||||
let mut back = Session::new();
|
||||
let opened = open_bytes(&mut back, "drawing.cmx", &bytes, None).unwrap();
|
||||
assert!(warnings(&opened).is_empty(), "{opened}");
|
||||
let doc = &back.doc().unwrap().doc;
|
||||
let sizes: Vec<(f64, f64)> = doc.artboards.iter().map(|a| (a.rect.width().round(), a.rect.height().round())).collect();
|
||||
assert_eq!(sizes, [(200.0, 100.0), (200.0, 100.0)]);
|
||||
let names: Vec<String> = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
let was: Vec<String> = s.doc().unwrap().doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, was, "the layers keep their names and order");
|
||||
let was = placed(&s);
|
||||
let now = placed(&back);
|
||||
assert_eq!(was.len(), now.len());
|
||||
for ((_, a), (_, b)) in was.iter().zip(&now) {
|
||||
assert!((a.x0 - b.x0).abs() < 0.01 && (a.y0 - b.y0).abs() < 0.01 && (a.x1 - b.x1).abs() < 0.01, "{a:?} {b:?}");
|
||||
}
|
||||
let fill = |n: &Node| n.appearance.fill().map(|f| f.paint.clone());
|
||||
let stroke = |n: &Node| n.appearance.stroke().cloned();
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let cmyk = &now[0].0;
|
||||
assert!(matches!(fill(cmyk).and_then(|p| p.color()), Some(Color::Cmyk { c, .. }) if (c - 0.6).abs() < 0.006), "{:?}", fill(cmyk));
|
||||
let st = stroke(cmyk).unwrap();
|
||||
assert!((st.width - 2.0).abs() < 1e-3 && matches!(st.paint.color(), Some(Color::Gray { k }) if (k - 0.5).abs() < 0.005));
|
||||
// Widths are stored to 0.1 µm.
|
||||
let dash = st.dash.as_ref().map(|d| d.pattern.clone()).unwrap_or_default();
|
||||
assert!(dash.len() == 2 && (dash[0] - 6.0).abs() < 1e-3 && (dash[1] - 2.0).abs() < 1e-3, "{dash:?}");
|
||||
let gold = &now[1].0;
|
||||
assert!(matches!(fill(gold), Some(Paint::Solid { swatch: Some(n), tint, .. }) if n == "Gold" && (tint - 0.4).abs() < 0.006), "{:?}", fill(gold));
|
||||
assert!(doc.swatch("Gold").is_some_and(|g| g.spot));
|
||||
let line = &now[2].0;
|
||||
assert!(fill(line).is_none_or(|p| p == Paint::None));
|
||||
// The document converted the RGB color to its CMYK mode; the file keeps the CMYK values.
|
||||
let (Some(Color::Cmyk { c, m, y, k }), Some(Color::Cmyk { c: c2, m: m2, y: y2, k: k2 })) =
|
||||
(stroke(&was[2].0).unwrap().paint.color(), stroke(line).unwrap().paint.color())
|
||||
else {
|
||||
panic!("not CMYK: {:?}", stroke(line))
|
||||
};
|
||||
assert!([c - c2, m - m2, y - y2, k - k2].iter().all(|d| d.abs() < 0.006));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_artboard_is_one_page_and_what_cmx_leaves_out_is_named() {
|
||||
let mut s = drawn();
|
||||
let bytes = b64(&s.execute("document.export", &json!({"format": "cmx", "artboard": 1})).unwrap());
|
||||
let d = craft_cdr::read_cmx(&bytes, craft_cdr::Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
let shapes: usize = d.pages[0].layers.iter().map(|l| l.objects.len()).sum();
|
||||
assert_eq!(shapes, 1, "only the art over the second artboard");
|
||||
assert_eq!(b64(&s.execute("document.serialize", &json!({"format": "cmx", "artboard": 1})).unwrap()), bytes);
|
||||
// A gradient is written as one color, and a placed image is left out.
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 60, "width": 10, "height": 10})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
let png = vectorcraft_format::base64_encode(&tiny_png());
|
||||
s.execute("file.place", &json!({"name": "dot.png", "dataBase64": png, "x": 150, "y": 60})).unwrap();
|
||||
let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap());
|
||||
assert!(w.iter().any(|w| w.contains("gradients are written as one colour")), "{w:?}");
|
||||
assert!(w.iter().any(|w| w == "placed images are left out of CMX files"), "{w:?}");
|
||||
assert!(w.iter().all(|w| !w.contains("edge of a page")), "{w:?}");
|
||||
// Art across the artboard's edge is written whole, and the warnings say so.
|
||||
s.execute("shape.rectangle", &json!({"x": 190, "y": 90, "width": 20, "height": 20})).unwrap();
|
||||
let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap());
|
||||
assert!(w.iter().any(|w| w.contains("edge of a page")), "{w:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nonzero_fill_that_would_fill_differently_even_odd_is_named() {
|
||||
let nonzero = |w: &[String]| w.iter().any(|w| w.contains("nonzero"));
|
||||
let export = |d: &str, rule: &str| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("path.create", &json!({"d": d})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#cc3333"})).unwrap();
|
||||
s.execute("path.setFillRule", &json!({"rule": rule})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "cmx"})).unwrap();
|
||||
let shapes: Vec<craft_cdr::model::Shape> = craft_cdr::read_cmx(&b64(&r), craft_cdr::Limits::default())
|
||||
.unwrap()
|
||||
.pages
|
||||
.into_iter()
|
||||
.flat_map(|p| p.layers)
|
||||
.flat_map(|l| l.objects)
|
||||
.filter_map(|o| match o {
|
||||
craft_cdr::model::Object::Shape(s) => Some(*s),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
(warnings(&r), shapes)
|
||||
};
|
||||
// Two squares that overlap and turn the same way leave a hole where they overlap even-odd.
|
||||
let overlapping = "M10 10 L50 10 L50 50 L10 50 Z M30 30 L70 30 L70 70 L30 70 Z";
|
||||
let (w, shapes) = export(overlapping, "nonZero");
|
||||
assert!(nonzero(&w), "{w:?}");
|
||||
assert!(shapes.len() == 1 && shapes[0].fill.is_some(), "{shapes:?}");
|
||||
// The same shape filled even-odd is written as it fills.
|
||||
assert!(!nonzero(&export(overlapping, "evenOdd").0));
|
||||
// A counter that turns the other way inside its shape fills the same either way.
|
||||
let counter = "M10 10 L50 10 L50 50 L10 50 Z M20 20 L20 40 L40 40 L40 20 Z";
|
||||
assert!(!nonzero(&export(counter, "nonZero").0));
|
||||
// Type exported from a document gives no warning about the fill rule.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Bob 80"})).unwrap();
|
||||
let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap());
|
||||
assert!(!nonzero(&w), "{w:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_miter_limit_the_file_cannot_hold_is_named() {
|
||||
let miter = |w: &[String]| w.iter().any(|w| w.contains("miter limit"));
|
||||
let export = |join: &str, limit: f64| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 40, "height": 30})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#3366cc"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 4, "join": join, "miterLimit": limit})).unwrap();
|
||||
warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap())
|
||||
};
|
||||
assert!(miter(&export("miter", 2.0)));
|
||||
// The limit a stroke opens with again, and corners that are not mitered, lose nothing.
|
||||
assert!(!miter(&export("miter", 10.0)));
|
||||
assert!(!miter(&export("round", 2.0)));
|
||||
}
|
||||
|
||||
/// A 1 x 1 PNG.
|
||||
fn tiny_png() -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_without_a_name_is_named_by_its_place() {
|
||||
// An empty layer, which is left out, then a layer named only by spaces: it comes in unnamed,
|
||||
|
||||
@@ -6013,6 +6013,58 @@ fn a_symbol_pasted_with_a_graph_inside_draws_it_with_the_documents_design_of_tha
|
||||
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
|
||||
}
|
||||
|
||||
/// A symbol a loaded look or text style brings, through the pattern it paints with, draws its
|
||||
/// graph with the document's design of that name, as a pasted one does.
|
||||
#[test]
|
||||
fn a_symbol_a_loaded_look_or_text_style_brings_draws_its_graph_with_the_documents_design() {
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut src);
|
||||
let id = graph(&mut src, "column");
|
||||
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
src.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let instance = src.execute("symbol.new", &json!({"name": "Chart"})).unwrap()["id"].clone();
|
||||
src.execute("object.pattern.make", &json!({"name": "Charts", "edit": false, "ids": [instance]})).unwrap();
|
||||
let r = src.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
src.execute("paint.setFill", &json!({"swatch": "Charts", "ids": [r]})).unwrap();
|
||||
let t = src.execute("text.create", &json!({"x": 10, "y": 80, "text": "Charts"})).unwrap()["id"].clone();
|
||||
src.execute("paint.setFill", &json!({"swatch": "Charts", "ids": [t]})).unwrap();
|
||||
src.execute("charStyle.new", &json!({"name": "Charted", "id": t})).unwrap();
|
||||
let source = (*src.doc().unwrap().doc).clone();
|
||||
let look = source.node(NodeId(r)).unwrap().appearance.clone();
|
||||
assert!(source.pattern("Charts").is_some());
|
||||
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let columns = |d: &vectorcraft_doc::Document| -> Vec<usize> {
|
||||
let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art;
|
||||
let mut graphs = vec![];
|
||||
art.walk(&mut |m| {
|
||||
if m.extras().graph.is_some() {
|
||||
graphs.push(m.clone());
|
||||
}
|
||||
});
|
||||
series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect()
|
||||
};
|
||||
for styles in [false, true] {
|
||||
// A document whose "Coin" is a rectangle and an ellipse.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
if styles {
|
||||
crate::cmd::clipboard::resources::import_text_styles(&source, d, true, false).unwrap();
|
||||
} else {
|
||||
crate::cmd::clipboard::resources::import_looks(&source, d, &look, &serde_json::Map::new()).unwrap();
|
||||
}
|
||||
assert_eq!(columns(d), [2, 2, 2, 2], "styles {styles}: drawn with the document's design");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_brought_in_from_a_library_redraws_the_graphs_in_symbols_that_name_it() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -411,6 +411,13 @@ impl Session {
|
||||
pub fn has_selected_blend(&self) -> bool {
|
||||
super::common::any_selected_of(self, is_blend, |_| true)
|
||||
}
|
||||
|
||||
/// The blends Blend Options edits, in ID order regardless of their selection order.
|
||||
pub fn selected_blend_ids(&self) -> Vec<NodeId> {
|
||||
let mut ids = selected_of(self, is_blend);
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
}
|
||||
}
|
||||
|
||||
/// The first selected blend: its id, spec and key ids.
|
||||
|
||||
@@ -199,7 +199,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Envelope Info",
|
||||
[],
|
||||
None,
|
||||
"{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, version (a warp's map: 1, each style as one Bézier patch; 0, the earlier map), rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}",
|
||||
"{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, version (a warp's map: 1, each style as one Bézier patch; 0, the earlier map), rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, a side shorter than 1e-6 pt taking the other side's, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}",
|
||||
has_doc,
|
||||
env_info
|
||||
),
|
||||
|
||||
@@ -675,6 +675,9 @@ fn transform_each_as(s: &mut Session, p: &Value, label: &str) -> Result<Value> {
|
||||
// Five draws whatever the scales are, so a seed gives the moves and the rotation
|
||||
// the same values whether a side is scaled or not.
|
||||
let [r_sh, r_sv, r_mh, r_mv, r_rot] = [rng.next(), rng.next(), rng.next(), rng.next(), rng.next()];
|
||||
// The same horizontal and vertical scale take one share, so the object scales
|
||||
// evenly (#9320).
|
||||
let r_sv = if sh == sv { r_sh } else { r_sv };
|
||||
k_sh = k_sh.map(|v| 1.0 + (v - 1.0) * r_sh);
|
||||
k_sv = k_sv.map(|v| 1.0 + (v - 1.0) * r_sv);
|
||||
k_mh = mh * (r_mh * 2.0 - 1.0);
|
||||
|
||||
@@ -286,9 +286,9 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
let read = self.read_selection_paints();
|
||||
let (fill_mixed, stroke_mixed) = read.as_ref().map_or_else(|| self.proxy_mixed(), |p| (p.fill_mixed, p.stroke_mixed));
|
||||
let (fill_mixed, stroke_mixed) = read.as_ref().map_or_else(|| self.proxy_mixed(), |p| (p.fill_mixed(), p.stroke_mixed()));
|
||||
let (fill, stroke) = self.proxy_paints();
|
||||
let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed);
|
||||
let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed());
|
||||
let weight = self.shown_stroke().filter(|st| st.paint != Paint::None && !weight_mixed).map(|st| st.width);
|
||||
// A proxy that shows the color the active tool paints with (the Shape Builder's fill) keeps it.
|
||||
if !fill_mixed && !self.tool_paints(false) {
|
||||
@@ -323,7 +323,7 @@ impl Session {
|
||||
Some(SelectionRecord { doc: Arc::downgrade(&st.doc), objects: st.selection.objects.clone(), settled, paints: Some(paints) });
|
||||
}
|
||||
let paints = st.selection_paints()?.clone();
|
||||
(!paints.in_live_paint && self.fill_mesh_points().is_empty()).then_some(paints)
|
||||
(!paints.in_live_paint() && self.fill_mesh_points().is_empty()).then_some(paints)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,10 +15,10 @@ use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Artboard, Background, ColorMode, Document, LayerColor, Node, Unit};
|
||||
use vectorcraft_doc::{Artboard, Background, ColorMode, CompositeFont, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, LayerColor, Node, Unit};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
|
||||
use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, str_param, switch_or};
|
||||
use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Profile",
|
||||
[],
|
||||
None,
|
||||
"{name: a category of file.newPresets} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result",
|
||||
"{name: a built-in category of file.newPresets (not Recent or Saved)} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result",
|
||||
always,
|
||||
edit_profile
|
||||
),
|
||||
@@ -72,10 +72,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reset Profile",
|
||||
[],
|
||||
None,
|
||||
"{name: a category of file.newPresets} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}",
|
||||
"{name: a built-in category of file.newPresets (not Recent or Saved)} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}",
|
||||
always,
|
||||
reset_profile
|
||||
),
|
||||
cmd!(
|
||||
"file.newProfiles.applyDefaults",
|
||||
"Use Profile Defaults",
|
||||
[],
|
||||
None,
|
||||
"{name: a built-in category of file.newPresets (not Recent or Saved)} give the active document the default fill and stroke and the default font of the category's New Document profile (VectorCraft's own command; a category without a profile file gives the shipped ones): the document's Default Graphic Style takes the fills, strokes, effects and transparency of the profile's, and its [Normal Character Style] the profile's attributes (a composite font of the profile they name replaces the document's of that name, as type.compositeFonts.import does), the profile's colors converted to the document's color mode, with the swatches, patterns, symbols and brushes they paint with, in one undo step (none when applying the profile leaves the document unchanged). As Redefine Graphic Style and Redefine Character Style do, objects still linked to the Default Graphic Style and type in [Normal Character Style] take the new definitions and keep their overrides. New art then starts as paint.default gives it (see appearance.newArt), and new type in the profile's [Normal Character Style]. An error when the profile's file can't be read, its [Normal Character Style] has attributes charStyle.new does not take, or the composite font it names can't join the document's (as type.compositeFonts.set checks them) → {name, changed: whether the document changed, warnings?: [text] (a color profile or font the profile's file carries that can't be used)}",
|
||||
has_doc,
|
||||
apply_defaults
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -394,9 +403,8 @@ impl DocSettings {
|
||||
if (o.contains_key("columns") && !o.contains_key("rows")) || self.layout != ArtboardLayout::GridByColumn {
|
||||
self.rows = 0;
|
||||
}
|
||||
if self.grid_rows().is_some() {
|
||||
self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX);
|
||||
}
|
||||
// While rows are set, `grid_columns` gives the columns they make; the stored columns stay as
|
||||
// they were given, and are the ones a later layout without rows uses.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1113,3 +1121,98 @@ fn reset_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
Ok(json!({ "name": name, "reset": reset }))
|
||||
}
|
||||
|
||||
/// `file.newProfiles.applyDefaults`: the active document takes the Default Graphic Style and
|
||||
/// [Normal Character Style] of profile `name`, and new art is reset to them.
|
||||
fn apply_defaults(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "file.newProfiles.applyDefaults";
|
||||
let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?;
|
||||
let mode = s.doc()?.doc.color_mode;
|
||||
let (mut src, warnings) = match s.read_profile(name) {
|
||||
Ok(Some(p)) => (p.doc, p.warnings),
|
||||
// The shipped profile: the defaults of a new document in this color mode.
|
||||
Ok(None) => (Document::new_with_mode(1.0, 1.0, mode), vec![]),
|
||||
Err(e) => return Err(bad(C, format!("the {name} profile can't be read: {e}"))),
|
||||
};
|
||||
if src.color_mode != mode {
|
||||
super::colormgmt::set_color_mode(&mut src, mode, true, None, super::colormgmt::Grays::Profile);
|
||||
}
|
||||
// A profile without a Default Graphic Style gives the shipped one, as a new document from it
|
||||
// starts with the shipped fill and stroke.
|
||||
let look = match src.graphic_style(DEFAULT_GRAPHIC_STYLE) {
|
||||
Some(g) => g.clone(),
|
||||
None => Document::new_with_mode(1.0, 1.0, mode).graphic_style(DEFAULT_GRAPHIC_STYLE).cloned().unwrap_or_else(shipped_default_style),
|
||||
};
|
||||
let normal = super::textstyles::style_attrs(&src, false, super::textstyles::NORMAL_CHAR).unwrap_or_default();
|
||||
let chars = s.prefs.override_char_color;
|
||||
// A composite font the style names comes with it, in place of the document's of its name, as
|
||||
// Import Composite Fonts brings it.
|
||||
let family = normal.get("font_family").and_then(Value::as_str);
|
||||
let fonts_before = s.doc()?.doc.composite_fonts.to_vec();
|
||||
let fonts = family
|
||||
.and_then(|f| CompositeFont::named(&src.composite_fonts, f))
|
||||
.map(|f| super::compositefonts::with_font(&fonts_before, f))
|
||||
.filter(|after| *after != fonts_before);
|
||||
if let Some(after) = &fonts {
|
||||
super::compositefonts::check_set(after, C)?;
|
||||
}
|
||||
let fonts_changed = match &fonts {
|
||||
Some(after) => super::compositefonts::register(s, &fonts_before, after),
|
||||
None => vec![],
|
||||
};
|
||||
let apply = |d: &mut Document| -> Result<()> {
|
||||
if let Some(after) = &fonts {
|
||||
super::compositefonts::set_fonts(d, after, &fonts_changed)?;
|
||||
}
|
||||
let before = d.clone();
|
||||
let (appearance, attrs) = super::clipboard::resources::import_looks(&src, d, &look.appearance, &normal)?;
|
||||
let attrs = if attrs.is_empty() {
|
||||
attrs
|
||||
} else {
|
||||
super::textstyles::stored_style_attrs(d, false, &attrs)
|
||||
.ok_or_else(|| bad(C, format!("the {name} profile's [Normal Character Style] has attributes charStyle.new does not take")))?
|
||||
};
|
||||
let new = GraphicStyle { appearance, ..look.clone() };
|
||||
match d.graphic_style_index(DEFAULT_GRAPHIC_STYLE) {
|
||||
Some(i) if d.graphic_styles[i].same_look(&new) => {}
|
||||
Some(i) => super::style::redefine_in(d, &before, i, new, None, chars),
|
||||
None => {
|
||||
let id = d.next_graphic_style_id();
|
||||
d.graphic_styles.insert(0, GraphicStyle { name: DEFAULT_GRAPHIC_STYLE.to_string(), id, ..new });
|
||||
}
|
||||
}
|
||||
super::textstyles::redefine_normal_char(d, &attrs)
|
||||
};
|
||||
// An undo step only when the document changes; Undo puts the new-art paints back too.
|
||||
let paint_before = super::colormgmt::new_art_colors_before(s)?;
|
||||
let mut run = || -> Result<bool> {
|
||||
let mut trial = (*s.doc()?.doc).clone();
|
||||
apply(&mut trial)?;
|
||||
let changed = trial != *s.doc()?.doc;
|
||||
if changed {
|
||||
s.edit("Use Profile Defaults", |d, _| apply(d))?;
|
||||
}
|
||||
Ok(changed)
|
||||
};
|
||||
let changed = run();
|
||||
if fonts.is_some() {
|
||||
super::compositefonts::sync(s);
|
||||
}
|
||||
let changed = changed?;
|
||||
super::newart::reset(s);
|
||||
// The selection's appearance does not replace the defaults just set.
|
||||
s.note_defaults_only();
|
||||
if changed || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() {
|
||||
super::colormgmt::record_new_art_colors(s, paint_before)?;
|
||||
}
|
||||
let mut out = json!({ "name": name, "changed": changed });
|
||||
if !warnings.is_empty() {
|
||||
out["warnings"] = json!(warnings);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The shipped Default Graphic Style: white fill, 1 pt black stroke.
|
||||
fn shipped_default_style() -> GraphicStyle {
|
||||
GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, vectorcraft_doc::Appearance::default_art())
|
||||
}
|
||||
@@ -194,13 +194,19 @@ pub(super) fn clip_make(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
pub(super) fn clip_release(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let ids = selected_roots(s)?;
|
||||
// With no clip group selected, the document and its undo history stay as they are.
|
||||
// With no clip group and no stray clipping path selected, the document and its undo history
|
||||
// stay as they are.
|
||||
let d = &s.doc()?.doc;
|
||||
if !ids.iter().any(|id| d.node(*id).is_some_and(Node::clips)) {
|
||||
if !ids.iter().any(|id| d.node(*id).is_some_and(Node::clips) || stray_clipping_path(d, *id)) {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Release Clipping Mask", |d, _| {
|
||||
for id in &ids {
|
||||
if stray_clipping_path(d, *id)
|
||||
&& let Some(NodeKind::Path { clipping, .. }) = d.node_mut(*id).map(|n| &mut n.kind)
|
||||
{
|
||||
*clipping = false;
|
||||
}
|
||||
release_clip(d, *id);
|
||||
}
|
||||
Ok(())
|
||||
@@ -208,6 +214,13 @@ pub(super) fn clip_release(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Whether `id` is a path marked as a clipping path that clips nothing: not the bottom child of a
|
||||
/// clip group or clipping layer. A paste made one before #9227; the path commands skip it.
|
||||
fn stray_clipping_path(d: &Document, id: NodeId) -> bool {
|
||||
let marked = d.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { clipping: true, .. }));
|
||||
marked && !d.position(id).is_some_and(|(parent, i, _)| i == 0 && parent.and_then(|p| d.node(p)).is_some_and(Node::clips))
|
||||
}
|
||||
|
||||
/// Selects the clipping path (`mask`) or the clipped contents of every selected clip group (or of the
|
||||
/// clip group containing a selected object), like Illustrator's Edit Contents / Edit Clipping Path toggle.
|
||||
pub(super) fn clip_edit(s: &mut Session, mask: bool) -> Result<Value> {
|
||||
|
||||
@@ -467,13 +467,20 @@ impl Session {
|
||||
(!self.menu.new_masks_unclipped, self.menu.new_masks_inverted)
|
||||
}
|
||||
|
||||
/// The Transparency panel's values for the selection, or for the object whose mask is being
|
||||
/// edited (`transparency.info` without ids).
|
||||
/// The Transparency panel's values for the selection or for the object whose mask is being
|
||||
/// edited. A selected dynamic symbol part supplies its opacity and blend mode.
|
||||
pub fn transparency_info(&self) -> TransparencyInfo {
|
||||
match (self.active(), transparency_targets(self, &Value::Null)) {
|
||||
(Some(st), Ok(ids)) => {
|
||||
let points = self.mesh_points_picked();
|
||||
TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points)
|
||||
let mut info = TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points);
|
||||
if st.doc.mask_edit.is_none()
|
||||
&& let Some(part) = st.selected_symbol_part()
|
||||
{
|
||||
info.opacity = Some((f64::from(part.opacity) * 10_000.0).round() / 100.0);
|
||||
info.blend = Some(part.blend);
|
||||
}
|
||||
info
|
||||
}
|
||||
_ => TransparencyInfo::default(),
|
||||
}
|
||||
|
||||
+128
-34
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row o
Line truncated
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row o
Line truncated
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
@@ -51,7 +51,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke",
|
||||
[],
|
||||
None,
|
||||
"{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill), opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke (while the Shape Builder is the active tool, the selection still takes the stroke); without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
|
||||
"{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill), opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke (while the Shape Builder is the active tool, the selection still takes the stroke); without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
|
||||
has_doc,
|
||||
|s, p| { set_paint(s, p, false) }
|
||||
),
|
||||
@@ -238,9 +238,11 @@ impl Session {
|
||||
}
|
||||
// A Live Paint group without faces (or edges) shows the next selected object's paint; any other
|
||||
// object without a painted object shows the defaults for new art. A face or edge selected with
|
||||
// its Live Paint group counts with the group, wherever it is in the selection.
|
||||
let covered = st.selection_live_paint_covered(st.selection.subjects());
|
||||
for id in st.selection.subjects().iter().filter(|id| !covered.contains(*id)) {
|
||||
// its Live Paint group counts with the group, wherever it is in the selection. A targeted
|
||||
// layer stands for its selected editable art, which the paint commands edit
|
||||
// (ItemTarget::targets), not for a locked or hidden object in it.
|
||||
let covered = st.selection_live_paint_covered(&st.selection.objects);
|
||||
for id in st.selection.objects.iter().filter(|id| !covered.contains(*id)) {
|
||||
let Some(n) = st.doc.node(*id) else { continue };
|
||||
let mut nodes = vec![];
|
||||
painted(n, true, stroke, &mut nodes);
|
||||
@@ -316,7 +318,7 @@ impl Session {
|
||||
.into_iter()
|
||||
.filter(|id| editable(&id))
|
||||
.collect();
|
||||
return targets.iter().zip(row.per_target(self, &targets)).find_map(|(id, at)| {
|
||||
return targets.iter().zip(row.each_target(self, &targets)).find_map(|(id, at)| {
|
||||
let n = st.doc.node(*id)?;
|
||||
of(n, at?.resolve(&n.appearance, !stroke, "paint.proxies").ok()?)
|
||||
});
|
||||
@@ -396,20 +398,62 @@ pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&'
|
||||
/// whether another one differs ([`DocState::proxy_mixed`] without an active Appearance item or
|
||||
/// picked mesh points, and [`super::stroke::StrokeMixed::weight`]), and whether an object lies in a
|
||||
/// Live Paint group or may hold a gradient mesh. The objects added to a selection are read with
|
||||
/// [`SelectionPaints::add`].
|
||||
/// [`SelectionPaints::add`], and the objects taken out of it with [`SelectionPaints::remove`].
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct SelectionPaints {
|
||||
fill: Option<Paint>,
|
||||
pub(crate) fill_mixed: bool,
|
||||
stroke: Option<Paint>,
|
||||
pub(crate) stroke_mixed: bool,
|
||||
weight: Option<f64>,
|
||||
pub(crate) weight_mixed: bool,
|
||||
/// An object is a face or edge of a Live Paint group, or lies inside one
|
||||
fill: Tally<Paint>,
|
||||
stroke: Tally<Paint>,
|
||||
weight: Tally<f64>,
|
||||
/// The objects that are a face or edge of a Live Paint group, or lie inside one
|
||||
/// ([`live_paint_covered`]).
|
||||
pub(crate) in_live_paint: bool,
|
||||
/// An object is a gradient mesh or a container ([`Session::fill_mesh_points`]).
|
||||
pub(crate) may_hold_mesh: bool,
|
||||
in_live_paint: usize,
|
||||
/// The objects that are a gradient mesh or a container ([`Session::fill_mesh_points`]).
|
||||
may_hold_mesh: usize,
|
||||
}
|
||||
|
||||
/// The first value met, how many of the values met are the same as it, and how many were met.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Tally<T> {
|
||||
first: Option<T>,
|
||||
same: usize,
|
||||
all: usize,
|
||||
}
|
||||
|
||||
impl<T> Default for Tally<T> {
|
||||
fn default() -> Self {
|
||||
Self { first: None, same: 0, all: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Tally<T> {
|
||||
fn add(&mut self, value: T, same: impl Fn(&T, &T) -> bool) {
|
||||
self.all += 1;
|
||||
match &self.first {
|
||||
Some(f) if same(f, &value) => self.same += 1,
|
||||
Some(_) => {}
|
||||
None => (self.first, self.same) = (Some(value), 1),
|
||||
}
|
||||
}
|
||||
/// Take out a value met before. → false when the values left must be met again to know which
|
||||
/// differ: every value the same as the first one is gone, and others are left.
|
||||
fn remove(&mut self, value: &T, same: impl Fn(&T, &T) -> bool) -> bool {
|
||||
let Some(f) = &self.first else { return false };
|
||||
if self.all == 0 {
|
||||
return false;
|
||||
}
|
||||
self.all -= 1;
|
||||
if same(f, value) {
|
||||
self.same = self.same.saturating_sub(1);
|
||||
}
|
||||
if self.same == 0 {
|
||||
self.first = None;
|
||||
return self.all == 0;
|
||||
}
|
||||
true
|
||||
}
|
||||
fn mixed(&self) -> bool {
|
||||
self.same < self.all
|
||||
}
|
||||
}
|
||||
|
||||
impl SelectionPaints {
|
||||
@@ -420,31 +464,76 @@ impl SelectionPaints {
|
||||
p
|
||||
}
|
||||
|
||||
/// Read objects `ids` of `doc` too.
|
||||
/// Do the fills differ?
|
||||
pub(crate) fn fill_mixed(&self) -> bool {
|
||||
self.fill.mixed()
|
||||
}
|
||||
|
||||
/// Do the strokes differ?
|
||||
pub(crate) fn stroke_mixed(&self) -> bool {
|
||||
self.stroke.mixed()
|
||||
}
|
||||
|
||||
/// Do the stroke weights differ?
|
||||
pub(crate) fn weight_mixed(&self) -> bool {
|
||||
self.weight.mixed()
|
||||
}
|
||||
|
||||
/// Is an object a face or edge of a Live Paint group, or inside one?
|
||||
pub(crate) fn in_live_paint(&self) -> bool {
|
||||
self.in_live_paint > 0
|
||||
}
|
||||
|
||||
/// Is an object a gradient mesh or a container?
|
||||
pub(crate) fn may_hold_mesh(&self) -> bool {
|
||||
self.may_hold_mesh > 0
|
||||
}
|
||||
|
||||
/// Read objects `ids` of `doc` too: ids that are not read yet, each named once.
|
||||
pub(crate) fn add(&mut self, doc: &Document, ids: &[NodeId]) {
|
||||
fn meet<T>(first: &mut Option<T>, mixed: &mut bool, value: T, same: impl Fn(&T, &T) -> bool) {
|
||||
match first {
|
||||
Some(f) => *mixed |= !same(f, &value),
|
||||
None => *first = Some(value),
|
||||
self.each(doc, ids, true);
|
||||
}
|
||||
|
||||
/// Take out objects `ids` of `doc`, read before in the same document: ids that are read, each
|
||||
/// named once. → false when the objects left must be read again ([`Tally::remove`]); the
|
||||
/// paints are then wrong.
|
||||
pub(crate) fn remove(&mut self, doc: &Document, ids: &[NodeId]) -> bool {
|
||||
self.each(doc, ids, false)
|
||||
}
|
||||
|
||||
/// [`Self::add`] (`add`) or [`Self::remove`].
|
||||
fn each(&mut self, doc: &Document, ids: &[NodeId], add: bool) -> bool {
|
||||
let mut ok = true;
|
||||
let mut meet = |tally: &mut Tally<Paint>, value: Paint| {
|
||||
if add {
|
||||
tally.add(value, same_in_proxy);
|
||||
} else {
|
||||
ok &= tally.remove(&value, same_in_proxy);
|
||||
}
|
||||
}
|
||||
// As in `proxy_mixed_with`: every node with an added id, in tree order.
|
||||
};
|
||||
// As in `proxy_mixed_with`: every node with one of the ids, in tree order.
|
||||
let (mut fills, mut strokes) = (vec![], vec![]);
|
||||
for n in doc.nodes_in_order(ids.iter().copied()) {
|
||||
painted(n, true, false, &mut fills);
|
||||
painted(n, true, true, &mut strokes);
|
||||
}
|
||||
for n in fills {
|
||||
meet(&mut self.fill, &mut self.fill_mixed, proxy_paint(n, false, None), same_in_proxy);
|
||||
meet(&mut self.fill, proxy_paint(n, false, None));
|
||||
}
|
||||
for n in strokes {
|
||||
meet(&mut self.stroke, &mut self.stroke_mixed, proxy_paint(n, true, None), same_in_proxy);
|
||||
meet(&mut self.stroke, proxy_paint(n, true, None));
|
||||
}
|
||||
// As in `stroke_mixed`: the node each added id names.
|
||||
for id in ids {
|
||||
// As in `stroke_mixed`: the node each id names.
|
||||
let step = |count: &mut usize, yes: bool| {
|
||||
if yes {
|
||||
*count = if add { *count + 1 } else { count.saturating_sub(1) };
|
||||
}
|
||||
};
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for id in ids.iter().filter(|id| seen.insert(**id)) {
|
||||
let Some(n) = doc.node(*id) else { continue };
|
||||
self.in_live_paint |= in_live_paint(doc, *id);
|
||||
self.may_hold_mesh |= matches!(n.kind, NodeKind::Mesh(_)) || n.is_container();
|
||||
step(&mut self.in_live_paint, in_live_paint(doc, *id));
|
||||
step(&mut self.may_hold_mesh, matches!(n.kind, NodeKind::Mesh(_)) || n.is_container());
|
||||
let mut nodes = vec![];
|
||||
painted(n, true, true, &mut nodes);
|
||||
for n in nodes {
|
||||
@@ -453,10 +542,15 @@ impl SelectionPaints {
|
||||
_ => n.appearance.stroke().map(|s| s.width).into_iter().collect(),
|
||||
};
|
||||
for w in widths {
|
||||
meet(&mut self.weight, &mut self.weight_mixed, w, |a, b| a == b);
|
||||
if add {
|
||||
self.weight.add(w, |a, b| a == b);
|
||||
} else {
|
||||
ok &= self.weight.remove(&w, |a, b| a == b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ok
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1159,7 +1253,7 @@ impl Session {
|
||||
/// takes from the selection now ([`Session::inherit_new_art`]). No appearance is captured
|
||||
/// while inheritance does not run (New Art Has Basic Appearance on, or the active tool painting
|
||||
/// with both the fill and the stroke).
|
||||
fn note_defaults_only(&mut self) {
|
||||
pub(crate) fn note_defaults_only(&mut self) {
|
||||
let inherits = !self.prefs.new_art_basic && !(self.tool_paints(false) && self.tool_paints(true));
|
||||
self.defaults_only_ran = Some(if inherits { self.new_art_source() } else { None });
|
||||
}
|
||||
@@ -1273,7 +1367,7 @@ impl DocState {
|
||||
/// [`live_paint_covered`] for `ids`, the selected objects or the selection's subjects: none
|
||||
/// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group.
|
||||
pub(crate) fn selection_live_paint_covered(&self, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
|
||||
if self.selection_paints().is_some_and(|p| !p.in_live_paint) {
|
||||
if self.selection_paints().is_some_and(|p| !p.in_live_paint()) {
|
||||
return std::collections::HashSet::new();
|
||||
}
|
||||
live_paint_covered(&self.doc, ids)
|
||||
@@ -1525,7 +1619,7 @@ impl Session {
|
||||
// Only gradient meshes have points to pick: a selection with no mesh and no container that
|
||||
// could hold one skips reading the tool's options.
|
||||
let may_hold_mesh = |id: &NodeId| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Mesh(_)) || n.is_container());
|
||||
let none_may = || st.selection_paints().map_or_else(|| !st.selection.subjects().iter().any(may_hold_mesh), |p| !p.may_hold_mesh);
|
||||
let none_may = || st.selection_paints().map_or_else(|| !st.selection.subjects().iter().any(may_hold_mesh), |p| !p.may_hold_mesh());
|
||||
if st.selection.symbol_part.is_some() || none_may() {
|
||||
return vec![];
|
||||
}
|
||||
|
||||
@@ -266,6 +266,36 @@ fn random_selections_match_a_walk_of_the_document() {
|
||||
}
|
||||
}
|
||||
|
||||
/// With an Appearance row active and many objects selected, the opacity proxy (read on every repaint of the Color
|
||||
/// Wheel panel) and `first_edited` match only the targets they read against the first object's stack, not every
|
||||
/// target, and still answer with the first object's row.
|
||||
#[test]
|
||||
fn an_active_row_matches_only_the_targets_read() {
|
||||
use super::super::appearance::{ItemTarget, first_edited, stacks_matched};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap();
|
||||
let ids: Vec<NodeId> = (0..30).map(|i| rect(&mut s, f64::from(i) * 25.0, "#ff0000", "#0000ff")).collect();
|
||||
s.execute("paint.setFill", &json!({"ids": [ids[0].0], "opacity": 40})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()})).unwrap();
|
||||
let fill = s.active().unwrap().doc.node(ids[0]).unwrap().appearance.items.iter().position(|it| it.is_fill()).unwrap();
|
||||
s.execute("appearance.setActiveItem", &json!({"index": fill})).unwrap();
|
||||
assert_eq!(s.appearance_item(), Some(fill));
|
||||
|
||||
let before = stacks_matched();
|
||||
assert!((s.proxy_opacity(false).unwrap() - 0.4).abs() < 1e-6, "the first object's fill opacity");
|
||||
assert!(stacks_matched() - before <= 1, "proxy_opacity matched {} stacks for {} targets", stacks_matched() - before, ids.len());
|
||||
|
||||
let row = ItemTarget::Item { index: fill, explicit: false, aligned: true };
|
||||
let before = stacks_matched();
|
||||
assert_eq!(first_edited(&s, row, None, &ids), Some((ids[0], row)));
|
||||
assert!(stacks_matched() - before <= 1, "first_edited matched {} stacks for {} targets", stacks_matched() - before, ids.len());
|
||||
|
||||
// Reading every target still matches each one but the first.
|
||||
let before = stacks_matched();
|
||||
assert_eq!(row.per_target(&s, &ids).len(), ids.len());
|
||||
assert_eq!(stacks_matched() - before, ids.len() as u64 - 1);
|
||||
}
|
||||
|
||||
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
|
||||
fn thread_cpu() -> Option<std::time::Duration> {
|
||||
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
|
||||
|
||||
@@ -260,6 +260,8 @@ thread_local! {
|
||||
pub(crate) static PARSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Whether [`known`] is skipped on this thread ([`uncached`]).
|
||||
static UNCACHED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// The cells [`distance`] worked out on this thread: one for each pair of characters it compared.
|
||||
pub(crate) static DISTANCE_CELLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Whether [`read_descriptions`] keeps what `doc` says.
|
||||
@@ -330,6 +332,8 @@ fn no_required_id_beside_ids(doc: &str) -> bool {
|
||||
/// The edits (insert, delete, replace, swap of neighbours) that turn `a` into `b`, ignoring case.
|
||||
fn distance(a: &str, b: &str) -> usize {
|
||||
let (a, b): (Vec<char>, Vec<char>) = (a.chars().map(|c| c.to_ascii_lowercase()).collect(), b.chars().map(|c| c.to_ascii_lowercase()).collect());
|
||||
#[cfg(test)]
|
||||
DISTANCE_CELLS.with(|n| n.set(n.get().saturating_add(a.len().saturating_mul(b.len()))));
|
||||
let (mut before, mut prev): (Vec<usize>, Vec<usize>) = (Vec::new(), (0..=b.len()).collect());
|
||||
for (i, ca) in a.iter().enumerate() {
|
||||
let mut row = vec![i + 1];
|
||||
|
||||
@@ -13,7 +13,7 @@ use vectorcraft_geom::{FillRule, PathData, SubPath};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_pathops::{BoolOp, PathfinderOp};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::edit::{selected_roots, selection_roots};
|
||||
use super::expand::{fill_shape, reshaped, seeded};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_switches, checked_ids_or_selection, cmd, has_doc, has_selected_path, has_selection,
|
||||
@@ -190,7 +190,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clean Up…",
|
||||
["Object", "Path"],
|
||||
None,
|
||||
"{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} → {removed}",
|
||||
"{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} remove them, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed}",
|
||||
has_doc,
|
||||
clean_up
|
||||
),
|
||||
@@ -1147,6 +1147,59 @@ pub(crate) fn outlinable(st: &StrokeLayer) -> bool {
|
||||
st.visible && !st.paint.is_none() && st.width > 0.0
|
||||
}
|
||||
|
||||
/// Whether any segment can paint a butt-capped stroke. Check only used control points:
|
||||
/// coincident endpoints can still describe a curve, but unused open-end handles cannot.
|
||||
fn may_paint_butt_stroke(n: &Node) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.subpaths.iter().any(|sp| {
|
||||
(0..sp.segment_count()).any(|i| {
|
||||
let c = sp.segment(i);
|
||||
c.p0 != c.p3 || c.p0 != c.p1 || c.p0 != c.p2
|
||||
})
|
||||
}),
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| may_paint_butt_stroke(c)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Does Outline Stroke have a stroke to turn into art under `n`, outside the dimension subtrees
|
||||
/// the command will keep? Guides, clipping paths and type are not outlined.
|
||||
fn has_outlinable_stroke(n: &Node, kept: &[NodeId]) -> bool {
|
||||
if kept.contains(&n.id) {
|
||||
return false;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => false,
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
|
||||
let geometry = std::cell::LazyCell::new(|| may_paint_butt_stroke(n));
|
||||
n.appearance.items.iter().any(|i| {
|
||||
let AppearanceItem::Stroke(st) = i else { return false };
|
||||
// Brushes, arrowheads, profiles and geometry effects can make a point paint.
|
||||
outlinable(st)
|
||||
&& (st.cap != vectorcraft_doc::LineCap::Butt
|
||||
|| st.brush.is_some()
|
||||
|| st.start_arrow.is_some()
|
||||
|| st.end_arrow.is_some()
|
||||
|| st.profile.is_some()
|
||||
|| vectorcraft_render::effects::has_geometry(&n.appearance.effects)
|
||||
|| vectorcraft_render::effects::has_geometry(&st.effects)
|
||||
|| *geometry)
|
||||
})
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().any(|c| has_outlinable_stroke(c, kept)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `object.path.outlineStroke` have a stroke to outline in `st`'s selection? It acts on the
|
||||
/// selection's roots (a compound path's member stands for its compound, which holds the
|
||||
/// appearance), excluding the linked dimensions that the command lifts while outlining their art.
|
||||
pub fn can_outline_stroke(st: &crate::DocState) -> bool {
|
||||
let roots = selection_roots(st);
|
||||
let kept = super::dimension::with_their_art(&st.doc, &roots);
|
||||
roots.into_iter().filter_map(|id| st.doc.node(id)).any(|n| has_outlinable_stroke(n, &kept))
|
||||
}
|
||||
|
||||
/// `n` with `opacity` and `blend` applied: set on it when it has none of its own, else on a
|
||||
/// group around it.
|
||||
pub(crate) fn with_transparency(d: &mut Document, mut n: Node, opacity: f32, blend: BlendMode) -> Node {
|
||||
@@ -1672,9 +1725,14 @@ fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut v = vec![];
|
||||
fn visit(n: &Node, parent_compound: bool, parent_clip: bool, first: bool, v: &mut Vec<NodeId>, opts: (bool, bool, bool)) {
|
||||
let (stray, unpainted, empty_text) = opts;
|
||||
// The clipping path of a group or layer stays as it is, whatever kind of object it is,
|
||||
// and so does everything a group or compound path used as one holds.
|
||||
if parent_clip && first {
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, clipping, guide, .. } => {
|
||||
if *guide || *clipping || (parent_clip && first) {
|
||||
if *guide || *clipping {
|
||||
return;
|
||||
}
|
||||
if (stray && path.anchor_count() <= 1) || (unpainted && !parent_compound && !is_painted(&n.appearance)) {
|
||||
@@ -1682,7 +1740,7 @@ fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
NodeKind::Compound { children, .. } => {
|
||||
if unpainted && !(parent_clip && first) && !is_painted(&n.appearance) {
|
||||
if unpainted && !is_painted(&n.appearance) {
|
||||
v.push(n.id);
|
||||
return;
|
||||
}
|
||||
@@ -1691,14 +1749,10 @@ fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
NodeKind::Text(t) if empty_text && t.plain_text().trim().is_empty() => v.push(n.id),
|
||||
NodeKind::Layer { children, .. } => {
|
||||
for c in children {
|
||||
visit(c, false, false, false, v, opts);
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, clip } => {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
|
||||
let clips = n.clips();
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
visit(c, false, *clip, i == 0, v, opts);
|
||||
visit(c, false, clips, i == 0, v, opts);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -19,6 +19,7 @@ use vectorcraft_doc::swatches::{PaintFn, graph_paints, node_paints, override_pai
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
|
||||
use super::brushsym::frame_marker;
|
||||
use super::edit::{outermost, selected_roots};
|
||||
use super::pathops::Beside;
|
||||
use super::{
|
||||
@@ -43,10 +44,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Replace Pattern Art",
|
||||
[],
|
||||
None,
|
||||
"{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, for an id that names no object, and for art painted with the pattern itself → {name}",
|
||||
"{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch and options; an unpainted rectangle at the back of the art (or at the back of one selected group, as pattern.placeArt places it) becomes the tile and is left out of the tile art, otherwise the tile keeps its size and moves as far as the art's bounds moved from the old tile art's (with Size Tile to Art on, the tile fits the new art); every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art and tile match the pattern's already; refused while a pattern is edited, with nothing selected, for an id that names no object, and for art painted with the pattern itself → {name}",
|
||||
can_replace_pattern_art,
|
||||
pattern_replace_art
|
||||
),
|
||||
cmd!(
|
||||
"pattern.placeArt",
|
||||
"Place Pattern Art",
|
||||
[],
|
||||
None,
|
||||
"{name, x?, y?} place a copy of pattern `name`'s tile art, as dragging its swatch from the Swatches panel onto an empty part of the canvas does: one group with an unpainted rectangle of the tile at its back, centered on (x, y) (default: the center of the first artboard) in the layer new art goes into, and selected; object.pattern.replaceArt reads the rectangle back as the tile; the pattern does not change; one undo step; refused while a pattern is edited and for a pattern with no art → {id}",
|
||||
can_replace_pattern_art,
|
||||
pattern_place_art
|
||||
),
|
||||
cmd!(
|
||||
"object.pattern.edit",
|
||||
"Edit Pattern",
|
||||
@@ -434,41 +444,102 @@ pub(crate) fn finish_edit(d: &mut Document, sel: &mut Selection) -> Result<Strin
|
||||
}
|
||||
|
||||
/// Give pattern `name` fresh-id copies of the selected art (or of `ids`) as its tile art, as one
|
||||
/// undo step (`object.pattern.replaceArt`). The pattern keeps its name, swatch, tile and options,
|
||||
/// and its tile fits the new art when its Size Tile to Art is on; paints refer to a pattern by
|
||||
/// name, so every fill and stroke of it draws the new tile. The art stays where it is, selected as
|
||||
/// before. Art that matches the tile art already records nothing.
|
||||
/// undo step (`object.pattern.replaceArt`). The pattern keeps its name, swatch and options. An
|
||||
/// unpainted rectangle at the back of the art becomes the tile ([`tile_and_art`]); without one the
|
||||
/// tile keeps its size and moves as far as the art's bounds moved from the old tile art's, so art
|
||||
/// drawn anywhere stays in its tile. With Size Tile to Art on, the tile fits the new art. Paints
|
||||
/// refer to a pattern by name, so every fill and stroke of it draws the new tile. The art stays
|
||||
/// where it is, selected as before. Art and a tile that match the pattern's already record nothing.
|
||||
fn pattern_replace_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.pattern.replaceArt";
|
||||
let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string();
|
||||
let roots = roots(s, p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let old = d.pattern(&name).map(|def| def.art.clone()).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?;
|
||||
if roots.is_empty() {
|
||||
let def = d.pattern(&name).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?;
|
||||
let (src, marked) = tile_and_art(roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect());
|
||||
if src.is_empty() {
|
||||
return Err(bad(C, "select the art for the pattern tile"));
|
||||
}
|
||||
let src: Vec<Arc<Node>> = roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect();
|
||||
if paints_pattern(d, &src, &name) {
|
||||
return Err(bad(C, format!("art painted with `{name}` can't be its tile")));
|
||||
}
|
||||
let mut next = def.clone();
|
||||
next.tile = match (marked, vectorcraft_doc::live::nodes_bounds(&def.art), vectorcraft_doc::live::nodes_bounds(&src)) {
|
||||
(Some(tile), ..) => tile,
|
||||
(None, Some(was), Some(now)) => def.tile + (now.origin() - was.origin()),
|
||||
(None, ..) => def.tile,
|
||||
};
|
||||
next.art = src.clone();
|
||||
if next.size_tile_to_art {
|
||||
next.fit_tile_to_art();
|
||||
}
|
||||
let tile = next.tile;
|
||||
// Copies made from the same next id are equal when the art matches the tile art.
|
||||
let fresh = |art: &[Arc<Node>]| copies(&mut Document::clone(d), art);
|
||||
if fresh(&old) == fresh(&src) {
|
||||
if tile == def.tile && fresh(&def.art) == fresh(&src) {
|
||||
return Ok(json!({ "name": name }));
|
||||
}
|
||||
s.edit("Replace Pattern Art", |d, _| {
|
||||
let art: Vec<Arc<Node>> = copies(d, &src).into_iter().map(Arc::new).collect();
|
||||
if let Some(def) = d.pattern_mut(&name) {
|
||||
def.art = art;
|
||||
if def.size_tile_to_art {
|
||||
def.fit_tile_to_art();
|
||||
}
|
||||
def.tile = tile;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
/// The tile art and the tile that art `src` (in paint order) gives a pattern: an unpainted
|
||||
/// rectangle at the back of the art ([`frame_marker`]), or at the back of a lone plain group as
|
||||
/// `pattern.placeArt` places it, is the tile and is left out of the art, and that group's members
|
||||
/// are the art. Without such a rectangle the art is `src` and there is no tile.
|
||||
fn tile_and_art(src: Vec<Arc<Node>>) -> (Vec<Arc<Node>>, Option<Rect>) {
|
||||
let mut art = src;
|
||||
if let [g] = art.as_slice()
|
||||
&& let NodeKind::Group { children, clip: false } = &g.kind
|
||||
&& children.first().is_some_and(|c| frame_marker(c).is_some())
|
||||
&& **g == Node::group(g.id, children.clone())
|
||||
{
|
||||
art = children.clone();
|
||||
}
|
||||
match art.first().and_then(|c| frame_marker(c)) {
|
||||
Some(tile) => (art.split_off(1), Some(tile)),
|
||||
None => (art, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// `pattern.placeArt`: a copy of pattern `name`'s tile art in one group, with an unpainted
|
||||
/// rectangle of its tile at the back, centered on (`x`, `y`) (default: the center of the first
|
||||
/// artboard) in the layer new art goes into, and selected, as one undo step. The pattern does not
|
||||
/// change; `object.pattern.replaceArt` reads the rectangle back as the tile ([`tile_and_art`]).
|
||||
fn pattern_place_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "pattern.placeArt";
|
||||
let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string();
|
||||
let d = &s.doc()?.doc;
|
||||
let center = d.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
|
||||
let at = Point::new(super::number_or(p, "x", center.x, C)?, super::number_or(p, "y", center.y, C)?);
|
||||
let def = d.pattern(&name).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?;
|
||||
if def.art.is_empty() {
|
||||
return Err(bad(C, "no artwork"));
|
||||
}
|
||||
let unpainted = vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0);
|
||||
let marker = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(def.tile), unpainted);
|
||||
let mut art = Node::group(NodeId(0), std::iter::once(Arc::new(marker)).chain(def.art.iter().cloned()).collect());
|
||||
if let Some(r) = art.geometric_bounds_with(&d.symbol_boxes()) {
|
||||
art.transform(vectorcraft_geom::Affine::translate(at - r.center()), false);
|
||||
}
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let id = s.edit("Place Pattern Art", |d, sel| {
|
||||
let art = d.reid(&art);
|
||||
let id = art.id;
|
||||
d.insert(parent, usize::MAX, art)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// What a piece of art uses by name, for [`paints_pattern`].
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
enum Uses<'a> {
|
||||
|
||||
@@ -49,6 +49,9 @@ pub(crate) mod docx;
|
||||
mod rtf;
|
||||
pub(super) mod text;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use doc::PRLS_READ;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -487,10 +487,18 @@ fn operand_len(sprm: u16, rest: &[u8]) -> Option<usize> {
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The Prls [`each_prl`] read on this thread.
|
||||
pub(crate) static PRLS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Calls `f` with each Prl of `grpprl`: its sprm and its operand.
|
||||
fn each_prl(grpprl: &[u8], mut f: impl FnMut(u16, &[u8])) {
|
||||
let mut at = 0;
|
||||
while let Some(sprm) = u16_at(grpprl, at) {
|
||||
#[cfg(test)]
|
||||
PRLS_READ.with(|n| n.set(n.get() + 1));
|
||||
let rest = grpprl.get(at + 2..).unwrap_or_default();
|
||||
let Some((n, op)) = operand_len(sprm, rest).and_then(|n| Some((n, rest.get(..n)?))) else { return };
|
||||
// A variable operand's bytes follow its size.
|
||||
|
||||
+456
-23
@@ -128,6 +128,9 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
if m.paint_output {
|
||||
v["paintOutput"] = json!(true);
|
||||
}
|
||||
if m.appearance_output {
|
||||
v["appearanceOutput"] = json!(true);
|
||||
}
|
||||
if let Some(script) = p.script() {
|
||||
v["runtime"] = json!(m.runtime.name());
|
||||
v["script"] = json!(script);
|
||||
@@ -204,6 +207,36 @@ pub struct FilterRun {
|
||||
limits: vectorcraft_plugins::Limits,
|
||||
}
|
||||
|
||||
/// What running a [`FilterRun`] away from the session takes ([`FilterRun::job`]).
|
||||
pub struct FilterJob {
|
||||
pub plugin: Arc<Plugin>,
|
||||
pub input: Vec<u8>,
|
||||
pub params: Vec<u8>,
|
||||
pub limits: vectorcraft_plugins::Limits,
|
||||
}
|
||||
|
||||
/// The run of a filter that calls commands that holds the documents ([`FilterRun::begin_calls`]):
|
||||
/// the run, what its calls keep fixed, and its open undo step.
|
||||
pub(crate) struct Calling {
|
||||
/// The command that applies its output: `plugin.run`, or the plug-in command it runs, and the
|
||||
/// params it was started with, which that command must be given.
|
||||
cmd: String,
|
||||
params: Value,
|
||||
run: FilterRun,
|
||||
calls: super::plugin_call::Calls,
|
||||
tx: super::plugin_call::Transaction,
|
||||
}
|
||||
|
||||
/// A module that a load in another place checked ([`Session::hand_in_checked_plugin`]): its
|
||||
/// SHA-256 and the manifest JSON that load read.
|
||||
pub(crate) struct Checked {
|
||||
hash: String,
|
||||
manifest: Vec<u8>,
|
||||
}
|
||||
|
||||
/// How many checked modules the session keeps.
|
||||
const MAX_CHECKED: usize = 4;
|
||||
|
||||
/// A filter's output handed in by a [`FilterRun`] made away from `plugin.run`, with what the run
|
||||
/// was made of: only a run of the same installation of the plug-in on the same input with the same
|
||||
/// parameters takes it (a plug-in's output depends on nothing else).
|
||||
@@ -338,6 +371,53 @@ impl FilterRun {
|
||||
&self.limits
|
||||
}
|
||||
|
||||
/// The input JSON it gives the plug-in: the objects.
|
||||
pub fn input(&self) -> &[u8] {
|
||||
&self.input
|
||||
}
|
||||
|
||||
/// The parameters JSON it gives the plug-in, `_context` included.
|
||||
pub fn params(&self) -> &[u8] {
|
||||
&self.params
|
||||
}
|
||||
|
||||
/// What running it away from the session takes: the plug-in, its input and parameters, and the
|
||||
/// limits it runs under.
|
||||
pub fn job(&self) -> FilterJob {
|
||||
FilterJob { plugin: Arc::clone(&self.plugin), input: self.input.clone(), params: self.params.clone(), limits: self.limits.clone() }
|
||||
}
|
||||
|
||||
/// [`FilterRun::prepare_for`] command `c` (`plugin.run` or a plug-in command) of a filter that
|
||||
/// calls commands, which runs away from the session (the web build's plug-in worker) while the
|
||||
/// session makes its command calls ([`Session::plugin_call`]). The edit in progress is kept
|
||||
/// first, as `c` keeps it. The session then holds the run's undo step open and refuses every
|
||||
/// command but queries and `c` ([`EngineError::PluginBusy`]) until `c` applies the output handed
|
||||
/// in for it ([`Session::hand_in_plugin_calls`]) or [`Session::end_plugin_calls`] ends it → what
|
||||
/// running it takes.
|
||||
pub fn begin_calls(s: &mut Session, c: &str, p: &Value) -> Result<FilterJob> {
|
||||
if s.plugin_calls_open() {
|
||||
return Err(EngineError::PluginBusy);
|
||||
}
|
||||
let r = FilterRun::prepare_for(s, c, p)?;
|
||||
let r = if super::plugin_call::settle(s)? { FilterRun::prepare_for(s, c, p)? } else { r };
|
||||
let tx = super::plugin_call::Transaction::begin(s, &r.label())?;
|
||||
let may = r.plugin.manifest().permissions();
|
||||
let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite));
|
||||
let job = r.job();
|
||||
s.plugin_calling = Some(Calling { cmd: c.to_string(), params: p.clone(), run: r, calls, tx });
|
||||
Ok(job)
|
||||
}
|
||||
|
||||
/// The run command `c`'s params `p` ask for: `plugin.run`'s ([`FilterRun::prepare`]), or a
|
||||
/// plug-in command's (`plugin.<id>.<command>`), on the active document.
|
||||
pub fn prepare_for(s: &Session, c: &str, p: &Value) -> Result<FilterRun> {
|
||||
if c == "plugin.run" {
|
||||
return FilterRun::prepare(s, p);
|
||||
}
|
||||
let (plugin, command) = command_of(c).ok_or_else(|| EngineError::UnknownCommand(c.into()))?;
|
||||
FilterRun::prepare_with(s, plugin, Some(command), c, p)
|
||||
}
|
||||
|
||||
/// The parameters it hands the plug-in, `_context` included.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn params_json(&self) -> Value {
|
||||
@@ -520,7 +600,10 @@ pub fn keep_unapplied_typing(s: &mut Session) -> Result<bool> {
|
||||
/// was applied, with the plug-in's name.
|
||||
fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// An output handed in is for this run only (the app hands it in just before), whatever it does.
|
||||
let handed = s.plugin_output.take();
|
||||
let mut handed = s.plugin_output.take();
|
||||
if let Some(r) = end_held(s, "plugin.run", p, &mut handed) {
|
||||
return r;
|
||||
}
|
||||
let r = FilterRun::prepare(s, p)?;
|
||||
// One that calls commands runs here, where it can make them, on the document with any edit in
|
||||
// progress committed.
|
||||
@@ -540,6 +623,32 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
r.finish(s, &output)
|
||||
}
|
||||
|
||||
/// Ends the run that holds the documents ([`FilterRun::begin_calls`]) when command `c` (with params
|
||||
/// `p`, the params the run was started with) is the one that applies its output and `handed` is
|
||||
/// that output: applied in the run's own undo step, to the objects the run was given → the
|
||||
/// command's result. Any other command, or other params, is refused while a run holds them, and so
|
||||
/// is the output once the plug-in is no longer installed as the run had it. `None`: no run holds
|
||||
/// them.
|
||||
fn end_held(s: &mut Session, c: &str, p: &Value, handed: &mut Option<HandedIn>) -> Option<Result<Value>> {
|
||||
let held = s.plugin_calling.take()?;
|
||||
let serial = held.run.plugin.serial();
|
||||
let installed = registry::get(held.run.plugin.id()).is_some_and(|plugin| plugin.serial() == serial);
|
||||
let same = held.cmd == c && *p == held.params && installed;
|
||||
let mine = handed.take().filter(|h| same && (h.serial, &h.input, &h.params) == (serial, &held.run.input, &held.run.params));
|
||||
let Some(h) = mine else {
|
||||
s.plugin_calling = Some(held);
|
||||
return Some(Err(EngineError::PluginBusy));
|
||||
};
|
||||
let Calling { cmd, run, calls, tx, .. } = held;
|
||||
// A panic applying the output still ends the run, so what its calls did is undone.
|
||||
let r = if calls.kept(s) {
|
||||
crate::guard::catch_panic(|| run.finish(s, &h.output)).unwrap_or_else(|msg| Err(EngineError::Internal { cmd, msg }))
|
||||
} else {
|
||||
Err(EngineError::Cancelled)
|
||||
};
|
||||
Some(tx.end(s, r))
|
||||
}
|
||||
|
||||
/// The command id of plug-in `plugin`'s command `command`: `plugin.<plugin>.<command>`.
|
||||
pub fn command_id(plugin: &str, command: &str) -> String {
|
||||
format!("{}{plugin}.{command}", vectorcraft_plugins::PREFIX)
|
||||
@@ -868,6 +977,7 @@ pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[
|
||||
(&["View"], "Snap to Pixel"),
|
||||
(&["View"], "Snap to Point"),
|
||||
(&["View"], "Snap to Glyph"),
|
||||
(&["View"], "Snapping"),
|
||||
(&["View"], "Saved View"),
|
||||
];
|
||||
|
||||
@@ -930,10 +1040,11 @@ fn unrouted(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
/// `_context.command`, under the plug-in's permissions and budget, applied as one undo step named
|
||||
/// after the command → `{plugin, command, ids, notice?, pluginName?}`. A run that fails (a trap, an exhausted
|
||||
/// budget, an output it may not make) leaves the document as it was, and the error names the
|
||||
/// plug-in and the command.
|
||||
/// plug-in and the command. An output handed in for this very run ([`FilterRun::hand_in`]) is
|
||||
/// applied instead of running the plug-in, as `plugin.run` applies one.
|
||||
pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
|
||||
// An output handed in is for `plugin.run` alone.
|
||||
s.plugin_output = None;
|
||||
// An output handed in is for this run only, whatever it does.
|
||||
let mut handed = s.plugin_output.take();
|
||||
let (plugin, command) = command_of(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
|
||||
let failed = {
|
||||
let (name, label) = (permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME), command.shown_label());
|
||||
@@ -942,6 +1053,9 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result<Value>
|
||||
e => EngineError::Other(format!("“{name}” › {label}: {e}")),
|
||||
}
|
||||
};
|
||||
if let Some(r) = end_held(s, id, p, &mut handed) {
|
||||
return r.map_err(failed);
|
||||
}
|
||||
let r = FilterRun::prepare_with(s, plugin, Some(command), id, p)?;
|
||||
if r.calls() {
|
||||
let r = match super::plugin_call::settle(s)? {
|
||||
@@ -960,7 +1074,11 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result<Value>
|
||||
}
|
||||
false => r,
|
||||
};
|
||||
let output = r.run().map_err(&failed)?;
|
||||
let handed = handed.filter(|h| (h.serial, &h.input, &h.params) == (r.plugin.serial(), &r.input, &r.params));
|
||||
let output = match handed {
|
||||
Some(h) => h.output,
|
||||
None => r.run().map_err(&failed)?,
|
||||
};
|
||||
r.finish(s, &output).map_err(failed)
|
||||
}
|
||||
|
||||
@@ -1021,15 +1139,22 @@ const MAX_DATA_CHARS: usize = (32 << 20) / 3 * 4 + 4;
|
||||
pub const EXTS: &[&str] = &["wasm", vectorcraft_plugins::js::PACKAGE_EXT];
|
||||
|
||||
/// The plug-in module command `c`'s params give, loaded and checked, and its bytes: `path` (a
|
||||
/// `.wasm` file) or `dataBase64` (the module, with `name` shown as its source).
|
||||
fn load_given(c: &str, p: &Value) -> Result<(Plugin, Vec<u8>)> {
|
||||
/// `.wasm` file) or `dataBase64` (the module, with `name` shown as its source). A module that a
|
||||
/// load in another place checked ([`Session::hand_in_checked_plugin`]) runs none of its code here.
|
||||
fn load_given(s: &Session, c: &str, p: &Value) -> Result<(Plugin, Vec<u8>)> {
|
||||
match (str_param(p, "path").filter(|s| !s.is_empty()), str_param(p, "dataBase64")) {
|
||||
(_, Some(data)) => {
|
||||
if data.len() > MAX_DATA_CHARS {
|
||||
return Err(bad(c, "`dataBase64` is larger than the module limit"));
|
||||
}
|
||||
let bytes = vectorcraft_format::base64_decode(data).ok_or_else(|| bad(c, "`dataBase64` is not valid base64"))?;
|
||||
let plugin = Plugin::load(&bytes, vectorcraft_plugins::Limits::default()).map_err(err)?;
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let hash = permissions::sha256_hex(&bytes);
|
||||
let plugin = match s.plugin_checked.iter().find(|k| k.hash == hash) {
|
||||
Some(k) => Plugin::load_checked(&bytes, limits, &k.manifest),
|
||||
None => Plugin::load(&bytes, limits),
|
||||
}
|
||||
.map_err(err)?;
|
||||
let plugin = match str_param(p, "name") {
|
||||
Some(name) => plugin.with_source(name),
|
||||
None => plugin,
|
||||
@@ -1077,6 +1202,93 @@ impl InstallApproval {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Hands in the manifest JSON `manifest` that a load of the module with SHA-256 `hash` read in
|
||||
/// another place (the web build's plug-in worker, [`vectorcraft_plugins::worker`]): a
|
||||
/// `plugin.inspect` or `plugin.install` of those very bytes (`dataBase64`) then loads the module
|
||||
/// with [`Plugin::load_checked`], which runs none of its code here. The newest
|
||||
/// [`MAX_CHECKED`] are kept.
|
||||
pub fn hand_in_checked_plugin(&mut self, hash: &str, manifest: Vec<u8>) {
|
||||
self.plugin_checked.retain(|c| c.hash != hash);
|
||||
if self.plugin_checked.len() >= MAX_CHECKED {
|
||||
self.plugin_checked.remove(0);
|
||||
}
|
||||
self.plugin_checked.push(Checked { hash: hash.to_string(), manifest });
|
||||
}
|
||||
|
||||
/// Has a load in another place checked the module with SHA-256 `hash`
|
||||
/// ([`Session::hand_in_checked_plugin`])?
|
||||
pub fn plugin_checked(&self, hash: &str) -> bool {
|
||||
self.plugin_checked.iter().any(|c| c.hash == hash)
|
||||
}
|
||||
|
||||
/// Does a plug-in run that calls commands hold the documents ([`FilterRun::begin_calls`])?
|
||||
pub fn plugin_calls_open(&self) -> bool {
|
||||
self.plugin_calling.is_some()
|
||||
}
|
||||
|
||||
/// Applies the edit the active tool computes on another thread (a Shape Builder merge), as a
|
||||
/// command that edits waits for it, and keeps the edit in progress (a drag, a preview, typing)
|
||||
/// as its own undo step, as a run that calls commands does before it starts, so a run made away
|
||||
/// from the session is given the document with them and applies as an undo step of its own →
|
||||
/// whether that changed the document or the selection.
|
||||
pub fn settle_for_plugin_run(&mut self) -> Result<bool> {
|
||||
let before = self.active().map(|d| (Arc::clone(&d.doc), d.selection.clone()));
|
||||
self.finish_tool_edit_later()?;
|
||||
let finished = match (&before, self.active()) {
|
||||
(Some((doc, selection)), Some(d)) => !Arc::ptr_eq(doc, &d.doc) || *selection != d.selection,
|
||||
(None, None) => false,
|
||||
_ => true,
|
||||
};
|
||||
Ok(super::plugin_call::settle(self)? || finished)
|
||||
}
|
||||
|
||||
/// Is command `id` the one that applies the output of the run that holds the documents?
|
||||
pub fn plugin_calls_end_with(&self, id: &str) -> bool {
|
||||
self.plugin_calling.as_ref().is_some_and(|c| c.cmd == id)
|
||||
}
|
||||
|
||||
/// Makes the command call `id` with `args` that the run [`FilterRun::begin_calls`] started asked
|
||||
/// for, as a call of that run on the page makes it → its result, or why it didn't run. With no
|
||||
/// such run, nothing runs.
|
||||
pub fn plugin_call(&mut self, id: &str, args: &Value) -> std::result::Result<Value, vectorcraft_plugins::host::CallFailure> {
|
||||
let Some(c) = self.plugin_calling.take() else {
|
||||
return Err(vectorcraft_plugins::host::CallFailure {
|
||||
code: vectorcraft_plugins::host::CALL_NO_CONTEXT,
|
||||
why: EngineError::Cancelled.to_string(),
|
||||
});
|
||||
};
|
||||
// As a step of `plugin.run`: not journaled on its own, and a panic fails the call.
|
||||
let depth = self.depth;
|
||||
self.depth += 1;
|
||||
let r = crate::guard::catch_panic(|| super::plugin_call::call(self, &c.calls, id, args));
|
||||
self.depth = depth;
|
||||
self.plugin_calling = Some(c);
|
||||
r.unwrap_or_else(|msg| {
|
||||
let why = EngineError::Internal { cmd: id.to_string(), msg }.to_string();
|
||||
Err(vectorcraft_plugins::host::CallFailure { code: vectorcraft_plugins::host::CALL_COMMAND_FAILED, why })
|
||||
})
|
||||
}
|
||||
|
||||
/// Hands in `output`, the output of the run [`FilterRun::begin_calls`] started, for the next run
|
||||
/// of the command that started it, with that run's params, to apply in its undo step.
|
||||
pub fn hand_in_plugin_calls(&mut self, output: Vec<u8>) {
|
||||
if let Some(c) = &self.plugin_calling {
|
||||
let r = &c.run;
|
||||
self.plugin_output = Some(HandedIn { serial: r.plugin.serial(), input: r.input.clone(), params: r.params.clone(), output });
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the run [`FilterRun::begin_calls`] started, which has no output (it failed, or was
|
||||
/// canceled): every document and the session state go back to how they were before it.
|
||||
pub fn end_plugin_calls(&mut self) {
|
||||
if let Some(c) = self.plugin_calling.take() {
|
||||
// An output handed in for it is dropped with it: a later run with the same input and
|
||||
// params is not given it.
|
||||
self.plugin_output = None;
|
||||
let _ = c.tx.end(self, Err(EngineError::Cancelled));
|
||||
}
|
||||
}
|
||||
|
||||
/// Lets the next `plugin.install` take its `grant` and `allowHeavy`, for the module `approval`
|
||||
/// describes. Call it only with what a person approved, just before that install.
|
||||
pub fn approve_plugin_install(&mut self, approval: InstallApproval) {
|
||||
@@ -1186,7 +1398,7 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let allow_heavy = switch_or(p, "allowHeavy", false, C)?;
|
||||
let grant = grant_param(C, p)?;
|
||||
let (plugin, bytes) = load_given(C, p)?;
|
||||
let (plugin, bytes) = load_given(s, C, p)?;
|
||||
// `hash` pins the module the user was shown: one with other bytes is refused.
|
||||
if let Some(h) = p.get("hash").filter(|v| !v.is_null())
|
||||
&& h.as_str() != Some(plugin.hash())
|
||||
@@ -1383,7 +1595,7 @@ pub(crate) fn keep_installed(s: &Session, turn: &StoreTurn, id: &str, bytes: &[u
|
||||
/// needs the user to grant its permissions first (`needsApproval`) and whether it would take
|
||||
/// another module's place (`needsReplace`).
|
||||
fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
load_given("plugin.inspect", p).map(|(plugin, _)| {
|
||||
load_given(s, "plugin.inspect", p).map(|(plugin, _)| {
|
||||
let mut v = describe(&plugin);
|
||||
v["needsApproval"] = json!(!s.plugin_approved(&plugin));
|
||||
v["needsReplace"] = json!(takes_over(s, &plugin));
|
||||
@@ -1614,8 +1826,14 @@ impl Drop for FolderPending {
|
||||
|
||||
/// Starts loading the plug-ins in `folder` on worker threads ([`registry::FolderLoad`]); `record`:
|
||||
/// the load's number in [`FOLDER`], whose record [`end_folder`] replaces with the report.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn start_folder(s: &Session, folder: &str, record: Option<u64>) -> FolderPending {
|
||||
start_folder_files(s, folder, None, record)
|
||||
}
|
||||
|
||||
/// [`start_folder`] for the one file `only` of `folder` when it is given, without listing the
|
||||
/// folder ([`registry::FolderLoad::list_file`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn start_folder_files(s: &Session, folder: &str, only: Option<&std::path::Path>, record: Option<u64>) -> FolderPending {
|
||||
let pending =
|
||||
|load| FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false };
|
||||
if let Err(e) = crate::file_access::check_read(folder) {
|
||||
@@ -1636,11 +1854,15 @@ fn start_folder(s: &Session, folder: &str, record: Option<u64>) -> FolderPending
|
||||
})
|
||||
};
|
||||
// The modules start loading once the loads queued before them are done.
|
||||
pending(registry::FolderLoad::list(std::path::Path::new(folder), allow).map_err(|e| json!({"folder": folder, "error": e.to_string()})))
|
||||
let listed = match only {
|
||||
Some(file) => registry::FolderLoad::list_file(file, allow),
|
||||
None => registry::FolderLoad::list(std::path::Path::new(folder), allow),
|
||||
};
|
||||
pending(listed.map_err(|e| json!({"folder": folder, "error": e.to_string()})))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn start_folder(s: &Session, folder: &str, record: Option<u64>) -> FolderPending {
|
||||
fn start_folder_files(s: &Session, folder: &str, _: Option<&std::path::Path>, record: Option<u64>) -> FolderPending {
|
||||
let load = Err(json!({"folder": folder, "error": "plug-in folders are not available on the web"}));
|
||||
FolderPending { folder: folder.to_string(), store: s.plugin_dir.clone(), record, reload: false, load: Some(load), canceled: false }
|
||||
}
|
||||
@@ -1658,6 +1880,13 @@ pub(crate) fn install_folder(s: &mut Session, load: &mut FolderPending, turn: &S
|
||||
{
|
||||
for id in load.install_ready(s.plugin_folder_approver()) {
|
||||
s.attach_plugin_storage(turn, &id);
|
||||
// A `plugin.reload` of the plug-in store's own folder installed a stored file that
|
||||
// failed before.
|
||||
if let Some(p) = registry::get(&id)
|
||||
&& let Some(source) = p.source()
|
||||
{
|
||||
crate::store::clear_stored_failure(std::path::Path::new(source));
|
||||
}
|
||||
}
|
||||
// A disabled plug-in's file matched by its id is saved in the same turn.
|
||||
if load.disabled_changed() && s.store_disabled_plugins_in(turn) {
|
||||
@@ -1789,12 +2018,206 @@ fn shown_report(mut report: Value) -> Value {
|
||||
report
|
||||
}
|
||||
|
||||
fn list(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r, _, _)| shown_report(r.clone()));
|
||||
let disabled: Vec<Value> = safe_mode::disabled().iter().map(shown_item).collect();
|
||||
Ok(
|
||||
json!({"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::<Vec<_>>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}),
|
||||
)
|
||||
let failed: Vec<Value> = failed_loads(s).iter().map(shown_failure).collect();
|
||||
Ok(json!({
|
||||
"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::<Vec<_>>(),
|
||||
"folder": folder,
|
||||
"failed": failed,
|
||||
"safeMode": safe_mode::active(),
|
||||
"disabled": disabled,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Where a plug-in that didn't load was loaded from.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum LoadedFrom {
|
||||
/// The session's plug-in store.
|
||||
Store,
|
||||
/// The Additional Plug-ins Folder, or the folder `plugin.reload` loaded last.
|
||||
Folder,
|
||||
}
|
||||
|
||||
impl LoadedFrom {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
LoadedFrom::Store => "store",
|
||||
LoadedFrom::Folder => "folder",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A plug-in file that didn't load in this process: the file, why, and where it was loaded from.
|
||||
type FailedLoad = (String, String, LoadedFrom);
|
||||
|
||||
/// The plug-in files that didn't load in this process and that a retry may load: those of the
|
||||
/// session's plug-in store ([`crate::store::failed_stored_plugins`]), then those of the folder last
|
||||
/// loaded ([`FOLDER`]). A disabled plug-in (it is listed in `disabled`) and one that another install
|
||||
/// or removal of its id replaced while it loaded are left out.
|
||||
fn failed_loads(s: &Session) -> Vec<FailedLoad> {
|
||||
let mut failed: Vec<FailedLoad> = s
|
||||
.plugin_dir
|
||||
.as_deref()
|
||||
.map(crate::store::failed_stored_plugins)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|(path, why)| (path.display().to_string(), why, LoadedFrom::Store))
|
||||
.collect();
|
||||
if let Some((_, _, report, _, _)) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref()
|
||||
&& let Some(rows) = report.get("failed").and_then(Value::as_array)
|
||||
{
|
||||
for row in rows {
|
||||
let (Some(file), Some(why)) = (row.get("file").and_then(Value::as_str), row.get("error").and_then(Value::as_str)) else { continue };
|
||||
// A `plugin.reload` of the plug-in store's own folder lists its stored files once, as
|
||||
// stored files.
|
||||
let stored = failed.iter().any(|(f, _, from)| *from == LoadedFrom::Store && std::path::Path::new(f) == std::path::Path::new(file));
|
||||
if why != registry::DISABLED && why != registry::SUPERSEDED && !stored {
|
||||
failed.push((file.to_string(), why.to_string(), LoadedFrom::Folder));
|
||||
}
|
||||
}
|
||||
}
|
||||
// A file turned off since it failed (`plugin.setEnabled`, listed in `disabled`) or skipped in this
|
||||
// launch, and a stored file whose plug-in id is, are left out.
|
||||
let off = safe_mode::disabled();
|
||||
let stems: std::collections::BTreeSet<String> =
|
||||
off.iter().filter_map(|i| i.id.clone()).chain(safe_mode::skipped_ids()).map(|id| crate::store::file_stem(&id)).collect();
|
||||
failed.retain(|(file, _, from)| {
|
||||
let item = safe_mode::Item::file(file.clone());
|
||||
let by_id =
|
||||
*from == LoadedFrom::Store && std::path::Path::new(file).file_stem().is_some_and(|s| stems.contains(s.to_string_lossy().as_ref()));
|
||||
!by_id && !safe_mode::skipped(&item) && !off.iter().any(|i| i.same(&item))
|
||||
});
|
||||
failed
|
||||
}
|
||||
|
||||
/// How many plug-in files didn't load in this process and may load on a retry ([`failed_loads`]):
|
||||
/// Object › Plug-ins › Plug-ins That Didn't Load… is enabled while there is one.
|
||||
pub fn failed_load_count(s: &Session) -> usize {
|
||||
failed_loads(s).len()
|
||||
}
|
||||
|
||||
/// A [`FailedLoad`] as a reply shows it: a file outside the automation read roots by its file name,
|
||||
/// in its error too.
|
||||
fn shown_failure((file, why, from): &FailedLoad) -> Value {
|
||||
json!({"file": shown_file(file), "error": shown_error(file, why), "from": from.name()})
|
||||
}
|
||||
|
||||
/// The error `why` about the plug-in file `file` as a reply shows it: the file, and then its folder,
|
||||
/// outside the automation read roots by their names, as [`shown_report`] shows a folder's errors.
|
||||
fn shown_error(file: &str, why: &str) -> String {
|
||||
let folder = std::path::Path::new(file).parent().map(|f| f.display().to_string()).filter(|f| !f.is_empty());
|
||||
let why = why.replace(file, &shown_file(file));
|
||||
match folder {
|
||||
Some(folder) => why.replace(folder.as_str(), &shown_file(&folder)),
|
||||
None => why,
|
||||
}
|
||||
}
|
||||
|
||||
/// `plugin.retry`: loads again the plug-in file `file` that didn't load (as `plugin.list`'s `failed`
|
||||
/// names it), or every one of them without `file`, each as the load it failed in loads it: a stored
|
||||
/// file as the plug-in store loads its files, and a folder file as `plugin.reload` loads the folder's
|
||||
/// → `{retried: [{file, loaded, id?, error?}]}`.
|
||||
fn retry(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "plugin.retry";
|
||||
let failed = failed_loads(s);
|
||||
let picked: Vec<FailedLoad> = match p.get("file") {
|
||||
None => failed,
|
||||
Some(v) => {
|
||||
let file =
|
||||
v.as_str().map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "`file` must be a file plugin.list's failed names"))?;
|
||||
// A file outside the automation read roots is named by its file name, when no other
|
||||
// failed file has it.
|
||||
let exact: Vec<&FailedLoad> = failed.iter().filter(|(f, _, _)| f == file).collect();
|
||||
let named: Vec<&FailedLoad> = failed.iter().filter(|(f, _, _)| shown_file(f) == file).collect();
|
||||
match (exact.as_slice(), named.as_slice()) {
|
||||
([one], _) | ([], [one]) => vec![(*one).clone()],
|
||||
_ => return Err(bad(C, format!("{file} is not a plug-in that failed to load (see plugin.list's failed)"))),
|
||||
}
|
||||
}
|
||||
};
|
||||
safe_mode::check().map_err(err)?;
|
||||
// Loads started earlier install first, so a retry's module replaces theirs.
|
||||
s.finish_plugin_loads();
|
||||
let mut retried = Vec::with_capacity(picked.len());
|
||||
for (file, _, from) in &picked {
|
||||
let outcome = match from {
|
||||
LoadedFrom::Store => retry_stored(s, file),
|
||||
LoadedFrom::Folder => retry_folder_file(s, file),
|
||||
};
|
||||
let shown = shown_file(file);
|
||||
retried.push(match outcome {
|
||||
Ok(id) => json!({"file": shown, "loaded": true, "id": id}),
|
||||
Err(why) => json!({"file": shown, "loaded": false, "error": shown_error(file, &why)}),
|
||||
});
|
||||
}
|
||||
Ok(json!({ "retried": retried }))
|
||||
}
|
||||
|
||||
/// Loads the stored plug-in `file` again → the id it installed with, or why it didn't.
|
||||
fn retry_stored(s: &mut Session, file: &str) -> std::result::Result<String, String> {
|
||||
let path = std::path::Path::new(file);
|
||||
// Under automation read roots, a file outside them is not read again, as a folder file isn't.
|
||||
crate::file_access::check_read(file)?;
|
||||
let installed = s.retry_stored_plugin(path);
|
||||
if let Some(why) = crate::store::stored_failure(path) {
|
||||
return Err(why);
|
||||
}
|
||||
match installed {
|
||||
Some(id) => {
|
||||
clear_folder_failure(path);
|
||||
Ok(id)
|
||||
}
|
||||
None if !path.is_file() => Err("the file is no longer in the plug-in store".into()),
|
||||
// Disabled, or replaced by another install of its id while it loaded.
|
||||
None => Err("it didn't install".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes `path` out of the folder report's failed files: a stored module may also have failed in
|
||||
/// a `plugin.reload` of the store's own folder.
|
||||
pub(crate) fn clear_folder_failure(path: &std::path::Path) {
|
||||
if let Some((_, _, report, _, _)) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_mut()
|
||||
&& let Some(rows) = report.get_mut("failed").and_then(Value::as_array_mut)
|
||||
{
|
||||
rows.retain(|row| row.get("file").and_then(Value::as_str).is_none_or(|f| std::path::Path::new(f) != path));
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the file `file` of the folder last loaded again, as `plugin.reload` loads each file, and
|
||||
/// updates that folder's report: the file is listed as loaded or, with the new error, as failed →
|
||||
/// the id it installed with, or why it didn't.
|
||||
fn retry_folder_file(s: &mut Session, file: &str) -> std::result::Result<String, String> {
|
||||
let path = std::path::Path::new(file);
|
||||
let folder = path.parent().map(|f| f.display().to_string()).unwrap_or_default();
|
||||
let load = start_folder_files(s, &folder, Some(path), None);
|
||||
let report = s.finish_plugin_load(PluginLoad::Folder(load));
|
||||
let loaded: Vec<Value> = report.get("loaded").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let failed: Vec<Value> = report.get("failed").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
// A retry that couldn't load the file (its folder can't be read) reports only an error and
|
||||
// leaves its row as it is.
|
||||
if report.get("failed").is_some()
|
||||
&& let Some((last, _, r, _, _)) = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_mut()
|
||||
&& std::path::Path::new(last.as_str()) == std::path::Path::new(&folder)
|
||||
{
|
||||
if let Some(rows) = r.get_mut("failed").and_then(Value::as_array_mut) {
|
||||
rows.retain(|row| row.get("file").and_then(Value::as_str) != Some(file));
|
||||
rows.extend(failed.iter().cloned());
|
||||
}
|
||||
if let Some(ids) = r.get_mut("loaded").and_then(Value::as_array_mut) {
|
||||
for id in &loaded {
|
||||
if !ids.contains(id) {
|
||||
ids.push(id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(id) = loaded.first().and_then(Value::as_str) {
|
||||
return Ok(id.to_string());
|
||||
}
|
||||
let why = failed.first().and_then(|row| row.get("error")).and_then(Value::as_str).or_else(|| report.get("error").and_then(Value::as_str));
|
||||
Err(why.unwrap_or("it didn't install").to_string())
|
||||
}
|
||||
|
||||
/// `plugin.safeMode`: whether Safe Mode is on and why, the plug-ins disabled for the next launch,
|
||||
@@ -1810,15 +2233,16 @@ fn safe_mode_state(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
/// The file of a plug-in `plugin.safeMode` lists as `file`, or `plugin.list` as `source`: one they name
|
||||
/// The file of a plug-in `plugin.safeMode` lists as `file`, or `plugin.list` as `source` or in `failed`: one they name
|
||||
/// by its file name (outside the automation read roots) is found by that name, when no other listed
|
||||
/// file has it.
|
||||
fn listed_file(file: String) -> String {
|
||||
fn listed_file(s: &Session, file: String) -> String {
|
||||
let mut listed: Vec<String> = safe_mode::disabled()
|
||||
.into_iter()
|
||||
.chain(safe_mode::previous())
|
||||
.filter_map(|i| i.file)
|
||||
.chain(registry::list().iter().filter_map(|p| p.source().map(str::to_string)))
|
||||
.chain(failed_loads(s).into_iter().map(|(f, _, _)| f))
|
||||
.collect();
|
||||
listed.sort();
|
||||
listed.dedup();
|
||||
@@ -1853,7 +2277,7 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let stored = if enabled { s.stored_plugin_file(&id).map(safe_mode::Item::file) } else { None };
|
||||
(registry::get(&id).map(|p| safe_mode::Item::of(&p)).unwrap_or(safe_mode::Item { id: Some(id), ..Default::default() }), stored)
|
||||
}
|
||||
(None, Some(file)) => (safe_mode::Item::file(listed_file(file)), None),
|
||||
(None, Some(file)) => (safe_mode::Item::file(listed_file(s, file)), None),
|
||||
(None, None) => return Err(bad(C, "give `id` or `file` (see plugin.safeMode)")),
|
||||
};
|
||||
let items: Vec<&safe_mode::Item> = std::iter::once(&item).chain(stored.as_ref()).collect();
|
||||
@@ -1970,7 +2394,7 @@ fn clear_cache(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// This module's commands: `plugin.list`, `.info`, `.run`, `.install`, `.inspect`, `.remove`,
|
||||
/// `.reload`, `.clearCache`, `.safeMode` and `.setEnabled`.
|
||||
/// `.reload`, `.retry`, `.clearCache`, `.safeMode` and `.setEnabled`.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -1978,7 +2402,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -2045,6 +2469,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
reload
|
||||
),
|
||||
cmd!(
|
||||
query "plugin.retry",
|
||||
"Retry Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{file?: a file plugin.list's failed names (under automation read roots, a file outside them by the file name shown, when no other failed file has it)} load again the plug-in file that didn't load, or every file plugin.list's failed names when file is left out (desktop; a stored file loads as the plug-in store loads its files, and a folder file as plugin.reload loads the folder's, with the same checks; under automation read roots, a file outside them is not read and reports why; a folder file's row in plugin.list's folder report changes to loaded or to its new error; an error in Safe Mode, or when file isn't one that failed) → {retried: [{file, loaded: bool, id? (the plug-in it installed), error? (why it didn't load again)}]}",
|
||||
always,
|
||||
retry
|
||||
),
|
||||
cmd!(
|
||||
query "plugin.safeMode",
|
||||
"Safe Mode",
|
||||
@@ -2059,7 +2492,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Enable on Re-launch",
|
||||
[],
|
||||
None,
|
||||
"{id | file: a plug-in as plugin.safeMode's disabled lists it or as plugin.list's source (under automation read roots, a file outside them by the file name shown, when no other listed file has it), enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}",
|
||||
"{id | file: a plug-in as plugin.safeMode's disabled lists it or as plugin.list's source or failed names it (under automation read roots, a file outside them by the file name shown, when no other listed file has it), enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}",
|
||||
always,
|
||||
set_enabled
|
||||
),
|
||||
|
||||
@@ -424,7 +424,7 @@ impl Calls {
|
||||
|
||||
/// Is `s` still as the run needs it: the same documents open, the same one active and the
|
||||
/// interaction holding the run's changes still open?
|
||||
fn kept(&self, s: &Session) -> bool {
|
||||
pub(crate) fn kept(&self, s: &Session) -> bool {
|
||||
s.active().map(|d| d.uid) == self.document
|
||||
&& s.docs.iter().map(|d| d.uid).eq(self.open.iter().copied())
|
||||
&& (!self.interaction || s.in_interaction())
|
||||
@@ -476,44 +476,77 @@ fn execute_confined(s: &mut Session, id: &str, args: &Value) -> Result<Value> {
|
||||
/// changes. A trace handed in for the next Image Trace is set aside while `f` runs, so a call
|
||||
/// traces anew, and handed back after; the next Image Trace still checks it was made of its inputs.
|
||||
pub(crate) fn transaction(s: &mut Session, label: &str, f: impl FnOnce(&mut Session) -> Result<Value>) -> Result<Value> {
|
||||
if s.active().is_some() && !s.previewing {
|
||||
super::edit::settle_interaction(s)?;
|
||||
}
|
||||
let own = s.active().is_some() && !s.previewing && !s.in_interaction();
|
||||
if own {
|
||||
s.begin_interaction(label)?;
|
||||
}
|
||||
let saved = Saved::of(s);
|
||||
let start = s.docs.clone();
|
||||
let active = s.active;
|
||||
let trace = s.trace_hand_off.take();
|
||||
let t = Transaction::begin(s, label)?;
|
||||
let r = f(s);
|
||||
s.trace_hand_off = trace;
|
||||
match r {
|
||||
Ok(v) => {
|
||||
if own
|
||||
&& let Some(st) = s.active_mut()
|
||||
&& let Some(it) = st.interaction.take()
|
||||
{
|
||||
st.keep_interaction(it);
|
||||
}
|
||||
Ok(v)
|
||||
t.end(s, r)
|
||||
}
|
||||
|
||||
/// A [`transaction`] that stays open between calls: [`Transaction::begin`] starts it, and
|
||||
/// [`Transaction::end`] keeps or undoes what was done meanwhile. A run of a plug-in that calls
|
||||
/// commands from the web build's plug-in worker holds one while it waits for the worker.
|
||||
pub(crate) struct Transaction {
|
||||
own: bool,
|
||||
saved: Saved,
|
||||
start: Vec<crate::DocState>,
|
||||
active: Option<usize>,
|
||||
trace: Option<super::Traced>,
|
||||
}
|
||||
|
||||
impl Transaction {
|
||||
/// Starts one undo step named `label` in the active document, as [`transaction`] does before it
|
||||
/// runs its function.
|
||||
pub(crate) fn begin(s: &mut Session, label: &str) -> Result<Transaction> {
|
||||
if s.active().is_some() && !s.previewing {
|
||||
super::edit::settle_interaction(s)?;
|
||||
}
|
||||
Err(e) => {
|
||||
let open = std::mem::replace(&mut s.docs, start);
|
||||
for st in &mut s.docs {
|
||||
// Past the newest revision the document reached, so the restored one redraws.
|
||||
let newest = open.iter().filter(|d| d.uid == st.uid).map(|d| d.revision).max().unwrap_or(st.revision);
|
||||
st.revision = newest.max(st.revision).saturating_add(1);
|
||||
crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection);
|
||||
let own = s.active().is_some() && !s.previewing && !s.in_interaction();
|
||||
if own {
|
||||
s.begin_interaction(label)?;
|
||||
}
|
||||
let saved = Saved::of(s);
|
||||
let start = s.docs.clone();
|
||||
let active = s.active;
|
||||
let trace = s.trace_hand_off.take();
|
||||
Ok(Transaction { own, saved, start, active, trace })
|
||||
}
|
||||
|
||||
/// Ends it with `r`, what was done in it: kept as one undo step when it succeeded, else every
|
||||
/// document and the session state go back to how they were when it began → `r`.
|
||||
pub(crate) fn end(self, s: &mut Session, r: Result<Value>) -> Result<Value> {
|
||||
let Transaction { own, saved, start, active, trace } = self;
|
||||
s.trace_hand_off = trace;
|
||||
match r {
|
||||
Ok(v) => {
|
||||
if own
|
||||
&& let Some(st) = s.active_mut()
|
||||
&& let Some(it) = st.interaction.take()
|
||||
{
|
||||
st.keep_interaction(it);
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
s.active = active;
|
||||
if own && let Some(st) = s.active_mut() {
|
||||
st.interaction = None;
|
||||
Err(e) => {
|
||||
let open = std::mem::replace(&mut s.docs, start);
|
||||
for st in &mut s.docs {
|
||||
// Past the newest revision the document reached, so the restored one redraws. A
|
||||
// document the transaction left as it was keeps its revision, so a run made
|
||||
// away from the session on it still applies.
|
||||
let reached: Vec<_> = open.iter().filter(|d| d.uid == st.uid).collect();
|
||||
let unchanged = !reached.is_empty() && reached.iter().all(|d| d.revision == st.revision && d.selection == st.selection);
|
||||
if !unchanged {
|
||||
let newest = reached.iter().map(|d| d.revision).max().unwrap_or(st.revision);
|
||||
st.revision = newest.max(st.revision).saturating_add(1);
|
||||
}
|
||||
crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection);
|
||||
}
|
||||
s.active = active;
|
||||
if own && let Some(st) = s.active_mut() {
|
||||
st.interaction = None;
|
||||
}
|
||||
saved.restore(s);
|
||||
s.sync_front_profiles();
|
||||
Err(e)
|
||||
}
|
||||
saved.restore(s);
|
||||
s.sync_front_profiles();
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -489,6 +489,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"pattern.delete",
|
||||
"pattern.list",
|
||||
"pattern.options",
|
||||
"pattern.placeArt",
|
||||
"pattern.transform",
|
||||
"perspective.attach",
|
||||
"perspective.draw",
|
||||
@@ -736,6 +737,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"variable.makeTextDynamic",
|
||||
"variable.makeVisibilityDynamic",
|
||||
"variable.rename",
|
||||
"variable.setBinding",
|
||||
"variable.sort",
|
||||
"variable.unbind",
|
||||
];
|
||||
|
||||
@@ -409,7 +409,7 @@ impl FolderStore {
|
||||
/// names that file.
|
||||
pub(crate) fn take(file: std::fs::File, path: &std::path::Path) -> std::result::Result<Lock, String> {
|
||||
match file.try_lock() {
|
||||
Ok(()) if Self::still_named(&file, path) => Ok(Lock::Held(Box::new(file))),
|
||||
Ok(()) if Self::still_named(&file, path) => Ok(Lock::Held(Box::new(crate::store::LockedFile::new(file)))),
|
||||
Ok(()) | Err(std::fs::TryLockError::WouldBlock) => Ok(Lock::Busy),
|
||||
// The lock file was removed meanwhile, and locking it failed instead.
|
||||
Err(std::fs::TryLockError::Error(_)) if !Self::still_named(&file, path) => Ok(Lock::Busy),
|
||||
@@ -498,7 +498,9 @@ impl RecoveryStore for FolderStore {
|
||||
Self::lock_area(&dir)
|
||||
}
|
||||
fn still_held(&self, area: &str, hold: &(dyn std::any::Any + Send + Sync)) -> bool {
|
||||
let (Some(file), Ok(dir)) = (hold.downcast_ref::<std::fs::File>(), self.area(area)) else { return true };
|
||||
let (Some(file), Ok(dir)) = (hold.downcast_ref::<crate::store::LockedFile>().map(crate::store::LockedFile::file), self.area(area)) else {
|
||||
return true;
|
||||
};
|
||||
let path = dir.join(LOCK_FILE);
|
||||
// Only a lock file or folder that is gone, or another one in its place, ends the hold. One
|
||||
// that can't be read now (a network folder that doesn't answer) still counts as held.
|
||||
|
||||
@@ -294,7 +294,7 @@ impl Line {
|
||||
let mut origins = |text: String| -> Vec<Point> {
|
||||
bare.text = text;
|
||||
let t = bare.probe(system_layout);
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
let lay = lay_out(&t);
|
||||
lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * Point::ORIGIN)).collect()
|
||||
};
|
||||
let joined = origins(ms.iter().map(|m| m.ch).collect());
|
||||
@@ -534,7 +534,7 @@ impl Line {
|
||||
let mut origins = |text: String| -> Vec<Point> {
|
||||
bare.text = text;
|
||||
let t = bare.probe(system_layout);
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
let lay = lay_out(&t);
|
||||
lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * Point::ORIGIN)).collect()
|
||||
};
|
||||
// With no spaces.
|
||||
@@ -723,7 +723,7 @@ fn round_tracking(t: f64) -> f64 {
|
||||
/// glyph (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing,
|
||||
/// more space than whole spaces make); `None` when the type draws every glyph in its place.
|
||||
fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64, slack: f64) -> Option<usize> {
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), t);
|
||||
let lay = lay_out(t);
|
||||
let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty());
|
||||
// With a tolerance, a near-matched glyph, or any glyph of a line whose first glyph is one,
|
||||
// may sit that much further (as a fraction of the size) from where the type draws it.
|
||||
@@ -998,6 +998,20 @@ fn max_wrap_work() -> usize {
|
||||
WRAP_LIMIT.with(|c| c.get())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The glyphs [`lay_out`] laid out on this thread.
|
||||
static GLYPHS_LAID_OUT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Type `t` laid out, for a check of where it draws its glyphs.
|
||||
fn lay_out(t: &TextObject) -> vectorcraft_text::TextLayout {
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), t);
|
||||
#[cfg(test)]
|
||||
GLYPHS_LAID_OUT.with(|n| n.set(n.get().saturating_add(lay.glyphs.len())));
|
||||
lay
|
||||
}
|
||||
|
||||
/// Lines farther apart than this many times their size do not join into one object.
|
||||
const MAX_LEADING: f64 = 3.0;
|
||||
|
||||
@@ -1159,7 +1173,7 @@ impl Block {
|
||||
let matches: Vec<GlyphMatch> = self.lines.iter().flat_map(|l| l.matches.iter().cloned()).collect();
|
||||
// Aligned at its end or center, point type starts its first line elsewhere: the type moves
|
||||
// so its first glyph is where the first outline is.
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
let lay = lay_out(&t);
|
||||
if let (Some(g), Some(m)) = (lay.glyphs.iter().find(|g| !g.outline.elements().is_empty()), matches.first()) {
|
||||
let at = t.xf * (g.xf * Point::ORIGIN);
|
||||
t.xf = kurbo::Affine::translate(m.origin - at) * t.xf;
|
||||
|
||||
@@ -692,21 +692,28 @@ fn timing_with_hundreds_of_cjk_outlines() {
|
||||
#[test]
|
||||
fn a_long_tracked_line_is_checked_in_time() {
|
||||
// Even tracking is kept on the line; the layout check of a long line must not lay out the rest
|
||||
// of the line again after each window.
|
||||
let text = "abe".repeat(150);
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": text.len(), "tracking": 50})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
let t0 = std::time::Instant::now();
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts, vec![text], "the whole line is one object: {r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}");
|
||||
assert_eq!(r["unmatched"], json!([]));
|
||||
eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len());
|
||||
// of the line again after each window: a line ten times as long lays out no more than twice as
|
||||
// many glyphs per glyph.
|
||||
let laid_out = |text: &str| {
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": text.len(), "tracking": 50})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [g]})).unwrap();
|
||||
super::GLYPHS_LAID_OUT.set(0);
|
||||
let r = s.execute("type.retype", &json!({})).unwrap();
|
||||
let laid = super::GLYPHS_LAID_OUT.get();
|
||||
let texts: Vec<String> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(texts, vec![text], "the whole line is one object: {r}");
|
||||
assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}");
|
||||
assert_eq!(r["unmatched"], json!([]));
|
||||
laid
|
||||
};
|
||||
let short = laid_out(&"abe".repeat(15));
|
||||
let long = laid_out(&"abe".repeat(150));
|
||||
assert!(short > 0, "the line is laid out to be checked");
|
||||
assert!(long <= 20 * short, "450 glyphs: {long} laid out; 45 glyphs: {short}");
|
||||
}
|
||||
|
||||
/// Every path in the document flattened into lines `tol` from its curves, each contour started at
|
||||
|
||||
@@ -295,6 +295,18 @@ impl Session {
|
||||
self.script_data_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
|
||||
}
|
||||
|
||||
/// Have listings of the Scripts and Startup Scripts folders measure their time with `clock`
|
||||
/// instead of the real time ([`script::folder::Clock::Wall`], the default).
|
||||
pub fn set_script_listing_clock(&mut self, clock: script::folder::Clock) {
|
||||
self.script_listing_clock = clock;
|
||||
}
|
||||
|
||||
/// How listings of the Scripts and Startup Scripts folders measure their time
|
||||
/// ([`Session::set_script_listing_clock`]).
|
||||
pub fn script_listing_clock(&self) -> script::folder::Clock {
|
||||
self.script_listing_clock
|
||||
}
|
||||
|
||||
/// The Scripts folder ([`Session::attach_scripts_dir`]); none on the web, which has no folders.
|
||||
pub fn scripts_dir(&self) -> Option<&std::path::Path> {
|
||||
self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
|
||||
@@ -581,7 +593,7 @@ fn startup_run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let folder = root.to_string_lossy().into_owned();
|
||||
// The folder is the app's: a refusal names it as the request may see it.
|
||||
crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?;
|
||||
let listing = script::startup::list(&root);
|
||||
let listing = script::startup::list(&root, s.script_listing_clock);
|
||||
let name_of = |path: &std::path::Path| path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let (disabled, scripts): (Vec<_>, Vec<_>) =
|
||||
listing.scripts.into_iter().partition(|path| vectorcraft_plugins::safe_mode::skipped(&startup_item(path)));
|
||||
@@ -647,7 +659,7 @@ fn list_installed(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let folder = root.to_string_lossy();
|
||||
// The Scripts folder is the app's: a refusal names it as the request may see it.
|
||||
crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?;
|
||||
let listing = script::folder::list(root);
|
||||
let listing = script::folder::list(root, s.script_listing_clock);
|
||||
let scripts: Vec<Value> = listing
|
||||
.scripts()
|
||||
.into_iter()
|
||||
|
||||
@@ -189,6 +189,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The selected slices, including selected objects that are object slices.
|
||||
pub fn selected_slice_ids(&self) -> Vec<NodeId> {
|
||||
self.active().map_or_else(Vec::new, |st| selected_slices(&st.doc, &st.selection))
|
||||
}
|
||||
|
||||
/// View → Hide Slices.
|
||||
pub fn slices_hidden(&self) -> bool {
|
||||
self.menu.slices_hidden
|
||||
|
||||
Loaded 100 of 545 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user