mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge main into fix/script-documents-strict-assign
# Conflicts: # crates/engine/src/script/dom.rs
This commit is contained in:
commit
1583808eec
280 files changed
+10692
-1947
No files matched your search
@@ -0,0 +1,35 @@
|
||||
name: Cache prune
|
||||
|
||||
# A pass of the cache prune after every CI attempt on main. ci.yml's `cache prune` job prunes while
|
||||
# a run's jobs save their entries, but "Re-run failed jobs" re-runs only the failed jobs: a re-run
|
||||
# `cache warm` leg saves a new entry, and the prune job, which succeeded in the first attempt, does
|
||||
# not run again. The entry it replaced would stay until the next main run, and with it the cache
|
||||
# would be over its 10 GB budget, where GitHub evicts entries a run still needs. This runs once
|
||||
# after every attempt, re-runs and canceled runs included (craft-common-actions actions/cache-prune).
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [CI]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
cache-prune:
|
||||
name: cache prune
|
||||
# A fork's pull request from a branch named main also matches `branches`.
|
||||
if: github.event.workflow_run.event != 'pull_request'
|
||||
timeout-minutes: 10
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
# A failed pass warns; the next run's prune deletes what it missed.
|
||||
- name: Prune replaced cache entries
|
||||
uses: storytold/craft-common-actions/actions/cache-prune@main
|
||||
continue-on-error: true
|
||||
@@ -1,10 +1,14 @@
|
||||
name: CI
|
||||
|
||||
# Quality gates for every push to main and every pull request (`cargo xtask ci`), through the
|
||||
# suite's shared gate workflow in craft-common-actions.
|
||||
# suite's shared gate workflow in craft-common-actions. Every night the gate runs a cold build:
|
||||
# the safety net for the workspace crates it keeps between runs (`cache-workspace-crates`), and a
|
||||
# fresh start for that cache entry.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
schedule:
|
||||
- cron: "37 3 * * *"
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
@@ -23,7 +27,10 @@ jobs:
|
||||
with:
|
||||
# Same craft-fonts commit as release.yml.
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
timeout-minutes: 90
|
||||
# A cold `cache warm` leg (the nightly run, or any run after a toolchain or lockfile change)
|
||||
# took 90 minutes to reach its last three steps on 2026-11-27 and was canceled there; with
|
||||
# those steps and the save it needs about two hours.
|
||||
timeout-minutes: 150
|
||||
# The gate's test binaries carry no debug info and no symbols (CARGO_PROFILE_TEST_DEBUG=0,
|
||||
# CARGO_PROFILE_TEST_STRIP=symbols), as photocraft's do: linking ~100 test binaries with line
|
||||
# tables ran the hosted runner out of resources, and it stopped mid-link with "received a
|
||||
@@ -39,7 +46,68 @@ jobs:
|
||||
test-shards: 5
|
||||
shard-command: cargo xtask ci shard
|
||||
warm-command: cargo xtask ci warm
|
||||
# The dependency cache also keeps the compiled workspace crates and test executables, so a
|
||||
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
|
||||
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
|
||||
# `cache-prune` below deletes the one it replaced. The nightly run restores nothing and
|
||||
# builds everything from source.
|
||||
cache-workspace-crates: true
|
||||
cold-build: ${{ github.event_name == 'schedule' }}
|
||||
packages: >-
|
||||
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev
|
||||
libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
|
||||
libgl1-mesa-dev
|
||||
|
||||
# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache
|
||||
# budget. It runs beside the gate and prunes each time the `cache warm` leg finishes saving. A
|
||||
# failed prune warns instead of failing the run, and cache-prune.yml prunes again after every
|
||||
# attempt, re-runs of failed jobs included. `watch-minutes` is longer than the gate's
|
||||
# `timeout-minutes`, so the watch outlasts a cold `cache warm` leg.
|
||||
cache-prune:
|
||||
name: cache prune
|
||||
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 170
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Prune replaced cache entries
|
||||
uses: storytold/craft-common-actions/actions/cache-prune@main
|
||||
continue-on-error: true
|
||||
with:
|
||||
watch: true
|
||||
watch-minutes: 160
|
||||
saving-jobs: |
|
||||
^gate( / cache warm \(.*\))?$
|
||||
|
||||
# The nightly cold run never restores the rolling crates entry, so the old entry is only overlap
|
||||
# while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the
|
||||
# 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes
|
||||
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
|
||||
# When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run
|
||||
# failed jobs" runs it again beside the re-run leg. The script's 160-minute wait starts when the leg
|
||||
# starts, which is after `gate / select legs` and a free runner, so this job's timeout leaves
|
||||
# 40 minutes for that.
|
||||
cold-cache-clear:
|
||||
name: cold cache clear
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 200
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Delete the old rolling entries before the save
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: python3 scripts/ci-clear-rolling-cache.py
|
||||
@@ -3,13 +3,14 @@ name: Nightly check
|
||||
# The app-side Nightly pieces, checked without a feed run: the Python suites that read the archive,
|
||||
# plist and signing scripts, the workflow contracts, and (on Windows) the packaging and signing
|
||||
# PowerShell suites. The producer itself is .github/workflows/nightly.yml; the Apple-silicon bundle
|
||||
# is built and verified by nightly-macos.yml behind the `full-ci` label.
|
||||
# is built and verified by nightly-macos.yml behind the `full-ci` label. The same job also runs the
|
||||
# suite for scripts/ci-clear-rolling-cache.py, which ci.yml's nightly cold run calls.
|
||||
on:
|
||||
push:
|
||||
branches: [main, release]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"]
|
||||
pull_request:
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -34,6 +35,8 @@ jobs:
|
||||
persist-credentials: false
|
||||
- name: Run the synthetic suites
|
||||
run: python3 packaging/nightly-tests.py
|
||||
- name: Run the cold cache clear suite
|
||||
run: python3 scripts/ci-clear-rolling-cache-tests.py
|
||||
- name: Parse every nightly shell script
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
Generated
+208
-106
@@ -1217,7 +1217,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
@@ -1258,7 +1258,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-affinity"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1269,9 +1269,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
@@ -1279,7 +1280,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-atomic"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
@@ -1287,7 +1288,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1312,7 +1313,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-behavior"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"bitflags 2.13.2",
|
||||
@@ -1330,7 +1331,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-browse"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-docpath",
|
||||
@@ -1348,7 +1349,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cdr"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
@@ -1357,7 +1358,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cloud-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"egui",
|
||||
]
|
||||
@@ -1365,7 +1366,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-cms"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"md-5",
|
||||
"rayon",
|
||||
@@ -1374,12 +1375,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
|
||||
[[package]]
|
||||
name = "craft-color-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-cms",
|
||||
@@ -1399,17 +1400,28 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-control-protocol",
|
||||
"craft-platform",
|
||||
"getrandom 0.3.4",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-control-protocol"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-dds"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
@@ -1417,9 +1429,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
"craft-browse",
|
||||
@@ -1442,7 +1455,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-docpath"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
@@ -1450,7 +1463,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-draw"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1469,7 +1482,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-dxf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-codepage",
|
||||
"encoding_rs",
|
||||
@@ -1481,12 +1494,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-eps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
@@ -1501,7 +1514,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-font-manager"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-catalog",
|
||||
@@ -1517,14 +1530,24 @@ dependencies = [
|
||||
"skrifa 0.47.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-os-windows"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"windows-registry",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
"craft-font-catalog",
|
||||
"craft-font-os-windows",
|
||||
"flate2",
|
||||
"log",
|
||||
"ruzstd",
|
||||
@@ -1542,12 +1565,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"gif",
|
||||
]
|
||||
@@ -1555,7 +1578,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
]
|
||||
@@ -1563,7 +1586,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-i18n",
|
||||
@@ -1576,7 +1599,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"fixed_decimal",
|
||||
@@ -1604,7 +1627,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-image-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-dds",
|
||||
"craft-jpeg",
|
||||
@@ -1617,7 +1640,7 @@ dependencies = [
|
||||
"hayro-jpeg2000",
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"jpeg-encoder 0.7.1",
|
||||
"png 0.18.1",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
@@ -1631,7 +1654,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-imaging"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-color-ui",
|
||||
@@ -1649,7 +1672,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jpeg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
@@ -1657,7 +1680,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-jxl"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"brotli-decompressor 5.0.3",
|
||||
"jixel",
|
||||
@@ -1668,7 +1691,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-keymap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-i18n",
|
||||
@@ -1683,7 +1706,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-layers"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -1697,7 +1720,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-menu"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1715,7 +1738,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metadata"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"brotli-decompressor 6.3.2",
|
||||
"chrono",
|
||||
@@ -1727,7 +1750,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
@@ -1738,7 +1761,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-mime"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-codepage",
|
||||
@@ -1748,7 +1771,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pages"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1764,7 +1787,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"hayro-interpret",
|
||||
"hayro-syntax",
|
||||
@@ -1776,7 +1799,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-platform"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"async-channel",
|
||||
"async-io",
|
||||
@@ -1807,7 +1830,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-plotter"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1816,7 +1839,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-print"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -1840,7 +1863,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-proof"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
@@ -1851,7 +1874,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ps"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-eps",
|
||||
"flate2",
|
||||
@@ -1865,7 +1888,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
@@ -1876,7 +1899,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"egui",
|
||||
@@ -1889,7 +1912,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-review"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"craft-behavior",
|
||||
@@ -1908,7 +1931,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-settings"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-host",
|
||||
@@ -1925,7 +1948,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
@@ -1936,7 +1959,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-svg"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-image-codecs",
|
||||
"craft-xml",
|
||||
@@ -1957,7 +1980,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-table"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -1969,7 +1992,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-text"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-font-manager",
|
||||
@@ -1994,7 +2017,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"craft-tracked",
|
||||
@@ -2009,7 +2032,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-theme-store"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
@@ -2024,7 +2047,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2034,7 +2057,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-time"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2043,7 +2066,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-timeline"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-keymap",
|
||||
@@ -2058,12 +2081,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-tracked"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-cloud-ui",
|
||||
"craft-ui-canvas",
|
||||
@@ -2077,7 +2100,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-canvas"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-i18n",
|
||||
@@ -2093,7 +2116,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-contract"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"craft-behavior",
|
||||
@@ -2131,7 +2154,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-macros"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
@@ -2142,7 +2165,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-panels"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2160,7 +2183,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-patterns"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2181,7 +2204,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-shell"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2202,7 +2225,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-ui-widgets"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-behavior",
|
||||
"craft-host",
|
||||
@@ -2221,13 +2244,15 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-update"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"craft-host",
|
||||
"craft-theme",
|
||||
"craft-ui",
|
||||
"dunce",
|
||||
"ed25519-dalek",
|
||||
"egui",
|
||||
"flate2",
|
||||
"image",
|
||||
@@ -2240,6 +2265,7 @@ dependencies = [
|
||||
"sha2 0.10.9",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"toml",
|
||||
"ureq",
|
||||
"verifysign",
|
||||
"winreg",
|
||||
@@ -2250,7 +2276,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-vectorcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"serde",
|
||||
@@ -2261,7 +2287,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-wayland"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"raw-window-handle",
|
||||
"wayland-backend",
|
||||
@@ -2271,7 +2297,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-web-api"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"serde_json",
|
||||
@@ -2282,7 +2308,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-win32"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"winsafe",
|
||||
]
|
||||
@@ -2290,7 +2316,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
@@ -2322,7 +2348,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "craft-xml"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -2424,6 +2450,33 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek"
|
||||
version = "4.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"curve25519-dalek-derive",
|
||||
"digest 0.10.7",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek-derive"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "data-url"
|
||||
version = "0.3.2"
|
||||
@@ -2640,16 +2693,40 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||
[[package]]
|
||||
name = "ecolor"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "2.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
|
||||
dependencies = [
|
||||
"pkcs8",
|
||||
"signature",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-dalek"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"ed25519",
|
||||
"serde",
|
||||
"sha2 0.10.9",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "eframe"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2684,7 +2761,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -2703,7 +2780,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2722,7 +2799,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-winit"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"accesskit_winit",
|
||||
"arboard",
|
||||
@@ -2747,7 +2824,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"egui",
|
||||
@@ -2761,7 +2838,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -2774,7 +2851,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_kittest"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"dify",
|
||||
"eframe",
|
||||
@@ -2800,7 +2877,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
||||
[[package]]
|
||||
name = "emath"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -2881,7 +2958,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -2907,7 +2984,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=932a73b28560acb1a695533307b2cd0d66a42081#932a73b28560acb1a695533307b2cd0d66a42081"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
@@ -3003,6 +3080,12 @@ version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
|
||||
[[package]]
|
||||
name = "filetime"
|
||||
version = "0.2.29"
|
||||
@@ -3620,7 +3703,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
[[package]]
|
||||
name = "hayro-cmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"hayro-postscript",
|
||||
@@ -3629,7 +3712,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-interpret"
|
||||
version = "0.7.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"hayro-cmap",
|
||||
@@ -3647,7 +3730,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"fearless_simd",
|
||||
"hayro-ccitt",
|
||||
@@ -3665,12 +3748,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "hayro-postscript"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.7.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hayro-ccitt",
|
||||
@@ -4411,6 +4494,12 @@ version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f"
|
||||
|
||||
[[package]]
|
||||
name = "jpeg-encoder"
|
||||
version = "0.7.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a0370574b86f7eca156b9f298392b5e69a23f8c86f3f865add60bbc2e79467a6"
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.106"
|
||||
@@ -4647,7 +4736,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
@@ -4804,7 +4893,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
[[package]]
|
||||
name = "linesweeper"
|
||||
version = "0.5.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b0d422cf0c23baccdaca314b916458a89c0952e0#b0d422cf0c23baccdaca314b916458a89c0952e0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=51fcc3b0413af193db952df28dffae2321745703#51fcc3b0413af193db952df28dffae2321745703"
|
||||
dependencies = [
|
||||
"arrayvec",
|
||||
"kurbo 0.13.1",
|
||||
@@ -6013,6 +6102,16 @@ dependencies = [
|
||||
"system-deps",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
|
||||
dependencies = [
|
||||
"der",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.34"
|
||||
@@ -6356,6 +6455,9 @@ name = "rand_core"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
||||
dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
@@ -8493,7 +8595,7 @@ dependencies = [
|
||||
"craft-stream-codecs",
|
||||
"flate2",
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
"jpeg-encoder 0.6.1",
|
||||
"kurbo 0.13.1",
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -8749,7 +8851,7 @@ dependencies = [
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
"jpeg-encoder 0.6.1",
|
||||
"krilla",
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
@@ -8806,7 +8908,7 @@ dependencies = [
|
||||
"craft-tiff",
|
||||
"flate2",
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
"jpeg-encoder 0.6.1",
|
||||
"log",
|
||||
"proptest",
|
||||
"serde_json",
|
||||
@@ -9175,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",
|
||||
@@ -9188,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",
|
||||
]
|
||||
@@ -10578,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
@@ -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" }
|
||||
@@ -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 }
|
||||
|
||||
+286
-144
@@ -4,10 +4,12 @@
|
||||
//! - Windows: text, SVG, PDF, PNG and an opaque bitmap (for apps that don't read PNG) in one go;
|
||||
//! Paste reads each of them and EPS, a bitmap as PNG, else as the device-independent bitmap that
|
||||
//! screenshots and most apps copy (`CF_DIBV5`, `CF_DIB`; the system makes them of a `CF_BITMAP`).
|
||||
//! - macOS and Linux: one format at a time, the text (a type-only copy's text or the SVG markup),
|
||||
//! else the PNG as a bitmap; Paste reads text and bitmaps, and on macOS the pasteboard's SVG, PDF
|
||||
//! and EPS as vector art (#1499) and its PNG or TIFF as they are, as screenshots copy them (on
|
||||
//! Linux arboard reads no other formats). On Wayland, arboard's data-control
|
||||
//! - macOS: text, SVG, PDF and PNG in one go: arboard writes the text, else the PNG as TIFF, and
|
||||
//! the other formats are added to the same pasteboard item ([`pasteboard_additions`]); Paste
|
||||
//! reads text and bitmaps, the pasteboard's SVG, PDF and EPS as vector art (#1499) and its PNG
|
||||
//! or TIFF as they are, as screenshots copy them.
|
||||
//! - Linux: one format at a time, the text (a type-only copy's text or the SVG markup), else the
|
||||
//! PNG as a bitmap; Paste reads text and bitmaps (arboard reads no other formats). On Wayland, arboard's data-control
|
||||
//! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps
|
||||
//! copied), falling back to X11 where the compositor lacks the protocol, and where there is no
|
||||
//! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection:
|
||||
@@ -137,6 +139,26 @@ fn pasteboard_types(mime: &str) -> &'static [(&'static str, &'static str)] {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pasteboard types and data Copy adds on macOS to the item arboard wrote (the text, else the
|
||||
/// PNG as TIFF), in the order of `flavors` (best first): the SVG, PDF and EPS under the first of
|
||||
/// their [`pasteboard_types`], and the PNG as `public.png`. Text, empty flavours and flavours the
|
||||
/// pasteboard has no type for are left out.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn pasteboard_additions(flavors: &[Flavor]) -> Vec<(&'static str, &[u8])> {
|
||||
flavors
|
||||
.iter()
|
||||
.filter(|f| !f.data.is_empty())
|
||||
.filter_map(|f| {
|
||||
let t = match engine_mime(&f.mime)? {
|
||||
TEXT => return None,
|
||||
PNG => "public.png",
|
||||
mime => pasteboard_types(mime).first()?.0,
|
||||
};
|
||||
Some((t, &f.data[..]))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Most pixels a side of a bitmap another app put on the clipboard (untrusted data).
|
||||
const MAX_SIDE: u32 = 32_768;
|
||||
|
||||
@@ -612,9 +634,46 @@ mod loads {
|
||||
|
||||
/// The longest a read waits for the clipboard's owner to send its data.
|
||||
pub(super) const LOAD_WAIT: Duration = Duration::from_secs(2);
|
||||
/// The longest a paste's bitmap read of arboard's waits for the app that copied, off the UI
|
||||
/// thread: the bitmap's transfer and its PNG decoding happen within the read. A paste waits as
|
||||
/// long, from when it was sent, for a read that got no answer in its wait, the core protocol's
|
||||
/// text read included. Text, file lists and the UI thread's bitmap check wait [`LOAD_WAIT`].
|
||||
pub(super) const IMAGE_WAIT: Duration = Duration::from_secs(10);
|
||||
/// What a read says once its worker has stopped.
|
||||
pub(super) const GONE: &str = "the clipboard's reader stopped";
|
||||
|
||||
/// How long the reads of a [`Loads`] wait for the clipboard's owner.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct Waits {
|
||||
/// A text or file-list read, the UI thread's bitmap check, and dropping an idle `Loads`.
|
||||
pub(super) load: Duration,
|
||||
/// A paste's bitmap read off the UI thread, and a paste's wait for a read that got no
|
||||
/// answer in its wait.
|
||||
pub(super) image: Duration,
|
||||
}
|
||||
|
||||
impl Waits {
|
||||
/// [`LOAD_WAIT`] and [`IMAGE_WAIT`].
|
||||
pub(super) const APP: Self = Self { load: LOAD_WAIT, image: IMAGE_WAIT };
|
||||
/// No limit: each wait ends when its answer comes or its worker stops.
|
||||
#[cfg(test)]
|
||||
pub(super) const UNTIL_ANSWERED: Self = Self { load: Duration::MAX, image: Duration::MAX };
|
||||
}
|
||||
|
||||
/// What is left at `now` of `limit` from `sent`; [`Duration::MAX`] (no limit) when the end is
|
||||
/// past the clock's range.
|
||||
pub(super) fn left(sent: Instant, limit: Duration, now: Instant) -> Duration {
|
||||
sent.checked_add(limit).map_or(Duration::MAX, |end| end.saturating_duration_since(now))
|
||||
}
|
||||
|
||||
/// What comes on `rx` within `wait`; a wait whose end is past the clock's range has no limit.
|
||||
fn recv_within<T>(rx: &mpsc::Receiver<T>, wait: Duration) -> Result<T, mpsc::RecvTimeoutError> {
|
||||
match Instant::now().checked_add(wait) {
|
||||
Some(_) => rx.recv_timeout(wait),
|
||||
None => rx.recv().map_err(mpsc::RecvTimeoutError::from),
|
||||
}
|
||||
}
|
||||
|
||||
/// Requests of type `R` answered with `A` on a worker thread.
|
||||
pub(super) struct Loads<R, A> {
|
||||
/// The worker's requests; the worker stops once this is dropped.
|
||||
@@ -623,6 +682,8 @@ mod loads {
|
||||
done: mpsc::Receiver<()>,
|
||||
/// How long after it was sent dropping `Loads` waits for an unanswered read to end.
|
||||
finish: Duration,
|
||||
/// How long its reads wait.
|
||||
waits: Waits,
|
||||
}
|
||||
|
||||
/// Where requests go to a [`Loads`] worker.
|
||||
@@ -685,18 +746,18 @@ mod loads {
|
||||
}
|
||||
}
|
||||
|
||||
/// When dropping `Loads` stops waiting for its worker: `finish` after the unanswered read
|
||||
/// `pending` was sent (at once if that time has passed), and with no read unanswered
|
||||
/// [`LOAD_WAIT`] from `now` at most (an idle worker ends at once).
|
||||
fn stop_by(pending: Option<Instant>, now: Instant, finish: Duration) -> Instant {
|
||||
pending.map_or(now + LOAD_WAIT, |sent| sent + finish)
|
||||
/// How long, from `now`, dropping `Loads` waits for its worker: until `finish` after the
|
||||
/// unanswered read `pending` was sent (not at all if that time has passed), and with no read
|
||||
/// unanswered `idle` at most (an idle worker ends at once).
|
||||
fn stop_wait(pending: Option<Instant>, now: Instant, finish: Duration, idle: Duration) -> Duration {
|
||||
pending.map_or(idle, |sent| left(sent, finish, now))
|
||||
}
|
||||
|
||||
impl<R: Send + 'static, A: Send + 'static> Loads<R, A> {
|
||||
/// A worker thread named `name` that answers each request with `load`; dropping the result
|
||||
/// waits up to `finish` after an unanswered read was sent for that read to end. None when the
|
||||
/// worker can't start.
|
||||
pub(super) fn spawn(name: &str, finish: Duration, mut load: impl FnMut(R) -> A + Send + 'static) -> Option<Self> {
|
||||
/// A worker thread named `name` that answers each request with `load`, whose reads wait as
|
||||
/// `waits` says; dropping the result waits up to `finish` after an unanswered read was sent
|
||||
/// for that read to end. None when the worker can't start.
|
||||
pub(super) fn spawn(name: &str, finish: Duration, waits: Waits, mut load: impl FnMut(R) -> A + Send + 'static) -> Option<Self> {
|
||||
let (requests, asked) = mpsc::channel::<(R, mpsc::Sender<A>)>();
|
||||
let (alive, done) = mpsc::channel::<()>();
|
||||
let open = Arc::new(AtomicUsize::new(0));
|
||||
@@ -714,7 +775,12 @@ mod loads {
|
||||
drop(alive);
|
||||
};
|
||||
std::thread::Builder::new().name(name.into()).spawn(work).ok()?;
|
||||
Some(Self { line: Arc::new(Line { requests, open, sent: Mutex::default() }), done, finish })
|
||||
Some(Self { line: Arc::new(Line { requests, open, sent: Mutex::default() }), done, finish, waits })
|
||||
}
|
||||
|
||||
/// How long its reads wait.
|
||||
pub(super) fn waits(&self) -> Waits {
|
||||
self.waits
|
||||
}
|
||||
|
||||
/// `request` sent to the worker; its answer comes on the channel returned, for
|
||||
@@ -741,9 +807,10 @@ mod loads {
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer that comes on `answer` ([`Loads::ask`]), or why there is none, after `wait` at most.
|
||||
/// The answer that comes on `answer` ([`Loads::ask`]), or why there is none, after `wait` at most
|
||||
/// ([`Duration::MAX`]: no limit).
|
||||
pub(super) fn wait_for_answer<A>(answer: &mpsc::Receiver<A>, wait: Duration) -> Result<A, String> {
|
||||
match answer.recv_timeout(wait) {
|
||||
match recv_within(answer, wait) {
|
||||
Ok(answer) => Ok(answer),
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => Err(format!("the clipboard's owner didn't send its data within {wait:?}")),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => Err(GONE.into()),
|
||||
@@ -751,16 +818,16 @@ mod loads {
|
||||
}
|
||||
|
||||
impl<R, A> Drop for Loads<R, A> {
|
||||
/// Stops the worker and waits until it has let go of what its `load` holds, until
|
||||
/// [`stop_by`] at most: on X11 the last arboard handle dropped hands what the app copied to
|
||||
/// the clipboard manager, and the app's own handle must be that one.
|
||||
/// Stops the worker and waits until it has let go of what its `load` holds, as long as
|
||||
/// [`stop_wait`] says at most: on X11 the last arboard handle dropped hands what the app
|
||||
/// copied to the clipboard manager, and the app's own handle must be that one.
|
||||
fn drop(&mut self) {
|
||||
// No `Asker` sends after this, and one that holds the line lets go once it has sent.
|
||||
let pending = self.line.close();
|
||||
drop(std::mem::replace(&mut self.line, Line::dead()));
|
||||
let end = stop_by(pending, Instant::now(), self.finish);
|
||||
// Nothing is sent on `done`: this ends when the worker drops `alive`, or at `end`.
|
||||
let _ = self.done.recv_timeout(end.saturating_duration_since(Instant::now()));
|
||||
let wait = stop_wait(pending, Instant::now(), self.finish, self.waits.load);
|
||||
// Nothing is sent on `done`: this ends when the worker drops `alive`, or after `wait`.
|
||||
let _ = recv_within(&self.done, wait);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -770,18 +837,38 @@ mod loads {
|
||||
|
||||
use super::*;
|
||||
|
||||
/// No limit: a wait ends when its answer comes.
|
||||
const UNTIL_ANSWERED: Duration = Duration::MAX;
|
||||
|
||||
#[test]
|
||||
fn a_read_that_answers_in_time_gives_the_text() {
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, |()| "<svg/>".to_string()).unwrap();
|
||||
assert_eq!(loads.get((), Duration::from_secs(5)), Ok("<svg/>".to_string()));
|
||||
assert_eq!(loads.get((), Duration::from_secs(5)), Ok("<svg/>".to_string()));
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| "<svg/>".to_string()).unwrap();
|
||||
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok("<svg/>".to_string()));
|
||||
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok("<svg/>".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wait_with_no_limit_ends_when_its_answer_comes() {
|
||||
let (reply, answer) = mpsc::channel();
|
||||
let late = std::thread::spawn(move || reply.send(7));
|
||||
assert_eq!(wait_for_answer(&answer, UNTIL_ANSWERED), Ok(7));
|
||||
assert_eq!(late.join().ok(), Some(Ok(())));
|
||||
// A worker that stops without answering ends the wait too.
|
||||
let (reply, answer) = mpsc::channel::<u8>();
|
||||
drop(reply);
|
||||
assert_eq!(wait_for_answer(&answer, UNTIL_ANSWERED), Err(GONE.to_string()));
|
||||
// Limits from a read's send: what is left, none once it is over, no limit past the clock.
|
||||
let now = Instant::now();
|
||||
assert_eq!(left(now, Duration::from_secs(10), now + Duration::from_secs(3)), Duration::from_secs(7));
|
||||
assert_eq!(left(now, Duration::from_secs(10), now + Duration::from_secs(20)), Duration::ZERO);
|
||||
assert_eq!(left(now, Duration::MAX, now), Duration::MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_owner_that_never_answers_holds_the_worker_not_the_caller() {
|
||||
let (release, gate) = mpsc::channel::<()>();
|
||||
let mut calls = 0;
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, move |()| {
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |()| {
|
||||
calls += 1;
|
||||
if calls == 1 {
|
||||
// The first owner sends nothing until released.
|
||||
@@ -793,11 +880,11 @@ mod loads {
|
||||
.unwrap();
|
||||
assert!(loads.get((), Duration::ZERO).is_err(), "the first read times out");
|
||||
// While it is unanswered, a read doesn't queue behind it or wait at all.
|
||||
assert!(loads.get((), Duration::from_secs(600)).is_err());
|
||||
assert!(loads.get((), UNTIL_ANSWERED).is_err());
|
||||
release.send(()).unwrap();
|
||||
// Once the late answer is in, it is dropped and a new read is made.
|
||||
let text = loop {
|
||||
match loads.get((), Duration::from_secs(600)) {
|
||||
match loads.get((), UNTIL_ANSWERED) {
|
||||
Ok(text) => break text,
|
||||
Err(why) => {
|
||||
// The late answer isn't in yet.
|
||||
@@ -811,17 +898,17 @@ mod loads {
|
||||
|
||||
#[test]
|
||||
fn a_read_after_the_worker_stops_says_so() {
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, |()| String::new()).unwrap();
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| String::new()).unwrap();
|
||||
// The worker ends when its requests stop: cut them off by hand.
|
||||
drop(std::mem::replace(&mut loads.line, Line::dead()));
|
||||
assert_eq!(loads.get((), Duration::from_millis(50)), Err(GONE.to_string()));
|
||||
assert_eq!(loads.get((), UNTIL_ANSWERED), Err(GONE.to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_threads_reads_stop_with_the_reads() {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, |()| 1).unwrap();
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| 1).unwrap();
|
||||
let asker = loads.asker();
|
||||
assert_eq!(asker.ask(()).and_then(|a| wait_for_answer(&a, Duration::from_secs(600))), Ok(1));
|
||||
assert_eq!(asker.ask(()).and_then(|a| wait_for_answer(&a, UNTIL_ANSWERED)), Ok(1));
|
||||
drop(loads);
|
||||
assert_eq!(asker.ask(()).err(), Some(GONE.to_string()));
|
||||
// Closed while an asker still holds the line: nothing more is sent.
|
||||
@@ -833,7 +920,7 @@ mod loads {
|
||||
#[test]
|
||||
fn an_answer_waited_for_on_another_thread_holds_back_the_next_read() {
|
||||
let (release, gate) = mpsc::channel::<()>();
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, move |n: u32| {
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |n: u32| {
|
||||
if n == 1 {
|
||||
let _ = gate.recv();
|
||||
}
|
||||
@@ -842,20 +929,21 @@ mod loads {
|
||||
.unwrap();
|
||||
let answer = loads.ask(1).unwrap();
|
||||
// The caller doesn't wait: the answer is waited for wherever the channel goes.
|
||||
let waiter = std::thread::spawn(move || wait_for_answer(&answer, Duration::from_secs(600)));
|
||||
let waiter = std::thread::spawn(move || wait_for_answer(&answer, UNTIL_ANSWERED));
|
||||
// Until it comes, a read fails at once instead of queuing behind it.
|
||||
assert!(loads.get(2, Duration::from_secs(600)).is_err());
|
||||
assert!(loads.get(2, UNTIL_ANSWERED).is_err());
|
||||
release.send(()).unwrap();
|
||||
assert_eq!(waiter.join().ok(), Some(Ok(1)));
|
||||
assert_eq!(loads.get(3, Duration::from_secs(600)), Ok(3));
|
||||
assert_eq!(loads.get(3, UNTIL_ANSWERED), Ok(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_the_reads_waits_until_the_worker_lets_go_of_its_clipboard() {
|
||||
let clipboard = Arc::new(());
|
||||
let held = clipboard.clone();
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, move |()| Arc::strong_count(&held)).unwrap();
|
||||
assert_eq!(loads.get((), Duration::from_secs(600)), Ok(2));
|
||||
// With no limit on the idle wait, the drop ends only once the worker has let go.
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |()| Arc::strong_count(&held)).unwrap();
|
||||
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok(2));
|
||||
drop(loads);
|
||||
assert_eq!(Arc::strong_count(&clipboard), 1, "the worker's handle is gone before the app's");
|
||||
}
|
||||
@@ -865,12 +953,12 @@ mod loads {
|
||||
let now = Instant::now();
|
||||
let limit = Duration::from_secs(25);
|
||||
// No read unanswered: the idle worker ends at once, LOAD_WAIT is only the bound.
|
||||
assert_eq!(stop_by(None, now, limit), now + LOAD_WAIT);
|
||||
assert_eq!(stop_wait(None, now, limit, LOAD_WAIT), LOAD_WAIT);
|
||||
// A read sent 2 s ago that timed out: wait for it until 25 s after it was sent.
|
||||
assert_eq!(stop_by(Some(now - Duration::from_secs(2)), now, limit), now + Duration::from_secs(23));
|
||||
assert_eq!(stop_wait(Some(now - Duration::from_secs(2)), now, limit, LOAD_WAIT), Duration::from_secs(23));
|
||||
// Its limit already over, or no limit (data-control, the core protocol): no wait.
|
||||
assert!(stop_by(Some(now - Duration::from_secs(30)), now, limit) <= now);
|
||||
assert_eq!(stop_by(Some(now), now, Duration::ZERO), now);
|
||||
assert_eq!(stop_wait(Some(now - Duration::from_secs(30)), now, limit, LOAD_WAIT), Duration::ZERO);
|
||||
assert_eq!(stop_wait(Some(now), now, Duration::ZERO, LOAD_WAIT), Duration::ZERO);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -885,6 +973,8 @@ mod portable {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
use super::loads::Waits;
|
||||
use super::{
|
||||
BITMAP, ClipboardBackend, ClipboardError, ClipboardImage, ClipboardRead, Flavor, Flavour, LaterFlavor, PNG, TEXT, copied_file, decode_png,
|
||||
engine_mimes, png_flavour, read_flavor, read_image_flavor, read_later_flavor, takes_files,
|
||||
@@ -991,28 +1081,21 @@ mod portable {
|
||||
reads.get(request, wait).unwrap_or_else(|why| Answer::failed(request, why))
|
||||
}
|
||||
|
||||
/// The longest a paste's bitmap read of arboard's waits for the app that copied, off the UI
|
||||
/// thread: the bitmap's transfer and its PNG decoding happen within the read. A paste waits as
|
||||
/// long, from when it was sent, for a read that got no answer in its wait, the core protocol's
|
||||
/// text read included. Text, file lists and the UI thread's bitmap check wait
|
||||
/// [`LOAD_WAIT`](super::loads::LOAD_WAIT).
|
||||
/// How long a read of `request` waits for the app that copied: `waits.image` for a bitmap,
|
||||
/// `waits.load` otherwise.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
const IMAGE_WAIT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// How long a read of `request` waits for the app that copied.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
fn wait_for(request: Request) -> Duration {
|
||||
fn wait_for(waits: Waits, request: Request) -> Duration {
|
||||
match request {
|
||||
Request::Image => IMAGE_WAIT,
|
||||
Request::Text | Request::Files => super::loads::LOAD_WAIT,
|
||||
Request::Image => waits.image,
|
||||
Request::Text | Request::Files => waits.load,
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a paste's read of `request` after a late answer waits at `now`: as long as any read
|
||||
/// of `request`, or until [`IMAGE_WAIT`] after the unanswered read was `sent` when that is later.
|
||||
/// of `request`, or until `waits.image` after the unanswered read was `sent` when that is later.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
fn follow_up_wait(request: Request, sent: Instant, now: Instant) -> Duration {
|
||||
wait_for(request).max((sent + IMAGE_WAIT).saturating_duration_since(now))
|
||||
fn follow_up_wait(waits: Waits, request: Request, sent: Instant, now: Instant) -> Duration {
|
||||
wait_for(waits, request).max(super::loads::left(sent, waits.image, now))
|
||||
}
|
||||
|
||||
/// The longest an X11 read of arboard's lasts while the owner sends nothing: a text read tries
|
||||
@@ -1063,6 +1146,8 @@ mod portable {
|
||||
sent: Instant,
|
||||
/// The worker, for the paste's other reads.
|
||||
reads: super::loads::Asker<Request, Answer>,
|
||||
/// How long the worker's reads wait.
|
||||
waits: Waits,
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
@@ -1078,7 +1163,8 @@ mod portable {
|
||||
}
|
||||
|
||||
/// What a paste of one of `mimes` takes, once this read's answer comes, waiting for it until
|
||||
/// [`IMAGE_WAIT`] after it was sent, as long as a paste's bitmap read waits. Once it comes,
|
||||
/// `waits.image` ([`IMAGE_WAIT`](super::loads::IMAGE_WAIT)) after it was sent, as long as a
|
||||
/// paste's bitmap read waits. Once it comes,
|
||||
/// the same read is made again, since the clipboard may have changed hands meanwhile.
|
||||
/// `None`, so the paste takes the internal clipboard, when that answer doesn't come or the
|
||||
/// new one is what `ours` put on the clipboard. Otherwise the clipboard is read as
|
||||
@@ -1088,12 +1174,12 @@ mod portable {
|
||||
/// names a picture (`adopt_system_clipboard_or_defer` in `vectorcraft-ui-egui`). Those reads
|
||||
/// wait as [`follow_up_wait`] says.
|
||||
fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
let wait = (self.sent + IMAGE_WAIT).saturating_duration_since(Instant::now());
|
||||
let wait = super::loads::left(self.sent, self.waits.image, Instant::now());
|
||||
super::loads::wait_for_answer(&self.answer, wait).ok()?;
|
||||
let fresh = |request: Request| {
|
||||
self.reads
|
||||
.ask(request)
|
||||
.and_then(|a| super::loads::wait_for_answer(&a, follow_up_wait(request, self.sent, Instant::now())))
|
||||
.and_then(|a| super::loads::wait_for_answer(&a, follow_up_wait(self.waits, request, self.sent, Instant::now())))
|
||||
.unwrap_or_else(|why| Answer::failed(request, why))
|
||||
};
|
||||
// The late answer may come from an app that lost the clipboard while it was awaited.
|
||||
@@ -1139,14 +1225,15 @@ mod portable {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
impl Late {
|
||||
/// What a paste of one of `mimes` takes once the answer comes ([`Unanswered::paste`]). The
|
||||
/// core protocol's answer is waited for as long, until [`IMAGE_WAIT`] after its read was
|
||||
/// sent; then the clipboard is read again and pasted as at once, unless it holds the Copy
|
||||
/// made here ([`super::wayland::Unanswered::paste`]).
|
||||
/// core protocol's answer is waited for as long, until
|
||||
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) after its read was sent; then the clipboard is
|
||||
/// read again and pasted as at once, unless it holds the Copy made here
|
||||
/// ([`super::wayland::Unanswered::paste`]).
|
||||
fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
match self {
|
||||
Self::Arboard(unanswered) => unanswered.paste(ours, mimes),
|
||||
#[cfg(target_os = "linux")]
|
||||
Self::Wayland(unanswered) => unanswered.paste(mimes, IMAGE_WAIT),
|
||||
Self::Wayland(unanswered) => unanswered.paste(mimes),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1163,8 +1250,9 @@ mod portable {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
{
|
||||
let mut reader = arboard::Clipboard::new().map_err(|e| e.to_string())?;
|
||||
let reads = super::loads::Loads::spawn("clipboard-read", finish(on_data_control()), move |request| answer(&mut reader, request))
|
||||
.ok_or("the clipboard's reader didn't start")?;
|
||||
let reads =
|
||||
super::loads::Loads::spawn("clipboard-read", finish(on_data_control()), Waits::APP, move |request| answer(&mut reader, request))
|
||||
.ok_or("the clipboard's reader didn't start")?;
|
||||
Ok(Self { reads, unanswered: None, cb })
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))]
|
||||
@@ -1181,13 +1269,13 @@ mod portable {
|
||||
impl<C> Arboard<C> {
|
||||
/// Reads on the worker; the write handle `C` is not used.
|
||||
fn read(&mut self, request: Request) -> Answer {
|
||||
self.read_waiting(request, wait_for(request))
|
||||
self.read_waiting(request, wait_for(self.reads.waits(), request))
|
||||
}
|
||||
|
||||
/// A bitmap read on the worker that waits [`LOAD_WAIT`](super::loads::LOAD_WAIT) at most, for
|
||||
/// a check on the UI thread.
|
||||
fn image_now(&mut self) -> Result<arboard::ImageData<'static>, String> {
|
||||
self.read_waiting(Request::Image, super::loads::LOAD_WAIT).image()
|
||||
self.read_waiting(Request::Image, self.reads.waits().load).image()
|
||||
}
|
||||
|
||||
/// `request` read on the worker, waiting `wait` at most. A read that gets no answer in that
|
||||
@@ -1202,7 +1290,7 @@ mod portable {
|
||||
Ok(answer) => answer,
|
||||
Err(why) => {
|
||||
if why != super::loads::GONE {
|
||||
self.unanswered = Some(Unanswered { request, answer, sent, reads: self.reads.asker() });
|
||||
self.unanswered = Some(Unanswered { request, answer, sent, reads: self.reads.asker(), waits: self.reads.waits() });
|
||||
}
|
||||
Answer::failed(request, why)
|
||||
}
|
||||
@@ -1217,11 +1305,13 @@ mod portable {
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// A bitmap read sent to the worker now; the work returned waits [`IMAGE_WAIT`] at most for
|
||||
/// it, so the caller can wait off the UI thread. Err when the read can't be sent.
|
||||
/// A bitmap read sent to the worker now; the work returned waits
|
||||
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most for it, so the caller can wait off the UI
|
||||
/// thread. Err when the read can't be sent.
|
||||
fn image_later(&mut self) -> Result<ImageWork, String> {
|
||||
let wait = self.reads.waits().image;
|
||||
let answer = self.ask(Request::Image)?;
|
||||
Ok(Box::new(move || super::loads::wait_for_answer(&answer, IMAGE_WAIT).and_then(Answer::image)))
|
||||
Ok(Box::new(move || super::loads::wait_for_answer(&answer, wait).and_then(Answer::image)))
|
||||
}
|
||||
|
||||
/// The read that got no answer in its wait, while its answer has still not come and a paste
|
||||
@@ -1503,12 +1593,12 @@ mod portable {
|
||||
/// Text and copied files are read here, and work that reads arboard's image comes back. On
|
||||
/// the Wayland core protocol the copied files, else the first of `mimes` the clipboard
|
||||
/// offers, is read: text here, file lists, SVG and PNG by the work that comes back, which
|
||||
/// waits [`IMAGE_WAIT`] at most.
|
||||
/// waits [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most.
|
||||
fn read_now_or_later(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
|
||||
let cb = self.cb(Asker::User).ok()?;
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Backend::Wayland(cb) = cb {
|
||||
return cb.read(mimes, IMAGE_WAIT);
|
||||
return cb.read(mimes);
|
||||
}
|
||||
if let Some(f) = copied_file(cb.file_list(), mimes) {
|
||||
return Some(ClipboardRead::Now(f));
|
||||
@@ -1554,7 +1644,8 @@ mod portable {
|
||||
/// arboard takes the text, else the PNG as a bitmap; the Wayland core protocol offers the
|
||||
/// SVG, PNG and text together ([`DataClipboard::copy`](super::wayland::DataClipboard::copy)).
|
||||
/// The index answered is the flavour that went out: the text, else the PNG, and on the
|
||||
/// core protocol the first flavour it offers.
|
||||
/// core protocol the first flavour it offers. On macOS the other flavours are then added
|
||||
/// to the pasteboard item arboard wrote ([`pasteboard_additions`](super::pasteboard_additions)).
|
||||
fn write(&mut self, flavors: &[Flavor]) -> Result<usize, ClipboardError> {
|
||||
let cb = self.cb(Asker::User).map_err(ClipboardError::Other)?;
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -1591,6 +1682,8 @@ mod portable {
|
||||
// What a read got late was on the clipboard before this write.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
cb.forget_unanswered();
|
||||
#[cfg(target_os = "macos")]
|
||||
super::mac::add(&super::pasteboard_additions(flavors));
|
||||
self.ours = ours;
|
||||
Ok(wrote)
|
||||
}
|
||||
@@ -1654,9 +1747,12 @@ mod portable {
|
||||
mod tests {
|
||||
use std::cell::Cell;
|
||||
|
||||
use super::super::loads::Loads;
|
||||
use super::super::loads::{Loads, Waits};
|
||||
use super::*;
|
||||
|
||||
/// No limit: a wait ends when its answer comes.
|
||||
const UNTIL_ANSWERED: Duration = Duration::MAX;
|
||||
|
||||
/// A clock that starts now and moves only when told.
|
||||
struct Clock(Cell<Instant>);
|
||||
|
||||
@@ -1780,27 +1876,27 @@ mod portable {
|
||||
fn reads_return_while_the_clipboard_owner_sends_nothing() {
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
// The app that copied never sends its data until released.
|
||||
let mut reads = Loads::spawn("test", Duration::ZERO, move |request| {
|
||||
let mut reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| {
|
||||
let _ = gate.recv();
|
||||
Answer::failed(request, "late".into())
|
||||
})
|
||||
.unwrap();
|
||||
// Copy's look at the text, Paste's file list and its bitmap: none waits for the owner.
|
||||
assert!(read_within(&mut reads, Request::Text, Duration::ZERO).text().is_err());
|
||||
assert!(read_within(&mut reads, Request::Files, Duration::from_secs(600)).files().is_empty());
|
||||
assert!(read_within(&mut reads, Request::Image, Duration::from_secs(600)).image().is_err());
|
||||
assert!(read_within(&mut reads, Request::Files, UNTIL_ANSWERED).files().is_empty());
|
||||
assert!(read_within(&mut reads, Request::Image, UNTIL_ANSWERED).image().is_err());
|
||||
drop(release);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_read_takes_its_own_answer() {
|
||||
let mut reads = Loads::spawn("test", Duration::ZERO, |request| match request {
|
||||
let mut reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |request| match request {
|
||||
Request::Text => Answer::Text(Ok("<svg/>".into())),
|
||||
Request::Image => Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) })),
|
||||
Request::Files => Answer::Files(vec![PathBuf::from("art.svg")]),
|
||||
})
|
||||
.unwrap();
|
||||
let wait = Duration::from_secs(600);
|
||||
let wait = UNTIL_ANSWERED;
|
||||
assert_eq!(read_within(&mut reads, Request::Text, wait).text(), Ok("<svg/>".to_string()));
|
||||
assert_eq!(read_within(&mut reads, Request::Image, wait).image().map(|i| (i.width, i.height)), Ok((2, 1)));
|
||||
assert_eq!(read_within(&mut reads, Request::Files, wait).files(), [PathBuf::from("art.svg")]);
|
||||
@@ -1847,7 +1943,8 @@ mod portable {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn arboards_reads_run_on_its_reader_and_wait_by_kind() {
|
||||
let reads = Loads::spawn("test", Duration::ZERO, |request| match request {
|
||||
// The reads wait for their answer however long it takes, so the answer decides the result.
|
||||
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |request| match request {
|
||||
Request::Text => Answer::Text(Ok("read on the worker".into())),
|
||||
_ => Answer::failed(request, "not asked".into()),
|
||||
})
|
||||
@@ -1855,15 +1952,18 @@ mod portable {
|
||||
// `()` for writes: a read made through the write handle wouldn't build.
|
||||
let mut cb = Arboard { reads, unanswered: None, cb: () };
|
||||
assert_eq!(cb.read(Request::Text).text(), Ok("read on the worker".to_string()));
|
||||
assert_eq!(wait_for(Request::Text), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(wait_for(Request::Files), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(wait_for(Request::Image), Duration::from_secs(10));
|
||||
let app = Waits::APP;
|
||||
assert_eq!(wait_for(app, Request::Text), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(wait_for(app, Request::Files), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(wait_for(app, Request::Image), Duration::from_secs(10));
|
||||
// A paste's reads after a late answer wait until 10 s after the unanswered read was
|
||||
// sent, and never less than any read of their kind.
|
||||
let sent = Instant::now();
|
||||
assert_eq!(follow_up_wait(Request::Text, sent, sent + Duration::from_secs(3)), Duration::from_secs(7));
|
||||
assert_eq!(follow_up_wait(Request::Files, sent, sent + Duration::from_secs(9)), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(follow_up_wait(Request::Image, sent, sent + Duration::from_secs(20)), IMAGE_WAIT);
|
||||
assert_eq!(follow_up_wait(app, Request::Text, sent, sent + Duration::from_secs(3)), Duration::from_secs(7));
|
||||
assert_eq!(follow_up_wait(app, Request::Files, sent, sent + Duration::from_secs(9)), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(follow_up_wait(app, Request::Image, sent, sent + Duration::from_secs(20)), super::super::loads::IMAGE_WAIT);
|
||||
// With no limit, the follow-up reads have none either.
|
||||
assert_eq!(follow_up_wait(Waits::UNTIL_ANSWERED, Request::Text, sent, sent + Duration::from_secs(20)), Duration::MAX);
|
||||
// X11 waits for an unanswered read when the clipboard closes; data-control doesn't.
|
||||
assert_eq!(finish(false), X11_READ_LIMIT);
|
||||
assert_eq!(finish(true), Duration::ZERO);
|
||||
@@ -1884,7 +1984,7 @@ mod portable {
|
||||
fn a_bitmap_paste_waits_for_the_owner_off_the_ui_thread() {
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
// The app that copied sends its bitmap only when released.
|
||||
let reads = Loads::spawn("test", Duration::ZERO, move |request| match request {
|
||||
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| match request {
|
||||
Request::Image => {
|
||||
let _ = gate.recv();
|
||||
Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) }))
|
||||
@@ -1903,11 +2003,12 @@ mod portable {
|
||||
}
|
||||
|
||||
/// An arboard clipboard whose owner answers each read with `answer` only once the sender
|
||||
/// returned is used or dropped.
|
||||
/// returned is used or dropped. Its reads wait for their answers with no limit: the
|
||||
/// release decides when a paste gets its answer.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
fn slow_owner(answer: impl Fn(Request) -> Answer + Send + 'static) -> (Arboard<()>, std::sync::mpsc::Sender<()>) {
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
let reads = Loads::spawn("test", Duration::ZERO, move |request| {
|
||||
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| {
|
||||
let _ = gate.recv();
|
||||
answer(request)
|
||||
})
|
||||
@@ -2028,10 +2129,10 @@ mod portable {
|
||||
|
||||
/// Core protocol reads of a clipboard offering `types`, whose owner answers each read
|
||||
/// of a text type with `text` and of `image/png` with `png`, only once the sender
|
||||
/// returned is used or dropped.
|
||||
/// returned is used or dropped. The reads wait for their answers with no limit.
|
||||
fn slow_owner(types: &[&str], text: &'static str, png: &'static [u8]) -> (Reads, Arc<Mutex<Seen>>, std::sync::mpsc::Sender<()>) {
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
|
||||
let _ = gate.recv();
|
||||
Ok(if wire == PNG { png.to_vec() } else { text.as_bytes().to_vec() })
|
||||
})
|
||||
@@ -2047,7 +2148,7 @@ mod portable {
|
||||
// in its wait (2 s on the UI thread, none here).
|
||||
assert!(reads.text(Duration::ZERO).is_err());
|
||||
// The paste's own read fails at once while the owner hasn't answered.
|
||||
assert!(reads.text(Duration::from_secs(600)).is_err());
|
||||
assert!(reads.text(UNTIL_ANSWERED).is_err());
|
||||
// A paste of a bitmap alone can't take text: the read stays kept.
|
||||
assert!(reads.unanswered(&[BITMAP]).is_none());
|
||||
let late = Late::Wayland(reads.unanswered(&PASTE_ORDER).expect("the check's read is kept for the paste"));
|
||||
@@ -2083,7 +2184,7 @@ mod portable {
|
||||
// again and takes the new owner's text.
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
let mut texts_read = 0;
|
||||
let loads = Loads::spawn("test", Duration::ZERO, move |_: String| {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |_: String| {
|
||||
let _ = gate.recv();
|
||||
texts_read += 1;
|
||||
Ok(if texts_read == 1 { "old owner" } else { "new owner" }.as_bytes().to_vec())
|
||||
@@ -2149,7 +2250,7 @@ mod wayland {
|
||||
use wayland_client::protocol::wl_seat::{self, WlSeat};
|
||||
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum};
|
||||
|
||||
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer};
|
||||
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, Waits, left, wait_for_answer};
|
||||
use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, takes_files, uri_list_paths};
|
||||
|
||||
/// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK
|
||||
@@ -2445,16 +2546,18 @@ mod wayland {
|
||||
/// The worker, for the reads made once the answer comes.
|
||||
reads: Asker<String, Got>,
|
||||
seen: Arc<Mutex<Seen>>,
|
||||
/// How long the worker's reads wait.
|
||||
waits: Waits,
|
||||
}
|
||||
|
||||
impl Unanswered {
|
||||
/// What a paste of one of `mimes` takes once this read's answer comes, waiting for it until
|
||||
/// `limit` after the read was sent: the clipboard read again as [`pick_pasted`] reads it,
|
||||
/// each read waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may
|
||||
/// have lost the clipboard meanwhile. None when the answer doesn't come or the clipboard holds this
|
||||
/// connection's Copy.
|
||||
pub(super) fn paste(self, mimes: &[&'static str], limit: Duration) -> Option<Flavour> {
|
||||
let left = |now: Instant| (self.sent + limit).saturating_duration_since(now);
|
||||
/// `waits.image` after the read was sent: the clipboard read again as [`pick_pasted`] reads
|
||||
/// it, each read waiting as long, `waits.load` ([`LOAD_WAIT`]) at least, since the app that
|
||||
/// answers late may have lost the clipboard meanwhile. None when the answer doesn't come or
|
||||
/// the clipboard holds this connection's Copy.
|
||||
pub(super) fn paste(self, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
let left = |now: Instant| left(self.sent, self.waits.image, now);
|
||||
let _late = wait_for_answer(&self.answer, left(Instant::now())).ok()?;
|
||||
let offered = {
|
||||
let seen = lock(&self.seen);
|
||||
@@ -2464,7 +2567,7 @@ mod wayland {
|
||||
seen.offered.clone()
|
||||
};
|
||||
pick_pasted(&offered, mimes, |wire| {
|
||||
wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok()
|
||||
wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, self.waits.load.max(left(Instant::now()))).ok()?.ok()
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2491,7 +2594,8 @@ mod wayland {
|
||||
Ok(got) => Ok(flavour(TEXT, got?).map(|f| String::from_utf8_lossy(&f.data).into_owned()).unwrap_or_default()),
|
||||
Err(why) => {
|
||||
if why != GONE {
|
||||
self.unanswered = Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone() });
|
||||
self.unanswered =
|
||||
Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone(), waits: self.loads.waits() });
|
||||
}
|
||||
Err(why)
|
||||
}
|
||||
@@ -2501,12 +2605,13 @@ mod wayland {
|
||||
/// What a paste of one of `mimes` reads: the files a file manager copied, else the first of
|
||||
/// `mimes` the clipboard offers. A file list is asked for here and read, with the files,
|
||||
/// by the work that comes back, which pastes the first file that is art ([`copied`]) and
|
||||
/// else reads `mimes` as [`pick`] does. Text is read here, [`LOAD_WAIT`] at most, and
|
||||
/// pasted unless it is empty; SVG and PNG are asked for here and waited for, `wait` at most,
|
||||
/// by the work that comes back. When that read fails or is empty, the work reads the rest
|
||||
/// of `mimes` as [`pick`] does. Each read the work makes after the first waits until `wait`
|
||||
/// after the first was sent, [`LOAD_WAIT`] at least.
|
||||
pub(super) fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option<ClipboardRead> {
|
||||
/// else reads `mimes` as [`pick`] does. Text is read here, `waits.load` ([`LOAD_WAIT`]) at
|
||||
/// most, and pasted unless it is empty; SVG and PNG are asked for here and waited for,
|
||||
/// `waits.image` at most, by the work that comes back. When that read fails or is empty,
|
||||
/// the work reads the rest of `mimes` as [`pick`] does. Each read the work makes after the
|
||||
/// first waits until `waits.image` after the first was sent, `waits.load` at least.
|
||||
pub(super) fn read(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
|
||||
let Waits { load, image: wait } = self.loads.waits();
|
||||
if takes_files(mimes) {
|
||||
let offered = lock(&self.seen).offered.clone();
|
||||
if let Some(list) = file_list_type(&offered).map(str::to_string) {
|
||||
@@ -2515,7 +2620,7 @@ mod wayland {
|
||||
self.unanswered = None;
|
||||
let (reads, mimes) = (self.loads.asker(), mimes.to_vec());
|
||||
return Some(ClipboardRead::Later(Box::new(move || {
|
||||
let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now()));
|
||||
let left = || load.max(left(sent, wait, Instant::now()));
|
||||
// The list asked for here is read from its answer, every other type anew.
|
||||
let mut first = Some((list, answer));
|
||||
pick_pasted(&offered, &mimes, |wire| {
|
||||
@@ -2531,7 +2636,7 @@ mod wayland {
|
||||
mimes.iter().enumerate().find_map(|(i, &mime)| {
|
||||
let wire = self.wire(mime)?;
|
||||
if mime == TEXT {
|
||||
let text = self.text(LOAD_WAIT).ok().filter(|t| !t.is_empty())?;
|
||||
let text = self.text(load).ok().filter(|t| !t.is_empty())?;
|
||||
return Some(ClipboardRead::Now(Flavour { mime: TEXT, data: text.into_bytes() }));
|
||||
}
|
||||
let sent = Instant::now();
|
||||
@@ -2543,7 +2648,7 @@ mod wayland {
|
||||
return Some(f);
|
||||
}
|
||||
let offered = lock(&seen).offered.clone();
|
||||
let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now()));
|
||||
let left = || load.max(left(sent, wait, Instant::now()));
|
||||
pick(&offered, &rest, |wire| wait_for_answer(&reads.ask(wire.to_string()).ok()?, left()).ok()?.ok())
|
||||
})))
|
||||
})
|
||||
@@ -2809,7 +2914,7 @@ mod wayland {
|
||||
let receiver = Receiver { conn: conn.clone(), objects: objects.clone(), _window: window.clone() };
|
||||
// Dropping doesn't wait for an unanswered read: only arboard's X11 handles hand what the
|
||||
// app copied on when the last one goes.
|
||||
let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, move |wire| receiver.receive(wire))?;
|
||||
let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, Waits::APP, move |wire| receiver.receive(wire))?;
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let (stopped, held) = (stop.clone(), window.clone());
|
||||
let work = move || {
|
||||
@@ -2846,14 +2951,16 @@ mod wayland {
|
||||
self.conn.flush().map_err(|e| format!("couldn't reach the compositor: {e}"))
|
||||
}
|
||||
|
||||
/// The text, waiting [`LOAD_WAIT`] at most ([`Reads::text`]).
|
||||
pub fn text(&mut self) -> Result<String, String> {
|
||||
self.reads.text(LOAD_WAIT)
|
||||
let wait = self.reads.loads.waits().load;
|
||||
self.reads.text(wait)
|
||||
}
|
||||
|
||||
/// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for `wait` at
|
||||
/// most.
|
||||
pub fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option<ClipboardRead> {
|
||||
self.reads.read(mimes, wait)
|
||||
/// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for
|
||||
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most.
|
||||
pub fn read(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
|
||||
self.reads.read(mimes)
|
||||
}
|
||||
|
||||
pub fn has(&self, mimes: &[&'static str]) -> bool {
|
||||
@@ -3022,8 +3129,8 @@ mod wayland {
|
||||
assert_eq!(keyboard_serial(&modifiers(9), None), None);
|
||||
}
|
||||
|
||||
/// A wait no test reaches: the other end of each pipe below either moves data or closes.
|
||||
const LONG: Duration = Duration::from_secs(600);
|
||||
/// No limit ([`idle_until`]): the other end of each pipe below either moves data or closes.
|
||||
const LONG: Duration = Duration::MAX;
|
||||
|
||||
/// A pipe holding `data`, its write end closed when `close`.
|
||||
fn pipe_with(data: &[u8], close: bool) -> (std::io::PipeReader, Option<std::io::PipeWriter>) {
|
||||
@@ -3041,7 +3148,7 @@ mod wayland {
|
||||
assert_eq!(read_capped(pipe_with(&[0u8; 9], true).0, 8, Duration::ZERO), Err("the clipboard's data is larger than 0 MiB".to_string()));
|
||||
// More than a pipe holds, from an app that is still sending.
|
||||
let (from, to) = std::io::pipe().unwrap();
|
||||
assert!(Sends::default().start(to, vec![0u8; (2 << 20) + 1].into()));
|
||||
assert!(Sends { idle: LONG, ..Sends::default() }.start(to, vec![0u8; (2 << 20) + 1].into()));
|
||||
assert_eq!(read_capped(from, 2 << 20, LONG), Err("the clipboard's data is larger than 2 MiB".to_string()));
|
||||
// A pipe that can't be read: the write end.
|
||||
let (_, to) = std::io::pipe().unwrap();
|
||||
@@ -3095,8 +3202,8 @@ mod wayland {
|
||||
|
||||
#[test]
|
||||
fn a_copys_data_is_sent_through_the_pipe_and_closed() {
|
||||
let sends = Sends::default();
|
||||
assert_eq!(sends.idle, IDLE_WAIT);
|
||||
assert_eq!(Sends::default().idle, IDLE_WAIT);
|
||||
let sends = Sends { idle: LONG, ..Sends::default() };
|
||||
let (from, to) = std::io::pipe().unwrap();
|
||||
let data: Arc<[u8]> = vec![7u8; 300_000].into();
|
||||
assert!(sends.start(to, data.clone()));
|
||||
@@ -3146,9 +3253,10 @@ mod wayland {
|
||||
const NOTHING: Held = &[];
|
||||
const UNKNOWN: Held = &[("application/x-other", b"x")];
|
||||
|
||||
/// Reads of a clipboard holding `data`, answered at once.
|
||||
/// Reads of a clipboard holding `data`, answered at once; each read waits for its answer
|
||||
/// with no limit.
|
||||
fn reads_of(data: Held) -> Reads {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
|
||||
data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.to_vec()).ok_or_else(|| "not offered".to_string())
|
||||
})
|
||||
.unwrap();
|
||||
@@ -3159,27 +3267,26 @@ mod wayland {
|
||||
#[test]
|
||||
fn a_picture_or_svg_alone_can_be_pasted_and_is() {
|
||||
use vectorcraft_engine::cmd::clipboard::PASTE_ORDER;
|
||||
let wait = Duration::from_secs(600);
|
||||
for (data, mime) in [(PNG_ONLY, PNG), (SVG_ONLY, SVG)] {
|
||||
let mut reads = reads_of(data);
|
||||
// The paste check enables Paste from the types alone.
|
||||
assert!(reads.has(&PASTE_ORDER));
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("{mime} is read off the UI thread") };
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("{mime} is read off the UI thread") };
|
||||
assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, data[0].1.to_vec())));
|
||||
}
|
||||
let mut reads = reads_of(TEXT_ONLY);
|
||||
assert!(reads.has(&[TEXT]) && !reads.has(&[BITMAP, SVG]));
|
||||
let Some(ClipboardRead::Now(f)) = reads.read(&PASTE_ORDER, wait) else { panic!("text is read at once") };
|
||||
let Some(ClipboardRead::Now(f)) = reads.read(&PASTE_ORDER) else { panic!("text is read at once") };
|
||||
assert_eq!((f.mime, f.data), (TEXT, b"words".to_vec()));
|
||||
// An empty clipboard, or one with no type a paste reads, enables nothing and pastes nothing.
|
||||
for data in [NOTHING, UNKNOWN] {
|
||||
let mut reads = reads_of(data);
|
||||
assert!(!reads.has(&PASTE_ORDER));
|
||||
assert!(reads.read(&PASTE_ORDER, wait).is_none());
|
||||
assert_eq!(reads.text(wait), Ok(String::new()));
|
||||
assert!(reads.read(&PASTE_ORDER).is_none());
|
||||
assert_eq!(reads.text(Duration::MAX), Ok(String::new()));
|
||||
}
|
||||
// Empty text is not pasted.
|
||||
assert!(reads_of(EMPTY_TEXT).read(&[TEXT], wait).is_none());
|
||||
assert!(reads_of(EMPTY_TEXT).read(&[TEXT]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3188,36 +3295,38 @@ mod wayland {
|
||||
const EMPTY_SVG_TEXT: Held = &[(SVG, b""), ("text/plain", b"words"), (PNG, b"\x89PNG")];
|
||||
const EMPTY_SVG_PNG: Held = &[(SVG, b""), (PNG, b"\x89PNG")];
|
||||
const EMPTY_SVG_URL: Held = &[(SVG, b""), ("text/plain", b"https://example.com/art.png"), (PNG, b"\x89PNG")];
|
||||
let wait = Duration::from_secs(600);
|
||||
const EMPTY_PNG: Held = &[(PNG, b"")];
|
||||
for (data, mime, bytes) in
|
||||
[(EMPTY_SVG_TEXT, TEXT, &b"words"[..]), (EMPTY_SVG_PNG, PNG, &b"\x89PNG"[..]), (EMPTY_SVG_URL, PNG, &b"\x89PNG"[..])]
|
||||
{
|
||||
// Held while the work runs, as the clipboard is.
|
||||
let mut reads = reads_of(data);
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the SVG is asked for") };
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("the SVG is asked for") };
|
||||
assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, bytes.to_vec())));
|
||||
}
|
||||
// A failed PNG read, last of all, pastes nothing.
|
||||
let mut reads = reads_of(EMPTY_PNG);
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the PNG is asked for") };
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("the PNG is asked for") };
|
||||
assert!(work().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_that_fails_pastes_nothing() {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, |_: String| Err::<Vec<u8>, _>("the clipboard's data is larger than 64 MiB".to_string()))
|
||||
.unwrap();
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |_: String| {
|
||||
Err::<Vec<u8>, _>("the clipboard's data is larger than 64 MiB".to_string())
|
||||
})
|
||||
.unwrap();
|
||||
let mut reads = Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&[PNG, "text/plain"]))));
|
||||
assert_eq!(reads.text(Duration::from_secs(600)), Err("the clipboard's data is larger than 64 MiB".to_string()));
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP], Duration::from_secs(600)) else { panic!("the PNG is asked for") };
|
||||
assert_eq!(reads.text(Duration::MAX), Err("the clipboard's data is larger than 64 MiB".to_string()));
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP]) else { panic!("the PNG is asked for") };
|
||||
assert!(work().is_none());
|
||||
}
|
||||
|
||||
/// Reads of a clipboard holding `data` by type, answered at once.
|
||||
/// Reads of a clipboard holding `data` by type, answered at once; each read waits for its
|
||||
/// answer with no limit.
|
||||
fn reads_holding(data: Vec<(String, Vec<u8>)>) -> Reads {
|
||||
let types: Vec<String> = data.iter().map(|(t, _)| t.clone()).collect();
|
||||
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
|
||||
data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.clone()).ok_or_else(|| "not offered".to_string())
|
||||
})
|
||||
.unwrap();
|
||||
@@ -3232,7 +3341,7 @@ mod wayland {
|
||||
|
||||
/// What a paste of `mimes` takes from `reads`.
|
||||
fn paste(reads: &mut Reads, mimes: &[&'static str]) -> Option<(&'static str, Vec<u8>)> {
|
||||
match reads.read(mimes, Duration::from_secs(600))? {
|
||||
match reads.read(mimes)? {
|
||||
ClipboardRead::Now(f) => Some((f.mime, f.data)),
|
||||
ClipboardRead::Later(work) => work().map(|f| (f.mime, f.data)),
|
||||
}
|
||||
@@ -3296,15 +3405,29 @@ mod wayland {
|
||||
}
|
||||
|
||||
/// The macOS pasteboard's vector art and bitmaps as they are (arboard reads text, and of the
|
||||
/// pictures TIFF only, decoded).
|
||||
/// pictures TIFF only, decoded), and the formats Copy adds to what arboard wrote.
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac {
|
||||
use objc2::rc::autoreleasepool;
|
||||
use objc2_app_kit::NSPasteboard;
|
||||
use objc2_foundation::{NSArray, NSString};
|
||||
use objc2_foundation::{NSArray, NSData, NSString};
|
||||
|
||||
use super::{Flavour, MAX_BYTES, copy_within, pasteboard_types};
|
||||
|
||||
/// Adds `types` ([`super::pasteboard_additions`]: each pasteboard type with its data) to the
|
||||
/// item arboard just wrote. A type that can't be added is logged, and what arboard wrote still
|
||||
/// carries the copy.
|
||||
pub fn add(types: &[(&str, &[u8])]) {
|
||||
autoreleasepool(|_| {
|
||||
let pasteboard = NSPasteboard::generalPasteboard();
|
||||
for &(t, data) in types {
|
||||
if !pasteboard.setData_forType(Some(&NSData::with_bytes(data)), &NSString::from_str(t)) {
|
||||
log::warn!("clipboard: couldn't add {t}");
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Does the pasteboard hold one of `mimes` ([`pasteboard_types`])? Asks for its types only.
|
||||
pub fn has(mimes: &[&'static str]) -> bool {
|
||||
autoreleasepool(|_| {
|
||||
@@ -3393,6 +3516,25 @@ mod tests {
|
||||
assert!(at(PDF) < at(EPS) && at(EPS) < at(TEXT) && at(TEXT) < at(BITMAP));
|
||||
}
|
||||
|
||||
/// On macOS a Copy puts every format on the pasteboard, not only the text or the picture
|
||||
/// arboard writes (#6310): with On Copy: PDF the PDF goes with the picture, and with Include
|
||||
/// SVG Code the SVG and the PDF go with the markup as text.
|
||||
#[test]
|
||||
fn a_copy_adds_its_other_formats_to_the_pasteboard() {
|
||||
let flavor = |mime: &'static str, data: &[u8]| Flavor::new(mime, data.to_vec());
|
||||
let added = |flavors: &[Flavor]| pasteboard_additions(flavors).into_iter().map(|(t, data)| (t, data.to_vec())).collect::<Vec<_>>();
|
||||
// On Copy: PDF alone: arboard writes the picture, and the PDF is added beside it.
|
||||
let pdf_only = [flavor(PDF, b"%PDF"), flavor(PNG, b"png")];
|
||||
assert_eq!(added(&pdf_only), [("com.adobe.pdf", b"%PDF".to_vec()), ("public.png", b"png".to_vec())]);
|
||||
// Include SVG Code with the PDF: arboard writes the markup as text, and the SVG, PDF and
|
||||
// picture are added in the order Copy offers them.
|
||||
let both = [flavor(TEXT, b"<svg/>"), flavor(SVG, b"<svg/>"), flavor(PDF, b"%PDF"), flavor(PNG, b"png")];
|
||||
let types: Vec<_> = added(&both).into_iter().map(|(t, _)| t).collect();
|
||||
assert_eq!(types, ["public.svg-image", "com.adobe.pdf", "public.png"]);
|
||||
// An empty flavour and a type the pasteboard doesn't carry are left out.
|
||||
assert!(added(&[flavor(PDF, b""), flavor(EMF, b"emf"), flavor("text/html", b"<p>")]).is_empty());
|
||||
}
|
||||
|
||||
/// An .eps file copied in a file manager pastes as EPS.
|
||||
#[test]
|
||||
fn a_copied_eps_file_pastes() {
|
||||
|
||||
@@ -220,11 +220,20 @@ fn report_path(dir: &Path) -> PathBuf {
|
||||
dir.join(format!("{REPORT_PREFIX}{}.txt", std::process::id()))
|
||||
}
|
||||
|
||||
/// A report file this process wrote and holds locked until the interface answers again.
|
||||
/// A report file this process holds locked: the one it wrote, until the interface answers again,
|
||||
/// or a left one while it is read. Dropping it unlocks the file. A child process that any thread
|
||||
/// starts holds a copy of the file's handle until it runs its program, and the lock is only freed
|
||||
/// by closing every copy or by unlocking.
|
||||
#[derive(Debug)]
|
||||
pub struct Held {
|
||||
path: PathBuf,
|
||||
_file: File,
|
||||
file: File,
|
||||
}
|
||||
|
||||
impl Drop for Held {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.file.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `text` to this process's report file in `dir` and lock it. Where the file system has no
|
||||
@@ -237,7 +246,7 @@ fn write_report(dir: &Path, text: &str) -> std::io::Result<Held> {
|
||||
log::warn!("the hang report file is written without a lock: {e}");
|
||||
}
|
||||
file.write_all(text.as_bytes())?;
|
||||
Ok(Held { path, _file: file })
|
||||
Ok(Held { path, file })
|
||||
}
|
||||
|
||||
/// Whether a report file whose `try_lock` gave `locked` was abandoned: nobody holds it. A file
|
||||
@@ -253,13 +262,14 @@ fn abandoned(locked: Result<(), std::fs::TryLockError>) -> bool {
|
||||
|
||||
/// The report file at `path`, opened and locked, with its length, when it was abandoned
|
||||
/// ([`abandoned`]) and is not empty (an empty one may be being written).
|
||||
fn open_abandoned(path: &Path) -> Option<(File, u64)> {
|
||||
fn open_abandoned(path: &Path) -> Option<(Held, u64)> {
|
||||
let file = File::options().read(true).write(true).open(path).ok()?;
|
||||
if !abandoned(file.try_lock()) {
|
||||
return None;
|
||||
}
|
||||
let len = file.metadata().map_or(0, |m| m.len());
|
||||
(len > 0).then_some((file, len))
|
||||
let held = Held { path: path.to_path_buf(), file };
|
||||
let len = held.file.metadata().map_or(0, |m| m.len());
|
||||
(len > 0).then_some((held, len))
|
||||
}
|
||||
|
||||
/// The reports that sessions closed while they did not answer left in `dir`, oldest first; `None`
|
||||
@@ -286,20 +296,20 @@ pub fn take_previous(dir: &Path) -> Option<String> {
|
||||
// Newest first: only abandoned reports count toward the limit.
|
||||
let mut texts = Vec::new();
|
||||
for (_, path) in found.into_iter().rev() {
|
||||
let Some((file, len)) = open_abandoned(&path) else { continue };
|
||||
let Some((held, len)) = open_abandoned(&path) else { continue };
|
||||
if texts.len() == MAX_REPORT_FILES {
|
||||
drop(file);
|
||||
drop(held);
|
||||
remove_quietly(&path);
|
||||
continue;
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
let text = if len <= MAX_REPORT_BYTES && (&file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() {
|
||||
let text = if len <= MAX_REPORT_BYTES && (&held.file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() {
|
||||
String::from_utf8_lossy(&bytes).into_owned()
|
||||
} else {
|
||||
format!("The report was larger than {MAX_REPORT_BYTES} bytes and was not read.\n")
|
||||
};
|
||||
// Closed (and unlocked) before it is moved: Windows moves no open file.
|
||||
drop(file);
|
||||
drop(held);
|
||||
if !texts.is_empty() {
|
||||
remove_quietly(&path);
|
||||
} else if let Err(e) = std::fs::rename(&path, dir.join(PREVIOUS_FILE)) {
|
||||
@@ -324,8 +334,8 @@ pub static CLOSING: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Remove `held`'s file, closing it first. → the error message; a file already gone is none.
|
||||
fn remove(held: Held) -> Option<String> {
|
||||
let Held { path, _file: file } = held;
|
||||
drop(file);
|
||||
let path = held.path.clone();
|
||||
drop(held);
|
||||
match std::fs::remove_file(&path) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Some(e.to_string()),
|
||||
_ => None,
|
||||
|
||||
@@ -136,6 +136,17 @@ fn a_stall_writes_the_report_file_and_its_end_removes_it() {
|
||||
assert!(shared.last.lock().unwrap().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_report_frees_its_lock_while_a_copy_of_its_handle_is_open() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let held = write_report(dir.path(), "left\n").unwrap();
|
||||
// A child process that is starting holds such a copy.
|
||||
let copy = held.file.try_clone().unwrap();
|
||||
drop(held);
|
||||
assert_eq!(take_previous(dir.path()).as_deref(), Some("left\n"), "a dropped report is no longer locked");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_normally_removes_the_report_and_writes_no_more() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -309,7 +309,7 @@ pub struct Scatter {
|
||||
pub art: Node,
|
||||
/// Size range in percent of the art.
|
||||
pub size: (f64, f64),
|
||||
/// Spacing range in percent of the (scaled) art width.
|
||||
/// Spacing range in percent of the (scaled) art width, its strokes included.
|
||||
pub spacing: (f64, f64),
|
||||
/// Perpendicular offset range in percent of the (scaled) art height.
|
||||
pub scatter: (f64, f64),
|
||||
|
||||
@@ -272,6 +272,22 @@ fn scatter_count_and_spacing() {
|
||||
assert_eq!(out.len(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_spaces_stroked_art_by_its_stroked_width() {
|
||||
let art = Node::path(
|
||||
NodeId(0),
|
||||
shapes::rectangle(Rect::new(0.0, -2.0, 10.0, 2.0)),
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0),
|
||||
);
|
||||
let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) };
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 120.0, 0.0), &stroke(1.0));
|
||||
let boxes: Vec<Rect> = out.iter().filter_map(Node::visual_bounds).collect();
|
||||
assert!(boxes.len() > 1, "{boxes:?}");
|
||||
for w in boxes.windows(2) {
|
||||
assert!(near(w[1].x0, w[0].x1, 1e-6), "stroked copies at 100% spacing touch: {boxes:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_is_deterministic_and_randomised() {
|
||||
let b = Brush {
|
||||
|
||||
@@ -540,7 +540,10 @@ fn vary(rng: &mut Rng, (a, b): (f64, f64), mode: Variation, pen: PenAt) -> f64 {
|
||||
|
||||
pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec<Node> {
|
||||
let Some(b) = sc.art.geometric_bounds() else { return vec![] };
|
||||
let (aw, ah) = (b.width().max(1e-3), b.height().max(1e-3));
|
||||
// Copies are spaced by the width of the art with its strokes, so at 100% spacing stroked
|
||||
// copies touch instead of overlapping by the stroke.
|
||||
let aw = sc.art.visual_bounds().unwrap_or(b).width().max(1e-3);
|
||||
let ah = b.height().max(1e-3);
|
||||
let mut rng = Rng::new(seed_of(bp, name));
|
||||
let [size_mode, spacing_mode, scatter_mode, rotation_mode] = sc.modes();
|
||||
let mut out = Budget::default();
|
||||
@@ -1129,11 +1132,23 @@ mod tests {
|
||||
/// Fitting is bounded however badly the map behaves: where it gives points that are not finite
|
||||
/// the tile falls back to chords with those points left out (or to nothing), and where it never
|
||||
/// fits (a map that jumps everywhere) the halving stops at its depth and anchor count. Either
|
||||
/// way the call comes back promptly with finite geometry.
|
||||
/// way the call comes back with finite geometry, having called the map a bounded number of
|
||||
/// times.
|
||||
#[test]
|
||||
fn a_map_that_misbehaves_still_returns_promptly_and_finite() {
|
||||
let b = Rect::new(0.0, -20.0, 40.0, 20.0);
|
||||
let tile = circle_tile(b);
|
||||
// Each piece the fitting tries reads its two ends, the derivatives there and the checks
|
||||
// between them. Fitted pieces are at most the chords, so the halving tries at most twice
|
||||
// as many pieces plus those on the way down to the one that gives up. The chord route
|
||||
// maps each chord point once more.
|
||||
let NodeKind::Path { path, .. } = &tile.kind else { panic!("the tile is a path") };
|
||||
let allowed: usize = path
|
||||
.subpaths
|
||||
.iter()
|
||||
.filter_map(|sp| densified(sp, 0.25, 1.5))
|
||||
.map(|dense| 1 + (FIT_CHECKS + 3) * (2 * dense.len() + FIT_DEPTH as usize + 1) + dense.len())
|
||||
.sum();
|
||||
let finite = |n: &Node| match &n.kind {
|
||||
NodeKind::Path { path, .. } => {
|
||||
path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite())
|
||||
@@ -1147,9 +1162,14 @@ mod tests {
|
||||
&|_| Point::new(f64::NAN, f64::NAN),
|
||||
];
|
||||
for (i, f) in maps.iter().enumerate() {
|
||||
let t0 = std::time::Instant::now();
|
||||
let out = warp_node(&tile, f, 0.25, 1.5, 0.25, 1.0);
|
||||
assert!(t0.elapsed() < std::time::Duration::from_secs(2), "map {i} took {:?}", t0.elapsed());
|
||||
// Past the allowance the map places nothing, so a warp that keeps calling it stops.
|
||||
let calls = std::cell::Cell::new(0usize);
|
||||
let counted = |p: Point| {
|
||||
calls.set(calls.get() + 1);
|
||||
if calls.get() > allowed { Point::new(f64::NAN, f64::NAN) } else { f(p) }
|
||||
};
|
||||
let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0);
|
||||
assert!(calls.get() <= allowed, "map {i} was called {} times, {allowed} allowed", calls.get());
|
||||
match (i, &out) {
|
||||
(3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"),
|
||||
(_, Some(n)) => assert!(finite(n), "map {i} drew non-finite geometry"),
|
||||
|
||||
@@ -708,16 +708,29 @@ fn rgb_color([r, g, b]: [u8; 3]) -> Color {
|
||||
Color::rgb8(r, g, b)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many names [`unique`] tried on this thread (tests).
|
||||
pub(crate) static SYMBOL_NAMES_TRIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Whether `taken` holds `name`, counted as one name tried (tests).
|
||||
fn is_taken(taken: &HashSet<String>, name: &str) -> bool {
|
||||
#[cfg(test)]
|
||||
SYMBOL_NAMES_TRIED.with(|n| n.set(n.get().saturating_add(1)));
|
||||
taken.contains(name)
|
||||
}
|
||||
|
||||
/// `base`, or `base 2`, `base 3`… when taken; `next` remembers where each base left off.
|
||||
fn unique(base: &str, next: &mut HashMap<String, usize>, taken: &HashSet<String>) -> String {
|
||||
if !taken.contains(base) {
|
||||
if !is_taken(taken, base) {
|
||||
return base.to_string();
|
||||
}
|
||||
let i = next.entry(base.to_string()).or_insert(2);
|
||||
loop {
|
||||
let name = format!("{base} {i}");
|
||||
*i += 1;
|
||||
if !taken.contains(&name) {
|
||||
if !is_taken(taken, &name) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,6 +175,32 @@ fn layer(l: model::Layer) -> LayerDef {
|
||||
/// drawings have a few dozen layouts with short names.
|
||||
const MAX_LAYOUT_NAME_BYTES: usize = 4 << 20;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`layouts`] compared two layout names on this thread (tests).
|
||||
pub(crate) static LAYOUT_NAME_COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A paper layout's name as [`layouts`] de-duplicates it (lower case: names differing only in
|
||||
/// ASCII case are one layout).
|
||||
struct LayoutKey(String);
|
||||
|
||||
impl PartialEq for LayoutKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
LAYOUT_NAME_COMPARISONS.with(|n| n.set(n.get().saturating_add(1)));
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for LayoutKey {}
|
||||
|
||||
impl std::hash::Hash for LayoutKey {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.0.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Model space, then each paper layout (its LAYOUT object, in tab order); a file without layout
|
||||
/// objects but with paper-space art has one paper layout.
|
||||
fn layouts(doc: &model::Document<'_>, block_names: &HashMap<u64, &str>) -> Vec<LayoutDef> {
|
||||
@@ -187,7 +213,7 @@ fn layouts(doc: &model::Document<'_>, block_names: &HashMap<u64, &str>) -> Vec<L
|
||||
continue;
|
||||
}
|
||||
let Some(block) = block else { continue };
|
||||
let key = l.name.to_ascii_lowercase();
|
||||
let key = LayoutKey(l.name.to_ascii_lowercase());
|
||||
let cost = l.name.len() + block.len();
|
||||
// A layout past the allowance is skipped alone: a later short one is still offered, and a
|
||||
// skipped one reserves neither its name nor its bytes.
|
||||
|
||||
@@ -743,15 +743,16 @@ fn many_by_block_looks_import_in_linear_time() {
|
||||
inserts.extend([(0, "INSERT"), (2, "Door"), (420, colour), (10, "0"), (20, "0")]);
|
||||
}
|
||||
let text = with_door(by_block, &inserts);
|
||||
let start = std::time::Instant::now();
|
||||
build::SYMBOL_NAMES_TRIED.with(|t| t.set(0));
|
||||
let doc = open(&text, &points()).document;
|
||||
let took = start.elapsed();
|
||||
let tried = build::SYMBOL_NAMES_TRIED.with(std::cell::Cell::get);
|
||||
let mut names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names.len(), n);
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
assert_eq!(names.len(), n, "names stay unique");
|
||||
assert!(took < std::time::Duration::from_secs(4), "import took {took:?}");
|
||||
// Each symbol after the first tries its label and then the next free suffix.
|
||||
assert!(tried < 2 * n, "{tried} names tried for {n} symbols");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1001,7 +1002,7 @@ fn binary_dwg_damaged_and_foreign_files() {
|
||||
// A binary DXF opens as its ASCII form does.
|
||||
let ascii = entities(LINE);
|
||||
let tags = craft_dxf::parse(&ascii).unwrap();
|
||||
let r = open(&craft_dxf::write_binary(&tags, true), &points());
|
||||
let r = open(&craft_dxf::write_binary(&tags, true).unwrap(), &points());
|
||||
assert_eq!(leaves(&r.document).len(), 1);
|
||||
let e = import(b"AC1032\x00\x00\x00", &ImportOptions::default()).unwrap_err();
|
||||
assert!(e.contains("DWG"), "{e}");
|
||||
@@ -1151,12 +1152,13 @@ fn with_layouts(names: &[String]) -> Vec<u8> {
|
||||
|
||||
#[test]
|
||||
fn many_paper_layouts_are_read_in_linear_time() {
|
||||
let names: Vec<String> = (0..100_000).map(|i| format!("L{i}")).collect();
|
||||
let names: Vec<String> = (0..10_000).map(|i| format!("L{i}")).collect();
|
||||
let bytes = with_layouts(&names);
|
||||
let t = std::time::Instant::now();
|
||||
reader::LAYOUT_NAME_COMPARISONS.with(|c| c.set(0));
|
||||
let info = info(&bytes).unwrap();
|
||||
let compared = reader::LAYOUT_NAME_COMPARISONS.with(std::cell::Cell::get);
|
||||
assert_eq!(info.layouts.len(), names.len() + 1);
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5), "layout de-duplication is quadratic: {:?}", t.elapsed());
|
||||
assert!(compared <= names.len(), "layout de-duplication compared {compared} names for {} layouts", names.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+17
-3
@@ -1211,7 +1211,18 @@ pub fn active_settings() -> ColorSettings {
|
||||
|
||||
/// The color-management context of Edit → Color Settings (the working spaces, intent and black
|
||||
/// point compensation), as [`set_active`] last set them, whatever profiles a document is assigned.
|
||||
/// Inside [`with_active`] on this thread: the working settings of the settings it was given.
|
||||
pub fn working() -> Arc<Cms> {
|
||||
if SCOPED_FLAGS.with(Cell::get) & SCOPED_SET != 0
|
||||
&& let Some(c) = SCOPED.with(|s| s.borrow().clone())
|
||||
{
|
||||
return c.working.clone().unwrap_or(c);
|
||||
}
|
||||
installed_working()
|
||||
}
|
||||
|
||||
/// The working settings of the process, as [`set_active`] last set them.
|
||||
fn installed_working() -> Arc<Cms> {
|
||||
if let Some(c) = WORKING.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
|
||||
return c.clone();
|
||||
}
|
||||
@@ -1241,7 +1252,7 @@ pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> {
|
||||
/// is not of its model, leaves the working space. The working settings stay as they are. True when
|
||||
/// the active settings changed.
|
||||
pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool {
|
||||
let working = working();
|
||||
let working = installed_working();
|
||||
let st = document_settings(&working.settings, rgb, cmyk);
|
||||
if st == installed().settings {
|
||||
return false;
|
||||
@@ -1281,7 +1292,7 @@ const DOCUMENT_CONTEXTS: usize = 8;
|
||||
/// loaded gives the working settings.
|
||||
pub fn for_document(rgb: Option<&str>, cmyk: Option<&str>) -> Arc<Cms> {
|
||||
static KEPT: Mutex<Vec<(u64, Arc<Cms>)>> = Mutex::new(Vec::new());
|
||||
let working = working();
|
||||
let working = installed_working();
|
||||
let st = document_settings(&working.settings, rgb, cmyk);
|
||||
let installed = installed();
|
||||
if st == installed.settings {
|
||||
@@ -1308,7 +1319,10 @@ pub fn for_document(rgb: Option<&str>, cmyk: Option<&str>) -> Arc<Cms> {
|
||||
|
||||
/// Run `f` with `cms` as the active settings on this thread ([`active`], [`crate::Color::to_rgb`]
|
||||
/// and the conversions that read them), as when drawing a document other than the front one
|
||||
/// through its own profiles. Other threads, and this thread after `f`, keep the settings they had.
|
||||
/// through its own profiles, and with the working settings `cms` was made from as the working
|
||||
/// settings ([`working`]): the ones [`for_document`] put the document's profiles in place of, else
|
||||
/// `cms` itself. A [`set_active`] while `f` runs, on any thread, does not change either on this
|
||||
/// thread. Other threads, and this thread after `f`, keep the settings they had.
|
||||
pub fn with_active<R>(cms: Arc<Cms>, f: impl FnOnce() -> R) -> R {
|
||||
/// Puts back the settings this thread had before, when `f` returns or unwinds.
|
||||
struct Restore(Option<Arc<Cms>>, u8);
|
||||
|
||||
@@ -519,6 +519,33 @@ fn with_active_puts_settings_in_place_on_this_thread_only() {
|
||||
assert_eq!((rgb.to_rgb(), ink.to_rgb()), before, "the active settings come back after a panic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_active_keeps_its_working_settings_while_another_thread_sets_them() {
|
||||
let before = working_settings();
|
||||
let p3 = Arc::new(Cms::new(&ColorSettings { rgb: DISPLAY_P3.into(), cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap());
|
||||
let (inside, after_other, other) = with_active(p3.clone(), || {
|
||||
let inside = working();
|
||||
// The same settings again, so other tests in this binary see the same values.
|
||||
let again = before.clone();
|
||||
let other = std::thread::spawn(move || {
|
||||
set_active(&again).unwrap();
|
||||
working()
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
(inside, working(), other)
|
||||
});
|
||||
assert!(Arc::ptr_eq(&inside, &p3), "settings made from no others are their own working settings");
|
||||
assert!(Arc::ptr_eq(&after_other, &p3), "a set_active on another thread leaves this thread's working settings");
|
||||
assert!(!Arc::ptr_eq(&other, &p3), "the other thread has the settings it set");
|
||||
assert_eq!(working_settings(), before, "the working settings come back after");
|
||||
// A document's context keeps the working settings it was made from.
|
||||
let doc = for_document(Some(DISPLAY_P3), None);
|
||||
let (active, working) = with_active(doc, || (active_settings(), working_settings()));
|
||||
assert_eq!(active.rgb, DISPLAY_P3, "the document's profile is active");
|
||||
assert_eq!(working, before, "the working RGB space stays the working one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_gets_the_same_context_for_the_same_profiles() {
|
||||
// Other tests load profiles meanwhile, and a load makes the contexts again: try until one pair
|
||||
|
||||
@@ -731,6 +731,152 @@ fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: O
|
||||
tops
|
||||
}
|
||||
|
||||
/// The most hits [`leaves_at`] lists.
|
||||
pub const MAX_LEAVES_AT: usize = 256;
|
||||
|
||||
/// The hits under `p`, topmost first, at most [`MAX_LEAVES_AT`]: one for each object a click with
|
||||
/// Direct Selection picks there (a path, a compound path or an image, also inside a group), each
|
||||
/// found by a hit test ([`hit_test`]) that passes over the ones found before it. In isolation mode
|
||||
/// (`opt.scope`) only what is inside the isolated group or object is hit. Cmd/Ctrl-clicks with the
|
||||
/// Selection tool step through them (Select Behind).
|
||||
pub fn leaves_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<Hit> {
|
||||
let _walk = ArtWalk::open();
|
||||
// A clipping mask, or a group drawn with its own geometry effects, hits by rules the single
|
||||
// traversal leaves to the hit test: the repeated hit test finds the rest, after the hits found
|
||||
// above them, which the art walked for them already counted against.
|
||||
leaves_at_once(doc, p, opt).unwrap_or_else(|above| leaves_at_repeated_after(doc, p, opt, above))
|
||||
}
|
||||
|
||||
/// [`leaves_at`] by repeated hit tests, each passing over the objects found before it.
|
||||
#[cfg(test)]
|
||||
fn leaves_at_repeated(doc: &Document, p: Point, opt: HitOptions) -> Vec<Hit> {
|
||||
leaves_at_repeated_after(doc, p, opt, vec![])
|
||||
}
|
||||
|
||||
/// [`leaves_at`] by repeated hit tests after `hits`, the topmost hits already found.
|
||||
fn leaves_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, mut hits: Vec<Hit>) -> Vec<Hit> {
|
||||
let mut found: HashSet<NodeId> = hits.iter().map(|h| h.leaf).collect();
|
||||
while hits.len() < MAX_LEAVES_AT
|
||||
&& let Some(h) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true)
|
||||
{
|
||||
if !found.insert(h.leaf) {
|
||||
break;
|
||||
}
|
||||
hits.push(h);
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
/// [`leaves_at`] in one traversal of the document, in the order repeated hit tests
|
||||
/// ([`hit_test_skipping`]) find them. `Err` with the hits found above it when a container under
|
||||
/// `p` clips or draws its art with its own geometry effects ([`leaves_in`]).
|
||||
fn leaves_at_once(doc: &Document, p: Point, opt: HitOptions) -> Result<Vec<Hit>, Vec<Hit>> {
|
||||
let finish = |mut h: Hit| {
|
||||
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
|
||||
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
|
||||
h
|
||||
};
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let on_locked = |id: NodeId| {
|
||||
!locks.is_empty() && doc.parent_of(id).and_then(|l| doc.node(l)).is_some_and(Node::is_layer) && doc.node(id).is_some_and(|n| locks.holds(n))
|
||||
};
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
let mut hits = Vec::new();
|
||||
if let Some(scope) = opt.scope
|
||||
&& let Some(isolated) = doc.node(scope)
|
||||
&& let Some(mut chain) = doc.ancestry(scope)
|
||||
{
|
||||
if !doc.is_editable_with(&locks, scope) {
|
||||
return Ok(hits);
|
||||
}
|
||||
let whole = if isolated.is_container() {
|
||||
leaves_in(isolated, p, opt, &symbols, &on_locked, &mut chain, &mut hits)
|
||||
} else {
|
||||
// A single object isolated: only it hits, among its siblings.
|
||||
chain.pop();
|
||||
let Some(parent) = chain.last().and_then(|id| doc.node(*id)) else { return Ok(hits) };
|
||||
leaves_in(parent, p, opt, &symbols, &|id| id != scope || on_locked(id), &mut chain, &mut hits)
|
||||
};
|
||||
let hits = hits.into_iter().map(finish).collect();
|
||||
return if whole { Ok(hits) } else { Err(hits) };
|
||||
}
|
||||
let mut chain = Vec::new();
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
chain.push(layer.id);
|
||||
let opt = if !opt.ignore_layer_preview && previews_off(layer) { HitOptions { outline: true, ..opt } } else { opt };
|
||||
if !leaves_in(layer, p, opt, &symbols, &on_locked, &mut chain, &mut hits) {
|
||||
return Err(hits.into_iter().map(finish).collect());
|
||||
}
|
||||
chain.pop();
|
||||
if hits.len() >= MAX_LEAVES_AT {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(hits.into_iter().map(finish).collect())
|
||||
}
|
||||
|
||||
/// Every editable hit under `p` in `parent`, topmost first, added to `hits` up to
|
||||
/// [`MAX_LEAVES_AT`]: what [`hit_children`] finds first, then what it finds passing over each hit
|
||||
/// found before. `false` when `parent` or a container in it under `p` clips or draws its art with
|
||||
/// its own geometry effects, which [`hit_children`] hits by rules of their own.
|
||||
fn leaves_in(
|
||||
parent: &Node,
|
||||
p: Point,
|
||||
opt: HitOptions,
|
||||
symbols: &SymbolBoxes,
|
||||
skip: &dyn Fn(NodeId) -> bool,
|
||||
chain: &mut Vec<NodeId>,
|
||||
hits: &mut Vec<Hit>,
|
||||
) -> bool {
|
||||
let Some(children) = parent.children() else { return true };
|
||||
if parent.clips() || drawn_art(symbols, parent, opt.outline).is_some() {
|
||||
return false;
|
||||
}
|
||||
for i in hit_order(parent, children, p) {
|
||||
if hits.len() >= MAX_LEAVES_AT {
|
||||
return true;
|
||||
}
|
||||
let Some(c) = children.get(i) else { continue };
|
||||
if !may_hit(parent, i, c, p, opt, symbols, true) || skip(c.id) {
|
||||
continue;
|
||||
}
|
||||
chain.push(c.id);
|
||||
let leaf = |hits: &mut Vec<Hit>, chain: &[NodeId]| {
|
||||
if let Some(kind) = hit_leaf(c, p, opt, symbols) {
|
||||
hits.push(Hit { leaf: c.id, ancestry: chain.to_vec(), kind, contents_of: None, layers: 1 });
|
||||
}
|
||||
};
|
||||
let whole = match &c.kind {
|
||||
NodeKind::Layer { preview: false, .. } if !opt.ignore_layer_preview => {
|
||||
leaves_in(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, hits)
|
||||
}
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } | NodeKind::Envelope { editing: true, .. } => {
|
||||
leaves_in(c, p, opt, symbols, skip, chain, hits)
|
||||
}
|
||||
// A blend's key objects first; its steps hit as the blend.
|
||||
NodeKind::Blend { .. } => {
|
||||
let whole = leaves_in(c, p, opt, symbols, skip, chain, hits);
|
||||
if whole && hits.len() < MAX_LEAVES_AT {
|
||||
leaf(hits, chain);
|
||||
}
|
||||
whole
|
||||
}
|
||||
_ => {
|
||||
leaf(hits, chain);
|
||||
true
|
||||
}
|
||||
};
|
||||
chain.pop();
|
||||
if !whole {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The most objects [`locked_objects_at`] lists.
|
||||
pub const MAX_LOCKED_AT: usize = 20;
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -431,6 +431,17 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// The box of what a path, or the paths of a compound path, draw before the strokes' reach
|
||||
/// ([`PathData::drawn_bounds`]): lone anchors of closed subpaths count only with `dots`. Other
|
||||
/// members of a compound path count by their geometric box. `None` when nothing is drawn.
|
||||
fn drawn(&self, symbols: Option<&SymbolBoxes>, dots: bool) -> Option<Rect> {
|
||||
match &self.kind {
|
||||
NodeKind::Path { path, .. } => path.drawn_bounds(dots),
|
||||
NodeKind::Compound { .. } => self.editing_children().iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.drawn(symbols, dots))),
|
||||
_ => self.geometric(symbols),
|
||||
}
|
||||
}
|
||||
|
||||
/// Visual bounds: what the object paints, its strokes included (paths and compound paths
|
||||
/// measure theirs along their own shape, see [`Appearance::stroked_bounds`]). An image is
|
||||
/// measured by its frame. A symbol instance is measured as in [`Node::geometric_bounds`],
|
||||
@@ -485,7 +496,9 @@ impl Node {
|
||||
self.geometric(symbols).map(|b| b.inflate(o, o))
|
||||
}
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
|
||||
let b = self.geometric(symbols)?;
|
||||
// A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath.
|
||||
let dots = self.appearance.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square));
|
||||
let b = self.drawn(symbols, dots).or_else(|| self.geometric(symbols))?;
|
||||
Some(self.appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default()))
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
|
||||
@@ -469,6 +469,35 @@ 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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]
|
||||
|
||||
@@ -619,7 +619,12 @@ fn moved_type(n: &Node, moves: &[serde_json::Value]) -> Option<Vec<Node>> {
|
||||
}
|
||||
let (_, all) = glyph_outlines(t);
|
||||
let outline = PathData::from_bezpath(&all).transformed(t.xf);
|
||||
let ink = outline.bounds()?;
|
||||
// A contour of one anchor paints only as the dot of a round or projecting character stroke cap.
|
||||
let dots = t
|
||||
.runs
|
||||
.iter()
|
||||
.any(|r| r.style.appearance().painted_strokes().any(|s| matches!(s.cap, vectorcraft_doc::LineCap::Round | vectorcraft_doc::LineCap::Square)));
|
||||
let ink = outline.drawn_bounds(dots)?;
|
||||
let offsets = transform_offsets(moves, &outline)?;
|
||||
if offsets.len() > MAX_TYPE_COPIES {
|
||||
return None;
|
||||
|
||||
@@ -447,6 +447,12 @@ pub(crate) fn apply_one(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &Geo
|
||||
budget.fits(Budget::of(&out)).then_some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The subpaths the Offset Path effect has offset on this thread.
|
||||
pub(crate) static OFFSET_SUBPATHS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Does geometry effect `id` build within the anchors it is given?
|
||||
fn builds_within(id: &str) -> bool {
|
||||
matches!(id, "distort.freeDistort" | "distort.roughen" | "distort.transform" | "distort.twist" | "distort.zigZag") || id.starts_with("warp.")
|
||||
@@ -472,6 +478,8 @@ fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomCont
|
||||
if off.abs() < 1e-9 {
|
||||
return path.clone();
|
||||
}
|
||||
#[cfg(test)]
|
||||
OFFSET_SUBPATHS.with(|n| n.set(n.get() + path.subpaths.len()));
|
||||
vectorcraft_pathops::offset_path(path, off, join(p, "joins"), num(p, "miterLimit", 4.0).clamp(1.0, 500.0))
|
||||
}
|
||||
// Outline Object returns the geometry unchanged. Type reaches every geometry effect as its
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -4,14 +4,15 @@
|
||||
//! (`vectorcraft_tools::addons::parametric_shape`), which SVG export leaves out.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point};
|
||||
use vectorcraft_doc::{Document, Node, NodeKind, Scaling};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point};
|
||||
use vectorcraft_pathops::addons::pathtools::shapes::{ParametricShape, ShapeKind, recognise};
|
||||
use vectorcraft_render::effects;
|
||||
use vectorcraft_tools::addons::parametric_shape::{CREATE, EDIT, KEY, apply, read, stored, to_json};
|
||||
|
||||
use super::super::super::menucmds::whole_or;
|
||||
use super::super::super::{CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection};
|
||||
use super::super::super::object;
|
||||
use super::super::super::{CommandSpec, bad, check_switches, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection};
|
||||
use crate::{EngineError, MAX_COORD, Result, Session};
|
||||
|
||||
/// The undo step's name and the command's label.
|
||||
@@ -33,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Parametric Shape",
|
||||
[],
|
||||
None,
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; a new center, size or rotation moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with it, and with `strokes` its strokes and effects scale; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
@@ -62,6 +63,25 @@ fn shape_node(n: &mut Node, s: &ParametricShape, path: PathData) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The transform that takes the outline of `old` to the one `new` would have if only their
|
||||
/// center, size and rotation differed: what moves, turns and scales the rest of the object (a
|
||||
/// linked opacity mask, gradients and patterns placed on it) with the new numbers.
|
||||
fn carry(old: &ParametricShape, new: &ParametricShape) -> Option<Affine> {
|
||||
let same = old.center == new.center && old.width == new.width && old.height == new.height && old.rotation == new.rotation;
|
||||
(!same).then(|| new.frame() * Affine::scale_non_uniform(new.width / old.width, new.height / old.height) * old.frame().inverse())
|
||||
}
|
||||
|
||||
/// Path node `n`, shape `old`, becomes shape `new`: the node takes the transform between them
|
||||
/// ([`carry`]) with `sc`, and then the outline and numbers of `new` ([`shape_node`]).
|
||||
fn reshape(n: &mut Node, old: &ParametricShape, new: &ParametricShape, sc: Scaling, cmd: &str) -> Result<()> {
|
||||
let path = outline(new, cmd)?;
|
||||
if let Some(xf) = carry(old, new) {
|
||||
n.transform(xf, sc);
|
||||
}
|
||||
shape_node(n, new, path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The outline of `s`, checked already.
|
||||
fn outline(s: &ParametricShape, cmd: &str) -> Result<PathData> {
|
||||
s.path().ok_or_else(|| bad(cmd, "the shape's numbers are out of range"))
|
||||
@@ -97,6 +117,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "the path is locked or hidden"));
|
||||
}
|
||||
let old = d.node(id).and_then(read).ok_or_else(|| bad(C, "the object is not an editable parametric shape"))?;
|
||||
check_switches(p, &["strokes", "corners", "patterns"], C)?;
|
||||
let reference = match p.get("reference").filter(|v| !v.is_null()) {
|
||||
Some(_) => match whole_or(p, "reference", 4, C)? {
|
||||
i @ 0..=8 => Some(i as usize),
|
||||
@@ -121,17 +142,21 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let path = outline(&shape, C)?;
|
||||
// A new center, size or rotation moves, turns or scales the object as a transform does,
|
||||
// with Scale Strokes & Effects and Transform Patterns from `strokes` and `patterns` or the
|
||||
// preferences.
|
||||
let scales = carry(&old, &shape).is_some_and(|xf| Scaling::factor(xf).is_some());
|
||||
let base = if scales { object::scaling(s, p) } else { Scaling::default() };
|
||||
let sc = Scaling { patterns: object::transform_patterns(s, p, &[id])?, ..base };
|
||||
s.edit(EDIT, |d, sel| {
|
||||
shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, path);
|
||||
reshape(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &old, &shape, sc, C)?;
|
||||
if let Some((i, m, was)) = keep
|
||||
&& let Some(now) = boxed(d, m).map(|(_, b)| b.reference_point(i))
|
||||
&& now != was
|
||||
{
|
||||
let mut moved = shape;
|
||||
moved.center += was - now;
|
||||
let path = outline(&moved, C)?;
|
||||
shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &moved, path);
|
||||
reshape(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, &moved, sc, C)?;
|
||||
}
|
||||
// A shape named by `id` and not selected is not checked after the edit: one the edit
|
||||
// takes past the coordinate limit is an error here, and nothing changes.
|
||||
|
||||
@@ -562,6 +562,50 @@ fn set_keeps_the_reference_point_of_the_bounding_box_in_place() {
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": edge.0, "width": 180, "reference": 2})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_takes_a_linked_mask_and_placed_gradient_with_the_shape() {
|
||||
let mut s = session();
|
||||
let id =
|
||||
id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": "rectangle", "center": [200, 150], "width": 100, "height": 60})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [id.0], "gradient": {"kind": "linear"}})).unwrap();
|
||||
s.execute("paint.setGradientGeom", &json!({"ids": [id.0], "start": [170, 150], "end": [230, 150]})).unwrap();
|
||||
let m = id_of(&s.execute("shape.rectangle", &json!({"x": 160, "y": 130, "width": 40, "height": 40})).unwrap());
|
||||
s.execute("transparency.makeOpacityMask", &json!({"ids": [id.0, m.0]})).unwrap();
|
||||
// Where the mask art and the gradient's vector sit in the shape's own frame: the same before and after.
|
||||
let local = |s: &Session| {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let frame = shape_of(s, id).unwrap();
|
||||
let to_local = vectorcraft_geom::Affine::scale_non_uniform(1.0 / frame.width, 1.0 / frame.height) * frame.frame().inverse();
|
||||
let mask = n.extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap();
|
||||
let vectorcraft_color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("a gradient fill") };
|
||||
let geom = g.geom.unwrap();
|
||||
[to_local * mask.center(), to_local * geom.start, to_local * geom.end]
|
||||
};
|
||||
let was = local(&s);
|
||||
for edit in [
|
||||
json!({"center": [320, 260]}),
|
||||
json!({"width": 180}),
|
||||
json!({"rotation": 90}),
|
||||
json!({"height": 90, "reference": 0}),
|
||||
json!({"count": 6, "kind": "polygon"}),
|
||||
] {
|
||||
let mut p = edit.clone();
|
||||
p["id"] = json!(id.0);
|
||||
s.execute("addon.pathtools.shape.set", &p).unwrap();
|
||||
for (now, then) in local(&s).iter().zip(&was) {
|
||||
assert!(now.distance(*then) < 1e-9, "{edit}: moved off the shape to {now:?} from {then:?}");
|
||||
}
|
||||
}
|
||||
// With Scale Strokes & Effects on, a new size scales the stroke as a transform does; off, it keeps its weight.
|
||||
let weight = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width();
|
||||
s.execute("stroke.set", &json!({"ids": [id.0], "weight": 4})).unwrap();
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 360, "height": 180, "strokes": false})).unwrap();
|
||||
assert!((weight(&s) - 4.0).abs() < 1e-9);
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 720, "height": 360, "strokes": true})).unwrap();
|
||||
assert!(weight(&s) > 4.0 + 1.0, "the stroke scaled with the shape");
|
||||
refuses(&mut s, "addon.pathtools.shape.set", &[json!({"id": id.0, "width": 50, "strokes": "yes"})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_shape_params_are_refused() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -322,35 +322,52 @@ impl ItemTarget {
|
||||
/// targets have. In a target without an equal item, and for any other target, the row stands
|
||||
/// for itself. Every entry is `Some`.
|
||||
pub(crate) fn per_target(self, s: &Session, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
|
||||
let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] };
|
||||
let Some(st) = s.active().filter(|_| ids.len() >= 2) else { return vec![Some(self); ids.len()] };
|
||||
let k = self.anchor(s, ids);
|
||||
let Some(first) = ids.get(k).and_then(|id| st.doc.node(*id)) else { return vec![Some(self); ids.len()] };
|
||||
ids.iter()
|
||||
.enumerate()
|
||||
.map(|(j, id)| match st.doc.node(*id) {
|
||||
self.each_target(s, ids).collect()
|
||||
}
|
||||
|
||||
/// [`ItemTarget::per_target`], one target at a time: a caller that stops at the first answer
|
||||
/// matches only the targets it reads against the anchor's stack.
|
||||
pub(crate) fn each_target<'a>(self, s: &'a Session, ids: &'a [NodeId]) -> impl Iterator<Item = Option<ItemTarget>> + 'a {
|
||||
let anchor = match self {
|
||||
ItemTarget::Item { aligned: true, .. } if ids.len() >= 2 => s.active().and_then(|st| {
|
||||
let k = self.anchor(s, ids);
|
||||
Some((&st.doc, k, ids.get(k).and_then(|id| st.doc.node(*id))?))
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
ids.iter().enumerate().map(move |(j, id)| {
|
||||
let (ItemTarget::Item { index, explicit, .. }, Some((d, k, first))) = (self, anchor) else { return Some(self) };
|
||||
match d.node(*id) {
|
||||
Some(n) if j != k => {
|
||||
let at = SharedStack::of(&[&*first.appearance, &*n.appearance]).item_in(index, 1);
|
||||
let at = shared_stack(&first.appearance, &n.appearance).item_in(index, 1);
|
||||
Some(at.map_or(self, |index| ItemTarget::Item { index, explicit, aligned: true }))
|
||||
}
|
||||
_ => Some(self),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// [`ItemTarget::per_target`], with an explicit aligned item a row of the stack of `of` (see [`design_reference`]),
|
||||
/// which is not among `ids`, when there is one: each target edits the item equal to it there, and a target without
|
||||
/// an equal item is left out (`None`).
|
||||
pub(crate) fn per_target_of(self, s: &Session, of: Option<NodeId>, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
|
||||
let ItemTarget::Item { index, explicit: true, aligned: true } = self else { return self.per_target(s, ids) };
|
||||
let Some(d) = s.active().map(|st| &st.doc) else { return self.per_target(s, ids) };
|
||||
let Some(r) = of.and_then(|of| d.node(of)) else { return self.per_target(s, ids) };
|
||||
ids.iter()
|
||||
.map(|id| {
|
||||
let index = SharedStack::of(&[&*r.appearance, &*d.node(*id)?.appearance]).item_in(index, 1)?;
|
||||
self.each_target_of(s, of, ids).collect()
|
||||
}
|
||||
|
||||
/// [`ItemTarget::per_target_of`], one target at a time (see [`ItemTarget::each_target`]).
|
||||
pub(crate) fn each_target_of<'a>(self, s: &'a Session, of: Option<NodeId>, ids: &'a [NodeId]) -> impl Iterator<Item = Option<ItemTarget>> + 'a {
|
||||
let reference = match self {
|
||||
ItemTarget::Item { index, explicit: true, aligned: true } => s.active().map(|st| &st.doc).and_then(|d| Some((d, d.node(of?)?, index))),
|
||||
_ => None,
|
||||
};
|
||||
let own = reference.is_none().then(|| self.each_target(s, ids));
|
||||
let shared = reference.map(|(d, r, index)| {
|
||||
ids.iter().map(move |id| {
|
||||
let index = shared_stack(&r.appearance, &d.node(*id)?.appearance).item_in(index, 1)?;
|
||||
Some(ItemTarget::Item { index, explicit: true, aligned: true })
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
own.into_iter().flatten().chain(shared.into_iter().flatten())
|
||||
}
|
||||
|
||||
/// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of
|
||||
@@ -392,6 +409,26 @@ impl ItemTarget {
|
||||
}
|
||||
}
|
||||
|
||||
/// The stack that `a` and `b` share ([`SharedStack::of`]), which [`ItemTarget::each_target`] and
|
||||
/// [`ItemTarget::each_target_of`] match each target's rows in.
|
||||
fn shared_stack(a: &Appearance, b: &Appearance) -> SharedStack {
|
||||
#[cfg(test)]
|
||||
STACKS_MATCHED.set(STACKS_MATCHED.get() + 1);
|
||||
SharedStack::of(&[a, b])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// [`stacks_matched`] of this thread.
|
||||
static STACKS_MATCHED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many shared stacks [`shared_stack`] has built on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn stacks_matched() -> u64 {
|
||||
STACKS_MATCHED.get()
|
||||
}
|
||||
|
||||
/// Does `p` say its item and effect indices are rows of the first target's stack (`aligned`),
|
||||
/// which each other target edits where it has them (see [`ItemTarget::per_target`])?
|
||||
pub(crate) fn aligned(p: &Value, cmd: &str) -> Result<bool> {
|
||||
@@ -865,7 +902,7 @@ fn edit_items_writing_then(
|
||||
/// The first of `ids` that [`edit_items`] aimed at `item` with `of` changes, and the item it changes there. Read it
|
||||
/// before the edit: once edited, a row that was equal to a row of the art of `of` no longer is.
|
||||
pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option<NodeId>, ids: &[NodeId]) -> Option<(NodeId, ItemTarget)> {
|
||||
ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
|
||||
ids.iter().zip(item.each_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
|
||||
}
|
||||
|
||||
/// Keep the object rows of the graph labels among `ids` for every label of their kind
|
||||
|
||||
@@ -823,7 +823,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
st.sync_new_art();
|
||||
super::maskedit::follow_history(st, editing);
|
||||
super::symboledit::follow_history(st, editing_symbol.as_ref());
|
||||
leave_isolation_if_gone(st);
|
||||
st.leave_isolation_if_gone();
|
||||
super::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
if let Some((before, _)) = paints {
|
||||
@@ -860,7 +860,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
st.sync_new_art();
|
||||
super::maskedit::follow_history(st, editing);
|
||||
super::symboledit::follow_history(st, editing_symbol.as_ref());
|
||||
leave_isolation_if_gone(st);
|
||||
st.leave_isolation_if_gone();
|
||||
super::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
if let Some((_, after)) = paints {
|
||||
@@ -869,15 +869,6 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "redone": label }))
|
||||
}
|
||||
|
||||
/// After undo or redo, isolation mode ends when the isolated object is no longer in the document,
|
||||
/// such as the clip group Draw Inside made around the isolated object (#3705), rather than naming
|
||||
/// an id a later object may take.
|
||||
fn leave_isolation_if_gone(st: &mut crate::DocState) {
|
||||
if st.isolation.is_some_and(|i| st.doc.node(i).is_none()) {
|
||||
st.isolation = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// History panel › Clear History: removes the steps after the current state and the steps before
|
||||
/// it, and leaves the document as it is. Typing or a drag still in progress is first kept as a
|
||||
/// step, as Undo keeps it, so it is removed with the others and its change stays in the document.
|
||||
@@ -1596,6 +1587,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
for xf in placements {
|
||||
for (k, n) in clip.nodes.iter().enumerate() {
|
||||
let mut c = d.reid(n);
|
||||
// A pasted object never goes in as a clip group's clipping path, so a copied clipping
|
||||
// path comes back as an ordinary path that the path commands work on (#9227).
|
||||
if let NodeKind::Path { clipping, .. } = &mut c.kind {
|
||||
*clipping = false;
|
||||
}
|
||||
// A pasted symbol set packs from the density recorded for it at Copy.
|
||||
d.carry_set_densities(n, &c, &clip.set_densities);
|
||||
imported.apply(&mut c, d);
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
//! - `metafile`: EMF and WMF export, open and place; PICT open and place.
|
||||
//! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, and `.cmx` files with
|
||||
//! 32-bit coordinates, open and place.
|
||||
//! - `cmx`: `.cmx` export (a page for each chosen artboard, a layer for each layer with art on it).
|
||||
//! - `hpgl`: HP-GL export options and plots.
|
||||
//! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no
|
||||
//! built-in format reads).
|
||||
@@ -31,6 +32,7 @@ mod action_batch;
|
||||
mod affinity;
|
||||
mod batch;
|
||||
mod cdr;
|
||||
mod cmx;
|
||||
pub mod dxf;
|
||||
pub mod dxfimport;
|
||||
mod encode;
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
//! `.cmx` exchange files for every path that writes them (`craft_cdr::write_cmx`):
|
||||
//! `document.export {format: cmx}` and Export As. The chosen artboard (default the first) is the
|
||||
//! file's page; with Use Artboards each chosen artboard (default all) is a page of one file. Each
|
||||
//! top-level layer with art over a page is a layer of that page, holding that art as
|
||||
//! [`vectorcraft_metafile::painted_layers`] gives it: fills and strokes in their colors (CMYK, RGB,
|
||||
//! gray, spot colors with their tints and Registration), type as glyph outlines, and gradients and
|
||||
//! patterns as one color. What the file can't hold comes back in the warnings.
|
||||
|
||||
use craft_cdr::Limits;
|
||||
use craft_cdr::model as cd;
|
||||
use kurbo::PathEl;
|
||||
use serde_json::Value;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::{Document, LineCap, LineJoin, StrokeLayer};
|
||||
use vectorcraft_geom::{BezPath, FillRule, Point};
|
||||
use vectorcraft_metafile::Painted;
|
||||
|
||||
use super::super::{Result, bad};
|
||||
use super::{ArtboardPick, Encoded, FormatOption};
|
||||
|
||||
const C: &str = "document.export";
|
||||
|
||||
/// The options `document.formats` lists for CMX.
|
||||
pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS, super::RANGE, super::USE_ARTBOARDS];
|
||||
|
||||
const IMAGES: &str = "placed images are left out of CMX files";
|
||||
const NONZERO: &str = "fills that use the nonzero fill rule are written even-odd: where a shape crosses itself, or parts of it that turn the same way overlap, they may leave holes";
|
||||
const SPLIT: &str = "paths with more than 7,281 points were written as several curves: their fills where their parts overlap, and their strokes where the curves meet, may draw differently";
|
||||
const PAST_PAGE: &str = "art that crosses the edge of a page is written whole, including the part past the edge";
|
||||
const DASHES: &str = "dash and gap lengths were rounded to whole stroke widths, the unit CMX files store them in";
|
||||
const CUT: &str = "filled shapes with a part of more than 7,281 points were written as open pieces of that part, so their fills draw differently";
|
||||
const ZERO_TINTS: &str = "spot colors at a low tint were written in the color they print at that tint, so their ink's color may open changed";
|
||||
const LONG_NAMES: &str = "layer and spot color names longer than 256 characters open again shortened";
|
||||
const UNNAMED_SPOTS: &str = "spot colors without a name were written as process colors";
|
||||
const UNKNOWN_LOOKS: &str = "spot colors whose color is not known were written as black at their tints";
|
||||
const MERGED_LOOKS: &str = "spot colors that share a name but not a color were all written in one of those colors";
|
||||
const LEFT_OUT: &str = "art the file can't hold was left out";
|
||||
const DASH_OFFSETS: &str = "dash offsets are left out: dashes start at the start of each path";
|
||||
const ALIGNED_DASHES: &str = "dashes aligned to corners and path ends are written as plain dashes";
|
||||
const MITER_LIMITS: &str = "miter limits are left out: mitered corners open again with a miter limit of 10";
|
||||
|
||||
/// Encode `doc` as CMX: one file with a page for the chosen artboard (default the first), or with
|
||||
/// `use_artboards` a page for each chosen artboard (default all), in the order they are chosen.
|
||||
pub(super) fn encode(doc: &Document, f: &super::Format, p: &Value, use_artboards: Option<bool>) -> Result<Encoded> {
|
||||
let pick: ArtboardPick = super::encode::options(f, p)?;
|
||||
let n = doc.artboards.len();
|
||||
let boards = match use_artboards {
|
||||
Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()),
|
||||
_ => vec![pick.one(n).map_err(|e| bad(C, e))?],
|
||||
};
|
||||
if boards.is_empty() {
|
||||
return Err(bad(C, "the document has no artboard"));
|
||||
}
|
||||
let rects = boards
|
||||
.iter()
|
||||
.map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?;
|
||||
let mut warnings = Vec::new();
|
||||
let mut note = |w: &str| {
|
||||
if !warnings.iter().any(|x: &String| x == w) {
|
||||
warnings.push(w.to_string());
|
||||
}
|
||||
};
|
||||
let mut pages = Vec::with_capacity(rects.len());
|
||||
for r in &rects {
|
||||
let art = vectorcraft_metafile::painted_layers(doc, *r).map_err(|e| bad(C, e))?;
|
||||
art.warnings.iter().for_each(|w| note(w));
|
||||
if art.images {
|
||||
note(IMAGES);
|
||||
}
|
||||
// The file has no clipping the reader reads, so art is not cut at the page's edge.
|
||||
let edge = r.abs().inflate(PAGE_EDGE_TOLERANCE, PAGE_EDGE_TOLERANCE);
|
||||
// A stroke reaches half its width past its path.
|
||||
let past = |bp: &BezPath, reach: f64| {
|
||||
let b = kurbo::Shape::bounding_box(bp).inflate(reach, reach);
|
||||
!bp.elements().is_empty() && (b.x0 < edge.x0 || b.y0 < edge.y0 || b.x1 > edge.x1 || b.y1 > edge.y1)
|
||||
};
|
||||
if art.layers.iter().flat_map(|(_, p)| p).any(|op| match op {
|
||||
Painted::Fill { path, .. } => past(path, 0.0),
|
||||
Painted::Stroke { path, width, .. } => past(path, width.max(0.0) / 2.0),
|
||||
}) {
|
||||
note(PAST_PAGE);
|
||||
}
|
||||
let page = Page { center: r.abs().center() };
|
||||
// The model lists layers and objects front to back; the document paints them back to front.
|
||||
// A layer with nothing drawn on the page is left out, as the reader leaves out a layer that
|
||||
// holds nothing.
|
||||
let layers = art
|
||||
.layers
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|(name, painted)| (name, page.objects(&art.swatches, painted, &mut note)))
|
||||
.filter(|(_, objects)| !objects.is_empty())
|
||||
.map(|(name, objects)| cd::Layer {
|
||||
name: name.clone(),
|
||||
kind: cd::LayerKind::Drawing,
|
||||
flags: cd::Flags::default(),
|
||||
objects: objects.into_iter().rev().collect(),
|
||||
guides: Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
pages.push(cd::Page { size: Some((r.width().abs(), r.height().abs())), layers });
|
||||
}
|
||||
let drawing = cd::Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: Vec::new() };
|
||||
// The limits `document.open` reads `.cmx` files with, so the file opens whole again.
|
||||
let written = craft_cdr::write_cmx(&drawing, Limits::default()).map_err(|e| bad(C, e.to_string()))?;
|
||||
for (set, w) in [
|
||||
(written.nonzero_fills, NONZERO),
|
||||
(written.split_paths, SPLIT),
|
||||
(written.cut_subpaths, CUT),
|
||||
(written.long_names, LONG_NAMES),
|
||||
(written.zero_tints, ZERO_TINTS),
|
||||
(written.rounded_dashes, DASHES),
|
||||
(written.unnamed_spots, UNNAMED_SPOTS),
|
||||
(written.unknown_looks, UNKNOWN_LOOKS),
|
||||
(written.merged_looks, MERGED_LOOKS),
|
||||
(written.left_out, LEFT_OUT),
|
||||
] {
|
||||
if set {
|
||||
note(w);
|
||||
}
|
||||
}
|
||||
let mut enc = Encoded::one(written.bytes);
|
||||
enc.warnings = warnings;
|
||||
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(&rects)));
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
/// A page's placement: document space (y down) to the page's coordinates (from its center, y up).
|
||||
struct Page {
|
||||
center: Point,
|
||||
}
|
||||
|
||||
impl Page {
|
||||
fn pt(&self, p: Point) -> cd::Pt {
|
||||
cd::Pt { x: p.x - self.center.x, y: self.center.y - p.y }
|
||||
}
|
||||
|
||||
/// `bp` in the page's coordinates. A quadratic segment becomes the cubic that draws it.
|
||||
fn path(&self, bp: &BezPath) -> cd::Path {
|
||||
let mut subpaths: Vec<cd::SubPath> = Vec::new();
|
||||
// The current point and the start of the current subpath, in document space.
|
||||
let (mut last, mut start) = (Point::ZERO, Point::ZERO);
|
||||
for el in bp.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
subpaths.push(cd::SubPath { start: self.pt(p), segments: Vec::new(), closed: false });
|
||||
(last, start) = (p, p);
|
||||
}
|
||||
PathEl::LineTo(p) => {
|
||||
self.segment(&mut subpaths, last, cd::Segment::Line(self.pt(p)));
|
||||
last = p;
|
||||
}
|
||||
PathEl::QuadTo(c, p) => {
|
||||
let (c1, c2) = (last + (c - last) * (2.0 / 3.0), p + (c - p) * (2.0 / 3.0));
|
||||
self.segment(&mut subpaths, last, cd::Segment::Cubic(self.pt(c1), self.pt(c2), self.pt(p)));
|
||||
last = p;
|
||||
}
|
||||
PathEl::CurveTo(c1, c2, p) => {
|
||||
self.segment(&mut subpaths, last, cd::Segment::Cubic(self.pt(c1), self.pt(c2), self.pt(p)));
|
||||
last = p;
|
||||
}
|
||||
PathEl::ClosePath => {
|
||||
if let Some(s) = subpaths.last_mut() {
|
||||
s.closed = true;
|
||||
}
|
||||
last = start;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A subpath of a lone point draws nothing.
|
||||
subpaths.retain(|s| !s.segments.is_empty());
|
||||
cd::Path { subpaths }
|
||||
}
|
||||
|
||||
/// Add `seg` to the open subpath, or to a new one from `from` after a close.
|
||||
fn segment(&self, subpaths: &mut Vec<cd::SubPath>, from: Point, seg: cd::Segment) {
|
||||
match subpaths.last_mut() {
|
||||
Some(s) if !s.closed => s.segments.push(seg),
|
||||
_ => subpaths.push(cd::SubPath { start: self.pt(from), segments: vec![seg], closed: false }),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fills and strokes of one layer as shapes, in paint order. A fill followed by a stroke of
|
||||
/// the same path is one shape with both. A path with no segments draws nothing and is left out.
|
||||
fn objects(&self, swatches: &[Swatch], painted: &[Painted], note: &mut impl FnMut(&str)) -> Vec<cd::Object> {
|
||||
let mut out = Vec::with_capacity(painted.len());
|
||||
let mut i = 0;
|
||||
while let Some(op) = painted.get(i) {
|
||||
i += 1;
|
||||
let shape = match op {
|
||||
Painted::Fill { path, rule, rgb, paint } => {
|
||||
let outline = match painted.get(i) {
|
||||
Some(s @ Painted::Stroke { path: stroked, .. }) if stroked == path => {
|
||||
i += 1;
|
||||
outline(swatches, s, note)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let fill = color(swatches, *rgb, paint.as_ref());
|
||||
let mut shape = cd::Shape::new(cd::Geometry::Path(self.path(path)), cd::Matrix::IDENTITY, Some(fill), outline);
|
||||
shape.nonzero = *rule == FillRule::NonZero;
|
||||
shape
|
||||
}
|
||||
Painted::Stroke { path, .. } => {
|
||||
cd::Shape::new(cd::Geometry::Path(self.path(path)), cd::Matrix::IDENTITY, None, outline(swatches, op, note))
|
||||
}
|
||||
};
|
||||
if matches!(&shape.geometry, cd::Geometry::Path(p) if p.subpaths.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
out.push(cd::Object::Shape(Box::new(shape)));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// How far (points) a path may reach past its page before the export says art crosses the edge.
|
||||
const PAGE_EDGE_TOLERANCE: f64 = 0.01;
|
||||
|
||||
/// The outline of a stroke: its width, color, cap, join and dashes in stroke widths. The file holds
|
||||
/// no miter limit, so a mitered stroke with a limit other than the one a stroke opens with is
|
||||
/// named in the warnings.
|
||||
fn outline(swatches: &[Swatch], p: &Painted, note: &mut impl FnMut(&str)) -> Option<cd::Outline> {
|
||||
let Painted::Stroke { rgb, paint, width, cap, join, miter, dash, .. } = p else { return None };
|
||||
if *join == LineJoin::Miter && *miter != StrokeLayer::new(Paint::None, *width).miter_limit {
|
||||
note(MITER_LIMITS);
|
||||
}
|
||||
let dashes = match dash {
|
||||
Some(d) if *width > 0.0 => {
|
||||
if d.offset != 0.0 {
|
||||
note(DASH_OFFSETS);
|
||||
}
|
||||
if d.align_corners {
|
||||
note(ALIGNED_DASHES);
|
||||
}
|
||||
d.pattern.iter().map(|x| x / width).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
Some(cd::Outline {
|
||||
width: *width,
|
||||
color: color(swatches, *rgb, paint.as_ref()),
|
||||
cap: match cap {
|
||||
LineCap::Butt => cd::Cap::Butt,
|
||||
LineCap::Round => cd::Cap::Round,
|
||||
LineCap::Square => cd::Cap::Square,
|
||||
},
|
||||
join: match join {
|
||||
LineJoin::Miter => cd::Join::Miter,
|
||||
LineJoin::Round => cd::Join::Round,
|
||||
LineJoin::Bevel => cd::Join::Bevel,
|
||||
},
|
||||
dashes,
|
||||
behind_fill: false,
|
||||
scale_with: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The color a fill or stroke is written in: Registration, a spot color at its tint with the look
|
||||
/// of its swatch among `swatches`, or the solid color in its own model (Lab as RGB); `rgb` for the
|
||||
/// one color of a gradient or pattern.
|
||||
fn color(swatches: &[Swatch], rgb: [u8; 3], paint: Option<&Paint>) -> cd::Color {
|
||||
let from_rgb = |[r, g, b]: [u8; 3]| cd::Color::Rgb([r, g, b].map(|v| f32::from(v) / 255.0));
|
||||
let Some(Paint::Solid { color, swatch, tint }) = paint else { return from_rgb(rgb) };
|
||||
if swatch.as_deref() == Some(REGISTRATION) {
|
||||
return cd::Color::Registration;
|
||||
}
|
||||
if let Some(s) = swatch.as_deref().and_then(|name| swatches.iter().find(|s| s.name == name)).filter(|s| s.spot) {
|
||||
let look = s.paint.color().map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
[r, g, b].map(|v| f32::from(v) / 255.0)
|
||||
});
|
||||
return cd::Color::Spot { name: s.name.clone(), tint: tint.clamp(0.0, 1.0), look };
|
||||
}
|
||||
match *color {
|
||||
Color::Rgb { r, g, b } => cd::Color::Rgb([r, g, b]),
|
||||
Color::Cmyk { c, m, y, k } => cd::Color::Cmyk([c, m, y, k]),
|
||||
Color::Gray { k } => cd::Color::Gray(k),
|
||||
Color::Lab { .. } => from_rgb(rgb),
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Serialize Document",
|
||||
[],
|
||||
None,
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)",
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)",
|
||||
has_doc,
|
||||
export::serialize
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), d
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Selection…",
|
||||
["File"],
|
||||
None,
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})",
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|cmx|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})",
|
||||
has_selection,
|
||||
export::export_selection
|
||||
),
|
||||
|
||||
@@ -1069,7 +1069,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
|
||||
}
|
||||
// Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so
|
||||
// themselves: SVG only when it outlines or embeds fonts).
|
||||
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl"))
|
||||
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl" | "cmx"))
|
||||
&& let Some(w) = crate::cmd::fonts::substitution_warning(doc)
|
||||
{
|
||||
enc.warnings.push(w);
|
||||
@@ -1110,7 +1110,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
let doc = &*doc.without_edit_modes();
|
||||
let n = doc.artboards.len();
|
||||
// SVG reads its own `useArtboards` (an SVG option).
|
||||
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(C, p)? } else { None };
|
||||
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None };
|
||||
// `rect`: that area of the page, as if it were the only artboard (the document is not changed).
|
||||
if let Some(rect) = page_rect(f, p)? {
|
||||
let mut q = super::export::without_artboards(p);
|
||||
@@ -1156,6 +1156,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
"emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf),
|
||||
"wmf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Wmf),
|
||||
"hpgl" => return super::hpgl::encode(doc, p, use_artboards),
|
||||
"cmx" => return super::cmx::encode(doc, f, p, use_artboards),
|
||||
"ai" => return super::save::encode_ai(C, f, doc, p),
|
||||
"pdf" => {
|
||||
let (bytes, notes) = super::pdf::encode(C, doc, p)?;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::super::unique_name;
|
||||
use super::{
|
||||
Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, dxf, eps, hpgl, json, metafile, native, pdf, screens, svg, text,
|
||||
Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, cmx, dxf, eps, hpgl, json, metafile, native, pdf, screens, svg, text,
|
||||
unsupported,
|
||||
};
|
||||
|
||||
@@ -553,9 +553,9 @@ pub const FORMATS: &[Format] = &[
|
||||
// them.
|
||||
reader("cdr", "CDR Drawing", &["cdr"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type
|
||||
reader("cdt", "CDR Template", &["cdt"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type
|
||||
// `.cmx` exchange files with 32-bit coordinates, read by `craft-cdr`; exports don't write
|
||||
// them.
|
||||
reader("cmx", "CMX", &["cmx"], "image/x-cmx", false),
|
||||
// `.cmx` exchange files with 32-bit coordinates, read and written by `craft-cdr`: a page for
|
||||
// each chosen artboard, with the art's fills and strokes in their colors.
|
||||
Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS },
|
||||
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images.
|
||||
reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false),
|
||||
];
|
||||
|
||||
@@ -196,7 +196,7 @@ pub(super) fn name_without_device(name: &str) -> String {
|
||||
pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"];
|
||||
|
||||
/// The writable formats a format row can't name.
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 6] = ["template", "txt", "dxf", "emf", "wmf", "hpgl"];
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 7] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx"];
|
||||
|
||||
/// One format row: what to write, at which size, with which suffix, into which sub-folder.
|
||||
struct Row {
|
||||
|
||||
@@ -532,7 +532,8 @@ fn export_extensions_name_every_writable_format() {
|
||||
"wmf",
|
||||
"plt",
|
||||
"tga",
|
||||
"psd"
|
||||
"psd",
|
||||
"cmx"
|
||||
]
|
||||
);
|
||||
for e in exts {
|
||||
@@ -568,7 +569,8 @@ fn formats_query_lists_readers_writers_and_options() {
|
||||
"wmf",
|
||||
"hpgl",
|
||||
"tga",
|
||||
"psd"
|
||||
"psd",
|
||||
"cmx"
|
||||
]
|
||||
);
|
||||
assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string()));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! `.cmx` files: Open and Place, by extension and by content, mapped to artboards, layers, groups,
|
||||
//! paths, solid paint and strokes, with their warnings and refusals.
|
||||
//! paths, solid paint and strokes, with their warnings and refusals; and export, read back.
|
||||
|
||||
use super::*;
|
||||
use craft_cdr::synth_cmx::*;
|
||||
@@ -61,7 +61,7 @@ fn detection_by_content_and_place() {
|
||||
s.execute("file.place", &json!({"name":"art.cmx", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty()));
|
||||
let f = format("cmx").unwrap();
|
||||
assert!(f.read && !f.write);
|
||||
assert!(f.read && f.write);
|
||||
assert!(OPEN_EXTS.contains(&"cmx") && PLACE_EXTS.contains(&"cmx") && UNASSOCIATED_EXTS.contains(&"cmx"));
|
||||
assert!(!SAVE_FORMATS.contains(&"cmx"));
|
||||
}
|
||||
@@ -123,6 +123,183 @@ fn files_that_are_not_read_say_why() {
|
||||
assert!(e.contains("this CMX file can't be read (not a CMX file)"), "{e}");
|
||||
}
|
||||
|
||||
fn b64(v: &serde_json::Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap()
|
||||
}
|
||||
|
||||
/// Two artboards of 200 x 100 pt. The first layer holds a CMYK rectangle with a dashed gray stroke on
|
||||
/// the first; layer "Front" a 40 % tint of spot ink "Gold" on the first and an RGB stroke on the
|
||||
/// second.
|
||||
fn drawn() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2, "colorMode": "cmyk"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Gold", "color": {"model": "cmyk", "c": 0.0, "m": 0.2, "y": 0.8, "k": 0.1}, "spot": true})).unwrap();
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect.x0;
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 40, "height": 30})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": {"model": "cmyk", "c": 0.6, "m": 0.1, "y": 0.0, "k": 0.2}})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": {"model": "gray", "k": 0.5}})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2, "dash": [6, 2]})).unwrap();
|
||||
s.execute("layer.new", &json!({"name": "Front"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Gold", "tint": 40})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": second + 5.0, "y": 5, "width": 10, "height": 10})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#3366cc"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 1})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Every path of a document with its bounds relative to the artboard it is on.
|
||||
fn placed(s: &Session) -> Vec<(Node, vectorcraft_geom::Rect)> {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let mut all = Vec::new();
|
||||
paths(&doc.layers, &mut all);
|
||||
all.into_iter()
|
||||
.map(|n| {
|
||||
let b = doc.bounds_of(&[n.id], false).unwrap();
|
||||
let board = doc.artboards.iter().find(|a| a.rect.contains(b.center())).map_or(vectorcraft_geom::Rect::ZERO, |a| a.rect);
|
||||
(n, b - board.origin().to_vec2())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exported_cmx_file_opens_with_its_pages_layers_colors_and_strokes() {
|
||||
let mut s = drawn();
|
||||
let r = s.execute("document.export", &json!({"format": "cmx", "useArtboards": true})).unwrap();
|
||||
assert_eq!(r["format"], "cmx");
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
let bytes = b64(&r);
|
||||
assert!(craft_cdr::is_cmx(&bytes), "one file holds both pages");
|
||||
let mut back = Session::new();
|
||||
let opened = open_bytes(&mut back, "drawing.cmx", &bytes, None).unwrap();
|
||||
assert!(warnings(&opened).is_empty(), "{opened}");
|
||||
let doc = &back.doc().unwrap().doc;
|
||||
let sizes: Vec<(f64, f64)> = doc.artboards.iter().map(|a| (a.rect.width().round(), a.rect.height().round())).collect();
|
||||
assert_eq!(sizes, [(200.0, 100.0), (200.0, 100.0)]);
|
||||
let names: Vec<String> = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
let was: Vec<String> = s.doc().unwrap().doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, was, "the layers keep their names and order");
|
||||
let was = placed(&s);
|
||||
let now = placed(&back);
|
||||
assert_eq!(was.len(), now.len());
|
||||
for ((_, a), (_, b)) in was.iter().zip(&now) {
|
||||
assert!((a.x0 - b.x0).abs() < 0.01 && (a.y0 - b.y0).abs() < 0.01 && (a.x1 - b.x1).abs() < 0.01, "{a:?} {b:?}");
|
||||
}
|
||||
let fill = |n: &Node| n.appearance.fill().map(|f| f.paint.clone());
|
||||
let stroke = |n: &Node| n.appearance.stroke().cloned();
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let cmyk = &now[0].0;
|
||||
assert!(matches!(fill(cmyk).and_then(|p| p.color()), Some(Color::Cmyk { c, .. }) if (c - 0.6).abs() < 0.006), "{:?}", fill(cmyk));
|
||||
let st = stroke(cmyk).unwrap();
|
||||
assert!((st.width - 2.0).abs() < 1e-3 && matches!(st.paint.color(), Some(Color::Gray { k }) if (k - 0.5).abs() < 0.005));
|
||||
// Widths are stored to 0.1 µm.
|
||||
let dash = st.dash.as_ref().map(|d| d.pattern.clone()).unwrap_or_default();
|
||||
assert!(dash.len() == 2 && (dash[0] - 6.0).abs() < 1e-3 && (dash[1] - 2.0).abs() < 1e-3, "{dash:?}");
|
||||
let gold = &now[1].0;
|
||||
assert!(matches!(fill(gold), Some(Paint::Solid { swatch: Some(n), tint, .. }) if n == "Gold" && (tint - 0.4).abs() < 0.006), "{:?}", fill(gold));
|
||||
assert!(doc.swatch("Gold").is_some_and(|g| g.spot));
|
||||
let line = &now[2].0;
|
||||
assert!(fill(line).is_none_or(|p| p == Paint::None));
|
||||
// The document converted the RGB color to its CMYK mode; the file keeps the CMYK values.
|
||||
let (Some(Color::Cmyk { c, m, y, k }), Some(Color::Cmyk { c: c2, m: m2, y: y2, k: k2 })) =
|
||||
(stroke(&was[2].0).unwrap().paint.color(), stroke(line).unwrap().paint.color())
|
||||
else {
|
||||
panic!("not CMYK: {:?}", stroke(line))
|
||||
};
|
||||
assert!([c - c2, m - m2, y - y2, k - k2].iter().all(|d| d.abs() < 0.006));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_artboard_is_one_page_and_what_cmx_leaves_out_is_named() {
|
||||
let mut s = drawn();
|
||||
let bytes = b64(&s.execute("document.export", &json!({"format": "cmx", "artboard": 1})).unwrap());
|
||||
let d = craft_cdr::read_cmx(&bytes, craft_cdr::Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
let shapes: usize = d.pages[0].layers.iter().map(|l| l.objects.len()).sum();
|
||||
assert_eq!(shapes, 1, "only the art over the second artboard");
|
||||
assert_eq!(b64(&s.execute("document.serialize", &json!({"format": "cmx", "artboard": 1})).unwrap()), bytes);
|
||||
// A gradient is written as one color, and a placed image is left out.
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 60, "width": 10, "height": 10})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
let png = vectorcraft_format::base64_encode(&tiny_png());
|
||||
s.execute("file.place", &json!({"name": "dot.png", "dataBase64": png, "x": 150, "y": 60})).unwrap();
|
||||
let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap());
|
||||
assert!(w.iter().any(|w| w.contains("gradients are written as one colour")), "{w:?}");
|
||||
assert!(w.iter().any(|w| w == "placed images are left out of CMX files"), "{w:?}");
|
||||
assert!(w.iter().all(|w| !w.contains("edge of a page")), "{w:?}");
|
||||
// Art across the artboard's edge is written whole, and the warnings say so.
|
||||
s.execute("shape.rectangle", &json!({"x": 190, "y": 90, "width": 20, "height": 20})).unwrap();
|
||||
let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap());
|
||||
assert!(w.iter().any(|w| w.contains("edge of a page")), "{w:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nonzero_fill_that_would_fill_differently_even_odd_is_named() {
|
||||
let nonzero = |w: &[String]| w.iter().any(|w| w.contains("nonzero"));
|
||||
let export = |d: &str, rule: &str| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("path.create", &json!({"d": d})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#cc3333"})).unwrap();
|
||||
s.execute("path.setFillRule", &json!({"rule": rule})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "cmx"})).unwrap();
|
||||
let shapes: Vec<craft_cdr::model::Shape> = craft_cdr::read_cmx(&b64(&r), craft_cdr::Limits::default())
|
||||
.unwrap()
|
||||
.pages
|
||||
.into_iter()
|
||||
.flat_map(|p| p.layers)
|
||||
.flat_map(|l| l.objects)
|
||||
.filter_map(|o| match o {
|
||||
craft_cdr::model::Object::Shape(s) => Some(*s),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
(warnings(&r), shapes)
|
||||
};
|
||||
// Two squares that overlap and turn the same way leave a hole where they overlap even-odd.
|
||||
let overlapping = "M10 10 L50 10 L50 50 L10 50 Z M30 30 L70 30 L70 70 L30 70 Z";
|
||||
let (w, shapes) = export(overlapping, "nonZero");
|
||||
assert!(nonzero(&w), "{w:?}");
|
||||
assert!(shapes.len() == 1 && shapes[0].fill.is_some(), "{shapes:?}");
|
||||
// The same shape filled even-odd is written as it fills.
|
||||
assert!(!nonzero(&export(overlapping, "evenOdd").0));
|
||||
// A counter that turns the other way inside its shape fills the same either way.
|
||||
let counter = "M10 10 L50 10 L50 50 L10 50 Z M20 20 L20 40 L40 40 L40 20 Z";
|
||||
assert!(!nonzero(&export(counter, "nonZero").0));
|
||||
// Type exported from a document gives no warning about the fill rule.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Bob 80"})).unwrap();
|
||||
let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap());
|
||||
assert!(!nonzero(&w), "{w:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_miter_limit_the_file_cannot_hold_is_named() {
|
||||
let miter = |w: &[String]| w.iter().any(|w| w.contains("miter limit"));
|
||||
let export = |join: &str, limit: f64| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 40, "height": 30})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#3366cc"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 4, "join": join, "miterLimit": limit})).unwrap();
|
||||
warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap())
|
||||
};
|
||||
assert!(miter(&export("miter", 2.0)));
|
||||
// The limit a stroke opens with again, and corners that are not mitered, lose nothing.
|
||||
assert!(!miter(&export("miter", 10.0)));
|
||||
assert!(!miter(&export("round", 2.0)));
|
||||
}
|
||||
|
||||
/// A 1 x 1 PNG.
|
||||
fn tiny_png() -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_without_a_name_is_named_by_its_place() {
|
||||
// An empty layer, which is left out, then a layer named only by spaces: it comes in unnamed,
|
||||
|
||||
@@ -411,6 +411,13 @@ impl Session {
|
||||
pub fn has_selected_blend(&self) -> bool {
|
||||
super::common::any_selected_of(self, is_blend, |_| true)
|
||||
}
|
||||
|
||||
/// The blends Blend Options edits, in ID order regardless of their selection order.
|
||||
pub fn selected_blend_ids(&self) -> Vec<NodeId> {
|
||||
let mut ids = selected_of(self, is_blend);
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
}
|
||||
}
|
||||
|
||||
/// The first selected blend: its id, spec and key ids.
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -194,13 +194,19 @@ pub(super) fn clip_make(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
|
||||
pub(super) fn clip_release(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let ids = selected_roots(s)?;
|
||||
// With no clip group selected, the document and its undo history stay as they are.
|
||||
// With no clip group and no stray clipping path selected, the document and its undo history
|
||||
// stay as they are.
|
||||
let d = &s.doc()?.doc;
|
||||
if !ids.iter().any(|id| d.node(*id).is_some_and(Node::clips)) {
|
||||
if !ids.iter().any(|id| d.node(*id).is_some_and(Node::clips) || stray_clipping_path(d, *id)) {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Release Clipping Mask", |d, _| {
|
||||
for id in &ids {
|
||||
if stray_clipping_path(d, *id)
|
||||
&& let Some(NodeKind::Path { clipping, .. }) = d.node_mut(*id).map(|n| &mut n.kind)
|
||||
{
|
||||
*clipping = false;
|
||||
}
|
||||
release_clip(d, *id);
|
||||
}
|
||||
Ok(())
|
||||
@@ -208,6 +214,13 @@ pub(super) fn clip_release(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Whether `id` is a path marked as a clipping path that clips nothing: not the bottom child of a
|
||||
/// clip group or clipping layer. A paste made one before #9227; the path commands skip it.
|
||||
fn stray_clipping_path(d: &Document, id: NodeId) -> bool {
|
||||
let marked = d.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { clipping: true, .. }));
|
||||
marked && !d.position(id).is_some_and(|(parent, i, _)| i == 0 && parent.and_then(|p| d.node(p)).is_some_and(Node::clips))
|
||||
}
|
||||
|
||||
/// Selects the clipping path (`mask`) or the clipped contents of every selected clip group (or of the
|
||||
/// clip group containing a selected object), like Illustrator's Edit Contents / Edit Clipping Path toggle.
|
||||
pub(super) fn clip_edit(s: &mut Session, mask: bool) -> Result<Value> {
|
||||
|
||||
@@ -467,13 +467,20 @@ impl Session {
|
||||
(!self.menu.new_masks_unclipped, self.menu.new_masks_inverted)
|
||||
}
|
||||
|
||||
/// The Transparency panel's values for the selection, or for the object whose mask is being
|
||||
/// edited (`transparency.info` without ids).
|
||||
/// The Transparency panel's values for the selection or for the object whose mask is being
|
||||
/// edited. A selected dynamic symbol part supplies its opacity and blend mode.
|
||||
pub fn transparency_info(&self) -> TransparencyInfo {
|
||||
match (self.active(), transparency_targets(self, &Value::Null)) {
|
||||
(Some(st), Ok(ids)) => {
|
||||
let points = self.mesh_points_picked();
|
||||
TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points)
|
||||
let mut info = TransparencyInfo::of(&st.doc, ids).with_mesh_points(&st.doc, points);
|
||||
if st.doc.mask_edit.is_none()
|
||||
&& let Some(part) = st.selected_symbol_part()
|
||||
{
|
||||
info.opacity = Some((f64::from(part.opacity) * 10_000.0).round() / 100.0);
|
||||
info.blend = Some(part.blend);
|
||||
}
|
||||
info
|
||||
}
|
||||
_ => TransparencyInfo::default(),
|
||||
}
|
||||
|
||||
@@ -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()?)
|
||||
});
|
||||
|
||||
@@ -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()?;
|
||||
|
||||
@@ -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
|
||||
),
|
||||
@@ -1725,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)) {
|
||||
@@ -1735,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;
|
||||
}
|
||||
@@ -1744,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);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -295,6 +295,18 @@ impl Session {
|
||||
self.script_data_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
|
||||
}
|
||||
|
||||
/// Have listings of the Scripts and Startup Scripts folders measure their time with `clock`
|
||||
/// instead of the real time ([`script::folder::Clock::Wall`], the default).
|
||||
pub fn set_script_listing_clock(&mut self, clock: script::folder::Clock) {
|
||||
self.script_listing_clock = clock;
|
||||
}
|
||||
|
||||
/// How listings of the Scripts and Startup Scripts folders measure their time
|
||||
/// ([`Session::set_script_listing_clock`]).
|
||||
pub fn script_listing_clock(&self) -> script::folder::Clock {
|
||||
self.script_listing_clock
|
||||
}
|
||||
|
||||
/// The Scripts folder ([`Session::attach_scripts_dir`]); none on the web, which has no folders.
|
||||
pub fn scripts_dir(&self) -> Option<&std::path::Path> {
|
||||
self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
|
||||
@@ -581,7 +593,7 @@ fn startup_run(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let folder = root.to_string_lossy().into_owned();
|
||||
// The folder is the app's: a refusal names it as the request may see it.
|
||||
crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?;
|
||||
let listing = script::startup::list(&root);
|
||||
let listing = script::startup::list(&root, s.script_listing_clock);
|
||||
let name_of = |path: &std::path::Path| path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let (disabled, scripts): (Vec<_>, Vec<_>) =
|
||||
listing.scripts.into_iter().partition(|path| vectorcraft_plugins::safe_mode::skipped(&startup_item(path)));
|
||||
@@ -647,7 +659,7 @@ fn list_installed(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let folder = root.to_string_lossy();
|
||||
// The Scripts folder is the app's: a refusal names it as the request may see it.
|
||||
crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?;
|
||||
let listing = script::folder::list(root);
|
||||
let listing = script::folder::list(root, s.script_listing_clock);
|
||||
let scripts: Vec<Value> = listing
|
||||
.scripts()
|
||||
.into_iter()
|
||||
|
||||
@@ -189,6 +189,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The selected slices, including selected objects that are object slices.
|
||||
pub fn selected_slice_ids(&self) -> Vec<NodeId> {
|
||||
self.active().map_or_else(Vec::new, |st| selected_slices(&st.doc, &st.selection))
|
||||
}
|
||||
|
||||
/// View → Hide Slices.
|
||||
pub fn slices_hidden(&self) -> bool {
|
||||
self.menu.slices_hidden
|
||||
|
||||
@@ -536,7 +536,7 @@ impl Session {
|
||||
ids.retain(|id| !matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::SymbolInstance { .. })));
|
||||
}
|
||||
let mut strokes = vec![];
|
||||
for (id, each) in ids.iter().zip(item.per_target(self, &ids)) {
|
||||
for (id, each) in ids.iter().zip(item.each_target(self, &ids)) {
|
||||
let n = st.doc.node(*id)?;
|
||||
let row = each?.resolve(&n.appearance, false, C).ok()?;
|
||||
if row.is_none() && matches!(n.kind, NodeKind::Text(_)) {
|
||||
|
||||
@@ -69,6 +69,9 @@ pub struct DocState {
|
||||
pub recalled_selection: RecalledSelection,
|
||||
/// Process-unique id of this open document (tab indices shift when tabs close).
|
||||
pub uid: u64,
|
||||
/// When the document last became the current one: a larger value is more recent
|
||||
/// ([`Session::front_order`]). It is not saved.
|
||||
pub(crate) activated: u64,
|
||||
/// How many times File → Revert replaced the document's content in its tab
|
||||
/// ([`Session::replace_document`]). Work started for the document (a file read for Place, a
|
||||
/// pasted bitmap) is dropped when this has changed by the time it finishes; edits do not
|
||||
@@ -421,6 +424,7 @@ impl DocState {
|
||||
last_selection_cmd: None,
|
||||
recalled_selection: RecalledSelection::default(),
|
||||
uid: NEXT_DOC_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||
activated: 0,
|
||||
reverts: 0,
|
||||
history_restores: 0,
|
||||
opened_as_tab: true,
|
||||
@@ -656,6 +660,32 @@ impl DocState {
|
||||
self.revision += 1;
|
||||
}
|
||||
}
|
||||
/// End isolation mode when the isolated object is no longer in the document (an edit deleted,
|
||||
/// cut, ungrouped or replaced it, or Undo or Redo took it out, such as the clip group Draw
|
||||
/// Inside made around it, #3705), rather than naming an id a later object may take. While
|
||||
/// opacity mask, pattern or symbol editing is on, isolation goes back to that mode's editing
|
||||
/// layer.
|
||||
pub(crate) fn leave_isolation_if_gone(&mut self) {
|
||||
if self.isolation.is_some_and(|i| self.doc.node(i).is_none()) {
|
||||
let d = &self.doc;
|
||||
let layer = d.mask_edit.map(|e| e.layer).or(d.pattern_edit.as_ref().map(|e| e.layer)).or(d.symbol_edit.as_ref().map(|e| e.layer));
|
||||
self.isolation = layer.filter(|l| d.node(*l).is_some());
|
||||
self.revision += 1;
|
||||
}
|
||||
}
|
||||
/// After the document went back from `undone` to a state from when `before` was isolated (a
|
||||
/// canceled undo group or undo scope, an interaction's next preview): `before` is isolated
|
||||
/// again when the edits taken back had removed it.
|
||||
pub(crate) fn restore_isolation(&mut self, before: Option<NodeId>, undone: &Document) {
|
||||
if let Some(b) = before
|
||||
&& self.isolation != before
|
||||
&& undone.node(b).is_none()
|
||||
&& self.doc.node(b).is_some()
|
||||
{
|
||||
self.isolation = before;
|
||||
self.revision += 1;
|
||||
}
|
||||
}
|
||||
/// Clear the Variables panel highlight when the document defines no variable of that name
|
||||
/// (deleted, or taken out by Undo or Redo), so a variable defined later under that name is
|
||||
/// not highlighted without a click.
|
||||
|
||||
@@ -154,6 +154,9 @@ pub struct UndoGroup {
|
||||
pub(crate) steps: Vec<BatchSteps>,
|
||||
/// The undo step's name; else the first edit's.
|
||||
pub(crate) label: Option<String>,
|
||||
/// The isolated object when the group began: a canceled group isolates it again when the
|
||||
/// group's edits removed it ([`crate::DocState::restore_isolation`]).
|
||||
pub(crate) isolation: Option<NodeId>,
|
||||
}
|
||||
|
||||
/// A `command.batch` journal entry's number and the steps of it that belong to an undo group, each
|
||||
@@ -172,6 +175,9 @@ pub struct UndoScope {
|
||||
/// that the group's undo step keeps, as they were when the scope began; `None` when the scope
|
||||
/// opened the group.
|
||||
pub(crate) joined: Option<(Arc<Document>, Selection, Option<Arc<Document>>)>,
|
||||
/// The isolated object when the scope began: canceling a joined scope isolates it again when
|
||||
/// the scope's edits removed it.
|
||||
pub(crate) isolation: Option<NodeId>,
|
||||
/// The new-art colors and the group's color-mode history metadata at the scope's start.
|
||||
/// Only used when cancelling a joined scope that converted those colors.
|
||||
pub(crate) paint: vectorcraft_tools::PaintDefaults,
|
||||
|
||||
@@ -121,6 +121,10 @@ pub struct Session {
|
||||
/// lent from: a follow-up in another document, after a tool switch (also one back to the same
|
||||
/// tool) or after the tool starts afresh is not lent. None when the press was not lent.
|
||||
pub(crate) press_lent: Option<(Option<u64>, &'static str, &'static str)>,
|
||||
/// The uid of the document in which a Cmd press with the Selection tool armed Select Behind
|
||||
/// ([`Session::behind_armed`]): Cmd has been held since. None once Cmd is let go, the tool
|
||||
/// changes or another document becomes active.
|
||||
pub(crate) behind_armed: Option<Option<u64>>,
|
||||
/// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`]
|
||||
/// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with
|
||||
/// the document state, active tool and keys it was found for. None when it was last asked
|
||||
@@ -222,6 +226,9 @@ pub struct Session {
|
||||
/// The Startup Scripts folder, whose scripts `script.startup.run` runs; `None`: no folder
|
||||
/// ([`Session::attach_startup_scripts_dir`]).
|
||||
startup_scripts_dir: Option<std::path::PathBuf>,
|
||||
/// How listings of the Scripts and Startup Scripts folders measure their time
|
||||
/// ([`Session::set_script_listing_clock`]).
|
||||
script_listing_clock: script::folder::Clock,
|
||||
/// The folder of File Info's metadata templates; `None`: no folder
|
||||
/// ([`Session::attach_metadata_templates_dir`]).
|
||||
metadata_templates_dir: Option<std::path::PathBuf>,
|
||||
|
||||
@@ -18,7 +18,8 @@
|
||||
//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName`
|
||||
//! gives, and a script may name the application's members without `app.`, as
|
||||
//! <https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/> describes; here
|
||||
//! that holds for `activeDocument`, `documents` and `selection`.
|
||||
//! that holds for `activeDocument`, `documents` and `selection`. `documents[0]` is the active
|
||||
//! document, as the same page says.
|
||||
//!
|
||||
//! VectorCraft's own rules:
|
||||
//! - A document's selection lists the selected objects topmost first, as `pageItems` does, whatever
|
||||
@@ -30,8 +31,8 @@
|
||||
//! active document's selection. A top-level `var selection = ...` does the same and does
|
||||
//! not make a variable of the script. An assignment to `documents` is ignored outside strict
|
||||
//! mode and throws a `TypeError` in strict mode code or with `#strict on`.
|
||||
//! - Collections list documents in tab order. The objectReferences page says `documents[0]` is
|
||||
//! always the active document; VectorCraft does not follow that yet.
|
||||
//! - After `documents[0]`, documents are listed from the one active most recently to the one
|
||||
//! active longest ago. A change a script makes to a document in the back does not move it.
|
||||
//! - `pageItems` lists every object, with the objects inside groups and compound paths after the
|
||||
//! group or compound path, and leaves out layers and ruler guides. An index out of range gives
|
||||
//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches.
|
||||
@@ -652,11 +653,11 @@ fn on_doc<T>(
|
||||
keep_selection: bool,
|
||||
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
let (index, active, before, layer) = {
|
||||
let (index, active, before, layer, activated) = {
|
||||
let s = h.session.borrow();
|
||||
let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
|
||||
let st = &s.documents()[index];
|
||||
(index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows()))
|
||||
(index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows()), st.activated)
|
||||
};
|
||||
let switch = active != Some(index);
|
||||
if switch {
|
||||
@@ -682,6 +683,13 @@ fn on_doc<T>(
|
||||
Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop),
|
||||
_ => Ok(()),
|
||||
};
|
||||
// The switch for the change does not move the document up in `documents`.
|
||||
if switch
|
||||
&& back.is_ok()
|
||||
&& let Some(st) = h.session.borrow_mut().document_mut(uid)
|
||||
{
|
||||
st.activated = activated;
|
||||
}
|
||||
let v = r?;
|
||||
restored?;
|
||||
back?;
|
||||
@@ -841,12 +849,17 @@ fn app_ref(_: &Host, _: &[Data]) -> Answer {
|
||||
Ok(host_ref("Application", &[]))
|
||||
}
|
||||
|
||||
/// The open documents in the order `documents` lists them ([`Session::front_order`]).
|
||||
fn front_docs(s: &Session) -> impl Iterator<Item = &DocState> {
|
||||
s.front_order().into_iter().map(|i| &s.documents()[i])
|
||||
}
|
||||
|
||||
/// `documents[i]`, and `documents["name"]` as `getByName` reads it.
|
||||
fn docs_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let s = h.session.borrow();
|
||||
let at = match arg(a, 1) {
|
||||
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)),
|
||||
Data::String(name) => match s.documents().iter().find(|d| d.title() == *name) {
|
||||
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| front_docs(&s).nth(i)),
|
||||
Data::String(name) => match front_docs(&s).find(|d| d.title() == *name) {
|
||||
None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())),
|
||||
found => found,
|
||||
},
|
||||
@@ -858,7 +871,7 @@ fn docs_at(h: &Host, a: &[Data]) -> Answer {
|
||||
fn docs_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.title() == *name).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?;
|
||||
let st = front_docs(&s).find(|d| d.title() == *name).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?;
|
||||
Ok(doc_ref(h, st.uid))
|
||||
}
|
||||
|
||||
@@ -1181,8 +1194,58 @@ fn preset_of(h: &Host, d: &Data) -> Option<usize> {
|
||||
(i < h.dom.presets.borrow().len()).then_some(i)
|
||||
}
|
||||
|
||||
/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`, and
|
||||
/// a value is checked when `addDocument` uses it.
|
||||
/// The enumeration whose values the `DocumentPreset` setting `key` takes, when it takes one.
|
||||
fn preset_enum(key: &str) -> Option<&'static str> {
|
||||
Some(match key {
|
||||
"artboardLayout" => "DocumentArtboardLayout",
|
||||
"colorMode" => "DocumentColorSpace",
|
||||
"previewMode" => "DocumentPreviewMode",
|
||||
"rasterResolution" => "DocumentRasterResolution",
|
||||
"transparencyGrid" => "DocumentTransparencyGrid",
|
||||
"units" => "RulerUnits",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks that `value` is of the kind the `DocumentPreset` setting `key` holds: a value of its
|
||||
/// enumeration, a finite number, a title of at most [`MAX_TEXT_BYTES`] bytes, `true` or `false` for
|
||||
/// `documentBleedLink`, or four finite numbers for `documentBleedOffsetRect`. `undefined` unsets any
|
||||
/// setting, and the three settings `addDocument` does not apply yet also take `null`.
|
||||
fn check_preset_value(key: &str, value: &Data) -> std::result::Result<(), HostError> {
|
||||
let wrong = |kind: &str| Err(HostError::Type(format!("DocumentPreset.{key} must be {kind}")));
|
||||
match value {
|
||||
Data::Undefined => return Ok(()),
|
||||
Data::Null if matches!(key, "documentBleedLink" | "documentBleedOffsetRect" | "transparencyGrid") => return Ok(()),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(name) = preset_enum(key) {
|
||||
let member = ENUMS.iter().find(|(n, _)| *n == name).map_or(&[][..], |(_, m)| *m);
|
||||
return match value {
|
||||
Data::String(s) if s.strip_prefix(name).and_then(|r| r.strip_prefix('.')).is_some_and(|m| member.contains(&m)) => Ok(()),
|
||||
_ => wrong(&format!("a {name} value")),
|
||||
};
|
||||
}
|
||||
match key {
|
||||
"title" => match value {
|
||||
Data::String(t) if t.len() > MAX_TEXT_BYTES => Err(HostError::Range("the title is too long".into())),
|
||||
Data::String(_) => Ok(()),
|
||||
_ => wrong("a string"),
|
||||
},
|
||||
"documentBleedLink" => match value {
|
||||
Data::Bool(_) => Ok(()),
|
||||
_ => wrong("true or false"),
|
||||
},
|
||||
"documentBleedOffsetRect" => match value {
|
||||
Data::Array(r) if r.len() == 4 && r.iter().all(|n| matches!(n, Data::Number(n) if n.is_finite())) => Ok(()),
|
||||
_ => wrong("an array of four finite numbers"),
|
||||
},
|
||||
_ => number(value, &format!("DocumentPreset.{key}")).map(|_| ()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`. The
|
||||
/// setter checks the kind and size of a value ([`check_preset_value`]) and keeps the old value when
|
||||
/// it throws; `addDocument` checks the ranges.
|
||||
fn preset_field(link: &Link, key: &'static str) -> HostMember {
|
||||
let not_preset = || HostError::Type("this is not a DocumentPreset".into());
|
||||
let l = link.clone();
|
||||
@@ -1202,6 +1265,7 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember {
|
||||
let value = arg(&a, 1).clone();
|
||||
h.charge_call(16 + data_size(&value))?;
|
||||
let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?;
|
||||
check_preset_value(key, &value)?;
|
||||
let mut presets = h.dom.presets.borrow_mut();
|
||||
let fields = &mut presets[i];
|
||||
match fields.iter_mut().find(|(k, _)| k == key) {
|
||||
|
||||
@@ -1026,7 +1026,7 @@ const LOCK_PAUSE: std::time::Duration = std::time::Duration::from_millis(50);
|
||||
/// then the result is `Err` with [`std::io::ErrorKind::TimedOut`]. A change is not made when the
|
||||
/// lock cannot be taken.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn lock_store(store: &Path) -> std::io::Result<std::fs::File> {
|
||||
pub(crate) fn lock_store(store: &Path) -> std::io::Result<crate::store::LockedFile> {
|
||||
let lock = store.with_extension("lock");
|
||||
let opened = store
|
||||
.parent()
|
||||
@@ -1041,11 +1041,11 @@ fn lock_store(store: &Path) -> std::io::Result<std::fs::File> {
|
||||
|
||||
/// `file`, locked within [`lock_store`]'s tries.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn take_lock(file: std::fs::File) -> std::io::Result<std::fs::File> {
|
||||
fn take_lock(file: std::fs::File) -> std::io::Result<crate::store::LockedFile> {
|
||||
let mut tries = 1;
|
||||
loop {
|
||||
match file.try_lock() {
|
||||
Ok(()) => return Ok(file),
|
||||
Ok(()) => return Ok(crate::store::LockedFile::new(file)),
|
||||
Err(std::fs::TryLockError::Error(e)) => return Err(e),
|
||||
Err(std::fs::TryLockError::WouldBlock) if tries >= LOCK_TRIES => {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "another process holds the lock"));
|
||||
@@ -1068,7 +1068,7 @@ thread_local! {
|
||||
|
||||
/// The browser has no folders to keep anything in.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
|
||||
fn lock_store(_: &Path) -> std::io::Result<crate::store::LockedFile> {
|
||||
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
|
||||
}
|
||||
|
||||
|
||||
@@ -50,6 +50,30 @@ impl Default for Limits {
|
||||
}
|
||||
}
|
||||
|
||||
/// How a listing measures the time it has taken, which [`Limits::time`] bounds.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Clock {
|
||||
/// The real time since the listing started.
|
||||
#[default]
|
||||
Wall,
|
||||
/// The same time at every check, whatever the real time: the listing reaches the time limit
|
||||
/// only when this time is past it.
|
||||
Fixed(Duration),
|
||||
}
|
||||
|
||||
impl Clock {
|
||||
/// Calls `f` with this clock's time since `f` was called.
|
||||
pub fn time<T>(self, f: impl FnOnce(&mut dyn FnMut() -> Duration) -> T) -> T {
|
||||
match self {
|
||||
Clock::Wall => {
|
||||
let start = std::time::Instant::now();
|
||||
f(&mut || start.elapsed())
|
||||
}
|
||||
Clock::Fixed(elapsed) => f(&mut || elapsed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One row of a listing.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Entry {
|
||||
@@ -93,11 +117,10 @@ impl Listing {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the folder `root` holds, within the default [`Limits`]. A folder that does not exist gives
|
||||
/// an empty listing.
|
||||
pub fn list(root: &Path) -> Listing {
|
||||
let start = std::time::Instant::now();
|
||||
list_with(root, &Limits::default(), &mut || start.elapsed())
|
||||
/// What the folder `root` holds, within the default [`Limits`], with the time measured by `clock`.
|
||||
/// A folder that does not exist gives an empty listing.
|
||||
pub fn list(root: &Path, clock: Clock) -> Listing {
|
||||
clock.time(|elapsed| list_with(root, &Limits::default(), elapsed))
|
||||
}
|
||||
|
||||
/// What the folder `root` holds, within `limits`; `elapsed` says how long the listing has taken.
|
||||
|
||||
@@ -37,11 +37,10 @@ pub fn takes(name: &str) -> bool {
|
||||
&& Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("jsx"))
|
||||
}
|
||||
|
||||
/// The startup scripts in `root`, within the Scripts folder's limits. A folder that does not exist
|
||||
/// gives an empty listing.
|
||||
pub fn list(root: &Path) -> Listing {
|
||||
let start = std::time::Instant::now();
|
||||
list_with(root, &folder::Limits::default(), &mut || start.elapsed())
|
||||
/// The startup scripts in `root`, within the Scripts folder's limits, with the time measured by
|
||||
/// `clock`. A folder that does not exist gives an empty listing.
|
||||
pub fn list(root: &Path, clock: folder::Clock) -> Listing {
|
||||
clock.time(|elapsed| list_with(root, &folder::Limits::default(), elapsed))
|
||||
}
|
||||
|
||||
/// The startup scripts in `root`, within `limits` (the entries, scripts and time ones);
|
||||
|
||||
@@ -72,6 +72,7 @@ impl Session {
|
||||
last_selection_tool: None,
|
||||
last_part_selection_tool: None,
|
||||
press_lent: None,
|
||||
behind_armed: None,
|
||||
hover_lent: None,
|
||||
last_view: ViewInfo::default(),
|
||||
preview_memo: Default::default(),
|
||||
@@ -112,6 +113,7 @@ impl Session {
|
||||
plugin_loads_in_background: false,
|
||||
scripts_dir: None,
|
||||
startup_scripts_dir: None,
|
||||
script_listing_clock: Default::default(),
|
||||
metadata_templates_dir: None,
|
||||
new_doc_profile_dir: None,
|
||||
proof_setup_dir: None,
|
||||
@@ -227,6 +229,7 @@ impl Session {
|
||||
}
|
||||
self.press_type_selection = None;
|
||||
self.press_lent = None;
|
||||
self.behind_armed = None;
|
||||
let view = self.last_view;
|
||||
// The edit the tool computes on another thread and the input held for it belong to the
|
||||
// document being left. The switch goes on whatever they did, as for the deactivation.
|
||||
@@ -256,11 +259,29 @@ impl Session {
|
||||
self.reset_tool_for_doc_switch();
|
||||
}
|
||||
|
||||
/// The tab indices of the open documents from the front: the current document first, then
|
||||
/// the others from the one that was current most recently to the one current longest ago
|
||||
/// (tab order among documents that have not been current).
|
||||
pub fn front_order(&self) -> Vec<usize> {
|
||||
let mut order: Vec<usize> = (0..self.docs.len()).collect();
|
||||
order.sort_by_key(|&i| (Some(i) != self.active, std::cmp::Reverse(self.docs[i].activated)));
|
||||
order
|
||||
}
|
||||
|
||||
/// Marks the document in tab `index` as the one current most recently ([`Session::front_order`]).
|
||||
fn stamp_activated(&mut self, index: usize) {
|
||||
let next = self.docs.iter().map(|d| d.activated).max().unwrap_or(0) + 1;
|
||||
if let Some(st) = self.docs.get_mut(index) {
|
||||
st.activated = next;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_active(&mut self, index: usize) -> bool {
|
||||
if index < self.docs.len() {
|
||||
let switched = self.active != Some(index);
|
||||
if switched {
|
||||
self.reset_tool_for_doc_switch();
|
||||
self.stamp_activated(index);
|
||||
}
|
||||
self.active = Some(index);
|
||||
if switched {
|
||||
@@ -385,6 +406,7 @@ impl Session {
|
||||
self.docs.push(st);
|
||||
let i = self.docs.len() - 1;
|
||||
self.active = Some(i);
|
||||
self.stamp_activated(i);
|
||||
self.sync_opened_composite_fonts(i);
|
||||
self.sync_front_profiles();
|
||||
if self.depth == 0
|
||||
@@ -428,6 +450,7 @@ impl Session {
|
||||
st.history.limit = old.history.limit;
|
||||
// Same open document (caches keyed by uid stay valid); a new revision redraws it.
|
||||
st.uid = old.uid;
|
||||
st.activated = old.activated;
|
||||
// Work started for the content being thrown away is dropped when it finishes.
|
||||
st.reverts = old.reverts + 1;
|
||||
st.opened_as_tab = old.opened_as_tab;
|
||||
@@ -512,6 +535,9 @@ impl Session {
|
||||
return true;
|
||||
}
|
||||
self.active = if self.docs.is_empty() { None } else { Some(index.min(self.docs.len() - 1)) };
|
||||
if let Some(i) = self.active {
|
||||
self.stamp_activated(i);
|
||||
}
|
||||
self.sync_front_composite_fonts();
|
||||
self.sync_front_profiles();
|
||||
true
|
||||
|
||||
@@ -149,6 +149,7 @@ impl Session {
|
||||
st.active_layer = st.doc.default_layer();
|
||||
}
|
||||
}
|
||||
st.leave_isolation_if_gone();
|
||||
st.revision += 1;
|
||||
if st.interaction.is_none() {
|
||||
let selection = match st.history.undo.last() {
|
||||
@@ -578,7 +579,8 @@ impl Session {
|
||||
if !Arc::ptr_eq(&st.doc, &it.doc) || selection_changed {
|
||||
st.revision += 1;
|
||||
}
|
||||
st.doc = it.doc.clone();
|
||||
let undone = std::mem::replace(&mut st.doc, it.doc.clone());
|
||||
let isolation = it.isolation;
|
||||
// A batch, or a preview that changed the new-art paints (a pattern rename), started from
|
||||
// the paints the interaction began with.
|
||||
it.used_defaults_only |= cmd::asks_defaults_only(params);
|
||||
@@ -601,6 +603,9 @@ impl Session {
|
||||
// Guides locked and slices locked or hidden during the interaction stay deselected,
|
||||
// even when the preview fails.
|
||||
deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
// The previous preview's end of isolation mode, when it removed the isolated object, is
|
||||
// undone with it.
|
||||
st.restore_isolation(isolation, &undone);
|
||||
cmd::globaledit::follow_history(st);
|
||||
(paint, restore_paint)
|
||||
};
|
||||
|
||||
@@ -17,7 +17,8 @@ impl Session {
|
||||
if let Some(st) = self.active_mut()
|
||||
&& st.undo_group.is_none()
|
||||
{
|
||||
st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label, paint });
|
||||
let isolation = st.isolation;
|
||||
st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label, paint, isolation });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +32,9 @@ impl Session {
|
||||
let paint = self.paint.clone();
|
||||
for st in &mut self.docs {
|
||||
if !open.contains(&st.uid) && st.undo_group.is_none() {
|
||||
st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone(), paint: paint.clone() });
|
||||
let isolation = st.isolation;
|
||||
st.undo_group =
|
||||
Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone(), paint: paint.clone(), isolation });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -113,9 +116,10 @@ impl Session {
|
||||
if let Some((before, _)) = e.color_mode_paints {
|
||||
self.paint = before;
|
||||
}
|
||||
st.doc = e.doc;
|
||||
let undone = std::mem::replace(&mut st.doc, e.doc);
|
||||
st.selection = Arc::unwrap_or_clone(e.selection);
|
||||
deselect_hidden(&self.menu, &st.doc, &mut st.selection);
|
||||
st.restore_isolation(g.isolation, &undone);
|
||||
st.sync_new_art();
|
||||
cmd::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
@@ -229,10 +233,11 @@ impl Session {
|
||||
.and_then(|first| st.history.undo.last().filter(|e| Arc::ptr_eq(&e.doc, first)).and_then(|e| e.color_mode_paints.clone()));
|
||||
let paint = self.paint.clone();
|
||||
let joined = st.undo_group.as_ref().map(|g| (st.doc.clone(), st.selection.clone(), g.first.clone()));
|
||||
let isolation = st.isolation;
|
||||
if joined.is_none() {
|
||||
self.begin_undo_group();
|
||||
}
|
||||
Some(UndoScope { uid, journal, joined, paint, color_mode_paints })
|
||||
Some(UndoScope { uid, journal, joined, isolation, paint, color_mode_paints })
|
||||
}
|
||||
|
||||
/// End `scope` in its own document, whichever document is active now; undo groups open in other
|
||||
@@ -268,8 +273,9 @@ impl Session {
|
||||
}
|
||||
Some(_) => return,
|
||||
}
|
||||
st.doc = doc;
|
||||
let undone = std::mem::replace(&mut st.doc, doc);
|
||||
st.selection = selection;
|
||||
st.restore_isolation(scope.isolation, &undone);
|
||||
cmd::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
|
||||
+41
-10
@@ -491,15 +491,40 @@ fn write_atomic(_: &Path, _: &[u8]) -> std::io::Result<()> {
|
||||
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
|
||||
}
|
||||
|
||||
/// [`DISABLED_LOCK`] in the plug-in store `dir`, locked until the file is dropped, waiting while
|
||||
/// A lock file this process locked, unlocked when it is dropped. 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.
|
||||
pub(crate) struct LockedFile(std::fs::File);
|
||||
|
||||
impl LockedFile {
|
||||
/// `file`, which the caller has locked.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn new(file: std::fs::File) -> Self {
|
||||
LockedFile(file)
|
||||
}
|
||||
|
||||
/// The locked file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn file(&self) -> &std::fs::File {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LockedFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/// [`DISABLED_LOCK`] in the plug-in store `dir`, locked until it is dropped, waiting while
|
||||
/// another window or process holds it, or another handle in this process. The file is opened for
|
||||
/// reading and writing (a handle that only appends can't be locked on Windows) and is never
|
||||
/// replaced or removed, so that every window locks the same file.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn lock_store(dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
fn lock_store(dir: &Path) -> std::io::Result<LockedFile> {
|
||||
let file = open_store_lock(dir)?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => return Ok(file),
|
||||
Ok(()) => return Ok(LockedFile::new(file)),
|
||||
Err(std::fs::TryLockError::WouldBlock) => {}
|
||||
Err(std::fs::TryLockError::Error(e)) => return Err(e),
|
||||
}
|
||||
@@ -508,7 +533,7 @@ fn lock_store(dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
waiting();
|
||||
}
|
||||
file.lock()?;
|
||||
Ok(file)
|
||||
Ok(LockedFile::new(file))
|
||||
}
|
||||
|
||||
/// [`DISABLED_LOCK`] in `dir`, opened (and made, with the folder) but not locked.
|
||||
@@ -520,10 +545,10 @@ fn open_store_lock(dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
|
||||
/// [`lock_store`] without waiting: `None` while another window or process holds the lock.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn try_lock_store(dir: &Path) -> std::io::Result<Option<std::fs::File>> {
|
||||
fn try_lock_store(dir: &Path) -> std::io::Result<Option<LockedFile>> {
|
||||
let file = open_store_lock(dir)?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => Ok(Some(file)),
|
||||
Ok(()) => Ok(Some(LockedFile::new(file))),
|
||||
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
|
||||
Err(std::fs::TryLockError::Error(e)) => Err(e),
|
||||
}
|
||||
@@ -531,13 +556,13 @@ fn try_lock_store(dir: &Path) -> std::io::Result<Option<std::fs::File>> {
|
||||
|
||||
/// The browser has no folders to keep anything in.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn try_lock_store(_: &Path) -> std::io::Result<Option<std::fs::File>> {
|
||||
fn try_lock_store(_: &Path) -> std::io::Result<Option<LockedFile>> {
|
||||
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
|
||||
}
|
||||
|
||||
/// The browser has no folders to keep anything in.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
|
||||
fn lock_store(_: &Path) -> std::io::Result<LockedFile> {
|
||||
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
|
||||
}
|
||||
|
||||
@@ -548,7 +573,7 @@ fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
|
||||
pub(crate) struct StoreTurn {
|
||||
/// [`DISABLED_LOCK`], locked; `None` without a store, and for a load that goes ahead without
|
||||
/// a turn ([`Session::plugin_store_turn_for_load`]), which then writes nothing to the store.
|
||||
lock: Option<std::fs::File>,
|
||||
lock: Option<LockedFile>,
|
||||
}
|
||||
|
||||
impl StoreTurn {
|
||||
@@ -557,6 +582,12 @@ impl StoreTurn {
|
||||
StoreTurn { lock: None }
|
||||
}
|
||||
|
||||
/// Tests: the locked [`DISABLED_LOCK`], when the turn is held.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn lock_file(&self) -> Option<&std::fs::File> {
|
||||
self.lock.as_ref().map(LockedFile::file)
|
||||
}
|
||||
|
||||
/// Whether the store may be written in this turn.
|
||||
fn held(&self) -> bool {
|
||||
self.lock.is_some()
|
||||
@@ -1838,7 +1869,7 @@ impl PluginStorage {
|
||||
|
||||
/// A turn on the plug-in store ([`lock_store`]), taken before [`PLUGIN_DATA_LOCK`], so that a
|
||||
/// window or process changing the same settings or cache waits for this change.
|
||||
fn turn(&self) -> Result<std::fs::File, StorageError> {
|
||||
fn turn(&self) -> Result<LockedFile, StorageError> {
|
||||
lock_store(&self.root).map_err(|e| StorageError::Io(format!("{STORE_NOT_LOCKED}: {e}")))
|
||||
}
|
||||
|
||||
|
||||
@@ -94,6 +94,7 @@ mod interaction_commands;
|
||||
mod interactivity;
|
||||
mod interpolate_handles;
|
||||
mod intertwine;
|
||||
mod isolation_removed;
|
||||
mod journal;
|
||||
mod keyanchor;
|
||||
mod keyguide;
|
||||
|
||||
@@ -5160,14 +5160,15 @@ fn a_cmd_double_click_after_switching_away_and_back_goes_to_the_active_tool() {
|
||||
|
||||
#[test]
|
||||
fn a_cmd_press_on_a_selected_object_keeps_select_behind() {
|
||||
// Over a selected object, a Cmd-click with the Selection tool selects the object behind it;
|
||||
// with Select Behind off, Direct Selection takes the press there too.
|
||||
// Over a selected object, a Cmd-click with the Selection tool after an earlier Cmd press
|
||||
// selects the object behind it; with Select Behind off, Direct Selection takes the press there
|
||||
// too.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
arm_select_behind(&mut s, v);
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
// The canvas shows the marks of the tool a press at the pointer takes, and the status bar and
|
||||
// the help bar name it.
|
||||
@@ -5206,7 +5207,7 @@ fn a_cmd_press_on_a_selected_object_keeps_select_behind() {
|
||||
#[test]
|
||||
fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() {
|
||||
// Without Use Preview Bounds the bounding box leaves out the outer half of a wide stroke, which
|
||||
// the Selection tool still hits: a Cmd press there selects the object behind.
|
||||
// the Selection tool still hits: once armed, a Cmd press there selects the object behind.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
@@ -5214,7 +5215,7 @@ fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() {
|
||||
let back = rect(&mut s, 50.0, 50.0, 300.0, 300.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.execute("stroke.set", &json!({"ids": [front.0], "weight": 40})).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
arm_select_behind(&mut s, v);
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
// 15 pt outside the path, on its stroke.
|
||||
let at = Point::new(200.0, 135.0);
|
||||
@@ -5229,12 +5230,12 @@ fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() {
|
||||
#[test]
|
||||
fn a_cmd_press_on_a_lone_selected_object_is_lent() {
|
||||
// With nothing behind the selected object, there is nothing to select behind: Direct Selection
|
||||
// takes the press.
|
||||
// takes the press, also once a Cmd press has armed Select Behind.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let lone = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
arm_select_behind(&mut s, v);
|
||||
s.execute("select.set", &json!({"ids": [lone.0]})).unwrap();
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "directSelection");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
@@ -5262,7 +5263,7 @@ fn a_layer_effect_that_moves_art_moves_where_a_cmd_press_selects_behind() {
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
let params = if effect == "distort.transform" { json!({"moveH": 250}) } else { json!({"x": 250, "y": 0, "blur": 0}) };
|
||||
s.execute("effect.apply", &json!({"effect": effect, "params": params, "ids": [layer.0], "item": null})).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
arm_select_behind(&mut s, v);
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
// The back rectangle is drawn moved too, so it is under both points.
|
||||
if effect == "distort.transform" {
|
||||
@@ -5310,6 +5311,105 @@ fn repeated_cmd_clicks_select_behind_a_group_whose_member_is_selected() {
|
||||
assert!(picked.contains(back) && !picked.contains(a), "the second Cmd-click selects the object behind the group");
|
||||
}
|
||||
|
||||
/// A back rectangle under a group whose small top member lies over a large one, all three under
|
||||
/// (200, 200): (back, group, large, small).
|
||||
fn stacked_group(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) {
|
||||
let back = rect(s, 100.0, 100.0, 200.0, 200.0);
|
||||
let large = rect(s, 120.0, 120.0, 160.0, 160.0);
|
||||
let small = rect(s, 170.0, 170.0, 60.0, 60.0);
|
||||
let group = NodeId(s.execute("object.group", &json!({"ids": [large.0, small.0]})).unwrap()["id"].as_u64().unwrap());
|
||||
(back, group, large, small)
|
||||
}
|
||||
|
||||
/// A Cmd-click at (200, 200), Cmd held before and after it.
|
||||
fn cmd_click(s: &mut Session, v: ViewInfo) {
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Arms Select Behind with a Cmd-click with the Selection tool on empty canvas, away from the art
|
||||
/// of the tests, Cmd still held: the next Cmd-click over the selection selects behind.
|
||||
fn arm_select_behind(s: &mut Session, v: ViewInfo) {
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
s.select_tool("selection", v).unwrap();
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, 900.0, 900.0).with_mods(cmd), v).unwrap();
|
||||
}
|
||||
assert!(s.behind_armed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_clicks_step_through_the_members_of_a_group_then_behind_it() {
|
||||
// With Cmd held, the first click picks the group's top member, and each further one the object
|
||||
// under it, the group's other member included, then back to the top member.
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let (back, group, large, small) = stacked_group(&mut s);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
for (i, want) in [small, large, back, small].into_iter().enumerate() {
|
||||
cmd_click(&mut s, v);
|
||||
let picked = &s.active().unwrap().selection.objects;
|
||||
assert_eq!(picked, &vec![want], "Cmd-click {}", i + 1);
|
||||
assert!(!picked.contains(&group), "Cmd-click {} picks one object", i + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_cmd_click_on_a_selected_group_does_not_select_behind() {
|
||||
// The first Cmd-click over the selected group is Direct Selection's: it does not select the
|
||||
// object behind the group. Clicking on with Cmd held reaches the object behind.
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let (back, group, ..) = stacked_group(&mut s);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "directSelection", "not armed yet: the press is lent");
|
||||
cmd_click(&mut s, v);
|
||||
assert!(!s.active().unwrap().selection.contains(back), "the first Cmd-click does not select behind");
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection", "armed: the next press selects behind");
|
||||
let reached = (0..3).any(|_| {
|
||||
cmd_click(&mut s, v);
|
||||
s.active().unwrap().selection.contains(back)
|
||||
});
|
||||
assert!(reached, "further Cmd-clicks reach the object behind the group");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn letting_go_of_cmd_ends_select_behind() {
|
||||
// After a Cmd-click, Cmd let go and pressed again: the next Cmd-click is Direct Selection's
|
||||
// again, which keeps the picked member, and does not step to the one under it.
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
let (_, _, large, small) = stacked_group(&mut s);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
cmd_click(&mut s, v);
|
||||
assert!(s.behind_armed());
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 200.0), v).unwrap();
|
||||
assert!(!s.behind_armed(), "Cmd let go");
|
||||
cmd_click(&mut s, v);
|
||||
let picked = &s.active().unwrap().selection;
|
||||
assert!(picked.contains(small) && !picked.contains(large), "the Cmd-click after letting go keeps the top member");
|
||||
// Cmd let go between frames, with no pointer event, also ends it.
|
||||
cmd_click(&mut s, v);
|
||||
assert!(s.active().unwrap().selection.contains(large), "armed again: the Cmd-click steps under");
|
||||
s.hover_tool_at(Some(Point::new(200.0, 200.0)), &Mods::default(), v);
|
||||
assert!(!s.behind_armed(), "the frame found Cmd up");
|
||||
// So does a key pressed without Cmd, as the automation interface sends it.
|
||||
cmd_click(&mut s, v);
|
||||
s.tool_key(ToolKey::Tab, Mods::default(), v).unwrap();
|
||||
assert!(!s.behind_armed(), "the key came without Cmd");
|
||||
// Choosing a tool ends it too.
|
||||
cmd_click(&mut s, v);
|
||||
s.select_tool("rectangle", v).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
assert!(!s.behind_armed(), "the tool changed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_double_click_after_a_selection_change_is_not_kept_for_select_behind() {
|
||||
// A double-click that follows a Cmd-click selecting behind keeps what it selected, but only
|
||||
@@ -5319,7 +5419,7 @@ fn a_double_click_after_a_selection_change_is_not_kept_for_select_behind() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
arm_select_behind(&mut s, v);
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
@@ -5336,7 +5436,7 @@ fn a_double_click_after_the_pointer_moved_away_is_not_kept_for_select_behind() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
arm_select_behind(&mut s, v);
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
@@ -5356,7 +5456,7 @@ fn a_double_click_after_a_select_behind_drag_is_not_kept_for_select_behind() {
|
||||
let mut s = session();
|
||||
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
arm_select_behind(&mut s, v);
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
@@ -5375,7 +5475,7 @@ fn a_double_click_after_a_select_behind_press_released_away_is_not_kept_for_sele
|
||||
let mut s = session();
|
||||
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
arm_select_behind(&mut s, v);
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 270.0, 270.0).with_mods(cmd), v).unwrap();
|
||||
@@ -5392,7 +5492,7 @@ fn a_double_click_in_the_frame_of_a_select_behind_press_keeps_what_it_selected()
|
||||
let mut s = session();
|
||||
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
arm_select_behind(&mut s, v);
|
||||
s.execute("select.set", &json!({"ids": [back.0]})).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0).with_mods(cmd), v).unwrap();
|
||||
@@ -5402,8 +5502,10 @@ fn a_double_click_in_the_frame_of_a_select_behind_press_keeps_what_it_selected()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmd_click_on_an_unselected_member_of_a_group_holding_the_selection_selects_behind() {
|
||||
// The group counts as selected wherever its art is, not only over its selected member.
|
||||
fn a_cmd_click_on_an_unselected_member_of_a_group_holding_the_selection_selects_that_member() {
|
||||
// Select Behind counts the members of a group one by one: with one member selected, a Cmd-click
|
||||
// on another member picks that member, not the object behind the group, also when armed. The
|
||||
// Cmd-click after it selects the object behind.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
@@ -5411,13 +5513,19 @@ fn a_cmd_click_on_an_unselected_member_of_a_group_holding_the_selection_selects_
|
||||
let a = rect(&mut s, 150.0, 150.0, 40.0, 40.0);
|
||||
let b = rect(&mut s, 300.0, 150.0, 40.0, 40.0);
|
||||
s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.select_tool("selection", v).unwrap();
|
||||
arm_select_behind(&mut s, v);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(320.0, 170.0)), &cmd, v), "selection", "on the unselected member");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 320.0, 170.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 170.0).with_mods(cmd), v).unwrap();
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(320.0, 170.0)), &cmd, v), "directSelection", "on the unselected member");
|
||||
let click = |s: &mut Session| {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 320.0, 170.0).with_mods(cmd), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 170.0).with_mods(cmd), v).unwrap();
|
||||
};
|
||||
click(&mut s);
|
||||
let picked = &s.active().unwrap().selection;
|
||||
assert!(picked.contains(back) && !picked.contains(b), "the Cmd-click selects the object behind the group");
|
||||
assert!(picked.contains(b) && !picked.contains(back) && !picked.contains(a), "the Cmd-click picks the member");
|
||||
click(&mut s);
|
||||
let picked = &s.active().unwrap().selection;
|
||||
assert!(picked.contains(back) && !picked.contains(b), "the next Cmd-click selects the object behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -5429,7 +5537,7 @@ fn a_cmd_click_on_a_selected_lines_segment_selects_behind() {
|
||||
let mut s = session();
|
||||
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = line(&mut s, 150.0, 150.0, 250.0, 250.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
arm_select_behind(&mut s, v);
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(150.0, 150.0)), &cmd, v), "directSelection", "on its anchor");
|
||||
// On the segment, away from the anchors and the bounding box's handles.
|
||||
@@ -5449,7 +5557,7 @@ fn a_hovers_lend_decision_holds_only_for_the_tool_and_selection_it_was_found_for
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
arm_select_behind(&mut s, v);
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
@@ -5468,7 +5576,7 @@ fn the_marks_follow_this_frames_pointer_with_cmd_held() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
|
||||
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
|
||||
s.select_tool("selection", v).unwrap();
|
||||
arm_select_behind(&mut s, v);
|
||||
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
|
||||
s.cursor(Point::new(200.0, 200.0), cmd, v);
|
||||
assert_eq!(s.hover_tool_id(&cmd), "selection");
|
||||
|
||||
@@ -273,6 +273,35 @@ fn fill_area_takes_art_in_nested_clipping_groups_only_where_every_mask_shows_it(
|
||||
assert_eq!(stack(&s), vec![outer, id_of(&r)]);
|
||||
}
|
||||
|
||||
/// A clipped open path with more segments than the mask can be cut against is not known to show or
|
||||
/// hide anywhere inside its mask: a square it crosses inside the mask is not filled across it. A
|
||||
/// square it stays clear of, and a square it crosses where its mask hides it, are still filled.
|
||||
#[test]
|
||||
fn fill_area_does_not_fill_across_a_clipped_path_its_mask_cannot_cut() {
|
||||
// The path's y, its mask's left edge and width, the click and whether the square is filled.
|
||||
for (y, (mx, mw), click, fills) in
|
||||
[(50.0, (-50.0, 200.0), [50, 25], false), (150.0, (-50.0, 200.0), [50, 50], true), (50.0, (200.0, 100.0), [50, 25], true)]
|
||||
{
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let n = vectorcraft_pathops::addons::pathtools::MAX_CROSSING_SEGMENTS + 1;
|
||||
let pts: Vec<Point> = (0..=n).map(|k| Point::new(-20.0 + 340.0 * k as f64 / n as f64, y)).collect();
|
||||
let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let huge = insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look);
|
||||
clip_by(&mut s, &[huge], mx, -50.0, mw, 250.0);
|
||||
deselect(&mut s);
|
||||
let (undo, kids) = (undo_len(&s), stack(&s));
|
||||
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": click}));
|
||||
if fills {
|
||||
let r = r.unwrap_or_else(|e| panic!("y {y}, mask at {mx}: {e:?}"));
|
||||
assert!((area(&s, id_of(&r)) - 10_000.0).abs() < 1.0, "{}", area(&s, id_of(&r)));
|
||||
} else {
|
||||
assert!(r.is_err(), "the path crosses the square where its mask shows it");
|
||||
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// In isolation mode only the isolated group's paths bound areas, for the command and the tool: a
|
||||
/// click in an area that art outside the group encloses adds nothing, and the new path goes inside
|
||||
/// the group, above the path along the area.
|
||||
@@ -912,6 +941,26 @@ fn fill_area_tool_hovers_a_large_document_on_another_thread() {
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
}
|
||||
|
||||
/// A clipped path with more segments than its mask can be cut against is in no map, but a search
|
||||
/// still checks it against the area, so the hover over a square beside it runs on another thread.
|
||||
#[test]
|
||||
fn fill_area_tool_hovers_beside_a_clipped_path_its_mask_cannot_cut_on_another_thread() {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let n = vectorcraft_pathops::addons::pathtools::MAX_CROSSING_SEGMENTS + 1;
|
||||
let pts: Vec<Point> = (0..=n).map(|k| Point::new(-20.0 + 140.0 * k as f64 / n as f64, 150.0)).collect();
|
||||
let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let huge = insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look);
|
||||
clip_by(&mut s, &[huge], -50.0, -50.0, 200.0, 250.0);
|
||||
deselect(&mut s);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("fillArea", v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 50.0, 50.0), v).unwrap();
|
||||
assert!(s.tool_waiting(), "the search runs on another thread");
|
||||
s.tool_poll(v, true).unwrap();
|
||||
assert_eq!(s.overlays(v).len(), 1, "the square is outlined");
|
||||
}
|
||||
|
||||
/// A press that is dropped before the release (a long or canceled touch) takes the new path back
|
||||
/// and records no undo step.
|
||||
#[test]
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! and Refresh Font List (`text.rescanFonts`).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_text::test_fonts::steady_fonts;
|
||||
use vectorcraft_text::{FontDb, system_font_dirs};
|
||||
|
||||
use crate::*;
|
||||
@@ -13,12 +14,12 @@ fn names(v: &Value) -> Vec<String> {
|
||||
#[test]
|
||||
fn the_font_list_names_every_available_family_with_its_styles() {
|
||||
let mut s = Session::new();
|
||||
let fams = names(&s.execute("text.fontList", &json!({})).unwrap()["families"]);
|
||||
// Other tests running at the same time add and remove composite fonts, which the lists show
|
||||
// first; the installed families are compared.
|
||||
let db = FontDb::global();
|
||||
let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::<Vec<_>>();
|
||||
assert_eq!(installed_only(&fams), installed_only(&db.menu_family_list()));
|
||||
// Tests running alongside add fonts and composite fonts to the process-wide database; their
|
||||
// changes wait until this test ends, so both lists are read from the same fonts.
|
||||
let _steady = steady_fonts(db);
|
||||
let fams = names(&s.execute("text.fontList", &json!({})).unwrap()["families"]);
|
||||
assert_eq!(fams, db.menu_family_list().to_vec());
|
||||
for f in ["Source Sans 3", "Source Serif 4", "Inter", "JetBrains Mono"] {
|
||||
assert!(fams.iter().any(|x| x == f), "{f}");
|
||||
}
|
||||
@@ -40,6 +41,9 @@ fn the_font_list_names_every_available_family_with_its_styles() {
|
||||
fn similar_fonts_lists_every_family_by_likeness() {
|
||||
let mut s = Session::new();
|
||||
let db = FontDb::global();
|
||||
// Tests running alongside add fonts and composite fonts to the process-wide database; their
|
||||
// changes wait until this test ends, so every answer is made from the same fonts.
|
||||
let _steady = steady_fonts(db);
|
||||
let r = s.execute("text.similarFonts", &json!({"family": "source sans 3"})).unwrap();
|
||||
assert_eq!(r["family"], "Source Sans 3");
|
||||
let order = names(&r["families"]);
|
||||
@@ -48,31 +52,10 @@ fn similar_fonts_lists_every_family_by_likeness() {
|
||||
sorted.sort();
|
||||
let mut listed = db.menu_family_list().to_vec();
|
||||
listed.sort();
|
||||
// Other tests running at the same time add and remove composite fonts; the installed families are compared.
|
||||
let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::<Vec<_>>();
|
||||
assert_eq!(installed_only(&sorted), installed_only(&listed), "every family once");
|
||||
// The two answers are compared whole when the available fonts did not change while both were
|
||||
// made (the same `FontDb::generation`), and by their installed families when they changed
|
||||
// during every try.
|
||||
let mut answers = (vec![], vec![], false);
|
||||
for _ in 0..20 {
|
||||
let generation = db.generation();
|
||||
let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]);
|
||||
let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]);
|
||||
let unchanged = db.generation() == generation;
|
||||
answers = (all, two, unchanged);
|
||||
if unchanged {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (all, two, unchanged) = answers;
|
||||
assert_eq!(two.len(), 2);
|
||||
if unchanged {
|
||||
assert_eq!(two, all[..2], "the first families, in order");
|
||||
} else {
|
||||
let (two, all) = (installed_only(&two), installed_only(&all));
|
||||
assert_eq!(two[..], all[..two.len()], "the first installed families, in order");
|
||||
}
|
||||
assert_eq!(sorted, listed, "every family once");
|
||||
let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]);
|
||||
let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]);
|
||||
assert_eq!(two, all[..2], "the first families, in order");
|
||||
for (params, error) in [
|
||||
(json!({}), "`family` is required"),
|
||||
(json!({"family": " "}), "`family` is required"),
|
||||
@@ -94,6 +77,9 @@ fn refreshing_the_font_list_redraws_type_without_editing_the_document() {
|
||||
s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Type", "font": "No Such Font"})).unwrap();
|
||||
s.doc_mut().unwrap().mark_saved();
|
||||
let revision = s.doc().unwrap().revision;
|
||||
// Fonts that tests running alongside add wait until this test ends, so the count is of the
|
||||
// fonts the rescan left.
|
||||
let _steady = steady_fonts(FontDb::global());
|
||||
let r = s.execute("text.rescanFonts", &json!({})).unwrap();
|
||||
assert_eq!(r["families"], json!(FontDb::global().menu_family_list().len()));
|
||||
assert!(r["faces"].is_u64());
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! Isolation mode ends when an edit removes the isolated object, and comes back when that edit is
|
||||
//! taken back by a canceled undo group or scope or by an interaction's next preview.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{rect, session};
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, cmd: &str, p: Value) -> Value {
|
||||
s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}"))
|
||||
}
|
||||
|
||||
fn isolation(s: &Session) -> Option<NodeId> {
|
||||
s.doc().unwrap().isolation
|
||||
}
|
||||
|
||||
fn exists(s: &Session, id: NodeId) -> bool {
|
||||
s.doc().unwrap().doc.node(id).is_some()
|
||||
}
|
||||
|
||||
/// A group of two rectangles, isolated.
|
||||
fn isolated_group(s: &mut Session) -> NodeId {
|
||||
let a = rect(s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(s, 20.0, 0.0, 10.0, 10.0);
|
||||
run(s, "select.set", json!({"ids": [a.0, b.0]}));
|
||||
let g = NodeId(run(s, "object.group", json!({}))["id"].as_u64().unwrap());
|
||||
run(s, "object.isolate", json!({"id": g.0}));
|
||||
g
|
||||
}
|
||||
|
||||
/// Clear and Ungroup on the isolated group end isolation mode; Undo brings the group back without
|
||||
/// isolating it, and Redo removes it again with isolation mode still off.
|
||||
#[test]
|
||||
fn an_edit_that_removes_the_isolated_object_ends_isolation_mode() {
|
||||
for cmd in ["edit.clear", "object.ungroup"] {
|
||||
let mut s = session();
|
||||
let g = isolated_group(&mut s);
|
||||
run(&mut s, cmd, json!({"ids": [g.0]}));
|
||||
assert!(!exists(&s, g), "{cmd}: the group is gone");
|
||||
assert_eq!(isolation(&s), None, "{cmd}");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(exists(&s, g), "{cmd}: undone");
|
||||
assert_eq!(isolation(&s), None, "{cmd}: undone");
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!(isolation(&s), None, "{cmd}: redone");
|
||||
}
|
||||
// So does a script that removes it.
|
||||
let mut s = session();
|
||||
let g = isolated_group(&mut s);
|
||||
run(&mut s, "script.run", json!({"source": "app.activeDocument.pageItems[0].remove();", "name": "t.js"}));
|
||||
assert!(!exists(&s, g), "script: the group is gone");
|
||||
assert_eq!(isolation(&s), None, "script");
|
||||
// Clearing the art inside the isolated group keeps the group and isolation mode.
|
||||
let mut s = session();
|
||||
let g = isolated_group(&mut s);
|
||||
let inside = s.doc().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id.0).collect::<Vec<_>>();
|
||||
run(&mut s, "edit.clear", json!({"ids": inside}));
|
||||
assert!(exists(&s, g));
|
||||
assert_eq!(isolation(&s), Some(g));
|
||||
}
|
||||
|
||||
/// While a symbol is edited, removing a group isolated inside the symbol's editing layer isolates
|
||||
/// that layer again, as Exit Isolation Mode from the group does, and symbol editing goes on.
|
||||
#[test]
|
||||
fn removing_a_group_isolated_in_symbol_editing_isolates_the_editing_layer() {
|
||||
for cmd in ["edit.clear", "object.ungroup"] {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 80.0, 40.0);
|
||||
let instance = NodeId(run(&mut s, "symbol.new", json!({"name": "Box"}))["id"].as_u64().unwrap());
|
||||
let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": instance.0}))["layer"].as_u64().unwrap());
|
||||
rect(&mut s, 100.0, 100.0, 10.0, 10.0);
|
||||
let art = s.doc().unwrap().doc.node(layer).unwrap().children().unwrap().iter().map(|n| n.id.0).collect::<Vec<_>>();
|
||||
run(&mut s, "select.set", json!({ "ids": art }));
|
||||
let inner = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "object.isolate", json!({"id": inner.0}));
|
||||
assert_eq!(isolation(&s), Some(inner), "{cmd}");
|
||||
run(&mut s, cmd, json!({"ids": [inner.0]}));
|
||||
assert!(!exists(&s, inner), "{cmd}: the group is gone");
|
||||
assert!(s.doc().unwrap().doc.symbol_edit.is_some(), "{cmd}: still editing the symbol");
|
||||
assert_eq!(isolation(&s), Some(layer), "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A canceled undo group, and a canceled undo scope that joined an open group, put back the
|
||||
/// isolated group and isolation mode with it; a kept group leaves isolation mode off.
|
||||
#[test]
|
||||
fn canceled_undo_groups_and_scopes_isolate_the_object_again() {
|
||||
for cancel in [true, false] {
|
||||
let mut s = session();
|
||||
let g = isolated_group(&mut s);
|
||||
s.begin_undo_group();
|
||||
run(&mut s, "edit.clear", json!({"ids": [g.0]}));
|
||||
assert_eq!(isolation(&s), None);
|
||||
s.end_undo_group(cancel);
|
||||
assert_eq!(exists(&s, g), cancel, "cancel: {cancel}");
|
||||
assert_eq!(isolation(&s), cancel.then_some(g), "cancel: {cancel}");
|
||||
}
|
||||
|
||||
let mut s = session();
|
||||
let g = isolated_group(&mut s);
|
||||
s.begin_undo_group();
|
||||
run(&mut s, "object.move", json!({"ids": [g.0], "dx": 5, "dy": 0}));
|
||||
let scope = s.begin_undo_scope().unwrap();
|
||||
run(&mut s, "edit.clear", json!({"ids": [g.0]}));
|
||||
assert_eq!(isolation(&s), None);
|
||||
s.end_undo_scope(scope, true);
|
||||
assert!(exists(&s, g));
|
||||
assert_eq!(isolation(&s), Some(g), "joined scope canceled");
|
||||
s.end_undo_group(false);
|
||||
assert_eq!(isolation(&s), Some(g));
|
||||
}
|
||||
|
||||
/// An interaction's preview that removes the isolated object ends isolation mode; the next preview,
|
||||
/// which keeps it, starts again from isolation mode, and so does a cancel. A commit of the removing
|
||||
/// preview leaves isolation mode off.
|
||||
#[test]
|
||||
fn previews_put_back_isolation_mode_with_the_document() {
|
||||
let mut s = session();
|
||||
let g = isolated_group(&mut s);
|
||||
s.begin_interaction("Test").unwrap();
|
||||
s.preview("edit.clear", &json!({"ids": [g.0]})).unwrap();
|
||||
assert_eq!(isolation(&s), None, "the preview removed the group");
|
||||
s.preview("object.move", &json!({"ids": [g.0], "dx": 5, "dy": 0})).unwrap();
|
||||
assert_eq!(isolation(&s), Some(g), "the next preview keeps it");
|
||||
s.preview("edit.clear", &json!({"ids": [g.0]})).unwrap();
|
||||
s.cancel_interaction().unwrap();
|
||||
assert_eq!(isolation(&s), Some(g), "canceled");
|
||||
|
||||
s.begin_interaction("Test").unwrap();
|
||||
s.preview("edit.clear", &json!({"ids": [g.0]})).unwrap();
|
||||
s.commit_interaction().unwrap();
|
||||
assert!(!exists(&s, g));
|
||||
assert_eq!(isolation(&s), None, "committed");
|
||||
}
|
||||
@@ -1153,6 +1153,28 @@ fn transform_each_random_is_deterministic_with_seed() {
|
||||
assert!(x.x0.abs() <= 50.0 && x.width() == 100.0);
|
||||
}
|
||||
|
||||
/// Random with the same horizontal and vertical scale scales each object evenly, Relative and
|
||||
/// Absolute alike: one random share takes both sides toward the value, so squares stay square, each
|
||||
/// by its own share (#9320).
|
||||
#[test]
|
||||
fn transform_each_random_with_equal_scales_keeps_proportions() {
|
||||
for p in [
|
||||
json!({"scaleH": 40, "scaleV": 40, "random": true, "seed": 7}),
|
||||
json!({"scaleH": 40, "scaleV": 40, "relative": false, "random": true, "seed": 7}),
|
||||
] {
|
||||
let mut s = session();
|
||||
let ids: Vec<NodeId> = (0..8).map(|i| rect(&mut s, f64::from(i) * 150.0, 0.0, 100.0, 100.0)).collect();
|
||||
sel(&mut s, &ids);
|
||||
s.execute("object.transformEach", &p).unwrap();
|
||||
let sizes: Vec<(f64, f64)> = ids.iter().map(|id| bounds(&s, *id)).map(|b| (b.width(), b.height())).collect();
|
||||
for (w, h) in &sizes {
|
||||
assert!(close(*w, *h), "{p}: a square came out {w} × {h}");
|
||||
assert!(*w < 100.0, "{p}: a square didn't shrink: {w}");
|
||||
}
|
||||
assert!(sizes.iter().any(|(w, _)| !close(*w, sizes[0].0)), "{p}: every square took the same share: {sizes:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A `reference` or `seed` that is not a whole number (a fraction, a negative number or a string) is an error naming
|
||||
/// the key, and the object stays as it was; a `reference` of 0.0 is the top-left point.
|
||||
#[test]
|
||||
|
||||
@@ -452,6 +452,34 @@ fn a_group_shows_its_contents_in_the_proxies() {
|
||||
assert_eq!(s.proxy_paints().0, s.paint.fill);
|
||||
}
|
||||
|
||||
/// A targeted layer without an active Appearance row: the proxies show the paint of the layer's
|
||||
/// editable art, which `paint.setFill` and `paint.editGradient` change, not that of a locked object
|
||||
/// before it.
|
||||
#[test]
|
||||
fn a_targeted_layer_shows_its_editable_art_in_the_proxies() {
|
||||
let mut s = session();
|
||||
let locked = rect(&mut s);
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
let open = rect(&mut s);
|
||||
let stops = json!([{"offset": 0, "color": "#0000ff"}, {"offset": 1, "color": "#00ff00"}]);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"stops": stops}})).unwrap();
|
||||
s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap();
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.target", &json!({"id": layer.0})).unwrap();
|
||||
assert_eq!(s.proxy_paints().0, node(&s, open).appearance.fill().unwrap().paint);
|
||||
assert_eq!(s.execute("paint.proxies", &json!({})).unwrap()["fill"], json!(s.proxy_paints().0));
|
||||
// A stop edit of the gradient shown changes the editable art's gradient and leaves the locked
|
||||
// object's red fill alone.
|
||||
let Paint::Gradient(g) = s.proxy_paints().0 else { panic!("the proxy shows the gradient") };
|
||||
let mut stops = vectorcraft_tools::params::stops_json(&g.gradient.stops);
|
||||
stops[0]["opacity"] = json!(0.3);
|
||||
s.execute("paint.editGradient", &json!({"stops": stops})).unwrap();
|
||||
let Paint::Gradient(edited) = node(&s, open).appearance.fill().unwrap().paint.clone() else { panic!("still a gradient") };
|
||||
assert!((edited.gradient.stops[0].opacity - 0.3).abs() < 1e-6, "{:?}", edited.gradient.stops);
|
||||
assert_eq!(edited.gradient.stops[1].color.to_hex(), "#00ff00");
|
||||
assert_eq!(node(&s, locked).appearance.fill().unwrap().paint.color().unwrap().to_hex(), "#ff0000");
|
||||
}
|
||||
|
||||
/// The top fill and top stroke of object `id`.
|
||||
fn paints(s: &Session, id: NodeId) -> (Paint, Paint, f64) {
|
||||
let n = node(s, id);
|
||||
|
||||
@@ -1066,6 +1066,100 @@ fn clean_up_removes_junk() {
|
||||
assert!(d.node(unpainted).is_none() && d.node(stray).is_none() && d.node(empty).is_none());
|
||||
}
|
||||
|
||||
/// A page-sized square under a ring (a compound path with a square hole), nothing selected.
|
||||
fn art_and_ring(s: &mut Session) -> (NodeId, NodeId) {
|
||||
let art = rect(s, 0.0, 0.0, 100.0, 100.0);
|
||||
let (outer, inner) = (rect(s, 10.0, 10.0, 80.0, 80.0), rect(s, 35.0, 35.0, 30.0, 30.0));
|
||||
s.execute("select.set", &json!({"ids": [inner.0]})).unwrap();
|
||||
s.execute("path.reverse", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let ring = s.doc().unwrap().selection.objects[0];
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
(art, ring)
|
||||
}
|
||||
|
||||
fn one_anchor_path(s: &mut Session) -> NodeId {
|
||||
NodeId(s.execute("path.create", &json!({"anchors": [{"x": 5, "y": 5}]})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn clip_group(s: &mut Session, ids: &[NodeId]) -> NodeId {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn clip_path_of(s: &Session, id: NodeId) -> vectorcraft_doc::Node {
|
||||
let n = node(s, id);
|
||||
assert!(n.clips(), "{id:?} still clips");
|
||||
(*n.children().unwrap()[0]).clone()
|
||||
}
|
||||
|
||||
/// Unpainted Objects leaves a clipping layer's clipping path, which has no paint of its own.
|
||||
#[test]
|
||||
fn clean_up_keeps_a_layers_clipping_path() {
|
||||
let mut s = session();
|
||||
let (art, ring) = art_and_ring(&mut s);
|
||||
let layer = s.doc().unwrap().current_layer().unwrap();
|
||||
assert!(s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap()["clip"].as_bool().unwrap());
|
||||
let r = s.execute("object.path.cleanUp", &json!({})).unwrap();
|
||||
assert_eq!(r["removed"], 0);
|
||||
assert_eq!(clip_path_of(&s, layer).id, ring);
|
||||
assert!(s.doc().unwrap().doc.node(art).is_some());
|
||||
}
|
||||
|
||||
/// Stray Points leaves the one-anchor members of a compound path used as a clipping path.
|
||||
#[test]
|
||||
fn clean_up_keeps_the_members_of_a_compound_clipping_path() {
|
||||
let mut s = session();
|
||||
let (art, ring) = art_and_ring(&mut s);
|
||||
let stray = one_anchor_path(&mut s);
|
||||
let g = clip_group(&mut s, &[art, ring]);
|
||||
s.edit("t", |d, _| {
|
||||
let n = d.remove(stray)?;
|
||||
d.children_mut(Some(ring))?.push(n);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("object.path.cleanUp", &json!({})).unwrap();
|
||||
assert_eq!(r["removed"], 0);
|
||||
let clip = clip_path_of(&s, g);
|
||||
assert_eq!(clip.id, ring);
|
||||
assert!(clip.children().unwrap().iter().any(|c| c.id == stray));
|
||||
}
|
||||
|
||||
/// No option removes a member of a group used as a clipping path, or empty type used as one.
|
||||
#[test]
|
||||
fn clean_up_keeps_a_group_or_type_used_as_a_clipping_path() {
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let top = rect(&mut s, 10.0, 10.0, 50.0, 50.0);
|
||||
let g = clip_group(&mut s, &[art, top]);
|
||||
let unpainted = rect(&mut s, 20.0, 20.0, 10.0, 10.0);
|
||||
let stray = one_anchor_path(&mut s);
|
||||
let empty = NodeId(s.execute("text.create", &json!({"x": 10, "y": 10, "text": ""})).unwrap()["id"].as_u64().unwrap());
|
||||
let inner = s
|
||||
.edit("t", |d, _| {
|
||||
d.node_mut(unpainted).unwrap().appearance = Appearance::basic(Paint::None, Paint::None, 1.0).into();
|
||||
let members = [top, unpainted, stray, empty].map(|id| d.remove(id)).into_iter().collect::<std::result::Result<Vec<_>, _>>()?;
|
||||
let inner = d.alloc_id();
|
||||
d.children_mut(Some(g))?.insert(0, std::sync::Arc::new(vectorcraft_doc::Node::group(inner, members)));
|
||||
Ok(inner)
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("object.path.cleanUp", &json!({})).unwrap();
|
||||
assert_eq!(r["removed"], 0);
|
||||
let clip = clip_path_of(&s, g);
|
||||
assert_eq!(clip.id, inner);
|
||||
assert_eq!(clip.children().unwrap().iter().map(|c| c.id).collect::<Vec<_>>(), [top, unpainted, stray, empty]);
|
||||
// Type of spaces on top of a clip group clips by nothing, and still stays its clipping path.
|
||||
let art = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
|
||||
let blank = NodeId(s.execute("text.create", &json!({"x": 210, "y": 10, "text": " "})).unwrap()["id"].as_u64().unwrap());
|
||||
let g = clip_group(&mut s, &[art, blank]);
|
||||
let r = s.execute("object.path.cleanUp", &json!({})).unwrap();
|
||||
assert_eq!(r["removed"], 0);
|
||||
assert_eq!(clip_path_of(&s, g).id, blank);
|
||||
}
|
||||
|
||||
/// Offset Path, Simplify, Split Into Grid and Clean Up refuse a param of the wrong type with an
|
||||
/// error naming the param, and leave the document, the selection and the undo history as they were.
|
||||
/// Null keeps a param's default, and a distance still takes a string with a unit.
|
||||
|
||||
@@ -181,6 +181,33 @@ fn a_placed_document_is_vectors_in_every_output() {
|
||||
assert!(info.to_string().contains("\"placedDocuments\""), "{info}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_documents_spot_color_stays_a_spot_color_in_a_cmx_file() {
|
||||
let dir = Folder::new("placed-cmx-spot");
|
||||
let src = dir.file("logo.vectorcraft");
|
||||
let mut d = Document::new(100.0, 50.0);
|
||||
let gold = Color::cmyk(0.0, 0.2, 0.8, 0.1);
|
||||
d.swatches.push(vectorcraft_color::Swatch { name: "Gold".into(), paint: Paint::solid(gold), global: true, spot: true });
|
||||
let layer = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let paint = Paint::Solid { color: gold, swatch: Some("Gold".into()), tint: 1.0 };
|
||||
let look = Appearance::basic(paint, Paint::None, 0.0);
|
||||
d.insert(Some(layer), 0, Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), look)).unwrap();
|
||||
write(&src, &vectorcraft_format::save_file(&d));
|
||||
let mut s = session();
|
||||
place(&mut s, &src);
|
||||
assert!(s.doc().unwrap().doc.swatch("Gold").is_none(), "the placing document has no swatch of that name");
|
||||
let bytes = decode(&s.execute("document.serialize", &json!({"format": "cmx"})).unwrap());
|
||||
let drawing = craft_cdr::read_cmx(&bytes, craft_cdr::Limits::default()).unwrap();
|
||||
let mut fills = Vec::new();
|
||||
for o in drawing.pages.iter().flat_map(|p| &p.layers).flat_map(|l| &l.objects) {
|
||||
if let craft_cdr::model::Object::Shape(shape) = o {
|
||||
fills.extend(shape.fill.clone());
|
||||
}
|
||||
}
|
||||
assert!(fills.iter().any(|c| matches!(c, craft_cdr::model::Color::Spot { name, .. } if name == "Gold")), "{fills:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preview_is_saved_so_the_document_shows_it_without_its_file() {
|
||||
let dir = Folder::new("placed-saved");
|
||||
|
||||
@@ -4256,6 +4256,21 @@ fn installs_from_two_processes_into_one_store_keep_each_module_with_its_grant()
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A turn on a plug-in store that ends frees the store while a copy of the lock file's handle is
|
||||
/// open, as a child process that is starting holds one: another process can take a turn.
|
||||
#[test]
|
||||
fn an_ended_store_turn_frees_the_store_while_a_copy_of_its_handle_is_open() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-turn-copied");
|
||||
let s = other_process(folder.0.clone());
|
||||
let turn = s.plugin_store_turn().unwrap();
|
||||
let copy = turn.lock_file().map(|file| file.try_clone().unwrap());
|
||||
assert!(copy.is_some(), "the turn is held");
|
||||
drop(turn);
|
||||
let other = std::fs::File::options().read(true).write(true).open(folder.0.join(crate::store::DISABLED_LOCK)).unwrap();
|
||||
assert!(other.try_lock().is_ok(), "an ended turn frees the store");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
/// Grants written for two plug-ins into one `Plug-ins` folder by two processes are both kept: the
|
||||
/// second write reads `grants.json` only once the first has written it.
|
||||
#[test]
|
||||
|
||||
@@ -641,10 +641,11 @@ fn selection_preferences_drive_the_selection_tool() {
|
||||
assert!(click(&mut s, 225.0, plain).is_empty(), "a click inside the fill selects nothing");
|
||||
assert_eq!(click(&mut s, 250.0, plain), vec![front], "a click on the path selects it");
|
||||
set(&mut s, "objectSelectionByPathOnly", json!(false));
|
||||
// Command Click to Select Objects Behind (on by default): each Cmd/Ctrl-click goes one down,
|
||||
// then back to the top.
|
||||
// Command Click to Select Objects Behind (on by default): the first Cmd/Ctrl-click is Direct
|
||||
// Selection's, then each one goes one down, then back to the top.
|
||||
let cmd = Mods { cmd: true, ..Mods::default() };
|
||||
assert_eq!(click(&mut s, 175.0, plain), vec![front]);
|
||||
assert_eq!(click(&mut s, 175.0, cmd), vec![front], "the first Cmd-click arms Select Behind");
|
||||
assert_eq!(click(&mut s, 175.0, cmd), vec![back], "the object behind");
|
||||
assert_eq!(click(&mut s, 175.0, cmd), vec![front], "back to the topmost");
|
||||
set(&mut s, "ctrlClickSelectsBehind", json!(false));
|
||||
|
||||
@@ -789,6 +789,23 @@ fn an_area_tidied_away_before_it_is_locked_is_busy() {
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A dropped hold frees its area while a copy of the lock file's handle is open, as a child
|
||||
/// process that is starting holds one: the area can be locked again.
|
||||
#[test]
|
||||
fn a_dropped_hold_frees_the_area_while_a_copy_of_its_handle_is_open() {
|
||||
use cmd::recovery::Lock;
|
||||
let base = std::env::temp_dir().join(format!("vc-recovery-copied-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let store = FolderStore::new(&base);
|
||||
let Ok(Lock::Held(hold)) = store.lock("6-1") else { panic!("the area is locked") };
|
||||
let copy = hold.downcast_ref::<crate::store::LockedFile>().map(|locked| locked.file().try_clone().unwrap());
|
||||
assert!(copy.is_some(), "the hold is the locked file");
|
||||
drop(hold);
|
||||
assert!(matches!(store.lock("6-1"), Ok(Lock::Held(_))), "a dropped hold frees the area");
|
||||
drop(copy);
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// Opening an area's lock file failed. When the folder went after it was checked, or the lock file
|
||||
/// is there but can't be opened (a removed lock file that another app still has open, on file
|
||||
/// systems that keep it until it is closed), the area is busy. A lock file that can't be made is an
|
||||
|
||||
@@ -46,7 +46,7 @@ fn app_documents_track_active_tab_and_new_document() {
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.documents; vc.log(d.length); vc.log(app.activeDocument.width);\
|
||||
app.activeDocument = d[0]; vc.log(app.activeDocument.width); vc.log(d[0].parent.typename);\
|
||||
app.activeDocument = d[1]; vc.log(app.activeDocument.width); vc.log(d[0].parent.typename);\
|
||||
vc.log(d[5] === undefined); vc.log(app.activeDocument instanceof Document);\
|
||||
var n = d.add(DocumentColorSpace.CMYK, 50, 60, 2);\
|
||||
vc.log(d.length); vc.log(app.activeDocument.name === n.name); vc.log(n.documentColorSpace); vc.log(n.height);\
|
||||
@@ -297,7 +297,7 @@ fn selection_assignment_is_atomic_across_invalid_items() {
|
||||
assert_eq!(s.active().unwrap().selection.objects, vec![a]);
|
||||
// An item of another document cannot be selected here.
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let e = failure(&mut s, "app.activeDocument.selection = app.documents[0].pageItems[0];");
|
||||
let e = failure(&mut s, "app.activeDocument.selection = app.documents[1].pageItems[0];");
|
||||
assert!(e.contains("Cannot select"), "{e}");
|
||||
}
|
||||
|
||||
@@ -324,13 +324,44 @@ fn a_guide_path_is_not_selected_while_guides_are_locked() {
|
||||
fn an_inactive_document_changes_without_switching_tabs() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
log(&mut s, "var d = app.documents[0]; d.pageItems[1].name = 'far'; d.selection = d.pageItems[0];");
|
||||
log(&mut s, "var d = app.documents[1]; d.pageItems[1].name = 'far'; d.selection = d.pageItems[0];");
|
||||
assert_eq!(s.active_index(), Some(1));
|
||||
let first = &s.documents()[0];
|
||||
assert_eq!(first.doc.node(a).unwrap().name.as_deref(), Some("far"));
|
||||
assert_eq!(first.selection.objects.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documents_list_the_current_document_first_then_the_most_recently_current() {
|
||||
let mut s = Session::new();
|
||||
for _ in 0..3 {
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
rect(&mut s, 0.0, 0.0, 5.0, 5.0);
|
||||
}
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = {}, n = ['A', 'B', 'C'];\
|
||||
for (var i = 0; i < 3; i++) t[app.documents[2 - i].name] = n[i];\
|
||||
function order() { var r = []; for (var i = 0; i < app.documents.length; i++) r.push(t[app.documents[i].name]); return r.join(''); }\
|
||||
var A = app.documents[2], B = app.documents[1], C = app.documents[0];\
|
||||
vc.log(order());\
|
||||
app.activeDocument = A; vc.log(order());\
|
||||
app.activeDocument = B; vc.log(order());\
|
||||
app.activeDocument = app.documents[2]; vc.log(order());\
|
||||
A.pageItems[0].name = 'far'; vc.log(order());\
|
||||
vc.log([app.documents[0] === app.activeDocument, app.documents.getByName(B.name) === B]);",
|
||||
);
|
||||
// A change to a document in the back leaves the order as it was.
|
||||
assert_eq!(out, vec![json!("CBA"), json!("ACB"), json!("BAC"), json!("CBA"), json!("CBA"), json!([true, true])]);
|
||||
// Closing a document in the back keeps the others in their order as the tabs shift.
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
s.execute("document.activate", &json!({"index": 1})).unwrap();
|
||||
s.execute("document.activate", &json!({"index": 2})).unwrap();
|
||||
assert_eq!(s.front_order(), vec![2, 1, 0]);
|
||||
s.close_document(0);
|
||||
assert_eq!(s.front_order(), vec![1, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_duplicate_and_zorder_obey_parent_order() {
|
||||
let (mut s, a, b) = doc();
|
||||
@@ -1178,12 +1209,12 @@ fn add_document_refuses_pixel_preview() {
|
||||
|
||||
#[test]
|
||||
fn document_preset_values_count_toward_the_data_a_run_passes() {
|
||||
// A 64 KiB title, set once, then read or handed to addDocument 32 times: 2 MiB, over a 1 MiB limit.
|
||||
// A 4 KiB title, set once, then read or handed to addDocument 512 times: 2 MiB, over a 1 MiB limit.
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20)));
|
||||
let mut s = Session::new();
|
||||
let set = "var p = new DocumentPreset(); p.title = new Array(65537).join('t');";
|
||||
let read = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) p.title;"));
|
||||
let added = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) try {{ app.documents.addDocument('Print', p, 5); }} catch (e) {{}}"));
|
||||
let set = "var p = new DocumentPreset(); p.title = new Array(4097).join('t');";
|
||||
let read = failure(&mut s, &format!("{set} for (var i = 0; i < 512; i++) p.title;"));
|
||||
let added = failure(&mut s, &format!("{set} for (var i = 0; i < 512; i++) try {{ app.documents.addDocument('Print', p, 5); }} catch (e) {{}}"));
|
||||
let within = run(&mut s, &format!("{set} for (var i = 0; i < 8; i++) p.title;"));
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
for e in [read, added] {
|
||||
@@ -1193,6 +1224,32 @@ fn document_preset_values_count_toward_the_data_a_run_passes() {
|
||||
assert!(s.documents().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_preset_setter_refuses_a_value_of_the_wrong_kind_or_size_and_keeps_the_old_one() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = new DocumentPreset(); p.title = 'Flyer';\
|
||||
var bad = [['title', new Array(4098).join('t')], ['title', 5], ['width', 'wide'], ['width', Infinity], ['height', null],\
|
||||
['colorMode', 'RGB'], ['units', {}], ['artboardLayout', 'DocumentColorSpace.RGB'], ['documentBleedLink', 1],\
|
||||
['documentBleedOffsetRect', [1, 2, 3]], ['documentBleedOffsetRect', [1, 2, 3, 'x']], ['transparencyGrid', 'TransparencyGridRed']];\
|
||||
for (var i = 0; i < bad.length; i++) { try { p[bad[i][0]] = bad[i][1]; vc.log('kept ' + bad[i][0]); } catch (e) { vc.log(e.name); } }\
|
||||
vc.log([p.title, p.width, p.height, p.colorMode === undefined, p.units === undefined, p.artboardLayout,\
|
||||
p.documentBleedLink === undefined, p.documentBleedOffsetRect === undefined, p.transparencyGrid === undefined]);",
|
||||
);
|
||||
let mut names = vec![json!("RangeError")];
|
||||
names.extend(std::iter::repeat_n(json!("TypeError"), 11));
|
||||
assert_eq!(out[..12], names[..], "{out:?}");
|
||||
assert_eq!(out[12], json!(["Flyer", 612, 792, true, true, "DocumentArtboardLayout.GridByRow", true, true, true]));
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = new DocumentPreset(); p.title = new Array(4097).join('t'); p.documentBleedLink = null; p.transparencyGrid = null;\
|
||||
p.documentBleedOffsetRect = [0, 0, 0, 0]; p.width = undefined; vc.log([p.title.length, p.documentBleedLink, p.width === undefined]);\
|
||||
p.documentBleedOffsetRect = undefined; vc.log(app.documents.addDocument('Print', p).typename);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([4096, null, true]), json!("Document")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrappers_go_stale_after_delete_and_undo() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -1516,12 +1573,12 @@ fn prototype_changes_cannot_forge_a_page_item() {
|
||||
let (mut s, a, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var f = Object.create(PathItem.prototype); var m = '';\
|
||||
try { f.name = 'x'; } catch (e) { m = e.message; } vc.log(m);\
|
||||
try { PathItem.prototype.name = 'y'; } catch (e) { m = e.message; } vc.log(m); PageItem = null; Document.prototype.pageItems = null;\
|
||||
"var f = Object.create(PathItem.prototype);\
|
||||
try { f.name = 'x'; vc.log('wrote'); } catch (e) { vc.log(e.message); }\
|
||||
try { PathItem.prototype.name = 'y'; vc.log('wrote'); } catch (e) { vc.log(e.message); } PageItem = null; Document.prototype.pageItems = null;\
|
||||
vc.log(Object.isFrozen(PathItem.prototype) || !Object.isExtensible(PathItem.prototype));\
|
||||
vc.log(app.activeDocument.pageItems.length);\
|
||||
try { new PathItem(); } catch (e) { m = e.name; } vc.log(m);",
|
||||
try { new PathItem(); vc.log('made'); } catch (e) { vc.log(e.name); }",
|
||||
);
|
||||
assert_eq!(out, vec![json!("this is not a page item"), json!("this is not a page item"), json!(true), json!(2), json!("TypeError")]);
|
||||
assert_eq!(s.active().unwrap().doc.node(a).unwrap().name, None);
|
||||
|
||||
@@ -61,7 +61,7 @@ fn scripts_and_subfolders_are_listed_by_name_without_the_extension() {
|
||||
touch(&root, name);
|
||||
}
|
||||
std::fs::create_dir_all(root.join("Empty/Also Empty")).unwrap();
|
||||
let listing = folder::list(&root);
|
||||
let listing = list(&root, Limits::default());
|
||||
assert_eq!(rows(&listing.entries), "A, b, Dessin (été) #1, v1.2 draft, Zeta/[Deep/[x], inner]");
|
||||
assert!(!listing.truncated && !listing.unreadable);
|
||||
// Each script keeps the path the folder gave, whatever its label.
|
||||
@@ -81,7 +81,7 @@ fn a_script_whose_label_another_row_has_shows_its_whole_file_name() {
|
||||
touch(&root, name);
|
||||
}
|
||||
// `tidy.js.js` is labeled `tidy.js` until `tidy.js` takes that label, then shows its whole name.
|
||||
assert_eq!(rows(&folder::list(&root).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx");
|
||||
assert_eq!(rows(&list(&root, Limits::default()).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ fn control_characters_in_a_name_are_written_as_escapes_and_a_long_label_is_cut()
|
||||
touch(&root, "a\u{202E}sj.js");
|
||||
let long = "n".repeat(200);
|
||||
touch(&root, &format!("{long}.jsx"));
|
||||
let listing = folder::list(&root);
|
||||
let listing = list(&root, Limits::default());
|
||||
let labels: Vec<&str> = listing.scripts().into_iter().map(|(_, label, _)| label).collect();
|
||||
assert_eq!(labels[0], "a\\u{202E}sj");
|
||||
assert_eq!(labels[1], format!("{}…", "n".repeat(folder::MAX_LABEL_CHARS - 1)));
|
||||
@@ -119,7 +119,7 @@ fn hidden_names_and_links_are_left_out() {
|
||||
let marked = touch(&root, "marked.js");
|
||||
assert!(std::process::Command::new("attrib").arg("+h").arg(&marked).status().unwrap().success());
|
||||
}
|
||||
let listing = folder::list(&root);
|
||||
let listing = list(&root, Limits::default());
|
||||
assert_eq!(rows(&listing.entries), "shown");
|
||||
assert!(!listing.truncated && !listing.unreadable);
|
||||
// Nor is a file behind a link read as a listed script.
|
||||
@@ -146,12 +146,12 @@ fn a_folder_that_is_missing_is_empty_and_one_that_is_a_file_or_a_link_is_unreada
|
||||
let dir = folder("root");
|
||||
let root = dir.join("Scripts");
|
||||
touch(&root, "a.js");
|
||||
assert_eq!(folder::list(&dir.join("None")), Listing::default());
|
||||
assert_eq!(list(&dir.join("None"), Limits::default()), Listing::default());
|
||||
let file = touch(&dir, "file");
|
||||
assert_eq!(folder::list(&file), Listing { unreadable: true, ..Listing::default() });
|
||||
assert_eq!(list(&file, Limits::default()), Listing { unreadable: true, ..Listing::default() });
|
||||
let link = dir.join("Link");
|
||||
link_folder(&root, &link);
|
||||
assert_eq!(folder::list(&link), Listing { unreadable: true, ..Listing::default() });
|
||||
assert_eq!(list(&link, Limits::default()), Listing { unreadable: true, ..Listing::default() });
|
||||
assert!(folder::read(&link, &link.join("a.js"), 10).is_none());
|
||||
let _ = std::fs::remove_dir_all(&link);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
@@ -187,7 +187,7 @@ fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() {
|
||||
let root = dir.join("Scripts");
|
||||
touch(&root, "1/2/3/4/kept.js");
|
||||
touch(&root, "1/2/3/4/5/deeper.js");
|
||||
let listing = folder::list(&root);
|
||||
let listing = list(&root, Limits::default());
|
||||
assert_eq!(rows(&listing.entries), "1/[2/[3/[4/[kept]]]]");
|
||||
assert!(listing.truncated);
|
||||
assert!(folder::holds(&root, &root.join("1/2/3/4/kept.js")));
|
||||
@@ -199,7 +199,7 @@ fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() {
|
||||
let listing = list(&root, Limits { folders: 1, ..Limits::default() });
|
||||
assert_eq!(rows(&listing.entries), "a/[x]");
|
||||
assert!(listing.truncated);
|
||||
assert!(!folder::list(&root).truncated);
|
||||
assert!(!list(&root, Limits::default()).truncated);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
let _ = std::fs::remove_dir_all(two);
|
||||
}
|
||||
@@ -249,6 +249,7 @@ fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() {
|
||||
touch(&root, "Tidy Layers.jsx");
|
||||
touch(&root, "Export/All Artboards.js");
|
||||
let mut s = Session::new();
|
||||
s.set_script_listing_clock(folder::Clock::Fixed(Duration::ZERO));
|
||||
assert_eq!(
|
||||
s.execute("script.listInstalled", &json!({})).unwrap(),
|
||||
json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false})
|
||||
@@ -276,6 +277,22 @@ fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_installed_stops_when_the_sessions_clock_is_past_the_time_limit() {
|
||||
let dir = folder("command-clock");
|
||||
let root = dir.join("Scripts");
|
||||
touch(&root, "a.jsx");
|
||||
let mut s = Session::new();
|
||||
s.attach_scripts_dir(root);
|
||||
s.set_script_listing_clock(folder::Clock::Fixed(folder::MAX_SCAN + Duration::from_millis(1)));
|
||||
let late = s.execute("script.listInstalled", &json!({})).unwrap();
|
||||
assert_eq!((&late["scripts"], &late["truncated"]), (&json!([]), &json!(true)));
|
||||
s.set_script_listing_clock(folder::Clock::Fixed(folder::MAX_SCAN));
|
||||
let on_time = s.execute("script.listInstalled", &json!({})).unwrap();
|
||||
assert_eq!((on_time["scripts"].as_array().map(Vec::len), &on_time["truncated"]), (Some(1), &json!(false)));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_installed_script_is_read_as_script_run_reads_a_file() {
|
||||
let dir = folder("installed");
|
||||
@@ -374,6 +391,7 @@ fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() {
|
||||
std::fs::create_dir_all(&work).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.attach_scripts_dir(root.clone());
|
||||
s.set_script_listing_clock(folder::Clock::Fixed(Duration::ZERO));
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&work], &[]).unwrap().unwrap();
|
||||
let e = crate::file_access::confine(Some(&roots), || s.execute("script.listInstalled", &json!({}))).unwrap_err();
|
||||
// The Scripts folder is the app's: the error keeps the root and names the folder by its name.
|
||||
|
||||
@@ -746,6 +746,29 @@ fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A grants lock that is dropped frees the grants file while a copy of its handle is open, as a
|
||||
/// child process that is starting holds one: the next change takes the lock without waiting.
|
||||
#[test]
|
||||
fn a_dropped_grants_lock_frees_the_file_while_a_copy_of_its_handle_is_open() {
|
||||
use crate::script::files::{GRANTS_FILE, WHILE_GRANTS_LOCKED, lock_store, revoke_grants};
|
||||
let base = folder("grants-lock-copied");
|
||||
let data = base.join("settings/Script Data");
|
||||
let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false});
|
||||
write(&base.join("settings").join(GRANTS_FILE), json!({"version": 1, "grants": [grant]}).to_string().as_bytes());
|
||||
let lock = lock_store(&base.join("settings").join(GRANTS_FILE)).unwrap();
|
||||
let copy = lock.file().try_clone().unwrap();
|
||||
drop(lock);
|
||||
let waits = std::rc::Rc::new(std::cell::Cell::new(0));
|
||||
let counted = waits.clone();
|
||||
WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1))));
|
||||
let revoked = revoke_grants(&data, None, None);
|
||||
WHILE_GRANTS_LOCKED.set(None);
|
||||
assert_eq!(revoked.map_err(|e| e.kind()), Ok(1), "a dropped lock is free");
|
||||
assert_eq!(waits.get(), 0, "it is taken without waiting");
|
||||
drop(copy);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `rename` of a file an earlier run wrote names both its old and its new path in `written`.
|
||||
#[test]
|
||||
fn a_renamed_file_names_its_old_and_new_paths_in_written() {
|
||||
|
||||
@@ -27,6 +27,8 @@ pub(crate) struct HoverKey {
|
||||
use_preview_bounds: bool,
|
||||
type_glyph_bounds: bool,
|
||||
show_handles_multiple_anchors: bool,
|
||||
/// [`Session::behind_armed`].
|
||||
behind_armed: bool,
|
||||
}
|
||||
|
||||
/// The tool whose radius is General › Corner Radius.
|
||||
@@ -203,8 +205,10 @@ impl Session {
|
||||
return Ok(());
|
||||
}
|
||||
// A double-click or triple-click after the switch is the new tool's, also when the switch
|
||||
// comes back to the tool a Cmd press was lent from.
|
||||
// comes back to the tool a Cmd press was lent from. Select Behind is armed again by the
|
||||
// next Cmd press.
|
||||
self.press_lent = None;
|
||||
self.behind_armed = None;
|
||||
// Sampling type keeps its highlighted characters as the target, and a whole story that
|
||||
// Select All selected. Capture before the Type tool deactivates (which commits typing and
|
||||
// clears its editing state).
|
||||
@@ -366,6 +370,22 @@ impl Session {
|
||||
use_preview_bounds: p.use_preview_bounds,
|
||||
type_glyph_bounds: p.type_glyph_bounds,
|
||||
show_handles_multiple_anchors: p.show_handles_multiple_anchors,
|
||||
behind_armed: self.behind_armed(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Has a Cmd press with the Selection tool in the active document armed Select Behind, with
|
||||
/// Cmd held since? Then a Cmd-click over the selection selects the object behind it (Selection
|
||||
/// & Anchor Display › Command Click to Select Objects Behind); the first Cmd press is lent to
|
||||
/// Direct Selection or Group Selection.
|
||||
pub fn behind_armed(&self) -> bool {
|
||||
self.behind_armed.is_some_and(|doc| doc == self.active().map(|d| d.uid))
|
||||
}
|
||||
|
||||
/// Cmd let go ends Select Behind's arming ([`Self::behind_armed`]).
|
||||
fn note_cmd_held(&mut self, mods: &Mods) {
|
||||
if !mods.cmd {
|
||||
self.behind_armed = None;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -374,6 +394,7 @@ impl Session {
|
||||
/// ([`Self::lent_tool_at`]; off the canvas, the one [`Self::lent_tool_id`] names), else the
|
||||
/// active tool. [`Self::hover_tool_id`] then answers the same until the pointer or the keys move.
|
||||
pub fn hover_tool_at(&mut self, p: Option<Point>, mods: &Mods, view: ViewInfo) -> &'static str {
|
||||
self.note_cmd_held(mods);
|
||||
let lends = mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held;
|
||||
let lent = match p {
|
||||
_ if !lends => None,
|
||||
@@ -387,7 +408,8 @@ impl Session {
|
||||
|
||||
/// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when
|
||||
/// the Selection tool keeps a Cmd press on a selected object to select the object behind it
|
||||
/// (Selection & Anchor Display › Command Click to Select Objects Behind).
|
||||
/// (Selection & Anchor Display › Command Click to Select Objects Behind), which an earlier Cmd
|
||||
/// press armed ([`Self::behind_armed`]).
|
||||
fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> {
|
||||
let id = self.lent_tool(self.tool.id(), mods)?;
|
||||
let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p));
|
||||
@@ -629,6 +651,7 @@ impl Session {
|
||||
double_click_isolate: self.prefs.double_click_to_isolate,
|
||||
double_click_adds_anchor: self.prefs.double_click_adds_anchor_points,
|
||||
select_behind: self.prefs.ctrl_click_selects_behind,
|
||||
behind_armed: self.behind_armed(),
|
||||
highlight_anchors: self.prefs.highlight_anchors_on_hover,
|
||||
snap_tolerance: self.prefs.snap_to_point_tolerance,
|
||||
handles_multiple: self.prefs.show_handles_multiple_anchors,
|
||||
@@ -921,7 +944,13 @@ impl Session {
|
||||
}
|
||||
self.leave_draw_inside(ev, view)?;
|
||||
self.tell_tool_history_moved();
|
||||
self.note_cmd_held(&ev.mods);
|
||||
// A Cmd press with the Selection tool, lent or not, arms Select Behind for the next one.
|
||||
let arms = ev.kind == PointerKind::Down && ev.mods.cmd && self.lender.is_none() && self.tool.id() == "selection";
|
||||
let (ev, settled) = self.lend_selection_tool(ev, view)?;
|
||||
if arms {
|
||||
self.behind_armed = Some(self.active().map(|d| d.uid));
|
||||
}
|
||||
let ev = &ev;
|
||||
let lent = self.lender.is_some();
|
||||
let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev));
|
||||
@@ -1220,6 +1249,7 @@ impl Session {
|
||||
}
|
||||
|
||||
fn tool_key_now(&mut self, key: ToolKey, mods: Mods, view: ViewInfo) -> Result<Vec<UiRequest>> {
|
||||
self.note_cmd_held(&mods);
|
||||
// 1–4 pick the active perspective plane while the grid is shown.
|
||||
if let Some(plane) = self.plane_key(key) {
|
||||
self.execute("perspective.plane.set", &serde_json::json!({ "plane": plane.id() }))?;
|
||||
@@ -1460,6 +1490,7 @@ impl Session {
|
||||
/// The pointer the active tool shows at `p`. With Cmd held, the pointer of the selection tool a
|
||||
/// press would borrow ([`Self::lend_selection_tool`]).
|
||||
pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor {
|
||||
self.note_cmd_held(&mods);
|
||||
// While an edit is computed, a Cmd press is held for the active tool, which shows it is busy.
|
||||
// Cmd pressed once a drag is under way lends nothing, so the tool keeps its pointer.
|
||||
let lends = mods.cmd && self.lender.is_none() && !self.tool_editing() && !self.pointer_held;
|
||||
@@ -1947,14 +1978,14 @@ impl Session {
|
||||
}
|
||||
|
||||
fn measure_deferred_preview(&mut self, cmd: &str, p: &Value) -> Option<DeferredFeedback> {
|
||||
let (snapshot, selection, revision, paint, interaction_fields) = {
|
||||
let (snapshot, selection, isolation, revision, paint, interaction_fields) = {
|
||||
let st = self.active()?;
|
||||
let it = st.interaction.as_ref()?;
|
||||
if !std::sync::Arc::ptr_eq(&it.doc, &st.doc) {
|
||||
return None;
|
||||
}
|
||||
let interaction_fields = (it.preview.clone(), it.copies.clone(), it.perspective_again.clone(), it.plane_placed);
|
||||
(st.doc.clone(), st.selection.clone(), st.revision, self.pending_paint.clone(), interaction_fields)
|
||||
(st.doc.clone(), st.selection.clone(), st.isolation, st.revision, self.pending_paint.clone(), interaction_fields)
|
||||
};
|
||||
let (overlays, transform_box) = if self.preview(cmd, p).is_ok() {
|
||||
let overlays = self.active().map(|st| outlines_for_selection(&st.doc, &st.selection, cmd, p)).unwrap_or_default();
|
||||
@@ -1970,6 +2001,8 @@ impl Session {
|
||||
if let Ok(st) = self.doc_mut() {
|
||||
st.doc = snapshot;
|
||||
st.selection = selection;
|
||||
// A measured preview that removed the isolated object leaves isolation mode as it was.
|
||||
st.isolation = isolation;
|
||||
st.revision = revision;
|
||||
if let Some(it) = &mut st.interaction {
|
||||
it.preview = interaction_fields.0;
|
||||
|
||||
@@ -26,6 +26,7 @@ mod lossy_overwrite;
|
||||
mod model_based;
|
||||
mod param_keys;
|
||||
mod paste_many;
|
||||
mod pasted_clipping_path;
|
||||
mod pen_click_after_smooth;
|
||||
mod pen_endpoint_picking;
|
||||
mod pen_rubber_band;
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
//! A copy of a clip group's clipping path pasted outside it is an ordinary path (#9227).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
fn run(s: &mut Session, command: &str, params: Value) -> Value {
|
||||
s.execute(command, ¶ms).unwrap()
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
NodeId(run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn clipping(s: &Session, id: NodeId) -> bool {
|
||||
matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Path { clipping: true, .. })
|
||||
}
|
||||
|
||||
/// A rectangle clipped by a smaller one, and the clipping path's id.
|
||||
fn clip_group(s: &mut Session) -> NodeId {
|
||||
run(s, "file.new", json!({"width": 400, "height": 400}));
|
||||
let art = rect(s, 20.0, 20.0, 200.0, 200.0);
|
||||
let mask = rect(s, 60.0, 60.0, 100.0, 100.0);
|
||||
run(s, "select.set", json!({"ids": [art.0, mask.0]}));
|
||||
run(s, "object.clippingMask.make", json!({}));
|
||||
assert!(clipping(s, mask));
|
||||
mask
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_path_offsets_a_pasted_copy_of_a_clipping_path() {
|
||||
let mut s = Session::new();
|
||||
let mask = clip_group(&mut s);
|
||||
run(&mut s, "select.set", json!({"ids": [mask.0]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let pasted = run(&mut s, "edit.pasteInPlace", json!({}));
|
||||
let copy = NodeId(pasted["ids"][0].as_u64().unwrap());
|
||||
assert!(!clipping(&s, copy), "the pasted copy clips nothing, so it is not a clipping path");
|
||||
assert!(clipping(&s, mask), "the original still clips its group");
|
||||
|
||||
run(&mut s, "select.set", json!({"ids": [copy.0]}));
|
||||
let out = s.execute("object.path.offsetPath", &json!({"offset": 5}));
|
||||
assert!(out.is_ok(), "Offset Path refuses the pasted copy: {out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_makes_a_lone_clipping_path_an_ordinary_path() {
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 400, "height": 400}));
|
||||
let lone = rect(&mut s, 60.0, 60.0, 100.0, 100.0);
|
||||
// As a paste made one before #9227, in a document saved then: flagged, outside any clip group.
|
||||
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
if let NodeKind::Path { clipping, .. } = &mut d.node_mut(lone).unwrap().kind {
|
||||
*clipping = true;
|
||||
}
|
||||
run(&mut s, "select.set", json!({"ids": [lone.0]}));
|
||||
assert!(s.execute("object.path.offsetPath", &json!({"offset": 5})).is_err(), "the flagged path is skipped");
|
||||
|
||||
run(&mut s, "object.clippingMask.release", json!({}));
|
||||
assert!(!clipping(&s, lone));
|
||||
let out = s.execute("object.path.offsetPath", &json!({"offset": 5}));
|
||||
assert!(out.is_ok(), "Offset Path refuses the released path: {out:?}");
|
||||
}
|
||||
@@ -8,7 +8,6 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::cmd::fileio;
|
||||
@@ -268,24 +267,31 @@ fn declines_and_bad_output_write_nothing_and_warnings_come_back() {
|
||||
}
|
||||
|
||||
/// Background Export's Cancel stops an exporter between two slices of its budget: here one that
|
||||
/// never returns, cancelled from another thread once it is running.
|
||||
/// never returns after it reports its first step, cancelled when that report arrives, so the cancel
|
||||
/// lands while it is running.
|
||||
#[test]
|
||||
fn a_cancelled_export_stops_the_exporter() {
|
||||
let mut s = session();
|
||||
install(&mut s, &tpl::module(&tpl::exporter("test.spins", r#"["tss"]"#, "{}"), "(loop $l (br $l)) (i64.const 0)", "", 1));
|
||||
let manifest = r#"{"id":"test.spins","name":"Test test.spins","version":"1","kind":"exporter","api":2,"extensions":["tss"],"params":{},"permissions":["doc.read","export.write","progress"]}"#;
|
||||
let spins = "(call $vc_progress (i64.const 1) (i64.const 7)) (loop $l (br $l))";
|
||||
let wasm = wat::parse_str(tpl::reporting(manifest, spins, r#"{"dataBase64":""}"#)).unwrap();
|
||||
let grant = json!(["doc.read", "export.write", "progress"]);
|
||||
s.allow_plugin_grants_from_requests();
|
||||
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant})).unwrap();
|
||||
let token = vectorcraft_doc::cancel::CancelToken::new();
|
||||
let cancel = token.clone();
|
||||
let wait = Duration::from_millis(300);
|
||||
let canceller = std::thread::spawn(move || {
|
||||
std::thread::sleep(wait);
|
||||
cancel.cancel();
|
||||
});
|
||||
let t = Instant::now();
|
||||
let r = vectorcraft_doc::cancel::scope(&token, None, || s.execute("document.export", &json!({"format": "plugin.test.spins"})));
|
||||
let took = t.elapsed();
|
||||
canceller.join().unwrap();
|
||||
let reports = std::rc::Rc::new(std::cell::Cell::new(0));
|
||||
let sink: vectorcraft_doc::cancel::ProgressSink = {
|
||||
let (token, reports) = (token.clone(), reports.clone());
|
||||
std::rc::Rc::new(move |done, total, _| {
|
||||
if (done, total) == (1, 7) {
|
||||
reports.set(reports.get() + 1);
|
||||
token.cancel();
|
||||
}
|
||||
})
|
||||
};
|
||||
let r = vectorcraft_doc::cancel::scope(&token, Some(sink), || s.execute("document.export", &json!({"format": "plugin.test.spins"})));
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
|
||||
assert!(took >= wait && took < Duration::from_secs(10), "stopped while running, not before: {took:?}");
|
||||
assert_eq!(reports.get(), 1, "cancelled once the exporter was running, not before");
|
||||
}
|
||||
|
||||
/// Every string in `v`, at any depth.
|
||||
|
||||
@@ -9,9 +9,11 @@
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_engine::script::folder::{self, Clock};
|
||||
use vectorcraft_plugins::safe_mode;
|
||||
use vectorcraft_testkit::TempDir;
|
||||
|
||||
@@ -56,9 +58,11 @@ fn write(dir: &Path, name: &str, text: &str) -> PathBuf {
|
||||
path
|
||||
}
|
||||
|
||||
/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on.
|
||||
/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on, whose listings take
|
||||
/// no time.
|
||||
fn session(dir: &Path) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.set_script_listing_clock(Clock::Fixed(Duration::ZERO));
|
||||
s.attach_startup_scripts_dir(dir.to_path_buf());
|
||||
s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap();
|
||||
s
|
||||
@@ -115,6 +119,20 @@ fn the_folders_jsx_files_run_in_name_order_at_launch_and_before_a_chosen_script(
|
||||
assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX", "a.jsx", "b.jsx", "C.JSX", "chosen"], "the startup scripts run first");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_listing_stops_when_the_sessions_clock_is_past_the_time_limit() {
|
||||
let _f = fresh();
|
||||
let dir = tmp_dir("clock");
|
||||
write(&dir, "a.jsx", "vc.log(1);");
|
||||
let mut s = session(&dir);
|
||||
s.set_script_listing_clock(Clock::Fixed(folder::MAX_SCAN + Duration::from_millis(1)));
|
||||
let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap();
|
||||
assert_eq!((names(&r["ran"]), &r["truncated"]), (vec![], &json!(true)));
|
||||
s.set_script_listing_clock(Clock::Fixed(folder::MAX_SCAN));
|
||||
let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap();
|
||||
assert_eq!((names(&r["ran"]), &r["truncated"]), (vec!["a.jsx"], &json!(false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_folder_runs_nothing_and_a_session_without_one_skips() {
|
||||
let _f = fresh();
|
||||
|
||||
@@ -306,7 +306,8 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep
|
||||
// Artboards that don't fit on the canvas are written on a large canvas, at 1/scale.
|
||||
let scale = canvas_scale(doc);
|
||||
// The objects that may keep their effects in an art style, as they are before baking (not on
|
||||
// a large canvas, whose scale the styles' strokes and effects would need).
|
||||
// a large canvas, whose scale the styles' strokes and effects would need; there only the styles
|
||||
// that link type's colors to their swatches are written, which hold no lengths).
|
||||
let styled = writer::styled_objects(doc);
|
||||
let (symbol_styled, pattern_styled) = writer::styled_definitions(doc);
|
||||
let own_styles = doc.graphic_styles != Document::new(1.0, 1.0).graphic_styles;
|
||||
|
||||
@@ -5088,6 +5088,89 @@ fn kinsoku_settings_come_back_on_each_paragraph() {
|
||||
assert_eq!(export_ai_editing(&lossy, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]);
|
||||
}
|
||||
|
||||
/// Type in spot inks (CMYK, RGB and Lab) and a global process color, as its fill and as its
|
||||
/// stroke, at full strength and at a tint: each color reads back linked to its swatch at its tint, with no warning, as key 5
|
||||
/// of the run's paint names an art style of one paint that holds the link. A link to a process
|
||||
/// swatch that isn't global still warns: the editing data can't hold it.
|
||||
#[test]
|
||||
fn type_in_spot_and_global_colors_reads_back_linked_at_its_tint() {
|
||||
use vectorcraft_doc::{CharStyle, TextObject, TextRun};
|
||||
use vectorcraft_geom::Point;
|
||||
let white = Color::cmyk(0.0, 0.0, 0.0, 0.0);
|
||||
let red = Color::cmyk(0.0, 1.0, 1.0, 0.0);
|
||||
let mut doc = Document::new(300.0, 200.0);
|
||||
doc.swatches = vec![
|
||||
Swatch { name: "[None]".into(), paint: Paint::None, global: false, spot: false },
|
||||
Swatch { name: "White Ink".into(), paint: solid(white), global: true, spot: true },
|
||||
Swatch { name: "Red Ink".into(), paint: solid(red), global: true, spot: true },
|
||||
Swatch { name: "Sky".into(), paint: solid(SKY), global: true, spot: true },
|
||||
Swatch { name: "Mint".into(), paint: solid(MINT), global: true, spot: true },
|
||||
Swatch { name: "Brand".into(), paint: solid(BRAND), global: true, spot: false },
|
||||
Swatch { name: "Ink".into(), paint: solid(GOLD), global: false, spot: false },
|
||||
]
|
||||
.into();
|
||||
doc.swatch_groups = vec![].into();
|
||||
let layer = doc.layers[0].id;
|
||||
let stroked = |fill: Paint, stroke: Paint| CharStyle { size: 24.0, fill, stroke, stroke_width: 1.0, ..CharStyle::default() };
|
||||
let mut t = TextObject::point(Point::new(20.0, 60.0), "", style(24.0, Color::BLACK));
|
||||
t.runs = vec![
|
||||
TextRun::new("WHITE ", stroked(linked("White Ink", white, 1.0), Paint::None)),
|
||||
TextRun::new("RED ", stroked(linked("Red Ink", red, 0.4), linked("Brand", BRAND, 0.6))),
|
||||
TextRun::new("SKY ", stroked(linked("Sky", SKY, 0.75), linked("Red Ink", red, 1.0))),
|
||||
TextRun::new("MINT ", stroked(linked("Mint", MINT, 0.3), Paint::None)),
|
||||
TextRun::new("BRAND", stroked(linked("Brand", BRAND, 1.0), linked("White Ink", white, 0.5))),
|
||||
];
|
||||
let n = text_node(&mut doc, t);
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
|
||||
let runs = |d: &Document| {
|
||||
let mut all = vec![];
|
||||
paths(&d.layers, &mut all);
|
||||
all.iter()
|
||||
.filter_map(|n| match &n.kind {
|
||||
NodeKind::Text(t) => Some(t.runs.iter().map(|r| (r.text.clone(), paint(&r.style.fill), paint(&r.style.stroke))).collect::<Vec<_>>()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(runs(&read_back(&doc)), runs(&doc));
|
||||
let mut process = doc.clone();
|
||||
let id = process.layers[0].children().unwrap()[0].id;
|
||||
if let Some(NodeKind::Text(t)) = process.node_mut(id).map(|n| &mut n.kind) {
|
||||
t.runs[0].style.fill = linked("Ink", GOLD, 1.0);
|
||||
}
|
||||
assert_eq!(export_ai_editing(&process, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]);
|
||||
}
|
||||
|
||||
/// Type whose story isn't written (a thread the text document can't hold, written as outlines)
|
||||
/// leaves no art style for its colors behind.
|
||||
#[test]
|
||||
fn type_written_as_outlines_leaves_no_style_for_its_colors() {
|
||||
use vectorcraft_doc::{CharStyle, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::Point;
|
||||
let red = Color::cmyk(0.0, 1.0, 1.0, 0.0);
|
||||
let mut doc = Document::new(300.0, 200.0);
|
||||
let mut swatches: Vec<Swatch> = doc.swatches.iter().cloned().collect();
|
||||
swatches.push(Swatch { name: "Red Ink".into(), paint: solid(red), global: true, spot: true });
|
||||
doc.swatches = swatches.into();
|
||||
let inked = CharStyle { size: 12.0, fill: linked("Red Ink", red, 1.0), ..CharStyle::default() };
|
||||
let mut first = TextObject::point(Point::ZERO, "A story in a spot ink that runs on.", inked.clone());
|
||||
first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(20.0, 20.0, 120.0, 60.0)) };
|
||||
first.xf = Affine::IDENTITY;
|
||||
// Point type can't be a frame of a thread: the text document doesn't hold the thread.
|
||||
let mut second = TextObject::point(Point::new(20.0, 120.0), "", inked.clone());
|
||||
second.runs = vec![TextRun::new("", inked)];
|
||||
let (first, second) = (text_node(&mut doc, first), text_node(&mut doc, second));
|
||||
doc.text_threads.push(vec![first.id, second.id]);
|
||||
let layer = doc.layers[0].id;
|
||||
doc.insert(Some(layer), usize::MAX, first).unwrap();
|
||||
doc.insert(Some(layer), usize::MAX, second).unwrap();
|
||||
let text = program(&doc);
|
||||
assert!(!text.contains("%AI11_BeginTextDocument"), "the thread was written as type");
|
||||
assert!(!text.contains("/SimpleStyle"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_is_written_again_as_the_same_bytes() {
|
||||
let doc = typed();
|
||||
@@ -8122,11 +8205,12 @@ fn a_masks_art_with_an_effect_no_style_holds_is_written_as_it_draws() {
|
||||
assert!(apart <= 4, "{apart} pixels differ");
|
||||
}
|
||||
|
||||
/// On a large canvas no art style is written (the reader scales the styles of a large canvas):
|
||||
/// objects with effects are written as their vector art with their geometry effects applied, with a
|
||||
/// warning.
|
||||
/// On a large canvas no art style of an object is written (the reader scales the styles of a large
|
||||
/// canvas): objects with effects are written as their vector art with their geometry effects
|
||||
/// applied, with a warning. Type's colors keep their swatch links there: their styles hold no
|
||||
/// lengths.
|
||||
#[test]
|
||||
fn a_large_canvas_writes_no_art_styles() {
|
||||
fn a_large_canvas_writes_only_the_art_styles_of_type_colors() {
|
||||
let mut doc = Document::new(20000.0, 100.0);
|
||||
let n = styled_rect(
|
||||
&mut doc,
|
||||
@@ -8141,6 +8225,33 @@ fn a_large_canvas_writes_no_art_styles() {
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w == writer::LARGE_CANVAS_STYLES), "{:?}", out.warnings);
|
||||
assert!(!String::from_utf8(out.program).unwrap().contains("ArtStyle"));
|
||||
|
||||
let mut typed = Document::new(20000.0, 100.0);
|
||||
let red = Color::cmyk(0.0, 1.0, 1.0, 0.0);
|
||||
let mut swatches: Vec<Swatch> = typed.swatches.iter().cloned().collect();
|
||||
swatches.push(Swatch { name: "Red Ink".into(), paint: solid(red), global: true, spot: true });
|
||||
typed.swatches = swatches.into();
|
||||
let fill = linked("Red Ink", red, 0.4);
|
||||
let t = vectorcraft_doc::TextObject::point(
|
||||
vectorcraft_geom::Point::new(20.0, 60.0),
|
||||
"FAR",
|
||||
vectorcraft_doc::CharStyle { size: 24.0, fill: fill.clone(), ..vectorcraft_doc::CharStyle::default() },
|
||||
);
|
||||
let n = text_node(&mut typed, t);
|
||||
let layer = typed.layers[0].id;
|
||||
typed.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let out = export_ai_editing(&typed, &opts()).unwrap();
|
||||
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
|
||||
let mut all = vec![];
|
||||
paths(&read_back(&typed).layers, &mut all);
|
||||
let fills: Vec<String> = all
|
||||
.iter()
|
||||
.filter_map(|n| match &n.kind {
|
||||
NodeKind::Text(t) => Some(paint(&t.runs[0].style.fill)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(fills, [paint(&fill)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1623,6 +1623,18 @@ impl<'a> Writer<'a> {
|
||||
if !self.take_objects(stub) {
|
||||
return;
|
||||
}
|
||||
// The art styles that hold the swatch links of its colors, its thread's too.
|
||||
let members: Vec<&vectorcraft_doc::TextObject> = match thread {
|
||||
Some(thread) => thread
|
||||
.iter()
|
||||
.filter_map(|id| match &doc.node(*id)?.kind {
|
||||
NodeKind::Text(t) => Some(t.as_ref()),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
None => vec![t],
|
||||
};
|
||||
self.link_type_colors(&members);
|
||||
let placed = if let Some(thread) = thread {
|
||||
// A thread is checked for what it loses, in every frame, when its story is written.
|
||||
let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id), &self.wraps_held);
|
||||
|
||||
@@ -20,7 +20,7 @@ use super::{Writer, Xy, blend_code, compound_path, hide};
|
||||
use crate::ai_ops;
|
||||
use crate::ps;
|
||||
|
||||
pub(in crate::ai_editing) const LARGE_CANVAS_STYLES: &str = "on a large canvas, no art styles or graphic styles are written: objects with live effects are written with their geometry effects applied to the artwork, where they can no longer be edited, and their other effects are left out of the editing data for other apps";
|
||||
pub(in crate::ai_editing) const LARGE_CANVAS_STYLES: &str = "on a large canvas, no graphic styles and no art styles of objects are written: objects with live effects are written with their geometry effects applied to the artwork, where they can no longer be edited, and their other effects are left out of the editing data for other apps";
|
||||
pub(in crate::ai_editing) const PANEL_STYLES: &str = "graphic styles with gradient or pattern fills, with fills, strokes or effects the editing data can't hold as a graphic style, with a name another style has, with names over 1,024 bytes, or past 4,096 styles, are left out of the editing data for other apps";
|
||||
pub(in crate::ai_editing) const PANEL_EMPTY: &str =
|
||||
"a Graphic Styles panel with no style written opens from the editing data with a new document's styles";
|
||||
@@ -173,6 +173,9 @@ pub(in crate::ai_editing) struct Styles {
|
||||
next_anon: u64,
|
||||
/// How many objects were written with the graphic style they are linked to.
|
||||
pub(super) links_written: usize,
|
||||
/// The styles that only link type's colors to their swatches ([`Writer::type_color_style`]):
|
||||
/// written only when the text document names them.
|
||||
type_colors: HashSet<String>,
|
||||
/// The style texts checked so far, as the reader parses them.
|
||||
pub(super) parsed: Parsed,
|
||||
}
|
||||
@@ -335,6 +338,33 @@ impl Writer<'_> {
|
||||
std::mem::replace(&mut self.body, saved)
|
||||
}
|
||||
|
||||
/// Look at the swatch links of the colors of type `texts` ([`super::texts::TextDoc::set_link`]):
|
||||
/// each is held by an art style of one paint, its color with its swatch at its tint, which key 5
|
||||
/// of a run's paint names ([`Self::type_color_style`]), or by none.
|
||||
pub(super) fn link_type_colors(&mut self, texts: &[&vectorcraft_doc::TextObject]) {
|
||||
for p in self.texts.unlooked_links(texts) {
|
||||
let style = self.type_color_style(p);
|
||||
self.texts.set_link(p, style);
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of the art style that holds the swatch link of type colored `p`: a style of one
|
||||
/// paint, its fill alone on (`0 1 Xd`), whose paint is `p` as a path's fill writes it (a spot or
|
||||
/// global process color by its name and tint, Registration). The reader gives type whose paint
|
||||
/// names that style the style's color at its tint, linked to its swatch
|
||||
/// ([`crate::import::parsed_type_color`]); `None`, and no style, when it wouldn't give the same
|
||||
/// swatch and tint (a swatch that is neither spot nor global, for one).
|
||||
fn type_color_style(&mut self, p: &Paint) -> Option<String> {
|
||||
let Paint::Solid { swatch: Some(name), tint, .. } = p else { return None };
|
||||
let ops = self.color_ops(p, false);
|
||||
let text = format!("/SimpleStyle :\n0 O\n{ops}0 1 0 0 0 Xy\n{NO_LINE}0 XR\n0 1 Xd\n/Paint ;\n /Def ;\n");
|
||||
let back = self.styles.parsed.get(&text).and_then(crate::import::parsed_type_color);
|
||||
let same = matches!(back, Some(Paint::Solid { swatch: Some(n), tint: t, .. }) if n == name && (t - tint).abs() <= 1e-4);
|
||||
let name = same.then(|| self.styles.object_style(text))?;
|
||||
self.styles.type_colors.insert(name.clone());
|
||||
Some(name)
|
||||
}
|
||||
|
||||
/// A fill style holding a color, as an effect's entry `key` or a fill's own.
|
||||
fn fill_style(&mut self, s: &mut String, color: vectorcraft_color::Color, key: &str) {
|
||||
let ops = self.color_ops(&Paint::solid(color), false);
|
||||
@@ -929,12 +959,17 @@ impl Writer<'_> {
|
||||
|
||||
/// The art styles written, in a non-printing block: `%AI9_BeginArtStyles`, each style,
|
||||
/// `%AI9_EndArtStyles`.
|
||||
/// A style that only links type's colors is written when the text document names it: type
|
||||
/// whose story isn't written (written as its outlines instead) leaves none behind.
|
||||
pub(in crate::ai_editing) fn art_styles(&self, s: &mut String) {
|
||||
if self.styles.known.is_empty() {
|
||||
let named = self.texts.named_styles();
|
||||
let written: Vec<&(String, String)> =
|
||||
self.styles.known.iter().filter(|(name, _)| !self.styles.type_colors.contains(name) || named.contains(name.as_str())).collect();
|
||||
if written.is_empty() {
|
||||
return;
|
||||
}
|
||||
s.push_str("%AI5_Begin_NonPrinting\nNp\n%AI9_BeginArtStyles\n");
|
||||
for (name, text) in &self.styles.known {
|
||||
for (name, text) in written {
|
||||
s.push_str(&known_style(name, text));
|
||||
}
|
||||
s.push_str("%AI9_EndArtStyles\n%AI5_End_NonPrinting--\n");
|
||||
|
||||
@@ -31,7 +31,7 @@ use vectorcraft_geom::{Affine, PathData, Point};
|
||||
use crate::{ai_ops, ps};
|
||||
|
||||
/// What the text document holds of type, and what it leaves out.
|
||||
pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps";
|
||||
pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (for example underline, kerning, OpenType features, swatch links of its colors other than to spot colors, global process colors and Registration, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps";
|
||||
|
||||
/// The version of the text document's form (`/98 << /0 n >>`), as the newest files users sent have it.
|
||||
const STREAM_VERSION: u32 = 14;
|
||||
@@ -177,15 +177,32 @@ fn set(resources: Vec<V>, display: bool) -> V {
|
||||
|
||||
/// A paint: kind 0 gray (`[alpha, lightness]`), 1 RGB, 2 CMYK, as the reader's `paint` reads them.
|
||||
/// RGB values are an RGB color's own (in the working RGB space) and a Lab color's converted into
|
||||
/// the working RGB space ([`ai_ops::rgb_values`]).
|
||||
fn paint(c: &Color) -> V {
|
||||
/// the working RGB space ([`ai_ops::rgb_values`]). With `style`, the art style that links the color
|
||||
/// to its swatch (key 5, [`TextDoc::link`]): the reader takes the style's color, at its tint, in
|
||||
/// place of these values.
|
||||
fn paint(c: &Color, style: Option<&str>) -> V {
|
||||
let (kind, values) = match *c {
|
||||
Color::Gray { k } => (0, vec![1.0 - f64::from(k.clamp(0.0, 1.0))]),
|
||||
Color::Cmyk { c, m, y, k } => (2, [c, m, y, k].iter().map(|v| f64::from(v.clamp(0.0, 1.0))).collect()),
|
||||
Color::Rgb { .. } | Color::Lab { .. } => (1, ai_ops::rgb_values(*c).iter().map(|v| f64::from(*v)).collect()),
|
||||
};
|
||||
let values: Vec<f64> = std::iter::once(1.0).chain(values).collect();
|
||||
dict(vec![(99, V::Name("SimplePaint")), (0, dict(vec![(0, V::Int(kind)), (1, reals(&values))]))])
|
||||
let color = dict(vec![(0, V::Int(kind)), (1, reals(&values))]);
|
||||
match style {
|
||||
Some(name) => dict(vec![(99, V::Name("CAITextPaint")), (5, V::Str(name.to_owned())), (0, color)]),
|
||||
None => dict(vec![(99, V::Name("SimplePaint")), (0, color)]),
|
||||
}
|
||||
}
|
||||
|
||||
/// A color linked to a swatch, by the swatch's name and its tint ([`TextDoc::links`]).
|
||||
pub(in crate::ai_editing) type LinkKey = (String, u32);
|
||||
|
||||
/// The swatch and tint paint `p` is linked to, if it is.
|
||||
pub(in crate::ai_editing) fn link_key(p: &Paint) -> Option<LinkKey> {
|
||||
match p {
|
||||
Paint::Solid { swatch: Some(name), tint, .. } => Some((name.clone(), tint.to_bits())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The color of paint `p` when the text document can hold it (a solid color or none).
|
||||
@@ -447,14 +464,16 @@ fn held_aki(v: f64) -> f64 {
|
||||
|
||||
/// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? `fonts` holds the
|
||||
/// fonts already resolved.
|
||||
fn loses(t: &TextObject, fonts: &mut ResolvedFonts) -> bool {
|
||||
fn loses(t: &TextObject, fonts: &mut ResolvedFonts, links: &HashMap<LinkKey, Option<String>>) -> bool {
|
||||
// Small capitals are read back at Document Setup's default size.
|
||||
let default_small_caps = vectorcraft_doc::DocSetup::default().small_caps_size;
|
||||
// Is paint `p` held with its swatch link, by an art style ([`TextDoc::link`])?
|
||||
let linked = |p: &Paint| link_key(p).is_some_and(|k| matches!(links.get(&k), Some(Some(_))));
|
||||
// A run's style as the text document holds it: every other attribute at its default. A color
|
||||
// is held without its swatch link.
|
||||
// is held without its swatch link, unless an art style holds the link.
|
||||
let held_char = |s: &CharStyle| {
|
||||
let unlinked = |p: &Paint| match p {
|
||||
Paint::Solid { color, .. } => Paint::solid(*color),
|
||||
Paint::Solid { color, .. } if !linked(p) => Paint::solid(*color),
|
||||
other => other.clone(),
|
||||
};
|
||||
let stroked = !s.stroke.is_none();
|
||||
@@ -500,8 +519,8 @@ fn loses(t: &TextObject, fonts: &mut ResolvedFonts) -> bool {
|
||||
..s.clone()
|
||||
}
|
||||
};
|
||||
// A Lab color is written as RGB.
|
||||
let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. });
|
||||
// A Lab color is written as RGB, unless an art style holds it with its link.
|
||||
let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. }) && !linked(p);
|
||||
s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !fonts.kept(&s)
|
||||
};
|
||||
// A paragraph's style as the text document holds it, and its text: aligned to the start of
|
||||
@@ -842,6 +861,10 @@ pub(in crate::ai_editing) struct TextDoc {
|
||||
doc_values: usize,
|
||||
/// The fonts of the styles written so far, as they resolve.
|
||||
resolved: ResolvedFonts,
|
||||
/// The swatch links of type's colors looked at so far, by swatch and tint: the art style that
|
||||
/// holds each (a style of one paint, the color with its swatch, which key 5 of a run's paint
|
||||
/// names), `None` when the editing data can't hold it ([`super::Writer::link_type_colors`]).
|
||||
links: HashMap<LinkKey, Option<String>>,
|
||||
}
|
||||
|
||||
impl TextDoc {
|
||||
@@ -851,7 +874,53 @@ impl TextDoc {
|
||||
|
||||
/// Has type `t` attributes the text document leaves out ([`loses`])?
|
||||
pub(in crate::ai_editing) fn loses(&mut self, t: &TextObject) -> bool {
|
||||
loses(t, &mut self.resolved)
|
||||
loses(t, &mut self.resolved, &self.links)
|
||||
}
|
||||
|
||||
/// The colors of type whose swatch links are still to be looked at: the fills and strokes of
|
||||
/// `texts`' runs that are linked to a swatch and not in [`Self::links`] yet, each once.
|
||||
pub(in crate::ai_editing) fn unlooked_links<'t>(&self, texts: &[&'t TextObject]) -> Vec<&'t Paint> {
|
||||
let mut seen = HashSet::new();
|
||||
texts
|
||||
.iter()
|
||||
.flat_map(|t| t.runs.iter().flat_map(|r| [&r.style.fill, &r.style.stroke]))
|
||||
.filter(|p| link_key(p).is_some_and(|k| !self.links.contains_key(&k) && seen.insert(k)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Record the art style `style` that holds the swatch link of colors linked as `p` is, or
|
||||
/// `None` when none does ([`Self::links`]).
|
||||
pub(in crate::ai_editing) fn set_link(&mut self, p: &Paint, style: Option<String>) {
|
||||
if let Some(k) = link_key(p) {
|
||||
self.links.insert(k, style);
|
||||
}
|
||||
}
|
||||
|
||||
/// The art styles the stories written name for their runs' colors (key 5 of a paint).
|
||||
pub(in crate::ai_editing) fn named_styles(&self) -> HashSet<&str> {
|
||||
fn walk<'v>(v: &'v V, out: &mut HashSet<&'v str>) {
|
||||
match v {
|
||||
V::Dict(d) => {
|
||||
if d.iter().any(|(k, v)| *k == 99 && matches!(v, V::Name("CAITextPaint"))) {
|
||||
out.extend(d.iter().filter_map(|(k, v)| match (k, v) {
|
||||
(5, V::Str(s)) => Some(s.as_str()),
|
||||
_ => None,
|
||||
}));
|
||||
}
|
||||
d.iter().for_each(|(_, v)| walk(v, out));
|
||||
}
|
||||
V::List(l) => l.iter().for_each(|v| walk(v, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = HashSet::new();
|
||||
self.stories.iter().for_each(|v| walk(v, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
/// The art style that holds the swatch link of `p`, if one does.
|
||||
fn link(&self, p: &Paint) -> Option<&str> {
|
||||
self.links.get(&link_key(p)?)?.as_deref()
|
||||
}
|
||||
|
||||
/// The index of the font of `st` in the font set.
|
||||
@@ -909,11 +978,13 @@ impl TextDoc {
|
||||
let fill = solid(&st.fill).flatten();
|
||||
// A stroke of no width keeps its paint.
|
||||
let stroke = solid(&st.stroke).flatten();
|
||||
// A color linked to a swatch names the art style that holds the link, the fill's for a
|
||||
// stroke too (the reader's `Texts::with_paints`).
|
||||
if let Some(c) = &fill {
|
||||
d.push((53, paint(c)));
|
||||
d.push((53, paint(c, self.link(&st.fill))));
|
||||
}
|
||||
if let Some(c) = &stroke {
|
||||
d.push((54, paint(c)));
|
||||
d.push((54, paint(c, self.link(&st.stroke))));
|
||||
}
|
||||
d.extend([(56, V::Bool(fill.is_some())), (57, V::Bool(stroke.is_some()))]);
|
||||
if stroke.is_some() {
|
||||
@@ -1243,7 +1314,7 @@ impl TextDoc {
|
||||
if !whole.runs.iter().any(|r| r.text.chars().any(|c| !c.is_whitespace())) || !self.room(&whole, texts.len()) {
|
||||
return None;
|
||||
}
|
||||
let lost = split_differs || texts.iter().any(|t| loses(t, &mut self.resolved));
|
||||
let lost = split_differs || texts.iter().any(|t| loses(t, &mut self.resolved, &self.links));
|
||||
let frames: Vec<usize> = texts.iter().map(|t| self.frame(t, canvas, scale)).collect();
|
||||
let story = self.story(&whole, &frames, scale);
|
||||
if !self.fits(mark) {
|
||||
@@ -1357,7 +1428,7 @@ impl TextDoc {
|
||||
(12, V::Int(0)),
|
||||
// Every run writes its own key 35, so this only sets where new type starts: Standard (1).
|
||||
(35, V::Int(1)),
|
||||
(53, paint(&Color::gray(1.0))),
|
||||
(53, paint(&Color::gray(1.0), None)),
|
||||
(56, V::Bool(true)),
|
||||
(57, V::Bool(false)),
|
||||
(63, real(1.0)),
|
||||
|
||||
@@ -98,7 +98,7 @@ pub(crate) use ai::{
|
||||
BLEND_BUDGET, BLEND_PLUGIN, BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS,
|
||||
MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, ParsedStyle,
|
||||
blend_reads, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, parse_art_style, parsed_moves_with,
|
||||
read_brush_object, read_parsed_style, read_style_list, symbol_art_member, turn_brush_art_over, warp_number,
|
||||
parsed_type_color, read_brush_object, read_parsed_style, read_style_list, symbol_art_member, turn_brush_art_over, warp_number,
|
||||
};
|
||||
pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version};
|
||||
pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from};
|
||||
|
||||
@@ -60,8 +60,8 @@ pub use read::read;
|
||||
#[cfg(test)]
|
||||
pub(crate) use read::with_image_limits;
|
||||
pub(crate) use read::{
|
||||
BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, read_over_page,
|
||||
read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member,
|
||||
BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, parsed_type_color,
|
||||
read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member,
|
||||
};
|
||||
pub use read::{
|
||||
BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles,
|
||||
|
||||
@@ -220,16 +220,53 @@ const PAINTED_SLACK: f64 = 1e-4;
|
||||
/// applied, so a stroke a Transform effect moves counts where it is moved to), measured by its
|
||||
/// visual bounds. Those are exact for miter joins (a tip counts where the miter limit keeps it) and
|
||||
/// round joins, and an upper bound for bevel joins, miters the limit cuts, width profiles and
|
||||
/// square-capped dashes; a contour of zero length, which paints nothing, doesn't count. Effects on
|
||||
/// the type object itself are left out: VectorCraft applies them after the envelope bends the type.
|
||||
/// `None` when nothing in it has bounds.
|
||||
/// square-capped dashes; a contour of zero length, which paints nothing in the files' drawn art,
|
||||
/// doesn't count, even where VectorCraft draws it as the dot of a round or projecting cap. Effects
|
||||
/// on the type object itself are left out: VectorCraft applies them after the envelope bends the
|
||||
/// type. `None` when nothing in it has bounds.
|
||||
fn painted_outlines(outlines: &Node) -> Option<Rect> {
|
||||
outlines.children().into_iter().flatten().fold(None, |acc, piece| {
|
||||
let baked = vectorcraft_effects::bake_type_appearance(None, piece);
|
||||
vectorcraft_geom::union_opt(acc, baked.as_ref().unwrap_or(piece).visual_bounds())
|
||||
let baked = baked.as_ref().unwrap_or(piece);
|
||||
let painted = without_zero_length_contours(baked);
|
||||
vectorcraft_geom::union_opt(acc, painted.as_ref().unwrap_or(baked).visual_bounds())
|
||||
})
|
||||
}
|
||||
|
||||
/// `n` with its paths, and the paths in its groups and compound paths, without their subpaths of
|
||||
/// one anchor (contours of zero length, which have no segment); a path with nothing else is left
|
||||
/// empty, with no bounds. `None` when nothing changes.
|
||||
fn without_zero_length_contours(n: &Node) -> Option<Node> {
|
||||
if let Some(path) = n.path_data() {
|
||||
let lone = |s: &vectorcraft_geom::SubPath| s.segment_count() == 0;
|
||||
if !path.subpaths.iter().any(lone) {
|
||||
return None;
|
||||
}
|
||||
let mut kept = n.clone();
|
||||
if let Some(p) = kept.path_data_mut() {
|
||||
p.subpaths.retain(|s| !lone(s));
|
||||
}
|
||||
return Some(kept);
|
||||
}
|
||||
if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Compound { .. }) {
|
||||
return None;
|
||||
}
|
||||
let members = n.children()?;
|
||||
let changed: Vec<Option<Node>> = members.iter().map(|c| without_zero_length_contours(c)).collect();
|
||||
if changed.iter().all(Option::is_none) {
|
||||
return None;
|
||||
}
|
||||
let mut kept = n.clone();
|
||||
if let Some(children) = kept.children_mut() {
|
||||
for (c, new) in children.iter_mut().zip(changed) {
|
||||
if let Some(new) = new {
|
||||
*c = Arc::new(new);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(kept)
|
||||
}
|
||||
|
||||
/// The box of `content` an envelope of type with Distort Appearance may map from in a file besides
|
||||
/// [`half_stroked_box`]: what it paints, type by its outlines ([`painted_outlines`]), groups by
|
||||
/// their members grown by as far as their own strokes paint along a side, other objects by their
|
||||
@@ -1368,6 +1405,30 @@ mod tests {
|
||||
assert_eq!(painted_outlines(&outlines), Some(Rect::new(9.0, 9.0, 21.0, 21.0)));
|
||||
}
|
||||
|
||||
/// A piece of type outlines that is only contours of zero length paints nothing either: a dot
|
||||
/// piece with a round 2 point stroke beside a stroked square adds nothing to the square's box.
|
||||
#[test]
|
||||
fn a_piece_of_only_zero_length_contours_paints_nothing() {
|
||||
let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
|
||||
(stroke.join, stroke.cap) = (LineJoin::Round, LineCap::Round);
|
||||
let mut appearance = Appearance::default();
|
||||
appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))));
|
||||
appearance.items.push(AppearanceItem::Stroke(stroke));
|
||||
let mut square = BezPath::new();
|
||||
square.move_to((10.0, 10.0));
|
||||
square.line_to((20.0, 10.0));
|
||||
square.line_to((20.0, 20.0));
|
||||
square.line_to((10.0, 20.0));
|
||||
square.close_path();
|
||||
let mut dot = BezPath::new();
|
||||
dot.move_to((50.0, 50.0));
|
||||
dot.line_to((50.0, 50.0));
|
||||
dot.close_path();
|
||||
let pieces = [(1, square), (2, dot)].map(|(id, bp)| Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&bp), appearance.clone())));
|
||||
let outlines = Node::group(NodeId(3), pieces.to_vec());
|
||||
assert_eq!(painted_outlines(&outlines), Some(Rect::new(9.0, 9.0, 21.0, 21.0)));
|
||||
}
|
||||
|
||||
/// Type that draws nothing adds no box next to other content in the boxes the import tries an
|
||||
/// envelope with Distort Appearance mapped from, loose and in a group, as it adds none to the
|
||||
/// contents' geometric box: a rectangle with a round 4 point stroke beside type of only spaces
|
||||
|
||||
@@ -155,7 +155,7 @@ pub use document::{
|
||||
};
|
||||
pub(crate) use document::{slot_frame, slot_of};
|
||||
use graph::Graph;
|
||||
pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, read_parsed_style, read_style_list};
|
||||
pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, parsed_type_color, read_parsed_style, read_style_list};
|
||||
#[cfg(test)]
|
||||
pub(crate) use raster::with_image_limits;
|
||||
pub(crate) use types::BLEND_BUDGET;
|
||||
@@ -219,10 +219,11 @@ pub struct Structure {
|
||||
pub warped_type: super::envelope::WarpedType,
|
||||
/// The document's graphic styles are those of the file's style list, in place of the defaults.
|
||||
pub styles_read: bool,
|
||||
/// The patterns that paint the text document's characters, placed in the document, by the
|
||||
/// name of the art style that gives each: the styles that are one paint, a pattern this read
|
||||
/// (see `ate::Texts::with_patterns`).
|
||||
pub text_patterns: HashMap<String, Paint>,
|
||||
/// The paints the text document's characters take in place of their own colors, by the name
|
||||
/// of the art style that gives each: the styles that are one paint, a pattern this read,
|
||||
/// placed in the document, or a color linked to its swatch at its tint (see
|
||||
/// `ate::Texts::with_paints`).
|
||||
pub text_paints: HashMap<String, Paint>,
|
||||
/// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not.
|
||||
pub canvas_scale: f64,
|
||||
/// The data's symbols are at their own size, whatever its scale: VectorCraft wrote it (its
|
||||
|
||||
@@ -1065,7 +1065,7 @@ impl<'a> Reader<'a> {
|
||||
/// whose name another swatch has, take the first free "Name 2", "Name 3"…
|
||||
/// ([`Document::free_swatch_name`]) once the other colors and the patterns have their swatches;
|
||||
/// a pattern a swatch already paints with gets no other.
|
||||
fn file_swatches(&self, doc: &mut Document, own_palette: bool) -> HashMap<String, String> {
|
||||
fn file_swatches(&self, doc: &mut Document, own_palette: bool, type_colors: &[super::Named]) -> HashMap<String, String> {
|
||||
let mut defined = std::collections::HashSet::new();
|
||||
let mut clashes = vec![];
|
||||
// The swatch names there are, looked up rather than scanned for each name a file defines
|
||||
@@ -1075,7 +1075,8 @@ impl<'a> Reader<'a> {
|
||||
// The names a swatch of another kind than a gradient or pattern has.
|
||||
let mut solid: std::collections::HashSet<String> =
|
||||
doc.swatches_iter().filter(|s| !matches!(s.paint, Paint::Gradient(_) | Paint::Pattern { .. })).map(|s| s.name.clone()).collect();
|
||||
let colors = self.spots.iter().chain(&self.stop_spots).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true)));
|
||||
let colors =
|
||||
self.spots.iter().chain(&self.stop_spots).chain(type_colors).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true)));
|
||||
for (n, spot) in colors {
|
||||
let first = defined.insert(n.name.clone());
|
||||
let swatch = Swatch { name: n.name.clone(), paint: Paint::solid(n.color), global: true, spot };
|
||||
@@ -1327,7 +1328,26 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
let renamed = self.file_swatches(&mut doc, own_palette);
|
||||
// The swatch colors of the styles that are one paint, which the text document's characters
|
||||
// name for their fills and strokes, in the order of the styles' names.
|
||||
let mut type_colors: Vec<(&String, &(Paint, Option<super::Named>))> =
|
||||
self.styles.iter().filter_map(|(style, st)| Some((style, st.simple_color.as_ref()?))).collect();
|
||||
type_colors.sort_by_key(|(style, _)| *style);
|
||||
let type_named: Vec<super::Named> = type_colors.iter().filter_map(|(_, (_, named))| named.clone()).collect();
|
||||
let renamed = self.file_swatches(&mut doc, own_palette, &type_named);
|
||||
let type_colors: Vec<(String, Paint)> = type_colors
|
||||
.into_iter()
|
||||
.map(|(style, (paint, _))| {
|
||||
let mut paint = paint.clone();
|
||||
// A color that took a free name is linked by that name.
|
||||
if let Paint::Solid { swatch: Some(link), .. } = &mut paint
|
||||
&& let Some(new) = renamed.get(link.as_str())
|
||||
{
|
||||
link.clone_from(new);
|
||||
}
|
||||
(style.clone(), paint)
|
||||
})
|
||||
.collect();
|
||||
if let Some(author) = self.author.take() {
|
||||
doc.metadata.author = author;
|
||||
}
|
||||
@@ -1394,8 +1414,9 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
warnings.extend(self.names.notes());
|
||||
// The patterns of the styles that are one paint, which the text document's characters
|
||||
// name for their fills and strokes: those that place in the document.
|
||||
let text_patterns = self
|
||||
// name for their fills and strokes: those that place in the document. With them, those
|
||||
// styles' swatch colors.
|
||||
let text_paints = self
|
||||
.styles
|
||||
.iter()
|
||||
.filter_map(|(style, st)| {
|
||||
@@ -1403,6 +1424,7 @@ impl<'a> Reader<'a> {
|
||||
let paint = super::ops::style_pattern(name, *matrix, controls, &self.pattern_tiles, &self.v7_patterns, &self.global_names, to_doc)?;
|
||||
Some((style.clone(), paint))
|
||||
})
|
||||
.chain(type_colors)
|
||||
.collect();
|
||||
Ok(Structure {
|
||||
doc,
|
||||
@@ -1430,7 +1452,7 @@ impl<'a> Reader<'a> {
|
||||
type_clips: self.type_clips,
|
||||
},
|
||||
styles_read,
|
||||
text_patterns,
|
||||
text_paints,
|
||||
canvas_scale: self.canvas_scale,
|
||||
symbols_own_size: self.symbols_own_size,
|
||||
xml_ids: self.xml_ids,
|
||||
|
||||
@@ -1488,7 +1488,7 @@ fn painted_bounds(object: &Node, appearance: &Appearance) -> Option<Rect> {
|
||||
let mut out = None;
|
||||
for item in &appearance.items {
|
||||
let painted = match item {
|
||||
AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() => path.bounds(),
|
||||
AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() => path.drawn_bounds(false),
|
||||
AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() => vectorcraft_effects::stroke::outline_region(&path, rule, s).bounds(),
|
||||
_ => None,
|
||||
};
|
||||
@@ -1763,6 +1763,14 @@ pub(crate) fn parse_art_style(section: &[u8], name: &str) -> Option<ParsedStyle>
|
||||
crate::import::ai::style::art_styles(section).remove(name).map(|style| ParsedStyle { style })
|
||||
}
|
||||
|
||||
/// The color type takes from art style `parsed` when a character's fill or stroke names it (key 5
|
||||
/// of its paint, `ate`): a style of one paint whose paint is a color with a swatch, at its tint and
|
||||
/// linked to that swatch ([`crate::import::ai::style::ArtStyle::simple_color`]). `None` for any
|
||||
/// other style.
|
||||
pub(crate) fn parsed_type_color(parsed: &ParsedStyle) -> Option<&Paint> {
|
||||
parsed.style.simple_color.as_ref().map(|(paint, _)| paint)
|
||||
}
|
||||
|
||||
/// Art style `parsed` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`], with a
|
||||
/// style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads it on
|
||||
/// objects other than type. A stroke that names a brush is read with that brush's name, as [`styled`]
|
||||
@@ -1984,6 +1992,31 @@ mod tests {
|
||||
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, Paint::None, 0.0)))
|
||||
}
|
||||
|
||||
/// A lone anchor, which a fill does not paint, does not move what the fill paints when the
|
||||
/// arrowheads are placed against the drawn look: a filled line with a head and a stray anchor
|
||||
/// well outside it still fits a look of the line and its head alone.
|
||||
#[test]
|
||||
fn a_lone_anchor_does_not_move_the_painted_box_heads_are_placed_by() {
|
||||
use vectorcraft_doc::{ArrowAlign, Arrowhead, CustomArrowhead, FillLayer, StrokeLayer};
|
||||
use vectorcraft_geom::{Point, SubPath};
|
||||
let wedge = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true));
|
||||
let mut stroke = StrokeLayer::new(Paint::solid(vectorcraft_doc::color::Color::BLACK), 2.0);
|
||||
stroke.end_arrow = Some(Arrowhead::Custom(Arc::new(CustomArrowhead::new("Wedge".into(), wedge))));
|
||||
stroke.arrow_align = ArrowAlign::Tip;
|
||||
let mut appearance = Appearance::default();
|
||||
appearance.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(vectorcraft_doc::color::Color::BLACK))));
|
||||
appearance.items.push(AppearanceItem::Stroke(stroke));
|
||||
let line = SubPath::polyline(&[Point::new(0.0, 50.0), Point::new(100.0, 50.0)], false);
|
||||
let plain = Node::path(NodeId(1), PathData::single(line.clone()), appearance.clone());
|
||||
let want = painted_bounds(&plain, &appearance).unwrap();
|
||||
let look =
|
||||
Node::path(NodeId(2), shapes::rectangle(want), Appearance::basic(Paint::solid(vectorcraft_doc::color::Color::BLACK), Paint::None, 0.0));
|
||||
let stray = SubPath::new(vec![vectorcraft_geom::Anchor::corner(Point::new(50.0, 200.0))], false);
|
||||
let object = Node::path(NodeId(3), PathData::new(vec![line, stray]), appearance.clone());
|
||||
let placed = heads_placed(&object, &look, appearance, Affine::IDENTITY).expect("the heads fit the look");
|
||||
assert!(placed.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.arrow_align == ArrowAlign::Tip)));
|
||||
}
|
||||
|
||||
/// The outline check works from one budget for the object: a look of the outline drawn twice
|
||||
/// (a fill and a stroke) matches, one drawn thousands of times gives up and keeps the drawn
|
||||
/// look instead of comparing every copy.
|
||||
|
||||
@@ -215,6 +215,13 @@ pub(super) struct ArtStyle {
|
||||
/// paint is a pattern: its [`StyleItem::Pattern`]. A text document's characters name such
|
||||
/// styles for their fills and strokes (`ate`). `None` for any other paint or style.
|
||||
pub simple_pattern: Option<StyleItem>,
|
||||
/// A style that is one paint, when that paint is a colour with a swatch (a spot ink or a
|
||||
/// global process colour, `x`, `Xx`, `Xk`; Registration): the paint at its tint, linked to the
|
||||
/// swatch, with the named colour that makes the swatch (none for Registration). Only when the
|
||||
/// style's fill alone is on (`0 1 Xd`) and it sets no stroke colour or pattern, before or after. A text
|
||||
/// document's characters name such styles for their fills and strokes (`ate`), and keep only
|
||||
/// the colour's process values themselves. `None` for any other paint or style.
|
||||
pub simple_color: Option<(Paint, Option<paint::Named>)>,
|
||||
/// A style that is one paint: its fill and stroke, bottom first, each there when its
|
||||
/// `stroke fill Xd` turns it on (none when neither is on). `Err` when it turns on a fill or
|
||||
/// stroke whose paint isn't read here (a gradient that names no swatch or isn't in a gradient
|
||||
@@ -477,16 +484,20 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap<String, A
|
||||
let mut open: Vec<usize> = vec![];
|
||||
let mut pending: Option<bool> = None;
|
||||
let mut in_basic = false;
|
||||
// A style that is one paint being read, and its pattern so far.
|
||||
let mut simple: Option<Option<StyleItem>> = None;
|
||||
// A style that is one paint being read, and its pattern or swatch colour so far.
|
||||
let mut simple: Option<SimplePaint> = None;
|
||||
// The same style's paint operators so far.
|
||||
let mut one_paint: Option<OnePaint> = None;
|
||||
let mut finish = |name: Option<String>, filters: &mut Vec<Filter>, simple_pattern: Option<StyleItem>, one_paint: Option<OnePaint>| {
|
||||
let mut finish = |name: Option<String>, filters: &mut Vec<Filter>, simple: SimplePaint, one_paint: Option<OnePaint>| {
|
||||
if let Some(name) = name {
|
||||
// Only a style that is one paint holds a pattern for type: one with filters as well
|
||||
// paints with more than that.
|
||||
let simple_pattern = simple_pattern.filter(|_| filters.is_empty());
|
||||
let mut st = ArtStyle { simple_pattern, ..style(filters) };
|
||||
// Only a style that is one paint holds a pattern or a swatch colour for type: one with
|
||||
// filters as well paints with more than that.
|
||||
let SimplePaint { pattern, color, stroke_painted } = if filters.is_empty() { simple } else { SimplePaint::default() };
|
||||
// The colour is the style's one paint: only its fill is on (`0 1 Xd`) and nothing sets a
|
||||
// stroke's colour or pattern.
|
||||
let filled = one_paint.as_ref().is_some_and(|one| one.xd && one.paint.paints == (false, true));
|
||||
let color = color.filter(|_| filled && !stroke_painted);
|
||||
let mut st = ArtStyle { simple_pattern: pattern, simple_color: color, ..style(filters) };
|
||||
if let Some(one) = one_paint.filter(|_| filters.is_empty()) {
|
||||
if let Some((mode, opacity)) = one.paint.xy {
|
||||
let (isolate, knockout) = one.paint.xy_group.unwrap_or((false, Knockout::Off));
|
||||
@@ -531,12 +542,12 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap<String, A
|
||||
}
|
||||
Tok::Name(n) => match n {
|
||||
b"KnownStyle" => {
|
||||
finish(name.take(), &mut filters, simple.take().flatten(), one_paint.take());
|
||||
finish(name.take(), &mut filters, simple.take().unwrap_or_default(), one_paint.take());
|
||||
operands.clear();
|
||||
open.clear();
|
||||
(pending, in_basic, style_entry, other_entry) = (None, false, None, None);
|
||||
}
|
||||
b"SimpleStyle" if filters.is_empty() => (simple, one_paint) = (Some(None), Some(OnePaint::default())),
|
||||
b"SimpleStyle" if filters.is_empty() => (simple, one_paint) = (Some(SimplePaint::default()), Some(OnePaint::default())),
|
||||
b"FillStyle" => style_entry = Some(Kind::Fill),
|
||||
b"StrokeStyle" | b"BlendStyle" => style_entry = Some(Kind::Other),
|
||||
b"Name" if name.is_none() && filters.is_empty() => name = operands.iter().rev().find_map(|v| names.text(v)),
|
||||
@@ -653,7 +664,7 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap<String, A
|
||||
operands.clear();
|
||||
}
|
||||
}
|
||||
finish(name, &mut filters, simple.take().flatten(), one_paint.take());
|
||||
finish(name, &mut filters, simple.take().unwrap_or_default(), one_paint.take());
|
||||
styles
|
||||
}
|
||||
|
||||
@@ -814,7 +825,7 @@ fn pattern_operands(vals: &[V], names: &mut Names) -> Option<(String, Option<[f6
|
||||
/// that is one paint (`simple` and `one_paint`, while one is read).
|
||||
fn style_paint_op(
|
||||
filters: &mut [Filter],
|
||||
simple: &mut Option<Option<StyleItem>>,
|
||||
simple: &mut Option<SimplePaint>,
|
||||
one_paint: &mut Option<OnePaint>,
|
||||
op: &str,
|
||||
vals: &[V],
|
||||
@@ -937,14 +948,35 @@ impl OnePaint {
|
||||
}
|
||||
}
|
||||
|
||||
/// What type takes from a style that is one paint ([`ArtStyle::simple_pattern`],
|
||||
/// [`ArtStyle::simple_color`]): one of them at most.
|
||||
#[derive(Default)]
|
||||
struct SimplePaint {
|
||||
pattern: Option<StyleItem>,
|
||||
color: Option<(Paint, Option<paint::Named>)>,
|
||||
/// A stroke's colour or pattern was set, before or after the fill's: the style isn't one
|
||||
/// colour, so it holds none for type (its pattern is kept as before).
|
||||
stroke_painted: bool,
|
||||
}
|
||||
|
||||
/// A paint operator of a style that is one paint: a pattern (`p`) is kept as its
|
||||
/// [`StyleItem::Pattern`], and any other paint after it (a colour, a stroke's pattern or a
|
||||
/// gradient) leaves the style without one.
|
||||
fn simple_paint_op(paint: &mut Option<StyleItem>, op: &str, vals: &[V], names: &mut Names) {
|
||||
/// [`StyleItem::Pattern`] and a fill colour that has a swatch as its paint and named colour. Any
|
||||
/// other paint after one of them (a colour, a stroke's colour or pattern, a gradient) leaves the
|
||||
/// style without it, and a stroke's colour or pattern anywhere is remembered
|
||||
/// ([`SimplePaint::stroke_painted`]).
|
||||
fn simple_paint_op(simple: &mut SimplePaint, op: &str, vals: &[V], names: &mut Names) {
|
||||
let stroke_painted = simple.stroke_painted;
|
||||
match op {
|
||||
"p" => *paint = pattern_operands(vals, names).map(|(name, matrix, controls)| StyleItem::Pattern { name, matrix, controls }),
|
||||
"Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" | "xa" | "xx" | "xk" | "xs"
|
||||
| "xz" | "P" | "Bg" => *paint = None,
|
||||
"p" => {
|
||||
let pattern = pattern_operands(vals, names).map(|(name, matrix, controls)| StyleItem::Pattern { name, matrix, controls });
|
||||
*simple = SimplePaint { pattern, color: None, stroke_painted };
|
||||
}
|
||||
"Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "xa" | "xx" | "xk" | "xs" | "xz" => {
|
||||
let color = paint::color_op_in(op, vals, names).filter(|(p, _)| matches!(p, Paint::Solid { swatch: Some(_), .. }));
|
||||
*simple = SimplePaint { pattern: None, color, stroke_painted };
|
||||
}
|
||||
"XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" | "P" => *simple = SimplePaint { stroke_painted: true, ..SimplePaint::default() },
|
||||
"Bg" => *simple = SimplePaint { stroke_painted, ..SimplePaint::default() },
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1548,6 +1548,54 @@ fn only_a_style_of_one_pattern_paint_holds_a_pattern_for_type() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A style that is one paint holds a swatch colour for type when its paint is a fill colour with a
|
||||
/// swatch: the paint at its tint and the named colour that makes the swatch. A process colour,
|
||||
/// another paint after the colour, a stroke's colour before it, a fill that is off, or filters
|
||||
/// beside it give none.
|
||||
#[test]
|
||||
fn only_a_style_of_one_swatch_colour_holds_it_for_type() {
|
||||
let painted = |paint: &str, xd: &str| format!("/SimpleStyle :\n0 O\n{paint}\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n{xd}/Paint ;\n");
|
||||
let simple = |paint: &str| painted(paint, "0 1 Xd\n");
|
||||
let active = "/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
|
||||
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n1 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\
|
||||
/FillStyle : 0 O\n1 0 0 0 k\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n";
|
||||
let color = |body: &str| {
|
||||
let styles = art_styles_in(format!("/KnownStyle :\n(S) /Name ,\n{body} /Def ;\n").as_bytes(), &mut Names::default());
|
||||
styles.get("S").and_then(|s| s.simple_color.clone())
|
||||
};
|
||||
let red = Color::cmyk(0.0, 1.0, 1.0, 0.0);
|
||||
let ink = "0 1 1 0 (Red Ink) 0.25 x";
|
||||
let linked = Paint::Solid { color: red.tinted(0.75), swatch: Some("Red Ink".into()), tint: 0.75 };
|
||||
let named = |spot: bool| paint::Named { name: "Red Ink".into(), color: red, tint: 0.75, spot };
|
||||
assert_eq!(color(&simple(ink)), Some((linked.clone(), Some(named(true)))));
|
||||
// A global process colour is no ink of its own.
|
||||
assert_eq!(color(&simple("0 1 1 0 (Red Ink) 0.25 0 Xk")), Some((linked, Some(named(false)))));
|
||||
// Registration has the built-in swatch.
|
||||
let registration = color(&simple("1 1 1 1 ([Registration]) 0 Xs"));
|
||||
assert!(matches!(®istration, Some((p, None)) if p.is_registration()), "{registration:?}");
|
||||
let dots = "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p";
|
||||
for body in [
|
||||
simple("0 1 1 0 k"),
|
||||
simple(&format!("{ink}\n{dots}")),
|
||||
simple(&format!("{ink}\n0 0 0 1 K")),
|
||||
simple(&format!("{ink}\n0 1 1 0 k")),
|
||||
// The order of the paints doesn't matter: a stroke's colour before the fill's.
|
||||
simple(&format!("0 0 0 1 K\n{ink}")),
|
||||
simple(&format!("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] P\n{ink}")),
|
||||
// The fill is off, both are off, the stroke is on too, or nothing says which is on.
|
||||
painted(ink, "1 0 Xd\n"),
|
||||
painted(ink, "0 0 Xd\n"),
|
||||
painted(ink, "1 1 Xd\n"),
|
||||
painted(ink, ""),
|
||||
format!("{}{active}", simple(ink)),
|
||||
format!("{active}{}", simple(ink)),
|
||||
] {
|
||||
assert_eq!(color(&body), None, "{body}");
|
||||
}
|
||||
// The last fill colour is the style's.
|
||||
assert!(color(&simple(&format!("{dots}\n{ink}"))).is_some());
|
||||
}
|
||||
|
||||
/// A style that is one paint reads as the fill and stroke its `Xd` turns on, in the paint's colors
|
||||
/// and the stroke's style; one that turns on a paint not read here, or has no `Xd`, isn't read.
|
||||
#[test]
|
||||
|
||||
@@ -527,11 +527,11 @@ struct Style {
|
||||
v_scale: f64,
|
||||
fill: Option<Color>,
|
||||
stroke: Option<Color>,
|
||||
/// The pattern that paints the fill or the stroke in place of its colour: the one the art
|
||||
/// style named by key 5 of its paint gives ([`Texts::with_patterns`]), placed in the document.
|
||||
/// `None` for any other paint, which keeps its colour.
|
||||
fill_pattern: Option<Paint>,
|
||||
stroke_pattern: Option<Paint>,
|
||||
/// The paint of the fill or the stroke in place of its colour: the one the art style named by
|
||||
/// key 5 of its paint gives ([`Texts::with_paints`]), a pattern placed in the document or a
|
||||
/// colour linked to its swatch. `None` for any other paint, which keeps its colour.
|
||||
fill_paint: Option<Paint>,
|
||||
stroke_paint: Option<Paint>,
|
||||
stroke_width: f64,
|
||||
/// Key 61, the stroke's cap: 0 butt, 1 round, 2 projecting (square).
|
||||
stroke_cap: LineCap,
|
||||
@@ -613,24 +613,30 @@ pub(super) struct Texts {
|
||||
/// attributes (key 5) and the paragraph style it is based on (key 6, an index into these).
|
||||
para_sheets: Vec<Val>,
|
||||
frames: Vec<Val>,
|
||||
/// The patterns that paint characters, by the name of the art style that gives each
|
||||
/// ([`Self::with_patterns`]).
|
||||
patterns: HashMap<String, Paint>,
|
||||
/// The paints characters take in place of their colours, by the name of the art style that
|
||||
/// gives each ([`Self::with_paints`]).
|
||||
paints: HashMap<String, Paint>,
|
||||
/// The document's Kinsoku sets (key 4 of its resources), in order, each by its name (key 0):
|
||||
/// Hard or Soft, `None` for any other set.
|
||||
kinsoku_sets: Vec<Option<Kinsoku>>,
|
||||
}
|
||||
|
||||
impl Texts {
|
||||
/// The text document with its characters painted by `patterns`: the patterns of the editing
|
||||
/// data's art styles that paint with one, each placed in the document, by the style's name.
|
||||
/// A run's fill or stroke (key 53 or 54) is a paint whose key 0 is a colour and whose key 5
|
||||
/// names the art style that paints it. In users' files (used locally, never committed), such a
|
||||
/// style is one paint: a colour, which key 0 already has, or a pattern, whose key 0 is black
|
||||
/// (`/0 0 /1 [ 1 0 ]`). The pattern's matrix is in art space, as a path's pattern fill has it:
|
||||
/// the files' own pages tile the type with the matrix a path's fill would get there.
|
||||
pub(super) fn with_patterns(self, patterns: HashMap<String, Paint>) -> Texts {
|
||||
Texts { patterns, ..self }
|
||||
/// The text document with its characters painted by `paints`: the paints of the editing data's
|
||||
/// art styles that are one paint, a pattern placed in the document or a colour linked to its
|
||||
/// swatch, by the style's name. A run's fill or stroke (key 53 or 54) is a paint whose key 0
|
||||
/// is a colour (grey, RGB or CMYK) and whose key 5 names the art style that paints it. In
|
||||
/// users' files (used locally, never committed), such a style is one paint, always its fill's,
|
||||
/// for a run's stroke too:
|
||||
/// - a process colour, which key 0 already has;
|
||||
/// - a spot ink or a global process colour at a tint (`c m y k (name) tint x`, `Xx`, `Xk`),
|
||||
/// whose process values at that tint are all key 0 keeps: the name and the tint are only in
|
||||
/// the style, so the type keeps its ink only when it takes the style's paint;
|
||||
/// - a pattern, whose key 0 is black (`/0 0 /1 [ 1 0 ]`). Its matrix is in art space, as a
|
||||
/// path's pattern fill has it: the files' own pages tile the type with the matrix a path's
|
||||
/// fill would get there.
|
||||
pub(super) fn with_paints(self, paints: HashMap<String, Paint>) -> Texts {
|
||||
Texts { paints, ..self }
|
||||
}
|
||||
|
||||
/// The text document in the editing copy `data`, if it has one that can be read.
|
||||
@@ -699,7 +705,7 @@ impl Texts {
|
||||
char_sheets,
|
||||
para_sheets,
|
||||
frames: doc.take("0")?.take("8")?.take("0")?.into_list(),
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets,
|
||||
})
|
||||
}
|
||||
@@ -939,8 +945,8 @@ impl Texts {
|
||||
let on = |k: &str| !matches!(pick(k), Some(Val::Bool(false)));
|
||||
let font = num("0").and_then(|i| self.fonts.get(i as usize)).filter(|f| !f.name.is_empty());
|
||||
let size = num("1").filter(|v| *v > 0.0 && *v < 1e5).unwrap_or(12.0);
|
||||
// Key 5 of a paint names the art style that paints it ([`Self::with_patterns`]).
|
||||
let pattern = |k: &str| pick(k).and_then(|p| p.get("5")).and_then(Val::str).and_then(|name| self.patterns.get(name)).cloned();
|
||||
// Key 5 of a paint names the art style that paints it ([`Self::with_paints`]).
|
||||
let styled = |k: &str| pick(k).and_then(|p| p.get("5")).and_then(Val::str).and_then(|name| self.paints.get(name)).cloned();
|
||||
Style {
|
||||
font: font.map(|f| f.font().clone()),
|
||||
size,
|
||||
@@ -951,8 +957,8 @@ impl Texts {
|
||||
v_scale: num("7").filter(|v| *v > 0.0 && *v < 100.0).unwrap_or(1.0),
|
||||
fill: if on("56") { Some(pick("53").and_then(paint).unwrap_or(Color::BLACK)) } else { None },
|
||||
stroke: if matches!(pick("57"), Some(Val::Bool(true))) { pick("54").and_then(paint) } else { None },
|
||||
fill_pattern: pattern("53"),
|
||||
stroke_pattern: pattern("54"),
|
||||
fill_paint: styled("53"),
|
||||
stroke_paint: styled("54"),
|
||||
stroke_width: num("63").filter(|v| *v >= 0.0 && *v < 1e4).unwrap_or(1.0),
|
||||
// Numbered as PostScript's `setlinecap` and `setlinejoin` operators number them
|
||||
// (PostScript Language Reference, 3rd ed.): in users' files the page strokes type with
|
||||
@@ -1588,16 +1594,18 @@ fn para_style(p: &Para, scale: f64) -> ParaStyle {
|
||||
|
||||
/// The character style of character attributes `s`: its font from the fonts the app has (the
|
||||
/// installed copy its font record names, [`DocFont::font`]), its lengths (size, leading, baseline
|
||||
/// shift, stroke width) scaled by `scale`, and its patterns placed in the type's text space by
|
||||
/// `to_text` (the document → its text space), where they stay as the document has them.
|
||||
/// shift, stroke width) scaled by `scale`, its patterns placed in the type's text space by
|
||||
/// `to_text` (the document → its text space), where they stay as the document has them, and its
|
||||
/// swatch colours linked to their swatches.
|
||||
fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle {
|
||||
let (family, style, version) = s.font.clone().unwrap_or_else(|| (CharStyle::default().font_family, "Regular".to_string(), None));
|
||||
// A fill or stroke that is on takes its pattern in place of its colour.
|
||||
let paint = |color: Option<Color>, pattern: &Option<Paint>| match (color, pattern) {
|
||||
// A fill or stroke that is on takes its style's paint in place of its colour.
|
||||
let paint = |color: Option<Color>, styled: &Option<Paint>| match (color, styled) {
|
||||
// A pattern that can't be placed (the type's text space out of range) keeps the colour.
|
||||
(Some(_), Some(Paint::Pattern { pattern, xf })) if (to_text * *xf).is_finite() => {
|
||||
Paint::Pattern { pattern: pattern.clone(), xf: to_text * *xf }
|
||||
}
|
||||
(Some(_), Some(linked @ Paint::Solid { swatch: Some(_), .. })) => linked.clone(),
|
||||
(color, _) => color.map_or(Paint::None, Paint::solid),
|
||||
};
|
||||
// Type without a stroke keeps the stroke's defaults, as its weight is 0.
|
||||
@@ -1616,8 +1624,8 @@ fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle {
|
||||
baseline_shift: s.baseline_shift * scale,
|
||||
h_scale: s.h_scale * 100.0,
|
||||
v_scale: s.v_scale * 100.0,
|
||||
fill: paint(s.fill, &s.fill_pattern),
|
||||
stroke: paint(s.stroke, &s.stroke_pattern),
|
||||
fill: paint(s.fill, &s.fill_paint),
|
||||
stroke: paint(s.stroke, &s.stroke_paint),
|
||||
stroke_width: if s.stroke.is_some() { s.stroke_width * scale } else { 0.0 },
|
||||
stroke_cap,
|
||||
stroke_join,
|
||||
@@ -1655,7 +1663,7 @@ mod tests {
|
||||
char_sheets: vec![],
|
||||
para_sheets: vec![],
|
||||
frames: vec![],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
let justify = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).justify;
|
||||
@@ -1680,7 +1688,7 @@ mod tests {
|
||||
char_sheets: vec![],
|
||||
para_sheets: vec![],
|
||||
frames: vec![],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
let auto = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).justification.auto_leading;
|
||||
@@ -1704,7 +1712,7 @@ mod tests {
|
||||
char_sheets: vec![],
|
||||
para_sheets: vec![],
|
||||
frames: vec![],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
let options = |own: &[u8], scale: f64| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), scale).hyphenation;
|
||||
@@ -1723,7 +1731,7 @@ mod tests {
|
||||
char_sheets: vec![],
|
||||
para_sheets: vec![],
|
||||
frames: vec![],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
let own = |own: &[u8]| para_style(&bare.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).hyphenation;
|
||||
@@ -1765,7 +1773,7 @@ mod tests {
|
||||
// [Normal Paragraph Style] has the Soft set; the second style has Force burasagari.
|
||||
para_sheets: vec![read(b"/5 << /27 1 >>").unwrap(), read(b"/5 << /24 2 /23 true >>").unwrap()],
|
||||
frames: vec![],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![Some(Kinsoku::Hard), Some(Kinsoku::Soft), None],
|
||||
};
|
||||
let para = |run: &[u8]| texts.para(Some(&read(run).unwrap()));
|
||||
@@ -1824,7 +1832,7 @@ mod tests {
|
||||
char_sheets: vec![],
|
||||
para_sheets: vec![],
|
||||
frames: vec![],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
let tabs = |own: &[u8], scale: f64| {
|
||||
@@ -1892,7 +1900,7 @@ mod tests {
|
||||
char_sheets: vec![],
|
||||
para_sheets: vec![],
|
||||
frames: vec![],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
}
|
||||
.para(None);
|
||||
@@ -1941,7 +1949,7 @@ mod tests {
|
||||
char_sheets: vec![],
|
||||
para_sheets: vec![],
|
||||
frames: cases.iter().map(|c| frame(c)).collect(),
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
let vertical: Vec<bool> = (0..cases.len() + 1).map(|i| texts.frame_vertical(i)).collect();
|
||||
@@ -1960,7 +1968,7 @@ mod tests {
|
||||
char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Block) /6 << /35 3 >>").unwrap()],
|
||||
para_sheets: vec![],
|
||||
frames: vec![],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
let tcy = |run: &[u8]| texts.style(Some(&read(run).unwrap())).tate_chu_yoko;
|
||||
@@ -1985,7 +1993,7 @@ mod tests {
|
||||
char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Rotated) /6 << /35 2 >>").unwrap()],
|
||||
para_sheets: vec![],
|
||||
frames: vec![],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
let roman = |defaults: &[u8], run: &[u8]| texts(defaults).style(Some(&read(run).unwrap())).standard_vertical_roman;
|
||||
@@ -2021,7 +2029,7 @@ mod tests {
|
||||
],
|
||||
para_sheets: vec![],
|
||||
frames: vec![],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
let aki = |defaults: &[u8], normal: &[u8], run: &[u8]| {
|
||||
@@ -2059,7 +2067,7 @@ mod tests {
|
||||
char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Rounded) /6 << /61 1 /62 1 >>").unwrap()],
|
||||
para_sheets: vec![],
|
||||
frames: vec![],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
let stroke = |run: &[u8]| {
|
||||
@@ -2102,10 +2110,10 @@ mod tests {
|
||||
char_sheets: vec![],
|
||||
para_sheets: vec![],
|
||||
frames: vec![],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
}
|
||||
.with_patterns(patterns)
|
||||
.with_paints(patterns)
|
||||
}
|
||||
|
||||
/// Key 5 of a run's fill or stroke names the art style that paints it: one that paints with a
|
||||
@@ -2142,6 +2150,25 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A run whose art style paints with a colour linked to a swatch takes that paint, the swatch
|
||||
/// and its tint, in place of the process values key 0 keeps for it; a fill or stroke that is
|
||||
/// off stays off.
|
||||
#[test]
|
||||
fn a_run_painted_by_a_swatch_colours_art_style_takes_the_swatch() {
|
||||
// GUARDS: type in a spot ink came in as the process colour key 0 keeps for it.
|
||||
let ink = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0).tinted(0.5), swatch: Some("Red Ink".into()), tint: 0.5 };
|
||||
let texts = patterned_texts().with_paints(HashMap::from([("Anon 1".to_string(), ink.clone())]));
|
||||
let paints = |run: &str| {
|
||||
let s = char_style(&texts.style(Some(&read(run.as_bytes()).unwrap())), 1.0, Affine::IDENTITY);
|
||||
(s.fill, s.stroke)
|
||||
};
|
||||
let red = |style: &str| format!("<< /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 .5 .5 0.0 ] >> {style} >>");
|
||||
let process = Paint::solid(Color::cmyk(0.0, 0.5, 0.5, 0.0));
|
||||
assert_eq!(paints(&format!("/6 << /53 {} >>", red("/5 (Anon 1)"))), (ink.clone(), Paint::None));
|
||||
assert_eq!(paints(&format!("/6 << /53 {} /57 true /54 {} >>", red(""), red("/5 (Anon 1)"))), (process, ink));
|
||||
assert_eq!(paints(&format!("/6 << /56 false /53 {} /54 {} >>", red("/5 (Anon 1)"), red("/5 (Anon 1)"))), (Paint::None, Paint::None));
|
||||
}
|
||||
|
||||
/// A run's pattern stays where the document has it whatever the type's own text space: turned
|
||||
/// and moved point type, and area type, whose text space is the document's.
|
||||
#[test]
|
||||
@@ -2154,9 +2181,9 @@ mod tests {
|
||||
] {
|
||||
let mut st = story("type", &[0.0], &Para::default());
|
||||
st.frames = vec![frame.clone()];
|
||||
st.runs[0].1.fill_pattern = Some(dots_at((10.0, 20.0)));
|
||||
st.runs[0].1.fill_paint = Some(dots_at((10.0, 20.0)));
|
||||
st.runs[0].1.stroke = Some(Color::BLACK);
|
||||
st.runs[0].1.stroke_pattern = Some(dots_at((-3.0, 8.0)));
|
||||
st.runs[0].1.stroke_paint = Some(dots_at((-3.0, 8.0)));
|
||||
let node = st.node(NodeId(1), 0, (0.0, 0.0), to_doc).unwrap();
|
||||
let NodeKind::Text(t) = node.kind else { panic!("not type") };
|
||||
for (paint, at) in [(&t.runs[0].style.fill, Point::new(10.0, 20.0)), (&t.runs[0].style.stroke, Point::new(-3.0, 8.0))] {
|
||||
@@ -2186,7 +2213,7 @@ mod tests {
|
||||
char_sheets: vec![],
|
||||
para_sheets: vec![],
|
||||
frames: vec![read(b"/0 << /0 [ 0 0 ] /2 << /0 0 >> >>").unwrap()],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
let text = |kerns: &[u8]| -> TextObject {
|
||||
@@ -2254,7 +2281,7 @@ mod tests {
|
||||
char_sheets: vec![],
|
||||
para_sheets: vec![],
|
||||
frames: vec![],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
let direction = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).direction;
|
||||
@@ -2303,7 +2330,7 @@ mod tests {
|
||||
char_sheets: vec![],
|
||||
para_sheets: vec![],
|
||||
frames: vec![read(doc.as_bytes()).unwrap()],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
texts.frame(0)
|
||||
@@ -2511,8 +2538,8 @@ mod tests {
|
||||
v_scale: 1.0,
|
||||
fill: Some(Color::BLACK),
|
||||
stroke: None,
|
||||
fill_pattern: None,
|
||||
stroke_pattern: None,
|
||||
fill_paint: None,
|
||||
stroke_paint: None,
|
||||
stroke_width: 1.0,
|
||||
stroke_cap: LineCap::Butt,
|
||||
stroke_join: LineJoin::Miter,
|
||||
@@ -2964,7 +2991,7 @@ mod tests {
|
||||
char_sheets: vec![],
|
||||
para_sheets: vec![],
|
||||
frames: vec![read(doc.as_bytes()).unwrap()],
|
||||
patterns: HashMap::new(),
|
||||
paints: HashMap::new(),
|
||||
kinsoku_sets: vec![],
|
||||
};
|
||||
texts.frame(0).unwrap()
|
||||
|
||||
@@ -184,10 +184,10 @@ impl ReadText {
|
||||
self.texts.get_or_insert_with(|| Texts::read(data)).as_ref()
|
||||
}
|
||||
|
||||
/// [`Self::texts`] with its characters painted by `patterns` ([`Texts::with_patterns`]).
|
||||
fn texts_with(&mut self, data: &[u8], patterns: std::collections::HashMap<String, vectorcraft_color::Paint>) -> Option<&Texts> {
|
||||
/// [`Self::texts`] with its characters painted by `paints` ([`Texts::with_paints`]).
|
||||
fn texts_with(&mut self, data: &[u8], paints: std::collections::HashMap<String, vectorcraft_color::Paint>) -> Option<&Texts> {
|
||||
self.forget_in_tests();
|
||||
let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_patterns(patterns));
|
||||
let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_paints(paints));
|
||||
self.texts.insert(texts).as_ref()
|
||||
}
|
||||
}
|
||||
@@ -336,7 +336,7 @@ pub(super) fn build_weighing(
|
||||
placed_pages,
|
||||
envelopes_drawn,
|
||||
styles_read,
|
||||
text_patterns,
|
||||
text_paints,
|
||||
canvas_scale,
|
||||
symbols_own_size,
|
||||
xml_ids,
|
||||
@@ -497,7 +497,7 @@ pub(super) fn build_weighing(
|
||||
// The page's type that needs no text object of the layers: the layers' own legacy text, or
|
||||
// placed files that show it.
|
||||
let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?;
|
||||
let texts = text.texts_with(data, text_patterns);
|
||||
let texts = text.texts_with(data, text_paints);
|
||||
// Each story is read once, however many text objects name it.
|
||||
let mut read: std::collections::BTreeMap<u32, Option<Arc<Story>>> = Default::default();
|
||||
let stories: Vec<Option<Arc<Story>>> = infos
|
||||
|
||||
@@ -3755,6 +3755,85 @@ fn type_painted_with_a_pattern_takes_it_from_the_art_style_its_paint_names() {
|
||||
assert_eq!(r.document.pattern("Dots").map(|p| p.tile.height()), Some(4.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_set_in_a_spot_ink_takes_it_from_the_art_style_its_paint_names() {
|
||||
// GUARDS: type set in a spot ink or a global process colour came in as a process colour, so it
|
||||
// printed on the process plates (and white type on none): the text document keeps only the
|
||||
// colour's process values at its tint, and the ink's name and tint are in the art style that
|
||||
// key 5 of the paint names, a style of one paint (`/SimpleStyle`), its fill's for a stroke too.
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let simple = |name: &str, paint: &str| {
|
||||
format!(
|
||||
"/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n0 O\n{paint}\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 1 Xd\n/Paint ;\n /Def ;\n"
|
||||
)
|
||||
};
|
||||
let styles = [
|
||||
simple("Anon 1", "0 0 0 0 (White Ink) 0 x"),
|
||||
simple("Anon 2", "0 1 1 0 (Red Ink) 0.4 x"),
|
||||
simple("Anon 3", "0 0 0 0 1 1 1 (Chalk) 0 1 Xx"),
|
||||
simple("Anon 4", "0 0.5 1 0 (Brand Orange) 0 0 Xk"),
|
||||
// Styles that give no swatch colour: a process colour, a stroke's colour after the fill's.
|
||||
simple("Anon 5", "0 1 1 0 k"),
|
||||
simple("Anon 6", "0 0 0 0 (Stray Ink) 0 x\n0 0 0 1 K"),
|
||||
]
|
||||
.concat();
|
||||
let styles = format!("%AI9_BeginArtStyles\n{styles}%AI9_EndArtStyles\n");
|
||||
let doc = text_document(&[("abcdefghijklmn\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]);
|
||||
let one = "<< /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 /53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> >> >> >> /1 15 >>";
|
||||
assert!(doc.contains(one));
|
||||
// Each paint keeps the process values of its colour at its tint, as the files do.
|
||||
let cmyk = |v: &str, style: &str| format!("<< /99 /CAITextPaint /5 ({style}) /0 << /0 2 /1 [ 1.0 {v} ] >> >>");
|
||||
let rgb = |v: &str, style: &str| format!("<< /99 /CAITextPaint /5 ({style}) /0 << /0 1 /1 [ 1.0 {v} ] >> >>");
|
||||
let run = |own: &str| format!("<< /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 {own} >> >> >> /1 2 >>");
|
||||
let white = cmyk("0.0 0.0 0.0 0.0", "Anon 1");
|
||||
let runs = [
|
||||
run(&format!("/53 {white}")),
|
||||
run(&format!("/53 {}", cmyk("0.0 .6 .6 0.0", "Anon 2"))),
|
||||
run(&format!("/53 {}", rgb("1.0 1.0 1.0", "Anon 3"))),
|
||||
run(&format!("/53 {}", cmyk("0.0 .5 1.0 0.0", "Anon 4"))),
|
||||
run(&format!("/53 {} /57 true /54 {white} /63 2.0", cmyk("0.0 1.0 1.0 0.0", "Anon 5"))),
|
||||
run(&format!("/53 {}", cmyk("0.0 0.0 0.0 0.0", "Anon 6"))),
|
||||
// A style the file doesn't have, over "m", "n" and the story's end.
|
||||
run(&format!("/53 {}", cmyk("0.0 0.0 0.0 1.0", "Anon 7"))).replace("/1 2 >>", "/1 3 >>"),
|
||||
];
|
||||
let doc = doc.replacen(one, &runs.join(" "), 1);
|
||||
// The art beside the type paints with one of the inks too: the type's is the same swatch.
|
||||
let spare = format!("0 1 1 0 (Red Ink) 0 x\n{}\n{}", square_path(30, 30), text_object(0));
|
||||
let art = native_with_text(&format!("{styles}{}{}", layer("Back", true, &square(10, 10)), layer("Spare", false, &spare)), &doc);
|
||||
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
|
||||
let texts = text_of(&r.document.layers[1]);
|
||||
assert_eq!(texts.len(), 1, "{:?}", r.warnings);
|
||||
// Each character's fill and stroke: the swatch it is linked to at its tint, else "process".
|
||||
let paint = |p: &Paint| match p {
|
||||
Paint::Solid { swatch: Some(name), tint, .. } => format!("{name} at {:.0} %", tint * 100.0),
|
||||
Paint::Solid { swatch: None, .. } => "process".into(),
|
||||
Paint::None => "none".into(),
|
||||
other => format!("{other:?}"),
|
||||
};
|
||||
let chars: Vec<(char, String, String)> =
|
||||
texts[0].runs.iter().flat_map(|r| r.text.chars().map(|c| (c, paint(&r.style.fill), paint(&r.style.stroke))).collect::<Vec<_>>()).collect();
|
||||
let want = |c: char, fill: &str, stroke: &str| (c, fill.to_string(), stroke.to_string());
|
||||
let mut expected = vec![];
|
||||
expected.extend(['a', 'b'].map(|c| want(c, "White Ink at 100 %", "none")));
|
||||
expected.extend(['c', 'd'].map(|c| want(c, "Red Ink at 60 %", "none")));
|
||||
expected.extend(['e', 'f'].map(|c| want(c, "Chalk at 100 %", "none")));
|
||||
expected.extend(['g', 'h'].map(|c| want(c, "Brand Orange at 100 %", "none")));
|
||||
expected.extend(['i', 'j'].map(|c| want(c, "process", "White Ink at 100 %")));
|
||||
expected.extend("klmn".chars().map(|c| want(c, "process", "none")));
|
||||
assert_eq!(chars, expected);
|
||||
// The tinted ink draws as its tint, the colour the text document keeps for it.
|
||||
let red = texts[0].runs.iter().find(|r| r.text.starts_with('c')).and_then(|r| r.style.fill.color());
|
||||
assert_eq!(red, Some(Color::cmyk(0.0, 1.0, 1.0, 0.0).tinted(0.6)));
|
||||
// The inks are the document's spot swatches, each once, and the global colour a process one.
|
||||
let swatch = |name: &str| r.document.swatches_iter().filter(|s| s.name == name).map(|s| (s.spot, s.global)).collect::<Vec<_>>();
|
||||
for ink in ["White Ink", "Red Ink", "Chalk"] {
|
||||
assert_eq!(swatch(ink), [(true, true)], "{ink}");
|
||||
}
|
||||
assert_eq!(swatch("Brand Orange"), [(false, true)]);
|
||||
assert_eq!(r.document.swatch("White Ink").and_then(|s| s.paint.color()), Some(Color::cmyk(0.0, 0.0, 0.0, 0.0)));
|
||||
assert_eq!(r.document.swatch("Chalk").and_then(|s| s.paint.color()), Some(Color::rgb(1.0, 1.0, 1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_keeps_its_manual_kerning() {
|
||||
// GUARDS: the text document's manual kerning (key 8 of a story's text: runs of characters, each
|
||||
|
||||
+43
-12
@@ -673,9 +673,9 @@ impl PathData {
|
||||
/// segment with a control point that is not finite or past `f64::MAX / 16` in x or y is measured
|
||||
/// by its control points.
|
||||
///
|
||||
/// Walks the segments in place, without building the path: the same segments in the same order,
|
||||
/// so the result is bit for bit `curve_bounds(&self.to_bezpath())` (a path of lone anchors, with
|
||||
/// no segment, is `Rect::ZERO`, as there).
|
||||
/// Walks the segments in place, without building the path: the same segments in the same order
|
||||
/// as `curve_bounds(&self.to_bezpath())`. A subpath of one anchor has no segment, and the box
|
||||
/// also holds that anchor's point, so a path of lone anchors measures the box around them.
|
||||
pub fn bounds(&self) -> Option<Rect> {
|
||||
if self.is_empty() {
|
||||
return None;
|
||||
@@ -685,8 +685,26 @@ impl PathData {
|
||||
{
|
||||
return Some(Rect::from_points(a.p, a.p));
|
||||
}
|
||||
Some(self.measured(|_| true).unwrap_or_default())
|
||||
}
|
||||
/// The box of what a stroke along the path draws, before the stroke's own reach: its segments,
|
||||
/// as in [`PathData::bounds`], and the lone anchors a stroke draws. A lone anchor of an open
|
||||
/// subpath draws nothing. A lone anchor of a closed subpath draws a dot when `dots` is set, as
|
||||
/// a round or projecting cap does, and nothing otherwise. `None` when the path draws nothing.
|
||||
pub fn drawn_bounds(&self, dots: bool) -> Option<Rect> {
|
||||
self.measured(|sp| dots && sp.closed)
|
||||
}
|
||||
/// The box of the segments and of the lone anchors of the subpaths `lone` keeps.
|
||||
fn measured(&self, lone: impl Fn(&SubPath) -> bool) -> Option<Rect> {
|
||||
let mut bbox: Option<Rect> = None;
|
||||
for sp in &self.subpaths {
|
||||
if sp.segment_count() == 0
|
||||
&& lone(sp)
|
||||
&& let Some(a) = sp.anchors.first()
|
||||
{
|
||||
let lone = Rect::from_points(a.p, a.p);
|
||||
bbox = Some(bbox.map_or(lone, |bb| bb.union(lone)));
|
||||
}
|
||||
MEASURED_SEGMENTS.set(MEASURED_SEGMENTS.get().saturating_add(sp.segment_count() as u64));
|
||||
for i in 0..sp.segment_count() {
|
||||
let c = sp.segment(i);
|
||||
@@ -704,7 +722,7 @@ impl PathData {
|
||||
bbox = Some(bbox.map_or(seg, |bb| bb.union(seg)));
|
||||
}
|
||||
}
|
||||
Some(bbox.unwrap_or_default())
|
||||
bbox
|
||||
}
|
||||
/// Bounds including control handles (used for quick culling).
|
||||
pub fn control_bounds(&self) -> Option<Rect> {
|
||||
@@ -873,7 +891,8 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `bounds` walks the anchors in place: bit for bit what the kurbo path it stands for gives,
|
||||
/// for lines, curves, open and closed subpaths, lone anchors and empty subpaths.
|
||||
/// joined with the point of each lone anchor, for lines, curves, open and closed subpaths, lone
|
||||
/// anchors and empty subpaths.
|
||||
#[test]
|
||||
fn bounds_match_the_bezpath_bit_for_bit() {
|
||||
use proptest::prelude::*;
|
||||
@@ -881,11 +900,10 @@ mod tests {
|
||||
if pd.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if pd.anchor_count() == 1 {
|
||||
let a = pd.subpaths.iter().find_map(|s| s.anchors.first())?;
|
||||
return Some(Rect::from_points(a.p, a.p));
|
||||
}
|
||||
Some(curve_bounds(&pd.to_bezpath()))
|
||||
let bp = pd.to_bezpath();
|
||||
let segments = bp.segments().next().is_some().then(|| curve_bounds(&bp));
|
||||
let lone = pd.subpaths.iter().filter(|s| s.segment_count() == 0).filter_map(|s| s.anchors.first()).map(|a| Rect::from_points(a.p, a.p));
|
||||
lone.chain(segments).reduce(|bb, r| bb.union(r))
|
||||
}
|
||||
let bits = |r: Option<Rect>| r.map(|r| [r.x0, r.y0, r.x1, r.y1].map(f64::to_bits));
|
||||
let coord = || prop_oneof![(-1e3f64..1e3), Just(0.0), Just(1e-300), Just(-7.25)];
|
||||
@@ -899,10 +917,23 @@ mod tests {
|
||||
proptest!(ProptestConfig::with_cases(2000), |(pd in path)| {
|
||||
prop_assert_eq!(bits(pd.bounds()), bits(reference(&pd)));
|
||||
});
|
||||
// Two lone anchors: no segment, as the path has none.
|
||||
// Two lone anchors: the path has no segment, and the box spans the two points.
|
||||
let lone = PathData::new(vec![SubPath::polyline(&[Point::new(5.0, 5.0)], false), SubPath::polyline(&[Point::new(9.0, 1.0)], true)]);
|
||||
assert_eq!(lone.bounds(), Some(Rect::ZERO));
|
||||
assert_eq!(lone.bounds(), Some(Rect::new(5.0, 1.0, 9.0, 5.0)));
|
||||
assert_eq!(bits(lone.bounds()), bits(reference(&lone)));
|
||||
// A lone anchor beside a segment widens the segment's box to reach it.
|
||||
let line = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(4.0, 2.0)], false);
|
||||
let beside = PathData::new(vec![line.clone(), SubPath::polyline(&[Point::new(20.0, -3.0)], false)]);
|
||||
let segment_only = PathData::single(line).bounds().unwrap_or_default();
|
||||
let both = beside.bounds().unwrap_or_default();
|
||||
assert!(both.x1 >= 20.0 && both.y0 <= -3.0, "{both:?} leaves out the lone anchor at (20, -3)");
|
||||
assert_eq!(both.union(segment_only), both, "{both:?} leaves out part of the segment's box {segment_only:?}");
|
||||
// What a stroke draws leaves out the open lone anchor, and a closed one without dots.
|
||||
assert_eq!(beside.drawn_bounds(true), Some(segment_only), "an open lone anchor draws nothing");
|
||||
let dot = PathData::new(vec![beside.subpaths[0].clone(), SubPath::polyline(&[Point::new(20.0, -3.0)], true)]);
|
||||
assert_eq!(dot.drawn_bounds(true), dot.bounds(), "a closed lone anchor draws a dot");
|
||||
assert_eq!(dot.drawn_bounds(false), Some(segment_only), "without dots, a closed lone anchor draws nothing");
|
||||
assert_eq!(lone.drawn_bounds(false), None, "lone anchors alone draw nothing");
|
||||
// A NaN anchor differs from itself: kurbo closes such a subpath with a line of its own.
|
||||
let nan = Point::new(f64::NAN, 1.0);
|
||||
let closed = |pts: &[Point]| SubPath::polyline(pts, true);
|
||||
|
||||
@@ -470,6 +470,36 @@ fn property_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsRe
|
||||
if matches!(v, Value::Undefined) { Ok(Value::str("")) } else { Ok(Value::String(i.to_str(&v)?)) }
|
||||
}
|
||||
|
||||
fn property_parts(value: &xmp::Value, item: Option<usize>) -> Option<(Option<&str>, u32, &str)> {
|
||||
match item {
|
||||
None => Some((value.text(), value.options(), "")),
|
||||
Some(index) => match value {
|
||||
xmp::Value::Array { items, .. } => {
|
||||
items.get(index).map(|item| (Some(item.text.as_str()), item.options(), item.lang.as_deref().unwrap_or("")))
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn property_at(i: &mut Interp, o: ObjId, at: usize, item: Option<usize>, ns: &str, path: &str) -> JsResult<Value> {
|
||||
let scan_bytes = match (&meta_of(i, o)?.props[at].value, item) {
|
||||
(xmp::Value::Array { form: Form::Alt, items }, None) => items.len().saturating_mul(std::mem::size_of::<Item>()).saturating_mul(2),
|
||||
_ => 0,
|
||||
};
|
||||
if scan_bytes != 0 {
|
||||
spend(i, scan_bytes)?;
|
||||
}
|
||||
let bytes = {
|
||||
let Some((text, _, locale)) = property_parts(&meta_of(i, o)?.props[at].value, item) else { return Ok(Value::Undefined) };
|
||||
text.map_or(0, str::len).saturating_add(locale.len())
|
||||
};
|
||||
spend(i, bytes.saturating_mul(4))?;
|
||||
let Some((text, options, locale)) = property_parts(&meta_of(i, o)?.props[at].value, item) else { return Ok(Value::Undefined) };
|
||||
let (text, locale) = (text.map(str::to_owned), locale.to_owned());
|
||||
property(i, ns, path, text.as_deref(), options, &locale)
|
||||
}
|
||||
|
||||
fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let what = "XMPMeta.getProperty";
|
||||
let o = this_meta(i, &this, what)?;
|
||||
@@ -480,22 +510,20 @@ fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul
|
||||
}
|
||||
let found = {
|
||||
let m = meta_of(i, o)?;
|
||||
match m.find(&ns, &name).map(|at| &m.props[at].value) {
|
||||
match m.find(&ns, &name) {
|
||||
None => Ok(None),
|
||||
Some(value) => match step {
|
||||
Step::Whole => Ok(Some((value.text().map(str::to_string), value.options(), String::new()))),
|
||||
Step::Item(index) => match value {
|
||||
xmp::Value::Array { items, .. } => Ok(position(index, items.len())
|
||||
.and_then(|p| items.get(p))
|
||||
.map(|item| (Some(item.text.clone()), item.options(), item.lang.clone().unwrap_or_default()))),
|
||||
Some(at) => match step {
|
||||
Step::Whole => Ok(Some((at, None))),
|
||||
Step::Item(index) => match &m.props[at].value {
|
||||
xmp::Value::Array { items, .. } => Ok(position(index, items.len()).map(|p| (at, Some(p)))),
|
||||
_ => Err(()),
|
||||
},
|
||||
},
|
||||
}
|
||||
};
|
||||
let found = found.map_err(|()| not_array(i, what, &name))?;
|
||||
let Some((text, options, locale)) = found else { return Ok(Value::Undefined) };
|
||||
property(i, &ns, &path, text.as_deref(), options, &locale)
|
||||
let Some((at, item)) = found else { return Ok(Value::Undefined) };
|
||||
property_at(i, o, at, item, &ns, &path)
|
||||
}
|
||||
|
||||
fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
@@ -629,13 +657,8 @@ fn get_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRes
|
||||
let index = item_index(i, &arg(args, 2), what)?;
|
||||
let Some((at, _, len)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) };
|
||||
let Some(p) = position(index, len) else { return Ok(Value::Undefined) };
|
||||
let item = match &meta_of(i, o)?.props[at].value {
|
||||
xmp::Value::Array { items, .. } => items.get(p).cloned(),
|
||||
_ => None,
|
||||
};
|
||||
let Some(item) = item else { return Ok(Value::Undefined) };
|
||||
let path = format!("{path}[{}]", p + 1);
|
||||
property(i, &ns, &path, Some(&item.text), item.options(), item.lang.as_deref().unwrap_or(""))
|
||||
property_at(i, o, at, Some(p), &ns, &path)
|
||||
}
|
||||
|
||||
fn does_array_item_exist(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
@@ -803,13 +826,13 @@ fn generic_lang(lang: Option<&str>, generic: &str) -> bool {
|
||||
|
||||
/// The item of `items` for `specific`, else one whose language starts with `generic`, else the
|
||||
/// `x-default` item, else the first.
|
||||
fn pick_lang<'a>(items: &'a [Item], generic: &str, specific: &str) -> Option<&'a Item> {
|
||||
fn pick_lang(items: &[Item], generic: &str, specific: &str) -> Option<usize> {
|
||||
items
|
||||
.iter()
|
||||
.find(|i| same_lang(i.lang.as_deref(), specific))
|
||||
.or_else(|| items.iter().find(|i| generic_lang(i.lang.as_deref(), generic)))
|
||||
.or_else(|| items.iter().find(|i| same_lang(i.lang.as_deref(), "x-default")))
|
||||
.or_else(|| items.first())
|
||||
.position(|i| same_lang(i.lang.as_deref(), specific))
|
||||
.or_else(|| items.iter().position(|i| generic_lang(i.lang.as_deref(), generic)))
|
||||
.or_else(|| items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default")))
|
||||
.or_else(|| (!items.is_empty()).then_some(0))
|
||||
}
|
||||
|
||||
/// A language argument: `null` and `undefined` are empty.
|
||||
@@ -843,11 +866,11 @@ fn get_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J
|
||||
return Err(not_alt_text(i, what, &name));
|
||||
}
|
||||
let found = match &meta_of(i, o)?.props[at].value {
|
||||
xmp::Value::Array { items, .. } => pick_lang(items, &generic, &specific).cloned(),
|
||||
xmp::Value::Array { items, .. } => pick_lang(items, &generic, &specific),
|
||||
_ => None,
|
||||
};
|
||||
match found {
|
||||
Some(item) => property(i, "", "", Some(&item.text), item.options(), item.lang.as_deref().unwrap_or("")),
|
||||
Some(item) => property_at(i, o, at, Some(item), "", ""),
|
||||
None => Ok(Value::Undefined),
|
||||
}
|
||||
}
|
||||
@@ -1477,6 +1500,55 @@ mod namespace_heap_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_property_values_charge_for_copying_their_text() {
|
||||
let mut interp = Interp::new(crate::Options::default(), crate::Limits::default());
|
||||
install(&mut interp).unwrap();
|
||||
let text = "x".repeat(1024 * 1024);
|
||||
let value = new_meta(
|
||||
&mut interp,
|
||||
Meta {
|
||||
props: vec![
|
||||
xmp::Prop { ns: xmp::DC.into(), name: "value".into(), value: xmp::Value::Simple { text: text.clone(), uri: false } },
|
||||
xmp::Prop {
|
||||
ns: xmp::DC.into(),
|
||||
name: "items".into(),
|
||||
value: xmp::Value::Array { form: Form::Alt, items: vec![Item { text, lang: Some("en-US".into()) }] },
|
||||
},
|
||||
],
|
||||
..Meta::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
interp
|
||||
.rooted(std::slice::from_ref(&value), |interp| {
|
||||
let mut limited = Vec::new();
|
||||
for fuel in [1_000, 100_000] {
|
||||
for getter in 0..3 {
|
||||
interp.fuel = fuel;
|
||||
let result = match getter {
|
||||
0 => get_property(interp, value.clone(), &[Value::str(xmp::DC), Value::str("value")], false),
|
||||
1 => get_array_item(interp, value.clone(), &[Value::str(xmp::DC), Value::str("items"), Value::Number(1.0)], false),
|
||||
_ => get_localized_text(
|
||||
interp,
|
||||
value.clone(),
|
||||
&[Value::str(xmp::DC), Value::str("items"), Value::str("fr"), Value::str("fr-FR")],
|
||||
false,
|
||||
),
|
||||
};
|
||||
if fuel == 1_000 {
|
||||
limited.push(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))));
|
||||
} else {
|
||||
assert!(result.is_ok(), "getter {getter} failed with sufficient fuel");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(limited, [true; 3]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn localized_text_lookup_charges_for_language_scans() {
|
||||
let mut interp = Interp::new(crate::Options::default(), crate::Limits::default());
|
||||
@@ -1499,8 +1571,12 @@ mod namespace_heap_tests {
|
||||
interp.fuel = 1_000;
|
||||
let result = get_localized_text(interp, value.clone(), &args, false);
|
||||
assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))), "{result:?}");
|
||||
interp.fuel = 1_000;
|
||||
let result = get_property(interp, value.clone(), &args[..2], false);
|
||||
assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))), "whole-array options did not charge for their scan");
|
||||
interp.fuel = 1_000_000;
|
||||
assert!(get_localized_text(interp, value.clone(), &args, false).is_ok());
|
||||
assert!(get_property(interp, value.clone(), &args[..2], false).is_ok());
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::net::{SocketAddr, ToSocketAddrs};
|
||||
|
||||
use craft::automation::args::{ControlOptions, EnvNames};
|
||||
use craft::automation::client::ControlClient;
|
||||
use craft::automation::client::{ConnectError, ControlClient};
|
||||
use serde_json::Value;
|
||||
|
||||
/// Something that answers control-channel methods (`engine.execute`, `document.inspect`,
|
||||
@@ -35,22 +35,31 @@ pub fn control_token() -> Result<String, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens and signs in one control connection; [`ControlClient::connect`] outside tests.
|
||||
pub(crate) type Connect = fn(SocketAddr, &str) -> Result<ControlClient, ConnectError>;
|
||||
|
||||
/// A running VectorCraft app, reached through its loopback control port.
|
||||
pub struct Remote {
|
||||
addr: String,
|
||||
sock: SocketAddr,
|
||||
token: String,
|
||||
client: Option<ControlClient>,
|
||||
connect: Connect,
|
||||
}
|
||||
|
||||
impl Remote {
|
||||
/// Connect to `addr` (e.g. `127.0.0.1:7979`) with the app's control `token`, failing fast when
|
||||
/// nothing is listening.
|
||||
pub fn connect(addr: &str, token: &str) -> std::io::Result<Self> {
|
||||
Self::connect_with(addr, token, ControlClient::connect)
|
||||
}
|
||||
|
||||
/// [`Remote::connect`], opening this connection and every reconnect with `connect`, one attempt each.
|
||||
pub(crate) fn connect_with(addr: &str, token: &str, connect: Connect) -> std::io::Result<Self> {
|
||||
let sock =
|
||||
addr.to_socket_addrs()?.next().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {addr}")))?;
|
||||
let client = ControlClient::connect(sock, token).map_err(std::io::Error::other)?;
|
||||
Ok(Self { addr: addr.to_string(), sock, token: token.to_string(), client: Some(client) })
|
||||
let client = connect(sock, token).map_err(std::io::Error::other)?;
|
||||
Ok(Self { addr: addr.to_string(), sock, token: token.to_string(), client: Some(client), connect })
|
||||
}
|
||||
|
||||
pub fn addr(&self) -> &str {
|
||||
@@ -67,7 +76,7 @@ impl Remote {
|
||||
fn open_client(&mut self, method: &str) -> Result<&mut ControlClient, String> {
|
||||
if !self.client.as_ref().is_some_and(ControlClient::is_usable) {
|
||||
self.client = None;
|
||||
let client = ControlClient::connect(self.sock, &self.token)
|
||||
let client = (self.connect)(self.sock, &self.token)
|
||||
.map_err(|e| format!("VectorCraft app at {} is not reachable: {e}; `{method}`: nothing was sent", self.addr))?;
|
||||
self.client = Some(client);
|
||||
}
|
||||
|
||||
+30
-15
@@ -20,12 +20,12 @@ use std::io::BufRead;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::SyncSender;
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::cancel::CancelToken;
|
||||
|
||||
use crate::server::{INVALID_REQUEST, MAX_LINE_BYTES, PARSE_ERROR, SERVER_BUSY, error, error_with, read_line_capped};
|
||||
use crate::server::{Clock, INVALID_REQUEST, MAX_LINE_BYTES, PARSE_ERROR, SERVER_BUSY, error, error_with, read_line_capped};
|
||||
|
||||
/// Most lines waiting for the engine. Past this the reader waits (it still reads nothing else).
|
||||
pub(crate) const MAX_QUEUED: usize = 64;
|
||||
@@ -55,7 +55,8 @@ struct Running {
|
||||
method: String,
|
||||
token: CancelToken,
|
||||
label: String,
|
||||
since: Instant,
|
||||
/// When it started, on [`Shared`]'s clock.
|
||||
since: Duration,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -66,6 +67,9 @@ struct State {
|
||||
eof: bool,
|
||||
/// The output failed: nobody reads replies any more.
|
||||
closed: bool,
|
||||
/// How often the reader found [`MAX_QUEUED`] lines queued and waited for room.
|
||||
#[cfg(test)]
|
||||
waits_for_room: usize,
|
||||
}
|
||||
|
||||
/// What the reader and the engine thread share.
|
||||
@@ -75,6 +79,7 @@ pub(crate) struct Shared {
|
||||
/// Whether the client speaks the `2026-07-28` revision, for results answered by the reader.
|
||||
pub(crate) modern: Arc<AtomicBool>,
|
||||
busy_after: Duration,
|
||||
clock: Clock,
|
||||
}
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
@@ -83,8 +88,8 @@ fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
pub(crate) fn new(modern: Arc<AtomicBool>, busy_after: Duration) -> Self {
|
||||
Self { state: Mutex::new(State::default()), wake: Condvar::new(), modern, busy_after }
|
||||
pub(crate) fn new(modern: Arc<AtomicBool>, busy_after: Duration, clock: Clock) -> Self {
|
||||
Self { state: Mutex::new(State::default()), wake: Condvar::new(), modern, busy_after, clock }
|
||||
}
|
||||
|
||||
/// The next job, or `None` once the transport is done and the queue empty (or the output
|
||||
@@ -102,7 +107,7 @@ impl Shared {
|
||||
method: m.method.clone(),
|
||||
token: m.token.clone(),
|
||||
label: m.label.clone(),
|
||||
since: Instant::now(),
|
||||
since: (self.clock)(),
|
||||
});
|
||||
}
|
||||
// The reader may be waiting for room.
|
||||
@@ -145,7 +150,7 @@ impl Shared {
|
||||
/// pipelined neighbour fail).
|
||||
fn long_running(&self, st: &State) -> Option<Value> {
|
||||
let r = st.running.as_ref()?;
|
||||
let secs = r.since.elapsed();
|
||||
let secs = (self.clock)().saturating_sub(r.since);
|
||||
// A long id isn't repeated: every busy reply would carry it twice.
|
||||
let key = r.key.as_deref().filter(|k| k.len() <= MAX_ECHOED_ID);
|
||||
(secs >= self.busy_after).then(|| json!({"running": r.label, "requestId": key, "seconds": secs.as_secs()}))
|
||||
@@ -236,6 +241,11 @@ fn submit_canned(shared: &Shared, out: &SyncSender<String>, reply: String) {
|
||||
if st.queue.len() < MAX_QUEUED {
|
||||
break;
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
st.waits_for_room += 1;
|
||||
shared.wake.notify_all();
|
||||
}
|
||||
// Wake now and then: the call ahead may turn long-running while the queue is full.
|
||||
st = shared.wake.wait_timeout(st, Duration::from_millis(50)).unwrap_or_else(PoisonError::into_inner).0;
|
||||
}
|
||||
@@ -289,6 +299,11 @@ fn intake(shared: &Shared, out: &SyncSender<String>, line: &str) {
|
||||
if st.queue.len() < MAX_QUEUED {
|
||||
break;
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
st.waits_for_room += 1;
|
||||
shared.wake.notify_all();
|
||||
}
|
||||
// Wake now and then: the call that fills the queue may be the one that turns it away.
|
||||
st = shared.wake.wait_timeout(st, Duration::from_millis(50)).unwrap_or_else(PoisonError::into_inner).0;
|
||||
}
|
||||
@@ -331,20 +346,20 @@ mod tests {
|
||||
#[test]
|
||||
fn parse_errors_wait_for_room_in_the_queue() {
|
||||
// No call has run past the busy limit, so the replies queue rather than go out at once.
|
||||
let shared = Shared::new(Arc::new(AtomicBool::new(false)), Duration::from_secs(60));
|
||||
let shared = Shared::new(Arc::new(AtomicBool::new(false)), Duration::from_secs(60), Arc::new(|| Duration::ZERO));
|
||||
let (out, _replies) = std::sync::mpsc::sync_channel(1);
|
||||
let lines = 3 * MAX_QUEUED;
|
||||
let input = "not json\n".repeat(lines);
|
||||
std::thread::scope(|scope| {
|
||||
let reader = scope.spawn(|| read_loop(&shared, &out, input.as_bytes()));
|
||||
// Nothing takes jobs off the queue yet, so the reader stops at the limit.
|
||||
let end = Instant::now() + Duration::from_secs(10);
|
||||
while !reader.is_finished() && lock(&shared.state).queue.len() < MAX_QUEUED && Instant::now() < end {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
// Nothing takes jobs off the queue yet, so the reader stops at the limit and waits.
|
||||
let mut st = lock(&shared.state);
|
||||
while st.waits_for_room == 0 && !st.eof {
|
||||
st = shared.wake.wait(st).unwrap_or_else(PoisonError::into_inner);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
let queued = lock(&shared.state).queue.len();
|
||||
assert!(queued <= MAX_QUEUED, "{queued} lines queued, more than {MAX_QUEUED}");
|
||||
let queued = st.queue.len();
|
||||
assert_eq!(queued, MAX_QUEUED, "the reader waited with {queued} lines queued, not {MAX_QUEUED}");
|
||||
drop(st);
|
||||
// Once the engine takes jobs, every line is answered with its parse error.
|
||||
let mut answered = 0;
|
||||
while let Some(job) = shared.next() {
|
||||
|
||||
@@ -50,24 +50,33 @@ const OUTBOX: usize = 256;
|
||||
/// Fewest time between two `notifications/progress` of one request, the last one excepted.
|
||||
const PROGRESS_EVERY: Duration = Duration::from_millis(200);
|
||||
|
||||
/// The time since a fixed start, for the busy limit and the progress throttle.
|
||||
pub(crate) type Clock = Arc<dyn Fn() -> Duration + Send + Sync>;
|
||||
|
||||
fn system_clock() -> Clock {
|
||||
let origin = Instant::now();
|
||||
Arc::new(move || origin.elapsed())
|
||||
}
|
||||
|
||||
/// The sink that turns the engine's progress into `notifications/progress` for the request
|
||||
/// `msg`, when the client asked for it with `_meta.progressToken`.
|
||||
/// <https://modelcontextprotocol.io/specification/2025-06-18/basic/utilities/progress>
|
||||
fn progress_sink(out: SyncSender<String>, msg: &Value) -> Option<cancel::ProgressSink> {
|
||||
fn progress_sink(out: SyncSender<String>, msg: &Value, clock: Clock) -> Option<cancel::ProgressSink> {
|
||||
let token = msg.get("params")?.get("_meta")?.get("progressToken").filter(|t| t.is_string() || t.is_number())?.clone();
|
||||
let last = Cell::new(None::<u64>);
|
||||
let at = Cell::new(None::<Instant>);
|
||||
let at = Cell::new(None::<Duration>);
|
||||
Some(Rc::new(move |done, total, what| {
|
||||
// `progress` must increase with each notification.
|
||||
if last.get().is_some_and(|l| done <= l) {
|
||||
return;
|
||||
}
|
||||
let finished = total > 0 && done >= total;
|
||||
if !finished && at.get().is_some_and(|t| t.elapsed() < PROGRESS_EVERY) {
|
||||
let now = clock();
|
||||
if !finished && at.get().is_some_and(|t| now.saturating_sub(t) < PROGRESS_EVERY) {
|
||||
return;
|
||||
}
|
||||
last.set(Some(done));
|
||||
at.set(Some(Instant::now()));
|
||||
at.set(Some(now));
|
||||
let mut params = json!({"progressToken": token, "progress": done, "message": what});
|
||||
if total > 0 {
|
||||
params["total"] = json!(total);
|
||||
@@ -98,6 +107,7 @@ pub struct Server {
|
||||
/// process-wide, so a server whose client didn't ask leaves it to the one that did.
|
||||
logging: bool,
|
||||
busy_after: Duration,
|
||||
clock: Clock,
|
||||
}
|
||||
|
||||
pub(crate) fn response(id: Value, result: Value) -> Value {
|
||||
@@ -225,7 +235,14 @@ fn write_reply(output: &mut impl Write, line: &str) -> std::io::Result<()> {
|
||||
|
||||
impl Server {
|
||||
pub fn new(backend: Box<dyn Backend>) -> Self {
|
||||
Self { backend, initialized: false, modern: Arc::new(AtomicBool::new(false)), logging: false, busy_after: DEFAULT_BUSY_AFTER }
|
||||
Self {
|
||||
backend,
|
||||
initialized: false,
|
||||
modern: Arc::new(AtomicBool::new(false)),
|
||||
logging: false,
|
||||
busy_after: DEFAULT_BUSY_AFTER,
|
||||
clock: system_clock(),
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a call runs before [`Server::serve`] turns away a request that would have to wait
|
||||
@@ -236,6 +253,13 @@ impl Server {
|
||||
self
|
||||
}
|
||||
|
||||
/// The clock that [`Server::serve`] measures the busy limit and the progress throttle on.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_clock(mut self, clock: Clock) -> Self {
|
||||
self.clock = clock;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn backend(&mut self) -> &mut dyn Backend {
|
||||
self.backend.as_mut()
|
||||
}
|
||||
@@ -275,7 +299,7 @@ impl Server {
|
||||
/// (the running call is then cancelled and the queue dropped; the reader thread ends with its
|
||||
/// next line, which a client that closed our output closes as well).
|
||||
pub fn serve<R: BufRead + Send, W: Write + Send>(&mut self, input: R, mut output: W) -> std::io::Result<()> {
|
||||
let shared = Shared::new(self.modern.clone(), self.busy_after);
|
||||
let shared = Shared::new(self.modern.clone(), self.busy_after, self.clock.clone());
|
||||
let shared = &shared;
|
||||
let (tx, rx) = sync_channel::<String>(OUTBOX);
|
||||
let reader_tx = tx.clone();
|
||||
@@ -323,7 +347,7 @@ impl Server {
|
||||
|
||||
fn run(&mut self, m: Message, out: &SyncSender<String>) {
|
||||
let Message { value, key, token, .. } = m;
|
||||
let sink = key.is_some().then(|| progress_sink(out.clone(), &value)).flatten();
|
||||
let sink = key.is_some().then(|| progress_sink(out.clone(), &value, self.clock.clone())).flatten();
|
||||
let reply = cancel::scope(&token, sink, || self.handle_parsed(value));
|
||||
// A cancelled request gets no reply (MCP: the receiver should not answer it). A call that
|
||||
// finished before it noticed is dropped the same way: the client has stopped waiting.
|
||||
|
||||
Loaded 100 of 280 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user