mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge main into fix/properties-profile-build
This commit is contained in:
commit
b2f3c35e66
642 files changed
+48877
-4601
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
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Notify Services on Release Change
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
- unpublished
|
||||
- created
|
||||
- edited
|
||||
- deleted
|
||||
- prereleased
|
||||
- released
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
|
||||
secrets:
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
Generated
+210
-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",
|
||||
@@ -8670,6 +8773,7 @@ name = "vectorcraft-js"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-xml",
|
||||
"getrandom 0.4.3",
|
||||
"proptest",
|
||||
"unicode-properties",
|
||||
@@ -8748,7 +8852,7 @@ dependencies = [
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
"jpeg-encoder 0.6.1",
|
||||
"krilla",
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
@@ -8805,7 +8909,7 @@ dependencies = [
|
||||
"craft-tiff",
|
||||
"flate2",
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
"jpeg-encoder 0.6.1",
|
||||
"log",
|
||||
"proptest",
|
||||
"serde_json",
|
||||
@@ -9174,9 +9278,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",
|
||||
@@ -9187,27 +9291,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",
|
||||
]
|
||||
@@ -10577,14 +10681,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" }
|
||||
@@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged.
|
||||
|
||||
- 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
|
||||
- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
@@ -255,6 +257,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. |
|
||||
| 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (checking #937's fix on the reporter's file, still unconfirmed). Headline numbers unchanged. |
|
||||
| 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). |
|
||||
| 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. |
|
||||
|
||||
@@ -27,7 +27,7 @@ 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 }
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -57,6 +57,37 @@ impl Document {
|
||||
pick(&|r| r.contains(p)).or_else(|| pick(&|r| artboard_holds(r, p)))
|
||||
}
|
||||
|
||||
/// Which artboard in the document owns object bounds `b`: the artboard that holds its center,
|
||||
/// or the one it has the greatest overlap area with if its center lies outside all artboards.
|
||||
/// Bounds with no width or no height (a straight horizontal or vertical line) have no area, so
|
||||
/// for them the overlap is the length of the line on the artboard.
|
||||
pub fn artboard_for_bounds(&self, b: Rect) -> Option<usize> {
|
||||
let c = b.center();
|
||||
if let Some(i) = self.artboard_holding(c, false) {
|
||||
return Some(i);
|
||||
}
|
||||
let (flat_x, flat_y) = (b.x1 - b.x0 <= 1e-9, b.y1 - b.y0 <= 1e-9);
|
||||
let mut best: Option<(usize, f64)> = None;
|
||||
for (i, a) in self.artboards.iter().enumerate() {
|
||||
let r = a.rect;
|
||||
let w = b.x1.min(r.x1) - b.x0.max(r.x0);
|
||||
let h = b.y1.min(r.y1) - b.y0.max(r.y0);
|
||||
if w < 0.0 || h < 0.0 {
|
||||
continue;
|
||||
}
|
||||
let overlap = match (flat_x, flat_y) {
|
||||
(true, true) => 0.0,
|
||||
(true, false) => h,
|
||||
(false, true) => w,
|
||||
(false, false) => w * h,
|
||||
};
|
||||
if overlap > 1e-9 && best.is_none_or(|(_, max)| overlap > max + 1e-9) {
|
||||
best = Some((i, overlap));
|
||||
}
|
||||
}
|
||||
best.map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// The art that moves with an artboard at `rect`: top-level objects (children of layers and
|
||||
/// sublayers) lying entirely inside it, with symbol instances measured by their art. Locked and
|
||||
/// hidden objects and layers stay put unless `locked_and_hidden` (Selection & Anchor Display ›
|
||||
@@ -89,6 +120,54 @@ impl Document {
|
||||
art
|
||||
}
|
||||
|
||||
/// The art that is copied when artboard `index` is duplicated or copied: objects wholly inside
|
||||
/// the artboard (with rounding tolerance), objects within its bleed rectangle, and artwork
|
||||
/// placed on/overlapping this artboard that belongs to it by center or primary overlap
|
||||
/// ([`Document::artboard_for_bounds`]).
|
||||
pub fn art_for_artboard_copy(&self, index: usize, locked_and_hidden: bool) -> Vec<NodeId> {
|
||||
let Some(rect) = self.artboards.get(index).map(|a| a.rect) else { return vec![] };
|
||||
let r = rect.inflate(1e-6, 1e-6);
|
||||
let on_copy = |b: Rect| -> bool {
|
||||
// 1. Wholly inside the artboard (edges included, with tolerance).
|
||||
if b.x0 >= r.x0 && b.y0 >= r.y0 && b.x1 <= r.x1 && b.y1 <= r.y1 {
|
||||
return true;
|
||||
}
|
||||
// 2. Within the artboard's bleed rectangle (if document setup specifies bleed).
|
||||
if self.setup.has_bleed() {
|
||||
let br = self.setup.bleed_rect(rect).inflate(1e-6, 1e-6);
|
||||
if b.x0 >= br.x0 && b.y0 >= br.y0 && b.x1 <= br.x1 && b.y1 <= br.y1 {
|
||||
return self.artboard_for_bounds(b).is_none_or(|owner| owner == index);
|
||||
}
|
||||
}
|
||||
// 3. Artwork that intersects this artboard and belongs to it (#4479).
|
||||
let inter_x0 = b.x0.max(r.x0);
|
||||
let inter_y0 = b.y0.max(r.y0);
|
||||
let inter_x1 = b.x1.min(r.x1);
|
||||
let inter_y1 = b.y1.min(r.y1);
|
||||
if inter_x1 < inter_x0 || inter_y1 < inter_y0 {
|
||||
return false;
|
||||
}
|
||||
self.artboard_for_bounds(b) == Some(index)
|
||||
};
|
||||
fn collect(n: &Node, s: &SymbolBoxes, on: &dyn Fn(Rect) -> bool, all: bool, out: &mut Vec<NodeId>) {
|
||||
for c in n.children().into_iter().flatten().filter(|c| c.rides_with_artboard(all)) {
|
||||
if c.is_layer() {
|
||||
collect(c, s, on, all, out);
|
||||
} else if let Some(b) = c.geometric_bounds_with(s)
|
||||
&& on(b)
|
||||
{
|
||||
out.push(c.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let symbols = self.symbol_boxes();
|
||||
let mut art = vec![];
|
||||
for l in self.layers.iter().filter(|l| l.rides_with_artboard(locked_and_hidden)) {
|
||||
collect(l, &symbols, &on_copy, locked_and_hidden, &mut art);
|
||||
}
|
||||
art
|
||||
}
|
||||
|
||||
/// Does any artwork lie on `rect` (an artboard)? Artwork is any object under the layers,
|
||||
/// hidden and locked ones and those on template layers included, whose visual bounds (symbol
|
||||
/// instances measured by their art) meet `rect`; touching its edge counts. A group (not a clip
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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 => {}
|
||||
|
||||
@@ -435,6 +435,142 @@ fn art_on_artboard_tolerates_roundoff_at_each_edge() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_for_artboard_copy_takes_artwork_larger_than_artboard_or_with_bleed() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
d.setup.bleed = [9.0; 4];
|
||||
let layer = d.layers[0].id;
|
||||
// An oversized background (250x250 centered on the 200x200 artboard, #4479).
|
||||
let bg = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(bg, shapes::rectangle(Rect::new(-25.0, -25.0, 225.0, 225.0)), Appearance::default_art())).unwrap();
|
||||
// A shape with 5pt bleed over the top-right corner.
|
||||
let bleed = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(bleed, shapes::rectangle(Rect::new(150.0, -5.0, 205.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
// A shape lying entirely in the bleed margin without touching the artboard itself (-8..-2 vs 0..200).
|
||||
let bleed_margin_only = d.alloc_id();
|
||||
d.insert(
|
||||
Some(layer),
|
||||
usize::MAX,
|
||||
Node::path(bleed_margin_only, shapes::rectangle(Rect::new(-8.0, 50.0, -2.0, 100.0)), Appearance::default_art()),
|
||||
)
|
||||
.unwrap();
|
||||
// A small shape hanging 20pt over the left edge (center outside, more than bleed).
|
||||
let hanging = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(hanging, shapes::rectangle(Rect::new(-20.0, 90.0, 10.0, 120.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
// A straight line hanging 60pt over the left edge (center outside, no area): it lies on the
|
||||
// artboard for 40pt, so it is copied as a thin rectangle there would be.
|
||||
let line = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(line, shapes::line(Point::new(-60.0, 150.0), Point::new(40.0, 150.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
// A shape completely outside the artboard.
|
||||
let outside = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(outside, shapes::rectangle(Rect::new(300.0, 300.0, 400.0, 400.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
|
||||
// Standard art_on_artboard keeps strict containment: none of the overhanging shapes are on it.
|
||||
let strict_art = d.art_on_artboard(Rect::new(0.0, 0.0, 200.0, 200.0), false);
|
||||
assert!(!strict_art.contains(&bg), "strict art_on_artboard excludes oversized background");
|
||||
assert!(!strict_art.contains(&bleed), "strict art_on_artboard excludes bleed shape");
|
||||
assert!(!strict_art.contains(&bleed_margin_only), "strict art_on_artboard excludes bleed-margin-only shape");
|
||||
assert!(!strict_art.contains(&hanging), "strict art_on_artboard excludes hanging shape");
|
||||
assert!(!strict_art.contains(&outside), "strict art_on_artboard excludes outside shape");
|
||||
|
||||
// Copying the artboard takes the artwork touching this artboard that belongs to it, or within bleed.
|
||||
let copy_art = d.art_for_artboard_copy(0, false);
|
||||
assert!(copy_art.contains(&bg), "oversized background is copied with artboard: {copy_art:?}");
|
||||
assert!(copy_art.contains(&bleed), "bleed shape is copied with artboard: {copy_art:?}");
|
||||
assert!(copy_art.contains(&bleed_margin_only), "bleed-margin-only shape is copied with artboard: {copy_art:?}");
|
||||
assert!(copy_art.contains(&hanging), "touching shape owned by artboard 0 is copied: {copy_art:?}");
|
||||
assert!(copy_art.contains(&line), "a line hanging over the edge is copied: {copy_art:?}");
|
||||
assert!(!copy_art.contains(&outside), "outside shape is not copied: {copy_art:?}");
|
||||
|
||||
// If Artboard 1 is added next to Artboard 0, art primarily on Artboard 1 is not copied with Artboard 0:
|
||||
d.artboards.push(Artboard {
|
||||
id: 2,
|
||||
name: "Artboard 2".into(),
|
||||
rect: Rect::new(200.0, 0.0, 400.0, 200.0),
|
||||
locked: false,
|
||||
show_center_mark: false,
|
||||
show_cross_hairs: false,
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
guide_label: None,
|
||||
});
|
||||
// Shape spanning (190..300) x (50..150): 10pt on Artboard 0, 100pt on Artboard 1.
|
||||
let neighbor_art = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(neighbor_art, shapes::rectangle(Rect::new(190.0, 50.0, 300.0, 150.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
|
||||
let copy_art0 = d.art_for_artboard_copy(0, false);
|
||||
assert!(!copy_art0.contains(&neighbor_art), "art owned by neighboring Artboard 1 is not copied with Artboard 0");
|
||||
let copy_art1 = d.art_for_artboard_copy(1, false);
|
||||
assert!(copy_art1.contains(&neighbor_art), "art owned by Artboard 1 is copied with Artboard 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artboard_for_bounds_edge_cases_and_tie_breaks() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
// Artboard 0: (0, 0, 100, 100)
|
||||
// Artboard 1: (200, 0, 300, 100)
|
||||
d.artboards.push(Artboard {
|
||||
id: 2,
|
||||
name: "Artboard 2".into(),
|
||||
rect: Rect::new(200.0, 0.0, 300.0, 100.0),
|
||||
locked: false,
|
||||
show_center_mark: false,
|
||||
show_cross_hairs: false,
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
guide_label: None,
|
||||
});
|
||||
|
||||
// 1. Artwork whose center is outside all boards, but overlaps Artboard 0 most:
|
||||
// Bounds: (50, -100, 150, 50) -> Center: (100, -25) which is outside all artboards.
|
||||
// Overlap with Board 0: 50x50 = 2500; Board 1: 0.
|
||||
let b_center_outside = Rect::new(50.0, -100.0, 150.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_center_outside), Some(0));
|
||||
|
||||
// 2. Equal overlap on two boards (defined tie-break: the lower index, board 0):
|
||||
// Bounds: (50, -50, 250, 50) -> Center: (150, 0) outside all boards.
|
||||
// Overlap with Board 0: (50..100) x (0..50) = 2500; Board 1: (200..250) x (0..50) = 2500.
|
||||
let b_equal_overlap = Rect::new(50.0, -50.0, 250.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_equal_overlap), Some(0), "equal overlap picks lower index");
|
||||
|
||||
// 3. No overlap at all: returns None.
|
||||
let b_no_overlap = Rect::new(500.0, 500.0, 600.0, 600.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_no_overlap), None);
|
||||
|
||||
// 4. Rotated object bounds (bounds, not the inner geometry):
|
||||
// A 40x40 square rotated 45 deg centered at (50, 50) has bounding box ~56.57x56.57.
|
||||
let b_rotated_bounds = Rect::new(50.0 - 28.28, 50.0 - 28.28, 50.0 + 28.28, 50.0 + 28.28);
|
||||
assert_eq!(d.artboard_for_bounds(b_rotated_bounds), Some(0));
|
||||
|
||||
// 5. Zero-size bounds (a point):
|
||||
// On board 0:
|
||||
let b_zero_on_board = Rect::new(50.0, 50.0, 50.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_zero_on_board), Some(0));
|
||||
// Outside all boards:
|
||||
let b_zero_outside = Rect::new(150.0, 50.0, 150.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_zero_outside), None);
|
||||
|
||||
// 6. Straight lines whose center is outside every board: owned by the board they lie on most,
|
||||
// as a rectangle of any thickness would be (they have no area to compare).
|
||||
// Horizontal, from x = -100 to 50 on board 0: center (-25, 50).
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.0)), Some(0));
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.1)), Some(0), "the same as a thin rectangle");
|
||||
// Vertical, from y = -100 to 50 on board 1: center (250, -25).
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(250.0, -100.0, 250.0, 50.0)), Some(1));
|
||||
// Below both boards.
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 120.0, 260.0, 120.0)), None);
|
||||
// Across the gap between the boards, 20 pt on board 0 and 60 on board 1.
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 50.0, 260.0, 50.0)), Some(1), "center (170, 50) in the gap: board 1 holds more of it");
|
||||
// Only touching a board's corner from outside: no overlap.
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 0.0, 0.0, 0.0)), None);
|
||||
}
|
||||
|
||||
/// The art on a locked artboard (each object of a layer whose bounds overlap it, a group as one
|
||||
/// object) can't be edited, and Select All, a click and a marquee pass over it; art flush with
|
||||
/// the artboard from outside isn't on it, a layer is on no artboard, and new art isn't on one.
|
||||
|
||||
@@ -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`,
|
||||
@@ -196,6 +209,15 @@ impl Unit {
|
||||
}
|
||||
parse_measure(×_as_asterisks(s), self).filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// Parse a measurement with decimal points or commas and no input locale. Refuse a
|
||||
/// number that looks like a grouped integer, even when it is part of an expression.
|
||||
pub fn parse_with_decimal_comma(self, text: &str) -> Option<f64> {
|
||||
if text.contains(',') && times_as_asterisks(text).split(['+', '-', '*', '/']).any(thousands_operand) {
|
||||
return None;
|
||||
}
|
||||
self.parse(&decimal_point(text))
|
||||
}
|
||||
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
|
||||
/// `feetInches`).
|
||||
pub const fn key(self) -> &'static str {
|
||||
@@ -397,6 +419,19 @@ pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() }
|
||||
}
|
||||
|
||||
/// Does the operand contain a thousands comma? Check both parts of a compact pica value and
|
||||
/// read a percentage's number without its percent sign.
|
||||
fn thousands_operand(operand: &str) -> bool {
|
||||
let operand = operand.trim();
|
||||
if let Some((picas, points)) = operand.split_once('p')
|
||||
&& !points.trim().is_empty()
|
||||
&& points.trim().bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b','))
|
||||
{
|
||||
return thousands(picas) || thousands(points);
|
||||
}
|
||||
thousands(operand.strip_suffix('%').unwrap_or(operand))
|
||||
}
|
||||
|
||||
/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or
|
||||
/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at
|
||||
/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.")
|
||||
@@ -472,6 +478,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 };
|
||||
|
||||
@@ -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()]));
|
||||
|
||||
@@ -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()
|
||||
};
|
||||
@@ -2691,7 +2691,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>| {
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
@@ -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"] }
|
||||
|
||||
@@ -97,6 +97,7 @@ mod style;
|
||||
pub use style::styled_node;
|
||||
pub mod stylelib;
|
||||
mod svgfilter;
|
||||
pub use svgfilter::MAX_IMPORT_BYTES as MAX_SVG_FILTER_IMPORT_BYTES;
|
||||
mod swatch;
|
||||
pub mod swatchlib;
|
||||
pub(crate) mod symboledit;
|
||||
@@ -963,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};
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once.
|
||||
//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and
|
||||
//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type
|
||||
//! `addon.units.convert` reads a length with units and arithmetic ([`Unit::parse`]) and gives
|
||||
//! it in each unit of Preferences › Units › East Asian Type
|
||||
//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]).
|
||||
//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform
|
||||
//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the
|
||||
@@ -10,7 +10,7 @@
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, finite_in_every_unit};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::{CommandSpec, always, bad, cmd, has_selection};
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert Units",
|
||||
[],
|
||||
None,
|
||||
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
"{value: a length (a number, or text with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point in \"0,5 mm\", but a thousands-shaped number is refused even in arithmetic, as in \"1,500+2\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
always,
|
||||
convert
|
||||
),
|
||||
@@ -76,7 +76,7 @@ fn convert(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(CONVERT, "missing `value`"));
|
||||
};
|
||||
let pt = match v {
|
||||
Value::String(s) if readable(s) => unit.parse(&decimal_point(s)),
|
||||
Value::String(s) if readable(s) => unit.parse_with_decimal_comma(s),
|
||||
Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
@@ -50,7 +50,7 @@ fn a_length_comes_back_in_every_unit_in_order() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_read_as_number_fields_read_them() {
|
||||
fn values_accept_units_arithmetic_and_decimal_commas() {
|
||||
let mut s = session();
|
||||
let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap();
|
||||
assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0));
|
||||
@@ -72,8 +72,9 @@ fn values_read_as_number_fields_read_them() {
|
||||
assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0));
|
||||
// Each number of a sum reads its own separator.
|
||||
assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4));
|
||||
// A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5.
|
||||
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
|
||||
assert!(near(pt(&mut s, json!({"value": "2x0,125 px"})), 0.25));
|
||||
assert!(near(pt(&mut s, json!({"value": "0,125p6+2"})), 9.5));
|
||||
assert!(near(pt(&mut s, json!({"value": "2p0,5+1"})), 25.5));
|
||||
// A sum of 128 signs still reads.
|
||||
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
|
||||
// x, X and × multiply as * does, and each counts toward the 128 signs.
|
||||
@@ -84,6 +85,15 @@ fn values_read_as_number_fields_read_them() {
|
||||
assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thousands_comma_in_an_arithmetic_operand_is_refused() {
|
||||
let mut s = session();
|
||||
for value in ["1,500+2", "1,000 px+2", "2+-1,000", "2/1,000", "2×1,000 in", "1,000'X2", "5pt+1,000%", "1,000p6+2", "2p1,000+2"] {
|
||||
let result = s.execute("addon.units.convert", &json!({"value": value}));
|
||||
assert!(matches!(result, Err(EngineError::BadParams { .. })), "{value}: {result:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_the_commands_do_not_take_are_refused() {
|
||||
let 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();
|
||||
|
||||
@@ -562,16 +562,30 @@ fn mode_converter(mode: ColorMode, intent: Option<Intent>, grays: Grays) -> impl
|
||||
}
|
||||
|
||||
/// The name and color of each global swatch of `d`, for [`mode_color`].
|
||||
fn global_bases(d: &vectorcraft_doc::Document) -> Vec<(String, Color)> {
|
||||
d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect()
|
||||
fn global_bases(d: &vectorcraft_doc::Document) -> BTreeMap<String, Color> {
|
||||
let mut first = BTreeMap::new();
|
||||
for w in d.swatches_iter() {
|
||||
// An ineligible first record still shadows a later global solid of the same name.
|
||||
first.entry(w.name.as_str()).or_insert(w);
|
||||
}
|
||||
first
|
||||
.into_values()
|
||||
.filter_map(|w| {
|
||||
if !w.global {
|
||||
return None;
|
||||
}
|
||||
let Paint::Solid { color, swatch: None, .. } = &w.paint else { return None };
|
||||
Some((w.name.clone(), d.linked_color(*color, w.spot)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The color Document Color Mode gives `col` (swatch link `link`): a tint of a global swatch in
|
||||
/// `bases` (already converted) is that swatch's color at its tint; any other color goes through
|
||||
/// `conv` ([`mode_converter`]).
|
||||
fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &dyn Fn(&Color) -> Color) -> Color {
|
||||
match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) {
|
||||
Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint),
|
||||
fn mode_color(col: &Color, link: proof::Link, bases: &BTreeMap<String, Color>, conv: &dyn Fn(&Color) -> Color) -> Color {
|
||||
match link.and_then(|(name, tint)| Some((bases.get(name)?, tint))) {
|
||||
Some((base, tint)) if tint < 1.0 => base.tinted(tint),
|
||||
_ => conv(col),
|
||||
}
|
||||
}
|
||||
@@ -579,10 +593,11 @@ fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &
|
||||
/// 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
|
||||
@@ -594,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
|
||||
@@ -685,8 +703,8 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co
|
||||
vectorcraft_brush::store(d, &brushes);
|
||||
}
|
||||
// This pass gives tint swatches their converted swatch's color at their tint; the passes above already did the same for the art's tints.
|
||||
d.map_solid_paints(&mut |c, link, tint| match bases.iter().find(|(n, _)| Some(n) == link.as_ref()) {
|
||||
Some((_, base)) if *tint < 1.0 => {
|
||||
d.map_solid_paints(&mut |c, link, tint| match link.as_ref().and_then(|name| bases.get(name)) {
|
||||
Some(base) if *tint < 1.0 => {
|
||||
*c = base.tinted(*tint);
|
||||
true
|
||||
}
|
||||
|
||||
@@ -157,14 +157,7 @@ pub fn encode(setup: &ProofSetup) -> Vec<u8> {
|
||||
pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "view.proofSetup.save";
|
||||
let (path, named) = file_path(s, p, C)?;
|
||||
let mut setup = proof::view().setup;
|
||||
setup_params(p, &mut setup, C)?;
|
||||
check_device(&setup.target).map_err(|e| bad(C, e))?;
|
||||
// A file `view.proofSetup.load` would refuse is not written (a device with a very long name).
|
||||
let bytes = encode(&setup);
|
||||
if bytes.len() > MAX_FILE {
|
||||
return Err(bad(C, format!("{path}: larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
let (setup, bytes) = encode_options(p, &path)?;
|
||||
if named
|
||||
&& let Some(dir) = std::path::Path::new(&path).parent()
|
||||
&& !dir.is_dir()
|
||||
@@ -179,19 +172,47 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Object(r))
|
||||
}
|
||||
|
||||
/// Serialize the Customize dialog's draft without committing it or writing a path.
|
||||
pub fn draft_bytes(p: &Value) -> Result<Vec<u8>> {
|
||||
encode_options(p, "Proof Setup").map(|(_, bytes)| bytes)
|
||||
}
|
||||
|
||||
fn encode_options(p: &Value, file: &str) -> Result<(ProofSetup, Vec<u8>)> {
|
||||
const C: &str = "view.proofSetup.save";
|
||||
let mut setup = proof::view().setup;
|
||||
setup_params(p, &mut setup, C)?;
|
||||
check_device(&setup.target).map_err(|e| bad(C, e))?;
|
||||
let bytes = encode(&setup);
|
||||
if bytes.len() > MAX_FILE {
|
||||
return Err(bad(C, format!("{file}: larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
Ok((setup, bytes))
|
||||
}
|
||||
|
||||
/// The file `p` names for `cmd` and the usable proof setup in it.
|
||||
fn read_setup(s: &Session, p: &Value, cmd: &str) -> Result<(String, ProofSetup)> {
|
||||
let (path, _) = file_path(s, p, cmd)?;
|
||||
// One byte past the limit shows a file over it, which is not read further.
|
||||
let bytes = fileio::read_file_head(&path, MAX_FILE + 1)?;
|
||||
if bytes.len() > MAX_FILE {
|
||||
return Err(bad(cmd, format!("{path}: larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
let setup = parse(&bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
check_device(&setup.target).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
let setup = checked_setup(&bytes, &path, cmd)?;
|
||||
Ok((path, setup))
|
||||
}
|
||||
|
||||
/// Read a picked proof setup's validated settings without applying them to the view.
|
||||
pub fn draft_fields(bytes: &[u8], name: &str) -> Result<Value> {
|
||||
let setup = checked_setup(bytes, name, "view.proofSetup.read")?;
|
||||
Ok(Value::Object(setup_json(&setup)))
|
||||
}
|
||||
|
||||
fn checked_setup(bytes: &[u8], name: &str, cmd: &str) -> Result<ProofSetup> {
|
||||
if bytes.len() > MAX_FILE {
|
||||
return Err(bad(cmd, format!("{name}: larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
let setup = parse(bytes).map_err(|e| bad(cmd, format!("{name}: {e}")))?;
|
||||
check_device(&setup.target).map_err(|e| bad(cmd, format!("{name}: {e}")))?;
|
||||
Ok(setup)
|
||||
}
|
||||
|
||||
pub(super) fn read(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (path, setup) = read_setup(s, p, "view.proofSetup.read")?;
|
||||
let mut r = setup_json(&setup);
|
||||
|
||||
@@ -27,7 +27,7 @@ pub const EXTS: &[&str] = &["vccomposite"];
|
||||
const EXPORT: &str = "type.compositeFonts.export";
|
||||
|
||||
/// The largest file Import reads, in bytes.
|
||||
const MAX_FILE_BYTES: usize = 4 << 20;
|
||||
pub const MAX_FILE_BYTES: usize = 4 << 20;
|
||||
|
||||
/// The keys a part may give.
|
||||
const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"];
|
||||
@@ -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> {
|
||||
@@ -349,7 +371,12 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let too_large = || bad(C, "the file is larger than 4 MB");
|
||||
let bytes = match given {
|
||||
(Some(path), None, None) if !path.trim().is_empty() => read_file_head(path, MAX_FILE_BYTES + 1)?,
|
||||
(None, Some(text), None) => text.as_bytes().to_vec(),
|
||||
(None, Some(text), None) => {
|
||||
if text.len() > MAX_FILE_BYTES {
|
||||
return Err(too_large());
|
||||
}
|
||||
text.as_bytes().to_vec()
|
||||
}
|
||||
(None, None, Some(b64)) => {
|
||||
if b64.len() > MAX_FILE_BYTES / 3 * 4 + 4 {
|
||||
return Err(too_large());
|
||||
@@ -372,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)?;
|
||||
|
||||
@@ -27,6 +27,27 @@ fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// Inline and encoded files share the same raw byte limit; rejection changes no fonts or history.
|
||||
#[test]
|
||||
fn import_file_byte_boundaries_preserve_the_document_on_refusal() {
|
||||
let mut s = session();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font("Existing")]})).unwrap();
|
||||
let before = steps(&s);
|
||||
let large = " ".repeat(super::MAX_FILE_BYTES + 1);
|
||||
for params in [json!({"data": large}), json!({"dataBase64": vectorcraft_format::base64_encode(large.as_bytes())})] {
|
||||
let error = s.execute("type.compositeFonts.import", ¶ms).unwrap_err();
|
||||
assert!(error.to_string().contains("the file is larger than 4 MB"), "{error}");
|
||||
assert_eq!(names(&s), ["Existing"]);
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
let mut exact = json!({"compositeFonts": [font("Imported")]}).to_string();
|
||||
exact.extend(std::iter::repeat_n(' ', super::MAX_FILE_BYTES - exact.len()));
|
||||
let imported = s.execute("type.compositeFonts.import", &json!({"data": exact, "apply": false})).unwrap();
|
||||
assert_eq!(imported["fonts"][0]["name"], "Imported");
|
||||
assert_eq!(names(&s), ["Existing"]);
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
|
||||
fn text(s: &Session, id: u64) -> vectorcraft_doc::TextObject {
|
||||
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -284,7 +284,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Import Metadata Template…",
|
||||
[],
|
||||
None,
|
||||
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
|
||||
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text, dataBase64?: XMP bytes (exactly one source; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
|
||||
has_doc,
|
||||
super::fileinfo::apply_template
|
||||
),
|
||||
|
||||
@@ -815,6 +815,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
turned.recost_paints();
|
||||
st.history.redo.push(turned);
|
||||
st.history.trim();
|
||||
st.history_restores += 1;
|
||||
st.revision += 1;
|
||||
st.selection.prune(&st.doc);
|
||||
// Guides locked and slices locked or hidden since the step was made stay deselected.
|
||||
@@ -822,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 {
|
||||
@@ -852,13 +853,14 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
turned.recost_paints();
|
||||
st.history.undo.push(turned);
|
||||
st.history.trim();
|
||||
st.history_restores += 1;
|
||||
st.revision += 1;
|
||||
st.selection.prune(&st.doc);
|
||||
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
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 {
|
||||
@@ -867,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.
|
||||
@@ -958,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:
|
||||
@@ -1590,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);
|
||||
|
||||
@@ -213,7 +213,7 @@ enum Merge {
|
||||
Append,
|
||||
}
|
||||
|
||||
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`.
|
||||
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?|dataBase64?, mode, apply?, base?}`.
|
||||
pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mode = match text_param(p, "mode", APPLY)? {
|
||||
Some("replace") => Merge::Replace,
|
||||
@@ -236,15 +236,14 @@ pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or
|
||||
/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long.
|
||||
/// Reads one template source from `p` up to [`MAX_TEMPLATE_FILE`] bytes.
|
||||
fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
|
||||
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?];
|
||||
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?, text_param(p, "dataBase64", APPLY)?];
|
||||
// At most one byte past the limit is read, so a huge file is never read whole.
|
||||
let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1);
|
||||
let bytes = match given {
|
||||
[Some(path), None, None] => read(path)?,
|
||||
[None, Some(name), None] => {
|
||||
[Some(path), None, None, None] => read(path)?,
|
||||
[None, Some(name), None, None] => {
|
||||
let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?;
|
||||
let mut path = template_path(dir, name, APPLY)?;
|
||||
// A template `file.info.templates` lists: by its `file` first, then by its `name` with
|
||||
@@ -268,9 +267,15 @@ fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
|
||||
// The app's own folder: no root applies.
|
||||
crate::file_access::unconfined(|| read(&path))?
|
||||
}
|
||||
[None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
|
||||
[None, None, Some(data)] => data.as_bytes().to_vec(),
|
||||
_ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")),
|
||||
[None, None, Some(data), None] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
|
||||
[None, None, Some(data), None] => data.as_bytes().to_vec(),
|
||||
[None, None, None, Some(data)] => {
|
||||
if data.len() > MAX_TEMPLATE_FILE.div_ceil(3) * 4 {
|
||||
return Err(too_big(APPLY));
|
||||
}
|
||||
vectorcraft_format::base64_decode(data).ok_or_else(|| bad(APPLY, "dataBase64 is not base64"))?
|
||||
}
|
||||
_ => return Err(bad(APPLY, "give one of `path`, `name`, `data` or `dataBase64`")),
|
||||
};
|
||||
if bytes.len() > MAX_TEMPLATE_FILE {
|
||||
return Err(too_big(APPLY));
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -124,6 +124,17 @@ impl StopOwner {
|
||||
}
|
||||
}
|
||||
|
||||
/// The drawing paints affected by an edit from the Gradient panel.
|
||||
#[derive(PartialEq)]
|
||||
pub struct GradientEditPaints(Vec<EditedPaint>);
|
||||
|
||||
#[derive(PartialEq)]
|
||||
struct EditedPaint {
|
||||
id: NodeId,
|
||||
item: Option<usize>,
|
||||
paints: Vec<Paint>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Does `paint.editGradient` without `ids` edit objects on the fill (or the stroke, `stroke`)? It does not
|
||||
/// while the active tool paints with the chosen fill (or stroke: [`Session::tool_paints`]) or when nothing it
|
||||
@@ -136,6 +147,36 @@ impl Session {
|
||||
.is_ok_and(|item| item.of_kind(self, !stroke).targets_for(self, &p, !stroke).is_ok_and(|ids| !ids.is_empty()))
|
||||
}
|
||||
|
||||
/// Snapshot the paints a gradient edit without explicit targets would write, by object and
|
||||
/// appearance item. Text without an item has one paint per run. The proxy can display just
|
||||
/// the first paint when an edit goes to several objects or text runs.
|
||||
pub fn gradient_edit_paints(&self, stroke: bool) -> Result<GradientEditPaints> {
|
||||
const CMD: &str = "paint.editGradient";
|
||||
let p = json!({ "stroke": stroke });
|
||||
if super::paint::for_tool(self, &p, stroke) {
|
||||
return Ok(GradientEditPaints(Vec::new()));
|
||||
}
|
||||
let doc = &self.doc()?.doc;
|
||||
let item = item_target(self, &p, CMD)?.of_kind(self, !stroke);
|
||||
let ids = item.targets_for(self, &p, !stroke)?;
|
||||
let ids = super::appearance::drop_design_art_rows(self, ids, item, !stroke, CMD)?;
|
||||
let mut out = Vec::with_capacity(ids.len());
|
||||
for (id, item) in ids.iter().copied().zip(item.per_target(self, &ids)) {
|
||||
let (Some(node), Some(item)) = (doc.node(id), item) else { continue };
|
||||
let index = item.resolve(&node.appearance, !stroke, CMD)?;
|
||||
let (item, paints) = if index.is_none()
|
||||
&& let NodeKind::Text(text) = &node.kind
|
||||
{
|
||||
(None, text.runs.iter().map(|run| if stroke { run.style.stroke.clone() } else { run.style.fill.clone() }).collect())
|
||||
} else {
|
||||
let item = index.or_else(|| node.appearance.items.iter().rposition(|row| row.is_fill() != stroke));
|
||||
(item, node.appearance.paint_at(index, !stroke).cloned().into_iter().collect())
|
||||
};
|
||||
out.push(EditedPaint { id, item, paints });
|
||||
}
|
||||
Ok(GradientEditPaints(out))
|
||||
}
|
||||
|
||||
/// The selected gradient stop (`gradient.selectStop`), while the gradient it was selected on
|
||||
/// is still the one behind the active proxy. Callers check it against the stop count (an undo
|
||||
/// can remove stops).
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -76,6 +76,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
relink
|
||||
),
|
||||
cmd!(
|
||||
"links.replaceEmbedded",
|
||||
"Replace Image",
|
||||
[],
|
||||
None,
|
||||
"{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids]}",
|
||||
has_doc,
|
||||
replace_embedded
|
||||
),
|
||||
cmd!(
|
||||
query "links.list",
|
||||
"Links",
|
||||
@@ -1248,6 +1257,28 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
|
||||
install(d, &[id], read, Some(Preserve::Bounds), None)
|
||||
}
|
||||
|
||||
/// The browser's Replace Image uses embedded bytes and the same Fit installer as a path-based replacement.
|
||||
fn replace_embedded(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.replaceEmbedded";
|
||||
let ids = ids_param(p, "ids", C)?.filter(|ids| !ids.is_empty()).ok_or_else(|| bad(C, "give the image ids to replace"))?;
|
||||
let doc = &s.doc()?.doc;
|
||||
let mut seen = BTreeSet::new();
|
||||
for id in &ids {
|
||||
if !seen.insert(*id) {
|
||||
return Err(bad(C, format!("image {} is listed twice", id.0)));
|
||||
}
|
||||
if !doc.node(*id).is_some_and(|node| matches!(node.kind, NodeKind::Image(_))) {
|
||||
return Err(bad(C, format!("object {} is not an image", id.0)));
|
||||
}
|
||||
}
|
||||
let data = text_param(p, "dataBase64", C)?.ok_or_else(|| bad(C, "give dataBase64"))?;
|
||||
let bytes = vectorcraft_format::base64_decode(data).ok_or_else(|| bad(C, "bad dataBase64"))?;
|
||||
let mut img = fileio::raster_image(&bytes)?;
|
||||
img.blob = readable_and_kept(img.blob, kept_unread(&bytes), false)?;
|
||||
s.edit("Replace Image", |d, _| install_with(d, &ids, None, img, Some(Preserve::Fit), None, false))?;
|
||||
Ok(json!({ "replaced": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
/// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels
|
||||
/// fill them. Its transform is scaled to the new pixel size, so a reader that places it by the
|
||||
/// transform still gives it its old size. Its Placement Options do not apply. The result is what
|
||||
@@ -1256,13 +1287,19 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
|
||||
/// new file (`img.clip`, else the path kept in its stored PNG or TIFF, as Unembed writes it:
|
||||
/// [`file_clip`]) are mapped to the page through its corners, anchors and handles alike, as a
|
||||
/// distort maps a path's.
|
||||
fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo {
|
||||
fn refill_distorted(
|
||||
n: &mut Node,
|
||||
old_clip: Option<&FileClip>,
|
||||
link: Option<&LinkInfo>,
|
||||
img: &RasterImage,
|
||||
held: Option<(&PathData, FillRule)>,
|
||||
) -> ClipTo {
|
||||
let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule)));
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 {
|
||||
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height));
|
||||
}
|
||||
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone()));
|
||||
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, link.cloned());
|
||||
}
|
||||
let file = img.clip.clone().or_else(|| file_clip(&img.blob)).and_then(|(path, rule)| Some((warped(&path, &n.image_map()?)?, rule)));
|
||||
placed_clip_to(old.as_ref(), None, file, held)
|
||||
@@ -1292,8 +1329,8 @@ fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
|
||||
/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say);
|
||||
/// with `also` (a file's path and the content shown), so do the images outside the layer tree that
|
||||
/// show that content.
|
||||
fn install(d: &mut Document, ids: &[NodeId], read: FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
|
||||
install_with(d, ids, read, force, also, false)
|
||||
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
|
||||
install_with(d, ids, Some(&link), img, force, also, false)
|
||||
}
|
||||
|
||||
/// What Unembed (`unembed`) does with the clip `to` of an image whose clip group holding just it
|
||||
@@ -1307,11 +1344,13 @@ fn unembed_clip(to: ClipTo, held: bool) -> ClipTo {
|
||||
}
|
||||
}
|
||||
|
||||
/// As [`install`]; with `unembed`, each clip goes through [`unembed_clip`].
|
||||
/// Installs raster pixels with their filesystem link, if any. With `unembed`, each clip goes
|
||||
/// through [`unembed_clip`].
|
||||
fn install_with(
|
||||
d: &mut Document,
|
||||
ids: &[NodeId],
|
||||
(link, img): FileRead,
|
||||
link: Option<&LinkInfo>,
|
||||
img: RasterImage,
|
||||
force: Option<Preserve>,
|
||||
also: Option<(&str, &str)>,
|
||||
unembed: bool,
|
||||
@@ -1341,7 +1380,7 @@ fn install_with(
|
||||
NodeKind::Image(im) => old.get(&im.key).and_then(|(_, clip)| clip.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held);
|
||||
let clip = refill_distorted(&mut n, old_clip.as_ref(), link, &img, held);
|
||||
return (n, keep(clip, held.is_some()));
|
||||
}
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
@@ -1353,7 +1392,7 @@ fn install_with(
|
||||
};
|
||||
let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o);
|
||||
clip = keep(clip_to(im.xf, old_clip, c, &img, xf, held), held.is_some());
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned());
|
||||
}
|
||||
(n, clip)
|
||||
};
|
||||
@@ -1367,7 +1406,7 @@ fn install_with(
|
||||
};
|
||||
let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule));
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
let clip = refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule)));
|
||||
let clip = refill_distorted(n, old_clip.as_ref(), link, &img, held.as_ref().map(|(path, rule)| (path, *rule)));
|
||||
clips.push((*id, keep(clip, held.is_some())));
|
||||
}
|
||||
continue;
|
||||
@@ -1384,12 +1423,12 @@ fn install_with(
|
||||
if let Some(n) = d.node_mut(*id)
|
||||
&& let NodeKind::Image(im) = &mut n.kind
|
||||
{
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned());
|
||||
}
|
||||
}
|
||||
// A DCS file's spot plates print on spot swatches of their inks.
|
||||
super::place::dcs::add_spot_swatches(d, &img.blob.spot_plates());
|
||||
store_image(d, &img.key, img.blob, true);
|
||||
store_image(d, &img.key, img.blob, link.is_some());
|
||||
clips.into_iter().try_for_each(|(id, clip)| match clip {
|
||||
ClipTo::Keep => Ok(()),
|
||||
ClipTo::Path(path) => clip_image_to(d, id, path),
|
||||
@@ -2881,9 +2920,9 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Read before writing: pixels that can't be read leave no file behind.
|
||||
let img = linked_image(&bytes, Some(&path))?;
|
||||
write_file(&path, &bytes)?;
|
||||
let read = (link_info(&path, &bytes), img);
|
||||
let link = link_info(&path, &bytes);
|
||||
drop(doc);
|
||||
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))?;
|
||||
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true)))?;
|
||||
Ok(json!({ "id": id.0, "path": path }))
|
||||
}
|
||||
|
||||
@@ -2950,7 +2989,9 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Re
|
||||
drop(doc);
|
||||
let done: Vec<Value> = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect();
|
||||
let edited = s.edit("Unembed", |d, _| {
|
||||
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))
|
||||
editing_brush_art(d, |d| {
|
||||
reads.into_iter().try_for_each(|(id, (link, img))| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true))
|
||||
})
|
||||
});
|
||||
if let Err(e) = edited {
|
||||
remove_written(&written);
|
||||
|
||||
@@ -406,6 +406,20 @@ fn edit_blends(s: &mut Session, label: &str, f: impl Fn(&mut Vec<Arc<Node>>, &mu
|
||||
ok()
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Whether Blend Options would operate on selected artwork rather than new-blend defaults.
|
||||
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.
|
||||
fn selected_spec(s: &Session) -> Option<(NodeId, BlendSpec, Vec<NodeId>)> {
|
||||
let b = *selected_of(s, is_blend).first()?;
|
||||
|
||||
@@ -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
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1113,3 +1122,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()?;
|
||||
|
||||
@@ -8,6 +8,7 @@ use vectorcraft_geom::{Rect, Vec2};
|
||||
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, bool_or, check_switches, cmd, has_doc, index, ok, switch_or};
|
||||
use crate::{Clipboard, EngineError};
|
||||
|
||||
/// The panel command specifications registered with the engine.
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("artboard.reorder", "Move Artboard Up/Down", [], None, "{index, to} change an artboard's number", has_doc, artboard_reorder),
|
||||
@@ -16,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Artboard",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{index?: n | indices?: [n…] (default: the artboards the Artboard tool has selected), selectedArtboards?: [n…] (the journal records that default here, for a replay), art?: bool (default: the Artboard tool's moveArt option), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (locked and hidden art goes too; default: prefs moveLockedWithArtboard), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the copies go together on that side of the artboards they copy, 20 pt away)} a copy of each artboard, the copies placed together right of the last artboard as they lay (or on `side`), with copies of the art fully inside each when `art`, in one undo step → {index: the first copy's index, indices: the copies' indices, ids: the art's copies}",
|
||||
"{index?: n | indices?: [n…] (default: the artboards the Artboard tool has selected), selectedArtboards?: [n…] (the journal records that default here, for a replay), art?: bool (default: the Artboard tool's moveArt option), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (locked and hidden art goes too; default: prefs moveLockedWithArtboard), side?: \"left\"|\"right\"|\"top\"|\"bottom\" (the copies go together on that side of the artboards they copy, 20 pt away)} a copy of each artboard, the copies placed together right of the last artboard as they lay (or on `side`), with copies of the art on each (fully inside, within its bleed or centered/overlapping on it, #4479) when `art`, in one undo step → {index: the first copy's index, indices: the copies' indices, ids: the art's copies}",
|
||||
has_doc,
|
||||
artboard_duplicate
|
||||
),
|
||||
@@ -25,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Copy Artboard",
|
||||
[],
|
||||
None,
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} (defaults as artboard.duplicate) put the artboards, and the art fully inside each when `art`, on the clipboard: edit.paste adds a copy of each, together right of the last artboard as they lay, edit.pasteInPlace/InFront/InBack where they were, in this or another document (one undo step; edit.pasteOnAllArtboards pastes only the art); edit.copy runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} (defaults as artboard.duplicate) put the artboards, and the art on each (fully inside, within its bleed or centered/overlapping on it, #4479) when `art`, on the clipboard: edit.paste adds a copy of each, together right of the last artboard as they lay, edit.pasteInPlace/InFront/InBack where they were, in this or another document (one undo step; edit.pasteOnAllArtboards pastes only the art); edit.copy runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
boards_and_art_noted(s, p, "artboard.copy")?;
|
||||
@@ -37,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Cut Artboard",
|
||||
[],
|
||||
None,
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} artboard.copy, then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
"{index? | indices?, selectedArtboards?, art?, lockedAndHidden?} put the artboards and the art fully inside each on the clipboard (leaving oversized or overhanging art on the canvas and off the clipboard), then delete the artboards and that art in one undo step (one artboard is always left: the cut fails when it names every artboard, or a locked one; art also on another locked artboard stays, and is left off the clipboard, unless lockedAndHidden); edit.cut runs this while the Artboard tool is chosen → {copied: objects}",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
boards_and_art_noted(s, p, "artboard.cut")?;
|
||||
@@ -288,16 +289,19 @@ pub(crate) fn locked_and_hidden(s: &mut Session, p: &Value, art: bool, cmd: &str
|
||||
Ok(all)
|
||||
}
|
||||
|
||||
/// The art that goes with artboard `i` when `art`: the objects fully inside it (locked and hidden
|
||||
/// ones only when `all`), in paint order. With `moving` (a move or a cut), the art also on another
|
||||
/// locked artboard stays unless `all` ([`vectorcraft_doc::Document::art_moving_with`]); a copy
|
||||
/// takes it.
|
||||
/// The art that goes with artboard `i` when `art`: when copying, the art on the artboard (fully
|
||||
/// inside, within its bleed or centered/overlapping on it, #4479); with `moving` (a move or a cut),
|
||||
/// the objects fully inside it (locked and hidden ones only when `all`), in paint order. With
|
||||
/// `moving`, the art also on another locked artboard stays unless `all`
|
||||
/// ([`vectorcraft_doc::Document::art_moving_with`]); a copy takes it.
|
||||
pub(crate) fn artboard_art(s: &Session, i: usize, art: bool, all: bool, moving: bool) -> Result<Vec<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let rect = d.artboards.get(i).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
|
||||
if i >= d.artboards.len() {
|
||||
return Err(EngineError::Other("no such artboard".into()));
|
||||
}
|
||||
Ok(match (art, moving) {
|
||||
(false, _) => vec![],
|
||||
(true, false) => d.art_on_artboard(rect, all),
|
||||
(true, false) => d.art_for_artboard_copy(i, all),
|
||||
(true, true) => d.art_moving_with(i, all),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -177,6 +177,13 @@ fn opened_document_art(
|
||||
super::super::links::resolve(&mut l.doc, super::super::links::LinkBase::file(path), false, false);
|
||||
}
|
||||
l.doc.drop_edit_modes();
|
||||
// The native file does not store type's layout bounds. Measure them before cropping or
|
||||
// copying the art, so the placed group keeps the positions of aligned point type.
|
||||
for warning in crate::Session::refresh_text_bounds(&mut l.doc) {
|
||||
if !l.warnings.contains(&warning) {
|
||||
l.warnings.push(warning);
|
||||
}
|
||||
}
|
||||
let n = l.doc.artboards.len();
|
||||
let board = (page as usize).checked_sub(1).and_then(|i| l.doc.artboards.get(i)).map(|a| a.rect);
|
||||
let artboards = if n == 1 { "artboard" } else { "artboards" };
|
||||
|
||||
+235
-13
@@ -868,6 +868,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"),
|
||||
];
|
||||
|
||||
@@ -1614,8 +1615,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 +1643,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 +1669,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 +1807,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 +2022,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 +2066,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 +2183,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 +2191,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), 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 +2258,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 +2281,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
|
||||
),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -536,7 +536,7 @@ impl Session {
|
||||
ids.retain(|id| !matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::SymbolInstance { .. })));
|
||||
}
|
||||
let mut strokes = vec![];
|
||||
for (id, each) in ids.iter().zip(item.per_target(self, &ids)) {
|
||||
for (id, each) in ids.iter().zip(item.each_target(self, &ids)) {
|
||||
let n = st.doc.node(*id)?;
|
||||
let row = each?.resolve(&n.appearance, false, C).ok()?;
|
||||
if row.is_none() && matches!(n.kind, NodeKind::Text(_)) {
|
||||
|
||||
@@ -545,40 +545,50 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let chars = s.prefs.override_char_color;
|
||||
let before = s.doc()?.doc.clone();
|
||||
s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| {
|
||||
let id = d.graphic_style_id(i);
|
||||
let old = std::mem::replace(&mut d.graphic_styles[i], GraphicStyle { name: name.clone(), id, ..look });
|
||||
// Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the
|
||||
// source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the
|
||||
// source or as a linked object: the graph draws it again from the design.
|
||||
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src);
|
||||
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) =
|
||||
linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old)));
|
||||
set_link(d, &edited, None);
|
||||
// A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and
|
||||
// goes back to the empty appearance the graph draws it with; a linked Axes or Legend group does the same with its
|
||||
// lines and labels. The source and the edited paths keep their look, and a member linked to another style keeps
|
||||
// its look and its link.
|
||||
let mut follow_marks = super::graph::series_group_marks(d, &follow);
|
||||
let edited: HashSet<NodeId> = edited.into_iter().collect();
|
||||
let takes_style = |nid: NodeId| d.node(nid).is_some_and(|n| n.extras().graphic_style.is_none_or(|g| g == id));
|
||||
follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid) && takes_style(*nid));
|
||||
super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks));
|
||||
let g = d.graphic_styles[i].clone();
|
||||
let mut shared = None;
|
||||
for nid in &follow_marks {
|
||||
apply_style(d, *nid, &g, &mut shared, chars);
|
||||
}
|
||||
super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true);
|
||||
super::graph::capture_label_rows(d, &follow_marks);
|
||||
if let Some(src) = src {
|
||||
let link = (!super::graph::is_design_art(d, src)).then_some(id);
|
||||
set_link(d, &[src], link);
|
||||
}
|
||||
redefine_in(d, &before, i, look, src, chars);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
/// Replace graphic style `i` of `d` with the fills, strokes, effects and transparency of `look`,
|
||||
/// keeping its name and id, as Redefine Graphic Style does: the objects still linked to it follow
|
||||
/// the new definition, edited ones are unlinked and keep their look, and object `src` (the one the
|
||||
/// look comes from, if any) becomes linked. `before` is `d` before the edit; `chars` is Override
|
||||
/// Character Color.
|
||||
pub(crate) fn redefine_in(d: &mut Document, before: &Document, i: usize, look: GraphicStyle, src: Option<NodeId>, chars: bool) {
|
||||
let id = d.graphic_style_id(i);
|
||||
let name = d.graphic_styles[i].name.clone();
|
||||
let old = std::mem::replace(&mut d.graphic_styles[i], GraphicStyle { name, id, ..look });
|
||||
// Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the
|
||||
// source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the
|
||||
// source or as a linked object: the graph draws it again from the design.
|
||||
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src);
|
||||
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) =
|
||||
linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old)));
|
||||
set_link(d, &edited, None);
|
||||
// A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and
|
||||
// goes back to the empty appearance the graph draws it with; a linked Axes or Legend group does the same with its
|
||||
// lines and labels. The source and the edited paths keep their look, and a member linked to another style keeps
|
||||
// its look and its link.
|
||||
let mut follow_marks = super::graph::series_group_marks(d, &follow);
|
||||
let edited: HashSet<NodeId> = edited.into_iter().collect();
|
||||
let takes_style = |nid: NodeId| d.node(nid).is_some_and(|n| n.extras().graphic_style.is_none_or(|g| g == id));
|
||||
follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid) && takes_style(*nid));
|
||||
super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks));
|
||||
let g = d.graphic_styles[i].clone();
|
||||
let mut shared = None;
|
||||
for nid in &follow_marks {
|
||||
apply_style(d, *nid, &g, &mut shared, chars);
|
||||
}
|
||||
super::appearance::capture_series_writes(before, d, &follow_marks, (true, true), (true, true), false, true);
|
||||
super::graph::capture_label_rows(d, &follow_marks);
|
||||
if let Some(src) = src {
|
||||
let link = (!super::graph::is_design_art(d, src)).then_some(id);
|
||||
set_link(d, &[src], link);
|
||||
}
|
||||
}
|
||||
|
||||
fn style_break_link(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = super::appearance::whole_targets(s, p, "graphicStyle.breakLink")?;
|
||||
s.edit("Break Link to Graphic Style", |d, _| {
|
||||
|
||||
Loaded 100 of 642 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user