Merge main into fix/test262-promise-async-markers

This commit is contained in:
dotCooCoo committed 2026-11-28 00:59:20 -08:00
commit 3c54a02fab
855 files changed
+80462 -6268

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
name: Cache prune
# A pass of the cache prune after every CI attempt on main. ci.yml's `cache prune` job prunes while
# a run's jobs save their entries, but "Re-run failed jobs" re-runs only the failed jobs: a re-run
# `cache warm` leg saves a new entry, and the prune job, which succeeded in the first attempt, does
# not run again. The entry it replaced would stay until the next main run, and with it the cache
# would be over its 10 GB budget, where GitHub evicts entries a run still needs. This runs once
# after every attempt, re-runs and canceled runs included (craft-common-actions actions/cache-prune).
on:
workflow_run:
workflows: [CI]
types: [completed]
branches: [main]
permissions:
contents: read
jobs:
cache-prune:
name: cache prune
# A fork's pull request from a branch named main also matches `branches`.
if: github.event.workflow_run.event != 'pull_request'
timeout-minutes: 10
runs-on: ubuntu-24.04
permissions:
actions: write
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
# A failed pass warns; the next run's prune deletes what it missed.
- name: Prune replaced cache entries
uses: storytold/craft-common-actions/actions/cache-prune@main
continue-on-error: true
+70 -2
View File
@@ -1,10 +1,14 @@
name: CI
# Quality gates for every push to main and every pull request (`cargo xtask ci`), through the
# suite's shared gate workflow in craft-common-actions.
# suite's shared gate workflow in craft-common-actions. Every night the gate runs a cold build:
# the safety net for the workspace crates it keeps between runs (`cache-workspace-crates`), and a
# fresh start for that cache entry.
on:
push:
branches: [main]
schedule:
- cron: "37 3 * * *"
pull_request:
workflow_dispatch:
@@ -23,7 +27,10 @@ jobs:
with:
# Same craft-fonts commit as release.yml.
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
timeout-minutes: 90
# A cold `cache warm` leg (the nightly run, or any run after a toolchain or lockfile change)
# took 90 minutes to reach its last three steps on 2026-11-27 and was canceled there; with
# those steps and the save it needs about two hours.
timeout-minutes: 150
# The gate's test binaries carry no debug info and no symbols (CARGO_PROFILE_TEST_DEBUG=0,
# CARGO_PROFILE_TEST_STRIP=symbols), as photocraft's do: linking ~100 test binaries with line
# tables ran the hosted runner out of resources, and it stopped mid-link with "received a
@@ -39,7 +46,68 @@ jobs:
test-shards: 5
shard-command: cargo xtask ci shard
warm-command: cargo xtask ci warm
# The dependency cache also keeps the compiled workspace crates and test executables, so a
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
# `cache-prune` below deletes the one it replaced. The nightly run restores nothing and
# builds everything from source.
cache-workspace-crates: true
cold-build: ${{ github.event_name == 'schedule' }}
packages: >-
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev
libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
libgl1-mesa-dev
# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache
# budget. It runs beside the gate and prunes each time the `cache warm` leg finishes saving. A
# failed prune warns instead of failing the run, and cache-prune.yml prunes again after every
# attempt, re-runs of failed jobs included. `watch-minutes` is longer than the gate's
# `timeout-minutes`, so the watch outlasts a cold `cache warm` leg.
cache-prune:
name: cache prune
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
runs-on: ubuntu-24.04
timeout-minutes: 170
permissions:
actions: write
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- name: Prune replaced cache entries
uses: storytold/craft-common-actions/actions/cache-prune@main
continue-on-error: true
with:
watch: true
watch-minutes: 160
saving-jobs: |
^gate( / cache warm \(.*\))?$
# The nightly cold run never restores the rolling crates entry, so the old entry is only overlap
# while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the
# 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
# When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run
# failed jobs" runs it again beside the re-run leg. The script's 160-minute wait starts when the leg
# starts, which is after `gate / select legs` and a free runner, so this job's timeout leaves
# 40 minutes for that.
cold-cache-clear:
name: cold cache clear
if: github.event_name == 'schedule'
runs-on: ubuntu-24.04
timeout-minutes: 200
permissions:
actions: write
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Delete the old rolling entries before the save
env:
GH_TOKEN: ${{ github.token }}
run: python3 scripts/ci-clear-rolling-cache.py
+6 -3
View File
@@ -3,13 +3,14 @@ name: Nightly check
# The app-side Nightly pieces, checked without a feed run: the Python suites that read the archive,
# plist and signing scripts, the workflow contracts, and (on Windows) the packaging and signing
# PowerShell suites. The producer itself is .github/workflows/nightly.yml; the Apple-silicon bundle
# is built and verified by nightly-macos.yml behind the `full-ci` label.
# is built and verified by nightly-macos.yml behind the `full-ci` label. The same job also runs the
# suite for scripts/ci-clear-rolling-cache.py, which ci.yml's nightly cold run calls.
on:
push:
branches: [main, release]
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"]
pull_request:
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"]
workflow_dispatch:
permissions:
@@ -34,6 +35,8 @@ jobs:
persist-credentials: false
- name: Run the synthetic suites
run: python3 packaging/nightly-tests.py
- name: Run the cold cache clear suite
run: python3 scripts/ci-clear-rolling-cache-tests.py
- name: Parse every nightly shell script
run: |
set -euo pipefail
+20
View File
@@ -0,0 +1,20 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+10 -1
View File
@@ -16,6 +16,15 @@
| `crates/text/patterns/hyph-or.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-or.tex | MIT (selected option) | Unmodified; full license in file |
| `crates/text/patterns/hyph-as.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-as.tex | MIT (selected option) | Unmodified; full license in file |
## Printing-condition characterization data
Fogra's terms (https://fogra.org/en/downloads/work-tools/characterisation-data): "Free use and redistribution of the Fogra characterisation data is permitted, including redistribution as part of commercial and non-commercial software, provided that the data are distributed unmodified and Fogra is identified as the source. The designation FOGRAxx may be used solely to identify the respective reference data. Such use does not imply certification, approval or endorsement by Fogra." VectorCraft computes its Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52) working spaces from these files at run time; the files themselves are not changed.
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
| `crates/color/data/FOGRA51.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5`, checked by a test) |
| `crates/color/data/FOGRA52.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6`, checked by a test) |
Every non-code asset in this repository (icons, images, fonts, example art, colour profiles, presets) is listed here with its author, source and licence. `cargo xtask assets` (part of `cargo xtask ci`) fails if an asset file is missing from this table.
**Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
@@ -24,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
+213 -106
View File
File diff suppressed because it is too large. Load diff
+48 -48
View File
@@ -11,44 +11,44 @@ rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
# The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON.
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
# the members it imports.
craft = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
# Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui
# without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes.
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -191,25 +191,25 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+13
View File
@@ -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:
@@ -152,6 +154,17 @@ Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option.
Original copyright and full license notices are preserved in each hyph-*.tex file.
Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5.
FOGRA51 and FOGRA52 characterization data (crates/color/data/):
Source: Fogra Forschungsgesellschaft Druck e.V., www.fogra.org,
https://fogra.org/en/downloads/work-tools/characterisation-data. The files are distributed
unmodified. Fogra's terms: "Free use and redistribution of the Fogra characterisation data is
permitted, including redistribution as part of commercial and non-commercial software, provided
that the data are distributed unmodified and Fogra is identified as the source. The designation
FOGRAxx may be used solely to identify the respective reference data. Such use does not imply
certification, approval or endorsement by Fogra." VectorCraft's Coated CMYK (FOGRA51) and
Uncoated CMYK (FOGRA52) working spaces are computed from this data by VectorCraft's own code;
they are not Fogra profiles.
JPEG encoder dependency notices
+6
View File
@@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
## Progress log
- 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged.
- 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
@@ -142,8 +144,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-19: Set Fold Angle in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and a Fold Angle field with Reset in the Fold Lines panel): a crease, partial cut or perforation line can fold at its own angle, from -180° to 180°, instead of its role's 90° away from or toward the print; native files keep the angle, and the Fold Preview folds each hinge at the angle of the line with the most length in it (`addon.packaging.setFoldAngle`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
- 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-11-20: Curvature Circle Tool Options (double-click the Curvature Circle tool): Snap Tolerance sets how near a path pulls the pointer, Snap with Smart Guides Off unchecked keeps it within the selection tolerance while Smart Guides are off, Annotate Radius hides the radius label, Anchors at Standard Positions off puts an anchor where the circle touches the path and one every 90° from there, and Use the Radius of Circular Arcs off gives a circular arc's own cubic curvature (`tool.setOption {tool: "curvatureCircle"}`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged.
@@ -151,6 +155,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen editing: with no path being drawn, a drag on an anchor or a segment of a selected path moves it, a line staying a line and an arc an arc beside a moved corner anchor (at a smooth anchor the handles stay in line and the segments bend to meet); a click selects an anchor, Shift-click adds one, and the canvas context menu's Delete removes the selected anchors (`path.moveAnchors`, `edit.clear`; #2660). Headline numbers unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
@@ -252,6 +257,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
| Date | Change | Summary |
|---|---|---|
| 2026-11-20 | minor | Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged. |
| 2026-11-22 | minor | Upcoming: the G11 item names what is left, the unit preference reverting to points (#864; SVG export units are fixed) and a Transform effect in a fill's or stroke's own effects (#885), instead of Shape Builder regions and Asset Export borders, which are fixed (#937, #983 / #1037); its estimate follows docs/roadmap.md and docs/gaps.md, 8–15 → 6–13 h, #8314. The Essentials readiness row's Shape Builder item names what its 4–8 h still covers (checking #937's fix on the reporter's file, still unconfirmed). Headline numbers unchanged. |
| 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). |
| 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. |
+3 -1
View File
@@ -238,11 +238,13 @@ fn main() -> ExitCode {
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's
/// (`script.listInstalled`) and finds its Startup Scripts folder (`script.startup.run`, never run on its own), keeps each
/// script's `Folder.userData` in the Script Data folder there, keeps File Info's
/// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_scripts_dir(&mut h.session);
prefs_dir::attach_startup_scripts_dir(&mut h.session);
prefs_dir::attach_script_data(&mut h.session);
prefs_dir::attach_metadata_templates_dir(&mut h.session);
prefs_dir::attach_new_doc_profiles(&mut h.session);
+1 -1
View File
@@ -27,7 +27,7 @@ log = { workspace = true }
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "b0d422cf0c23baccdaca314b916458a89c0952e0", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "51fcc3b0413af193db952df28dffae2321745703", version = "0.1.0" }
wasm-bindgen = "0.2"
serde_json = { workspace = true }
+198 -15
View File
@@ -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]
+1 -1
View File
@@ -69,7 +69,7 @@ vectorcraft-render = { workspace = true }
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = "0.6"
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSpace", "NSControl", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSpace", "NSControl", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSView", "NSWindow"] }
# Files opened from Finder and the Dock (src/open_documents.rs) and pasted bitmaps (src/clipboard.rs); both already come with winit.
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] }
block2 = "0.6"
-11
View File
@@ -243,14 +243,3 @@ pub(crate) fn open_files(app: &mut VectorcraftApp, files: Vec<String>) {
}
}
}
/// Tell the macOS input method to drop its composition (the Type tool kept the marked text as
/// typed). winit's IME toggle only clears its own copy, so the IME would type it again.
#[cfg(target_os = "macos")]
fn discard_marked_text() {
if let Some(mtm) = objc2::MainThreadMarker::new()
&& let Some(ic) = objc2_app_kit::NSTextInputContext::currentInputContext(mtm)
{
ic.discardMarkedText();
}
}
+286 -144
View File
@@ -4,10 +4,12 @@
//! - Windows: text, SVG, PDF, PNG and an opaque bitmap (for apps that don't read PNG) in one go;
//! Paste reads each of them and EPS, a bitmap as PNG, else as the device-independent bitmap that
//! screenshots and most apps copy (`CF_DIBV5`, `CF_DIB`; the system makes them of a `CF_BITMAP`).
//! - macOS and Linux: one format at a time, the text (a type-only copy's text or the SVG markup),
//! else the PNG as a bitmap; Paste reads text and bitmaps, and on macOS the pasteboard's SVG, PDF
//! and EPS as vector art (#1499) and its PNG or TIFF as they are, as screenshots copy them (on
//! Linux arboard reads no other formats). On Wayland, arboard's data-control
//! - macOS: text, SVG, PDF and PNG in one go: arboard writes the text, else the PNG as TIFF, and
//! the other formats are added to the same pasteboard item ([`pasteboard_additions`]); Paste
//! reads text and bitmaps, the pasteboard's SVG, PDF and EPS as vector art (#1499) and its PNG
//! or TIFF as they are, as screenshots copy them.
//! - Linux: one format at a time, the text (a type-only copy's text or the SVG markup), else the
//! PNG as a bitmap; Paste reads text and bitmaps (arboard reads no other formats). On Wayland, arboard's data-control
//! backend reads the compositor's clipboard (X11 through XWayland only sees what X11 apps
//! copied), falling back to X11 where the compositor lacks the protocol, and where there is no
//! X11 either (a Flatpak on GNOME) to the compositor's core protocol on the window's connection:
@@ -137,6 +139,26 @@ fn pasteboard_types(mime: &str) -> &'static [(&'static str, &'static str)] {
}
}
/// The pasteboard types and data Copy adds on macOS to the item arboard wrote (the text, else the
/// PNG as TIFF), in the order of `flavors` (best first): the SVG, PDF and EPS under the first of
/// their [`pasteboard_types`], and the PNG as `public.png`. Text, empty flavours and flavours the
/// pasteboard has no type for are left out.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn pasteboard_additions(flavors: &[Flavor]) -> Vec<(&'static str, &[u8])> {
flavors
.iter()
.filter(|f| !f.data.is_empty())
.filter_map(|f| {
let t = match engine_mime(&f.mime)? {
TEXT => return None,
PNG => "public.png",
mime => pasteboard_types(mime).first()?.0,
};
Some((t, &f.data[..]))
})
.collect()
}
/// Most pixels a side of a bitmap another app put on the clipboard (untrusted data).
const MAX_SIDE: u32 = 32_768;
@@ -612,9 +634,46 @@ mod loads {
/// The longest a read waits for the clipboard's owner to send its data.
pub(super) const LOAD_WAIT: Duration = Duration::from_secs(2);
/// The longest a paste's bitmap read of arboard's waits for the app that copied, off the UI
/// thread: the bitmap's transfer and its PNG decoding happen within the read. A paste waits as
/// long, from when it was sent, for a read that got no answer in its wait, the core protocol's
/// text read included. Text, file lists and the UI thread's bitmap check wait [`LOAD_WAIT`].
pub(super) const IMAGE_WAIT: Duration = Duration::from_secs(10);
/// What a read says once its worker has stopped.
pub(super) const GONE: &str = "the clipboard's reader stopped";
/// How long the reads of a [`Loads`] wait for the clipboard's owner.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Waits {
/// A text or file-list read, the UI thread's bitmap check, and dropping an idle `Loads`.
pub(super) load: Duration,
/// A paste's bitmap read off the UI thread, and a paste's wait for a read that got no
/// answer in its wait.
pub(super) image: Duration,
}
impl Waits {
/// [`LOAD_WAIT`] and [`IMAGE_WAIT`].
pub(super) const APP: Self = Self { load: LOAD_WAIT, image: IMAGE_WAIT };
/// No limit: each wait ends when its answer comes or its worker stops.
#[cfg(test)]
pub(super) const UNTIL_ANSWERED: Self = Self { load: Duration::MAX, image: Duration::MAX };
}
/// What is left at `now` of `limit` from `sent`; [`Duration::MAX`] (no limit) when the end is
/// past the clock's range.
pub(super) fn left(sent: Instant, limit: Duration, now: Instant) -> Duration {
sent.checked_add(limit).map_or(Duration::MAX, |end| end.saturating_duration_since(now))
}
/// What comes on `rx` within `wait`; a wait whose end is past the clock's range has no limit.
fn recv_within<T>(rx: &mpsc::Receiver<T>, wait: Duration) -> Result<T, mpsc::RecvTimeoutError> {
match Instant::now().checked_add(wait) {
Some(_) => rx.recv_timeout(wait),
None => rx.recv().map_err(mpsc::RecvTimeoutError::from),
}
}
/// Requests of type `R` answered with `A` on a worker thread.
pub(super) struct Loads<R, A> {
/// The worker's requests; the worker stops once this is dropped.
@@ -623,6 +682,8 @@ mod loads {
done: mpsc::Receiver<()>,
/// How long after it was sent dropping `Loads` waits for an unanswered read to end.
finish: Duration,
/// How long its reads wait.
waits: Waits,
}
/// Where requests go to a [`Loads`] worker.
@@ -685,18 +746,18 @@ mod loads {
}
}
/// When dropping `Loads` stops waiting for its worker: `finish` after the unanswered read
/// `pending` was sent (at once if that time has passed), and with no read unanswered
/// [`LOAD_WAIT`] from `now` at most (an idle worker ends at once).
fn stop_by(pending: Option<Instant>, now: Instant, finish: Duration) -> Instant {
pending.map_or(now + LOAD_WAIT, |sent| sent + finish)
/// How long, from `now`, dropping `Loads` waits for its worker: until `finish` after the
/// unanswered read `pending` was sent (not at all if that time has passed), and with no read
/// unanswered `idle` at most (an idle worker ends at once).
fn stop_wait(pending: Option<Instant>, now: Instant, finish: Duration, idle: Duration) -> Duration {
pending.map_or(idle, |sent| left(sent, finish, now))
}
impl<R: Send + 'static, A: Send + 'static> Loads<R, A> {
/// A worker thread named `name` that answers each request with `load`; dropping the result
/// waits up to `finish` after an unanswered read was sent for that read to end. None when the
/// worker can't start.
pub(super) fn spawn(name: &str, finish: Duration, mut load: impl FnMut(R) -> A + Send + 'static) -> Option<Self> {
/// A worker thread named `name` that answers each request with `load`, whose reads wait as
/// `waits` says; dropping the result waits up to `finish` after an unanswered read was sent
/// for that read to end. None when the worker can't start.
pub(super) fn spawn(name: &str, finish: Duration, waits: Waits, mut load: impl FnMut(R) -> A + Send + 'static) -> Option<Self> {
let (requests, asked) = mpsc::channel::<(R, mpsc::Sender<A>)>();
let (alive, done) = mpsc::channel::<()>();
let open = Arc::new(AtomicUsize::new(0));
@@ -714,7 +775,12 @@ mod loads {
drop(alive);
};
std::thread::Builder::new().name(name.into()).spawn(work).ok()?;
Some(Self { line: Arc::new(Line { requests, open, sent: Mutex::default() }), done, finish })
Some(Self { line: Arc::new(Line { requests, open, sent: Mutex::default() }), done, finish, waits })
}
/// How long its reads wait.
pub(super) fn waits(&self) -> Waits {
self.waits
}
/// `request` sent to the worker; its answer comes on the channel returned, for
@@ -741,9 +807,10 @@ mod loads {
}
}
/// The answer that comes on `answer` ([`Loads::ask`]), or why there is none, after `wait` at most.
/// The answer that comes on `answer` ([`Loads::ask`]), or why there is none, after `wait` at most
/// ([`Duration::MAX`]: no limit).
pub(super) fn wait_for_answer<A>(answer: &mpsc::Receiver<A>, wait: Duration) -> Result<A, String> {
match answer.recv_timeout(wait) {
match recv_within(answer, wait) {
Ok(answer) => Ok(answer),
Err(mpsc::RecvTimeoutError::Timeout) => Err(format!("the clipboard's owner didn't send its data within {wait:?}")),
Err(mpsc::RecvTimeoutError::Disconnected) => Err(GONE.into()),
@@ -751,16 +818,16 @@ mod loads {
}
impl<R, A> Drop for Loads<R, A> {
/// Stops the worker and waits until it has let go of what its `load` holds, until
/// [`stop_by`] at most: on X11 the last arboard handle dropped hands what the app copied to
/// the clipboard manager, and the app's own handle must be that one.
/// Stops the worker and waits until it has let go of what its `load` holds, as long as
/// [`stop_wait`] says at most: on X11 the last arboard handle dropped hands what the app
/// copied to the clipboard manager, and the app's own handle must be that one.
fn drop(&mut self) {
// No `Asker` sends after this, and one that holds the line lets go once it has sent.
let pending = self.line.close();
drop(std::mem::replace(&mut self.line, Line::dead()));
let end = stop_by(pending, Instant::now(), self.finish);
// Nothing is sent on `done`: this ends when the worker drops `alive`, or at `end`.
let _ = self.done.recv_timeout(end.saturating_duration_since(Instant::now()));
let wait = stop_wait(pending, Instant::now(), self.finish, self.waits.load);
// Nothing is sent on `done`: this ends when the worker drops `alive`, or after `wait`.
let _ = recv_within(&self.done, wait);
}
}
@@ -770,18 +837,38 @@ mod loads {
use super::*;
/// No limit: a wait ends when its answer comes.
const UNTIL_ANSWERED: Duration = Duration::MAX;
#[test]
fn a_read_that_answers_in_time_gives_the_text() {
let mut loads = Loads::spawn("test", Duration::ZERO, |()| "<svg/>".to_string()).unwrap();
assert_eq!(loads.get((), Duration::from_secs(5)), Ok("<svg/>".to_string()));
assert_eq!(loads.get((), Duration::from_secs(5)), Ok("<svg/>".to_string()));
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| "<svg/>".to_string()).unwrap();
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok("<svg/>".to_string()));
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok("<svg/>".to_string()));
}
#[test]
fn a_wait_with_no_limit_ends_when_its_answer_comes() {
let (reply, answer) = mpsc::channel();
let late = std::thread::spawn(move || reply.send(7));
assert_eq!(wait_for_answer(&answer, UNTIL_ANSWERED), Ok(7));
assert_eq!(late.join().ok(), Some(Ok(())));
// A worker that stops without answering ends the wait too.
let (reply, answer) = mpsc::channel::<u8>();
drop(reply);
assert_eq!(wait_for_answer(&answer, UNTIL_ANSWERED), Err(GONE.to_string()));
// Limits from a read's send: what is left, none once it is over, no limit past the clock.
let now = Instant::now();
assert_eq!(left(now, Duration::from_secs(10), now + Duration::from_secs(3)), Duration::from_secs(7));
assert_eq!(left(now, Duration::from_secs(10), now + Duration::from_secs(20)), Duration::ZERO);
assert_eq!(left(now, Duration::MAX, now), Duration::MAX);
}
#[test]
fn an_owner_that_never_answers_holds_the_worker_not_the_caller() {
let (release, gate) = mpsc::channel::<()>();
let mut calls = 0;
let mut loads = Loads::spawn("test", Duration::ZERO, move |()| {
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |()| {
calls += 1;
if calls == 1 {
// The first owner sends nothing until released.
@@ -793,11 +880,11 @@ mod loads {
.unwrap();
assert!(loads.get((), Duration::ZERO).is_err(), "the first read times out");
// While it is unanswered, a read doesn't queue behind it or wait at all.
assert!(loads.get((), Duration::from_secs(600)).is_err());
assert!(loads.get((), UNTIL_ANSWERED).is_err());
release.send(()).unwrap();
// Once the late answer is in, it is dropped and a new read is made.
let text = loop {
match loads.get((), Duration::from_secs(600)) {
match loads.get((), UNTIL_ANSWERED) {
Ok(text) => break text,
Err(why) => {
// The late answer isn't in yet.
@@ -811,17 +898,17 @@ mod loads {
#[test]
fn a_read_after_the_worker_stops_says_so() {
let mut loads = Loads::spawn("test", Duration::ZERO, |()| String::new()).unwrap();
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| String::new()).unwrap();
// The worker ends when its requests stop: cut them off by hand.
drop(std::mem::replace(&mut loads.line, Line::dead()));
assert_eq!(loads.get((), Duration::from_millis(50)), Err(GONE.to_string()));
assert_eq!(loads.get((), UNTIL_ANSWERED), Err(GONE.to_string()));
}
#[test]
fn another_threads_reads_stop_with_the_reads() {
let loads = Loads::spawn("test", Duration::ZERO, |()| 1).unwrap();
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| 1).unwrap();
let asker = loads.asker();
assert_eq!(asker.ask(()).and_then(|a| wait_for_answer(&a, Duration::from_secs(600))), Ok(1));
assert_eq!(asker.ask(()).and_then(|a| wait_for_answer(&a, UNTIL_ANSWERED)), Ok(1));
drop(loads);
assert_eq!(asker.ask(()).err(), Some(GONE.to_string()));
// Closed while an asker still holds the line: nothing more is sent.
@@ -833,7 +920,7 @@ mod loads {
#[test]
fn an_answer_waited_for_on_another_thread_holds_back_the_next_read() {
let (release, gate) = mpsc::channel::<()>();
let mut loads = Loads::spawn("test", Duration::ZERO, move |n: u32| {
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |n: u32| {
if n == 1 {
let _ = gate.recv();
}
@@ -842,20 +929,21 @@ mod loads {
.unwrap();
let answer = loads.ask(1).unwrap();
// The caller doesn't wait: the answer is waited for wherever the channel goes.
let waiter = std::thread::spawn(move || wait_for_answer(&answer, Duration::from_secs(600)));
let waiter = std::thread::spawn(move || wait_for_answer(&answer, UNTIL_ANSWERED));
// Until it comes, a read fails at once instead of queuing behind it.
assert!(loads.get(2, Duration::from_secs(600)).is_err());
assert!(loads.get(2, UNTIL_ANSWERED).is_err());
release.send(()).unwrap();
assert_eq!(waiter.join().ok(), Some(Ok(1)));
assert_eq!(loads.get(3, Duration::from_secs(600)), Ok(3));
assert_eq!(loads.get(3, UNTIL_ANSWERED), Ok(3));
}
#[test]
fn dropping_the_reads_waits_until_the_worker_lets_go_of_its_clipboard() {
let clipboard = Arc::new(());
let held = clipboard.clone();
let mut loads = Loads::spawn("test", Duration::ZERO, move |()| Arc::strong_count(&held)).unwrap();
assert_eq!(loads.get((), Duration::from_secs(600)), Ok(2));
// With no limit on the idle wait, the drop ends only once the worker has let go.
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |()| Arc::strong_count(&held)).unwrap();
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok(2));
drop(loads);
assert_eq!(Arc::strong_count(&clipboard), 1, "the worker's handle is gone before the app's");
}
@@ -865,12 +953,12 @@ mod loads {
let now = Instant::now();
let limit = Duration::from_secs(25);
// No read unanswered: the idle worker ends at once, LOAD_WAIT is only the bound.
assert_eq!(stop_by(None, now, limit), now + LOAD_WAIT);
assert_eq!(stop_wait(None, now, limit, LOAD_WAIT), LOAD_WAIT);
// A read sent 2 s ago that timed out: wait for it until 25 s after it was sent.
assert_eq!(stop_by(Some(now - Duration::from_secs(2)), now, limit), now + Duration::from_secs(23));
assert_eq!(stop_wait(Some(now - Duration::from_secs(2)), now, limit, LOAD_WAIT), Duration::from_secs(23));
// Its limit already over, or no limit (data-control, the core protocol): no wait.
assert!(stop_by(Some(now - Duration::from_secs(30)), now, limit) <= now);
assert_eq!(stop_by(Some(now), now, Duration::ZERO), now);
assert_eq!(stop_wait(Some(now - Duration::from_secs(30)), now, limit, LOAD_WAIT), Duration::ZERO);
assert_eq!(stop_wait(Some(now), now, Duration::ZERO, LOAD_WAIT), Duration::ZERO);
}
}
}
@@ -885,6 +973,8 @@ mod portable {
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
use super::loads::Waits;
use super::{
BITMAP, ClipboardBackend, ClipboardError, ClipboardImage, ClipboardRead, Flavor, Flavour, LaterFlavor, PNG, TEXT, copied_file, decode_png,
engine_mimes, png_flavour, read_flavor, read_image_flavor, read_later_flavor, takes_files,
@@ -991,28 +1081,21 @@ mod portable {
reads.get(request, wait).unwrap_or_else(|why| Answer::failed(request, why))
}
/// The longest a paste's bitmap read of arboard's waits for the app that copied, off the UI
/// thread: the bitmap's transfer and its PNG decoding happen within the read. A paste waits as
/// long, from when it was sent, for a read that got no answer in its wait, the core protocol's
/// text read included. Text, file lists and the UI thread's bitmap check wait
/// [`LOAD_WAIT`](super::loads::LOAD_WAIT).
/// How long a read of `request` waits for the app that copied: `waits.image` for a bitmap,
/// `waits.load` otherwise.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
const IMAGE_WAIT: Duration = Duration::from_secs(10);
/// How long a read of `request` waits for the app that copied.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn wait_for(request: Request) -> Duration {
fn wait_for(waits: Waits, request: Request) -> Duration {
match request {
Request::Image => IMAGE_WAIT,
Request::Text | Request::Files => super::loads::LOAD_WAIT,
Request::Image => waits.image,
Request::Text | Request::Files => waits.load,
}
}
/// How long a paste's read of `request` after a late answer waits at `now`: as long as any read
/// of `request`, or until [`IMAGE_WAIT`] after the unanswered read was `sent` when that is later.
/// of `request`, or until `waits.image` after the unanswered read was `sent` when that is later.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn follow_up_wait(request: Request, sent: Instant, now: Instant) -> Duration {
wait_for(request).max((sent + IMAGE_WAIT).saturating_duration_since(now))
fn follow_up_wait(waits: Waits, request: Request, sent: Instant, now: Instant) -> Duration {
wait_for(waits, request).max(super::loads::left(sent, waits.image, now))
}
/// The longest an X11 read of arboard's lasts while the owner sends nothing: a text read tries
@@ -1063,6 +1146,8 @@ mod portable {
sent: Instant,
/// The worker, for the paste's other reads.
reads: super::loads::Asker<Request, Answer>,
/// How long the worker's reads wait.
waits: Waits,
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
@@ -1078,7 +1163,8 @@ mod portable {
}
/// What a paste of one of `mimes` takes, once this read's answer comes, waiting for it until
/// [`IMAGE_WAIT`] after it was sent, as long as a paste's bitmap read waits. Once it comes,
/// `waits.image` ([`IMAGE_WAIT`](super::loads::IMAGE_WAIT)) after it was sent, as long as a
/// paste's bitmap read waits. Once it comes,
/// the same read is made again, since the clipboard may have changed hands meanwhile.
/// `None`, so the paste takes the internal clipboard, when that answer doesn't come or the
/// new one is what `ours` put on the clipboard. Otherwise the clipboard is read as
@@ -1088,12 +1174,12 @@ mod portable {
/// names a picture (`adopt_system_clipboard_or_defer` in `vectorcraft-ui-egui`). Those reads
/// wait as [`follow_up_wait`] says.
fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option<Flavour> {
let wait = (self.sent + IMAGE_WAIT).saturating_duration_since(Instant::now());
let wait = super::loads::left(self.sent, self.waits.image, Instant::now());
super::loads::wait_for_answer(&self.answer, wait).ok()?;
let fresh = |request: Request| {
self.reads
.ask(request)
.and_then(|a| super::loads::wait_for_answer(&a, follow_up_wait(request, self.sent, Instant::now())))
.and_then(|a| super::loads::wait_for_answer(&a, follow_up_wait(self.waits, request, self.sent, Instant::now())))
.unwrap_or_else(|why| Answer::failed(request, why))
};
// The late answer may come from an app that lost the clipboard while it was awaited.
@@ -1139,14 +1225,15 @@ mod portable {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
impl Late {
/// What a paste of one of `mimes` takes once the answer comes ([`Unanswered::paste`]). The
/// core protocol's answer is waited for as long, until [`IMAGE_WAIT`] after its read was
/// sent; then the clipboard is read again and pasted as at once, unless it holds the Copy
/// made here ([`super::wayland::Unanswered::paste`]).
/// core protocol's answer is waited for as long, until
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) after its read was sent; then the clipboard is
/// read again and pasted as at once, unless it holds the Copy made here
/// ([`super::wayland::Unanswered::paste`]).
fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option<Flavour> {
match self {
Self::Arboard(unanswered) => unanswered.paste(ours, mimes),
#[cfg(target_os = "linux")]
Self::Wayland(unanswered) => unanswered.paste(mimes, IMAGE_WAIT),
Self::Wayland(unanswered) => unanswered.paste(mimes),
}
}
}
@@ -1163,8 +1250,9 @@ mod portable {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
{
let mut reader = arboard::Clipboard::new().map_err(|e| e.to_string())?;
let reads = super::loads::Loads::spawn("clipboard-read", finish(on_data_control()), move |request| answer(&mut reader, request))
.ok_or("the clipboard's reader didn't start")?;
let reads =
super::loads::Loads::spawn("clipboard-read", finish(on_data_control()), Waits::APP, move |request| answer(&mut reader, request))
.ok_or("the clipboard's reader didn't start")?;
Ok(Self { reads, unanswered: None, cb })
}
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))]
@@ -1181,13 +1269,13 @@ mod portable {
impl<C> Arboard<C> {
/// Reads on the worker; the write handle `C` is not used.
fn read(&mut self, request: Request) -> Answer {
self.read_waiting(request, wait_for(request))
self.read_waiting(request, wait_for(self.reads.waits(), request))
}
/// A bitmap read on the worker that waits [`LOAD_WAIT`](super::loads::LOAD_WAIT) at most, for
/// a check on the UI thread.
fn image_now(&mut self) -> Result<arboard::ImageData<'static>, String> {
self.read_waiting(Request::Image, super::loads::LOAD_WAIT).image()
self.read_waiting(Request::Image, self.reads.waits().load).image()
}
/// `request` read on the worker, waiting `wait` at most. A read that gets no answer in that
@@ -1202,7 +1290,7 @@ mod portable {
Ok(answer) => answer,
Err(why) => {
if why != super::loads::GONE {
self.unanswered = Some(Unanswered { request, answer, sent, reads: self.reads.asker() });
self.unanswered = Some(Unanswered { request, answer, sent, reads: self.reads.asker(), waits: self.reads.waits() });
}
Answer::failed(request, why)
}
@@ -1217,11 +1305,13 @@ mod portable {
Ok(answer)
}
/// A bitmap read sent to the worker now; the work returned waits [`IMAGE_WAIT`] at most for
/// it, so the caller can wait off the UI thread. Err when the read can't be sent.
/// A bitmap read sent to the worker now; the work returned waits
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most for it, so the caller can wait off the UI
/// thread. Err when the read can't be sent.
fn image_later(&mut self) -> Result<ImageWork, String> {
let wait = self.reads.waits().image;
let answer = self.ask(Request::Image)?;
Ok(Box::new(move || super::loads::wait_for_answer(&answer, IMAGE_WAIT).and_then(Answer::image)))
Ok(Box::new(move || super::loads::wait_for_answer(&answer, wait).and_then(Answer::image)))
}
/// The read that got no answer in its wait, while its answer has still not come and a paste
@@ -1503,12 +1593,12 @@ mod portable {
/// Text and copied files are read here, and work that reads arboard's image comes back. On
/// the Wayland core protocol the copied files, else the first of `mimes` the clipboard
/// offers, is read: text here, file lists, SVG and PNG by the work that comes back, which
/// waits [`IMAGE_WAIT`] at most.
/// waits [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most.
fn read_now_or_later(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
let cb = self.cb(Asker::User).ok()?;
#[cfg(target_os = "linux")]
if let Backend::Wayland(cb) = cb {
return cb.read(mimes, IMAGE_WAIT);
return cb.read(mimes);
}
if let Some(f) = copied_file(cb.file_list(), mimes) {
return Some(ClipboardRead::Now(f));
@@ -1554,7 +1644,8 @@ mod portable {
/// arboard takes the text, else the PNG as a bitmap; the Wayland core protocol offers the
/// SVG, PNG and text together ([`DataClipboard::copy`](super::wayland::DataClipboard::copy)).
/// The index answered is the flavour that went out: the text, else the PNG, and on the
/// core protocol the first flavour it offers.
/// core protocol the first flavour it offers. On macOS the other flavours are then added
/// to the pasteboard item arboard wrote ([`pasteboard_additions`](super::pasteboard_additions)).
fn write(&mut self, flavors: &[Flavor]) -> Result<usize, ClipboardError> {
let cb = self.cb(Asker::User).map_err(ClipboardError::Other)?;
#[cfg(target_os = "linux")]
@@ -1591,6 +1682,8 @@ mod portable {
// What a read got late was on the clipboard before this write.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
cb.forget_unanswered();
#[cfg(target_os = "macos")]
super::mac::add(&super::pasteboard_additions(flavors));
self.ours = ours;
Ok(wrote)
}
@@ -1654,9 +1747,12 @@ mod portable {
mod tests {
use std::cell::Cell;
use super::super::loads::Loads;
use super::super::loads::{Loads, Waits};
use super::*;
/// No limit: a wait ends when its answer comes.
const UNTIL_ANSWERED: Duration = Duration::MAX;
/// A clock that starts now and moves only when told.
struct Clock(Cell<Instant>);
@@ -1780,27 +1876,27 @@ mod portable {
fn reads_return_while_the_clipboard_owner_sends_nothing() {
let (release, gate) = std::sync::mpsc::channel::<()>();
// The app that copied never sends its data until released.
let mut reads = Loads::spawn("test", Duration::ZERO, move |request| {
let mut reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| {
let _ = gate.recv();
Answer::failed(request, "late".into())
})
.unwrap();
// Copy's look at the text, Paste's file list and its bitmap: none waits for the owner.
assert!(read_within(&mut reads, Request::Text, Duration::ZERO).text().is_err());
assert!(read_within(&mut reads, Request::Files, Duration::from_secs(600)).files().is_empty());
assert!(read_within(&mut reads, Request::Image, Duration::from_secs(600)).image().is_err());
assert!(read_within(&mut reads, Request::Files, UNTIL_ANSWERED).files().is_empty());
assert!(read_within(&mut reads, Request::Image, UNTIL_ANSWERED).image().is_err());
drop(release);
}
#[test]
fn each_read_takes_its_own_answer() {
let mut reads = Loads::spawn("test", Duration::ZERO, |request| match request {
let mut reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |request| match request {
Request::Text => Answer::Text(Ok("<svg/>".into())),
Request::Image => Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) })),
Request::Files => Answer::Files(vec![PathBuf::from("art.svg")]),
})
.unwrap();
let wait = Duration::from_secs(600);
let wait = UNTIL_ANSWERED;
assert_eq!(read_within(&mut reads, Request::Text, wait).text(), Ok("<svg/>".to_string()));
assert_eq!(read_within(&mut reads, Request::Image, wait).image().map(|i| (i.width, i.height)), Ok((2, 1)));
assert_eq!(read_within(&mut reads, Request::Files, wait).files(), [PathBuf::from("art.svg")]);
@@ -1847,7 +1943,8 @@ mod portable {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn arboards_reads_run_on_its_reader_and_wait_by_kind() {
let reads = Loads::spawn("test", Duration::ZERO, |request| match request {
// The reads wait for their answer however long it takes, so the answer decides the result.
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |request| match request {
Request::Text => Answer::Text(Ok("read on the worker".into())),
_ => Answer::failed(request, "not asked".into()),
})
@@ -1855,15 +1952,18 @@ mod portable {
// `()` for writes: a read made through the write handle wouldn't build.
let mut cb = Arboard { reads, unanswered: None, cb: () };
assert_eq!(cb.read(Request::Text).text(), Ok("read on the worker".to_string()));
assert_eq!(wait_for(Request::Text), super::super::loads::LOAD_WAIT);
assert_eq!(wait_for(Request::Files), super::super::loads::LOAD_WAIT);
assert_eq!(wait_for(Request::Image), Duration::from_secs(10));
let app = Waits::APP;
assert_eq!(wait_for(app, Request::Text), super::super::loads::LOAD_WAIT);
assert_eq!(wait_for(app, Request::Files), super::super::loads::LOAD_WAIT);
assert_eq!(wait_for(app, Request::Image), Duration::from_secs(10));
// A paste's reads after a late answer wait until 10 s after the unanswered read was
// sent, and never less than any read of their kind.
let sent = Instant::now();
assert_eq!(follow_up_wait(Request::Text, sent, sent + Duration::from_secs(3)), Duration::from_secs(7));
assert_eq!(follow_up_wait(Request::Files, sent, sent + Duration::from_secs(9)), super::super::loads::LOAD_WAIT);
assert_eq!(follow_up_wait(Request::Image, sent, sent + Duration::from_secs(20)), IMAGE_WAIT);
assert_eq!(follow_up_wait(app, Request::Text, sent, sent + Duration::from_secs(3)), Duration::from_secs(7));
assert_eq!(follow_up_wait(app, Request::Files, sent, sent + Duration::from_secs(9)), super::super::loads::LOAD_WAIT);
assert_eq!(follow_up_wait(app, Request::Image, sent, sent + Duration::from_secs(20)), super::super::loads::IMAGE_WAIT);
// With no limit, the follow-up reads have none either.
assert_eq!(follow_up_wait(Waits::UNTIL_ANSWERED, Request::Text, sent, sent + Duration::from_secs(20)), Duration::MAX);
// X11 waits for an unanswered read when the clipboard closes; data-control doesn't.
assert_eq!(finish(false), X11_READ_LIMIT);
assert_eq!(finish(true), Duration::ZERO);
@@ -1884,7 +1984,7 @@ mod portable {
fn a_bitmap_paste_waits_for_the_owner_off_the_ui_thread() {
let (release, gate) = std::sync::mpsc::channel::<()>();
// The app that copied sends its bitmap only when released.
let reads = Loads::spawn("test", Duration::ZERO, move |request| match request {
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| match request {
Request::Image => {
let _ = gate.recv();
Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) }))
@@ -1903,11 +2003,12 @@ mod portable {
}
/// An arboard clipboard whose owner answers each read with `answer` only once the sender
/// returned is used or dropped.
/// returned is used or dropped. Its reads wait for their answers with no limit: the
/// release decides when a paste gets its answer.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn slow_owner(answer: impl Fn(Request) -> Answer + Send + 'static) -> (Arboard<()>, std::sync::mpsc::Sender<()>) {
let (release, gate) = std::sync::mpsc::channel::<()>();
let reads = Loads::spawn("test", Duration::ZERO, move |request| {
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| {
let _ = gate.recv();
answer(request)
})
@@ -2028,10 +2129,10 @@ mod portable {
/// Core protocol reads of a clipboard offering `types`, whose owner answers each read
/// of a text type with `text` and of `image/png` with `png`, only once the sender
/// returned is used or dropped.
/// returned is used or dropped. The reads wait for their answers with no limit.
fn slow_owner(types: &[&str], text: &'static str, png: &'static [u8]) -> (Reads, Arc<Mutex<Seen>>, std::sync::mpsc::Sender<()>) {
let (release, gate) = std::sync::mpsc::channel::<()>();
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
let _ = gate.recv();
Ok(if wire == PNG { png.to_vec() } else { text.as_bytes().to_vec() })
})
@@ -2047,7 +2148,7 @@ mod portable {
// in its wait (2 s on the UI thread, none here).
assert!(reads.text(Duration::ZERO).is_err());
// The paste's own read fails at once while the owner hasn't answered.
assert!(reads.text(Duration::from_secs(600)).is_err());
assert!(reads.text(UNTIL_ANSWERED).is_err());
// A paste of a bitmap alone can't take text: the read stays kept.
assert!(reads.unanswered(&[BITMAP]).is_none());
let late = Late::Wayland(reads.unanswered(&PASTE_ORDER).expect("the check's read is kept for the paste"));
@@ -2083,7 +2184,7 @@ mod portable {
// again and takes the new owner's text.
let (release, gate) = std::sync::mpsc::channel::<()>();
let mut texts_read = 0;
let loads = Loads::spawn("test", Duration::ZERO, move |_: String| {
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |_: String| {
let _ = gate.recv();
texts_read += 1;
Ok(if texts_read == 1 { "old owner" } else { "new owner" }.as_bytes().to_vec())
@@ -2149,7 +2250,7 @@ mod wayland {
use wayland_client::protocol::wl_seat::{self, WlSeat};
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum};
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer};
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, Waits, left, wait_for_answer};
use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, takes_files, uri_list_paths};
/// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK
@@ -2445,16 +2546,18 @@ mod wayland {
/// The worker, for the reads made once the answer comes.
reads: Asker<String, Got>,
seen: Arc<Mutex<Seen>>,
/// How long the worker's reads wait.
waits: Waits,
}
impl Unanswered {
/// What a paste of one of `mimes` takes once this read's answer comes, waiting for it until
/// `limit` after the read was sent: the clipboard read again as [`pick_pasted`] reads it,
/// each read waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may
/// have lost the clipboard meanwhile. None when the answer doesn't come or the clipboard holds this
/// connection's Copy.
pub(super) fn paste(self, mimes: &[&'static str], limit: Duration) -> Option<Flavour> {
let left = |now: Instant| (self.sent + limit).saturating_duration_since(now);
/// `waits.image` after the read was sent: the clipboard read again as [`pick_pasted`] reads
/// it, each read waiting as long, `waits.load` ([`LOAD_WAIT`]) at least, since the app that
/// answers late may have lost the clipboard meanwhile. None when the answer doesn't come or
/// the clipboard holds this connection's Copy.
pub(super) fn paste(self, mimes: &[&'static str]) -> Option<Flavour> {
let left = |now: Instant| left(self.sent, self.waits.image, now);
let _late = wait_for_answer(&self.answer, left(Instant::now())).ok()?;
let offered = {
let seen = lock(&self.seen);
@@ -2464,7 +2567,7 @@ mod wayland {
seen.offered.clone()
};
pick_pasted(&offered, mimes, |wire| {
wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok()
wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, self.waits.load.max(left(Instant::now()))).ok()?.ok()
})
}
}
@@ -2491,7 +2594,8 @@ mod wayland {
Ok(got) => Ok(flavour(TEXT, got?).map(|f| String::from_utf8_lossy(&f.data).into_owned()).unwrap_or_default()),
Err(why) => {
if why != GONE {
self.unanswered = Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone() });
self.unanswered =
Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone(), waits: self.loads.waits() });
}
Err(why)
}
@@ -2501,12 +2605,13 @@ mod wayland {
/// What a paste of one of `mimes` reads: the files a file manager copied, else the first of
/// `mimes` the clipboard offers. A file list is asked for here and read, with the files,
/// by the work that comes back, which pastes the first file that is art ([`copied`]) and
/// else reads `mimes` as [`pick`] does. Text is read here, [`LOAD_WAIT`] at most, and
/// pasted unless it is empty; SVG and PNG are asked for here and waited for, `wait` at most,
/// by the work that comes back. When that read fails or is empty, the work reads the rest
/// of `mimes` as [`pick`] does. Each read the work makes after the first waits until `wait`
/// after the first was sent, [`LOAD_WAIT`] at least.
pub(super) fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option<ClipboardRead> {
/// else reads `mimes` as [`pick`] does. Text is read here, `waits.load` ([`LOAD_WAIT`]) at
/// most, and pasted unless it is empty; SVG and PNG are asked for here and waited for,
/// `waits.image` at most, by the work that comes back. When that read fails or is empty,
/// the work reads the rest of `mimes` as [`pick`] does. Each read the work makes after the
/// first waits until `waits.image` after the first was sent, `waits.load` at least.
pub(super) fn read(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
let Waits { load, image: wait } = self.loads.waits();
if takes_files(mimes) {
let offered = lock(&self.seen).offered.clone();
if let Some(list) = file_list_type(&offered).map(str::to_string) {
@@ -2515,7 +2620,7 @@ mod wayland {
self.unanswered = None;
let (reads, mimes) = (self.loads.asker(), mimes.to_vec());
return Some(ClipboardRead::Later(Box::new(move || {
let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now()));
let left = || load.max(left(sent, wait, Instant::now()));
// The list asked for here is read from its answer, every other type anew.
let mut first = Some((list, answer));
pick_pasted(&offered, &mimes, |wire| {
@@ -2531,7 +2636,7 @@ mod wayland {
mimes.iter().enumerate().find_map(|(i, &mime)| {
let wire = self.wire(mime)?;
if mime == TEXT {
let text = self.text(LOAD_WAIT).ok().filter(|t| !t.is_empty())?;
let text = self.text(load).ok().filter(|t| !t.is_empty())?;
return Some(ClipboardRead::Now(Flavour { mime: TEXT, data: text.into_bytes() }));
}
let sent = Instant::now();
@@ -2543,7 +2648,7 @@ mod wayland {
return Some(f);
}
let offered = lock(&seen).offered.clone();
let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now()));
let left = || load.max(left(sent, wait, Instant::now()));
pick(&offered, &rest, |wire| wait_for_answer(&reads.ask(wire.to_string()).ok()?, left()).ok()?.ok())
})))
})
@@ -2809,7 +2914,7 @@ mod wayland {
let receiver = Receiver { conn: conn.clone(), objects: objects.clone(), _window: window.clone() };
// Dropping doesn't wait for an unanswered read: only arboard's X11 handles hand what the
// app copied on when the last one goes.
let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, move |wire| receiver.receive(wire))?;
let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, Waits::APP, move |wire| receiver.receive(wire))?;
let stop = Arc::new(AtomicBool::new(false));
let (stopped, held) = (stop.clone(), window.clone());
let work = move || {
@@ -2846,14 +2951,16 @@ mod wayland {
self.conn.flush().map_err(|e| format!("couldn't reach the compositor: {e}"))
}
/// The text, waiting [`LOAD_WAIT`] at most ([`Reads::text`]).
pub fn text(&mut self) -> Result<String, String> {
self.reads.text(LOAD_WAIT)
let wait = self.reads.loads.waits().load;
self.reads.text(wait)
}
/// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for `wait` at
/// most.
pub fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option<ClipboardRead> {
self.reads.read(mimes, wait)
/// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most.
pub fn read(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
self.reads.read(mimes)
}
pub fn has(&self, mimes: &[&'static str]) -> bool {
@@ -3022,8 +3129,8 @@ mod wayland {
assert_eq!(keyboard_serial(&modifiers(9), None), None);
}
/// A wait no test reaches: the other end of each pipe below either moves data or closes.
const LONG: Duration = Duration::from_secs(600);
/// No limit ([`idle_until`]): the other end of each pipe below either moves data or closes.
const LONG: Duration = Duration::MAX;
/// A pipe holding `data`, its write end closed when `close`.
fn pipe_with(data: &[u8], close: bool) -> (std::io::PipeReader, Option<std::io::PipeWriter>) {
@@ -3041,7 +3148,7 @@ mod wayland {
assert_eq!(read_capped(pipe_with(&[0u8; 9], true).0, 8, Duration::ZERO), Err("the clipboard's data is larger than 0 MiB".to_string()));
// More than a pipe holds, from an app that is still sending.
let (from, to) = std::io::pipe().unwrap();
assert!(Sends::default().start(to, vec![0u8; (2 << 20) + 1].into()));
assert!(Sends { idle: LONG, ..Sends::default() }.start(to, vec![0u8; (2 << 20) + 1].into()));
assert_eq!(read_capped(from, 2 << 20, LONG), Err("the clipboard's data is larger than 2 MiB".to_string()));
// A pipe that can't be read: the write end.
let (_, to) = std::io::pipe().unwrap();
@@ -3095,8 +3202,8 @@ mod wayland {
#[test]
fn a_copys_data_is_sent_through_the_pipe_and_closed() {
let sends = Sends::default();
assert_eq!(sends.idle, IDLE_WAIT);
assert_eq!(Sends::default().idle, IDLE_WAIT);
let sends = Sends { idle: LONG, ..Sends::default() };
let (from, to) = std::io::pipe().unwrap();
let data: Arc<[u8]> = vec![7u8; 300_000].into();
assert!(sends.start(to, data.clone()));
@@ -3146,9 +3253,10 @@ mod wayland {
const NOTHING: Held = &[];
const UNKNOWN: Held = &[("application/x-other", b"x")];
/// Reads of a clipboard holding `data`, answered at once.
/// Reads of a clipboard holding `data`, answered at once; each read waits for its answer
/// with no limit.
fn reads_of(data: Held) -> Reads {
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.to_vec()).ok_or_else(|| "not offered".to_string())
})
.unwrap();
@@ -3159,27 +3267,26 @@ mod wayland {
#[test]
fn a_picture_or_svg_alone_can_be_pasted_and_is() {
use vectorcraft_engine::cmd::clipboard::PASTE_ORDER;
let wait = Duration::from_secs(600);
for (data, mime) in [(PNG_ONLY, PNG), (SVG_ONLY, SVG)] {
let mut reads = reads_of(data);
// The paste check enables Paste from the types alone.
assert!(reads.has(&PASTE_ORDER));
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("{mime} is read off the UI thread") };
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("{mime} is read off the UI thread") };
assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, data[0].1.to_vec())));
}
let mut reads = reads_of(TEXT_ONLY);
assert!(reads.has(&[TEXT]) && !reads.has(&[BITMAP, SVG]));
let Some(ClipboardRead::Now(f)) = reads.read(&PASTE_ORDER, wait) else { panic!("text is read at once") };
let Some(ClipboardRead::Now(f)) = reads.read(&PASTE_ORDER) else { panic!("text is read at once") };
assert_eq!((f.mime, f.data), (TEXT, b"words".to_vec()));
// An empty clipboard, or one with no type a paste reads, enables nothing and pastes nothing.
for data in [NOTHING, UNKNOWN] {
let mut reads = reads_of(data);
assert!(!reads.has(&PASTE_ORDER));
assert!(reads.read(&PASTE_ORDER, wait).is_none());
assert_eq!(reads.text(wait), Ok(String::new()));
assert!(reads.read(&PASTE_ORDER).is_none());
assert_eq!(reads.text(Duration::MAX), Ok(String::new()));
}
// Empty text is not pasted.
assert!(reads_of(EMPTY_TEXT).read(&[TEXT], wait).is_none());
assert!(reads_of(EMPTY_TEXT).read(&[TEXT]).is_none());
}
#[test]
@@ -3188,36 +3295,38 @@ mod wayland {
const EMPTY_SVG_TEXT: Held = &[(SVG, b""), ("text/plain", b"words"), (PNG, b"\x89PNG")];
const EMPTY_SVG_PNG: Held = &[(SVG, b""), (PNG, b"\x89PNG")];
const EMPTY_SVG_URL: Held = &[(SVG, b""), ("text/plain", b"https://example.com/art.png"), (PNG, b"\x89PNG")];
let wait = Duration::from_secs(600);
const EMPTY_PNG: Held = &[(PNG, b"")];
for (data, mime, bytes) in
[(EMPTY_SVG_TEXT, TEXT, &b"words"[..]), (EMPTY_SVG_PNG, PNG, &b"\x89PNG"[..]), (EMPTY_SVG_URL, PNG, &b"\x89PNG"[..])]
{
// Held while the work runs, as the clipboard is.
let mut reads = reads_of(data);
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the SVG is asked for") };
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("the SVG is asked for") };
assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, bytes.to_vec())));
}
// A failed PNG read, last of all, pastes nothing.
let mut reads = reads_of(EMPTY_PNG);
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the PNG is asked for") };
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("the PNG is asked for") };
assert!(work().is_none());
}
#[test]
fn a_read_that_fails_pastes_nothing() {
let loads = Loads::spawn("test", Duration::ZERO, |_: String| Err::<Vec<u8>, _>("the clipboard's data is larger than 64 MiB".to_string()))
.unwrap();
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |_: String| {
Err::<Vec<u8>, _>("the clipboard's data is larger than 64 MiB".to_string())
})
.unwrap();
let mut reads = Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&[PNG, "text/plain"]))));
assert_eq!(reads.text(Duration::from_secs(600)), Err("the clipboard's data is larger than 64 MiB".to_string()));
let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP], Duration::from_secs(600)) else { panic!("the PNG is asked for") };
assert_eq!(reads.text(Duration::MAX), Err("the clipboard's data is larger than 64 MiB".to_string()));
let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP]) else { panic!("the PNG is asked for") };
assert!(work().is_none());
}
/// Reads of a clipboard holding `data` by type, answered at once.
/// Reads of a clipboard holding `data` by type, answered at once; each read waits for its
/// answer with no limit.
fn reads_holding(data: Vec<(String, Vec<u8>)>) -> Reads {
let types: Vec<String> = data.iter().map(|(t, _)| t.clone()).collect();
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.clone()).ok_or_else(|| "not offered".to_string())
})
.unwrap();
@@ -3232,7 +3341,7 @@ mod wayland {
/// What a paste of `mimes` takes from `reads`.
fn paste(reads: &mut Reads, mimes: &[&'static str]) -> Option<(&'static str, Vec<u8>)> {
match reads.read(mimes, Duration::from_secs(600))? {
match reads.read(mimes)? {
ClipboardRead::Now(f) => Some((f.mime, f.data)),
ClipboardRead::Later(work) => work().map(|f| (f.mime, f.data)),
}
@@ -3296,15 +3405,29 @@ mod wayland {
}
/// The macOS pasteboard's vector art and bitmaps as they are (arboard reads text, and of the
/// pictures TIFF only, decoded).
/// pictures TIFF only, decoded), and the formats Copy adds to what arboard wrote.
#[cfg(target_os = "macos")]
mod mac {
use objc2::rc::autoreleasepool;
use objc2_app_kit::NSPasteboard;
use objc2_foundation::{NSArray, NSString};
use objc2_foundation::{NSArray, NSData, NSString};
use super::{Flavour, MAX_BYTES, copy_within, pasteboard_types};
/// Adds `types` ([`super::pasteboard_additions`]: each pasteboard type with its data) to the
/// item arboard just wrote. A type that can't be added is logged, and what arboard wrote still
/// carries the copy.
pub fn add(types: &[(&str, &[u8])]) {
autoreleasepool(|_| {
let pasteboard = NSPasteboard::generalPasteboard();
for &(t, data) in types {
if !pasteboard.setData_forType(Some(&NSData::with_bytes(data)), &NSString::from_str(t)) {
log::warn!("clipboard: couldn't add {t}");
}
}
})
}
/// Does the pasteboard hold one of `mimes` ([`pasteboard_types`])? Asks for its types only.
pub fn has(mimes: &[&'static str]) -> bool {
autoreleasepool(|_| {
@@ -3393,6 +3516,25 @@ mod tests {
assert!(at(PDF) < at(EPS) && at(EPS) < at(TEXT) && at(TEXT) < at(BITMAP));
}
/// On macOS a Copy puts every format on the pasteboard, not only the text or the picture
/// arboard writes (#6310): with On Copy: PDF the PDF goes with the picture, and with Include
/// SVG Code the SVG and the PDF go with the markup as text.
#[test]
fn a_copy_adds_its_other_formats_to_the_pasteboard() {
let flavor = |mime: &'static str, data: &[u8]| Flavor::new(mime, data.to_vec());
let added = |flavors: &[Flavor]| pasteboard_additions(flavors).into_iter().map(|(t, data)| (t, data.to_vec())).collect::<Vec<_>>();
// On Copy: PDF alone: arboard writes the picture, and the PDF is added beside it.
let pdf_only = [flavor(PDF, b"%PDF"), flavor(PNG, b"png")];
assert_eq!(added(&pdf_only), [("com.adobe.pdf", b"%PDF".to_vec()), ("public.png", b"png".to_vec())]);
// Include SVG Code with the PDF: arboard writes the markup as text, and the SVG, PDF and
// picture are added in the order Copy offers them.
let both = [flavor(TEXT, b"<svg/>"), flavor(SVG, b"<svg/>"), flavor(PDF, b"%PDF"), flavor(PNG, b"png")];
let types: Vec<_> = added(&both).into_iter().map(|(t, _)| t).collect();
assert_eq!(types, ["public.svg-image", "com.adobe.pdf", "public.png"]);
// An empty flavour and a type the pasteboard doesn't carry are left out.
assert!(added(&[flavor(PDF, b""), flavor(EMF, b"emf"), flavor("text/html", b"<p>")]).is_empty());
}
/// An .eps file copied in a file manager pastes as EPS.
#[test]
fn a_copied_eps_file_pastes() {
+22 -12
View File
@@ -220,11 +220,20 @@ fn report_path(dir: &Path) -> PathBuf {
dir.join(format!("{REPORT_PREFIX}{}.txt", std::process::id()))
}
/// A report file this process wrote and holds locked until the interface answers again.
/// A report file this process holds locked: the one it wrote, until the interface answers again,
/// or a left one while it is read. Dropping it unlocks the file. A child process that any thread
/// starts holds a copy of the file's handle until it runs its program, and the lock is only freed
/// by closing every copy or by unlocking.
#[derive(Debug)]
pub struct Held {
path: PathBuf,
_file: File,
file: File,
}
impl Drop for Held {
fn drop(&mut self) {
let _ = self.file.unlock();
}
}
/// Write `text` to this process's report file in `dir` and lock it. Where the file system has no
@@ -237,7 +246,7 @@ fn write_report(dir: &Path, text: &str) -> std::io::Result<Held> {
log::warn!("the hang report file is written without a lock: {e}");
}
file.write_all(text.as_bytes())?;
Ok(Held { path, _file: file })
Ok(Held { path, file })
}
/// Whether a report file whose `try_lock` gave `locked` was abandoned: nobody holds it. A file
@@ -253,13 +262,14 @@ fn abandoned(locked: Result<(), std::fs::TryLockError>) -> bool {
/// The report file at `path`, opened and locked, with its length, when it was abandoned
/// ([`abandoned`]) and is not empty (an empty one may be being written).
fn open_abandoned(path: &Path) -> Option<(File, u64)> {
fn open_abandoned(path: &Path) -> Option<(Held, u64)> {
let file = File::options().read(true).write(true).open(path).ok()?;
if !abandoned(file.try_lock()) {
return None;
}
let len = file.metadata().map_or(0, |m| m.len());
(len > 0).then_some((file, len))
let held = Held { path: path.to_path_buf(), file };
let len = held.file.metadata().map_or(0, |m| m.len());
(len > 0).then_some((held, len))
}
/// The reports that sessions closed while they did not answer left in `dir`, oldest first; `None`
@@ -286,20 +296,20 @@ pub fn take_previous(dir: &Path) -> Option<String> {
// Newest first: only abandoned reports count toward the limit.
let mut texts = Vec::new();
for (_, path) in found.into_iter().rev() {
let Some((file, len)) = open_abandoned(&path) else { continue };
let Some((held, len)) = open_abandoned(&path) else { continue };
if texts.len() == MAX_REPORT_FILES {
drop(file);
drop(held);
remove_quietly(&path);
continue;
}
let mut bytes = Vec::new();
let text = if len <= MAX_REPORT_BYTES && (&file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() {
let text = if len <= MAX_REPORT_BYTES && (&held.file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() {
String::from_utf8_lossy(&bytes).into_owned()
} else {
format!("The report was larger than {MAX_REPORT_BYTES} bytes and was not read.\n")
};
// Closed (and unlocked) before it is moved: Windows moves no open file.
drop(file);
drop(held);
if !texts.is_empty() {
remove_quietly(&path);
} else if let Err(e) = std::fs::rename(&path, dir.join(PREVIOUS_FILE)) {
@@ -324,8 +334,8 @@ pub static CLOSING: AtomicBool = AtomicBool::new(false);
/// Remove `held`'s file, closing it first. → the error message; a file already gone is none.
fn remove(held: Held) -> Option<String> {
let Held { path, _file: file } = held;
drop(file);
let path = held.path.clone();
drop(held);
match std::fs::remove_file(&path) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Some(e.to_string()),
_ => None,
+11
View File
@@ -136,6 +136,17 @@ fn a_stall_writes_the_report_file_and_its_end_removes_it() {
assert!(shared.last.lock().unwrap().is_some());
}
#[test]
fn a_dropped_report_frees_its_lock_while_a_copy_of_its_handle_is_open() {
let dir = tempfile::tempdir().unwrap();
let held = write_report(dir.path(), "left\n").unwrap();
// A child process that is starting holds such a copy.
let copy = held.file.try_clone().unwrap();
drop(held);
assert_eq!(take_previous(dir.path()).as_deref(), Some("left\n"), "a dropped report is no longer locked");
drop(copy);
}
#[test]
fn closing_normally_removes_the_report_and_writes_no_more() {
let dir = tempfile::tempdir().unwrap();
+4
View File
@@ -189,6 +189,10 @@ pub(crate) fn services(window: Parent) -> Services {
open_in_application: Some(Box::new(open_in_application)),
// File → Print: the system's printers and print queue.
print: Some(Box::new(printing::SystemPrint)),
// The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens
// only while the active tool uses the wheel.
#[cfg(all(windows, not(target_vendor = "win7")))]
stylus_wheel: Some(Box::new(super::windows_wintab::set_wheel_used)),
..Default::default()
}
}
+5
View File
@@ -124,10 +124,13 @@ pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: O
/// The arguments a child of this process starts with: a nightly launch hands its profile on, so the
/// child opens the same private profile instead of being refused ("Open VectorCraft Nightly…"), and
/// `--` keeps a file whose name starts with '-' a file. Stable's child arguments are unchanged.
/// Only `single_instance` starts a child, and macOS does not build it.
#[cfg(not(target_os = "macos"))]
pub fn child_args(files: &[String]) -> Vec<OsString> {
child_args_for(current(), files)
}
#[cfg(not(target_os = "macos"))]
fn child_args_for(profile: &Profile, files: &[String]) -> Vec<OsString> {
let mut args: Vec<OsString> = match profile {
Profile::Stable => Vec::new(),
@@ -245,12 +248,14 @@ mod tests {
}
}
#[cfg(not(target_os = "macos"))]
#[test]
fn a_stable_child_gets_the_file_delimiter_only() {
let child = child_args_for(&Profile::Stable, &["a file.svg".to_string(), "--looks-like-a-flag".to_string()]);
assert_eq!(child, args(&["--", "a file.svg", "--looks-like-a-flag"]));
}
#[cfg(not(target_os = "macos"))]
#[test]
fn a_nightly_child_inherits_the_selected_profile() {
let root = PathBuf::from(absolute());
+6
View File
@@ -74,6 +74,7 @@ mod windows_cores;
mod windows_display_size;
mod windows_stylus;
mod windows_symbol_chars;
mod windows_wintab;
mod xwayland;
use std::sync::{Arc, Mutex};
@@ -823,6 +824,8 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_plugin_store(&mut session);
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
prefs_dir::attach_scripts_dir(&mut session);
// The startup scripts are in the Startup Scripts folder next to the preferences.
prefs_dir::attach_startup_scripts_dir(&mut session);
// File Info's metadata templates live in their own folder next to the preferences.
prefs_dir::attach_metadata_templates_dir(&mut session);
prefs_dir::attach_new_doc_profiles(&mut session);
@@ -976,6 +979,9 @@ fn main() -> std::process::ExitCode {
single_instance::set_ui(&cc.egui_ctx);
}
let held_files = file_access::unconfined(|| open_or_hold(&mut app, command_line_files));
// With General › Run Startup Scripts on and Safe Mode off, the startup scripts run
// now, as the person's own; in Safe Mode they wait for the choice that ends it.
file_access::unconfined(|| vectorcraft_ui_egui::script_runs::run_at_launch(&mut app));
// The first frame is due from now (`gpu::watch_first_frame`).
#[cfg(feature = "wgpu")]
created.ready();
+8
View File
@@ -66,6 +66,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
}
}
/// Have `script.startup.run` run the scripts of the `Startup Scripts` folder. The folder is only
/// read: the user makes it.
pub fn attach_startup_scripts_dir(session: &mut vectorcraft_engine::Session) {
if let Some(dir) = store_dir("Startup Scripts") {
session.attach_startup_scripts_dir(dir);
}
}
/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template
/// makes.
pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) {
+81 -46
View File
@@ -46,6 +46,17 @@ const SERVER_TIMEOUT: Duration = Duration::from_secs(2);
/// How long a launch waits on the primary: longer than a launch served before it can take.
const CLIENT_TIMEOUT: Duration = Duration::from_secs(5);
/// How long each side of a hand-over waits on the other.
#[derive(Clone, Copy)]
struct Timeouts {
connect: Duration,
server: Duration,
client: Duration,
}
/// The waits a launch and the running app use.
const TIMEOUTS: Timeouts = Timeouts { connect: CONNECT_TIMEOUT, server: SERVER_TIMEOUT, client: CLIENT_TIMEOUT };
/// Paths handed over by later launches that the UI hasn't opened yet.
static PENDING: Mutex<Vec<String>> = Mutex::new(Vec::new());
/// This app while it is the one later launches hand their files to ([`hold`]).
@@ -68,25 +79,25 @@ pub fn start(automation: bool, new_instance: bool, safe_mode: bool, files: &[Str
return Start::Running(None);
}
let Some(path) = prefs_dir().map(|dir| dir.join(FILE_NAME)) else { return Start::Running(None) };
start_at(&path, new_instance, safe_mode, files)
start_at(&path, TIMEOUTS, new_instance, safe_mode, files)
}
/// [`start`] with the endpoint file `path`. A launch with `--new-instance` or `--safe-mode` keeps
/// [`start`] with the endpoint file `path` and the waits `timeouts`. A launch with `--new-instance` or `--safe-mode` keeps
/// its files and runs as its own app: a running app would open them with its plug-ins loaded. A
/// `--safe-mode` launch never becomes the app later launches hand their files to, which would open
/// them without plug-ins.
fn start_at(path: &Path, new_instance: bool, safe_mode: bool, files: &[String]) -> Start {
fn start_at(path: &Path, timeouts: Timeouts, new_instance: bool, safe_mode: bool, files: &[String]) -> Start {
if safe_mode {
return Start::Running(None);
}
// With nothing to hand over, the same exchange only asks whether an app is running.
let send: &[String] = if new_instance { &[] } else { files };
match forward(path, send) {
match forward(path, timeouts, send) {
Ok(()) if send.is_empty() => Start::Running(None),
Ok(()) => Start::Forwarded,
Err(e) => {
log::debug!("no running VectorCraft to hand files to ({e})");
Start::Running(listen(path, queue))
Start::Running(listen(path, timeouts, queue))
}
}
}
@@ -195,12 +206,12 @@ fn read_endpoint(path: &Path) -> Option<Endpoint> {
/// Hand `files` (made absolute against this launch's folder) to the app recorded at `path`; `Ok`
/// once it acknowledged them.
fn forward(path: &Path, files: &[String]) -> io::Result<()> {
fn forward(path: &Path, timeouts: Timeouts, files: &[String]) -> io::Result<()> {
let endpoint = read_endpoint(path).ok_or_else(|| invalid("no endpoint file"))?;
let files = files.iter().map(|f| std::path::absolute(f).map(|p| p.to_string_lossy().into_owned())).collect::<io::Result<Vec<_>>>()?;
let stream = TcpStream::connect_timeout(&(Ipv4Addr::LOCALHOST, endpoint.port).into(), CONNECT_TIMEOUT)?;
stream.set_read_timeout(Some(CLIENT_TIMEOUT))?;
stream.set_write_timeout(Some(CLIENT_TIMEOUT))?;
let stream = TcpStream::connect_timeout(&(Ipv4Addr::LOCALHOST, endpoint.port).into(), timeouts.connect)?;
stream.set_read_timeout(Some(timeouts.client))?;
stream.set_write_timeout(Some(timeouts.client))?;
// The token and the paths go only to a listener that knows the greeting.
if !same(read_message(&stream)?.get("hello"), &endpoint.hello) {
return Err(invalid("the listener isn't VectorCraft"));
@@ -214,11 +225,11 @@ fn forward(path: &Path, files: &[String]) -> io::Result<()> {
/// Listen for later launches and record this app at `path`; each launch's files go to `deliver`.
/// `None` when that fails (logged): the app then runs on its own, as before.
fn listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> Option<Primary> {
try_listen(path, deliver).inspect_err(|e| log::warn!("files opened while VectorCraft runs will open in another window: {e}")).ok()
fn listen(path: &Path, timeouts: Timeouts, deliver: impl Fn(Vec<String>) + Send + 'static) -> Option<Primary> {
try_listen(path, timeouts, deliver).inspect_err(|e| log::warn!("files opened while VectorCraft runs will open in another window: {e}")).ok()
}
fn try_listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> io::Result<Primary> {
fn try_listen(path: &Path, timeouts: Timeouts, deliver: impl Fn(Vec<String>) + Send + 'static) -> io::Result<Primary> {
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
let port = listener.local_addr()?.port();
let (token, hello) = random_tokens();
@@ -227,7 +238,7 @@ fn try_listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> io
let primary = Primary { path: path.to_path_buf(), token: token.clone() };
std::thread::Builder::new().name("open-files-listener".into()).spawn(move || {
for stream in listener.incoming() {
match stream.and_then(|s| receive(&s, &hello, &token)) {
match stream.and_then(|s| receive(&s, timeouts.server, &hello, &token)) {
Ok(files) if files.is_empty() => {}
Ok(files) => deliver(files),
Err(e) => {
@@ -241,10 +252,11 @@ fn try_listen(path: &Path, deliver: impl Fn(Vec<String>) + Send + 'static) -> io
Ok(primary)
}
/// Serve one launch: greet it, check its token, keep the paths that are existing files.
fn receive(stream: &TcpStream, hello: &str, token: &str) -> io::Result<Vec<String>> {
stream.set_read_timeout(Some(SERVER_TIMEOUT))?;
stream.set_write_timeout(Some(SERVER_TIMEOUT))?;
/// Serve one launch, waiting on it at most `timeout`: greet it, check its token, keep the paths
/// that are existing files.
fn receive(stream: &TcpStream, timeout: Duration, hello: &str, token: &str) -> io::Result<Vec<String>> {
stream.set_read_timeout(Some(timeout))?;
stream.set_write_timeout(Some(timeout))?;
write_message(stream, &json!({ "hello": hello }))?;
let message = read_message(stream)?;
if !same(message.get("token"), token) {
@@ -357,17 +369,38 @@ mod tests {
(dir.path().join(FILE_NAME), TestDir(dir), file)
}
/// Stops a test that hangs. A hand-over on a busy machine still ends long before it, so no
/// result depends on how long a step takes.
const HANG_GUARD: Duration = Duration::from_secs(60);
/// The waits both sides get in the tests.
const PATIENT: Timeouts = Timeouts { connect: HANG_GUARD, server: HANG_GUARD, client: HANG_GUARD };
fn primary(path: &Path) -> (Primary, mpsc::Receiver<Vec<String>>) {
let (tx, rx) = mpsc::channel();
let primary = listen(path, move |files| tx.send(files).unwrap()).unwrap();
let primary = listen(path, PATIENT, move |files| tx.send(files).unwrap()).unwrap();
(primary, rx)
}
/// The next files the app delivered. The app delivers them after it acknowledges the launch,
/// so this waits for them.
fn delivered(rx: &mpsc::Receiver<Vec<String>>) -> Vec<String> {
rx.recv_timeout(HANG_GUARD).unwrap_or_else(|e| panic!("the app delivered no files: {e}"))
}
/// `result` is an error from the other side, not a wait that ran out.
fn refused<T>(result: io::Result<T>) -> bool {
result.is_err_and(|e| {
assert!(!matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut), "a wait ran out instead: {e}");
true
})
}
/// Connects as a launch would and sends `message` after the greeting; what came back.
fn send_raw(path: &Path, message: &[u8]) -> io::Result<Value> {
let endpoint = read_endpoint(path).unwrap();
let stream = TcpStream::connect((Ipv4Addr::LOCALHOST, endpoint.port)).unwrap();
stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap();
stream.set_read_timeout(Some(HANG_GUARD)).unwrap();
stream.set_write_timeout(Some(HANG_GUARD)).unwrap();
assert!(same(read_message(&stream).unwrap().get("hello"), &endpoint.hello));
(&stream).write_all(message)?;
read_message(&stream)
@@ -378,12 +411,12 @@ mod tests {
let (path, dir, file) = folder("forward");
let (primary, rx) = primary(&path);
let missing = dir.join("missing.svg").to_string_lossy().into_owned();
forward(&path, &[file.clone(), missing]).unwrap();
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file), "the missing file is left out");
forward(&path, PATIENT, &[file.clone(), missing]).unwrap();
assert_eq!(delivered(&rx), std::slice::from_ref(&file), "the missing file is left out");
// An empty list only asks whether the app runs: nothing is delivered.
forward(&path, &[]).unwrap();
forward(&path, std::slice::from_ref(&file)).unwrap();
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
forward(&path, PATIENT, &[]).unwrap();
forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap();
assert_eq!(delivered(&rx), [file]);
drop(primary);
assert!(!path.exists(), "the endpoint file goes with the app");
}
@@ -393,11 +426,11 @@ mod tests {
let (path, _dir, file) = folder("own");
let (primary, rx) = primary(&path);
for (new_instance, safe_mode) in [(true, false), (false, true)] {
let start = start_at(&path, new_instance, safe_mode, std::slice::from_ref(&file));
let start = start_at(&path, PATIENT, new_instance, safe_mode, std::slice::from_ref(&file));
assert!(matches!(start, Start::Running(None)), "runs as its own app (new instance {new_instance}, Safe Mode {safe_mode})");
}
assert!(matches!(start_at(&path, false, false, std::slice::from_ref(&file)), Start::Forwarded));
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), std::slice::from_ref(&file));
assert!(matches!(start_at(&path, PATIENT, false, false, std::slice::from_ref(&file)), Start::Forwarded));
assert_eq!(delivered(&rx), std::slice::from_ref(&file));
assert!(rx.try_recv().is_err(), "only the plain launch handed its file over");
drop(primary);
}
@@ -407,10 +440,10 @@ mod tests {
let _globals = globals();
let (path, _dir, file) = folder("safe-mode-alone");
// With no app running, a Safe Mode launch runs without listening.
assert!(matches!(start_at(&path, false, true, std::slice::from_ref(&file)), Start::Running(None)));
assert!(matches!(start_at(&path, PATIENT, false, true, std::slice::from_ref(&file)), Start::Running(None)));
assert!(!path.exists(), "a Safe Mode launch records no endpoint");
// A plain launch after it starts its own app and takes later launches' files.
let Start::Running(Some(primary)) = start_at(&path, false, false, std::slice::from_ref(&file)) else {
let Start::Running(Some(primary)) = start_at(&path, PATIENT, false, false, std::slice::from_ref(&file)) else {
panic!("the plain launch runs and listens")
};
assert!(path.exists());
@@ -427,7 +460,7 @@ mod tests {
resign();
drop(take());
let (path, _dir, file) = folder("safe-mode-later");
let Start::Running(Some(primary)) = start_at(&path, false, false, &[]) else { panic!("the first launch listens") };
let Start::Running(Some(primary)) = start_at(&path, PATIENT, false, false, &[]) else { panic!("the first launch listens") };
hold(Some(primary));
// A later launch handed its file over while the choice about a stopped plug-in was up.
queue(vec![file.clone()]);
@@ -460,17 +493,18 @@ mod tests {
let (_primary, rx) = primary(&path);
let token = read_endpoint(&path).unwrap().token;
let wrong = format!("{}\n", json!({ "token": "0".repeat(token.len()), "files": [file] }));
assert!(send_raw(&path, wrong.as_bytes()).is_err());
assert!(send_raw(&path, b"not json\n").is_err());
assert!(send_raw(&path, &vec![b'a'; MAX_MESSAGE as usize + 10]).is_err());
assert!(refused(send_raw(&path, wrong.as_bytes())));
assert!(refused(send_raw(&path, b"not json\n")));
assert!(refused(send_raw(&path, &vec![b'a'; MAX_MESSAGE as usize + 10])));
let many = format!("{}\n", json!({ "token": token, "files": vec![file.clone(); MAX_FILES + 1] }));
assert!(send_raw(&path, many.as_bytes()).is_err());
assert!(refused(send_raw(&path, many.as_bytes())));
let relative = format!("{}\n", json!({ "token": token, "files": ["a b.svg", 7] }));
assert_eq!(send_raw(&path, relative.as_bytes()).unwrap(), json!({ "ok": true }));
assert!(rx.try_recv().is_err(), "nothing was delivered");
// The listener still serves a launch with the right token.
forward(&path, std::slice::from_ref(&file)).unwrap();
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
// The listener still serves a launch with the right token. It serves launches in turn, so
// anything delivered for the messages above would come before this file.
forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap();
assert_eq!(delivered(&rx), [file]);
}
#[test]
@@ -483,27 +517,28 @@ mod tests {
let port = gone.local_addr().unwrap().port();
write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap();
let closed = std::thread::spawn(move || drop(gone.accept()));
assert!(forward(&path, std::slice::from_ref(&file)).is_err());
assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file))));
closed.join().unwrap();
// A listener that doesn't know the greeting gets neither the token nor the paths.
// A listener that doesn't know the greeting gets neither the token nor the paths: the
// launch closes the connection instead.
let impostor = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
let port = impostor.local_addr().unwrap().port();
write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap();
let heard = std::thread::spawn(move || {
let (stream, _) = impostor.accept().unwrap();
write_message(&stream, &json!({ "hello": "x" })).unwrap();
stream.set_read_timeout(Some(CLIENT_TIMEOUT)).unwrap();
read_message(&stream).ok()
stream.set_read_timeout(Some(HANG_GUARD)).unwrap();
read_message(&stream)
});
assert!(forward(&path, std::slice::from_ref(&file)).is_err());
assert!(heard.join().unwrap().is_none());
assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file))));
assert!(refused(heard.join().unwrap()));
// Garbage in the file is no endpoint either.
fs::write(&path, b"\xff not json").unwrap();
assert!(forward(&path, std::slice::from_ref(&file)).is_err());
assert!(refused(forward(&path, PATIENT, std::slice::from_ref(&file))));
// A new primary replaces the stale file.
let (_primary, rx) = primary(&path);
forward(&path, std::slice::from_ref(&file)).unwrap();
assert_eq!(rx.recv_timeout(CLIENT_TIMEOUT).unwrap(), [file]);
forward(&path, PATIENT, std::slice::from_ref(&file)).unwrap();
assert_eq!(delivered(&rx), [file]);
}
#[test]
+134 -15
View File
@@ -1,7 +1,8 @@
//! Windows pen tablets: with Windows Ink, winit reports a pen in contact as a touch and drops its
//! barrel button and which end of the pen is down. For each pointer message of a pen,
//! [`msg_hook`] reads the pen's `POINTER_PEN_INFO` before winit handles the message and writes its
//! pressure, end, tilt and rotation into the framework's [`PenSource`] ([`start`]):
//! pressure, end, tilt and rotation, and an airbrush pen's finger wheel, into the framework's
//! [`PenSource`] ([`start`]):
//! `PEN_FLAG_INVERTED` ("The pen is inverted") or `PEN_FLAG_ERASER` ("The eraser button is
//! pressed") is the eraser end
//! (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/pen-flags-constants>). Pointer
@@ -24,9 +25,12 @@
//! `rotation` in degrees 0..359 clockwise
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-pointer_pen_info>).
//! Toward the user is down the screen, so they are the sample's axes and direction as they come,
//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel.
//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel, which
//! comes from the tablet driver's Wintab interface instead, when it has one
//! ([`crate::windows_wintab`]).
#![cfg_attr(not(windows), allow(dead_code))]
use std::cell::Cell;
use std::sync::OnceLock;
use craft::behavior::PointerSample;
@@ -38,6 +42,8 @@ const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020;
/// `POINTER_MESSAGE_FLAG_INRANGE` (`winuser.h`): not set on the message of a pointer that has left
/// detection range.
const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002;
/// `POINTER_MESSAGE_FLAG_CANCELED` (`winuser.h`): the pointer's input was canceled.
const POINTER_MESSAGE_FLAG_CANCELED: usize = 0x8000;
/// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`.
const PEN_FLAG_INVERTED: u32 = 0x0002;
const PEN_FLAG_ERASER: u32 = 0x0004;
@@ -65,6 +71,13 @@ const WM_POINTERLEAVE: u32 = 0x024A;
/// A pen's tilt along x and y and its barrel rotation, in radians.
type Pose = ([f32; 2], f32);
thread_local! {
/// The pointer id of the pen whose leaving starts the Wintab wheel readings afresh: the pen that
/// took them, or the pen whose message last asked for the wheel when none has
/// ([`crate::windows_wintab::wheel_pen`]).
static WHEEL_PEN: Cell<Option<u32>> = const { Cell::new(None) };
}
/// The pen source [`msg_hook`] writes, once [`start`] has made it.
static FEED: OnceLock<PenSource> = OnceLock::new();
@@ -89,14 +102,22 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
let Some(pen) = FEED.get() else {
return false;
};
crate::windows_wintab::msg_hook(msg);
if forgets_wheel(msg.message, msg.wParam.0, WHEEL_PEN.get()) {
crate::windows_wintab::forget();
}
let read_pen = || {
let mut info = POINTER_PEN_INFO::default();
let id = (msg.wParam.0 & 0xffff) as u32;
// SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a
// pointer that is not a pen.
unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?;
unsafe { GetPointerPenInfo(id, &mut info) }.ok()?;
let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0;
let eraser = info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0;
let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, id, eraser);
WHEEL_PEN.set(Some(crate::windows_wintab::wheel_pen(id)));
let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation);
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose))
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose, wheel))
};
// SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message.
let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32);
@@ -111,8 +132,10 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
/// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags`
/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen
/// in contact that reports none; the eraser end while it is inverted or its eraser button is
/// pressed; and how it is held, `pose` ([`pen_pose`]).
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose) -> PointerSample {
/// pressed; how it is held, `pose` ([`pen_pose`]); and `wheel`, the airbrush finger wheel the tablet
/// driver's Wintab interface reported for the message, if any ([`crate::windows_wintab`]), kept
/// within 0..1 and none when it is not a number.
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose, wheel: Option<f32>) -> PointerSample {
let pressure = match pressure {
1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0,
_ if in_contact => 1.0,
@@ -122,6 +145,7 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (t
sample.tilt = tilt;
sample.rotation = rotation;
sample.eraser = pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0;
sample.wheel = wheel.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 1.0));
sample
}
@@ -134,6 +158,43 @@ fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> Pose {
([along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)], turn)
}
/// Whether a message with this `wParam` starts the Wintab wheel readings afresh: a pointer message
/// of a pointer that has left detection range or whose press was canceled, or a pointer leaving the
/// window, when the pointer is `pen`, the pen whose leaving starts them afresh. A touch or another
/// pen leaving keeps the readings.
fn forgets_wheel(message: u32, wparam: usize, pen: Option<u32>) -> bool {
if pen != Some((wparam & 0xffff) as u32) {
return false;
}
let flags = wparam >> 16;
match message {
WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP => {
flags & POINTER_MESSAGE_FLAG_INRANGE == 0 || flags & POINTER_MESSAGE_FLAG_CANCELED != 0
}
WM_POINTERLEAVE => true,
_ => false,
}
}
/// Whether a pointer message that Windows sends to the window procedure, so that winit's message hook
/// never sees it, starts the Wintab wheel readings afresh ([`forgets_wheel`]): `WM_POINTERENTER` and
/// `WM_POINTERLEAVE` are sent
/// (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/wm-pointerleave>); the posted pointer
/// messages are left to [`msg_hook`].
fn sent_forgets_wheel(message: u32, wparam: usize, pen: Option<u32>) -> bool {
matches!(message, WM_POINTERENTER | WM_POINTERLEAVE) && forgets_wheel(message, wparam, pen)
}
/// A message Windows sent to a window procedure of the thread, from the Wintab reader's hook on
/// them ([`crate::windows_wintab`]): a pen leaving the window starts the wheel readings afresh, as
/// [`msg_hook`] does for the messages it sees.
#[cfg(windows)]
pub fn sent_message(message: u32, wparam: usize) {
if sent_forgets_wheel(message, wparam, WHEEL_PEN.get()) {
crate::windows_wintab::forget();
}
}
/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse,
/// not from a pen or a touch.
fn is_mouse(extra_info: u32) -> bool {
@@ -175,7 +236,7 @@ mod tests {
#[test]
fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() {
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT).eraser;
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT, None).eraser;
assert!(!eraser(0), "the tip");
assert!(!eraser(PEN_FLAG_BARREL), "the barrel button");
assert!(eraser(PEN_FLAG_INVERTED), "turned over");
@@ -194,19 +255,77 @@ mod tests {
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), ([0.0, 0.0], deg(359.0)), "a 6D Art Pen's barrel");
assert_eq!(pen_pose(all, 400, i32::MIN, 720), ([deg(90.0), deg(-90.0)], 0.0), "kept within the ranges");
let pose = pen_pose(all, 10, 20, 180);
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose);
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose, None);
assert_eq!((sample.tilt, sample.rotation), pose);
}
#[test]
fn an_airbrush_wheel_goes_into_the_sample() {
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, Some(0.25)).wheel, Some(0.25));
let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION;
let pose = pen_pose(all, 10, 20, 180);
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose, Some(0.75));
assert_eq!((sample.tilt, sample.rotation, sample.wheel), (pose.0, pose.1, Some(0.75)), "with the tilt and rotation");
assert_eq!(sample.pressure, 0.5, "the pressure as before");
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).wheel, None, "no wheel");
assert_eq!(pen_sample(0, 0, 0, false, UPRIGHT, Some(f32::NAN)).wheel, None, "not a number");
assert_eq!(pen_sample(0, 0, 0, false, UPRIGHT, Some(1.5)).wheel, Some(1.0), "kept within 0..1");
}
#[test]
fn leaving_range_or_the_window_and_a_cancel_forget_the_wheel() {
let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7;
let canceled = ((POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_CANCELED) << 16) | 7;
let pen = Some(7);
for m in [WM_POINTERENTER, WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] {
assert!(!forgets_wheel(m, in_range, pen), "{m:#x}");
assert!(forgets_wheel(m, 7, pen), "out of range: {m:#x}");
assert!(forgets_wheel(m, canceled, pen), "canceled: {m:#x}");
}
assert!(forgets_wheel(WM_POINTERLEAVE, in_range, pen));
// WM_MOUSEMOVE and WT_PACKET.
assert!(!forgets_wheel(0x0200, 0, Some(0)));
assert!(!forgets_wheel(0x7FF0, 7, pen));
}
#[test]
fn another_pointer_leaving_keeps_the_wheel() {
// A touch, pointer 9, leaves the window and detection range while pen 7 hovers.
let touch_leaves = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9;
assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, Some(7)));
assert!(!forgets_wheel(WM_POINTERUPDATE, 9, Some(7)), "out of range");
let canceled = (POINTER_MESSAGE_FLAG_CANCELED << 16) | 9;
assert!(!forgets_wheel(WM_POINTERUP, canceled, Some(7)), "canceled");
assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, None), "no pen has read the wheel");
assert!(forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7, Some(7)), "the pen itself");
}
#[test]
fn the_sent_leave_of_the_wheel_pen_forgets_the_wheel() {
let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7;
let pen = Some(7);
assert!(sent_forgets_wheel(WM_POINTERLEAVE, in_range, pen), "the pen leaves the window");
assert!(sent_forgets_wheel(WM_POINTERLEAVE, 7, pen), "or detection range");
assert!(!sent_forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9, pen), "another pointer leaves");
assert!(!sent_forgets_wheel(WM_POINTERLEAVE, in_range, None), "no pen has read the wheel");
assert!(!sent_forgets_wheel(WM_POINTERENTER, in_range, pen), "the pen comes over the window");
// Posted messages, which the message hook already sees.
for m in [WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] {
assert!(!sent_forgets_wheel(m, 7, pen), "{m:#x}");
}
// WT_CTXCLOSE.
assert!(!sent_forgets_wheel(0x7FF2, 7, pen));
}
#[test]
fn a_pens_pressure_is_the_one_winit_gives_its_touch() {
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 0.5);
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0);
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT), eraser_sample(0.0), "hovering");
assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT).pressure, 1.0, "a pressure without the pressure mask is not one");
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0, "as winit, which gives no force for 0");
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT).pressure, 0.0);
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 0.5);
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0);
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT, None), eraser_sample(0.0), "hovering");
assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pressure without the pressure mask is not one");
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0, "as winit, which gives no force for 0");
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT, None).pressure, 0.0);
}
#[test]
File diff suppressed because it is too large. Load diff
+7 -17
View File
@@ -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
+2 -26
View File
@@ -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)]) {
+72
View File
@@ -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());
}
+1 -1
View File
@@ -309,7 +309,7 @@ pub struct Scatter {
pub art: Node,
/// Size range in percent of the art.
pub size: (f64, f64),
/// Spacing range in percent of the (scaled) art width.
/// Spacing range in percent of the (scaled) art width, its strokes included.
pub spacing: (f64, f64),
/// Perpendicular offset range in percent of the (scaled) art height.
pub scatter: (f64, f64),
+16
View File
@@ -272,6 +272,22 @@ fn scatter_count_and_spacing() {
assert_eq!(out.len(), 5);
}
#[test]
fn scatter_spaces_stroked_art_by_its_stroked_width() {
let art = Node::path(
NodeId(0),
shapes::rectangle(Rect::new(0.0, -2.0, 10.0, 2.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0),
);
let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) };
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 120.0, 0.0), &stroke(1.0));
let boxes: Vec<Rect> = out.iter().filter_map(Node::visual_bounds).collect();
assert!(boxes.len() > 1, "{boxes:?}");
for w in boxes.windows(2) {
assert!(near(w[1].x0, w[0].x1, 1e-6), "stroked copies at 100% spacing touch: {boxes:?}");
}
}
#[test]
fn scatter_is_deterministic_and_randomised() {
let b = Brush {
+25 -5
View File
@@ -540,7 +540,10 @@ fn vary(rng: &mut Rng, (a, b): (f64, f64), mode: Variation, pen: PenAt) -> f64 {
pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec<Node> {
let Some(b) = sc.art.geometric_bounds() else { return vec![] };
let (aw, ah) = (b.width().max(1e-3), b.height().max(1e-3));
// Copies are spaced by the width of the art with its strokes, so at 100% spacing stroked
// copies touch instead of overlapping by the stroke.
let aw = sc.art.visual_bounds().unwrap_or(b).width().max(1e-3);
let ah = b.height().max(1e-3);
let mut rng = Rng::new(seed_of(bp, name));
let [size_mode, spacing_mode, scatter_mode, rotation_mode] = sc.modes();
let mut out = Budget::default();
@@ -1129,11 +1132,23 @@ mod tests {
/// Fitting is bounded however badly the map behaves: where it gives points that are not finite
/// the tile falls back to chords with those points left out (or to nothing), and where it never
/// fits (a map that jumps everywhere) the halving stops at its depth and anchor count. Either
/// way the call comes back promptly with finite geometry.
/// way the call comes back with finite geometry, having called the map a bounded number of
/// times.
#[test]
fn a_map_that_misbehaves_still_returns_promptly_and_finite() {
let b = Rect::new(0.0, -20.0, 40.0, 20.0);
let tile = circle_tile(b);
// Each piece the fitting tries reads its two ends, the derivatives there and the checks
// between them. Fitted pieces are at most the chords, so the halving tries at most twice
// as many pieces plus those on the way down to the one that gives up. The chord route
// maps each chord point once more.
let NodeKind::Path { path, .. } = &tile.kind else { panic!("the tile is a path") };
let allowed: usize = path
.subpaths
.iter()
.filter_map(|sp| densified(sp, 0.25, 1.5))
.map(|dense| 1 + (FIT_CHECKS + 3) * (2 * dense.len() + FIT_DEPTH as usize + 1) + dense.len())
.sum();
let finite = |n: &Node| match &n.kind {
NodeKind::Path { path, .. } => {
path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite())
@@ -1147,9 +1162,14 @@ mod tests {
&|_| Point::new(f64::NAN, f64::NAN),
];
for (i, f) in maps.iter().enumerate() {
let t0 = std::time::Instant::now();
let out = warp_node(&tile, f, 0.25, 1.5, 0.25, 1.0);
assert!(t0.elapsed() < std::time::Duration::from_secs(2), "map {i} took {:?}", t0.elapsed());
// Past the allowance the map places nothing, so a warp that keeps calling it stops.
let calls = std::cell::Cell::new(0usize);
let counted = |p: Point| {
calls.set(calls.get() + 1);
if calls.get() > allowed { Point::new(f64::NAN, f64::NAN) } else { f(p) }
};
let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0);
assert!(calls.get() <= allowed, "map {i} was called {} times, {allowed} allowed", calls.get());
match (i, &out) {
(3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"),
(_, Some(n)) => assert!(finite(n), "map {i} drew non-finite geometry"),
+15 -2
View File
@@ -708,16 +708,29 @@ fn rgb_color([r, g, b]: [u8; 3]) -> Color {
Color::rgb8(r, g, b)
}
#[cfg(test)]
thread_local! {
/// How many names [`unique`] tried on this thread (tests).
pub(crate) static SYMBOL_NAMES_TRIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Whether `taken` holds `name`, counted as one name tried (tests).
fn is_taken(taken: &HashSet<String>, name: &str) -> bool {
#[cfg(test)]
SYMBOL_NAMES_TRIED.with(|n| n.set(n.get().saturating_add(1)));
taken.contains(name)
}
/// `base`, or `base 2`, `base 3`… when taken; `next` remembers where each base left off.
fn unique(base: &str, next: &mut HashMap<String, usize>, taken: &HashSet<String>) -> String {
if !taken.contains(base) {
if !is_taken(taken, base) {
return base.to_string();
}
let i = next.entry(base.to_string()).or_insert(2);
loop {
let name = format!("{base} {i}");
*i += 1;
if !taken.contains(&name) {
if !is_taken(taken, &name) {
return name;
}
}
+27 -1
View File
@@ -175,6 +175,32 @@ fn layer(l: model::Layer) -> LayerDef {
/// drawings have a few dozen layouts with short names.
const MAX_LAYOUT_NAME_BYTES: usize = 4 << 20;
#[cfg(test)]
thread_local! {
/// How many times [`layouts`] compared two layout names on this thread (tests).
pub(crate) static LAYOUT_NAME_COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// A paper layout's name as [`layouts`] de-duplicates it (lower case: names differing only in
/// ASCII case are one layout).
struct LayoutKey(String);
impl PartialEq for LayoutKey {
fn eq(&self, other: &Self) -> bool {
#[cfg(test)]
LAYOUT_NAME_COMPARISONS.with(|n| n.set(n.get().saturating_add(1)));
self.0 == other.0
}
}
impl Eq for LayoutKey {}
impl std::hash::Hash for LayoutKey {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
/// Model space, then each paper layout (its LAYOUT object, in tab order); a file without layout
/// objects but with paper-space art has one paper layout.
fn layouts(doc: &model::Document<'_>, block_names: &HashMap<u64, &str>) -> Vec<LayoutDef> {
@@ -187,7 +213,7 @@ fn layouts(doc: &model::Document<'_>, block_names: &HashMap<u64, &str>) -> Vec<L
continue;
}
let Some(block) = block else { continue };
let key = l.name.to_ascii_lowercase();
let key = LayoutKey(l.name.to_ascii_lowercase());
let cost = l.name.len() + block.len();
// A layout past the allowance is skipped alone: a later short one is still offered, and a
// skipped one reserves neither its name nor its bytes.
+9 -7
View File
@@ -743,15 +743,16 @@ fn many_by_block_looks_import_in_linear_time() {
inserts.extend([(0, "INSERT"), (2, "Door"), (420, colour), (10, "0"), (20, "0")]);
}
let text = with_door(by_block, &inserts);
let start = std::time::Instant::now();
build::SYMBOL_NAMES_TRIED.with(|t| t.set(0));
let doc = open(&text, &points()).document;
let took = start.elapsed();
let tried = build::SYMBOL_NAMES_TRIED.with(std::cell::Cell::get);
let mut names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names.len(), n);
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), n, "names stay unique");
assert!(took < std::time::Duration::from_secs(4), "import took {took:?}");
// Each symbol after the first tries its label and then the next free suffix.
assert!(tried < 2 * n, "{tried} names tried for {n} symbols");
}
#[test]
@@ -1001,7 +1002,7 @@ fn binary_dwg_damaged_and_foreign_files() {
// A binary DXF opens as its ASCII form does.
let ascii = entities(LINE);
let tags = craft_dxf::parse(&ascii).unwrap();
let r = open(&craft_dxf::write_binary(&tags, true), &points());
let r = open(&craft_dxf::write_binary(&tags, true).unwrap(), &points());
assert_eq!(leaves(&r.document).len(), 1);
let e = import(b"AC1032\x00\x00\x00", &ImportOptions::default()).unwrap_err();
assert!(e.contains("DWG"), "{e}");
@@ -1151,12 +1152,13 @@ fn with_layouts(names: &[String]) -> Vec<u8> {
#[test]
fn many_paper_layouts_are_read_in_linear_time() {
let names: Vec<String> = (0..100_000).map(|i| format!("L{i}")).collect();
let names: Vec<String> = (0..10_000).map(|i| format!("L{i}")).collect();
let bytes = with_layouts(&names);
let t = std::time::Instant::now();
reader::LAYOUT_NAME_COMPARISONS.with(|c| c.set(0));
let info = info(&bytes).unwrap();
let compared = reader::LAYOUT_NAME_COMPARISONS.with(std::cell::Cell::get);
assert_eq!(info.layouts.len(), names.len() + 1);
assert!(t.elapsed() < std::time::Duration::from_secs(5), "layout de-duplication is quadratic: {:?}", t.elapsed());
assert!(compared <= names.len(), "layout de-duplication compared {compared} names for {} layouts", names.len());
}
#[test]
+1
View File
@@ -22,3 +22,4 @@ moxcms = "0.8"
[dev-dependencies]
proptest = { workspace = true }
serde_json = { workspace = true }
sha2 = { version = "0.10", default-features = false }
+2
View File
@@ -0,0 +1,2 @@
# The characterization data files are kept byte for byte as published (CRLF line endings).
*.txt -text
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+58 -9
View File
@@ -5,7 +5,9 @@
//! (1998 primaries), Display P3, ProPhoto RGB) or user `.icc` files. Display output is sRGB;
//! the desktop canvas converts it into the display's own profile last, in the app.
//! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model
//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers);
//! ([`generic`]); [`FOGRA51_CMYK`] and [`FOGRA52_CMYK`] are the same model computed from
//! Fogra's published characterization data ([`measured`]); [`DEVICE_CMYK`] is the old
//! profile-free formula (kept for exact legacy numbers);
//! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles).
//! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with
//! the profiles [`use_document_profiles`] last put in place of the working spaces;
@@ -16,6 +18,7 @@
pub mod generic;
pub mod icc;
pub mod lab;
pub mod measured;
use std::cell::{Cell, RefCell};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -36,6 +39,12 @@ pub const DISPLAY_P3: &str = "Display P3";
pub const PROPHOTO_RGB: &str = "ProPhoto RGB";
/// Our parametric press model (see [`generic`]). Not an Adobe/ECI profile.
pub const GENERIC_CMYK: &str = "VectorCraft Generic CMYK (SWOP-like)";
/// VectorCraft's own press model computed from Fogra's FOGRA51 characterization data (offset on
/// premium coated paper, see [`measured`]).
pub const FOGRA51_CMYK: &str = "VectorCraft Coated CMYK (FOGRA51)";
/// VectorCraft's own press model computed from Fogra's FOGRA52 characterization data (offset on
/// wood-free uncoated paper, see [`measured`]).
pub const FOGRA52_CMYK: &str = "VectorCraft Uncoated CMYK (FOGRA52)";
/// Profile-free CMYK (`rgb = (1−c)(1−k)` …): uncalibrated, kept for legacy numbers.
pub const DEVICE_CMYK: &str = "Device CMYK (uncalibrated)";
/// The grey space greyscale exports are written in: sRGB's tone curve (a grey shows as on screen).
@@ -43,7 +52,7 @@ pub const GRAY: &str = "Gray (sRGB tone curve)";
/// Built-in RGB and CMYK working spaces, in menu order.
const BUILTIN_RGB: [&str; 4] = [SRGB, WIDE_GAMUT_RGB, DISPLAY_P3, PROPHOTO_RGB];
const BUILTIN_CMYK: [&str; 2] = [GENERIC_CMYK, DEVICE_CMYK];
const BUILTIN_CMYK: [&str; 4] = [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK];
/// Names earlier versions gave built-in profiles: (old name, current name). Settings, documents
/// and commands that still use an old name get the current profile.
@@ -239,6 +248,21 @@ fn generic() -> Arc<GenericCmyk> {
G.get_or_init(|| Arc::new(GenericCmyk::new(generic::swop_like()))).clone()
}
/// The working space of `condition`, computed from its data once and kept.
fn measured_space(condition: &measured::Condition) -> Result<Arc<GenericCmyk>, CmsError> {
static SPACES: [OnceLock<Option<Arc<GenericCmyk>>>; measured::CONDITIONS.len()] = [const { OnceLock::new() }; measured::CONDITIONS.len()];
let slot = measured::CONDITIONS.iter().position(|c| c.name == condition.name).and_then(|i| SPACES.get(i));
slot.and_then(|s| s.get_or_init(|| measured::model(condition).map(Arc::new)).clone())
.ok_or_else(|| CmsError::BadProfile(format!("{}: the {} data does not give a press model", condition.name, condition.reference)))
}
/// The registered printing condition a built-in CMYK working space characterizes: its reference
/// name, the `/OutputConditionIdentifier` of a PDF/X output intent, and the registry it belongs
/// to (by its current or legacy name). `None` for every other profile.
pub fn characterization(name: &str) -> Option<(&'static str, &'static str)> {
measured::condition(canonical_name(name)).map(|c| (c.reference, measured::REGISTRY))
}
static USER: RwLock<Vec<Arc<IccProfile>>> = RwLock::new(Vec::new());
/// Counts the profiles [`register_icc`] has registered ([`profiles_generation`]).
static PROFILES_GENERATION: AtomicU64 = AtomicU64::new(0);
@@ -259,7 +283,11 @@ fn user_profile(name: &str) -> Option<Arc<IccProfile>> {
}
fn cmyk_space(name: &str) -> Result<CmykSpace, CmsError> {
match canonical_name(name) {
let canonical = canonical_name(name);
if let Some(c) = measured::condition(canonical) {
return measured_space(c).map(CmykSpace::Generic);
}
match canonical {
GENERIC_CMYK => Ok(CmykSpace::Generic(generic())),
DEVICE_CMYK => Ok(CmykSpace::Device),
_ => match user_profile(name) {
@@ -382,9 +410,13 @@ pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> {
CmykSpace::Generic(g) => g.paper_xyz(),
CmykSpace::Device | CmykSpace::Icc(_) => lab::D50,
};
let copyright = match measured::condition(name) {
Some(c) => format!("Computed by VectorCraft from the {} characterization data. Data source: Fogra, www.fogra.org", c.reference),
None => icc::NO_COPYRIGHT.to_string(),
};
let to_lab = |c| cms.cmyk_to_lab(c);
let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric);
icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
icc::encode(&icc::cmyk_profile(name, paper, &copyright, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
} else {
icc::builtin_rgb_bytes(name)?
}
@@ -496,7 +528,8 @@ impl Cms {
/// directly into the RGB profile: not through display sRGB, which would clip colours a wider
/// RGB space holds (Wide Gamut RGB keeps CMYK cyan that sRGB can't show), and with the
/// settings' black-point compensation. The built-in CMYK spaces go through sRGB as before
/// (Generic CMYK compensates in its own model).
/// (Generic CMYK compensates in its own model); with the absolute colorimetric intent the
/// paper colour shows.
pub fn cmyk_to_rgb(&self, cmyk: [f32; 4], intent: Intent) -> [f32; 3] {
let cmyk = cmyk.map(|v| v.clamp(0.0, 1.0));
let src = match &self.cmyk {
@@ -509,7 +542,7 @@ impl Cms {
};
src.zip(dest)
.and_then(|(s, d)| s.to_rgb_of(&d, &cmyk, intent, self.settings.bpc))
.unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, false)))
.unwrap_or_else(|| self.srgb_to_rgb(self.cmyk_to_srgb(cmyk, intent == Intent::AbsoluteColorimetric)))
}
/// Display sRGB → working CMYK with `intent`.
pub fn srgb_to_cmyk(&self, srgb: [f32; 3], intent: Intent) -> [f32; 4] {
@@ -1178,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();
}
@@ -1208,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;
@@ -1248,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 {
@@ -1275,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);
@@ -1315,3 +1362,5 @@ pub(crate) fn cmyk_is_device() -> bool {
mod tests;
#[cfg(test)]
mod tests_icc;
#[cfg(test)]
mod tests_measured;
+30 -2
View File
@@ -30,6 +30,7 @@ use std::sync::OnceLock;
use super::Intent;
use super::lab::{D50, Lab, delta_e2000, lab_to_xyz, srgb_to_lab, xyz_to_lab, xyz_to_srgb};
use super::measured::Lattice;
/// Black generation.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -129,6 +130,9 @@ pub struct GenericCmyk {
paper_xyz: [f32; 3],
/// Media-relative XYZ of the black point (for black-point compensation).
black_rel: [f32; 3],
/// A media-relative Lab correction added to the model, fitted to measured data
/// ([`super::measured`]).
correction: Option<Lattice>,
gbd: OnceLock<Gbd>,
}
@@ -139,6 +143,15 @@ impl GenericCmyk {
}
pub fn new(params: GenericCmykParams) -> Self {
Self::build(params, None)
}
/// The model of `params` with `correction` added to its media-relative Lab.
pub fn with_correction(params: GenericCmykParams, correction: Lattice) -> Self {
Self::build(params, Some(correction))
}
fn build(params: GenericCmykParams, correction: Option<Lattice>) -> Self {
let paper_xyz = lab_to_xyz(params.paper);
let mut prim = [D50; 16];
for (p, lab) in prim[1..].iter_mut().zip(params.primaries.iter()) {
@@ -149,7 +162,7 @@ impl GenericCmyk {
let g = params.tvi50[i];
if g > 1e-6 { (1.0 - params.tvi40[i] / (0.96 * g)) / 0.2 } else { 0.0 }
});
let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], gbd: OnceLock::new() };
let mut g = Self { params, prim, skew, paper_xyz, black_rel: [0.0; 3], correction, gbd: OnceLock::new() };
g.black_rel = g.to_xyz_rel(g.black_point_build());
g
}
@@ -218,6 +231,14 @@ impl GenericCmyk {
/// Media-relative XYZ (paper = D50 white).
pub fn to_xyz_rel(&self, cmyk: [f32; 4]) -> [f32; 3] {
match &self.correction {
Some(_) => lab_to_xyz(self.to_lab_rel(cmyk)),
None => self.neugebauer(cmyk),
}
}
/// Media-relative XYZ of the Neugebauer model alone.
fn neugebauer(&self, cmyk: [f32; 4]) -> [f32; 3] {
let e = [0, 1, 2, 3].map(|i| self.gain(i, cmyk[i]));
let mut out = [0.0f32; 3];
for (i, p) in self.prim.iter().enumerate() {
@@ -236,7 +257,14 @@ impl GenericCmyk {
}
pub fn to_lab_rel(&self, cmyk: [f32; 4]) -> Lab {
xyz_to_lab(self.to_xyz_rel(cmyk))
let lab = xyz_to_lab(self.neugebauer(cmyk));
match &self.correction {
Some(c) => {
let d = c.at(cmyk);
Lab::new((lab.l + d[0]).max(0.0), lab.a + d[1], lab.b + d[2])
}
None => lab,
}
}
pub fn to_lab_abs(&self, cmyk: [f32; 4]) -> Lab {
xyz_to_lab(self.to_xyz(cmyk))
+12 -4
View File
@@ -432,10 +432,17 @@ fn text_tag(s: &str) -> Option<ProfileText> {
Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), s.into())]))
}
/// The copyright text of profiles made here: they carry no copyright claim.
pub(super) const NO_COPYRIGHT: &str = "No copyright, use freely";
/// Profiles made here carry their name and no copyright claim.
fn labelled(mut p: ColorProfile, name: &str) -> ColorProfile {
fn labelled(p: ColorProfile, name: &str) -> ColorProfile {
with_copyright(p, name, NO_COPYRIGHT)
}
fn with_copyright(mut p: ColorProfile, name: &str, copyright: &str) -> ColorProfile {
p.description = text_tag(name);
p.copyright = text_tag("No copyright, use freely");
p.copyright = text_tag(copyright);
p
}
@@ -452,10 +459,11 @@ const GAMUT_GRID: usize = 9;
/// It carries every tag ICC.1 requires of an output profile: the tables for all three intents
/// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK
/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which
/// the ICC-absolute colorimetric intent reproduces.
/// the ICC-absolute colorimetric intent reproduces; the copyright tag holds `copyright`.
pub(super) fn cmyk_profile(
name: &str,
paper: [f32; 3],
copyright: &str,
to_lab: impl Fn([f32; 4]) -> lab::Lab,
mapped: impl Fn(lab::Lab) -> [f32; 4],
colorimetric: impl Fn(lab::Lab) -> [f32; 4],
@@ -520,7 +528,7 @@ pub(super) fn cmyk_profile(
p.lut_b_to_a_saturation = Some(b2a_mapped);
p.lut_b_to_a_colorimetric = Some(b2a);
p.gamut = Some(gamut);
labelled(p, name)
with_copyright(p, name, copyright)
}
/// The grey space of greyscale exports: sRGB's tone curve, D50 white.
+378
View File
@@ -0,0 +1,378 @@
//! CMYK working spaces computed from published characterization data.
//!
//! Fogra publishes the measured colors of its reference printing conditions
//! (<https://fogra.org/en/downloads/work-tools/characterisation-data>) and allows the data to be
//! redistributed unmodified, with Fogra named as the source. VectorCraft embeds the FOGRA51 and
//! FOGRA52 files byte for byte (`crates/color/data/`) and computes each press model from them the
//! first time it is used:
//!
//! * The paper is the measured blank patch. The 15 solids and overprints of the
//! [`super::generic`] model are the measured patches of those builds, and each ink's tone curve
//! is fitted to its single-ink ramp.
//! * What that model still misses at each patch (in media-relative Lab) is fitted with a smoothed
//! lattice over CMYK ([`Lattice`]), which [`GenericCmyk::to_xyz_rel`] adds to the model. The
//! smoothing carries the fit into regions the patch set does not sample, such as dark builds
//! with more than 60% black.
//!
//! The total ink limit and the black generation are VectorCraft's own values.
use super::generic::{GenericCmyk, GenericCmykParams, swop_like};
use super::lab::{D50, Lab, lab_to_xyz, xyz_to_lab};
/// A printing condition with published characterization data.
#[derive(Clone, Copy, Debug)]
pub struct Condition {
/// The working space's name.
pub name: &'static str,
/// The reference name of the characterization data, which a PDF/X output intent uses as
/// its `/OutputConditionIdentifier`.
pub reference: &'static str,
/// The characterization data file, as published.
pub data: &'static [u8],
/// Total area coverage limit (sum of inks, 1.0 = 100%): VectorCraft's own value.
pub tac: f32,
}
/// The registry that the reference names of [`CONDITIONS`] belong to
/// (<https://registry.color.org/cmyk-registry/>).
pub const REGISTRY: &str = "http://www.color.org";
/// The printing conditions VectorCraft computes working spaces for.
pub const CONDITIONS: [Condition; 2] = [
Condition { name: super::FOGRA51_CMYK, reference: "FOGRA51", data: include_bytes!("../../data/FOGRA51.txt"), tac: 3.0 },
Condition { name: super::FOGRA52_CMYK, reference: "FOGRA52", data: include_bytes!("../../data/FOGRA52.txt"), tac: 3.0 },
];
/// The condition a working space of [`CONDITIONS`] is computed for.
pub fn condition(name: &str) -> Option<&'static Condition> {
CONDITIONS.iter().find(|c| c.name == name)
}
/// One measured patch: nominal inks (0..1) and absolute Lab (D50).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Patch {
pub cmyk: [f32; 4],
pub lab: Lab,
}
/// The most patches [`parse`] reads.
const MAX_PATCHES: usize = 20_000;
/// The patches of a CGATS / ISO 28178 characterization data file with `CMYK_C`, `CMYK_M`,
/// `CMYK_Y`, `CMYK_K`, `LAB_L`, `LAB_A` and `LAB_B` fields. `None` when a field is missing, a
/// row is short or holds a value that is not a finite number, an ink is outside 0 to 100, the
/// file has no rows, the rows do not end with `END_DATA`, or a `NUMBER_OF_SETS` in the header is
/// not the number of rows.
pub fn parse(data: &[u8]) -> Option<Vec<Patch>> {
let text = std::str::from_utf8(data).ok()?;
let sets = text.lines().map(str::trim).take_while(|l| *l != "BEGIN_DATA").find_map(|l| {
let mut words = l.split_whitespace();
(words.next() == Some("NUMBER_OF_SETS")).then(|| words.next().map(|n| n.trim_matches('"')))
});
let sets = match sets {
Some(n) => Some(n?.parse::<usize>().ok()?),
None => None,
};
let mut lines = text.lines().map(str::trim);
lines.by_ref().find(|l| *l == "BEGIN_DATA_FORMAT")?;
let mut fields = vec![];
for line in lines.by_ref() {
if line == "END_DATA_FORMAT" {
break;
}
fields.extend(line.split_whitespace());
}
let at = |f: &str| fields.iter().position(|x| *x == f);
let cols = [at("CMYK_C")?, at("CMYK_M")?, at("CMYK_Y")?, at("CMYK_K")?, at("LAB_L")?, at("LAB_A")?, at("LAB_B")?];
lines.by_ref().find(|l| *l == "BEGIN_DATA")?;
let mut out = vec![];
let mut ended = false;
for line in lines {
if line == "END_DATA" {
ended = true;
break;
}
if line.is_empty() {
continue;
}
if out.len() >= MAX_PATCHES {
return None;
}
let row: Vec<&str> = line.split_whitespace().collect();
let mut v = [0f32; 7];
for (slot, &col) in v.iter_mut().zip(&cols) {
*slot = row.get(col)?.parse::<f32>().ok().filter(|x| x.is_finite())?;
}
if v[..4].iter().any(|x| !(0.0..=100.0).contains(x)) {
return None;
}
out.push(Patch { cmyk: [v[0], v[1], v[2], v[3]].map(|x| x / 100.0), lab: Lab::new(v[4], v[5], v[6]) });
}
(ended && !out.is_empty() && sets.is_none_or(|n| n == out.len())).then_some(out)
}
/// Absolute Lab → media-relative Lab (`paper` maps to the D50 white).
fn relative(lab: Lab, paper: [f32; 3]) -> Lab {
let x = lab_to_xyz(lab);
xyz_to_lab([0, 1, 2].map(|i| x[i] * D50[i] / paper[i]))
}
/// The mean of the Lab values of the patches whose inks are `inks`, in XYZ.
fn mean_lab(patches: &[Patch], inks: [f32; 4]) -> Option<Lab> {
let mut sum = [0f32; 3];
let mut n = 0;
for p in patches.iter().filter(|p| p.cmyk.iter().zip(&inks).all(|(a, b)| (a - b).abs() < 1e-4)) {
let x = lab_to_xyz(p.lab);
for i in 0..3 {
sum[i] += x[i];
}
n += 1;
}
(n > 0).then(|| xyz_to_lab(sum.map(|v| v / n as f32)))
}
/// The tone value increase at 50% and 40% of ink `ink`, fitted to its single-ink ramp with the
/// curve of [`super::generic`]: the effective area is `a + u·4a(1−a) + v·4a(1−a)(2a−1)`, so the
/// 50% increase is `u` and the 40% increase is `0.96·u − 0.192·v`. Each patch's effective area
/// comes from the Murray–Davies formula in the media-relative XYZ channel the ink darkens most
/// (`paper` is the paper's absolute XYZ, `solid` the solid's media-relative XYZ).
fn tone_increase(patches: &[Patch], ink: usize, paper: [f32; 3], solid: [f32; 3]) -> Option<(f32, f32)> {
let ch = (0..3).max_by(|&a, &b| (D50[a] - solid[a]).abs().total_cmp(&(D50[b] - solid[b]).abs()))?;
let span = D50[ch] - solid[ch];
if span.abs() < 1e-4 {
return None;
}
let (mut s11, mut s12, mut s22, mut r1, mut r2) = (0f64, 0f64, 0f64, 0f64, 0f64);
for p in patches {
let a = p.cmyk[ink];
let alone = p.cmyk.iter().enumerate().all(|(i, v)| i == ink || *v == 0.0);
if !alone || a <= 0.0 || a >= 1.0 {
continue;
}
let e = (D50[ch] - relative_xyz(p.lab, paper)[ch]) / span;
let (b1, b2) = (f64::from(4.0 * a * (1.0 - a)), f64::from(4.0 * a * (1.0 - a) * (2.0 * a - 1.0)));
let d = f64::from(e - a);
s11 += b1 * b1;
s12 += b1 * b2;
s22 += b2 * b2;
r1 += b1 * d;
r2 += b2 * d;
}
let det = s11 * s22 - s12 * s12;
if det.abs() < 1e-12 {
return None;
}
let u = ((r1 * s22 - r2 * s12) / det) as f32;
let v = ((s11 * r2 - s12 * r1) / det) as f32;
let tvi50 = u.clamp(0.0, 0.45);
let tvi40 = (0.96 * u - 0.192 * v).clamp(0.0, 0.45);
Some((tvi50, tvi40))
}
/// Absolute Lab → media-relative XYZ.
fn relative_xyz(lab: Lab, paper: [f32; 3]) -> [f32; 3] {
let x = lab_to_xyz(lab);
[0, 1, 2].map(|i| x[i] * D50[i] / paper[i])
}
/// The press model of `condition`, computed from its data. `None` when the data does not parse,
/// lacks the paper, a solid or overprint, or a single-ink ramp, or gives a paper whose XYZ is not
/// positive and finite.
pub fn model(condition: &Condition) -> Option<GenericCmyk> {
fit(condition, &parse(condition.data)?, SMOOTHING)
}
/// The press model of `condition` fitted to `patches`, with the lattice's `smoothing` (`None` in
/// the cases [`model`] lists).
pub(crate) fn fit(condition: &Condition, patches: &[Patch], smoothing: f64) -> Option<GenericCmyk> {
let paper = mean_lab(patches, [0.0; 4])?;
let paper_xyz = lab_to_xyz(paper);
if paper_xyz.iter().any(|v| !v.is_finite() || *v <= 0.0) {
return None;
}
let mut primaries = [Lab::new(0.0, 0.0, 0.0); 15];
for (i, slot) in primaries.iter_mut().enumerate() {
let bits = i + 1;
let inks = [0, 1, 2, 3].map(|b| if bits & (1 << b) != 0 { 1.0 } else { 0.0 });
*slot = relative(mean_lab(patches, inks)?, paper_xyz);
}
let mut tvi50 = [0f32; 4];
let mut tvi40 = [0f32; 4];
for ink in 0..4 {
let solid = lab_to_xyz(primaries[(1 << ink) - 1]);
(tvi50[ink], tvi40[ink]) = tone_increase(patches, ink, paper_xyz, solid)?;
}
let params = GenericCmykParams { name: condition.name, paper, primaries, tvi50, tvi40, tac: condition.tac, bg: swop_like().bg };
let base = GenericCmyk::new(params.clone());
let points: Vec<([f32; 4], [f32; 3])> = patches
.iter()
.map(|p| {
let want = relative(p.lab, paper_xyz);
let got = base.to_lab_rel(p.cmyk);
(p.cmyk, [want.l - got.l, want.a - got.a, want.b - got.b])
})
.collect();
Some(GenericCmyk::with_correction(params, Lattice::fit(&points, smoothing)))
}
/// Weight of the lattice's smoothness against its fit to the patches.
pub(crate) const SMOOTHING: f64 = 0.02;
/// Knots of each ink's axis of the [`Lattice`]: the steps of the published single-ink ramps.
const KNOTS: [f32; 9] = [0.0, 0.1, 0.2, 0.3, 0.4, 0.55, 0.7, 0.85, 1.0];
const N: usize = KNOTS.len();
const NODES: usize = N * N * N * N;
/// A Lab correction over CMYK, read by multilinear interpolation between nodes at [`KNOTS`].
#[derive(Clone, Debug)]
pub struct Lattice {
values: Vec<[f32; 3]>,
}
/// The cell of `v` along an axis and its position in it.
fn locate(v: f32) -> (usize, f32) {
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
let i = KNOTS.iter().skip(1).position(|k| v <= *k).unwrap_or(N - 2).min(N - 2);
let (lo, hi) = (KNOTS[i], KNOTS[i + 1]);
(i, ((v - lo) / (hi - lo)).clamp(0.0, 1.0))
}
/// The 16 nodes around `cmyk` with their interpolation weights.
fn corners(cmyk: [f32; 4]) -> [(usize, f32); 16] {
let cells = cmyk.map(locate);
let mut out = [(0, 0.0); 16];
for (corner, slot) in out.iter_mut().enumerate() {
let mut index = 0;
let mut w = 1.0;
for (axis, (cell, t)) in cells.iter().enumerate() {
let up = corner & (1 << axis) != 0;
index = index * N + cell + usize::from(up);
w *= if up { *t } else { 1.0 - t };
}
*slot = (index, w);
}
out
}
/// Index strides of the four axes (C is the slowest).
const STRIDES: [usize; 4] = [N * N * N, N * N, N, 1];
impl Lattice {
/// The correction at `cmyk`.
pub fn at(&self, cmyk: [f32; 4]) -> [f32; 3] {
let mut out = [0f32; 3];
for (i, w) in corners(cmyk) {
if w == 0.0 {
continue;
}
let v = self.values.get(i).copied().unwrap_or_default();
for c in 0..3 {
out[c] += w * v[c];
}
}
out
}
/// The lattice that best fits `points` (inks, correction) in the least-squares sense, with
/// `smoothing` times the squared second differences of the nodes along each axis added to the
/// error. The node at no ink stays 0, so the paper keeps the model's color (white, media-
/// relative). Solved by conjugate gradients, one Lab channel at a time.
pub fn fit(points: &[([f32; 4], [f32; 3])], smoothing: f64) -> Lattice {
let weights: Vec<[(usize, f32); 16]> = points.iter().map(|(cmyk, _)| corners(*cmyk)).collect();
// The divided second difference at interior knot j, scaled to a unit spacing of 1/8.
let curvature: Vec<[f64; 3]> = (1..N - 1)
.map(|j| {
let (h1, h2) = (f64::from(KNOTS[j] - KNOTS[j - 1]), f64::from(KNOTS[j + 1] - KNOTS[j]));
let s = 0.125f64 * 0.125;
[2.0 / (h1 * (h1 + h2)) * s, -2.0 / (h1 * h2) * s, 2.0 / (h2 * (h1 + h2)) * s]
})
.collect();
let apply = |x: &[f64], out: &mut [f64]| {
out.fill(0.0);
for w in &weights {
let v: f64 = w.iter().map(|(i, w)| f64::from(*w) * x.get(*i).copied().unwrap_or(0.0)).sum();
for (i, w) in w {
if let Some(o) = out.get_mut(*i) {
*o += f64::from(*w) * v;
}
}
}
for node in 0..NODES {
let mut rest = node;
for stride in STRIDES {
let j = rest / stride;
rest %= stride;
// Only interior knots (1 to N − 2) have a second difference.
let Some(c) = j.checked_sub(1).and_then(|k| curvature.get(k)) else { continue };
let idx = [node - stride, node, node + stride];
let d: f64 = idx.iter().zip(c).map(|(i, c)| c * x.get(*i).copied().unwrap_or(0.0)).sum();
for (i, c) in idx.iter().zip(c) {
if let Some(o) = out.get_mut(*i) {
*o += smoothing * c * d;
}
}
}
}
for (o, v) in out.iter_mut().zip(x) {
*o += 1e-9 * v;
}
// The paper's node is held: with its right-hand side 0 it stays 0 in every iterate.
if let (Some(o), Some(v)) = (out.first_mut(), x.first()) {
*o = *v;
}
};
let mut values = vec![[0f32; 3]; NODES];
for ch in 0..3 {
let mut b = vec![0f64; NODES];
for (w, (_, r)) in weights.iter().zip(points) {
for (i, w) in w {
if let Some(o) = b.get_mut(*i) {
*o += f64::from(*w) * f64::from(r[ch]);
}
}
}
if let Some(o) = b.first_mut() {
*o = 0.0;
}
let x = conjugate_gradients(&apply, &b, 4000);
for (v, x) in values.iter_mut().zip(&x) {
v[ch] = *x as f32;
}
}
Lattice { values }
}
}
/// Solve `A x = b` for the symmetric positive definite `A` that `apply` multiplies by.
fn conjugate_gradients(apply: &dyn Fn(&[f64], &mut [f64]), b: &[f64], max_iterations: usize) -> Vec<f64> {
let n = b.len();
let mut x = vec![0f64; n];
let mut r = b.to_vec();
let mut p = r.clone();
let mut ap = vec![0f64; n];
let dot = |a: &[f64], b: &[f64]| a.iter().zip(b).map(|(a, b)| a * b).sum::<f64>();
let mut rr = dot(&r, &r);
let stop = rr * 1e-20;
for _ in 0..max_iterations {
if rr <= stop || rr == 0.0 {
break;
}
apply(&p, &mut ap);
let pap = dot(&p, &ap);
if pap <= 0.0 || !pap.is_finite() {
break;
}
let alpha = rr / pap;
for i in 0..n {
x[i] += alpha * p[i];
r[i] -= alpha * ap[i];
}
let next = dot(&r, &r);
let beta = next / rr;
rr = next;
for i in 0..n {
p[i] = r[i] + beta * p[i];
}
}
x
}
+27
View File
@@ -519,6 +519,33 @@ fn with_active_puts_settings_in_place_on_this_thread_only() {
assert_eq!((rgb.to_rgb(), ink.to_rgb()), before, "the active settings come back after a panic");
}
#[test]
fn with_active_keeps_its_working_settings_while_another_thread_sets_them() {
let before = working_settings();
let p3 = Arc::new(Cms::new(&ColorSettings { rgb: DISPLAY_P3.into(), cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap());
let (inside, after_other, other) = with_active(p3.clone(), || {
let inside = working();
// The same settings again, so other tests in this binary see the same values.
let again = before.clone();
let other = std::thread::spawn(move || {
set_active(&again).unwrap();
working()
})
.join()
.unwrap();
(inside, working(), other)
});
assert!(Arc::ptr_eq(&inside, &p3), "settings made from no others are their own working settings");
assert!(Arc::ptr_eq(&after_other, &p3), "a set_active on another thread leaves this thread's working settings");
assert!(!Arc::ptr_eq(&other, &p3), "the other thread has the settings it set");
assert_eq!(working_settings(), before, "the working settings come back after");
// A document's context keeps the working settings it was made from.
let doc = for_document(Some(DISPLAY_P3), None);
let (active, working) = with_active(doc, || (active_settings(), working_settings()));
assert_eq!(active.rgb, DISPLAY_P3, "the document's profile is active");
assert_eq!(working, before, "the working RGB space stays the working one");
}
#[test]
fn a_document_gets_the_same_context_for_the_same_profiles() {
// Other tests load profiles meanwhile, and a load makes the contexts again: try until one pair
+250
View File
@@ -0,0 +1,250 @@
use super::*;
use sha2::{Digest, Sha256};
fn hex(bytes: &[u8]) -> String {
Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
}
/// The data files ship exactly as Fogra publishes them in
/// https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip.
#[test]
fn characterization_data_is_the_published_files() {
let want = [
("FOGRA51", "ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5", 57_111),
("FOGRA52", "be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6", 56_781),
];
for (c, (reference, sha, len)) in measured::CONDITIONS.iter().zip(want) {
assert_eq!(c.reference, reference);
assert_eq!((c.data.len(), hex(c.data).as_str()), (len, sha), "{reference}");
}
}
#[test]
fn the_data_parses_into_its_patches() {
for c in &measured::CONDITIONS {
let patches = measured::parse(c.data).unwrap();
assert_eq!(patches.len(), 1617, "{}", c.reference);
assert_eq!(patches[0].cmyk, [0.0; 4]);
}
let p = measured::parse(measured::CONDITIONS[0].data).unwrap();
assert_eq!(p[0].lab, Lab::new(95.0, 1.5, -6.0));
assert_eq!(p[1].cmyk, [0.0, 0.1, 0.0, 0.0]);
assert_eq!(p[1].lab, Lab::new(90.08, 8.15, -7.42));
}
#[test]
fn malformed_data_is_refused() {
let file = |format: &str, rows: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{format}\nEND_DATA_FORMAT\nBEGIN_DATA\n{rows}\nEND_DATA\n");
let fields = "SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B";
let good = file(fields, "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50");
assert_eq!(measured::parse(good.as_bytes()).map(|p| p.len()), Some(2));
for bad in [
file("SAMPLE_ID CMYK_C CMYK_M CMYK_Y LAB_L LAB_A LAB_B", "1 0 0 0 95 1 -6"),
file(fields, "1 0 0 0 0 95 1"),
file(fields, "1 0 0 0 0 95 NaN -6"),
file(fields, "1 0 0 0 0 95 x -6"),
file(fields, "1 0 0 0 101 95 1 -6"),
file(fields, "1 -1 0 0 0 95 1 -6"),
file(fields, ""),
"BEGIN_DATA\n1 0 0 0 0 95 1 -6\nEND_DATA\n".into(),
] {
assert_eq!(measured::parse(bad.as_bytes()), None, "{bad}");
}
assert_eq!(measured::parse(&[0xff, 0xfe, 0x00]), None);
// The rows end with END_DATA, and a NUMBER_OF_SETS in the header counts them.
let rows = "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50";
let header = |sets: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{fields}\nEND_DATA_FORMAT\n{sets}\nBEGIN_DATA\n{rows}\n");
assert_eq!(measured::parse(header("NUMBER_OF_SETS\t2").as_bytes()), None, "no END_DATA");
for (sets, len) in [
("NUMBER_OF_SETS\t2", Some(2)),
("NUMBER_OF_SETS\t3", None),
("NUMBER_OF_SETS\t1", None),
("NUMBER_OF_SETS\tx", None),
("NUMBER_OF_SETS", None),
] {
assert_eq!(measured::parse(format!("{}END_DATA\n", header(sets)).as_bytes()).map(|p| p.len()), len, "{sets}");
}
}
/// A paper measured as black has no XYZ to make the other patches relative to.
#[test]
fn a_paper_without_light_is_refused() {
let c = &measured::CONDITIONS[0];
let mut patches = measured::parse(c.data).unwrap();
for p in patches.iter_mut().filter(|p| p.cmyk == [0.0; 4]) {
p.lab = Lab::new(0.0, 0.0, 0.0);
}
assert!(measured::fit(c, &patches, measured::SMOOTHING).is_none());
}
/// ΔE2000 between each measured patch and the model's absolute Lab for its inks: (mean, max).
fn accuracy(g: &GenericCmyk, patches: &[measured::Patch]) -> (f32, f32) {
let errors: Vec<f32> = patches.iter().map(|p| delta_e2000(g.to_lab_abs(p.cmyk), p.lab)).collect();
(errors.iter().sum::<f32>() / errors.len() as f32, errors.iter().copied().fold(0.0, f32::max))
}
#[test]
fn the_working_spaces_reproduce_the_measured_patches() {
for c in &measured::CONDITIONS {
let patches = measured::parse(c.data).unwrap();
let start = std::time::Instant::now();
let g = measured::model(c).unwrap();
let took = start.elapsed();
let (mean, max) = accuracy(&g, &patches);
println!("{}: computed in {took:?}, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference);
assert!(mean < 0.1 && max < 0.6, "{}: mean {mean}, max {max}", c.reference);
// The paper is the measured blank patch.
assert!(delta_e2000(g.to_lab_abs([0.0; 4]), patches[0].lab) < 0.05);
}
}
/// A model fitted without every fourth patch (the paper and the solids and overprints stay in)
/// predicts the patches it left out. The data repeats some builds, and every row of a build is
/// on the side of the build's first row, so the fit never sees a left-out build.
#[test]
fn the_fit_predicts_patches_it_left_out() {
for c in &measured::CONDITIONS {
let patches = measured::parse(c.data).unwrap();
let corner = |p: &measured::Patch| p.cmyk.iter().all(|v| *v == 0.0 || *v == 1.0);
let first = |p: &measured::Patch| patches.iter().position(|q| q.cmyk == p.cmyk).unwrap_or(0);
let (kept, left): (Vec<&measured::Patch>, Vec<_>) = patches.iter().partition(|p| first(p) % 4 != 3 || corner(p));
assert!(left.iter().all(|l| kept.iter().all(|k| k.cmyk != l.cmyk)), "{}", c.reference);
let kept: Vec<measured::Patch> = kept.into_iter().copied().collect();
let left: Vec<measured::Patch> = left.into_iter().copied().collect();
let g = measured::fit(c, &kept, measured::SMOOTHING).unwrap();
let (mean, max) = accuracy(&g, &left);
println!("{}: {} patches left out, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference, left.len());
assert!(mean < 0.3 && max < 2.5, "{}: mean {mean}, max {max}", c.reference);
}
}
/// More of any ink makes a build lighter by less than 0.3 L*, also where the data has few patches
/// (black above 60%, and builds over the ink limit).
#[test]
fn more_ink_lightens_a_build_by_less_than_0_3_l() {
let steps: Vec<f32> = (0..=20).map(|i| i as f32 / 20.0).collect();
let coarse = [0.0, 0.25, 0.5, 0.75, 1.0];
for c in &measured::CONDITIONS {
let g = measured::model(c).unwrap();
let mut worst = 0f32;
for ink in 0..4 {
for a in coarse {
for b in coarse {
for d in coarse {
let mut others = [a, b, d].into_iter();
let mut build = [0f32; 4];
for (i, slot) in build.iter_mut().enumerate() {
if i != ink {
*slot = others.next().unwrap();
}
}
let mut last = f32::INFINITY;
for &v in &steps {
build[ink] = v;
let l = g.to_lab_rel(build).l;
worst = worst.max(l - last);
last = l;
}
}
}
}
}
println!("{}: largest L* rise with more ink {worst:.3}", c.reference);
assert!(worst < 0.3, "{}: {worst}", c.reference);
}
}
#[test]
fn the_working_spaces_follow_generic_cmyk_in_the_list() {
let cmyk: Vec<String> = profiles().into_iter().filter(|p| p.kind == ProfileKind::Cmyk && p.builtin).map(|p| p.name).collect();
assert_eq!(cmyk, [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK]);
assert_eq!(ColorSettings::default().cmyk, GENERIC_CMYK);
assert_eq!(characterization(FOGRA51_CMYK), Some(("FOGRA51", "http://www.color.org")));
assert_eq!(characterization(FOGRA52_CMYK), Some(("FOGRA52", "http://www.color.org")));
assert_eq!(characterization(GENERIC_CMYK), None);
assert!(matches!(register_icc(&icc_bytes(FOGRA51_CMYK).unwrap(), None), Err(CmsError::Unsupported(_))));
}
#[test]
fn colors_separate_and_come_back_in_the_measured_spaces() {
for name in [FOGRA51_CMYK, FOGRA52_CMYK] {
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap();
// A 50% gray (L* 53) lies well inside both measured gamuts (the darkest patches measure
// L* 11.43 and 26.36), so it comes back whatever the gamut check says.
let gray = [0.5, 0.5, 0.5];
for srgb in [[0.8, 0.3, 0.2], [0.2, 0.5, 0.7], gray, [0.9, 0.85, 0.6], [0.1, 0.1, 0.1]] {
let inks = cms.srgb_to_cmyk(srgb, Intent::RelativeColorimetric);
assert!(inks.iter().sum::<f32>() <= 3.0 + 1e-3, "{name} {srgb:?}: {inks:?}");
if srgb == gray || cms.gamut_error(&Color::Rgb { r: srgb[0], g: srgb[1], b: srgb[2] }) < GAMUT_THRESHOLD {
let back = cms.cmyk_to_srgb(inks, false);
let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(back));
assert!(de < 1.5, "{name} {srgb:?}: {inks:?} -> {back:?} (ΔE {de})");
}
}
// White is paper with no ink, and black is the darkest build within the ink limit.
assert_eq!(cms.srgb_to_cmyk([1.0; 3], Intent::RelativeColorimetric), [0.0; 4]);
let black = cms.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric);
assert!(black[3] > 0.8 && black.iter().sum::<f32>() <= 3.0 + 1e-3, "{name}: {black:?}");
}
// The coated paper prints a larger gamut than the uncoated one.
let blue = Color::Rgb { r: 0.1, g: 0.2, b: 0.6 };
let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap();
let uncoated = Cms::new(&ColorSettings { cmyk: FOGRA52_CMYK.into(), ..ColorSettings::default() }).unwrap();
assert!(coated.gamut_error(&blue) < uncoated.gamut_error(&blue));
}
/// Absolute Lab of `cmyk` in a context whose CMYK space is one of the Generic-type spaces.
fn absolute_lab(cms: &Cms, cmyk: [f32; 4]) -> Lab {
match &cms.cmyk {
CmykSpace::Generic(g) => g.to_lab_abs(cmyk),
CmykSpace::Device | CmykSpace::Icc(_) => panic!("not a Generic-type CMYK space"),
}
}
#[test]
fn absolute_cmyk_to_rgb_shows_the_paper() {
for name in [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK] {
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap();
let paper = cms.cmyk_to_rgb([0.0; 4], Intent::AbsoluteColorimetric);
assert_eq!(paper, cms.srgb_to_rgb(cms.cmyk_to_srgb([0.0; 4], true)), "{name}");
assert_ne!(paper, cms.cmyk_to_rgb([0.0; 4], Intent::RelativeColorimetric), "{name}");
}
}
#[test]
fn absolute_cmyk_conversion_keeps_the_source_paper() {
// Generic CMYK's paper (L* 93, b* 2.5) is darker and yellower than FOGRA51's (L* 95, b* -6),
// so printing it on FOGRA51 paper takes ink.
let generic = Cms::new(&ColorSettings { cmyk: GENERIC_CMYK.into(), ..ColorSettings::default() }).unwrap();
let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap();
let Color::Cmyk { c, m, y, k } = generic.convert_into(&coated, &Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 0.0 }, Intent::AbsoluteColorimetric)
else {
panic!("a CMYK colour converts to CMYK");
};
let inks = [c, m, y, k];
assert!(inks.iter().sum::<f32>() > 0.01, "{inks:?}");
let de = delta_e2000(absolute_lab(&coated, inks), absolute_lab(&generic, [0.0; 4]));
assert!(de < 2.0, "{inks:?}: ΔE {de}");
}
#[test]
fn the_profiles_carry_the_paper_and_the_data_source() {
for c in &measured::CONDITIONS {
let start = std::time::Instant::now();
let bytes = icc_bytes(c.name).unwrap();
println!("{}: {} bytes in {:?}", c.reference, bytes.len(), start.elapsed());
let p = moxcms::ColorProfile::new_from_slice(&bytes).unwrap();
assert_eq!(
(p.profile_class, p.color_space, p.pcs),
(moxcms::ProfileClass::OutputDevice, moxcms::DataColorSpace::Cmyk, moxcms::DataColorSpace::Lab)
);
assert!(p.lut_a_to_b_perceptual.is_some() && p.lut_b_to_a_perceptual.is_some() && p.lut_a_to_b_colorimetric.is_some());
let paper = lab::lab_to_xyz(measured::parse(c.data).unwrap()[0].lab);
let white = p.media_white_point.unwrap();
for (got, want) in [white.x, white.y, white.z].iter().zip(paper) {
assert!((*got - f64::from(want)).abs() < 2e-3, "{}: {white:?} vs {paper:?}", c.reference);
}
let text = format!("{:?}", p.copyright);
assert!(text.contains(c.reference) && text.contains("Fogra"), "{text}");
}
}
+32 -8
View File
@@ -12,7 +12,7 @@ pub const CHROMA_FULL: f64 = 0.4;
pub const POWERLESS_CHROMA: f64 = 0.000_004;
/// How far outside 0..=1 an sRGB component may be and still count as inside the gamut.
const GAMUT_SLACK: f64 = 1e-4;
const GAMUT_SLACK: f64 = 1e-5;
/// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they
/// are. The hue is in 0..360, and 0 while the chroma is powerless.
@@ -46,7 +46,7 @@ pub fn max_chroma(l: f64, h: f64) -> f64 {
///
/// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of
/// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313,
/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic
/// and the ray can leave and return near black as well. Each linear sRGB channel is a cubic
/// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The
/// search finds each such chroma between the cubic's turning points and takes the largest one that
/// fits.
@@ -69,8 +69,7 @@ fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 {
let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)];
let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)];
let mut ends = vec![0.0];
for ch in 0..3 {
let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]];
for (((y0, y1), y2), y3) in y[0].into_iter().zip(y[1]).zip(y[2]).zip(y[3]) {
let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0);
let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0];
let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0];
@@ -113,11 +112,16 @@ fn turning_points(a: f64, b: f64, c: f64) -> Vec<f64> {
/// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered:
/// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that
/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more.
/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. Lightness 0 gives exactly black and
/// lightness 1 exactly white, as CSS Color 4 specifies, and a positive chroma there counts as
/// lowered.
pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) {
let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) };
let c = if c.is_nan() { 0.0 } else { c.max(0.0) };
let h = if h.is_finite() { h } else { 0.0 };
if l == 0.0 || l == 1.0 {
return ([l as f32; 3], c > 0.0);
}
let exact = oklch_to_srgb(l, c, h);
let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) };
(rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered)
@@ -240,12 +244,10 @@ mod tests {
}
/// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at
/// every hue and at lightnesses near black too, where the ray can come back into sRGB away from
/// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012).
/// every hue and at lightnesses near black too.
#[test]
fn the_largest_chroma_is_never_below_a_scan_of_the_ray() {
let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max);
assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0));
for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] {
for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) {
let max = max_chroma(l, h);
@@ -263,4 +265,26 @@ mod tests {
assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]);
assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]);
}
/// The lightness endpoints give exactly black and white at any chroma and hue, and report a
/// positive chroma as lowered. A rounded 8-bit comparison would hide a small leftover channel.
#[test]
fn the_lightness_endpoints_give_exact_black_and_white() {
assert_eq!(from_oklch(0.0, 0.04, 0.0), ([0.0; 3], true));
assert_eq!(from_oklch(0.0, 0.0, 120.0), ([0.0; 3], false));
assert_eq!(from_oklch(1.0, 0.1, 250.0), ([1.0; 3], true));
assert_eq!(from_oklch(1.0, 0.0, 0.0), ([1.0; 3], false));
}
/// A color whose green is 0.000024 below sRGB is outside it: it is lowered to the chroma that
/// fits, not clipped at its own chroma.
#[test]
fn a_channel_just_below_zero_is_outside_the_gamut() {
assert!(!in_srgb(oklch_to_srgb(0.01, 0.01, 0.0)));
let (rgb, lowered) = from_oklch(0.01, 0.01, 0.0);
assert!(lowered, "{rgb:?}");
let [_, c, _] = to_oklch(rgb);
assert!(c < 0.01, "{c}");
assert!(in_srgb(oklch_to_srgb(0.01, max_chroma(0.01, 0.0), 0.0)));
}
}
+79
View File
@@ -57,6 +57,37 @@ impl Document {
pick(&|r| r.contains(p)).or_else(|| pick(&|r| artboard_holds(r, p)))
}
/// Which artboard in the document owns object bounds `b`: the artboard that holds its center,
/// or the one it has the greatest overlap area with if its center lies outside all artboards.
/// Bounds with no width or no height (a straight horizontal or vertical line) have no area, so
/// for them the overlap is the length of the line on the artboard.
pub fn artboard_for_bounds(&self, b: Rect) -> Option<usize> {
let c = b.center();
if let Some(i) = self.artboard_holding(c, false) {
return Some(i);
}
let (flat_x, flat_y) = (b.x1 - b.x0 <= 1e-9, b.y1 - b.y0 <= 1e-9);
let mut best: Option<(usize, f64)> = None;
for (i, a) in self.artboards.iter().enumerate() {
let r = a.rect;
let w = b.x1.min(r.x1) - b.x0.max(r.x0);
let h = b.y1.min(r.y1) - b.y0.max(r.y0);
if w < 0.0 || h < 0.0 {
continue;
}
let overlap = match (flat_x, flat_y) {
(true, true) => 0.0,
(true, false) => h,
(false, true) => w,
(false, false) => w * h,
};
if overlap > 1e-9 && best.is_none_or(|(_, max)| overlap > max + 1e-9) {
best = Some((i, overlap));
}
}
best.map(|(i, _)| i)
}
/// The art that moves with an artboard at `rect`: top-level objects (children of layers and
/// sublayers) lying entirely inside it, with symbol instances measured by their art. Locked and
/// hidden objects and layers stay put unless `locked_and_hidden` (Selection & Anchor Display ›
@@ -89,6 +120,54 @@ impl Document {
art
}
/// The art that is copied when artboard `index` is duplicated or copied: objects wholly inside
/// the artboard (with rounding tolerance), objects within its bleed rectangle, and artwork
/// placed on/overlapping this artboard that belongs to it by center or primary overlap
/// ([`Document::artboard_for_bounds`]).
pub fn art_for_artboard_copy(&self, index: usize, locked_and_hidden: bool) -> Vec<NodeId> {
let Some(rect) = self.artboards.get(index).map(|a| a.rect) else { return vec![] };
let r = rect.inflate(1e-6, 1e-6);
let on_copy = |b: Rect| -> bool {
// 1. Wholly inside the artboard (edges included, with tolerance).
if b.x0 >= r.x0 && b.y0 >= r.y0 && b.x1 <= r.x1 && b.y1 <= r.y1 {
return true;
}
// 2. Within the artboard's bleed rectangle (if document setup specifies bleed).
if self.setup.has_bleed() {
let br = self.setup.bleed_rect(rect).inflate(1e-6, 1e-6);
if b.x0 >= br.x0 && b.y0 >= br.y0 && b.x1 <= br.x1 && b.y1 <= br.y1 {
return self.artboard_for_bounds(b).is_none_or(|owner| owner == index);
}
}
// 3. Artwork that intersects this artboard and belongs to it (#4479).
let inter_x0 = b.x0.max(r.x0);
let inter_y0 = b.y0.max(r.y0);
let inter_x1 = b.x1.min(r.x1);
let inter_y1 = b.y1.min(r.y1);
if inter_x1 < inter_x0 || inter_y1 < inter_y0 {
return false;
}
self.artboard_for_bounds(b) == Some(index)
};
fn collect(n: &Node, s: &SymbolBoxes, on: &dyn Fn(Rect) -> bool, all: bool, out: &mut Vec<NodeId>) {
for c in n.children().into_iter().flatten().filter(|c| c.rides_with_artboard(all)) {
if c.is_layer() {
collect(c, s, on, all, out);
} else if let Some(b) = c.geometric_bounds_with(s)
&& on(b)
{
out.push(c.id);
}
}
}
let symbols = self.symbol_boxes();
let mut art = vec![];
for l in self.layers.iter().filter(|l| l.rides_with_artboard(locked_and_hidden)) {
collect(l, &symbols, &on_copy, locked_and_hidden, &mut art);
}
art
}
/// Does any artwork lie on `rect` (an artboard)? Artwork is any object under the layers,
/// hidden and locked ones and those on template layers included, whose visual bounds (symbol
/// instances measured by their art) meet `rect`; touching its edge counts. A group (not a clip
+155
View File
@@ -731,6 +731,152 @@ fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: O
tops
}
/// The most hits [`leaves_at`] lists.
pub const MAX_LEAVES_AT: usize = 256;
/// The hits under `p`, topmost first, at most [`MAX_LEAVES_AT`]: one for each object a click with
/// Direct Selection picks there (a path, a compound path or an image, also inside a group), each
/// found by a hit test ([`hit_test`]) that passes over the ones found before it. In isolation mode
/// (`opt.scope`) only what is inside the isolated group or object is hit. Cmd/Ctrl-clicks with the
/// Selection tool step through them (Select Behind).
pub fn leaves_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<Hit> {
let _walk = ArtWalk::open();
// A clipping mask, or a group drawn with its own geometry effects, hits by rules the single
// traversal leaves to the hit test: the repeated hit test finds the rest, after the hits found
// above them, which the art walked for them already counted against.
leaves_at_once(doc, p, opt).unwrap_or_else(|above| leaves_at_repeated_after(doc, p, opt, above))
}
/// [`leaves_at`] by repeated hit tests, each passing over the objects found before it.
#[cfg(test)]
fn leaves_at_repeated(doc: &Document, p: Point, opt: HitOptions) -> Vec<Hit> {
leaves_at_repeated_after(doc, p, opt, vec![])
}
/// [`leaves_at`] by repeated hit tests after `hits`, the topmost hits already found.
fn leaves_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, mut hits: Vec<Hit>) -> Vec<Hit> {
let mut found: HashSet<NodeId> = hits.iter().map(|h| h.leaf).collect();
while hits.len() < MAX_LEAVES_AT
&& let Some(h) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true)
{
if !found.insert(h.leaf) {
break;
}
hits.push(h);
}
hits
}
/// [`leaves_at`] in one traversal of the document, in the order repeated hit tests
/// ([`hit_test_skipping`]) find them. `Err` with the hits found above it when a container under
/// `p` clips or draws its art with its own geometry effects ([`leaves_in`]).
fn leaves_at_once(doc: &Document, p: Point, opt: HitOptions) -> Result<Vec<Hit>, Vec<Hit>> {
let finish = |mut h: Hit| {
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
h
};
let locks = doc.locked_artboards_kept();
let on_locked = |id: NodeId| {
!locks.is_empty() && doc.parent_of(id).and_then(|l| doc.node(l)).is_some_and(Node::is_layer) && doc.node(id).is_some_and(|n| locks.holds(n))
};
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
let mut hits = Vec::new();
if let Some(scope) = opt.scope
&& let Some(isolated) = doc.node(scope)
&& let Some(mut chain) = doc.ancestry(scope)
{
if !doc.is_editable_with(&locks, scope) {
return Ok(hits);
}
let whole = if isolated.is_container() {
leaves_in(isolated, p, opt, &symbols, &on_locked, &mut chain, &mut hits)
} else {
// A single object isolated: only it hits, among its siblings.
chain.pop();
let Some(parent) = chain.last().and_then(|id| doc.node(*id)) else { return Ok(hits) };
leaves_in(parent, p, opt, &symbols, &|id| id != scope || on_locked(id), &mut chain, &mut hits)
};
let hits = hits.into_iter().map(finish).collect();
return if whole { Ok(hits) } else { Err(hits) };
}
let mut chain = Vec::new();
for layer in doc.layers.iter().rev() {
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
continue;
}
chain.push(layer.id);
let opt = if !opt.ignore_layer_preview && previews_off(layer) { HitOptions { outline: true, ..opt } } else { opt };
if !leaves_in(layer, p, opt, &symbols, &on_locked, &mut chain, &mut hits) {
return Err(hits.into_iter().map(finish).collect());
}
chain.pop();
if hits.len() >= MAX_LEAVES_AT {
break;
}
}
Ok(hits.into_iter().map(finish).collect())
}
/// Every editable hit under `p` in `parent`, topmost first, added to `hits` up to
/// [`MAX_LEAVES_AT`]: what [`hit_children`] finds first, then what it finds passing over each hit
/// found before. `false` when `parent` or a container in it under `p` clips or draws its art with
/// its own geometry effects, which [`hit_children`] hits by rules of their own.
fn leaves_in(
parent: &Node,
p: Point,
opt: HitOptions,
symbols: &SymbolBoxes,
skip: &dyn Fn(NodeId) -> bool,
chain: &mut Vec<NodeId>,
hits: &mut Vec<Hit>,
) -> bool {
let Some(children) = parent.children() else { return true };
if parent.clips() || drawn_art(symbols, parent, opt.outline).is_some() {
return false;
}
for i in hit_order(parent, children, p) {
if hits.len() >= MAX_LEAVES_AT {
return true;
}
let Some(c) = children.get(i) else { continue };
if !may_hit(parent, i, c, p, opt, symbols, true) || skip(c.id) {
continue;
}
chain.push(c.id);
let leaf = |hits: &mut Vec<Hit>, chain: &[NodeId]| {
if let Some(kind) = hit_leaf(c, p, opt, symbols) {
hits.push(Hit { leaf: c.id, ancestry: chain.to_vec(), kind, contents_of: None, layers: 1 });
}
};
let whole = match &c.kind {
NodeKind::Layer { preview: false, .. } if !opt.ignore_layer_preview => {
leaves_in(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, hits)
}
NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } | NodeKind::Envelope { editing: true, .. } => {
leaves_in(c, p, opt, symbols, skip, chain, hits)
}
// A blend's key objects first; its steps hit as the blend.
NodeKind::Blend { .. } => {
let whole = leaves_in(c, p, opt, symbols, skip, chain, hits);
if whole && hits.len() < MAX_LEAVES_AT {
leaf(hits, chain);
}
whole
}
_ => {
leaf(hits, chain);
true
}
};
chain.pop();
if !whole {
return false;
}
}
true
}
/// The most objects [`locked_objects_at`] lists.
pub const MAX_LOCKED_AT: usize = 20;
@@ -1417,6 +1563,15 @@ fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64)
let decoration_sq = decoration_reach * decoration_reach;
let mut near_decoration = false;
for sp in &path.subpaths {
// A closed lone anchor has no segment, and a cap can draw a dot on it: the full check
// decides a click near it.
if sp.closed
&& sp.segment_count() == 0
&& let Some(a) = sp.anchors.first()
&& (a.p - p).hypot2() <= radius_sq.max(decoration_sq)
{
near_decoration = true;
}
for i in 0..sp.segment_count() {
let c = sp.segment(i);
if decoration_reach > 0.0 && !near_decoration && ([c.p0, c.p3].iter().any(|q| (*q - p).hypot2() <= decoration_sq)) {
+82
View File
@@ -1992,10 +1992,58 @@ fn objects_at_matches_repeated_hits_on_random_documents() {
let p = Point::new(f64::from(next(120)), f64::from(next(120)));
let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() };
assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None), "round {round}, {p:?}, {opt:?}");
assert_eq!(leaf_chains(leaves_at(&d, p, opt)), leaf_chains(leaves_at_repeated(&d, p, opt)), "leaves: round {round}, {p:?}, {opt:?}");
// Isolated in a group of the document, now and then.
let groups: Vec<NodeId> =
d.layers[0].children().into_iter().flatten().filter(|n| n.is_container() && !n.is_layer()).map(|n| n.id).collect();
if let Some(&g) = groups.first().filter(|_| next(3) == 0) {
let opt = HitOptions { scope: Some(g), ..opt };
assert_eq!(leaf_chains(leaves_at(&d, p, opt)), leaf_chains(leaves_at_repeated(&d, p, opt)), "isolated: round {round}, {p:?}");
}
}
}
}
/// A hit's leaf, ancestry, kind, layer count and edited envelope.
type LeafChain = (NodeId, Vec<NodeId>, HitKind, usize, Option<NodeId>);
/// Each hit's [`LeafChain`], to compare two lists.
fn leaf_chains(hits: Vec<Hit>) -> Vec<LeafChain> {
hits.into_iter().map(|h| (h.leaf, h.ancestry, h.kind, h.layers, h.contents_of)).collect()
}
/// Select Behind steps through the members of groups one by one, front to back, in one traversal
/// for a large stack, as the hit test repeated over what is left finds them.
#[test]
fn leaves_at_lists_group_members_one_by_one() {
let mut d = Document::new(100.0, 100.0);
let layer = d.layers[0].id;
let square = |d: &mut Document| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art());
let below = square(&mut d);
let below_id = below.id;
d.insert(Some(layer), usize::MAX, below).unwrap();
let members: Vec<Node> = (0..300).map(|_| square(&mut d)).collect();
let mut ids: Vec<NodeId> = members.iter().map(|n| n.id).collect();
let g = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap();
ids.reverse();
ids.push(below_id);
let p = Point::new(25.0, 25.0);
let hits = leaves_at(&d, p, HitOptions::default());
assert_eq!(hits.len(), MAX_LEAVES_AT, "the list stops at its limit");
assert_eq!(hits.iter().map(|h| h.leaf).collect::<Vec<_>>(), ids[..MAX_LEAVES_AT], "the group's members, topmost first");
assert!(hits.iter().all(|h| h.ancestry.contains(&g)));
assert_eq!(leaf_chains(hits), leaf_chains(leaves_at_repeated(&d, p, HitOptions::default())));
// Hidden past the limit, the object below the group comes after the members that are left.
for id in &ids[3..300] {
d.node_mut(*id).unwrap().visible = false;
}
let shown: Vec<NodeId> = leaves_at(&d, p, HitOptions::default()).iter().map(|h| h.leaf).collect();
assert_eq!(shown, [ids[0], ids[1], ids[2], below_id]);
let isolated = leaves_at(&d, p, HitOptions { scope: Some(g), ..Default::default() });
assert!(!isolated.iter().any(|h| h.leaf == below_id), "isolated: only the group's members");
}
/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the
/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times.
fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
@@ -2322,6 +2370,40 @@ fn select_behind_keeps_one_art_limit_when_it_falls_back() {
assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked");
}
/// [`leaves_at`] falls back to repeated hit tests at a clip group, after the hits its single
/// traversal found above it: an instance hit by its art, with the limit of symbol art then used
/// up, stays in the list.
#[test]
fn leaves_at_keeps_the_hits_above_a_clip_group_it_falls_back_at() {
let p = Point::new(150.0, 50.0);
let mut d = Document::new(600.0, 400.0);
clipped_symbol(&mut d, false);
// A clip group at the bottom of the layer, its art under (150, 50).
let square = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art()));
let (mask, art) = (d.alloc_id(), d.alloc_id());
let mut clip_group = Node::group(d.alloc_id(), vec![square(mask), square(art)]);
clip_group.set_clips(true);
let l = d.layers[0].id;
d.insert(Some(l), 0, clip_group).unwrap();
let (mut shown_mask, shown_art) = half_clipped(&mut d);
shown_mask.appearance.effects.push(test_move());
let mut shown = Node::group(d.alloc_id(), vec![Arc::new(shown_mask), Arc::new(shown_art)]);
shown.set_clips(true);
group_symbol(&mut d, "Shown", vec![Arc::new(shown)]);
let hit = instance_of(&mut d, "Shown");
let hit_id = hit.id;
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap();
for _ in 0..32 {
let inst = instance_of(&mut d, "Clipped");
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap();
}
let (hits, _, arts) = with_art_limit(100, || leaves_at(&d, p, HitOptions::default()));
let leaves: Vec<NodeId> = hits.iter().map(|h| h.leaf).collect();
assert_eq!(leaves.first(), Some(&hit_id), "hit before the fallback: {leaves:?}");
assert!(leaves.contains(&art), "the clipped art after it: {leaves:?}");
assert!(arts <= 34, "{arts} instances' art walked");
}
#[test]
fn locked_and_hidden_skip() {
let mut d = Document::new(200.0, 200.0);
+1 -1
View File
@@ -116,7 +116,7 @@ pub use metadata::{CopyrightStatus, DocMetadata};
pub use node::Knockout;
pub use node::Scaling;
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS};
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
pub use orient::OrientedBox;
pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType};
pub use perspective::PerspectiveAttachment;
+13 -2
View File
@@ -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();
+26 -14
View File
@@ -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)
}
+32
View File
@@ -278,6 +278,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
if let Some(e) = n.extras_box() {
b += ALLOC + size_of::<NodeExtras>();
b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective);
b += e.attrs.as_deref().map_or(0, attrs_bytes);
b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize);
b += e
.color_mask
@@ -404,6 +405,22 @@ fn swatches_bytes(s: &[Swatch]) -> usize {
ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap_bytes(&w.paint)).sum::<usize>()
}
/// The heap an object's attributes own: their text, data, events, classes, foreign attributes and
/// tags.
fn attrs_bytes(a: &crate::ObjectAttributes) -> usize {
let pairs = |v: &Vec<(String, String)>| vec_bytes(v) + v.iter().map(|(k, v)| k.capacity() + v.capacity()).sum::<usize>();
a.url.capacity()
+ a.note.capacity()
+ pairs(&a.data)
+ pairs(&a.events)
+ vec_bytes(&a.classes)
+ a.classes.iter().map(String::capacity).sum::<usize>()
+ vec_bytes(&a.foreign)
+ a.foreign.iter().map(|f| f.ns.capacity() + f.prefix.capacity() + f.name.capacity() + f.value.capacity()).sum::<usize>()
+ vec_bytes(&a.tags)
+ a.tags.iter().map(|t| t.name.capacity() + t.value.capacity()).sum::<usize>()
}
/// A vector's buffer (not what its elements own).
fn vec_bytes<T>(v: &Vec<T>) -> usize {
if v.capacity() == 0 { 0 } else { ALLOC + v.capacity() * size_of::<T>() }
@@ -490,6 +507,21 @@ mod tests {
assert!((400..1200).contains(&per), "{per} bytes per moved rectangle");
}
/// An object's attributes count with their text: a version of a rectangle with a long tag and
/// a long note keeps both.
#[test]
fn tags_and_notes_count() {
let before = doc_with_rects(1);
let mut after = before.clone();
let id = after.layers[0].children().unwrap()[0].id;
after.node_mut(id).unwrap().edit_attrs(|a| {
a.note = "n".repeat(30_000);
a.tags.push(crate::ObjectTag { id: 1, name: "size".into(), value: "v".repeat(60_000) });
});
let bytes = after.retained_bytes(&before);
assert!(bytes >= 90_000, "{bytes} bytes for a rectangle with 90,000 bytes of attributes");
}
#[test]
fn a_grouped_object_is_found_shared() {
let before = doc_with_rects(100);
+1 -1
View File
@@ -24,7 +24,7 @@ mod opacity;
mod ops;
mod wire;
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS};
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
pub use clip::{ClipPaint, Uniter};
pub use extras::{Extras, ExtrasMut, NodeExtras};
pub use ids::{LAYER_COLORS, LayerColor, NodeId};
+135
View File
@@ -38,6 +38,141 @@ pub struct ObjectAttributes {
/// with it.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub foreign: Vec<ForeignAttribute>,
/// The object's tags, in order: name and value pairs that scripts read and write
/// (`object.tag.add`). Names may be empty or repeated. At most [`MAX_TAGS`], each name and
/// value at most [`MAX_TAG_TEXT`] bytes.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<ObjectTag>,
}
/// The most tags one object has.
pub const MAX_TAGS: usize = 64;
/// The longest name or value a tag has, in bytes.
pub const MAX_TAG_TEXT: usize = 64 * 1024;
/// A tag on an object: a name and a value, with an id that tells it apart from the object's other
/// tags while its name and value change.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ObjectTag {
/// Distinct among the object's tags: a new tag takes an id from
/// [`crate::Document::alloc_tag_id`], and deleting a tag raises the next node id above its id,
/// so a deleted tag's id is not given out again.
#[serde(default, deserialize_with = "lenient_tag_id")]
pub id: u64,
#[serde(default)]
pub name: String,
#[serde(default)]
pub value: String,
}
/// Reading a native file never fails over a tag id that is not a whole number from 0 to
/// `u64::MAX` (a negative one, a fraction, text): it reads as 0, and
/// [`crate::Document::tidy_tags`] gives the tag a new id.
fn lenient_tag_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
Ok(serde_json::Value::deserialize(d)?.as_u64().unwrap_or(0))
}
impl ObjectAttributes {
/// Keeps the tags within the limits: the first [`MAX_TAGS`] whose name and value are at most
/// [`MAX_TAG_TEXT`] bytes. → whether any was dropped.
pub fn tidy_tags(&mut self) -> bool {
let before = self.tags.len();
self.tags.retain(|t| t.name.len() <= MAX_TAG_TEXT && t.value.len() <= MAX_TAG_TEXT);
self.tags.truncate(MAX_TAGS);
self.tags.len() != before
}
}
impl crate::Document {
/// Keeps every object's tags within the limits ([`ObjectAttributes::tidy_tags`]) in the art of
/// the layers, symbols, graph designs and pattern swatches (opacity-mask art included). A tag
/// keeps its id when the id is from 1 to below [`crate::limits::MAX_NEXT_ID`] and no earlier
/// tag of the object has it. Every other tag gets a new id: from the next node id on, above
/// every kept id, when those ids stay below that limit; otherwise the smallest id the object's
/// other tags do not have. The next node id is then raised past every tag id below the limit.
/// It recurses through the art: call it on a document no deeper than
/// [`crate::depth::MAX_DEPTH`].
pub fn tidy_tags(&mut self) {
fn keeps(t: &ObjectTag, earlier: &[ObjectTag]) -> bool {
(1..crate::limits::MAX_NEXT_ID).contains(&t.id) && !earlier.iter().any(|o| o.id == t.id)
}
// The limits, the largest kept id and the number of new ids first, so that a new id never
// meets a kept one.
let mut next = self.peek_next_id();
let mut fresh = 0u64;
self.each_tagged(&mut |a| {
a.tidy_tags();
for (i, t) in a.tags.iter().enumerate() {
if keeps(t, &a.tags[..i]) {
next = next.max(t.id.saturating_add(1));
} else {
fresh = fresh.saturating_add(1);
}
}
});
if fresh == 0 {
self.raise_next_id(next);
return;
}
let in_range = next.saturating_add(fresh) <= crate::limits::MAX_NEXT_ID;
self.each_tagged(&mut |a| {
let kept: Vec<bool> = (0..a.tags.len()).map(|i| keeps(&a.tags[i], &a.tags[..i])).collect();
let mut used: Vec<u64> = a.tags.iter().zip(&kept).filter(|(_, k)| **k).map(|(t, _)| t.id).collect();
for (i, k) in kept.iter().enumerate() {
if *k {
continue;
}
let id = if in_range {
next = next.saturating_add(1);
next - 1
} else {
(1..).find(|c| !used.contains(c)).unwrap_or(1)
};
a.tags[i].id = id;
used.push(id);
}
});
self.raise_next_id(next);
}
/// A new tag id for object `id`, which none of its tags has: the next node id. `None` once the
/// next node id has reached [`crate::limits::MAX_NEXT_ID`] (a file with ids at the top of the
/// range), since an id from there would be outside the range [`Self::tidy_tags`] keeps and an
/// id below it could be a deleted tag's.
pub fn alloc_tag_id(&mut self, id: crate::NodeId) -> Option<u64> {
let used: Vec<u64> =
self.node(id).map(|n| n.extras().attrs.as_deref().map_or(Vec::new(), |a| a.tags.iter().map(|t| t.id).collect())).unwrap_or_default();
for _ in 0..=used.len() {
if self.peek_next_id() >= crate::limits::MAX_NEXT_ID {
return None;
}
let tag = self.alloc_id().0;
if !used.contains(&tag) {
return Some(tag);
}
}
None
}
/// Calls `f` with the attributes of every object with tags in the art [`Self::tidy_tags`] reads.
fn each_tagged(&mut self, f: &mut impl FnMut(&mut ObjectAttributes)) {
let mut fix = |n: &mut Node| {
if n.extras().attrs.as_deref().is_some_and(|a| !a.tags.is_empty()) {
n.edit_attrs(&mut *f);
}
};
let roots = self
.layers
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
for root in roots {
crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix);
}
}
}
/// An attribute in another application's XML namespace: `plotter:pen="2"` with `xmlns:plotter=
+41 -6
View File
@@ -131,6 +131,13 @@ impl Node {
matches!(self.kind, NodeKind::Layer { template: true, .. })
}
/// Whether a view that hides template layers (`templates`) or guides (`guides`) leaves this
/// object out: a template layer while templates are hidden, or a path made into a guide while
/// guides are hidden. The canvas draws ruler guides apart from the art.
pub fn hidden_by_view(&self, templates: bool, guides: bool) -> bool {
(templates && self.is_template()) || (guides && matches!(self.kind, NodeKind::Path { guide: true, .. }))
}
/// The art objects of this container: its children, looking through sublayers, which are not
/// objects (bottom first). With `editable`, only the visible, unlocked objects in visible,
/// unlocked, non-template sublayers.
@@ -360,17 +367,32 @@ impl Node {
self.geometric(Some(symbols))
}
/// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a
/// hidden bitmap for re-tracing/release; only source-image views measure that bitmap.
/// Children that contribute to a container's editing bounds. A live trace retains a hidden bitmap for
/// re-tracing/release; only source-image views measure that bitmap. Selection highlights outline
/// [`Node::drawn_children`].
pub fn editing_children(&self) -> &[Arc<Node>] {
let children = self.children().map(Vec::as_slice).unwrap_or_default();
let trace_source = self.extras().trace.is_some()
&& !self.trace_view().shows_source()
&& children.first().is_some_and(|n| !n.visible && matches!(n.kind, NodeKind::Image(_)));
let trace_source = !self.trace_view().shows_source() && self.trace_source().is_some_and(|n| !n.visible);
let skip = usize::from(self.extras().shaper.is_some() || trace_source);
children.get(skip..).unwrap_or_default()
}
/// The children a selection highlight outlines: [`Node::editing_children`] without the hidden
/// members, which the canvas does not draw. An Image Trace object's hidden source image stays
/// when the object's view shows it, and every path of a compound path stays, since the compound
/// path draws all of them.
pub fn drawn_children(&self) -> impl Iterator<Item = &Arc<Node>> {
let members = !matches!(self.kind, NodeKind::Compound { .. });
let source = self.trace_source().filter(|_| self.trace_view().shows_source());
self.editing_children().iter().filter(move |c| !members || c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c)))
}
/// The first child of an Image Trace object when it is an image: the bitmap the trace keeps.
fn trace_source(&self) -> Option<&Arc<Node>> {
self.extras().trace.as_ref()?;
self.children()?.first().filter(|n| matches!(n.kind, NodeKind::Image(_)))
}
/// The box of [`Node::geometric_bounds`], or of [`Node::geometric_bounds_with`] when `symbols`
/// is given.
pub(crate) fn geometric(&self, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
@@ -409,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`],
@@ -463,7 +496,9 @@ impl Node {
self.geometric(symbols).map(|b| b.inflate(o, o))
}
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
let b = self.geometric(symbols)?;
// A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath.
let dots = self.appearance.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square));
let b = self.drawn(symbols, dots).or_else(|| self.geometric(symbols))?;
Some(self.appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default()))
}
NodeKind::SymbolInstance { symbol, xf } => {
+54
View File
@@ -469,6 +469,60 @@ fn visual_bounds_include_stroke() {
assert_eq!(p.visual_bounds(), Some(Rect::new(-0.5, -0.5, 10.5, 10.5)));
}
/// A lone anchor 20 points right of a stroked square widens the path's geometric box, and its
/// visual box only where the stroke draws it: as the dot of a round or projecting cap on a closed
/// subpath. An open lone anchor, or a closed one under a butt cap, draws nothing.
#[test]
fn a_lone_anchor_widens_the_visual_box_only_where_its_cap_draws_a_dot() {
use crate::appearance::LineCap;
use vectorcraft_geom::{Point, SubPath};
let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
let node = |closed: bool, cap: LineCap| {
let mut subpaths = square.subpaths.clone();
subpaths.push(SubPath::polyline(&[Point::new(30.0, 5.0)], closed));
let mut p = Node::path(NodeId(2), PathData::new(subpaths), Appearance::default_art());
let s = p.appearance.stroke_mut().unwrap();
(s.cap, s.join) = (cap, crate::appearance::LineJoin::Round);
p
};
for closed in [false, true] {
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
let p = node(closed, cap);
let geometric = p.geometric_bounds().unwrap();
let visual = p.visual_bounds().unwrap();
assert!(geometric.x1 >= 30.0, "{closed} {cap:?}: the geometric box {geometric:?} leaves out the lone anchor");
let dot = closed && cap != LineCap::Butt;
assert_eq!(visual.x1 > 30.0, dot, "{closed} {cap:?}: the visual box {visual:?}");
assert!(dot || visual.x1 < 11.0, "{closed} {cap:?}: the visual box {visual:?} reaches toward the lone anchor");
}
}
}
/// The dot a round or projecting cap draws for a closed lone anchor reaches half the stroke's
/// width round the anchor under every join, miter and bevel joins included, which measure the
/// stroke along its segments.
#[test]
fn a_lone_anchors_dot_reaches_half_the_stroke_width_under_every_join() {
use crate::appearance::{LineCap, LineJoin};
use vectorcraft_geom::{Point, SubPath};
let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
for join in [LineJoin::Miter, LineJoin::Bevel, LineJoin::Round] {
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
let mut subpaths = square.subpaths.clone();
subpaths.push(SubPath::polyline(&[Point::new(30.0, 5.0)], true));
let mut p = Node::path(NodeId(2), PathData::new(subpaths), Appearance::default_art());
let s = p.appearance.stroke_mut().unwrap();
(s.cap, s.join, s.width) = (cap, join, 4.0);
let visual = p.visual_bounds().unwrap();
if cap == LineCap::Butt {
assert!(visual.x1 < 13.0, "{join:?} {cap:?}: the visual box {visual:?} reaches toward a lone anchor that draws nothing");
} else {
assert!(visual.x1 >= 32.0 - 1e-9 && visual.y1 >= 10.0, "{join:?} {cap:?}: the visual box {visual:?} leaves out the dot's reach");
}
}
}
}
/// A group's box from its members' boxes grows by the group's own strokes, leaves out members
/// without a box, and is `None` when none has one.
#[test]
+50 -4
View File
@@ -17,15 +17,16 @@
//! other stop there, showing their previews).
use std::borrow::Cow;
use std::cell::Cell;
use std::collections::BTreeSet;
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
use serde::{Deserialize, Serialize};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_geom::{Affine, PathData, Rect, SubPath};
use vectorcraft_color::Paint;
use vectorcraft_color::{Color, Paint};
use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol};
use crate::{Appearance, AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol};
/// A placed document: an artboard of another VectorCraft file, a page of a PDF or `.ai` file, or
/// an EPS file's art, shown as one locked object.
@@ -123,12 +124,27 @@ impl PlacedDocument {
}
/// The art the object shows, as plain objects with `n`'s id: one group, its resources named
/// as [`Document::with_placed_art`] adds them (nothing until that has read it).
/// as [`Document::with_placed_art`] adds them (nothing until that has read it). While
/// [`Crossed`] is on for this thread, its box crossed from corner to corner instead
/// ([`Self::crossed_art`]).
pub fn art(&self, n: &Node) -> Vec<Node> {
if crossed() {
return vec![self.crossed_art(n)];
}
let prefix = prefix(&self.key);
read_cached(self).and_then(|e| self.art_node(n, &e, &prefix)).into_iter().collect()
}
/// The object's box crossed from corner to corner, as one group with `n`'s id: a path of the
/// box's outline and its two diagonals with a black 1 pt stroke. Outline mode without Document
/// Setup → Show Images in Outline Mode shows the object so, and its effects reshape this art.
pub fn crossed_art(&self, n: &Node) -> Node {
let q = self.corners();
let path = PathData::new(vec![SubPath::polyline(&q, true), SubPath::polyline(&[q[0], q[2]], false), SubPath::polyline(&[q[1], q[3]], false)]);
let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
Node::group(n.id, vec![Arc::new(Node::path(art_id(), path, stroke))])
}
/// Read `e`'s art placed as this object `n` shows it (`n`'s id), its resources renamed with
/// `prefix`.
fn art_node(&self, n: &Node, e: &ReadDocument, prefix: &str) -> Option<Node> {
@@ -470,6 +486,36 @@ fn read_preview(p: &PlacedDocument, bytes: &Arc<Vec<u8>>) -> Option<Arc<ReadDocu
Some(e)
}
thread_local! {
/// Whether [`PlacedDocument::art`] gives the crossed box on this thread ([`Crossed`]).
static CROSSED: Cell<bool> = const { Cell::new(false) };
}
/// While alive, [`PlacedDocument::art`] on this thread gives each placed document's box crossed
/// from corner to corner ([`PlacedDocument::crossed_art`]) when it was made with `true`, and the
/// file's art when made with `false`; once dropped, the setting before it applies again. A
/// renderer holds one while it draws or measures Outline mode without Document Setup → Show Images
/// in Outline Mode, so that effects and live objects make their art from the crossed box.
#[must_use]
pub struct Crossed(bool);
impl Crossed {
pub fn set(on: bool) -> Self {
Self(CROSSED.with(|c| c.replace(on)))
}
}
impl Drop for Crossed {
fn drop(&mut self) {
CROSSED.with(|c| c.set(self.0));
}
}
/// Whether [`PlacedDocument::art`] gives the crossed box on this thread ([`Crossed`]).
pub fn crossed() -> bool {
CROSSED.with(Cell::get)
}
/// `p`'s file as read already (else its preview's), without reading it.
pub fn read_cached(p: &PlacedDocument) -> Option<Arc<ReadDocument>> {
let mut c = cache();
+81 -5
View File
@@ -291,9 +291,12 @@ impl StrokeLayer {
// past them are measured.
match self.body_along(&segs, side, out) {
Some(body) => out = out.union(body),
// A subpath with no length paints at most its caps' dot.
// A subpath with no length paints at most its caps' dot. A closed subpath with
// no segment, a lone anchor, has its dot at that anchor under a round or
// projecting cap.
None if !butt => {
let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b));
let lone = (self.cap != LineCap::Butt).then(|| els[r.start].end_point()).flatten().map(|p| Rect::from_points(p, p));
let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)).or(lone);
out = dot.map_or(out, |d| out.union(d.inflate(side, side)));
}
None => {}
@@ -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]);
}
}
+136
View File
@@ -435,6 +435,142 @@ fn art_on_artboard_tolerates_roundoff_at_each_edge() {
}
}
#[test]
fn art_for_artboard_copy_takes_artwork_larger_than_artboard_or_with_bleed() {
let mut d = Document::new(200.0, 200.0);
d.setup.bleed = [9.0; 4];
let layer = d.layers[0].id;
// An oversized background (250x250 centered on the 200x200 artboard, #4479).
let bg = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::path(bg, shapes::rectangle(Rect::new(-25.0, -25.0, 225.0, 225.0)), Appearance::default_art())).unwrap();
// A shape with 5pt bleed over the top-right corner.
let bleed = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::path(bleed, shapes::rectangle(Rect::new(150.0, -5.0, 205.0, 50.0)), Appearance::default_art())).unwrap();
// A shape lying entirely in the bleed margin without touching the artboard itself (-8..-2 vs 0..200).
let bleed_margin_only = d.alloc_id();
d.insert(
Some(layer),
usize::MAX,
Node::path(bleed_margin_only, shapes::rectangle(Rect::new(-8.0, 50.0, -2.0, 100.0)), Appearance::default_art()),
)
.unwrap();
// A small shape hanging 20pt over the left edge (center outside, more than bleed).
let hanging = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::path(hanging, shapes::rectangle(Rect::new(-20.0, 90.0, 10.0, 120.0)), Appearance::default_art()))
.unwrap();
// A straight line hanging 60pt over the left edge (center outside, no area): it lies on the
// artboard for 40pt, so it is copied as a thin rectangle there would be.
let line = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::path(line, shapes::line(Point::new(-60.0, 150.0), Point::new(40.0, 150.0)), Appearance::default_art()))
.unwrap();
// A shape completely outside the artboard.
let outside = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::path(outside, shapes::rectangle(Rect::new(300.0, 300.0, 400.0, 400.0)), Appearance::default_art()))
.unwrap();
// Standard art_on_artboard keeps strict containment: none of the overhanging shapes are on it.
let strict_art = d.art_on_artboard(Rect::new(0.0, 0.0, 200.0, 200.0), false);
assert!(!strict_art.contains(&bg), "strict art_on_artboard excludes oversized background");
assert!(!strict_art.contains(&bleed), "strict art_on_artboard excludes bleed shape");
assert!(!strict_art.contains(&bleed_margin_only), "strict art_on_artboard excludes bleed-margin-only shape");
assert!(!strict_art.contains(&hanging), "strict art_on_artboard excludes hanging shape");
assert!(!strict_art.contains(&outside), "strict art_on_artboard excludes outside shape");
// Copying the artboard takes the artwork touching this artboard that belongs to it, or within bleed.
let copy_art = d.art_for_artboard_copy(0, false);
assert!(copy_art.contains(&bg), "oversized background is copied with artboard: {copy_art:?}");
assert!(copy_art.contains(&bleed), "bleed shape is copied with artboard: {copy_art:?}");
assert!(copy_art.contains(&bleed_margin_only), "bleed-margin-only shape is copied with artboard: {copy_art:?}");
assert!(copy_art.contains(&hanging), "touching shape owned by artboard 0 is copied: {copy_art:?}");
assert!(copy_art.contains(&line), "a line hanging over the edge is copied: {copy_art:?}");
assert!(!copy_art.contains(&outside), "outside shape is not copied: {copy_art:?}");
// If Artboard 1 is added next to Artboard 0, art primarily on Artboard 1 is not copied with Artboard 0:
d.artboards.push(Artboard {
id: 2,
name: "Artboard 2".into(),
rect: Rect::new(200.0, 0.0, 400.0, 200.0),
locked: false,
show_center_mark: false,
show_cross_hairs: false,
show_video_safe_areas: false,
video_ruler_pixel_aspect_ratio: 1.0,
color: None,
guide_label: None,
});
// Shape spanning (190..300) x (50..150): 10pt on Artboard 0, 100pt on Artboard 1.
let neighbor_art = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::path(neighbor_art, shapes::rectangle(Rect::new(190.0, 50.0, 300.0, 150.0)), Appearance::default_art()))
.unwrap();
let copy_art0 = d.art_for_artboard_copy(0, false);
assert!(!copy_art0.contains(&neighbor_art), "art owned by neighboring Artboard 1 is not copied with Artboard 0");
let copy_art1 = d.art_for_artboard_copy(1, false);
assert!(copy_art1.contains(&neighbor_art), "art owned by Artboard 1 is copied with Artboard 1");
}
#[test]
fn artboard_for_bounds_edge_cases_and_tie_breaks() {
let mut d = Document::new(100.0, 100.0);
// Artboard 0: (0, 0, 100, 100)
// Artboard 1: (200, 0, 300, 100)
d.artboards.push(Artboard {
id: 2,
name: "Artboard 2".into(),
rect: Rect::new(200.0, 0.0, 300.0, 100.0),
locked: false,
show_center_mark: false,
show_cross_hairs: false,
show_video_safe_areas: false,
video_ruler_pixel_aspect_ratio: 1.0,
color: None,
guide_label: None,
});
// 1. Artwork whose center is outside all boards, but overlaps Artboard 0 most:
// Bounds: (50, -100, 150, 50) -> Center: (100, -25) which is outside all artboards.
// Overlap with Board 0: 50x50 = 2500; Board 1: 0.
let b_center_outside = Rect::new(50.0, -100.0, 150.0, 50.0);
assert_eq!(d.artboard_for_bounds(b_center_outside), Some(0));
// 2. Equal overlap on two boards (defined tie-break: the lower index, board 0):
// Bounds: (50, -50, 250, 50) -> Center: (150, 0) outside all boards.
// Overlap with Board 0: (50..100) x (0..50) = 2500; Board 1: (200..250) x (0..50) = 2500.
let b_equal_overlap = Rect::new(50.0, -50.0, 250.0, 50.0);
assert_eq!(d.artboard_for_bounds(b_equal_overlap), Some(0), "equal overlap picks lower index");
// 3. No overlap at all: returns None.
let b_no_overlap = Rect::new(500.0, 500.0, 600.0, 600.0);
assert_eq!(d.artboard_for_bounds(b_no_overlap), None);
// 4. Rotated object bounds (bounds, not the inner geometry):
// A 40x40 square rotated 45 deg centered at (50, 50) has bounding box ~56.57x56.57.
let b_rotated_bounds = Rect::new(50.0 - 28.28, 50.0 - 28.28, 50.0 + 28.28, 50.0 + 28.28);
assert_eq!(d.artboard_for_bounds(b_rotated_bounds), Some(0));
// 5. Zero-size bounds (a point):
// On board 0:
let b_zero_on_board = Rect::new(50.0, 50.0, 50.0, 50.0);
assert_eq!(d.artboard_for_bounds(b_zero_on_board), Some(0));
// Outside all boards:
let b_zero_outside = Rect::new(150.0, 50.0, 150.0, 50.0);
assert_eq!(d.artboard_for_bounds(b_zero_outside), None);
// 6. Straight lines whose center is outside every board: owned by the board they lie on most,
// as a rectangle of any thickness would be (they have no area to compare).
// Horizontal, from x = -100 to 50 on board 0: center (-25, 50).
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.0)), Some(0));
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.1)), Some(0), "the same as a thin rectangle");
// Vertical, from y = -100 to 50 on board 1: center (250, -25).
assert_eq!(d.artboard_for_bounds(Rect::new(250.0, -100.0, 250.0, 50.0)), Some(1));
// Below both boards.
assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 120.0, 260.0, 120.0)), None);
// Across the gap between the boards, 20 pt on board 0 and 60 on board 1.
assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 50.0, 260.0, 50.0)), Some(1), "center (170, 50) in the gap: board 1 holds more of it");
// Only touching a board's corner from outside: no overlap.
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 0.0, 0.0, 0.0)), None);
}
/// The art on a locked artboard (each object of a layer whose bounds overlap it, a group as one
/// object) can't be edited, and Select All, a click and a marquee pass over it; art flush with
/// the artboard from outside isn't on it, a layer is on no artboard, and new art isn't on one.
+12
View File
@@ -291,3 +291,15 @@ fn q_and_ha_suffixes_do_not_take_other_units_suffixes() {
// A suffix after math covers the whole expression, as for the other units.
assert!((Unit::Points.parse("26/2 q").unwrap() - Unit::Q.to_pt(13.0)).abs() < 1e-9);
}
#[test]
fn format_area_formats_and_trims_cleanly() {
assert_eq!(Unit::Points.format_area(100.0), "100 pt²");
assert_eq!(Unit::Inches.format_area(4.5 * 72.0 * 72.0), "4.5 in²");
let mm_side = Unit::Millimeters.to_pt(1.0);
assert_eq!(Unit::Millimeters.format_area(12.5 * mm_side * mm_side), "12.5 mm²");
assert_eq!(Unit::Points.format_area(0.0), "0 pt²");
assert_eq!(Unit::Points.format_area(-10.0), "0 pt²");
assert_eq!(Unit::Points.format_area(f64::NAN), "0 pt²");
assert_eq!(Unit::Points.format_area(f64::INFINITY), "0 pt²");
}
+35
View File
@@ -166,6 +166,19 @@ impl Unit {
pub fn format(self, pt: f64) -> String {
format!("{} {}", self.number(pt), self.suffix())
}
/// Format an area in square points into this unit (e.g. `12.5 mm²`, `4.5 in²`, `100 pt²`).
pub fn format_area(self, pt2: f64) -> String {
if !pt2.is_finite() || pt2 <= 0.0 {
return format!("0 {}²", self.suffix());
}
let side = self.from_pt(1.0);
let val = pt2 * side * side;
let decimals = if matches!(self, Unit::Points | Unit::Pixels | Unit::Picas | Unit::Q | Unit::Ha) { 3 } else { 4 };
let s = format!("{:.*}", decimals, val);
let s = s.trim_end_matches('0').trim_end_matches('.');
let s = if s == "-0" || s.is_empty() { "0" } else { s };
format!("{s} {}²", self.suffix())
}
/// [`Unit::format`] without the suffix (`12.5`), for narrow fields.
pub fn number(self, pt: f64) -> String {
// Three decimals for the small units (`595.276 pt`), four for the large ones (`8.2677 in`,
@@ -196,6 +209,15 @@ impl Unit {
}
parse_measure(&times_as_asterisks(s), self).filter(|v| v.is_finite())
}
/// Parse a measurement with decimal points or commas and no input locale. Refuse a
/// number that looks like a grouped integer, even when it is part of an expression.
pub fn parse_with_decimal_comma(self, text: &str) -> Option<f64> {
if text.contains(',') && times_as_asterisks(text).split(['+', '-', '*', '/']).any(thousands_operand) {
return None;
}
self.parse(&decimal_point(text))
}
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
/// `feetInches`).
pub const fn key(self) -> &'static str {
@@ -397,6 +419,19 @@ pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> {
if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() }
}
/// Does the operand contain a thousands comma? Check both parts of a compact pica value and
/// read a percentage's number without its percent sign.
fn thousands_operand(operand: &str) -> bool {
let operand = operand.trim();
if let Some((picas, points)) = operand.split_once('p')
&& !points.trim().is_empty()
&& points.trim().bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b','))
{
return thousands(picas) || thousands(points);
}
thousands(operand.strip_suffix('%').unwrap_or(operand))
}
/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or
/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at
/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it
+7 -2
View File
@@ -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;
+69 -6
View File
@@ -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…",
@@ -326,21 +383,21 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"stylize.dropShadow",
"Drop Shadow…",
STYLIZE,
"{mode: blend mode (\"multiply\"), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)",
"{mode: blend mode (\"multiply\"; normal, darken, multiply, colorBurn, lighten, screen, colorDodge, overlay, softLight, hardLight, difference, exclusion, hue, saturation, color or luminosity, in any letter case), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)",
json!({"mode": "multiply", "opacity": 75.0, "x": 7.0, "y": 7.0, "blur": 5.0, "shade": "color", "color": "#000000", "darkness": 100.0}),
),
r(
"stylize.innerGlow",
"Inner Glow…",
STYLIZE,
"{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}",
"{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}",
json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffffff", "source": "edge"}),
),
r(
"stylize.outerGlow",
"Outer Glow…",
STYLIZE,
"{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}",
"{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}",
json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}),
),
r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})),
@@ -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}),
),
]);
@@ -875,6 +932,12 @@ pub(crate) fn catalog_index() -> &'static std::collections::HashMap<&'static str
INDEX.get_or_init(|| effect_catalog().into_iter().map(|e| (e.id, e)).collect())
}
/// The id and menu label of built-in effect `id`, as the catalog holds them (no plug-in
/// effects).
pub fn built_in_effect(id: &str) -> Option<(&'static str, &'static str)> {
catalog_index().get(id).map(|e| (e.id, e.label))
}
/// Catalogue entry for `id` (built-in, or an installed plug-in effect).
pub fn effect_info(id: &str) -> Option<EffectInfo> {
catalog_index().get(id).cloned().or_else(|| plugin_info(id))
+9
View File
@@ -447,6 +447,12 @@ pub(crate) fn apply_one(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &Geo
budget.fits(Budget::of(&out)).then_some(out)
}
#[cfg(test)]
thread_local! {
/// The subpaths the Offset Path effect has offset on this thread.
pub(crate) static OFFSET_SUBPATHS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Does geometry effect `id` build within the anchors it is given?
fn builds_within(id: &str) -> bool {
matches!(id, "distort.freeDistort" | "distort.roughen" | "distort.transform" | "distort.twist" | "distort.zigZag") || id.starts_with("warp.")
@@ -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
+1 -1
View File
@@ -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 };
+8 -5
View File
@@ -82,11 +82,12 @@ pub use group::{
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
pub use params::{blend_mode_id, parse_blend_mode, takes_blend_mode};
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use placement::pinned_gradient_item;
pub use raster::{
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects,
without_geometry,
RASTERIZE, RasterFx, Rasterize, blend_mode, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps,
staged_effects, without_geometry,
};
pub use reshape::{
SYMBOL_ART_MAX_NODES, add_instance_row_effects_to_parts, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster,
@@ -124,7 +125,9 @@ mod catalog;
mod geometry;
mod params;
pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range};
pub use catalog::{
EffectInfo, Lengths, WARP_STYLES, built_in_effect, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range,
};
pub(crate) use geometry::{Budget, apply_one};
pub use geometry::{
Carry, GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_bez_carrying, apply_geometry_carrying, apply_geometry_with,
@@ -132,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,
};
+217
View File
@@ -1,6 +1,28 @@
use vectorcraft_doc::color::BlendMode;
use super::catalog::{catalog_index, plugin_info};
use super::{CROP_MARKS, Effect, Map, Node, PIXEL_EFFECTS, RASTERIZE, Value, is_adjustment, is_pathfinder, is_three_d, json, util};
/// Whether parameter `key` of effect `effect` is the blend mode the effect draws in.
pub fn takes_blend_mode(effect: &str, key: &str) -> bool {
key == "mode" && matches!(effect, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow")
}
/// Read a blend mode name as the effect renderer does. Case and punctuation do not change the mode.
pub fn parse_blend_mode(s: &str) -> Option<BlendMode> {
let name: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
BlendMode::parse(&name)
}
/// The name an effect stores for blend mode `mode`, such as `normal`, `multiply`, or `colorBurn`.
pub fn blend_mode_id(mode: BlendMode) -> String {
let mut name = format!("{mode:?}");
if let Some(first) = name.get_mut(..1) {
first.make_ascii_lowercase();
}
name
}
/// Dialog defaults for `id` (`None` for unknown effects).
pub fn default_params(id: &str) -> Option<Value> {
match catalog_index().get(id) {
@@ -117,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
+2 -2
View File
@@ -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()]));
+6 -1
View File
@@ -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
View File
@@ -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: &params, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held };
let strict = complete.is_some();
let step = Step { e, params: &params, 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, &params, &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));
+59 -1
View File
@@ -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, &region, 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(&region, 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(&region, 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, &region, &what);
}
}
}
}
}
assert_eq!(painted, 22, "dots drawn");
}
#[test]
fn bounds_and_clicks_cover_every_arrowhead() {
let bp = &paths()[0];
+7 -6
View File
@@ -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);
+118
View File
@@ -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:?}");
}
+447 -1
View File
@@ -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);
}
+3 -1
View File
@@ -120,8 +120,10 @@ vectorcraft-testkit = { workspace = true }
proptest = { workspace = true }
# A variable font built in code (no font file is committed).
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
# How many times an open reads a PDF.
# How many times an open reads a PDF, and the work its import takes.
vectorcraft-pdf = { workspace = true, features = ["read-count"] }
# The work `.ai` blends take to be checked and made live.
vectorcraft-eps = { workspace = true, features = ["work-count"] }
# How many times the symbol list is read to find symbols by name, and how many objects are
# measured against locked artboards.
vectorcraft-doc = { workspace = true, features = ["symbol-read-count", "locked-artboard-count"] }
+9 -1
View File
@@ -97,11 +97,13 @@ mod style;
pub use style::styled_node;
pub mod stylelib;
mod svgfilter;
pub use svgfilter::MAX_IMPORT_BYTES as MAX_SVG_FILTER_IMPORT_BYTES;
mod swatch;
pub mod swatchlib;
pub(crate) mod symboledit;
pub mod symbollib;
pub(crate) mod tabs;
pub(crate) mod tags;
mod textedit;
pub use textedit::effective_kerning;
@@ -376,6 +378,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(library::specs());
v.extend(expand::specs());
v.extend(attributes::specs());
v.extend(tags::specs());
v.extend(interactivity::specs());
v.extend(spelling::specs());
v.extend(svgfilter::specs());
@@ -845,7 +848,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
pub use addons::{fold_source, print_hidden};
pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
/// Document Info's category titles, the Objects category's count labels, and how its image rows
/// write a resolution and a number of bytes.
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
@@ -924,6 +927,9 @@ pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYT
/// An Image Trace made off the UI thread, and what it traced (#3098).
pub use buildcmds::{TraceRun, Traced, image_trace_target};
/// Retype's search of the installed fonts, made off the UI thread.
pub use retype::{RetypeFound, RetypeRun, RetypeSearch};
/// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them).
pub(crate) use buildcmds::TracePresetChanges;
@@ -958,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};
+1 -1
View File
@@ -17,7 +17,7 @@ mod typetools;
mod units;
pub(crate) use image::{DecodedImages, refresh_color_masks};
pub use packaging::{fold_source, print_hidden};
pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
use super::CommandSpec;
+1 -1
View File
@@ -173,7 +173,7 @@ fn filter(s: &mut Session, p: &Value) -> Result<Value> {
let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…'));
let kinds = effects::addons::duotone::swatch_kinds(&s.doc()?.doc);
let swatches = |name: &str| kinds.get(name).copied();
recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))
s.edit_effect(id, |s| recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches)))
}
/// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own
+6 -2
View File
@@ -2,13 +2,16 @@
//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line
//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold
//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Set
//! Fold Angle ([`angle`]) gives a fold line its own angle. Its submenu (Object › Plug-ins ›
//! Packaging Tools) and its Fold Lines panel are the UI's.
mod angle;
mod check;
mod fold;
mod roles;
pub use angle::{FoldAngles, selection_fold_angles, selection_fold_lines};
pub use fold::{fold_source, print_hidden};
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
@@ -17,6 +20,7 @@ use super::super::CommandSpec;
pub fn specs() -> Vec<CommandSpec> {
let mut v = roles::specs();
v.extend(check::specs());
v.extend(angle::specs());
v.extend(fold::specs());
v
}
@@ -0,0 +1,266 @@
//! Set Fold Angle (`addon.packaging.setFoldAngle`): the angle each fold line folds at. A Crease,
//! Partial Cut or Perforation line keeps its own angle in its data under [`KEY`], as a number of
//! degrees from -180 to 180; without one it folds at its role's angle (90° for a Crease or a
//! Perforation, -90° for a Partial Cut). A positive angle folds away from the printed side.
use std::collections::HashSet;
use std::sync::{Arc, Weak};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_three_d::fold::kept_angle;
use super::super::super::edit::refuse_symbol_part;
use super::super::super::overprint::edit_counted;
use super::super::super::pathops::number_given;
use super::super::super::{CommandSpec, bad, cmd, switch_or};
use super::check::kind;
use super::roles::{Role, RoleTable, editable_members, role_targets, taken_roots};
use crate::{Result, Session};
/// Object data key: a fold line's own fold angle, in degrees. Native save keeps it; SVG export
/// leaves `vc-` keys out.
pub(crate) const KEY: &str = "vc-fold-angle";
const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle";
/// The range a fold angle may take, in degrees.
const RANGE: std::ops::RangeInclusive<f64> = -180.0..=180.0;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.packaging.setFoldAngle",
"Set Fold Angle…",
["Object", "Plug-ins", "Packaging Tools"],
None,
"{angle?: degrees -180..180, reset?: bool (false), ids?: [id…] (default: the selection)} give each Crease, Partial Cut and Perforation line among the objects (addon.packaging.roles; through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) its own fold angle, rounded to the millionth of a degree, or with reset: true take it away, so the line folds at its role's angle again: 90° for a Crease or a Perforation, -90° for a Partial Cut. A positive angle folds the panel away from the printed side, a negative one toward it; addon.packaging.fold and the Fold Preview window fold each hinge at the angle of the line with the most length in it. Cut lines and objects without a role are skipped and counted. Give exactly one of angle and reset: true. One undo step, none when nothing changes → {ids (the fold lines changed or kept), changed, skipped}",
has_fold_line,
set_fold_angle
)]
}
/// Why Set Fold Angle has nothing to change.
const NO_FOLD_LINE: &str = "select a crease, partial cut or perforation line that is neither locked nor hidden";
/// The last answer of [`has_fold_line`], with what it was for.
struct Answer {
/// The document (a weak reference keeps another document from taking the same address).
doc: Weak<Document>,
revision: u64,
/// The objects looked at: the selection, or the `ids` a command was given in its place.
objects: Vec<NodeId>,
found: bool,
}
thread_local! {
/// Menus ask [`has_fold_line`] on every refresh, and its answer changes only with the
/// document, its revision and the objects looked at.
static LAST_ANSWER: std::cell::RefCell<Option<Answer>> = const { std::cell::RefCell::new(None) };
}
/// The selection holds a line that folds and that Set Fold Angle can change, or an id of no object.
fn has_fold_line(s: &Session) -> std::result::Result<(), String> {
refuse_symbol_part(s).map_err(|e| e.to_string())?;
let st = s.doc().map_err(|e| e.to_string())?;
let objects = &st.selection.objects;
let kept = LAST_ANSWER.with_borrow(|last| match last {
Some(a) if a.revision == st.revision && a.objects == *objects && Weak::ptr_eq(&a.doc, &Arc::downgrade(&st.doc)) => Some(a.found),
_ => None,
});
let found = kept.unwrap_or_else(|| {
// An id of no object (given as `ids`) is left to the command, which names it.
let found = objects.iter().any(|id| st.doc.node(*id).is_none()) || any_fold_line(&st.doc, objects);
LAST_ANSWER.set(Some(Answer { doc: Arc::downgrade(&st.doc), revision: st.revision, objects: objects.clone(), found }));
found
});
if found { Ok(()) } else { Err(NO_FOLD_LINE.into()) }
}
/// Whether the objects `roots` of `d` hold a line that folds and can be changed, looking through
/// groups and clip groups as [`role_targets`] does and stopping at the first. As [`taken_roots`]
/// takes them, an object inside another one given is left out (a crease in a selected layer counts
/// no more than the layer does), a layer is left out, and a path of a compound path stands for the
/// compound path, which holds its role, unless it is locked or hidden.
fn any_fold_line(d: &Document, roots: &[NodeId]) -> bool {
fn find(n: &Node, hit: &dyn Fn(&Node) -> bool) -> bool {
match &n.kind {
// A group's clipping path draws no stroke.
NodeKind::Group { children, .. } => children.iter().any(|c| !matches!(c.kind, NodeKind::Path { clipping: true, .. }) && find(c, hit)),
_ => hit(n),
}
}
let table = RoleTable::of(d);
let editable = d.editable();
let hit = |n: &Node| table.role_of(n).is_some_and(folds) && editable(n.id);
let given: HashSet<NodeId> = roots.iter().copied().collect();
// Each object's place, from the document's lookup of ids.
let outer = |id: NodeId| -> Option<NodeId> {
let a = d.ancestry(id)?;
let (_, up) = a.split_last()?;
if up.iter().any(|p| given.contains(p)) {
return None;
}
match up.last().copied().filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))) {
// A locked or hidden path of a compound path is left out, as `editable_members` leaves it.
Some(_) if !editable(id) => None,
Some(compound) => Some(compound),
None => Some(id),
}
};
// An object given twice is looked through once.
let mut seen = HashSet::new();
roots
.iter()
.filter_map(|id| outer(*id))
.filter(|id| seen.insert(*id))
.filter_map(|id| d.node(id))
.filter(|n| !n.is_layer())
.any(|n| find(n, &hit))
}
/// The text `n`'s data holds under [`KEY`], if any.
fn stored(n: &Node) -> Option<&str> {
n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str())
}
/// `n`'s own fold angle: the number its data holds under [`KEY`], when it is a finite number from
/// -180 to 180, to the millionth of a degree it folds at ([`kept_angle`]). Anything else reads as
/// no angle of its own.
pub(super) fn own_angle(n: &Node) -> Option<f64> {
stored(n)?.trim().parse::<f64>().ok().filter(|a| a.is_finite() && RANGE.contains(a)).map(kept_angle)
}
/// Whether a line with `role` folds: every role but Cut.
pub(super) fn folds(role: Role) -> bool {
kind(role).fold_angle().is_some()
}
/// Writes `angle` (`None`: takes it away) into object `id`'s data → whether its data changed.
fn store(d: &mut Document, id: NodeId, angle: Option<f64>) -> bool {
// `+ 0.0` turns -0 into 0, so a line set to 0° reads "0".
let text = angle.map(|a| format!("{}", a + 0.0));
// Read first: taking the node to change it copies it, its geometry included. An angle stored
// as other text for the same number ("45.0") is kept; a reset removes any stored text.
let same = |n: &Node| match angle {
Some(a) => own_angle(n) == Some(a),
None => stored(n).is_none(),
};
if d.node(id).is_none_or(same) {
return false;
}
let Some(n) = d.node_mut(id) else { return false };
n.edit_attrs(|a| match text {
Some(text) => match a.data.iter_mut().find(|(k, _)| k == KEY) {
Some(e) => e.1 = text,
None => a.data.push((KEY.into(), text)),
},
None => a.data.retain(|(k, _)| k != KEY),
});
true
}
fn set_fold_angle(s: &mut Session, p: &Value) -> Result<Value> {
let angle = number_given(p, "angle", SET_FOLD_ANGLE)?;
let reset = switch_or(p, "reset", false, SET_FOLD_ANGLE)?;
let angle = match (angle, reset) {
(Some(_), true) => return Err(bad(SET_FOLD_ANGLE, "give `angle` or `reset: true`, not both")),
(None, false) => return Err(bad(SET_FOLD_ANGLE, "missing `angle`")),
(Some(a), false) if !RANGE.contains(&a) => return Err(bad(SET_FOLD_ANGLE, "`angle` must be from -180 to 180 degrees")),
// Kept to the millionth of a degree, the angle the line folds at.
(a, _) => a.map(kept_angle),
};
let (roots, named) = taken_roots(s, p, SET_FOLD_ANGLE)?;
let d = &s.doc()?.doc;
let (targets, skipped) = role_targets(d, &roots, false);
let mut skipped = skipped + named;
let mut ids = folding(d, &RoleTable::of(d), &targets);
{
let editable = d.editable();
ids.retain(|id| editable(*id));
}
skipped += targets.len() - ids.len();
if ids.is_empty() {
return Err(bad(SET_FOLD_ANGLE, NO_FOLD_LINE));
}
let label = if angle.is_some() { "Set Fold Angle" } else { "Reset Fold Angle" };
let changed = edit_counted(s, label, |d| Ok(ids.iter().filter(|id| store(d, **id, angle)).count()))?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "changed": changed, "skipped": skipped }))
}
/// The lines among `ids` of `d` that fold (Crease, Partial Cut, Perforation), in order.
fn folding(d: &Document, table: &RoleTable, ids: &[NodeId]) -> Vec<NodeId> {
ids.iter().copied().filter(|id| d.node(*id).and_then(|n| table.role_of(n)).is_some_and(folds)).collect()
}
/// What Set Fold Angle can change among the objects `roots` of `d` (through groups and clip
/// groups, leaving out what is locked or hidden, as `addon.packaging.setFoldAngle` does).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FoldAngles {
/// How many lines that fold it can change.
pub lines: usize,
/// The angle they all fold at (their own or their role's); `None` when they differ or there
/// are none.
pub angle: Option<f64>,
/// How many of them have an angle of their own.
pub own: usize,
/// How many of them hold text under [`KEY`], an angle or not: what `reset: true` takes away.
pub stored: usize,
}
/// The [`FoldAngles`] of the selected objects of the active document, as Set Fold Angle reads them
/// with no `ids` (nothing, while it would refuse the selection).
pub fn selection_fold_angles(s: &Session) -> FoldAngles {
match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) {
(Ok((roots, _)), Ok(st)) => fold_angles(&st.doc, &roots),
_ => FoldAngles::default(),
}
}
/// The lines Set Fold Angle changes among the selected objects of the active document, as it takes
/// them with no `ids` (none, while it would refuse the selection). Given back as `ids`, they are the
/// lines it changes.
pub fn selection_fold_lines(s: &Session) -> Vec<NodeId> {
match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) {
(Ok((roots, _)), Ok(st)) => changeable(&st.doc, &roots).into_iter().map(|(n, _)| n.id).collect(),
_ => Vec::new(),
}
}
/// The [`FoldAngles`] of the outermost objects `roots` of `d`.
pub(super) fn fold_angles(d: &Document, roots: &[NodeId]) -> FoldAngles {
let mut f = FoldAngles::default();
for (n, role) in changeable(d, roots) {
f.add(n, role);
}
f
}
/// The lines that fold among the outermost objects `roots` of `d` that Set Fold Angle can change,
/// with their roles, in order.
fn changeable<'a>(d: &'a Document, roots: &[NodeId]) -> Vec<(&'a Node, Role)> {
let table = RoleTable::of(d);
let editable = d.editable();
let targets = role_targets(d, &editable_members(d, roots.to_vec()).0, false).0;
// The role first: whether an object can be edited can take its bounds to find out.
targets
.iter()
.filter_map(|id| d.node(*id))
.filter_map(|n| table.role_of(n).filter(|r| folds(*r)).filter(|_| editable(n.id)).map(|r| (n, r)))
.collect()
}
impl FoldAngles {
/// Counts line `n`, which has `role` and can be changed; a line that does not fold is left out.
pub(super) fn add(&mut self, n: &Node, role: Role) {
let Some(default) = kind(role).fold_angle() else { return };
let own = own_angle(n);
let a = own.unwrap_or(default);
self.angle = if self.lines == 0 { Some(a) } else { self.angle.filter(|b| *b == a) };
self.lines += 1;
self.own += usize::from(own.is_some());
self.stored += usize::from(stored(n).is_some());
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,409 @@
//! Tests for Set Fold Angle: a fold line's own angle, where it is kept, and how the fold uses it.
use serde_json::{Value, json};
use super::{KEY, fold_angles, own_angle};
use crate::*;
const SET: &str = "addon.packaging.setFoldAngle";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
s
}
fn path(s: &mut Session, d: &str) -> u64 {
s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()
}
fn role(s: &mut Session, role: &str, ids: &[u64]) {
s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap();
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn err(s: &mut Session, p: Value) -> String {
s.execute(SET, &p).unwrap_err().to_string()
}
/// The text object `id`'s data holds under the fold angle key.
fn stored(s: &Session, id: u64) -> Option<String> {
let d = &s.doc().unwrap().doc;
let n = d.node(NodeId(id)).unwrap();
n.extras().attrs.as_deref().and_then(|a| a.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.clone()))
}
/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side →
/// (outline, creases: top, right, bottom, left).
fn tray(s: &mut Session) -> (u64, Vec<u64>) {
let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")];
role(s, "cut", &[outline]);
role(s, "crease", &creases);
s.execute("select.none", &json!({})).unwrap();
(outline, creases)
}
/// Whether panel `p` of a fold is the tray's top wall (y 100 to 140): the middle of the bounds of
/// its outline's points (absolute moves and lines only) is above the base.
fn top_wall(p: &Value) -> bool {
let d = p["outline"].as_str().unwrap();
let n: Vec<f64> = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect();
let ys = n.iter().skip(1).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t)));
(ys.0 + ys.1) / 2.0 < 140.0
}
fn vector(v: &Value) -> [f64; 3] {
let a = v.as_array().unwrap();
[a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()]
}
#[test]
fn set_fold_angle_keeps_the_angle_on_the_line_and_reset_takes_it_away() {
let mut s = session();
let (_, creases) = tray(&mut s);
let before = steps(&s);
let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(0), &json!([creases[0]])), "{r}");
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
assert_eq!(steps(&s), before + 1, "one undo step");
// The same angle again changes nothing and records no undo step.
let r = s.execute(SET, &json!({"angle": 45.0, "ids": [creases[0]]})).unwrap();
assert_eq!(r["changed"].as_u64(), Some(0));
assert_eq!(steps(&s), before + 1);
// An angle is kept to the millionth of a degree, so one closer to 45 than that is 45.
let r = s.execute(SET, &json!({"angle": 45.00000001, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before + 1), "{r}");
s.execute(SET, &json!({"angle": 179.99999998, "ids": [creases[3]]})).unwrap();
assert_eq!(stored(&s, creases[3]).as_deref(), Some("180"));
s.execute("edit.undo", &json!({})).unwrap();
// A number as text, and the selection when ids is left out; -0 is kept as 0.
s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap();
let r = s.execute(SET, &json!({"angle": "-0"})).unwrap();
assert_eq!(r["changed"].as_u64(), Some(2), "{r}");
assert_eq!(stored(&s, creases[1]).as_deref(), Some("0"));
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0], creases[1], creases[3]]})).unwrap();
assert_eq!(r["changed"].as_u64(), Some(2), "the line without an angle of its own is unchanged: {r}");
assert_eq!((stored(&s, creases[0]), stored(&s, creases[1])), (None, None));
// Nothing left to reset: no undo step.
let at = steps(&s);
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), at));
// Undo brings the angle back.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
}
#[test]
fn bad_angles_and_targets_are_refused() {
let mut s = session();
let (outline, creases) = tray(&mut s);
let plain = path(&mut s, "M10 10 L50 50");
let before = steps(&s);
let ids = json!([creases[0]]);
assert!(err(&mut s, json!({"ids": ids})).contains("missing `angle`"));
assert!(err(&mut s, json!({"angle": 30, "reset": true, "ids": ids})).contains("not both"));
assert!(err(&mut s, json!({"angle": 180.5, "ids": ids})).contains("from -180 to 180"));
assert!(err(&mut s, json!({"angle": -181, "ids": ids})).contains("from -180 to 180"));
assert!(err(&mut s, json!({"angle": "wide", "ids": ids})).contains("must be a number"));
assert!(err(&mut s, json!({"angle": true, "ids": ids})).contains("must be a number"));
assert!(err(&mut s, json!({"reset": "yes", "ids": ids})).contains("true or false"));
// A cut line and a path without a role do not fold.
assert!(err(&mut s, json!({"angle": 30, "ids": [outline, plain]})).contains("crease, partial cut or perforation"));
// An id of no object is named as such, alone or beside a crease.
assert!(err(&mut s, json!({"angle": 30, "ids": [999_999]})).contains("no such object id 999999"));
assert!(err(&mut s, json!({"angle": 30, "ids": [creases[0], 999_999]})).contains("no such object id 999999"));
assert_eq!(steps(&s), before, "no refusal records an undo step");
// The ends of the range are allowed; cut lines and plain paths among fold lines are skipped.
let r = s.execute(SET, &json!({"angle": -180, "ids": [creases[0], outline, plain]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(2), &json!([creases[0]])), "{r}");
s.execute(SET, &json!({"angle": 180, "ids": [creases[0]]})).unwrap();
assert_eq!(stored(&s, creases[0]).as_deref(), Some("180"));
assert_eq!(stored(&s, outline), None);
}
#[test]
fn set_fold_angle_is_dimmed_without_a_line_it_can_change() {
let mut s = session();
let (outline, creases) = tray(&mut s);
let enabled = |s: &Session| (find_command(SET).unwrap().enabled)(s).is_ok();
assert!(!enabled(&s), "nothing selected");
s.execute("select.set", &json!({"ids": [outline]})).unwrap();
assert!(!enabled(&s), "a cut line does not fold");
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
s.execute("select.set", &json!({"ids": [creases[0]]})).unwrap();
assert!(enabled(&s));
s.execute("object.lock", &json!({})).unwrap();
assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(creases[0])]).lines, 0, "a locked crease can't be changed");
// A group holding a crease is enough.
s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
assert!(enabled(&s));
// A layer selected with a crease in it: the crease is inside the layer, which is left out, as
// Set Fold Angle itself leaves them out.
let layer = s.doc().unwrap().doc.layer_of(NodeId(creases[3])).unwrap();
s.execute("select.set", &json!({"ids": [layer.0, creases[3]]})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "both are selected");
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
assert!(!enabled(&s), "dimmed as the command refuses it");
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}");
// With nothing selected the counts are the document's, but Set Fold Angle takes no line.
s.execute("select.set", &json!({"ids": []})).unwrap();
assert!(s.execute(SET, &json!({"angle": 30})).is_err());
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
assert_eq!(r["scope"].as_str(), Some("document"), "{r}");
assert_eq!(r["roles"][1]["count"].as_u64(), Some(4), "{r}");
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}");
}
#[test]
fn a_crease_named_in_ids_is_set_after_the_menu_found_none_in_the_selection() {
let mut s = session();
let (outline, creases) = tray(&mut s);
s.execute("select.set", &json!({"ids": [outline]})).unwrap();
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "a cut line does not fold");
let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap();
assert_eq!(r["changed"].as_u64(), Some(1), "{r}");
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "the selection is still the cut line");
}
#[test]
fn the_selection_s_fold_angles_count_a_crease_and_its_selected_group_once() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let group = s.doc().unwrap().selection.objects[0].0;
s.execute("select.set", &json!({"ids": [group, creases[0]]})).unwrap();
let f = crate::cmd::selection_fold_angles(&s);
assert_eq!((f.lines, f.angle, f.own), (2, None, 1), "{f:?}");
}
#[test]
fn a_locked_crease_is_skipped() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0], creases[1]]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)), "{r}");
assert_eq!(stored(&s, creases[1]), None);
}
#[test]
fn a_locked_path_of_a_compound_crease_named_by_id_is_skipped() {
let mut s = session();
let (_, creases) = tray(&mut s);
let (a, b) = (path(&mut s, "M300 300 L400 300"), path(&mut s, "M300 320 L400 320"));
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
role(&mut s, "crease", &[compound]);
s.edit("Test", |d, _| {
if let Some(n) = d.node_mut(NodeId(a)) {
n.locked = true;
}
Ok(())
})
.unwrap();
assert!(err(&mut s, json!({"angle": 30, "ids": [a]})).contains("crease, partial cut or perforation"));
// Named twice, it is skipped once.
let r = s.execute(SET, &json!({"angle": 30, "ids": [a, a, creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(1), &json!([creases[0]])), "{r}");
assert_eq!(stored(&s, compound), None);
assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(a)]).lines, 0);
let r = s.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap();
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}");
// The same with the locked path selected.
s.execute("select.set", &json!({"ids": [a]})).unwrap();
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "dimmed");
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
assert_eq!(crate::cmd::selection_fold_angles(&s).lines, 0);
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}");
assert_eq!(stored(&s, compound), None);
// With its compound, given or selected, the locked path is part of the compound, not skipped.
let r = s.execute(SET, &json!({"angle": 20, "ids": [compound, a]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}");
s.execute("select.set", &json!({"ids": [compound, a]})).unwrap();
let r = s.execute(SET, &json!({"angle": 25})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}");
s.execute(SET, &json!({"reset": true, "ids": [compound]})).unwrap();
// The compound named by id takes the angle; its other path, not locked, names it too.
let r = s.execute(SET, &json!({"angle": 30, "ids": [b]})).unwrap();
assert_eq!((r["changed"].as_u64(), &r["ids"]), (Some(1), &json!([compound])), "{r}");
assert_eq!(stored(&s, compound).as_deref(), Some("30"));
}
#[test]
fn a_damaged_angle_reads_as_none_of_its_own() {
let mut s = session();
let (_, creases) = tray(&mut s);
let mut n = s.doc().unwrap().doc.node(NodeId(creases[0])).cloned().unwrap();
for (text, want) in [("45", Some(45.0)), (" -30.5 ", Some(-30.5)), ("wide", None), ("NaN", None), ("inf", None), ("181", None), ("", None)] {
n.edit_attrs(|a| {
a.data.retain(|(k, _)| k != KEY);
a.data.push((KEY.into(), text.into()));
});
assert_eq!(own_angle(&n), want, "{text:?}");
}
}
#[test]
fn an_angle_stored_as_other_text_for_the_same_number_is_unchanged() {
let mut s = session();
let (_, creases) = tray(&mut s);
let id = NodeId(creases[0]);
s.edit("Test", |d, _| {
if let Some(n) = d.node_mut(id) {
n.edit_attrs(|a| a.data.push((KEY.into(), "45.0".into())));
}
Ok(())
})
.unwrap();
let before = steps(&s);
let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before), "{r}");
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45.0"));
s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
assert_eq!(stored(&s, creases[0]), None);
// A reset also removes text that is not an angle.
s.edit("Test", |d, _| {
if let Some(n) = d.node_mut(id) {
n.edit_attrs(|a| a.data.push((KEY.into(), "wide".into())));
}
Ok(())
})
.unwrap();
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), stored(&s, creases[0])), (Some(1), None), "{r}");
}
#[test]
fn a_line_keeps_its_own_angle_through_a_role_change() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
role(&mut s, "partialCut", &[creases[0]]);
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}");
role(&mut s, "none", &[creases[0]]);
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
role(&mut s, "crease", &[creases[0]]);
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}");
}
#[test]
fn native_save_and_preserve_editing_keep_the_angle_and_svg_leaves_it_out() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": 120, "ids": [creases[0]]})).unwrap();
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
let svg = svg["text"]
.as_str()
.map(str::to_string)
.unwrap_or_else(|| String::from_utf8_lossy(&vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).into_owned());
assert!(svg.contains("<svg"), "{svg}");
assert!(!svg.contains("fold-angle"), "{svg}");
// An SVG with Preserve Editing reopens as the document it carries, the angle with it.
let editing = s.execute("document.serialize", &json!({"format": "svg", "preserveEditing": true})).unwrap();
let editing = editing["text"].as_str().unwrap().to_string();
let mut t = Session::new();
t.execute("document.open", &json!({"name": "box.svg", "dataBase64": vectorcraft_format::base64_encode(editing.as_bytes())})).unwrap();
assert_eq!(stored(&t, creases[0]).as_deref(), Some("120"));
let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap();
s.execute("document.open", &json!({"name": "box.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert_eq!(stored(&s, creases[0]).as_deref(), Some("120"));
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
let angles: Vec<f64> = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect();
assert!(angles.contains(&120.0), "{r}");
}
#[test]
fn a_tray_wall_with_its_own_angle_stands_at_that_angle() {
let mut s = session();
let (_, creases) = tray(&mut s);
// The top wall (y 100 to 140) folds at 45°.
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
let base = r["base"].as_u64().unwrap() as usize;
let mut angles: Vec<f64> = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect();
angles.sort_by(f64::total_cmp);
assert_eq!(angles, [45.0, 90.0, 90.0, 90.0]);
for (i, p) in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base) {
let z = vector(&p["frame"]["z"]);
let top = top_wall(p);
let tilt = if top { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 };
assert!((z[2] - tilt).abs() < 1e-9, "panel {i}: {p}");
}
}
#[test]
fn a_negative_angle_folds_a_crease_toward_the_print() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": -90, "ids": [creases[0]]})).unwrap();
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
let base = r["base"].as_u64().unwrap() as usize;
let mut up = 0;
for p in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base).map(|(_, p)| p) {
// The top wall folds toward the print, so its printed side faces back over the base
// (toward -y in the y-up frame); the other walls stand square to the base as before.
let top = top_wall(p);
let z = vector(&p["frame"]["z"]);
if top {
assert!((z[1] + 1.0).abs() < 1e-9, "the top wall's print faces the base: {p}");
up += 1;
} else {
assert!(z[2].abs() < 1e-9, "{p}");
}
}
assert_eq!(up, 1);
}
#[test]
fn roles_reports_the_angle_the_selected_fold_lines_share() {
let mut s = session();
let (outline, creases) = tray(&mut s);
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(90.0), Some(0)), "the role's angle: {r}");
s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap();
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap();
assert_eq!((r["foldAngle"].clone(), r["ownAngles"].as_u64()), (Value::Null, Some(1)), "they differ: {r}");
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], outline]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(30.0), Some(1)), "a cut line has no angle: {r}");
let r = s.execute("addon.packaging.roles", &json!({"ids": [outline]})).unwrap();
assert!(r["foldAngle"].is_null(), "{r}");
// A partial cut folds at -90° unless it has an angle of its own.
role(&mut s, "partialCut", &[creases[2]]);
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[2]]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["foldLines"].as_u64()), (Some(-90.0), Some(1)), "{r}");
}
#[test]
fn roles_leaves_locked_fold_lines_out_of_the_angle_as_set_fold_angle_does() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": 45, "ids": [creases[1]]})).unwrap();
s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let group = s.doc().unwrap().selection.objects[0].0;
s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let r = s.execute("addon.packaging.roles", &json!({"ids": [group]})).unwrap();
assert_eq!(r["roles"][1]["count"].as_u64(), Some(2), "both are counted: {r}");
assert_eq!((r["foldLines"].as_u64(), r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(1), Some(90.0), Some(0)), "{r}");
// So Reset has nothing to change, as the panel shows it.
let r = s.execute(SET, &json!({"reset": true, "ids": [group]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}");
let (lines, angle, own) = {
let f = fold_angles(&s.doc().unwrap().doc, &[NodeId(group)]);
(f.lines, f.angle, f.own)
};
assert_eq!((lines, angle, own), (1, Some(90.0), 0));
}
@@ -8,6 +8,7 @@ use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX
use super::super::super::pathops::length_given;
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
use super::angle::own_angle;
use super::roles::{Role, RoleTable, can_carry, role_targets};
use crate::{Result, Session};
@@ -92,7 +93,8 @@ fn on_non_printing_layer(d: &Document, id: NodeId) -> bool {
d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. }))
}
fn kind(role: Role) -> LineKind {
/// The kind of fold line a line with `role` is.
pub(super) fn kind(role: Role) -> LineKind {
match role {
Role::Cut => LineKind::Cut,
Role::Crease => LineKind::Crease,
@@ -155,7 +157,7 @@ fn lines_of(d: &Document, scope: &'static str, targets: Vec<NodeId>) -> Lines {
non_printing.push(id.0);
}
segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum());
lines.push(FoldLine { path, kind: kind(role), key: id.0 });
lines.push(FoldLine { path, kind: kind(role), key: id.0, angle: own_angle(n) });
}
Lines { scope, lines, non_printing }
}
@@ -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: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 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 within tolerance or 0.5% of the hinge's length. 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. 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
)]
@@ -10,6 +10,7 @@ use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use super::super::super::edit::{outermost, refuse_symbol_part, roots_of};
use super::super::super::overprint::edit_counted;
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
use crate::{Result, Session};
@@ -194,6 +195,41 @@ pub(super) fn can_carry(n: &Node) -> bool {
}
}
/// The objects a command that changes roles or angles takes for params `p`: `ids` (the outermost of
/// them), or else the selection (as `selected_roots` takes it), with a path of a compound path that
/// is locked or hidden, or in a locked or hidden group or layer, or on a locked artboard, left out
/// before it stands for its compound, and how many such paths were left out, each once.
pub(super) fn taken_roots(s: &Session, p: &Value, command: &str) -> Result<(Vec<NodeId>, usize)> {
if p.get("ids").is_some_and(|v| !v.is_null()) {
let roots = checked_ids_or_selection(s, p, command)?;
return Ok(editable_members(&s.doc()?.doc, roots));
}
refuse_symbol_part(s)?;
let st = s.doc()?;
// An object inside another selected one is left out first, as it is from `ids`.
let (kept, left) = editable_members(&st.doc, outermost(&st.doc, st.selection.in_paint_order(&st.doc)));
Ok((roots_of(&st.doc, kept), left))
}
/// `ids` less the paths of compound paths among them that are locked or hidden (or in a locked or
/// hidden group or layer, or on a locked artboard), and how many different ones were left out.
pub(super) fn editable_members(d: &Document, ids: Vec<NodeId>) -> (Vec<NodeId>, usize) {
let ok = d.editable();
let member = |id: NodeId| d.parent_of(id).is_some_and(|p| matches!(d.node(p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
let mut left = std::collections::HashSet::new();
let kept = ids
.into_iter()
.filter(|id| {
let out = member(*id) && !ok(*id);
if out {
left.insert(*id);
}
!out
})
.collect();
(kept, left.len())
}
/// The objects under the outermost objects `roots` that can carry a role, through groups and clip
/// groups, each once, and
/// how many of `roots` and their members can't (text, images, symbol instances and other objects).
@@ -257,7 +293,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make Fold Line",
["Object", "Plug-ins", "Packaging Tools"],
None,
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. A line keeps its own fold angle (addon.packaging.setFoldAngle) through a role change and through none. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
has_selection,
set_role
),
@@ -266,7 +302,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fold Lines",
[],
None,
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out",
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected), foldLines, foldAngle, ownAngles, storedAngles}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out. foldLines is how many of the Crease, Partial Cut and Perforation lines among them addon.packaging.setFoldAngle can change (those not locked or hidden; none while nothing is selected and ids is left out, or while the selection holds only a layer and objects in it), foldAngle the angle in degrees they all fold at (their own or their role's), null when they fold at different angles or there are none, ownAngles how many of them have an angle of their own, and storedAngles how many hold stored angle text, an angle or not, which setFoldAngle's reset: true removes",
has_doc,
roles
),
@@ -382,8 +418,9 @@ fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Pai
fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
let role = role_param(p, SET_ROLE, true)?;
let overprint = switch_or(p, "overprint", true, SET_ROLE)?;
let roots = checked_ids_or_selection(s, p, SET_ROLE)?;
let (roots, left) = taken_roots(s, p, SET_ROLE)?;
let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true);
let skipped = skipped + left;
if ids.is_empty() {
return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role"));
}
@@ -403,19 +440,38 @@ fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
fn roles(s: &mut Session, p: &Value) -> Result<Value> {
let given = p.get("ids").is_some_and(|v| !v.is_null());
let roots = checked_ids_or_selection(s, p, ROLES)?;
let d = &s.doc()?.doc;
// The objects Set Fold Angle takes: a locked or hidden path of a compound path does not stand
// for its compound there. They are the objects the counts are of unless such a path was left
// out, and only then are those found apart.
let (taken, left) = taken_roots(s, p, ROLES)?;
let (roots, angle_roots) = if left == 0 { (taken, vec![]) } else { (checked_ids_or_selection(s, p, ROLES)?, taken) };
let st = s.doc()?;
let d = &st.doc;
let (scope, ids) = match (given, roots.is_empty()) {
(true, _) => ("ids", role_targets(d, &roots, false).0),
(false, false) => ("selection", role_targets(d, &roots, false).0),
(false, true) => ("document", document_targets(d)),
};
let whole = scope == "document";
// The lines Set Fold Angle can change are those of the objects it takes: with nothing selected,
// or a selection that holds no such object (only a layer and what is in it), it takes none,
// though the counts are the document's.
let angles_of_all = given || !roots.is_empty();
let table = RoleTable::of(d);
let mut counts = [0usize; 4];
for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) {
let editable = d.editable();
let mut angles = super::angle::FoldAngles::default();
for n in ids.iter().filter_map(|id| d.node(*id)) {
let Some(r) = table.role_of(n) else { continue };
if let Some(c) = counts.get_mut(r.index()) {
*c += 1;
}
if left == 0 && angles_of_all && super::angle::folds(r) && editable(n.id) {
angles.add(n, r);
}
}
if !whole && left > 0 {
angles = super::angle::fold_angles(d, &angle_roots);
}
let rows: Vec<Value> = Role::ALL
.into_iter()
@@ -425,7 +481,10 @@ fn roles(s: &mut Session, p: &Value) -> Result<Value> {
json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count })
})
.collect();
Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() }))
Ok(json!({
"roles": rows, "scope": scope, "selected": roots.len(),
"foldLines": angles.lines, "foldAngle": angles.angle, "ownAngles": angles.own, "storedAngles": angles.stored,
}))
}
fn set_role_swatch(s: &mut Session, p: &Value) -> Result<Value> {
@@ -537,4 +537,20 @@ fn compound_paths_carry_a_role() {
let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]}));
assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1)));
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
// A locked member named by id is skipped, and its compound keeps its role.
s.edit("Test", |d, _| {
if let Some(n) = d.node_mut(a) {
n.locked = true;
}
Ok(())
})
.unwrap();
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0]})).contains("neither locked nor hidden"));
// The same with the locked path selected.
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut"})).contains("neither locked nor hidden"));
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
// Named twice, it is skipped once.
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, a.0, b.0]}));
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([c.0]), Some(1)), "{r}");
}
@@ -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();
@@ -1172,6 +1216,64 @@ fn the_tangent_circle_tool_keeps_its_first_segment_when_drawing_fails() {
assert!(!shown(&mut s), "the first segment is forgotten once the circle is drawn");
}
/// With Add Points to Existing Paths on, the Tangent Circle tool's circle and an anchor point where
/// it touches each line are one undo step; the lines keep their shape, and one Undo takes all of it
/// back.
#[test]
fn the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step() {
let mut s = session();
let a = line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false);
let b = line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false);
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
s.select_tool("tangentCircle", view).unwrap();
s.set_tool_option("addPoints", &json!(true));
let n = steps(&s);
for (kind, x, y) in
[(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)]
{
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
}
assert_eq!(steps(&s), n + 1, "one undo step");
let points = |s: &Session, id| path(s, id).subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::<Vec<_>>();
let near = |got: Vec<(f64, f64)>, want: &[(f64, f64)]| {
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6)
};
assert!(near(points(&s, a), &[(100.0, 100.0), (150.0, 100.0), (300.0, 100.0)]), "{:?}", points(&s, a));
assert!(near(points(&s, b), &[(100.0, 140.0), (150.0, 140.0), (300.0, 140.0)]), "{:?}", points(&s, b));
let st = s.doc().unwrap();
let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) };
let r = st.doc.node(circle).and_then(|c| c.path_data()).and_then(|pd| pd.bounds()).unwrap();
assert!((r.x0 - 130.0).abs() < 1e-6 && (r.y0 - 100.0).abs() < 1e-6 && (r.width() - 40.0).abs() < 1e-6, "{r:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((steps(&s), points(&s, a).len(), points(&s, b).len()), (n, 2, 2));
assert!(s.doc().unwrap().doc.node(circle).is_none(), "the circle is gone too");
}
/// In Draw Behind, the Tangent Circle tool's circle goes behind the object selected before the
/// clicks, also when Add Points to Existing Paths adds anchors to lines that were not selected.
#[test]
fn the_tangent_circle_tool_adding_points_draws_behind_the_selection() {
let mut s = session();
line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false);
line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false);
let other = line(&mut s, &[(100.0, 400.0), (300.0, 400.0)], false);
select(&mut s, &[other]);
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
s.select_tool("tangentCircle", view).unwrap();
s.set_tool_option("addPoints", &json!(true));
for (kind, x, y) in
[(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)]
{
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
}
let st = s.doc().unwrap();
let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) };
let at = |id| st.doc.position(id).map(|(parent, index, _)| (parent, index));
let (Some((p, c)), Some((q, o))) = (at(circle), at(other)) else { panic!("not placed") };
assert!(p == q && c + 1 == o, "the circle is right behind the selected line: {c} and {o}");
}
fn ids(v: &Value) -> Vec<NodeId> {
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
}
+6 -2
View File
@@ -20,7 +20,7 @@ use vectorcraft_text::edit;
use super::super::menucmds::whole_or;
use super::super::object::choice;
use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges};
use super::super::typecmd::refresh_bounds;
use super::super::typecmd::{refresh_bounds, refresh_with_given_leading};
use super::super::typemenu::{bake_dynamic_text, text_ids};
use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets};
use crate::{EngineError, Result, Session};
@@ -170,7 +170,11 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result<Value> {
for (id, changes) in &plans {
let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?;
t.runs = tweak(std::mem::take(&mut t.runs), changes);
refresh_bounds(t);
// With Block on, the first changed character's leading goes to the frame's line gap.
match changes.first().filter(|_| key == "leading") {
Some(&(at, _)) => refresh_with_given_leading(t, at),
None => refresh_bounds(t),
}
}
Ok(())
})?;
+5 -5
View File
@@ -1,6 +1,6 @@
//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once.
//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and
//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type
//! `addon.units.convert` reads a length with units and arithmetic ([`Unit::parse`]) and gives
//! it in each unit of Preferences › Units › East Asian Type
//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]).
//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform
//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the
@@ -10,7 +10,7 @@
mod tests;
use serde_json::{Value, json};
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit};
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, finite_in_every_unit};
use vectorcraft_render::effects;
use super::super::{CommandSpec, always, bad, cmd, has_selection};
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Convert Units",
[],
None,
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
"{value: a length (a number, or text with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point in \"0,5 mm\", but a thousands-shaped number is refused even in arithmetic, as in \"1,500+2\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
always,
convert
),
@@ -76,7 +76,7 @@ fn convert(_: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(CONVERT, "missing `value`"));
};
let pt = match v {
Value::String(s) if readable(s) => unit.parse(&decimal_point(s)),
Value::String(s) if readable(s) => unit.parse_with_decimal_comma(s),
Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)),
_ => None,
};
+13 -3
View File
@@ -50,7 +50,7 @@ fn a_length_comes_back_in_every_unit_in_order() {
}
#[test]
fn values_read_as_number_fields_read_them() {
fn values_accept_units_arithmetic_and_decimal_commas() {
let mut s = session();
let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap();
assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0));
@@ -72,8 +72,9 @@ fn values_read_as_number_fields_read_them() {
assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0));
// Each number of a sum reads its own separator.
assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4));
// A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5.
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
assert!(near(pt(&mut s, json!({"value": "2x0,125 px"})), 0.25));
assert!(near(pt(&mut s, json!({"value": "0,125p6+2"})), 9.5));
assert!(near(pt(&mut s, json!({"value": "2p0,5+1"})), 25.5));
// A sum of 128 signs still reads.
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
// x, X and × multiply as * does, and each counts toward the 128 signs.
@@ -84,6 +85,15 @@ fn values_read_as_number_fields_read_them() {
assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err());
}
#[test]
fn a_thousands_comma_in_an_arithmetic_operand_is_refused() {
let mut s = session();
for value in ["1,500+2", "1,000 px+2", "2+-1,000", "2/1,000", "2×1,000 in", "1,000'X2", "5pt+1,000%", "1,000p6+2", "2p1,000+2"] {
let result = s.execute("addon.units.convert", &json!({"value": value}));
assert!(matches!(result, Err(EngineError::BadParams { .. })), "{value}: {result:?}");
}
}
#[test]
fn keys_the_commands_do_not_take_are_refused() {
let s = session();
+55 -18
View File
@@ -322,35 +322,52 @@ impl ItemTarget {
/// targets have. In a target without an equal item, and for any other target, the row stands
/// for itself. Every entry is `Some`.
pub(crate) fn per_target(self, s: &Session, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] };
let Some(st) = s.active().filter(|_| ids.len() >= 2) else { return vec![Some(self); ids.len()] };
let k = self.anchor(s, ids);
let Some(first) = ids.get(k).and_then(|id| st.doc.node(*id)) else { return vec![Some(self); ids.len()] };
ids.iter()
.enumerate()
.map(|(j, id)| match st.doc.node(*id) {
self.each_target(s, ids).collect()
}
/// [`ItemTarget::per_target`], one target at a time: a caller that stops at the first answer
/// matches only the targets it reads against the anchor's stack.
pub(crate) fn each_target<'a>(self, s: &'a Session, ids: &'a [NodeId]) -> impl Iterator<Item = Option<ItemTarget>> + 'a {
let anchor = match self {
ItemTarget::Item { aligned: true, .. } if ids.len() >= 2 => s.active().and_then(|st| {
let k = self.anchor(s, ids);
Some((&st.doc, k, ids.get(k).and_then(|id| st.doc.node(*id))?))
}),
_ => None,
};
ids.iter().enumerate().map(move |(j, id)| {
let (ItemTarget::Item { index, explicit, .. }, Some((d, k, first))) = (self, anchor) else { return Some(self) };
match d.node(*id) {
Some(n) if j != k => {
let at = SharedStack::of(&[&*first.appearance, &*n.appearance]).item_in(index, 1);
let at = shared_stack(&first.appearance, &n.appearance).item_in(index, 1);
Some(at.map_or(self, |index| ItemTarget::Item { index, explicit, aligned: true }))
}
_ => Some(self),
})
.collect()
}
})
}
/// [`ItemTarget::per_target`], with an explicit aligned item a row of the stack of `of` (see [`design_reference`]),
/// which is not among `ids`, when there is one: each target edits the item equal to it there, and a target without
/// an equal item is left out (`None`).
pub(crate) fn per_target_of(self, s: &Session, of: Option<NodeId>, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
let ItemTarget::Item { index, explicit: true, aligned: true } = self else { return self.per_target(s, ids) };
let Some(d) = s.active().map(|st| &st.doc) else { return self.per_target(s, ids) };
let Some(r) = of.and_then(|of| d.node(of)) else { return self.per_target(s, ids) };
ids.iter()
.map(|id| {
let index = SharedStack::of(&[&*r.appearance, &*d.node(*id)?.appearance]).item_in(index, 1)?;
self.each_target_of(s, of, ids).collect()
}
/// [`ItemTarget::per_target_of`], one target at a time (see [`ItemTarget::each_target`]).
pub(crate) fn each_target_of<'a>(self, s: &'a Session, of: Option<NodeId>, ids: &'a [NodeId]) -> impl Iterator<Item = Option<ItemTarget>> + 'a {
let reference = match self {
ItemTarget::Item { index, explicit: true, aligned: true } => s.active().map(|st| &st.doc).and_then(|d| Some((d, d.node(of?)?, index))),
_ => None,
};
let own = reference.is_none().then(|| self.each_target(s, ids));
let shared = reference.map(|(d, r, index)| {
ids.iter().map(move |id| {
let index = shared_stack(&r.appearance, &d.node(*id)?.appearance).item_in(index, 1)?;
Some(ItemTarget::Item { index, explicit: true, aligned: true })
})
.collect()
});
own.into_iter().flatten().chain(shared.into_iter().flatten())
}
/// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of
@@ -392,6 +409,26 @@ impl ItemTarget {
}
}
/// The stack that `a` and `b` share ([`SharedStack::of`]), which [`ItemTarget::each_target`] and
/// [`ItemTarget::each_target_of`] match each target's rows in.
fn shared_stack(a: &Appearance, b: &Appearance) -> SharedStack {
#[cfg(test)]
STACKS_MATCHED.set(STACKS_MATCHED.get() + 1);
SharedStack::of(&[a, b])
}
#[cfg(test)]
thread_local! {
/// [`stacks_matched`] of this thread.
static STACKS_MATCHED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// How many shared stacks [`shared_stack`] has built on this thread.
#[cfg(test)]
pub(crate) fn stacks_matched() -> u64 {
STACKS_MATCHED.get()
}
/// Does `p` say its item and effect indices are rows of the first target's stack (`aligned`),
/// which each other target edits where it has them (see [`ItemTarget::per_target`])?
pub(crate) fn aligned(p: &Value, cmd: &str) -> Result<bool> {
@@ -865,7 +902,7 @@ fn edit_items_writing_then(
/// The first of `ids` that [`edit_items`] aimed at `item` with `of` changes, and the item it changes there. Read it
/// before the edit: once edited, a row that was equal to a row of the art of `of` no longer is.
pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option<NodeId>, ids: &[NodeId]) -> Option<(NodeId, ItemTarget)> {
ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
ids.iter().zip(item.each_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
}
/// Keep the object rows of the graph labels among `ids` for every label of their kind
+1 -1
View File
@@ -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,
+8 -4
View File
@@ -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)
}
+6 -3
View File
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Swatch Conflicts",
[],
None,
"{profileMismatch?: as edit.paste} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours",
"{profileMismatch?: as edit.paste, allArtboards?: false (true: for edit.pasteOnAllArtboards, which leaves the background colors of copied artboards behind)} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours",
has_doc,
conflicts
),
@@ -568,9 +568,12 @@ fn import_svg(s: &mut Session, p: &Value) -> Result<Value> {
fn conflicts(s: &mut Session, p: &Value) -> Result<Value> {
let hex = |w: &Swatch| w.paint.color().map(|c| c.to_hex());
// The swatches as the paste brings them: converted from another profile when it converts.
let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?;
const CMD: &str = "clipboard.conflicts";
let profile = super::colormgmt::PasteProfile::param(p, CMD)?;
// Paste on All Artboards leaves the copied artboards, and so their backgrounds, behind.
let all_artboards = super::switch_or(p, "allArtboards", false, CMD)?;
let st = s.doc()?;
let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, true);
let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, !all_artboards);
let list: Vec<Value> = converted
.as_ref()
.unwrap_or(&s.clipboard)
+49 -1
View File
@@ -1601,7 +1601,8 @@ impl Clipboard {
/// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's
/// filter of its name; one that draws another definition than that filter takes the document's
/// filter when pasted back into the document it came from, and elsewhere keeps its own under a
/// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone. When that name would
/// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone; an
/// effect of the document that draws the same definition under a name no filter has gives that name. When that name would
/// make the filter too long to draw, the free name is a shorter start of its name ("Shif"), else
/// a free letter, digit or other printable ASCII character; the filter's id is always its name. An error when no free name fits.
fn filter_links(&self, d: &Document, same_doc: bool) -> Result<BTreeMap<(String, String), (String, String)>> {
@@ -1627,6 +1628,8 @@ impl Clipboard {
}
let mut taken: BTreeSet<String> = d.svg_filters.iter().map(|f| f.name.clone()).chain(found.iter().map(|(n, _)| n.clone())).collect();
let mut effects_read = false;
// The filter effects of the document, by name and definition.
let mut held_effects = BTreeSet::new();
let mut links = BTreeMap::new();
for (name, xml) in found {
let Some(held) = d.svg_filters.iter().find(|f| f.name == name).filter(|f| f.xml != xml.trim()) else { continue };
@@ -1640,14 +1643,28 @@ impl Clipboard {
effects_read = true;
for root in d.art_roots() {
node_filter_names(root, &mut taken);
node_filters(root, &mut held_effects);
}
for a in vectorcraft_brush::library(d).iter().flat_map(Brush::art) {
node_filter_names(a, &mut taken);
node_filters(a, &mut held_effects);
}
for g in &d.graphic_styles {
appearance_filter_names(&g.appearance, &mut taken);
appearance_filters(&g.appearance, &mut held_effects);
}
}
// An effect of the document that already draws this filter under a name no filter
// of the document has (one pasted or loaded before) gives its name, so pasting or
// loading the same filter again adds no other name.
let earlier = held_effects.iter().find(|(n, x)| {
!d.svg_filters.iter().any(|f| &f.name == n)
&& vectorcraft_render::effects::svg_filter::with_id(&xml, n).is_some_and(|drawn| drawn == *x)
});
if let Some((n, x)) = earlier {
links.insert((name, xml), (n.clone(), x.clone()));
continue;
}
// Free names made from the starts of the name, longest first, then free letters and
// digits, then other single printable ASCII characters: the first under which the
// filter still draws.
@@ -1845,6 +1862,8 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
let clip = Clipboard::with_used(src, &used, &library, vec![]);
let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::<BTreeSet<_>>());
let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?;
// Graphs in the symbols added draw with the designs `d` kept, as pasted ones do.
crate::cmd::graph::redraw_symbols_with_designs(d, &out.added_symbols, &out.kept_designs);
let mut placed: Vec<LoadedStyle> = vec![];
for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] {
for s in list {
@@ -1857,6 +1876,35 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
Ok(placed)
}
/// Add to `d` the swatches, patterns, symbols and brushes (and what their art uses) that the
/// appearance `look` of `src` and the character style attributes `attrs` of `src` paint with, as
/// [`import_text_styles`] adds those of loaded styles, and give back `look` and `attrs` relinked to
/// them (a resource `d` has under the same name and with the same contents is used; another is
/// added under a free name; a global or spot color whose name `d` gives another color is `d`'s;
/// an SVG filter whose name `d` gives another filter is renamed).
pub(crate) fn import_looks(
src: &Document,
d: &mut Document,
look: &Appearance,
attrs: &Map<String, Value>,
) -> Result<(Appearance, Map<String, Value>)> {
let library = OnceCell::new();
let defs = Defs::of(src, &library);
let mut used = Used::default();
used.follow(&defs, vec![Source::Appearance(look), Source::Attrs(attrs)]);
// The look goes on an empty path, so that its SVG filters are renamed where `d` gives their
// names other filters, as a pasted object's are.
let carrier = Node::path(vectorcraft_doc::NodeId(0), vectorcraft_geom::PathData::default(), look.clone());
let clip = Clipboard::with_used(src, &used, &library, vec![carrier]);
let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?;
// Graphs in the symbols added draw with the designs `d` kept, as pasted ones do.
crate::cmd::graph::redraw_symbols_with_designs(d, &out.added_symbols, &out.kept_designs);
let (mut look, mut attrs) = (look.clone(), attrs.clone());
out.relink.appearance(&mut look);
out.relink.attrs(&mut attrs);
Ok((look, attrs))
}
/// The resources graph designs `names` of `src` use, through the definitions they lead to.
fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used {
let mut used = Used::default();
+4 -3
View File
@@ -141,7 +141,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Contrast",
[],
None,
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
always,
contrast
),
@@ -1260,8 +1260,9 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re
.transpose()
};
let drawing;
// Selected objects that share a color but draw it differently have no one answer.
if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) {
// Selected objects that share a color but draw it differently have no one answer. While the
// active tool paints with the proxy's color, the selection does not draw it.
if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none() && !s.tool_paints(stroke)) {
let item = s.appearance_item();
// Every painted object inside a selected group counts, as the proxy's color comes from all,
// except hidden ones and those inside a hidden group, which draw nothing. The first shown
+31 -13
View File
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Color Settings…",
["Edit"],
Some("Cmd+Shift+K"),
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
"{rgb?: profile, cmyk?: profile (built in: \"VectorCraft Generic CMYK (SWOP-like)\" (default), \"VectorCraft Coated CMYK (FOGRA51)\" and \"VectorCraft Uncoated CMYK (FOGRA52)\" (computed from Fogra's characterization data), \"Device CMYK (uncalibrated)\"), intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
always,
color_settings
),
@@ -562,16 +562,30 @@ fn mode_converter(mode: ColorMode, intent: Option<Intent>, grays: Grays) -> impl
}
/// The name and color of each global swatch of `d`, for [`mode_color`].
fn global_bases(d: &vectorcraft_doc::Document) -> Vec<(String, Color)> {
d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect()
fn global_bases(d: &vectorcraft_doc::Document) -> BTreeMap<String, Color> {
let mut first = BTreeMap::new();
for w in d.swatches_iter() {
// An ineligible first record still shadows a later global solid of the same name.
first.entry(w.name.as_str()).or_insert(w);
}
first
.into_values()
.filter_map(|w| {
if !w.global {
return None;
}
let Paint::Solid { color, swatch: None, .. } = &w.paint else { return None };
Some((w.name.clone(), d.linked_color(*color, w.spot)))
})
.collect()
}
/// The color Document Color Mode gives `col` (swatch link `link`): a tint of a global swatch in
/// `bases` (already converted) is that swatch's color at its tint; any other color goes through
/// `conv` ([`mode_converter`]).
fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &dyn Fn(&Color) -> Color) -> Color {
match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) {
Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint),
fn mode_color(col: &Color, link: proof::Link, bases: &BTreeMap<String, Color>, conv: &dyn Fn(&Color) -> Color) -> Color {
match link.and_then(|(name, tint)| Some((bases.get(name)?, tint))) {
Some((base, tint)) if tint < 1.0 => base.tinted(tint),
_ => conv(col),
}
}
@@ -579,10 +593,11 @@ fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &
/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks,
/// effect colors and the series paints and label styles that graphs keep included), symbols,
/// graph designs, pattern tiles (the tile that pattern editing's Cancel puts back included),
/// graphic styles (their effects included), brushes (their art and a Hue Shift key color) and
/// swatches through the color settings (`intent`, default: theirs) → how many colors of the art
/// (opacity masks, effect colors and graphs' paints included), symbols, graph designs and pattern
/// tiles changed; the colors of graphic styles and brushes convert without being counted. Gray
/// graphic styles (their effects included), brushes (their art and a Hue Shift key color),
/// character and paragraph styles (their fill and stroke) and swatches through the color settings
/// (`intent`, default: theirs) → how many colors of the art (opacity masks, effect colors and
/// graphs' paints included), symbols, graph designs and pattern tiles changed; the colors of
/// graphic styles, brushes and text styles convert without being counted. Gray
/// colors stay Gray (they print on the black plate in either mode); RGB grays are colors like any
/// other and separate through the CMYK profile, unless `grays` puts them on the black plate
/// ([`mode_converter`]). Lab colors
@@ -594,7 +609,10 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode,
if !convert {
return 0;
}
convert_colors(d, &mode_converter(mode, intent, grays))
let conv = mode_converter(mode, intent, grays);
let changed = convert_colors(d, &conv);
convert_style_colors(d, &conv);
changed
}
/// Every color of `d` that [`set_color_mode`] converts, converted with `conv` → how many colors of
@@ -685,8 +703,8 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co
vectorcraft_brush::store(d, &brushes);
}
// This pass gives tint swatches their converted swatch's color at their tint; the passes above already did the same for the art's tints.
d.map_solid_paints(&mut |c, link, tint| match bases.iter().find(|(n, _)| Some(n) == link.as_ref()) {
Some((_, base)) if *tint < 1.0 => {
d.map_solid_paints(&mut |c, link, tint| match link.as_ref().and_then(|name| bases.get(name)) {
Some(base) if *tint < 1.0 => {
*c = base.tinted(*tint);
true
}
+34 -13
View File
@@ -157,14 +157,7 @@ pub fn encode(setup: &ProofSetup) -> Vec<u8> {
pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "view.proofSetup.save";
let (path, named) = file_path(s, p, C)?;
let mut setup = proof::view().setup;
setup_params(p, &mut setup, C)?;
check_device(&setup.target).map_err(|e| bad(C, e))?;
// A file `view.proofSetup.load` would refuse is not written (a device with a very long name).
let bytes = encode(&setup);
if bytes.len() > MAX_FILE {
return Err(bad(C, format!("{path}: larger than {MAX_FILE} bytes")));
}
let (setup, bytes) = encode_options(p, &path)?;
if named
&& let Some(dir) = std::path::Path::new(&path).parent()
&& !dir.is_dir()
@@ -179,19 +172,47 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Object(r))
}
/// Serialize the Customize dialog's draft without committing it or writing a path.
pub fn draft_bytes(p: &Value) -> Result<Vec<u8>> {
encode_options(p, "Proof Setup").map(|(_, bytes)| bytes)
}
fn encode_options(p: &Value, file: &str) -> Result<(ProofSetup, Vec<u8>)> {
const C: &str = "view.proofSetup.save";
let mut setup = proof::view().setup;
setup_params(p, &mut setup, C)?;
check_device(&setup.target).map_err(|e| bad(C, e))?;
let bytes = encode(&setup);
if bytes.len() > MAX_FILE {
return Err(bad(C, format!("{file}: larger than {MAX_FILE} bytes")));
}
Ok((setup, bytes))
}
/// The file `p` names for `cmd` and the usable proof setup in it.
fn read_setup(s: &Session, p: &Value, cmd: &str) -> Result<(String, ProofSetup)> {
let (path, _) = file_path(s, p, cmd)?;
// One byte past the limit shows a file over it, which is not read further.
let bytes = fileio::read_file_head(&path, MAX_FILE + 1)?;
if bytes.len() > MAX_FILE {
return Err(bad(cmd, format!("{path}: larger than {MAX_FILE} bytes")));
}
let setup = parse(&bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
check_device(&setup.target).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
let setup = checked_setup(&bytes, &path, cmd)?;
Ok((path, setup))
}
/// Read a picked proof setup's validated settings without applying them to the view.
pub fn draft_fields(bytes: &[u8], name: &str) -> Result<Value> {
let setup = checked_setup(bytes, name, "view.proofSetup.read")?;
Ok(Value::Object(setup_json(&setup)))
}
fn checked_setup(bytes: &[u8], name: &str, cmd: &str) -> Result<ProofSetup> {
if bytes.len() > MAX_FILE {
return Err(bad(cmd, format!("{name}: larger than {MAX_FILE} bytes")));
}
let setup = parse(bytes).map_err(|e| bad(cmd, format!("{name}: {e}")))?;
check_device(&setup.target).map_err(|e| bad(cmd, format!("{name}: {e}")))?;
Ok(setup)
}
pub(super) fn read(s: &mut Session, p: &Value) -> Result<Value> {
let (path, setup) = read_setup(s, p, "view.proofSetup.read")?;
let mut r = setup_json(&setup);
+44 -20
View File
@@ -27,7 +27,7 @@ pub const EXTS: &[&str] = &["vccomposite"];
const EXPORT: &str = "type.compositeFonts.export";
/// The largest file Import reads, in bytes.
const MAX_FILE_BYTES: usize = 4 << 20;
pub const MAX_FILE_BYTES: usize = 4 << 20;
/// The keys a part may give.
const PART_KEYS: [&str; 7] = ["font", "style", "size", "baseline", "hScale", "vScale", "scaleAtCenter"];
@@ -204,7 +204,7 @@ fn parse_set(v: &Value, font: &str, kanji: &CompositePart, c: &str) -> Result<Cu
/// Error unless `fonts` can stand together in a document: names unique in any case, none naming
/// an installed font, no part set in a composite font, and at most [`COMPOSITE_FONTS_MAX`].
fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
pub(crate) fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> {
if fonts.len() > COMPOSITE_FONTS_MAX {
return Err(bad(c, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
}
@@ -237,31 +237,53 @@ fn replace(s: &mut Session, label: &str, after: Vec<CompositeFont>) -> Result<()
if before == after {
return Ok(());
}
let changed = register(s, &before, &after);
let r = s.edit(label, |d, _| set_fonts(d, &after, &changed));
sync(s);
r
}
/// Before an edit makes `after` the active document's composite fonts (it has `before`), register
/// them in the font database and forget the ones taken out → the lowercased names of the fonts that
/// change, for [`set_fonts`]. Run [`sync`] after the edit, whether it was made or not.
pub(crate) fn register(s: &mut Session, before: &[CompositeFont], after: &[CompositeFont]) -> Vec<String> {
let changed: Vec<String> =
before.iter().filter(|b| !after.contains(b)).chain(after.iter().filter(|a| !before.contains(a))).map(|f| f.name.to_lowercase()).collect();
// A refused or panicked edit leaves the document without the new fonts: `sync` forgets a name
// listed here that the document doesn't define.
s.composite_names.extend(after.iter().map(|f| f.name.to_lowercase()));
let db = FontDb::global();
for f in &before {
for f in before {
if !after.iter().any(|a| CompositeFont::same_name(&a.name, &f.name)) {
db.remove_composite_font(&f.name);
}
}
for f in &after {
for f in after {
db.set_composite_font(f);
}
let r = s.edit(label, |d, _| {
*d.composite_fonts = after.clone();
each_text_mut(d, &mut |t| {
if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) {
refresh_bounds(t);
}
Ok(())
})
});
sync(s);
r
changed
}
/// Make `after` the composite fonts of `d`, and measure the type set in a font of `changed` again.
pub(crate) fn set_fonts(d: &mut vectorcraft_doc::Document, after: &[CompositeFont], changed: &[String]) -> Result<()> {
*d.composite_fonts = after.to_vec();
each_text_mut(d, &mut |t| {
if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) {
refresh_bounds(t);
}
Ok(())
})
}
/// `fonts` with `f` in place of the composite font of its name, or added, as Import Composite Fonts
/// adds a font.
pub(crate) fn with_font(fonts: &[CompositeFont], f: &CompositeFont) -> Vec<CompositeFont> {
let mut after = fonts.to_vec();
match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) {
Some(a) => *a = f.clone(),
None => after.push(f.clone()),
}
after
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
@@ -349,7 +371,12 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
let too_large = || bad(C, "the file is larger than 4 MB");
let bytes = match given {
(Some(path), None, None) if !path.trim().is_empty() => read_file_head(path, MAX_FILE_BYTES + 1)?,
(None, Some(text), None) => text.as_bytes().to_vec(),
(None, Some(text), None) => {
if text.len() > MAX_FILE_BYTES {
return Err(too_large());
}
text.as_bytes().to_vec()
}
(None, None, Some(b64)) => {
if b64.len() > MAX_FILE_BYTES / 3 * 4 + 4 {
return Err(too_large());
@@ -372,10 +399,7 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
if apply {
let mut after = s.doc()?.doc.composite_fonts.to_vec();
for f in &fonts {
match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) {
Some(a) => *a = f.clone(),
None => after.push(f.clone()),
}
after = with_font(&after, f);
}
check_set(&after, C)?;
replace(s, "Import Composite Fonts", after)?;
@@ -27,6 +27,27 @@ fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
/// Inline and encoded files share the same raw byte limit; rejection changes no fonts or history.
#[test]
fn import_file_byte_boundaries_preserve_the_document_on_refusal() {
let mut s = session();
s.execute("type.compositeFonts.set", &json!({"fonts": [font("Existing")]})).unwrap();
let before = steps(&s);
let large = " ".repeat(super::MAX_FILE_BYTES + 1);
for params in [json!({"data": large}), json!({"dataBase64": vectorcraft_format::base64_encode(large.as_bytes())})] {
let error = s.execute("type.compositeFonts.import", &params).unwrap_err();
assert!(error.to_string().contains("the file is larger than 4 MB"), "{error}");
assert_eq!(names(&s), ["Existing"]);
assert_eq!(steps(&s), before);
}
let mut exact = json!({"compositeFonts": [font("Imported")]}).to_string();
exact.extend(std::iter::repeat_n(' ', super::MAX_FILE_BYTES - exact.len()));
let imported = s.execute("type.compositeFonts.import", &json!({"data": exact, "apply": false})).unwrap();
assert_eq!(imported["fonts"][0]["name"], "Imported");
assert_eq!(names(&s), ["Existing"]);
assert_eq!(steps(&s), before);
}
fn text(s: &Session, id: u64) -> vectorcraft_doc::TextObject {
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => (**t).clone(),
+21 -6
View File
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Curvature Circle",
[],
None,
"{id, subpath?=0, segment, t: 0..1, convex?=false} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn",
"{id, subpath?=0, segment, t: 0..1, convex?=false, constantRadius?=true, anchors?: \"standard\"|\"touch\" (default standard: a live ellipse with four anchors at 0°, 90°, 180° and 270°; touch: a path with an anchor where the circle touches the path and one every 90° from there)} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; with constantRadius, a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle, and with constantRadius false the cubic's own curvature at `t`; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn",
has_doc,
curvature_circle
),
@@ -548,7 +548,8 @@ fn selected_anchor_points(s: &Session) -> Result<Option<Vec<Point>>> {
}
/// A live ellipse that touches a path at a point with the path's curvature there
/// ([`curvature::curvature_circle_on`]). One undo step, named as an Ellipse tool drag is.
/// ([`curvature::curvature_circle_on_with`]); with `anchors: "touch"`, a plain path with an anchor
/// at the point it touches and one every 90° from there ([`shapes::circle_with_anchors_at`]). One undo step, named as an Ellipse tool drag is.
fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "shape.curvatureCircle";
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
@@ -559,6 +560,13 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "`t` must be from 0 to 1"));
}
let convex = switch_or(p, "convex", false, C)?;
let arcs = switch_or(p, "constantRadius", true, C)?;
let key = "anchors";
let at_touch = match p.get(key).map(Value::as_str) {
None | Some(Some("standard")) => false,
Some(Some("touch")) => true,
Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, touch"))),
};
let found = {
let st = s.doc()?;
let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
@@ -570,7 +578,7 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
if seg >= sp.segment_count() {
return Err(bad(C, "no such segment"));
}
curvature::curvature_circle_on(sp, seg, t, convex)
curvature::curvature_circle_on_with(sp, seg, t, convex, arcs)
};
let circle = found.map_err(|e| match e {
NoCircle::Straight => bad(C, "the path is straight there, so no circle matches its curvature"),
@@ -579,12 +587,19 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
})?;
let (center, radius) = (circle.center, circle.radius);
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.abs() <= MAX_COORD) {
let (path, live) = if at_touch {
(shapes::circle_with_anchors_at(center, radius, &[circle.at]), None)
} else {
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
(live.to_path(), Some(live))
};
// The bounds of the path drawn: started where it touches, its cubics reach a little past the
// circle.
if path.bounds().is_none_or(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= MAX_COORD)) {
return Err(bad(C, "the circle that matches the path there would reach past the canvas"));
}
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
// Not pixel-aligned: the circle stays on the path.
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
let mut out = add_art_unaligned(s, "Ellipse", path_kind(path, live))?;
out["cx"] = json!(center.x);
out["cy"] = json!(center.y);
out["radius"] = json!(radius);
Loaded 100 of 855 files, more files were not shown because too many files have changed in this diff. Show more