mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge main into fix/variables-browser-download
This commit is contained in:
commit
f97f7f7c36
729 files changed
+59925
-5657
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,69 @@ 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 leg starts after `gate / select legs` and a
|
||||
# free runner: the script fails when the leg has not started within 120 minutes, and then waits
|
||||
# up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the
|
||||
# script reports a leg that starts late with its own error before the job times out.
|
||||
cold-cache-clear:
|
||||
name: cold cache clear
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 290
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Delete the old rolling entries before the save
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: python3 scripts/ci-clear-rolling-cache.py
|
||||
@@ -3,13 +3,14 @@ name: Nightly check
|
||||
# The app-side Nightly pieces, checked without a feed run: the Python suites that read the archive,
|
||||
# plist and signing scripts, the workflow contracts, and (on Windows) the packaging and signing
|
||||
# PowerShell suites. The producer itself is .github/workflows/nightly.yml; the Apple-silicon bundle
|
||||
# is built and verified by nightly-macos.yml behind the `full-ci` label.
|
||||
# is built and verified by nightly-macos.yml behind the `full-ci` label. The same job also runs the
|
||||
# suite for scripts/ci-clear-rolling-cache.py, which ci.yml's nightly cold run calls.
|
||||
on:
|
||||
push:
|
||||
branches: [main, release]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"]
|
||||
pull_request:
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -34,6 +35,8 @@ jobs:
|
||||
persist-credentials: false
|
||||
- name: Run the synthetic suites
|
||||
run: python3 packaging/nightly-tests.py
|
||||
- name: Run the cold cache clear suite
|
||||
run: python3 scripts/ci-clear-rolling-cache-tests.py
|
||||
- name: Parse every nightly shell script
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Notify Services on Release Change
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
- unpublished
|
||||
- created
|
||||
- edited
|
||||
- deleted
|
||||
- prereleased
|
||||
- released
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
|
||||
secrets:
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
@@ -33,7 +33,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
|
||||
**Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay.
|
||||
|
||||
**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=<craft-fonts checkout>` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-<family>.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them.
|
||||
**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=<craft-fonts checkout>` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-<family>.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. Desktop builds with a checkout whose opt-in `fonts/latin-manifest.txt` lists Noto Sans Condensed SemiBold (The Noto Project Authors, SIL Open Font License 1.1, from the [notofonts/latin-greek-cyrillic NotoSans-v2.015 release](https://github.com/notofonts/latin-greek-cyrillic/releases/tag/NotoSans-v2.015)) also embed that face, for document tab titles.
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
|
||||
Generated
+220
-106
File diff suppressed because it is too large.
Load diff
+48
-48
@@ -11,44 +11,44 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/vectorcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# Native Affinity documents (craft-libs#914).
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
|
||||
# the members it imports.
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui
|
||||
# without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes.
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -191,25 +191,25 @@ lto = "thin"
|
||||
codegen-units = 1
|
||||
|
||||
[patch.crates-io]
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
@@ -45,6 +45,8 @@ fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.m
|
||||
Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC and Noto Sans Arabic in the current manifest;
|
||||
web builds BIZ UDPGothic Regular only) under the SIL
|
||||
Open Font License 1.1. Their license texts ship with the release packages as OFL-<family>.txt.
|
||||
Desktop builds with a craft-fonts checkout whose fonts/latin-manifest.txt lists Noto Sans Condensed
|
||||
SemiBold (Copyright 2022 The Noto Project Authors, SIL Open Font License 1.1) also embed that face.
|
||||
|
||||
PDF import decodes CJK text with Adobe's CMap resources (https://github.com/adobe-type-tools/cmap-resources),
|
||||
compiled into the app through the hayro-cmap crate under the BSD 3-Clause License:
|
||||
|
||||
@@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged.
|
||||
|
||||
- 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
|
||||
- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
@@ -255,6 +257,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. |
|
||||
| 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (checking #937's fix on the reporter's file, still unconfirmed). Headline numbers unchanged. |
|
||||
| 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). |
|
||||
| 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. |
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "vectorcraft-plugin-worker"
|
||||
description = "The web build's plug-in worker: checks plug-in modules being installed and runs filters off the page"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "vectorcraft-plugin-worker"
|
||||
path = "src/main.rs"
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
vectorcraft-plugins = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["DedicatedWorkerGlobalScope", "MessageEvent"] }
|
||||
@@ -0,0 +1,37 @@
|
||||
//! The web build's plug-in worker ([`vectorcraft_plugins::worker`]). Trunk builds it beside the
|
||||
//! app (`data-type="worker"` in `apps/vectorcraft-web/index.html`), and the page starts one for each
|
||||
//! module it checks and each filter it runs, through the loader Trunk writes for it
|
||||
//! (`vectorcraft-plugin-worker_loader.js`). Each message, both ways, is one `Uint8Array`.
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn main() {
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::prelude::Closure;
|
||||
use web_sys::{DedicatedWorkerGlobalScope, MessageEvent};
|
||||
|
||||
let scope: DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
|
||||
let poster = scope.clone();
|
||||
let post = Rc::new(move |msg: Vec<u8>| {
|
||||
let bytes = js_sys::Uint8Array::from(msg.as_slice());
|
||||
// A message that can't be posted leaves the page waiting, and its time budget ends the run.
|
||||
let _ = poster.post_message_with_transfer(&bytes, &js_sys::Array::of1(&bytes.buffer()));
|
||||
});
|
||||
let worker = Rc::new(RefCell::new(vectorcraft_plugins::worker::Worker::new(post)));
|
||||
let handler = Rc::clone(&worker);
|
||||
let on_message = Closure::<dyn FnMut(MessageEvent)>::new(move |e: MessageEvent| {
|
||||
let msg = js_sys::Uint8Array::new(&e.data()).to_vec();
|
||||
handler.borrow_mut().handle(&msg);
|
||||
});
|
||||
scope.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
|
||||
// The handler lives as long as the worker.
|
||||
on_message.forget();
|
||||
worker.borrow().ready();
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn main() {
|
||||
eprintln!("vectorcraft-plugin-worker only runs in the browser, as the web build's plug-in worker");
|
||||
}
|
||||
@@ -27,10 +27,10 @@ log = { workspace = true }
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlInputElement", "KeyboardEvent", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlInputElement", "KeyboardEvent", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal", "Node", "Worker", "MessageEvent", "ErrorEvent", "Performance"] }
|
||||
@@ -17,6 +17,8 @@
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="icons/32/ai.storyteller.vectorcraft.png">
|
||||
<link rel="apple-touch-icon" href="icons/256/ai.storyteller.vectorcraft.png">
|
||||
<link data-trunk rel="rust" data-bin="vectorcraft-web" data-wasm-opt="z" data-weak-refs />
|
||||
<!-- The plug-in worker: checks plug-ins being installed and runs filters off the page (apps/vectorcraft-plugin-worker). -->
|
||||
<link data-trunk rel="rust" href="../vectorcraft-plugin-worker/Cargo.toml" data-bin="vectorcraft-plugin-worker" data-type="worker" data-loader-shim data-wasm-opt="z" />
|
||||
<style>
|
||||
/* iPad: no page scroll, bounce, pinch zoom, text selection or callout; the app takes the gestures. */
|
||||
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #262626;
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
//! - no TCP control server (browsers can't listen on sockets);
|
||||
//! - File → Open uses the browser file picker, through the host's file service (`BrowserFiles`);
|
||||
//! - Save / Export trigger a browser download;
|
||||
//! - plug-ins are checked when installed, and filters run, in Web Workers of their own
|
||||
//! (`plugin_workers`, the `vectorcraft-plugin-worker` build), so a plug-in never runs on the page;
|
||||
//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox;
|
||||
//! - pen and finger input is read from Pointer Events by `pencil` (Apple Pencil pressure and
|
||||
//! hover, palm rejection, fingers navigate once a pen has been seen, the pen's eraser end
|
||||
@@ -28,6 +30,8 @@ mod keys;
|
||||
mod locks;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod pencil;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod plugin_workers;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod saved_files;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -53,6 +53,20 @@ pub struct Pointers {
|
||||
/// The pen's pressure and end for the canvas, the source the install reads.
|
||||
// PLAN: named `source`, not `pen`: `pen` is the pressing pen's pointer id above.
|
||||
source: PenSource,
|
||||
/// The pen whose finger wheel is read ([`Pointers::wheel`]).
|
||||
wheel: Option<Wheel>,
|
||||
/// Every reading written into the source, in order.
|
||||
#[cfg(test)]
|
||||
readings: Vec<PointerSample>,
|
||||
}
|
||||
|
||||
/// A pen, by pointer id and the end it is turned to, and whether it has reported a tangential
|
||||
/// pressure other than 0 since it came near.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Wheel {
|
||||
id: i32,
|
||||
eraser: bool,
|
||||
reads: bool,
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -64,6 +78,11 @@ struct Input<'a> {
|
||||
id: i32,
|
||||
button: i16,
|
||||
pressure: f32,
|
||||
/// Pointer Events' `tangentialPressure`, −1..1: an airbrush pen's finger wheel.
|
||||
tangential: f32,
|
||||
/// Whether the event names an element the pointer moved onto (`relatedTarget`): a pen leaving
|
||||
/// one element for another is still in its hover range.
|
||||
entered: bool,
|
||||
modifiers: egui::Modifiers,
|
||||
}
|
||||
|
||||
@@ -90,11 +109,29 @@ impl Pointers {
|
||||
self.source.clone()
|
||||
}
|
||||
|
||||
/// A pen moved or pressed with `pressure`, with the end it last pressed with.
|
||||
fn pen_sample(&self, pressure: f32) {
|
||||
/// A pen pressed, moved or lifted with `pressure` and `wheel`, with the end it last pressed
|
||||
/// with. The source queues each reading, and the runtime pairs the readings with the frame's
|
||||
/// pointer moves, so each move written after its own reading keeps that reading's wheel.
|
||||
fn pen_sample(&mut self, pressure: f32, wheel: Option<f32>) {
|
||||
let mut sample = PointerSample::new(pressure);
|
||||
sample.eraser = self.eraser;
|
||||
sample.wheel = wheel;
|
||||
self.source.set(Some(sample));
|
||||
#[cfg(test)]
|
||||
self.readings.push(sample);
|
||||
}
|
||||
|
||||
/// The finger wheel of pen `id`, turned to the end it last pressed with, for a sample with
|
||||
/// Pointer Events' `tangentialPressure` (−1..1,
|
||||
/// <https://www.w3.org/TR/pointerevents3/#dom-pointerevent-tangentialpressure>): a wheel of
|
||||
/// 0..1, −1 at 0 and 1 at 1, a value past either end clamped. Pointer Events give 0 for a pen
|
||||
/// without a wheel, so 0 reads as none until that pen, with that end, has reported a value
|
||||
/// other than 0 since it came near. A value that is not a number is none.
|
||||
fn wheel(&mut self, id: i32, tangential: f32) -> Option<f32> {
|
||||
let known = self.wheel.is_some_and(|w| w.id == id && w.eraser == self.eraser && w.reads);
|
||||
let reads = known || (tangential.is_finite() && tangential != 0.0);
|
||||
self.wheel = Some(Wheel { id, eraser: self.eraser, reads });
|
||||
(reads && tangential.is_finite()).then(|| (tangential.clamp(-1.0, 1.0) + 1.0) / 2.0)
|
||||
}
|
||||
|
||||
fn touch(&mut self, device: TouchDeviceId, id: i32, phase: TouchPhase, pos: Pos2, force: Option<f32>) {
|
||||
@@ -134,7 +171,10 @@ impl Pointers {
|
||||
}
|
||||
|
||||
/// Follow one pointer event; `true` if it was the pen's or a finger's (taken from eframe).
|
||||
fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32)], on_canvas: bool) -> bool {
|
||||
///
|
||||
/// `coalesced` holds the positions the pen reported since the last event, each with its
|
||||
/// pressure and tangential pressure, the last one at `pos`.
|
||||
fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32, f32)], on_canvas: bool) -> bool {
|
||||
let id = e.id;
|
||||
if e.pointer_type != "pen" && self.pen.is_none() && matches!(kind, "pointerdown" | "pointermove") {
|
||||
// Another pointer moved while no pen presses (a palm under a pen pressing is
|
||||
@@ -163,19 +203,24 @@ impl Pointers {
|
||||
if let Some(end) = end {
|
||||
self.eraser = end;
|
||||
}
|
||||
self.pen_sample(e.pressure);
|
||||
let wheel = self.wheel(id, e.tangential);
|
||||
self.pen_sample(e.pressure, wheel);
|
||||
self.pen = Some(id);
|
||||
self.touch(PEN_DEVICE, id, TouchPhase::Start, pos, force);
|
||||
self.press(id, pos, button, e.modifiers);
|
||||
}
|
||||
"pointermove" if self.pen == Some(id) => {
|
||||
self.pen_sample(e.pressure);
|
||||
// The positions the pen reported between two events (up to 240 a second
|
||||
// on an iPad), each with its pressure, so fast strokes keep their curve.
|
||||
for c in coalesced.iter().take(coalesced.len().saturating_sub(1)) {
|
||||
self.touch(PEN_DEVICE, id, TouchPhase::Move, c.0, Some(c.1));
|
||||
self.events.push(Event::PointerMoved(c.0));
|
||||
// on an iPad), each with its pressure and wheel, so fast strokes keep
|
||||
// their curve.
|
||||
for &(at, pressure, tangential) in coalesced.iter().take(coalesced.len().saturating_sub(1)) {
|
||||
let wheel = self.wheel(id, tangential);
|
||||
self.pen_sample(pressure, wheel);
|
||||
self.touch(PEN_DEVICE, id, TouchPhase::Move, at, Some(pressure));
|
||||
self.events.push(Event::PointerMoved(at));
|
||||
}
|
||||
let wheel = self.wheel(id, e.tangential);
|
||||
self.pen_sample(e.pressure, wheel);
|
||||
self.touch(PEN_DEVICE, id, TouchPhase::Move, pos, force);
|
||||
self.events.push(Event::PointerMoved(pos));
|
||||
}
|
||||
@@ -189,12 +234,19 @@ impl Pointers {
|
||||
}
|
||||
// Pointer Events report no end while a pen hovers: it keeps the end it
|
||||
// last pressed with.
|
||||
self.pen_sample(e.pressure);
|
||||
let wheel = self.wheel(id, e.tangential);
|
||||
self.pen_sample(e.pressure, wheel);
|
||||
self.events.push(Event::PointerMoved(pos));
|
||||
}
|
||||
"pointerup" | "pointercancel" if self.pen == Some(id) => {
|
||||
let phase = if kind == "pointerup" { TouchPhase::End } else { TouchPhase::Cancel };
|
||||
self.pen_sample(0.0);
|
||||
let (phase, wheel) = if kind == "pointerup" {
|
||||
// Lifted, the pen hovers on and keeps what it read of its wheel.
|
||||
(TouchPhase::End, self.wheel(id, e.tangential))
|
||||
} else {
|
||||
self.wheel = None;
|
||||
(TouchPhase::Cancel, None)
|
||||
};
|
||||
self.pen_sample(0.0, wheel);
|
||||
self.pen = None;
|
||||
self.touch(PEN_DEVICE, id, phase, pos, None);
|
||||
self.release(pos, e.modifiers);
|
||||
@@ -204,6 +256,13 @@ impl Pointers {
|
||||
if kind == "pointerleave" && self.primary.is_none() && on_canvas {
|
||||
self.events.push(Event::PointerGone);
|
||||
}
|
||||
// Left the hover range (a leave onto no element, on the canvas or off it)
|
||||
// or canceled: the pen reads its wheel afresh. Moving onto another element
|
||||
// keeps what it read.
|
||||
let gone = (kind == "pointerleave" && !e.entered && self.pen.is_none()) || kind == "pointercancel";
|
||||
if gone && self.wheel.is_some_and(|w| w.id == id) {
|
||||
self.wheel = None;
|
||||
}
|
||||
return self.pen.is_some();
|
||||
}
|
||||
}
|
||||
@@ -276,7 +335,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement,
|
||||
let z = runner.egui_ctx().zoom_factor();
|
||||
let pos = egui::pos2((e.client_x() as f32 - rect.left() as f32) / z, (e.client_y() as f32 - rect.top() as f32) / z);
|
||||
let at = |x: i32, y: i32| egui::pos2((x as f32 - rect.left() as f32) / z, (y as f32 - rect.top() as f32) / z);
|
||||
let coalesced: Vec<(Pos2, f32)> = if kind == "pointermove"
|
||||
let coalesced: Vec<(Pos2, f32, f32)> = if kind == "pointermove"
|
||||
&& e.pointer_type() == "pen"
|
||||
// Safari before 17 hasn't it, and calling a missing method would abort the app.
|
||||
&& js_sys::Reflect::has(&e, &"getCoalescedEvents".into()).unwrap_or(false)
|
||||
@@ -284,7 +343,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement,
|
||||
e.get_coalesced_events()
|
||||
.iter()
|
||||
.filter_map(|c| c.dyn_into::<web_sys::PointerEvent>().ok())
|
||||
.map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0)))
|
||||
.map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0), c.tangential_pressure()))
|
||||
.collect()
|
||||
} else {
|
||||
vec![]
|
||||
@@ -295,6 +354,8 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement,
|
||||
id: e.pointer_id(),
|
||||
button: e.button(),
|
||||
pressure: e.pressure(),
|
||||
tangential: e.tangential_pressure(),
|
||||
entered: e.related_target().is_some(),
|
||||
// Same semantics as eframe's modifiers_from_mouse_event.
|
||||
modifiers: egui::Modifiers {
|
||||
alt: e.alt_key(),
|
||||
@@ -343,7 +404,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn input(pointer_type: &str, button: i16) -> Input<'_> {
|
||||
Input { pointer_type, id: 7, button, pressure: 0.6, modifiers: egui::Modifiers::default() }
|
||||
Input { pointer_type, id: 7, button, pressure: 0.6, tangential: 0.0, entered: false, modifiers: egui::Modifiers::default() }
|
||||
}
|
||||
|
||||
fn reset() {
|
||||
@@ -505,6 +566,128 @@ mod tests {
|
||||
reset();
|
||||
}
|
||||
|
||||
fn pen_at(button: i16, tangential: f32) -> Input<'static> {
|
||||
Input { pointer_type: "pen", id: 7, button, pressure: 0.6, tangential, entered: false, modifiers: egui::Modifiers::default() }
|
||||
}
|
||||
|
||||
/// The wheels of the readings written since the last call, in order.
|
||||
fn wheels(p: &mut Pointers) -> Vec<Option<f32>> {
|
||||
p.readings.drain(..).map(|s| s.wheel).collect()
|
||||
}
|
||||
|
||||
/// The wheel of the source's latest reading.
|
||||
fn current_wheel(p: &Pointers) -> Option<f32> {
|
||||
p.pen().current().and_then(|s| s.wheel)
|
||||
}
|
||||
|
||||
/// An airbrush pen's finger wheel (Pointer Events' `tangentialPressure`, −1..1) reaches the
|
||||
/// source as 0..1 with each move, once the pen has reported a value other than 0.
|
||||
#[test]
|
||||
fn an_airbrush_wheel_goes_into_the_feed() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
assert!(p.feed("pointerdown", &pen_at(0, 0.0), Pos2::ZERO, &[], true));
|
||||
for t in [0.0, -1.0, 0.5, 0.0, 3.0, f32::NAN, -0.5] {
|
||||
assert!(p.feed("pointermove", &pen_at(-1, t), Pos2::ZERO, &[], true));
|
||||
}
|
||||
assert_eq!(
|
||||
wheels(&mut p),
|
||||
[None, None, Some(0.0), Some(0.75), Some(0.5), Some(1.0), None, Some(0.25)],
|
||||
"none until reported; then 0 is half way, past the ends is clamped and not a number is none"
|
||||
);
|
||||
assert!(p.feed("pointerup", &pen_at(0, 0.0), Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), Some(0.5), "the lift keeps the wheel");
|
||||
reset();
|
||||
}
|
||||
|
||||
/// The positions a fast stroke's event coalesced each get a reading with their own wheel and
|
||||
/// pressure, in order, before their move, and the event's own position comes last with its own.
|
||||
#[test]
|
||||
fn coalesced_moves_keep_their_wheel() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
let (a, b, c) = (Pos2::new(1.0, 2.0), Pos2::new(3.0, 4.0), Pos2::new(5.0, 6.0));
|
||||
assert!(p.feed("pointerdown", &pen_at(0, -1.0), Pos2::ZERO, &[], true));
|
||||
let coalesced = [(a, 0.3, -0.5), (b, 0.4, 0.5), (c, 0.5, 0.75)];
|
||||
assert!(p.feed("pointermove", &pen_at(-1, 1.0), c, &coalesced, true));
|
||||
let moved: Vec<Pos2> = p.take().into_iter().filter_map(|e| if let Event::PointerMoved(at) = e { Some(at) } else { None }).collect();
|
||||
let kept = std::mem::take(&mut p.readings);
|
||||
assert_eq!(moved, [Pos2::ZERO, a, b, c]);
|
||||
assert_eq!(kept.iter().map(|s| s.wheel).collect::<Vec<_>>(), [Some(0.0), Some(0.25), Some(0.75), Some(1.0)]);
|
||||
assert_eq!(kept.iter().map(|s| s.pressure).collect::<Vec<_>>(), [0.6, 0.3, 0.4, 0.6], "each move keeps its pressure too");
|
||||
reset();
|
||||
}
|
||||
|
||||
/// A pen that leaves the hover range, a canceled press, another pen and the other end each
|
||||
/// read the wheel afresh; a lift into hover does not. A mouse or a finger reads no wheel.
|
||||
#[test]
|
||||
fn the_wheel_is_read_afresh_for_each_pen_and_end() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
let feed = p.pen();
|
||||
let learn = |p: &mut Pointers, button: i16| {
|
||||
assert!(p.feed("pointerdown", &pen_at(button, 0.5), Pos2::ZERO, &[], true));
|
||||
assert!(p.feed("pointerup", &pen_at(button, 0.5), Pos2::ZERO, &[], true));
|
||||
};
|
||||
let hover = |p: &mut Pointers, id: i32| {
|
||||
let mut e = pen_at(-1, 0.0);
|
||||
e.id = id;
|
||||
e.pressure = 0.0;
|
||||
assert!(p.feed("pointermove", &e, Pos2::ZERO, &[], true));
|
||||
};
|
||||
learn(&mut p, 0);
|
||||
hover(&mut p, 7);
|
||||
assert_eq!(current_wheel(&p), Some(0.5), "a lift into hover keeps it");
|
||||
p.feed("pointerleave", &pen_at(-1, 0.0), Pos2::ZERO, &[], true);
|
||||
hover(&mut p, 7);
|
||||
assert_eq!(current_wheel(&p), None, "left the hover range");
|
||||
learn(&mut p, 0);
|
||||
assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true));
|
||||
assert!(p.feed("pointercancel", &pen_at(0, 0.5), Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), None, "a canceled press");
|
||||
hover(&mut p, 7);
|
||||
assert_eq!(current_wheel(&p), None, "after a canceled press");
|
||||
learn(&mut p, 0);
|
||||
hover(&mut p, 8);
|
||||
assert_eq!(current_wheel(&p), None, "another pen");
|
||||
learn(&mut p, 0);
|
||||
assert!(p.feed("pointerdown", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), None, "the other end");
|
||||
assert!(p.feed("pointerup", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true));
|
||||
p.readings.clear();
|
||||
for (pointer_type, kind) in [("mouse", "pointermove"), ("touch", "pointerdown"), ("touch", "pointermove")] {
|
||||
let mut other = pen_at(0, 0.5);
|
||||
(other.pointer_type, other.id) = (pointer_type, 10);
|
||||
p.feed(kind, &other, Pos2::ZERO, &[], true);
|
||||
assert_eq!(feed.current(), None, "{pointer_type} {kind}");
|
||||
assert!(p.readings.is_empty(), "{pointer_type} {kind}");
|
||||
}
|
||||
reset();
|
||||
}
|
||||
|
||||
/// A hovering pen that moves off the canvas onto another element and back keeps what it read
|
||||
/// of its wheel; one that leaves the hover range off the canvas reads it afresh.
|
||||
#[test]
|
||||
fn the_wheel_survives_crossing_the_canvas_edge() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true));
|
||||
assert!(p.feed("pointerup", &pen_at(0, 0.5), Pos2::ZERO, &[], true));
|
||||
let mut hover = pen_at(-1, 0.0);
|
||||
hover.pressure = 0.0;
|
||||
let mut onto = pen_at(-1, 0.0);
|
||||
(onto.pressure, onto.entered) = (0.0, true);
|
||||
p.feed("pointerleave", &onto, Pos2::ZERO, &[], true);
|
||||
assert!(!p.feed("pointermove", &hover, Pos2::ZERO, &[], false));
|
||||
assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), Some(0.5), "moved onto another element and back");
|
||||
p.feed("pointerleave", &onto, Pos2::ZERO, &[], true);
|
||||
p.feed("pointerleave", &hover, Pos2::ZERO, &[], false);
|
||||
assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), None, "left the hover range off the canvas");
|
||||
reset();
|
||||
}
|
||||
|
||||
/// A palm that lands or moves while the eraser end presses is rejected, and the feed keeps the
|
||||
/// eraser end for the canvas's next frame.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! The plug-in workers ([`vectorcraft_ui_egui::plugin_runs::Workers`]): each one a Web Worker that
|
||||
//! runs `vectorcraft-plugin-worker`, which Trunk builds beside the app (`index.html`), started from
|
||||
//! the loader file Trunk writes for it next to `index.html`.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use vectorcraft_ui_egui::plugin_runs::{SharedInbox, WorkerLink, Workers};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::prelude::Closure;
|
||||
|
||||
/// The loader Trunk writes for the worker (`data-loader-shim`), beside `index.html`.
|
||||
const LOADER: &str = "vectorcraft-plugin-worker_loader.js";
|
||||
|
||||
/// Starts the workers; each message or failure asks for a frame, which reads it.
|
||||
pub(crate) struct PageWorkers {
|
||||
pub(crate) ctx: egui::Context,
|
||||
}
|
||||
|
||||
/// One worker and its message and error handlers.
|
||||
struct PageWorker {
|
||||
worker: web_sys::Worker,
|
||||
_on_message: Closure<dyn FnMut(web_sys::MessageEvent)>,
|
||||
_on_error: Closure<dyn FnMut(web_sys::Event)>,
|
||||
}
|
||||
|
||||
/// The text of a browser error value.
|
||||
fn js_err(e: wasm_bindgen::JsValue) -> String {
|
||||
e.as_string().unwrap_or_else(|| format!("{e:?}"))
|
||||
}
|
||||
|
||||
impl Workers for PageWorkers {
|
||||
fn start(&self, inbox: SharedInbox) -> Result<Box<dyn WorkerLink>, String> {
|
||||
let document = web_sys::window().and_then(|w| w.document()).ok_or_else(|| "no document".to_string())?;
|
||||
let base = document.base_uri().map_err(js_err)?.ok_or_else(|| "no document".to_string())?;
|
||||
let url = web_sys::Url::new_with_base(LOADER, &base).map_err(js_err)?.href();
|
||||
let worker = web_sys::Worker::new(&url).map_err(js_err)?;
|
||||
let (to, ctx) = (Rc::clone(&inbox), self.ctx.clone());
|
||||
let on_message = Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |e: web_sys::MessageEvent| {
|
||||
to.borrow_mut().push(&js_sys::Uint8Array::new(&e.data()).to_vec());
|
||||
ctx.request_repaint();
|
||||
});
|
||||
let ctx = self.ctx.clone();
|
||||
// A worker that fails to load, panics or posts a message that can't be read.
|
||||
let on_error = Closure::<dyn FnMut(web_sys::Event)>::new(move |e: web_sys::Event| {
|
||||
let why = e.dyn_ref::<web_sys::ErrorEvent>().map_or_else(|| e.type_(), web_sys::ErrorEvent::message);
|
||||
inbox.borrow_mut().fail(why);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
worker.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
|
||||
worker.set_onerror(Some(on_error.as_ref().unchecked_ref()));
|
||||
worker.set_onmessageerror(Some(on_error.as_ref().unchecked_ref()));
|
||||
Ok(Box::new(PageWorker { worker, _on_message: on_message, _on_error: on_error }))
|
||||
}
|
||||
|
||||
fn now_ms(&self) -> f64 {
|
||||
web_sys::window().and_then(|w| w.performance()).map_or(0.0, |p| p.now())
|
||||
}
|
||||
}
|
||||
|
||||
impl WorkerLink for PageWorker {
|
||||
fn post(&mut self, msg: Vec<u8>) -> Result<(), String> {
|
||||
let bytes = js_sys::Uint8Array::from(msg.as_slice());
|
||||
self.worker.post_message_with_transfer(&bytes, &js_sys::Array::of1(&bytes.buffer())).map_err(js_err)
|
||||
}
|
||||
|
||||
fn terminate(&mut self) {
|
||||
self.worker.set_onmessage(None);
|
||||
self.worker.set_onerror(None);
|
||||
self.worker.set_onmessageerror(None);
|
||||
self.worker.terminate();
|
||||
}
|
||||
}
|
||||
@@ -156,7 +156,7 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
|
||||
.jobs(Arc::new(InlineJobs))
|
||||
.files(Arc::new(files))
|
||||
.install(ctx);
|
||||
let services = services(host.inbox.clone(), host.place_inbox.clone(), host.locks.clone());
|
||||
let services = services(host.inbox.clone(), host.place_inbox.clone(), host.locks.clone(), ctx.clone());
|
||||
let mut app = match taken.borrow_mut().take() {
|
||||
Some(mut app) => {
|
||||
// The old services asked the old context for frames.
|
||||
@@ -461,8 +461,10 @@ impl eframe::App for WebShell {
|
||||
}
|
||||
}
|
||||
|
||||
fn services(inbox: OpenInboxes, place_inbox: PlaceInbox, locks: Option<WebLocks>) -> Services {
|
||||
fn services(inbox: OpenInboxes, place_inbox: PlaceInbox, locks: Option<WebLocks>, ctx: egui::Context) -> Services {
|
||||
Services {
|
||||
// Plug-ins are checked and filters run in workers of their own, off the page.
|
||||
plugin_workers: vectorcraft_ui_egui::plugin_runs::workers(Box::new(crate::plugin_workers::PageWorkers { ctx })),
|
||||
// A download that couldn't be started fails the save or export it is for (#1693).
|
||||
download: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes).inspect_err(|e| log::error!("download of {name} failed: {e}")))),
|
||||
inbox: Some(inbox.dropped),
|
||||
|
||||
@@ -69,7 +69,7 @@ vectorcraft-render = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2 = "0.6"
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSpace", "NSControl", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSpace", "NSControl", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSView", "NSWindow"] }
|
||||
# Files opened from Finder and the Dock (src/open_documents.rs) and pasted bitmaps (src/clipboard.rs); both already come with winit.
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] }
|
||||
block2 = "0.6"
|
||||
|
||||
@@ -243,14 +243,3 @@ pub(crate) fn open_files(app: &mut VectorcraftApp, files: Vec<String>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tell the macOS input method to drop its composition (the Type tool kept the marked text as
|
||||
/// typed). winit's IME toggle only clears its own copy, so the IME would type it again.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn discard_marked_text() {
|
||||
if let Some(mtm) = objc2::MainThreadMarker::new()
|
||||
&& let Some(ic) = objc2_app_kit::NSTextInputContext::currentInputContext(mtm)
|
||||
{
|
||||
ic.discardMarkedText();
|
||||
}
|
||||
}
|
||||
+286
-144
@@ -4,10 +4,12 @@
|
||||
//! - Windows: text, SVG, PDF, PNG and an opaque bitmap (for apps that don't read PNG) in one go;
|
||||
//! Paste reads each of them and EPS, a bitmap as PNG, else as the device-independent bitmap that
|
||||
//! screenshots and most apps copy (`CF_DIBV5`, `CF_DIB`; the system makes them of a `CF_BITMAP`).
|
||||
//! - macOS and Linux: one format at a time, the text (a type-only copy's text or the SVG markup),
|
||||
//! else the PNG as a bitmap; Paste reads text and bitmaps, and on macOS the pasteboard's SVG, PDF
|
||||
//! and EPS as vector art (#1499) and its PNG or TIFF as they are, as screenshots copy them (on
|
||||
//! Linux arboard reads no other formats). On Wayland, arboard's data-control
|
||||
//! - macOS: text, SVG, PDF and PNG in one go: arboard writes the text, else the PNG as TIFF, and
|
||||
//! the other formats are added to the same pasteboard item ([`pasteboard_additions`]); Paste
|
||||
//! reads text and bitmaps, the pasteboard's SVG, PDF and EPS as vector art (#1499) and its PNG
|
||||
//! or TIFF as they are, as screenshots copy them.
|
||||
//! - Linux: one format at a time, the text (a type-only copy's text or the SVG markup), else the
|
||||
//! PNG as a bitmap; Paste reads text and bitmaps (arboard reads no other formats). On Wayland, arboard's data-control
|
||||
//! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps
|
||||
//! copied), falling back to X11 where the compositor lacks the protocol, and where there is no
|
||||
//! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection:
|
||||
@@ -137,6 +139,26 @@ fn pasteboard_types(mime: &str) -> &'static [(&'static str, &'static str)] {
|
||||
}
|
||||
}
|
||||
|
||||
/// The pasteboard types and data Copy adds on macOS to the item arboard wrote (the text, else the
|
||||
/// PNG as TIFF), in the order of `flavors` (best first): the SVG, PDF and EPS under the first of
|
||||
/// their [`pasteboard_types`], and the PNG as `public.png`. Text, empty flavours and flavours the
|
||||
/// pasteboard has no type for are left out.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn pasteboard_additions(flavors: &[Flavor]) -> Vec<(&'static str, &[u8])> {
|
||||
flavors
|
||||
.iter()
|
||||
.filter(|f| !f.data.is_empty())
|
||||
.filter_map(|f| {
|
||||
let t = match engine_mime(&f.mime)? {
|
||||
TEXT => return None,
|
||||
PNG => "public.png",
|
||||
mime => pasteboard_types(mime).first()?.0,
|
||||
};
|
||||
Some((t, &f.data[..]))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Most pixels a side of a bitmap another app put on the clipboard (untrusted data).
|
||||
const MAX_SIDE: u32 = 32_768;
|
||||
|
||||
@@ -612,9 +634,46 @@ mod loads {
|
||||
|
||||
/// The longest a read waits for the clipboard's owner to send its data.
|
||||
pub(super) const LOAD_WAIT: Duration = Duration::from_secs(2);
|
||||
/// The longest a paste's bitmap read of arboard's waits for the app that copied, off the UI
|
||||
/// thread: the bitmap's transfer and its PNG decoding happen within the read. A paste waits as
|
||||
/// long, from when it was sent, for a read that got no answer in its wait, the core protocol's
|
||||
/// text read included. Text, file lists and the UI thread's bitmap check wait [`LOAD_WAIT`].
|
||||
pub(super) const IMAGE_WAIT: Duration = Duration::from_secs(10);
|
||||
/// What a read says once its worker has stopped.
|
||||
pub(super) const GONE: &str = "the clipboard's reader stopped";
|
||||
|
||||
/// How long the reads of a [`Loads`] wait for the clipboard's owner.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct Waits {
|
||||
/// A text or file-list read, the UI thread's bitmap check, and dropping an idle `Loads`.
|
||||
pub(super) load: Duration,
|
||||
/// A paste's bitmap read off the UI thread, and a paste's wait for a read that got no
|
||||
/// answer in its wait.
|
||||
pub(super) image: Duration,
|
||||
}
|
||||
|
||||
impl Waits {
|
||||
/// [`LOAD_WAIT`] and [`IMAGE_WAIT`].
|
||||
pub(super) const APP: Self = Self { load: LOAD_WAIT, image: IMAGE_WAIT };
|
||||
/// No limit: each wait ends when its answer comes or its worker stops.
|
||||
#[cfg(test)]
|
||||
pub(super) const UNTIL_ANSWERED: Self = Self { load: Duration::MAX, image: Duration::MAX };
|
||||
}
|
||||
|
||||
/// What is left at `now` of `limit` from `sent`; [`Duration::MAX`] (no limit) when the end is
|
||||
/// past the clock's range.
|
||||
pub(super) fn left(sent: Instant, limit: Duration, now: Instant) -> Duration {
|
||||
sent.checked_add(limit).map_or(Duration::MAX, |end| end.saturating_duration_since(now))
|
||||
}
|
||||
|
||||
/// What comes on `rx` within `wait`; a wait whose end is past the clock's range has no limit.
|
||||
fn recv_within<T>(rx: &mpsc::Receiver<T>, wait: Duration) -> Result<T, mpsc::RecvTimeoutError> {
|
||||
match Instant::now().checked_add(wait) {
|
||||
Some(_) => rx.recv_timeout(wait),
|
||||
None => rx.recv().map_err(mpsc::RecvTimeoutError::from),
|
||||
}
|
||||
}
|
||||
|
||||
/// Requests of type `R` answered with `A` on a worker thread.
|
||||
pub(super) struct Loads<R, A> {
|
||||
/// The worker's requests; the worker stops once this is dropped.
|
||||
@@ -623,6 +682,8 @@ mod loads {
|
||||
done: mpsc::Receiver<()>,
|
||||
/// How long after it was sent dropping `Loads` waits for an unanswered read to end.
|
||||
finish: Duration,
|
||||
/// How long its reads wait.
|
||||
waits: Waits,
|
||||
}
|
||||
|
||||
/// Where requests go to a [`Loads`] worker.
|
||||
@@ -685,18 +746,18 @@ mod loads {
|
||||
}
|
||||
}
|
||||
|
||||
/// When dropping `Loads` stops waiting for its worker: `finish` after the unanswered read
|
||||
/// `pending` was sent (at once if that time has passed), and with no read unanswered
|
||||
/// [`LOAD_WAIT`] from `now` at most (an idle worker ends at once).
|
||||
fn stop_by(pending: Option<Instant>, now: Instant, finish: Duration) -> Instant {
|
||||
pending.map_or(now + LOAD_WAIT, |sent| sent + finish)
|
||||
/// How long, from `now`, dropping `Loads` waits for its worker: until `finish` after the
|
||||
/// unanswered read `pending` was sent (not at all if that time has passed), and with no read
|
||||
/// unanswered `idle` at most (an idle worker ends at once).
|
||||
fn stop_wait(pending: Option<Instant>, now: Instant, finish: Duration, idle: Duration) -> Duration {
|
||||
pending.map_or(idle, |sent| left(sent, finish, now))
|
||||
}
|
||||
|
||||
impl<R: Send + 'static, A: Send + 'static> Loads<R, A> {
|
||||
/// A worker thread named `name` that answers each request with `load`; dropping the result
|
||||
/// waits up to `finish` after an unanswered read was sent for that read to end. None when the
|
||||
/// worker can't start.
|
||||
pub(super) fn spawn(name: &str, finish: Duration, mut load: impl FnMut(R) -> A + Send + 'static) -> Option<Self> {
|
||||
/// A worker thread named `name` that answers each request with `load`, whose reads wait as
|
||||
/// `waits` says; dropping the result waits up to `finish` after an unanswered read was sent
|
||||
/// for that read to end. None when the worker can't start.
|
||||
pub(super) fn spawn(name: &str, finish: Duration, waits: Waits, mut load: impl FnMut(R) -> A + Send + 'static) -> Option<Self> {
|
||||
let (requests, asked) = mpsc::channel::<(R, mpsc::Sender<A>)>();
|
||||
let (alive, done) = mpsc::channel::<()>();
|
||||
let open = Arc::new(AtomicUsize::new(0));
|
||||
@@ -714,7 +775,12 @@ mod loads {
|
||||
drop(alive);
|
||||
};
|
||||
std::thread::Builder::new().name(name.into()).spawn(work).ok()?;
|
||||
Some(Self { line: Arc::new(Line { requests, open, sent: Mutex::default() }), done, finish })
|
||||
Some(Self { line: Arc::new(Line { requests, open, sent: Mutex::default() }), done, finish, waits })
|
||||
}
|
||||
|
||||
/// How long its reads wait.
|
||||
pub(super) fn waits(&self) -> Waits {
|
||||
self.waits
|
||||
}
|
||||
|
||||
/// `request` sent to the worker; its answer comes on the channel returned, for
|
||||
@@ -741,9 +807,10 @@ mod loads {
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer that comes on `answer` ([`Loads::ask`]), or why there is none, after `wait` at most.
|
||||
/// The answer that comes on `answer` ([`Loads::ask`]), or why there is none, after `wait` at most
|
||||
/// ([`Duration::MAX`]: no limit).
|
||||
pub(super) fn wait_for_answer<A>(answer: &mpsc::Receiver<A>, wait: Duration) -> Result<A, String> {
|
||||
match answer.recv_timeout(wait) {
|
||||
match recv_within(answer, wait) {
|
||||
Ok(answer) => Ok(answer),
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => Err(format!("the clipboard's owner didn't send its data within {wait:?}")),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => Err(GONE.into()),
|
||||
@@ -751,16 +818,16 @@ mod loads {
|
||||
}
|
||||
|
||||
impl<R, A> Drop for Loads<R, A> {
|
||||
/// Stops the worker and waits until it has let go of what its `load` holds, until
|
||||
/// [`stop_by`] at most: on X11 the last arboard handle dropped hands what the app copied to
|
||||
/// the clipboard manager, and the app's own handle must be that one.
|
||||
/// Stops the worker and waits until it has let go of what its `load` holds, as long as
|
||||
/// [`stop_wait`] says at most: on X11 the last arboard handle dropped hands what the app
|
||||
/// copied to the clipboard manager, and the app's own handle must be that one.
|
||||
fn drop(&mut self) {
|
||||
// No `Asker` sends after this, and one that holds the line lets go once it has sent.
|
||||
let pending = self.line.close();
|
||||
drop(std::mem::replace(&mut self.line, Line::dead()));
|
||||
let end = stop_by(pending, Instant::now(), self.finish);
|
||||
// Nothing is sent on `done`: this ends when the worker drops `alive`, or at `end`.
|
||||
let _ = self.done.recv_timeout(end.saturating_duration_since(Instant::now()));
|
||||
let wait = stop_wait(pending, Instant::now(), self.finish, self.waits.load);
|
||||
// Nothing is sent on `done`: this ends when the worker drops `alive`, or after `wait`.
|
||||
let _ = recv_within(&self.done, wait);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -770,18 +837,38 @@ mod loads {
|
||||
|
||||
use super::*;
|
||||
|
||||
/// No limit: a wait ends when its answer comes.
|
||||
const UNTIL_ANSWERED: Duration = Duration::MAX;
|
||||
|
||||
#[test]
|
||||
fn a_read_that_answers_in_time_gives_the_text() {
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, |()| "<svg/>".to_string()).unwrap();
|
||||
assert_eq!(loads.get((), Duration::from_secs(5)), Ok("<svg/>".to_string()));
|
||||
assert_eq!(loads.get((), Duration::from_secs(5)), Ok("<svg/>".to_string()));
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| "<svg/>".to_string()).unwrap();
|
||||
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok("<svg/>".to_string()));
|
||||
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok("<svg/>".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wait_with_no_limit_ends_when_its_answer_comes() {
|
||||
let (reply, answer) = mpsc::channel();
|
||||
let late = std::thread::spawn(move || reply.send(7));
|
||||
assert_eq!(wait_for_answer(&answer, UNTIL_ANSWERED), Ok(7));
|
||||
assert_eq!(late.join().ok(), Some(Ok(())));
|
||||
// A worker that stops without answering ends the wait too.
|
||||
let (reply, answer) = mpsc::channel::<u8>();
|
||||
drop(reply);
|
||||
assert_eq!(wait_for_answer(&answer, UNTIL_ANSWERED), Err(GONE.to_string()));
|
||||
// Limits from a read's send: what is left, none once it is over, no limit past the clock.
|
||||
let now = Instant::now();
|
||||
assert_eq!(left(now, Duration::from_secs(10), now + Duration::from_secs(3)), Duration::from_secs(7));
|
||||
assert_eq!(left(now, Duration::from_secs(10), now + Duration::from_secs(20)), Duration::ZERO);
|
||||
assert_eq!(left(now, Duration::MAX, now), Duration::MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_owner_that_never_answers_holds_the_worker_not_the_caller() {
|
||||
let (release, gate) = mpsc::channel::<()>();
|
||||
let mut calls = 0;
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, move |()| {
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |()| {
|
||||
calls += 1;
|
||||
if calls == 1 {
|
||||
// The first owner sends nothing until released.
|
||||
@@ -793,11 +880,11 @@ mod loads {
|
||||
.unwrap();
|
||||
assert!(loads.get((), Duration::ZERO).is_err(), "the first read times out");
|
||||
// While it is unanswered, a read doesn't queue behind it or wait at all.
|
||||
assert!(loads.get((), Duration::from_secs(600)).is_err());
|
||||
assert!(loads.get((), UNTIL_ANSWERED).is_err());
|
||||
release.send(()).unwrap();
|
||||
// Once the late answer is in, it is dropped and a new read is made.
|
||||
let text = loop {
|
||||
match loads.get((), Duration::from_secs(600)) {
|
||||
match loads.get((), UNTIL_ANSWERED) {
|
||||
Ok(text) => break text,
|
||||
Err(why) => {
|
||||
// The late answer isn't in yet.
|
||||
@@ -811,17 +898,17 @@ mod loads {
|
||||
|
||||
#[test]
|
||||
fn a_read_after_the_worker_stops_says_so() {
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, |()| String::new()).unwrap();
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| String::new()).unwrap();
|
||||
// The worker ends when its requests stop: cut them off by hand.
|
||||
drop(std::mem::replace(&mut loads.line, Line::dead()));
|
||||
assert_eq!(loads.get((), Duration::from_millis(50)), Err(GONE.to_string()));
|
||||
assert_eq!(loads.get((), UNTIL_ANSWERED), Err(GONE.to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_threads_reads_stop_with_the_reads() {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, |()| 1).unwrap();
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| 1).unwrap();
|
||||
let asker = loads.asker();
|
||||
assert_eq!(asker.ask(()).and_then(|a| wait_for_answer(&a, Duration::from_secs(600))), Ok(1));
|
||||
assert_eq!(asker.ask(()).and_then(|a| wait_for_answer(&a, UNTIL_ANSWERED)), Ok(1));
|
||||
drop(loads);
|
||||
assert_eq!(asker.ask(()).err(), Some(GONE.to_string()));
|
||||
// Closed while an asker still holds the line: nothing more is sent.
|
||||
@@ -833,7 +920,7 @@ mod loads {
|
||||
#[test]
|
||||
fn an_answer_waited_for_on_another_thread_holds_back_the_next_read() {
|
||||
let (release, gate) = mpsc::channel::<()>();
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, move |n: u32| {
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |n: u32| {
|
||||
if n == 1 {
|
||||
let _ = gate.recv();
|
||||
}
|
||||
@@ -842,20 +929,21 @@ mod loads {
|
||||
.unwrap();
|
||||
let answer = loads.ask(1).unwrap();
|
||||
// The caller doesn't wait: the answer is waited for wherever the channel goes.
|
||||
let waiter = std::thread::spawn(move || wait_for_answer(&answer, Duration::from_secs(600)));
|
||||
let waiter = std::thread::spawn(move || wait_for_answer(&answer, UNTIL_ANSWERED));
|
||||
// Until it comes, a read fails at once instead of queuing behind it.
|
||||
assert!(loads.get(2, Duration::from_secs(600)).is_err());
|
||||
assert!(loads.get(2, UNTIL_ANSWERED).is_err());
|
||||
release.send(()).unwrap();
|
||||
assert_eq!(waiter.join().ok(), Some(Ok(1)));
|
||||
assert_eq!(loads.get(3, Duration::from_secs(600)), Ok(3));
|
||||
assert_eq!(loads.get(3, UNTIL_ANSWERED), Ok(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropping_the_reads_waits_until_the_worker_lets_go_of_its_clipboard() {
|
||||
let clipboard = Arc::new(());
|
||||
let held = clipboard.clone();
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, move |()| Arc::strong_count(&held)).unwrap();
|
||||
assert_eq!(loads.get((), Duration::from_secs(600)), Ok(2));
|
||||
// With no limit on the idle wait, the drop ends only once the worker has let go.
|
||||
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |()| Arc::strong_count(&held)).unwrap();
|
||||
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok(2));
|
||||
drop(loads);
|
||||
assert_eq!(Arc::strong_count(&clipboard), 1, "the worker's handle is gone before the app's");
|
||||
}
|
||||
@@ -865,12 +953,12 @@ mod loads {
|
||||
let now = Instant::now();
|
||||
let limit = Duration::from_secs(25);
|
||||
// No read unanswered: the idle worker ends at once, LOAD_WAIT is only the bound.
|
||||
assert_eq!(stop_by(None, now, limit), now + LOAD_WAIT);
|
||||
assert_eq!(stop_wait(None, now, limit, LOAD_WAIT), LOAD_WAIT);
|
||||
// A read sent 2 s ago that timed out: wait for it until 25 s after it was sent.
|
||||
assert_eq!(stop_by(Some(now - Duration::from_secs(2)), now, limit), now + Duration::from_secs(23));
|
||||
assert_eq!(stop_wait(Some(now - Duration::from_secs(2)), now, limit, LOAD_WAIT), Duration::from_secs(23));
|
||||
// Its limit already over, or no limit (data-control, the core protocol): no wait.
|
||||
assert!(stop_by(Some(now - Duration::from_secs(30)), now, limit) <= now);
|
||||
assert_eq!(stop_by(Some(now), now, Duration::ZERO), now);
|
||||
assert_eq!(stop_wait(Some(now - Duration::from_secs(30)), now, limit, LOAD_WAIT), Duration::ZERO);
|
||||
assert_eq!(stop_wait(Some(now), now, Duration::ZERO, LOAD_WAIT), Duration::ZERO);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -885,6 +973,8 @@ mod portable {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
use super::loads::Waits;
|
||||
use super::{
|
||||
BITMAP, ClipboardBackend, ClipboardError, ClipboardImage, ClipboardRead, Flavor, Flavour, LaterFlavor, PNG, TEXT, copied_file, decode_png,
|
||||
engine_mimes, png_flavour, read_flavor, read_image_flavor, read_later_flavor, takes_files,
|
||||
@@ -991,28 +1081,21 @@ mod portable {
|
||||
reads.get(request, wait).unwrap_or_else(|why| Answer::failed(request, why))
|
||||
}
|
||||
|
||||
/// The longest a paste's bitmap read of arboard's waits for the app that copied, off the UI
|
||||
/// thread: the bitmap's transfer and its PNG decoding happen within the read. A paste waits as
|
||||
/// long, from when it was sent, for a read that got no answer in its wait, the core protocol's
|
||||
/// text read included. Text, file lists and the UI thread's bitmap check wait
|
||||
/// [`LOAD_WAIT`](super::loads::LOAD_WAIT).
|
||||
/// How long a read of `request` waits for the app that copied: `waits.image` for a bitmap,
|
||||
/// `waits.load` otherwise.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
const IMAGE_WAIT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// How long a read of `request` waits for the app that copied.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
fn wait_for(request: Request) -> Duration {
|
||||
fn wait_for(waits: Waits, request: Request) -> Duration {
|
||||
match request {
|
||||
Request::Image => IMAGE_WAIT,
|
||||
Request::Text | Request::Files => super::loads::LOAD_WAIT,
|
||||
Request::Image => waits.image,
|
||||
Request::Text | Request::Files => waits.load,
|
||||
}
|
||||
}
|
||||
|
||||
/// How long a paste's read of `request` after a late answer waits at `now`: as long as any read
|
||||
/// of `request`, or until [`IMAGE_WAIT`] after the unanswered read was `sent` when that is later.
|
||||
/// of `request`, or until `waits.image` after the unanswered read was `sent` when that is later.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
fn follow_up_wait(request: Request, sent: Instant, now: Instant) -> Duration {
|
||||
wait_for(request).max((sent + IMAGE_WAIT).saturating_duration_since(now))
|
||||
fn follow_up_wait(waits: Waits, request: Request, sent: Instant, now: Instant) -> Duration {
|
||||
wait_for(waits, request).max(super::loads::left(sent, waits.image, now))
|
||||
}
|
||||
|
||||
/// The longest an X11 read of arboard's lasts while the owner sends nothing: a text read tries
|
||||
@@ -1063,6 +1146,8 @@ mod portable {
|
||||
sent: Instant,
|
||||
/// The worker, for the paste's other reads.
|
||||
reads: super::loads::Asker<Request, Answer>,
|
||||
/// How long the worker's reads wait.
|
||||
waits: Waits,
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
@@ -1078,7 +1163,8 @@ mod portable {
|
||||
}
|
||||
|
||||
/// What a paste of one of `mimes` takes, once this read's answer comes, waiting for it until
|
||||
/// [`IMAGE_WAIT`] after it was sent, as long as a paste's bitmap read waits. Once it comes,
|
||||
/// `waits.image` ([`IMAGE_WAIT`](super::loads::IMAGE_WAIT)) after it was sent, as long as a
|
||||
/// paste's bitmap read waits. Once it comes,
|
||||
/// the same read is made again, since the clipboard may have changed hands meanwhile.
|
||||
/// `None`, so the paste takes the internal clipboard, when that answer doesn't come or the
|
||||
/// new one is what `ours` put on the clipboard. Otherwise the clipboard is read as
|
||||
@@ -1088,12 +1174,12 @@ mod portable {
|
||||
/// names a picture (`adopt_system_clipboard_or_defer` in `vectorcraft-ui-egui`). Those reads
|
||||
/// wait as [`follow_up_wait`] says.
|
||||
fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
let wait = (self.sent + IMAGE_WAIT).saturating_duration_since(Instant::now());
|
||||
let wait = super::loads::left(self.sent, self.waits.image, Instant::now());
|
||||
super::loads::wait_for_answer(&self.answer, wait).ok()?;
|
||||
let fresh = |request: Request| {
|
||||
self.reads
|
||||
.ask(request)
|
||||
.and_then(|a| super::loads::wait_for_answer(&a, follow_up_wait(request, self.sent, Instant::now())))
|
||||
.and_then(|a| super::loads::wait_for_answer(&a, follow_up_wait(self.waits, request, self.sent, Instant::now())))
|
||||
.unwrap_or_else(|why| Answer::failed(request, why))
|
||||
};
|
||||
// The late answer may come from an app that lost the clipboard while it was awaited.
|
||||
@@ -1139,14 +1225,15 @@ mod portable {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
impl Late {
|
||||
/// What a paste of one of `mimes` takes once the answer comes ([`Unanswered::paste`]). The
|
||||
/// core protocol's answer is waited for as long, until [`IMAGE_WAIT`] after its read was
|
||||
/// sent; then the clipboard is read again and pasted as at once, unless it holds the Copy
|
||||
/// made here ([`super::wayland::Unanswered::paste`]).
|
||||
/// core protocol's answer is waited for as long, until
|
||||
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) after its read was sent; then the clipboard is
|
||||
/// read again and pasted as at once, unless it holds the Copy made here
|
||||
/// ([`super::wayland::Unanswered::paste`]).
|
||||
fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
match self {
|
||||
Self::Arboard(unanswered) => unanswered.paste(ours, mimes),
|
||||
#[cfg(target_os = "linux")]
|
||||
Self::Wayland(unanswered) => unanswered.paste(mimes, IMAGE_WAIT),
|
||||
Self::Wayland(unanswered) => unanswered.paste(mimes),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1163,8 +1250,9 @@ mod portable {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
{
|
||||
let mut reader = arboard::Clipboard::new().map_err(|e| e.to_string())?;
|
||||
let reads = super::loads::Loads::spawn("clipboard-read", finish(on_data_control()), move |request| answer(&mut reader, request))
|
||||
.ok_or("the clipboard's reader didn't start")?;
|
||||
let reads =
|
||||
super::loads::Loads::spawn("clipboard-read", finish(on_data_control()), Waits::APP, move |request| answer(&mut reader, request))
|
||||
.ok_or("the clipboard's reader didn't start")?;
|
||||
Ok(Self { reads, unanswered: None, cb })
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))]
|
||||
@@ -1181,13 +1269,13 @@ mod portable {
|
||||
impl<C> Arboard<C> {
|
||||
/// Reads on the worker; the write handle `C` is not used.
|
||||
fn read(&mut self, request: Request) -> Answer {
|
||||
self.read_waiting(request, wait_for(request))
|
||||
self.read_waiting(request, wait_for(self.reads.waits(), request))
|
||||
}
|
||||
|
||||
/// A bitmap read on the worker that waits [`LOAD_WAIT`](super::loads::LOAD_WAIT) at most, for
|
||||
/// a check on the UI thread.
|
||||
fn image_now(&mut self) -> Result<arboard::ImageData<'static>, String> {
|
||||
self.read_waiting(Request::Image, super::loads::LOAD_WAIT).image()
|
||||
self.read_waiting(Request::Image, self.reads.waits().load).image()
|
||||
}
|
||||
|
||||
/// `request` read on the worker, waiting `wait` at most. A read that gets no answer in that
|
||||
@@ -1202,7 +1290,7 @@ mod portable {
|
||||
Ok(answer) => answer,
|
||||
Err(why) => {
|
||||
if why != super::loads::GONE {
|
||||
self.unanswered = Some(Unanswered { request, answer, sent, reads: self.reads.asker() });
|
||||
self.unanswered = Some(Unanswered { request, answer, sent, reads: self.reads.asker(), waits: self.reads.waits() });
|
||||
}
|
||||
Answer::failed(request, why)
|
||||
}
|
||||
@@ -1217,11 +1305,13 @@ mod portable {
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// A bitmap read sent to the worker now; the work returned waits [`IMAGE_WAIT`] at most for
|
||||
/// it, so the caller can wait off the UI thread. Err when the read can't be sent.
|
||||
/// A bitmap read sent to the worker now; the work returned waits
|
||||
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most for it, so the caller can wait off the UI
|
||||
/// thread. Err when the read can't be sent.
|
||||
fn image_later(&mut self) -> Result<ImageWork, String> {
|
||||
let wait = self.reads.waits().image;
|
||||
let answer = self.ask(Request::Image)?;
|
||||
Ok(Box::new(move || super::loads::wait_for_answer(&answer, IMAGE_WAIT).and_then(Answer::image)))
|
||||
Ok(Box::new(move || super::loads::wait_for_answer(&answer, wait).and_then(Answer::image)))
|
||||
}
|
||||
|
||||
/// The read that got no answer in its wait, while its answer has still not come and a paste
|
||||
@@ -1503,12 +1593,12 @@ mod portable {
|
||||
/// Text and copied files are read here, and work that reads arboard's image comes back. On
|
||||
/// the Wayland core protocol the copied files, else the first of `mimes` the clipboard
|
||||
/// offers, is read: text here, file lists, SVG and PNG by the work that comes back, which
|
||||
/// waits [`IMAGE_WAIT`] at most.
|
||||
/// waits [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most.
|
||||
fn read_now_or_later(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
|
||||
let cb = self.cb(Asker::User).ok()?;
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Backend::Wayland(cb) = cb {
|
||||
return cb.read(mimes, IMAGE_WAIT);
|
||||
return cb.read(mimes);
|
||||
}
|
||||
if let Some(f) = copied_file(cb.file_list(), mimes) {
|
||||
return Some(ClipboardRead::Now(f));
|
||||
@@ -1554,7 +1644,8 @@ mod portable {
|
||||
/// arboard takes the text, else the PNG as a bitmap; the Wayland core protocol offers the
|
||||
/// SVG, PNG and text together ([`DataClipboard::copy`](super::wayland::DataClipboard::copy)).
|
||||
/// The index answered is the flavour that went out: the text, else the PNG, and on the
|
||||
/// core protocol the first flavour it offers.
|
||||
/// core protocol the first flavour it offers. On macOS the other flavours are then added
|
||||
/// to the pasteboard item arboard wrote ([`pasteboard_additions`](super::pasteboard_additions)).
|
||||
fn write(&mut self, flavors: &[Flavor]) -> Result<usize, ClipboardError> {
|
||||
let cb = self.cb(Asker::User).map_err(ClipboardError::Other)?;
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -1591,6 +1682,8 @@ mod portable {
|
||||
// What a read got late was on the clipboard before this write.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
cb.forget_unanswered();
|
||||
#[cfg(target_os = "macos")]
|
||||
super::mac::add(&super::pasteboard_additions(flavors));
|
||||
self.ours = ours;
|
||||
Ok(wrote)
|
||||
}
|
||||
@@ -1654,9 +1747,12 @@ mod portable {
|
||||
mod tests {
|
||||
use std::cell::Cell;
|
||||
|
||||
use super::super::loads::Loads;
|
||||
use super::super::loads::{Loads, Waits};
|
||||
use super::*;
|
||||
|
||||
/// No limit: a wait ends when its answer comes.
|
||||
const UNTIL_ANSWERED: Duration = Duration::MAX;
|
||||
|
||||
/// A clock that starts now and moves only when told.
|
||||
struct Clock(Cell<Instant>);
|
||||
|
||||
@@ -1780,27 +1876,27 @@ mod portable {
|
||||
fn reads_return_while_the_clipboard_owner_sends_nothing() {
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
// The app that copied never sends its data until released.
|
||||
let mut reads = Loads::spawn("test", Duration::ZERO, move |request| {
|
||||
let mut reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| {
|
||||
let _ = gate.recv();
|
||||
Answer::failed(request, "late".into())
|
||||
})
|
||||
.unwrap();
|
||||
// Copy's look at the text, Paste's file list and its bitmap: none waits for the owner.
|
||||
assert!(read_within(&mut reads, Request::Text, Duration::ZERO).text().is_err());
|
||||
assert!(read_within(&mut reads, Request::Files, Duration::from_secs(600)).files().is_empty());
|
||||
assert!(read_within(&mut reads, Request::Image, Duration::from_secs(600)).image().is_err());
|
||||
assert!(read_within(&mut reads, Request::Files, UNTIL_ANSWERED).files().is_empty());
|
||||
assert!(read_within(&mut reads, Request::Image, UNTIL_ANSWERED).image().is_err());
|
||||
drop(release);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_read_takes_its_own_answer() {
|
||||
let mut reads = Loads::spawn("test", Duration::ZERO, |request| match request {
|
||||
let mut reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |request| match request {
|
||||
Request::Text => Answer::Text(Ok("<svg/>".into())),
|
||||
Request::Image => Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) })),
|
||||
Request::Files => Answer::Files(vec![PathBuf::from("art.svg")]),
|
||||
})
|
||||
.unwrap();
|
||||
let wait = Duration::from_secs(600);
|
||||
let wait = UNTIL_ANSWERED;
|
||||
assert_eq!(read_within(&mut reads, Request::Text, wait).text(), Ok("<svg/>".to_string()));
|
||||
assert_eq!(read_within(&mut reads, Request::Image, wait).image().map(|i| (i.width, i.height)), Ok((2, 1)));
|
||||
assert_eq!(read_within(&mut reads, Request::Files, wait).files(), [PathBuf::from("art.svg")]);
|
||||
@@ -1847,7 +1943,8 @@ mod portable {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn arboards_reads_run_on_its_reader_and_wait_by_kind() {
|
||||
let reads = Loads::spawn("test", Duration::ZERO, |request| match request {
|
||||
// The reads wait for their answer however long it takes, so the answer decides the result.
|
||||
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |request| match request {
|
||||
Request::Text => Answer::Text(Ok("read on the worker".into())),
|
||||
_ => Answer::failed(request, "not asked".into()),
|
||||
})
|
||||
@@ -1855,15 +1952,18 @@ mod portable {
|
||||
// `()` for writes: a read made through the write handle wouldn't build.
|
||||
let mut cb = Arboard { reads, unanswered: None, cb: () };
|
||||
assert_eq!(cb.read(Request::Text).text(), Ok("read on the worker".to_string()));
|
||||
assert_eq!(wait_for(Request::Text), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(wait_for(Request::Files), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(wait_for(Request::Image), Duration::from_secs(10));
|
||||
let app = Waits::APP;
|
||||
assert_eq!(wait_for(app, Request::Text), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(wait_for(app, Request::Files), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(wait_for(app, Request::Image), Duration::from_secs(10));
|
||||
// A paste's reads after a late answer wait until 10 s after the unanswered read was
|
||||
// sent, and never less than any read of their kind.
|
||||
let sent = Instant::now();
|
||||
assert_eq!(follow_up_wait(Request::Text, sent, sent + Duration::from_secs(3)), Duration::from_secs(7));
|
||||
assert_eq!(follow_up_wait(Request::Files, sent, sent + Duration::from_secs(9)), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(follow_up_wait(Request::Image, sent, sent + Duration::from_secs(20)), IMAGE_WAIT);
|
||||
assert_eq!(follow_up_wait(app, Request::Text, sent, sent + Duration::from_secs(3)), Duration::from_secs(7));
|
||||
assert_eq!(follow_up_wait(app, Request::Files, sent, sent + Duration::from_secs(9)), super::super::loads::LOAD_WAIT);
|
||||
assert_eq!(follow_up_wait(app, Request::Image, sent, sent + Duration::from_secs(20)), super::super::loads::IMAGE_WAIT);
|
||||
// With no limit, the follow-up reads have none either.
|
||||
assert_eq!(follow_up_wait(Waits::UNTIL_ANSWERED, Request::Text, sent, sent + Duration::from_secs(20)), Duration::MAX);
|
||||
// X11 waits for an unanswered read when the clipboard closes; data-control doesn't.
|
||||
assert_eq!(finish(false), X11_READ_LIMIT);
|
||||
assert_eq!(finish(true), Duration::ZERO);
|
||||
@@ -1884,7 +1984,7 @@ mod portable {
|
||||
fn a_bitmap_paste_waits_for_the_owner_off_the_ui_thread() {
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
// The app that copied sends its bitmap only when released.
|
||||
let reads = Loads::spawn("test", Duration::ZERO, move |request| match request {
|
||||
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| match request {
|
||||
Request::Image => {
|
||||
let _ = gate.recv();
|
||||
Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) }))
|
||||
@@ -1903,11 +2003,12 @@ mod portable {
|
||||
}
|
||||
|
||||
/// An arboard clipboard whose owner answers each read with `answer` only once the sender
|
||||
/// returned is used or dropped.
|
||||
/// returned is used or dropped. Its reads wait for their answers with no limit: the
|
||||
/// release decides when a paste gets its answer.
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
fn slow_owner(answer: impl Fn(Request) -> Answer + Send + 'static) -> (Arboard<()>, std::sync::mpsc::Sender<()>) {
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
let reads = Loads::spawn("test", Duration::ZERO, move |request| {
|
||||
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| {
|
||||
let _ = gate.recv();
|
||||
answer(request)
|
||||
})
|
||||
@@ -2028,10 +2129,10 @@ mod portable {
|
||||
|
||||
/// Core protocol reads of a clipboard offering `types`, whose owner answers each read
|
||||
/// of a text type with `text` and of `image/png` with `png`, only once the sender
|
||||
/// returned is used or dropped.
|
||||
/// returned is used or dropped. The reads wait for their answers with no limit.
|
||||
fn slow_owner(types: &[&str], text: &'static str, png: &'static [u8]) -> (Reads, Arc<Mutex<Seen>>, std::sync::mpsc::Sender<()>) {
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
|
||||
let _ = gate.recv();
|
||||
Ok(if wire == PNG { png.to_vec() } else { text.as_bytes().to_vec() })
|
||||
})
|
||||
@@ -2047,7 +2148,7 @@ mod portable {
|
||||
// in its wait (2 s on the UI thread, none here).
|
||||
assert!(reads.text(Duration::ZERO).is_err());
|
||||
// The paste's own read fails at once while the owner hasn't answered.
|
||||
assert!(reads.text(Duration::from_secs(600)).is_err());
|
||||
assert!(reads.text(UNTIL_ANSWERED).is_err());
|
||||
// A paste of a bitmap alone can't take text: the read stays kept.
|
||||
assert!(reads.unanswered(&[BITMAP]).is_none());
|
||||
let late = Late::Wayland(reads.unanswered(&PASTE_ORDER).expect("the check's read is kept for the paste"));
|
||||
@@ -2083,7 +2184,7 @@ mod portable {
|
||||
// again and takes the new owner's text.
|
||||
let (release, gate) = std::sync::mpsc::channel::<()>();
|
||||
let mut texts_read = 0;
|
||||
let loads = Loads::spawn("test", Duration::ZERO, move |_: String| {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |_: String| {
|
||||
let _ = gate.recv();
|
||||
texts_read += 1;
|
||||
Ok(if texts_read == 1 { "old owner" } else { "new owner" }.as_bytes().to_vec())
|
||||
@@ -2149,7 +2250,7 @@ mod wayland {
|
||||
use wayland_client::protocol::wl_seat::{self, WlSeat};
|
||||
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum};
|
||||
|
||||
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer};
|
||||
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, Waits, left, wait_for_answer};
|
||||
use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, takes_files, uri_list_paths};
|
||||
|
||||
/// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK
|
||||
@@ -2445,16 +2546,18 @@ mod wayland {
|
||||
/// The worker, for the reads made once the answer comes.
|
||||
reads: Asker<String, Got>,
|
||||
seen: Arc<Mutex<Seen>>,
|
||||
/// How long the worker's reads wait.
|
||||
waits: Waits,
|
||||
}
|
||||
|
||||
impl Unanswered {
|
||||
/// What a paste of one of `mimes` takes once this read's answer comes, waiting for it until
|
||||
/// `limit` after the read was sent: the clipboard read again as [`pick_pasted`] reads it,
|
||||
/// each read waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may
|
||||
/// have lost the clipboard meanwhile. None when the answer doesn't come or the clipboard holds this
|
||||
/// connection's Copy.
|
||||
pub(super) fn paste(self, mimes: &[&'static str], limit: Duration) -> Option<Flavour> {
|
||||
let left = |now: Instant| (self.sent + limit).saturating_duration_since(now);
|
||||
/// `waits.image` after the read was sent: the clipboard read again as [`pick_pasted`] reads
|
||||
/// it, each read waiting as long, `waits.load` ([`LOAD_WAIT`]) at least, since the app that
|
||||
/// answers late may have lost the clipboard meanwhile. None when the answer doesn't come or
|
||||
/// the clipboard holds this connection's Copy.
|
||||
pub(super) fn paste(self, mimes: &[&'static str]) -> Option<Flavour> {
|
||||
let left = |now: Instant| left(self.sent, self.waits.image, now);
|
||||
let _late = wait_for_answer(&self.answer, left(Instant::now())).ok()?;
|
||||
let offered = {
|
||||
let seen = lock(&self.seen);
|
||||
@@ -2464,7 +2567,7 @@ mod wayland {
|
||||
seen.offered.clone()
|
||||
};
|
||||
pick_pasted(&offered, mimes, |wire| {
|
||||
wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok()
|
||||
wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, self.waits.load.max(left(Instant::now()))).ok()?.ok()
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2491,7 +2594,8 @@ mod wayland {
|
||||
Ok(got) => Ok(flavour(TEXT, got?).map(|f| String::from_utf8_lossy(&f.data).into_owned()).unwrap_or_default()),
|
||||
Err(why) => {
|
||||
if why != GONE {
|
||||
self.unanswered = Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone() });
|
||||
self.unanswered =
|
||||
Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone(), waits: self.loads.waits() });
|
||||
}
|
||||
Err(why)
|
||||
}
|
||||
@@ -2501,12 +2605,13 @@ mod wayland {
|
||||
/// What a paste of one of `mimes` reads: the files a file manager copied, else the first of
|
||||
/// `mimes` the clipboard offers. A file list is asked for here and read, with the files,
|
||||
/// by the work that comes back, which pastes the first file that is art ([`copied`]) and
|
||||
/// else reads `mimes` as [`pick`] does. Text is read here, [`LOAD_WAIT`] at most, and
|
||||
/// pasted unless it is empty; SVG and PNG are asked for here and waited for, `wait` at most,
|
||||
/// by the work that comes back. When that read fails or is empty, the work reads the rest
|
||||
/// of `mimes` as [`pick`] does. Each read the work makes after the first waits until `wait`
|
||||
/// after the first was sent, [`LOAD_WAIT`] at least.
|
||||
pub(super) fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option<ClipboardRead> {
|
||||
/// else reads `mimes` as [`pick`] does. Text is read here, `waits.load` ([`LOAD_WAIT`]) at
|
||||
/// most, and pasted unless it is empty; SVG and PNG are asked for here and waited for,
|
||||
/// `waits.image` at most, by the work that comes back. When that read fails or is empty,
|
||||
/// the work reads the rest of `mimes` as [`pick`] does. Each read the work makes after the
|
||||
/// first waits until `waits.image` after the first was sent, `waits.load` at least.
|
||||
pub(super) fn read(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
|
||||
let Waits { load, image: wait } = self.loads.waits();
|
||||
if takes_files(mimes) {
|
||||
let offered = lock(&self.seen).offered.clone();
|
||||
if let Some(list) = file_list_type(&offered).map(str::to_string) {
|
||||
@@ -2515,7 +2620,7 @@ mod wayland {
|
||||
self.unanswered = None;
|
||||
let (reads, mimes) = (self.loads.asker(), mimes.to_vec());
|
||||
return Some(ClipboardRead::Later(Box::new(move || {
|
||||
let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now()));
|
||||
let left = || load.max(left(sent, wait, Instant::now()));
|
||||
// The list asked for here is read from its answer, every other type anew.
|
||||
let mut first = Some((list, answer));
|
||||
pick_pasted(&offered, &mimes, |wire| {
|
||||
@@ -2531,7 +2636,7 @@ mod wayland {
|
||||
mimes.iter().enumerate().find_map(|(i, &mime)| {
|
||||
let wire = self.wire(mime)?;
|
||||
if mime == TEXT {
|
||||
let text = self.text(LOAD_WAIT).ok().filter(|t| !t.is_empty())?;
|
||||
let text = self.text(load).ok().filter(|t| !t.is_empty())?;
|
||||
return Some(ClipboardRead::Now(Flavour { mime: TEXT, data: text.into_bytes() }));
|
||||
}
|
||||
let sent = Instant::now();
|
||||
@@ -2543,7 +2648,7 @@ mod wayland {
|
||||
return Some(f);
|
||||
}
|
||||
let offered = lock(&seen).offered.clone();
|
||||
let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now()));
|
||||
let left = || load.max(left(sent, wait, Instant::now()));
|
||||
pick(&offered, &rest, |wire| wait_for_answer(&reads.ask(wire.to_string()).ok()?, left()).ok()?.ok())
|
||||
})))
|
||||
})
|
||||
@@ -2809,7 +2914,7 @@ mod wayland {
|
||||
let receiver = Receiver { conn: conn.clone(), objects: objects.clone(), _window: window.clone() };
|
||||
// Dropping doesn't wait for an unanswered read: only arboard's X11 handles hand what the
|
||||
// app copied on when the last one goes.
|
||||
let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, move |wire| receiver.receive(wire))?;
|
||||
let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, Waits::APP, move |wire| receiver.receive(wire))?;
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let (stopped, held) = (stop.clone(), window.clone());
|
||||
let work = move || {
|
||||
@@ -2846,14 +2951,16 @@ mod wayland {
|
||||
self.conn.flush().map_err(|e| format!("couldn't reach the compositor: {e}"))
|
||||
}
|
||||
|
||||
/// The text, waiting [`LOAD_WAIT`] at most ([`Reads::text`]).
|
||||
pub fn text(&mut self) -> Result<String, String> {
|
||||
self.reads.text(LOAD_WAIT)
|
||||
let wait = self.reads.loads.waits().load;
|
||||
self.reads.text(wait)
|
||||
}
|
||||
|
||||
/// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for `wait` at
|
||||
/// most.
|
||||
pub fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option<ClipboardRead> {
|
||||
self.reads.read(mimes, wait)
|
||||
/// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for
|
||||
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most.
|
||||
pub fn read(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
|
||||
self.reads.read(mimes)
|
||||
}
|
||||
|
||||
pub fn has(&self, mimes: &[&'static str]) -> bool {
|
||||
@@ -3022,8 +3129,8 @@ mod wayland {
|
||||
assert_eq!(keyboard_serial(&modifiers(9), None), None);
|
||||
}
|
||||
|
||||
/// A wait no test reaches: the other end of each pipe below either moves data or closes.
|
||||
const LONG: Duration = Duration::from_secs(600);
|
||||
/// No limit ([`idle_until`]): the other end of each pipe below either moves data or closes.
|
||||
const LONG: Duration = Duration::MAX;
|
||||
|
||||
/// A pipe holding `data`, its write end closed when `close`.
|
||||
fn pipe_with(data: &[u8], close: bool) -> (std::io::PipeReader, Option<std::io::PipeWriter>) {
|
||||
@@ -3041,7 +3148,7 @@ mod wayland {
|
||||
assert_eq!(read_capped(pipe_with(&[0u8; 9], true).0, 8, Duration::ZERO), Err("the clipboard's data is larger than 0 MiB".to_string()));
|
||||
// More than a pipe holds, from an app that is still sending.
|
||||
let (from, to) = std::io::pipe().unwrap();
|
||||
assert!(Sends::default().start(to, vec![0u8; (2 << 20) + 1].into()));
|
||||
assert!(Sends { idle: LONG, ..Sends::default() }.start(to, vec![0u8; (2 << 20) + 1].into()));
|
||||
assert_eq!(read_capped(from, 2 << 20, LONG), Err("the clipboard's data is larger than 2 MiB".to_string()));
|
||||
// A pipe that can't be read: the write end.
|
||||
let (_, to) = std::io::pipe().unwrap();
|
||||
@@ -3095,8 +3202,8 @@ mod wayland {
|
||||
|
||||
#[test]
|
||||
fn a_copys_data_is_sent_through_the_pipe_and_closed() {
|
||||
let sends = Sends::default();
|
||||
assert_eq!(sends.idle, IDLE_WAIT);
|
||||
assert_eq!(Sends::default().idle, IDLE_WAIT);
|
||||
let sends = Sends { idle: LONG, ..Sends::default() };
|
||||
let (from, to) = std::io::pipe().unwrap();
|
||||
let data: Arc<[u8]> = vec![7u8; 300_000].into();
|
||||
assert!(sends.start(to, data.clone()));
|
||||
@@ -3146,9 +3253,10 @@ mod wayland {
|
||||
const NOTHING: Held = &[];
|
||||
const UNKNOWN: Held = &[("application/x-other", b"x")];
|
||||
|
||||
/// Reads of a clipboard holding `data`, answered at once.
|
||||
/// Reads of a clipboard holding `data`, answered at once; each read waits for its answer
|
||||
/// with no limit.
|
||||
fn reads_of(data: Held) -> Reads {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
|
||||
data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.to_vec()).ok_or_else(|| "not offered".to_string())
|
||||
})
|
||||
.unwrap();
|
||||
@@ -3159,27 +3267,26 @@ mod wayland {
|
||||
#[test]
|
||||
fn a_picture_or_svg_alone_can_be_pasted_and_is() {
|
||||
use vectorcraft_engine::cmd::clipboard::PASTE_ORDER;
|
||||
let wait = Duration::from_secs(600);
|
||||
for (data, mime) in [(PNG_ONLY, PNG), (SVG_ONLY, SVG)] {
|
||||
let mut reads = reads_of(data);
|
||||
// The paste check enables Paste from the types alone.
|
||||
assert!(reads.has(&PASTE_ORDER));
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("{mime} is read off the UI thread") };
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("{mime} is read off the UI thread") };
|
||||
assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, data[0].1.to_vec())));
|
||||
}
|
||||
let mut reads = reads_of(TEXT_ONLY);
|
||||
assert!(reads.has(&[TEXT]) && !reads.has(&[BITMAP, SVG]));
|
||||
let Some(ClipboardRead::Now(f)) = reads.read(&PASTE_ORDER, wait) else { panic!("text is read at once") };
|
||||
let Some(ClipboardRead::Now(f)) = reads.read(&PASTE_ORDER) else { panic!("text is read at once") };
|
||||
assert_eq!((f.mime, f.data), (TEXT, b"words".to_vec()));
|
||||
// An empty clipboard, or one with no type a paste reads, enables nothing and pastes nothing.
|
||||
for data in [NOTHING, UNKNOWN] {
|
||||
let mut reads = reads_of(data);
|
||||
assert!(!reads.has(&PASTE_ORDER));
|
||||
assert!(reads.read(&PASTE_ORDER, wait).is_none());
|
||||
assert_eq!(reads.text(wait), Ok(String::new()));
|
||||
assert!(reads.read(&PASTE_ORDER).is_none());
|
||||
assert_eq!(reads.text(Duration::MAX), Ok(String::new()));
|
||||
}
|
||||
// Empty text is not pasted.
|
||||
assert!(reads_of(EMPTY_TEXT).read(&[TEXT], wait).is_none());
|
||||
assert!(reads_of(EMPTY_TEXT).read(&[TEXT]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3188,36 +3295,38 @@ mod wayland {
|
||||
const EMPTY_SVG_TEXT: Held = &[(SVG, b""), ("text/plain", b"words"), (PNG, b"\x89PNG")];
|
||||
const EMPTY_SVG_PNG: Held = &[(SVG, b""), (PNG, b"\x89PNG")];
|
||||
const EMPTY_SVG_URL: Held = &[(SVG, b""), ("text/plain", b"https://example.com/art.png"), (PNG, b"\x89PNG")];
|
||||
let wait = Duration::from_secs(600);
|
||||
const EMPTY_PNG: Held = &[(PNG, b"")];
|
||||
for (data, mime, bytes) in
|
||||
[(EMPTY_SVG_TEXT, TEXT, &b"words"[..]), (EMPTY_SVG_PNG, PNG, &b"\x89PNG"[..]), (EMPTY_SVG_URL, PNG, &b"\x89PNG"[..])]
|
||||
{
|
||||
// Held while the work runs, as the clipboard is.
|
||||
let mut reads = reads_of(data);
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the SVG is asked for") };
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("the SVG is asked for") };
|
||||
assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, bytes.to_vec())));
|
||||
}
|
||||
// A failed PNG read, last of all, pastes nothing.
|
||||
let mut reads = reads_of(EMPTY_PNG);
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the PNG is asked for") };
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("the PNG is asked for") };
|
||||
assert!(work().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_that_fails_pastes_nothing() {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, |_: String| Err::<Vec<u8>, _>("the clipboard's data is larger than 64 MiB".to_string()))
|
||||
.unwrap();
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |_: String| {
|
||||
Err::<Vec<u8>, _>("the clipboard's data is larger than 64 MiB".to_string())
|
||||
})
|
||||
.unwrap();
|
||||
let mut reads = Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&[PNG, "text/plain"]))));
|
||||
assert_eq!(reads.text(Duration::from_secs(600)), Err("the clipboard's data is larger than 64 MiB".to_string()));
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP], Duration::from_secs(600)) else { panic!("the PNG is asked for") };
|
||||
assert_eq!(reads.text(Duration::MAX), Err("the clipboard's data is larger than 64 MiB".to_string()));
|
||||
let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP]) else { panic!("the PNG is asked for") };
|
||||
assert!(work().is_none());
|
||||
}
|
||||
|
||||
/// Reads of a clipboard holding `data` by type, answered at once.
|
||||
/// Reads of a clipboard holding `data` by type, answered at once; each read waits for its
|
||||
/// answer with no limit.
|
||||
fn reads_holding(data: Vec<(String, Vec<u8>)>) -> Reads {
|
||||
let types: Vec<String> = data.iter().map(|(t, _)| t.clone()).collect();
|
||||
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
|
||||
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
|
||||
data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.clone()).ok_or_else(|| "not offered".to_string())
|
||||
})
|
||||
.unwrap();
|
||||
@@ -3232,7 +3341,7 @@ mod wayland {
|
||||
|
||||
/// What a paste of `mimes` takes from `reads`.
|
||||
fn paste(reads: &mut Reads, mimes: &[&'static str]) -> Option<(&'static str, Vec<u8>)> {
|
||||
match reads.read(mimes, Duration::from_secs(600))? {
|
||||
match reads.read(mimes)? {
|
||||
ClipboardRead::Now(f) => Some((f.mime, f.data)),
|
||||
ClipboardRead::Later(work) => work().map(|f| (f.mime, f.data)),
|
||||
}
|
||||
@@ -3296,15 +3405,29 @@ mod wayland {
|
||||
}
|
||||
|
||||
/// The macOS pasteboard's vector art and bitmaps as they are (arboard reads text, and of the
|
||||
/// pictures TIFF only, decoded).
|
||||
/// pictures TIFF only, decoded), and the formats Copy adds to what arboard wrote.
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac {
|
||||
use objc2::rc::autoreleasepool;
|
||||
use objc2_app_kit::NSPasteboard;
|
||||
use objc2_foundation::{NSArray, NSString};
|
||||
use objc2_foundation::{NSArray, NSData, NSString};
|
||||
|
||||
use super::{Flavour, MAX_BYTES, copy_within, pasteboard_types};
|
||||
|
||||
/// Adds `types` ([`super::pasteboard_additions`]: each pasteboard type with its data) to the
|
||||
/// item arboard just wrote. A type that can't be added is logged, and what arboard wrote still
|
||||
/// carries the copy.
|
||||
pub fn add(types: &[(&str, &[u8])]) {
|
||||
autoreleasepool(|_| {
|
||||
let pasteboard = NSPasteboard::generalPasteboard();
|
||||
for &(t, data) in types {
|
||||
if !pasteboard.setData_forType(Some(&NSData::with_bytes(data)), &NSString::from_str(t)) {
|
||||
log::warn!("clipboard: couldn't add {t}");
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Does the pasteboard hold one of `mimes` ([`pasteboard_types`])? Asks for its types only.
|
||||
pub fn has(mimes: &[&'static str]) -> bool {
|
||||
autoreleasepool(|_| {
|
||||
@@ -3393,6 +3516,25 @@ mod tests {
|
||||
assert!(at(PDF) < at(EPS) && at(EPS) < at(TEXT) && at(TEXT) < at(BITMAP));
|
||||
}
|
||||
|
||||
/// On macOS a Copy puts every format on the pasteboard, not only the text or the picture
|
||||
/// arboard writes (#6310): with On Copy: PDF the PDF goes with the picture, and with Include
|
||||
/// SVG Code the SVG and the PDF go with the markup as text.
|
||||
#[test]
|
||||
fn a_copy_adds_its_other_formats_to_the_pasteboard() {
|
||||
let flavor = |mime: &'static str, data: &[u8]| Flavor::new(mime, data.to_vec());
|
||||
let added = |flavors: &[Flavor]| pasteboard_additions(flavors).into_iter().map(|(t, data)| (t, data.to_vec())).collect::<Vec<_>>();
|
||||
// On Copy: PDF alone: arboard writes the picture, and the PDF is added beside it.
|
||||
let pdf_only = [flavor(PDF, b"%PDF"), flavor(PNG, b"png")];
|
||||
assert_eq!(added(&pdf_only), [("com.adobe.pdf", b"%PDF".to_vec()), ("public.png", b"png".to_vec())]);
|
||||
// Include SVG Code with the PDF: arboard writes the markup as text, and the SVG, PDF and
|
||||
// picture are added in the order Copy offers them.
|
||||
let both = [flavor(TEXT, b"<svg/>"), flavor(SVG, b"<svg/>"), flavor(PDF, b"%PDF"), flavor(PNG, b"png")];
|
||||
let types: Vec<_> = added(&both).into_iter().map(|(t, _)| t).collect();
|
||||
assert_eq!(types, ["public.svg-image", "com.adobe.pdf", "public.png"]);
|
||||
// An empty flavour and a type the pasteboard doesn't carry are left out.
|
||||
assert!(added(&[flavor(PDF, b""), flavor(EMF, b"emf"), flavor("text/html", b"<p>")]).is_empty());
|
||||
}
|
||||
|
||||
/// An .eps file copied in a file manager pastes as EPS.
|
||||
#[test]
|
||||
fn a_copied_eps_file_pastes() {
|
||||
|
||||
@@ -629,6 +629,15 @@ struct StartFile {
|
||||
record: StartRecord,
|
||||
}
|
||||
|
||||
impl Drop for StartFile {
|
||||
/// Frees the lock when the start releases the file. A child process that any thread starts holds
|
||||
/// a copy of the file's handle until it runs its program, and the lock is only freed by closing
|
||||
/// every copy or by unlocking.
|
||||
fn drop(&mut self) {
|
||||
let _ = self.file.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
impl StartFile {
|
||||
/// Open `dir`'s [`START_FILE`], with the record the last start left in it (`None` when there is
|
||||
/// none or it can't be read). `Ok(None)` when another copy of the app holds it.
|
||||
|
||||
@@ -613,9 +613,7 @@ fn a_normal_exit_or_another_failure_does_not_restart() {
|
||||
assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into()));
|
||||
}
|
||||
|
||||
/// A log folder of its own for each test, and the guard that keeps other tests from starting a
|
||||
/// program while it runs: the test releases the start file's lock and takes it again, and a child
|
||||
/// starting meanwhile would keep it held (`crate::no_spawns`).
|
||||
/// A log folder of its own for each test.
|
||||
struct TestDir(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
@@ -632,10 +630,23 @@ impl AsRef<std::path::Path> for TestDir {
|
||||
}
|
||||
}
|
||||
|
||||
fn start_dir(tag: &str) -> (TestDir, std::sync::RwLockReadGuard<'static, ()>) {
|
||||
let spawns = crate::no_spawns();
|
||||
let dir = tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap();
|
||||
(TestDir(dir), spawns)
|
||||
fn start_dir(tag: &str) -> TestDir {
|
||||
TestDir(tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap())
|
||||
}
|
||||
|
||||
/// A start that ends frees the start file even while another handle to it is open, as a child
|
||||
/// process that is starting holds one: the next start reads the file instead of taking it for
|
||||
/// another copy of the app that is starting.
|
||||
#[test]
|
||||
fn an_ended_start_frees_the_start_file_while_a_copy_of_its_handle_is_open() {
|
||||
let dir = start_dir("copy");
|
||||
let starting = Startup::default();
|
||||
starting.track(&dir, None, false);
|
||||
let copy = starting.start.lock().unwrap().as_ref().map(|start| start.file.try_clone().unwrap());
|
||||
assert!(copy.is_some(), "the start holds the file");
|
||||
starting.ended();
|
||||
assert!(StartFile::open(&dir).unwrap().is_some(), "an ended start frees the start file");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
/// What a start in `dir` leaves out; it then ends without crashing.
|
||||
@@ -661,7 +672,7 @@ fn issue_2243() -> Vec<Candidate> {
|
||||
/// it, without a status-bar note.
|
||||
#[test]
|
||||
fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
|
||||
let (dir, _spawns) = start_dir("crash");
|
||||
let dir = start_dir("crash");
|
||||
let c = issue_2243();
|
||||
let first = Startup::default();
|
||||
assert_eq!(first.track(&dir, None, false), LeftOut::default());
|
||||
@@ -691,7 +702,7 @@ fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
|
||||
/// an error, a restart on another adapter), leaves nothing out of the next.
|
||||
#[test]
|
||||
fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
|
||||
let (dir, _spawns) = start_dir("shown");
|
||||
let dir = start_dir("shown");
|
||||
let c = issue_2243();
|
||||
for end in [Startup::presented as fn(&Startup), Startup::ended] {
|
||||
let first = Startup::default();
|
||||
@@ -714,7 +725,7 @@ fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
|
||||
/// macOS, where wgpu has none.
|
||||
#[test]
|
||||
fn a_crash_while_listing_lists_opengl_alone() {
|
||||
let (dir, _spawns) = start_dir("listing");
|
||||
let dir = start_dir("listing");
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
drop(first);
|
||||
@@ -740,7 +751,7 @@ fn a_crash_while_listing_lists_opengl_alone() {
|
||||
/// start shows its first frame on the adapter that crashed, the adapter counts again.
|
||||
#[test]
|
||||
fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
|
||||
let (dir, _spawns) = start_dir("explicit");
|
||||
let dir = start_dir("explicit");
|
||||
let c = issue_2243();
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
@@ -760,7 +771,7 @@ fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
|
||||
/// are ignored: the start goes on with nothing left out.
|
||||
#[test]
|
||||
fn a_damaged_or_unreadable_start_file_is_ignored() {
|
||||
let (dir, _spawns) = start_dir("damaged");
|
||||
let dir = start_dir("damaged");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let damaged: [&[u8]; 9] = [
|
||||
b"",
|
||||
|
||||
@@ -220,11 +220,20 @@ fn report_path(dir: &Path) -> PathBuf {
|
||||
dir.join(format!("{REPORT_PREFIX}{}.txt", std::process::id()))
|
||||
}
|
||||
|
||||
/// A report file this process wrote and holds locked until the interface answers again.
|
||||
/// A report file this process holds locked: the one it wrote, until the interface answers again,
|
||||
/// or a left one while it is read. Dropping it unlocks the file. A child process that any thread
|
||||
/// starts holds a copy of the file's handle until it runs its program, and the lock is only freed
|
||||
/// by closing every copy or by unlocking.
|
||||
#[derive(Debug)]
|
||||
pub struct Held {
|
||||
path: PathBuf,
|
||||
_file: File,
|
||||
file: File,
|
||||
}
|
||||
|
||||
impl Drop for Held {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.file.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `text` to this process's report file in `dir` and lock it. Where the file system has no
|
||||
@@ -237,7 +246,7 @@ fn write_report(dir: &Path, text: &str) -> std::io::Result<Held> {
|
||||
log::warn!("the hang report file is written without a lock: {e}");
|
||||
}
|
||||
file.write_all(text.as_bytes())?;
|
||||
Ok(Held { path, _file: file })
|
||||
Ok(Held { path, file })
|
||||
}
|
||||
|
||||
/// Whether a report file whose `try_lock` gave `locked` was abandoned: nobody holds it. A file
|
||||
@@ -253,13 +262,14 @@ fn abandoned(locked: Result<(), std::fs::TryLockError>) -> bool {
|
||||
|
||||
/// The report file at `path`, opened and locked, with its length, when it was abandoned
|
||||
/// ([`abandoned`]) and is not empty (an empty one may be being written).
|
||||
fn open_abandoned(path: &Path) -> Option<(File, u64)> {
|
||||
fn open_abandoned(path: &Path) -> Option<(Held, u64)> {
|
||||
let file = File::options().read(true).write(true).open(path).ok()?;
|
||||
if !abandoned(file.try_lock()) {
|
||||
return None;
|
||||
}
|
||||
let len = file.metadata().map_or(0, |m| m.len());
|
||||
(len > 0).then_some((file, len))
|
||||
let held = Held { path: path.to_path_buf(), file };
|
||||
let len = held.file.metadata().map_or(0, |m| m.len());
|
||||
(len > 0).then_some((held, len))
|
||||
}
|
||||
|
||||
/// The reports that sessions closed while they did not answer left in `dir`, oldest first; `None`
|
||||
@@ -286,20 +296,20 @@ pub fn take_previous(dir: &Path) -> Option<String> {
|
||||
// Newest first: only abandoned reports count toward the limit.
|
||||
let mut texts = Vec::new();
|
||||
for (_, path) in found.into_iter().rev() {
|
||||
let Some((file, len)) = open_abandoned(&path) else { continue };
|
||||
let Some((held, len)) = open_abandoned(&path) else { continue };
|
||||
if texts.len() == MAX_REPORT_FILES {
|
||||
drop(file);
|
||||
drop(held);
|
||||
remove_quietly(&path);
|
||||
continue;
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
let text = if len <= MAX_REPORT_BYTES && (&file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() {
|
||||
let text = if len <= MAX_REPORT_BYTES && (&held.file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() {
|
||||
String::from_utf8_lossy(&bytes).into_owned()
|
||||
} else {
|
||||
format!("The report was larger than {MAX_REPORT_BYTES} bytes and was not read.\n")
|
||||
};
|
||||
// Closed (and unlocked) before it is moved: Windows moves no open file.
|
||||
drop(file);
|
||||
drop(held);
|
||||
if !texts.is_empty() {
|
||||
remove_quietly(&path);
|
||||
} else if let Err(e) = std::fs::rename(&path, dir.join(PREVIOUS_FILE)) {
|
||||
@@ -324,8 +334,8 @@ pub static CLOSING: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Remove `held`'s file, closing it first. → the error message; a file already gone is none.
|
||||
fn remove(held: Held) -> Option<String> {
|
||||
let Held { path, _file: file } = held;
|
||||
drop(file);
|
||||
let path = held.path.clone();
|
||||
drop(held);
|
||||
match std::fs::remove_file(&path) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Some(e.to_string()),
|
||||
_ => None,
|
||||
|
||||
@@ -136,6 +136,17 @@ fn a_stall_writes_the_report_file_and_its_end_removes_it() {
|
||||
assert!(shared.last.lock().unwrap().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_report_frees_its_lock_while_a_copy_of_its_handle_is_open() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let held = write_report(dir.path(), "left\n").unwrap();
|
||||
// A child process that is starting holds such a copy.
|
||||
let copy = held.file.try_clone().unwrap();
|
||||
drop(held);
|
||||
assert_eq!(take_previous(dir.path()).as_deref(), Some("left\n"), "a dropped report is no longer locked");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_normally_removes_the_report_and_writes_no_more() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -124,10 +124,13 @@ pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: O
|
||||
/// The arguments a child of this process starts with: a nightly launch hands its profile on, so the
|
||||
/// child opens the same private profile instead of being refused ("Open VectorCraft Nightly…"), and
|
||||
/// `--` keeps a file whose name starts with '-' a file. Stable's child arguments are unchanged.
|
||||
/// Only `single_instance` starts a child, and macOS does not build it.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn child_args(files: &[String]) -> Vec<OsString> {
|
||||
child_args_for(current(), files)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn child_args_for(profile: &Profile, files: &[String]) -> Vec<OsString> {
|
||||
let mut args: Vec<OsString> = match profile {
|
||||
Profile::Stable => Vec::new(),
|
||||
@@ -245,12 +248,14 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[test]
|
||||
fn a_stable_child_gets_the_file_delimiter_only() {
|
||||
let child = child_args_for(&Profile::Stable, &["a file.svg".to_string(), "--looks-like-a-flag".to_string()]);
|
||||
assert_eq!(child, args(&["--", "a file.svg", "--looks-like-a-flag"]));
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[test]
|
||||
fn a_nightly_child_inherits_the_selected_profile() {
|
||||
let root = PathBuf::from(absolute());
|
||||
|
||||
@@ -1034,19 +1034,5 @@ fn main() -> std::process::ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests only: while a test starts another program, the child briefly holds a copy of every file
|
||||
/// this process has open, until it runs that program. A file lock held through such a copy outlives
|
||||
/// its own handle, so a GPU start test that released the start file and opened it again found it
|
||||
/// still locked, as if another copy of the app were running, and failed. A test that starts a
|
||||
/// program holds its write side; a test that depends on the start file's lock holds [`no_spawns`].
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
static CHILD_SPAWN: std::sync::RwLock<()> = std::sync::RwLock::new(());
|
||||
|
||||
/// Held by a test that releases a locked file and opens it again (see [`CHILD_SPAWN`]).
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
fn no_spawns() -> std::sync::RwLockReadGuard<'static, ()> {
|
||||
CHILD_SPAWN.read().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
mod tests;
|
||||
@@ -16,12 +16,38 @@ static SESSION: Mutex<Option<Session>> = Mutex::new(None);
|
||||
static NOTICE_SHOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
pub struct Session {
|
||||
_lease: File,
|
||||
_lease: Lease,
|
||||
path: PathBuf,
|
||||
own_record: Vec<u8>,
|
||||
previous_unclean: bool,
|
||||
}
|
||||
|
||||
/// The profile's [`LEASE`], open and locked.
|
||||
struct Lease(File);
|
||||
|
||||
impl Lease {
|
||||
/// Lock `root`'s [`LEASE`]: `None` when another window of the same profile holds it.
|
||||
fn take(root: &Path) -> io::Result<Option<Self>> {
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => Ok(Some(Self(lease))),
|
||||
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Lease {
|
||||
/// Frees the lease when the session ends, or when a session could not be started after the lock
|
||||
/// was taken. A child process that any thread starts holds a copy of the lease's handle until it
|
||||
/// runs its program, and the lock is only freed by closing every copy or by unlocking.
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
fn regular_or_missing(path: &Path) -> io::Result<bool> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
|
||||
@@ -73,14 +99,13 @@ impl Session {
|
||||
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
|
||||
}
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => return Err(error),
|
||||
}
|
||||
let Some(lease) = Lease::take(root)? else { return Ok(None) };
|
||||
Self::record(lease, root, version, commit).map(Some)
|
||||
}
|
||||
|
||||
/// Write this launch's record while `lease` is held. On an error `lease` is dropped, which
|
||||
/// unlocks it.
|
||||
fn record(lease: Lease, root: &Path, version: &str, commit: Option<&str>) -> io::Result<Self> {
|
||||
let path = root.join(RECORD);
|
||||
let previous_unclean = regular_or_missing(&path)?;
|
||||
let own_record = serde_json::to_vec(&serde_json::json!({
|
||||
@@ -90,7 +115,7 @@ impl Session {
|
||||
"commit": commit.filter(|value| !value.is_empty()),
|
||||
}))?;
|
||||
atomic_write_no_follow(&path, &own_record)?;
|
||||
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
|
||||
Ok(Self { _lease: lease, path, own_record, previous_unclean })
|
||||
}
|
||||
|
||||
pub fn previous_unclean(&self) -> bool {
|
||||
@@ -258,6 +283,54 @@ mod tests {
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a controlled return clears its record");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ended_session_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
let first = Session::begin(Some(&fixture.0), "first", None).unwrap().unwrap();
|
||||
// A child process that is starting holds such a copy.
|
||||
let first_copy = first._lease.0.try_clone().unwrap();
|
||||
first.complete().unwrap();
|
||||
let second = Session::begin(Some(&fixture.0), "second", None).unwrap();
|
||||
assert!(second.is_some(), "a completed session frees the lease");
|
||||
let second_copy = second.as_ref().map(|session| session._lease.0.try_clone().unwrap());
|
||||
drop(second);
|
||||
assert!(Session::begin(Some(&fixture.0), "third", None).unwrap().is_some(), "a dropped session frees the lease");
|
||||
drop((first_copy, second_copy));
|
||||
}
|
||||
|
||||
/// `root`'s lease, locked as [`Session::begin`] locks it, and a copy of its handle such as a
|
||||
/// child process that is starting holds.
|
||||
fn locked_with_a_copy(root: &Path) -> (Lease, File) {
|
||||
let lease = Lease::take(root).unwrap().unwrap();
|
||||
let copy = lease.0.try_clone().unwrap();
|
||||
(lease, copy)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_cannot_check_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
std::fs::create_dir(fixture.0.join(RECORD)).unwrap();
|
||||
let (lease, copy) = locked_with_a_copy(&fixture.0);
|
||||
assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "a folder is not a record");
|
||||
std::fs::remove_dir(fixture.0.join(RECORD)).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to check its record frees the lease");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_cannot_write_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
// A folder at the temporary file's name makes the write fail after the record was checked.
|
||||
let temporary = fixture.0.join(format!(".{RECORD}.{}.tmp", std::process::id()));
|
||||
std::fs::create_dir(&temporary).unwrap();
|
||||
let (lease, copy) = locked_with_a_copy(&fixture.0);
|
||||
assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "the record cannot be written");
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
std::fs::remove_dir(&temporary).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to write its record frees the lease");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_never_removes_an_unknown_changed_record() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
@@ -145,6 +145,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_font_scans_read_the_fonts_folder_next_to_the_settings() {
|
||||
// No test installs a launch's root in this process, so the settings folder stays the same here.
|
||||
assert_eq!(profile::data_root(), None, "a test installed a launch's root beside the others");
|
||||
install_fonts();
|
||||
let fonts = prefs_dir().map(|dir| dir.join("Fonts"));
|
||||
assert!(fonts.is_some(), "a home folder to keep the settings in");
|
||||
|
||||
@@ -457,10 +457,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the process-wide root: the one test that may, since a `OnceLock` is set once per
|
||||
/// process (nextest gives every test its own).
|
||||
/// Runs the test `name` of this module again in a child process of the test binary → whether
|
||||
/// this is that child. For a test that installs the process-wide root, which every test running
|
||||
/// beside it would then read as the settings folder.
|
||||
fn in_own_process(name: &str) -> bool {
|
||||
const CHILD: &str = "VECTORCRAFT_TEST_OWN_PROCESS";
|
||||
if std::env::var_os(CHILD).is_some() {
|
||||
return true;
|
||||
}
|
||||
// The test's path without the crate's name: the desktop app and `vectorcraft-cli` both build this file.
|
||||
let module = module_path!().split_once("::").map_or(module_path!(), |(_, path)| path);
|
||||
let path = format!("{module}::{name}");
|
||||
let output =
|
||||
std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact", &path, "--nocapture"]).env(CHILD, "1").output().unwrap();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
|
||||
"{path} failed in its own process:\n{stdout}\n{}",
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
false
|
||||
}
|
||||
|
||||
/// Installs the process-wide root, which a `OnceLock` holds once per process, so the test runs in
|
||||
/// a process of its own.
|
||||
#[test]
|
||||
fn the_installed_root_is_used_once_and_must_be_absolute() {
|
||||
if !in_own_process("the_installed_root_is_used_once_and_must_be_absolute") {
|
||||
return;
|
||||
}
|
||||
let dir = temp("installed-root");
|
||||
assert!(install_data_root(PathBuf::from("relative/root")).is_err(), "a relative root is refused");
|
||||
install_data_root(dir.to_path_buf()).unwrap();
|
||||
|
||||
@@ -46,6 +46,17 @@ const SERVER_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
/// How long a launch waits on the primary: longer than a launch served before it can take.
|
||||
const CLIENT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// How long each side of a hand-over waits on the other.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Timeouts {
|
||||
connect: Duration,
|
||||
server: Duration,
|
||||
client: Duration,
|
||||
}
|
||||
|
||||
/// The waits a launch and the running app use.
|
||||
const TIMEOUTS: Timeouts = Timeouts { connect: CONNECT_TIMEOUT, server: SERVER_TIMEOUT, client: CLIENT_TIMEOUT };
|
||||
|
||||
/// Paths handed over by later launches that the UI hasn't opened yet.
|
||||
static PENDING: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
/// This app while it is the one later launches hand their files to ([`hold`]).
|
||||
@@ -68,25 +79,25 @@ pub fn start(automation: bool, new_instance: bool, safe_mode: bool, files: &[Str
|
||||
return Start::Running(None);
|
||||
}
|
||||
let Some(path) = prefs_dir().map(|dir| dir.join(FILE_NAME)) else { return Start::Running(None) };
|
||||
start_at(&path, new_instance, safe_mode, files)
|
||||
start_at(&path, TIMEOUTS, new_instance, safe_mode, files)
|
||||
}
|
||||
|
||||
/// [`start`] with the endpoint file `path`. A launch with `--new-instance` or `--safe-mode` keeps
|
||||
/// [`start`] with the endpoint file `path` and the waits `timeouts`. A launch with `--new-instance` or `--safe-mode` keeps
|
||||
/// its files and runs as its own app: a running app would open them with its plug-ins loaded. A
|
||||
/// `--safe-mode` launch never becomes the app later launches hand their files to, which would open
|
||||
/// them without plug-ins.
|
||||
fn start_at(path: &Path, new_instance: bool, safe_mode: bool, files: &[String]) -> Start {
|
||||
fn start_at(path: &Path, timeouts: Timeouts, new_instance: bool, safe_mode: bool, files: &[String]) -> Start {
|
||||
if safe_mode {
|
||||
return Start::Running(None);
|
||||
}
|
||||
// With nothing to hand over, the same exchange only asks whether an app is running.
|
||||
let send: &[String] = if new_instance { &[] } else { files };
|
||||
match forward(path, send) {
|
||||
match forward(path, timeouts, send) {
|
||||
Ok(()) if send.is_empty() => Start::Running(None),
|
||||
Ok(()) => Start::Forwarded,
|
||||
Err(e) => {
|
||||
log::debug!("no running VectorCraft to hand files to ({e})");
|
||||
Start::Running(listen(path, queue))
|
||||
Start::Running(listen(path, timeouts, queue))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -195,12 +206,12 @@ fn read_endpoint(path: &Path) -> Option<Endpoint> {
|
||||
|
||||
/// Hand `files` (made absolute against this launch's folder) to the app recorded at `path`; `Ok`
|
||||
/// once it acknowledged them.
|
||||
fn forward(path: &Path, files: &[String]) -> io::Result<()> {
|
||||
fn forward(path: &Path, timeouts: Timeouts, files: &[String]) -> io::Result<()> {
|
||||
let endpoint = read_endpoint(path).ok_or_else(|| invalid("no endpoint file"))?;
|
||||
let files = files.iter().map(|f| std::path::absolute(f).map(|p| p.to_string_lossy().into_owned())).collect::<io::Result<Vec<_>>>()?;
|
||||
let stream = TcpStream::connect_timeout(&(Ipv4Addr::LOCALHOST, endpoint.port).into(), CONNECT_TIMEOUT)?;
|
||||
stream.set_read_timeout(Some(CLIENT_TIMEOUT))?;
|
||||
stream.set_write_timeout(Some(CLIENT_TIMEOUT))?;
|
||||
let stream = TcpStream::connect_timeout(&(Ipv4Addr::LOCALHOST, endpoint.port).into(), timeouts.connect)?;
|
||||
stream.set_read_timeout(Some(timeouts.client))?;
|
||||
stream.set_write_timeout(Some(timeouts.client))?;
|
||||
// The token and the paths go only to a listener that knows the greeting.
|
||||
if !same(read_message(&stream)?.get("hello"), &endpoint.hello) {
|
||||
return Err(invalid("the listener isn't VectorCraft"));
|
||||
@@ -214,11 +225,11 @@ fn forward(path: &Path, files: &[String]) -> io::Result<()> {
|
||||
|
||||
/// Listen for later launches and record this app at `path`; each launch's files go to `deliver`.
|
||||
/// `None` when that fails (logged): the app then runs on its own, as before.
|
||||
fn listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> Option<Primary> {
|
||||
try_listen(path, deliver).inspect_err(|e| log::warn!("files opened while VectorCraft runs will open in another window: {e}")).ok()
|
||||
fn listen(path: &Path, timeouts: Timeouts, deliver: impl Fn(Vec<String>) + Send + 'static) -> Option<Primary> {
|
||||
try_listen(path, timeouts, deliver).inspect_err(|e| log::warn!("files opened while VectorCraft runs will open in another window: {e}")).ok()
|
||||
}
|
||||
|
||||
fn try_listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> io::Result<Primary> {
|
||||
fn try_listen(path: &Path, timeouts: Timeouts, deliver: impl Fn(Vec<String>) + Send + 'static) -> io::Result<Primary> {
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
|
||||
let port = listener.local_addr()?.port();
|
||||
let (token, hello) = random_tokens();
|
||||
@@ -227,7 +238,7 @@ fn try_listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> io
|
||||
let primary = Primary { path: path.to_path_buf(), token: token.clone() };
|
||||
std::thread::Builder::new().name("open-files-listener".into()).spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
match stream.and_then(|s| receive(&s, &hello, &token)) {
|
||||
match stream.and_then(|s| receive(&s, timeouts.server, &hello, &token)) {
|
||||
Ok(files) if files.is_empty() => {}
|
||||
Ok(files) => deliver(files),
|
||||
Err(e) => {
|
||||
@@ -241,10 +252,11 @@ fn try_listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> io
|
||||
Ok(primary)
|
||||
}
|
||||
|
||||
/// Serve one launch: greet it, check its token, keep the paths that are existing files.
|
||||
fn receive(stream: &TcpStream, hello: &str, token: &str) -> io::Result<Vec<String>> {
|
||||
stream.set_read_timeout(Some(SERVER_TIMEOUT))?;
|
||||
stream.set_write_timeout(Some(SERVER_TIMEOUT))?;
|
||||
/// Serve one launch, waiting on it at most `timeout`: greet it, check its token, keep the paths
|
||||
/// that are existing files.
|
||||
fn receive(stream: &TcpStream, timeout: Duration, hello: &str, token: &str) -> io::Result<Vec<String>> {
|
||||
stream.set_read_timeout(Some(timeout))?;
|
||||
stream.set_write_timeout(Some(timeout))?;
|
||||
write_message(stream, &json!({ "hello": hello }))?;
|
||||
let message = read_message(stream)?;
|
||||
if !same(message.get("token"), token) {
|
||||
@@ -357,17 +369,38 @@ mod tests {
|
||||
(dir.path().join(FILE_NAME), TestDir(dir), file)
|
||||
}
|
||||
|
||||
/// Stops a test that hangs. A hand-over on a busy machine still ends long before it, so no
|
||||
/// result depends on how long a step takes.
|
||||
const HANG_GUARD: Duration = Duration::from_secs(60);
|
||||
/// The waits both sides get in the tests.
|
||||
const PATIENT: Timeouts = Timeouts { connect: HANG_GUARD, server: HANG_GUARD, client: HANG_GUARD };
|
||||
|
||||
fn primary(path: &Path) -> (Primary, mpsc::Receiver<Vec<String>>) {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let primary = listen(path, move |files| tx.send(files).unwrap()).unwrap();
|
||||
let primary = listen(path, PATIENT, move |files| tx.send(files).unwrap()).unwrap();
|
||||
(primary, rx)
|
||||
}
|
||||
|
||||
/// The next files the app delivered. The app delivers them after it acknowledges the launch,
|
||||
/// so this waits for them.
|
||||
fn delivered(rx: &mpsc::Receiver<Vec<String>>) -> Vec<String> {
|
||||
rx.recv_timeout(HANG_GUARD).unwrap_or_else(|e| panic!("the app delivered no files: {e}"))
|
||||
}
|
||||
|
||||
/// `result` is an error from the other side, not a wait that ran out.
|
||||
fn refused<T>(result: io::Result<T>) -> bool {
|
||||
result.is_err_and(|e| {
|
||||
assert!(!matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut), "a wait ran out instead: {e}");
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
/// Connects as a launch would and sends `message` after the greeting; what came back.
|
||||
fn send_raw(path: &Path, message: &[u8]) -> io::Result<Value> {
|
||||
let endpoint = read_endpoint(path).unwrap();
|
||||
let stream = TcpStream::connect((Ipv4Addr::LOCALHOST, endpoint.port)).unwrap();
|
||||
stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap();
|
||||
stream.set_read_timeout(Some(HANG_GUARD)).unwrap();
|
||||
stream.set_write_timeout(Some(HANG_GUARD)).unwrap();
|
||||
assert!(same(read_message(&stream).unwrap().get("hello"), &endpoint.hello));
|
||||
(&stream).write_all(message)?;
|
||||
read_message(&stream)
|
||||
@@ -378,12 +411,12 @@ mod tests {
|
||||
let (path, dir, file) = folder("forward");
|
||||
let (primary, rx) = primary(&path);
|
||||
let missing = dir.join("missing.svg").to_string_lossy().into_owned();
|
||||
forward(&path, &[file.clone(), missing]).unwrap();
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file), "the missing file is left out");
|
||||
forward(&path, PATIENT, &[file.clone(), missing]).unwrap();
|
||||
assert_eq!(delivered(&rx), std::slice::from_ref(&file), "the missing file is left out");
|
||||
// An empty list only asks whether the app runs: nothing is delivered.
|
||||
forward(&path, &[]).unwrap();
|
||||
forward(&path, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
|
||||
forward(&path, PATIENT, &[]).unwrap();
|
||||
forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(delivered(&rx), [file]);
|
||||
drop(primary);
|
||||
assert!(!path.exists(), "the endpoint file goes with the app");
|
||||
}
|
||||
@@ -393,11 +426,11 @@ mod tests {
|
||||
let (path, _dir, file) = folder("own");
|
||||
let (primary, rx) = primary(&path);
|
||||
for (new_instance, safe_mode) in [(true, false), (false, true)] {
|
||||
let start = start_at(&path, new_instance, safe_mode, std::slice::from_ref(&file));
|
||||
let start = start_at(&path, PATIENT, new_instance, safe_mode, std::slice::from_ref(&file));
|
||||
assert!(matches!(start, Start::Running(None)), "runs as its own app (new instance {new_instance}, Safe Mode {safe_mode})");
|
||||
}
|
||||
assert!(matches!(start_at(&path, false, false, std::slice::from_ref(&file)), Start::Forwarded));
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file));
|
||||
assert!(matches!(start_at(&path, PATIENT, false, false, std::slice::from_ref(&file)), Start::Forwarded));
|
||||
assert_eq!(delivered(&rx), std::slice::from_ref(&file));
|
||||
assert!(rx.try_recv().is_err(), "only the plain launch handed its file over");
|
||||
drop(primary);
|
||||
}
|
||||
@@ -407,10 +440,10 @@ mod tests {
|
||||
let _globals = globals();
|
||||
let (path, _dir, file) = folder("safe-mode-alone");
|
||||
// With no app running, a Safe Mode launch runs without listening.
|
||||
assert!(matches!(start_at(&path, false, true, std::slice::from_ref(&file)), Start::Running(None)));
|
||||
assert!(matches!(start_at(&path, PATIENT, false, true, std::slice::from_ref(&file)), Start::Running(None)));
|
||||
assert!(!path.exists(), "a Safe Mode launch records no endpoint");
|
||||
// A plain launch after it starts its own app and takes later launches' files.
|
||||
let Start::Running(Some(primary)) = start_at(&path, false, false, std::slice::from_ref(&file)) else {
|
||||
let Start::Running(Some(primary)) = start_at(&path, PATIENT, false, false, std::slice::from_ref(&file)) else {
|
||||
panic!("the plain launch runs and listens")
|
||||
};
|
||||
assert!(path.exists());
|
||||
@@ -427,7 +460,7 @@ mod tests {
|
||||
resign();
|
||||
drop(take());
|
||||
let (path, _dir, file) = folder("safe-mode-later");
|
||||
let Start::Running(Some(primary)) = start_at(&path, false, false, &[]) else { panic!("the first launch listens") };
|
||||
let Start::Running(Some(primary)) = start_at(&path, PATIENT, false, false, &[]) else { panic!("the first launch listens") };
|
||||
hold(Some(primary));
|
||||
// A later launch handed its file over while the choice about a stopped plug-in was up.
|
||||
queue(vec![file.clone()]);
|
||||
@@ -460,17 +493,18 @@ mod tests {
|
||||
let (_primary, rx) = primary(&path);
|
||||
let token = read_endpoint(&path).unwrap().token;
|
||||
let wrong = format!("{}\n", json!({ "token": "0".repeat(token.len()), "files": [file] }));
|
||||
assert!(send_raw(&path, wrong.as_bytes()).is_err());
|
||||
assert!(send_raw(&path, b"not json\n").is_err());
|
||||
assert!(send_raw(&path, &vec![b'a'; MAX_MESSAGE as usize + 10]).is_err());
|
||||
assert!(refused(send_raw(&path, wrong.as_bytes())));
|
||||
assert!(refused(send_raw(&path, b"not json\n")));
|
||||
assert!(refused(send_raw(&path, &vec![b'a'; MAX_MESSAGE as usize + 10])));
|
||||
let many = format!("{}\n", json!({ "token": token, "files": vec![file.clone(); MAX_FILES + 1] }));
|
||||
assert!(send_raw(&path, many.as_bytes()).is_err());
|
||||
assert!(refused(send_raw(&path, many.as_bytes())));
|
||||
let relative = format!("{}\n", json!({ "token": token, "files": ["a b.svg", 7] }));
|
||||
assert_eq!(send_raw(&path, relative.as_bytes()).unwrap(), json!({ "ok": true }));
|
||||
assert!(rx.try_recv().is_err(), "nothing was delivered");
|
||||
// The listener still serves a launch with the right token.
|
||||
forward(&path, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
|
||||
// The listener still serves a launch with the right token. It serves launches in turn, so
|
||||
// anything delivered for the messages above would come before this file.
|
||||
forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(delivered(&rx), [file]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -483,27 +517,28 @@ mod tests {
|
||||
let port = gone.local_addr().unwrap().port();
|
||||
write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap();
|
||||
let closed = std::thread::spawn(move || drop(gone.accept()));
|
||||
assert!(forward(&path, std::slice::from_ref(&file)).is_err());
|
||||
assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file))));
|
||||
closed.join().unwrap();
|
||||
// A listener that doesn't know the greeting gets neither the token nor the paths.
|
||||
// A listener that doesn't know the greeting gets neither the token nor the paths: the
|
||||
// launch closes the connection instead.
|
||||
let impostor = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let port = impostor.local_addr().unwrap().port();
|
||||
write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap();
|
||||
let heard = std::thread::spawn(move || {
|
||||
let (stream, _) = impostor.accept().unwrap();
|
||||
write_message(&stream, &json!({ "hello": "x" })).unwrap();
|
||||
stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap();
|
||||
read_message(&stream).ok()
|
||||
stream.set_read_timeout(Some(HANG_GUARD)).unwrap();
|
||||
read_message(&stream)
|
||||
});
|
||||
assert!(forward(&path, std::slice::from_ref(&file)).is_err());
|
||||
assert!(heard.join().unwrap().is_none());
|
||||
assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file))));
|
||||
assert!(refused(heard.join().unwrap()));
|
||||
// Garbage in the file is no endpoint either.
|
||||
fs::write(&path, b"\xff not json").unwrap();
|
||||
assert!(forward(&path, std::slice::from_ref(&file)).is_err());
|
||||
assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file))));
|
||||
// A new primary replaces the stale file.
|
||||
let (_primary, rx) = primary(&path);
|
||||
forward(&path, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
|
||||
forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap();
|
||||
assert_eq!(delivered(&rx), [file]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Invalid roots must exit before desktop initialization on every platform, including a CI
|
||||
/// machine with no display. A regression must fail rather than hang with a window open.
|
||||
@@ -7,9 +6,14 @@ fn rejects(args: &[&str], message: &str) {
|
||||
rejects_with_env(args, &[], message);
|
||||
}
|
||||
|
||||
/// Runs the desktop binary without a display, so on Linux a regression exits with a display
|
||||
/// error, which the exact stderr check rejects, instead of opening a window.
|
||||
fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) {
|
||||
let mut child = Command::new(crate::bin())
|
||||
let child = Command::new(crate::bin())
|
||||
.args(args)
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WAYLAND_SOCKET")
|
||||
.env_remove("VECTORCRAFT_CONTROL_PORT")
|
||||
.env_remove("VECTORCRAFT_AUTOMATION_READ_ROOT")
|
||||
.env_remove("VECTORCRAFT_AUTOMATION_WRITE_ROOT")
|
||||
@@ -20,21 +24,7 @@ fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) {
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
// Long enough for the binary to start on a loaded machine (the workspace's other tests run
|
||||
// meanwhile), short enough to catch a desktop that started instead of exiting.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let timed_out = loop {
|
||||
if child.try_wait().unwrap().is_some() {
|
||||
break false;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
child.kill().unwrap();
|
||||
break true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
let out = child.wait_with_output().unwrap();
|
||||
assert!(!timed_out, "{args:?}: desktop started or did not exit promptly");
|
||||
let out = crate::exit_output(child, &format!("{args:?}: the desktop started instead of exiting"));
|
||||
assert!(!out.status.success(), "{args:?}");
|
||||
assert!(out.stdout.is_empty(), "{args:?}: {:?}", out.stdout);
|
||||
// Exact stderr excludes unrelated startup warnings or display errors that could otherwise
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
//! `vectorcraft --help` prints the usage and exits before the app starts (#2110): run from a
|
||||
//! terminal, SSH or an agent's shell it used to open the window (or hang without a display).
|
||||
|
||||
use std::io::Read;
|
||||
use std::process::{Command, Output, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Runs the desktop binary without a display and with a control port it cannot parse, so a
|
||||
/// regression exits with that error instead of opening a window.
|
||||
fn run(args: &[&str], env: &[(&str, &str)]) -> Output {
|
||||
let mut child = Command::new(crate::bin())
|
||||
let child = Command::new(crate::bin())
|
||||
.args(args)
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
@@ -22,28 +19,7 @@ fn run(args: &[&str], env: &[(&str, &str)]) -> Output {
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
// Both pipes end when the binary exits, however long a loaded machine takes to start it. The
|
||||
// deadline only stops a binary that is still running.
|
||||
let deadline = Instant::now() + Duration::from_secs(120);
|
||||
let stdout = read_to_end(child.stdout.take().unwrap());
|
||||
let stderr = read_to_end(child.stderr.take().unwrap());
|
||||
let recv = |rx: &mpsc::Receiver<Vec<u8>>| rx.recv_timeout(deadline.saturating_duration_since(Instant::now()));
|
||||
let (Ok(stdout), Ok(stderr)) = (recv(&stdout), recv(&stderr)) else {
|
||||
child.kill().unwrap();
|
||||
panic!("{args:?}: the app started instead of printing its usage");
|
||||
};
|
||||
Output { status: child.wait().unwrap(), stdout, stderr }
|
||||
}
|
||||
|
||||
/// Reads `pipe` to its end on another thread.
|
||||
fn read_to_end(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver<Vec<u8>> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
let _ = tx.send(buf);
|
||||
});
|
||||
rx
|
||||
crate::exit_output(child, &format!("{args:?}: the app started instead of printing its usage"))
|
||||
}
|
||||
|
||||
fn prints_usage(args: &[&str], env: &[(&str, &str)]) {
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::io::Read;
|
||||
use std::process::{Child, Output};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
mod automation_args;
|
||||
mod help;
|
||||
|
||||
@@ -12,3 +17,70 @@ fn bin() -> std::path::PathBuf {
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft").into())
|
||||
}
|
||||
|
||||
/// Waits for `child`, spawned with piped stdout and stderr, to exit and returns its output. Both
|
||||
/// pipes end when the binary exits, however long a loaded machine takes to start it. The deadline
|
||||
/// only stops a binary that is still running: the test then fails with `started`.
|
||||
fn exit_output(child: Child, started: &str) -> Output {
|
||||
exit_output_by(child, started, Instant::now() + Duration::from_secs(120))
|
||||
}
|
||||
|
||||
/// [`exit_output`] with the deadline given. A binary that has exited by the deadline passes even
|
||||
/// when its output arrives after it; the output then has 10 seconds more to arrive.
|
||||
fn exit_output_by(mut child: Child, started: &str, deadline: Instant) -> Output {
|
||||
let stdout = read_to_end(child.stdout.take().unwrap());
|
||||
let stderr = read_to_end(child.stderr.take().unwrap());
|
||||
let (mut out, mut err) = (None, None);
|
||||
if !receive([(&stdout, &mut out), (&stderr, &mut err)], deadline) && child.try_wait().unwrap().is_none() {
|
||||
child.kill().unwrap();
|
||||
child.wait().unwrap();
|
||||
panic!("{started}");
|
||||
}
|
||||
receive([(&stdout, &mut out), (&stderr, &mut err)], Instant::now() + Duration::from_secs(10));
|
||||
let (Some(stdout), Some(stderr)) = (out, err) else {
|
||||
panic!("{started}: the binary exited, but its output pipes stayed open");
|
||||
};
|
||||
Output { status: child.wait().unwrap(), stdout, stderr }
|
||||
}
|
||||
|
||||
/// A pipe's reader and the slot that holds its output once it arrives.
|
||||
type Pipe<'a> = (&'a mpsc::Receiver<Vec<u8>>, &'a mut Option<Vec<u8>>);
|
||||
|
||||
/// Fills each empty slot from its reader, waiting until `until` at the latest. Returns whether
|
||||
/// every slot is filled.
|
||||
fn receive(pipes: [Pipe<'_>; 2], until: Instant) -> bool {
|
||||
let mut filled = true;
|
||||
for (rx, slot) in pipes {
|
||||
if slot.is_none() {
|
||||
*slot = rx.recv_timeout(until.saturating_duration_since(Instant::now())).ok();
|
||||
}
|
||||
filled &= slot.is_some();
|
||||
}
|
||||
filled
|
||||
}
|
||||
|
||||
/// Reads `pipe` to its end on another thread.
|
||||
fn read_to_end(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver<Vec<u8>> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
let _ = tx.send(buf);
|
||||
});
|
||||
rx
|
||||
}
|
||||
|
||||
/// A binary that exits before the deadline passes even when a process it started keeps its
|
||||
/// output pipes open past the deadline.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn exit_output_accepts_an_exit_whose_output_arrives_after_the_deadline() {
|
||||
use std::process::{Command, Stdio};
|
||||
let mut child =
|
||||
Command::new("sh").args(["-c", "sleep 1 & exit 0"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
// `sh` has exited; the `sleep` it started still holds both pipes for about a second.
|
||||
child.wait().unwrap();
|
||||
let out = exit_output_by(child, "an exited binary was reported as running", Instant::now());
|
||||
assert!(out.status.success());
|
||||
assert!(out.stdout.is_empty() && out.stderr.is_empty());
|
||||
}
|
||||
@@ -309,7 +309,7 @@ pub struct Scatter {
|
||||
pub art: Node,
|
||||
/// Size range in percent of the art.
|
||||
pub size: (f64, f64),
|
||||
/// Spacing range in percent of the (scaled) art width.
|
||||
/// Spacing range in percent of the (scaled) art width, its strokes included.
|
||||
pub spacing: (f64, f64),
|
||||
/// Perpendicular offset range in percent of the (scaled) art height.
|
||||
pub scatter: (f64, f64),
|
||||
|
||||
@@ -272,6 +272,22 @@ fn scatter_count_and_spacing() {
|
||||
assert_eq!(out.len(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_spaces_stroked_art_by_its_stroked_width() {
|
||||
let art = Node::path(
|
||||
NodeId(0),
|
||||
shapes::rectangle(Rect::new(0.0, -2.0, 10.0, 2.0)),
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0),
|
||||
);
|
||||
let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) };
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 120.0, 0.0), &stroke(1.0));
|
||||
let boxes: Vec<Rect> = out.iter().filter_map(Node::visual_bounds).collect();
|
||||
assert!(boxes.len() > 1, "{boxes:?}");
|
||||
for w in boxes.windows(2) {
|
||||
assert!(near(w[1].x0, w[0].x1, 1e-6), "stroked copies at 100% spacing touch: {boxes:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_is_deterministic_and_randomised() {
|
||||
let b = Brush {
|
||||
|
||||
@@ -540,7 +540,10 @@ fn vary(rng: &mut Rng, (a, b): (f64, f64), mode: Variation, pen: PenAt) -> f64 {
|
||||
|
||||
pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec<Node> {
|
||||
let Some(b) = sc.art.geometric_bounds() else { return vec![] };
|
||||
let (aw, ah) = (b.width().max(1e-3), b.height().max(1e-3));
|
||||
// Copies are spaced by the width of the art with its strokes, so at 100% spacing stroked
|
||||
// copies touch instead of overlapping by the stroke.
|
||||
let aw = sc.art.visual_bounds().unwrap_or(b).width().max(1e-3);
|
||||
let ah = b.height().max(1e-3);
|
||||
let mut rng = Rng::new(seed_of(bp, name));
|
||||
let [size_mode, spacing_mode, scatter_mode, rotation_mode] = sc.modes();
|
||||
let mut out = Budget::default();
|
||||
@@ -1129,11 +1132,23 @@ mod tests {
|
||||
/// Fitting is bounded however badly the map behaves: where it gives points that are not finite
|
||||
/// the tile falls back to chords with those points left out (or to nothing), and where it never
|
||||
/// fits (a map that jumps everywhere) the halving stops at its depth and anchor count. Either
|
||||
/// way the call comes back promptly with finite geometry.
|
||||
/// way the call comes back with finite geometry, having called the map a bounded number of
|
||||
/// times.
|
||||
#[test]
|
||||
fn a_map_that_misbehaves_still_returns_promptly_and_finite() {
|
||||
let b = Rect::new(0.0, -20.0, 40.0, 20.0);
|
||||
let tile = circle_tile(b);
|
||||
// Each piece the fitting tries reads its two ends, the derivatives there and the checks
|
||||
// between them. Fitted pieces are at most the chords, so the halving tries at most twice
|
||||
// as many pieces plus those on the way down to the one that gives up. The chord route
|
||||
// maps each chord point once more.
|
||||
let NodeKind::Path { path, .. } = &tile.kind else { panic!("the tile is a path") };
|
||||
let allowed: usize = path
|
||||
.subpaths
|
||||
.iter()
|
||||
.filter_map(|sp| densified(sp, 0.25, 1.5))
|
||||
.map(|dense| 1 + (FIT_CHECKS + 3) * (2 * dense.len() + FIT_DEPTH as usize + 1) + dense.len())
|
||||
.sum();
|
||||
let finite = |n: &Node| match &n.kind {
|
||||
NodeKind::Path { path, .. } => {
|
||||
path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite())
|
||||
@@ -1147,9 +1162,14 @@ mod tests {
|
||||
&|_| Point::new(f64::NAN, f64::NAN),
|
||||
];
|
||||
for (i, f) in maps.iter().enumerate() {
|
||||
let t0 = std::time::Instant::now();
|
||||
let out = warp_node(&tile, f, 0.25, 1.5, 0.25, 1.0);
|
||||
assert!(t0.elapsed() < std::time::Duration::from_secs(2), "map {i} took {:?}", t0.elapsed());
|
||||
// Past the allowance the map places nothing, so a warp that keeps calling it stops.
|
||||
let calls = std::cell::Cell::new(0usize);
|
||||
let counted = |p: Point| {
|
||||
calls.set(calls.get() + 1);
|
||||
if calls.get() > allowed { Point::new(f64::NAN, f64::NAN) } else { f(p) }
|
||||
};
|
||||
let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0);
|
||||
assert!(calls.get() <= allowed, "map {i} was called {} times, {allowed} allowed", calls.get());
|
||||
match (i, &out) {
|
||||
(3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"),
|
||||
(_, Some(n)) => assert!(finite(n), "map {i} drew non-finite geometry"),
|
||||
|
||||
@@ -708,16 +708,29 @@ fn rgb_color([r, g, b]: [u8; 3]) -> Color {
|
||||
Color::rgb8(r, g, b)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many names [`unique`] tried on this thread (tests).
|
||||
pub(crate) static SYMBOL_NAMES_TRIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Whether `taken` holds `name`, counted as one name tried (tests).
|
||||
fn is_taken(taken: &HashSet<String>, name: &str) -> bool {
|
||||
#[cfg(test)]
|
||||
SYMBOL_NAMES_TRIED.with(|n| n.set(n.get().saturating_add(1)));
|
||||
taken.contains(name)
|
||||
}
|
||||
|
||||
/// `base`, or `base 2`, `base 3`… when taken; `next` remembers where each base left off.
|
||||
fn unique(base: &str, next: &mut HashMap<String, usize>, taken: &HashSet<String>) -> String {
|
||||
if !taken.contains(base) {
|
||||
if !is_taken(taken, base) {
|
||||
return base.to_string();
|
||||
}
|
||||
let i = next.entry(base.to_string()).or_insert(2);
|
||||
loop {
|
||||
let name = format!("{base} {i}");
|
||||
*i += 1;
|
||||
if !taken.contains(&name) {
|
||||
if !is_taken(taken, &name) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,6 +175,32 @@ fn layer(l: model::Layer) -> LayerDef {
|
||||
/// drawings have a few dozen layouts with short names.
|
||||
const MAX_LAYOUT_NAME_BYTES: usize = 4 << 20;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`layouts`] compared two layout names on this thread (tests).
|
||||
pub(crate) static LAYOUT_NAME_COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A paper layout's name as [`layouts`] de-duplicates it (lower case: names differing only in
|
||||
/// ASCII case are one layout).
|
||||
struct LayoutKey(String);
|
||||
|
||||
impl PartialEq for LayoutKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
LAYOUT_NAME_COMPARISONS.with(|n| n.set(n.get().saturating_add(1)));
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for LayoutKey {}
|
||||
|
||||
impl std::hash::Hash for LayoutKey {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.0.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Model space, then each paper layout (its LAYOUT object, in tab order); a file without layout
|
||||
/// objects but with paper-space art has one paper layout.
|
||||
fn layouts(doc: &model::Document<'_>, block_names: &HashMap<u64, &str>) -> Vec<LayoutDef> {
|
||||
@@ -187,7 +213,7 @@ fn layouts(doc: &model::Document<'_>, block_names: &HashMap<u64, &str>) -> Vec<L
|
||||
continue;
|
||||
}
|
||||
let Some(block) = block else { continue };
|
||||
let key = l.name.to_ascii_lowercase();
|
||||
let key = LayoutKey(l.name.to_ascii_lowercase());
|
||||
let cost = l.name.len() + block.len();
|
||||
// A layout past the allowance is skipped alone: a later short one is still offered, and a
|
||||
// skipped one reserves neither its name nor its bytes.
|
||||
|
||||
@@ -743,15 +743,16 @@ fn many_by_block_looks_import_in_linear_time() {
|
||||
inserts.extend([(0, "INSERT"), (2, "Door"), (420, colour), (10, "0"), (20, "0")]);
|
||||
}
|
||||
let text = with_door(by_block, &inserts);
|
||||
let start = std::time::Instant::now();
|
||||
build::SYMBOL_NAMES_TRIED.with(|t| t.set(0));
|
||||
let doc = open(&text, &points()).document;
|
||||
let took = start.elapsed();
|
||||
let tried = build::SYMBOL_NAMES_TRIED.with(std::cell::Cell::get);
|
||||
let mut names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names.len(), n);
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
assert_eq!(names.len(), n, "names stay unique");
|
||||
assert!(took < std::time::Duration::from_secs(4), "import took {took:?}");
|
||||
// Each symbol after the first tries its label and then the next free suffix.
|
||||
assert!(tried < 2 * n, "{tried} names tried for {n} symbols");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1001,7 +1002,7 @@ fn binary_dwg_damaged_and_foreign_files() {
|
||||
// A binary DXF opens as its ASCII form does.
|
||||
let ascii = entities(LINE);
|
||||
let tags = craft_dxf::parse(&ascii).unwrap();
|
||||
let r = open(&craft_dxf::write_binary(&tags, true), &points());
|
||||
let r = open(&craft_dxf::write_binary(&tags, true).unwrap(), &points());
|
||||
assert_eq!(leaves(&r.document).len(), 1);
|
||||
let e = import(b"AC1032\x00\x00\x00", &ImportOptions::default()).unwrap_err();
|
||||
assert!(e.contains("DWG"), "{e}");
|
||||
@@ -1151,12 +1152,13 @@ fn with_layouts(names: &[String]) -> Vec<u8> {
|
||||
|
||||
#[test]
|
||||
fn many_paper_layouts_are_read_in_linear_time() {
|
||||
let names: Vec<String> = (0..100_000).map(|i| format!("L{i}")).collect();
|
||||
let names: Vec<String> = (0..10_000).map(|i| format!("L{i}")).collect();
|
||||
let bytes = with_layouts(&names);
|
||||
let t = std::time::Instant::now();
|
||||
reader::LAYOUT_NAME_COMPARISONS.with(|c| c.set(0));
|
||||
let info = info(&bytes).unwrap();
|
||||
let compared = reader::LAYOUT_NAME_COMPARISONS.with(std::cell::Cell::get);
|
||||
assert_eq!(info.layouts.len(), names.len() + 1);
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5), "layout de-duplication is quadratic: {:?}", t.elapsed());
|
||||
assert!(compared <= names.len(), "layout de-duplication compared {compared} names for {} layouts", names.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+17
-3
@@ -1211,7 +1211,18 @@ pub fn active_settings() -> ColorSettings {
|
||||
|
||||
/// The color-management context of Edit → Color Settings (the working spaces, intent and black
|
||||
/// point compensation), as [`set_active`] last set them, whatever profiles a document is assigned.
|
||||
/// Inside [`with_active`] on this thread: the working settings of the settings it was given.
|
||||
pub fn working() -> Arc<Cms> {
|
||||
if SCOPED_FLAGS.with(Cell::get) & SCOPED_SET != 0
|
||||
&& let Some(c) = SCOPED.with(|s| s.borrow().clone())
|
||||
{
|
||||
return c.working.clone().unwrap_or(c);
|
||||
}
|
||||
installed_working()
|
||||
}
|
||||
|
||||
/// The working settings of the process, as [`set_active`] last set them.
|
||||
fn installed_working() -> Arc<Cms> {
|
||||
if let Some(c) = WORKING.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
|
||||
return c.clone();
|
||||
}
|
||||
@@ -1241,7 +1252,7 @@ pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> {
|
||||
/// is not of its model, leaves the working space. The working settings stay as they are. True when
|
||||
/// the active settings changed.
|
||||
pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool {
|
||||
let working = working();
|
||||
let working = installed_working();
|
||||
let st = document_settings(&working.settings, rgb, cmyk);
|
||||
if st == installed().settings {
|
||||
return false;
|
||||
@@ -1281,7 +1292,7 @@ const DOCUMENT_CONTEXTS: usize = 8;
|
||||
/// loaded gives the working settings.
|
||||
pub fn for_document(rgb: Option<&str>, cmyk: Option<&str>) -> Arc<Cms> {
|
||||
static KEPT: Mutex<Vec<(u64, Arc<Cms>)>> = Mutex::new(Vec::new());
|
||||
let working = working();
|
||||
let working = installed_working();
|
||||
let st = document_settings(&working.settings, rgb, cmyk);
|
||||
let installed = installed();
|
||||
if st == installed.settings {
|
||||
@@ -1308,7 +1319,10 @@ pub fn for_document(rgb: Option<&str>, cmyk: Option<&str>) -> Arc<Cms> {
|
||||
|
||||
/// Run `f` with `cms` as the active settings on this thread ([`active`], [`crate::Color::to_rgb`]
|
||||
/// and the conversions that read them), as when drawing a document other than the front one
|
||||
/// through its own profiles. Other threads, and this thread after `f`, keep the settings they had.
|
||||
/// through its own profiles, and with the working settings `cms` was made from as the working
|
||||
/// settings ([`working`]): the ones [`for_document`] put the document's profiles in place of, else
|
||||
/// `cms` itself. A [`set_active`] while `f` runs, on any thread, does not change either on this
|
||||
/// thread. Other threads, and this thread after `f`, keep the settings they had.
|
||||
pub fn with_active<R>(cms: Arc<Cms>, f: impl FnOnce() -> R) -> R {
|
||||
/// Puts back the settings this thread had before, when `f` returns or unwinds.
|
||||
struct Restore(Option<Arc<Cms>>, u8);
|
||||
|
||||
@@ -519,6 +519,33 @@ fn with_active_puts_settings_in_place_on_this_thread_only() {
|
||||
assert_eq!((rgb.to_rgb(), ink.to_rgb()), before, "the active settings come back after a panic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_active_keeps_its_working_settings_while_another_thread_sets_them() {
|
||||
let before = working_settings();
|
||||
let p3 = Arc::new(Cms::new(&ColorSettings { rgb: DISPLAY_P3.into(), cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap());
|
||||
let (inside, after_other, other) = with_active(p3.clone(), || {
|
||||
let inside = working();
|
||||
// The same settings again, so other tests in this binary see the same values.
|
||||
let again = before.clone();
|
||||
let other = std::thread::spawn(move || {
|
||||
set_active(&again).unwrap();
|
||||
working()
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
(inside, working(), other)
|
||||
});
|
||||
assert!(Arc::ptr_eq(&inside, &p3), "settings made from no others are their own working settings");
|
||||
assert!(Arc::ptr_eq(&after_other, &p3), "a set_active on another thread leaves this thread's working settings");
|
||||
assert!(!Arc::ptr_eq(&other, &p3), "the other thread has the settings it set");
|
||||
assert_eq!(working_settings(), before, "the working settings come back after");
|
||||
// A document's context keeps the working settings it was made from.
|
||||
let doc = for_document(Some(DISPLAY_P3), None);
|
||||
let (active, working) = with_active(doc, || (active_settings(), working_settings()));
|
||||
assert_eq!(active.rgb, DISPLAY_P3, "the document's profile is active");
|
||||
assert_eq!(working, before, "the working RGB space stays the working one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_gets_the_same_context_for_the_same_profiles() {
|
||||
// Other tests load profiles meanwhile, and a load makes the contexts again: try until one pair
|
||||
|
||||
@@ -57,6 +57,37 @@ impl Document {
|
||||
pick(&|r| r.contains(p)).or_else(|| pick(&|r| artboard_holds(r, p)))
|
||||
}
|
||||
|
||||
/// Which artboard in the document owns object bounds `b`: the artboard that holds its center,
|
||||
/// or the one it has the greatest overlap area with if its center lies outside all artboards.
|
||||
/// Bounds with no width or no height (a straight horizontal or vertical line) have no area, so
|
||||
/// for them the overlap is the length of the line on the artboard.
|
||||
pub fn artboard_for_bounds(&self, b: Rect) -> Option<usize> {
|
||||
let c = b.center();
|
||||
if let Some(i) = self.artboard_holding(c, false) {
|
||||
return Some(i);
|
||||
}
|
||||
let (flat_x, flat_y) = (b.x1 - b.x0 <= 1e-9, b.y1 - b.y0 <= 1e-9);
|
||||
let mut best: Option<(usize, f64)> = None;
|
||||
for (i, a) in self.artboards.iter().enumerate() {
|
||||
let r = a.rect;
|
||||
let w = b.x1.min(r.x1) - b.x0.max(r.x0);
|
||||
let h = b.y1.min(r.y1) - b.y0.max(r.y0);
|
||||
if w < 0.0 || h < 0.0 {
|
||||
continue;
|
||||
}
|
||||
let overlap = match (flat_x, flat_y) {
|
||||
(true, true) => 0.0,
|
||||
(true, false) => h,
|
||||
(false, true) => w,
|
||||
(false, false) => w * h,
|
||||
};
|
||||
if overlap > 1e-9 && best.is_none_or(|(_, max)| overlap > max + 1e-9) {
|
||||
best = Some((i, overlap));
|
||||
}
|
||||
}
|
||||
best.map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// The art that moves with an artboard at `rect`: top-level objects (children of layers and
|
||||
/// sublayers) lying entirely inside it, with symbol instances measured by their art. Locked and
|
||||
/// hidden objects and layers stay put unless `locked_and_hidden` (Selection & Anchor Display ›
|
||||
@@ -89,6 +120,54 @@ impl Document {
|
||||
art
|
||||
}
|
||||
|
||||
/// The art that is copied when artboard `index` is duplicated or copied: objects wholly inside
|
||||
/// the artboard (with rounding tolerance), objects within its bleed rectangle, and artwork
|
||||
/// placed on/overlapping this artboard that belongs to it by center or primary overlap
|
||||
/// ([`Document::artboard_for_bounds`]).
|
||||
pub fn art_for_artboard_copy(&self, index: usize, locked_and_hidden: bool) -> Vec<NodeId> {
|
||||
let Some(rect) = self.artboards.get(index).map(|a| a.rect) else { return vec![] };
|
||||
let r = rect.inflate(1e-6, 1e-6);
|
||||
let on_copy = |b: Rect| -> bool {
|
||||
// 1. Wholly inside the artboard (edges included, with tolerance).
|
||||
if b.x0 >= r.x0 && b.y0 >= r.y0 && b.x1 <= r.x1 && b.y1 <= r.y1 {
|
||||
return true;
|
||||
}
|
||||
// 2. Within the artboard's bleed rectangle (if document setup specifies bleed).
|
||||
if self.setup.has_bleed() {
|
||||
let br = self.setup.bleed_rect(rect).inflate(1e-6, 1e-6);
|
||||
if b.x0 >= br.x0 && b.y0 >= br.y0 && b.x1 <= br.x1 && b.y1 <= br.y1 {
|
||||
return self.artboard_for_bounds(b).is_none_or(|owner| owner == index);
|
||||
}
|
||||
}
|
||||
// 3. Artwork that intersects this artboard and belongs to it (#4479).
|
||||
let inter_x0 = b.x0.max(r.x0);
|
||||
let inter_y0 = b.y0.max(r.y0);
|
||||
let inter_x1 = b.x1.min(r.x1);
|
||||
let inter_y1 = b.y1.min(r.y1);
|
||||
if inter_x1 < inter_x0 || inter_y1 < inter_y0 {
|
||||
return false;
|
||||
}
|
||||
self.artboard_for_bounds(b) == Some(index)
|
||||
};
|
||||
fn collect(n: &Node, s: &SymbolBoxes, on: &dyn Fn(Rect) -> bool, all: bool, out: &mut Vec<NodeId>) {
|
||||
for c in n.children().into_iter().flatten().filter(|c| c.rides_with_artboard(all)) {
|
||||
if c.is_layer() {
|
||||
collect(c, s, on, all, out);
|
||||
} else if let Some(b) = c.geometric_bounds_with(s)
|
||||
&& on(b)
|
||||
{
|
||||
out.push(c.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let symbols = self.symbol_boxes();
|
||||
let mut art = vec![];
|
||||
for l in self.layers.iter().filter(|l| l.rides_with_artboard(locked_and_hidden)) {
|
||||
collect(l, &symbols, &on_copy, locked_and_hidden, &mut art);
|
||||
}
|
||||
art
|
||||
}
|
||||
|
||||
/// Does any artwork lie on `rect` (an artboard)? Artwork is any object under the layers,
|
||||
/// hidden and locked ones and those on template layers included, whose visual bounds (symbol
|
||||
/// instances measured by their art) meet `rect`; touching its edge counts. A group (not a clip
|
||||
|
||||
+265
-20
@@ -81,6 +81,11 @@ pub struct HitOptions {
|
||||
/// The point hit tests ([`hit_test`], [`hit_test_visible`] and [`hit_test_visible_skipping`])
|
||||
/// hit the art on a layer whose Preview is off as painted, not in outline.
|
||||
pub ignore_layer_preview: bool,
|
||||
/// The selection tools: where a click hits nothing else, a closed path or compound path with
|
||||
/// no fill is hit inside its closed subpaths, the topmost first, as a filled one is. Off with
|
||||
/// [`Self::path_only`] and in outline. Clipping paths and guides are still hit on their
|
||||
/// outline only. [`hit_test`] and [`objects_at`] try every other object first.
|
||||
pub unfilled_interiors: bool,
|
||||
}
|
||||
|
||||
impl Default for HitOptions {
|
||||
@@ -94,6 +99,7 @@ impl Default for HitOptions {
|
||||
clip_outlines: false,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
unfilled_interiors: false,
|
||||
scope: None,
|
||||
}
|
||||
}
|
||||
@@ -417,11 +423,35 @@ impl Drop for DrawnOff {
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Whether a clipping path is being tested ([`InMask`]).
|
||||
static IN_MASK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// While a guard lives, a clipping path is tested: it is not hit inside by its interior alone
|
||||
/// ([`takes_interior`]).
|
||||
struct InMask {
|
||||
was: bool,
|
||||
}
|
||||
|
||||
impl InMask {
|
||||
fn set() -> Self {
|
||||
Self { was: IN_MASK.replace(true) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for InMask {
|
||||
fn drop(&mut self) {
|
||||
IN_MASK.set(self.was);
|
||||
}
|
||||
}
|
||||
|
||||
/// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a
|
||||
/// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to
|
||||
/// the region it clips to.
|
||||
/// the region it clips to. It is also under an [`InMask`] guard.
|
||||
fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
|
||||
let _off = mask.then(DrawnOff::set);
|
||||
let _mask = mask.then(InMask::set);
|
||||
f()
|
||||
}
|
||||
|
||||
@@ -636,17 +666,23 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) {
|
||||
// An envelope in Edit Contents may expose objects *within* a top-level group.
|
||||
// The repeated traversal handles that mixed hierarchy precisely. The objects found
|
||||
// so far lie above the envelope and stay first; the repeated traversal finds the
|
||||
// rest with what is left of the limit of symbol art to walk.
|
||||
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
|
||||
break;
|
||||
// As [`hit_test`] does: the objects hit by what they paint first, then those hit only inside
|
||||
// an unfilled closed path ([`HitOptions::unfilled_interiors`]).
|
||||
let painted = HitOptions { unfilled_interiors: false, ..opt };
|
||||
let interiors = opt.unfilled_interiors && !opt.path_only && !opt.outline;
|
||||
'passes: for pass in [Some(painted), interiors.then_some(opt)].into_iter().flatten() {
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
if !objects_at_layer(layer, p, pass, &symbols, &mut tops, &mut seen) {
|
||||
// An envelope in Edit Contents may expose objects *within* a top-level group.
|
||||
// The repeated traversal handles that mixed hierarchy precisely. The objects found
|
||||
// so far lie above the envelope and stay first; the repeated traversal finds the
|
||||
// rest with what is left of the limit of symbol art to walk.
|
||||
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
|
||||
break 'passes;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them.
|
||||
@@ -731,6 +767,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;
|
||||
|
||||
@@ -834,7 +1016,18 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
|
||||
/// `editable_only` over the objects of layers and sublayers on a locked artboard, and over all of
|
||||
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
|
||||
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
|
||||
/// With [`HitOptions::unfilled_interiors`], a second walk looks inside the unfilled closed paths
|
||||
/// only when the first, without it, hits nothing.
|
||||
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let painted = hit_test_walk(doc, p, HitOptions { unfilled_interiors: false, ..opt }, skip, editable_only);
|
||||
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline {
|
||||
return painted;
|
||||
}
|
||||
hit_test_walk(doc, p, opt, skip, editable_only)
|
||||
}
|
||||
|
||||
/// One walk of [`hit_test_skipping`], with `opt` as given.
|
||||
fn hit_test_walk(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let _walk = ArtWalk::open();
|
||||
let finish = |mut h: Hit| {
|
||||
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
|
||||
@@ -1378,7 +1571,10 @@ fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: &
|
||||
return false;
|
||||
}
|
||||
}
|
||||
hit_order(n, children, p).any(|i| children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept)))
|
||||
hit_order(n, children, p).any(|i| {
|
||||
let _mask = (i == 0 && n.clips()).then(InMask::set);
|
||||
children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept))
|
||||
})
|
||||
}
|
||||
_ => hit_leaf(n, p, opt, symbols).is_some_and(|kind| accept(n.id, kind)),
|
||||
}
|
||||
@@ -1417,6 +1613,15 @@ fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64)
|
||||
let decoration_sq = decoration_reach * decoration_reach;
|
||||
let mut near_decoration = false;
|
||||
for sp in &path.subpaths {
|
||||
// A closed lone anchor has no segment, and a cap can draw a dot on it: the full check
|
||||
// decides a click near it.
|
||||
if sp.closed
|
||||
&& sp.segment_count() == 0
|
||||
&& let Some(a) = sp.anchors.first()
|
||||
&& (a.p - p).hypot2() <= radius_sq.max(decoration_sq)
|
||||
{
|
||||
near_decoration = true;
|
||||
}
|
||||
for i in 0..sp.segment_count() {
|
||||
let c = sp.segment(i);
|
||||
if decoration_reach > 0.0 && !near_decoration && ([c.p0, c.p3].iter().any(|q| (*q - p).hypot2() <= decoration_sq)) {
|
||||
@@ -1467,6 +1672,8 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => {
|
||||
let has_fill = n.appearance.has_visible_fill();
|
||||
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed) && takes_interior(n, opt);
|
||||
let inside = || (interior && fill_contains(&closed_subpaths_at([path], p), *rule, p)).then_some(HitKind::Fill);
|
||||
if opt.outline
|
||||
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
|
||||
{
|
||||
@@ -1501,7 +1708,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
return Some(HitKind::Stroke);
|
||||
}
|
||||
if !near_decoration {
|
||||
return None;
|
||||
return inside();
|
||||
}
|
||||
}
|
||||
let bp = path.to_bezpath();
|
||||
@@ -1511,7 +1718,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) {
|
||||
return Some(HitKind::Fill);
|
||||
}
|
||||
None
|
||||
inside()
|
||||
}
|
||||
NodeKind::Compound { children, rule } => {
|
||||
// Painted strokes follow the whole compound path (alignment, dashes, width profiles):
|
||||
@@ -1529,7 +1736,11 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol {
|
||||
return Some(HitKind::Outline);
|
||||
}
|
||||
(!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill)
|
||||
if n.appearance.has_visible_fill() {
|
||||
return (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill);
|
||||
}
|
||||
let closed = || closed_subpaths_at(children.iter().filter_map(|m| m.path_data()), p);
|
||||
(takes_interior(n, opt) && fill_contains(&closed(), *rule, p)).then_some(HitKind::Fill)
|
||||
}
|
||||
// The type path lies within the bounds: they rule out the rest before it is measured.
|
||||
NodeKind::Text(t) if opt.type_path_only => {
|
||||
@@ -1601,6 +1812,30 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
}
|
||||
}
|
||||
|
||||
/// Is path or compound path `n`, which has no visible fill, hit inside its closed subpaths
|
||||
/// ([`HitOptions::unfilled_interiors`])? Not a clipping path ([`InMask`]) or a guide.
|
||||
fn takes_interior(n: &Node, opt: HitOptions) -> bool {
|
||||
opt.unfilled_interiors
|
||||
&& !opt.outline
|
||||
&& !opt.path_only
|
||||
&& !IN_MASK.get()
|
||||
&& !matches!(n.kind, NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
/// The closed subpaths of `paths` whose control points' box holds `p`, as one path. A path outside
|
||||
/// that box winds zero times round `p`, so this path's fill holds `p` as all the closed subpaths'
|
||||
/// fill does. Open subpaths are left out: they bound no area.
|
||||
fn closed_subpaths_at<'a>(paths: impl IntoIterator<Item = &'a PathData>, p: Point) -> BezPath {
|
||||
let holds = |b: Rect| b.x0 <= p.x && p.x <= b.x1 && b.y0 <= p.y && p.y <= b.y1;
|
||||
let mut bp = BezPath::new();
|
||||
for pd in paths.into_iter().filter(|pd| pd.control_bounds().is_some_and(holds)) {
|
||||
for sp in pd.subpaths.iter().filter(|sp| sp.closed) {
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
}
|
||||
}
|
||||
bp
|
||||
}
|
||||
|
||||
/// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a
|
||||
/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a
|
||||
/// stroke along its shape, a fill inside it except with Selection by Path Only.
|
||||
@@ -1877,13 +2112,23 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
/// (blends, envelopes, repeats) are tested without those effects. `None` when `inst` is not a
|
||||
/// symbol instance or no editable object of its art is under `p`.
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
let _walk = ArtWalk::open();
|
||||
let walk = ArtWalk::open();
|
||||
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
let art = InstanceArt::drawn(doc, inst, outline)?;
|
||||
let symbols = doc.kept_symbol_boxes();
|
||||
let mut path = vec![];
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
let pick = |opt: HitOptions| {
|
||||
let mut path = vec![];
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
};
|
||||
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit.
|
||||
pick(HitOptions { unfilled_interiors: false, ..opt }).or_else(|| {
|
||||
if !opt.unfilled_interiors || opt.path_only || outline {
|
||||
return None;
|
||||
}
|
||||
walk.restart();
|
||||
pick(opt)
|
||||
})
|
||||
}
|
||||
|
||||
/// The walk of a symbol instance's placed art that [`symbol_part_at`] and [`instance_art_hit`] make.
|
||||
|
||||
@@ -38,6 +38,168 @@ fn unfilled_interior_misses() {
|
||||
assert!(hit_test(&d, Point::new(50.5, 25.0), HitOptions::default()).is_some());
|
||||
}
|
||||
|
||||
/// The selection tools' options with unfilled closed paths hit inside.
|
||||
const INTERIORS: HitOptions = HitOptions { unfilled_interiors: true, ..SELECTING };
|
||||
|
||||
/// A path of `points` with a black stroke and no fill, inserted at the top of the first layer.
|
||||
fn stroked(d: &mut Document, points: &[(f64, f64)], closed: bool) -> NodeId {
|
||||
let l = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let pts: Vec<Point> = points.iter().map(|&(x, y)| Point::new(x, y)).collect();
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pts, closed));
|
||||
d.insert(Some(l), 99, Node::path(id, path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
const FRAME: [(f64, f64); 4] = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
|
||||
|
||||
#[test]
|
||||
fn an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let frame = stroked(&mut d, &FRAME, true);
|
||||
let at = |opt: HitOptions| hit_test(&d, Point::new(50.0, 50.0), opt).map(|h| h.leaf);
|
||||
assert_eq!(at(INTERIORS), Some(frame));
|
||||
assert_eq!(at(SELECTING), None, "without the option, the interior misses");
|
||||
assert_eq!(at(HitOptions { path_only: true, ..INTERIORS }), None, "Object Selection by Path Only");
|
||||
assert_eq!(at(HitOptions { outline: true, ..INTERIORS }), None, "Outline view");
|
||||
assert_eq!(objects_at(&d, Point::new(50.0, 50.0), INTERIORS, None), vec![frame]);
|
||||
assert!(objects_at(&d, Point::new(150.0, 50.0), INTERIORS, None).is_empty(), "outside it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_path_is_not_hit_inside() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
stroked(&mut d, &FRAME, false);
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 50.0), INTERIORS), None);
|
||||
}
|
||||
|
||||
/// What a click paints over comes first: an object drawn inside an unfilled frame above it is hit
|
||||
/// where it paints, and the frame elsewhere inside; Select Behind lists the frame after it.
|
||||
#[test]
|
||||
fn art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let dot = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::path(dot, shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), Appearance::default_art())).unwrap();
|
||||
let frame = stroked(&mut d, &FRAME, true);
|
||||
let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(&d, 50.0), Some(dot));
|
||||
assert_eq!(at(&d, 20.0), Some(frame));
|
||||
assert_eq!(objects_at(&d, Point::new(50.0, 50.0), INTERIORS, None), vec![dot, frame]);
|
||||
// The topmost of two unfilled frames is hit inside both.
|
||||
let inner = stroked(&mut d, &[(10.0, 10.0), (90.0, 10.0), (90.0, 90.0), (10.0, 90.0)], true);
|
||||
assert_eq!(at(&d, 20.0), Some(inner));
|
||||
assert_eq!(at(&d, 5.0), Some(frame));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let (id, outer, hole) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let members = vec![ring(outer, Rect::new(0.0, 0.0, 100.0, 100.0)), ring(hole, Rect::new(30.0, 30.0, 70.0, 70.0))];
|
||||
let mut compound = Node::new(id, NodeKind::Compound { children: members, rule: FillRule::EvenOdd });
|
||||
compound.appearance = look().into();
|
||||
d.insert(Some(l), 0, compound).unwrap();
|
||||
let at = |x: f64| hit_test(&d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(15.0), Some(id));
|
||||
assert_eq!(at(50.0), None, "in the hole");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_and_clipping_paths_are_not_hit_inside() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let guide = stroked(&mut d, &FRAME, true);
|
||||
if let Some(NodeKind::Path { guide: g, .. }) = d.node_mut(guide).map(|n| &mut n.kind) {
|
||||
*g = true;
|
||||
}
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 50.0), INTERIORS), None, "a guide");
|
||||
// A clip group whose art covers only part of its unfilled clipping path.
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (g, clip, art) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let mut mask = Node::path(clip, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::None, Paint::None, 0.0));
|
||||
if let NodeKind::Path { clipping, .. } = &mut mask.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let picture = Node::path(art, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 100.0)), Appearance::default_art());
|
||||
d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(mask), Arc::new(picture)], clip: true })).unwrap();
|
||||
let at = |x: f64| hit_test(&d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(25.0), Some(art));
|
||||
assert_eq!(at(75.0), None, "inside the mask where no art paints");
|
||||
assert!(objects_at(&d, Point::new(75.0, 50.0), INTERIORS, None).is_empty());
|
||||
}
|
||||
|
||||
/// A repeat's copies of an unfilled frame are hit inside, and the copies of a clip group's unfilled
|
||||
/// compound clipping path are not.
|
||||
#[test]
|
||||
fn a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks() {
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let kind = crate::pattern::RepeatKind::Grid {
|
||||
h_spacing: 20.0,
|
||||
v_spacing: 20.0,
|
||||
rows: 1,
|
||||
cols: 2,
|
||||
grid_type: crate::pattern::TileType::Grid,
|
||||
flip_rows: false,
|
||||
flip_cols: false,
|
||||
};
|
||||
let repeat = |d: &mut Document, source: Node| {
|
||||
let r = d.alloc_id();
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, Node::new(r, NodeKind::Repeat(crate::pattern::RepeatSpec { kind: kind.clone(), source: vec![Arc::new(source)] })))
|
||||
.unwrap();
|
||||
r
|
||||
};
|
||||
// Copies at 0..40 and 60..100.
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), look());
|
||||
let r = repeat(&mut d, frame);
|
||||
assert_eq!(hit_test(&d, Point::new(80.0, 20.0), INTERIORS).map(|h| h.leaf), Some(r));
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 20.0), INTERIORS), None, "between the copies");
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let members = vec![ring(d.alloc_id(), Rect::new(0.0, 0.0, 40.0, 40.0)), ring(d.alloc_id(), Rect::new(5.0, 5.0, 35.0, 35.0))];
|
||||
let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
mask.appearance = look().into();
|
||||
let picture = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 40.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(picture)]);
|
||||
clip.set_clips(true);
|
||||
let r = repeat(&mut d, clip);
|
||||
assert_eq!(hit_test(&d, Point::new(65.0, 20.0), INTERIORS).map(|h| h.leaf), Some(r), "on the clipped art");
|
||||
assert_eq!(hit_test(&d, Point::new(80.0, 20.0), INTERIORS), None, "inside the mask where no art paints");
|
||||
}
|
||||
|
||||
/// Direct Selection in a dynamic symbol's art picks parts as a click on the document does: what
|
||||
/// paints first, then an unfilled frame inside; an unfilled compound clipping path by its outline.
|
||||
#[test]
|
||||
fn symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), Appearance::default_art());
|
||||
let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look());
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let (mask_id, a, b) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let members = vec![ring(a, Rect::new(150.0, 0.0, 250.0, 100.0)), ring(b, Rect::new(160.0, 10.0, 240.0, 90.0))];
|
||||
let mut mask = Node::new(mask_id, NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
mask.appearance = look().into();
|
||||
let picture = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(150.0, 0.0, 180.0, 100.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(picture)]);
|
||||
clip.set_clips(true);
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(dot), Arc::new(frame), Arc::new(clip)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Framed".into(), art: Arc::new(root) });
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Framed".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
let n = d.node(inst).unwrap();
|
||||
let at = |x: f64| symbol_part_at(&d, n, Point::new(x, 50.0), INTERIORS);
|
||||
assert_eq!(at(50.0), Some(vec![0]), "the dot under the frame");
|
||||
assert_eq!(at(20.0), Some(vec![1]), "inside the frame");
|
||||
assert_eq!(at(220.0), None, "inside the clipping path where no art paints");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_plain_stroke_hits_its_middle_and_curved_end() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
@@ -1464,6 +1626,7 @@ const SELECTING: HitOptions = HitOptions {
|
||||
clip_outlines: true,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
unfilled_interiors: false,
|
||||
scope: None,
|
||||
};
|
||||
|
||||
@@ -1992,10 +2155,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 +2533,40 @@ fn select_behind_keeps_one_art_limit_when_it_falls_back() {
|
||||
assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked");
|
||||
}
|
||||
|
||||
/// [`leaves_at`] falls back to repeated hit tests at a clip group, after the hits its single
|
||||
/// traversal found above it: an instance hit by its art, with the limit of symbol art then used
|
||||
/// up, stays in the list.
|
||||
#[test]
|
||||
fn leaves_at_keeps_the_hits_above_a_clip_group_it_falls_back_at() {
|
||||
let p = Point::new(150.0, 50.0);
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
clipped_symbol(&mut d, false);
|
||||
// A clip group at the bottom of the layer, its art under (150, 50).
|
||||
let square = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art()));
|
||||
let (mask, art) = (d.alloc_id(), d.alloc_id());
|
||||
let mut clip_group = Node::group(d.alloc_id(), vec![square(mask), square(art)]);
|
||||
clip_group.set_clips(true);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, clip_group).unwrap();
|
||||
let (mut shown_mask, shown_art) = half_clipped(&mut d);
|
||||
shown_mask.appearance.effects.push(test_move());
|
||||
let mut shown = Node::group(d.alloc_id(), vec![Arc::new(shown_mask), Arc::new(shown_art)]);
|
||||
shown.set_clips(true);
|
||||
group_symbol(&mut d, "Shown", vec![Arc::new(shown)]);
|
||||
let hit = instance_of(&mut d, "Shown");
|
||||
let hit_id = hit.id;
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap();
|
||||
for _ in 0..32 {
|
||||
let inst = instance_of(&mut d, "Clipped");
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
}
|
||||
let (hits, _, arts) = with_art_limit(100, || leaves_at(&d, p, HitOptions::default()));
|
||||
let leaves: Vec<NodeId> = hits.iter().map(|h| h.leaf).collect();
|
||||
assert_eq!(leaves.first(), Some(&hit_id), "hit before the fallback: {leaves:?}");
|
||||
assert!(leaves.contains(&art), "the clipped art after it: {leaves:?}");
|
||||
assert!(arts <= 34, "{arts} instances' art walked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_skip() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
|
||||
+13
-2
@@ -54,8 +54,8 @@ pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation,
|
||||
use blend_spec::{blend_color_shift, blend_ramp};
|
||||
pub use envelope::{
|
||||
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, TypeInk, envelope_bounds, envelope_content_bounds,
|
||||
envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of,
|
||||
envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid,
|
||||
envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_margin_lengths,
|
||||
envelope_of, envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid,
|
||||
};
|
||||
pub use expand::{
|
||||
Hooks, MAX_GENERATED, Outliner, PatternTiles, affine_near, expand_deep, expand_deep_hooks, expand_live, expand_live_hooks, expand_live_with,
|
||||
@@ -975,6 +975,17 @@ mod tests {
|
||||
assert_eq!(margin(&turned, frame).map(|m| (m * 1000.0).round()), before.map(|m| (m * 1000.0).round()));
|
||||
// Margins an `f32` can't hold are none.
|
||||
assert_eq!(envelope_stroke_margin(Rect::new(-5e41, 0.0, 100.0, 100.0), Rect::new(0.0, 0.0, 100.0, 100.0)), None);
|
||||
// A straight line along an axis has margins across it, as shares of its length, and maps
|
||||
// from its box with them; a point has none.
|
||||
let line =
|
||||
Node::path(NodeId(4), vectorcraft_geom::shapes::line(Point::new(10.0, 20.0), Point::new(110.0, 20.0)), crate::Appearance::default_art());
|
||||
let line = [Arc::new(line)];
|
||||
let stroked_line = Rect::new(10.0, 15.0, 110.0, 25.0);
|
||||
let across = envelope_stroke_margin(stroked_line, Rect::new(10.0, 20.0, 110.0, 20.0)).unwrap();
|
||||
assert!(across[0] > 0.0 && across[1] > 0.0 && across[2] == 0.0 && across[3] == 0.0, "{across:?}");
|
||||
let from = src(&line, Affine::IDENTITY, EnvelopeOptions { bounds_margin: across, ..on });
|
||||
assert!((from.y0 - 15.0).abs() + (from.y1 - 25.0).abs() + (from.x0 - 10.0).abs() + (from.x1 - 110.0).abs() < 1e-4, "{from:?}");
|
||||
assert_eq!(envelope_stroke_margin(stroked_line, Rect::new(60.0, 20.0, 60.0, 20.0)), None);
|
||||
|
||||
assert!(serde_json::to_value(EnvelopeOptions::default()).unwrap().get("boundsMargin").is_none());
|
||||
let saved = serde_json::to_value(on).unwrap();
|
||||
|
||||
@@ -95,7 +95,9 @@ pub struct EnvelopeOptions {
|
||||
/// Distort Pattern Fills (with Distort Appearance): pattern tiles bend with the art.
|
||||
pub distort_pattern_fills: bool,
|
||||
/// With Distort Appearance, how far the box the content maps from reaches past its geometric
|
||||
/// bounds at the top, bottom, left and right, as shares of their height and width. An envelope
|
||||
/// bounds at the top, bottom, left and right, as shares of their height and width; when the
|
||||
/// height or width is shorter than 1e-6 pt, the margins along that side are shares of the other side
|
||||
/// ([`envelope_margin_lengths`]). An envelope
|
||||
/// opened from a `.ai` whose saved size includes its strokes has these margins. New envelopes
|
||||
/// have none. Leaving Edit Contents measures them again when the strokes reach differently.
|
||||
#[serde(skip_serializing_if = "crate::skip::is_default")]
|
||||
@@ -140,7 +142,8 @@ impl EnvelopeOptions {
|
||||
if !self.distort_appearance || !self.bounds_margin.iter().all(|m| m.is_finite() && *m >= 0.0) {
|
||||
return r;
|
||||
}
|
||||
let grown = crate::marks::outset(r, [top * r.height(), bottom * r.height(), left * r.width(), right * r.width()]);
|
||||
let Some([v, _, h, _]) = envelope_margin_lengths(r) else { return r };
|
||||
let grown = crate::marks::outset(r, [top * v, bottom * v, left * h, right * h]);
|
||||
if grown.is_finite() { grown } else { r }
|
||||
}
|
||||
}
|
||||
@@ -457,19 +460,28 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`. `None` for
|
||||
/// content with no width or no height, or for margins an `f32` can't hold.
|
||||
/// The lengths the top, bottom, left and right [`EnvelopeOptions::bounds_margin`] of content with
|
||||
/// geometric bounds `plain` are shares of: its height for the top and bottom and its width for the
|
||||
/// left and right. A side shorter than 1e-6 pt takes the other side's length, so a stroked straight
|
||||
/// line along an axis has margins across it. `None` when neither side has a length.
|
||||
pub fn envelope_margin_lengths(plain: Rect) -> Option<[f64; 4]> {
|
||||
let long = |l: f64| l.is_finite() && l >= 1e-6;
|
||||
let (h, w) = match (long(plain.height()), long(plain.width())) {
|
||||
(true, true) => (plain.height(), plain.width()),
|
||||
(false, true) => (plain.width(), plain.width()),
|
||||
(true, false) => (plain.height(), plain.height()),
|
||||
(false, false) => return None,
|
||||
};
|
||||
Some([h, h, w, w])
|
||||
}
|
||||
|
||||
/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`, as shares
|
||||
/// of [`envelope_margin_lengths`]. `None` for content with neither a width nor a height, or for
|
||||
/// margins an `f32` can't hold.
|
||||
pub fn envelope_stroke_margin(stroked: Rect, plain: Rect) -> Option<[f32; 4]> {
|
||||
if plain.width() < 1e-6 || plain.height() < 1e-6 {
|
||||
return None;
|
||||
}
|
||||
let margin = [
|
||||
(plain.y0 - stroked.y0) / plain.height(),
|
||||
(stroked.y1 - plain.y1) / plain.height(),
|
||||
(plain.x0 - stroked.x0) / plain.width(),
|
||||
(stroked.x1 - plain.x1) / plain.width(),
|
||||
]
|
||||
.map(|m| m as f32);
|
||||
let [v, _, h, _] = envelope_margin_lengths(plain)?;
|
||||
let margin =
|
||||
[(plain.y0 - stroked.y0) / v, (stroked.y1 - plain.y1) / v, (plain.x0 - stroked.x0) / h, (stroked.x1 - plain.x1) / h].map(|m| m as f32);
|
||||
margin.iter().all(|m| m.is_finite()).then_some(margin)
|
||||
}
|
||||
|
||||
|
||||
@@ -431,6 +431,17 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// The box of what a path, or the paths of a compound path, draw before the strokes' reach
|
||||
/// ([`PathData::drawn_bounds`]): lone anchors of closed subpaths count only with `dots`. Other
|
||||
/// members of a compound path count by their geometric box. `None` when nothing is drawn.
|
||||
fn drawn(&self, symbols: Option<&SymbolBoxes>, dots: bool) -> Option<Rect> {
|
||||
match &self.kind {
|
||||
NodeKind::Path { path, .. } => path.drawn_bounds(dots),
|
||||
NodeKind::Compound { .. } => self.editing_children().iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.drawn(symbols, dots))),
|
||||
_ => self.geometric(symbols),
|
||||
}
|
||||
}
|
||||
|
||||
/// Visual bounds: what the object paints, its strokes included (paths and compound paths
|
||||
/// measure theirs along their own shape, see [`Appearance::stroked_bounds`]). An image is
|
||||
/// measured by its frame. A symbol instance is measured as in [`Node::geometric_bounds`],
|
||||
@@ -485,7 +496,9 @@ impl Node {
|
||||
self.geometric(symbols).map(|b| b.inflate(o, o))
|
||||
}
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
|
||||
let b = self.geometric(symbols)?;
|
||||
// A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath.
|
||||
let dots = self.appearance.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square));
|
||||
let b = self.drawn(symbols, dots).or_else(|| self.geometric(symbols))?;
|
||||
Some(self.appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default()))
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
|
||||
@@ -469,6 +469,60 @@ fn visual_bounds_include_stroke() {
|
||||
assert_eq!(p.visual_bounds(), Some(Rect::new(-0.5, -0.5, 10.5, 10.5)));
|
||||
}
|
||||
|
||||
/// A lone anchor 20 points right of a stroked square widens the path's geometric box, and its
|
||||
/// visual box only where the stroke draws it: as the dot of a round or projecting cap on a closed
|
||||
/// subpath. An open lone anchor, or a closed one under a butt cap, draws nothing.
|
||||
#[test]
|
||||
fn a_lone_anchor_widens_the_visual_box_only_where_its_cap_draws_a_dot() {
|
||||
use crate::appearance::LineCap;
|
||||
use vectorcraft_geom::{Point, SubPath};
|
||||
let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let node = |closed: bool, cap: LineCap| {
|
||||
let mut subpaths = square.subpaths.clone();
|
||||
subpaths.push(SubPath::polyline(&[Point::new(30.0, 5.0)], closed));
|
||||
let mut p = Node::path(NodeId(2), PathData::new(subpaths), Appearance::default_art());
|
||||
let s = p.appearance.stroke_mut().unwrap();
|
||||
(s.cap, s.join) = (cap, crate::appearance::LineJoin::Round);
|
||||
p
|
||||
};
|
||||
for closed in [false, true] {
|
||||
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
|
||||
let p = node(closed, cap);
|
||||
let geometric = p.geometric_bounds().unwrap();
|
||||
let visual = p.visual_bounds().unwrap();
|
||||
assert!(geometric.x1 >= 30.0, "{closed} {cap:?}: the geometric box {geometric:?} leaves out the lone anchor");
|
||||
let dot = closed && cap != LineCap::Butt;
|
||||
assert_eq!(visual.x1 > 30.0, dot, "{closed} {cap:?}: the visual box {visual:?}");
|
||||
assert!(dot || visual.x1 < 11.0, "{closed} {cap:?}: the visual box {visual:?} reaches toward the lone anchor");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The dot a round or projecting cap draws for a closed lone anchor reaches half the stroke's
|
||||
/// width round the anchor under every join, miter and bevel joins included, which measure the
|
||||
/// stroke along its segments.
|
||||
#[test]
|
||||
fn a_lone_anchors_dot_reaches_half_the_stroke_width_under_every_join() {
|
||||
use crate::appearance::{LineCap, LineJoin};
|
||||
use vectorcraft_geom::{Point, SubPath};
|
||||
let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
for join in [LineJoin::Miter, LineJoin::Bevel, LineJoin::Round] {
|
||||
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
|
||||
let mut subpaths = square.subpaths.clone();
|
||||
subpaths.push(SubPath::polyline(&[Point::new(30.0, 5.0)], true));
|
||||
let mut p = Node::path(NodeId(2), PathData::new(subpaths), Appearance::default_art());
|
||||
let s = p.appearance.stroke_mut().unwrap();
|
||||
(s.cap, s.join, s.width) = (cap, join, 4.0);
|
||||
let visual = p.visual_bounds().unwrap();
|
||||
if cap == LineCap::Butt {
|
||||
assert!(visual.x1 < 13.0, "{join:?} {cap:?}: the visual box {visual:?} reaches toward a lone anchor that draws nothing");
|
||||
} else {
|
||||
assert!(visual.x1 >= 32.0 - 1e-9 && visual.y1 >= 10.0, "{join:?} {cap:?}: the visual box {visual:?} leaves out the dot's reach");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's box from its members' boxes grows by the group's own strokes, leaves out members
|
||||
/// without a box, and is `None` when none has one.
|
||||
#[test]
|
||||
|
||||
@@ -17,15 +17,16 @@
|
||||
//! other stop there, showing their previews).
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cell::Cell;
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
use vectorcraft_geom::{Affine, PathData, Rect, SubPath};
|
||||
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
|
||||
use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol};
|
||||
use crate::{Appearance, AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol};
|
||||
|
||||
/// A placed document: an artboard of another VectorCraft file, a page of a PDF or `.ai` file, or
|
||||
/// an EPS file's art, shown as one locked object.
|
||||
@@ -123,12 +124,27 @@ impl PlacedDocument {
|
||||
}
|
||||
|
||||
/// The art the object shows, as plain objects with `n`'s id: one group, its resources named
|
||||
/// as [`Document::with_placed_art`] adds them (nothing until that has read it).
|
||||
/// as [`Document::with_placed_art`] adds them (nothing until that has read it). While
|
||||
/// [`Crossed`] is on for this thread, its box crossed from corner to corner instead
|
||||
/// ([`Self::crossed_art`]).
|
||||
pub fn art(&self, n: &Node) -> Vec<Node> {
|
||||
if crossed() {
|
||||
return vec![self.crossed_art(n)];
|
||||
}
|
||||
let prefix = prefix(&self.key);
|
||||
read_cached(self).and_then(|e| self.art_node(n, &e, &prefix)).into_iter().collect()
|
||||
}
|
||||
|
||||
/// The object's box crossed from corner to corner, as one group with `n`'s id: a path of the
|
||||
/// box's outline and its two diagonals with a black 1 pt stroke. Outline mode without Document
|
||||
/// Setup → Show Images in Outline Mode shows the object so, and its effects reshape this art.
|
||||
pub fn crossed_art(&self, n: &Node) -> Node {
|
||||
let q = self.corners();
|
||||
let path = PathData::new(vec![SubPath::polyline(&q, true), SubPath::polyline(&[q[0], q[2]], false), SubPath::polyline(&[q[1], q[3]], false)]);
|
||||
let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
Node::group(n.id, vec![Arc::new(Node::path(art_id(), path, stroke))])
|
||||
}
|
||||
|
||||
/// Read `e`'s art placed as this object `n` shows it (`n`'s id), its resources renamed with
|
||||
/// `prefix`.
|
||||
fn art_node(&self, n: &Node, e: &ReadDocument, prefix: &str) -> Option<Node> {
|
||||
@@ -364,6 +380,28 @@ pub type Loader = fn(&PlacedDocument, &[u8]) -> Option<(Document, Node, Rect)>;
|
||||
|
||||
static LOADER: OnceLock<Loader> = OnceLock::new();
|
||||
|
||||
std::thread_local! {
|
||||
/// Open checks use previews rather than loading placed documents for drawing.
|
||||
static PREVIEWS_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Restores whether only previews are used when an open check ends, including on unwind.
|
||||
struct PreviewsOnly(bool);
|
||||
|
||||
impl Drop for PreviewsOnly {
|
||||
fn drop(&mut self) {
|
||||
PREVIEWS_ONLY.with(|p| p.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Run an open check using placed documents' previews instead of loading their art on this
|
||||
/// thread. Nested checks keep the scope active until the outer check ends. This prevents an
|
||||
/// open check and drawing from recursively loading each other's nested files.
|
||||
pub fn with_previews<T>(check: impl FnOnce() -> T) -> T {
|
||||
let _scope = PreviewsOnly(PREVIEWS_ONLY.with(|p| p.replace(true)));
|
||||
check()
|
||||
}
|
||||
|
||||
/// Register how files are read (the first registration stays).
|
||||
pub fn set_loader(l: Loader) {
|
||||
// Already set: the same loader, registered by another session.
|
||||
@@ -438,8 +476,12 @@ impl Cache {
|
||||
}
|
||||
|
||||
/// `p`'s file (`bytes`) read, from the cache when it was read already: what the renderer draws a
|
||||
/// placed document from. `None` when it can't be read (or no loader is registered).
|
||||
/// placed document from. `None` when it can't be read, no loader is registered, or an open check
|
||||
/// uses [`with_previews`].
|
||||
pub fn read(p: &PlacedDocument, bytes: &Arc<Vec<u8>>) -> Option<Arc<ReadDocument>> {
|
||||
if PREVIEWS_ONLY.with(std::cell::Cell::get) {
|
||||
return None;
|
||||
}
|
||||
if let Some(e) = cache().get(&p.key, false, Some(bytes)) {
|
||||
return Some(e);
|
||||
}
|
||||
@@ -470,6 +512,36 @@ fn read_preview(p: &PlacedDocument, bytes: &Arc<Vec<u8>>) -> Option<Arc<ReadDocu
|
||||
Some(e)
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Whether [`PlacedDocument::art`] gives the crossed box on this thread ([`Crossed`]).
|
||||
static CROSSED: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
|
||||
/// While alive, [`PlacedDocument::art`] on this thread gives each placed document's box crossed
|
||||
/// from corner to corner ([`PlacedDocument::crossed_art`]) when it was made with `true`, and the
|
||||
/// file's art when made with `false`; once dropped, the setting before it applies again. A
|
||||
/// renderer holds one while it draws or measures Outline mode without Document Setup → Show Images
|
||||
/// in Outline Mode, so that effects and live objects make their art from the crossed box.
|
||||
#[must_use]
|
||||
pub struct Crossed(bool);
|
||||
|
||||
impl Crossed {
|
||||
pub fn set(on: bool) -> Self {
|
||||
Self(CROSSED.with(|c| c.replace(on)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Crossed {
|
||||
fn drop(&mut self) {
|
||||
CROSSED.with(|c| c.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether [`PlacedDocument::art`] gives the crossed box on this thread ([`Crossed`]).
|
||||
pub fn crossed() -> bool {
|
||||
CROSSED.with(Cell::get)
|
||||
}
|
||||
|
||||
/// `p`'s file as read already (else its preview's), without reading it.
|
||||
pub fn read_cached(p: &PlacedDocument) -> Option<Arc<ReadDocument>> {
|
||||
let mut c = cache();
|
||||
@@ -692,6 +764,22 @@ mod tests {
|
||||
Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0)))
|
||||
}
|
||||
|
||||
/// Nested open checks skip both new and cached art, and restore ordinary reads afterward.
|
||||
#[test]
|
||||
fn open_checks_leave_placed_documents_for_drawing_afterward() {
|
||||
set_loader(stub_loader);
|
||||
let p = placed("open-check-1");
|
||||
let bytes = Arc::new(b"leaf".to_vec());
|
||||
with_previews(|| assert!(read(&p, &bytes).is_none()));
|
||||
assert!(read(&p, &bytes).is_some());
|
||||
with_previews(|| {
|
||||
assert!(read(&p, &bytes).is_none());
|
||||
with_previews(|| assert!(read(&p, &bytes).is_none()));
|
||||
assert!(read(&p, &bytes).is_none());
|
||||
});
|
||||
assert!(read(&p, &bytes).is_some());
|
||||
}
|
||||
|
||||
/// A color-masked image in a placed document's art keeps its masked pixels under the prefixed
|
||||
/// names its resources get.
|
||||
#[test]
|
||||
|
||||
+81
-5
@@ -291,9 +291,12 @@ impl StrokeLayer {
|
||||
// past them are measured.
|
||||
match self.body_along(&segs, side, out) {
|
||||
Some(body) => out = out.union(body),
|
||||
// A subpath with no length paints at most its caps' dot.
|
||||
// A subpath with no length paints at most its caps' dot. A closed subpath with
|
||||
// no segment, a lone anchor, has its dot at that anchor under a round or
|
||||
// projecting cap.
|
||||
None if !butt => {
|
||||
let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b));
|
||||
let lone = (self.cap != LineCap::Butt).then(|| els[r.start].end_point()).flatten().map(|p| Rect::from_points(p, p));
|
||||
let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)).or(lone);
|
||||
out = dot.map_or(out, |d| out.union(d.inflate(side, side)));
|
||||
}
|
||||
None => {}
|
||||
@@ -353,13 +356,18 @@ impl StrokeLayer {
|
||||
/// wider side of a farther one can paint past the nearest.
|
||||
pub fn hits(&self, bp: &BezPath, rule: FillRule, p: Point, tol: f64) -> bool {
|
||||
let reach = self.reach() + tol;
|
||||
if self.width.is_nan() || self.width <= 0.0 || !bp.bounding_box().inflate(reach, reach).contains(p) {
|
||||
if self.width.is_nan() || self.width <= 0.0 {
|
||||
return false;
|
||||
}
|
||||
let els = bp.elements();
|
||||
// The box of the segments leaves out a closed subpath of one anchor, which has none: away
|
||||
// from the segments only the dot a cap draws for such a subpath can paint.
|
||||
if !bp.bounding_box().inflate(reach, reach).contains(p) {
|
||||
return self.draws_dots() && subpaths(bp).into_iter().any(|(r, closed)| self.dot_contains(bp, rule, (&els[r], closed), p, tol));
|
||||
}
|
||||
if head_ends(self, bp).into_iter().any(|(at, out, end)| self.head_contains(at, out, end, p, tol)) {
|
||||
return true;
|
||||
}
|
||||
let els = bp.elements();
|
||||
// Aligned strokes paint on one side of the path only.
|
||||
let on_side = |region: Option<bool>, d: f64| region.is_none_or(|inside| d <= tol || fill_contains(bp, rule, p) == inside);
|
||||
// Every dash gets the caps, as wide as the stroke where the dash ends: round ones reach as
|
||||
@@ -371,7 +379,13 @@ impl StrokeLayer {
|
||||
LineCap::Square => Some(std::f64::consts::SQRT_2),
|
||||
};
|
||||
for (r, closed) in subpaths(bp) {
|
||||
let segs = drawn(&els[r]);
|
||||
let segs = drawn(&els[r.clone()]);
|
||||
if segs.is_empty() {
|
||||
if self.dot_contains(bp, rule, (&els[r], closed), p, tol) {
|
||||
return true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (half, region) = self.body(closed);
|
||||
let full = half * self.profile_max() * dash_caps.unwrap_or(1.0);
|
||||
// Past a butt cap or a bevel the stroke stops at the segments' corners. A width profile
|
||||
@@ -442,6 +456,32 @@ impl StrokeLayer {
|
||||
false
|
||||
}
|
||||
|
||||
/// Does this stroke draw a dot for a subpath that never leaves its first point? A round or a
|
||||
/// projecting cap draws one on a stroke without a dash pattern or a width profile.
|
||||
fn draws_dots(&self) -> bool {
|
||||
self.cap != LineCap::Butt && self.profile.is_none() && !self.dash.as_ref().is_some_and(Dash::is_dashed)
|
||||
}
|
||||
|
||||
/// Is `p` within `tol` of the dot this stroke draws for the subpath `els` (`closed`: a closed
|
||||
/// one) of `bp`, filled with `rule`, when every point of the subpath is its first point
|
||||
/// ([`Self::draws_dots`])? A round cap draws a disc there and a projecting cap a square along
|
||||
/// the x axis, as wide as the stroke's body ([`StrokeLayer::body`]). Inside and outside
|
||||
/// strokes of a closed subpath paint on their own side of `bp` only.
|
||||
fn dot_contains(&self, bp: &BezPath, rule: FillRule, (els, closed): (&[vectorcraft_geom::PathEl], bool), p: Point, tol: f64) -> bool {
|
||||
if !self.draws_dots() || vectorcraft_geom::kurbo::segments(els.iter().copied()).any(|s| has_length(&s)) {
|
||||
return false;
|
||||
}
|
||||
let Some(at) = els.first().and_then(vectorcraft_geom::PathEl::end_point) else { return false };
|
||||
let (half, region) = self.body(closed);
|
||||
let v = p - at;
|
||||
let d = v.hypot();
|
||||
let on_dot = match self.cap {
|
||||
LineCap::Square => v.x.abs().max(v.y.abs()) <= half + tol,
|
||||
_ => d <= half + tol,
|
||||
};
|
||||
on_dot && region.is_none_or(|inside| d <= tol || fill_contains(bp, rule, p) == inside)
|
||||
}
|
||||
|
||||
/// Does this stroke, where it stops at the corners of its segments ([`Self::stops_at_corners`]),
|
||||
/// paint `p`, which is within `side` (and `tol`) of segment `i` of the subpath `segs`
|
||||
/// (`closed`: a closed one) and nearest to it at `t`? It does when `p` is not past the end of
|
||||
@@ -998,4 +1038,40 @@ mod tests {
|
||||
assert!(hit::hit_test(&d, Point::new(108.0, 150.0), opt).is_none(), "an unfilled interior");
|
||||
assert_eq!(d.node(id).unwrap().visual_bounds(), Some(Rect::new(90.0, 90.0, 210.0, 210.0)));
|
||||
}
|
||||
|
||||
/// A round cap draws a disc and a projecting cap a square on a subpath that never leaves its
|
||||
/// first point, a closed lone anchor or a line to the same point: a click on it hits the path,
|
||||
/// and one past it misses. A butt cap draws nothing there.
|
||||
#[test]
|
||||
fn clicks_hit_the_dot_of_a_lone_anchor() {
|
||||
let at = Point::new(150.0, 120.0);
|
||||
let mut lone = BezPath::new();
|
||||
lone.move_to(at);
|
||||
lone.close_path();
|
||||
let mut zero = BezPath::new();
|
||||
zero.move_to(at);
|
||||
zero.line_to(at);
|
||||
let (on_edge, corner, past) = (Point::new(154.5, 120.0), Point::new(154.0, 124.0), Point::new(156.0, 120.0));
|
||||
for (name, bp) in [("closed lone anchor", &lone), ("zero-length line", &zero)] {
|
||||
let round = stroke(10.0, |s| s.cap = LineCap::Round);
|
||||
let square = stroke(10.0, |s| s.cap = LineCap::Square);
|
||||
assert!(round.hits(bp, FillRule::NonZero, at, 0.1) && round.hits(bp, FillRule::NonZero, on_edge, 0.1), "{name}: round dot");
|
||||
assert!(!round.hits(bp, FillRule::NonZero, corner, 0.1) && !round.hits(bp, FillRule::NonZero, past, 0.1), "{name}: past the disc");
|
||||
assert!(square.hits(bp, FillRule::NonZero, corner, 0.1), "{name}: the square's corner");
|
||||
assert!(!square.hits(bp, FillRule::NonZero, past, 0.1), "{name}: past the square");
|
||||
assert!(!stroke(10.0, |_| {}).hits(bp, FillRule::NonZero, on_edge, 0.1), "{name}: a butt cap draws no dot");
|
||||
}
|
||||
// In a document: a click on the dot of a closed lone anchor hits the path's stroke, and a
|
||||
// marquee over the anchor selects it.
|
||||
let mut d = Document::new(300.0, 300.0);
|
||||
let (l, id) = (d.layers[0].id, d.alloc_id());
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 10.0);
|
||||
ap.stroke_mut().unwrap().cap = LineCap::Round;
|
||||
d.insert(Some(l), 0, Node::path(id, PathData::from_bezpath(&lone), ap)).unwrap();
|
||||
let opt = hit::HitOptions { tol: 0.5, ..Default::default() };
|
||||
let h = hit::hit_test(&d, Point::new(153.5, 121.0), opt).expect("a click on the dot");
|
||||
assert_eq!((h.leaf, h.kind), (id, hit::HitKind::Stroke));
|
||||
assert!(hit::hit_test(&d, Point::new(157.0, 120.0), opt).is_none(), "past the dot");
|
||||
assert_eq!(hit::marquee(&d, Rect::new(140.0, 110.0, 160.0, 130.0), None, false), vec![id]);
|
||||
}
|
||||
}
|
||||
@@ -435,6 +435,142 @@ fn art_on_artboard_tolerates_roundoff_at_each_edge() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_for_artboard_copy_takes_artwork_larger_than_artboard_or_with_bleed() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
d.setup.bleed = [9.0; 4];
|
||||
let layer = d.layers[0].id;
|
||||
// An oversized background (250x250 centered on the 200x200 artboard, #4479).
|
||||
let bg = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(bg, shapes::rectangle(Rect::new(-25.0, -25.0, 225.0, 225.0)), Appearance::default_art())).unwrap();
|
||||
// A shape with 5pt bleed over the top-right corner.
|
||||
let bleed = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(bleed, shapes::rectangle(Rect::new(150.0, -5.0, 205.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
// A shape lying entirely in the bleed margin without touching the artboard itself (-8..-2 vs 0..200).
|
||||
let bleed_margin_only = d.alloc_id();
|
||||
d.insert(
|
||||
Some(layer),
|
||||
usize::MAX,
|
||||
Node::path(bleed_margin_only, shapes::rectangle(Rect::new(-8.0, 50.0, -2.0, 100.0)), Appearance::default_art()),
|
||||
)
|
||||
.unwrap();
|
||||
// A small shape hanging 20pt over the left edge (center outside, more than bleed).
|
||||
let hanging = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(hanging, shapes::rectangle(Rect::new(-20.0, 90.0, 10.0, 120.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
// A straight line hanging 60pt over the left edge (center outside, no area): it lies on the
|
||||
// artboard for 40pt, so it is copied as a thin rectangle there would be.
|
||||
let line = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(line, shapes::line(Point::new(-60.0, 150.0), Point::new(40.0, 150.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
// A shape completely outside the artboard.
|
||||
let outside = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(outside, shapes::rectangle(Rect::new(300.0, 300.0, 400.0, 400.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
|
||||
// Standard art_on_artboard keeps strict containment: none of the overhanging shapes are on it.
|
||||
let strict_art = d.art_on_artboard(Rect::new(0.0, 0.0, 200.0, 200.0), false);
|
||||
assert!(!strict_art.contains(&bg), "strict art_on_artboard excludes oversized background");
|
||||
assert!(!strict_art.contains(&bleed), "strict art_on_artboard excludes bleed shape");
|
||||
assert!(!strict_art.contains(&bleed_margin_only), "strict art_on_artboard excludes bleed-margin-only shape");
|
||||
assert!(!strict_art.contains(&hanging), "strict art_on_artboard excludes hanging shape");
|
||||
assert!(!strict_art.contains(&outside), "strict art_on_artboard excludes outside shape");
|
||||
|
||||
// Copying the artboard takes the artwork touching this artboard that belongs to it, or within bleed.
|
||||
let copy_art = d.art_for_artboard_copy(0, false);
|
||||
assert!(copy_art.contains(&bg), "oversized background is copied with artboard: {copy_art:?}");
|
||||
assert!(copy_art.contains(&bleed), "bleed shape is copied with artboard: {copy_art:?}");
|
||||
assert!(copy_art.contains(&bleed_margin_only), "bleed-margin-only shape is copied with artboard: {copy_art:?}");
|
||||
assert!(copy_art.contains(&hanging), "touching shape owned by artboard 0 is copied: {copy_art:?}");
|
||||
assert!(copy_art.contains(&line), "a line hanging over the edge is copied: {copy_art:?}");
|
||||
assert!(!copy_art.contains(&outside), "outside shape is not copied: {copy_art:?}");
|
||||
|
||||
// If Artboard 1 is added next to Artboard 0, art primarily on Artboard 1 is not copied with Artboard 0:
|
||||
d.artboards.push(Artboard {
|
||||
id: 2,
|
||||
name: "Artboard 2".into(),
|
||||
rect: Rect::new(200.0, 0.0, 400.0, 200.0),
|
||||
locked: false,
|
||||
show_center_mark: false,
|
||||
show_cross_hairs: false,
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
guide_label: None,
|
||||
});
|
||||
// Shape spanning (190..300) x (50..150): 10pt on Artboard 0, 100pt on Artboard 1.
|
||||
let neighbor_art = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(neighbor_art, shapes::rectangle(Rect::new(190.0, 50.0, 300.0, 150.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
|
||||
let copy_art0 = d.art_for_artboard_copy(0, false);
|
||||
assert!(!copy_art0.contains(&neighbor_art), "art owned by neighboring Artboard 1 is not copied with Artboard 0");
|
||||
let copy_art1 = d.art_for_artboard_copy(1, false);
|
||||
assert!(copy_art1.contains(&neighbor_art), "art owned by Artboard 1 is copied with Artboard 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artboard_for_bounds_edge_cases_and_tie_breaks() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
// Artboard 0: (0, 0, 100, 100)
|
||||
// Artboard 1: (200, 0, 300, 100)
|
||||
d.artboards.push(Artboard {
|
||||
id: 2,
|
||||
name: "Artboard 2".into(),
|
||||
rect: Rect::new(200.0, 0.0, 300.0, 100.0),
|
||||
locked: false,
|
||||
show_center_mark: false,
|
||||
show_cross_hairs: false,
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
guide_label: None,
|
||||
});
|
||||
|
||||
// 1. Artwork whose center is outside all boards, but overlaps Artboard 0 most:
|
||||
// Bounds: (50, -100, 150, 50) -> Center: (100, -25) which is outside all artboards.
|
||||
// Overlap with Board 0: 50x50 = 2500; Board 1: 0.
|
||||
let b_center_outside = Rect::new(50.0, -100.0, 150.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_center_outside), Some(0));
|
||||
|
||||
// 2. Equal overlap on two boards (defined tie-break: the lower index, board 0):
|
||||
// Bounds: (50, -50, 250, 50) -> Center: (150, 0) outside all boards.
|
||||
// Overlap with Board 0: (50..100) x (0..50) = 2500; Board 1: (200..250) x (0..50) = 2500.
|
||||
let b_equal_overlap = Rect::new(50.0, -50.0, 250.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_equal_overlap), Some(0), "equal overlap picks lower index");
|
||||
|
||||
// 3. No overlap at all: returns None.
|
||||
let b_no_overlap = Rect::new(500.0, 500.0, 600.0, 600.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_no_overlap), None);
|
||||
|
||||
// 4. Rotated object bounds (bounds, not the inner geometry):
|
||||
// A 40x40 square rotated 45 deg centered at (50, 50) has bounding box ~56.57x56.57.
|
||||
let b_rotated_bounds = Rect::new(50.0 - 28.28, 50.0 - 28.28, 50.0 + 28.28, 50.0 + 28.28);
|
||||
assert_eq!(d.artboard_for_bounds(b_rotated_bounds), Some(0));
|
||||
|
||||
// 5. Zero-size bounds (a point):
|
||||
// On board 0:
|
||||
let b_zero_on_board = Rect::new(50.0, 50.0, 50.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_zero_on_board), Some(0));
|
||||
// Outside all boards:
|
||||
let b_zero_outside = Rect::new(150.0, 50.0, 150.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_zero_outside), None);
|
||||
|
||||
// 6. Straight lines whose center is outside every board: owned by the board they lie on most,
|
||||
// as a rectangle of any thickness would be (they have no area to compare).
|
||||
// Horizontal, from x = -100 to 50 on board 0: center (-25, 50).
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.0)), Some(0));
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.1)), Some(0), "the same as a thin rectangle");
|
||||
// Vertical, from y = -100 to 50 on board 1: center (250, -25).
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(250.0, -100.0, 250.0, 50.0)), Some(1));
|
||||
// Below both boards.
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 120.0, 260.0, 120.0)), None);
|
||||
// Across the gap between the boards, 20 pt on board 0 and 60 on board 1.
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 50.0, 260.0, 50.0)), Some(1), "center (170, 50) in the gap: board 1 holds more of it");
|
||||
// Only touching a board's corner from outside: no overlap.
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 0.0, 0.0, 0.0)), None);
|
||||
}
|
||||
|
||||
/// The art on a locked artboard (each object of a layer whose bounds overlap it, a group as one
|
||||
/// object) can't be edited, and Select All, a click and a marquee pass over it; art flush with
|
||||
/// the artboard from outside isn't on it, a layer is on no artboard, and new art isn't on one.
|
||||
|
||||
@@ -291,3 +291,15 @@ fn q_and_ha_suffixes_do_not_take_other_units_suffixes() {
|
||||
// A suffix after math covers the whole expression, as for the other units.
|
||||
assert!((Unit::Points.parse("26/2 q").unwrap() - Unit::Q.to_pt(13.0)).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_area_formats_and_trims_cleanly() {
|
||||
assert_eq!(Unit::Points.format_area(100.0), "100 pt²");
|
||||
assert_eq!(Unit::Inches.format_area(4.5 * 72.0 * 72.0), "4.5 in²");
|
||||
let mm_side = Unit::Millimeters.to_pt(1.0);
|
||||
assert_eq!(Unit::Millimeters.format_area(12.5 * mm_side * mm_side), "12.5 mm²");
|
||||
assert_eq!(Unit::Points.format_area(0.0), "0 pt²");
|
||||
assert_eq!(Unit::Points.format_area(-10.0), "0 pt²");
|
||||
assert_eq!(Unit::Points.format_area(f64::NAN), "0 pt²");
|
||||
assert_eq!(Unit::Points.format_area(f64::INFINITY), "0 pt²");
|
||||
}
|
||||
@@ -166,6 +166,19 @@ impl Unit {
|
||||
pub fn format(self, pt: f64) -> String {
|
||||
format!("{} {}", self.number(pt), self.suffix())
|
||||
}
|
||||
/// Format an area in square points into this unit (e.g. `12.5 mm²`, `4.5 in²`, `100 pt²`).
|
||||
pub fn format_area(self, pt2: f64) -> String {
|
||||
if !pt2.is_finite() || pt2 <= 0.0 {
|
||||
return format!("0 {}²", self.suffix());
|
||||
}
|
||||
let side = self.from_pt(1.0);
|
||||
let val = pt2 * side * side;
|
||||
let decimals = if matches!(self, Unit::Points | Unit::Pixels | Unit::Picas | Unit::Q | Unit::Ha) { 3 } else { 4 };
|
||||
let s = format!("{:.*}", decimals, val);
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
let s = if s == "-0" || s.is_empty() { "0" } else { s };
|
||||
format!("{s} {}²", self.suffix())
|
||||
}
|
||||
/// [`Unit::format`] without the suffix (`12.5`), for narrow fields.
|
||||
pub fn number(self, pt: f64) -> String {
|
||||
// Three decimals for the small units (`595.276 pt`), four for the large ones (`8.2677 in`,
|
||||
@@ -196,6 +209,15 @@ impl Unit {
|
||||
}
|
||||
parse_measure(×_as_asterisks(s), self).filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// Parse a measurement with decimal points or commas and no input locale. Refuse a
|
||||
/// number that looks like a grouped integer, even when it is part of an expression.
|
||||
pub fn parse_with_decimal_comma(self, text: &str) -> Option<f64> {
|
||||
if text.contains(',') && times_as_asterisks(text).split(['+', '-', '*', '/']).any(thousands_operand) {
|
||||
return None;
|
||||
}
|
||||
self.parse(&decimal_point(text))
|
||||
}
|
||||
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
|
||||
/// `feetInches`).
|
||||
pub const fn key(self) -> &'static str {
|
||||
@@ -397,6 +419,19 @@ pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() }
|
||||
}
|
||||
|
||||
/// Does the operand contain a thousands comma? Check both parts of a compact pica value and
|
||||
/// read a percentage's number without its percent sign.
|
||||
fn thousands_operand(operand: &str) -> bool {
|
||||
let operand = operand.trim();
|
||||
if let Some((picas, points)) = operand.split_once('p')
|
||||
&& !points.trim().is_empty()
|
||||
&& points.trim().bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b','))
|
||||
{
|
||||
return thousands(picas) || thousands(points);
|
||||
}
|
||||
thousands(operand.strip_suffix('%').unwrap_or(operand))
|
||||
}
|
||||
|
||||
/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or
|
||||
/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at
|
||||
/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it
|
||||
|
||||
@@ -82,7 +82,7 @@ pub(crate) fn apply(effects: &[vectorcraft_doc::Effect], path: &PathData, ctx: &
|
||||
if !has_geometry(effects) || path.is_empty() {
|
||||
return (path.clone(), crate::Carry::default());
|
||||
}
|
||||
let b = vectorcraft_geom::Shape::bounding_box(&path.to_bezpath());
|
||||
let b = path.bounds().unwrap_or_default();
|
||||
apply_geometry_carrying(effects, path, b, ctx)
|
||||
}
|
||||
|
||||
@@ -619,7 +619,12 @@ fn moved_type(n: &Node, moves: &[serde_json::Value]) -> Option<Vec<Node>> {
|
||||
}
|
||||
let (_, all) = glyph_outlines(t);
|
||||
let outline = PathData::from_bezpath(&all).transformed(t.xf);
|
||||
let ink = outline.bounds()?;
|
||||
// A contour of one anchor paints only as the dot of a round or projecting character stroke cap.
|
||||
let dots = t
|
||||
.runs
|
||||
.iter()
|
||||
.any(|r| r.style.appearance().painted_strokes().any(|s| matches!(s.cap, vectorcraft_doc::LineCap::Round | vectorcraft_doc::LineCap::Square)));
|
||||
let ink = outline.drawn_bounds(dots)?;
|
||||
let offsets = transform_offsets(moves, &outline)?;
|
||||
if offsets.len() > MAX_TYPE_COPIES {
|
||||
return None;
|
||||
|
||||
@@ -58,10 +58,61 @@ pub fn raster_px_range(id: &str, key: &str) -> Option<std::ops::RangeInclusive<f
|
||||
documented_range(id, key, "px")
|
||||
}
|
||||
|
||||
/// The range parameter `key` of effect `id` is documented with, after any number of unit words
|
||||
/// (`key: lo..hi`, `key: unit lo..hi`, `key: screen angle deg lo..hi`) or as the first word of its
|
||||
/// description in parentheses (`key: unit (lo..hi, default)`), and before the rest of that
|
||||
/// description or the next parameter; `None` when its documentation gives none.
|
||||
pub(crate) fn any_documented_range(id: &str, key: &str) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
let doc = catalog_index().get(id)?.params;
|
||||
let starts = |at: usize| starts_key(doc, at);
|
||||
doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| {
|
||||
let rest = doc.get(at + key.len()..)?;
|
||||
let rest = rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?;
|
||||
for word in rest.split_whitespace() {
|
||||
let opens = word.starts_with('(');
|
||||
if let Some((lo, hi)) = word.trim_start_matches('(').split_once("..") {
|
||||
let (lo, hi) = (lo.parse::<f64>().ok()?, hi.trim_end_matches([',', ';', ')', '}']).parse::<f64>().ok()?);
|
||||
return (lo.is_finite() && hi.is_finite() && lo <= hi).then_some(lo..=hi);
|
||||
}
|
||||
if opens {
|
||||
return None;
|
||||
}
|
||||
if word.ends_with([',', '}']) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
/// The choices parameter `key` of effect `id` is documented with (`key: "a"|"b"`, a note in
|
||||
/// parentheses allowed after a choice: `key: "a" (note)|"b"`); `None` when its documentation gives
|
||||
/// fewer than two.
|
||||
pub(crate) fn documented_choices(id: &str, key: &str) -> Option<Vec<&'static str>> {
|
||||
let doc = catalog_index().get(id)?.params;
|
||||
doc.match_indices(key).map(|(at, _)| at).filter(|at| starts_key(doc, *at)).find_map(|at| {
|
||||
let rest = doc.get(at + key.len()..)?;
|
||||
let mut rest = rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?;
|
||||
let mut choices = vec![];
|
||||
while let Some((choice, after)) = rest.strip_prefix('"').and_then(|r| r.split_once('"')) {
|
||||
choices.push(choice);
|
||||
let after = match after.strip_prefix(" (") {
|
||||
Some(note) => note.get(note.find(')')? + 1..)?,
|
||||
None => after,
|
||||
};
|
||||
match after.strip_prefix('|') {
|
||||
Some(next) => rest = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
(choices.len() >= 2).then_some(choices)
|
||||
})
|
||||
}
|
||||
|
||||
/// The range parameter `key` of effect `id` is documented with in `unit` (`key: unit lo..hi`).
|
||||
fn documented_range(id: &str, key: &str, unit: &str) -> Option<std::ops::RangeInclusive<f64>> {
|
||||
let doc = catalog_index().get(id)?.params;
|
||||
let starts = |at: usize| doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| c == '{' || c == ' ');
|
||||
let starts = |at: usize| starts_key(doc, at);
|
||||
let rest = doc.match_indices(key).map(|(at, _)| at).filter(|at| starts(*at)).find_map(|at| {
|
||||
let rest = doc.get(at + key.len()..)?;
|
||||
rest.strip_prefix(": ").or_else(|| rest.strip_prefix("?: "))?.strip_prefix(unit)?.strip_prefix(' ')
|
||||
@@ -71,6 +122,12 @@ fn documented_range(id: &str, key: &str, unit: &str) -> Option<std::ops::RangeIn
|
||||
(lo.is_finite() && hi.is_finite() && lo <= hi).then_some(lo..=hi)
|
||||
}
|
||||
|
||||
/// Can a parameter name start at byte `at` of parameter documentation `doc`: after `{`, a space or
|
||||
/// a comma?
|
||||
fn starts_key(doc: &str, at: usize) -> bool {
|
||||
doc.get(..at).and_then(|s| s.chars().last()).is_some_and(|c| matches!(c, '{' | ' ' | ','))
|
||||
}
|
||||
|
||||
/// The distance parameters of effect `id` (none for unknown effects).
|
||||
fn lengths_of(id: &str) -> Lengths {
|
||||
let always = |always| Lengths { always, absolute: &[] };
|
||||
@@ -257,7 +314,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"{corners: [[x,y]×4] (new positions of the bounding-box corners TL, TR, BR, BL in unit box coordinates; identity [[0,0],[1,0],[1,1],[0,1]]; placed gradients move and scale from the object's bounds to its distorted bounds)}",
|
||||
json!({"corners": [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}),
|
||||
),
|
||||
g("distort.puckerBloat", "Pucker & Bloat…", DT, "{amount: % (-200 pucker … 200 bloat, default 0)}", json!({"amount": 0.0})),
|
||||
g("distort.puckerBloat", "Pucker & Bloat…", DT, "{amount: % -200..200 (0; -200 puckers, 200 bloats)}", json!({"amount": 0.0})),
|
||||
g(
|
||||
"distort.roughen",
|
||||
"Roughen…",
|
||||
@@ -808,7 +865,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"adjust.temperatureTint",
|
||||
"Temperature/Tint…",
|
||||
ADJUST,
|
||||
"{temperature: -100 (cooler) .. 100 (warmer) (0), tint: -100 (greener) .. 100 (more magenta) (0)} recolours as Brightness/Contrast does",
|
||||
"{temperature: -100..100 (0; -100 cooler, 100 warmer), tint: -100..100 (0; -100 greener, 100 more magenta)} recolours as Brightness/Contrast does",
|
||||
json!({"temperature": 0.0, "tint": 0.0}),
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -447,6 +447,12 @@ pub(crate) fn apply_one(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &Geo
|
||||
budget.fits(Budget::of(&out)).then_some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The subpaths the Offset Path effect has offset on this thread.
|
||||
pub(crate) static OFFSET_SUBPATHS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Does geometry effect `id` build within the anchors it is given?
|
||||
fn builds_within(id: &str) -> bool {
|
||||
matches!(id, "distort.freeDistort" | "distort.roughen" | "distort.transform" | "distort.twist" | "distort.zigZag") || id.starts_with("warp.")
|
||||
@@ -456,6 +462,7 @@ fn builds_within(id: &str) -> bool {
|
||||
fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomContext, max: usize) -> PathData {
|
||||
use util::{join, num};
|
||||
if let Some(plugin) = vectorcraft_plugins::effect::plugin_id(id) {
|
||||
crate::params::check_returned_effects();
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item, at: ctx.stage };
|
||||
return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints, ctx.doc).unwrap_or_else(|| path.clone());
|
||||
}
|
||||
@@ -472,6 +479,8 @@ fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomCont
|
||||
if off.abs() < 1e-9 {
|
||||
return path.clone();
|
||||
}
|
||||
#[cfg(test)]
|
||||
OFFSET_SUBPATHS.with(|n| n.set(n.get() + path.subpaths.len()));
|
||||
vectorcraft_pathops::offset_path(path, off, join(p, "joins"), num(p, "miterLimit", 4.0).clamp(1.0, 500.0))
|
||||
}
|
||||
// Outline Object returns the geometry unchanged. Type reaches every geometry effect as its
|
||||
|
||||
@@ -350,7 +350,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod
|
||||
fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node {
|
||||
let mut m = src.clone();
|
||||
if let Some((path, rule)) = geometry(src) {
|
||||
let bounds = vectorcraft_geom::Shape::bounding_box(&path.to_bezpath());
|
||||
let bounds = path.bounds().unwrap_or_default();
|
||||
let (g, carry) =
|
||||
crate::apply_geometry_carrying(&n.appearance.effects, &path, bounds, &crate::GeomContext { doc, ..crate::GeomContext::of(n) });
|
||||
m.kind = NodeKind::Path { path: g, rule, live: None, clipping: false, guide: false };
|
||||
|
||||
@@ -135,6 +135,6 @@ pub use geometry::{
|
||||
#[cfg(test)]
|
||||
pub(crate) use geometry::{MAX_EFFECT_LINES, apply_geometry_within};
|
||||
pub use params::{
|
||||
any_plugin_paints_output, default_params, has_geometry, has_painted_plugin_effect, has_plugin_effect, is_geometry, is_raster, merged_params,
|
||||
new_effect, plugin_revision, scale_effect, upgrade_params,
|
||||
any_plugin_paints_output, check_returned_effect, default_params, has_geometry, has_painted_plugin_effect, has_plugin_effect, is_geometry,
|
||||
is_raster, merged_params, new_effect, plugin_revision, scale_effect, upgrade_params,
|
||||
};
|
||||
@@ -139,6 +139,201 @@ pub fn new_effect(id: &str, params: &Value) -> Option<Effect> {
|
||||
Some(Effect { id: id.to_string(), params, visible: true })
|
||||
}
|
||||
|
||||
/// Checks an effect record that a painted live-effect plug-in returns on a piece, or on one of its
|
||||
/// fills or strokes (`row`) ([`vectorcraft_plugins::painted::CheckEffect`]): a built-in effect other
|
||||
/// than a 3D or Pathfinder effect, a raster effect only on a fill or stroke, and parameters that effect takes. A
|
||||
/// parameter is one its defaults or its parameter documentation name, of the type its default has,
|
||||
/// within the range its documentation gives ([`crate::catalog::any_documented_range`]) and one of the
|
||||
/// choices it lists ([`crate::catalog::documented_choices`]); a texture is one as `effect.list`
|
||||
/// gives it, and an SVG filter's XML one drawable filter. A plug-in effect, the plug-in itself
|
||||
/// included, is refused, so the effects a plug-in returns never run a plug-in.
|
||||
pub fn check_returned_effect(e: &Effect, row: bool) -> Result<(), String> {
|
||||
if e.id.starts_with(vectorcraft_plugins::effect::PREFIX) {
|
||||
return Err("plug-in effects are not allowed in returned effects".into());
|
||||
}
|
||||
let Some(info) = catalog_index().get(e.id.as_str()) else {
|
||||
return Err(format!("unknown effect {:?}", e.id));
|
||||
};
|
||||
if is_three_d(&e.id) {
|
||||
return Err("3D effects are not allowed in returned effects".into());
|
||||
}
|
||||
if is_pathfinder(&e.id) {
|
||||
return Err("Pathfinder effects are not allowed in returned effects; a piece is one path, with nothing to combine".into());
|
||||
}
|
||||
if row && !is_raster(&e.id) {
|
||||
return Err(format!("{:?} is not a raster effect; a fill or stroke takes raster effects only", e.id));
|
||||
}
|
||||
let given = match &e.params {
|
||||
Value::Null => return Ok(()),
|
||||
Value::Object(m) => m,
|
||||
_ => return Err("`params` must be an object".into()),
|
||||
};
|
||||
let defaults = info.defaults.as_object();
|
||||
for (key, v) in given {
|
||||
let default = defaults.and_then(|d| d.get(key));
|
||||
if default.is_none() && !documents_key(info.params, key) {
|
||||
return Err(format!("`{key}` is not a parameter of {:?}", e.id));
|
||||
}
|
||||
let kind = |v: &Value| std::mem::discriminant(v);
|
||||
// A `color` is checked as a color, in any form the effect draws ([`is_color`]).
|
||||
let color = key == "color" && default.is_some_and(Value::is_string);
|
||||
// Curves' `points` is also taken as [[x, y], …], as the effect draws it.
|
||||
let curve = e.id == "adjust.curves" && key == "points" && v.is_array();
|
||||
if let Some(d) = default
|
||||
&& !d.is_null()
|
||||
&& !color
|
||||
&& !curve
|
||||
&& kind(d) != kind(v)
|
||||
{
|
||||
return Err(format!("`{key}` must be of the type its default {d} has"));
|
||||
}
|
||||
let range = crate::catalog::any_documented_range(&e.id, key);
|
||||
if let (Some(r), Some(x)) = (range, v.as_f64())
|
||||
&& !r.contains(&x)
|
||||
{
|
||||
return Err(format!("`{key}` must be from {} to {}", r.start(), r.end()));
|
||||
}
|
||||
if let Some(choices) = crate::catalog::documented_choices(&e.id, key)
|
||||
&& !v.as_str().is_some_and(|v| choices.contains(&v))
|
||||
{
|
||||
return Err(format!("`{key}` must be one of \"{}\"", choices.join("\", \"")));
|
||||
}
|
||||
}
|
||||
if let Some(t) = given.get(crate::pixel::TEXTURE_IMAGE)
|
||||
&& t.as_str().is_none_or(|t| crate::pixel::texture(t).is_none())
|
||||
{
|
||||
return Err("`textureImage` must be a texture as effect.list gives it".into());
|
||||
}
|
||||
check_returned_values(&e.id, given)
|
||||
}
|
||||
|
||||
/// The values in `given`, the parameters of built-in effect `id` that a painted live-effect plug-in
|
||||
/// returned, that are checked further: an SVG filter's XML, `scale`, `origin`, `axes` and
|
||||
/// `name`; a Free Distort's four `corners`; Curves' `points` as pairs from 0 to 255; a Transform's whole
|
||||
/// `copies` and `reference`; a Warp's `version`; a `color` the effect can draw; a
|
||||
/// shadow's or glow's blend `mode`; a Levels or Curves `channel`; a Radial
|
||||
/// Blur's center; and the type of each parameter without a default.
|
||||
fn check_returned_values(id: &str, given: &Map<String, Value>) -> Result<(), String> {
|
||||
let number = |key: &str| given.get(key).is_some_and(|v| !v.is_number());
|
||||
let switch = |key: &str| given.get(key).is_some_and(|v| !v.is_boolean());
|
||||
if id == crate::SVG_FILTER {
|
||||
if let Some(xml) = given.get("xml") {
|
||||
crate::svg_filter::check(xml.as_str().ok_or("`xml` must be a string")?)?;
|
||||
}
|
||||
if given.get("scale").is_some_and(|s| !s.as_f64().is_some_and(|k| (0.001..=1000.0).contains(&k))) {
|
||||
return Err("`scale` must be a number from 0.001 to 1000".into());
|
||||
}
|
||||
if given
|
||||
.get("origin")
|
||||
.is_some_and(|o| !o.as_array().is_some_and(|o| o.len() == 2 && o.iter().all(|v| v.as_f64().is_some_and(f64::is_finite))))
|
||||
{
|
||||
return Err("`origin` must be [x, y] in points".into());
|
||||
}
|
||||
if given.get("axes").is_some_and(|a| crate::svg_filter::valid_axes(a).is_none()) {
|
||||
return Err("`axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0".into());
|
||||
}
|
||||
if given.contains_key("name") && !given.contains_key("xml") {
|
||||
return Err("an SVG filter is named by its id: give `xml` with `name`".into());
|
||||
}
|
||||
}
|
||||
let pair = |p: &Value| p.as_array().is_some_and(|p| p.len() == 2 && p.iter().all(|v| v.as_f64().is_some_and(f64::is_finite)));
|
||||
if id == "distort.freeDistort" && given.get("corners").is_some_and(|c| !c.as_array().is_some_and(|c| c.len() == 4 && c.iter().all(pair))) {
|
||||
return Err("`corners` must be four [x, y] pairs of numbers".into());
|
||||
}
|
||||
if id == "adjust.curves" && given.get("points").is_some_and(|p| !is_curve_points(p)) {
|
||||
return Err("`points` must be \"x,y x,y …\" or [[x, y], …] pairs of numbers from 0 to 255".into());
|
||||
}
|
||||
if id == "distort.transform"
|
||||
&& let Some(key) = ["copies", "reference"].into_iter().find(|k| given.get(*k).and_then(Value::as_f64).is_some_and(|x| x.fract() != 0.0))
|
||||
{
|
||||
return Err(format!("`{key}` must be a whole number"));
|
||||
}
|
||||
if id.starts_with("warp.") && given.get("version").is_some_and(|v| crate::warp_version(v).is_none()) {
|
||||
return Err(format!("`version` must be 0 or {}", crate::WARP_NET));
|
||||
}
|
||||
let takes_color = catalog_index().get(id).is_some_and(|info| info.defaults.get("color").is_some_and(Value::is_string));
|
||||
if takes_color && given.get("color").is_some_and(|v| !is_color(v)) {
|
||||
return Err("`color` must be a #rrggbb color, [r, g, b] from 0 to 1 or a color object".into());
|
||||
}
|
||||
let takes_blend_mode = catalog_index().get(id).is_some_and(|info| info.params.contains("mode: blend mode"));
|
||||
if takes_blend_mode && given.get("mode").is_some_and(|v| v.as_str().and_then(crate::raster::named_blend_mode).is_none()) {
|
||||
return Err("`mode` must be a blend mode, such as \"multiply\" or \"screen\"".into());
|
||||
}
|
||||
if matches!(id, "adjust.levels" | "adjust.curves") && given.get("channel").is_some_and(|v| !v.as_str().is_some_and(crate::is_channel)) {
|
||||
return Err(format!("`channel` must be one of {}", crate::CHANNELS.join(", ")));
|
||||
}
|
||||
if id == "blur.radial" {
|
||||
for key in ["centerX", "centerY"] {
|
||||
if given.get(key).is_some_and(|v| !v.as_f64().is_some_and(|x| (0.0..=1.0).contains(&x))) {
|
||||
return Err(format!("`{key}` must be a number from 0 to 1"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let numbers: &[&str] = match id {
|
||||
"stylize.scribble" => &["variation"],
|
||||
"path.outlineStroke" => &["width"],
|
||||
_ => &[],
|
||||
};
|
||||
if let Some(key) = numbers.iter().find(|k| number(k)) {
|
||||
return Err(format!("`{key}` must be a number"));
|
||||
}
|
||||
if id == "blur.gaussian" && switch("linear") {
|
||||
return Err("`linear` must be true or false".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Can Curves read `v` as its `points`: `"x,y x,y …"` (pairs split by whitespace or `;`) or
|
||||
/// `[[x, y], …]`, each number from 0 to 255?
|
||||
fn is_curve_points(v: &Value) -> bool {
|
||||
let level = |x: f64| (0.0..=255.0).contains(&x);
|
||||
match v {
|
||||
Value::String(s) => s
|
||||
.split(|c: char| c.is_whitespace() || c == ';')
|
||||
.filter(|p| !p.is_empty())
|
||||
.all(|p| p.split_once(',').is_some_and(|(x, y)| [x, y].into_iter().all(|n| n.trim().parse::<f64>().is_ok_and(level)))),
|
||||
Value::Array(a) => a.iter().all(|p| p.as_array().is_some_and(|p| p.len() == 2 && p.iter().all(|n| n.as_f64().is_some_and(level)))),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Can an effect read `v` as its `color`: a hex color or name [`Color::from_hex`] reads, `[r, g, b]`
|
||||
/// with three numbers from 0 to 1 first, or a color object with its components from 0 to 1 (a Lab
|
||||
/// color's lightness from 0 to 100, and finite a and b)?
|
||||
///
|
||||
/// [`Color::from_hex`]: vectorcraft_doc::color::Color::from_hex
|
||||
fn is_color(v: &Value) -> bool {
|
||||
use vectorcraft_doc::color::Color;
|
||||
let unit = |x: f32| (0.0..=1.0).contains(&x);
|
||||
match v {
|
||||
Value::String(s) => Color::from_hex(s).is_some(),
|
||||
Value::Array(a) => a.len() >= 3 && a.iter().take(3).all(|c| c.as_f64().is_some_and(|c| (0.0..=1.0).contains(&c))),
|
||||
Value::Object(_) => match serde_json::from_value::<Color>(v.clone()) {
|
||||
Ok(Color::Rgb { r, g, b }) => [r, g, b].into_iter().all(unit),
|
||||
Ok(Color::Cmyk { c, m, y, k }) => [c, m, y, k].into_iter().all(unit),
|
||||
Ok(Color::Gray { k }) => unit(k),
|
||||
Ok(Color::Lab { l, a, b }) => (0.0..=100.0).contains(&l) && a.is_finite() && b.is_finite(),
|
||||
Err(_) => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Does parameter documentation `doc` (`{edgeWidth: pt 1..14 (2), …}`) name parameter `key`?
|
||||
fn documents_key(doc: &str, key: &str) -> bool {
|
||||
doc.match_indices(key).any(|(at, _)| {
|
||||
let before = doc.get(..at).and_then(|s| s.chars().last());
|
||||
let after = doc.get(at + key.len()..).unwrap_or_default();
|
||||
matches!(before, Some('{' | ' ' | ',' | '|')) && (after.starts_with(':') || after.starts_with('?'))
|
||||
})
|
||||
}
|
||||
|
||||
/// Makes [`check_returned_effect`] how this process checks the effect records painted live-effect
|
||||
/// plug-ins return ([`vectorcraft_plugins::painted::set_effect_check`]).
|
||||
pub(crate) fn check_returned_effects() {
|
||||
vectorcraft_plugins::painted::set_effect_check(check_returned_effect);
|
||||
}
|
||||
|
||||
/// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see
|
||||
/// [`EffectInfo::lengths`]), and its sizes in raster pixels ([`crate::raster_px_range`]), which
|
||||
/// keep their share of the object so. A distance left at its default is written out scaled; one
|
||||
|
||||
@@ -435,7 +435,7 @@ fn reshapes(n: &Node) -> bool {
|
||||
fn path_art(n: &Node) -> Option<Node> {
|
||||
let (path, rule) = leaf_geometry(n)?;
|
||||
let ctx = GeomContext::of(n);
|
||||
let g = apply_geometry_with(&n.appearance.effects, &path, path.to_bezpath().bounding_box(), &ctx);
|
||||
let g = apply_geometry_with(&n.appearance.effects, &path, path.bounds().unwrap_or_default(), &ctx);
|
||||
let piece = |geometry: PathData, items: Vec<AppearanceItem>| {
|
||||
let mut ap: Appearance = (*n.appearance).clone();
|
||||
ap.items = items;
|
||||
@@ -454,7 +454,7 @@ fn path_art(n: &Node) -> Option<Node> {
|
||||
if own.is_empty() || plain.iter().any(|i| paints(i)) {
|
||||
pieces.push(piece(g.clone(), plain.into_iter().cloned().collect()));
|
||||
}
|
||||
let bounds = g.to_bezpath().bounding_box();
|
||||
let bounds = g.bounds().unwrap_or_default();
|
||||
for item in own {
|
||||
let geometry = apply_geometry_with(item.effects(), &g, bounds, &ctx.item(item));
|
||||
pieces.push(piece(geometry, vec![item.clone()]));
|
||||
|
||||
@@ -365,8 +365,13 @@ impl Rasterize {
|
||||
|
||||
/// Parse a blend mode name (`"multiply"`, `"Screen"`, `"color-burn"`…).
|
||||
pub fn blend_mode(s: &str) -> BlendMode {
|
||||
named_blend_mode(s).unwrap_or(BlendMode::Normal)
|
||||
}
|
||||
|
||||
/// The blend mode `s` names as [`blend_mode`] reads it; `None` when it names none.
|
||||
pub(crate) fn named_blend_mode(s: &str) -> Option<BlendMode> {
|
||||
let key: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();
|
||||
BlendMode::ALL.iter().copied().find(|m| format!("{m:?}").to_ascii_lowercase() == key).unwrap_or(BlendMode::Normal)
|
||||
BlendMode::ALL.iter().copied().find(|m| format!("{m:?}").to_ascii_lowercase() == key)
|
||||
}
|
||||
|
||||
/// An effect's `color` parameter (`"#rrggbb"`, `[r, g, b]` 0..1 or a colour object).
|
||||
|
||||
+195
-42
@@ -20,7 +20,7 @@ use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak};
|
||||
|
||||
use vectorcraft_doc::live::Hooks;
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, ImageObject, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape, shapes};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes};
|
||||
|
||||
use crate::{Budget, GeomContext, OutlineHook, apply_one, is_geometry, merged_params};
|
||||
|
||||
@@ -659,7 +659,7 @@ fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRu
|
||||
for item in c.appearance.items.iter().filter(|i| crate::paints(i)) {
|
||||
let fx = item.effects();
|
||||
let shape = if crate::has_geometry(fx) && !g.elements().is_empty() {
|
||||
crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item))
|
||||
crate::apply_geometry_bez(fx, &g, vectorcraft_geom::path::anchored_curve_bounds(&g).unwrap_or_default(), &ctx.item(item))
|
||||
} else {
|
||||
g.clone()
|
||||
};
|
||||
@@ -1260,7 +1260,7 @@ fn as_art_opts(
|
||||
) -> Option<Node> {
|
||||
if let Some(t) = copied_raster_at(n) {
|
||||
let outlined = |s: &Node| as_art_opts(symbols, paint_doc, s, symbol_art, outline, nodes, apart);
|
||||
return copied_raster_art(paint_doc, n, t, apart, &outlined).map(|art| dressed_keeping_effects(art, n));
|
||||
return copied_raster_art(paint_doc, n, t, (apart, true), &outlined, None).map(|art| dressed_keeping_effects(art, n));
|
||||
}
|
||||
let fx = geometry_effects(n);
|
||||
let mut art = match &n.kind {
|
||||
@@ -1382,13 +1382,26 @@ fn dressed_keeping_effects(mut art: Node, n: &Node) -> Node {
|
||||
/// object of its own ([`copy_leaf`]). Type, an image or a symbol instance becomes its art through
|
||||
/// `outlined` ([`as_art_opts`]) before it is copied: type as its outlines, an image in its frame
|
||||
/// and an instance as its symbol's art, whose members take their own geometry effects first
|
||||
/// ([`crate::group::members_as_drawn`]). `None` when `outlined` gives no art.
|
||||
fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, outlined: &dyn Fn(&Node) -> Option<Node>) -> Option<Node> {
|
||||
/// ([`crate::group::members_as_drawn`]). With `items`, the pieces a path's fills and strokes make
|
||||
/// of it ([`transform_items`]) are made before it is copied; without, its fills and strokes keep
|
||||
/// their effects for their own stage. Given `check`, a budget and a flag, the art keeps to that
|
||||
/// budget in place of [`Budget::EFFECTS`], and the flag is set to `false` when an effect leaves a
|
||||
/// path with its shape or makes fewer copies than it asks for ([`reshape_leaves_checked`]); the
|
||||
/// art is then incomplete. `None` when `outlined` gives no art.
|
||||
fn copied_raster_art(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
t: usize,
|
||||
(apart, items): (bool, bool),
|
||||
outlined: &dyn Fn(&Node) -> Option<Node>,
|
||||
mut check: Option<(Budget, &mut bool)>,
|
||||
) -> Option<Node> {
|
||||
let budget = check.as_ref().map_or(Budget::EFFECTS, |(b, _)| *b);
|
||||
let (before, rest) = n.appearance.effects.split_at(t);
|
||||
let mut source = n.clone();
|
||||
source.appearance.effects = before.to_vec();
|
||||
let piece = match copied_raster_at(&source) {
|
||||
Some(at) => copied_raster_art(doc, &source, at, apart, outlined)?,
|
||||
Some(at) => copied_raster_art(doc, &source, at, (apart, items), outlined, check.as_mut().map(|(b, c)| (*b, &mut **c)))?,
|
||||
None if needs_outline(&source) => {
|
||||
let mut art = outlined(&source)?;
|
||||
if matches!(source.kind, NodeKind::SymbolInstance { .. }) && geometry_effects(&source).is_empty() {
|
||||
@@ -1404,11 +1417,15 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou
|
||||
None => {
|
||||
let mut art = one_piece(&source);
|
||||
let rows = has_copied_row_raster(&source);
|
||||
let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, (apart, rows), doc);
|
||||
let fx = geometry_effects(&source);
|
||||
let carry =
|
||||
reshape_leaves_checked(&mut art, &fx, &source.appearance.effects, budget, (apart, rows), doc, check.as_mut().map(|(_, c)| &mut **c));
|
||||
if apart {
|
||||
hoist_copies(&mut art);
|
||||
}
|
||||
transform_items(&mut art, doc);
|
||||
if items {
|
||||
transform_items(&mut art, doc);
|
||||
}
|
||||
let mut ran = source.appearance.effects.clone();
|
||||
if carry.skipped() {
|
||||
carry.hide_skipped(&mut ran);
|
||||
@@ -1425,8 +1442,13 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou
|
||||
// The raster effects follow the copies below; Scale Strokes & Effects scales the others.
|
||||
let mut scaling = copy_scaling(options);
|
||||
scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64));
|
||||
let max = Budget::EFFECTS.at_least(art_cost(&art));
|
||||
let max = budget.at_least(art_cost(&art));
|
||||
copy_art(&mut art, m, copies, scaling, max);
|
||||
if let Some((_, complete)) = check.as_mut()
|
||||
&& art.children().map_or(0, Vec::len) <= copies
|
||||
{
|
||||
**complete = false;
|
||||
}
|
||||
if let Some(children) = art.children_mut() {
|
||||
// The original is last, and each copy above it is mapped once more by `m`.
|
||||
let step = m.with_translation(vectorcraft_geom::Vec2::ZERO);
|
||||
@@ -1445,7 +1467,8 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou
|
||||
}
|
||||
}
|
||||
let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect();
|
||||
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), doc);
|
||||
let rows = has_copied_row_raster(n);
|
||||
let carry = reshape_leaves_checked(&mut art, &later, &n.appearance.effects, budget, (apart, rows), doc, check.map(|(_, c)| c));
|
||||
let mut ran = n.appearance.effects.clone();
|
||||
if carry.skipped() {
|
||||
carry.hide_skipped(&mut ran);
|
||||
@@ -1493,7 +1516,7 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option<Node>
|
||||
return None;
|
||||
}
|
||||
if let Some(t) = copied_raster_at(n) {
|
||||
return copied_raster_art(doc, n, t, false, &|_| None).map(|art| dressed_keeping_effects(art, n));
|
||||
return copied_raster_art(doc, n, t, (false, true), &|_| None, None).map(|art| dressed_keeping_effects(art, n));
|
||||
}
|
||||
if n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) {
|
||||
// One element: its pieces never knock each other out.
|
||||
@@ -1625,12 +1648,27 @@ fn hoist_copies(art: &mut Node) {
|
||||
/// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked
|
||||
/// masks keeps its shape under that effect.
|
||||
fn reshape_leaves_apart(
|
||||
art: &mut Node,
|
||||
fx: &[&Effect],
|
||||
owner: &[Effect],
|
||||
budget: Budget,
|
||||
flags: (bool, bool),
|
||||
doc: Option<&Document>,
|
||||
) -> crate::Carry {
|
||||
reshape_leaves_checked(art, fx, owner, budget, flags, doc, None)
|
||||
}
|
||||
|
||||
/// [`reshape_leaves_apart`] that, given `complete`, stops at the first effect that leaves a path in
|
||||
/// the art with its shape or makes fewer copies than it asks for, past `budget` ([`Ran::kept`],
|
||||
/// [`Ran::short`]), and sets `complete` to `false`; the art is then partly reshaped.
|
||||
fn reshape_leaves_checked(
|
||||
art: &mut Node,
|
||||
fx: &[&Effect],
|
||||
owner: &[Effect],
|
||||
budget: Budget,
|
||||
(apart, rows): (bool, bool),
|
||||
doc: Option<&Document>,
|
||||
mut complete: Option<&mut bool>,
|
||||
) -> crate::Carry {
|
||||
let mut whole = crate::Carry::default();
|
||||
if fx.is_empty() {
|
||||
@@ -1668,11 +1706,18 @@ fn reshape_leaves_apart(
|
||||
let params = merged_params(&e.id, &e.params);
|
||||
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
|
||||
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
|
||||
let step = Step { e, params: ¶ms, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held };
|
||||
let strict = complete.is_some();
|
||||
let step = Step { e, params: ¶ms, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held, strict };
|
||||
// Art with linked masks keeps its shape under an effect that a mask in it could not take
|
||||
// as the art it masks did, so no mask is left apart from its art.
|
||||
let before = masked.then(|| (art.clone(), used));
|
||||
let ran = step.run(art, max, &mut used, copy_whole, Some(&mut warped), false, 0);
|
||||
if (ran.kept || ran.short)
|
||||
&& let Some(complete) = complete.as_deref_mut()
|
||||
{
|
||||
*complete = false;
|
||||
return whole;
|
||||
}
|
||||
if (ran.masks || ran.short)
|
||||
&& let Some((was, cost)) = before
|
||||
{
|
||||
@@ -1704,7 +1749,8 @@ fn reshape_leaves_apart(
|
||||
/// swatches and patterns of painted pieces are looked up in, [`copies_whole`] of the art of
|
||||
/// each linked mask before the first effect, by the id of the object it masks, and whether one of
|
||||
/// the object's effects holds the raster effects in its art back from its Transform effects
|
||||
/// ([`follow_art`]).
|
||||
/// ([`follow_art`]), and whether a Transform effect that makes fewer copies of anything in the art
|
||||
/// than it asks for is reported ([`Ran::short`]) wherever it is (`strict`).
|
||||
struct Step<'a> {
|
||||
e: &'a Effect,
|
||||
params: &'a serde_json::Value,
|
||||
@@ -1716,6 +1762,7 @@ struct Step<'a> {
|
||||
doc: Option<&'a Document>,
|
||||
wholes: &'a HashMap<NodeId, bool>,
|
||||
held: bool,
|
||||
strict: bool,
|
||||
}
|
||||
|
||||
/// What [`Step::run`] did to a piece of art.
|
||||
@@ -1728,7 +1775,8 @@ struct Ran {
|
||||
/// took the effect, or could have ([`Step::reshape_masks`]).
|
||||
masks: bool,
|
||||
/// A Transform effect made fewer copies of a path, image or symbol instance than it asks for
|
||||
/// (past the budget or out of reach), where a linked mask could take a different number.
|
||||
/// (past the budget or out of reach), where a linked mask could take a different number, or
|
||||
/// anywhere in the art for a [`Step`] with `strict`.
|
||||
short: bool,
|
||||
/// How what paints the art as a whole follows the effect, when it does.
|
||||
whole: Option<crate::Carry>,
|
||||
@@ -1840,7 +1888,8 @@ impl Step<'_> {
|
||||
{
|
||||
if !own {
|
||||
*used = copy_art(art, m, copies, copy_scaling(options), max);
|
||||
return Ran { kept: false, took: true, masks: false, short: false, whole: None };
|
||||
let short = self.strict && art.children().is_some_and(|c| c.iter().filter(|c| !c.is_guide()).count() <= copies);
|
||||
return Ran { kept: false, took: true, masks: false, short, whole: None };
|
||||
}
|
||||
// A mask's art: its copies keep to what the rest of the art leaves of `max`, and the
|
||||
// linked mask of the art itself takes them too. That mask's art stays in `used`, as
|
||||
@@ -1861,7 +1910,7 @@ impl Step<'_> {
|
||||
if watch && !own {
|
||||
masked_ids(art, false, &mut covered);
|
||||
}
|
||||
let counts = |id: NodeId| watch && (own || covered.contains(&id));
|
||||
let counts = |id: NodeId| self.strict || (watch && (own || covered.contains(&id)));
|
||||
let mut short = false;
|
||||
let mut took = false;
|
||||
for_each_leaf(art, &mut |leaf| {
|
||||
@@ -1902,7 +1951,7 @@ impl Step<'_> {
|
||||
if options.objects {
|
||||
moved_ids.insert(leaf.id);
|
||||
}
|
||||
short |= counts(leaf.id) && copied(leaf) <= copies;
|
||||
short |= copies > 0 && counts(leaf.id) && copied(leaf) <= copies;
|
||||
} else {
|
||||
kept_ids.insert(leaf.id);
|
||||
}
|
||||
@@ -2517,7 +2566,8 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling
|
||||
/// path or compound path, as one of its object's effects with reference box `bounds`: `leaf`
|
||||
/// becomes a group with its id and name of one object for each piece returned, in order, each with
|
||||
/// the piece's geometry and the leaf's appearance with the piece's fills and strokes in place of
|
||||
/// its own ([`vectorcraft_plugins::painted::appearance`]). The swatches and patterns the pieces
|
||||
/// its own ([`vectorcraft_plugins::painted::appearance`]), and the piece's opacity, blending mode
|
||||
/// and effects ([`dress_piece`]). The swatches and patterns the pieces
|
||||
/// name must be in `doc`, and without one the pieces may name none. Returns what the pieces cost
|
||||
/// ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails, the pieces are
|
||||
/// refused, or they would pass `budget`. A deferred run is listed by `at`.
|
||||
@@ -2531,28 +2581,112 @@ fn paint_leaf(
|
||||
at: Option<vectorcraft_plugins::deferred::Stage>,
|
||||
) -> Option<Budget> {
|
||||
let (path, rule) = leaf_geometry(leaf)?;
|
||||
crate::params::check_returned_effects();
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: None, at };
|
||||
let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?;
|
||||
let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
|
||||
let mut made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
|
||||
if !budget.fits(made) {
|
||||
return None;
|
||||
}
|
||||
let children = pieces
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let mut one = leaf.clone();
|
||||
one.name = None;
|
||||
one.appearance = vectorcraft_plugins::painted::appearance(&leaf.appearance, p).into();
|
||||
set_geometry(&mut one, p.path.clone(), p.rule);
|
||||
Arc::new(one)
|
||||
})
|
||||
.collect();
|
||||
let mut children = Vec::with_capacity(pieces.len());
|
||||
for p in pieces.iter() {
|
||||
let mut one = leaf.clone();
|
||||
one.name = None;
|
||||
one.appearance = vectorcraft_plugins::painted::appearance(&leaf.appearance, p).into();
|
||||
set_geometry(&mut one, p.path.clone(), p.rule);
|
||||
// The pieces' own geometry effects keep to what the pieces before them leave of the budget.
|
||||
made = made.plus(dress_piece(&mut one, &p.look, budget.minus(made), doc)?);
|
||||
children.push(Arc::new(one));
|
||||
}
|
||||
let mut g = Node::group(leaf.id, children);
|
||||
g.name = leaf.name.clone();
|
||||
*leaf = g;
|
||||
Some(made)
|
||||
}
|
||||
|
||||
/// Gives `one`, the object a painted piece becomes, the piece's `look`: its opacity times the
|
||||
/// object's, its blending mode, and its effects after the object's own. The visible geometry effects
|
||||
/// among them, and only those, reshape the piece at once ([`reshape_leaves_checked`], with `doc`), so they run
|
||||
/// before the source's later effects and the effects of its fills and strokes stay for their own
|
||||
/// stage; the object becomes a group with its id around the reshaped piece, carrying its
|
||||
/// transparency and effects. The piece's raster effects stay on it and draw on it, except that when
|
||||
/// they are listed before a Transform effect that makes copies ([`copied_raster_at`]), each copy
|
||||
/// carries its own, moved, turned, reflected and scaled with it ([`copied_raster_art`]). When the object
|
||||
/// has a blending mode other than Normal and the piece gives one, the same one included, the object
|
||||
/// becomes a group with its blending mode around the piece, so both apply. Returns what the reshaped piece costs
|
||||
/// past its own path; `None` when its geometry effects would cost more than `room` past it: they stop at the first
|
||||
/// effect that does not fit, and `one` is then incomplete.
|
||||
pub(crate) fn dress_piece(one: &mut Node, look: &vectorcraft_plugins::painted::Look, room: Budget, doc: Option<&Document>) -> Option<Budget> {
|
||||
use vectorcraft_doc::color::BlendMode;
|
||||
let none = Budget { anchors: 0, lines: 0 };
|
||||
if look.is_empty() {
|
||||
return Some(none);
|
||||
}
|
||||
let outer = look.blend.filter(|_| one.blend != BlendMode::Normal).map(|_| one.blend);
|
||||
if let Some(o) = look.opacity {
|
||||
one.opacity *= o;
|
||||
}
|
||||
if let Some(b) = look.blend {
|
||||
one.blend = b;
|
||||
}
|
||||
// A Transform effect that makes copies, with raster effects listed before it: each copy is an
|
||||
// object of its own carrying those raster effects, as an object's copies are
|
||||
// ([`copied_raster_art`]). The object's own effects paint around all of them, then the piece's
|
||||
// from the Transform effect on.
|
||||
let mut probe = one.clone();
|
||||
probe.appearance.effects = look.effects.clone();
|
||||
let mut extra = none;
|
||||
if let Some(t) = copied_raster_at(&probe) {
|
||||
let before = art_cost(one);
|
||||
let mut complete = true;
|
||||
let art = copied_raster_art(doc, &probe, t, (false, false), &|_| None, Some((room.plus(before), &mut complete)))?;
|
||||
#[cfg(test)]
|
||||
DRESSED.with(|d| d.set(d.get().plus(art_cost(&art))));
|
||||
extra = art_cost(&art).minus(before);
|
||||
if !complete || !room.fits(extra) {
|
||||
return None;
|
||||
}
|
||||
let mut effects = std::mem::take(&mut one.appearance.effects);
|
||||
effects.extend(art.appearance.effects.iter().cloned());
|
||||
let mut art = dressed(art, one);
|
||||
art.appearance.effects = effects;
|
||||
*one = art;
|
||||
} else {
|
||||
let shape: Vec<Effect> = look.effects.iter().filter(|e| e.visible && is_geometry(&e.id)).cloned().collect();
|
||||
// The raster effects before a Transform effect follow it, as an object's do once its
|
||||
// geometry effects are applied ([`crate::raster::without_geometry`]); hidden records stay
|
||||
// as they are.
|
||||
one.appearance.effects.extend(crate::raster::followed(&look.effects).iter().filter(|e| !(e.visible && is_geometry(&e.id))).cloned());
|
||||
if !shape.is_empty() {
|
||||
let before = art_cost(one);
|
||||
let mut art = one_piece(one);
|
||||
let mut complete = true;
|
||||
reshape_leaves_checked(&mut art, &shape.iter().collect::<Vec<_>>(), &shape, room.plus(before), (false, false), doc, Some(&mut complete));
|
||||
#[cfg(test)]
|
||||
DRESSED.with(|d| d.set(d.get().plus(art_cost(&art))));
|
||||
extra = art_cost(&art).minus(before);
|
||||
if !complete || !room.fits(extra) {
|
||||
return None;
|
||||
}
|
||||
let mut art = dressed(art, one);
|
||||
art.appearance.effects = one.appearance.effects.clone();
|
||||
*one = art;
|
||||
}
|
||||
}
|
||||
if let Some(blend) = outer {
|
||||
let mut g = Node::group(one.id, vec![Arc::new(one.clone())]);
|
||||
g.blend = blend;
|
||||
*one = g;
|
||||
}
|
||||
Some(extra)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// What the art [`dress_piece`] has reshaped on this thread has cost, all together.
|
||||
pub(crate) static DRESSED: std::cell::Cell<Budget> = const { std::cell::Cell::new(Budget { anchors: 0, lines: 0 }) };
|
||||
}
|
||||
|
||||
/// What a painted piece with geometry `path` costs: its anchors and lines, plus a share of the
|
||||
/// effects' budget for the object it becomes, so that a budget of [`Budget::EFFECTS`] holds at most
|
||||
/// [`MAX_OBJECTS`](vectorcraft_plugins::objects::MAX_OBJECTS) pieces however small their paths.
|
||||
@@ -2572,7 +2706,8 @@ fn piece_share() -> Budget {
|
||||
/// order. The plug-in is given `appearance`'s fills and strokes and told that it is on item `index`
|
||||
/// of them. A piece that gives fills (on a fill) or strokes (on a stroke) is painted by copies of
|
||||
/// `item` with those paints ([`vectorcraft_plugins::painted::items`]), under the leaf's other fills
|
||||
/// and strokes; one that gives none keeps the leaf's. Returns
|
||||
/// and strokes; one that gives none keeps the leaf's. Each path takes its piece's opacity, blending
|
||||
/// mode and effects ([`dress_piece`]). Returns
|
||||
/// what the paths cost ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails,
|
||||
/// the pieces are refused (a swatch or pattern not in `doc`, or any without one), or they would pass
|
||||
/// `budget`. A deferred run is listed by `at`.
|
||||
@@ -2588,9 +2723,10 @@ fn paint_piece(
|
||||
at: Option<vectorcraft_plugins::deferred::Stage>,
|
||||
) -> Option<Budget> {
|
||||
let (path, rule) = leaf_geometry(leaf)?;
|
||||
crate::params::check_returned_effects();
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(appearance), item: Some(index), at };
|
||||
let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?;
|
||||
let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
|
||||
let mut made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
|
||||
if !budget.fits(made) {
|
||||
return None;
|
||||
}
|
||||
@@ -2613,6 +2749,7 @@ fn paint_piece(
|
||||
let mut one = leaf.clone();
|
||||
one.appearance.items = items;
|
||||
set_geometry(&mut one, p.path.clone(), p.rule);
|
||||
made = made.plus(dress_piece(&mut one, &p.look, budget.minus(made), doc)?);
|
||||
children.push(Arc::new(one));
|
||||
}
|
||||
*leaf = Node::group(leaf.id, children);
|
||||
@@ -2691,7 +2828,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
let Some((path, rule)) = leaf_geometry(leaf) else { return };
|
||||
let original = leaf.clone();
|
||||
let ctx = GeomContext::of(&original);
|
||||
let bounds = path.to_bezpath().bounding_box();
|
||||
let bounds = path.bounds().unwrap_or_default();
|
||||
// A path of the leaf's geometry painted by `items` alone, without the leaf's transparency and
|
||||
// object effects (the group keeps them).
|
||||
let piece = |items: Vec<AppearanceItem>| {
|
||||
@@ -2766,18 +2903,34 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
|
||||
let it = one.items.pop().unwrap_or(it);
|
||||
let stage = vectorcraft_plugins::deferred::Stage { object: ctx.seed, effect: at, item: Some(i) };
|
||||
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&original.appearance), item: Some(i), at: Some(stage) };
|
||||
crate::params::check_returned_effects();
|
||||
let painted = vectorcraft_plugins::effect::apply_painted(plugin, ¶ms, &g, tb, rule, paints, doc)
|
||||
.map(|pieces| pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p))).collect::<Vec<_>>())
|
||||
.map(|pieces| {
|
||||
pieces.iter().map(|p| (p.path.clone(), p.rule, vectorcraft_plugins::painted::items(&it, p), p.look.clone())).collect::<Vec<_>>()
|
||||
})
|
||||
.filter(|pieces| room.fits(pieces.iter().map(|(p, ..)| piece_cost(p)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus)));
|
||||
// A failed run draws the fill or stroke on the geometry it was given.
|
||||
let returned = painted.unwrap_or_else(|| vec![(g.clone(), rule, vec![it])]);
|
||||
let mut group: Vec<Arc<Node>> = vec![];
|
||||
for (path, rule, items) in returned.into_iter().filter(|(_, _, items)| !items.is_empty()) {
|
||||
*used = used.plus(piece_cost(&path));
|
||||
let mut p = piece(items);
|
||||
set_geometry(&mut p, path, rule);
|
||||
group.push(Arc::new(p));
|
||||
}
|
||||
// The paths the pieces become, with their own geometry effects applied, and what they
|
||||
// cost; `None` as soon as a piece's own geometry effects would pass `room`.
|
||||
let build = |returned: Vec<(PathData, FillRule, Vec<AppearanceItem>, vectorcraft_plugins::painted::Look)>| {
|
||||
let returned: Vec<_> = returned.into_iter().filter(|(_, _, items, _)| !items.is_empty()).collect();
|
||||
let mut made = returned.iter().map(|(path, ..)| piece_cost(path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
|
||||
let mut group: Vec<Arc<Node>> = vec![];
|
||||
for (path, rule, items, look) in returned {
|
||||
let mut p = piece(items);
|
||||
set_geometry(&mut p, path, rule);
|
||||
made = made.plus(dress_piece(&mut p, &look, room.minus(made), doc)?);
|
||||
group.push(Arc::new(p));
|
||||
}
|
||||
Some((group, made))
|
||||
};
|
||||
// A failed run, or pieces whose own geometry effects would pass the budget, draws the
|
||||
// fill or stroke on the geometry it was given, at that geometry's own cost.
|
||||
let (group, made) = painted.and_then(build).unwrap_or_else(|| {
|
||||
let mut p = piece(vec![it]);
|
||||
set_geometry(&mut p, g.clone(), rule);
|
||||
(vec![Arc::new(p)], piece_cost(&g))
|
||||
});
|
||||
*used = used.plus(made);
|
||||
let mut p = Node::group(leaf.id, group);
|
||||
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), true, limit, used, doc);
|
||||
pieces.push(Arc::new(p));
|
||||
|
||||
@@ -38,6 +38,12 @@ fn check(bp: &BezPath, st: &StrokeLayer, what: &str) {
|
||||
let painted = region.bounding_box();
|
||||
let bounds = st.bounds_on(bp, bp.bounding_box());
|
||||
assert!(bounds.inflate(0.05, 0.05).contains_rect(painted), "{what}: paints {painted:?} outside {bounds:?}");
|
||||
check_clicks(bp, st, ®ion, what);
|
||||
}
|
||||
|
||||
/// Check that points of `region`, what `st` paints along `bp`, hit as [`check`] says.
|
||||
fn check_clicks(bp: &BezPath, st: &StrokeLayer, region: &BezPath, what: &str) {
|
||||
let painted = region.bounding_box();
|
||||
let tol = if st.profile.is_some() { 1.0 } else { 0.25 };
|
||||
// Off the outline's own coordinates, so no sample sits level with a vertex.
|
||||
let (mut x, mut checked) = (painted.x0 + 0.371, 0);
|
||||
@@ -45,7 +51,7 @@ fn check(bp: &BezPath, st: &StrokeLayer, what: &str) {
|
||||
let mut y = painted.y0 + 0.293;
|
||||
while y <= painted.y1 {
|
||||
let p = Point::new(x, y);
|
||||
if fill_contains(®ion, FillRule::EvenOdd, p) {
|
||||
if fill_contains(region, FillRule::EvenOdd, p) {
|
||||
assert!(st.hits(bp, FillRule::NonZero, p, tol), "{what}: painted {p:?} doesn't hit");
|
||||
checked += 1;
|
||||
}
|
||||
@@ -140,6 +146,58 @@ fn custom_heads() -> Vec<Arrowhead> {
|
||||
vec![head("Wedge", &[(0.0, 0.0), (3.0, 2.0), (3.0, -1.0)]), head("Spindle", &[(-10.0, 0.0), (0.0, 2.0), (10.0, 0.0), (0.0, -2.0)])]
|
||||
}
|
||||
|
||||
/// Paths with a subpath that never leaves its first point, which a round or projecting cap draws
|
||||
/// as a dot at (140, 130): a closed lone anchor, a line to the same point, open and closed, and a
|
||||
/// curve with every handle on the point, alone and after a closed triangle.
|
||||
fn dot_paths() -> Vec<BezPath> {
|
||||
let at = Point::new(140.0, 130.0);
|
||||
let mut lone = BezPath::new();
|
||||
lone.move_to(at);
|
||||
lone.close_path();
|
||||
let mut line = BezPath::new();
|
||||
line.move_to(at);
|
||||
line.line_to(at);
|
||||
let mut closed_line = line.clone();
|
||||
closed_line.close_path();
|
||||
let mut curve = BezPath::new();
|
||||
curve.move_to(at);
|
||||
curve.curve_to(at, at, at);
|
||||
curve.close_path();
|
||||
let mut beside = paths()[2].clone();
|
||||
beside.extend(lone.iter());
|
||||
vec![lone, line, closed_line, curve, beside]
|
||||
}
|
||||
|
||||
/// A click on the dot a round or projecting cap draws for a subpath that never leaves its first
|
||||
/// point hits the path, and where no dot is drawn (butt caps, dashes, width profiles, an inside
|
||||
/// stroke of a closed subpath) a click beside the point misses.
|
||||
#[test]
|
||||
fn clicks_hit_the_dot_a_cap_draws_for_a_subpath_with_no_length() {
|
||||
let beside = Point::new(142.0, 130.0);
|
||||
let mut painted = 0;
|
||||
for (pi, bp) in dot_paths().iter().enumerate() {
|
||||
for align in [StrokeAlign::Center, StrokeAlign::Inside, StrokeAlign::Outside] {
|
||||
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
|
||||
for profile in [None, Some(WidthProfile::lens())] {
|
||||
for dash in [None, Some(Dash { pattern: vec![7.0, 4.0], offset: 0.0, align_corners: false })] {
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 6.0);
|
||||
(st.align, st.cap, st.profile, st.dash) = (align, cap, profile.clone(), dash.clone());
|
||||
let what = format!("path {pi} {align:?} {cap:?} profile {} dashed {}", profile.is_some(), dash.is_some());
|
||||
let region = outline_region(&PathData::from_bezpath(bp), FillRule::NonZero, &st).to_bezpath();
|
||||
if !fill_contains(®ion, FillRule::EvenOdd, beside) {
|
||||
assert!(!st.hits(bp, FillRule::NonZero, beside, 0.25), "{what}: a click beside the point hits, where no dot is drawn");
|
||||
continue;
|
||||
}
|
||||
painted += 1;
|
||||
check_clicks(bp, &st, ®ion, &what);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(painted, 22, "dots drawn");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_and_clicks_cover_every_arrowhead() {
|
||||
let bp = &paths()[0];
|
||||
|
||||
@@ -6,6 +6,7 @@ use super::*;
|
||||
|
||||
mod clipfx;
|
||||
mod imageoutline;
|
||||
mod loneanchor;
|
||||
mod painted;
|
||||
mod rasterfollow;
|
||||
mod scale;
|
||||
@@ -1117,10 +1118,10 @@ fn transform_copies_before_offset_path_evaluates_without_ram_spike() {
|
||||
fx("path.offsetPath", json!({"offset": 10.0, "joins": "round"})),
|
||||
];
|
||||
let path = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
|
||||
let start = std::time::Instant::now();
|
||||
crate::geometry::OFFSET_SUBPATHS.with(|n| n.set(0));
|
||||
let out = apply_geometry(&effects, &path, path.bounds().unwrap());
|
||||
let elapsed = start.elapsed();
|
||||
assert!(elapsed < std::time::Duration::from_secs(2), "elapsed: {:?}", elapsed);
|
||||
// Offset Path offsets the one rectangle, not the 31 overlapping copies.
|
||||
assert_eq!(crate::geometry::OFFSET_SUBPATHS.with(|n| n.get()), path.subpaths.len());
|
||||
assert_eq!(out.subpaths.len(), 31);
|
||||
}
|
||||
|
||||
@@ -1135,10 +1136,10 @@ fn reshape_leaves_within_optimizes_transform_before_terminal_offset_path() {
|
||||
let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 10}));
|
||||
let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"}));
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
crate::geometry::OFFSET_SUBPATHS.with(|n| n.set(0));
|
||||
crate::reshape::reshape_leaves_within(&mut art, &[&transform, &offset], Budget::EFFECTS, None);
|
||||
let elapsed = start.elapsed();
|
||||
assert!(elapsed < std::time::Duration::from_secs(2));
|
||||
// Offset Path offsets each leaf's one rectangle, not its 11 copies.
|
||||
assert_eq!(crate::geometry::OFFSET_SUBPATHS.with(|n| n.get()), 5);
|
||||
|
||||
let children = art.children().unwrap();
|
||||
assert_eq!(children.len(), 5);
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Geometry effects on a path with a lone anchor work from the path's bounds with that anchor
|
||||
//! included ([`PathData::bounds`]), as the selection's box, Align and Transform Each measure the
|
||||
//! path, wherever the effects are applied.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A 10 pt line from the origin and a lone anchor at (100, 50): its bounds are (0, 0) to
|
||||
/// (100, 50), and the line alone measures (0, 0) to (10, 0).
|
||||
fn marked() -> PathData {
|
||||
PathData::new(vec![
|
||||
SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0)], false),
|
||||
SubPath::polyline(&[Point::new(100.0, 50.0)], false),
|
||||
])
|
||||
}
|
||||
|
||||
/// The Transform effect at 200%, about the center of the box it is given.
|
||||
fn scale() -> Effect {
|
||||
fx("distort.transform", json!({"scaleH": 200, "scaleV": 200}))
|
||||
}
|
||||
|
||||
/// `marked` with a 1 pt black stroke, and `scale` on the object (`on_stroke` false) or on its
|
||||
/// stroke.
|
||||
fn node(on_stroke: bool) -> Node {
|
||||
let mut n = Node::path(NodeId(5), marked(), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0));
|
||||
if on_stroke {
|
||||
if let Some(s) = n.appearance.stroke_mut() {
|
||||
s.effects.push(scale());
|
||||
}
|
||||
} else {
|
||||
n.appearance.effects.push(scale());
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// The first point of each subpath of each path under `n`.
|
||||
fn starts(n: &Node, out: &mut Vec<Point>) {
|
||||
if let NodeKind::Path { path, .. } = &n.kind {
|
||||
out.extend(path.subpaths.iter().filter_map(|s| s.anchors.first()).map(|a| a.p));
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
starts(c, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// Does a path under `n` start where the line scaled about (50, 25) starts, (-50, -25), and
|
||||
/// none where the line scaled about its own center (5, 0) starts, (-5, 0)?
|
||||
fn scaled_about_the_bounds(n: &Node) -> bool {
|
||||
let mut pts = vec![];
|
||||
starts(n, &mut pts);
|
||||
let at = |x: f64, y: f64| pts.iter().any(|p| close(p.x, x, 1e-6) && close(p.y, y, 1e-6));
|
||||
assert_eq!(apply_geometry(&[scale()], &marked(), marked().bounds().unwrap()).subpaths[0].anchors[0].p, Point::new(-50.0, -25.0));
|
||||
at(-50.0, -25.0) && !at(-5.0, 0.0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_appearance_scales_about_bounds_with_the_lone_anchor() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, node(false)).unwrap();
|
||||
let baked = bake_document(&d).expect("the effect bakes");
|
||||
let layer = &baked.layers[0];
|
||||
assert!(scaled_about_the_bounds(layer), "{layer:?}");
|
||||
}
|
||||
|
||||
/// A stroke's Transform effect with Scale Strokes & Effects on makes the stroke a path of its own
|
||||
/// when the object's own effects are reshaped, its geometry after the stroke's effects before it.
|
||||
#[test]
|
||||
fn a_stroke_effect_scales_about_bounds_with_the_lone_anchor() {
|
||||
let mut n = node(true);
|
||||
n.appearance.effects = vec![fx("distort.transform", json!({}))];
|
||||
if let Some(s) = n.appearance.stroke_mut() {
|
||||
s.effects.push(fx("distort.transform", json!({"strokes": true})));
|
||||
}
|
||||
let art = reshape(None, &n, None).expect("the effects make art");
|
||||
assert!(scaled_about_the_bounds(&art), "{art:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_art_scales_about_bounds_with_the_lone_anchor() {
|
||||
let art = shape_art(None, &node(false), None).expect("the effect makes art");
|
||||
assert!(scaled_about_the_bounds(&art), "{art:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_art_scales_about_bounds_with_the_lone_anchor() {
|
||||
let d = Document::new(200.0, 200.0);
|
||||
let symbols = d.symbol_boxes();
|
||||
for on_stroke in [false, true] {
|
||||
let art = crate::preview::drawn_art(&symbols, &node(on_stroke)).expect("the effect makes art");
|
||||
assert!(scaled_about_the_bounds(&art), "on the stroke {on_stroke}: {art:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_paints_its_art_scaled_about_bounds_with_the_lone_anchor() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
d.symbols.push(Symbol { dynamic: false, name: "s".into(), art: Arc::new(node(true)) });
|
||||
let mut inst = Node::new(NodeId(9), NodeKind::SymbolInstance { symbol: "s".into(), xf: Affine::IDENTITY });
|
||||
inst.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into();
|
||||
if let Some(s) = inst.appearance.stroke_mut() {
|
||||
s.effects.push(fx("distort.transform", json!({})));
|
||||
}
|
||||
let painted = image_paint(Some(&d), &inst);
|
||||
let pts: Vec<Point> = painted
|
||||
.iter()
|
||||
.filter_map(|(bp, _, _)| match bp.elements().first() {
|
||||
Some(vectorcraft_geom::PathEl::MoveTo(p)) => Some(*p),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(pts.iter().any(|p| close(p.x, -50.0, 1e-6) && close(p.y, -25.0, 1e-6)), "{pts:?}");
|
||||
assert!(!pts.iter().any(|p| close(p.x, -5.0, 1e-6) && close(p.y, 0.0, 1e-6)), "{pts:?}");
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use vectorcraft_plugins::wat as tpl;
|
||||
|
||||
use crate::geometry::Budget;
|
||||
use crate::reshape;
|
||||
use crate::reshape::{HELD_PEAK, PLUGIN_RUNS};
|
||||
use crate::reshape::{DRESSED, HELD_PEAK, PLUGIN_RUNS};
|
||||
|
||||
/// Installs live-effect plug-in `id`, which paints what it returns, replacing one with the same id:
|
||||
/// its effect returns `output` whatever it is given.
|
||||
@@ -268,3 +268,449 @@ fn a_built_in_result_on_the_path_before_it_is_taken_near_the_budget() {
|
||||
let height = |b: Option<Rect>| b.map_or(0.0, |b| b.height());
|
||||
assert!((height(*bounds) - height(tall.bounds())).abs() < 1.0, "{bounds:?} is not {:?} tall", tall.bounds());
|
||||
}
|
||||
|
||||
/// The host takes a built-in effect with parameters it has, of their type and in range, on a piece,
|
||||
/// and a raster effect on a fill or stroke; it refuses a plug-in effect, a 3D effect, a Pathfinder
|
||||
/// effect (a piece is one path, with nothing to combine), an unknown effect or parameter, a value
|
||||
/// of another type or out of range, and a geometry effect on a fill or stroke.
|
||||
#[test]
|
||||
fn returned_effects_are_built_in_effects_with_their_own_parameters() {
|
||||
let e = |id: &str, params: serde_json::Value| Effect { id: id.into(), params, visible: true };
|
||||
let check = crate::check_returned_effect;
|
||||
assert_eq!(check(&e("path.offsetPath", json!({"offset": 4.0})), false), Ok(()));
|
||||
assert_eq!(check(&e("path.offsetPath", serde_json::Value::Null), false), Ok(()));
|
||||
assert_eq!(check(&e("stylize.dropShadow", json!({"x": 2.0})), true), Ok(()));
|
||||
assert_eq!(check(&e("brushStrokes.accentedEdges", json!({"edgeWidth": 14.0})), false), Ok(()));
|
||||
assert_eq!(check(&e("distort.transform", json!({"copies": 1000})), false), Ok(()));
|
||||
// A parameter documented right after a comma has its range checked too.
|
||||
assert_eq!(check(&e("artistic.paintDaubs", json!({"sharpness": 25})), false), Ok(()));
|
||||
// Each documented choice and each end of a documented range passes.
|
||||
for (id, params) in [
|
||||
("distort.roughen", json!({"points": "smooth"})),
|
||||
("distort.roughen", json!({"points": "corner"})),
|
||||
("distort.zigZag", json!({"points": "corner"})),
|
||||
("distort.puckerBloat", json!({"amount": -200})),
|
||||
("distort.puckerBloat", json!({"amount": 200})),
|
||||
("adjust.temperatureTint", json!({"temperature": -100, "tint": 100})),
|
||||
("stylize.dropShadow", json!({"mode": "color-burn"})),
|
||||
("stylize.outerGlow", json!({"mode": "Normal"})),
|
||||
// A `color` is also taken as [r, g, b] 0..1 or a color object, as the effects draw it.
|
||||
("stylize.dropShadow", json!({"color": [1.0, 0.0, 0.0]})),
|
||||
("stylize.dropShadow", json!({"color": [1, 0, 0]})),
|
||||
("stylize.outerGlow", json!({"color": {"model": "gray", "k": 0.5}})),
|
||||
("stylize.innerGlow", json!({"color": {"model": "cmyk", "c": 0, "m": 1, "y": 0, "k": 0}})),
|
||||
("stylize.innerGlow", json!({"color": {"model": "lab", "l": 100, "a": -128, "b": 127}})),
|
||||
// Curves' `points` is also taken as [[x, y], …], and a Transform's whole numbers as such.
|
||||
("adjust.curves", json!({"points": [[0, 255], [255, 0]]})),
|
||||
("adjust.curves", json!({"points": "0,0; 64,32 255,255"})),
|
||||
("distort.transform", json!({"copies": 2, "reference": 0.0})),
|
||||
] {
|
||||
assert_eq!(check(&e(id, params.clone()), false), Ok(()), "{id} {params}");
|
||||
}
|
||||
// Every effect's own defaults pass the check, so each documented range holds its default.
|
||||
for info in crate::effect_catalog().into_iter().filter(|i| !crate::is_three_d(i.id) && !crate::is_pathfinder(i.id)) {
|
||||
assert_eq!(check(&e(info.id, info.defaults.clone()), false), Ok(()), "{}", info.id);
|
||||
}
|
||||
for (effect, row) in [
|
||||
(e("distort.transform", json!({"copies": 1001})), false),
|
||||
(e("path.offsetPath", json!({"offset": null})), false),
|
||||
(e("plugin.test.effects.self", json!({})), false),
|
||||
(e("threeD.extrude", json!({})), false),
|
||||
(e("pathfinder.add", serde_json::Value::Null), false),
|
||||
(e("pathfinder.divide", json!({"precision": 1.0})), false),
|
||||
(e("stylize.nope", json!({})), false),
|
||||
(e("path.offsetPath", json!({"inset": 4.0})), false),
|
||||
(e("path.offsetPath", json!({"offset": "4"})), false),
|
||||
(e("brushStrokes.accentedEdges", json!({"edgeWidth": 15.0})), false),
|
||||
(e("artistic.paintDaubs", json!({"sharpness": 41})), false),
|
||||
(e("path.offsetPath", json!([4.0])), false),
|
||||
(e("path.offsetPath", json!({"offset": 4.0})), true),
|
||||
] {
|
||||
assert!(check(&effect, row).is_err(), "{effect:?} on a fill or stroke: {row}");
|
||||
}
|
||||
let why = check(&e("pathfinder.add", serde_json::Value::Null), false).unwrap_err();
|
||||
assert!(why.contains("Pathfinder effects are not allowed"), "{why}");
|
||||
// The values checked for one effect are refused with the parameter named.
|
||||
for (id, params, key) in [
|
||||
(crate::SVG_FILTER, json!({"axes": [1, 0, 0, 0]}), "axes"),
|
||||
(crate::SVG_FILTER, json!({"scale": 0.0}), "scale"),
|
||||
(crate::SVG_FILTER, json!({"origin": [1.0]}), "origin"),
|
||||
(crate::SVG_FILTER, json!({"name": "f"}), "name"),
|
||||
("warp.arc", json!({"version": 99}), "version"),
|
||||
("stylize.dropShadow", json!({"color": "#zz0000"}), "color"),
|
||||
("stylize.dropShadow", json!({"color": [1.0, "0", 0.0]}), "color"),
|
||||
("stylize.innerGlow", json!({"color": {"model": "rgb"}}), "color"),
|
||||
("stylize.outerGlow", json!({"color": true}), "color"),
|
||||
// Color components are from 0 to 1, Lab's lightness from 0 to 100.
|
||||
("stylize.dropShadow", json!({"color": [2, -1, 0]}), "color"),
|
||||
("stylize.dropShadow", json!({"color": [0.5, 0.5, 1.01]}), "color"),
|
||||
("stylize.outerGlow", json!({"color": {"model": "rgb", "r": 2.0, "g": 0.0, "b": 0.0}}), "color"),
|
||||
("stylize.innerGlow", json!({"color": {"model": "gray", "k": -0.5}}), "color"),
|
||||
("stylize.innerGlow", json!({"color": {"model": "lab", "l": 101, "a": 0, "b": 0}}), "color"),
|
||||
("adjust.curves", json!({"points": [[0, 255], [255]]}), "points"),
|
||||
("adjust.curves", json!({"points": ["0,0", "255,255"]}), "points"),
|
||||
// Curves' points are read as "x,y" or [x, y] pairs, each number from 0 to 255.
|
||||
("adjust.curves", json!({"points": "not-points"}), "points"),
|
||||
("adjust.curves", json!({"points": "0,0 255,-1"}), "points"),
|
||||
("adjust.curves", json!({"points": [[0, 300], [255, 0]]}), "points"),
|
||||
("distort.transform", json!({"copies": 1.5}), "copies"),
|
||||
("distort.transform", json!({"reference": 4.5}), "reference"),
|
||||
("adjust.levels", json!({"channel": "cyan"}), "channel"),
|
||||
("blur.radial", json!({"centerX": 1.5}), "centerX"),
|
||||
("blur.gaussian", json!({"linear": 1}), "linear"),
|
||||
("pixelate.colorHalftone", json!({"channel1": 400.0}), "channel1"),
|
||||
("distort.twist", json!({"angle": 4000.0}), "angle"),
|
||||
("distort.freeDistort", json!({"corners": []}), "corners"),
|
||||
("distort.freeDistort", json!({"corners": [[0, 0], [1, 0], [1, 1], [0]]}), "corners"),
|
||||
("distort.roughen", json!({"points": "invalid"}), "points"),
|
||||
("distort.zigZag", json!({"points": "Corner"}), "points"),
|
||||
("path.offsetPath", json!({"joins": "square"}), "joins"),
|
||||
(crate::RASTERIZE, json!({"colorModel": "cmyk"}), "colorModel"),
|
||||
(crate::CROP_MARKS, json!({"style": 1}), "style"),
|
||||
("distort.puckerBloat", json!({"amount": -201}), "amount"),
|
||||
("distort.puckerBloat", json!({"amount": 201}), "amount"),
|
||||
("adjust.temperatureTint", json!({"temperature": 101}), "temperature"),
|
||||
("adjust.temperatureTint", json!({"tint": -101}), "tint"),
|
||||
("stylize.dropShadow", json!({"mode": "not-a-mode"}), "mode"),
|
||||
("stylize.innerGlow", json!({"mode": "???"}), "mode"),
|
||||
] {
|
||||
let why = check(&e(id, params.clone()), false).expect_err(&format!("{id} {params}"));
|
||||
assert!(why.contains(key), "{id} {params}: {why}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A painted effect on a fill whose piece fits the budget, but whose piece's own Transform copy
|
||||
/// would not fit beside the source: the fill is drawn on the source's path, and nothing is drawn
|
||||
/// where the piece would be.
|
||||
#[test]
|
||||
fn a_piece_s_own_geometry_effects_keep_to_the_budget() {
|
||||
let id = "test.effects.look.budget";
|
||||
let source = drawn_share(0.45, 0.0);
|
||||
let piece = json!({"path": drawn_share(0.3, 2_000.0), "effects": [{"id": "distort.transform", "params": {"copies": 1, "moveH": 10.0}}]});
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"#
|
||||
);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": [piece] }).to_string())).unwrap();
|
||||
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
|
||||
let mut n = Node::path(NodeId(9), source.clone(), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap();
|
||||
n.appearance.items[fill].effects_mut().push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true });
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let mut bounds = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if let Some(b) = c.path_data().and_then(PathData::bounds) {
|
||||
bounds.push(b);
|
||||
}
|
||||
});
|
||||
assert!(!bounds.is_empty() && bounds.iter().all(|b| b.x1 < 2_000.0), "{bounds:?}");
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
}
|
||||
|
||||
/// Where [`many_heavy_pieces`] puts its effect.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum HeavyOn {
|
||||
/// The object's own effects.
|
||||
Object,
|
||||
/// The square's fill, as its only effect.
|
||||
Fill,
|
||||
/// The square's fill, after a painted effect that returns the square.
|
||||
LaterOnFill,
|
||||
}
|
||||
|
||||
/// Ten painted pieces, each drawn with 4% of the effects' budget, each with a Transform effect that
|
||||
/// makes 14 copies of it (60% of the budget per piece), from an effect on a square `on`: they would
|
||||
/// pass the budget together, so the square is drawn as it was. The pieces' own geometry effects keep
|
||||
/// to what the pieces before them left: the art reshaped for them costs less than the budget
|
||||
/// together, and so does the art drawn.
|
||||
fn many_heavy_pieces(on: HeavyOn) {
|
||||
let id = format!("test.effects.look.heavy{on:?}").to_lowercase();
|
||||
let pieces: Vec<_> = (0..10)
|
||||
.map(|k| json!({"path": drawn_share(0.04, 1_000.0 * f64::from(k)), "effects": [{"id": "distort.transform", "params": {"copies": 14, "moveH": 10.0}}]}))
|
||||
.collect();
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"#
|
||||
);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": pieces }).to_string())).unwrap();
|
||||
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
|
||||
let square = shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0));
|
||||
let first = format!("{id}.first");
|
||||
install_painting(&first, &json!({"objects": [{"path": square}]}));
|
||||
let mut n = Node::path(NodeId(9), square.clone(), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let heavy = Effect { id: format!("plugin.{id}"), params: json!({}), visible: true };
|
||||
let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap();
|
||||
match on {
|
||||
HeavyOn::Object => n.appearance.effects.push(heavy),
|
||||
HeavyOn::Fill => n.appearance.items[fill].effects_mut().push(heavy),
|
||||
HeavyOn::LaterOnFill => {
|
||||
n.appearance.items[fill].effects_mut().push(Effect { id: format!("plugin.{first}"), params: json!({}), visible: true });
|
||||
n.appearance.items[fill].effects_mut().push(heavy);
|
||||
}
|
||||
}
|
||||
DRESSED.with(|d| d.set(Budget { anchors: 0, lines: 0 }));
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let dressed = DRESSED.with(std::cell::Cell::get);
|
||||
assert!(Budget::EFFECTS.fits(dressed), "{on:?}: the pieces' own effects made {dressed:?}");
|
||||
let (mut bounds, mut drawn) = (vec![], Budget { anchors: 0, lines: 0 });
|
||||
art.walk(&mut |c| {
|
||||
if let Some(p) = c.path_data() {
|
||||
bounds.push(p.bounds());
|
||||
drawn = drawn.plus(Budget::of(p));
|
||||
}
|
||||
});
|
||||
// On a fill, the fill and the stroke are paths of their own.
|
||||
assert!(!bounds.is_empty() && bounds.iter().all(|b| *b == square.bounds()), "{on:?}: {bounds:?}");
|
||||
assert!(Budget::EFFECTS.fits(drawn), "{on:?}: the art costs {drawn:?}");
|
||||
vectorcraft_plugins::registry::remove(&id);
|
||||
vectorcraft_plugins::registry::remove(&first);
|
||||
}
|
||||
|
||||
/// [`many_heavy_pieces`] from the object's own effect.
|
||||
#[test]
|
||||
fn heavy_pieces_of_an_object_s_effect_stop_within_the_budget() {
|
||||
many_heavy_pieces(HeavyOn::Object);
|
||||
}
|
||||
|
||||
/// [`many_heavy_pieces`] from an effect on a fill.
|
||||
#[test]
|
||||
fn heavy_pieces_of_a_fill_s_effect_stop_within_the_budget() {
|
||||
many_heavy_pieces(HeavyOn::Fill);
|
||||
}
|
||||
|
||||
/// [`many_heavy_pieces`] from a later effect on a fill.
|
||||
#[test]
|
||||
fn heavy_pieces_of_a_later_effect_on_a_fill_stop_within_the_budget() {
|
||||
many_heavy_pieces(HeavyOn::LaterOnFill);
|
||||
}
|
||||
|
||||
/// A piece's own geometry effect reshapes it before the source's later effects run, and those run
|
||||
/// on it once: the square at 120, 40 grown by a 10 pt Offset Path, then moved 100 pt right by the
|
||||
/// source's Transform effect. The piece's opacity and blending mode stay on the path it becomes.
|
||||
#[test]
|
||||
fn later_source_effects_run_after_generated_effects_once() {
|
||||
let id = "test.effects.look.offset";
|
||||
let piece = json!({"path": shapes::rectangle(Rect::new(120.0, 40.0, 140.0, 60.0)), "opacity": 0.5, "blend": "Multiply",
|
||||
"effects": [{"id": "path.offsetPath", "params": {"offset": 10.0}}]});
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"#
|
||||
);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": [piece] }).to_string())).unwrap();
|
||||
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
n.appearance.effects.push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true });
|
||||
n.appearance.effects.push(Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true });
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let (mut paths, mut looks) = (vec![], vec![]);
|
||||
art.walk(&mut |c| {
|
||||
if let Some(p) = c.path_data() {
|
||||
paths.push(p.bounds());
|
||||
}
|
||||
if c.opacity != 1.0 || c.blend != vectorcraft_doc::color::BlendMode::Normal {
|
||||
looks.push((c.opacity, c.blend));
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 1, "{paths:?}");
|
||||
// Once, on the piece and what holds it.
|
||||
assert_eq!(looks, [(0.5, vectorcraft_doc::color::BlendMode::Multiply)]);
|
||||
let b = paths[0].unwrap();
|
||||
assert!((b.x0 - 210.0).abs() < 0.5 && (b.x1 - 250.0).abs() < 0.5 && (b.y0 - 30.0).abs() < 0.5, "{b:?}");
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
}
|
||||
|
||||
/// A piece's look reshapes it by its own geometry effects alone: the Transform effect of the fill
|
||||
/// it carries stays on the fill for its own stage and does not move the piece now.
|
||||
#[test]
|
||||
fn a_piece_s_look_runs_only_its_own_geometry_effects() {
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap();
|
||||
n.appearance.items[fill].effects_mut().push(Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true });
|
||||
let look = vectorcraft_plugins::painted::Look {
|
||||
effects: vec![Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: true }],
|
||||
..Default::default()
|
||||
};
|
||||
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap();
|
||||
let mut paths = vec![];
|
||||
n.walk(&mut |c| {
|
||||
if let Some(b) = c.path_data().and_then(PathData::bounds) {
|
||||
paths.push((b, c.appearance.items.iter().map(|i| i.effects().len()).sum::<usize>()));
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 1, "{paths:?}");
|
||||
let (b, kept) = paths[0];
|
||||
assert!((b.x0 + 10.0).abs() < 0.5 && (b.x1 - 30.0).abs() < 0.5, "{b:?}");
|
||||
assert_eq!(kept, 1, "the fill keeps its Transform effect");
|
||||
}
|
||||
|
||||
/// A piece's blending mode on an object that blends in the same mode keeps both: the object
|
||||
/// becomes a group in its mode around the piece in the piece's.
|
||||
#[test]
|
||||
fn a_piece_s_blending_mode_nests_in_the_object_s_same_mode() {
|
||||
use vectorcraft_doc::color::BlendMode;
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
n.blend = BlendMode::Multiply;
|
||||
let look = vectorcraft_plugins::painted::Look { blend: Some(BlendMode::Multiply), ..Default::default() };
|
||||
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap();
|
||||
let mut blends = vec![];
|
||||
n.walk(&mut |c| blends.push(c.blend));
|
||||
assert_eq!(blends, [BlendMode::Multiply, BlendMode::Multiply]);
|
||||
}
|
||||
|
||||
/// A piece with an opacity, a blending mode and a geometry effect draws them once: the group the
|
||||
/// reshaped piece becomes carries them, and the path inside it draws at full opacity in Normal.
|
||||
#[test]
|
||||
fn a_reshaped_piece_s_opacity_and_blending_mode_apply_once() {
|
||||
use vectorcraft_doc::color::BlendMode;
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let look = vectorcraft_plugins::painted::Look {
|
||||
opacity: Some(0.5),
|
||||
blend: Some(BlendMode::Screen),
|
||||
effects: vec![Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: true }],
|
||||
};
|
||||
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap();
|
||||
let (mut opacity, mut blends) = (1.0f32, vec![]);
|
||||
n.walk(&mut |c| {
|
||||
opacity *= c.opacity;
|
||||
if c.blend != BlendMode::Normal {
|
||||
blends.push(c.blend);
|
||||
}
|
||||
});
|
||||
assert!((opacity - 0.5).abs() < 1e-6, "{opacity}");
|
||||
assert_eq!(blends, [BlendMode::Screen]);
|
||||
}
|
||||
|
||||
/// A piece's raster effect listed before its Transform effect follows the Transform, as an
|
||||
/// object's does: a Drop Shadow before a scale of 200% keeps twice its offset. A hidden record
|
||||
/// stays as it is.
|
||||
#[test]
|
||||
fn a_piece_s_raster_effects_follow_its_transform_effect() {
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let hidden = Effect { id: "path.offsetPath".into(), params: json!({"offset": 10.0}), visible: false };
|
||||
let look = vectorcraft_plugins::painted::Look {
|
||||
effects: vec![
|
||||
Effect { id: "stylize.dropShadow".into(), params: json!({"x": 3.0, "y": 4.0}), visible: true },
|
||||
hidden.clone(),
|
||||
Effect { id: "distort.transform".into(), params: json!({"scaleH": 200, "scaleV": 200}), visible: true },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).unwrap();
|
||||
let mut kept = vec![];
|
||||
n.walk(&mut |c| kept.extend(c.appearance.effects.iter().cloned()));
|
||||
let shadow = kept.iter().find(|e| e.id == "stylize.dropShadow").expect("the piece keeps its Drop Shadow");
|
||||
let at = |k: &str| shadow.params.get(k).and_then(serde_json::Value::as_f64).unwrap_or(f64::NAN);
|
||||
assert!((at("x") - 6.0).abs() < 1e-9 && (at("y") - 8.0).abs() < 1e-9, "{shadow:?}");
|
||||
assert_eq!(kept.iter().filter(|e| **e == hidden).count(), 1, "{kept:?}");
|
||||
assert!(kept.iter().all(|e| e.id != "distort.transform"), "{kept:?}");
|
||||
}
|
||||
|
||||
/// A piece's raster effect listed before a Transform effect that makes copies goes on each copy,
|
||||
/// as an object's does: every copy carries its own Drop Shadow, scaled with it, and the art around
|
||||
/// the copies carries none.
|
||||
#[test]
|
||||
fn each_copy_of_a_piece_carries_its_own_raster_effects() {
|
||||
let shadow = Effect { id: "stylize.dropShadow".into(), params: json!({"x": 3.0, "y": 4.0}), visible: true };
|
||||
let copying = Effect { id: "distort.transform".into(), params: json!({"scaleH": 200, "scaleV": 200, "copies": 1}), visible: true };
|
||||
let square =
|
||||
|| Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
// The offsets of the Drop Shadows the nodes under `art` carry, and how many `art` itself
|
||||
// carries.
|
||||
let shadows = |art: &Node| {
|
||||
let offsets = |c: &Node| {
|
||||
c.appearance
|
||||
.effects
|
||||
.iter()
|
||||
.filter(|e| e.id == "stylize.dropShadow")
|
||||
.map(|e| {
|
||||
let at = |k: &str| e.params.get(k).and_then(serde_json::Value::as_f64).unwrap_or(f64::NAN);
|
||||
((at("x") * 1000.0).round() as i64, (at("y") * 1000.0).round() as i64)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let mut inside = vec![];
|
||||
for c in art.children().into_iter().flatten() {
|
||||
c.walk(&mut |d| inside.extend(offsets(d)));
|
||||
}
|
||||
inside.sort_unstable();
|
||||
(inside, offsets(art).len())
|
||||
};
|
||||
let mut object = square();
|
||||
object.appearance.effects = vec![shadow.clone(), copying.clone()];
|
||||
let expected = shadows(&crate::reshape::own_effects_art(None, &object).expect("the object's copies are drawn"));
|
||||
assert_eq!(expected.0.len(), 2, "{expected:?}");
|
||||
assert_eq!(expected.1, 0, "{expected:?}");
|
||||
let mut n = square();
|
||||
let look = vectorcraft_plugins::painted::Look { effects: vec![shadow, copying], ..Default::default() };
|
||||
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).expect("the piece is dressed");
|
||||
assert_eq!(shadows(&n), expected);
|
||||
}
|
||||
|
||||
/// A piece whose copies, each with its own raster effects, would pass the room left to it is
|
||||
/// refused rather than drawn with fewer copies than its Transform effect asks for.
|
||||
#[test]
|
||||
fn a_piece_s_copies_with_raster_effects_keep_to_its_room() {
|
||||
let square = shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0));
|
||||
let mut n = Node::path(NodeId(9), square.clone(), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let look = vectorcraft_plugins::painted::Look {
|
||||
effects: vec![
|
||||
Effect { id: "stylize.dropShadow".into(), params: json!({"x": 3.0, "y": 4.0}), visible: true },
|
||||
Effect { id: "distort.transform".into(), params: json!({"moveH": 30.0, "copies": 5}), visible: true },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
// Room for one more square: not for five.
|
||||
assert!(crate::reshape::dress_piece(&mut n, &look, Budget::of(&square), None).is_none());
|
||||
}
|
||||
|
||||
/// A piece's Transform effect with no copies and Scale Strokes & Effects on moves the piece: no
|
||||
/// copies were asked for, so none are missing.
|
||||
#[test]
|
||||
fn a_piece_s_transform_without_copies_scaling_strokes_moves_it() {
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let look = vectorcraft_plugins::painted::Look {
|
||||
effects: vec![Effect { id: "distort.transform".into(), params: json!({"moveH": 30.0, "copies": 0, "strokes": true}), visible: true }],
|
||||
..Default::default()
|
||||
};
|
||||
crate::reshape::dress_piece(&mut n, &look, Budget::EFFECTS, None).expect("the piece is dressed");
|
||||
let mut paths = vec![];
|
||||
n.walk(&mut |c| paths.extend(c.path_data().and_then(PathData::bounds)));
|
||||
assert_eq!(paths.len(), 1, "{paths:?}");
|
||||
assert!((paths[0].x0 - 30.0).abs() < 0.5 && (paths[0].x1 - 50.0).abs() < 0.5, "{paths:?}");
|
||||
}
|
||||
|
||||
/// The same on a fill: the plug-in and the Transform effect after it are the fill's. The piece's
|
||||
/// Offset Path runs on it alone, so the plug-in runs once and the square moves once.
|
||||
#[test]
|
||||
fn a_fill_s_later_effects_run_after_its_piece_s_effects_once() {
|
||||
let id = "test.effects.look.rowoffset";
|
||||
let piece = json!({"path": shapes::rectangle(Rect::new(120.0, 40.0, 140.0, 60.0)), "opacity": 0.5,
|
||||
"effects": [{"id": "path.offsetPath", "params": {"offset": 10.0}}]});
|
||||
let manifest = format!(
|
||||
r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":3,"paintOutput":true,"appearanceOutput":true,"params":{{}}}}"#
|
||||
);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, &json!({ "objects": [piece] }).to_string())).unwrap();
|
||||
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
|
||||
let mut n =
|
||||
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap();
|
||||
let fx = n.appearance.items[fill].effects_mut();
|
||||
fx.push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true });
|
||||
fx.push(Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true });
|
||||
let art = reshape(None, &n, None).unwrap();
|
||||
let mut paths = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if let Some(b) = c.path_data().and_then(PathData::bounds)
|
||||
&& c.appearance.items.iter().any(|i| i.is_fill() && crate::paints(i))
|
||||
{
|
||||
paths.push(b);
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 1, "{paths:?}");
|
||||
let b = paths[0];
|
||||
assert!((b.x0 - 210.0).abs() < 0.5 && (b.x1 - 250.0).abs() < 0.5 && (b.y0 - 30.0).abs() < 0.5, "{b:?}");
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
}
|
||||
@@ -120,8 +120,11 @@ vectorcraft-testkit = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
# A variable font built in code (no font file is committed).
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
# How many times an open reads a PDF.
|
||||
# How many times an open reads a PDF, and the work its import takes.
|
||||
vectorcraft-pdf = { workspace = true, features = ["read-count"] }
|
||||
# The work `.ai` blends take to be checked and made live, and how many included EPS open checks
|
||||
# an open performs.
|
||||
vectorcraft-eps = { workspace = true, features = ["work-count"] }
|
||||
# How many times the symbol list is read to find symbols by name, and how many objects are
|
||||
# measured against locked artboards.
|
||||
vectorcraft-doc = { workspace = true, features = ["symbol-read-count", "locked-artboard-count"] }
|
||||
|
||||
@@ -97,6 +97,7 @@ mod style;
|
||||
pub use style::styled_node;
|
||||
pub mod stylelib;
|
||||
mod svgfilter;
|
||||
pub use svgfilter::MAX_IMPORT_BYTES as MAX_SVG_FILTER_IMPORT_BYTES;
|
||||
mod swatch;
|
||||
pub mod swatchlib;
|
||||
pub(crate) mod symboledit;
|
||||
@@ -963,6 +964,8 @@ pub use variablecmds::utf16_order_without_mark;
|
||||
/// file: its size limit, its text, its cells and the data `graph.setData` takes from them.
|
||||
pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text};
|
||||
|
||||
/// The kind of variable that drives an object's content (`variable.setBinding`).
|
||||
pub(crate) use variablecmds::content_kind;
|
||||
/// The Variables panel's sort (`variable.sort`) and its rows in that order.
|
||||
pub use variablecmds::{VariableSort, VariableSortKey, variable_order};
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fold",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true when the gap is within the larger of tolerance and 0.5% of the distance between the hinge's two ends. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
|
||||
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it; the lowest id wins a tie. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true when the gap is within the larger of tolerance and 0.5% of the distance between the hinge's two ends. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
|
||||
has_doc,
|
||||
fold_command
|
||||
)]
|
||||
|
||||
@@ -4,14 +4,15 @@
|
||||
//! (`vectorcraft_tools::addons::parametric_shape`), which SVG export leaves out.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point};
|
||||
use vectorcraft_doc::{Document, Node, NodeKind, Scaling};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point};
|
||||
use vectorcraft_pathops::addons::pathtools::shapes::{ParametricShape, ShapeKind, recognise};
|
||||
use vectorcraft_render::effects;
|
||||
use vectorcraft_tools::addons::parametric_shape::{CREATE, EDIT, KEY, apply, read, stored, to_json};
|
||||
|
||||
use super::super::super::menucmds::whole_or;
|
||||
use super::super::super::{CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection};
|
||||
use super::super::super::object;
|
||||
use super::super::super::{CommandSpec, bad, check_switches, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection};
|
||||
use crate::{EngineError, MAX_COORD, Result, Session};
|
||||
|
||||
/// The undo step's name and the command's label.
|
||||
@@ -33,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Parametric Shape",
|
||||
[],
|
||||
None,
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; a new center, size or rotation moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with it, and with `strokes` its strokes and effects scale; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
@@ -62,6 +63,25 @@ fn shape_node(n: &mut Node, s: &ParametricShape, path: PathData) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The transform that takes the outline of `old` to the one `new` would have if only their
|
||||
/// center, size and rotation differed: what moves, turns and scales the rest of the object (a
|
||||
/// linked opacity mask, gradients and patterns placed on it) with the new numbers.
|
||||
fn carry(old: &ParametricShape, new: &ParametricShape) -> Option<Affine> {
|
||||
let same = old.center == new.center && old.width == new.width && old.height == new.height && old.rotation == new.rotation;
|
||||
(!same).then(|| new.frame() * Affine::scale_non_uniform(new.width / old.width, new.height / old.height) * old.frame().inverse())
|
||||
}
|
||||
|
||||
/// Path node `n`, shape `old`, becomes shape `new`: the node takes the transform between them
|
||||
/// ([`carry`]) with `sc`, and then the outline and numbers of `new` ([`shape_node`]).
|
||||
fn reshape(n: &mut Node, old: &ParametricShape, new: &ParametricShape, sc: Scaling, cmd: &str) -> Result<()> {
|
||||
let path = outline(new, cmd)?;
|
||||
if let Some(xf) = carry(old, new) {
|
||||
n.transform(xf, sc);
|
||||
}
|
||||
shape_node(n, new, path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The outline of `s`, checked already.
|
||||
fn outline(s: &ParametricShape, cmd: &str) -> Result<PathData> {
|
||||
s.path().ok_or_else(|| bad(cmd, "the shape's numbers are out of range"))
|
||||
@@ -97,6 +117,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "the path is locked or hidden"));
|
||||
}
|
||||
let old = d.node(id).and_then(read).ok_or_else(|| bad(C, "the object is not an editable parametric shape"))?;
|
||||
check_switches(p, &["strokes", "corners", "patterns"], C)?;
|
||||
let reference = match p.get("reference").filter(|v| !v.is_null()) {
|
||||
Some(_) => match whole_or(p, "reference", 4, C)? {
|
||||
i @ 0..=8 => Some(i as usize),
|
||||
@@ -121,17 +142,21 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let path = outline(&shape, C)?;
|
||||
// A new center, size or rotation moves, turns or scales the object as a transform does,
|
||||
// with Scale Strokes & Effects and Transform Patterns from `strokes` and `patterns` or the
|
||||
// preferences.
|
||||
let scales = carry(&old, &shape).is_some_and(|xf| Scaling::factor(xf).is_some());
|
||||
let base = if scales { object::scaling(s, p) } else { Scaling::default() };
|
||||
let sc = Scaling { patterns: object::transform_patterns(s, p, &[id])?, ..base };
|
||||
s.edit(EDIT, |d, sel| {
|
||||
shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, path);
|
||||
reshape(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &old, &shape, sc, C)?;
|
||||
if let Some((i, m, was)) = keep
|
||||
&& let Some(now) = boxed(d, m).map(|(_, b)| b.reference_point(i))
|
||||
&& now != was
|
||||
{
|
||||
let mut moved = shape;
|
||||
moved.center += was - now;
|
||||
let path = outline(&moved, C)?;
|
||||
shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &moved, path);
|
||||
reshape(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, &moved, sc, C)?;
|
||||
}
|
||||
// A shape named by `id` and not selected is not checked after the edit: one the edit
|
||||
// takes past the coordinate limit is an error here, and nothing changes.
|
||||
|
||||
@@ -562,6 +562,50 @@ fn set_keeps_the_reference_point_of_the_bounding_box_in_place() {
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": edge.0, "width": 180, "reference": 2})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_takes_a_linked_mask_and_placed_gradient_with_the_shape() {
|
||||
let mut s = session();
|
||||
let id =
|
||||
id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": "rectangle", "center": [200, 150], "width": 100, "height": 60})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [id.0], "gradient": {"kind": "linear"}})).unwrap();
|
||||
s.execute("paint.setGradientGeom", &json!({"ids": [id.0], "start": [170, 150], "end": [230, 150]})).unwrap();
|
||||
let m = id_of(&s.execute("shape.rectangle", &json!({"x": 160, "y": 130, "width": 40, "height": 40})).unwrap());
|
||||
s.execute("transparency.makeOpacityMask", &json!({"ids": [id.0, m.0]})).unwrap();
|
||||
// Where the mask art and the gradient's vector sit in the shape's own frame: the same before and after.
|
||||
let local = |s: &Session| {
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let frame = shape_of(s, id).unwrap();
|
||||
let to_local = vectorcraft_geom::Affine::scale_non_uniform(1.0 / frame.width, 1.0 / frame.height) * frame.frame().inverse();
|
||||
let mask = n.extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap();
|
||||
let vectorcraft_color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("a gradient fill") };
|
||||
let geom = g.geom.unwrap();
|
||||
[to_local * mask.center(), to_local * geom.start, to_local * geom.end]
|
||||
};
|
||||
let was = local(&s);
|
||||
for edit in [
|
||||
json!({"center": [320, 260]}),
|
||||
json!({"width": 180}),
|
||||
json!({"rotation": 90}),
|
||||
json!({"height": 90, "reference": 0}),
|
||||
json!({"count": 6, "kind": "polygon"}),
|
||||
] {
|
||||
let mut p = edit.clone();
|
||||
p["id"] = json!(id.0);
|
||||
s.execute("addon.pathtools.shape.set", &p).unwrap();
|
||||
for (now, then) in local(&s).iter().zip(&was) {
|
||||
assert!(now.distance(*then) < 1e-9, "{edit}: moved off the shape to {now:?} from {then:?}");
|
||||
}
|
||||
}
|
||||
// With Scale Strokes & Effects on, a new size scales the stroke as a transform does; off, it keeps its weight.
|
||||
let weight = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().appearance.stroke_width();
|
||||
s.execute("stroke.set", &json!({"ids": [id.0], "weight": 4})).unwrap();
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 360, "height": 180, "strokes": false})).unwrap();
|
||||
assert!((weight(&s) - 4.0).abs() < 1e-9);
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 720, "height": 360, "strokes": true})).unwrap();
|
||||
assert!(weight(&s) > 4.0 + 1.0, "the stroke scaled with the shape");
|
||||
refuses(&mut s, "addon.pathtools.shape.set", &[json!({"id": id.0, "width": 50, "strokes": "yes"})]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_shape_params_are_refused() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once.
|
||||
//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and
|
||||
//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type
|
||||
//! `addon.units.convert` reads a length with units and arithmetic ([`Unit::parse`]) and gives
|
||||
//! it in each unit of Preferences › Units › East Asian Type
|
||||
//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]).
|
||||
//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform
|
||||
//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the
|
||||
@@ -10,7 +10,7 @@
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, finite_in_every_unit};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::{CommandSpec, always, bad, cmd, has_selection};
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert Units",
|
||||
[],
|
||||
None,
|
||||
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
"{value: a length (a number, or text with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point in \"0,5 mm\", but a thousands-shaped number is refused even in arithmetic, as in \"1,500+2\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
always,
|
||||
convert
|
||||
),
|
||||
@@ -76,7 +76,7 @@ fn convert(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(CONVERT, "missing `value`"));
|
||||
};
|
||||
let pt = match v {
|
||||
Value::String(s) if readable(s) => unit.parse(&decimal_point(s)),
|
||||
Value::String(s) if readable(s) => unit.parse_with_decimal_comma(s),
|
||||
Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
@@ -50,7 +50,7 @@ fn a_length_comes_back_in_every_unit_in_order() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_read_as_number_fields_read_them() {
|
||||
fn values_accept_units_arithmetic_and_decimal_commas() {
|
||||
let mut s = session();
|
||||
let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap();
|
||||
assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0));
|
||||
@@ -72,8 +72,9 @@ fn values_read_as_number_fields_read_them() {
|
||||
assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0));
|
||||
// Each number of a sum reads its own separator.
|
||||
assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4));
|
||||
// A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5.
|
||||
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
|
||||
assert!(near(pt(&mut s, json!({"value": "2x0,125 px"})), 0.25));
|
||||
assert!(near(pt(&mut s, json!({"value": "0,125p6+2"})), 9.5));
|
||||
assert!(near(pt(&mut s, json!({"value": "2p0,5+1"})), 25.5));
|
||||
// A sum of 128 signs still reads.
|
||||
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
|
||||
// x, X and × multiply as * does, and each counts toward the 128 signs.
|
||||
@@ -84,6 +85,15 @@ fn values_read_as_number_fields_read_them() {
|
||||
assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thousands_comma_in_an_arithmetic_operand_is_refused() {
|
||||
let mut s = session();
|
||||
for value in ["1,500+2", "1,000 px+2", "2+-1,000", "2/1,000", "2×1,000 in", "1,000'X2", "5pt+1,000%", "1,000p6+2", "2p1,000+2"] {
|
||||
let result = s.execute("addon.units.convert", &json!({"value": value}));
|
||||
assert!(matches!(result, Err(EngineError::BadParams { .. })), "{value}: {result:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_the_commands_do_not_take_are_refused() {
|
||||
let s = session();
|
||||
|
||||
@@ -322,35 +322,52 @@ impl ItemTarget {
|
||||
/// targets have. In a target without an equal item, and for any other target, the row stands
|
||||
/// for itself. Every entry is `Some`.
|
||||
pub(crate) fn per_target(self, s: &Session, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
|
||||
let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] };
|
||||
let Some(st) = s.active().filter(|_| ids.len() >= 2) else { return vec![Some(self); ids.len()] };
|
||||
let k = self.anchor(s, ids);
|
||||
let Some(first) = ids.get(k).and_then(|id| st.doc.node(*id)) else { return vec![Some(self); ids.len()] };
|
||||
ids.iter()
|
||||
.enumerate()
|
||||
.map(|(j, id)| match st.doc.node(*id) {
|
||||
self.each_target(s, ids).collect()
|
||||
}
|
||||
|
||||
/// [`ItemTarget::per_target`], one target at a time: a caller that stops at the first answer
|
||||
/// matches only the targets it reads against the anchor's stack.
|
||||
pub(crate) fn each_target<'a>(self, s: &'a Session, ids: &'a [NodeId]) -> impl Iterator<Item = Option<ItemTarget>> + 'a {
|
||||
let anchor = match self {
|
||||
ItemTarget::Item { aligned: true, .. } if ids.len() >= 2 => s.active().and_then(|st| {
|
||||
let k = self.anchor(s, ids);
|
||||
Some((&st.doc, k, ids.get(k).and_then(|id| st.doc.node(*id))?))
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
ids.iter().enumerate().map(move |(j, id)| {
|
||||
let (ItemTarget::Item { index, explicit, .. }, Some((d, k, first))) = (self, anchor) else { return Some(self) };
|
||||
match d.node(*id) {
|
||||
Some(n) if j != k => {
|
||||
let at = SharedStack::of(&[&*first.appearance, &*n.appearance]).item_in(index, 1);
|
||||
let at = shared_stack(&first.appearance, &n.appearance).item_in(index, 1);
|
||||
Some(at.map_or(self, |index| ItemTarget::Item { index, explicit, aligned: true }))
|
||||
}
|
||||
_ => Some(self),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// [`ItemTarget::per_target`], with an explicit aligned item a row of the stack of `of` (see [`design_reference`]),
|
||||
/// which is not among `ids`, when there is one: each target edits the item equal to it there, and a target without
|
||||
/// an equal item is left out (`None`).
|
||||
pub(crate) fn per_target_of(self, s: &Session, of: Option<NodeId>, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
|
||||
let ItemTarget::Item { index, explicit: true, aligned: true } = self else { return self.per_target(s, ids) };
|
||||
let Some(d) = s.active().map(|st| &st.doc) else { return self.per_target(s, ids) };
|
||||
let Some(r) = of.and_then(|of| d.node(of)) else { return self.per_target(s, ids) };
|
||||
ids.iter()
|
||||
.map(|id| {
|
||||
let index = SharedStack::of(&[&*r.appearance, &*d.node(*id)?.appearance]).item_in(index, 1)?;
|
||||
self.each_target_of(s, of, ids).collect()
|
||||
}
|
||||
|
||||
/// [`ItemTarget::per_target_of`], one target at a time (see [`ItemTarget::each_target`]).
|
||||
pub(crate) fn each_target_of<'a>(self, s: &'a Session, of: Option<NodeId>, ids: &'a [NodeId]) -> impl Iterator<Item = Option<ItemTarget>> + 'a {
|
||||
let reference = match self {
|
||||
ItemTarget::Item { index, explicit: true, aligned: true } => s.active().map(|st| &st.doc).and_then(|d| Some((d, d.node(of?)?, index))),
|
||||
_ => None,
|
||||
};
|
||||
let own = reference.is_none().then(|| self.each_target(s, ids));
|
||||
let shared = reference.map(|(d, r, index)| {
|
||||
ids.iter().map(move |id| {
|
||||
let index = shared_stack(&r.appearance, &d.node(*id)?.appearance).item_in(index, 1)?;
|
||||
Some(ItemTarget::Item { index, explicit: true, aligned: true })
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
own.into_iter().flatten().chain(shared.into_iter().flatten())
|
||||
}
|
||||
|
||||
/// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of
|
||||
@@ -392,6 +409,26 @@ impl ItemTarget {
|
||||
}
|
||||
}
|
||||
|
||||
/// The stack that `a` and `b` share ([`SharedStack::of`]), which [`ItemTarget::each_target`] and
|
||||
/// [`ItemTarget::each_target_of`] match each target's rows in.
|
||||
fn shared_stack(a: &Appearance, b: &Appearance) -> SharedStack {
|
||||
#[cfg(test)]
|
||||
STACKS_MATCHED.set(STACKS_MATCHED.get() + 1);
|
||||
SharedStack::of(&[a, b])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// [`stacks_matched`] of this thread.
|
||||
static STACKS_MATCHED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many shared stacks [`shared_stack`] has built on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn stacks_matched() -> u64 {
|
||||
STACKS_MATCHED.get()
|
||||
}
|
||||
|
||||
/// Does `p` say its item and effect indices are rows of the first target's stack (`aligned`),
|
||||
/// which each other target edits where it has them (see [`ItemTarget::per_target`])?
|
||||
pub(crate) fn aligned(p: &Value, cmd: &str) -> Result<bool> {
|
||||
@@ -865,7 +902,7 @@ fn edit_items_writing_then(
|
||||
/// The first of `ids` that [`edit_items`] aimed at `item` with `of` changes, and the item it changes there. Read it
|
||||
/// before the edit: once edited, a row that was equal to a row of the art of `of` no longer is.
|
||||
pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option<NodeId>, ids: &[NodeId]) -> Option<(NodeId, ItemTarget)> {
|
||||
ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
|
||||
ids.iter().zip(item.each_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
|
||||
}
|
||||
|
||||
/// Keep the object rows of the graph labels among `ids` for every label of their kind
|
||||
|
||||
@@ -38,7 +38,7 @@ mod dynamic;
|
||||
mod symbolism;
|
||||
mod symbols;
|
||||
|
||||
pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint};
|
||||
pub(crate) use brushes::{apply_brush, brush_targets, frame_marker, stroke_paint};
|
||||
use brushes::{
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options,
|
||||
brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
|
||||
@@ -766,10 +766,12 @@ pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]): the
|
||||
/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]), and
|
||||
/// the tile such a rectangle at the back of a pattern's art marks (`object.pattern.replaceArt`): the
|
||||
/// rectangle's bounds, when `n` is a path of one closed subpath through the four corners of its
|
||||
/// bounds, without curves, whose fills and strokes paint nothing and that has no other appearance.
|
||||
fn frame_marker(n: &Node) -> Option<vectorcraft_geom::Rect> {
|
||||
/// bounds in order around them (either way), without curves, whose fills and strokes paint nothing
|
||||
/// and that has no other appearance.
|
||||
pub(crate) fn frame_marker(n: &Node) -> Option<vectorcraft_geom::Rect> {
|
||||
let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return None };
|
||||
let unpainted = n.appearance.effects.is_empty()
|
||||
&& n.appearance.items.iter().all(|i| match i {
|
||||
@@ -781,7 +783,9 @@ fn frame_marker(n: &Node) -> Option<vectorcraft_geom::Rect> {
|
||||
let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)];
|
||||
let at_corners = sp.anchors.len() == 4
|
||||
&& sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p)
|
||||
&& corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c));
|
||||
&& corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c))
|
||||
// Each side, the closing one included, joins two corners that share an edge.
|
||||
&& sp.anchors.iter().zip(sp.anchors.iter().cycle().skip(1)).all(|(a, b)| a.p.x == b.p.x || a.p.y == b.p.y);
|
||||
(unpainted && sp.closed && at_corners && r.width() > 1e-9 && r.height() > 1e-9).then_some(r)
|
||||
}
|
||||
|
||||
|
||||
@@ -1601,7 +1601,8 @@ impl Clipboard {
|
||||
/// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's
|
||||
/// filter of its name; one that draws another definition than that filter takes the document's
|
||||
/// filter when pasted back into the document it came from, and elsewhere keeps its own under a
|
||||
/// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone. When that name would
|
||||
/// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone; an
|
||||
/// effect of the document that draws the same definition under a name no filter has gives that name. When that name would
|
||||
/// make the filter too long to draw, the free name is a shorter start of its name ("Shif"), else
|
||||
/// a free letter, digit or other printable ASCII character; the filter's id is always its name. An error when no free name fits.
|
||||
fn filter_links(&self, d: &Document, same_doc: bool) -> Result<BTreeMap<(String, String), (String, String)>> {
|
||||
@@ -1627,6 +1628,8 @@ impl Clipboard {
|
||||
}
|
||||
let mut taken: BTreeSet<String> = d.svg_filters.iter().map(|f| f.name.clone()).chain(found.iter().map(|(n, _)| n.clone())).collect();
|
||||
let mut effects_read = false;
|
||||
// The filter effects of the document, by name and definition.
|
||||
let mut held_effects = BTreeSet::new();
|
||||
let mut links = BTreeMap::new();
|
||||
for (name, xml) in found {
|
||||
let Some(held) = d.svg_filters.iter().find(|f| f.name == name).filter(|f| f.xml != xml.trim()) else { continue };
|
||||
@@ -1640,14 +1643,28 @@ impl Clipboard {
|
||||
effects_read = true;
|
||||
for root in d.art_roots() {
|
||||
node_filter_names(root, &mut taken);
|
||||
node_filters(root, &mut held_effects);
|
||||
}
|
||||
for a in vectorcraft_brush::library(d).iter().flat_map(Brush::art) {
|
||||
node_filter_names(a, &mut taken);
|
||||
node_filters(a, &mut held_effects);
|
||||
}
|
||||
for g in &d.graphic_styles {
|
||||
appearance_filter_names(&g.appearance, &mut taken);
|
||||
appearance_filters(&g.appearance, &mut held_effects);
|
||||
}
|
||||
}
|
||||
// An effect of the document that already draws this filter under a name no filter
|
||||
// of the document has (one pasted or loaded before) gives its name, so pasting or
|
||||
// loading the same filter again adds no other name.
|
||||
let earlier = held_effects.iter().find(|(n, x)| {
|
||||
!d.svg_filters.iter().any(|f| &f.name == n)
|
||||
&& vectorcraft_render::effects::svg_filter::with_id(&xml, n).is_some_and(|drawn| drawn == *x)
|
||||
});
|
||||
if let Some((n, x)) = earlier {
|
||||
links.insert((name, xml), (n.clone(), x.clone()));
|
||||
continue;
|
||||
}
|
||||
// Free names made from the starts of the name, longest first, then free letters and
|
||||
// digits, then other single printable ASCII characters: the first under which the
|
||||
// filter still draws.
|
||||
@@ -1845,6 +1862,8 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
|
||||
let clip = Clipboard::with_used(src, &used, &library, vec![]);
|
||||
let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::<BTreeSet<_>>());
|
||||
let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?;
|
||||
// Graphs in the symbols added draw with the designs `d` kept, as pasted ones do.
|
||||
crate::cmd::graph::redraw_symbols_with_designs(d, &out.added_symbols, &out.kept_designs);
|
||||
let mut placed: Vec<LoadedStyle> = vec![];
|
||||
for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] {
|
||||
for s in list {
|
||||
@@ -1857,6 +1876,35 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
|
||||
Ok(placed)
|
||||
}
|
||||
|
||||
/// Add to `d` the swatches, patterns, symbols and brushes (and what their art uses) that the
|
||||
/// appearance `look` of `src` and the character style attributes `attrs` of `src` paint with, as
|
||||
/// [`import_text_styles`] adds those of loaded styles, and give back `look` and `attrs` relinked to
|
||||
/// them (a resource `d` has under the same name and with the same contents is used; another is
|
||||
/// added under a free name; a global or spot color whose name `d` gives another color is `d`'s;
|
||||
/// an SVG filter whose name `d` gives another filter is renamed).
|
||||
pub(crate) fn import_looks(
|
||||
src: &Document,
|
||||
d: &mut Document,
|
||||
look: &Appearance,
|
||||
attrs: &Map<String, Value>,
|
||||
) -> Result<(Appearance, Map<String, Value>)> {
|
||||
let library = OnceCell::new();
|
||||
let defs = Defs::of(src, &library);
|
||||
let mut used = Used::default();
|
||||
used.follow(&defs, vec![Source::Appearance(look), Source::Attrs(attrs)]);
|
||||
// The look goes on an empty path, so that its SVG filters are renamed where `d` gives their
|
||||
// names other filters, as a pasted object's are.
|
||||
let carrier = Node::path(vectorcraft_doc::NodeId(0), vectorcraft_geom::PathData::default(), look.clone());
|
||||
let clip = Clipboard::with_used(src, &used, &library, vec![carrier]);
|
||||
let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?;
|
||||
// Graphs in the symbols added draw with the designs `d` kept, as pasted ones do.
|
||||
crate::cmd::graph::redraw_symbols_with_designs(d, &out.added_symbols, &out.kept_designs);
|
||||
let (mut look, mut attrs) = (look.clone(), attrs.clone());
|
||||
out.relink.appearance(&mut look);
|
||||
out.relink.attrs(&mut attrs);
|
||||
Ok((look, attrs))
|
||||
}
|
||||
|
||||
/// The resources graph designs `names` of `src` use, through the definitions they lead to.
|
||||
fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used {
|
||||
let mut used = Used::default();
|
||||
|
||||
@@ -562,16 +562,30 @@ fn mode_converter(mode: ColorMode, intent: Option<Intent>, grays: Grays) -> impl
|
||||
}
|
||||
|
||||
/// The name and color of each global swatch of `d`, for [`mode_color`].
|
||||
fn global_bases(d: &vectorcraft_doc::Document) -> Vec<(String, Color)> {
|
||||
d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect()
|
||||
fn global_bases(d: &vectorcraft_doc::Document) -> BTreeMap<String, Color> {
|
||||
let mut first = BTreeMap::new();
|
||||
for w in d.swatches_iter() {
|
||||
// An ineligible first record still shadows a later global solid of the same name.
|
||||
first.entry(w.name.as_str()).or_insert(w);
|
||||
}
|
||||
first
|
||||
.into_values()
|
||||
.filter_map(|w| {
|
||||
if !w.global {
|
||||
return None;
|
||||
}
|
||||
let Paint::Solid { color, swatch: None, .. } = &w.paint else { return None };
|
||||
Some((w.name.clone(), d.linked_color(*color, w.spot)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The color Document Color Mode gives `col` (swatch link `link`): a tint of a global swatch in
|
||||
/// `bases` (already converted) is that swatch's color at its tint; any other color goes through
|
||||
/// `conv` ([`mode_converter`]).
|
||||
fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &dyn Fn(&Color) -> Color) -> Color {
|
||||
match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) {
|
||||
Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint),
|
||||
fn mode_color(col: &Color, link: proof::Link, bases: &BTreeMap<String, Color>, conv: &dyn Fn(&Color) -> Color) -> Color {
|
||||
match link.and_then(|(name, tint)| Some((bases.get(name)?, tint))) {
|
||||
Some((base, tint)) if tint < 1.0 => base.tinted(tint),
|
||||
_ => conv(col),
|
||||
}
|
||||
}
|
||||
@@ -579,10 +593,11 @@ fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &
|
||||
/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks,
|
||||
/// effect colors and the series paints and label styles that graphs keep included), symbols,
|
||||
/// graph designs, pattern tiles (the tile that pattern editing's Cancel puts back included),
|
||||
/// graphic styles (their effects included), brushes (their art and a Hue Shift key color) and
|
||||
/// swatches through the color settings (`intent`, default: theirs) → how many colors of the art
|
||||
/// (opacity masks, effect colors and graphs' paints included), symbols, graph designs and pattern
|
||||
/// tiles changed; the colors of graphic styles and brushes convert without being counted. Gray
|
||||
/// graphic styles (their effects included), brushes (their art and a Hue Shift key color),
|
||||
/// character and paragraph styles (their fill and stroke) and swatches through the color settings
|
||||
/// (`intent`, default: theirs) → how many colors of the art (opacity masks, effect colors and
|
||||
/// graphs' paints included), symbols, graph designs and pattern tiles changed; the colors of
|
||||
/// graphic styles, brushes and text styles convert without being counted. Gray
|
||||
/// colors stay Gray (they print on the black plate in either mode); RGB grays are colors like any
|
||||
/// other and separate through the CMYK profile, unless `grays` puts them on the black plate
|
||||
/// ([`mode_converter`]). Lab colors
|
||||
@@ -594,7 +609,10 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
|
||||
if !convert {
|
||||
return 0;
|
||||
}
|
||||
convert_colors(d, &mode_converter(mode, intent, grays))
|
||||
let conv = mode_converter(mode, intent, grays);
|
||||
let changed = convert_colors(d, &conv);
|
||||
convert_style_colors(d, &conv);
|
||||
changed
|
||||
}
|
||||
|
||||
/// Every color of `d` that [`set_color_mode`] converts, converted with `conv` → how many colors of
|
||||
@@ -685,8 +703,8 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co
|
||||
vectorcraft_brush::store(d, &brushes);
|
||||
}
|
||||
// This pass gives tint swatches their converted swatch's color at their tint; the passes above already did the same for the art's tints.
|
||||
d.map_solid_paints(&mut |c, link, tint| match bases.iter().find(|(n, _)| Some(n) == link.as_ref()) {
|
||||
Some((_, base)) if *tint < 1.0 => {
|
||||
d.map_solid_paints(&mut |c, link, tint| match link.as_ref().and_then(|name| bases.get(name)) {
|
||||
Some(base) if *tint < 1.0 => {
|
||||
*c = base.tinted(*tint);
|
||||
true
|
||||
}
|
||||
|
||||
@@ -157,14 +157,7 @@ pub fn encode(setup: &ProofSetup) -> Vec<u8> {
|
||||
pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "view.proofSetup.save";
|
||||
let (path, named) = file_path(s, p, C)?;
|
||||
let mut setup = proof::view().setup;
|
||||
setup_params(p, &mut setup, C)?;
|
||||
check_device(&setup.target).map_err(|e| bad(C, e))?;
|
||||
// A file `view.proofSetup.load` would refuse is not written (a device with a very long name).
|
||||
let bytes = encode(&setup);
|
||||
if bytes.len() > MAX_FILE {
|
||||
return Err(bad(C, format!("{path}: larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
let (setup, bytes) = encode_options(p, &path)?;
|
||||
if named
|
||||
&& let Some(dir) = std::path::Path::new(&path).parent()
|
||||
&& !dir.is_dir()
|
||||
@@ -179,19 +172,47 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Object(r))
|
||||
}
|
||||
|
||||
/// Serialize the Customize dialog's draft without committing it or writing a path.
|
||||
pub fn draft_bytes(p: &Value) -> Result<Vec<u8>> {
|
||||
encode_options(p, "Proof Setup").map(|(_, bytes)| bytes)
|
||||
}
|
||||
|
||||
fn encode_options(p: &Value, file: &str) -> Result<(ProofSetup, Vec<u8>)> {
|
||||
const C: &str = "view.proofSetup.save";
|
||||
let mut setup = proof::view().setup;
|
||||
setup_params(p, &mut setup, C)?;
|
||||
check_device(&setup.target).map_err(|e| bad(C, e))?;
|
||||
let bytes = encode(&setup);
|
||||
if bytes.len() > MAX_FILE {
|
||||
return Err(bad(C, format!("{file}: larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
Ok((setup, bytes))
|
||||
}
|
||||
|
||||
/// The file `p` names for `cmd` and the usable proof setup in it.
|
||||
fn read_setup(s: &Session, p: &Value, cmd: &str) -> Result<(String, ProofSetup)> {
|
||||
let (path, _) = file_path(s, p, cmd)?;
|
||||
// One byte past the limit shows a file over it, which is not read further.
|
||||
let bytes = fileio::read_file_head(&path, MAX_FILE + 1)?;
|
||||
if bytes.len() > MAX_FILE {
|
||||
return Err(bad(cmd, format!("{path}: larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
let setup = parse(&bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
check_device(&setup.target).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
let setup = checked_setup(&bytes, &path, cmd)?;
|
||||
Ok((path, setup))
|
||||
}
|
||||
|
||||
/// Read a picked proof setup's validated settings without applying them to the view.
|
||||
pub fn draft_fields(bytes: &[u8], name: &str) -> Result<Value> {
|
||||
let setup = checked_setup(bytes, name, "view.proofSetup.read")?;
|
||||
Ok(Value::Object(setup_json(&setup)))
|
||||
}
|
||||
|
||||
fn checked_setup(bytes: &[u8], name: &str, cmd: &str) -> Result<ProofSetup> {
|
||||
if bytes.len() > MAX_FILE {
|
||||
return Err(bad(cmd, format!("{name}: larger than {MAX_FILE} bytes")));
|
||||
}
|
||||
let setup = parse(bytes).map_err(|e| bad(cmd, format!("{name}: {e}")))?;
|
||||
check_device(&setup.target).map_err(|e| bad(cmd, format!("{name}: {e}")))?;
|
||||
Ok(setup)
|
||||
}
|
||||
|
||||
pub(super) fn read(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (path, setup) = read_setup(s, p, "view.proofSetup.read")?;
|
||||
let mut r = setup_json(&setup);
|
||||
|
||||
@@ -27,7 +27,7 @@ pub const EXTS: &[&str] = &["vccomposite"];
|
||||
const EXPORT: &str = "type.compositeFonts.export";
|
||||
|
||||
/// The largest file Import reads, in bytes.
|
||||
const MAX_FILE_BYTES: usize = 4 << 20;
|
||||
pub const MAX_FILE_BYTES: usize = 4 << 20;
|
||||
|
||||
/// The keys a part may give.
|
||||
const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"];
|
||||
@@ -204,7 +204,7 @@ fn parse_set(v: &Value, font: &str, kanji: &CompositePart, c: &str) -> Result<Cu
|
||||
|
||||
/// Error unless `fonts` can stand together in a document: names unique in any case, none naming
|
||||
/// an installed font, no part set in a composite font, and at most [`COMPOSITE_FONTS_MAX`].
|
||||
fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
|
||||
pub(crate) fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
|
||||
if fonts.len() > COMPOSITE_FONTS_MAX {
|
||||
return Err(bad(c, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
|
||||
}
|
||||
@@ -237,31 +237,53 @@ fn replace(s: &mut Session, label: &str, after: Vec<CompositeFont>) -> Result<()
|
||||
if before == after {
|
||||
return Ok(());
|
||||
}
|
||||
let changed = register(s, &before, &after);
|
||||
let r = s.edit(label, |d, _| set_fonts(d, &after, &changed));
|
||||
sync(s);
|
||||
r
|
||||
}
|
||||
|
||||
/// Before an edit makes `after` the active document's composite fonts (it has `before`), register
|
||||
/// them in the font database and forget the ones taken out → the lowercased names of the fonts that
|
||||
/// change, for [`set_fonts`]. Run [`sync`] after the edit, whether it was made or not.
|
||||
pub(crate) fn register(s: &mut Session, before: &[CompositeFont], after: &[CompositeFont]) -> Vec<String> {
|
||||
let changed: Vec<String> =
|
||||
before.iter().filter(|b| !after.contains(b)).chain(after.iter().filter(|a| !before.contains(a))).map(|f| f.name.to_lowercase()).collect();
|
||||
// A refused or panicked edit leaves the document without the new fonts: `sync` forgets a name
|
||||
// listed here that the document doesn't define.
|
||||
s.composite_names.extend(after.iter().map(|f| f.name.to_lowercase()));
|
||||
let db = FontDb::global();
|
||||
for f in &before {
|
||||
for f in before {
|
||||
if !after.iter().any(|a| CompositeFont::same_name(&a.name, &f.name)) {
|
||||
db.remove_composite_font(&f.name);
|
||||
}
|
||||
}
|
||||
for f in &after {
|
||||
for f in after {
|
||||
db.set_composite_font(f);
|
||||
}
|
||||
let r = s.edit(label, |d, _| {
|
||||
*d.composite_fonts = after.clone();
|
||||
each_text_mut(d, &mut |t| {
|
||||
if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) {
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
sync(s);
|
||||
r
|
||||
changed
|
||||
}
|
||||
|
||||
/// Make `after` the composite fonts of `d`, and measure the type set in a font of `changed` again.
|
||||
pub(crate) fn set_fonts(d: &mut vectorcraft_doc::Document, after: &[CompositeFont], changed: &[String]) -> Result<()> {
|
||||
*d.composite_fonts = after.to_vec();
|
||||
each_text_mut(d, &mut |t| {
|
||||
if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) {
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// `fonts` with `f` in place of the composite font of its name, or added, as Import Composite Fonts
|
||||
/// adds a font.
|
||||
pub(crate) fn with_font(fonts: &[CompositeFont], f: &CompositeFont) -> Vec<CompositeFont> {
|
||||
let mut after = fonts.to_vec();
|
||||
match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) {
|
||||
Some(a) => *a = f.clone(),
|
||||
None => after.push(f.clone()),
|
||||
}
|
||||
after
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -349,7 +371,12 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let too_large = || bad(C, "the file is larger than 4 MB");
|
||||
let bytes = match given {
|
||||
(Some(path), None, None) if !path.trim().is_empty() => read_file_head(path, MAX_FILE_BYTES + 1)?,
|
||||
(None, Some(text), None) => text.as_bytes().to_vec(),
|
||||
(None, Some(text), None) => {
|
||||
if text.len() > MAX_FILE_BYTES {
|
||||
return Err(too_large());
|
||||
}
|
||||
text.as_bytes().to_vec()
|
||||
}
|
||||
(None, None, Some(b64)) => {
|
||||
if b64.len() > MAX_FILE_BYTES / 3 * 4 + 4 {
|
||||
return Err(too_large());
|
||||
@@ -372,10 +399,7 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if apply {
|
||||
let mut after = s.doc()?.doc.composite_fonts.to_vec();
|
||||
for f in &fonts {
|
||||
match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) {
|
||||
Some(a) => *a = f.clone(),
|
||||
None => after.push(f.clone()),
|
||||
}
|
||||
after = with_font(&after, f);
|
||||
}
|
||||
check_set(&after, C)?;
|
||||
replace(s, "Import Composite Fonts", after)?;
|
||||
|
||||
@@ -27,6 +27,27 @@ fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// Inline and encoded files share the same raw byte limit; rejection changes no fonts or history.
|
||||
#[test]
|
||||
fn import_file_byte_boundaries_preserve_the_document_on_refusal() {
|
||||
let mut s = session();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font("Existing")]})).unwrap();
|
||||
let before = steps(&s);
|
||||
let large = " ".repeat(super::MAX_FILE_BYTES + 1);
|
||||
for params in [json!({"data": large}), json!({"dataBase64": vectorcraft_format::base64_encode(large.as_bytes())})] {
|
||||
let error = s.execute("type.compositeFonts.import", ¶ms).unwrap_err();
|
||||
assert!(error.to_string().contains("the file is larger than 4 MB"), "{error}");
|
||||
assert_eq!(names(&s), ["Existing"]);
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
let mut exact = json!({"compositeFonts": [font("Imported")]}).to_string();
|
||||
exact.extend(std::iter::repeat_n(' ', super::MAX_FILE_BYTES - exact.len()));
|
||||
let imported = s.execute("type.compositeFonts.import", &json!({"data": exact, "apply": false})).unwrap();
|
||||
assert_eq!(imported["fonts"][0]["name"], "Imported");
|
||||
assert_eq!(names(&s), ["Existing"]);
|
||||
assert_eq!(steps(&s), before);
|
||||
}
|
||||
|
||||
fn text(s: &Session, id: u64) -> vectorcraft_doc::TextObject {
|
||||
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file, format, effectivePpi, memoryBytes, storedBytes}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one; format: a linked image's file format by its extension, else the format of the pixels the document holds, null when unknown; effectivePpi: [x, y] pixels per inch at the size it is placed at, a distorted image measured at its middle, null when it has no area; memoryBytes: for an embedded image width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, else null; storedBytes: for an embedded image the bytes of the encoded image the document holds, else null; a Linked Images row gives the format, the size, the resolution and the file (`PNG; 1200 × 800 px; 150 ppi — /art/photo.png`), an Embedded Images row the format, the size and the memory (`PNG; 1200 × 800 px; estimated memory 3.7 MiB`)), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freef
Line truncated
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), pathArea?: bool (default true; false skips the paths' area pass, as a category other than objects does), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), pathArea: pt² (the paths' total area, compound paths' included, guides left out; null unless the request covers the Objects category (no category, or objects) and pathArea? is not false: the area pass normalizes every closed path's geometry, so a caller showing another category can skip it), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file, format, effectivePpi, memoryBytes, storedBytes}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one; format: a linked image's file format by its extension, else the format of the pixels the document holds, null when unknown; effectivePpi: [x, y] pixels per inch at the size it is placed at, a distorted image measured at its middle, null when it has no area; memoryBytes: for an embedded image width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, else null; storedBytes: for an embedded image the bytes of the encoded image the document holds, else null; a Linked Images row gives the format, the size, the resolution and the file (`PNG; 1200 × 800 px; 150 ppi — /art/photo.png`), an Embedded Images row the format, the size and the memory (`PNG; 1200 × 800 px; estimated memory 3.7 MiB`)), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which obje
Line truncated
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -445,6 +445,12 @@ fn sections(
|
||||
if let Some(at) = rows.iter().position(|(label, _)| label == "Paths") {
|
||||
rows.insert(at + 1, ("Path Length".into(), u.format(info["pathLength"].as_f64().unwrap_or(0.0))));
|
||||
}
|
||||
let area = info["pathArea"].as_f64().unwrap_or(0.0);
|
||||
if area > 0.0
|
||||
&& let Some(at) = rows.iter().position(|(label, _)| label == "Path Length")
|
||||
{
|
||||
rows.insert(at + 1, ("Path Area".into(), u.format_area(area)));
|
||||
}
|
||||
rows
|
||||
}
|
||||
"graphicStyles" => names("graphicStyleNames"),
|
||||
@@ -755,6 +761,38 @@ fn object_paints(d: &Document, spots: &HashSet<&str>, members: &HashSet<*const N
|
||||
used
|
||||
}
|
||||
|
||||
/// Filled area of a path's closed subpaths under its fill rule (holes subtracted; open subpaths left out).
|
||||
fn closed_path_area(path: &vectorcraft_geom::PathData, rule: vectorcraft_geom::FillRule) -> f64 {
|
||||
let closed = vectorcraft_geom::PathData { subpaths: path.subpaths.iter().filter(|s| s.closed).cloned().collect() };
|
||||
if closed.subpaths.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let a = vectorcraft_pathops::area(&closed, rule);
|
||||
if a.is_finite() && a > 0.0 { a } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Recursively collects non-guide subpaths from a node and its descendants for compound path area calculation.
|
||||
fn collect_compound_subpaths(n: &Node, subs: &mut Vec<vectorcraft_geom::SubPath>) {
|
||||
if n.is_guide() {
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, guide: false, .. } => {
|
||||
subs.extend(path.subpaths.clone());
|
||||
}
|
||||
NodeKind::Compound { children, .. } => {
|
||||
for c in children {
|
||||
collect_compound_subpaths(c, subs);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if let Some((pd, _)) = super::pathops::node_path(n) {
|
||||
subs.extend(pd.subpaths);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.info";
|
||||
let category = str_param(p, "category");
|
||||
@@ -782,6 +820,10 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The paths' total length, as Document Info › Objects shows it (the length of a cut line, a
|
||||
// strip of LEDs along the letters, #1958).
|
||||
let mut path_length = 0.0;
|
||||
let mut path_area = 0.0;
|
||||
// The area normalizes every closed path's geometry, so it is worked out only for a request
|
||||
// that covers the Objects category and does not turn it off with `pathArea: false`.
|
||||
let want_area = bool_or(p, "pathArea", true) && category.is_none_or(|c| c == "objects");
|
||||
// Each font with the number of text objects set in it.
|
||||
let mut fonts: BTreeMap<super::fonts::UsedFont, usize> = BTreeMap::new();
|
||||
let mut images: BTreeMap<String, Value> = BTreeMap::new();
|
||||
@@ -830,6 +872,19 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
members.extend(children.iter().map(|c| std::ptr::from_ref(&**c)));
|
||||
}
|
||||
});
|
||||
// The members of the compound paths that the roots contain. Only these leave their area to the compound.
|
||||
let mut compound_members: HashSet<*const Node> = HashSet::new();
|
||||
for (r, _) in roots.iter().filter(|_| want_area) {
|
||||
r.walk(&mut |n| {
|
||||
if let NodeKind::Compound { children, .. } = &n.kind {
|
||||
for c in children {
|
||||
c.walk(&mut |descendant| {
|
||||
compound_members.insert(std::ptr::from_ref(descendant));
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
// Depth first, in paint order, as `Node::walk` visits: each object with whether it and the groups and layers around it
|
||||
// draw. An object that does not draw is still counted, and its members are visited.
|
||||
let mut stack: Vec<(&Node, bool)> = vec![];
|
||||
@@ -849,14 +904,26 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
NodeKind::Group { clip: true, .. } => Some("clipGroups"),
|
||||
NodeKind::Group { .. } => Some("groups"),
|
||||
NodeKind::Path { guide: true, .. } => Some("guides"),
|
||||
NodeKind::Path { path, .. } => {
|
||||
NodeKind::Path { path, rule, .. } => {
|
||||
let l = path.length();
|
||||
if l.is_finite() {
|
||||
path_length += l;
|
||||
}
|
||||
if want_area && !compound_members.contains(&std::ptr::from_ref(n)) {
|
||||
path_area += closed_path_area(path, *rule);
|
||||
}
|
||||
Some("paths")
|
||||
}
|
||||
NodeKind::Compound { .. } => Some("compoundPaths"),
|
||||
NodeKind::Compound { children, rule } => {
|
||||
if want_area && !compound_members.contains(&std::ptr::from_ref(n)) {
|
||||
let mut subs = Vec::new();
|
||||
for c in children {
|
||||
collect_compound_subpaths(c, &mut subs);
|
||||
}
|
||||
path_area += closed_path_area(&vectorcraft_geom::PathData::new(subs), *rule);
|
||||
}
|
||||
Some("compoundPaths")
|
||||
}
|
||||
NodeKind::Text(t) => {
|
||||
count_fonts(&mut fonts, t);
|
||||
Some("textObjects")
|
||||
@@ -972,6 +1039,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"document": document_summary(d),
|
||||
"objects": counts,
|
||||
"pathLength": path_length,
|
||||
"pathArea": want_area.then_some(path_area),
|
||||
"fonts": font_names,
|
||||
"fontUses": font_uses,
|
||||
"fontDetails": font_entries,
|
||||
@@ -1347,6 +1415,115 @@ mod tests {
|
||||
assert_eq!(length(&mut s, json!({"selectionOnly": true})), 0.0);
|
||||
}
|
||||
|
||||
/// Document Info › Objects gives the paths' total area in the document's units: an open line
|
||||
/// counts 0, a closed rectangle encloses its area, and a compound path's holes are subtracted.
|
||||
#[test]
|
||||
fn info_gives_the_paths_total_area() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400, "units": "Points"})).unwrap();
|
||||
let line = s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 72, "y2": 0})).unwrap()["id"].clone();
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 10, "height": 20})).unwrap()["id"].clone();
|
||||
let area = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["pathArea"].as_f64().unwrap();
|
||||
// The rectangle encloses 200 pt²; the open line encloses 0.
|
||||
assert!((area(&mut s, json!({})) - 200.0).abs() < 1e-6);
|
||||
// An open line selected: pathArea is 0, so no "Path Area" row is inserted.
|
||||
s.execute("select.set", &json!({"ids": [line]})).unwrap();
|
||||
assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0);
|
||||
let rows = s.execute("document.info", &json!({"selectionOnly": true, "category": "objects"})).unwrap()["sections"][0]["rows"].clone();
|
||||
assert_eq!(rows, json!([["Paths", "1"], ["Path Length", "72 pt"]]));
|
||||
// The rectangle selected: "Path Area" row follows "Path Length".
|
||||
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
|
||||
assert!((area(&mut s, json!({"selectionOnly": true})) - 200.0).abs() < 1e-6);
|
||||
let rows = s.execute("document.info", &json!({"selectionOnly": true, "category": "objects"})).unwrap()["sections"][0]["rows"].clone();
|
||||
assert_eq!(rows, json!([["Paths", "1"], ["Path Length", "60 pt"], ["Path Area", "200 pt²"]]));
|
||||
// A compound path's pieces are paths: their areas count.
|
||||
let other = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 5, "height": 5})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({"ids": [rect, other]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
assert!((area(&mut s, json!({"selectionOnly": true})) - 225.0).abs() < 1e-6);
|
||||
// A compound path (a 10x10 outer contour with a 6x6 inner hole) subtracts the hole:
|
||||
let mut s2 = Session::new();
|
||||
s2.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points"})).unwrap();
|
||||
let outer = s2.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let inner = s2.execute("shape.rectangle", &json!({"x": 12, "y": 12, "width": 6, "height": 6})).unwrap()["id"].clone();
|
||||
s2.execute("select.set", &json!({"ids": [outer, inner]})).unwrap();
|
||||
let cp1 = s2.execute("object.compoundPath.make", &json!({})).unwrap()["id"].clone();
|
||||
assert!((area(&mut s2, json!({"selectionOnly": true})) - 64.0).abs() < 1e-6);
|
||||
// A nested compound path (cp1 compounded with another disjoint 5x5 rectangle) does not double-count cp1:
|
||||
let extra = s2.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 5, "height": 5})).unwrap()["id"].clone();
|
||||
s2.execute("select.set", &json!({"ids": [cp1, extra]})).unwrap();
|
||||
s2.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
assert!((area(&mut s2, json!({"selectionOnly": true})) - 89.0).abs() < 1e-6);
|
||||
// A guide path is left out.
|
||||
let guide = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(guide)).unwrap().kind {
|
||||
*g = true;
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [guide]})).unwrap();
|
||||
assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0);
|
||||
// A compound path whose members are guides is left out.
|
||||
let g1 = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
let g2 = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(g1)).unwrap().kind {
|
||||
*g = true;
|
||||
}
|
||||
if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(g2)).unwrap().kind {
|
||||
*g = true;
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [g1, g2]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0);
|
||||
// Nothing with no paths, and no area row.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0);
|
||||
}
|
||||
|
||||
/// The area pass normalizes every closed path, so `document.info` leaves it out (`pathArea`
|
||||
/// null) for a request that does not cover the Objects category or turns it off, and still
|
||||
/// gives it for Objects and for every category.
|
||||
#[test]
|
||||
fn info_works_out_the_path_area_only_for_the_objects_category() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap();
|
||||
let area = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["pathArea"].as_f64();
|
||||
assert!(area(&mut s, json!({})).is_some_and(|a| a > 0.0));
|
||||
assert!(area(&mut s, json!({"category": "objects"})).is_some_and(|a| a > 0.0));
|
||||
assert_eq!(area(&mut s, json!({"category": "fonts"})), None);
|
||||
assert_eq!(area(&mut s, json!({"pathArea": false})), None);
|
||||
// Without the area, Objects has no Path Area row and keeps its other rows.
|
||||
let rows = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["sections"][0]["rows"].clone();
|
||||
let without = rows(&mut s, json!({"category": "objects", "pathArea": false}));
|
||||
let with = rows(&mut s, json!({"category": "objects"}));
|
||||
assert!(without.as_array().unwrap().iter().all(|r| r[0] != "Path Area"), "{without}");
|
||||
assert!(with.as_array().unwrap().iter().any(|r| r[0] == "Path Area"), "{with}");
|
||||
assert_eq!(with.as_array().unwrap().len(), without.as_array().unwrap().len() + 1);
|
||||
}
|
||||
|
||||
/// A selection containing both a compound and its member counts the member once; selecting
|
||||
/// only the member still reports that path's area.
|
||||
#[test]
|
||||
fn info_path_area_counts_selected_compound_members_once() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let p = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
let q = s.execute("shape.rectangle", &json!({"x": 30, "y": 30, "width": 5, "height": 5})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({"ids": [p, q]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let st = s.doc_mut().unwrap();
|
||||
let NodeKind::Compound { children, .. } = &st.doc.node(NodeId(compound)).unwrap().kind else { panic!("not a compound path") };
|
||||
let member = children.iter().find(|child| child.id.0 == p).unwrap().id;
|
||||
let area = |s: &mut Session| s.execute("document.info", &json!({"selectionOnly": true})).unwrap()["pathArea"].as_f64().unwrap();
|
||||
let picked = s.execute("select.set", &json!({"ids": [member.0]})).unwrap();
|
||||
assert_eq!(picked["count"], 1);
|
||||
assert!((area(&mut s) - 100.0).abs() < 1e-6);
|
||||
let picked = s.execute("select.set", &json!({"ids": [member.0, compound]})).unwrap();
|
||||
assert_eq!(picked["count"], 2);
|
||||
assert!((area(&mut s) - 125.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// Document Info › Brushes lists the brushes the art's strokes use, each once with its type, and
|
||||
/// leaves out the Brushes panel's brushes no art uses (`panelBrushNames` lists those). With
|
||||
/// Selection Only it lists the brushes the selected objects' strokes use.
|
||||
|
||||
@@ -284,7 +284,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Import Metadata Template…",
|
||||
[],
|
||||
None,
|
||||
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
|
||||
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text, dataBase64?: XMP bytes (exactly one source; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
|
||||
has_doc,
|
||||
super::fileinfo::apply_template
|
||||
),
|
||||
|
||||
@@ -333,11 +333,18 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<A
|
||||
}
|
||||
|
||||
/// Pieces of curve that one Smooth drag measures against the drag while it searches the segments
|
||||
/// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach,
|
||||
/// each of which gets at least one: enough to search 300,000 pt of curve within the default reach
|
||||
/// of the drag.
|
||||
/// under it ([`reach_samples`]), besides the whole of each curved segment, which is measured once
|
||||
/// however many there are: a drag measures no more than this many pieces plus one for each curved
|
||||
/// segment of the paths it searches. Shared equally by the curved segments that come within its
|
||||
/// reach, it is enough to search 300,000 pt of curve within the default reach of the drag.
|
||||
const MAX_REACH_PIECES: usize = 1 << 17;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many pieces of curve [`reach_samples`] measured against a drag on this thread.
|
||||
static PIECES_MEASURED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The box around the control points of `s`, which holds all of `s`.
|
||||
fn control_box(s: CubicBez) -> Rect {
|
||||
Rect::from_points(s.p0, s.p1).union_pt(s.p2).union_pt(s.p3)
|
||||
@@ -529,13 +536,24 @@ fn segments_in_reach(pd: &PathData, reach: &DragReach) -> usize {
|
||||
/// Samples along the part of `c` from `t0` to `t1`, in order: (t, whether the point there is within
|
||||
/// `radius` of the stretches `of` of the drag `pts`). A piece no stretch comes near gives one sample
|
||||
/// out of reach; the others are halved until their control polygon is no longer than half the
|
||||
/// reach, or until `budget` pieces have been measured, and then give one sample: in reach at the
|
||||
/// piece's middle or at its place nearest the drag when either is in reach, otherwise out of reach
|
||||
/// at its middle. Each piece measures only the stretches near
|
||||
/// reach, or until fewer than the two halves are left in this segment's `budget` or in `shared`,
|
||||
/// the pieces the whole drag may still measure past the first piece of each segment, and then give
|
||||
/// one sample: in reach at the piece's middle or at its place nearest the drag when either is in
|
||||
/// reach, otherwise out of reach at its middle. Both halves of a piece are taken from `budget` and
|
||||
/// from `shared` before either is measured, so a search measures no more than one piece besides
|
||||
/// what it takes from them. Each piece measures only the stretches near
|
||||
/// the piece it was cut from, so a long drag along a long curve costs about one pass over the drag
|
||||
/// per halving, plus the stretches near each piece.
|
||||
fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usize]), radius: f64, budget: &mut usize, out: &mut Vec<(f64, bool)>) {
|
||||
*budget = budget.saturating_sub(1);
|
||||
fn reach_samples(
|
||||
c: CubicBez,
|
||||
(t0, t1): (f64, f64),
|
||||
(pts, of): (&[Point], &[usize]),
|
||||
radius: f64,
|
||||
(budget, shared): (&mut usize, &mut usize),
|
||||
out: &mut Vec<(f64, bool)>,
|
||||
) {
|
||||
#[cfg(test)]
|
||||
PIECES_MEASURED.set(PIECES_MEASURED.get() + 1);
|
||||
let s = c.subsegment(t0..t1);
|
||||
let mid = 0.5 * (t0 + t1);
|
||||
let near = stretches_near(pts, of, control_box(s), radius);
|
||||
@@ -544,7 +562,7 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz
|
||||
return;
|
||||
}
|
||||
let len = s.p0.distance(s.p1) + s.p1.distance(s.p2) + s.p2.distance(s.p3);
|
||||
if len <= (radius / 2.0).max(1e-3) || *budget == 0 || mid <= t0 || mid >= t1 {
|
||||
if len <= (radius / 2.0).max(1e-3) || *budget < 2 || *shared < 2 || mid <= t0 || mid >= t1 {
|
||||
// The piece's middle, or the place on it nearest the drag when the middle is out of reach.
|
||||
let sample = if dist_to_stretches(pts, &near, c.eval(mid)) <= radius {
|
||||
(mid, true)
|
||||
@@ -555,8 +573,10 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz
|
||||
out.push(sample);
|
||||
return;
|
||||
}
|
||||
reach_samples(c, (t0, mid), (pts, &near), radius, budget, out);
|
||||
reach_samples(c, (mid, t1), (pts, &near), radius, budget, out);
|
||||
*budget -= 2;
|
||||
*shared -= 2;
|
||||
reach_samples(c, (t0, mid), (pts, &near), radius, (&mut *budget, &mut *shared), out);
|
||||
reach_samples(c, (mid, t1), (pts, &near), radius, (budget, shared), out);
|
||||
}
|
||||
|
||||
/// `sp` cut where the reach of the drag crosses its curved segments, and whether each
|
||||
@@ -565,8 +585,11 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz
|
||||
/// out of reach in the middle of each stretch out of reach between two stretches in reach, so that a
|
||||
/// stretch in reach is smoothed even when the segment's anchors are not, and the stretches between
|
||||
/// stay as they are. A segment is searched no more than half the reach apart where it comes within
|
||||
/// the reach of the drag ([`reach_samples`]), measuring up to `share` pieces of each segment.
|
||||
fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec<bool>) {
|
||||
/// the reach of the drag ([`reach_samples`]): each curved segment is measured whole, and then up
|
||||
/// to `share` more pieces of it are measured while the drag's `shared` pieces last, so the segments
|
||||
/// in reach share the search equally whatever order they come in, and a segment searched after
|
||||
/// the pieces run out is still found where its middle or its place nearest the drag is in reach.
|
||||
fn mark_reached(sp: &SubPath, reach: &DragReach, (share, shared): (usize, &mut usize)) -> (SubPath, Vec<bool>) {
|
||||
let (pts, radius) = (reach.pts, reach.radius);
|
||||
let n = sp.anchors.len();
|
||||
let marked: Vec<bool> = sp.anchors.iter().map(|a| reach.in_reach(a.p, 0.0)).collect();
|
||||
@@ -578,7 +601,7 @@ fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec<
|
||||
let c = sp.segment(i);
|
||||
let (mut samples, mut budget) = (vec![], share);
|
||||
let near = reach.near_rect(control_box(c.subsegment(0.0..1.0)));
|
||||
reach_samples(c, (0.0, 1.0), (pts, &near), radius, &mut budget, &mut samples);
|
||||
reach_samples(c, (0.0, 1.0), (pts, &near), radius, (&mut budget, &mut *shared), &mut samples);
|
||||
// Stretches of samples alike, in order: (in reach, first, last).
|
||||
let mut runs: Vec<(bool, usize, usize)> = vec![];
|
||||
for (k, s) in samples.iter().enumerate() {
|
||||
@@ -623,15 +646,16 @@ fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec<
|
||||
|
||||
/// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach.
|
||||
/// A closed path whose first anchor is in reach starts at the point of the refitted path nearest
|
||||
/// that anchor's place (VectorCraft's own rule).
|
||||
fn smooth_subpath(sp: &SubPath, reach: &DragReach, share: usize, tol: f64, sigma: f64) -> Option<SubPath> {
|
||||
/// that anchor's place (VectorCraft's own rule). `search` is each curved segment's share of the
|
||||
/// drag's search and the pieces the drag has left ([`mark_reached`]).
|
||||
fn smooth_subpath(sp: &SubPath, reach: &DragReach, search: (usize, &mut usize), tol: f64, sigma: f64) -> Option<SubPath> {
|
||||
if sp.anchors.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let radius = reach.radius;
|
||||
let near = &|q: Point| reach.in_reach(q, 0.0);
|
||||
// A drag along a segment smooths it even when its anchors are out of reach.
|
||||
let (sp, marked) = mark_reached(sp, reach, share);
|
||||
let (sp, marked) = mark_reached(sp, reach, search);
|
||||
let sp = &sp;
|
||||
if !marked.iter().any(|m| *m) {
|
||||
return None;
|
||||
@@ -948,15 +972,17 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
paths.push((id, path_of(&st.doc, id)?.0));
|
||||
}
|
||||
let reach = DragReach::new(&pts, radius);
|
||||
// Each curved segment in reach gets the same share of the search, whatever order they come in.
|
||||
// Each curved segment in reach gets the same share of the search, whatever order they come in,
|
||||
// and all of them together measure no more than `MAX_REACH_PIECES` pieces past their first.
|
||||
let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &reach)).sum();
|
||||
let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1);
|
||||
let mut shared = MAX_REACH_PIECES;
|
||||
for (id, pd) in paths {
|
||||
let mut changed = false;
|
||||
let subs: Vec<SubPath> = pd
|
||||
.subpaths
|
||||
.iter()
|
||||
.map(|sp| match smooth_subpath(sp, &reach, share, tol, sigma) {
|
||||
.map(|sp| match smooth_subpath(sp, &reach, (share, &mut shared), tol, sigma) {
|
||||
Some(n) if n != *sp && n.anchors.len() >= 2 => {
|
||||
changed = true;
|
||||
n
|
||||
@@ -1304,19 +1330,106 @@ mod tests {
|
||||
assert_eq!(start_nearest(ring(), Point::new(f64::NAN, 0.0), &ring()), ring());
|
||||
}
|
||||
|
||||
/// How many pieces `f` makes [`reach_samples`] measure on this thread.
|
||||
fn pieces_measured(f: impl FnOnce()) -> usize {
|
||||
let before = PIECES_MEASURED.get();
|
||||
f();
|
||||
PIECES_MEASURED.get() - before
|
||||
}
|
||||
|
||||
/// Searching a curve 1,000,000 pt long under a drag of 1,000 points along it measures no more
|
||||
/// pieces than the budget it is given, and a search with none left gives one sample.
|
||||
/// than one piece besides the drag's `MAX_REACH_PIECES`, counting the pieces it halves as well
|
||||
/// as those it samples, and a search with none of the drag's pieces left measures the curve
|
||||
/// once and gives one sample, whatever share of its own it has.
|
||||
#[test]
|
||||
fn searching_a_segment_under_a_drag_stays_within_its_budget() {
|
||||
let c = CubicBez::new(Point::new(0.0, 0.0), Point::new(300000.0, 0.0), Point::new(700000.0, 0.0), Point::new(1000000.0, 0.0));
|
||||
let pts: Vec<Point> = (0..1000).map(|i| Point::new(f64::from(i) * 1000.0, 0.0)).collect();
|
||||
let all = drag_stretches(&pts);
|
||||
let mut budget = MAX_REACH_PIECES;
|
||||
let (mut budget, mut shared) = (MAX_REACH_PIECES, MAX_REACH_PIECES);
|
||||
let (mut first, mut second) = (vec![], vec![]);
|
||||
reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, &mut budget, &mut first);
|
||||
reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, &mut budget, &mut second);
|
||||
assert!(first.len() <= MAX_REACH_PIECES, "{} samples", first.len());
|
||||
assert_eq!((budget, second.len()), (0, 1), "the budget is spent, so the next search gives one sample");
|
||||
let measured = pieces_measured(|| reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, (&mut budget, &mut shared), &mut first));
|
||||
assert!(measured <= MAX_REACH_PIECES + 1, "{measured} pieces measured");
|
||||
assert!(first.len() <= measured && first.len() > 1, "{} samples", first.len());
|
||||
assert!(shared < 2, "{shared} pieces left");
|
||||
let mut fresh = MAX_REACH_PIECES;
|
||||
let again = pieces_measured(|| reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, (&mut fresh, &mut shared), &mut second));
|
||||
assert_eq!((again, second.len()), (1, 1), "the drag's pieces are spent, so the next search gives one sample");
|
||||
}
|
||||
|
||||
/// One curved segment `w` pt wide from `(x, y)`, bowed `h` pt up.
|
||||
fn bow((x, y): (f64, f64), w: f64, h: f64) -> CubicBez {
|
||||
CubicBez::new(Point::new(x, y), Point::new(x + w / 3.0, y + h), Point::new(x + 2.0 * w / 3.0, y + h), Point::new(x + w, y))
|
||||
}
|
||||
|
||||
/// An open subpath of the curved segments `segs`, each starting where the one before ends.
|
||||
fn chain(segs: &[CubicBez]) -> SubPath {
|
||||
let mut anchors: Vec<Anchor> = vec![];
|
||||
for s in segs {
|
||||
match anchors.last_mut() {
|
||||
Some(last) => *last = Anchor::with_handles(s.p0, last.h_in, s.p1),
|
||||
None => anchors.push(Anchor::with_handles(s.p0, s.p0, s.p1)),
|
||||
}
|
||||
anchors.push(Anchor::with_handles(s.p3, s.p2, s.p3));
|
||||
}
|
||||
SubPath::new(anchors, false)
|
||||
}
|
||||
|
||||
/// A drag along two subpaths of 21,845 curved segments 100 pt long each, which share the search
|
||||
/// three pieces to a segment, and past a third of 1,000 curved segments far from the drag: every
|
||||
/// segment is measured whole and the whole drag measures no more than `MAX_REACH_PIECES` pieces
|
||||
/// past those, though each segment in reach would halve its pieces while its share lasts. Each
|
||||
/// segment in reach, the last one included, is halved once with its share of three, so the
|
||||
/// segments searched first leave the later ones their share.
|
||||
#[test]
|
||||
fn a_drag_over_many_curved_segments_measures_at_most_its_pieces_past_the_first_of_each() {
|
||||
let row = |(x, y): (f64, f64), n: u32| chain(&(0..n).map(|i| bow((x + f64::from(i) * 100.0, y), 100.0, 8.0)).collect::<Vec<_>>());
|
||||
let subs = [row((0.0, 0.0), 21_845), row((3_000_000.0, 0.0), 21_845), row((0.0, 1e6), 1000)];
|
||||
let pts = [Point::new(-10.0, 0.0), Point::new(6_000_000.0, 0.0)];
|
||||
let segments: usize = subs.iter().map(SubPath::segment_count).sum();
|
||||
assert_eq!(segments, 2 * 21_845 + 1000);
|
||||
let reach = DragReach::new(&pts, 12.0);
|
||||
let in_reach = segments_in_reach(&PathData::new(subs.to_vec()), &reach);
|
||||
assert_eq!(in_reach, 2 * 21_845, "the far segments are not counted");
|
||||
let share = (MAX_REACH_PIECES / in_reach).max(1);
|
||||
assert_eq!(share, 3);
|
||||
let mut shared = MAX_REACH_PIECES;
|
||||
let mut marks = vec![];
|
||||
let measured = pieces_measured(|| {
|
||||
for sp in &subs {
|
||||
marks.push(mark_reached(sp, &reach, (share, &mut shared)).1);
|
||||
}
|
||||
});
|
||||
assert!(measured >= segments && measured <= segments + MAX_REACH_PIECES, "{measured} pieces measured for {segments} segments");
|
||||
assert_eq!((measured, shared), (segments + 2 * in_reach, MAX_REACH_PIECES - 2 * in_reach), "every segment in reach is halved once");
|
||||
assert!(marks[0].iter().all(|m| *m), "the first path's anchors are all on the drag");
|
||||
}
|
||||
|
||||
/// More than `MAX_REACH_PIECES` short curved segments in reach are each measured once, and a
|
||||
/// segment searched after the drag's pieces are spent is still found in reach where only a
|
||||
/// narrow stretch of it, away from its middle, comes near the drag.
|
||||
#[test]
|
||||
fn every_curved_segment_is_searched_after_the_drags_pieces_run_out() {
|
||||
let n = 140_000;
|
||||
let tiny = chain(&(0..n).map(|i| bow((f64::from(i) * 4.0, 0.0), 4.0, 1.0)).collect::<Vec<_>>());
|
||||
let pts = [Point::new(0.0, 0.0), Point::new(f64::from(n) * 4.0, 0.0)];
|
||||
let reach = DragReach::new(&pts, 12.0);
|
||||
let share = (MAX_REACH_PIECES / segments_in_reach(&PathData::single(tiny.clone()), &reach).max(1)).max(1);
|
||||
let mut shared = MAX_REACH_PIECES;
|
||||
let measured = pieces_measured(|| {
|
||||
mark_reached(&tiny, &reach, (share, &mut shared));
|
||||
});
|
||||
assert_eq!(measured, 140_000, "each segment is measured whole once");
|
||||
// An arch 1,000 pt wide and 300 pt high, with the drag on it a quarter of the way along.
|
||||
let arch = CubicBez::new(Point::new(0.0, 0.0), Point::new(0.0, 400.0), Point::new(1000.0, 400.0), Point::new(1000.0, 0.0));
|
||||
let sp = chain(&[arch]);
|
||||
let hit = [arch.eval(0.25)];
|
||||
assert!(dist_to_polyline(&hit, arch.eval(0.5)) > 12.0, "the arch's middle is out of reach");
|
||||
let mut spent = 0;
|
||||
let (out, marked) = mark_reached(&sp, &DragReach::new(&hit, 12.0), (MAX_REACH_PIECES, &mut spent));
|
||||
assert_eq!(out.anchors.len(), 3, "{out:?}");
|
||||
assert_eq!(marked, vec![false, true, false]);
|
||||
assert!(out.anchors[1].p.distance(hit[0]) <= 12.0, "{out:?}");
|
||||
}
|
||||
|
||||
/// A small piece of curve is measured only against the few stretches of a drag of 100,000
|
||||
@@ -1384,14 +1497,14 @@ mod tests {
|
||||
assert!(in_reach > 0 && boxes < 100_000, "{in_reach} segments in reach, {boxes} measures");
|
||||
let share = (MAX_REACH_PIECES / in_reach).max(1);
|
||||
let mut got = None;
|
||||
let marks = stretch_tests(|| got = Some(mark_reached(&sp, &reach, share)));
|
||||
let marks = stretch_tests(|| got = Some(mark_reached(&sp, &reach, (share, &mut { MAX_REACH_PIECES }))));
|
||||
assert!(marks < 100_000, "{marks} measures");
|
||||
let smoothed = smooth_subpath(&sp, &reach, share, 2.5, 4.0);
|
||||
let smoothed = smooth_subpath(&sp, &reach, (share, &mut { MAX_REACH_PIECES }), 2.5, 4.0);
|
||||
assert!(smoothed.is_some());
|
||||
let all = linear(&pts, 12.0);
|
||||
assert_eq!(segments_in_reach(&pd, &all), in_reach);
|
||||
assert_eq!(Some(mark_reached(&sp, &all, share)), got);
|
||||
assert_eq!(smooth_subpath(&sp, &all, share, 2.5, 4.0), smoothed);
|
||||
assert_eq!(Some(mark_reached(&sp, &all, (share, &mut { MAX_REACH_PIECES }))), got);
|
||||
assert_eq!(smooth_subpath(&sp, &all, (share, &mut { MAX_REACH_PIECES }), 2.5, 4.0), smoothed);
|
||||
}
|
||||
|
||||
/// Paths and drags of many shapes, a drag of one point, one far away, one with a stretch longer
|
||||
@@ -1444,10 +1557,20 @@ mod tests {
|
||||
let in_reach = segments_in_reach(&pd, &all);
|
||||
assert_eq!(segments_in_reach(&pd, &grid), in_reach, "path {k}, reach {radius}, drag {:?}", pts.first());
|
||||
let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1);
|
||||
assert_eq!(mark_reached(sp, &grid, share), mark_reached(sp, &all, share), "path {k}, reach {radius}, drag {:?}", pts.first());
|
||||
assert_eq!(
|
||||
mark_reached(sp, &grid, (share, &mut { MAX_REACH_PIECES })),
|
||||
mark_reached(sp, &all, (share, &mut { MAX_REACH_PIECES })),
|
||||
"path {k}, reach {radius}, drag {:?}",
|
||||
pts.first()
|
||||
);
|
||||
let sigma = radius * SMOOTH_SPREAD;
|
||||
let want = smooth_subpath(sp, &all, share, 2.5, sigma);
|
||||
assert_eq!(smooth_subpath(sp, &grid, share, 2.5, sigma), want, "path {k}, reach {radius}, drag {:?}", pts.first());
|
||||
let want = smooth_subpath(sp, &all, (share, &mut { MAX_REACH_PIECES }), 2.5, sigma);
|
||||
assert_eq!(
|
||||
smooth_subpath(sp, &grid, (share, &mut { MAX_REACH_PIECES }), 2.5, sigma),
|
||||
want,
|
||||
"path {k}, reach {radius}, drag {:?}",
|
||||
pts.first()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -815,6 +815,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
turned.recost_paints();
|
||||
st.history.redo.push(turned);
|
||||
st.history.trim();
|
||||
st.history_restores += 1;
|
||||
st.revision += 1;
|
||||
st.selection.prune(&st.doc);
|
||||
// Guides locked and slices locked or hidden since the step was made stay deselected.
|
||||
@@ -822,7 +823,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
st.sync_new_art();
|
||||
super::maskedit::follow_history(st, editing);
|
||||
super::symboledit::follow_history(st, editing_symbol.as_ref());
|
||||
leave_isolation_if_gone(st);
|
||||
st.leave_isolation_if_gone();
|
||||
super::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
if let Some((before, _)) = paints {
|
||||
@@ -852,13 +853,14 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
turned.recost_paints();
|
||||
st.history.undo.push(turned);
|
||||
st.history.trim();
|
||||
st.history_restores += 1;
|
||||
st.revision += 1;
|
||||
st.selection.prune(&st.doc);
|
||||
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
st.sync_new_art();
|
||||
super::maskedit::follow_history(st, editing);
|
||||
super::symboledit::follow_history(st, editing_symbol.as_ref());
|
||||
leave_isolation_if_gone(st);
|
||||
st.leave_isolation_if_gone();
|
||||
super::globaledit::follow_history(st);
|
||||
st.drop_stale_variables_highlight();
|
||||
if let Some((_, after)) = paints {
|
||||
@@ -867,15 +869,6 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "redone": label }))
|
||||
}
|
||||
|
||||
/// After undo or redo, isolation mode ends when the isolated object is no longer in the document,
|
||||
/// such as the clip group Draw Inside made around the isolated object (#3705), rather than naming
|
||||
/// an id a later object may take.
|
||||
fn leave_isolation_if_gone(st: &mut crate::DocState) {
|
||||
if st.isolation.is_some_and(|i| st.doc.node(i).is_none()) {
|
||||
st.isolation = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// History panel › Clear History: removes the steps after the current state and the steps before
|
||||
/// it, and leaves the document as it is. Typing or a drag still in progress is first kept as a
|
||||
/// step, as Undo keeps it, so it is removed with the others and its change stays in the document.
|
||||
@@ -958,8 +951,12 @@ fn shared_selection(selection: vectorcraft_doc::Selection, like: Option<&crate::
|
||||
/// instance as it is. Copy copies the instance whole ([`copy_cut_targets`]).
|
||||
pub(crate) fn selected_roots(s: &Session) -> Result<Vec<NodeId>> {
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
Ok(roots_of(&st.doc, st.selection.in_paint_order(&st.doc)))
|
||||
Ok(selection_roots(s.doc()?))
|
||||
}
|
||||
|
||||
/// [`selected_roots`] of one document's selection.
|
||||
pub(crate) fn selection_roots(st: &crate::DocState) -> Vec<NodeId> {
|
||||
roots_of(&st.doc, st.selection.in_paint_order(&st.doc))
|
||||
}
|
||||
|
||||
/// [`super::brushsym::part_only`] while an object of a dynamic symbol instance's art is selected:
|
||||
@@ -1590,6 +1587,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
for xf in placements {
|
||||
for (k, n) in clip.nodes.iter().enumerate() {
|
||||
let mut c = d.reid(n);
|
||||
// A pasted object never goes in as a clip group's clipping path, so a copied clipping
|
||||
// path comes back as an ordinary path that the path commands work on (#9227).
|
||||
if let NodeKind::Path { clipping, .. } = &mut c.kind {
|
||||
*clipping = false;
|
||||
}
|
||||
// A pasted symbol set packs from the density recorded for it at Copy.
|
||||
d.carry_set_densities(n, &c, &clip.set_densities);
|
||||
imported.apply(&mut c, d);
|
||||
|
||||
@@ -213,7 +213,7 @@ enum Merge {
|
||||
Append,
|
||||
}
|
||||
|
||||
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?, mode, apply?, base?}`.
|
||||
/// File Info › Import: `file.info.applyTemplate {path?|name?|data?|dataBase64?, mode, apply?, base?}`.
|
||||
pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mode = match text_param(p, "mode", APPLY)? {
|
||||
Some("replace") => Merge::Replace,
|
||||
@@ -236,15 +236,14 @@ pub(crate) fn apply_template(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The bytes of the template `p` names: `path`, `name` (in the metadata templates folder) or
|
||||
/// `data`, exactly one, at most [`MAX_TEMPLATE_FILE`] long.
|
||||
/// Reads one template source from `p` up to [`MAX_TEMPLATE_FILE`] bytes.
|
||||
fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
|
||||
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?];
|
||||
let given = [text_param(p, "path", APPLY)?, text_param(p, "name", APPLY)?, text_param(p, "data", APPLY)?, text_param(p, "dataBase64", APPLY)?];
|
||||
// At most one byte past the limit is read, so a huge file is never read whole.
|
||||
let read = |path: &str| super::fileio::read_file_head(path, MAX_TEMPLATE_FILE + 1);
|
||||
let bytes = match given {
|
||||
[Some(path), None, None] => read(path)?,
|
||||
[None, Some(name), None] => {
|
||||
[Some(path), None, None, None] => read(path)?,
|
||||
[None, Some(name), None, None] => {
|
||||
let dir = s.metadata_templates_dir().ok_or_else(|| bad(APPLY, "no metadata templates folder here"))?;
|
||||
let mut path = template_path(dir, name, APPLY)?;
|
||||
// A template `file.info.templates` lists: by its `file` first, then by its `name` with
|
||||
@@ -268,9 +267,15 @@ fn template_bytes(s: &Session, p: &Value) -> Result<Vec<u8>> {
|
||||
// The app's own folder: no root applies.
|
||||
crate::file_access::unconfined(|| read(&path))?
|
||||
}
|
||||
[None, None, Some(data)] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
|
||||
[None, None, Some(data)] => data.as_bytes().to_vec(),
|
||||
_ => return Err(bad(APPLY, "give one of `path`, `name` and `data`")),
|
||||
[None, None, Some(data), None] if data.len() > MAX_TEMPLATE_FILE => return Err(too_big(APPLY)),
|
||||
[None, None, Some(data), None] => data.as_bytes().to_vec(),
|
||||
[None, None, None, Some(data)] => {
|
||||
if data.len() > MAX_TEMPLATE_FILE.div_ceil(3) * 4 {
|
||||
return Err(too_big(APPLY));
|
||||
}
|
||||
vectorcraft_format::base64_decode(data).ok_or_else(|| bad(APPLY, "dataBase64 is not base64"))?
|
||||
}
|
||||
_ => return Err(bad(APPLY, "give one of `path`, `name`, `data` or `dataBase64`")),
|
||||
};
|
||||
if bytes.len() > MAX_TEMPLATE_FILE {
|
||||
return Err(too_big(APPLY));
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
//! - `metafile`: EMF and WMF export, open and place; PICT open and place.
|
||||
//! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, and `.cmx` files with
|
||||
//! 32-bit coordinates, open and place.
|
||||
//! - `cmx`: `.cmx` export (a page for each chosen artboard, a layer for each layer with art on it).
|
||||
//! - `hpgl`: HP-GL export options and plots.
|
||||
//! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no
|
||||
//! built-in format reads).
|
||||
@@ -31,6 +32,7 @@ mod action_batch;
|
||||
mod affinity;
|
||||
mod batch;
|
||||
mod cdr;
|
||||
mod cmx;
|
||||
pub mod dxf;
|
||||
pub mod dxfimport;
|
||||
mod encode;
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
//! `.cmx` exchange files for every path that writes them (`craft_cdr::write_cmx`):
|
||||
//! `document.export {format: cmx}` and Export As. The chosen artboard (default the first) is the
|
||||
//! file's page; with Use Artboards each chosen artboard (default all) is a page of one file. Each
|
||||
//! top-level layer with art over a page is a layer of that page, holding that art as
|
||||
//! [`vectorcraft_metafile::painted_layers`] gives it: fills and strokes in their colors (CMYK, RGB,
|
||||
//! gray, spot colors with their tints and Registration), type as glyph outlines, and gradients and
|
||||
//! patterns as one color. What the file can't hold comes back in the warnings.
|
||||
|
||||
use craft_cdr::Limits;
|
||||
use craft_cdr::model as cd;
|
||||
use kurbo::PathEl;
|
||||
use serde_json::Value;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::{Document, LineCap, LineJoin, StrokeLayer};
|
||||
use vectorcraft_geom::{BezPath, FillRule, Point};
|
||||
use vectorcraft_metafile::Painted;
|
||||
|
||||
use super::super::{Result, bad};
|
||||
use super::{ArtboardPick, Encoded, FormatOption};
|
||||
|
||||
const C: &str = "document.export";
|
||||
|
||||
/// The options `document.formats` lists for CMX.
|
||||
pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS, super::RANGE, super::USE_ARTBOARDS];
|
||||
|
||||
const IMAGES: &str = "placed images are left out of CMX files";
|
||||
const NONZERO: &str = "fills that use the nonzero fill rule are written even-odd: where a shape crosses itself, or parts of it that turn the same way overlap, they may leave holes";
|
||||
const SPLIT: &str = "paths with more than 7,281 points were written as several curves: their fills where their parts overlap, and their strokes where the curves meet, may draw differently";
|
||||
const PAST_PAGE: &str = "art that crosses the edge of a page is written whole, including the part past the edge";
|
||||
const DASHES: &str = "dash and gap lengths were rounded to whole stroke widths, the unit CMX files store them in";
|
||||
const CUT: &str = "filled shapes with a part of more than 7,281 points were written as open pieces of that part, so their fills draw differently";
|
||||
const ZERO_TINTS: &str = "spot colors at a low tint were written in the color they print at that tint, so their ink's color may open changed";
|
||||
const LONG_NAMES: &str = "layer and spot color names longer than 256 characters open again shortened";
|
||||
const UNNAMED_SPOTS: &str = "spot colors without a name were written as process colors";
|
||||
const UNKNOWN_LOOKS: &str = "spot colors whose color is not known were written as black at their tints";
|
||||
const MERGED_LOOKS: &str = "spot colors that share a name but not a color were all written in one of those colors";
|
||||
const LEFT_OUT: &str = "art the file can't hold was left out";
|
||||
const DASH_OFFSETS: &str = "dash offsets are left out: dashes start at the start of each path";
|
||||
const ALIGNED_DASHES: &str = "dashes aligned to corners and path ends are written as plain dashes";
|
||||
const MITER_LIMITS: &str = "miter limits are left out: mitered corners open again with a miter limit of 10";
|
||||
|
||||
/// Encode `doc` as CMX: one file with a page for the chosen artboard (default the first), or with
|
||||
/// `use_artboards` a page for each chosen artboard (default all), in the order they are chosen.
|
||||
pub(super) fn encode(doc: &Document, f: &super::Format, p: &Value, use_artboards: Option<bool>) -> Result<Encoded> {
|
||||
let pick: ArtboardPick = super::encode::options(f, p)?;
|
||||
let n = doc.artboards.len();
|
||||
let boards = match use_artboards {
|
||||
Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()),
|
||||
_ => vec![pick.one(n).map_err(|e| bad(C, e))?],
|
||||
};
|
||||
if boards.is_empty() {
|
||||
return Err(bad(C, "the document has no artboard"));
|
||||
}
|
||||
let rects = boards
|
||||
.iter()
|
||||
.map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?;
|
||||
let mut warnings = Vec::new();
|
||||
let mut note = |w: &str| {
|
||||
if !warnings.iter().any(|x: &String| x == w) {
|
||||
warnings.push(w.to_string());
|
||||
}
|
||||
};
|
||||
let mut pages = Vec::with_capacity(rects.len());
|
||||
for r in &rects {
|
||||
let art = vectorcraft_metafile::painted_layers(doc, *r).map_err(|e| bad(C, e))?;
|
||||
art.warnings.iter().for_each(|w| note(w));
|
||||
if art.images {
|
||||
note(IMAGES);
|
||||
}
|
||||
// The file has no clipping the reader reads, so art is not cut at the page's edge.
|
||||
let edge = r.abs().inflate(PAGE_EDGE_TOLERANCE, PAGE_EDGE_TOLERANCE);
|
||||
// A stroke reaches half its width past its path.
|
||||
let past = |bp: &BezPath, reach: f64| {
|
||||
let b = kurbo::Shape::bounding_box(bp).inflate(reach, reach);
|
||||
!bp.elements().is_empty() && (b.x0 < edge.x0 || b.y0 < edge.y0 || b.x1 > edge.x1 || b.y1 > edge.y1)
|
||||
};
|
||||
if art.layers.iter().flat_map(|(_, p)| p).any(|op| match op {
|
||||
Painted::Fill { path, .. } => past(path, 0.0),
|
||||
Painted::Stroke { path, width, .. } => past(path, width.max(0.0) / 2.0),
|
||||
}) {
|
||||
note(PAST_PAGE);
|
||||
}
|
||||
let page = Page { center: r.abs().center() };
|
||||
// The model lists layers and objects front to back; the document paints them back to front.
|
||||
// A layer with nothing drawn on the page is left out, as the reader leaves out a layer that
|
||||
// holds nothing.
|
||||
let layers = art
|
||||
.layers
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|(name, painted)| (name, page.objects(&art.swatches, painted, &mut note)))
|
||||
.filter(|(_, objects)| !objects.is_empty())
|
||||
.map(|(name, objects)| cd::Layer {
|
||||
name: name.clone(),
|
||||
kind: cd::LayerKind::Drawing,
|
||||
flags: cd::Flags::default(),
|
||||
objects: objects.into_iter().rev().collect(),
|
||||
guides: Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
pages.push(cd::Page { size: Some((r.width().abs(), r.height().abs())), layers });
|
||||
}
|
||||
let drawing = cd::Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: Vec::new() };
|
||||
// The limits `document.open` reads `.cmx` files with, so the file opens whole again.
|
||||
let written = craft_cdr::write_cmx(&drawing, Limits::default()).map_err(|e| bad(C, e.to_string()))?;
|
||||
for (set, w) in [
|
||||
(written.nonzero_fills, NONZERO),
|
||||
(written.split_paths, SPLIT),
|
||||
(written.cut_subpaths, CUT),
|
||||
(written.long_names, LONG_NAMES),
|
||||
(written.zero_tints, ZERO_TINTS),
|
||||
(written.rounded_dashes, DASHES),
|
||||
(written.unnamed_spots, UNNAMED_SPOTS),
|
||||
(written.unknown_looks, UNKNOWN_LOOKS),
|
||||
(written.merged_looks, MERGED_LOOKS),
|
||||
(written.left_out, LEFT_OUT),
|
||||
] {
|
||||
if set {
|
||||
note(w);
|
||||
}
|
||||
}
|
||||
let mut enc = Encoded::one(written.bytes);
|
||||
enc.warnings = warnings;
|
||||
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(&rects)));
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
/// A page's placement: document space (y down) to the page's coordinates (from its center, y up).
|
||||
struct Page {
|
||||
center: Point,
|
||||
}
|
||||
|
||||
impl Page {
|
||||
fn pt(&self, p: Point) -> cd::Pt {
|
||||
cd::Pt { x: p.x - self.center.x, y: self.center.y - p.y }
|
||||
}
|
||||
|
||||
/// `bp` in the page's coordinates. A quadratic segment becomes the cubic that draws it.
|
||||
fn path(&self, bp: &BezPath) -> cd::Path {
|
||||
let mut subpaths: Vec<cd::SubPath> = Vec::new();
|
||||
// The current point and the start of the current subpath, in document space.
|
||||
let (mut last, mut start) = (Point::ZERO, Point::ZERO);
|
||||
for el in bp.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
subpaths.push(cd::SubPath { start: self.pt(p), segments: Vec::new(), closed: false });
|
||||
(last, start) = (p, p);
|
||||
}
|
||||
PathEl::LineTo(p) => {
|
||||
self.segment(&mut subpaths, last, cd::Segment::Line(self.pt(p)));
|
||||
last = p;
|
||||
}
|
||||
PathEl::QuadTo(c, p) => {
|
||||
let (c1, c2) = (last + (c - last) * (2.0 / 3.0), p + (c - p) * (2.0 / 3.0));
|
||||
self.segment(&mut subpaths, last, cd::Segment::Cubic(self.pt(c1), self.pt(c2), self.pt(p)));
|
||||
last = p;
|
||||
}
|
||||
PathEl::CurveTo(c1, c2, p) => {
|
||||
self.segment(&mut subpaths, last, cd::Segment::Cubic(self.pt(c1), self.pt(c2), self.pt(p)));
|
||||
last = p;
|
||||
}
|
||||
PathEl::ClosePath => {
|
||||
if let Some(s) = subpaths.last_mut() {
|
||||
s.closed = true;
|
||||
}
|
||||
last = start;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A subpath of a lone point draws nothing.
|
||||
subpaths.retain(|s| !s.segments.is_empty());
|
||||
cd::Path { subpaths }
|
||||
}
|
||||
|
||||
/// Add `seg` to the open subpath, or to a new one from `from` after a close.
|
||||
fn segment(&self, subpaths: &mut Vec<cd::SubPath>, from: Point, seg: cd::Segment) {
|
||||
match subpaths.last_mut() {
|
||||
Some(s) if !s.closed => s.segments.push(seg),
|
||||
_ => subpaths.push(cd::SubPath { start: self.pt(from), segments: vec![seg], closed: false }),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fills and strokes of one layer as shapes, in paint order. A fill followed by a stroke of
|
||||
/// the same path is one shape with both. A path with no segments draws nothing and is left out.
|
||||
fn objects(&self, swatches: &[Swatch], painted: &[Painted], note: &mut impl FnMut(&str)) -> Vec<cd::Object> {
|
||||
let mut out = Vec::with_capacity(painted.len());
|
||||
let mut i = 0;
|
||||
while let Some(op) = painted.get(i) {
|
||||
i += 1;
|
||||
let shape = match op {
|
||||
Painted::Fill { path, rule, rgb, paint } => {
|
||||
let outline = match painted.get(i) {
|
||||
Some(s @ Painted::Stroke { path: stroked, .. }) if stroked == path => {
|
||||
i += 1;
|
||||
outline(swatches, s, note)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let fill = color(swatches, *rgb, paint.as_ref());
|
||||
let mut shape = cd::Shape::new(cd::Geometry::Path(self.path(path)), cd::Matrix::IDENTITY, Some(fill), outline);
|
||||
shape.nonzero = *rule == FillRule::NonZero;
|
||||
shape
|
||||
}
|
||||
Painted::Stroke { path, .. } => {
|
||||
cd::Shape::new(cd::Geometry::Path(self.path(path)), cd::Matrix::IDENTITY, None, outline(swatches, op, note))
|
||||
}
|
||||
};
|
||||
if matches!(&shape.geometry, cd::Geometry::Path(p) if p.subpaths.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
out.push(cd::Object::Shape(Box::new(shape)));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// How far (points) a path may reach past its page before the export says art crosses the edge.
|
||||
const PAGE_EDGE_TOLERANCE: f64 = 0.01;
|
||||
|
||||
/// The outline of a stroke: its width, color, cap, join and dashes in stroke widths. The file holds
|
||||
/// no miter limit, so a mitered stroke with a limit other than the one a stroke opens with is
|
||||
/// named in the warnings.
|
||||
fn outline(swatches: &[Swatch], p: &Painted, note: &mut impl FnMut(&str)) -> Option<cd::Outline> {
|
||||
let Painted::Stroke { rgb, paint, width, cap, join, miter, dash, .. } = p else { return None };
|
||||
if *join == LineJoin::Miter && *miter != StrokeLayer::new(Paint::None, *width).miter_limit {
|
||||
note(MITER_LIMITS);
|
||||
}
|
||||
let dashes = match dash {
|
||||
Some(d) if *width > 0.0 => {
|
||||
if d.offset != 0.0 {
|
||||
note(DASH_OFFSETS);
|
||||
}
|
||||
if d.align_corners {
|
||||
note(ALIGNED_DASHES);
|
||||
}
|
||||
d.pattern.iter().map(|x| x / width).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
Some(cd::Outline {
|
||||
width: *width,
|
||||
color: color(swatches, *rgb, paint.as_ref()),
|
||||
cap: match cap {
|
||||
LineCap::Butt => cd::Cap::Butt,
|
||||
LineCap::Round => cd::Cap::Round,
|
||||
LineCap::Square => cd::Cap::Square,
|
||||
},
|
||||
join: match join {
|
||||
LineJoin::Miter => cd::Join::Miter,
|
||||
LineJoin::Round => cd::Join::Round,
|
||||
LineJoin::Bevel => cd::Join::Bevel,
|
||||
},
|
||||
dashes,
|
||||
behind_fill: false,
|
||||
scale_with: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The color a fill or stroke is written in: Registration, a spot color at its tint with the look
|
||||
/// of its swatch among `swatches`, or the solid color in its own model (Lab as RGB); `rgb` for the
|
||||
/// one color of a gradient or pattern.
|
||||
fn color(swatches: &[Swatch], rgb: [u8; 3], paint: Option<&Paint>) -> cd::Color {
|
||||
let from_rgb = |[r, g, b]: [u8; 3]| cd::Color::Rgb([r, g, b].map(|v| f32::from(v) / 255.0));
|
||||
let Some(Paint::Solid { color, swatch, tint }) = paint else { return from_rgb(rgb) };
|
||||
if swatch.as_deref() == Some(REGISTRATION) {
|
||||
return cd::Color::Registration;
|
||||
}
|
||||
if let Some(s) = swatch.as_deref().and_then(|name| swatches.iter().find(|s| s.name == name)).filter(|s| s.spot) {
|
||||
let look = s.paint.color().map(|c| {
|
||||
let [r, g, b, _] = c.to_rgba8(1.0);
|
||||
[r, g, b].map(|v| f32::from(v) / 255.0)
|
||||
});
|
||||
return cd::Color::Spot { name: s.name.clone(), tint: tint.clamp(0.0, 1.0), look };
|
||||
}
|
||||
match *color {
|
||||
Color::Rgb { r, g, b } => cd::Color::Rgb([r, g, b]),
|
||||
Color::Cmyk { c, m, y, k } => cd::Color::Cmyk([c, m, y, k]),
|
||||
Color::Gray { k } => cd::Color::Gray(k),
|
||||
Color::Lab { .. } => from_rgb(rgb),
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Serialize Document",
|
||||
[],
|
||||
None,
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)",
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked)",
|
||||
has_doc,
|
||||
export::serialize
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), d
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|cmx|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), …cmx writes one file with a page for the artboard (useArtboards: true a page for each chosen artboard, false the bounds of the visible art; a layer for each
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Selection…",
|
||||
["File"],
|
||||
None,
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})",
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|cmx|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg, svgz and the files that carry the native document are refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them (an image among the selected objects), as document.export refuses them. In the app, with no params or {}, the save panel picks the file and its format's options dialog follows (Save PDF, SVG Options, the raster options, EPS Options, DXF Options, Text Export Options or an exporter plug-in's parameters; other formats are written at once), whose OK writes the selection: the call returns null while the dialog is open, and OK returns what file.exportAs returns, without format or bounds (Text Export Options: {path})",
|
||||
has_selection,
|
||||
export::export_selection
|
||||
),
|
||||
|
||||
@@ -1069,7 +1069,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
|
||||
}
|
||||
// Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so
|
||||
// themselves: SVG only when it outlines or embeds fonts).
|
||||
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl"))
|
||||
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl" | "cmx"))
|
||||
&& let Some(w) = crate::cmd::fonts::substitution_warning(doc)
|
||||
{
|
||||
enc.warnings.push(w);
|
||||
@@ -1110,7 +1110,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
let doc = &*doc.without_edit_modes();
|
||||
let n = doc.artboards.len();
|
||||
// SVG reads its own `useArtboards` (an SVG option).
|
||||
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(C, p)? } else { None };
|
||||
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl" | "cmx") { use_artboards(C, p)? } else { None };
|
||||
// `rect`: that area of the page, as if it were the only artboard (the document is not changed).
|
||||
if let Some(rect) = page_rect(f, p)? {
|
||||
let mut q = super::export::without_artboards(p);
|
||||
@@ -1156,6 +1156,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
"emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf),
|
||||
"wmf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Wmf),
|
||||
"hpgl" => return super::hpgl::encode(doc, p, use_artboards),
|
||||
"cmx" => return super::cmx::encode(doc, f, p, use_artboards),
|
||||
"ai" => return super::save::encode_ai(C, f, doc, p),
|
||||
"pdf" => {
|
||||
let (bytes, notes) = super::pdf::encode(C, doc, p)?;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::super::unique_name;
|
||||
use super::{
|
||||
Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, dxf, eps, hpgl, json, metafile, native, pdf, screens, svg, text,
|
||||
Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, cmx, dxf, eps, hpgl, json, metafile, native, pdf, screens, svg, text,
|
||||
unsupported,
|
||||
};
|
||||
|
||||
@@ -553,9 +553,9 @@ pub const FORMATS: &[Format] = &[
|
||||
// them.
|
||||
reader("cdr", "CDR Drawing", &["cdr"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type
|
||||
reader("cdt", "CDR Template", &["cdt"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type
|
||||
// `.cmx` exchange files with 32-bit coordinates, read by `craft-cdr`; exports don't write
|
||||
// them.
|
||||
reader("cmx", "CMX", &["cmx"], "image/x-cmx", false),
|
||||
// `.cmx` exchange files with 32-bit coordinates, read and written by `craft-cdr`: a page for
|
||||
// each chosen artboard, with the art's fills and strokes in their colors.
|
||||
Format { id: "cmx", label: "CMX", extensions: &["cmx"], mime: "image/x-cmx", read: true, write: true, raster: false, options: cmx::OPTIONS },
|
||||
// QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images.
|
||||
reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false),
|
||||
];
|
||||
|
||||
@@ -196,7 +196,7 @@ pub(super) fn name_without_device(name: &str) -> String {
|
||||
pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"];
|
||||
|
||||
/// The writable formats a format row can't name.
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 6] = ["template", "txt", "dxf", "emf", "wmf", "hpgl"];
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 7] = ["template", "txt", "dxf", "emf", "wmf", "hpgl", "cmx"];
|
||||
|
||||
/// One format row: what to write, at which size, with which suffix, into which sub-folder.
|
||||
struct Row {
|
||||
|
||||
@@ -532,7 +532,8 @@ fn export_extensions_name_every_writable_format() {
|
||||
"wmf",
|
||||
"plt",
|
||||
"tga",
|
||||
"psd"
|
||||
"psd",
|
||||
"cmx"
|
||||
]
|
||||
);
|
||||
for e in exts {
|
||||
@@ -568,7 +569,8 @@ fn formats_query_lists_readers_writers_and_options() {
|
||||
"wmf",
|
||||
"hpgl",
|
||||
"tga",
|
||||
"psd"
|
||||
"psd",
|
||||
"cmx"
|
||||
]
|
||||
);
|
||||
assert!(ids("readable").contains(&"tiff".to_string()) && ids("readable").contains(&"ait".to_string()));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! `.cmx` files: Open and Place, by extension and by content, mapped to artboards, layers, groups,
|
||||
//! paths, solid paint and strokes, with their warnings and refusals.
|
||||
//! paths, solid paint and strokes, with their warnings and refusals; and export, read back.
|
||||
|
||||
use super::*;
|
||||
use craft_cdr::synth_cmx::*;
|
||||
@@ -61,7 +61,7 @@ fn detection_by_content_and_place() {
|
||||
s.execute("file.place", &json!({"name":"art.cmx", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty()));
|
||||
let f = format("cmx").unwrap();
|
||||
assert!(f.read && !f.write);
|
||||
assert!(f.read && f.write);
|
||||
assert!(OPEN_EXTS.contains(&"cmx") && PLACE_EXTS.contains(&"cmx") && UNASSOCIATED_EXTS.contains(&"cmx"));
|
||||
assert!(!SAVE_FORMATS.contains(&"cmx"));
|
||||
}
|
||||
@@ -123,6 +123,183 @@ fn files_that_are_not_read_say_why() {
|
||||
assert!(e.contains("this CMX file can't be read (not a CMX file)"), "{e}");
|
||||
}
|
||||
|
||||
fn b64(v: &serde_json::Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap()
|
||||
}
|
||||
|
||||
/// Two artboards of 200 x 100 pt. The first layer holds a CMYK rectangle with a dashed gray stroke on
|
||||
/// the first; layer "Front" a 40 % tint of spot ink "Gold" on the first and an RGB stroke on the
|
||||
/// second.
|
||||
fn drawn() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2, "colorMode": "cmyk"})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Gold", "color": {"model": "cmyk", "c": 0.0, "m": 0.2, "y": 0.8, "k": 0.1}, "spot": true})).unwrap();
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect.x0;
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 40, "height": 30})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": {"model": "cmyk", "c": 0.6, "m": 0.1, "y": 0.0, "k": 0.2}})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": {"model": "gray", "k": 0.5}})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 2, "dash": [6, 2]})).unwrap();
|
||||
s.execute("layer.new", &json!({"name": "Front"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 100, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"swatch": "Gold", "tint": 40})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": second + 5.0, "y": 5, "width": 10, "height": 10})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#3366cc"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 1})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Every path of a document with its bounds relative to the artboard it is on.
|
||||
fn placed(s: &Session) -> Vec<(Node, vectorcraft_geom::Rect)> {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let mut all = Vec::new();
|
||||
paths(&doc.layers, &mut all);
|
||||
all.into_iter()
|
||||
.map(|n| {
|
||||
let b = doc.bounds_of(&[n.id], false).unwrap();
|
||||
let board = doc.artboards.iter().find(|a| a.rect.contains(b.center())).map_or(vectorcraft_geom::Rect::ZERO, |a| a.rect);
|
||||
(n, b - board.origin().to_vec2())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exported_cmx_file_opens_with_its_pages_layers_colors_and_strokes() {
|
||||
let mut s = drawn();
|
||||
let r = s.execute("document.export", &json!({"format": "cmx", "useArtboards": true})).unwrap();
|
||||
assert_eq!(r["format"], "cmx");
|
||||
assert!(warnings(&r).is_empty(), "{r}");
|
||||
let bytes = b64(&r);
|
||||
assert!(craft_cdr::is_cmx(&bytes), "one file holds both pages");
|
||||
let mut back = Session::new();
|
||||
let opened = open_bytes(&mut back, "drawing.cmx", &bytes, None).unwrap();
|
||||
assert!(warnings(&opened).is_empty(), "{opened}");
|
||||
let doc = &back.doc().unwrap().doc;
|
||||
let sizes: Vec<(f64, f64)> = doc.artboards.iter().map(|a| (a.rect.width().round(), a.rect.height().round())).collect();
|
||||
assert_eq!(sizes, [(200.0, 100.0), (200.0, 100.0)]);
|
||||
let names: Vec<String> = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
let was: Vec<String> = s.doc().unwrap().doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
||||
assert_eq!(names, was, "the layers keep their names and order");
|
||||
let was = placed(&s);
|
||||
let now = placed(&back);
|
||||
assert_eq!(was.len(), now.len());
|
||||
for ((_, a), (_, b)) in was.iter().zip(&now) {
|
||||
assert!((a.x0 - b.x0).abs() < 0.01 && (a.y0 - b.y0).abs() < 0.01 && (a.x1 - b.x1).abs() < 0.01, "{a:?} {b:?}");
|
||||
}
|
||||
let fill = |n: &Node| n.appearance.fill().map(|f| f.paint.clone());
|
||||
let stroke = |n: &Node| n.appearance.stroke().cloned();
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let cmyk = &now[0].0;
|
||||
assert!(matches!(fill(cmyk).and_then(|p| p.color()), Some(Color::Cmyk { c, .. }) if (c - 0.6).abs() < 0.006), "{:?}", fill(cmyk));
|
||||
let st = stroke(cmyk).unwrap();
|
||||
assert!((st.width - 2.0).abs() < 1e-3 && matches!(st.paint.color(), Some(Color::Gray { k }) if (k - 0.5).abs() < 0.005));
|
||||
// Widths are stored to 0.1 µm.
|
||||
let dash = st.dash.as_ref().map(|d| d.pattern.clone()).unwrap_or_default();
|
||||
assert!(dash.len() == 2 && (dash[0] - 6.0).abs() < 1e-3 && (dash[1] - 2.0).abs() < 1e-3, "{dash:?}");
|
||||
let gold = &now[1].0;
|
||||
assert!(matches!(fill(gold), Some(Paint::Solid { swatch: Some(n), tint, .. }) if n == "Gold" && (tint - 0.4).abs() < 0.006), "{:?}", fill(gold));
|
||||
assert!(doc.swatch("Gold").is_some_and(|g| g.spot));
|
||||
let line = &now[2].0;
|
||||
assert!(fill(line).is_none_or(|p| p == Paint::None));
|
||||
// The document converted the RGB color to its CMYK mode; the file keeps the CMYK values.
|
||||
let (Some(Color::Cmyk { c, m, y, k }), Some(Color::Cmyk { c: c2, m: m2, y: y2, k: k2 })) =
|
||||
(stroke(&was[2].0).unwrap().paint.color(), stroke(line).unwrap().paint.color())
|
||||
else {
|
||||
panic!("not CMYK: {:?}", stroke(line))
|
||||
};
|
||||
assert!([c - c2, m - m2, y - y2, k - k2].iter().all(|d| d.abs() < 0.006));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_artboard_is_one_page_and_what_cmx_leaves_out_is_named() {
|
||||
let mut s = drawn();
|
||||
let bytes = b64(&s.execute("document.export", &json!({"format": "cmx", "artboard": 1})).unwrap());
|
||||
let d = craft_cdr::read_cmx(&bytes, craft_cdr::Limits::default()).unwrap();
|
||||
assert_eq!(d.pages.len(), 1);
|
||||
let shapes: usize = d.pages[0].layers.iter().map(|l| l.objects.len()).sum();
|
||||
assert_eq!(shapes, 1, "only the art over the second artboard");
|
||||
assert_eq!(b64(&s.execute("document.serialize", &json!({"format": "cmx", "artboard": 1})).unwrap()), bytes);
|
||||
// A gradient is written as one color, and a placed image is left out.
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 60, "width": 10, "height": 10})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
let png = vectorcraft_format::base64_encode(&tiny_png());
|
||||
s.execute("file.place", &json!({"name": "dot.png", "dataBase64": png, "x": 150, "y": 60})).unwrap();
|
||||
let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap());
|
||||
assert!(w.iter().any(|w| w.contains("gradients are written as one colour")), "{w:?}");
|
||||
assert!(w.iter().any(|w| w == "placed images are left out of CMX files"), "{w:?}");
|
||||
assert!(w.iter().all(|w| !w.contains("edge of a page")), "{w:?}");
|
||||
// Art across the artboard's edge is written whole, and the warnings say so.
|
||||
s.execute("shape.rectangle", &json!({"x": 190, "y": 90, "width": 20, "height": 20})).unwrap();
|
||||
let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap());
|
||||
assert!(w.iter().any(|w| w.contains("edge of a page")), "{w:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nonzero_fill_that_would_fill_differently_even_odd_is_named() {
|
||||
let nonzero = |w: &[String]| w.iter().any(|w| w.contains("nonzero"));
|
||||
let export = |d: &str, rule: &str| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("path.create", &json!({"d": d})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#cc3333"})).unwrap();
|
||||
s.execute("path.setFillRule", &json!({"rule": rule})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "cmx"})).unwrap();
|
||||
let shapes: Vec<craft_cdr::model::Shape> = craft_cdr::read_cmx(&b64(&r), craft_cdr::Limits::default())
|
||||
.unwrap()
|
||||
.pages
|
||||
.into_iter()
|
||||
.flat_map(|p| p.layers)
|
||||
.flat_map(|l| l.objects)
|
||||
.filter_map(|o| match o {
|
||||
craft_cdr::model::Object::Shape(s) => Some(*s),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
(warnings(&r), shapes)
|
||||
};
|
||||
// Two squares that overlap and turn the same way leave a hole where they overlap even-odd.
|
||||
let overlapping = "M10 10 L50 10 L50 50 L10 50 Z M30 30 L70 30 L70 70 L30 70 Z";
|
||||
let (w, shapes) = export(overlapping, "nonZero");
|
||||
assert!(nonzero(&w), "{w:?}");
|
||||
assert!(shapes.len() == 1 && shapes[0].fill.is_some(), "{shapes:?}");
|
||||
// The same shape filled even-odd is written as it fills.
|
||||
assert!(!nonzero(&export(overlapping, "evenOdd").0));
|
||||
// A counter that turns the other way inside its shape fills the same either way.
|
||||
let counter = "M10 10 L50 10 L50 50 L10 50 Z M20 20 L20 40 L40 40 L40 20 Z";
|
||||
assert!(!nonzero(&export(counter, "nonZero").0));
|
||||
// Type exported from a document gives no warning about the fill rule.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Bob 80"})).unwrap();
|
||||
let w = warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap());
|
||||
assert!(!nonzero(&w), "{w:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_miter_limit_the_file_cannot_hold_is_named() {
|
||||
let miter = |w: &[String]| w.iter().any(|w| w.contains("miter limit"));
|
||||
let export = |join: &str, limit: f64| {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 40, "height": 30})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#3366cc"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 4, "join": join, "miterLimit": limit})).unwrap();
|
||||
warnings(&s.execute("document.export", &json!({"format": "cmx"})).unwrap())
|
||||
};
|
||||
assert!(miter(&export("miter", 2.0)));
|
||||
// The limit a stroke opens with again, and corners that are not mitered, lose nothing.
|
||||
assert!(!miter(&export("miter", 10.0)));
|
||||
assert!(!miter(&export("round", 2.0)));
|
||||
}
|
||||
|
||||
/// A 1 x 1 PNG.
|
||||
fn tiny_png() -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_without_a_name_is_named_by_its_place() {
|
||||
// An empty layer, which is left out, then a layer named only by spaces: it comes in unnamed,
|
||||
|
||||
@@ -124,6 +124,17 @@ impl StopOwner {
|
||||
}
|
||||
}
|
||||
|
||||
/// The drawing paints affected by an edit from the Gradient panel.
|
||||
#[derive(PartialEq)]
|
||||
pub struct GradientEditPaints(Vec<EditedPaint>);
|
||||
|
||||
#[derive(PartialEq)]
|
||||
struct EditedPaint {
|
||||
id: NodeId,
|
||||
item: Option<usize>,
|
||||
paints: Vec<Paint>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Does `paint.editGradient` without `ids` edit objects on the fill (or the stroke, `stroke`)? It does not
|
||||
/// while the active tool paints with the chosen fill (or stroke: [`Session::tool_paints`]) or when nothing it
|
||||
@@ -136,6 +147,36 @@ impl Session {
|
||||
.is_ok_and(|item| item.of_kind(self, !stroke).targets_for(self, &p, !stroke).is_ok_and(|ids| !ids.is_empty()))
|
||||
}
|
||||
|
||||
/// Snapshot the paints a gradient edit without explicit targets would write, by object and
|
||||
/// appearance item. Text without an item has one paint per run. The proxy can display just
|
||||
/// the first paint when an edit goes to several objects or text runs.
|
||||
pub fn gradient_edit_paints(&self, stroke: bool) -> Result<GradientEditPaints> {
|
||||
const CMD: &str = "paint.editGradient";
|
||||
let p = json!({ "stroke": stroke });
|
||||
if super::paint::for_tool(self, &p, stroke) {
|
||||
return Ok(GradientEditPaints(Vec::new()));
|
||||
}
|
||||
let doc = &self.doc()?.doc;
|
||||
let item = item_target(self, &p, CMD)?.of_kind(self, !stroke);
|
||||
let ids = item.targets_for(self, &p, !stroke)?;
|
||||
let ids = super::appearance::drop_design_art_rows(self, ids, item, !stroke, CMD)?;
|
||||
let mut out = Vec::with_capacity(ids.len());
|
||||
for (id, item) in ids.iter().copied().zip(item.per_target(self, &ids)) {
|
||||
let (Some(node), Some(item)) = (doc.node(id), item) else { continue };
|
||||
let index = item.resolve(&node.appearance, !stroke, CMD)?;
|
||||
let (item, paints) = if index.is_none()
|
||||
&& let NodeKind::Text(text) = &node.kind
|
||||
{
|
||||
(None, text.runs.iter().map(|run| if stroke { run.style.stroke.clone() } else { run.style.fill.clone() }).collect())
|
||||
} else {
|
||||
let item = index.or_else(|| node.appearance.items.iter().rposition(|row| row.is_fill() != stroke));
|
||||
(item, node.appearance.paint_at(index, !stroke).cloned().into_iter().collect())
|
||||
};
|
||||
out.push(EditedPaint { id, item, paints });
|
||||
}
|
||||
Ok(GradientEditPaints(out))
|
||||
}
|
||||
|
||||
/// The selected gradient stop (`gradient.selectStop`), while the gradient it was selected on
|
||||
/// is still the one behind the active proxy. Callers check it against the stop count (an undo
|
||||
/// can remove stops).
|
||||
|
||||
@@ -6013,6 +6013,58 @@ fn a_symbol_pasted_with_a_graph_inside_draws_it_with_the_documents_design_of_tha
|
||||
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
|
||||
}
|
||||
|
||||
/// A symbol a loaded look or text style brings, through the pattern it paints with, draws its
|
||||
/// graph with the document's design of that name, as a pasted one does.
|
||||
#[test]
|
||||
fn a_symbol_a_loaded_look_or_text_style_brings_draws_its_graph_with_the_documents_design() {
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_coin_design(&mut src);
|
||||
let id = graph(&mut src, "column");
|
||||
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
src.execute("graph.column", &json!({"design": "Coin"})).unwrap();
|
||||
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let instance = src.execute("symbol.new", &json!({"name": "Chart"})).unwrap()["id"].clone();
|
||||
src.execute("object.pattern.make", &json!({"name": "Charts", "edit": false, "ids": [instance]})).unwrap();
|
||||
let r = src.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
|
||||
src.execute("paint.setFill", &json!({"swatch": "Charts", "ids": [r]})).unwrap();
|
||||
let t = src.execute("text.create", &json!({"x": 10, "y": 80, "text": "Charts"})).unwrap()["id"].clone();
|
||||
src.execute("paint.setFill", &json!({"swatch": "Charts", "ids": [t]})).unwrap();
|
||||
src.execute("charStyle.new", &json!({"name": "Charted", "id": t})).unwrap();
|
||||
let source = (*src.doc().unwrap().doc).clone();
|
||||
let look = source.node(NodeId(r)).unwrap().appearance.clone();
|
||||
assert!(source.pattern("Charts").is_some());
|
||||
|
||||
let paths = |n: &vectorcraft_doc::Node| {
|
||||
let mut count = 0;
|
||||
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
|
||||
count
|
||||
};
|
||||
let columns = |d: &vectorcraft_doc::Document| -> Vec<usize> {
|
||||
let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art;
|
||||
let mut graphs = vec![];
|
||||
art.walk(&mut |m| {
|
||||
if m.extras().graph.is_some() {
|
||||
graphs.push(m.clone());
|
||||
}
|
||||
});
|
||||
series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect()
|
||||
};
|
||||
for styles in [false, true] {
|
||||
// A document whose "Coin" is a rectangle and an ellipse.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Coin");
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
if styles {
|
||||
crate::cmd::clipboard::resources::import_text_styles(&source, d, true, false).unwrap();
|
||||
} else {
|
||||
crate::cmd::clipboard::resources::import_looks(&source, d, &look, &serde_json::Map::new()).unwrap();
|
||||
}
|
||||
assert_eq!(columns(d), [2, 2, 2, 2], "styles {styles}: drawn with the document's design");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_design_brought_in_from_a_library_redraws_the_graphs_in_symbols_that_name_it() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -76,6 +76,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
relink
|
||||
),
|
||||
cmd!(
|
||||
"links.replaceEmbedded",
|
||||
"Replace Image",
|
||||
[],
|
||||
None,
|
||||
"{ids: [canvas image ids], dataBase64: raster file bytes} replace the images with embedded pixels, keeping their ids and fitting their new aspect ratio inside their old bounds. Distorted images keep their corners. One undo step → {replaced: [ids]}",
|
||||
has_doc,
|
||||
replace_embedded
|
||||
),
|
||||
cmd!(
|
||||
query "links.list",
|
||||
"Links",
|
||||
@@ -1248,6 +1257,28 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
|
||||
install(d, &[id], read, Some(Preserve::Bounds), None)
|
||||
}
|
||||
|
||||
/// The browser's Replace Image uses embedded bytes and the same Fit installer as a path-based replacement.
|
||||
fn replace_embedded(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "links.replaceEmbedded";
|
||||
let ids = ids_param(p, "ids", C)?.filter(|ids| !ids.is_empty()).ok_or_else(|| bad(C, "give the image ids to replace"))?;
|
||||
let doc = &s.doc()?.doc;
|
||||
let mut seen = BTreeSet::new();
|
||||
for id in &ids {
|
||||
if !seen.insert(*id) {
|
||||
return Err(bad(C, format!("image {} is listed twice", id.0)));
|
||||
}
|
||||
if !doc.node(*id).is_some_and(|node| matches!(node.kind, NodeKind::Image(_))) {
|
||||
return Err(bad(C, format!("object {} is not an image", id.0)));
|
||||
}
|
||||
}
|
||||
let data = text_param(p, "dataBase64", C)?.ok_or_else(|| bad(C, "give dataBase64"))?;
|
||||
let bytes = vectorcraft_format::base64_decode(data).ok_or_else(|| bad(C, "bad dataBase64"))?;
|
||||
let mut img = fileio::raster_image(&bytes)?;
|
||||
img.blob = readable_and_kept(img.blob, kept_unread(&bytes), false)?;
|
||||
s.edit("Replace Image", |d, _| install_with(d, &ids, None, img, Some(Preserve::Fit), None, false))?;
|
||||
Ok(json!({ "replaced": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
/// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels
|
||||
/// fill them. Its transform is scaled to the new pixel size, so a reader that places it by the
|
||||
/// transform still gives it its old size. Its Placement Options do not apply. The result is what
|
||||
@@ -1256,13 +1287,19 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
|
||||
/// new file (`img.clip`, else the path kept in its stored PNG or TIFF, as Unembed writes it:
|
||||
/// [`file_clip`]) are mapped to the page through its corners, anchors and handles alike, as a
|
||||
/// distort maps a path's.
|
||||
fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo {
|
||||
fn refill_distorted(
|
||||
n: &mut Node,
|
||||
old_clip: Option<&FileClip>,
|
||||
link: Option<&LinkInfo>,
|
||||
img: &RasterImage,
|
||||
held: Option<(&PathData, FillRule)>,
|
||||
) -> ClipTo {
|
||||
let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule)));
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 {
|
||||
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height));
|
||||
}
|
||||
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone()));
|
||||
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, link.cloned());
|
||||
}
|
||||
let file = img.clip.clone().or_else(|| file_clip(&img.blob)).and_then(|(path, rule)| Some((warped(&path, &n.image_map()?)?, rule)));
|
||||
placed_clip_to(old.as_ref(), None, file, held)
|
||||
@@ -1292,8 +1329,8 @@ fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
|
||||
/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say);
|
||||
/// with `also` (a file's path and the content shown), so do the images outside the layer tree that
|
||||
/// show that content.
|
||||
fn install(d: &mut Document, ids: &[NodeId], read: FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
|
||||
install_with(d, ids, read, force, also, false)
|
||||
fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option<Preserve>, also: Option<(&str, &str)>) -> Result<()> {
|
||||
install_with(d, ids, Some(&link), img, force, also, false)
|
||||
}
|
||||
|
||||
/// What Unembed (`unembed`) does with the clip `to` of an image whose clip group holding just it
|
||||
@@ -1307,11 +1344,13 @@ fn unembed_clip(to: ClipTo, held: bool) -> ClipTo {
|
||||
}
|
||||
}
|
||||
|
||||
/// As [`install`]; with `unembed`, each clip goes through [`unembed_clip`].
|
||||
/// Installs raster pixels with their filesystem link, if any. With `unembed`, each clip goes
|
||||
/// through [`unembed_clip`].
|
||||
fn install_with(
|
||||
d: &mut Document,
|
||||
ids: &[NodeId],
|
||||
(link, img): FileRead,
|
||||
link: Option<&LinkInfo>,
|
||||
img: RasterImage,
|
||||
force: Option<Preserve>,
|
||||
also: Option<(&str, &str)>,
|
||||
unembed: bool,
|
||||
@@ -1341,7 +1380,7 @@ fn install_with(
|
||||
NodeKind::Image(im) => old.get(&im.key).and_then(|(_, clip)| clip.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held);
|
||||
let clip = refill_distorted(&mut n, old_clip.as_ref(), link, &img, held);
|
||||
return (n, keep(clip, held.is_some()));
|
||||
}
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
@@ -1353,7 +1392,7 @@ fn install_with(
|
||||
};
|
||||
let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o);
|
||||
clip = keep(clip_to(im.xf, old_clip, c, &img, xf, held), held.is_some());
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned());
|
||||
}
|
||||
(n, clip)
|
||||
};
|
||||
@@ -1367,7 +1406,7 @@ fn install_with(
|
||||
};
|
||||
let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule));
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
let clip = refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule)));
|
||||
let clip = refill_distorted(n, old_clip.as_ref(), link, &img, held.as_ref().map(|(path, rule)| (path, *rule)));
|
||||
clips.push((*id, keep(clip, held.is_some())));
|
||||
}
|
||||
continue;
|
||||
@@ -1384,12 +1423,12 @@ fn install_with(
|
||||
if let Some(n) = d.node_mut(*id)
|
||||
&& let NodeKind::Image(im) = &mut n.kind
|
||||
{
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone()));
|
||||
(im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, link.cloned());
|
||||
}
|
||||
}
|
||||
// A DCS file's spot plates print on spot swatches of their inks.
|
||||
super::place::dcs::add_spot_swatches(d, &img.blob.spot_plates());
|
||||
store_image(d, &img.key, img.blob, true);
|
||||
store_image(d, &img.key, img.blob, link.is_some());
|
||||
clips.into_iter().try_for_each(|(id, clip)| match clip {
|
||||
ClipTo::Keep => Ok(()),
|
||||
ClipTo::Path(path) => clip_image_to(d, id, path),
|
||||
@@ -2881,9 +2920,9 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Read before writing: pixels that can't be read leave no file behind.
|
||||
let img = linked_image(&bytes, Some(&path))?;
|
||||
write_file(&path, &bytes)?;
|
||||
let read = (link_info(&path, &bytes), img);
|
||||
let link = link_info(&path, &bytes);
|
||||
drop(doc);
|
||||
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))?;
|
||||
s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true)))?;
|
||||
Ok(json!({ "id": id.0, "path": path }))
|
||||
}
|
||||
|
||||
@@ -2950,7 +2989,9 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Re
|
||||
drop(doc);
|
||||
let done: Vec<Value> = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect();
|
||||
let edited = s.edit("Unembed", |d, _| {
|
||||
editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))
|
||||
editing_brush_art(d, |d| {
|
||||
reads.into_iter().try_for_each(|(id, (link, img))| install_with(d, &[id], Some(&link), img, Some(Preserve::Bounds), None, true))
|
||||
})
|
||||
});
|
||||
if let Err(e) = edited {
|
||||
remove_written(&written);
|
||||
|
||||
@@ -406,6 +406,20 @@ fn edit_blends(s: &mut Session, label: &str, f: impl Fn(&mut Vec<Arc<Node>>, &mu
|
||||
ok()
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Whether Blend Options would operate on selected artwork rather than new-blend defaults.
|
||||
pub fn has_selected_blend(&self) -> bool {
|
||||
super::common::any_selected_of(self, is_blend, |_| true)
|
||||
}
|
||||
|
||||
/// The blends Blend Options edits, in ID order regardless of their selection order.
|
||||
pub fn selected_blend_ids(&self) -> Vec<NodeId> {
|
||||
let mut ids = selected_of(self, is_blend);
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
}
|
||||
}
|
||||
|
||||
/// The first selected blend: its id, spec and key ids.
|
||||
fn selected_spec(s: &Session) -> Option<(NodeId, BlendSpec, Vec<NodeId>)> {
|
||||
let b = *selected_of(s, is_blend).first()?;
|
||||
|
||||
@@ -199,7 +199,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Envelope Info",
|
||||
[],
|
||||
None,
|
||||
"{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, version (a warp's map: 1, each style as one Bézier patch; 0, the earlier map), rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}",
|
||||
"{} the selected envelope's settings, or with none selected the defaults new envelopes get → {id: n|null, type: warp|mesh|topObject, style, bend, h, v, horizontal, version (a warp's map: 1, each style as one Bézier patch; 0, the earlier map), rows, cols, fidelity, antiAlias, preserveShape: clippingMask|transparency, distortAppearance, distortLinearGradients, distortPatternFills, boundsMargin?: [top, bottom, left, right] (shares of the content's height and width, a side shorter than 1e-6 pt taking the other side's, reported only when not zero: with distortAppearance, how far the box the content maps from reaches past its geometric bounds), editing}",
|
||||
has_doc,
|
||||
env_info
|
||||
),
|
||||
|
||||
@@ -675,6 +675,9 @@ fn transform_each_as(s: &mut Session, p: &Value, label: &str) -> Result<Value> {
|
||||
// Five draws whatever the scales are, so a seed gives the moves and the rotation
|
||||
// the same values whether a side is scaled or not.
|
||||
let [r_sh, r_sv, r_mh, r_mv, r_rot] = [rng.next(), rng.next(), rng.next(), rng.next(), rng.next()];
|
||||
// The same horizontal and vertical scale take one share, so the object scales
|
||||
// evenly (#9320).
|
||||
let r_sv = if sh == sv { r_sh } else { r_sv };
|
||||
k_sh = k_sh.map(|v| 1.0 + (v - 1.0) * r_sh);
|
||||
k_sv = k_sv.map(|v| 1.0 + (v - 1.0) * r_sv);
|
||||
k_mh = mh * (r_mh * 2.0 - 1.0);
|
||||
|
||||
Loaded 100 of 729 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user