Merge main into feat/toolbar-command-buttons

This commit is contained in:
dotCooCoo committed 2026-11-27 23:03:16 -08:00
commit e99a3e11cf
854 files changed
+82562 -6571

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
+13 -6
View File
@@ -2,13 +2,13 @@
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/vectorcraft",
"repository_id": 1398097510,
"producer_workflow_id": null,
"producer_workflow_id": 430275079,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
@@ -79,7 +79,14 @@
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
+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
+72
View File
@@ -0,0 +1,72 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [VectorCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
if: >-
false && github.repository == 'storytold/vectorcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected signer-branch validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/vectorcraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/vectorcraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/vectorcraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/vectorcraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'vectorcraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
+10 -7
View File
@@ -1,7 +1,8 @@
name: VectorCraft release-ref nightly signer
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
# fast-forwards to reviewed main commits (never the stable release branch).
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
on:
workflow_dispatch:
inputs:
@@ -22,21 +23,23 @@ concurrency:
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
if: >-
github.repository == 'storytold/vectorcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: vectorcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment and export keys in its signing step.
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
+4 -4
View File
@@ -22,13 +22,13 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
app-name: vectorcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+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 }}
+9
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).
Generated
+519 -130
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" }
+11
View File
@@ -152,6 +152,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 }
+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();
+10 -1
View File
@@ -50,9 +50,10 @@ pub fn attach_color_settings(session: &mut vectorcraft_engine::Session) {
}
/// Install the plug-ins Install Plug-in kept in the `Plug-ins` folder (#2541), and keep the ones
/// installed from now on there.
/// installed from now on there. The key of the grants kept there is in the system's key store.
pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) {
if let Some(dir) = store_dir("Plug-ins") {
vectorcraft_engine::store::grant_keys::use_os_grant_keys();
session.attach_plugin_store(dir);
}
}
@@ -65,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
+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3" y="8" width="13" height="8" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M16 4V20" stroke-width="1" /></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="2" y="7" width="11" height="10" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>

Before

Width:  |  Height:  |  Size: 321 B

After

Width:  |  Height:  |  Size: 323 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 8H12A4 4 0 0 1 12 16H3Z" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M12 4V20" stroke-width="1" /></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M2 7H13A5 5 0 0 1 13 17H2Z" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>

Before

Width:  |  Height:  |  Size: 318 B

After

Width:  |  Height:  |  Size: 319 B

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3" y="8" width="17" height="8" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M16 4V20" stroke-width="1" /></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="2" y="7" width="16" height="10" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>

Before

Width:  |  Height:  |  Size: 321 B

After

Width:  |  Height:  |  Size: 323 B

