Merge main into fix/appearance-drag-document-current

This commit is contained in:
dotCooCoo committed 2026-11-27 23:34:47 -08:00
commit 75573edf9d
704 files changed
+56261 -5047

No files matched your search

+35
View File
@@ -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
+70 -2
View File
@@ -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
+6 -3
View File
@@ -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
+20
View File
@@ -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
+211 -106
View File
@@ -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",
@@ -8670,6 +8772,7 @@ name = "vectorcraft-js"
version = "0.24.1"
dependencies = [
"chrono",
"craft-xml",
"getrandom 0.4.3",
"proptest",
"unicode-properties",
@@ -8748,7 +8851,7 @@ dependencies = [
"flate2",
"getrandom 0.4.3",
"image",
"jpeg-encoder",
"jpeg-encoder 0.6.1",
"krilla",
"kurbo 0.13.1",
"log",
@@ -8787,6 +8890,7 @@ dependencies = [
"vectorcraft-color",
"vectorcraft-doc",
"vectorcraft-geom 0.24.1",
"vectorcraft-js",
"wasmi",
"wasmparser 0.228.0",
"wat",
@@ -8804,7 +8908,7 @@ dependencies = [
"craft-tiff",
"flate2",
"image",
"jpeg-encoder",
"jpeg-encoder 0.6.1",
"log",
"proptest",
"serde_json",
@@ -8931,6 +9035,7 @@ dependencies = [
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
"vectorcraft-text",
"vectorcraft-tools",
]
[[package]]
@@ -9172,9 +9277,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",
@@ -9185,27 +9290,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",
]
@@ -10575,14 +10680,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
View File
@@ -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" }
+4
View File
@@ -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.
@@ -153,6 +155,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen editing: with no path being drawn, a drag on an anchor or a segment of a selected path moves it, a line staying a line and an arc an arc beside a moved corner anchor (at a smooth anchor the handles stay in line and the segments bend to meet); a click selects an anchor, Shift-click adds one, and the canvas context menu's Delete removes the selected anchors (`path.moveAnchors`, `edit.clear`; #2660). Headline numbers unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
@@ -254,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. |
+3 -1
View File
@@ -238,11 +238,13 @@ fn main() -> ExitCode {
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's
/// (`script.listInstalled`) and finds its Startup Scripts folder (`script.startup.run`, never run on its own), keeps each
/// script's `Folder.userData` in the Script Data folder there, keeps File Info's
/// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_scripts_dir(&mut h.session);
prefs_dir::attach_startup_scripts_dir(&mut h.session);
prefs_dir::attach_script_data(&mut h.session);
prefs_dir::attach_metadata_templates_dir(&mut h.session);
prefs_dir::attach_new_doc_profiles(&mut h.session);
+1 -1
View File
@@ -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 }
+1 -1
View File
@@ -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"
-11
View File
@@ -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
View File
@@ -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() {
+22 -12
View File
@@ -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,
+11
View File
@@ -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();
+5
View File
@@ -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());
+5
View File
@@ -824,6 +824,8 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_plugin_store(&mut session);
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
prefs_dir::attach_scripts_dir(&mut session);
// The startup scripts are in the Startup Scripts folder next to the preferences.
prefs_dir::attach_startup_scripts_dir(&mut session);
// File Info's metadata templates live in their own folder next to the preferences.
prefs_dir::attach_metadata_templates_dir(&mut session);
prefs_dir::attach_new_doc_profiles(&mut session);
@@ -977,6 +979,9 @@ fn main() -> std::process::ExitCode {
single_instance::set_ui(&cc.egui_ctx);
}
let held_files = file_access::unconfined(|| open_or_hold(&mut app, command_line_files));
// With General › Run Startup Scripts on and Safe Mode off, the startup scripts run
// now, as the person's own; in Safe Mode they wait for the choice that ends it.
file_access::unconfined(|| vectorcraft_ui_egui::script_runs::run_at_launch(&mut app));
// The first frame is due from now (`gpu::watch_first_frame`).
#[cfg(feature = "wgpu")]
created.ready();
+8
View File
@@ -66,6 +66,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
}
}
/// Have `script.startup.run` run the scripts of the `Startup Scripts` folder. The folder is only
/// read: the user makes it.
pub fn attach_startup_scripts_dir(session: &mut vectorcraft_engine::Session) {
if let Some(dir) = store_dir("Startup Scripts") {
session.attach_startup_scripts_dir(dir);
}
}
/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template
/// makes.
pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) {
+81 -46
View File
@@ -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 -1
View File
@@ -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),
+16
View File
@@ -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 {
+25 -5
View File
@@ -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"),
+15 -2
View File
@@ -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;
}
}
+27 -1
View File
@@ -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.
+9 -7
View File
@@ -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
View File
@@ -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);
+27
View File
@@ -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
+31 -6
View File
@@ -12,7 +12,7 @@ pub const CHROMA_FULL: f64 = 0.4;
pub const POWERLESS_CHROMA: f64 = 0.000_004;
/// How far outside 0..=1 an sRGB component may be and still count as inside the gamut.
const GAMUT_SLACK: f64 = 1e-4;
const GAMUT_SLACK: f64 = 1e-5;
/// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they
/// are. The hue is in 0..360, and 0 while the chroma is powerless.
@@ -46,7 +46,7 @@ pub fn max_chroma(l: f64, h: f64) -> f64 {
///
/// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of
/// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313,
/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic
/// and the ray can leave and return near black as well. Each linear sRGB channel is a cubic
/// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The
/// search finds each such chroma between the cubic's turning points and takes the largest one that
/// fits.
@@ -112,11 +112,16 @@ fn turning_points(a: f64, b: f64, c: f64) -> Vec<f64> {
/// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered:
/// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that
/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more.
/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. Lightness 0 gives exactly black and
/// lightness 1 exactly white, as CSS Color 4 specifies, and a positive chroma there counts as
/// lowered.
pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) {
let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) };
let c = if c.is_nan() { 0.0 } else { c.max(0.0) };
let h = if h.is_finite() { h } else { 0.0 };
if l == 0.0 || l == 1.0 {
return ([l as f32; 3], c > 0.0);
}
let exact = oklch_to_srgb(l, c, h);
let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) };
(rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered)
@@ -239,12 +244,10 @@ mod tests {
}
/// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at
/// every hue and at lightnesses near black too, where the ray can come back into sRGB away from
/// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012).
/// every hue and at lightnesses near black too.
#[test]
fn the_largest_chroma_is_never_below_a_scan_of_the_ray() {
let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max);
assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0));
for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] {
for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) {
let max = max_chroma(l, h);
@@ -262,4 +265,26 @@ mod tests {
assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]);
assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]);
}
/// The lightness endpoints give exactly black and white at any chroma and hue, and report a
/// positive chroma as lowered. A rounded 8-bit comparison would hide a small leftover channel.
#[test]
fn the_lightness_endpoints_give_exact_black_and_white() {
assert_eq!(from_oklch(0.0, 0.04, 0.0), ([0.0; 3], true));
assert_eq!(from_oklch(0.0, 0.0, 120.0), ([0.0; 3], false));
assert_eq!(from_oklch(1.0, 0.1, 250.0), ([1.0; 3], true));
assert_eq!(from_oklch(1.0, 0.0, 0.0), ([1.0; 3], false));
}
/// A color whose green is 0.000024 below sRGB is outside it: it is lowered to the chroma that
/// fits, not clipped at its own chroma.
#[test]
fn a_channel_just_below_zero_is_outside_the_gamut() {
assert!(!in_srgb(oklch_to_srgb(0.01, 0.01, 0.0)));
let (rgb, lowered) = from_oklch(0.01, 0.01, 0.0);
assert!(lowered, "{rgb:?}");
let [_, c, _] = to_oklch(rgb);
assert!(c < 0.01, "{c}");
assert!(in_srgb(oklch_to_srgb(0.01, max_chroma(0.01, 0.0), 0.0)));
}
}
+79
View File
@@ -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
+146
View File
@@ -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;
+82
View File
@@ -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);
+1 -1
View File
@@ -116,7 +116,7 @@ pub use metadata::{CopyrightStatus, DocMetadata};
pub use node::Knockout;
pub use node::Scaling;
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS};
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
pub use orient::OrientedBox;
pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType};
pub use perspective::PerspectiveAttachment;
+32
View File
@@ -278,6 +278,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
if let Some(e) = n.extras_box() {
b += ALLOC + size_of::<NodeExtras>();
b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective);
b += e.attrs.as_deref().map_or(0, attrs_bytes);
b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize);
b += e
.color_mask
@@ -404,6 +405,22 @@ fn swatches_bytes(s: &[Swatch]) -> usize {
ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap_bytes(&w.paint)).sum::<usize>()
}
/// The heap an object's attributes own: their text, data, events, classes, foreign attributes and
/// tags.
fn attrs_bytes(a: &crate::ObjectAttributes) -> usize {
let pairs = |v: &Vec<(String, String)>| vec_bytes(v) + v.iter().map(|(k, v)| k.capacity() + v.capacity()).sum::<usize>();
a.url.capacity()
+ a.note.capacity()
+ pairs(&a.data)
+ pairs(&a.events)
+ vec_bytes(&a.classes)
+ a.classes.iter().map(String::capacity).sum::<usize>()
+ vec_bytes(&a.foreign)
+ a.foreign.iter().map(|f| f.ns.capacity() + f.prefix.capacity() + f.name.capacity() + f.value.capacity()).sum::<usize>()
+ vec_bytes(&a.tags)
+ a.tags.iter().map(|t| t.name.capacity() + t.value.capacity()).sum::<usize>()
}
/// A vector's buffer (not what its elements own).
fn vec_bytes<T>(v: &Vec<T>) -> usize {
if v.capacity() == 0 { 0 } else { ALLOC + v.capacity() * size_of::<T>() }
@@ -490,6 +507,21 @@ mod tests {
assert!((400..1200).contains(&per), "{per} bytes per moved rectangle");
}
/// An object's attributes count with their text: a version of a rectangle with a long tag and
/// a long note keeps both.
#[test]
fn tags_and_notes_count() {
let before = doc_with_rects(1);
let mut after = before.clone();
let id = after.layers[0].children().unwrap()[0].id;
after.node_mut(id).unwrap().edit_attrs(|a| {
a.note = "n".repeat(30_000);
a.tags.push(crate::ObjectTag { id: 1, name: "size".into(), value: "v".repeat(60_000) });
});
let bytes = after.retained_bytes(&before);
assert!(bytes >= 90_000, "{bytes} bytes for a rectangle with 90,000 bytes of attributes");
}
#[test]
fn a_grouped_object_is_found_shared() {
let before = doc_with_rects(100);
+1 -1
View File
@@ -24,7 +24,7 @@ mod opacity;
mod ops;
mod wire;
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS};
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
pub use clip::{ClipPaint, Uniter};
pub use extras::{Extras, ExtrasMut, NodeExtras};
pub use ids::{LAYER_COLORS, LayerColor, NodeId};
+135
View File
@@ -38,6 +38,141 @@ pub struct ObjectAttributes {
/// with it.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub foreign: Vec<ForeignAttribute>,
/// The object's tags, in order: name and value pairs that scripts read and write
/// (`object.tag.add`). Names may be empty or repeated. At most [`MAX_TAGS`], each name and
/// value at most [`MAX_TAG_TEXT`] bytes.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<ObjectTag>,
}
/// The most tags one object has.
pub const MAX_TAGS: usize = 64;
/// The longest name or value a tag has, in bytes.
pub const MAX_TAG_TEXT: usize = 64 * 1024;
/// A tag on an object: a name and a value, with an id that tells it apart from the object's other
/// tags while its name and value change.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ObjectTag {
/// Distinct among the object's tags: a new tag takes an id from
/// [`crate::Document::alloc_tag_id`], and deleting a tag raises the next node id above its id,
/// so a deleted tag's id is not given out again.
#[serde(default, deserialize_with = "lenient_tag_id")]
pub id: u64,
#[serde(default)]
pub name: String,
#[serde(default)]
pub value: String,
}
/// Reading a native file never fails over a tag id that is not a whole number from 0 to
/// `u64::MAX` (a negative one, a fraction, text): it reads as 0, and
/// [`crate::Document::tidy_tags`] gives the tag a new id.
fn lenient_tag_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
Ok(serde_json::Value::deserialize(d)?.as_u64().unwrap_or(0))
}
impl ObjectAttributes {
/// Keeps the tags within the limits: the first [`MAX_TAGS`] whose name and value are at most
/// [`MAX_TAG_TEXT`] bytes. → whether any was dropped.
pub fn tidy_tags(&mut self) -> bool {
let before = self.tags.len();
self.tags.retain(|t| t.name.len() <= MAX_TAG_TEXT && t.value.len() <= MAX_TAG_TEXT);
self.tags.truncate(MAX_TAGS);
self.tags.len() != before
}
}
impl crate::Document {
/// Keeps every object's tags within the limits ([`ObjectAttributes::tidy_tags`]) in the art of
/// the layers, symbols, graph designs and pattern swatches (opacity-mask art included). A tag
/// keeps its id when the id is from 1 to below [`crate::limits::MAX_NEXT_ID`] and no earlier
/// tag of the object has it. Every other tag gets a new id: from the next node id on, above
/// every kept id, when those ids stay below that limit; otherwise the smallest id the object's
/// other tags do not have. The next node id is then raised past every tag id below the limit.
/// It recurses through the art: call it on a document no deeper than
/// [`crate::depth::MAX_DEPTH`].
pub fn tidy_tags(&mut self) {
fn keeps(t: &ObjectTag, earlier: &[ObjectTag]) -> bool {
(1..crate::limits::MAX_NEXT_ID).contains(&t.id) && !earlier.iter().any(|o| o.id == t.id)
}
// The limits, the largest kept id and the number of new ids first, so that a new id never
// meets a kept one.
let mut next = self.peek_next_id();
let mut fresh = 0u64;
self.each_tagged(&mut |a| {
a.tidy_tags();
for (i, t) in a.tags.iter().enumerate() {
if keeps(t, &a.tags[..i]) {
next = next.max(t.id.saturating_add(1));
} else {
fresh = fresh.saturating_add(1);
}
}
});
if fresh == 0 {
self.raise_next_id(next);
return;
}
let in_range = next.saturating_add(fresh) <= crate::limits::MAX_NEXT_ID;
self.each_tagged(&mut |a| {
let kept: Vec<bool> = (0..a.tags.len()).map(|i| keeps(&a.tags[i], &a.tags[..i])).collect();
let mut used: Vec<u64> = a.tags.iter().zip(&kept).filter(|(_, k)| **k).map(|(t, _)| t.id).collect();
for (i, k) in kept.iter().enumerate() {
if *k {
continue;
}
let id = if in_range {
next = next.saturating_add(1);
next - 1
} else {
(1..).find(|c| !used.contains(c)).unwrap_or(1)
};
a.tags[i].id = id;
used.push(id);
}
});
self.raise_next_id(next);
}
/// A new tag id for object `id`, which none of its tags has: the next node id. `None` once the
/// next node id has reached [`crate::limits::MAX_NEXT_ID`] (a file with ids at the top of the
/// range), since an id from there would be outside the range [`Self::tidy_tags`] keeps and an
/// id below it could be a deleted tag's.
pub fn alloc_tag_id(&mut self, id: crate::NodeId) -> Option<u64> {
let used: Vec<u64> =
self.node(id).map(|n| n.extras().attrs.as_deref().map_or(Vec::new(), |a| a.tags.iter().map(|t| t.id).collect())).unwrap_or_default();
for _ in 0..=used.len() {
if self.peek_next_id() >= crate::limits::MAX_NEXT_ID {
return None;
}
let tag = self.alloc_id().0;
if !used.contains(&tag) {
return Some(tag);
}
}
None
}
/// Calls `f` with the attributes of every object with tags in the art [`Self::tidy_tags`] reads.
fn each_tagged(&mut self, f: &mut impl FnMut(&mut ObjectAttributes)) {
let mut fix = |n: &mut Node| {
if n.extras().attrs.as_deref().is_some_and(|a| !a.tags.is_empty()) {
n.edit_attrs(&mut *f);
}
};
let roots = self
.layers
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
for root in roots {
crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix);
}
}
}
/// An attribute in another application's XML namespace: `plotter:pen="2"` with `xmlns:plotter=
+14 -1
View File
@@ -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 } => {
+54
View File
@@ -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]
+50 -4
View File
@@ -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();
+5 -2
View File
@@ -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 => {}
+136
View File
@@ -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.
+12
View File
@@ -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²");
}
+35
View File
@@ -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(&times_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
+6 -1
View File
@@ -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;
+6
View File
@@ -875,6 +875,12 @@ pub(crate) fn catalog_index() -> &'static std::collections::HashMap<&'static str
INDEX.get_or_init(|| effect_catalog().into_iter().map(|e| (e.id, e)).collect())
}
/// The id and menu label of built-in effect `id`, as the catalog holds them (no plug-in
/// effects).
pub fn built_in_effect(id: &str) -> Option<(&'static str, &'static str)> {
catalog_index().get(id).map(|e| (e.id, e.label))
}
/// Catalogue entry for `id` (built-in, or an installed plug-in effect).
pub fn effect_info(id: &str) -> Option<EffectInfo> {
catalog_index().get(id).cloned().or_else(|| plugin_info(id))
+8
View File
@@ -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
+3 -1
View File
@@ -125,7 +125,9 @@ mod catalog;
mod geometry;
mod params;
pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range};
pub use catalog::{
EffectInfo, Lengths, WARP_STYLES, built_in_effect, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range,
};
pub(crate) use geometry::{Budget, apply_one};
pub use geometry::{
Carry, GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_bez_carrying, apply_geometry_carrying, apply_geometry_with,
+6 -6
View File
@@ -1117,10 +1117,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 +1135,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);
+6
View File
@@ -97,11 +97,13 @@ 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;
pub mod symbollib;
pub(crate) mod tabs;
pub(crate) mod tags;
mod textedit;
pub use textedit::effective_kerning;
@@ -376,6 +378,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(library::specs());
v.extend(expand::specs());
v.extend(attributes::specs());
v.extend(tags::specs());
v.extend(interactivity::specs());
v.extend(spelling::specs());
v.extend(svgfilter::specs());
@@ -924,6 +927,9 @@ pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYT
/// An Image Trace made off the UI thread, and what it traced (#3098).
pub use buildcmds::{TraceRun, Traced, image_trace_target};
/// Retype's search of the installed fonts, made off the UI thread.
pub use retype::{RetypeFound, RetypeRun, RetypeSearch};
/// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them).
pub(crate) use buildcmds::TracePresetChanges;
+1 -1
View File
@@ -173,7 +173,7 @@ fn filter(s: &mut Session, p: &Value) -> Result<Value> {
let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…'));
let kinds = effects::addons::duotone::swatch_kinds(&s.doc()?.doc);
let swatches = |name: &str| kinds.get(name).copied();
recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))
s.edit_effect(id, |s| recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches)))
}
/// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own
@@ -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();
+6 -2
View File
@@ -20,7 +20,7 @@ use vectorcraft_text::edit;
use super::super::menucmds::whole_or;
use super::super::object::choice;
use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges};
use super::super::typecmd::refresh_bounds;
use super::super::typecmd::{refresh_bounds, refresh_with_given_leading};
use super::super::typemenu::{bake_dynamic_text, text_ids};
use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets};
use crate::{EngineError, Result, Session};
@@ -170,7 +170,11 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result<Value> {
for (id, changes) in &plans {
let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?;
t.runs = tweak(std::mem::take(&mut t.runs), changes);
refresh_bounds(t);
// With Block on, the first changed character's leading goes to the frame's line gap.
match changes.first().filter(|_| key == "leading") {
Some(&(at, _)) => refresh_with_given_leading(t, at),
None => refresh_bounds(t),
}
}
Ok(())
})?;
+5 -5
View File
@@ -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,
};
+13 -3
View File
@@ -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();
+55 -18
View File
@@ -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
+6 -3
View File
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Swatch Conflicts",
[],
None,
"{profileMismatch?: as edit.paste} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours",
"{profileMismatch?: as edit.paste, allArtboards?: false (true: for edit.pasteOnAllArtboards, which leaves the background colors of copied artboards behind)} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours",
has_doc,
conflicts
),
@@ -568,9 +568,12 @@ fn import_svg(s: &mut Session, p: &Value) -> Result<Value> {
fn conflicts(s: &mut Session, p: &Value) -> Result<Value> {
let hex = |w: &Swatch| w.paint.color().map(|c| c.to_hex());
// The swatches as the paste brings them: converted from another profile when it converts.
let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?;
const CMD: &str = "clipboard.conflicts";
let profile = super::colormgmt::PasteProfile::param(p, CMD)?;
// Paste on All Artboards leaves the copied artboards, and so their backgrounds, behind.
let all_artboards = super::switch_or(p, "allArtboards", false, CMD)?;
let st = s.doc()?;
let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, true);
let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, !all_artboards);
let list: Vec<Value> = converted
.as_ref()
.unwrap_or(&s.clipboard)
+49 -1
View File
@@ -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();
+30 -12
View File
@@ -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
}
+34 -13
View File
@@ -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);
+44 -20
View File
@@ -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", &params).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(),
+180 -3
View File
@@ -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.
+1 -1
View File
@@ -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
),
+17 -13
View File
@@ -809,11 +809,13 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
let selection = shared_selection(selection, st.history.redo.last());
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
turned.named = e.named;
turned.effect = e.effect;
let paints = e.color_mode_paints.clone();
turned.color_mode_paints = e.color_mode_paints;
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.
@@ -821,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 {
@@ -845,18 +847,20 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
let selection = shared_selection(selection, st.history.undo.last());
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
turned.named = e.named;
turned.effect = e.effect;
let paints = e.color_mode_paints.clone();
turned.color_mode_paints = e.color_mode_paints;
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 {
@@ -865,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.
@@ -956,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:
@@ -1588,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);
+41 -32
View File
@@ -514,11 +514,13 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
let label = effects::effect_info(id).map(|e| e.label.trim_end_matches('…').to_string()).unwrap_or_default();
aligned(p, C)?;
if let Some(loose) = loose_for_pathfinder(s, p, id)? {
let gid = s.edit(&label, |d, sel| {
let gid = super::object::group_nodes(d, &loose)?;
d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone());
sel.set([gid]);
Ok(gid)
let gid = s.edit_effect(id, |s| {
s.edit(&label, |d, sel| {
let gid = super::object::group_nodes(d, &loose)?;
d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone());
sel.set([gid]);
Ok(gid)
})
})?;
return Ok(json!({ "ids": [gid.0], "index": 0, "item": null, "grouped": true }));
}
@@ -549,9 +551,11 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| {
fx.push(effect.clone());
true
let ids = s.edit_effect(id, |s| {
edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| {
fx.push(effect.clone());
true
})
})?;
// The item the effect landed on in the object whose row the item is (the first selected object
// for the active item, which applies where it fits), and the effect's index in that object.
@@ -892,32 +896,37 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| {
let Some(e) = fx.get_mut(index) else { return false };
if let Some(id) = &warp_id {
e.id.clone_from(id);
}
if let Some(to) = kind
&& e.id != to
{
e.params = effects::three_d_params_as(&e.id, &e.params, to);
e.id = to.to_string();
}
if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, &params), &mut e.params) {
if !cur.is_object() {
*cur = effects::merged_params(&e.id, &Value::Null);
// The effect edited, when every target has one at `index` and all are the same: a dialog's
// preview names its step after it.
let one = edited.first().filter(|e| edited.len() == targets.len() && edited.iter().all(|other| other == *e)).cloned().unwrap_or_default();
let ids = s.edit_effect(&one, |s| {
edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| {
let Some(e) = fx.get_mut(index) else { return false };
if let Some(id) = &warp_id {
e.id.clone_from(id);
}
// Earlier parameters (a Perspective strength, a light by azimuth and elevation) take
// their current form first, so the new values replace them and the rest is kept.
*cur = effects::upgrade_params(&e.id, cur);
if let Value::Object(m) = cur {
m.extend(new);
if let Some(to) = kind
&& e.id != to
{
e.params = effects::three_d_params_as(&e.id, &e.params, to);
e.id = to.to_string();
}
}
if let Some(v) = visible {
e.visible = v;
}
true
if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, &params), &mut e.params) {
if !cur.is_object() {
*cur = effects::merged_params(&e.id, &Value::Null);
}
// Earlier parameters (a Perspective strength, a light by azimuth and elevation) take
// their current form first, so the new values replace them and the rest is kept.
*cur = effects::upgrade_params(&e.id, cur);
if let Value::Object(m) = cur {
m.extend(new);
}
}
if let Some(v) = visible {
e.visible = v;
}
true
})
})?;
Ok(json!({ "ids": ids_json(&ids) }))
}
+14 -9
View File
@@ -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));
+2
View File
@@ -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;
+284
View File
@@ -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),
}
}
+3 -3
View File
@@ -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
),
+3 -2
View File
@@ -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)?;
+4 -4
View File
@@ -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),
];
+1 -1
View File
@@ -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 {
+4 -2
View File
@@ -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()));
+179 -2
View File
@@ -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,
+52 -4
View File
@@ -87,10 +87,12 @@ fn select_stop(s: &mut Session, p: &Value) -> Result<Value> {
/// front, the Appearance panel's active item and the tool the proxy in front shows the default
/// paint for (the Live Paint Bucket, or the Shape Builder's Fill proxy). Selecting other art,
/// picking a part of the instance, toggling the proxy, picking another item or choosing such a
/// tool or leaving it leaves no stop selected.
/// tool or leaving it leaves no stop selected. The Gradient panel keys its selected midpoint
/// diamond by it as well ([`Session::gradient_owner`]).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct StopOwner {
doc: Option<usize>,
pub struct StopOwner {
/// The active document's uid, which stays the same when its tab moves.
doc: Option<u64>,
object: Option<NodeId>,
/// The object whose paint the active proxy shows: a Live Paint group without faces (or edges)
/// first in the selection shows the next object's.
@@ -106,7 +108,7 @@ impl StopOwner {
pub(crate) fn of(s: &Session) -> Self {
let st = s.active();
Self {
doc: s.active,
doc: st.map(|d| d.uid),
object: st.and_then(|d| d.selection.objects.first().copied()),
source: s.proxy_source(!s.fill_active).map(|(n, _)| n.id),
part: st.is_some_and(|d| d.selection.symbol_part.is_some()),
@@ -122,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
@@ -134,12 +147,47 @@ 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).
pub fn selected_stop(&self) -> Option<usize> {
self.gradient_stop.filter(|(_, owner)| *owner == StopOwner::of(self)).map(|(i, _)| i)
}
/// Whose gradient the active proxy shows now, as a selected stop keeps it ([`StopOwner`]).
pub fn gradient_owner(&self) -> StopOwner {
StopOwner::of(self)
}
}
type Parsed<T> = std::result::Result<T, String>;
+52
View File
@@ -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();
+55 -14
View File
@@ -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);
+14
View File
@@ -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()?;
+3
View File
@@ -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);
+3 -3
View File
@@ -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)
}
}
+108 -4
View File
@@ -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())
}
+15 -2
View File
@@ -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> {
+10 -3
View File
@@ -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
View File
@@ -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![];
}
+30
View File
@@ -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()?;
+13 -9
View File
@@ -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),
})
}
+2
View File
@@ -715,6 +715,7 @@ pub const UNCHECKED: &[&str] = &[
"document.exportForScreens",
"document.exportForWeb",
"document.exportForWeb.preview",
"document.exportForWeb.saveColorTable",
"document.exportPdf",
"document.find",
"document.inspect",
@@ -820,6 +821,7 @@ pub const UNCHECKED: &[&str] = &[
"transparency.setOpacityMask",
"transparency.unlinkOpacityMask",
"type.pathOptions",
"webExport.loadColorTable",
"webExport.optimizeToFileSize",
"webExport.presets.save",
"webExport.settings",
+65 -11
View File
@@ -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);
}
}
_ => {}
+7
View File
@@ -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" };
+262 -20
View File
@@ -50,6 +50,10 @@
//! also given the parts of the active document it names in `_context.document`, whether or not
//! anything is selected: the settings, artboards, layers and swatches, as plain values
//! ([`context`]).
//!
//! A filter may be written in JavaScript ([`vectorcraft_plugins::js`]): `plugin.install {path}`
//! takes its `.vcplugin` manifest and reads the `.js` file the manifest names beside it, and the
//! plug-in store keeps the two as one module.
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
@@ -124,6 +128,10 @@ pub fn describe(p: &Plugin) -> Value {
if m.paint_output {
v["paintOutput"] = json!(true);
}
if let Some(script) = p.script() {
v["runtime"] = json!(m.runtime.name());
v["script"] = json!(script);
}
if !m.command_allowlist.is_empty() {
v["commandAllowlist"] = json!(m.command_allowlist);
}
@@ -860,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"),
];
@@ -1008,8 +1017,9 @@ pub(crate) fn admit_effects_for(cmd: &str, fx: &[Effect], n: &Node) -> std::resu
/// Largest base64 payload `plugin.install` accepts (the module limit, encoded).
const MAX_DATA_CHARS: usize = (32 << 20) / 3 * 4 + 4;
/// The `.wasm` extension plug-in files have (File › Open installs them).
pub const EXTS: &[&str] = &["wasm"];
/// The extensions plug-in files have (File › Open installs them): a WebAssembly module, and a
/// JavaScript plug-in's manifest.
pub const EXTS: &[&str] = &["wasm", vectorcraft_plugins::js::PACKAGE_EXT];
/// The plug-in module command `c`'s params give, loaded and checked, and its bytes: `path` (a
/// `.wasm` file) or `dataBase64` (the module, with `name` shown as its source).
@@ -1389,12 +1399,23 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
})
}
/// The plug-in in the `.wasm` file `path`, and its module.
/// The plug-in in the `.wasm` file `path`, or in the `.vcplugin` manifest `path` and the `.js` file
/// it names, and its module: for a JavaScript plug-in, the manifest with the script's text
/// ([`registry::read_js_package`]). Under automation read roots the script must be inside them too.
#[cfg(not(target_arch = "wasm32"))]
fn load_path(path: &str) -> Result<(Plugin, Vec<u8>)> {
crate::file_access::check_read(path).map_err(EngineError::Other)?;
let limits = vectorcraft_plugins::Limits::default();
let bytes = crate::store::read_capped(std::path::Path::new(path), limits.max_module_bytes as u64).map_err(EngineError::Other)?;
let file = std::path::Path::new(path);
let bytes = if registry::is_js_package(file) {
let allow = |script: &std::path::Path| match script.to_str() {
Some(script) => crate::file_access::check_read(script),
None => Err(format!("automation path rejected: {} isn't valid text", script.display())),
};
registry::read_js_package(file, &allow).map_err(err)?
} else {
crate::store::read_capped(file, limits.max_module_bytes as u64).map_err(EngineError::Other)?
};
Ok((Plugin::load(&bytes, limits).map_err(err)?.with_source(path), bytes))
}
@@ -1594,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) {
@@ -1616,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 }
}
@@ -1638,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) {
@@ -1769,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,
@@ -1790,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();
@@ -1833,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();
@@ -1950,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!(
@@ -1958,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), 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
),
@@ -1985,7 +2218,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Install Plug-in",
[],
None,
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
"{path: a .wasm file or a JavaScript plug-in's .vcplugin manifest (read with the .js file its script names) (desktop) | dataBase64: the module or a JavaScript plug-in as one JSON object (its manifest, with the script's text in source) (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)",
always,
install
),
@@ -1994,7 +2227,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Inspect Plug-in",
[],
None,
"{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)",
"{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)",
always,
inspect
),
@@ -2021,10 +2254,19 @@ pub fn specs() -> Vec<CommandSpec> {
"Reload Plug-ins",
["Object", "Plug-ins"],
None,
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm files past the first 1,000, not tried}",
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm and *.vcplugin in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm and *.vcplugin files past the first 1,000, not tried}",
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",
@@ -2039,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
),
@@ -404,6 +404,11 @@ pub(super) const ALLOWED: &[&str] = &[
"object.slice.release",
"object.slice.select",
"object.slice.setRect",
"object.tag.add",
"object.tag.remove",
"object.tag.removeAll",
"object.tag.set",
"object.tags",
"object.textWrap.make",
"object.textWrap.options",
"object.textWrap.release",
+1
View File
@@ -146,6 +146,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("showToolTips", "General", "Options", "Show Tool Tips", bool),
p!("showToolCards", "General", "Options", "Show Tool Cards", bool),
p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool),
p!("runStartupScripts", "General", "Options", "Run Startup Scripts", bool),
p!("antiAliasedArtwork", "General", "Options", "Anti-aliased Artwork", bool),
p!("selectSameTintPercent", "General", "Options", "Select Same Tint %", bool),
p!("showHomeScreen", "General", "Options", "Show The Home Screen When No Documents Are Open", bool),
+4 -2
View File
@@ -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.
+190 -63
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Retype",
["Type"],
None,
"{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05",
"{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only), installed?: bool} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; shapes none of those fonts match are then compared in the same way (the tolerance and the splitting included) with the installed fonts not loaded yet, unless installed is false (true, omitted or null: compared): their files are read smallest first, one at a time, until each such shape matches the fonts read, leaving out files over 256 MiB and the files and faces past 2 GiB read or 500,000 glyphs drawn in all, and a font whose glyphs match such a shape, or complete the glyphs of a split one with the fonts found before it, is loaded; a plain shape (one contour of up to four straight edges, such as a rectangle) starts no such reading and matches only a font the other shapes found; a cancel stops between files; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are wh Line truncated
has_selected_path,
retype
)]
@@ -56,6 +56,10 @@ pub fn specs() -> Vec<CommandSpec> {
#[path = "retype_fonts.rs"]
pub(super) mod fonts;
#[path = "retype_installed.rs"]
mod installed;
pub use installed::{RetypeFound, RetypeRun, RetypeSearch};
/// A shape to match: a path or compound path, in document space.
struct Piece {
@@ -141,7 +145,8 @@ fn type_can_paint(ap: &Appearance) -> bool {
ap.is_basic() && ap.stroke().is_none_or(|s| s.start_arrow.is_none() && s.end_arrow.is_none() && s.profile.is_none() && s.brush.is_none())
}
/// The faces to match against: the families in `fonts`, the document's fonts, then every loaded face.
/// The faces to match against: the families in `fonts`, the document's fonts, the faces earlier
/// searches of the installed fonts loaded ([`installed::found`]), then every other loaded face.
fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec<Arc<vectorcraft_text::FontFace>> {
let mut families: Vec<String> = fonts.iter().take(MAX_FONT_PARAMS).cloned().collect();
d.walk(|n| {
@@ -168,7 +173,8 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec<Arc<vecto
}
}
}
for face in db.loaded_faces() {
// The faces earlier searches of the installed fonts found, then the other loaded faces.
for face in installed::found(db).into_iter().chain(db.loaded_faces()) {
if faces.len() >= cap {
break;
}
@@ -1357,6 +1363,48 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option<Line> {
})
}
/// `type.retype`'s `fonts` param: the family names it lists.
fn fonts_param(p: &Value) -> Result<Vec<String>> {
const C: &str = "type.retype";
match p.get("fonts") {
None => Ok(vec![]),
Some(Value::Array(a)) => {
a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect()
}
Some(_) => Err(bad(C, "fonts must be a list of family names")),
}
}
/// `type.retype`'s `tolerance` param: 0 (exact matches only) when omitted.
fn tolerance_param(p: &Value) -> Result<f64> {
const C: &str = "type.retype";
match p.get("tolerance") {
None => Ok(0.0),
Some(v) => match v.as_f64() {
Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => Ok(t),
_ => Err(bad(C, "tolerance must be a number from 0 to 0.05")),
},
}
}
/// The shapes of the selected objects, in paint order, and whether shapes past the limits were
/// left out; an error when the selection holds none.
fn selected_pieces(s: &Session) -> Result<(Vec<Piece>, bool)> {
let roots = selected_roots(s)?;
let d = &s.doc()?.doc;
let mut pieces = vec![];
let (mut barrier, mut truncated) = (true, false);
for r in &roots {
if let Some(n) = d.node(*r) {
collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces);
}
}
if pieces.is_empty() {
return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into()));
}
Ok((pieces, truncated))
}
/// The lines, by index, to drop so that no shape of several glyphs becomes type in part: each line
/// is given by the shapes it sets, one per glyph, and `glyphs_of` says how many glyphs a shape
/// is. A line setting a glyph of a shape not all of whose glyphs are set goes, and then so do the
@@ -1675,26 +1723,70 @@ fn lookup_keys<'a>(
(wanted, near_wanted)
}
/// The candidates of `path` in `indexes`: the exact ones of every index (for a `part` of a split
/// shape, either way round), or, when there are none and `near` is set, the near ones within
/// `tolerance`. With `fill` (`Some(nonzero)`, for a shape with a visible fill), only glyphs that
/// paint the area `path` paints under that rule are kept.
fn candidates(indexes: &[&RetypeIndex], path: &BezPath, part: bool, near: bool, fill: Option<bool>, tolerance: f64) -> Vec<GlyphMatch> {
let painted = |index: &RetypeIndex, ms: Vec<GlyphMatch>, tol: f64| -> Vec<GlyphMatch> {
match fill {
Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(),
None => ms,
}
};
let exact: Vec<GlyphMatch> =
indexes.iter().flat_map(|ix| painted(ix, if part { ix.matches_either_way(path) } else { ix.all_matches(path) }, 0.0)).collect();
if exact.is_empty() && near { indexes.iter().flat_map(|ix| painted(ix, ix.near_matches(path, tolerance), tolerance)).collect() } else { exact }
}
/// The parts of the shape `path` ([`parts`]: the whole shape, or the glyphs of its contour
/// `groups`), each with its [`candidates`] in `indexes`; empty when it matches nothing. `fill` is
/// as [`candidates`] takes it, and `once` is set when the shape paints its overlaps once, as
/// several objects would ([`paints_once`]).
fn shape_parts(path: &BezPath, groups: &[BezPath], fill: Option<bool>, once: bool, indexes: &[&RetypeIndex], tolerance: f64) -> Vec<Vec<GlyphMatch>> {
let find = |p: &BezPath, part: bool, near: bool| candidates(indexes, p, part, near, fill, tolerance);
// Parts that all match exactly are checked at tolerance 0, in the near phase as in the exact
// one; only a part that matches nearly brings the tolerance in. The glyphs of a split may
// become separate objects: when the shape does not paint its overlaps as several objects
// would (translucent, another blend, a gradient or pattern fill, a stroke), its parts must not
// overlap, which the parts read by the even-odd rule against them all joined show.
let together = |runs: &[BezPath], near: bool| {
if fill.is_none() && once {
return true;
}
let nearly = near && runs.iter().any(|r| find(r, true, false).is_empty());
let tol = if nearly { tolerance } else { 0.0 };
fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(path, runs, nz, tol))
&& (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol))
};
parts(path, groups, &find, &together)
}
/// Each of `pieces`' parts, as [`shape_parts`] finds them in `indexes`: none for a piece that
/// keeps its outline or matches nothing. `groups` holds each piece's contour groups.
fn match_pieces(pieces: &[Piece], groups: &[Vec<BezPath>], indexes: &[&RetypeIndex], tolerance: f64) -> Vec<Vec<Vec<GlyphMatch>>> {
pieces
.iter()
.zip(groups)
.map(|(pc, g)| {
if pc.keeps_outline {
return vec![];
}
shape_parts(&pc.path, g, pc.filled.then_some(pc.nonzero), paints_once(pc.opacity, pc.blend, &pc.appearance), indexes, tolerance)
})
.collect()
}
fn retype(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.retype";
let fonts: Vec<String> = match p.get("fonts") {
None => vec![],
Some(Value::Array(a)) => {
a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::<Result<_>>()?
}
Some(_) => return Err(bad(C, "fonts must be a list of family names")),
};
let tolerance = match p.get("tolerance") {
None => 0.0,
Some(v) => match v.as_f64() {
Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => t,
_ => return Err(bad(C, "tolerance must be a number from 0 to 0.05")),
},
};
let fonts = fonts_param(p)?;
let tolerance = tolerance_param(p)?;
let search_installed = installed::wanted(C, p)?;
let handed = installed::handed(s);
let roots = selected_roots(s)?;
let db = FontDb::global();
let system_layout = s.doc()?.doc.setup.system_layout;
let (lines, unmatched, truncated) = {
let (lines, unmatched, truncated, installed) = {
let d = &s.doc()?.doc;
let mut pieces = vec![];
let mut truncated = false;
@@ -1725,52 +1817,69 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
let (wanted, near_wanted) =
lookup_keys(pieces.iter().zip(&groups).filter(|(pc, _)| !pc.keeps_outline).map(|(pc, g)| (&pc.path, g.as_slice())), tolerance);
// Nothing to match (every shape stays an outline): no font is read.
let index = if wanted.is_empty() && near_wanted.is_empty() {
RetypeIndex::default()
} else {
RetypeIndex::build_near(db, candidate_faces(db, d, &fonts), &wanted, &near_wanted)
let keyed = !(wanted.is_empty() && near_wanted.is_empty());
let cands = if keyed { candidate_faces(db, d, &fonts) } else { vec![] };
let mut compared: Vec<u32> = cands.iter().map(|f| f.id()).collect();
let build = |faces: Vec<Arc<vectorcraft_text::FontFace>>| {
if keyed { RetypeIndex::build_near(db, faces, &wanted, &near_wanted) } else { RetypeIndex::default() }
};
// Exact matches first; near ones, when allowed, only for a path with none.
// With a visible fill, a glyph is kept only when it paints the area the shape paints under
// the shape's fill rule (`fill` is `Some(nonzero)`).
let find = |path: &BezPath, part: bool, near: bool, fill: Option<bool>| {
let painted = |ms: Vec<GlyphMatch>, tol: f64| -> Vec<GlyphMatch> {
match fill {
Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(),
None => ms,
}
};
let exact = painted(if part { index.matches_either_way(path) } else { index.all_matches(path) }, 0.0);
if exact.is_empty() && near { painted(index.near_matches(path, tolerance), tolerance) } else { exact }
};
// Each shape's parts (one, unless it holds several glyphs), each with its candidates.
let found: Vec<Vec<Vec<GlyphMatch>>> = pieces
.iter()
.zip(&groups)
.map(|(pc, g)| {
if pc.keeps_outline {
return vec![];
}
let fill = pc.filled.then_some(pc.nonzero);
// Parts that all match exactly are checked at tolerance 0, in the near phase as in
// the exact one; only a part that matches nearly brings the tolerance in.
// The glyphs of a split may become separate objects: when the shape does not paint
// its overlaps as several objects would (translucent, another blend, a gradient or
// pattern fill, a stroke), its parts must not overlap, which the parts read by the
// even-odd rule against them all joined show.
let once = paints_once(pc.opacity, pc.blend, &pc.appearance);
let together = |runs: &[BezPath], near: bool| {
if fill.is_none() && once {
return true;
}
let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty());
let tol = if nearly { tolerance } else { 0.0 };
fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tol))
&& (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol))
let index = build(cands.clone());
// Exact matches first; near ones, when allowed, only for a path with none. With a visible
// fill, a glyph is kept only when it paints the area the shape paints under the shape's
// fill rule. Each shape's parts (one, unless it holds several glyphs), each with its
// candidates.
let mut found = match_pieces(&pieces, &groups, &[&index], tolerance);
// Shapes no face matched are compared with the other loaded faces, then with the installed
// fonts not loaded yet; or with what a search made off the UI thread found for them.
let left = left_shapes(&pieces, &groups, &found);
// A split shape's glyphs may be spread over the candidates and the other faces. Near
// matching spends an index's comparison budget, so with a tolerance the candidates are
// indexed again for each search that has a split shape to look for.
let again = |needed: bool| (needed && tolerance > 0.0).then(|| build(cands.clone()));
let (more, installed) = match handed {
Some(handed) => {
let mut more = handed.faces.clone();
compared.extend(handed.faces.iter().map(|f| f.id()));
// The shapes still left are compared with the loaded faces the search did not
// compare: none, unless a face was loaded after it looked.
compared.extend(handed.scanned.iter().copied());
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
more.extend(installed::loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?.0);
(more, handed)
}
None => {
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
let (mut more, done, kept) = installed::loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?;
let left: Vec<installed::Sought> = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect();
let installed = if search_installed {
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
let kept: Vec<RetypeIndex> = if tolerance > 0.0 { kept.iter().map(|ix| build(ix.faces().to_vec())).collect() } else { kept };
let beside: Vec<&RetypeIndex> = std::iter::once(fresh.as_ref().unwrap_or(&index)).chain(&kept).collect();
installed::search_beside(db, &left, &beside, tolerance, false)?
} else {
installed::Installed::default()
};
parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together)
})
.collect();
more.extend(installed.faces.iter().cloned());
(more, installed)
}
};
// The faces found join the candidates, the way the loaded ones are matched (near matches
// and split shapes included), and every shape is matched again with them all, so a shape
// that matched already can take the face its neighbors found.
let mut extra: Vec<Arc<vectorcraft_text::FontFace>> = vec![];
for f in more {
if !cands.iter().chain(&extra).any(|k| k.id() == f.id()) {
extra.push(f);
}
}
if !extra.is_empty() {
// Near matching spends an index's comparison budget, so with a tolerance the
// candidates are indexed again for this pass.
let first = if tolerance > 0.0 { build(cands) } else { index };
let others: Vec<RetypeIndex> = extra.chunks(vectorcraft_text::retype::MAX_FACES).map(|g| build(g.to_vec())).collect();
let all: Vec<&RetypeIndex> = std::iter::once(&first).chain(&others).collect();
found = match_pieces(&pieces, &groups, &all, tolerance);
}
// The face most shapes match, so a glyph several fonts share is set in the same font as
// the glyphs around it. Among faces that as many shapes match, the one whose glyphs fit
// them closest in all (the least leftover distance summed over those shapes), so every
@@ -1916,7 +2025,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
// Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room
// for small blocks.
let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256);
(blocks(lines, follows, system_layout, &mut budget), unmatched, truncated)
(blocks(lines, follows, system_layout, &mut budget), unmatched, truncated, installed)
};
if lines.is_empty() {
return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len())));
@@ -2050,9 +2159,27 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
.collect::<Vec<_>>(),
"unmatched": unmatched.iter().map(|i| i.0).collect::<Vec<_>>(),
"truncated": truncated,
"installed": installed.json(),
}))
}
/// The shapes of `pieces` that may become type and that `found` holds no part for, each with its
/// contour groups from `groups`.
fn left_shapes<'a>(pieces: &'a [Piece], groups: &'a [Vec<BezPath>], found: &[Vec<Vec<GlyphMatch>>]) -> Vec<installed::Sought<'a>> {
pieces
.iter()
.zip(groups)
.zip(found)
.filter(|((pc, _), parts)| !pc.keeps_outline && parts.is_empty())
.map(|((pc, g), _)| installed::Sought {
path: &pc.path,
groups: g,
fill: pc.filled.then_some(pc.nonzero),
once: paints_once(pc.opacity, pc.blend, &pc.appearance),
})
.collect()
}
#[cfg(test)]
#[path = "retype_tests.rs"]
mod tests;
+103 -45
View File
@@ -3,22 +3,25 @@
//! (<https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html>,
//! <https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html>).
//! The panel lists ten fonts and five more on request. Each selected glyph shape is compared with
//! the glyphs of up to 96 loaded fonts, those of the document's live type first, by the same
//! matching as `type.retype` (exact matches only). Of two versions of one font, only the version its
//! the glyphs of up to 96 loaded fonts, those of the document's live type first, and of the
//! installed fonts not loaded yet (`retype_installed.rs`), by the same matching as `type.retype`
//! (exact matches only). Of two versions of one font, only the version its
//! family and style name gives is compared. The order is VectorCraft's own: a font ranks by how many
//! of the shapes it matches, then by how closely, on average, and then by name. The query changes
//! nothing.
//! of the shapes it matches, then by how closely, on average, and then by name. The query does not
//! change the document; the installed fonts that match are loaded.
use std::collections::BTreeSet;
use std::sync::Arc;
use kurbo::BezPath;
use serde_json::{Value, json};
use vectorcraft_text::FontDb;
use vectorcraft_doc::Document;
use vectorcraft_text::retype::{RetypeIndex, shape_key};
use vectorcraft_text::{FontDb, FontFace};
use super::super::edit::selected_roots;
use super::super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path};
use super::{candidate_faces, collect};
use super::super::{CommandSpec, Result, Session, bad, cmd, has_selected_path};
use super::installed::Installed;
use super::{candidate_faces, selected_pieces};
pub(in crate::cmd) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
@@ -26,7 +29,7 @@ pub(in crate::cmd) fn specs() -> Vec<CommandSpec> {
"Find Matching Fonts",
[],
None,
"{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed; of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error",
"{count?: 1..96 (default 10), installed?: bool} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed, and, unless installed is false (true, omitted or null: compared), with the installed fonts not loaded yet, within type.retype's limits on reading them (every file within them is read, and the fonts that match are loaded while the list holds fewer than 96 fonts, loaded ones included); of two versions of a font, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out), installed: {read, skipped} (as type.retype reports them)}; a count that is not a whole number from 1 to 96, or an installed that is not true, false or null, is an error",
has_selected_path,
retype_fonts
)]
@@ -38,7 +41,7 @@ pub(super) const DEFAULT_COUNT: usize = 10;
pub(super) const MAX_COUNT: usize = vectorcraft_text::retype::MAX_FACES;
/// One font that matched some of the shapes.
struct Ranked {
pub(super) struct Ranked {
face: Arc<vectorcraft_text::FontFace>,
/// How many shapes it matched.
matched: usize,
@@ -49,62 +52,99 @@ struct Ranked {
}
impl Ranked {
/// The font.
pub(super) fn face(&self) -> &Arc<FontFace> {
&self.face
}
fn mean(&self) -> f64 {
self.residual / self.matched.max(1) as f64
}
}
pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result<Value> {
retype_fonts_in(s, p, FontDb::global())
}
/// [`retype_fonts`] with the fonts of `db`.
fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
const C: &str = "type.retypeFonts";
let count = match p.get("count") {
None | Some(Value::Null) => DEFAULT_COUNT,
/// The `count` param: how many fonts to list.
pub(super) fn count_param(p: &Value) -> Result<usize> {
match p.get("count") {
None | Some(Value::Null) => Ok(DEFAULT_COUNT),
Some(v) => v
.as_u64()
.and_then(|n| usize::try_from(n).ok())
.filter(|n| (1..=MAX_COUNT).contains(n))
.ok_or_else(|| bad(C, "`count` must be a whole number from 1 to 96"))?,
};
let roots = selected_roots(s)?;
let d = &s.doc()?.doc;
let mut pieces = vec![];
let (mut barrier, mut truncated) = (true, false);
for r in &roots {
if let Some(n) = d.node(*r) {
collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces);
}
.ok_or_else(|| bad("type.retypeFonts", "`count` must be a whole number from 1 to 96")),
}
if pieces.is_empty() {
return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into()));
}
// Only glyphs with a selected shape's key (segments per contour) can match one.
let wanted: BTreeSet<u64> = pieces.iter().filter_map(|pc| shape_key(&pc.path)).collect();
// A font is chosen by its family and style, which set the version the name gives: of two
// versions of one font, only that one is compared. The other versions do not take the places
// of fonts loaded after them.
let by_name = |f: &Arc<vectorcraft_text::FontFace>| db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id());
let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(by_name).collect();
}
/// Is `f` the version of its font that its family and style name gives? A font is chosen by its
/// family and style, which set that version: of two versions of one font, only that one is
/// compared, and the other versions do not take the places of fonts loaded after them.
fn by_name(db: &FontDb, f: &FontFace) -> bool {
db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id())
}
/// The loaded faces the list compares: those of the document's live type first, then the other
/// loaded faces, each the version its name gives, at most [`MAX_COUNT`].
pub(super) fn listed_faces(db: &FontDb, d: &Document) -> Vec<Arc<FontFace>> {
let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(|f| by_name(db, f)).collect();
for f in db.loaded_faces() {
if faces.len() >= vectorcraft_text::retype::MAX_FACES {
if faces.len() >= MAX_COUNT {
break;
}
if by_name(&f) && !faces.iter().any(|k| k.id() == f.id()) {
if by_name(db, &f) && !faces.iter().any(|k| k.id() == f.id()) {
faces.push(f);
}
}
faces
}
/// The fonts of `faces` whose glyphs match `shapes`, unranked, and with `search_installed` those of
/// the installed fonts not loaded yet, for the places left of [`MAX_COUNT`] (loading the ones that
/// match), with what that search read. With `handed` (what a search made off the UI thread found,
/// [`super::installed::RetypeFound`]) its faces are ranked instead, and the installed fonts are not
/// read again.
pub(super) fn rank_fonts(
db: &FontDb,
faces: Vec<Arc<FontFace>>,
shapes: &[&BezPath],
search_installed: bool,
handed: Option<Installed>,
) -> Result<(Vec<Ranked>, Installed)> {
// Only glyphs with a selected shape's key (segments per contour) can match one.
let wanted: BTreeSet<u64> = shapes.iter().filter_map(|s| shape_key(s)).collect();
// No shape has a key: no font is read.
let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, faces, &wanted) };
// A shape's paint does not change which glyph it is: shapes that would stay outlines count too.
let mut ranked: Vec<Ranked> = vec![];
for pc in &pieces {
rank(&index, shapes, &mut ranked);
// The installed fonts not loaded yet: those whose glyphs match a shape, of the version their
// family and style name gives, up to 96 fonts listed in all. A font that matches only as
// combining marks is not listed, so it takes no place.
let room = MAX_COUNT.saturating_sub(ranked.iter().filter(|r| r.character).count());
let found = if let Some(handed) = handed {
handed
} else if !search_installed {
Installed::default()
} else if room == 0 {
// The list is full: the installed faces a search would compare count as skipped, none
// when no shape would start one.
let skipped = if super::installed::starts_search(shapes) { db.unloaded_installed_faces().len() } else { 0 };
Installed { skipped, ..Default::default() }
} else {
super::installed::search_listed(db, shapes, room, &|f| by_name(db, f))?
};
// A face found earlier (handed in) may be loaded and ranked already: it counts once.
let more: Vec<_> = found.faces.iter().filter(|f| !ranked.iter().any(|r| r.face.id() == f.id())).cloned().collect();
if !more.is_empty() {
rank(&RetypeIndex::build(db, more, &wanted), shapes, &mut ranked);
}
Ok((ranked, found))
}
/// Adds to `ranked` the fonts of `index` that match `shapes`.
fn rank(index: &RetypeIndex, shapes: &[&BezPath], ranked: &mut Vec<Ranked>) {
for shape in shapes {
// A shape can fit several glyphs or poses of one font: it counts once for the font, at its
// closest fit.
let mut best: Vec<(Arc<vectorcraft_text::FontFace>, f64, bool)> = vec![];
for m in index.all_matches(&pc.path) {
let mut best: Vec<(Arc<FontFace>, f64, bool)> = vec![];
for m in index.all_matches(shape) {
let character = !vectorcraft_text::retype::is_combining_mark(m.ch);
match best.iter_mut().find(|(f, _, _)| f.id() == m.face.id()) {
Some(b) => {
@@ -125,6 +165,23 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
}
}
}
}
pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result<Value> {
retype_fonts_in(s, p, FontDb::global())
}
/// [`retype_fonts`] with the fonts of `db`.
fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
const C: &str = "type.retypeFonts";
let count = count_param(p)?;
let search_installed = super::installed::wanted(C, p)?;
let handed = super::installed::handed(s);
let (pieces, truncated) = selected_pieces(s)?;
let d = &s.doc()?.doc;
// A shape's paint does not change which glyph it is: shapes that would stay outlines count too.
let shapes: Vec<&BezPath> = pieces.iter().map(|pc| &pc.path).collect();
let (mut ranked, found) = rank_fonts(db, listed_faces(db, d), &shapes, search_installed, handed)?;
// A font whose glyphs match the shapes only as combining marks would retype none of them, as
// type.retype starts no line with a mark: it is not listed.
ranked.retain(|r| r.character);
@@ -143,6 +200,7 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
"shapes": pieces.len(),
"more": more,
"truncated": truncated,
"installed": found.json(),
}))
}
+60 -2
View File
@@ -99,7 +99,7 @@ fn shapes_that_are_no_glyph_list_no_font() {
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
let r = query(&mut s, json!({}), bundled());
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false}));
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}}));
// Live type alone holds no shape to compare.
let t = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "live"})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [t]})).unwrap();
@@ -113,7 +113,7 @@ fn a_font_that_matches_only_combining_marks_is_not_listed() {
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = query(&mut s, json!({}), bundled());
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false}));
assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}}));
// After a base, the mark counts with it.
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
@@ -161,6 +161,64 @@ fn of_two_versions_only_the_one_the_name_gives_is_listed() {
assert_eq!(names(&r).iter().filter(|f| f.0 == FAMILY).count(), 1, "version 1 matches and is listed once: {r}");
}
#[test]
fn installed_fonts_not_loaded_are_ranked_too_unless_left_out() {
use vectorcraft_text::test_fonts::named_copy;
let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed");
let file = dir.join("RetypeListed-Regular.ttf");
std::fs::write(&file, named_copy(true, ("Retype Listed", "Regular", "Version 1.000", "RetypeListed-Regular")).unwrap()).unwrap();
let db = FontDb::with_font_dirs(vec![dir]);
let mut s = session();
let inter = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Kgw", "size": 40, "font": "Inter", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [inter]})).unwrap();
// Left out: the installed copy is not read, and stays unloaded.
let r = query(&mut s, json!({"count": 96, "installed": false}), &db);
assert!(!names(&r).iter().any(|f| f.0 == "Retype Listed"), "{r}");
assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}");
assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed"));
// Compared: the copy of Inter matches every shape, as Inter does, and is loaded.
let r = query(&mut s, json!({"count": 96}), &db);
let fonts = names(&r);
assert!(fonts.contains(&("Retype Listed".to_string(), "Regular".to_string(), 3)), "{r}");
assert!(fonts.contains(&("Inter".to_string(), "Regular".to_string(), 3)), "{r}");
assert_eq!(r["installed"], json!({"read": 1, "skipped": 0}), "{r}");
assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed"));
}
#[test]
fn installed_fonts_fill_the_list_up_to_96_fonts_in_all() {
use vectorcraft_text::test_fonts::named_copy;
let copy = |family: &str| {
let postscript = format!("{}-Regular", family.replace(' ', ""));
(named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap(), postscript)
};
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rg", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
// Loaded copies that match fill most of the list.
let loaded = FontDb::with_font_dirs(vec![]);
for i in 0..super::MAX_COUNT {
loaded.add_font(copy(&format!("Fullcopy {i:02}")).0);
}
let listed = names(&query(&mut s, json!({"count": 96, "installed": false}), &loaded)).len();
assert!(listed < super::MAX_COUNT, "{listed}");
// Installed copies, two more than the places left.
let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed-full");
for i in 0..super::MAX_COUNT - listed + 2 {
let (data, postscript) = copy(&format!("Installed {i:02}"));
std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap();
}
let db = FontDb::with_font_dirs(vec![dir]);
for i in 0..super::MAX_COUNT {
db.add_font(copy(&format!("Fullcopy {i:02}")).0);
}
let r = query(&mut s, json!({"count": 96}), &db);
assert_eq!(names(&r).len(), super::MAX_COUNT, "the installed copies fill the places left: {r}");
assert_eq!(r["more"], json!(false), "no font past the list is found: {r}");
assert_eq!(r["installed"]["skipped"], json!(2), "{r}");
assert_eq!(db.unloaded_installed_faces().len(), 2, "the two past the list stay unloaded");
}
#[test]
fn shapes_that_stay_outlines_still_name_their_font() {
// A glyph with paint type cannot take (two fills) is not retyped, but it is still that font's glyph.
+773
View File
@@ -0,0 +1,773 @@
//! Retype's installed fonts: the faces of installed fonts that nothing has loaded yet are
//! candidates too, as the fonts on the device are among the sources Retype suggests fonts from
//! (<https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html>).
//! Each font file is read for the search and let go; a face whose glyphs match a shape is loaded
//! as it was read, without the family's other files. Files are read smallest first, within a budget
//! of bytes read and glyphs drawn, and the search stops between files when it is canceled. The app
//! runs it off the UI thread ([`RetypeRun`]), with a Cancel. A face read is matched as a loaded one
//! is: with Retype's tolerance, near matches count, and a compound path of several glyphs counts
//! when every glyph it splits into matches, in one face or in several.
use std::collections::BTreeSet;
use std::sync::Arc;
use kurbo::BezPath;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, NodeId};
use vectorcraft_text::retype::{MAX_FACES, NearKey, RetypeIndex, encoded_glyphs, is_plain, shape_key};
use vectorcraft_text::{FontDb, FontFace};
use super::super::{EngineError, Result, Session, bad};
/// How much one search reads.
#[derive(Clone, Copy)]
struct Limits {
/// Font files (a suitcase font's resource fork) longer than this are not read.
file: u64,
/// The bytes of font files read, in all.
read: u64,
/// The glyphs of installed faces drawn, in all, to tell which can match a shape.
glyphs: usize,
/// The faces found: the faces after the last one found are not compared.
faces: usize,
}
const LIMITS: Limits = Limits { file: 256 << 20, read: 2 << 30, glyphs: 500_000, faces: MAX_FACES };
/// The `installed` param: whether to look in the installed fonts (default true).
pub(super) fn wanted(cmd: &str, p: &Value) -> Result<bool> {
match p.get("installed") {
None | Some(Value::Null) => Ok(true),
Some(Value::Bool(b)) => Ok(*b),
Some(_) => Err(bad(cmd, "`installed` must be true, false or null")),
}
}
/// What a search of the installed fonts found and read.
#[derive(Default)]
pub(super) struct Installed {
/// The faces whose glyphs match a shape, loaded now, in the order they were read.
pub(super) faces: Vec<Arc<FontFace>>,
/// Faces read and compared.
pub(super) read: usize,
/// Faces left out by the limits ([`LIMITS`]).
pub(super) skipped: usize,
/// For a search made away from its command, the ids of the loaded faces it compared: the
/// command does not compare them again.
pub(super) scanned: Vec<u32>,
}
impl Installed {
/// As a command's result reports it.
pub(super) fn json(&self) -> Value {
json!({"read": self.read, "skipped": self.skipped})
}
}
/// A shape to look for: its path, the contour groups it splits into when it may hold several
/// glyphs (none for a shape matched whole only), its fill rule when it has a visible fill
/// (`Some(nonzero)`) and whether it paints its overlaps once ([`super::paints_once`]), as
/// `type.retype` reads them.
#[derive(Clone, Copy)]
pub(super) struct Sought<'a> {
pub(super) path: &'a BezPath,
pub(super) groups: &'a [BezPath],
pub(super) fill: Option<bool>,
pub(super) once: bool,
}
impl<'a> Sought<'a> {
/// `path` split into `groups`, with no paint check.
pub(super) fn unpainted(path: &'a BezPath, groups: &'a [BezPath]) -> Self {
Sought { path, groups, fill: None, once: true }
}
}
/// `shapes`, each matched whole only.
fn whole<'a>(shapes: &[&'a BezPath]) -> Vec<Sought<'a>> {
shapes.iter().map(|path| Sought::unpainted(path, &[])).collect()
}
/// The keys to look glyphs up by for `shapes`, at `tolerance` ([`super::lookup_keys`]).
fn keys_of(shapes: &[Sought], tolerance: f64) -> (BTreeSet<u64>, Vec<NearKey>) {
super::lookup_keys(shapes.iter().map(|s| (s.path, s.groups)), tolerance)
}
/// Does a search look for `s`: is it not plain ([`is_plain`]: a rectangle, a triangle or a bar),
/// with a key to look glyphs up by? A shape without one matches no face.
fn starts(s: &Sought, tolerance: f64) -> bool {
if is_plain(s.path) {
return false;
}
let (keys, near) = keys_of(std::slice::from_ref(s), tolerance);
!keys.is_empty() || !near.is_empty()
}
/// Is `s` found in `indexes` at `tolerance`: does its whole shape match a glyph there, or does
/// every glyph it splits into, painting the area `s` paints ([`super::shape_parts`])?
fn found_in(indexes: &[&RetypeIndex], s: &Sought, tolerance: f64) -> bool {
!super::shape_parts(s.path, s.groups, s.fill, s.once, indexes, tolerance).is_empty()
}
/// [`search_for`] of `shapes` matched whole, exactly.
#[cfg(test)]
pub(super) fn search(db: &FontDb, shapes: &[&BezPath], every: bool) -> Result<Installed> {
search_within(db, shapes, every, LIMITS, &|_| true)
}
/// [`search_beside`] with no loaded faces.
#[cfg(test)]
pub(super) fn search_for(db: &FontDb, shapes: &[Sought], tolerance: f64, every: bool) -> Result<Installed> {
search_beside(db, shapes, &[], tolerance, every)
}
/// The installed faces nothing has loaded that `shapes` that are not plain ([`is_plain`]) are found
/// in at `tolerance` ([`found_in`]), each loaded into `db` as it was read. With `every` false, a
/// face is found when it matches such a shape, or completes the glyphs of a split one with the
/// loaded faces of `loaded` (the indexes of faces the command compares too) and the faces found or
/// read before it (a face read before whose glyphs it completes is found with it), and the search
/// stops once each such shape is found; with it, every face within the limits ([`LIMITS`]) is
/// compared, and found when it matches a shape on its own. No file is read when every shape is
/// plain. At most [`MAX_FACES`] faces are found; the faces not compared past that count as skipped.
/// The faces of `loaded` whose glyphs complete a split shape with a face found are among the faces
/// found too, so the command compares them with it.
pub(super) fn search_beside(db: &FontDb, shapes: &[Sought], loaded: &[&RetypeIndex], tolerance: f64, every: bool) -> Result<Installed> {
search_sought(db, shapes, loaded, tolerance, every, LIMITS, &|_| true)
}
/// [`search`] comparing every face within the limits, for a list of at most `faces` faces: a face
/// found that `listed` turns down is loaded and not listed, and takes no place of the `faces`.
pub(super) fn search_listed(db: &FontDb, shapes: &[&BezPath], faces: usize, listed: &dyn Fn(&FontFace) -> bool) -> Result<Installed> {
search_sought(db, &whole(shapes), &[], 0.0, true, Limits { faces: faces.min(MAX_FACES), ..LIMITS }, listed)
}
/// Would a search for `shapes`, matched whole and exactly, read any installed file: is one of them
/// not plain, with a glyph's key ([`shape_key`])?
pub(super) fn starts_search(shapes: &[&BezPath]) -> bool {
shapes.iter().any(|s| !is_plain(s) && shape_key(s).is_some())
}
/// [`loaded_rest_for`] of `shapes` matched whole, exactly: the faces only.
#[cfg(test)]
pub(super) fn loaded_rest(db: &FontDb, shapes: &[&BezPath], compared: &[u32]) -> Result<Vec<Arc<FontFace>>> {
Ok(loaded_rest_for(db, &whole(shapes), &[], 0.0, compared)?.0)
}
/// The loaded faces that are not among `compared` (those past the [`MAX_FACES`] a Retype compares
/// first) that one of `shapes` that is not plain ([`is_plain`]) is found in at `tolerance`
/// ([`found_in`]), indexed [`MAX_FACES`] at a time: the faces of the glyphs it matches. The glyphs of
/// a split shape may be spread over those groups and the faces of `beside` (the indexes of faces
/// among `compared`). With them, whether each shape was found, and the indexes of the latest
/// groups that hold glyphs of the shapes while a split shape is not found (at most
/// [`MAX_KEPT_GROUPS`]), for the search of the installed fonts. A cancel stops it between those
/// groups.
pub(super) fn loaded_rest_for(db: &FontDb, shapes: &[Sought], beside: &[&RetypeIndex], tolerance: f64, compared: &[u32]) -> Result<LoadedRest> {
let mut done = vec![false; shapes.len()];
let looked: Vec<(usize, &Sought)> = shapes.iter().enumerate().filter(|(_, s)| !is_plain(s.path)).collect();
let (keys, near) = super::lookup_keys(looked.iter().map(|(_, s)| (s.path, s.groups)), tolerance);
let mut out: Vec<Arc<FontFace>> = vec![];
if keys.is_empty() && near.is_empty() {
return Ok((out, done, vec![]));
}
let rest: Vec<Arc<FontFace>> = db.loaded_faces().into_iter().filter(|f| !compared.contains(&f.id())).collect();
// The earlier groups' indexes that hold glyphs of the shapes, while a split shape is not found
// yet: the latest [`MAX_KEPT_GROUPS`].
let mut kept: Vec<RetypeIndex> = vec![];
for group in rest.chunks(MAX_FACES) {
vectorcraft_doc::cancel::check()?;
let index = RetypeIndex::build_near(db, group.iter().cloned(), &keys, &near);
let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&kept).chain(std::iter::once(&index)).collect();
for (k, s) in &looked {
// A split shape not found yet is matched with the faces before the group too (one pass,
// as near matching spends an index's budget); any other shape with the group alone.
let combined = !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true);
let indexes: &[&RetypeIndex] = if combined { &with } else { &[&index] };
let parts = super::shape_parts(s.path, s.groups, s.fill, s.once, indexes, tolerance);
if parts.is_empty() {
continue;
}
if let Some(d) = done.get_mut(*k) {
*d = true;
}
for m in parts.into_iter().flatten() {
if !compared.contains(&m.face.id()) && !out.iter().any(|f| f.id() == m.face.id()) {
out.push(m.face);
}
}
}
let open = looked.iter().any(|(k, s)| !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true));
if open && !index.is_empty() {
// The latest groups are kept: the oldest goes when the cap is reached.
if kept.len() >= MAX_KEPT_GROUPS {
kept.remove(0);
}
kept.push(index);
}
}
if !looked.iter().any(|(k, s)| !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true)) {
kept.clear();
}
Ok((out, done, kept))
}
/// What [`loaded_rest_for`] finds: the faces, whether each shape was found, and the indexes kept
/// for the search of the installed fonts.
type LoadedRest = (Vec<Arc<FontFace>>, Vec<bool>, Vec<RetypeIndex>);
/// Earlier groups of [`MAX_FACES`] loaded faces past the ones compared first that a group's faces
/// complete a split shape's glyphs with, at most: the latest ones.
const MAX_KEPT_GROUPS: usize = 4;
/// An installed font file: its path, its length and the (family, style) of the faces wanted from it.
type File = (std::path::PathBuf, u64, Vec<(String, String)>);
/// [`search`] within `limits`, keeping in its faces only those `listed` accepts.
#[cfg(test)]
fn search_within(db: &FontDb, shapes: &[&BezPath], every: bool, limits: Limits, listed: &dyn Fn(&FontFace) -> bool) -> Result<Installed> {
search_sought(db, &whole(shapes), &[], 0.0, every, limits, listed)
}
/// [`search_beside`] within `limits`, keeping in its faces only those `listed` accepts.
fn search_sought(
db: &FontDb,
shapes: &[Sought],
beside: &[&RetypeIndex],
tolerance: f64,
every: bool,
limits: Limits,
listed: &dyn Fn(&FontFace) -> bool,
) -> Result<Installed> {
let mut out = Installed::default();
// A shape without a glyph's key matches no face: the search does not wait for it.
let shapes: Vec<Sought> = shapes.iter().copied().filter(|s| starts(s, tolerance)).collect();
let (keys, near) = keys_of(&shapes, tolerance);
if keys.is_empty() && near.is_empty() {
return Ok(out);
}
let (keys, near) = (&keys, near.as_slice());
// The indexes of the faces found, which the glyphs of a split shape may be spread over.
let mut found: Vec<RetypeIndex> = vec![];
// The faces read, not loaded, that hold glyphs of the shapes without completing one, with their
// indexes: a later face may complete a split shape with them. The latest [`MAX_FACES`].
let mut partial: Vec<(Arc<FontFace>, RetypeIndex)> = vec![];
// The faces wanted from each file, smallest file first.
let mut files: Vec<File> = vec![];
let mut at: std::collections::HashMap<std::path::PathBuf, usize> = std::collections::HashMap::new();
for f in db.unloaded_installed_faces() {
match at.get(&f.path).and_then(|i| files.get_mut(*i)) {
Some(file) => file.2.push((f.family, f.style)),
None => {
at.insert(f.path.clone(), files.len());
files.push((f.path, f.len, vec![(f.family, f.style)]));
}
}
}
files.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0)));
let mut matched = vec![false; shapes.len()];
// Is a split shape not found yet: only then are faces kept in `partial`.
let open = |matched: &[bool]| shapes.iter().zip(matched).any(|(s, m)| !*m && !s.groups.is_empty());
let (mut bytes_left, mut glyphs_left) = (limits.read, limits.glyphs);
let total = files.len() as u64;
for (i, (path, len, styles)) in files.iter().enumerate() {
vectorcraft_doc::cancel::check()?;
vectorcraft_doc::cancel::progress(i as u64, total, "Retype: reading installed fonts");
// A file too long for what is left, or read when no glyph is left to draw, is not read.
if *len > limits.file || *len > bytes_left || glyphs_left == 0 {
out.skipped += styles.len();
continue;
}
// A file that grew since the scan is read only within what is left.
let file = db.read_unloaded_file(path, limits.file.min(bytes_left));
// The bytes read, those of a file that grew past the limits too.
bytes_left = bytes_left.saturating_sub(file.bytes);
if file.too_long {
out.skipped += styles.len();
continue;
}
let wanted = |f: &FontFace| styles.iter().any(|(family, style)| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style));
let faces: Vec<Arc<FontFace>> = file.faces.into_iter().filter(|f| wanted(f)).collect();
for (j, face) in faces.iter().enumerate() {
if out.faces.len() >= limits.faces {
// The faces not compared past the cap: the rest of this file's and the later files'.
out.skipped += styles.len().saturating_sub(j) + files.iter().skip(i + 1).map(|f| f.2.len()).sum::<usize>();
return Ok(out);
}
let n = encoded_glyphs(face);
if n > glyphs_left {
out.skipped += 1;
continue;
}
glyphs_left -= n;
out.read += 1;
let index = RetypeIndex::build_unloaded_near(db, face.clone(), keys, near);
if index.is_empty() {
continue;
}
// With `every`, a face fits a shape it matches on its own; otherwise a shape not found
// yet that it completes with the loaded faces of `beside`, the faces found before it and
// the faces read before it that hold some of its glyphs (`partial`).
let parts: Vec<&RetypeIndex> = partial.iter().map(|(_, ix)| ix).collect();
let parts_with = |extra: &[&RetypeIndex], ix: &RetypeIndex, k: usize| -> Vec<Vec<super::GlyphMatch>> {
let Some(s) = shapes.get(k) else { return vec![] };
if every {
return super::shape_parts(s.path, s.groups, s.fill, s.once, &[ix], tolerance);
}
if matched.get(k).copied().unwrap_or(true) {
return vec![];
}
// A shape matched whole only takes one glyph: the faces read before it do not hold it.
let extra = if s.groups.is_empty() { &[] } else { extra };
let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(extra.iter().copied()).chain(std::iter::once(ix)).collect();
super::shape_parts(s.path, s.groups, s.fill, s.once, &with, tolerance)
};
let fit_with = |extra: &[&RetypeIndex], ix: &RetypeIndex, k: usize| !parts_with(extra, ix, k).is_empty();
let fit = |ix: &RetypeIndex, k: usize| fit_with(&parts, ix, k);
// Each shape it fits, with the glyphs it matches: one pass, as near matching spends an
// index's budget.
let first: Vec<(usize, Vec<Vec<super::GlyphMatch>>)> =
(0..shapes.len()).map(|k| (k, parts_with(&parts, &index, k))).filter(|(_, p)| !p.is_empty()).collect();
let fits: Vec<usize> = first.iter().map(|(k, _)| *k).collect();
if fits.is_empty() {
// The face holds glyphs of a shape without completing one: a later face may, while
// a split shape is not found. The latest are kept: the oldest goes when the cap is
// reached.
if !every && open(&matched) {
#[cfg(test)]
KEPT_PARTIAL.with(|n| n.set(n.get() + 1));
if partial.len() >= MAX_FACES {
partial.remove(0);
}
partial.push((face.clone(), index));
}
continue;
}
let loaded = load(db, face);
let same = loaded.id() == face.id();
let (mut fits, index) = still_fit(db, face, &loaded, index, keys, near, fits, &fit);
if fits.is_empty() {
continue;
}
// The faces read before whose glyphs the shapes it fits use, loaded with it: those
// that leave room under the cap, or else only the shapes it fits without them. A face
// loaded in place of the one read is matched again for them.
let matches: Vec<Vec<super::GlyphMatch>> = if same {
first.into_iter().flat_map(|(_, p)| p).collect()
} else {
fits.iter().flat_map(|k| parts_with(&parts, &index, *k)).collect()
};
let held: Vec<&Arc<FontFace>> = index.faces().iter().chain(found.iter().flat_map(|ix| ix.faces())).chain(&out.faces).collect();
let (mut used, mut with_loaded) = companions(&matches, &held, beside, &partial);
if out.faces.len() + used.len() + with_loaded.len() >= limits.faces {
let alone: Vec<&RetypeIndex> = found.iter().chain(std::iter::once(&index)).collect();
fits.retain(|k| shapes.get(*k).is_some_and(|s| found_in(&alone, s, tolerance)));
used.clear();
with_loaded.clear();
if fits.is_empty() {
continue;
}
}
let mut shadowed = false;
let mut promoted: Vec<Arc<FontFace>> = vec![];
for at in used.into_iter().rev() {
let (read, ix) = partial.remove(at);
let loaded = load(db, &read);
let ix = if loaded.id() == read.id() {
ix
} else {
shadowed = true;
RetypeIndex::build_near(db, [loaded.clone()], keys, near)
};
promoted.insert(0, loaded);
found.push(ix);
}
// A face loaded in place of one read may have other glyphs: the shapes are checked again.
if shadowed {
let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(std::iter::once(&index)).collect();
fits.retain(|k| shapes.get(*k).is_some_and(|s| found_in(&with, s, tolerance)));
if fits.is_empty() {
continue;
}
}
// The faces it completes shapes with, once the match holds.
out.faces.extend(with_loaded);
for loaded in promoted {
if listed(&loaded) {
remember(db, &loaded);
if !out.faces.iter().any(|f| f.id() == loaded.id()) {
out.faces.push(loaded);
}
}
}
// A face `listed` turns down (another version shadows it) is not compared ahead of others.
if listed(&loaded) {
remember(db, &loaded);
if !out.faces.iter().any(|f| f.id() == loaded.id()) {
out.faces.push(loaded);
}
}
found.push(index);
for k in fits {
if let Some(m) = matched.get_mut(k) {
*m = true;
}
}
if !every && matched.iter().all(|m| *m) {
return Ok(out);
}
// With every split shape found, the faces kept for them are dropped.
if !open(&matched) {
partial.clear();
}
}
// The cap reached with the file's last face: the later files are not compared.
if out.faces.len() >= limits.faces {
out.skipped += files.iter().skip(i + 1).map(|f| f.2.len()).sum::<usize>();
return Ok(out);
}
}
Ok(out)
}
#[cfg(test)]
thread_local! {
/// How many times a search on this thread kept a face it read in `partial`.
static KEPT_PARTIAL: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// For each of `parts` (each part's candidates) that none of the faces of `held` has a glyph of,
/// one face that does: a loaded face of `beside` (the command compares it with the face found),
/// or else a face of `partial`, read before. The places in `partial` of those, in order, and the
/// loaded faces.
fn companions(
parts: &[Vec<super::GlyphMatch>],
held: &[&Arc<FontFace>],
beside: &[&RetypeIndex],
partial: &[(Arc<FontFace>, RetypeIndex)],
) -> (Vec<usize>, Vec<Arc<FontFace>>) {
let (mut used, mut loaded) = (BTreeSet::new(), Vec::<Arc<FontFace>>::new());
for part in parts {
let has = |f: &Arc<FontFace>| part.iter().any(|m| m.face.id() == f.id());
let chosen = used.iter().filter_map(|at: &usize| partial.get(*at).map(|(f, _)| f));
if held.iter().copied().chain(&loaded).chain(chosen).any(has) {
continue;
}
let of_beside = part.iter().find(|m| beside.iter().any(|ix| ix.faces().iter().any(|f| f.id() == m.face.id())));
if let Some(m) = of_beside {
loaded.push(m.face.clone());
} else if let Some(at) = part.iter().find_map(|m| partial.iter().position(|(f, _)| Arc::ptr_eq(f, &m.face))) {
used.insert(at);
}
}
(used.into_iter().collect(), loaded)
}
/// The faces searches loaded from installed files, by database ([`FontDb::id`]) and face id, the
/// latest first: at most [`MAX_FACES`].
static FOUND: std::sync::Mutex<Vec<(u64, u32)>> = std::sync::Mutex::new(Vec::new());
/// Keep `face`, which a search loaded into `db`, among [`found`]'s faces.
fn remember(db: &FontDb, face: &FontFace) {
let mut kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let at = (db.id(), face.id());
kept.retain(|k| *k != at);
kept.insert(0, at);
kept.truncate(MAX_FACES);
}
/// The faces of `db` that searches of the installed fonts found and loaded, the latest first. A
/// later Retype compares them ahead of the other loaded faces.
pub(super) fn found(db: &FontDb) -> Vec<Arc<FontFace>> {
let kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
kept.into_iter().filter(|(d, _)| *d == db.id()).filter_map(|(_, id)| db.face_by_id(id)).collect()
}
/// Of `fits` (the shapes `index`, the index of `read`, fits as `fit` tells), those that `loaded`,
/// the face loading `read` gave, fits too, with the index they fit in: all of them and `index`
/// when it is `read` itself. Another face of the same family, style and version, loaded from
/// another file, may have other glyphs; it is indexed by `keys` and `near`.
#[allow(clippy::too_many_arguments)]
fn still_fit(
db: &FontDb,
read: &FontFace,
loaded: &Arc<FontFace>,
index: RetypeIndex,
keys: &BTreeSet<u64>,
near: &[NearKey],
fits: Vec<usize>,
fit: &dyn Fn(&RetypeIndex, usize) -> bool,
) -> (Vec<usize>, RetypeIndex) {
if loaded.id() == read.id() {
return (fits, index);
}
let index = RetypeIndex::build_near(db, [loaded.clone()], keys, near);
let fits = fits.into_iter().filter(|k| fit(&index, *k)).collect();
(fits, index)
}
/// `face` (read from an installed file and not loaded) loaded into `db` as it was read
/// ([`FontDb::load_read_face`]): neither its file nor the family's other files are read again.
fn load(db: &FontDb, face: &Arc<FontFace>) -> Arc<FontFace> {
db.load_read_face(face.clone())
}
/// A search of the installed fonts made away from its command, so the app can run it off the UI
/// thread with a Cancel. [`RetypeRun::prepare`] takes the selected shapes and the document from the
/// session, checking the params as the command checks them; [`RetypeSearch::run`] picks the loaded
/// faces to compare, compares them and searches the installed fonts on any thread, loading the
/// faces that match; and
/// [`RetypeFound::hand_in`] gives what it found to the command, which then runs with
/// [`RetypeRun::params`] and compares those faces as its own search would, without reading the
/// installed fonts again.
pub struct RetypeRun {
params: Value,
/// The document ([`crate::DocState::uid`]), its content and the selection the search is for.
doc: u64,
content: Arc<Document>,
selection: Vec<NodeId>,
search: Arc<RetypeSearch>,
}
/// What a [`RetypeRun`] compares and searches, without the session: it can be sent to another
/// thread ([`RetypeRun::search`]).
pub struct RetypeSearch {
command: &'static str,
/// The document it is for ([`crate::DocState::uid`]).
doc: u64,
/// The shapes to match, and the loaded faces they are compared with first.
shapes: Vec<Shape>,
faces: Faces,
/// `type.retype`'s tolerance (0 for `type.retypeFonts`).
tolerance: f64,
}
/// The loaded faces a [`RetypeSearch`] compares first.
enum Faces {
/// These faces.
#[cfg(test)]
Given(Vec<Arc<FontFace>>),
/// Those the command picks in `doc`: with `fonts` (`type.retype`'s `fonts` param), the faces of
/// those families and of the document's live type ([`super::candidate_faces`]), and without, the
/// faces `type.retypeFonts` lists ([`super::fonts::listed_faces`]). They are picked on the
/// search's thread, since a family not loaded yet is read from its files.
Of { doc: Arc<Document>, fonts: Option<Vec<String>> },
}
impl Faces {
fn get(&self, db: &FontDb) -> Vec<Arc<FontFace>> {
match self {
#[cfg(test)]
Faces::Given(faces) => faces.clone(),
Faces::Of { doc, fonts: Some(fonts) } => super::candidate_faces(db, doc, fonts),
Faces::Of { doc, fonts: None } => super::fonts::listed_faces(db, doc),
}
}
}
/// A shape a [`RetypeSearch`] compares, as `type.retype` matches it ([`super::shape_parts`]): its
/// path, its contour groups when it may hold several glyphs, its fill rule when it has a visible
/// fill (`Some(nonzero)`), and whether it paints its overlaps once ([`super::paints_once`]).
struct Shape {
path: BezPath,
groups: Vec<BezPath>,
fill: Option<bool>,
once: bool,
}
impl Shape {
/// `path`, matched whole, with no paint check.
fn whole(path: BezPath) -> Self {
Shape { path, groups: vec![], fill: None, once: true }
}
fn sought(&self) -> Sought<'_> {
Sought { path: &self.path, groups: &self.groups, fill: self.fill, once: self.once }
}
}
/// What a [`RetypeSearch`] found: for `type.retype`, the faces it compared first that match, the
/// loaded faces past those that match ([`loaded_rest`]), the installed faces whose glyphs match,
/// loaded, and the loaded faces it compared; and what it read of the installed fonts.
pub struct RetypeFound {
doc: u64,
installed: Installed,
}
impl RetypeFound {
/// Hand it to the next `type.retype` or `type.retypeFonts`, which compares the faces found as
/// its own search of the installed fonts would, in the document the search was made for. Any
/// such command takes it; one in another document compares only what is loaded.
pub fn hand_in(self, s: &mut Session) {
s.retype_hand_off = Some(self);
}
/// Drop what was handed in and no command took, as when the command failed before it took
/// it: a later command searches for itself.
pub fn drop_handed(s: &mut Session) {
s.retype_hand_off = None;
}
/// What it read, as the commands report it.
pub fn json(&self) -> Value {
self.installed.json()
}
}
/// What a search found for the active document of `s`, handed in for this command ([`RetypeFound`]).
/// It is taken whatever the document, so it is used once.
pub(super) fn handed(s: &mut Session) -> Option<Installed> {
let found = s.retype_hand_off.take()?;
let doc = s.doc().ok()?.uid;
(found.doc == doc).then_some(found.installed)
}
impl RetypeRun {
/// The search `command` (`type.retype` or `type.retypeFonts`) with params `p` makes in the
/// active document. None when it reads no installed font: `installed` is false, or no shape
/// starts a search ([`starts`]: each is plain or has no glyph's key). An error where the command fails on its params or on the selection.
/// The faces to compare are picked when the search runs.
pub fn prepare(s: &Session, command: &str, p: &Value) -> Result<Option<RetypeRun>> {
let (command, fonts, tolerance) = match command {
"type.retype" => ("type.retype", Some(super::fonts_param(p)?), super::tolerance_param(p)?),
"type.retypeFonts" => {
super::fonts::count_param(p)?;
("type.retypeFonts", None, 0.0)
}
other => return Err(EngineError::Other(format!("`{other}` doesn't search the installed fonts"))),
};
// The keys the command refuses (an unknown one) fail here too, before any search.
s.check_params(command, p)?;
if !wanted(command, p)? {
return Ok(None);
}
let (pieces, _) = super::selected_pieces(s)?;
let st = s.doc()?;
// Retype compares the shapes that may become type, split as it splits them; the list
// compares every shape whole.
let shapes: Vec<Shape> = if fonts.is_some() {
let mut budget = super::MAX_SPLIT_TOTAL_CONTOURS;
pieces
.into_iter()
.filter(|pc| !pc.keeps_outline)
.map(|pc| Shape {
groups: super::split_groups(&pc.path, &mut budget),
fill: pc.filled.then_some(pc.nonzero),
once: super::paints_once(pc.opacity, pc.blend, &pc.appearance),
path: pc.path,
})
.collect()
} else {
pieces.into_iter().map(|pc| Shape::whole(pc.path)).collect()
};
if !shapes.iter().any(|s| starts(&s.sought(), tolerance)) {
return Ok(None);
}
let faces = Faces::Of { doc: st.doc.clone(), fonts };
Ok(Some(RetypeRun {
params: p.clone(),
doc: st.uid,
content: st.doc.clone(),
selection: st.selection.objects.clone(),
search: Arc::new(RetypeSearch { command, doc: st.uid, shapes, faces, tolerance }),
}))
}
/// `type.retype` or `type.retypeFonts`.
pub fn command(&self) -> &'static str {
self.search.command
}
/// What it compares and searches, for another thread.
pub fn search(&self) -> Arc<RetypeSearch> {
self.search.clone()
}
/// The command's params: those it was prepared with.
pub fn params(&self) -> &Value {
&self.params
}
/// Does it still apply: is the document it was prepared in active, with the same content and
/// the same objects selected?
pub fn current(&self, s: &Session) -> bool {
s.doc().is_ok_and(|st| st.uid == self.doc && Arc::ptr_eq(&st.doc, &self.content) && st.selection.objects == self.selection)
}
/// [`RetypeSearch::run`] with the fonts of `db`.
#[cfg(test)]
fn run_in(&self, db: &FontDb) -> Result<RetypeFound> {
self.search.run_in(db)
}
}
impl RetypeSearch {
/// Compare the shapes with the loaded faces, then search the installed fonts as the command
/// would, loading the faces that match → what it found ([`EngineError::Cancelled`] when a
/// cancel stopped it). It touches no document, so it can run on any thread.
pub fn run(&self) -> Result<RetypeFound> {
self.run_in(FontDb::global())
}
/// [`RetypeSearch::run`] with the fonts of `db`.
fn run_in(&self, db: &FontDb) -> Result<RetypeFound> {
let picked = self.faces.get(db);
let installed = if self.command == "type.retypeFonts" {
let shapes: Vec<&BezPath> = self.shapes.iter().map(|s| &s.path).collect();
let (ranked, mut found) = super::fonts::rank_fonts(db, picked, &shapes, true, None)?;
// The loaded faces that match are handed in too, ahead of the installed ones found:
// loading those can move a loaded face past the 96 the command lists.
let mut faces: Vec<Arc<FontFace>> = ranked.iter().map(|r| r.face().clone()).collect();
for f in std::mem::take(&mut found.faces) {
if !faces.iter().any(|k| k.id() == f.id()) {
faces.push(f);
}
}
found.faces = faces;
found
} else {
// The shapes are matched as the command matches them first.
let tolerance = self.tolerance;
let sought: Vec<Sought> = self.shapes.iter().map(Shape::sought).collect();
let (keys, near) = keys_of(&sought, tolerance);
let index = RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near);
let parts: Vec<Vec<Vec<super::GlyphMatch>>> =
self.shapes.iter().map(|s| super::shape_parts(&s.path, &s.groups, s.fill, s.once, &[&index], tolerance)).collect();
let left: Vec<Sought> = sought.iter().zip(&parts).filter(|(_, p)| p.is_empty()).map(|(s, _)| *s).collect();
// The first faces that match are handed in too: loading the faces found can move one
// past the first 96 the command compares.
let mut first: Vec<Arc<FontFace>> = vec![];
for m in parts.into_iter().flatten().flatten() {
if !first.iter().any(|f| f.id() == m.face.id()) {
first.push(m.face);
}
}
// The loaded faces past the ones compared first, then the installed fonts for what
// none of them matches; the command takes both from what is handed in.
let compared: Vec<u32> = picked.iter().map(|f| f.id()).collect();
// Every face loaded now is compared, among the first ones or with the rest.
let scanned: Vec<u32> = compared.iter().copied().chain(db.loaded_faces().iter().map(|f| f.id())).collect();
// A split shape's glyphs may be spread over the faces compared first and the others.
// Near matching spends an index's comparison budget, so with a tolerance the faces
// compared first are indexed again for each search that has a split shape to look for.
let again = |needed: bool| (needed && tolerance > 0.0).then(|| RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near));
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
let (rest, done, kept) = loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?;
let left: Vec<Sought> = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect();
let fresh = again(left.iter().any(|s| !s.groups.is_empty()));
let kept: Vec<RetypeIndex> = if tolerance > 0.0 {
kept.iter().map(|ix| RetypeIndex::build_near(db, ix.faces().iter().cloned(), &keys, &near)).collect()
} else {
kept
};
let beside: Vec<&RetypeIndex> = std::iter::once(fresh.as_ref().unwrap_or(&index)).chain(&kept).collect();
let mut found = search_beside(db, &left, &beside, tolerance, false)?;
found.faces.splice(0..0, first.into_iter().chain(rest));
found.scanned = scanned;
found
};
Ok(RetypeFound { doc: self.doc, installed })
}
}
#[cfg(test)]
#[path = "retype_installed_tests.rs"]
mod tests;
@@ -0,0 +1,833 @@
use std::collections::BTreeSet;
use std::path::PathBuf;
use kurbo::{Affine, BezPath, Shape};
use serde_json::json;
use vectorcraft_text::FontDb;
use vectorcraft_text::retype::shape_key;
use super::{Limits, search, search_within};
use crate::Session;
/// A database whose installed fonts are copies of the bundled Source Sans 3 Regular named
/// `families`, one file each, in a folder of their own: they are installed and not loaded.
/// Returns the database and the files.
fn installed(tag: &str, families: &[&str]) -> (FontDb, Vec<PathBuf>) {
let dir = vectorcraft_testkit::temp_dir(&format!("retype-installed-{tag}"));
let mut files = vec![];
for family in families {
let postscript = format!("{}-Regular", family.replace(' ', ""));
let data = vectorcraft_text::test_fonts::named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap();
let path = dir.join(format!("{postscript}.ttf"));
std::fs::write(&path, data).unwrap();
files.push(path);
}
(FontDb::with_font_dirs(vec![dir]), files)
}
/// The glyphs of `text` in the bundled Source Sans 3 Regular, as outlines at 30 pt.
fn glyphs(db: &FontDb, text: &str) -> Vec<BezPath> {
let face = db.face("Source Sans 3", "Regular").unwrap();
text.chars()
.enumerate()
.map(|(i, c)| Affine::translate((40.0 + 30.0 * i as f64, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for(c)))
.collect()
}
fn keys(shapes: &[BezPath]) -> BTreeSet<u64> {
shapes.iter().filter_map(shape_key).collect()
}
/// `paths` as a search compares them, each matched whole.
fn whole(paths: Vec<BezPath>) -> Vec<super::Shape> {
paths.into_iter().map(super::Shape::whole).collect()
}
fn unloaded(db: &FontDb, family: &str) -> bool {
db.unloaded_installed_faces().iter().any(|f| f.family == family)
}
#[test]
fn an_installed_face_whose_glyphs_match_is_found_and_loaded() {
let (db, files) = installed("found", &["Retype Copy A"]);
assert!(unloaded(&db, "Retype Copy A"));
let shapes = glyphs(&db, "Rx");
let refs: Vec<&BezPath> = shapes.iter().collect();
let found = search(&db, &refs, false).unwrap();
assert_eq!((found.read, found.skipped), (1, 0));
let face = found.faces.first().expect("the installed copy matches");
assert_eq!((face.family.as_str(), face.style.as_str()), ("Retype Copy A", "Regular"));
assert_eq!(face.path(), Some(files[0].as_path()));
// Loaded now, as it was read.
assert!(db.loaded_faces().iter().any(|f| f.id() == face.id()));
assert!(!unloaded(&db, "Retype Copy A"));
assert_eq!(found.json(), json!({"read": 1, "skipped": 0}));
// A later Retype compares it ahead of the other loaded faces, however many are loaded.
assert_eq!(super::found(&db).first().map(|f| f.id()), Some(face.id()));
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let candidates = super::super::candidate_faces(&db, &s.doc().unwrap().doc, &[]);
assert_eq!(candidates.first().map(|f| f.id()), Some(face.id()));
// Only this database's faces.
assert!(super::found(&FontDb::with_font_dirs(vec![])).is_empty());
}
#[test]
fn a_matching_face_loads_without_the_family_s_other_files() {
let dir = vectorcraft_testkit::temp_dir("retype-installed-family");
for style in ["Regular", "Bold"] {
let data =
vectorcraft_text::test_fonts::named_copy(false, ("Retype Copy N", style, "Version 1.000", &format!("RetypeCopyN-{style}"))).unwrap();
std::fs::write(dir.join(format!("RetypeCopyN-{style}.ttf")), data).unwrap();
}
let db = FontDb::with_font_dirs(vec![dir]);
let shapes = glyphs(&db, "Rx");
let refs: Vec<&BezPath> = shapes.iter().collect();
let found = search(&db, &refs, false).unwrap();
assert_eq!((found.read, found.faces.len()), (1, 1));
let style = found.faces[0].style.clone();
let loaded: Vec<String> = db.loaded_faces().iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style.clone()).collect();
assert_eq!(loaded, std::slice::from_ref(&style), "only the face that matched is loaded");
let left: Vec<String> = db.unloaded_installed_faces().into_iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style).collect();
assert_eq!(left.len(), 1);
assert_ne!(left[0], style);
}
#[test]
fn a_loaded_face_of_the_same_names_counts_only_for_the_shapes_it_matches() {
use vectorcraft_text::test_fonts::named_copy;
let names = ("Retype Twin", "Regular", "Version 1.000", "RetypeTwin-Regular");
let db = FontDb::with_font_dirs(vec![]);
// Inter's glyphs, loaded under the names a file of Source Sans 3's glyphs has too.
db.add_font(named_copy(true, names).unwrap());
let dir = vectorcraft_testkit::temp_dir("retype-installed-twin");
let path = dir.join("RetypeTwin-Regular.ttf");
std::fs::write(&path, named_copy(false, names).unwrap()).unwrap();
let read = db.read_unloaded_file(&path, u64::MAX).faces.into_iter().next().unwrap();
let shapes = glyphs(&db, "Rx");
let refs: Vec<&BezPath> = shapes.iter().collect();
let keys = keys(&shapes);
let loaded = super::load(&db, &read);
assert_ne!(loaded.id(), read.id(), "the face loaded first is kept");
let fit = |ix: &super::super::RetypeIndex, k: usize| !ix.matches(refs[k]).is_empty();
let index = || super::super::RetypeIndex::build_unloaded(&db, read.clone(), &keys);
let (fits, _) = super::still_fit(&db, &read, &loaded, index(), &keys, &[], vec![0, 1], &fit);
assert!(fits.is_empty(), "Inter's R and x are not these");
let (fits, _) = super::still_fit(&db, &read, &read, index(), &keys, &[], vec![0, 1], &fit);
assert_eq!(fits, [0, 1]);
}
#[test]
fn an_installed_face_no_shape_matches_is_read_and_not_loaded() {
let (db, _) = installed("none", &["Retype Copy B"]);
let shapes = [kurbo::Circle::new((40.0, 40.0), 20.0).to_path(0.1)];
let refs: Vec<&BezPath> = shapes.iter().collect();
let found = search(&db, &refs, false).unwrap();
assert_eq!((found.read, found.faces.len()), (1, 0));
assert!(unloaded(&db, "Retype Copy B"), "a face that matches nothing stays unloaded");
// No shape: no file is read.
let none = search(&db, &[], false).unwrap();
assert_eq!((none.read, none.skipped), (0, 0));
}
#[test]
fn plain_shapes_alone_read_no_installed_font() {
// A hyphen is a bar: many fonts have a glyph of its shape, so it tells no font apart.
let (db, _) = installed("plain", &["Retype Copy L"]);
let mut shapes = glyphs(&db, "-");
shapes.push(kurbo::Rect::new(0.0, 0.0, 80.0, 40.0).to_path(0.1));
assert!(shapes.iter().all(vectorcraft_text::retype::is_plain));
let refs: Vec<&BezPath> = shapes.iter().collect();
for every in [false, true] {
let found = search(&db, &refs, every).unwrap();
assert_eq!((found.read, found.skipped, found.faces.len()), (0, 0, 0));
}
assert!(unloaded(&db, "Retype Copy L"));
// Beside a shape that is not plain, the search reads the file for that shape.
shapes.extend(glyphs(&db, "q"));
let refs: Vec<&BezPath> = shapes.iter().collect();
assert_eq!(search(&db, &refs, false).unwrap().faces.len(), 1);
}
#[test]
fn a_shape_without_a_glyph_s_key_does_not_keep_the_search_going() {
let (db, _) = installed("keyless", &["Retype Copy Keyless A", "Retype Copy Keyless B"]);
let mut shapes = glyphs(&db, "k");
// More contours than any glyph's key counts: no face can match it.
let mut dots = BezPath::new();
for i in 0..49 {
dots.extend(kurbo::Circle::new((10.0 * f64::from(i), 300.0), 3.0).path_elements(0.1));
}
assert!(shape_key(&dots).is_none() && !vectorcraft_text::retype::is_plain(&dots));
shapes.push(dots);
let refs: Vec<&BezPath> = shapes.iter().collect();
let found = search(&db, &refs, false).unwrap();
assert_eq!((found.read, found.faces.len()), (1, 1), "the second file is not read");
}
#[test]
fn the_search_stops_once_every_shape_matches_unless_every_face_is_wanted() {
let (db, _) = installed("every", &["Retype Copy C", "Retype Copy D"]);
let shapes = glyphs(&db, "ab");
let refs: Vec<&BezPath> = shapes.iter().collect();
let first = search(&db, &refs, false).unwrap();
assert_eq!((first.read, first.faces.len()), (1, 1), "the second file is not read");
let (db, _) = installed("every-all", &["Retype Copy E", "Retype Copy F"]);
let all = search(&db, &refs, true).unwrap();
assert_eq!((all.read, all.faces.len()), (2, 2));
let mut families: Vec<&str> = all.faces.iter().map(|f| f.family.as_str()).collect();
families.sort_unstable();
assert_eq!(families, ["Retype Copy E", "Retype Copy F"]);
}
#[test]
fn faces_read_are_kept_for_split_shapes_only() {
let (db, _) = installed("kept-whole", &["Retype Kept Whole A", "Retype Kept Whole B", "Retype Kept Whole C"]);
// The k matches in the first file and the circle in none, so every file is read; the later
// files hold the k's glyph without completing a shape. With every shape whole, none is kept.
let mut shapes = glyphs(&db, "k");
shapes.push(kurbo::Circle::new((300.0, 100.0), 7.3).to_path(0.1));
assert!(shape_key(&shapes[1]).is_some(), "the circle has a key to look glyphs up by");
let refs: Vec<&BezPath> = shapes.iter().collect();
super::KEPT_PARTIAL.with(|n| n.set(0));
let found = search(&db, &refs, false).unwrap();
assert_eq!((found.read, found.faces.len()), (3, 1));
assert_eq!(super::KEPT_PARTIAL.with(std::cell::Cell::get), 0, "no face read is kept");
}
#[test]
fn faces_past_the_limits_are_skipped_and_counted() {
let (db, files) = installed("limits", &["Retype Copy G", "Retype Copy H"]);
let shapes = glyphs(&db, "k");
let refs: Vec<&BezPath> = shapes.iter().collect();
let len = files.iter().map(|f| std::fs::metadata(f).unwrap().len()).max().unwrap();
// Files longer than the limit for one file.
let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: usize::MAX, faces: usize::MAX };
let all = |_: &vectorcraft_text::FontFace| true;
let small = search_within(&db, &refs, true, Limits { file: len / 2, ..open }, &all).unwrap();
assert_eq!((small.read, small.skipped, small.faces.len()), (0, 2, 0));
// Bytes for one file only.
let one = search_within(&db, &refs, true, Limits { read: len + len / 2, ..open }, &all).unwrap();
assert_eq!((one.read, one.skipped, one.faces.len()), (1, 1, 1));
// Glyphs for no face.
let (db, _) = installed("limits-glyphs", &["Retype Copy I"]);
let few = search_within(&db, &refs, true, Limits { glyphs: 10, ..open }, &all).unwrap();
assert_eq!((few.read, few.skipped, few.faces.len()), (0, 1, 0));
assert!(unloaded(&db, "Retype Copy I"));
// Faces found up to the cap: the faces after it are not compared, and count as skipped.
let (db, _) = installed("limits-faces", &["Retype Copy O", "Retype Copy P", "Retype Copy Q"]);
let capped = search_within(&db, &refs, true, Limits { faces: 1, ..open }, &all).unwrap();
assert_eq!((capped.read, capped.skipped, capped.faces.len()), (1, 2, 1));
}
#[test]
fn a_file_that_grows_past_the_limits_after_the_listing_is_skipped_and_its_bytes_count() {
let (db, mut files) = installed("grown", &["Retype Copy Y", "Retype Copy Z"]);
let shapes = glyphs(&db, "k");
let refs: Vec<&BezPath> = shapes.iter().collect();
// The order the search reads them in: smallest first.
let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len();
files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b)));
let (first, second) = (len(&files[0]), len(&files[1]));
let grown = files[0].clone();
// The first file grows past the limit for one file as its reading starts, after the listing.
let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| {
if done == 0 {
let mut data = std::fs::read(&grown).unwrap();
data.resize(data.len() + second as usize + 1, 0);
std::fs::write(&grown, data).unwrap();
}
});
// Bytes for both files as listed: the grown file's reading takes one more than the limit for
// one file, which leaves too little for the second.
let limits = Limits { file: second, read: first + second, glyphs: usize::MAX, faces: usize::MAX };
let token = vectorcraft_doc::cancel::CancelToken::new();
let all = |_: &vectorcraft_text::FontFace| true;
let found = vectorcraft_doc::cancel::scope(&token, Some(sink), || search_within(&db, &refs, true, limits, &all)).unwrap();
assert_eq!((found.read, found.skipped, found.faces.len()), (0, 2, 0));
}
#[test]
fn the_glyph_budget_counts_the_glyphs_drawn() {
let (db, files) = installed("glyph-budget", &["Retype Copy Budget"]);
let shapes = glyphs(&db, "k");
let refs: Vec<&BezPath> = shapes.iter().collect();
let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap();
let mapped = face.mapped_chars().len();
let drawn = vectorcraft_text::retype::encoded_glyphs(&face);
assert!(drawn < mapped, "{drawn} of {mapped}");
// A budget below the face's characters and at the glyphs drawn: the face is compared.
let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX };
let found = search_within(&db, &refs, true, open, &|_| true).unwrap();
assert_eq!((found.read, found.skipped, found.faces.len()), (1, 0, 1));
}
#[test]
fn a_run_away_from_the_list_hands_in_the_loaded_faces_that_match_with_the_installed_ones() {
let (db, _) = installed("list-run", &["Retype Copy List"]);
db.add_font(
vectorcraft_text::test_fonts::named_copy(false, ("Retype Loaded List", "Regular", "Version 1.000", "RetypeLoadedList-Regular")).unwrap(),
);
let loaded: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Loaded List").collect();
let search = super::RetypeSearch {
command: "type.retypeFonts",
doc: 1,
shapes: whole(glyphs(&db, "Rx")),
faces: super::Faces::Given(loaded.clone()),
tolerance: 0.0,
};
let found = search.run_in(&db).unwrap();
let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect();
// The loaded face first, then the installed one, each once.
assert_eq!(families, ["Retype Loaded List", "Retype Copy List"]);
assert_eq!((found.installed.read, found.installed.skipped), (1, 0));
}
#[test]
fn faces_a_list_turns_down_are_loaded_and_take_no_place() {
let (db, _) = installed("listed", &["Retype Copy R", "Retype Copy S", "Retype Copy T"]);
let shapes = glyphs(&db, "k");
let refs: Vec<&BezPath> = shapes.iter().collect();
// Two places, and the first face found is turned down: the next two are listed.
let found = super::search_listed(&db, &refs, 2, &|f| f.family != "Retype Copy R").unwrap();
let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
families.sort_unstable();
assert_eq!(families, ["Retype Copy S", "Retype Copy T"]);
assert_eq!((found.read, found.skipped), (3, 0));
assert!(!unloaded(&db, "Retype Copy R"), "the face turned down was loaded");
// Only the faces listed are compared ahead of the other loaded faces later.
let ahead: Vec<String> = super::found(&db).iter().map(|f| f.family.clone()).collect();
assert!(ahead.iter().any(|f| f == "Retype Copy S") && !ahead.iter().any(|f| f == "Retype Copy R"), "{ahead:?}");
}
#[test]
fn a_cancel_stops_the_search_between_files() {
let (db, _) = installed("cancel-between", &["Retype Copy U", "Retype Copy V", "Retype Copy W"]);
let shapes = glyphs(&db, "k");
let refs: Vec<&BezPath> = shapes.iter().collect();
let token = vectorcraft_doc::cancel::CancelToken::new();
let stop = token.clone();
// The cancel comes as the second file starts: it is read, the third is not.
let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| {
if done == 1 {
stop.cancel();
}
});
let r = vectorcraft_doc::cancel::scope(&token, Some(sink), || search(&db, &refs, true));
assert!(matches!(r, Err(crate::EngineError::Cancelled)));
let left = ["Retype Copy U", "Retype Copy V", "Retype Copy W"].iter().filter(|f| unloaded(&db, f)).count();
assert_eq!(left, 1, "two files were read and loaded, the third was not");
}
#[test]
fn a_run_away_from_the_command_loads_the_faces_it_finds() {
let (db, _) = installed("run", &["Retype Copy X"]);
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let ids: Vec<u64> =
glyphs(&db, "Wk").iter().map(|p| s.execute("path.create", &json!({"d": p.to_svg()})).unwrap()["id"].as_u64().unwrap()).collect();
s.execute("select.set", &json!({"ids": ids})).unwrap();
// Off: nothing to run.
for cmd in ["type.retype", "type.retypeFonts"] {
assert!(super::RetypeRun::prepare(&s, cmd, &json!({"installed": false})).unwrap().is_none());
}
// The command's params are checked as it checks them.
assert!(super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 0})).is_err());
assert!(super::RetypeRun::prepare(&s, "type.retype", &json!({"fonts": 1})).is_err());
assert!(super::RetypeRun::prepare(&s, "type.text", &json!({})).is_err());
// An unknown key fails before any search, as the command fails on it.
for cmd in ["type.retype", "type.retypeFonts"] {
let e = super::RetypeRun::prepare(&s, cmd, &json!({"typo": true})).err().map(|e| e.to_string()).unwrap_or_default();
assert!(e.contains("typo"), "{cmd}: {e}");
assert!(s.execute(cmd, &json!({"typo": true})).is_err());
}
// Retype: the loaded Source Sans 3 matches both shapes, so no installed file is read.
let run = super::RetypeRun::prepare(&s, "type.retype", &json!({})).unwrap().unwrap();
assert_eq!(run.command(), "type.retype");
assert_eq!(run.params(), &json!({}));
assert_eq!(run.run_in(&db).unwrap().json(), json!({"read": 0, "skipped": 0}));
assert!(unloaded(&db, "Retype Copy X"));
// The list compares every installed face: the copy is read and loaded.
let run = super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 5})).unwrap().unwrap();
assert_eq!(run.params(), &json!({"count": 5}));
assert!(run.current(&s));
let found = run.run_in(&db).unwrap();
assert_eq!(found.json(), json!({"read": 1, "skipped": 0}));
// The loaded faces that match are handed in with it, ahead of it.
let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families.last(), Some(&"Retype Copy X"), "{families:?}");
assert_eq!(families.iter().filter(|f| **f == "Retype Copy X").count(), 1, "{families:?}");
assert!(families.contains(&"Source Sans 3"), "{families:?}");
assert!(!unloaded(&db, "Retype Copy X"));
// A change of selection or content: it no longer applies.
s.execute("select.set", &json!({"ids": [ids[0]]})).unwrap();
assert!(!run.current(&s));
s.execute("select.set", &json!({"ids": ids})).unwrap();
assert!(run.current(&s));
s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap();
assert!(!run.current(&s));
}
#[test]
fn plain_shapes_alone_start_no_run_away_from_the_command() {
// A rectangle and a bar are plain: the search reads no installed font for them, so the
// command runs at once.
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap();
let bar = s.execute("shape.rectangle", &json!({"x": 10, "y": 100, "width": 4, "height": 60})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [rect, bar]})).unwrap();
for (cmd, p) in [("type.retype", json!({})), ("type.retype", json!({"tolerance": 0.05})), ("type.retypeFonts", json!({}))] {
assert!(super::RetypeRun::prepare(&s, cmd, &p).unwrap().is_none(), "{cmd} {p}");
}
}
#[test]
fn what_a_search_found_is_handed_to_the_next_command_in_its_document() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let uid = s.doc().unwrap().uid;
let handed = |doc| super::RetypeFound { doc, installed: super::Installed { read: 7, skipped: 3, ..Default::default() } };
// Taken instead of a search of the installed fonts, also with installed false.
handed(uid).hand_in(&mut s);
let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap();
assert_eq!(r["installed"], json!({"read": 7, "skipped": 3}), "{r}");
// Used once.
let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap();
assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}");
// Another document's is dropped.
handed(uid + 1).hand_in(&mut s);
let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap();
assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}");
assert!(s.retype_hand_off.is_none(), "taken");
// Retype takes it too, whether or not a loaded font matches the rectangle.
handed(uid).hand_in(&mut s);
let _ = s.execute("type.retype", &json!({"installed": false}));
assert!(s.retype_hand_off.is_none());
}
#[test]
fn a_canceled_search_stops_before_reading_a_file() {
let (db, _) = installed("cancel", &["Retype Copy J"]);
let shapes = glyphs(&db, "z");
let refs: Vec<&BezPath> = shapes.iter().collect();
let token = vectorcraft_doc::cancel::CancelToken::new();
token.cancel();
let r = vectorcraft_doc::cancel::scope(&token, None, || search(&db, &refs, false));
assert!(matches!(r, Err(crate::EngineError::Cancelled)));
assert!(unloaded(&db, "Retype Copy J"), "nothing was loaded");
}
/// The shapes of `text` set in Source Sans 3 and outlined, as `type.retype` collects them.
fn pieces(text: &str) -> Vec<super::super::Piece> {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let id =
s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 30, "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let group = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let d = &s.doc().unwrap().doc;
let node = d.node(vectorcraft_doc::NodeId(group)).unwrap();
let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]);
super::super::collect(node, None, 0, &mut barrier, &mut truncated, &mut pieces);
pieces
}
#[test]
fn retype_fills_the_shapes_no_loaded_font_matches_from_the_installed_fonts() {
let (db, _) = installed("retype", &["Retype Copy K"]);
let pieces = pieces("Wk-");
assert_eq!(pieces.len(), 3);
let groups = vec![vec![]; pieces.len()];
// The first shape is taken as matched already: the others are looked for.
let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()]));
let found = super::super::match_pieces(&pieces, &groups, &[&keep], 0.0);
assert!(!found[0].is_empty() && found[1].is_empty() && found[2].is_empty());
let left = super::super::left_shapes(&pieces, &groups, &found);
assert_eq!(left.len(), 2);
let installed = super::search_for(&db, &left, 0.0, false).unwrap();
assert_eq!(installed.read, 1);
// The faces found join the index, and every shape is matched again.
let all_keys = keys(&pieces.iter().map(|pc| pc.path.clone()).collect::<Vec<_>>());
let extra = super::super::RetypeIndex::build(&db, installed.faces.iter().cloned(), &all_keys);
let found = super::super::match_pieces(&pieces, &groups, &[&keep, &extra], 0.0);
let whole = |k: usize| found[k].first().expect("one part").clone();
assert_eq!(whole(0).first().map(|m| m.face.family.as_str()), Some("Source Sans 3"), "a matched shape keeps its match");
// and gets the face found too, so its line can be set in the face the others match.
assert!(whole(0).iter().any(|m| m.face.family == "Retype Copy K" && m.ch == 'W'), "the W also matches the face found");
let k = whole(1);
let m = k.first().expect("the installed copy matches the k");
assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", 'k'));
assert!(db.loaded_faces().iter().any(|f| f.id() == m.face.id()), "the match is in a loaded face");
// The hyphen, a plain shape, matches the font the k found.
let hyphen = whole(2);
let m = hyphen.first().expect("the installed copy matches the hyphen");
assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", '-'));
}
/// `path` flattened into lines `tol` from its curves, each contour started at its second point
/// and run backwards: an outline built nothing like the font's.
fn simplified(path: &BezPath, tol: f64) -> BezPath {
let mut contours: Vec<Vec<kurbo::Point>> = vec![];
kurbo::flatten(path.iter(), tol, |el| match el {
kurbo::PathEl::MoveTo(q) => contours.push(vec![q]),
kurbo::PathEl::LineTo(q) => contours.last_mut().unwrap().push(q),
_ => {}
});
let mut out = BezPath::new();
for mut c in contours {
if c.len() > 1 && c.first() == c.last() {
c.pop();
}
c.rotate_left(1);
c.reverse();
out.move_to(c[0]);
for q in &c[1..] {
out.line_to(*q);
}
out.close_path();
}
out
}
#[test]
fn an_installed_face_is_found_through_the_glyphs_of_a_split_shape_and_through_near_matches() {
// A word outlined as one compound path: the whole shape is no glyph, and its glyphs are.
let (db, _) = installed("split", &["Retype Copy Split"]);
let mut word = BezPath::new();
for g in glyphs(&db, "Wk") {
word.extend(g.iter());
}
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
let groups = super::super::split_groups(&word, &mut budget);
assert_eq!(groups.len(), 2);
let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap();
assert_eq!(found.read, 1);
let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families, ["Retype Copy Split"], "the face the split's glyphs match is found");
assert!(!unloaded(&db, "Retype Copy Split"));
// A simplified outline: no installed glyph matches it exactly, and one does within a tolerance.
let (db, _) = installed("near", &["Retype Copy Near"]);
let r = simplified(&glyphs(&db, "R")[0], 0.05);
let shape = [super::Sought::unpainted(&r, &[])];
let exact = super::search_for(&db, &shape, 0.0, false).unwrap();
assert_eq!((exact.read, exact.faces.len()), (1, 0));
assert!(unloaded(&db, "Retype Copy Near"));
let near = super::search_for(&db, &shape, 0.02, false).unwrap();
let families: Vec<&str> = near.faces.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families, ["Retype Copy Near"], "the face the outline nearly matches is found");
assert!(!unloaded(&db, "Retype Copy Near"));
}
#[test]
fn a_split_shape_whose_glyphs_are_in_different_installed_faces_finds_them_all() {
// A W of Source Sans 3 and a k of Inter, outlined as one compound path, with a copy of each
// font installed: neither face holds both glyphs.
let dir = vectorcraft_testkit::temp_dir("retype-installed-split-two");
for (inter, family) in [(false, "Retype Mix S"), (true, "Retype Mix I")] {
let postscript = format!("{}-Regular", family.replace(' ', ""));
let data = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", "Version 1.000", &postscript)).unwrap();
std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap();
}
let db = FontDb::with_font_dirs(vec![dir]);
let mut word = BezPath::new();
word.extend(glyphs(&db, "W")[0].iter());
let inter = db.face("Inter", "Regular").unwrap();
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
word.extend(k.iter());
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
let groups = super::super::split_groups(&word, &mut budget);
assert_eq!(groups.len(), 2);
let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap();
assert_eq!(found.read, 2);
let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
families.sort_unstable();
assert_eq!(families, ["Retype Mix I", "Retype Mix S"], "the faces of both glyphs are found");
assert!(!unloaded(&db, "Retype Mix S") && !unloaded(&db, "Retype Mix I"));
}
#[test]
fn a_split_shape_completes_with_the_loaded_faces_it_is_searched_beside() {
// A W of Source Sans 3 and a k of Inter, outlined as one compound path. Source Sans 3 is the
// loaded face compared first; the only other face is an installed copy of Inter.
let dir = vectorcraft_testkit::temp_dir("retype-installed-beside");
let data = vectorcraft_text::test_fonts::named_copy(true, ("Retype Beside I", "Regular", "Version 1.000", "RetypeBesideI-Regular")).unwrap();
std::fs::write(dir.join("RetypeBesideI-Regular.ttf"), data).unwrap();
let db = FontDb::with_font_dirs(vec![dir]);
let mut word = BezPath::new();
word.extend(glyphs(&db, "W")[0].iter());
let inter = db.face("Inter", "Regular").unwrap();
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
word.extend(k.iter());
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
let groups = super::super::split_groups(&word, &mut budget);
assert_eq!(groups.len(), 2);
let shapes = [super::Sought::unpainted(&word, &groups)];
let (keys, near) = super::keys_of(&shapes, 0.0);
let first = super::super::RetypeIndex::build_near(&db, db.face("Source Sans 3", "Regular"), &keys, &near);
let found = super::search_beside(&db, &shapes, &[&first], 0.0, false).unwrap();
let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families, ["Source Sans 3", "Retype Beside I"], "the installed face completes the loaded face's glyphs");
}
#[test]
fn one_loaded_face_per_glyph_completes_a_split_shape_however_many_hold_it() {
// A W of Source Sans 3 and a k of Inter in one compound path. More loaded copies of Source
// Sans 3 than a search finds faces hold the W; an installed copy of Inter holds the k.
let n = vectorcraft_text::retype::MAX_FACES + 4;
let dir = vectorcraft_testkit::temp_dir("retype-installed-many");
let data = vectorcraft_text::test_fonts::named_copy(true, ("Retype Many I", "Regular", "Version 1.000", "RetypeManyI-Regular")).unwrap();
std::fs::write(dir.join("RetypeManyI-Regular.ttf"), data).unwrap();
let db = FontDb::with_font_dirs(vec![dir]);
for i in 0..n {
let family = format!("Retype Many {i}");
db.add_font(
vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("RetypeMany{i}-Regular"))).unwrap(),
);
}
let mut word = BezPath::new();
word.extend(glyphs(&db, "W")[0].iter());
let inter = db.face("Inter", "Regular").unwrap();
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
word.extend(k.iter());
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
let groups = super::super::split_groups(&word, &mut budget);
let shapes = [super::Sought::unpainted(&word, &groups)];
let (keys, near) = super::keys_of(&shapes, 0.0);
let copies: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Many ")).collect();
assert_eq!(copies.len(), n);
let indexes: Vec<super::super::RetypeIndex> = copies
.chunks(vectorcraft_text::retype::MAX_FACES)
.map(|g| super::super::RetypeIndex::build_near(&db, g.iter().cloned(), &keys, &near))
.collect();
let beside: Vec<&super::super::RetypeIndex> = indexes.iter().collect();
let found = super::search_beside(&db, &shapes, &beside, 0.0, false).unwrap();
let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families.len(), 2, "{families:?}");
assert_eq!(families.last(), Some(&"Retype Many I"));
}
#[test]
fn a_split_shape_completes_with_loaded_faces_past_the_first_and_installed_ones() {
// A W of Source Sans 3 and a k of Inter in one compound path. Past the faces compared first
// (the bundled ones), a loaded copy of Inter holds the k and an installed copy of Source Sans 3
// the W.
let dir = vectorcraft_testkit::temp_dir("retype-installed-kept");
let data = vectorcraft_text::test_fonts::named_copy(false, ("Retype Kept S", "Regular", "Version 1.000", "RetypeKeptS-Regular")).unwrap();
std::fs::write(dir.join("RetypeKeptS-Regular.ttf"), data).unwrap();
let db = FontDb::with_font_dirs(vec![dir]);
let compared: Vec<u32> = db.loaded_faces().iter().map(|f| f.id()).collect();
db.add_font(vectorcraft_text::test_fonts::named_copy(true, ("Retype Kept I", "Regular", "Version 1.000", "RetypeKeptI-Regular")).unwrap());
let mut word = BezPath::new();
word.extend(glyphs(&db, "W")[0].iter());
let inter = db.face("Inter", "Regular").unwrap();
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
word.extend(k.iter());
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
let groups = super::super::split_groups(&word, &mut budget);
assert_eq!(groups.len(), 2);
let shapes = [super::Sought::unpainted(&word, &groups)];
let (rest, done, kept) = super::loaded_rest_for(&db, &shapes, &[], 0.0, &compared).unwrap();
assert!(rest.is_empty() && done == [false]);
assert_eq!(kept.len(), 1, "the group with the k is kept for the installed fonts");
let beside: Vec<&super::super::RetypeIndex> = kept.iter().collect();
let found = super::search_beside(&db, &shapes, &beside, 0.0, false).unwrap();
let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families, ["Retype Kept I", "Retype Kept S"], "the loaded copy's k and the installed copy's W");
}
#[test]
fn an_installed_face_whose_glyphs_paint_otherwise_than_the_shape_is_not_found() {
// Two o's moved onto each other in one compound path filled by the even-odd rule: the overlap
// is unpainted, and two glyphs set side by side would paint it.
let paths = |db: &FontDb| {
let face = db.face("Source Sans 3", "Regular").unwrap();
let o = Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('o'));
let mut word = BezPath::new();
for x in [40.0, 49.0] {
word.extend((Affine::translate((x, 100.0)) * o.clone()).iter());
}
word
};
let (db, _) = installed("paint", &["Retype Copy Paint"]);
let word = paths(&db);
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
let groups = super::super::split_groups(&word, &mut budget);
assert_eq!(groups.len(), 2);
let even_odd = super::Sought { path: &word, groups: &groups, fill: Some(false), once: true };
let found = super::search_for(&db, &[even_odd], 0.0, false).unwrap();
assert_eq!((found.read, found.faces.len()), (1, 0), "the o's paint the overlap");
assert!(unloaded(&db, "Retype Copy Paint"));
// Without a fill to compare, the same glyphs are found.
let (db, _) = installed("paint-none", &["Retype Copy Unpainted"]);
let word = paths(&db);
let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap();
assert_eq!(found.faces.len(), 1);
}
#[test]
fn retype_reads_no_installed_font_for_plain_shapes_alone() {
let (db, _) = installed("retype-plain", &["Retype Copy M"]);
let pieces = pieces("W-");
let groups = vec![vec![]; pieces.len()];
let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()]));
let found = super::super::match_pieces(&pieces, &groups, &[&keep], 0.0);
let left = super::super::left_shapes(&pieces, &groups, &found);
assert_eq!(left.len(), 1, "the hyphen is left");
let installed = super::search_for(&db, &left, 0.0, false).unwrap();
assert_eq!((installed.read, installed.faces.len()), (0, 0));
assert!(unloaded(&db, "Retype Copy M"));
}
#[test]
fn installed_must_be_a_bool_or_null() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
for cmd in ["type.retype", "type.retypeFonts"] {
for bad in [json!(1), json!("yes"), json!([])] {
let e = s.execute(cmd, &json!({"installed": bad})).unwrap_err().to_string();
assert!(e.contains("`installed` must be true, false or null"), "{cmd} {bad}: {e}");
}
}
// false: no installed font is read, and the result says so.
let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap();
assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}");
}
/// A database with no installed fonts and `n` copies of the bundled Source Sans 3 Regular loaded,
/// named `{tag} 0` to `{tag} n-1`, after `inter` copies of Inter named `{tag} Inter 0` and on.
fn loaded_copies(tag: &str, inter: usize, n: usize) -> FontDb {
let db = FontDb::with_font_dirs(vec![]);
let copies = (0..inter).map(|i| (true, format!("{tag} Inter {i}"))).chain((0..n).map(|i| (false, format!("{tag} {i}"))));
for (inter, family) in copies {
let postscript = format!("{}-Regular", family.replace(' ', ""));
db.add_font(vectorcraft_text::test_fonts::named_copy(inter, (&family, "Regular", "Version 1.000", &postscript)).unwrap());
}
db
}
#[test]
fn loaded_faces_past_the_ones_compared_first_are_compared_too() {
let n = vectorcraft_text::retype::MAX_FACES + 4;
let db = loaded_copies("Retype Rest", 0, n);
let shapes = glyphs(&db, "Rx");
let refs: Vec<&BezPath> = shapes.iter().collect();
// Every loaded face that matches, more than one index takes.
let rest = super::loaded_rest(&db, &refs, &[]).unwrap();
for i in 0..n {
assert!(rest.iter().any(|f| f.family == format!("Retype Rest {i}")), "copy {i} of {}", rest.len());
}
// The faces compared already are left out.
let last = format!("Retype Rest {}", n - 1);
let compared: Vec<u32> = db.loaded_faces().iter().filter(|f| f.family != last).map(|f| f.id()).collect();
let rest = super::loaded_rest(&db, &refs, &compared).unwrap();
assert_eq!(rest.iter().map(|f| f.family.as_str()).collect::<Vec<_>>(), [last.as_str()]);
// A plain shape alone compares none.
let bar = [kurbo::Rect::new(0.0, 0.0, 80.0, 10.0).to_path(0.1)];
assert!(super::loaded_rest(&db, &[&bar[0]], &[]).unwrap().is_empty());
}
#[test]
fn a_split_shape_completes_with_loaded_faces_past_the_ones_compared_first() {
// A W of Source Sans 3 and a k of Inter in one compound path. Source Sans 3 and Inter are
// compared first; past them, a loaded copy of Inter holds the k.
let db = loaded_copies("Retype Rest Split", 1, 0);
let mut word = BezPath::new();
word.extend(glyphs(&db, "W")[0].iter());
let inter = db.face("Inter", "Regular").unwrap();
let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k'));
word.extend(k.iter());
let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS;
let groups = super::super::split_groups(&word, &mut budget);
assert_eq!(groups.len(), 2);
let shapes = [super::Sought::unpainted(&word, &groups)];
let (keys, near) = super::keys_of(&shapes, 0.0);
let source = db.face("Source Sans 3", "Regular").unwrap();
let compared = [source.id(), inter.id()];
let first = super::super::RetypeIndex::build_near(&db, [source], &keys, &near);
let (rest, done, kept) = super::loaded_rest_for(&db, &shapes, &[&first], 0.0, &compared).unwrap();
assert!(kept.is_empty(), "no split shape is left");
let families: Vec<&str> = rest.iter().map(|f| f.family.as_str()).collect();
assert_eq!(families, ["Retype Rest Split Inter 0"], "the copy completes the glyphs of the face compared first");
assert_eq!(done, [true]);
}
#[test]
fn files_past_the_glyph_budget_are_skipped_without_being_read() {
let (db, mut files) = installed("budget-spent", &["Retype Copy E1", "Retype Copy E2"]);
let shapes = glyphs(&db, "k");
let refs: Vec<&BezPath> = shapes.iter().collect();
// The order the search reads them in: smallest first.
let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len();
files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b)));
assert_eq!(db.unloaded_installed_faces().len(), 2);
let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap();
let drawn = vectorcraft_text::retype::encoded_glyphs(&face);
// The second file holds no font after the listing: had it been read, it would give no face
// to skip.
std::fs::write(&files[1], vec![0u8; len(&files[1]) as usize]).unwrap();
let limits = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX };
let found = search_within(&db, &refs, true, limits, &|_| true).unwrap();
assert_eq!((found.read, found.skipped, found.faces.len()), (1, 1, 1));
}
#[test]
fn a_run_away_from_the_command_hands_in_the_loaded_faces_past_the_ones_compared_first() {
let db = loaded_copies("Retype Run Rest", vectorcraft_text::retype::MAX_FACES, 1);
let shapes = glyphs(&db, "Rx");
// The Inter copies are compared first: none matches, and the copy loaded after them does.
let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Run Rest Inter")).collect();
assert_eq!(faces.len(), vectorcraft_text::retype::MAX_FACES);
let search =
super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes.clone()), faces: super::Faces::Given(faces), tolerance: 0.0 };
let found = search.run_in(&db).unwrap();
assert!(found.installed.faces.iter().any(|f| f.family == "Retype Run Rest 0"), "the loaded copy is handed in");
assert_eq!((found.installed.read, found.installed.skipped), (0, 0), "no installed file is read for it");
// Every loaded face was compared: the command does not compare them again.
assert!(db.loaded_faces().iter().all(|f| found.installed.scanned.contains(&f.id())));
// A face compared first that matches is handed in too, as loading others may move it past
// the faces the command compares first.
let copy: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Run Rest 0").collect();
let found = super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes), faces: super::Faces::Given(copy), tolerance: 0.0 }
.run_in(&db)
.unwrap();
assert_eq!(found.installed.faces.first().map(|f| f.family.as_str()), Some("Retype Run Rest 0"));
}
#[test]
fn a_full_list_counts_skipped_installed_faces_only_when_a_shape_would_start_a_search() {
let (db, _) = installed("full-list", &["Retype Copy Full"]);
for i in 0..super::super::fonts::MAX_COUNT {
let family = format!("Retype Full {i}");
let postscript = format!("RetypeFull{i}-Regular");
db.add_font(vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &postscript)).unwrap());
}
let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Full ")).collect();
// A hyphen is plain: it fills the list and would start no search, so nothing is skipped.
let hyphen = glyphs(&db, "-");
let refs: Vec<&BezPath> = hyphen.iter().collect();
let (ranked, found) = super::super::fonts::rank_fonts(&db, faces.clone(), &refs, true, None).unwrap();
assert_eq!(ranked.len(), super::super::fonts::MAX_COUNT);
assert_eq!((found.read, found.skipped), (0, 0));
// A shape that is not plain would: the installed face counts as skipped.
let shapes = glyphs(&db, "-q");
let refs: Vec<&BezPath> = shapes.iter().collect();
let (_, found) = super::super::fonts::rank_fonts(&db, faces, &refs, true, None).unwrap();
assert_eq!((found.read, found.skipped), (0, 1));
assert!(unloaded(&db, "Retype Copy Full"));
}
#[test]
fn what_is_handed_in_and_not_taken_can_be_dropped() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let doc = s.doc().unwrap().uid;
super::RetypeFound { doc, installed: super::Installed::default() }.hand_in(&mut s);
assert!(s.retype_hand_off.is_some());
super::RetypeFound::drop_handed(&mut s);
assert!(s.retype_hand_off.is_none());
}
+33 -19
View File
@@ -123,11 +123,13 @@ fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() {
#[test]
fn a_combining_mark_starts_no_line() {
// A combining mark on its own (a drawn dot, bar or ring is the same shape) stays an outline.
// The calls that leave a shape an outline leave the installed fonts out, so what this machine
// has installed does not change the result.
let mut s = session();
let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string();
assert!(e.contains("no selected shape matches"), "{e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
// A shape that is both a mark (tilde below) and a character (small tilde) starts its line as
@@ -145,7 +147,7 @@ fn a_combining_mark_starts_no_line() {
let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "\u{312}ab", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[0].id.0;
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
assert_eq!(r["texts"], json!(["ab"]), "{r}");
assert_eq!(r["unmatched"], json!([mark]));
// After a base, the mark is retyped with it.
@@ -160,7 +162,7 @@ fn a_combining_mark_starts_no_line() {
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yz"]), &json!([mark])), "{r}");
// A mark that is also another character (dot below, dot above) becomes that character there.
let g = outlined(&mut s, json!({"x": 300, "y": 120, "text": "x\u{323}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
@@ -183,7 +185,7 @@ fn a_combining_mark_starts_no_line() {
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yzw"]), &json!([mark])), "{r}");
assert_eq!(r["fonts"][1]["tracking"], json!(50.0), "{r}");
// A one-contour glyph after a mark that stays an outline (a bar, then a dot) is alone, and
@@ -193,7 +195,7 @@ fn a_combining_mark_starts_no_line() {
pair.sort_unstable();
let word = outlined(&mut s, json!({"x": 40, "y": 380, "text": "ab", "size": 40, "font": "Source Sans 3", "style": "Regular"}));
s.execute("select.set", &json!({"ids": [dot, word]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
assert_eq!(r["texts"], json!(["ab"]), "{r}");
let mut left: Vec<u64> = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
left.sort_unstable();
@@ -246,7 +248,8 @@ fn marks_first_after_a_split_leave_other_lines_their_tracking() {
s.execute("select.set", &json!({"ids": moved})).unwrap();
s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap();
s.execute("select.set", &json!({"ids": [marks, tracked]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
// The installed fonts left out: what this machine has installed does not change the result.
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
let texts = r["texts"].as_array().unwrap();
let at = texts.iter().position(|t| t == "yzw").unwrap_or_else(|| panic!("yzw in {r}"));
assert_eq!(r["fonts"][at]["tracking"], json!(50.0), "{r}");
@@ -374,7 +377,7 @@ fn an_open_path_along_a_glyph_is_not_a_glyph() {
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
assert!(s.execute("type.retype", &json!({})).is_err(), "nothing matches");
assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nothing matches");
}
#[test]
@@ -488,7 +491,8 @@ fn a_glyph_painted_beyond_what_type_takes_stays_an_outline() {
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
// The installed fonts left out: what this machine has installed does not change the result.
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
assert_eq!(r["texts"], json!(["B"]), "two fills: A stays an outline: {r}");
assert_eq!(r["unmatched"], json!([a]));
}
@@ -551,7 +555,8 @@ fn a_drawn_dot_or_bar_beside_type_stays_art() {
// A bar that is exactly a hyphen of the font, somewhere else: the worst case.
let bar = outlined(&mut s, json!({"x": 200, "y": 300, "text": "-", "size": 50}));
s.execute("select.set", &json!({"ids": [g, dot, bar]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
// The installed fonts left out: what this machine has installed does not change the result.
let r = s.execute("type.retype", &json!({"installed": false})).unwrap();
assert_eq!(r["texts"], json!(["AB"]), "{r}");
let un = r["unmatched"].as_array().unwrap();
assert!(un.contains(&json!(dot)) && un.len() == 2, "the dot and the bar stay art: {r}");
@@ -754,7 +759,8 @@ fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() {
simplify_every_path(&mut s, 0.05);
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
// The installed fonts left out: what this machine has installed does not change the result.
let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string();
assert!(e.contains("no selected shape matches"), "no exact match: {e}");
for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true), json!(null)] {
let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string();
@@ -825,8 +831,9 @@ fn two_overlapping_lone_glyphs_beside_art_stay_outlines() {
let b = outlined(&mut s, json!({"x": 49, "y": 100, "text": "M", "size": 30}));
let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b, dot]})).unwrap();
// Nothing is left to retype: both stay outlines, as the lone bar beside art does.
let e = s.execute("type.retype", &json!({})).unwrap_err();
// Nothing is left to retype: both stay outlines, as the lone bar beside art does. The installed
// fonts are left out, so what this machine has installed does not change the result.
let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err();
assert!(format!("{e:?}").contains("no selected shape matches"), "{e:?}");
}
@@ -1363,7 +1370,8 @@ fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() {
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = match s.execute("type.retype", &json!({})) {
// The installed fonts left out: what this machine has installed does not change the result.
let e = match s.execute("type.retype", &json!({"installed": false})) {
Ok(r) => panic!("the period became type: {r}"),
Err(e) => e.to_string(),
};
@@ -1423,7 +1431,8 @@ fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() {
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = s.execute("type.retype", &json!({})).unwrap_err().to_string();
// The installed fonts left out: what this machine has installed does not change the result.
let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string();
assert!(e.contains("(1 checked)"), "reported once: {e}");
assert!(s.doc().unwrap().doc == before, "nothing changes");
}
@@ -1440,7 +1449,8 @@ fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() {
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = match s.execute("type.retype", &json!({})) {
// The installed fonts left out: what this machine has installed does not change the result.
let e = match s.execute("type.retype", &json!({"installed": false})) {
Ok(r) => panic!("the overlapping o's became type: {r}"),
Err(e) => e.to_string(),
};
@@ -1481,7 +1491,8 @@ fn a_translucent_compound_whose_glyphs_overlap_stays_an_outline() {
})
.unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({}));
// The installed fonts left out: what this machine has installed does not change the result.
let r = s.execute("type.retype", &json!({"installed": false}));
if opacity == 1.0 {
let r = r.unwrap();
assert_eq!(r["texts"], json!(["i", "i"]), "opaque, the two lines become type: {r}");
@@ -1502,8 +1513,9 @@ fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() {
s.execute("select.set", &json!({"ids": kids})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
// The installed fonts left out: what this machine has installed does not change the result.
for tolerance in [0.0, 0.05] {
if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance})) {
if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance, "installed": false})) {
panic!("the overlapping o's became type at dx {dx}, tolerance {tolerance}: {r}");
}
}
@@ -1564,7 +1576,8 @@ fn a_glyph_with_only_some_contours_turned_in_an_even_odd_compound_still_becomes_
})
.unwrap();
s.execute("select.set", &json!({"ids": [c]})).unwrap();
assert!(s.execute("type.retype", &json!({})).is_err(), "nonzero, contour {turned} turned paints the counter");
// The installed fonts left out: what this machine has installed does not change the result.
assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nonzero, contour {turned} turned paints the counter");
s.execute("path.setFillRule", &json!({"rule": "evenOdd", "ids": [c]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
assert_eq!(r["texts"], json!(["do"]), "contour {turned} turned: {r}");
@@ -1591,7 +1604,8 @@ fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() {
let r = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [c, r]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let e = match s.execute("type.retype", &json!({})) {
// The installed fonts left out: what this machine has installed does not change the result.
let e = match s.execute("type.retype", &json!({"installed": false})) {
Ok(r) => panic!("the A became type without its period: {r}"),
Err(e) => e.to_string(),
};
+321 -15
View File
@@ -90,6 +90,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
list_installed
),
cmd!(
query "script.startup.run",
"Run Startup Scripts",
[],
None,
"{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays; included files are read again when the chosen run starts; a preflight compilation failure clears the previous script report; each app queue pump processes at most one startup entry",
always,
startup_run
),
cmd!(
query "script.grants",
"List Script File Permissions",
@@ -104,7 +113,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Revoke Script File Permissions",
[],
None,
"{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}",
"{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as given, as script.grants lists it, or after its links are followed when no grant holds it as given (a path outside the automation read roots is matched as given only); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}",
always,
grants_revoke
),
@@ -149,6 +158,21 @@ const NOT_TEXT: &str = "the script is not UTF-8 text";
pub const TOO_LARGE: &str = "the script is too large to run";
fn run(s: &mut Session, p: &Value) -> Result<Value> {
let request = prepare(s, p)?;
run_prepared(s, request)
}
fn run_prepared(s: &mut Session, request: script::Request) -> Result<Value> {
let name = s.script_start(request)?;
if s.script_frames {
return Ok(json!({"running": true, "name": name}));
}
s.script_run_to_end()
}
/// The run `script.run`'s parameters `p` ask for, with its file read and checked, or the error that
/// keeps it from starting.
fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
let optional_str = |key: &str| match p.get(key) {
None => Ok(None),
Some(Value::String(t)) => Ok(Some(t.as_str())),
@@ -207,7 +231,7 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
};
let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string());
let locale = script::dollar::ui_locale(s.ui_language.as_deref().unwrap_or(&s.prefs.interface_language));
let request = script::Request {
Ok(script::Request {
name,
name_given: given_name.is_some(),
file: path.map(str::to_string),
@@ -217,12 +241,7 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {
fuel,
locale,
answers,
};
let name = s.script_start(request)?;
if s.script_frames {
return Ok(json!({"running": true, "name": name}));
}
s.script_run_to_end()
})
}
fn stop(s: &mut Session, _: &Value) -> Result<Value> {
@@ -276,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"))
@@ -342,6 +373,278 @@ impl Session {
}
}
/// The error of a startup script that is no longer a `.jsx` file of the Startup Scripts folder, or
/// cannot be read, when its turn comes.
pub const STARTUP_UNREADABLE: &str = "the startup script could not be read";
impl Session {
/// Have `script.startup.run` run the scripts of the folder `dir`. The folder is only read, and
/// never made.
pub fn attach_startup_scripts_dir(&mut self, dir: std::path::PathBuf) {
self.startup_scripts_dir = Some(dir);
}
/// The Startup Scripts folder ([`Session::attach_startup_scripts_dir`]); none on the web.
pub fn startup_scripts_dir(&self) -> Option<&std::path::Path> {
self.startup_scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
}
/// Why `script.startup.run` runs nothing now: `off` (the `runStartupScripts` preference),
/// `safeMode`, or `noFolder` (no Startup Scripts folder); `None` when it runs the folder.
pub fn startup_skip(&self) -> Option<&'static str> {
if !self.prefs.run_startup_scripts {
Some("off")
} else if vectorcraft_plugins::safe_mode::active() {
Some("safeMode")
} else if self.startup_scripts_dir().is_none() {
Some("noFolder")
} else {
None
}
}
/// The startup script that ran has ended: the launch marker no longer names it.
pub(crate) fn startup_ended(&mut self) {
if let Some(token) = self.startup_loading.take() {
vectorcraft_plugins::safe_mode::loaded(token);
}
}
/// The running script is a startup script (`script.startup.run`), not the script queued after
/// them.
pub fn startup_script_running(&self) -> bool {
self.startup_loading.is_some()
}
/// Begins a run of the startup script at `path`, read now and checked as `script.run` checks a
/// file, with the launch marker naming it while it runs. → the run's name, or the error that kept
/// it from starting, which the Script Console also shows.
fn start_startup(&mut self, path: &std::path::Path, fuel: u64) -> std::result::Result<String, String> {
let name = file_name_of(path);
let text = self.startup_text(path);
let (text, real) = match text {
Ok(read) => read,
Err(message) => {
self.note_unread(&name, &message);
return Err(message);
}
};
let item = startup_item(path);
self.startup_loading = Some(vectorcraft_plugins::safe_mode::loading(&item));
let locale = script::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language));
let request = script::Request {
name: name.clone(),
name_given: false,
file: Some(path.to_string_lossy().into_owned()),
checked_real: Some(real),
source: text,
args: serde_json::Map::new(),
fuel,
locale,
answers: vec![],
};
let runs = self.script_runs;
self.script_start(request).map_err(|e| {
self.startup_ended();
let message = e.to_string();
// A run refused before it began, such as with an undo group open, has no console entry yet.
if self.script_runs == runs {
self.note_unread(&name, &message);
}
message
})
}
/// The text of the startup script at `path` and its real path, or the error that keeps it from
/// running.
fn startup_text(&self, path: &std::path::Path) -> std::result::Result<(String, std::path::PathBuf), String> {
let unreadable = || STARTUP_UNREADABLE.to_string();
let root = self.startup_scripts_dir().ok_or_else(unreadable)?;
let mut real = std::fs::canonicalize(root).map_err(|_| unreadable())?;
real.push(path.file_name().ok_or_else(unreadable)?);
// One byte more than a script may have shows that the file is too large.
let bytes = script::startup::read(root, path, script::MAX_SOURCE_BYTES + 1).ok_or_else(unreadable)?;
if bytes.len() > script::MAX_SOURCE_BYTES {
return Err(TOO_LARGE.to_string());
}
Ok((script_text(&bytes).map_err(|e| e.to_string())?, real))
}
/// With no script running, starts the next run `script.startup.run` queued: the next startup
/// script that starts, or the script queued after them. A run that cannot start is kept for
/// [`Self::take_startup_failures`], and the next one starts on a later pump. → the reply of the script queued
/// after them when it ran to its end at once.
pub(crate) fn start_queued(&mut self) -> Option<Value> {
// Held aside while a run starts, so that the queue does not count as a running script then.
let mut queue = std::mem::take(&mut self.script_queue);
// Each run starts in the file access scope of the request that queued it, which the run
// keeps, and not in the scope of the frame that starts it.
let scope = self.script_queue_scope.clone().unwrap_or_else(crate::file_access::ScopeHandle::capture);
let mut reply = None;
if self.script_key.is_none()
&& let Some(next) = queue.pop_front()
{
match next {
script::startup::Queued::Startup { path, fuel } => {
if let Err(e) = scope.clone().run(|| self.start_startup(&path, fuel)) {
self.startup_failures.push((file_name_of(&path), e));
}
}
script::startup::Queued::Then(params) => {
let prepared = self.script_queue_then.take();
match scope.clone().run(|| match prepared {
Some(request) => run_prepared(self, request),
None => run(self, &params),
}) {
Ok(_) if self.script_key.is_some() => {}
Ok(v) => reply = Some(v),
Err(e) => self.startup_failures.push((then_name(&params), e.to_string())),
}
}
}
}
if queue.is_empty() {
self.script_queue_scope = None;
self.script_queue_then = None;
}
self.script_queue = queue;
reply
}
/// The runs `script.startup.run` queued that could not start since the last call, as (name,
/// error), in order.
pub fn take_startup_failures(&mut self) -> Vec<(String, String)> {
std::mem::take(&mut self.startup_failures)
}
}
/// The file name of `path`, or the whole path when it has none.
fn file_name_of(path: &std::path::Path) -> String {
path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned())
}
/// The name a failure of the script `params` (`script.run`'s) names it by: `name`, else the file
/// name of `path`, else "script".
fn then_name(params: &Value) -> String {
let given = |key: &str| params.get(key).and_then(Value::as_str).filter(|v| !v.trim().is_empty());
match (given("name"), given("path")) {
(Some(name), _) => name.to_string(),
(None, Some(path)) => file_name_of(std::path::Path::new(path)),
(None, None) => "script".to_string(),
}
}
/// The launch marker's entry for the startup script at `path`: its file and its file name.
fn startup_item(path: &std::path::Path) -> vectorcraft_plugins::safe_mode::Item {
let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
vectorcraft_plugins::safe_mode::Item { id: None, file: Some(path.to_string_lossy().into_owned()), name }
}
fn startup_run(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "script.startup.run";
let reason = match p.get("reason").and_then(Value::as_str) {
Some(r @ ("launch" | "menu")) => r,
_ => {
let key = "reason";
return Err(bad(C, format!("`{key}` must be one of {}", "launch, menu")));
}
};
let then = match p.get("then") {
None => None,
Some(v @ Value::Object(_)) => Some(v.clone()),
Some(_) => {
let key = "then";
return Err(bad(C, format!("`{key}` must be an object")));
}
};
let fuel = match p.get("maxFuel") {
None => script::DEFAULT_FUEL,
Some(v) => v.as_u64().filter(|n| (1..=script::MAX_FUEL).contains(n)).ok_or_else(|| EngineError::BadParams {
cmd: C.into(),
msg: format!("`maxFuel` must be a whole number from 1 to {}", script::MAX_FUEL),
})?,
};
if s.script_running() {
return Err(EngineError::Busy);
}
// A chosen script that cannot start ends the request before any startup script runs, and its
// parameters are checked as `script.run` checks them.
if let Some(then) = &then {
super::params::check_params("script.run", then)?;
}
let root = match (s.startup_skip(), s.startup_scripts_dir()) {
(None, Some(root)) => root.to_path_buf(),
(why, _) => {
let mut out = json!({"reason": reason, "skipped": true, "why": why.unwrap_or("noFolder")});
if let Some(then) = then {
out["then"] = run(s, &then)?;
}
return Ok(out);
}
};
let prepared = then.as_ref().map(|params| prepare(s, params)).transpose()?;
if let Some(request) = &prepared {
let mut preflight = Session::new();
if let Err(error) = preflight.script_start(request.clone()) {
s.script_report = None;
return Err(error);
}
}
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, 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)));
let disabled: Vec<String> = disabled.iter().map(|p| name_of(p)).collect();
if s.script_frames {
s.script_queue =
scripts.into_iter().map(|path| script::startup::Queued::Startup { path, fuel }).chain(then.map(script::startup::Queued::Then)).collect();
s.script_queue_scope = Some(crate::file_access::ScopeHandle::capture());
s.script_queue_then = prepared;
let queued = s.script_queue.len();
s.startup_failures.clear();
let then = s.start_queued();
let failed: Vec<Value> = s.take_startup_failures().into_iter().map(|(name, error)| json!({"name": name, "error": error})).collect();
let mut out = json!({
"reason": reason,
"skipped": false,
"running": s.script_running(),
"queued": queued,
"failed": failed,
"disabled": disabled,
"truncated": listing.truncated,
"unreadable": listing.unreadable,
});
if let Some(then) = then {
out["then"] = then;
}
return Ok(out);
}
let (mut ran, mut failed) = (vec![], vec![]);
for path in scripts {
let name = name_of(&path);
match s.start_startup(&path, fuel).map_err(EngineError::Other).and_then(|_| s.script_run_to_end()) {
Ok(_) => ran.push(name),
Err(e) => failed.push(json!({"name": name, "error": e.to_string()})),
}
}
let mut out = json!({
"reason": reason,
"skipped": false,
"ran": ran,
"failed": failed,
"disabled": disabled,
"truncated": listing.truncated,
"unreadable": listing.unreadable,
});
if let Some(request) = prepared {
out["then"] = run_prepared(s, request)?;
}
Ok(out)
}
/// The file name a reply names `path` by when the file is outside the automation read roots; `None`
/// when a reply may name it whole.
fn hidden_name(path: &str) -> Option<String> {
@@ -356,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()
@@ -384,16 +687,19 @@ fn grants(s: &mut Session, _: &Value) -> Result<Value> {
fn grants_revoke(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "script.grants.revoke";
// A path is matched as given, or with its links followed when no grant holds it as given, so a
// grant whose path a link has since taken the place of is still removed. A path the request may not read (outside the
// automation read roots, a network path among them) is compared as written, without looking it up.
let path_of = |key: &str| match p.get(key) {
None => Ok(None),
// A path the request may not read (outside the automation read roots, a network path among
// them) is compared as written, without looking it up.
Some(Value::String(t)) if !t.is_empty() => Ok(Some(
crate::file_access::check_read(t)
Some(Value::String(t)) if !t.is_empty() => {
let real = crate::file_access::check_read(t)
.ok()
.and_then(|()| std::fs::canonicalize(t).ok())
.map_or_else(|| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()),
)),
.map(|real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned())
.filter(|real| real != t);
Ok(Some([Some(t.clone()), real].into_iter().flatten().collect::<Vec<_>>()))
}
Some(_) => Err(bad(C, format!("`{key}` must be a path"))),
};
let (script_path, path) = (path_of("script")?, path_of("path")?);
+5
View File
@@ -189,6 +189,11 @@ pub fn specs() -> Vec<CommandSpec> {
}
impl Session {
/// The selected slices, including selected objects that are object slices.
pub fn selected_slice_ids(&self) -> Vec<NodeId> {
self.active().map_or_else(Vec::new, |st| selected_slices(&st.doc, &st.selection))
}
/// View → Hide Slices.
pub fn slices_hidden(&self) -> bool {
self.menu.slices_hidden
Loaded 100 of 704 files, more files were not shown because too many files have changed in this diff. Show more