+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)));
}
}
+85 -2
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
@@ -406,8 +485,10 @@ impl Document {
/// gives it. A line that stays vertical or horizontal stays a ruler guide, at its new place. A
/// line at any other angle becomes a guide path with that line, on the guide's layer, named
/// as the guide was; `sel` then holds the path as a selected object instead of the guide.
/// Guides that cannot be edited ([`Self::guide_editable`]) stay as they are.
pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) {
/// Guides that cannot be edited ([`Self::guide_editable`]) stay as they are. Returns the ids
/// of the guide paths it adds, in the order it adds them.
pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) -> Vec<NodeId> {
let mut paths = vec![];
for id in sel.guides.clone() {
let Some(g) = self.ruler_guide(id).filter(|g| self.guide_editable(g)) else { continue };
let (a, b) = match self.transformed_guide(&g, xf) {
@@ -431,7 +512,9 @@ impl Document {
}
self.retain_guides(sel, |g| g.id != Some(id));
sel.objects.push(path);
paths.push(path);
}
paths
}
/// The ruler guide node `g` names, if this document has it.
+146
View File
@@ -731,6 +731,152 @@ fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: O
tops
}
/// The most hits [`leaves_at`] lists.
pub const MAX_LEAVES_AT: usize = 256;
/// The hits under `p`, topmost first, at most [`MAX_LEAVES_AT`]: one for each object a click with
/// Direct Selection picks there (a path, a compound path or an image, also inside a group), each
/// found by a hit test ([`hit_test`]) that passes over the ones found before it. In isolation mode
/// (`opt.scope`) only what is inside the isolated group or object is hit. Cmd/Ctrl-clicks with the
/// Selection tool step through them (Select Behind).
pub fn leaves_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<Hit> {
let _walk = ArtWalk::open();
// A clipping mask, or a group drawn with its own geometry effects, hits by rules the single
// traversal leaves to the hit test: the repeated hit test finds the rest, after the hits found
// above them, which the art walked for them already counted against.
leaves_at_once(doc, p, opt).unwrap_or_else(|above| leaves_at_repeated_after(doc, p, opt, above))
}
/// [`leaves_at`] by repeated hit tests, each passing over the objects found before it.
#[cfg(test)]
fn leaves_at_repeated(doc: &Document, p: Point, opt: HitOptions) -> Vec<Hit> {
leaves_at_repeated_after(doc, p, opt, vec![])
}
/// [`leaves_at`] by repeated hit tests after `hits`, the topmost hits already found.
fn leaves_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, mut hits: Vec<Hit>) -> Vec<Hit> {
let mut found: HashSet<NodeId> = hits.iter().map(|h| h.leaf).collect();
while hits.len() < MAX_LEAVES_AT
&& let Some(h) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true)
{
if !found.insert(h.leaf) {
break;
}
hits.push(h);
}
hits
}
/// [`leaves_at`] in one traversal of the document, in the order repeated hit tests
/// ([`hit_test_skipping`]) find them. `Err` with the hits found above it when a container under
/// `p` clips or draws its art with its own geometry effects ([`leaves_in`]).
fn leaves_at_once(doc: &Document, p: Point, opt: HitOptions) -> Result<Vec<Hit>, Vec<Hit>> {
let finish = |mut h: Hit| {
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
h
};
let locks = doc.locked_artboards_kept();
let on_locked = |id: NodeId| {
!locks.is_empty() && doc.parent_of(id).and_then(|l| doc.node(l)).is_some_and(Node::is_layer) && doc.node(id).is_some_and(|n| locks.holds(n))
};
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
let mut hits = Vec::new();
if let Some(scope) = opt.scope
&& let Some(isolated) = doc.node(scope)
&& let Some(mut chain) = doc.ancestry(scope)
{
if !doc.is_editable_with(&locks, scope) {
return Ok(hits);
}
let whole = if isolated.is_container() {
leaves_in(isolated, p, opt, &symbols, &on_locked, &mut chain, &mut hits)
} else {
// A single object isolated: only it hits, among its siblings.
chain.pop();
let Some(parent) = chain.last().and_then(|id| doc.node(*id)) else { return Ok(hits) };
leaves_in(parent, p, opt, &symbols, &|id| id != scope || on_locked(id), &mut chain, &mut hits)
};
let hits = hits.into_iter().map(finish).collect();
return if whole { Ok(hits) } else { Err(hits) };
}
let mut chain = Vec::new();
for layer in doc.layers.iter().rev() {
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
continue;
}
chain.push(layer.id);
let opt = if !opt.ignore_layer_preview && previews_off(layer) { HitOptions { outline: true, ..opt } } else { opt };
if !leaves_in(layer, p, opt, &symbols, &on_locked, &mut chain, &mut hits) {
return Err(hits.into_iter().map(finish).collect());
}
chain.pop();
if hits.len() >= MAX_LEAVES_AT {
break;
}
}
Ok(hits.into_iter().map(finish).collect())
}
/// Every editable hit under `p` in `parent`, topmost first, added to `hits` up to
/// [`MAX_LEAVES_AT`]: what [`hit_children`] finds first, then what it finds passing over each hit
/// found before. `false` when `parent` or a container in it under `p` clips or draws its art with
/// its own geometry effects, which [`hit_children`] hits by rules of their own.
fn leaves_in(
parent: &Node,
p: Point,
opt: HitOptions,
symbols: &SymbolBoxes,
skip: &dyn Fn(NodeId) -> bool,
chain: &mut Vec<NodeId>,
hits: &mut Vec<Hit>,
) -> bool {
let Some(children) = parent.children() else { return true };
if parent.clips() || drawn_art(symbols, parent, opt.outline).is_some() {
return false;
}
for i in hit_order(parent, children, p) {
if hits.len() >= MAX_LEAVES_AT {
return true;
}
let Some(c) = children.get(i) else { continue };
if !may_hit(parent, i, c, p, opt, symbols, true) || skip(c.id) {
continue;
}
chain.push(c.id);
let leaf = |hits: &mut Vec<Hit>, chain: &[NodeId]| {
if let Some(kind) = hit_leaf(c, p, opt, symbols) {
hits.push(Hit { leaf: c.id, ancestry: chain.to_vec(), kind, contents_of: None, layers: 1 });
}
};
let whole = match &c.kind {
NodeKind::Layer { preview: false, .. } if !opt.ignore_layer_preview => {
leaves_in(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, hits)
}
NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } | NodeKind::Envelope { editing: true, .. } => {
leaves_in(c, p, opt, symbols, skip, chain, hits)
}
// A blend's key objects first; its steps hit as the blend.
NodeKind::Blend { .. } => {
let whole = leaves_in(c, p, opt, symbols, skip, chain, hits);
if whole && hits.len() < MAX_LEAVES_AT {
leaf(hits, chain);
}
whole
}
_ => {
leaf(hits, chain);
true
}
};
chain.pop();
if !whole {
return false;
}
}
true
}
/// The most objects [`locked_objects_at`] lists.
pub const MAX_LOCKED_AT: usize = 20;
+82
View File
@@ -1992,10 +1992,58 @@ fn objects_at_matches_repeated_hits_on_random_documents() {
let p = Point::new(f64::from(next(120)), f64::from(next(120)));
let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() };
assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None), "round {round}, {p:?}, {opt:?}");
assert_eq!(leaf_chains(leaves_at(&d, p, opt)), leaf_chains(leaves_at_repeated(&d, p, opt)), "leaves: round {round}, {p:?}, {opt:?}");
// Isolated in a group of the document, now and then.
let groups: Vec<NodeId> =
d.layers[0].children().into_iter().flatten().filter(|n| n.is_container() && !n.is_layer()).map(|n| n.id).collect();
if let Some(&g) = groups.first().filter(|_| next(3) == 0) {
let opt = HitOptions { scope: Some(g), ..opt };
assert_eq!(leaf_chains(leaves_at(&d, p, opt)), leaf_chains(leaves_at_repeated(&d, p, opt)), "isolated: round {round}, {p:?}");
}
}
}
}
/// A hit's leaf, ancestry, kind, layer count and edited envelope.
type LeafChain = (NodeId, Vec<NodeId>, HitKind, usize, Option<NodeId>);
/// Each hit's [`LeafChain`], to compare two lists.
fn leaf_chains(hits: Vec<Hit>) -> Vec<LeafChain> {
hits.into_iter().map(|h| (h.leaf, h.ancestry, h.kind, h.layers, h.contents_of)).collect()
}
/// Select Behind steps through the members of groups one by one, front to back, in one traversal
/// for a large stack, as the hit test repeated over what is left finds them.
#[test]
fn leaves_at_lists_group_members_one_by_one() {
let mut d = Document::new(100.0, 100.0);
let layer = d.layers[0].id;
let square = |d: &mut Document| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art());
let below = square(&mut d);
let below_id = below.id;
d.insert(Some(layer), usize::MAX, below).unwrap();
let members: Vec<Node> = (0..300).map(|_| square(&mut d)).collect();
let mut ids: Vec<NodeId> = members.iter().map(|n| n.id).collect();
let g = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap();
ids.reverse();
ids.push(below_id);
let p = Point::new(25.0, 25.0);
let hits = leaves_at(&d, p, HitOptions::default());
assert_eq!(hits.len(), MAX_LEAVES_AT, "the list stops at its limit");
assert_eq!(hits.iter().map(|h| h.leaf).collect::<Vec<_>>(), ids[..MAX_LEAVES_AT], "the group's members, topmost first");
assert!(hits.iter().all(|h| h.ancestry.contains(&g)));
assert_eq!(leaf_chains(hits), leaf_chains(leaves_at_repeated(&d, p, HitOptions::default())));
// Hidden past the limit, the object below the group comes after the members that are left.
for id in &ids[3..300] {
d.node_mut(*id).unwrap().visible = false;
}
let shown: Vec<NodeId> = leaves_at(&d, p, HitOptions::default()).iter().map(|h| h.leaf).collect();
assert_eq!(shown, [ids[0], ids[1], ids[2], below_id]);
let isolated = leaves_at(&d, p, HitOptions { scope: Some(g), ..Default::default() });
assert!(!isolated.iter().any(|h| h.leaf == below_id), "isolated: only the group's members");
}
/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the
/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times.
fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
@@ -2322,6 +2370,40 @@ fn select_behind_keeps_one_art_limit_when_it_falls_back() {
assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked");
}
/// [`leaves_at`] falls back to repeated hit tests at a clip group, after the hits its single
/// traversal found above it: an instance hit by its art, with the limit of symbol art then used
/// up, stays in the list.
#[test]
fn leaves_at_keeps_the_hits_above_a_clip_group_it_falls_back_at() {
let p = Point::new(150.0, 50.0);
let mut d = Document::new(600.0, 400.0);
clipped_symbol(&mut d, false);
// A clip group at the bottom of the layer, its art under (150, 50).
let square = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art()));
let (mask, art) = (d.alloc_id(), d.alloc_id());
let mut clip_group = Node::group(d.alloc_id(), vec![square(mask), square(art)]);
clip_group.set_clips(true);
let l = d.layers[0].id;
d.insert(Some(l), 0, clip_group).unwrap();
let (mut shown_mask, shown_art) = half_clipped(&mut d);
shown_mask.appearance.effects.push(test_move());
let mut shown = Node::group(d.alloc_id(), vec![Arc::new(shown_mask), Arc::new(shown_art)]);
shown.set_clips(true);
group_symbol(&mut d, "Shown", vec![Arc::new(shown)]);
let hit = instance_of(&mut d, "Shown");
let hit_id = hit.id;
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap();
for _ in 0..32 {
let inst = instance_of(&mut d, "Clipped");
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap();
}
let (hits, _, arts) = with_art_limit(100, || leaves_at(&d, p, HitOptions::default()));
let leaves: Vec<NodeId> = hits.iter().map(|h| h.leaf).collect();
assert_eq!(leaves.first(), Some(&hit_id), "hit before the fallback: {leaves:?}");
assert!(leaves.contains(&art), "the clipped art after it: {leaves:?}");
assert!(arts <= 34, "{arts} instances' art walked");
}
#[test]
fn locked_and_hidden_skip() {
let mut d = Document::new(200.0, 200.0);
+1 -1
View File
@@ -116,7 +116,7 @@ pub use metadata::{CopyrightStatus, DocMetadata};
pub use node::Knockout;
pub use node::Scaling;
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS};
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
pub use orient::OrientedBox;
pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType};
pub use perspective::PerspectiveAttachment;
+32
View File
@@ -278,6 +278,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
if let Some(e) = n.extras_box() {
b += ALLOC + size_of::<NodeExtras>();
b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective);
b += e.attrs.as_deref().map_or(0, attrs_bytes);
b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize);
b += e
.color_mask
@@ -404,6 +405,22 @@ fn swatches_bytes(s: &[Swatch]) -> usize {
ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap_bytes(&w.paint)).sum::<usize>()
}
/// The heap an object's attributes own: their text, data, events, classes, foreign attributes and
/// tags.
fn attrs_bytes(a: &crate::ObjectAttributes) -> usize {
let pairs = |v: &Vec<(String, String)>| vec_bytes(v) + v.iter().map(|(k, v)| k.capacity() + v.capacity()).sum::<usize>();
a.url.capacity()
+ a.note.capacity()
+ pairs(&a.data)
+ pairs(&a.events)
+ vec_bytes(&a.classes)
+ a.classes.iter().map(String::capacity).sum::<usize>()
+ vec_bytes(&a.foreign)
+ a.foreign.iter().map(|f| f.ns.capacity() + f.prefix.capacity() + f.name.capacity() + f.value.capacity()).sum::<usize>()
+ vec_bytes(&a.tags)
+ a.tags.iter().map(|t| t.name.capacity() + t.value.capacity()).sum::<usize>()
}
/// A vector's buffer (not what its elements own).
fn vec_bytes<T>(v: &Vec<T>) -> usize {
if v.capacity() == 0 { 0 } else { ALLOC + v.capacity() * size_of::<T>() }
@@ -490,6 +507,21 @@ mod tests {
assert!((400..1200).contains(&per), "{per} bytes per moved rectangle");
}
/// An object's attributes count with their text: a version of a rectangle with a long tag and
/// a long note keeps both.
#[test]
fn tags_and_notes_count() {
let before = doc_with_rects(1);
let mut after = before.clone();
let id = after.layers[0].children().unwrap()[0].id;
after.node_mut(id).unwrap().edit_attrs(|a| {
a.note = "n".repeat(30_000);
a.tags.push(crate::ObjectTag { id: 1, name: "size".into(), value: "v".repeat(60_000) });
});
let bytes = after.retained_bytes(&before);
assert!(bytes >= 90_000, "{bytes} bytes for a rectangle with 90,000 bytes of attributes");
}
#[test]
fn a_grouped_object_is_found_shared() {
let before = doc_with_rects(100);
+1 -1
View File
@@ -24,7 +24,7 @@ mod opacity;
mod ops;
mod wire;
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS};
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
pub use clip::{ClipPaint, Uniter};
pub use extras::{Extras, ExtrasMut, NodeExtras};
pub use ids::{LAYER_COLORS, LayerColor, NodeId};
+135
View File
@@ -38,6 +38,141 @@ pub struct ObjectAttributes {
/// with it.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub foreign: Vec<ForeignAttribute>,
/// The object's tags, in order: name and value pairs that scripts read and write
/// (`object.tag.add`). Names may be empty or repeated. At most [`MAX_TAGS`], each name and
/// value at most [`MAX_TAG_TEXT`] bytes.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<ObjectTag>,
}
/// The most tags one object has.
pub const MAX_TAGS: usize = 64;
/// The longest name or value a tag has, in bytes.
pub const MAX_TAG_TEXT: usize = 64 * 1024;
/// A tag on an object: a name and a value, with an id that tells it apart from the object's other
/// tags while its name and value change.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ObjectTag {
/// Distinct among the object's tags: a new tag takes an id from
/// [`crate::Document::alloc_tag_id`], and deleting a tag raises the next node id above its id,
/// so a deleted tag's id is not given out again.
#[serde(default, deserialize_with = "lenient_tag_id")]
pub id: u64,
#[serde(default)]
pub name: String,
#[serde(default)]
pub value: String,
}
/// Reading a native file never fails over a tag id that is not a whole number from 0 to
/// `u64::MAX` (a negative one, a fraction, text): it reads as 0, and
/// [`crate::Document::tidy_tags`] gives the tag a new id.
fn lenient_tag_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
Ok(serde_json::Value::deserialize(d)?.as_u64().unwrap_or(0))
}
impl ObjectAttributes {
/// Keeps the tags within the limits: the first [`MAX_TAGS`] whose name and value are at most
/// [`MAX_TAG_TEXT`] bytes. → whether any was dropped.
pub fn tidy_tags(&mut self) -> bool {
let before = self.tags.len();
self.tags.retain(|t| t.name.len() <= MAX_TAG_TEXT && t.value.len() <= MAX_TAG_TEXT);
self.tags.truncate(MAX_TAGS);
self.tags.len() != before
}
}
impl crate::Document {
/// Keeps every object's tags within the limits ([`ObjectAttributes::tidy_tags`]) in the art of
/// the layers, symbols, graph designs and pattern swatches (opacity-mask art included). A tag
/// keeps its id when the id is from 1 to below [`crate::limits::MAX_NEXT_ID`] and no earlier
/// tag of the object has it. Every other tag gets a new id: from the next node id on, above
/// every kept id, when those ids stay below that limit; otherwise the smallest id the object's
/// other tags do not have. The next node id is then raised past every tag id below the limit.
/// It recurses through the art: call it on a document no deeper than
/// [`crate::depth::MAX_DEPTH`].
pub fn tidy_tags(&mut self) {
fn keeps(t: &ObjectTag, earlier: &[ObjectTag]) -> bool {
(1..crate::limits::MAX_NEXT_ID).contains(&t.id) && !earlier.iter().any(|o| o.id == t.id)
}
// The limits, the largest kept id and the number of new ids first, so that a new id never
// meets a kept one.
let mut next = self.peek_next_id();
let mut fresh = 0u64;
self.each_tagged(&mut |a| {
a.tidy_tags();
for (i, t) in a.tags.iter().enumerate() {
if keeps(t, &a.tags[..i]) {
next = next.max(t.id.saturating_add(1));
} else {
fresh = fresh.saturating_add(1);
}
}
});
if fresh == 0 {
self.raise_next_id(next);
return;
}
let in_range = next.saturating_add(fresh) <= crate::limits::MAX_NEXT_ID;
self.each_tagged(&mut |a| {
let kept: Vec<bool> = (0..a.tags.len()).map(|i| keeps(&a.tags[i], &a.tags[..i])).collect();
let mut used: Vec<u64> = a.tags.iter().zip(&kept).filter(|(_, k)| **k).map(|(t, _)| t.id).collect();
for (i, k) in kept.iter().enumerate() {
if *k {
continue;
}
let id = if in_range {
next = next.saturating_add(1);
next - 1
} else {
(1..).find(|c| !used.contains(c)).unwrap_or(1)
};
a.tags[i].id = id;
used.push(id);
}
});
self.raise_next_id(next);
}
/// A new tag id for object `id`, which none of its tags has: the next node id. `None` once the
/// next node id has reached [`crate::limits::MAX_NEXT_ID`] (a file with ids at the top of the
/// range), since an id from there would be outside the range [`Self::tidy_tags`] keeps and an
/// id below it could be a deleted tag's.
pub fn alloc_tag_id(&mut self, id: crate::NodeId) -> Option<u64> {
let used: Vec<u64> =
self.node(id).map(|n| n.extras().attrs.as_deref().map_or(Vec::new(), |a| a.tags.iter().map(|t| t.id).collect())).unwrap_or_default();
for _ in 0..=used.len() {
if self.peek_next_id() >= crate::limits::MAX_NEXT_ID {
return None;
}
let tag = self.alloc_id().0;
if !used.contains(&tag) {
return Some(tag);
}
}
None
}
/// Calls `f` with the attributes of every object with tags in the art [`Self::tidy_tags`] reads.
fn each_tagged(&mut self, f: &mut impl FnMut(&mut ObjectAttributes)) {
let mut fix = |n: &mut Node| {
if n.extras().attrs.as_deref().is_some_and(|a| !a.tags.is_empty()) {
n.edit_attrs(&mut *f);
}
};
let roots = self
.layers
.iter_mut()
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
for root in roots {
crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix);
}
}
}
/// An attribute in another application's XML namespace: `plotter:pen="2"` with `xmlns:plotter=
+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]
+30 -2
View File
@@ -5,9 +5,10 @@
//! stay attached and deleted objects leave nothing stale behind.
use serde::{Deserialize, Serialize};
use vectorcraft_geom::{Homography, Rect};
use vectorcraft_geom::{Homography, Point, Rect};
use crate::{Node, NodeKind};
use crate::symbols::SYMBOL_SQUARE;
use crate::{Node, NodeKind, SymbolBoxes};
/// The plane an object in perspective lies on.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
@@ -58,6 +59,33 @@ impl Node {
}
}
/// The corners of the box a symbol instance or type is drawn in, on the page (top left, top
/// right, bottom right, bottom left): an instance's art box (measured from `symbols`, or
/// `SYMBOL_SQUARE` when it has none) placed by its transform, and type's flat bounds, both
/// through the projection of type or an instance in perspective. Joined by straight lines,
/// they outline the box as drawn. When the projection sends a corner to infinity the corners
/// stay flat, as the flat box is kept for [`Node::geometric_bounds_with`]. `None` for other
/// objects and for type without bounds.
pub fn drawn_corners(&self, symbols: &SymbolBoxes) -> Option<[Point; 4]> {
let flat = match &self.kind {
NodeKind::SymbolInstance { symbol, xf } => {
let art = symbols.art(symbol).map_or(SYMBOL_SQUARE, |a| a.geometric);
[(art.x0, art.y0), (art.x1, art.y0), (art.x1, art.y1), (art.x0, art.y1)].map(|(x, y)| *xf * Point::new(x, y))
}
NodeKind::Text(t) => {
let b = t.bounds()?;
[(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| Point::new(x, y))
}
_ => return None,
};
let Some(h) = self.projection() else { return Some(flat) };
let [a, b, c, d] = flat.map(|p| h.apply(p));
Some(match (a, b, c, d) {
(Some(a), Some(b), Some(c), Some(d)) => [a, b, c, d],
_ => flat,
})
}
/// Keep a projection drawing the same picture moved by `a` (the flat art moves by `a` too). An
/// invertible `a` that the projection cannot follow removes it, and the art is drawn flat.
pub(crate) fn transform_projection(&mut self, a: vectorcraft_geom::Affine) {
+50 -4
View File
@@ -17,15 +17,16 @@
//! other stop there, showing their previews).
use std::borrow::Cow;
use std::cell::Cell;
use std::collections::BTreeSet;
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
use serde::{Deserialize, Serialize};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_geom::{Affine, PathData, Rect, SubPath};
use vectorcraft_color::Paint;
use vectorcraft_color::{Color, Paint};
use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol};
use crate::{Appearance, AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol};
/// A placed document: an artboard of another VectorCraft file, a page of a PDF or `.ai` file, or
/// an EPS file's art, shown as one locked object.
@@ -123,12 +124,27 @@ impl PlacedDocument {
}
/// The art the object shows, as plain objects with `n`'s id: one group, its resources named
/// as [`Document::with_placed_art`] adds them (nothing until that has read it).
/// as [`Document::with_placed_art`] adds them (nothing until that has read it). While
/// [`Crossed`] is on for this thread, its box crossed from corner to corner instead
/// ([`Self::crossed_art`]).
pub fn art(&self, n: &Node) -> Vec<Node> {
if crossed() {
return vec![self.crossed_art(n)];
}
let prefix = prefix(&self.key);
read_cached(self).and_then(|e| self.art_node(n, &e, &prefix)).into_iter().collect()
}
/// The object's box crossed from corner to corner, as one group with `n`'s id: a path of the
/// box's outline and its two diagonals with a black 1 pt stroke. Outline mode without Document
/// Setup → Show Images in Outline Mode shows the object so, and its effects reshape this art.
pub fn crossed_art(&self, n: &Node) -> Node {
let q = self.corners();
let path = PathData::new(vec![SubPath::polyline(&q, true), SubPath::polyline(&[q[0], q[2]], false), SubPath::polyline(&[q[1], q[3]], false)]);
let stroke = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
Node::group(n.id, vec![Arc::new(Node::path(art_id(), path, stroke))])
}
/// Read `e`'s art placed as this object `n` shows it (`n`'s id), its resources renamed with
/// `prefix`.
fn art_node(&self, n: &Node, e: &ReadDocument, prefix: &str) -> Option<Node> {
@@ -470,6 +486,36 @@ fn read_preview(p: &PlacedDocument, bytes: &Arc<Vec<u8>>) -> Option<Arc<ReadDocu
Some(e)
}
thread_local! {
/// Whether [`PlacedDocument::art`] gives the crossed box on this thread ([`Crossed`]).
static CROSSED: Cell<bool> = const { Cell::new(false) };
}
/// While alive, [`PlacedDocument::art`] on this thread gives each placed document's box crossed
/// from corner to corner ([`PlacedDocument::crossed_art`]) when it was made with `true`, and the
/// file's art when made with `false`; once dropped, the setting before it applies again. A
/// renderer holds one while it draws or measures Outline mode without Document Setup → Show Images
/// in Outline Mode, so that effects and live objects make their art from the crossed box.
#[must_use]
pub struct Crossed(bool);
impl Crossed {
pub fn set(on: bool) -> Self {
Self(CROSSED.with(|c| c.replace(on)))
}
}
impl Drop for Crossed {
fn drop(&mut self) {
CROSSED.with(|c| c.set(self.0));
}
}
/// Whether [`PlacedDocument::art`] gives the crossed box on this thread ([`Crossed`]).
pub fn crossed() -> bool {
CROSSED.with(Cell::get)
}
/// `p`'s file as read already (else its preview's), without reading it.
pub fn read_cached(p: &PlacedDocument) -> Option<Arc<ReadDocument>> {
let mut c = cache();
+5 -2
View File
@@ -291,9 +291,12 @@ impl StrokeLayer {
// past them are measured.
match self.body_along(&segs, side, out) {
Some(body) => out = out.union(body),
// A subpath with no length paints at most its caps' dot.
// A subpath with no length paints at most its caps' dot. A closed subpath with
// no segment, a lone anchor, has its dot at that anchor under a round or
// projecting cap.
None if !butt => {
let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b));
let lone = (self.cap != LineCap::Butt).then(|| els[r.start].end_point()).flatten().map(|p| Rect::from_points(p, p));
let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)).or(lone);
out = dot.map_or(out, |d| out.union(d.inflate(side, side)));
}
None => {}
+136
View File
@@ -435,6 +435,142 @@ fn art_on_artboard_tolerates_roundoff_at_each_edge() {
}
}
#[test]
fn art_for_artboard_copy_takes_artwork_larger_than_artboard_or_with_bleed() {
let mut d = Document::new(200.0, 200.0);
d.setup.bleed = [9.0; 4];
let layer = d.layers[0].id;
// An oversized background (250x250 centered on the 200x200 artboard, #4479).
let bg = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::path(bg, shapes::rectangle(Rect::new(-25.0, -25.0, 225.0, 225.0)), Appearance::default_art())).unwrap();
// A shape with 5pt bleed over the top-right corner.
let bleed = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::path(bleed, shapes::rectangle(Rect::new(150.0, -5.0, 205.0, 50.0)), Appearance::default_art())).unwrap();
// A shape lying entirely in the bleed margin without touching the artboard itself (-8..-2 vs 0..200).
let bleed_margin_only = d.alloc_id();
d.insert(
Some(layer),
usize::MAX,
Node::path(bleed_margin_only, shapes::rectangle(Rect::new(-8.0, 50.0, -2.0, 100.0)), Appearance::default_art()),
)
.unwrap();
// A small shape hanging 20pt over the left edge (center outside, more than bleed).
let hanging = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::path(hanging, shapes::rectangle(Rect::new(-20.0, 90.0, 10.0, 120.0)), Appearance::default_art()))
.unwrap();
// A straight line hanging 60pt over the left edge (center outside, no area): it lies on the
// artboard for 40pt, so it is copied as a thin rectangle there would be.
let line = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::path(line, shapes::line(Point::new(-60.0, 150.0), Point::new(40.0, 150.0)), Appearance::default_art()))
.unwrap();
// A shape completely outside the artboard.
let outside = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::path(outside, shapes::rectangle(Rect::new(300.0, 300.0, 400.0, 400.0)), Appearance::default_art()))
.unwrap();
// Standard art_on_artboard keeps strict containment: none of the overhanging shapes are on it.
let strict_art = d.art_on_artboard(Rect::new(0.0, 0.0, 200.0, 200.0), false);
assert!(!strict_art.contains(&bg), "strict art_on_artboard excludes oversized background");
assert!(!strict_art.contains(&bleed), "strict art_on_artboard excludes bleed shape");
assert!(!strict_art.contains(&bleed_margin_only), "strict art_on_artboard excludes bleed-margin-only shape");
assert!(!strict_art.contains(&hanging), "strict art_on_artboard excludes hanging shape");
assert!(!strict_art.contains(&outside), "strict art_on_artboard excludes outside shape");
// Copying the artboard takes the artwork touching this artboard that belongs to it, or within bleed.
let copy_art = d.art_for_artboard_copy(0, false);
assert!(copy_art.contains(&bg), "oversized background is copied with artboard: {copy_art:?}");
assert!(copy_art.contains(&bleed), "bleed shape is copied with artboard: {copy_art:?}");
assert!(copy_art.contains(&bleed_margin_only), "bleed-margin-only shape is copied with artboard: {copy_art:?}");
assert!(copy_art.contains(&hanging), "touching shape owned by artboard 0 is copied: {copy_art:?}");
assert!(copy_art.contains(&line), "a line hanging over the edge is copied: {copy_art:?}");
assert!(!copy_art.contains(&outside), "outside shape is not copied: {copy_art:?}");
// If Artboard 1 is added next to Artboard 0, art primarily on Artboard 1 is not copied with Artboard 0:
d.artboards.push(Artboard {
id: 2,
name: "Artboard 2".into(),
rect: Rect::new(200.0, 0.0, 400.0, 200.0),
locked: false,
show_center_mark: false,
show_cross_hairs: false,
show_video_safe_areas: false,
video_ruler_pixel_aspect_ratio: 1.0,
color: None,
guide_label: None,
});
// Shape spanning (190..300) x (50..150): 10pt on Artboard 0, 100pt on Artboard 1.
let neighbor_art = d.alloc_id();
d.insert(Some(layer), usize::MAX, Node::path(neighbor_art, shapes::rectangle(Rect::new(190.0, 50.0, 300.0, 150.0)), Appearance::default_art()))
.unwrap();
let copy_art0 = d.art_for_artboard_copy(0, false);
assert!(!copy_art0.contains(&neighbor_art), "art owned by neighboring Artboard 1 is not copied with Artboard 0");
let copy_art1 = d.art_for_artboard_copy(1, false);
assert!(copy_art1.contains(&neighbor_art), "art owned by Artboard 1 is copied with Artboard 1");
}
#[test]
fn artboard_for_bounds_edge_cases_and_tie_breaks() {
let mut d = Document::new(100.0, 100.0);
// Artboard 0: (0, 0, 100, 100)
// Artboard 1: (200, 0, 300, 100)
d.artboards.push(Artboard {
id: 2,
name: "Artboard 2".into(),
rect: Rect::new(200.0, 0.0, 300.0, 100.0),
locked: false,
show_center_mark: false,
show_cross_hairs: false,
show_video_safe_areas: false,
video_ruler_pixel_aspect_ratio: 1.0,
color: None,
guide_label: None,
});
// 1. Artwork whose center is outside all boards, but overlaps Artboard 0 most:
// Bounds: (50, -100, 150, 50) -> Center: (100, -25) which is outside all artboards.
// Overlap with Board 0: 50x50 = 2500; Board 1: 0.
let b_center_outside = Rect::new(50.0, -100.0, 150.0, 50.0);
assert_eq!(d.artboard_for_bounds(b_center_outside), Some(0));
// 2. Equal overlap on two boards (defined tie-break: the lower index, board 0):
// Bounds: (50, -50, 250, 50) -> Center: (150, 0) outside all boards.
// Overlap with Board 0: (50..100) x (0..50) = 2500; Board 1: (200..250) x (0..50) = 2500.
let b_equal_overlap = Rect::new(50.0, -50.0, 250.0, 50.0);
assert_eq!(d.artboard_for_bounds(b_equal_overlap), Some(0), "equal overlap picks lower index");
// 3. No overlap at all: returns None.
let b_no_overlap = Rect::new(500.0, 500.0, 600.0, 600.0);
assert_eq!(d.artboard_for_bounds(b_no_overlap), None);
// 4. Rotated object bounds (bounds, not the inner geometry):
// A 40x40 square rotated 45 deg centered at (50, 50) has bounding box ~56.57x56.57.
let b_rotated_bounds = Rect::new(50.0 - 28.28, 50.0 - 28.28, 50.0 + 28.28, 50.0 + 28.28);
assert_eq!(d.artboard_for_bounds(b_rotated_bounds), Some(0));
// 5. Zero-size bounds (a point):
// On board 0:
let b_zero_on_board = Rect::new(50.0, 50.0, 50.0, 50.0);
assert_eq!(d.artboard_for_bounds(b_zero_on_board), Some(0));
// Outside all boards:
let b_zero_outside = Rect::new(150.0, 50.0, 150.0, 50.0);
assert_eq!(d.artboard_for_bounds(b_zero_outside), None);
// 6. Straight lines whose center is outside every board: owned by the board they lie on most,
// as a rectangle of any thickness would be (they have no area to compare).
// Horizontal, from x = -100 to 50 on board 0: center (-25, 50).
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.0)), Some(0));
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.1)), Some(0), "the same as a thin rectangle");
// Vertical, from y = -100 to 50 on board 1: center (250, -25).
assert_eq!(d.artboard_for_bounds(Rect::new(250.0, -100.0, 250.0, 50.0)), Some(1));
// Below both boards.
assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 120.0, 260.0, 120.0)), None);
// Across the gap between the boards, 20 pt on board 0 and 60 on board 1.
assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 50.0, 260.0, 50.0)), Some(1), "center (170, 50) in the gap: board 1 holds more of it");
// Only touching a board's corner from outside: no overlap.
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 0.0, 0.0, 0.0)), None);
}
/// The art on a locked artboard (each object of a layer whose bounds overlap it, a group as one
/// object) can't be edited, and Select All, a click and a marquee pass over it; art flush with
/// the artboard from outside isn't on it, a layer is on no artboard, and new art isn't on one.
+12
View File
@@ -291,3 +291,15 @@ fn q_and_ha_suffixes_do_not_take_other_units_suffixes() {
// A suffix after math covers the whole expression, as for the other units.
assert!((Unit::Points.parse("26/2 q").unwrap() - Unit::Q.to_pt(13.0)).abs() < 1e-9);
}
#[test]
fn format_area_formats_and_trims_cleanly() {
assert_eq!(Unit::Points.format_area(100.0), "100 pt²");
assert_eq!(Unit::Inches.format_area(4.5 * 72.0 * 72.0), "4.5 in²");
let mm_side = Unit::Millimeters.to_pt(1.0);
assert_eq!(Unit::Millimeters.format_area(12.5 * mm_side * mm_side), "12.5 mm²");
assert_eq!(Unit::Points.format_area(0.0), "0 pt²");
assert_eq!(Unit::Points.format_area(-10.0), "0 pt²");
assert_eq!(Unit::Points.format_area(f64::NAN), "0 pt²");
assert_eq!(Unit::Points.format_area(f64::INFINITY), "0 pt²");
}
+4
View File
@@ -7,6 +7,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Vec2};
use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer};
mod area;
mod attr_ranges;
mod char_style;
mod composite;
mod file_fonts;
@@ -18,6 +19,9 @@ mod tabs_lists;
mod wrap;
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
pub use attr_ranges::{
AttrRangeError, CHAR_MITER_LIMIT, CHAR_ROTATION, CHAR_SCALE, CHAR_SPACING, FONT_SIZE, LEADING, MAX_BASELINE_SHIFT, MAX_PARA_DISTANCE,
};
use char_style::yes;
pub use char_style::{
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_DIACRITIC_POSITION, MAX_TSUME,
+215
View File
@@ -0,0 +1,215 @@
//! The ranges the character and paragraph style commands keep each numeric attribute to, checked
//! in one place: the style commands check the attributes a call changes, and type a plug-in
//! returns has every attribute checked.
use std::fmt;
use std::ops::RangeInclusive;
use super::{CharStyle, JustificationOptions, ParaStyle, TabStop};
/// Font size ([`CharStyle::size`]), in points.
pub const FONT_SIZE: RangeInclusive<f64> = 0.1..=1296.0;
/// Leading ([`CharStyle::leading`]) other than Auto, in points.
pub const LEADING: RangeInclusive<f64> = 0.1..=5000.0;
/// Horizontal and vertical scale ([`CharStyle::h_scale`], [`CharStyle::v_scale`]), in percent.
pub const CHAR_SCALE: RangeInclusive<f64> = 1.0..=10000.0;
/// Tracking, kerning and the space before a line's first character ([`CharStyle::tracking`],
/// [`CharStyle::kerning`], [`CharStyle::kerning_before`]), in 1/1000 em.
pub const CHAR_SPACING: RangeInclusive<f64> = -1000.0..=10000.0;
/// The largest baseline shift and Tate-chu-yoko Up/Down and Left/Right either way, in points.
pub const MAX_BASELINE_SHIFT: f64 = 1296.0;
/// Character rotation ([`CharStyle::rotation`]), in degrees.
pub const CHAR_ROTATION: RangeInclusive<f64> = -360.0..=360.0;
/// The miter limit of a character stroke ([`CharStyle::stroke_miter_limit`]).
pub const CHAR_MITER_LIMIT: RangeInclusive<f64> = 1.0..=500.0;
/// The largest paragraph indent, space before or after and Hyphenation Zone either way, in points.
pub const MAX_PARA_DISTANCE: f64 = 1296.0;
/// An attribute outside the range the style commands keep it to.
#[derive(Clone, Debug, PartialEq)]
pub struct AttrRangeError {
/// The attribute's JSON name, a nested field after a dot (`hyphenation.zone`).
pub key: String,
/// What is wrong, naming the attribute.
pub message: String,
}
impl fmt::Display for AttrRangeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for AttrRangeError {}
fn out(key: &str, message: String) -> AttrRangeError {
AttrRangeError { key: key.to_string(), message }
}
/// `value` within `lo..=hi`, or the error naming `key` (a value that is not a number is outside).
fn within(key: &str, value: f64, lo: f64, hi: f64) -> Result<(), AttrRangeError> {
if (lo..=hi).contains(&value) { Ok(()) } else { Err(out(key, format!("`{key}` must be from {lo} to {hi}"))) }
}
impl CharStyle {
/// Checks each numeric attribute `check` names, by its JSON key, against the range the
/// character style commands keep it to: size, leading, scales, tracking, kerning, baseline
/// shift, rotation, the character stroke's weight, miter limit and dashes, Small Caps, Insert
/// Aki, Tsume, diacritic positions, the Tate-chu-yoko offsets, the Warichu settings and the
/// variable font axes. The first attribute out of its range is the error.
pub fn check_ranges(&self, check: impl Fn(&str) -> bool) -> Result<(), AttrRangeError> {
for (key, value, range) in [("size", self.size, FONT_SIZE), ("h_scale", self.h_scale, CHAR_SCALE), ("v_scale", self.v_scale, CHAR_SCALE)] {
if check(key) {
within(key, value, *range.start(), *range.end())?;
}
}
if check("leading") && self.leading.is_some_and(|value| !LEADING.contains(&value)) {
let (lo, hi) = (LEADING.start(), LEADING.end());
return Err(out("leading", format!("`leading` must be from {lo} to {hi}, or null for Auto")));
}
let shift = MAX_BASELINE_SHIFT;
for (key, value) in [("baseline_shift", self.baseline_shift), ("tcyUpDown", self.tcy_up_down), ("tcyLeftRight", self.tcy_left_right)] {
if check(key) {
within(key, value, -shift, shift)?;
}
}
let spacing = [("tracking", Some(self.tracking)), ("kerning", self.kerning), ("kerningBefore", Some(self.kerning_before))];
for (key, value) in spacing {
if check(key)
&& let Some(value) = value
{
within(key, value, *CHAR_SPACING.start(), *CHAR_SPACING.end())?;
}
}
if check("rotation") {
within("rotation", self.rotation, *CHAR_ROTATION.start(), *CHAR_ROTATION.end())?;
}
for (key, value) in [("akiLeft", self.aki_left), ("akiRight", self.aki_right)] {
if check(key) {
within(key, value, 0.0, super::MAX_AKI)?;
}
}
if check("tsume") {
within("tsume", self.tsume, 0.0, super::MAX_TSUME)?;
}
let hi = super::MAX_DIACRITIC_POSITION;
for (key, value) in [("diacriticHorizontal", self.diacritic_horizontal), ("diacriticVertical", self.diacritic_vertical)] {
if check(key) {
within(key, value, -hi, hi)?;
}
}
let lines = super::WARICHU_LINES;
if check("warichuLines") && !lines.contains(&self.warichu_lines) {
return Err(out("warichuLines", format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
}
let scale = super::WARICHU_SCALE;
for (key, value, lo, hi) in
[("warichuGap", self.warichu_gap, 0.0, super::MAX_WARICHU_GAP), ("warichuScale", self.warichu_scale, *scale.start(), *scale.end())]
{
if check(key) {
within(key, value, lo, hi)?;
}
}
if check("stroke_width") {
within("stroke_width", self.stroke_width, 0.0, crate::MAX_COORD)?;
}
if check("stroke_miter_limit") {
within("stroke_miter_limit", self.stroke_miter_limit, *CHAR_MITER_LIMIT.start(), *CHAR_MITER_LIMIT.end())?;
}
if check("stroke_dash")
&& let Some(dash) = &self.stroke_dash
{
for value in &dash.pattern {
within("stroke_dash.pattern", *value, 0.0, crate::MAX_COORD)?;
}
within("stroke_dash.offset", dash.offset, -crate::MAX_COORD, crate::MAX_COORD)?;
}
if check("small_caps")
&& let Some(value) = self.small_caps
{
within("small_caps", value, 1.0, crate::setup::MAX_SMALL_CAPS)?;
}
if check("fontAxes")
&& let Some((tag, _)) = self.font_axes.iter().find(|(_, v)| !v.is_finite())
{
return Err(out("fontAxes", format!("`fontAxes`: the setting of axis `{tag}` must be a number")));
}
Ok(())
}
}
impl ParaStyle {
/// Checks each paragraph attribute `check` names, by its JSON key and for a nested option its
/// field, against the range the paragraph style commands keep it to: the indents and the space
/// before and after, each Hyphenation option, each Justification option in `justification`
/// (the options as given, since reading a paragraph style brings them into range) with
/// Minimum, Desired and Maximum in order, and the number of tab stops with the position and
/// leader of each stop that is not in `kept_tabs`. The first attribute out of its range is the
/// error.
pub fn check_ranges(
&self,
justification: Option<&JustificationOptions>,
kept_tabs: &[TabStop],
check: impl Fn(&str, Option<&str>) -> bool,
) -> Result<(), AttrRangeError> {
for (key, value) in [
("left_indent", self.left_indent),
("right_indent", self.right_indent),
("first_line_indent", self.first_line_indent),
("space_before", self.space_before),
("space_after", self.space_after),
] {
if check(key, None) {
within(key, value, -MAX_PARA_DISTANCE, MAX_PARA_DISTANCE)?;
}
}
let h = &self.hyphenation;
for (field, value, lo, hi) in [
("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0),
("after_first", f64::from(h.after_first), 1.0, 15.0),
("before_last", f64::from(h.before_last), 1.0, 15.0),
("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0),
("zone", h.zone, 0.0, MAX_PARA_DISTANCE),
] {
if check("hyphenation", Some(field)) {
within(&format!("hyphenation.{field}"), value, lo, hi)?;
}
}
if let Some(j) = justification {
for (field, values, (lo, hi)) in [
("word_spacing", j.word_spacing, JustificationOptions::WORD_SPACING),
("letter_spacing", j.letter_spacing, JustificationOptions::LETTER_SPACING),
("glyph_scaling", j.glyph_scaling, JustificationOptions::GLYPH_SCALING),
] {
if !check("justification", Some(field)) {
continue;
}
let name = format!("justification.{field}");
for value in values {
within(&name, value, lo, hi)?;
}
if !(values[0] <= values[1] && values[1] <= values[2]) {
return Err(out(&name, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")));
}
}
if check("justification", Some("auto_leading")) {
let (lo, hi) = JustificationOptions::AUTO_LEADING;
within("justification.auto_leading", j.auto_leading, lo, hi)?;
}
}
if check("tabs", None) {
let max = TabStop::MAX_STOPS;
if self.tabs.len() > max.max(kept_tabs.len()) {
return Err(out("tabs", format!("at most {max} tab stops")));
}
for stop in self.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
if stop.leader.chars().count() > max {
return Err(out("tabs.leader", format!("{label} must be at most {max} characters")));
}
}
}
Ok(())
}
}
+39
View File
@@ -802,6 +802,45 @@ fn auto_alignment_saves_readable_by_older_builds() {
assert_eq!(serde_json::from_str::<ParaStyle>(r#"{"justify":"Center"}"#).unwrap().justify, Justify::Center);
}
/// The default character and paragraph styles are in range, and each number outside its range,
/// one that is not a number included, is the error naming its attribute; an attribute the check
/// is not asked about is not checked.
#[test]
fn style_ranges_name_the_attribute_out_of_range() {
let all = |_: &str| true;
assert_eq!(CharStyle::default().check_ranges(all), Ok(()));
let key = |s: CharStyle| s.check_ranges(all).map_err(|e| e.key);
let d = CharStyle::default();
assert_eq!(key(CharStyle { baseline_shift: f64::NAN, ..d.clone() }), Err("baseline_shift".into()));
assert_eq!(key(CharStyle { leading: Some(1e9), ..d.clone() }), Err("leading".into()));
assert_eq!(key(CharStyle { v_scale: 0.0, ..d.clone() }), Err("v_scale".into()));
assert_eq!(key(CharStyle { kerning: Some(f64::INFINITY), ..d.clone() }), Err("kerning".into()));
assert_eq!(key(CharStyle { rotation: 720.0, ..d.clone() }), Err("rotation".into()));
assert_eq!(key(CharStyle { warichu_lines: 9, ..d.clone() }), Err("warichuLines".into()));
assert_eq!(key(CharStyle { stroke_miter_limit: 0.0, ..d.clone() }), Err("stroke_miter_limit".into()));
assert_eq!(key(CharStyle { small_caps: Some(0.0), ..d.clone() }), Err("small_caps".into()));
let axes = std::iter::once(("wght".to_string(), f64::NAN)).collect();
assert_eq!(key(CharStyle { font_axes: axes, ..d.clone() }), Err("fontAxes".into()));
let dash = Some(Dash { pattern: vec![2.0, -1.0], offset: 0.0, align_corners: false });
assert_eq!(key(CharStyle { stroke_dash: dash, ..d.clone() }), Err("stroke_dash.pattern".into()));
assert_eq!(CharStyle { size: 0.0, ..d.clone() }.check_ranges(|k| k != "size"), Ok(()));
let all = |_: &str, _: Option<&str>| true;
let p = ParaStyle::default();
assert_eq!(p.check_ranges(Some(&JustificationOptions::default()), &[], all), Ok(()));
let key = |s: ParaStyle, j: Option<&JustificationOptions>| s.check_ranges(j, &[], all).map_err(|e| e.key);
assert_eq!(key(ParaStyle { first_line_indent: f64::NAN, ..p.clone() }, None), Err("first_line_indent".into()));
let stop = TabStop { position: 1.0, align: TabAlign::Left, leader: String::new(), align_on: '.' };
assert_eq!(key(ParaStyle { tabs: vec![stop.clone(); TabStop::MAX_STOPS + 1], ..p.clone() }, None), Err("tabs".into()));
let far = TabStop { position: -1.0, ..stop.clone() };
assert_eq!(key(ParaStyle { tabs: vec![far.clone()], ..p.clone() }, None), Err("tabs.position".into()));
assert_eq!(ParaStyle { tabs: vec![far.clone()], ..p.clone() }.check_ranges(None, &[far], all), Ok(()), "a kept stop");
let hyphenation = HyphenationOptions { hyphen_limit: 99, ..HyphenationOptions::default() };
assert_eq!(key(ParaStyle { hyphenation, ..p.clone() }, None), Err("hyphenation.hyphen_limit".into()));
let reversed = JustificationOptions { word_spacing: [133.0, 100.0, 80.0], ..JustificationOptions::default() };
assert_eq!(key(p.clone(), Some(&reversed)), Err("justification.word_spacing".into()));
}
#[test]
fn file_fonts_draw_type_only_while_its_text_is_the_files() {
use super::file_fonts::*;
+35
View File
@@ -166,6 +166,19 @@ impl Unit {
pub fn format(self, pt: f64) -> String {
format!("{} {}", self.number(pt), self.suffix())
}
/// Format an area in square points into this unit (e.g. `12.5 mm²`, `4.5 in²`, `100 pt²`).
pub fn format_area(self, pt2: f64) -> String {
if !pt2.is_finite() || pt2 <= 0.0 {
return format!("0 {}²", self.suffix());
}
let side = self.from_pt(1.0);
let val = pt2 * side * side;
let decimals = if matches!(self, Unit::Points | Unit::Pixels | Unit::Picas | Unit::Q | Unit::Ha) { 3 } else { 4 };
let s = format!("{:.*}", decimals, val);
let s = s.trim_end_matches('0').trim_end_matches('.');
let s = if s == "-0" || s.is_empty() { "0" } else { s };
format!("{s} {}²", self.suffix())
}
/// [`Unit::format`] without the suffix (`12.5`), for narrow fields.
pub fn number(self, pt: f64) -> String {
// Three decimals for the small units (`595.276 pt`), four for the large ones (`8.2677 in`,
@@ -196,6 +209,15 @@ impl Unit {
}
parse_measure(&times_as_asterisks(s), self).filter(|v| v.is_finite())
}
/// Parse a measurement with decimal points or commas and no input locale. Refuse a
/// number that looks like a grouped integer, even when it is part of an expression.
pub fn parse_with_decimal_comma(self, text: &str) -> Option<f64> {
if text.contains(',') && times_as_asterisks(text).split(['+', '-', '*', '/']).any(thousands_operand) {
return None;
}
self.parse(&decimal_point(text))
}
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
/// `feetInches`).
pub const fn key(self) -> &'static str {
@@ -397,6 +419,19 @@ pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> {
if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() }
}
/// Does the operand contain a thousands comma? Check both parts of a compact pica value and
/// read a percentage's number without its percent sign.
fn thousands_operand(operand: &str) -> bool {
let operand = operand.trim();
if let Some((picas, points)) = operand.split_once('p')
&& !points.trim().is_empty()
&& points.trim().bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b','))
{
return thousands(picas) || thousands(points);
}
thousands(operand.strip_suffix('%').unwrap_or(operand))
}
/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or
/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at
/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it
+6 -1
View File
@@ -619,7 +619,12 @@ fn moved_type(n: &Node, moves: &[serde_json::Value]) -> Option<Vec<Node>> {
}
let (_, all) = glyph_outlines(t);
let outline = PathData::from_bezpath(&all).transformed(t.xf);
let ink = outline.bounds()?;
// A contour of one anchor paints only as the dot of a round or projecting character stroke cap.
let dots = t
.runs
.iter()
.any(|r| r.style.appearance().painted_strokes().any(|s| matches!(s.cap, vectorcraft_doc::LineCap::Round | vectorcraft_doc::LineCap::Square)));
let ink = outline.drawn_bounds(dots)?;
let offsets = transform_offsets(moves, &outline)?;
if offsets.len() > MAX_TYPE_COPIES {
return None;
+9 -3
View File
@@ -326,21 +326,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})),
@@ -875,6 +875,12 @@ pub(crate) fn catalog_index() -> &'static std::collections::HashMap<&'static str
INDEX.get_or_init(|| effect_catalog().into_iter().map(|e| (e.id, e)).collect())
}
/// The id and menu label of built-in effect `id`, as the catalog holds them (no plug-in
/// effects).
pub fn built_in_effect(id: &str) -> Option<(&'static str, &'static str)> {
catalog_index().get(id).map(|e| (e.id, e.label))
}
/// Catalogue entry for `id` (built-in, or an installed plug-in effect).
pub fn effect_info(id: &str) -> Option<EffectInfo> {
catalog_index().get(id).cloned().or_else(|| plugin_info(id))
+8
View File
@@ -447,6 +447,12 @@ pub(crate) fn apply_one(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &Geo
budget.fits(Budget::of(&out)).then_some(out)
}
#[cfg(test)]
thread_local! {
/// The subpaths the Offset Path effect has offset on this thread.
pub(crate) static OFFSET_SUBPATHS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Does geometry effect `id` build within the anchors it is given?
fn builds_within(id: &str) -> bool {
matches!(id, "distort.freeDistort" | "distort.roughen" | "distort.transform" | "distort.twist" | "distort.zigZag") || id.starts_with("warp.")
@@ -472,6 +478,8 @@ fn apply_unchecked(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomCont
if off.abs() < 1e-9 {
return path.clone();
}
#[cfg(test)]
OFFSET_SUBPATHS.with(|n| n.set(n.get() + path.subpaths.len()));
vectorcraft_pathops::offset_path(path, off, join(p, "joins"), num(p, "miterLimit", 4.0).clamp(1.0, 500.0))
}
// Outline Object returns the geometry unchanged. Type reaches every geometry effect as its
+6 -3
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,
+22
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) {
+6 -6
View File
@@ -1117,10 +1117,10 @@ fn transform_copies_before_offset_path_evaluates_without_ram_spike() {
fx("path.offsetPath", json!({"offset": 10.0, "joins": "round"})),
];
let path = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
let start = std::time::Instant::now();
crate::geometry::OFFSET_SUBPATHS.with(|n| n.set(0));
let out = apply_geometry(&effects, &path, path.bounds().unwrap());
let elapsed = start.elapsed();
assert!(elapsed < std::time::Duration::from_secs(2), "elapsed: {:?}", elapsed);
// Offset Path offsets the one rectangle, not the 31 overlapping copies.
assert_eq!(crate::geometry::OFFSET_SUBPATHS.with(|n| n.get()), path.subpaths.len());
assert_eq!(out.subpaths.len(), 31);
}
@@ -1135,10 +1135,10 @@ fn reshape_leaves_within_optimizes_transform_before_terminal_offset_path() {
let transform = fx("distort.transform", json!({"moveH": 2.0, "moveV": 2.0, "copies": 10}));
let offset = fx("path.offsetPath", json!({"offset": 4.0, "joins": "round"}));
let start = std::time::Instant::now();
crate::geometry::OFFSET_SUBPATHS.with(|n| n.set(0));
crate::reshape::reshape_leaves_within(&mut art, &[&transform, &offset], Budget::EFFECTS, None);
let elapsed = start.elapsed();
assert!(elapsed < std::time::Duration::from_secs(2));
// Offset Path offsets each leaf's one rectangle, not its 11 copies.
assert_eq!(crate::geometry::OFFSET_SUBPATHS.with(|n| n.get()), 5);
let children = art.children().unwrap();
assert_eq!(children.len(), 5);
+17
View File
@@ -80,11 +80,28 @@ rustix = { workspace = true, features = ["std", "process"] }
# (walkdir), so this adds no new crate.
[target.'cfg(windows)'.dependencies]
same-file = "1.0.6"
# Credential Manager, the system key store of grant_keys.rs on Windows (see keyring-core below).
windows-native-keyring-store = "1.1"
# The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true }
rayon = { version = "1.12", optional = true }
# The MAC that `grants.json` carries (grant_keys.rs) and the random key it is made with, which the
# user's key store keeps: Keychain on macOS, Credential Manager on Windows, the Secret Service on
# Linux. All MIT OR Apache-2.0.
hmac = "0.12.1"
sha2 = { version = "0.10", default-features = false }
getrandom = "0.4"
keyring-core = "1.1"
# The system key store of grant_keys.rs on each platform, connected through keyring-core: the same
# store crates and features that keyring 4.2 uses. All MIT OR Apache-2.0.
[target.'cfg(target_os = "macos")'.dependencies]
apple-native-keyring-store = { version = "1.0.2", features = ["keychain"] }
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))'.dependencies]
zbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-rust"] }
[dev-dependencies]
# JPEG XL files for the `.jxl` open and place tests.
+7 -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;
+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), 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
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fill Area",
[],
None,
"{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, only the paths of the listed objects that are in it), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}",
"{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, the paths of the listed objects that are in it, and all of its paths when a listed layer or group holds it or is it; other listed objects are ignored), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}",
has_doc,
sb_copy_region
),
+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
+59 -18
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
}
@@ -704,7 +722,7 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co
/// from. → a note for each profile, and whether `d` changed.
pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec<String>, bool) {
// Without a choice nothing can fail.
apply_open_policies_choosing(d, None).unwrap_or_default()
apply_open_policies_choosing(d, None, &cms::working_settings()).unwrap_or_default()
}
/// What opening a document can ask about its profile (Edit › Color Settings' Ask When Opening
@@ -879,10 +897,14 @@ impl ProfileQuestion {
/// mismatch choice takes the place of the policy of the document's color mode, and a missing
/// choice tags the document after the policies ran. A choice for the other kind of question, or
/// for a document with none, is not used. → as [`apply_open_policies`]; an error when the profile
/// to assign is not a profile of that model.
pub(crate) fn apply_open_policies_choosing(d: &mut vectorcraft_doc::Document, choice: Option<&ProfileChoice>) -> Result<(Vec<String>, bool)> {
let working = cms::working_settings();
let question = ProfileQuestion::of(d, &working);
/// to assign is not a profile of that model. `working` is the settings snapshot the question is
/// built from and the policies are read from.
pub(crate) fn apply_open_policies_choosing(
d: &mut vectorcraft_doc::Document,
choice: Option<&ProfileChoice>,
working: &ColorSettings,
) -> Result<(Vec<String>, bool)> {
let question = ProfileQuestion::of(d, working);
let choice = choice.filter(|c| question.as_ref().is_some_and(|q| q.issue == c.issue()));
// A mismatch answer stands in for the policy of the document's color mode.
let chosen = |model: ColorMode, policy: Policy| -> (Policy, bool) {
@@ -1596,3 +1618,22 @@ fn set_spot(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(json!({"name": name, "spot": spot}))
}
#[cfg(test)]
mod tests {
use super::*;
/// The policies come from the settings snapshot the question was built from, not from the
/// working settings as they are when the policies run.
#[test]
fn open_policies_use_the_snapshot_they_are_given() {
let tagged = |d: &mut vectorcraft_doc::Document| d.color_profiles.rgb = Some(cms::canonical_name(cms::WIDE_GAMUT_RGB).to_string());
let snapshot = ColorSettings { rgb_policy: Policy::Off, ..ColorSettings::default() };
let mut d = vectorcraft_doc::Document::new(100.0, 100.0);
tagged(&mut d);
let (notes, changed) = apply_open_policies_choosing(&mut d, None, &snapshot).unwrap();
assert!(changed, "the Off policy of the snapshot takes the profile off");
assert_eq!(d.color_profiles.rgb, None);
assert!(notes.iter().any(|n| n.contains("policy is")), "{notes:?}");
}
}
+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);
+180 -3
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Info",
["Window", "Document Info"],
None,
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file, format, effectivePpi, memoryBytes, storedBytes}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one; format: a linked image's file format by its extension, else the format of the pixels the document holds, null when unknown; effectivePpi: [x, y] pixels per inch at the size it is placed at, a distorted image measured at its middle, null when it has no area; memoryBytes: for an embedded image width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, else null; storedBytes: for an embedded image the bytes of the encoded image the document holds, else null; a Linked Images row gives the format, the size, the resolution and the file (`PNG; 1200 × 800 px; 150 ppi — /art/photo.png`), an Embedded Images row the format, the size and the memory (`PNG; 1200 × 800 px; estimated memory 3.7 MiB`)), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freef Line truncated
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), pathArea?: bool (default true; false skips the paths' area pass, as a category other than objects does), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), pathArea: pt² (the paths' total area, compound paths' included, guides left out; null unless the request covers the Objects category (no category, or objects) and pathArea? is not false: the area pass normalizes every closed path's geometry, so a caller showing another category can skip it), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file, format, effectivePpi, memoryBytes, storedBytes}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one; format: a linked image's file format by its extension, else the format of the pixels the document holds, null when unknown; effectivePpi: [x, y] pixels per inch at the size it is placed at, a distorted image measured at its middle, null when it has no area; memoryBytes: for an embedded image width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, else null; storedBytes: for an embedded image the bytes of the encoded image the document holds, else null; a Linked Images row gives the format, the size, the resolution and the file (`PNG; 1200 × 800 px; 150 ppi — /art/photo.png`), an Embedded Images row the format, the size and the memory (`PNG; 1200 × 800 px; estimated memory 3.7 MiB`)), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which obje Line truncated
has_doc,
info
),
@@ -445,6 +445,12 @@ fn sections(
if let Some(at) = rows.iter().position(|(label, _)| label == "Paths") {
rows.insert(at + 1, ("Path Length".into(), u.format(info["pathLength"].as_f64().unwrap_or(0.0))));
}
let area = info["pathArea"].as_f64().unwrap_or(0.0);
if area > 0.0
&& let Some(at) = rows.iter().position(|(label, _)| label == "Path Length")
{
rows.insert(at + 1, ("Path Area".into(), u.format_area(area)));
}
rows
}
"graphicStyles" => names("graphicStyleNames"),
@@ -755,6 +761,38 @@ fn object_paints(d: &Document, spots: &HashSet<&str>, members: &HashSet<*const N
used
}
/// Filled area of a path's closed subpaths under its fill rule (holes subtracted; open subpaths left out).
fn closed_path_area(path: &vectorcraft_geom::PathData, rule: vectorcraft_geom::FillRule) -> f64 {
let closed = vectorcraft_geom::PathData { subpaths: path.subpaths.iter().filter(|s| s.closed).cloned().collect() };
if closed.subpaths.is_empty() {
return 0.0;
}
let a = vectorcraft_pathops::area(&closed, rule);
if a.is_finite() && a > 0.0 { a } else { 0.0 }
}
/// Recursively collects non-guide subpaths from a node and its descendants for compound path area calculation.
fn collect_compound_subpaths(n: &Node, subs: &mut Vec<vectorcraft_geom::SubPath>) {
if n.is_guide() {
return;
}
match &n.kind {
NodeKind::Path { path, guide: false, .. } => {
subs.extend(path.subpaths.clone());
}
NodeKind::Compound { children, .. } => {
for c in children {
collect_compound_subpaths(c, subs);
}
}
_ => {
if let Some((pd, _)) = super::pathops::node_path(n) {
subs.extend(pd.subpaths);
}
}
}
}
fn info(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "document.info";
let category = str_param(p, "category");
@@ -782,6 +820,10 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
// The paths' total length, as Document Info › Objects shows it (the length of a cut line, a
// strip of LEDs along the letters, #1958).
let mut path_length = 0.0;
let mut path_area = 0.0;
// The area normalizes every closed path's geometry, so it is worked out only for a request
// that covers the Objects category and does not turn it off with `pathArea: false`.
let want_area = bool_or(p, "pathArea", true) && category.is_none_or(|c| c == "objects");
// Each font with the number of text objects set in it.
let mut fonts: BTreeMap<super::fonts::UsedFont, usize> = BTreeMap::new();
let mut images: BTreeMap<String, Value> = BTreeMap::new();
@@ -830,6 +872,19 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
members.extend(children.iter().map(|c| std::ptr::from_ref(&**c)));
}
});
// The members of the compound paths that the roots contain. Only these leave their area to the compound.
let mut compound_members: HashSet<*const Node> = HashSet::new();
for (r, _) in roots.iter().filter(|_| want_area) {
r.walk(&mut |n| {
if let NodeKind::Compound { children, .. } = &n.kind {
for c in children {
c.walk(&mut |descendant| {
compound_members.insert(std::ptr::from_ref(descendant));
});
}
}
});
}
// Depth first, in paint order, as `Node::walk` visits: each object with whether it and the groups and layers around it
// draw. An object that does not draw is still counted, and its members are visited.
let mut stack: Vec<(&Node, bool)> = vec![];
@@ -849,14 +904,26 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
NodeKind::Group { clip: true, .. } => Some("clipGroups"),
NodeKind::Group { .. } => Some("groups"),
NodeKind::Path { guide: true, .. } => Some("guides"),
NodeKind::Path { path, .. } => {
NodeKind::Path { path, rule, .. } => {
let l = path.length();
if l.is_finite() {
path_length += l;
}
if want_area && !compound_members.contains(&std::ptr::from_ref(n)) {
path_area += closed_path_area(path, *rule);
}
Some("paths")
}
NodeKind::Compound { .. } => Some("compoundPaths"),
NodeKind::Compound { children, rule } => {
if want_area && !compound_members.contains(&std::ptr::from_ref(n)) {
let mut subs = Vec::new();
for c in children {
collect_compound_subpaths(c, &mut subs);
}
path_area += closed_path_area(&vectorcraft_geom::PathData::new(subs), *rule);
}
Some("compoundPaths")
}
NodeKind::Text(t) => {
count_fonts(&mut fonts, t);
Some("textObjects")
@@ -972,6 +1039,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
"document": document_summary(d),
"objects": counts,
"pathLength": path_length,
"pathArea": want_area.then_some(path_area),
"fonts": font_names,
"fontUses": font_uses,
"fontDetails": font_entries,
@@ -1347,6 +1415,115 @@ mod tests {
assert_eq!(length(&mut s, json!({"selectionOnly": true})), 0.0);
}
/// Document Info › Objects gives the paths' total area in the document's units: an open line
/// counts 0, a closed rectangle encloses its area, and a compound path's holes are subtracted.
#[test]
fn info_gives_the_paths_total_area() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400, "units": "Points"})).unwrap();
let line = s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 72, "y2": 0})).unwrap()["id"].clone();
let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 10, "height": 20})).unwrap()["id"].clone();
let area = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["pathArea"].as_f64().unwrap();
// The rectangle encloses 200 pt²; the open line encloses 0.
assert!((area(&mut s, json!({})) - 200.0).abs() < 1e-6);
// An open line selected: pathArea is 0, so no "Path Area" row is inserted.
s.execute("select.set", &json!({"ids": [line]})).unwrap();
assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0);
let rows = s.execute("document.info", &json!({"selectionOnly": true, "category": "objects"})).unwrap()["sections"][0]["rows"].clone();
assert_eq!(rows, json!([["Paths", "1"], ["Path Length", "72 pt"]]));
// The rectangle selected: "Path Area" row follows "Path Length".
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
assert!((area(&mut s, json!({"selectionOnly": true})) - 200.0).abs() < 1e-6);
let rows = s.execute("document.info", &json!({"selectionOnly": true, "category": "objects"})).unwrap()["sections"][0]["rows"].clone();
assert_eq!(rows, json!([["Paths", "1"], ["Path Length", "60 pt"], ["Path Area", "200 pt²"]]));
// A compound path's pieces are paths: their areas count.
let other = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 5, "height": 5})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [rect, other]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
assert!((area(&mut s, json!({"selectionOnly": true})) - 225.0).abs() < 1e-6);
// A compound path (a 10x10 outer contour with a 6x6 inner hole) subtracts the hole:
let mut s2 = Session::new();
s2.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points"})).unwrap();
let outer = s2.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].clone();
let inner = s2.execute("shape.rectangle", &json!({"x": 12, "y": 12, "width": 6, "height": 6})).unwrap()["id"].clone();
s2.execute("select.set", &json!({"ids": [outer, inner]})).unwrap();
let cp1 = s2.execute("object.compoundPath.make", &json!({})).unwrap()["id"].clone();
assert!((area(&mut s2, json!({"selectionOnly": true})) - 64.0).abs() < 1e-6);
// A nested compound path (cp1 compounded with another disjoint 5x5 rectangle) does not double-count cp1:
let extra = s2.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 5, "height": 5})).unwrap()["id"].clone();
s2.execute("select.set", &json!({"ids": [cp1, extra]})).unwrap();
s2.execute("object.compoundPath.make", &json!({})).unwrap();
assert!((area(&mut s2, json!({"selectionOnly": true})) - 89.0).abs() < 1e-6);
// A guide path is left out.
let guide = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(guide)).unwrap().kind {
*g = true;
}
s.execute("select.set", &json!({"ids": [guide]})).unwrap();
assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0);
// A compound path whose members are guides is left out.
let g1 = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
let g2 = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(g1)).unwrap().kind {
*g = true;
}
if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(g2)).unwrap().kind {
*g = true;
}
s.execute("select.set", &json!({"ids": [g1, g2]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0);
// Nothing with no paths, and no area row.
s.execute("select.none", &json!({})).unwrap();
assert_eq!(area(&mut s, json!({"selectionOnly": true})), 0.0);
}
/// The area pass normalizes every closed path, so `document.info` leaves it out (`pathArea`
/// null) for a request that does not cover the Objects category or turns it off, and still
/// gives it for Objects and for every category.
#[test]
fn info_works_out_the_path_area_only_for_the_objects_category() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 20})).unwrap();
let area = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["pathArea"].as_f64();
assert!(area(&mut s, json!({})).is_some_and(|a| a > 0.0));
assert!(area(&mut s, json!({"category": "objects"})).is_some_and(|a| a > 0.0));
assert_eq!(area(&mut s, json!({"category": "fonts"})), None);
assert_eq!(area(&mut s, json!({"pathArea": false})), None);
// Without the area, Objects has no Path Area row and keeps its other rows.
let rows = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["sections"][0]["rows"].clone();
let without = rows(&mut s, json!({"category": "objects", "pathArea": false}));
let with = rows(&mut s, json!({"category": "objects"}));
assert!(without.as_array().unwrap().iter().all(|r| r[0] != "Path Area"), "{without}");
assert!(with.as_array().unwrap().iter().any(|r| r[0] == "Path Area"), "{with}");
assert_eq!(with.as_array().unwrap().len(), without.as_array().unwrap().len() + 1);
}
/// A selection containing both a compound and its member counts the member once; selecting
/// only the member still reports that path's area.
#[test]
fn info_path_area_counts_selected_compound_members_once() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let p = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
let q = s.execute("shape.rectangle", &json!({"x": 30, "y": 30, "width": 5, "height": 5})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [p, q]})).unwrap();
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
let st = s.doc_mut().unwrap();
let NodeKind::Compound { children, .. } = &st.doc.node(NodeId(compound)).unwrap().kind else { panic!("not a compound path") };
let member = children.iter().find(|child| child.id.0 == p).unwrap().id;
let area = |s: &mut Session| s.execute("document.info", &json!({"selectionOnly": true})).unwrap()["pathArea"].as_f64().unwrap();
let picked = s.execute("select.set", &json!({"ids": [member.0]})).unwrap();
assert_eq!(picked["count"], 1);
assert!((area(&mut s) - 100.0).abs() < 1e-6);
let picked = s.execute("select.set", &json!({"ids": [member.0, compound]})).unwrap();
assert_eq!(picked["count"], 2);
assert!((area(&mut s) - 125.0).abs() < 1e-6);
}
/// Document Info › Brushes lists the brushes the art's strokes use, each once with its type, and
/// leaves out the Brushes panel's brushes no art uses (`panelBrushNames` lists those). With
/// Selection Only it lists the brushes the selected objects' strokes use.
+1 -1
View File
@@ -284,7 +284,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Metadata Template…",
[],
None,
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text (exactly one of the three; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
"{path?: an XMP file, name?: a template of the metadata templates folder by the name or file file.info.templates lists, data?: XMP text, dataBase64?: XMP bytes (exactly one source; at most 8 MB), mode: \"replace\" (clear the author, authorTitle, description, keywords, rating, copyright status, notice and URL, then take the template's; the title stays unless the template has one) | \"keep\" (keep the File Info, and take each field the template has) | \"append\" (keep the File Info, add the template's keywords, and take its other fields only where the File Info has none: a title only over an Untitled-N one, a rating only over 0, a copyright status only over unknown), apply?: true (false: change nothing and return the merged File Info), base?: {File Info fields as file.info takes them} merged into instead of the document's} merge a metadata template into the File Info in one undo step, none when nothing changes; a template value file.info would refuse is left out; a missing file, a file larger than 8 MB or one that is not XMP is an error → the File Info as file.info reports it, with changed: true|false (with apply: false, the merged File Info without changed)",
has_doc,
super::fileinfo::apply_template
),
Loaded 100 of 854 files, more files were not shown because too many files have changed in this diff. Show more