Merge main into feat/script-warning-reaches
No files matched your search
@@ -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-----
|
||||
@@ -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",
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
name: Cache prune
|
||||
|
||||
# A pass of the cache prune after every CI attempt on main. ci.yml's `cache prune` job prunes while
|
||||
# a run's jobs save their entries, but "Re-run failed jobs" re-runs only the failed jobs: a re-run
|
||||
# `cache warm` leg saves a new entry, and the prune job, which succeeded in the first attempt, does
|
||||
# not run again. The entry it replaced would stay until the next main run, and with it the cache
|
||||
# would be over its 10 GB budget, where GitHub evicts entries a run still needs. This runs once
|
||||
# after every attempt, re-runs and canceled runs included (craft-common-actions actions/cache-prune).
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [CI]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
cache-prune:
|
||||
name: cache prune
|
||||
# A fork's pull request from a branch named main also matches `branches`.
|
||||
if: github.event.workflow_run.event != 'pull_request'
|
||||
timeout-minutes: 10
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
# A failed pass warns; the next run's prune deletes what it missed.
|
||||
- name: Prune replaced cache entries
|
||||
uses: storytold/craft-common-actions/actions/cache-prune@main
|
||||
continue-on-error: true
|
||||
@@ -1,10 +1,14 @@
|
||||
name: CI
|
||||
|
||||
# Quality gates for every push to main and every pull request (`cargo xtask ci`), through the
|
||||
# suite's shared gate workflow in craft-common-actions.
|
||||
# suite's shared gate workflow in craft-common-actions. Every night the gate runs a cold build:
|
||||
# the safety net for the workspace crates it keeps between runs (`cache-workspace-crates`), and a
|
||||
# fresh start for that cache entry.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
schedule:
|
||||
- cron: "37 3 * * *"
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
@@ -23,7 +27,10 @@ jobs:
|
||||
with:
|
||||
# Same craft-fonts commit as release.yml.
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
timeout-minutes: 90
|
||||
# A cold `cache warm` leg (the nightly run, or any run after a toolchain or lockfile change)
|
||||
# took 90 minutes to reach its last three steps on 2026-11-27 and was canceled there; with
|
||||
# those steps and the save it needs about two hours.
|
||||
timeout-minutes: 150
|
||||
# The gate's test binaries carry no debug info and no symbols (CARGO_PROFILE_TEST_DEBUG=0,
|
||||
# CARGO_PROFILE_TEST_STRIP=symbols), as photocraft's do: linking ~100 test binaries with line
|
||||
# tables ran the hosted runner out of resources, and it stopped mid-link with "received a
|
||||
@@ -39,7 +46,68 @@ jobs:
|
||||
test-shards: 5
|
||||
shard-command: cargo xtask ci shard
|
||||
warm-command: cargo xtask ci warm
|
||||
# The dependency cache also keeps the compiled workspace crates and test executables, so a
|
||||
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
|
||||
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
|
||||
# `cache-prune` below deletes the one it replaced. The nightly run restores nothing and
|
||||
# builds everything from source.
|
||||
cache-workspace-crates: true
|
||||
cold-build: ${{ github.event_name == 'schedule' }}
|
||||
packages: >-
|
||||
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev
|
||||
libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
|
||||
libgl1-mesa-dev
|
||||
|
||||
# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache
|
||||
# budget. It runs beside the gate and prunes each time the `cache warm` leg finishes saving. A
|
||||
# failed prune warns instead of failing the run, and cache-prune.yml prunes again after every
|
||||
# attempt, re-runs of failed jobs included. `watch-minutes` is longer than the gate's
|
||||
# `timeout-minutes`, so the watch outlasts a cold `cache warm` leg.
|
||||
cache-prune:
|
||||
name: cache prune
|
||||
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 170
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Prune replaced cache entries
|
||||
uses: storytold/craft-common-actions/actions/cache-prune@main
|
||||
continue-on-error: true
|
||||
with:
|
||||
watch: true
|
||||
watch-minutes: 160
|
||||
saving-jobs: |
|
||||
^gate( / cache warm \(.*\))?$
|
||||
|
||||
# The nightly cold run never restores the rolling crates entry, so the old entry is only overlap
|
||||
# while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the
|
||||
# 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes
|
||||
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
|
||||
# When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run
|
||||
# failed jobs" runs it again beside the re-run leg. The script's 160-minute wait starts when the leg
|
||||
# starts, which is after `gate / select legs` and a free runner, so this job's timeout leaves
|
||||
# 40 minutes for that.
|
||||
cold-cache-clear:
|
||||
name: cold cache clear
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 200
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Delete the old rolling entries before the save
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: python3 scripts/ci-clear-rolling-cache.py
|
||||
@@ -3,13 +3,14 @@ name: Nightly check
|
||||
# The app-side Nightly pieces, checked without a feed run: the Python suites that read the archive,
|
||||
# plist and signing scripts, the workflow contracts, and (on Windows) the packaging and signing
|
||||
# PowerShell suites. The producer itself is .github/workflows/nightly.yml; the Apple-silicon bundle
|
||||
# is built and verified by nightly-macos.yml behind the `full-ci` label.
|
||||
# is built and verified by nightly-macos.yml behind the `full-ci` label. The same job also runs the
|
||||
# suite for scripts/ci-clear-rolling-cache.py, which ci.yml's nightly cold run calls.
|
||||
on:
|
||||
push:
|
||||
branches: [main, release]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"]
|
||||
pull_request:
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -34,6 +35,8 @@ jobs:
|
||||
persist-credentials: false
|
||||
- name: Run the synthetic suites
|
||||
run: python3 packaging/nightly-tests.py
|
||||
- name: Run the cold cache clear suite
|
||||
run: python3 scripts/ci-clear-rolling-cache-tests.py
|
||||
- name: Parse every nightly shell script
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -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.')
|
||||
@@ -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.
|
||||
@@ -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"]'
|
||||
@@ -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 }}
|
||||
@@ -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).
|
||||
@@ -141,6 +150,8 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-arrow-down.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-arrow-extend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-arrow-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Selection and Direct Selection arrows' fill, painted black or white under their outline |
|
||||
| `assets/icons/dc-arrow-left.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-arrow-right.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-arrow-tip.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-arrow-up.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-artboard.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
@@ -213,6 +224,8 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-graphic-styles.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-grid-view.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-group-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-guide-horizontal.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a ruler down the left with a line across) | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-guide-vertical.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a ruler along the top with a line down) | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-help.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a question mark in a circle) | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-join-bevel.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-join-miter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
|
||||
@@ -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 = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
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 = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
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 = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
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 = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
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 = "6fcf61c816c399508a60c7029a59e2c7b6139e0b", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
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 = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
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 = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
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 = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
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 = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
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 = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
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 = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b" }
|
||||
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" }
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G5: 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); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-22 · **Change:** minor (Upcoming: G11 names what is left (#864's unit preference, #885), not the fixed Shape Builder regions and Asset Export borders, with docs/roadmap.md's 6–13 h, and the Essentials row names Shape Builder's remaining depth, #8314; previously: G5: 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); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
|
||||
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
|
||||
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
|
||||
@@ -35,7 +35,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
|
||||
|---|---:|---:|---:|---|
|
||||
| **Full Illustrator** (ready for real work; decides the stage) | **~62%** (57–67%) | **~340–560 h** | ~95–160 h | the mainstream work below, plus 3D (50–85 h), raster effects (23–39 h), advanced type (20–28 h), generative AI (30–60 h), localization (50–85 h) and ecosystem |
|
||||
| **Mainstream illustrator** | **~65%** (60–70%) | **~230–380 h** | ~65–110 h | the interaction-fidelity pass (60–90 h), hardening and QA (30–50 h), stability (20–35 h), performance budgets (15–25 h), `.ai` exchange (10–20 h), the remaining depth of the everyday areas |
|
||||
| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder regions (4–8 h), UI polish |
|
||||
| **Essentials user** | **~75%** (70–80%) | **~60–105 h** | ~25–45 h | launch and stability on Windows (20–35 h), in-app help and onboarding (8–15 h), basic QA (10–15 h), Shape Builder depth (4–8 h; #937's reproduced case is fixed, unconfirmed on the reporter's file), UI polish |
|
||||
|
||||
Hours are Opus 5.5 agent wall-clock hours, calibrated from this repo's merged-PR timestamps (e.g. 0.7–1.2 h per
|
||||
Photoshop-style filter, ~0.8 h per medium feature); see [calibration](docs/target-app-parity.md#calibration).
|
||||
@@ -119,11 +119,13 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
1. **Interaction-fidelity pass** (G1), tool by tool from [ui-parity.md](docs/ui-parity.md): 60–90 h.
|
||||
2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h.
|
||||
3. **Launch and stability on real machines** (G10): 20–35 h.
|
||||
4. **Core-tool correctness** (G11: Shape Builder regions, Asset Export borders): 8–15 h.
|
||||
4. **Core-tool correctness** (G11: the unit preference reverting to points, #864, SVG export units fixed; a Transform effect in a fill's or stroke's own effects, #885; Shape Builder regions and Asset Export borders are fixed): 6–13 h.
|
||||
5. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). The Effect Gallery's filter thumbnails and in-dialog preview are in (G2).
|
||||
|
||||
## 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,14 +144,18 @@ 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.
|
||||
- 2026-11-17: Circle tool, From Center (a Control bar checkbox, `tool.setOption` `fromCenter`): the first point is the circle's center and the outline passes through the pointer, which snaps to Smart Guides and anchor points, so a circle centered on one corner of a rectangle can pass through the opposite corner; `shape.circleThroughPoints {center, points: [[x, y]]}` draws it. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
|
||||
- 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.
|
||||
@@ -251,6 +257,8 @@ 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. |
|
||||
| 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. |
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 = "6fcf61c816c399508a60c7029a59e2c7b6139e0b", 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 }
|
||||
|
||||
@@ -61,8 +61,9 @@ pollster = "1"
|
||||
# which src/host_services.rs uses to read the path PhotoCraft registers under App Paths.
|
||||
# Win32_Devices_Display has `QueryDisplayConfig`, Win32_UI_ColorSystem the display's ICC profile and
|
||||
# Win32_System_LibraryLoader `GetProcAddress`, which src/display_profile.rs uses to read the
|
||||
# display's color profile for the canvas.
|
||||
windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Foundation", "Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_ColorSystem", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
|
||||
# display's color profile for the canvas. Win32_UI_HiDpi has `GetDpiForMonitor`, which
|
||||
# src/windows_display_size.rs uses to read a monitor's raw density for Display Print Size.
|
||||
windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Foundation", "Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_ColorSystem", "Win32_UI_HiDpi", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
|
||||
# The renderer's worker count follows those cores (src/windows_cores.rs).
|
||||
vectorcraft-render = { workspace = true }
|
||||
|
||||
@@ -83,7 +84,8 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std"
|
||||
# The windows' Metal layers and the sRGB color space they are tagged with (src/mac_color_space.rs).
|
||||
# Zlib OR Apache-2.0 OR MIT, already in the build through wgpu with these features.
|
||||
objc2-quartz-core = { version = "0.3", default-features = false, features = ["std", "objc2-core-foundation", "objc2-core-graphics", "CALayer", "CAMetalLayer"] }
|
||||
objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGColorSpace"] }
|
||||
# CGDisplayScreenSize gives a display's physical size for Display Print Size (src/screen_density.rs).
|
||||
objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGColorSpace", "CGDirectDisplay", "CGDisplayConfiguration"] }
|
||||
# Waits for the answer of a file dialog shown as a sheet (src/main.rs, #867). MIT OR Apache-2.0,
|
||||
# already in the build through eframe.
|
||||
pollster = "1"
|
||||
|
||||
@@ -184,6 +184,11 @@ impl App {
|
||||
let now = ctx.input(|i| i.time);
|
||||
if let Some(w) = &self.winit_window {
|
||||
self.display_profile.tick(w, now, self.app.session.prefs.monitor_profile_display, &self.app.display_profile, ctx);
|
||||
if let Some(read) = self.screen_density.tick(w, self.app.session.prefs.display_print_size, ctx) {
|
||||
self.app.services.screens = read.screens;
|
||||
self.app.set_screen_reading(read.main);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
self.app.tick(ctx);
|
||||
if self.app.ui.status == "quit" {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -398,6 +398,31 @@ pub fn adapter_order(
|
||||
order.into_iter().map(|(i, _)| i).collect()
|
||||
}
|
||||
|
||||
/// [`adapter_order`] without the adapters a restart left out after they failed (`skip`) and those
|
||||
/// that crashed an earlier start (`crashed`), and `true` when that left none and the ones that
|
||||
/// crashed are tried again. A crash record can't stop a start that has no other adapter to try:
|
||||
/// the record may be from a start ended from outside before its first frame (#9183), which looks
|
||||
/// the same as a crash in the driver. An adapter in `skip` failed in this run of the app and
|
||||
/// stays left out.
|
||||
pub fn order_leaving_out(
|
||||
candidates: &[Candidate],
|
||||
power: PowerPreference,
|
||||
displays: &[DisplayGpu],
|
||||
compositor: Option<(u32, u32)>,
|
||||
named: Option<&str>,
|
||||
skip: &[String],
|
||||
crashed: &[String],
|
||||
) -> (Vec<usize>, bool) {
|
||||
let left_out: Vec<String> = skip.iter().chain(crashed).cloned().collect();
|
||||
let order = adapter_order(candidates, power, displays, compositor, named, &left_out);
|
||||
if !order.is_empty() || crashed.is_empty() {
|
||||
return (order, false);
|
||||
}
|
||||
let again = adapter_order(candidates, power, displays, compositor, named, skip);
|
||||
let retried = !again.is_empty();
|
||||
(again, retried)
|
||||
}
|
||||
|
||||
/// wgpu's own ranking for a power preference: the preferred kind of GPU, the other kind, unknown,
|
||||
/// virtual, software.
|
||||
fn power_rank(t: DeviceType, power: PowerPreference) -> u8 {
|
||||
@@ -845,10 +870,9 @@ pub fn selector(
|
||||
) -> NativeAdapterSelectorMethod {
|
||||
let named = std::env::var(NAME_ENV).ok();
|
||||
let skip = skipped();
|
||||
let left_out: Vec<String> = skip.iter().chain(&crashed).cloned().collect();
|
||||
Arc::new(move |adapters, surface| {
|
||||
let candidates: Vec<Candidate> = adapters.iter().map(|a| Candidate::new(a, surface)).collect();
|
||||
let order = adapter_order(&candidates, power, &displays, compositor, named.as_deref(), &left_out);
|
||||
let (order, retried) = order_leaving_out(&candidates, power, &displays, compositor, named.as_deref(), &skip, &crashed);
|
||||
let listed: Vec<String> = candidates
|
||||
.iter()
|
||||
.map(|c| {
|
||||
@@ -872,6 +896,9 @@ pub fn selector(
|
||||
})
|
||||
.collect();
|
||||
log::info!("graphics adapters: {}", listed.join("; "));
|
||||
if retried {
|
||||
log::warn!("every graphics adapter that can show the window crashed an earlier start: trying them again");
|
||||
}
|
||||
let first = order.first().and_then(|&i| adapters.get(i).zip(candidates.get(i)));
|
||||
let Some((adapter, chosen)) = first else {
|
||||
startup.none_left();
|
||||
|
||||
@@ -827,3 +827,17 @@ fn pci_ids_reject_a_sign_in_the_hex_digits() {
|
||||
assert_eq!(pci_ids("PCI\\VEN_+10DE&DEV_2204"), None);
|
||||
assert_eq!(pci_ids("PCI\\VEN_10DE&DEV_+2204"), None);
|
||||
}
|
||||
|
||||
/// #9183: a Mac lists one adapter. A start ended from outside before its first frame left it
|
||||
/// recorded as crashed, and the next start left it out and had nothing to draw on. It is tried
|
||||
/// again when nothing else is left; an adapter a restart left out after it failed stays out, and
|
||||
/// with another adapter to try, the one that crashed is still left out.
|
||||
#[test]
|
||||
fn an_adapter_that_crashed_an_earlier_start_is_tried_again_when_no_other_is_left() {
|
||||
let mac = [gpu("Apple M6", Backend::Metal, DeviceType::IntegratedGpu)];
|
||||
let crashed = vec![mac[0].key.clone()];
|
||||
assert_eq!(order_leaving_out(&mac, PowerPreference::LowPower, &[], None, None, &[], &crashed), (vec![0], true));
|
||||
assert_eq!(order_leaving_out(&mac, PowerPreference::LowPower, &[], None, None, &crashed, &crashed), (vec![], false));
|
||||
let two = [gpu("Apple M6", Backend::Metal, DeviceType::IntegratedGpu), gpu("llvmpipe", Backend::Gl, DeviceType::Cpu)];
|
||||
assert_eq!(order_leaving_out(&two, PowerPreference::LowPower, &[], None, None, &[], &crashed), (vec![1], false));
|
||||
}
|
||||
@@ -220,11 +220,20 @@ fn report_path(dir: &Path) -> PathBuf {
|
||||
dir.join(format!("{REPORT_PREFIX}{}.txt", std::process::id()))
|
||||
}
|
||||
|
||||
/// A report file this process wrote and holds locked until the interface answers again.
|
||||
/// A report file this process holds locked: the one it wrote, until the interface answers again,
|
||||
/// or a left one while it is read. Dropping it unlocks the file. A child process that any thread
|
||||
/// starts holds a copy of the file's handle until it runs its program, and the lock is only freed
|
||||
/// by closing every copy or by unlocking.
|
||||
#[derive(Debug)]
|
||||
pub struct Held {
|
||||
path: PathBuf,
|
||||
_file: File,
|
||||
file: File,
|
||||
}
|
||||
|
||||
impl Drop for Held {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.file.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `text` to this process's report file in `dir` and lock it. Where the file system has no
|
||||
@@ -237,7 +246,7 @@ fn write_report(dir: &Path, text: &str) -> std::io::Result<Held> {
|
||||
log::warn!("the hang report file is written without a lock: {e}");
|
||||
}
|
||||
file.write_all(text.as_bytes())?;
|
||||
Ok(Held { path, _file: file })
|
||||
Ok(Held { path, file })
|
||||
}
|
||||
|
||||
/// Whether a report file whose `try_lock` gave `locked` was abandoned: nobody holds it. A file
|
||||
@@ -253,13 +262,14 @@ fn abandoned(locked: Result<(), std::fs::TryLockError>) -> bool {
|
||||
|
||||
/// The report file at `path`, opened and locked, with its length, when it was abandoned
|
||||
/// ([`abandoned`]) and is not empty (an empty one may be being written).
|
||||
fn open_abandoned(path: &Path) -> Option<(File, u64)> {
|
||||
fn open_abandoned(path: &Path) -> Option<(Held, u64)> {
|
||||
let file = File::options().read(true).write(true).open(path).ok()?;
|
||||
if !abandoned(file.try_lock()) {
|
||||
return None;
|
||||
}
|
||||
let len = file.metadata().map_or(0, |m| m.len());
|
||||
(len > 0).then_some((file, len))
|
||||
let held = Held { path: path.to_path_buf(), file };
|
||||
let len = held.file.metadata().map_or(0, |m| m.len());
|
||||
(len > 0).then_some((held, len))
|
||||
}
|
||||
|
||||
/// The reports that sessions closed while they did not answer left in `dir`, oldest first; `None`
|
||||
@@ -286,20 +296,20 @@ pub fn take_previous(dir: &Path) -> Option<String> {
|
||||
// Newest first: only abandoned reports count toward the limit.
|
||||
let mut texts = Vec::new();
|
||||
for (_, path) in found.into_iter().rev() {
|
||||
let Some((file, len)) = open_abandoned(&path) else { continue };
|
||||
let Some((held, len)) = open_abandoned(&path) else { continue };
|
||||
if texts.len() == MAX_REPORT_FILES {
|
||||
drop(file);
|
||||
drop(held);
|
||||
remove_quietly(&path);
|
||||
continue;
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
let text = if len <= MAX_REPORT_BYTES && (&file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() {
|
||||
let text = if len <= MAX_REPORT_BYTES && (&held.file).take(MAX_REPORT_BYTES).read_to_end(&mut bytes).is_ok() {
|
||||
String::from_utf8_lossy(&bytes).into_owned()
|
||||
} else {
|
||||
format!("The report was larger than {MAX_REPORT_BYTES} bytes and was not read.\n")
|
||||
};
|
||||
// Closed (and unlocked) before it is moved: Windows moves no open file.
|
||||
drop(file);
|
||||
drop(held);
|
||||
if !texts.is_empty() {
|
||||
remove_quietly(&path);
|
||||
} else if let Err(e) = std::fs::rename(&path, dir.join(PREVIOUS_FILE)) {
|
||||
@@ -324,8 +334,8 @@ pub static CLOSING: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Remove `held`'s file, closing it first. → the error message; a file already gone is none.
|
||||
fn remove(held: Held) -> Option<String> {
|
||||
let Held { path, _file: file } = held;
|
||||
drop(file);
|
||||
let path = held.path.clone();
|
||||
drop(held);
|
||||
match std::fs::remove_file(&path) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Some(e.to_string()),
|
||||
_ => None,
|
||||
|
||||
@@ -136,6 +136,17 @@ fn a_stall_writes_the_report_file_and_its_end_removes_it() {
|
||||
assert!(shared.last.lock().unwrap().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_report_frees_its_lock_while_a_copy_of_its_handle_is_open() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let held = write_report(dir.path(), "left\n").unwrap();
|
||||
// A child process that is starting holds such a copy.
|
||||
let copy = held.file.try_clone().unwrap();
|
||||
drop(held);
|
||||
assert_eq!(take_previous(dir.path()).as_deref(), Some("left\n"), "a dropped report is no longer locked");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_normally_removes_the_report_and_writes_no_more() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,7 @@ mod process_identity;
|
||||
mod profile_root;
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
mod quit_windows;
|
||||
mod screen_density;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
mod single_instance;
|
||||
#[cfg(windows)]
|
||||
@@ -69,8 +70,11 @@ mod window_frame;
|
||||
mod windows_alt_codes;
|
||||
#[cfg(windows)]
|
||||
mod windows_cores;
|
||||
#[cfg(windows)]
|
||||
mod windows_display_size;
|
||||
mod windows_stylus;
|
||||
mod windows_symbol_chars;
|
||||
mod windows_wintab;
|
||||
mod xwayland;
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
@@ -206,6 +210,9 @@ struct App {
|
||||
held_files: Vec<String>,
|
||||
/// Reads the profile of the display that shows the main window, for the canvas.
|
||||
display_profile: display_profile::Reader,
|
||||
/// Measures the density of the display that shows the main window, for Display Print Size at
|
||||
/// 100% Zoom.
|
||||
screen_density: screen_density::Tracker,
|
||||
/// When this frame's input hook started, for the hang report's frame times (`hang_watch`).
|
||||
frame_start: Option<std::time::Instant>,
|
||||
/// The shortest time between the starts of two frames, while the window presents without vsync
|
||||
@@ -817,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);
|
||||
@@ -970,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();
|
||||
@@ -989,6 +1001,7 @@ fn main() -> std::process::ExitCode {
|
||||
winit_window,
|
||||
held_files,
|
||||
display_profile: Default::default(),
|
||||
screen_density: Default::default(),
|
||||
frame_start: None,
|
||||
min_frame,
|
||||
last_frame_began: None,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -0,0 +1,817 @@
|
||||
//! The densities of the connected displays, in points (at each display's scale factor) per inch,
|
||||
//! for Preferences › General › Display Print Size at 100% Zoom (`Services::screen_ppi` for the
|
||||
//! display that shows most of the main window, `Services::screens` for every display): a
|
||||
//! display's size in points divided by the physical size the system reports for it.
|
||||
//!
|
||||
//! - macOS: `CGDisplayScreenSize`.
|
||||
//! - Windows: `GetDpiForMonitor`'s raw density (`windows_display_size`).
|
||||
//! - X11 on Linux, XWayland included: the RandR output's width and height in millimeters.
|
||||
//! - Wayland on Linux: the physical width and height of the compositor's `wl_output` for the display.
|
||||
//! - Other systems: no size, so an inch takes 96 points.
|
||||
//!
|
||||
//! A display that reports no size, or a size no display has, gives `None`, and an inch then takes
|
||||
//! 96 points. While the preference is on, the displays are listed once a second while the app
|
||||
//! draws. When the list changes, a background thread reads every display's size, and a later
|
||||
//! frame takes the result. A reading that fails is tried again after [`RETRY_AFTER`] seconds, and
|
||||
//! the displays are read again [`READ_AGAIN_AFTER`] seconds after the last reading; the app draws a
|
||||
//! frame for each of these when nothing else makes it draw.
|
||||
|
||||
use std::sync::mpsc::{Receiver, TryRecvError};
|
||||
|
||||
use vectorcraft_ui_egui::{ScreenDensity, ScreenPpi};
|
||||
use winit::dpi::{PhysicalPosition, PhysicalSize};
|
||||
use winit::monitor::MonitorHandle;
|
||||
|
||||
/// Seconds between two listings of the displays.
|
||||
const LOOK_EVERY: f64 = 1.0;
|
||||
|
||||
/// Seconds after a failed reading before the same displays are read again.
|
||||
const RETRY_AFTER: f64 = 10.0;
|
||||
|
||||
/// Seconds after a reading before the same displays are read again: a display can be replaced by
|
||||
/// one the listing cannot tell apart (the same connector, resolution and scale).
|
||||
const READ_AGAIN_AFTER: f64 = 60.0;
|
||||
|
||||
/// Millimeters in an inch.
|
||||
const MM_PER_INCH: f64 = 25.4;
|
||||
|
||||
/// How far the horizontal and vertical densities of one display may differ, as a fraction of the
|
||||
/// larger: square pixels on a display that reports its true size give two densities this close.
|
||||
const AXES_AGREE: f64 = 0.1;
|
||||
|
||||
/// A connected display as winit lists it: what a reading needs, and what tells two lists apart.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Display {
|
||||
name: Option<String>,
|
||||
position: PhysicalPosition<i32>,
|
||||
size: PhysicalSize<u32>,
|
||||
/// The display's scale factor, as its bits.
|
||||
scale: u64,
|
||||
/// The system's id of the display ([`native_id`]).
|
||||
id: i64,
|
||||
}
|
||||
|
||||
impl Display {
|
||||
fn of(m: &MonitorHandle) -> Self {
|
||||
Self { name: m.name(), position: m.position(), size: m.size(), scale: m.scale_factor().to_bits(), id: native_id(m) }
|
||||
}
|
||||
}
|
||||
|
||||
/// One display's physical size in millimeters: `None` when the system reports none, an error when
|
||||
/// asking for it failed.
|
||||
type Size = Result<Option<[f64; 2]>, String>;
|
||||
|
||||
/// The physical sizes of displays, one for each display read, or why none could be read.
|
||||
type Reading = Result<Vec<Size>, String>;
|
||||
|
||||
/// What the host hands the app: the density of the main window's display, unread while that
|
||||
/// display is unknown or has not answered yet, and every display's that answered.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Densities {
|
||||
pub(crate) main: ScreenPpi,
|
||||
pub(crate) screens: Vec<ScreenDensity>,
|
||||
}
|
||||
|
||||
/// What a display answered: its physical size (`Some(None)` for none), or `None` while it has not
|
||||
/// answered.
|
||||
type Answer = Option<Option<[f64; 2]>>;
|
||||
|
||||
/// What a listing gives: the displays, the one that shows most of the main window, and the main
|
||||
/// window's scale factor.
|
||||
type Listing = (Vec<Display>, Option<Display>, f64);
|
||||
|
||||
/// Keeps the densities current from the main window's frames.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Tracker {
|
||||
/// When the displays were last listed.
|
||||
looked: Option<f64>,
|
||||
/// The display that showed most of the main window at the last listing, and the window's scale
|
||||
/// factor then.
|
||||
current: Option<(Display, f64)>,
|
||||
/// The displays of the last reading that finished, each with what it answered.
|
||||
read: Option<Vec<(Display, Answer)>>,
|
||||
/// The displays of the last reading that failed, and when it failed.
|
||||
failed: Option<(Vec<Display>, f64)>,
|
||||
/// The reading in progress: the displays it reads, and where its result arrives.
|
||||
running: Option<(Vec<Display>, Receiver<Reading>)>,
|
||||
/// The reading in progress started before the preference was last turned off: its result is
|
||||
/// dropped when it arrives, and no other reading starts until then.
|
||||
obsolete: bool,
|
||||
/// What [`Self::tick`] returned last.
|
||||
reported: Option<Densities>,
|
||||
/// The displays of the last listing.
|
||||
listed: Option<Vec<Display>>,
|
||||
/// When the last reading that finished ended.
|
||||
read_at: f64,
|
||||
/// When the first tick ran: the tracker's clock, which runs while the window draws nothing.
|
||||
origin: Option<std::time::Instant>,
|
||||
}
|
||||
|
||||
impl Tracker {
|
||||
/// Lists the displays when a listing is due and Display Print Size is `enabled`, starts a
|
||||
/// reading on a background thread when they changed, and returns the densities when they
|
||||
/// differ from what it returned before. The thread asks `ctx` for a frame when its reading is
|
||||
/// ready.
|
||||
pub(crate) fn tick(&mut self, window: &winit::window::Window, enabled: bool, ctx: &egui::Context) -> Option<Densities> {
|
||||
let now = self.origin.get_or_insert_with(std::time::Instant::now).elapsed().as_secs_f64();
|
||||
let list = || {
|
||||
// winit stops on a display that went away while it is being asked about (Windows); that
|
||||
// listing is dropped, and the next one is made a second later.
|
||||
let listing = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
let current = window.current_monitor().map(|m| Display::of(&m));
|
||||
(window.available_monitors().map(|m| Display::of(&m)).collect::<Vec<_>>(), current, window.scale_factor())
|
||||
}));
|
||||
listing.map_err(|_| log::debug!("a display went away while the displays were listed")).ok()
|
||||
};
|
||||
let wayland = is_wayland(window);
|
||||
let start = |displays: Vec<Display>| {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let ctx = ctx.clone();
|
||||
let spawned = std::thread::Builder::new().name("display size".into()).spawn(move || {
|
||||
// The app may have quit, and dropped the receiver, before the reading ends.
|
||||
let _ = tx.send(read_all(&displays, wayland));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
spawned.map(|_| rx).map_err(|e| format!("couldn't start reading the displays' sizes: {e}"))
|
||||
};
|
||||
let densities = self.update(now, enabled, list, start);
|
||||
// A failed reading is tried again at a listing RETRY_AFTER seconds later, also in an app
|
||||
// that is not drawing. A reading in progress asks for a frame when it ends.
|
||||
if enabled
|
||||
&& self.running.is_none()
|
||||
&& let Some((_, at)) = &self.failed
|
||||
{
|
||||
let due = (at + RETRY_AFTER).max(self.looked.map_or(0.0, |l| l + LOOK_EVERY));
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64((due - now).clamp(0.0, RETRY_AFTER)));
|
||||
} else if enabled && self.running.is_none() && self.read.is_some() {
|
||||
// An app that is not drawing still lists and reads the displays READ_AGAIN_AFTER seconds
|
||||
// after the last reading.
|
||||
let due = (self.read_at + READ_AGAIN_AFTER).max(self.looked.map_or(0.0, |l| l + LOOK_EVERY));
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64((due - now).clamp(0.0, READ_AGAIN_AFTER)));
|
||||
}
|
||||
densities
|
||||
}
|
||||
|
||||
/// [`Self::tick`] with the listing (`list`) and the start of a reading (`start`) passed in.
|
||||
fn update(
|
||||
&mut self,
|
||||
now: f64,
|
||||
enabled: bool,
|
||||
list: impl FnOnce() -> Option<Listing>,
|
||||
start: impl FnOnce(Vec<Display>) -> Result<Receiver<Reading>, String>,
|
||||
) -> Option<Densities> {
|
||||
let was_running = self.running.is_some();
|
||||
if let Some((displays, rx)) = self.running.take() {
|
||||
match rx.try_recv() {
|
||||
Err(TryRecvError::Empty) => self.running = Some((displays, rx)),
|
||||
_ if self.obsolete => self.obsolete = false,
|
||||
Ok(Ok(sizes)) => {
|
||||
// A display whose size could not be read keeps what an earlier reading gave it,
|
||||
// or stays unanswered, until the reading is tried again.
|
||||
let mut failed = false;
|
||||
let read: Vec<_> = displays
|
||||
.iter()
|
||||
.zip(sizes.into_iter().chain(std::iter::repeat(Ok(None))))
|
||||
.map(|(d, s)| {
|
||||
let mm = s.map(Some).unwrap_or_else(|e| {
|
||||
log::debug!("couldn't read a display's physical size: {e}");
|
||||
failed = true;
|
||||
self.earlier(d)
|
||||
});
|
||||
(d.clone(), mm)
|
||||
})
|
||||
.collect();
|
||||
self.failed = failed.then_some((displays, now));
|
||||
self.read = Some(read);
|
||||
self.read_at = now;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
log::debug!("couldn't read the displays' physical sizes: {e}");
|
||||
self.fail(displays, now);
|
||||
}
|
||||
Err(TryRecvError::Disconnected) => {
|
||||
log::debug!("the reading of the displays' physical sizes stopped without a result");
|
||||
self.fail(displays, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
// When a reading ends, the displays are listed again at once: they may have changed while
|
||||
// it ran, and the frame its end asked for may be the last one for a while.
|
||||
if was_running && self.running.is_none() {
|
||||
self.looked = None;
|
||||
}
|
||||
if !enabled {
|
||||
// Turned on again, the displays are read and the densities reported anew: a display
|
||||
// may have been replaced meanwhile by one that lists the same.
|
||||
self.reported = None;
|
||||
self.read = None;
|
||||
self.failed = None;
|
||||
self.looked = None;
|
||||
self.obsolete = self.running.is_some();
|
||||
return None;
|
||||
}
|
||||
// The densities change only at a listing, and one follows the end of every reading.
|
||||
let listing = !self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now));
|
||||
if !listing && self.reported.is_some() {
|
||||
return None;
|
||||
}
|
||||
if listing {
|
||||
self.looked = Some(now);
|
||||
}
|
||||
if let Some((displays, current, scale)) = listing.then(list).flatten() {
|
||||
// winit can give the window's display as it was before a change of resolution: the
|
||||
// display is found in the listing by its id and name.
|
||||
let current = current.map(|c| displays.iter().find(|d| d.id == c.id && d.name == c.name).cloned().unwrap_or(c));
|
||||
self.current = current.map(|c| (c, scale));
|
||||
self.listed = Some(displays.clone());
|
||||
// These displays are read once, and again RETRY_AFTER seconds after a reading of them
|
||||
// failed in whole or in part.
|
||||
let known = self.read.as_ref().is_some_and(|r| r.iter().map(|(d, _)| d).eq(displays.iter()));
|
||||
let due = match &self.failed {
|
||||
Some((d, at)) if *d == displays => !(*at..*at + RETRY_AFTER).contains(&now),
|
||||
_ => !known || now - self.read_at >= READ_AGAIN_AFTER,
|
||||
};
|
||||
if self.running.is_none() && due {
|
||||
match start(displays.clone()) {
|
||||
Ok(rx) => self.running = Some((displays, rx)),
|
||||
Err(e) => {
|
||||
log::warn!("{e}");
|
||||
self.fail(displays, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let read = self.read.as_ref()?;
|
||||
// The main window counts in its own scale factor, which on Wayland can be a fraction where
|
||||
// the display gives a whole number. A window on no display (a Wayland window before it is
|
||||
// shown, or after its display went), or on one that is being read or has not answered, has
|
||||
// its density unread.
|
||||
let main = match &self.current {
|
||||
Some((c, scale)) => match read.iter().find(|(d, _)| d == c) {
|
||||
Some((d, Some(mm))) => ScreenPpi::Read(mm.and_then(|mm| points_per_inch(d.size, *scale, mm))),
|
||||
_ => ScreenPpi::Unread,
|
||||
},
|
||||
None => ScreenPpi::Unread,
|
||||
};
|
||||
// The displays where the last listing has them, each with what the reading of it gave; a
|
||||
// display the readings have not reached yet is unread.
|
||||
let listed = self.listed.as_deref().unwrap_or_default();
|
||||
let screens = listed
|
||||
.iter()
|
||||
.map(|d| {
|
||||
let [w, h] = [d.size.width, d.size.height].map(|v| i32::try_from(v).unwrap_or(i32::MAX));
|
||||
let scale = f64::from_bits(d.scale);
|
||||
let mm = read.iter().find(|(e, _)| e == d).and_then(|(_, mm)| *mm);
|
||||
let ppi = mm.map_or(ScreenPpi::Unread, |mm| ScreenPpi::Read(mm.and_then(|mm| points_per_inch(d.size, scale, mm))));
|
||||
ScreenDensity { rect: [d.position.x, d.position.y, w, h], scale, ppi }
|
||||
})
|
||||
.collect();
|
||||
let densities = Densities { main, screens };
|
||||
if self.reported.as_ref() == Some(&densities) {
|
||||
return None;
|
||||
}
|
||||
match main {
|
||||
ScreenPpi::Read(Some(p)) => log::info!("the window's display has {p:.1} points to an inch"),
|
||||
ScreenPpi::Read(None) => log::info!("the window's display reports no physical size; an inch is 96 points"),
|
||||
ScreenPpi::Unread => log::info!("the window's display has not been read; an inch is 96 points"),
|
||||
}
|
||||
self.reported = Some(densities.clone());
|
||||
Some(densities)
|
||||
}
|
||||
}
|
||||
|
||||
impl Tracker {
|
||||
/// What the last reading gave display `d`, when it answered.
|
||||
fn earlier(&self, d: &Display) -> Answer {
|
||||
self.read.as_ref()?.iter().find(|(e, _)| e == d)?.1
|
||||
}
|
||||
|
||||
/// Records that reading `displays` failed at `now`; they are read again after [`RETRY_AFTER`]
|
||||
/// seconds. After an earlier reading, they become the displays known, each with what that
|
||||
/// reading gave it, if anything. Before any reading, nothing is reported yet.
|
||||
fn fail(&mut self, displays: Vec<Display>, now: f64) {
|
||||
if self.read.is_some() {
|
||||
let read = displays.iter().map(|d| (d.clone(), self.earlier(d))).collect();
|
||||
self.read = Some(read);
|
||||
}
|
||||
self.failed = Some((displays, now));
|
||||
}
|
||||
}
|
||||
|
||||
/// The density, in points per inch, of a display `size` physical pixels wide and high, drawn at
|
||||
/// `scale` pixels to a point, that the system says is `mm` millimeters wide and high. `None` for a
|
||||
/// size that is no display's: zero or less, an aspect ratio given in place of the size (16 × 9,
|
||||
/// 160 × 90 and the like), axes whose densities disagree in either orientation, or a pixel density
|
||||
/// outside [`vectorcraft_ui_egui::state::SCREEN_PPI_RANGE`]. The range applies to the pixels, before
|
||||
/// the scale divides them into points. A display turned a quarter turn may report the size of its
|
||||
/// panel upright, so the axes are also tried swapped.
|
||||
pub(crate) fn points_per_inch(size: PhysicalSize<u32>, scale: f64, mm: [f64; 2]) -> Option<f64> {
|
||||
if !(scale.is_finite() && scale > 0.0) || mm.iter().any(|v| !(v.is_finite() && *v > 0.0)) || aspect_as_size(mm) {
|
||||
return None;
|
||||
}
|
||||
let pixels = [f64::from(size.width), f64::from(size.height)];
|
||||
let density = |[w, h]: [f64; 2]| [pixels[0] / (w / MM_PER_INCH), pixels[1] / (h / MM_PER_INCH)];
|
||||
let agree = |[x, y]: [f64; 2]| (x - y).abs() <= AXES_AGREE * x.max(y);
|
||||
let [x, y] = [density(mm), density([mm[1], mm[0]])].into_iter().find(|d| agree(*d))?;
|
||||
let ppi = (x + y) / 2.0;
|
||||
vectorcraft_ui_egui::state::SCREEN_PPI_RANGE.contains(&ppi).then_some(ppi / scale)
|
||||
}
|
||||
|
||||
/// Whether `mm` is an aspect ratio that a display's EDID gave in place of its size: 16:9, 16:10
|
||||
/// or 4:3, in centimeters or tenths of them.
|
||||
fn aspect_as_size(mm: [f64; 2]) -> bool {
|
||||
const RATIOS: [[f64; 2]; 3] = [[16.0, 9.0], [16.0, 10.0], [4.0, 3.0]];
|
||||
let sorted = if mm[0] >= mm[1] { mm } else { [mm[1], mm[0]] };
|
||||
RATIOS.iter().any(|r| [1.0, 10.0].iter().any(|k| sorted == [r[0] * k, r[1] * k]))
|
||||
}
|
||||
|
||||
/// Whether `window` is a Wayland window, whose displays the compositor describes.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn is_wayland(window: &winit::window::Window) -> bool {
|
||||
use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle};
|
||||
window.window_handle().ok().is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Wayland(_)))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn is_wayland(_: &winit::window::Window) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The system's id of `monitor`: the display id on macOS, the monitor handle on Windows, the RandR
|
||||
/// CRTC on X11.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn native_id(monitor: &MonitorHandle) -> i64 {
|
||||
use winit::platform::macos::MonitorHandleExtMacOS as _;
|
||||
i64::from(monitor.native_id())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn native_id(monitor: &MonitorHandle) -> i64 {
|
||||
use winit::platform::windows::MonitorHandleExtWindows as _;
|
||||
monitor.hmonitor() as i64
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn native_id(monitor: &MonitorHandle) -> i64 {
|
||||
use winit::platform::x11::MonitorHandleExtX11 as _;
|
||||
i64::from(monitor.native_id())
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", windows, target_os = "linux")))]
|
||||
fn native_id(_: &MonitorHandle) -> i64 {
|
||||
0
|
||||
}
|
||||
|
||||
/// The physical width and height, in millimeters, the system reports for each of `displays`.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn read_all(displays: &[Display], _: bool) -> Reading {
|
||||
Ok(displays
|
||||
.iter()
|
||||
.map(|d| {
|
||||
Ok(u32::try_from(d.id).ok().map(|id| {
|
||||
let size = objc2_core_graphics::CGDisplayScreenSize(id);
|
||||
[size.width, size.height]
|
||||
}))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn read_all(displays: &[Display], _: bool) -> Reading {
|
||||
Ok(displays
|
||||
.iter()
|
||||
.map(|d| {
|
||||
let dpi = crate::windows_display_size::raw_dpi(d.id as isize)?;
|
||||
Ok(dpi.map(|[x, y]| [f64::from(d.size.width) / x * MM_PER_INCH, f64::from(d.size.height) / y * MM_PER_INCH]))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn read_all(displays: &[Display], wayland: bool) -> Reading {
|
||||
if wayland { wayland::read_all(displays) } else { x11::read_all(displays) }
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", windows, target_os = "linux")))]
|
||||
fn read_all(displays: &[Display], _: bool) -> Reading {
|
||||
Ok(displays.iter().map(|_| Ok(None)).collect())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod x11 {
|
||||
use x11rb::CURRENT_TIME;
|
||||
use x11rb::protocol::randr;
|
||||
|
||||
use super::{Display, Reading, Size};
|
||||
|
||||
/// The millimeters RandR reports for the first output of each display's CRTC.
|
||||
pub(super) fn read_all(displays: &[Display]) -> Reading {
|
||||
let (conn, _) = x11rb::connect(None).map_err(|e| format!("couldn't connect to the X11 display: {e}"))?;
|
||||
let ask = |e: x11rb::errors::ConnectionError| format!("couldn't ask the X11 display: {e}");
|
||||
// RandR answers only a client that gave the version it speaks; 1.2 has CRTCs and outputs.
|
||||
randr::query_version(&conn, 1, 2).map_err(ask)?.reply().map_err(|e| format!("the X11 display has no RandR 1.2: {e}"))?;
|
||||
let size = |d: &Display| -> Size {
|
||||
let Ok(crtc) = u32::try_from(d.id) else { return Ok(None) };
|
||||
let info = randr::get_crtc_info(&conn, crtc, CURRENT_TIME)
|
||||
.map_err(ask)?
|
||||
.reply()
|
||||
.map_err(|e| format!("the X11 display has no such CRTC: {e}"))?;
|
||||
let Some(output) = info.outputs.first() else { return Ok(None) };
|
||||
let info = randr::get_output_info(&conn, *output, CURRENT_TIME)
|
||||
.map_err(ask)?
|
||||
.reply()
|
||||
.map_err(|e| format!("the X11 display has no such output: {e}"))?;
|
||||
Ok(Some([f64::from(info.mm_width), f64::from(info.mm_height)]))
|
||||
};
|
||||
Ok(displays.iter().map(size).collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod wayland {
|
||||
use wayland_client::globals::{GlobalListContents, registry_queue_init};
|
||||
use wayland_client::protocol::wl_output::{self, WlOutput};
|
||||
use wayland_client::protocol::wl_registry::{self, WlRegistry};
|
||||
use wayland_client::{Connection, Dispatch, QueueHandle};
|
||||
|
||||
use super::{Display, Reading};
|
||||
|
||||
/// The physical size the compositor gives for the output of each display's name, asked on a
|
||||
/// connection of its own; with no name, or a compositor that names no outputs, the only
|
||||
/// output's.
|
||||
pub(super) fn read_all(displays: &[Display]) -> Reading {
|
||||
let conn = Connection::connect_to_env().map_err(|e| format!("no Wayland compositor: {e}"))?;
|
||||
let (globals, mut queue) = registry_queue_init::<Outputs>(&conn).map_err(|e| e.to_string())?;
|
||||
let qh = queue.handle();
|
||||
let mut state = Outputs::default();
|
||||
for global in globals.contents().clone_list().into_iter().filter(|g| g.interface == "wl_output") {
|
||||
// Version 4 names the output; older ones give its size only.
|
||||
let output: WlOutput = globals.registry().bind(global.name, global.version.min(4), &qh, state.outputs.len());
|
||||
state.outputs.push((output, Output::default()));
|
||||
}
|
||||
// The compositor sends each output's geometry, name and `done` in reply to the bind.
|
||||
queue.roundtrip(&mut state).map_err(|e| e.to_string())?;
|
||||
let found: Vec<&Output> = state.outputs.iter().map(|(_, o)| o).collect();
|
||||
let named = found.iter().any(|o| o.name.is_some());
|
||||
Ok(displays
|
||||
.iter()
|
||||
.map(|d| {
|
||||
let pick = match d.name.as_deref() {
|
||||
Some(name) if named => found.iter().find(|o| o.name.as_deref() == Some(name)),
|
||||
_ if found.len() == 1 => found.first(),
|
||||
_ => None,
|
||||
};
|
||||
Ok(pick.and_then(|o| o.mm))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// One output's name and physical size.
|
||||
#[derive(Default)]
|
||||
struct Output {
|
||||
name: Option<String>,
|
||||
mm: Option<[f64; 2]>,
|
||||
}
|
||||
|
||||
/// The outputs bound, each with what its events gave.
|
||||
#[derive(Default)]
|
||||
struct Outputs {
|
||||
outputs: Vec<(WlOutput, Output)>,
|
||||
}
|
||||
|
||||
impl Dispatch<WlRegistry, GlobalListContents> for Outputs {
|
||||
fn event(_: &mut Self, _: &WlRegistry, _: wl_registry::Event, _: &GlobalListContents, _: &Connection, _: &QueueHandle<Self>) {}
|
||||
}
|
||||
|
||||
impl Dispatch<WlOutput, usize> for Outputs {
|
||||
fn event(state: &mut Self, _: &WlOutput, event: wl_output::Event, index: &usize, _: &Connection, _: &QueueHandle<Self>) {
|
||||
let Some((_, output)) = state.outputs.get_mut(*index) else { return };
|
||||
match event {
|
||||
wl_output::Event::Geometry { physical_width, physical_height, .. } => {
|
||||
output.mm = Some([f64::from(physical_width), f64::from(physical_height)]);
|
||||
}
|
||||
wl_output::Event::Name { name } => output.name = Some(name),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::cell::Cell;
|
||||
use std::sync::mpsc::{Sender, channel};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A 14-inch laptop panel at twice its points: 3024 × 1964 pixels, 302 × 196 mm, draws 127
|
||||
/// points to an inch, more than the 96 a fixed inch assumes.
|
||||
#[test]
|
||||
fn a_laptop_panel_has_more_points_to_an_inch_than_the_reference() {
|
||||
let ppi = points_per_inch(PhysicalSize::new(3024, 1964), 2.0, [302.0, 196.0]);
|
||||
assert!(ppi.is_some_and(|p| p > 96.0 && (p - 1512.0 / (302.0 / MM_PER_INCH)).abs() < 1.0), "{ppi:?}");
|
||||
}
|
||||
|
||||
/// The same display in a scaled mode (more points on the same glass) draws more points to an
|
||||
/// inch, and at a higher scale factor fewer: the density counts the window's points.
|
||||
#[test]
|
||||
fn the_density_counts_points_at_the_windows_scale() {
|
||||
let at = |w, h, scale| points_per_inch(PhysicalSize::new(w, h), scale, [527.0, 296.0]).unwrap_or(0.0);
|
||||
assert!(at(1920, 1080, 1.0) > 0.0);
|
||||
assert!(at(2560, 1440, 1.0) > at(1920, 1080, 1.0), "more pixels on the same glass");
|
||||
assert!(at(3840, 2160, 2.0) < at(3840, 2160, 1.5), "a larger scale factor makes each point larger");
|
||||
}
|
||||
|
||||
/// A display turned a quarter turn whose system reports its panel's size upright still
|
||||
/// measures; axes that disagree either way do not.
|
||||
#[test]
|
||||
fn a_turned_display_measures_and_disagreeing_axes_do_not() {
|
||||
let upright = points_per_inch(PhysicalSize::new(1920, 1080), 1.0, [527.0, 296.0]);
|
||||
let turned = points_per_inch(PhysicalSize::new(1080, 1920), 1.0, [527.0, 296.0]);
|
||||
assert!(upright.is_some() && turned.is_some());
|
||||
assert!((upright.unwrap_or(0.0) - turned.unwrap_or(1.0)).abs() < 1e-9);
|
||||
assert_eq!(points_per_inch(PhysicalSize::new(1920, 1080), 1.0, [527.0, 527.0]), None);
|
||||
}
|
||||
|
||||
/// Sizes no display has give no density: none, an aspect ratio in place of the size, and
|
||||
/// densities past the range a display can have.
|
||||
#[test]
|
||||
fn reports_that_are_no_displays_size_give_no_density() {
|
||||
let at = |mm| points_per_inch(PhysicalSize::new(1920, 1080), 1.0, mm);
|
||||
for mm in [[0.0, 0.0], [-1.0, 300.0], [f64::NAN, 300.0], [160.0, 90.0], [16.0, 9.0], [160.0, 100.0], [40.0, 30.0], [9.0, 16.0]] {
|
||||
assert_eq!(at(mm), None, "{mm:?}");
|
||||
}
|
||||
assert_eq!(points_per_inch(PhysicalSize::new(1920, 1080), 0.0, [527.0, 296.0]), None, "no scale");
|
||||
assert_eq!(points_per_inch(PhysicalSize::new(100, 56), 1.0, [5270.0, 2960.0]), None, "under the range");
|
||||
assert_eq!(points_per_inch(PhysicalSize::new(7680, 4320), 1.0, [53.0, 30.0]), None, "over it");
|
||||
}
|
||||
|
||||
/// The range applies to the display's pixels: a 1920 × 1080 display of 527 × 296 mm drawn at
|
||||
/// scale 4 has about 23 points to an inch, which is a real density.
|
||||
#[test]
|
||||
fn a_large_scale_factor_does_not_put_a_display_out_of_range() {
|
||||
let ppi = points_per_inch(PhysicalSize::new(1920, 1080), 4.0, [527.0, 296.0]);
|
||||
let pixels = points_per_inch(PhysicalSize::new(1920, 1080), 1.0, [527.0, 296.0]).unwrap_or(0.0);
|
||||
assert!(ppi.is_some_and(|p| p < 30.0 && (p - pixels / 4.0).abs() < 1e-9), "{ppi:?}");
|
||||
let print = vectorcraft_ui_egui::state::print_ppi(true, ppi);
|
||||
assert_eq!(print, ppi, "Actual Size counts from it, not from 96");
|
||||
}
|
||||
|
||||
/// A 1920 × 1080 display at scale 1 and position `x`, named `name`.
|
||||
fn display(name: &str, x: i32) -> Display {
|
||||
Display {
|
||||
name: Some(name.into()),
|
||||
position: PhysicalPosition::new(x, 0),
|
||||
size: PhysicalSize::new(1920, 1080),
|
||||
scale: 1.0f64.to_bits(),
|
||||
id: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The sizes of a 24-inch display (about 92 points to an inch) and a 27-inch one (about 82).
|
||||
const SIZES: [[f64; 2]; 2] = [[531.0, 299.0], [598.0, 336.0]];
|
||||
|
||||
/// A reading that gives every display one of [`SIZES`], in turn.
|
||||
fn sizes(n: usize) -> Reading {
|
||||
Ok((0..n).map(|i| Ok(Some(SIZES[i % SIZES.len()]))).collect())
|
||||
}
|
||||
|
||||
/// Drives a tracker: counts its listings and readings, and hands out the sender of the reading
|
||||
/// it started last.
|
||||
struct Rig {
|
||||
tracker: Tracker,
|
||||
displays: Vec<Display>,
|
||||
current: usize,
|
||||
/// The window's display as winit last gave it, when that lags behind the listing.
|
||||
lagging: Option<Display>,
|
||||
window_scale: f64,
|
||||
lists: Cell<usize>,
|
||||
reads: Cell<usize>,
|
||||
sender: Option<Sender<Reading>>,
|
||||
fail_to_start: bool,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
tracker: Tracker::default(),
|
||||
displays: vec![display("left", 0), display("right", 1920)],
|
||||
current: 0,
|
||||
lagging: None,
|
||||
window_scale: 1.0,
|
||||
lists: Cell::new(0),
|
||||
reads: Cell::new(0),
|
||||
sender: None,
|
||||
fail_to_start: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn tick(&mut self, now: f64, enabled: bool) -> Option<Densities> {
|
||||
let current = self.lagging.clone().or_else(|| self.displays.get(self.current).cloned());
|
||||
let (displays, scale) = (self.displays.clone(), self.window_scale);
|
||||
let (lists, reads, fail) = (&self.lists, &self.reads, self.fail_to_start);
|
||||
let mut sender = None;
|
||||
let out = self.tracker.update(
|
||||
now,
|
||||
enabled,
|
||||
|| {
|
||||
lists.set(lists.get() + 1);
|
||||
Some((displays, current, scale))
|
||||
},
|
||||
|_| {
|
||||
reads.set(reads.get() + 1);
|
||||
if fail {
|
||||
return Err("no thread".into());
|
||||
}
|
||||
let (tx, rx) = channel();
|
||||
sender = Some(tx);
|
||||
Ok(rx)
|
||||
},
|
||||
);
|
||||
if sender.is_some() {
|
||||
self.sender = sender;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn finish(&mut self, reading: Reading) {
|
||||
if let Some(tx) = self.sender.take() {
|
||||
tx.send(reading).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The first listing starts a reading, and the densities arrive once the reading ends, without
|
||||
/// a frame waiting for it. The main window's density is its display's, and every display gets
|
||||
/// its own.
|
||||
#[test]
|
||||
fn the_densities_arrive_when_the_reading_ends() {
|
||||
let mut rig = Rig::new();
|
||||
assert_eq!(rig.tick(0.0, true), None, "the reading runs in the background");
|
||||
assert_eq!(rig.reads.get(), 1);
|
||||
assert_eq!(rig.tick(2.0, true), None, "still running: no second reading");
|
||||
assert_eq!(rig.reads.get(), 1);
|
||||
rig.finish(sizes(2));
|
||||
let got = rig.tick(2.1, true).unwrap_or_else(|| panic!("the densities"));
|
||||
let ppi = got.screens.iter().map(|s| s.ppi.ppi().unwrap_or(0.0)).collect::<Vec<_>>();
|
||||
assert!(ppi[0] > ppi[1] && ppi[1] > 0.0, "the smaller display is denser: {ppi:?}");
|
||||
assert_eq!(got.main, ScreenPpi::Read(Some(ppi[0])), "the main window is on the left display");
|
||||
assert_eq!(got.screens[1].rect, [1920, 0, 1920, 1080]);
|
||||
assert_eq!(rig.tick(5.0, true), None, "nothing changed");
|
||||
assert_eq!(rig.reads.get(), 1, "the same displays are not read again");
|
||||
assert_eq!(rig.tick(5.2, false), None, "off, nothing is reported");
|
||||
assert_eq!(rig.tick(5.4, true), None, "turned on again, the displays are read again at once");
|
||||
assert_eq!(rig.reads.get(), 2);
|
||||
rig.finish(sizes(2));
|
||||
assert_eq!(rig.tick(5.5, true), Some(got), "and the densities reported anew");
|
||||
}
|
||||
|
||||
/// The displays are listed at most once a second, and not at all with the preference off.
|
||||
#[test]
|
||||
fn the_displays_are_listed_once_a_second_while_the_preference_is_on() {
|
||||
let mut rig = Rig::new();
|
||||
rig.tick(0.0, true);
|
||||
rig.tick(0.5, true);
|
||||
assert_eq!(rig.lists.get(), 1);
|
||||
rig.tick(1.0, true);
|
||||
assert_eq!(rig.lists.get(), 2);
|
||||
rig.tick(5.0, false);
|
||||
assert_eq!(rig.lists.get(), 2, "off, nothing is asked of the system");
|
||||
}
|
||||
|
||||
/// The main window moving to the other display reports that display's density without a new
|
||||
/// reading; a display joining the list is read again, and while a display that changed is
|
||||
/// read, the densities reported before stay.
|
||||
#[test]
|
||||
fn a_change_of_display_is_reported() {
|
||||
let mut rig = Rig::new();
|
||||
rig.tick(0.0, true);
|
||||
rig.finish(sizes(2));
|
||||
let left = rig.tick(0.1, true).and_then(|d| d.main.ppi());
|
||||
rig.current = 1;
|
||||
let right = rig.tick(1.5, true).and_then(|d| d.main.ppi());
|
||||
assert!(left.is_some() && right.is_some() && left != right, "{left:?} then {right:?}");
|
||||
assert_eq!(rig.reads.get(), 1);
|
||||
// A window drawn at 1.5 pixels a point (a fractional scale the display does not list)
|
||||
// has fewer points to an inch than the display's own scale of 1 gives.
|
||||
rig.window_scale = 1.5;
|
||||
let scaled = rig.tick(2.6, true).and_then(|d| d.main.ppi());
|
||||
assert!(scaled.zip(right).is_some_and(|(s, r)| (s * 1.5 - r).abs() < 1e-9), "{scaled:?} at 1.5, {right:?} at 1");
|
||||
rig.window_scale = 1.0;
|
||||
rig.displays.push(display("third", 3840));
|
||||
rig.tick(4.0, true);
|
||||
assert_eq!(rig.reads.get(), 2, "a new display is read");
|
||||
rig.finish(sizes(3));
|
||||
rig.tick(4.5, true);
|
||||
// The window's display changes resolution: until it is read again its density is unread.
|
||||
rig.displays[1].size = PhysicalSize::new(2560, 1440);
|
||||
assert_eq!(rig.tick(6.0, true).map(|d| d.main), Some(ScreenPpi::Unread), "the display is being read");
|
||||
assert_eq!(rig.reads.get(), 3);
|
||||
rig.finish(sizes(3));
|
||||
let sharper = rig.tick(6.1, true).and_then(|d| d.main.ppi());
|
||||
assert!(sharper.zip(right).is_some_and(|(s, r)| s > r), "more pixels on the same glass: {sharper:?}, {right:?}");
|
||||
// winit still gives the window's display at its old resolution: it is found by its name.
|
||||
let mut old = rig.displays[1].clone();
|
||||
old.size = PhysicalSize::new(1920, 1080);
|
||||
rig.lagging = Some(old);
|
||||
rig.window_scale = 1.25;
|
||||
let lagging = rig.tick(7.2, true).and_then(|d| d.main.ppi());
|
||||
assert!(lagging.zip(sharper).is_some_and(|(l, s)| (l * 1.25 - s).abs() < 1e-9), "{lagging:?} from {sharper:?}");
|
||||
rig.lagging = None;
|
||||
// It changes again and this time the reading fails: its density is unread.
|
||||
rig.displays[1].size = PhysicalSize::new(3840, 2160);
|
||||
let reading = rig.tick(8.5, true).unwrap_or_else(|| panic!("a report"));
|
||||
assert_eq!(reading.main, ScreenPpi::Unread, "the display is being read: {reading:?}");
|
||||
assert!(reading.screens.iter().any(|s| s.rect[2] == 3840 && s.ppi == ScreenPpi::Unread), "listed where it is now, unread: {reading:?}");
|
||||
rig.finish(Err("the display server went away".into()));
|
||||
assert_eq!(rig.tick(8.6, true), None, "the failed reading leaves it unread");
|
||||
}
|
||||
|
||||
/// A display that changes while a reading runs is read as soon as that reading ends.
|
||||
#[test]
|
||||
fn a_change_during_a_reading_is_read_when_it_ends() {
|
||||
let mut rig = Rig::new();
|
||||
rig.tick(0.0, true);
|
||||
rig.displays[1].size = PhysicalSize::new(2560, 1440);
|
||||
rig.tick(1.0, true);
|
||||
assert_eq!(rig.reads.get(), 1, "one reading at a time");
|
||||
rig.finish(sizes(2));
|
||||
rig.tick(1.2, true);
|
||||
assert_eq!(rig.reads.get(), 2, "the changed display is read at once");
|
||||
}
|
||||
|
||||
/// A display whose size could not be read does not hold back the others, and the displays are
|
||||
/// read again after a while.
|
||||
#[test]
|
||||
fn one_display_that_fails_leaves_the_others() {
|
||||
let mut rig = Rig::new();
|
||||
rig.tick(0.0, true);
|
||||
rig.finish(Ok(vec![Ok(Some(SIZES[0])), Err("no answer".into())]));
|
||||
let got = rig.tick(0.1, true).unwrap_or_else(|| panic!("the densities"));
|
||||
assert!(got.main.ppi().is_some() && got.screens[1].ppi == ScreenPpi::Unread, "the display that did not answer is unread: {got:?}");
|
||||
rig.tick(5.0, true);
|
||||
assert_eq!(rig.reads.get(), 1, "not again at once");
|
||||
rig.tick(0.1 + RETRY_AFTER, true);
|
||||
assert_eq!(rig.reads.get(), 2, "tried again");
|
||||
rig.finish(sizes(2));
|
||||
let full = rig.tick(11.0, true).unwrap_or_else(|| panic!("the densities"));
|
||||
assert!(full.screens.iter().all(|s| s.ppi.ppi().is_some()), "{full:?}");
|
||||
rig.tick(30.0, true);
|
||||
assert_eq!(rig.reads.get(), 2, "and left alone once every display was read");
|
||||
// A display joins, and the window's display, unchanged, fails to answer: it keeps its size.
|
||||
rig.displays.push(display("third", 3840));
|
||||
rig.tick(32.0, true);
|
||||
rig.finish(Ok(vec![Err("no answer".into()), Ok(Some(SIZES[1])), Ok(Some(SIZES[0]))]));
|
||||
let kept = rig.tick(32.1, true).unwrap_or_else(|| panic!("the densities"));
|
||||
assert!(kept.main.ppi().is_some() && kept.main == full.main, "{kept:?}");
|
||||
// A window on no display has its density unread.
|
||||
rig.current = 9;
|
||||
assert_eq!(rig.tick(34.0, true).map(|d| d.main), Some(ScreenPpi::Unread));
|
||||
// The window's display fails to answer the first reading: its density is unread, not a
|
||||
// display without a size.
|
||||
let mut rig = Rig::new();
|
||||
rig.tick(0.0, true);
|
||||
rig.finish(Ok(vec![Err("no answer".into()), Ok(Some(SIZES[1]))]));
|
||||
let first = rig.tick(0.1, true).unwrap_or_else(|| panic!("the densities"));
|
||||
assert_eq!((first.main, first.screens[0].ppi), (ScreenPpi::Unread, ScreenPpi::Unread), "{first:?}");
|
||||
}
|
||||
|
||||
/// A reading that fails, or a thread that cannot start, is tried again after a while; the
|
||||
/// same displays are not read on every listing until then.
|
||||
#[test]
|
||||
fn a_failed_reading_is_tried_again() {
|
||||
let mut rig = Rig::new();
|
||||
rig.tick(0.0, true);
|
||||
rig.finish(Err("the display server went away".into()));
|
||||
assert_eq!(rig.tick(1.0, true), None);
|
||||
assert_eq!(rig.reads.get(), 1, "not again at once");
|
||||
rig.tick(5.0, true);
|
||||
assert_eq!(rig.reads.get(), 1);
|
||||
rig.tick(1.0 + RETRY_AFTER, true);
|
||||
assert_eq!(rig.reads.get(), 2, "tried again");
|
||||
rig.finish(sizes(2));
|
||||
assert!(rig.tick(12.0, true).is_some_and(|d| d.main.ppi().is_some()), "and read");
|
||||
let mut rig = Rig::new();
|
||||
rig.fail_to_start = true;
|
||||
rig.tick(0.0, true);
|
||||
rig.tick(1.0 + RETRY_AFTER, true);
|
||||
assert_eq!(rig.reads.get(), 2, "a thread that did not start is tried again too");
|
||||
}
|
||||
|
||||
/// Displays that list the same are read again a while after the last reading, so a display
|
||||
/// replaced by one on the same connector at the same resolution and scale gets its own size.
|
||||
#[test]
|
||||
fn displays_that_list_the_same_are_read_again_after_a_while() {
|
||||
let mut rig = Rig::new();
|
||||
rig.tick(0.0, true);
|
||||
rig.finish(sizes(2));
|
||||
let first = rig.tick(0.1, true).unwrap_or_else(|| panic!("the densities"));
|
||||
rig.tick(0.1 + READ_AGAIN_AFTER - 1.0, true);
|
||||
assert_eq!(rig.reads.get(), 1, "not before the time is up");
|
||||
rig.tick(0.1 + READ_AGAIN_AFTER, true);
|
||||
assert_eq!(rig.reads.get(), 2, "read again");
|
||||
rig.finish(Ok(vec![Ok(Some(SIZES[1])), Ok(Some(SIZES[0]))]));
|
||||
let replaced = rig.tick(0.2 + READ_AGAIN_AFTER, true).unwrap_or_else(|| panic!("the densities"));
|
||||
assert!(replaced.main.ppi().is_some() && replaced.main != first.main, "the new panel's density: {first:?} then {replaced:?}");
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Windows: a monitor's raw density, the pixels per inch of the screen itself as Windows reads it
|
||||
//! from the monitor, for Display Print Size at 100% Zoom (`crate::screen_density`).
|
||||
//!
|
||||
//! `GetDpiForMonitor` is a C API with no safe binding, hence the scoped `unsafe_code` allowance.
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use windows::Win32::Graphics::Gdi::HMONITOR;
|
||||
use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MDT_RAW_DPI};
|
||||
|
||||
/// The horizontal and vertical pixels per inch of the monitor winit's handle `monitor` names:
|
||||
/// `None` when Windows reports no density for it, an error when the call fails.
|
||||
pub(crate) fn raw_dpi(monitor: isize) -> Result<Option<[f64; 2]>, String> {
|
||||
let (mut x, mut y) = (0u32, 0u32);
|
||||
// SAFETY: `monitor` is a handle winit got from Windows for a connected monitor; a handle that
|
||||
// has gone stale makes the call fail, which returns an error. Both pointers point at live
|
||||
// `u32`s for the length of the call.
|
||||
unsafe { GetDpiForMonitor(HMONITOR(monitor as *mut core::ffi::c_void), MDT_RAW_DPI, &mut x, &mut y) }
|
||||
.map_err(|e| format!("couldn't read a monitor's density: {e}"))?;
|
||||
Ok((x > 0 && y > 0).then(|| [f64::from(x), f64::from(y)]))
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -0,0 +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="M19 12H5M10.5 6.5L5 12L10.5 17.5" stroke-width="1.6" /></svg>
|
||||
|
After Width: | Height: | Size: 253 B |
@@ -0,0 +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="M5 12H19M13.5 6.5L19 12L13.5 17.5" stroke-width="1.6" /></svg>
|
||||
|
After Width: | Height: | Size: 254 B |
@@ -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 @@
|
||||
<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 @@
|
||||
<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 |
@@ -0,0 +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="round" stroke-linejoin="round"><rect x="3" y="3" width="4" height="18"/><path d="M5 6.5h2M5 9.5h2M5 14.5h2M5 17.5h2"/><path d="M9.5 12H21"/></svg>
|
||||
|
After Width: | Height: | Size: 299 B |
@@ -0,0 +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="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="4"/><path d="M6.5 5v2M9.5 5v2M14.5 5v2M17.5 5v2"/><path d="M12 9.5V21"/></svg>
|
||||
|
After Width: | Height: | Size: 299 B |
@@ -309,7 +309,7 @@ pub struct Scatter {
|
||||
pub art: Node,
|
||||
/// Size range in percent of the art.
|
||||
pub size: (f64, f64),
|
||||
/// Spacing range in percent of the (scaled) art width.
|
||||
/// Spacing range in percent of the (scaled) art width, its strokes included.
|
||||
pub spacing: (f64, f64),
|
||||
/// Perpendicular offset range in percent of the (scaled) art height.
|
||||
pub scatter: (f64, f64),
|
||||
|
||||
@@ -272,6 +272,22 @@ fn scatter_count_and_spacing() {
|
||||
assert_eq!(out.len(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_spaces_stroked_art_by_its_stroked_width() {
|
||||
let art = Node::path(
|
||||
NodeId(0),
|
||||
shapes::rectangle(Rect::new(0.0, -2.0, 10.0, 2.0)),
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0),
|
||||
);
|
||||
let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) };
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 120.0, 0.0), &stroke(1.0));
|
||||
let boxes: Vec<Rect> = out.iter().filter_map(Node::visual_bounds).collect();
|
||||
assert!(boxes.len() > 1, "{boxes:?}");
|
||||
for w in boxes.windows(2) {
|
||||
assert!(near(w[1].x0, w[0].x1, 1e-6), "stroked copies at 100% spacing touch: {boxes:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_is_deterministic_and_randomised() {
|
||||
let b = Brush {
|
||||
|
||||
@@ -540,7 +540,10 @@ fn vary(rng: &mut Rng, (a, b): (f64, f64), mode: Variation, pen: PenAt) -> f64 {
|
||||
|
||||
pub(crate) fn scatter(sc: &Scatter, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec<Node> {
|
||||
let Some(b) = sc.art.geometric_bounds() else { return vec![] };
|
||||
let (aw, ah) = (b.width().max(1e-3), b.height().max(1e-3));
|
||||
// Copies are spaced by the width of the art with its strokes, so at 100% spacing stroked
|
||||
// copies touch instead of overlapping by the stroke.
|
||||
let aw = sc.art.visual_bounds().unwrap_or(b).width().max(1e-3);
|
||||
let ah = b.height().max(1e-3);
|
||||
let mut rng = Rng::new(seed_of(bp, name));
|
||||
let [size_mode, spacing_mode, scatter_mode, rotation_mode] = sc.modes();
|
||||
let mut out = Budget::default();
|
||||
@@ -1129,11 +1132,23 @@ mod tests {
|
||||
/// Fitting is bounded however badly the map behaves: where it gives points that are not finite
|
||||
/// the tile falls back to chords with those points left out (or to nothing), and where it never
|
||||
/// fits (a map that jumps everywhere) the halving stops at its depth and anchor count. Either
|
||||
/// way the call comes back promptly with finite geometry.
|
||||
/// way the call comes back with finite geometry, having called the map a bounded number of
|
||||
/// times.
|
||||
#[test]
|
||||
fn a_map_that_misbehaves_still_returns_promptly_and_finite() {
|
||||
let b = Rect::new(0.0, -20.0, 40.0, 20.0);
|
||||
let tile = circle_tile(b);
|
||||
// Each piece the fitting tries reads its two ends, the derivatives there and the checks
|
||||
// between them. Fitted pieces are at most the chords, so the halving tries at most twice
|
||||
// as many pieces plus those on the way down to the one that gives up. The chord route
|
||||
// maps each chord point once more.
|
||||
let NodeKind::Path { path, .. } = &tile.kind else { panic!("the tile is a path") };
|
||||
let allowed: usize = path
|
||||
.subpaths
|
||||
.iter()
|
||||
.filter_map(|sp| densified(sp, 0.25, 1.5))
|
||||
.map(|dense| 1 + (FIT_CHECKS + 3) * (2 * dense.len() + FIT_DEPTH as usize + 1) + dense.len())
|
||||
.sum();
|
||||
let finite = |n: &Node| match &n.kind {
|
||||
NodeKind::Path { path, .. } => {
|
||||
path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite())
|
||||
@@ -1147,9 +1162,14 @@ mod tests {
|
||||
&|_| Point::new(f64::NAN, f64::NAN),
|
||||
];
|
||||
for (i, f) in maps.iter().enumerate() {
|
||||
let t0 = std::time::Instant::now();
|
||||
let out = warp_node(&tile, f, 0.25, 1.5, 0.25, 1.0);
|
||||
assert!(t0.elapsed() < std::time::Duration::from_secs(2), "map {i} took {:?}", t0.elapsed());
|
||||
// Past the allowance the map places nothing, so a warp that keeps calling it stops.
|
||||
let calls = std::cell::Cell::new(0usize);
|
||||
let counted = |p: Point| {
|
||||
calls.set(calls.get() + 1);
|
||||
if calls.get() > allowed { Point::new(f64::NAN, f64::NAN) } else { f(p) }
|
||||
};
|
||||
let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0);
|
||||
assert!(calls.get() <= allowed, "map {i} was called {} times, {allowed} allowed", calls.get());
|
||||
match (i, &out) {
|
||||
(3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"),
|
||||
(_, Some(n)) => assert!(finite(n), "map {i} drew non-finite geometry"),
|
||||
|
||||
@@ -708,16 +708,29 @@ fn rgb_color([r, g, b]: [u8; 3]) -> Color {
|
||||
Color::rgb8(r, g, b)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many names [`unique`] tried on this thread (tests).
|
||||
pub(crate) static SYMBOL_NAMES_TRIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Whether `taken` holds `name`, counted as one name tried (tests).
|
||||
fn is_taken(taken: &HashSet<String>, name: &str) -> bool {
|
||||
#[cfg(test)]
|
||||
SYMBOL_NAMES_TRIED.with(|n| n.set(n.get().saturating_add(1)));
|
||||
taken.contains(name)
|
||||
}
|
||||
|
||||
/// `base`, or `base 2`, `base 3`… when taken; `next` remembers where each base left off.
|
||||
fn unique(base: &str, next: &mut HashMap<String, usize>, taken: &HashSet<String>) -> String {
|
||||
if !taken.contains(base) {
|
||||
if !is_taken(taken, base) {
|
||||
return base.to_string();
|
||||
}
|
||||
let i = next.entry(base.to_string()).or_insert(2);
|
||||
loop {
|
||||
let name = format!("{base} {i}");
|
||||
*i += 1;
|
||||
if !taken.contains(&name) {
|
||||
if !is_taken(taken, &name) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,6 +175,32 @@ fn layer(l: model::Layer) -> LayerDef {
|
||||
/// drawings have a few dozen layouts with short names.
|
||||
const MAX_LAYOUT_NAME_BYTES: usize = 4 << 20;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`layouts`] compared two layout names on this thread (tests).
|
||||
pub(crate) static LAYOUT_NAME_COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A paper layout's name as [`layouts`] de-duplicates it (lower case: names differing only in
|
||||
/// ASCII case are one layout).
|
||||
struct LayoutKey(String);
|
||||
|
||||
impl PartialEq for LayoutKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
#[cfg(test)]
|
||||
LAYOUT_NAME_COMPARISONS.with(|n| n.set(n.get().saturating_add(1)));
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for LayoutKey {}
|
||||
|
||||
impl std::hash::Hash for LayoutKey {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.0.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Model space, then each paper layout (its LAYOUT object, in tab order); a file without layout
|
||||
/// objects but with paper-space art has one paper layout.
|
||||
fn layouts(doc: &model::Document<'_>, block_names: &HashMap<u64, &str>) -> Vec<LayoutDef> {
|
||||
@@ -187,7 +213,7 @@ fn layouts(doc: &model::Document<'_>, block_names: &HashMap<u64, &str>) -> Vec<L
|
||||
continue;
|
||||
}
|
||||
let Some(block) = block else { continue };
|
||||
let key = l.name.to_ascii_lowercase();
|
||||
let key = LayoutKey(l.name.to_ascii_lowercase());
|
||||
let cost = l.name.len() + block.len();
|
||||
// A layout past the allowance is skipped alone: a later short one is still offered, and a
|
||||
// skipped one reserves neither its name nor its bytes.
|
||||
|
||||
@@ -743,15 +743,16 @@ fn many_by_block_looks_import_in_linear_time() {
|
||||
inserts.extend([(0, "INSERT"), (2, "Door"), (420, colour), (10, "0"), (20, "0")]);
|
||||
}
|
||||
let text = with_door(by_block, &inserts);
|
||||
let start = std::time::Instant::now();
|
||||
build::SYMBOL_NAMES_TRIED.with(|t| t.set(0));
|
||||
let doc = open(&text, &points()).document;
|
||||
let took = start.elapsed();
|
||||
let tried = build::SYMBOL_NAMES_TRIED.with(std::cell::Cell::get);
|
||||
let mut names: Vec<&str> = doc.symbols.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names.len(), n);
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
assert_eq!(names.len(), n, "names stay unique");
|
||||
assert!(took < std::time::Duration::from_secs(4), "import took {took:?}");
|
||||
// Each symbol after the first tries its label and then the next free suffix.
|
||||
assert!(tried < 2 * n, "{tried} names tried for {n} symbols");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1001,7 +1002,7 @@ fn binary_dwg_damaged_and_foreign_files() {
|
||||
// A binary DXF opens as its ASCII form does.
|
||||
let ascii = entities(LINE);
|
||||
let tags = craft_dxf::parse(&ascii).unwrap();
|
||||
let r = open(&craft_dxf::write_binary(&tags, true), &points());
|
||||
let r = open(&craft_dxf::write_binary(&tags, true).unwrap(), &points());
|
||||
assert_eq!(leaves(&r.document).len(), 1);
|
||||
let e = import(b"AC1032\x00\x00\x00", &ImportOptions::default()).unwrap_err();
|
||||
assert!(e.contains("DWG"), "{e}");
|
||||
@@ -1151,12 +1152,13 @@ fn with_layouts(names: &[String]) -> Vec<u8> {
|
||||
|
||||
#[test]
|
||||
fn many_paper_layouts_are_read_in_linear_time() {
|
||||
let names: Vec<String> = (0..100_000).map(|i| format!("L{i}")).collect();
|
||||
let names: Vec<String> = (0..10_000).map(|i| format!("L{i}")).collect();
|
||||
let bytes = with_layouts(&names);
|
||||
let t = std::time::Instant::now();
|
||||
reader::LAYOUT_NAME_COMPARISONS.with(|c| c.set(0));
|
||||
let info = info(&bytes).unwrap();
|
||||
let compared = reader::LAYOUT_NAME_COMPARISONS.with(std::cell::Cell::get);
|
||||
assert_eq!(info.layouts.len(), names.len() + 1);
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(5), "layout de-duplication is quadratic: {:?}", t.elapsed());
|
||||
assert!(compared <= names.len(), "layout de-duplication compared {compared} names for {} layouts", names.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -22,3 +22,4 @@ moxcms = "0.8"
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
sha2 = { version = "0.10", default-features = false }
|
||||
@@ -0,0 +1,2 @@
|
||||
# The characterization data files are kept byte for byte as published (CRLF line endings).
|
||||
*.txt -text
|
||||
@@ -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, ©right, 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,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))
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ pub mod oklab;
|
||||
pub mod palette_io;
|
||||
pub mod recolor;
|
||||
pub mod swatch;
|
||||
pub mod wcag;
|
||||
|
||||
pub use blend::BlendMode;
|
||||
pub use freeform::{Freeform, FreeformMode, FreeformPoint};
|
||||
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//! Contrast between two colors as WCAG 2 measures it (<https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio>):
|
||||
//! the relative luminance of display sRGB with the 0.04045 threshold, the ratio
|
||||
//! (L1 + 0.05) / (L2 + 0.05) from 1 to 21, and the minimum ratios of success criteria 1.4.3
|
||||
//! (Contrast (Minimum), AA), 1.4.6 (Contrast (Enhanced), AAA) and 1.4.11 (Non-text Contrast, AA).
|
||||
|
||||
/// What the content in front is, which sets the ratio it needs.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Category {
|
||||
/// Text below the large-scale size: AA 4.5:1, AAA 7:1.
|
||||
#[default]
|
||||
NormalText,
|
||||
/// Large-scale text (at least 18 pt, or 14 pt bold): AA 3:1, AAA 4.5:1.
|
||||
LargeText,
|
||||
/// User interface components and graphical objects: AA 3:1, no AAA level.
|
||||
Graphics,
|
||||
}
|
||||
|
||||
impl Category {
|
||||
pub const ALL: [Category; 3] = [Category::NormalText, Category::LargeText, Category::Graphics];
|
||||
|
||||
/// The id commands and settings use.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Category::NormalText => "normalText",
|
||||
Category::LargeText => "largeText",
|
||||
Category::Graphics => "graphics",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|c| c.id() == s)
|
||||
}
|
||||
|
||||
/// The English name shown in menus.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Category::NormalText => "Normal Text",
|
||||
Category::LargeText => "Large Text",
|
||||
Category::Graphics => "Graphics",
|
||||
}
|
||||
}
|
||||
|
||||
/// The minimum ratio for AA, and for AAA where the category has that level.
|
||||
pub fn minimums(self) -> (f64, Option<f64>) {
|
||||
match self {
|
||||
Category::NormalText => (4.5, Some(7.0)),
|
||||
Category::LargeText => (3.0, Some(4.5)),
|
||||
Category::Graphics => (3.0, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `ratio` meets AA, and AAA where the category has that level. The unrounded ratio
|
||||
/// is compared, so 4.499:1 fails 4.5:1.
|
||||
pub fn passes(self, ratio: f64) -> (bool, Option<bool>) {
|
||||
let (aa, aaa) = self.minimums();
|
||||
(ratio >= aa, aaa.map(|m| ratio >= m))
|
||||
}
|
||||
}
|
||||
|
||||
/// The relative luminance of display sRGB `srgb` (each channel 0 to 1), from 0 for black to 1
|
||||
/// for white.
|
||||
pub fn relative_luminance(srgb: [f32; 3]) -> f64 {
|
||||
let lin = |v: f32| {
|
||||
let v = f64::from(v.clamp(0.0, 1.0));
|
||||
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
|
||||
};
|
||||
0.2126 * lin(srgb[0]) + 0.7152 * lin(srgb[1]) + 0.0722 * lin(srgb[2])
|
||||
}
|
||||
|
||||
/// The contrast ratio of display sRGB colors `a` and `b`, from 1 to 21, whichever is lighter.
|
||||
pub fn contrast_ratio(a: [f32; 3], b: [f32; 3]) -> f64 {
|
||||
let (la, lb) = (relative_luminance(a), relative_luminance(b));
|
||||
(la.max(lb) + 0.05) / (la.min(lb) + 0.05)
|
||||
}
|
||||
|
||||
/// Display sRGB `fg` drawn at `opacity` (0 to 1) over the opaque `bg`, mixed per channel as the
|
||||
/// canvas mixes a translucent color.
|
||||
pub fn over(fg: [f32; 3], opacity: f32, bg: [f32; 3]) -> [f32; 3] {
|
||||
let a = if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 1.0 };
|
||||
std::array::from_fn(|i| fg[i] * a + bg[i] * (1.0 - a))
|
||||
}
|
||||
|
||||
/// `ratio` as text with two decimals, cut off rather than rounded, so a ratio just under a
|
||||
/// minimum never reads as the minimum: 4.4963 is "4.49:1".
|
||||
pub fn ratio_text(ratio: f64) -> String {
|
||||
let r = if ratio.is_finite() { ratio.clamp(1.0, 21.0) } else { 1.0 };
|
||||
format!("{:.2}:1", (r * 100.0).floor() / 100.0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn hex(s: &str) -> [f32; 3] {
|
||||
let v = |i: usize| u8::from_str_radix(&s[i..i + 2], 16).map_or(0.0, |b| f32::from(b) / 255.0);
|
||||
[v(0), v(2), v(4)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_on_white_is_21_and_a_color_on_itself_is_1() {
|
||||
assert!((contrast_ratio(hex("000000"), hex("ffffff")) - 21.0).abs() < 1e-9);
|
||||
assert!((contrast_ratio(hex("ffffff"), hex("000000")) - 21.0).abs() < 1e-9);
|
||||
assert!((contrast_ratio(hex("355f78"), hex("355f78")) - 1.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ratios_near_a_minimum_are_compared_unrounded_and_cut_off_in_text() {
|
||||
let r = contrast_ratio(hex("fdc96e"), hex("355f78"));
|
||||
assert!((r - 4.4963).abs() < 1e-3, "{r}");
|
||||
assert_eq!(ratio_text(r), "4.49:1");
|
||||
assert_eq!(Category::NormalText.passes(r), (false, Some(false)));
|
||||
assert_eq!(Category::LargeText.passes(r), (true, Some(false)));
|
||||
let gray = contrast_ratio(hex("767676"), hex("ffffff"));
|
||||
assert!((gray - 4.542).abs() < 1e-3, "{gray}");
|
||||
assert_eq!(ratio_text(gray), "4.54:1");
|
||||
assert!(Category::NormalText.passes(gray).0);
|
||||
let lighter = contrast_ratio(hex("777777"), hex("ffffff"));
|
||||
assert!((lighter - 4.478).abs() < 1e-3, "{lighter}");
|
||||
assert_eq!(ratio_text(lighter), "4.47:1");
|
||||
assert!(!Category::NormalText.passes(lighter).0);
|
||||
assert_eq!(ratio_text(21.0), "21.00:1");
|
||||
assert_eq!(ratio_text(f64::NAN), "1.00:1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphics_have_no_aaa_level() {
|
||||
assert_eq!(Category::Graphics.passes(3.0), (true, None));
|
||||
assert_eq!(Category::Graphics.passes(2.99), (false, None));
|
||||
assert_eq!(Category::LargeText.passes(4.5), (true, Some(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn category_ids_parse_back() {
|
||||
for c in Category::ALL {
|
||||
assert_eq!(Category::parse(c.id()), Some(c));
|
||||
}
|
||||
assert_eq!(Category::parse("NormalText"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_opaque_black_over_white_is_mid_gray() {
|
||||
assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]);
|
||||
assert_eq!(over([0.2; 3], f32::NAN, [1.0; 3]), [0.2; 3]);
|
||||
assert_eq!(over([0.2; 3], 2.0, [1.0; 3]), [0.2; 3]);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,15 @@ use super::node::{held_guides, map_held, strip_held};
|
||||
use super::{Affine, Arc, Document, Node, NodeId, NodeKind, PatternDef, Point, Rect, Selection, SymbolBoxes, Vec2, artboard_holds};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
/// What a transform makes of a ruler guide ([`Document::transformed_guide`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum GuideTransform {
|
||||
/// It stays a ruler guide: vertical at x `pos`, or horizontal at y `pos`.
|
||||
Ruler { vertical: bool, pos: f64 },
|
||||
/// It becomes a guide path along the line between the two points.
|
||||
Path(Point, Point),
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Union of the geometric bounds of `ids` (their visual bounds when `visual`), with symbol
|
||||
/// instances measured by their art ([`Node::geometric_bounds_with`]).
|
||||
@@ -48,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 ›
|
||||
@@ -80,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
|
||||
@@ -369,6 +457,66 @@ impl Document {
|
||||
Some(if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) })
|
||||
}
|
||||
|
||||
/// The line ruler guide `g` stands for as a path: across its artboard for an artboard guide,
|
||||
/// and across the bounds of all the artboards for a canvas guide. None when there is no
|
||||
/// artboard to measure a canvas guide by.
|
||||
pub fn guide_line(&self, g: &Guide) -> Option<(Point, Point)> {
|
||||
let artboards = || self.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b));
|
||||
let (a, b) = self.guide_span(g).or_else(|| artboards().map(|r| if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) }))?;
|
||||
Some(if g.vertical { (Point::new(g.pos, a), Point::new(g.pos, b)) } else { (Point::new(a, g.pos), Point::new(b, g.pos)) })
|
||||
}
|
||||
|
||||
/// What `xf` makes of ruler guide `g` ([`Self::transform_ruler_guides`]), or None when the
|
||||
/// document has no line for it ([`Self::guide_line`]).
|
||||
pub fn transformed_guide(&self, g: &Guide, xf: Affine) -> Option<GuideTransform> {
|
||||
let (a, b) = self.guide_line(g)?;
|
||||
let (a, b) = (xf * a, xf * b);
|
||||
let tol = 1e-9 * a.distance(b).max(1.0);
|
||||
Some(if (a.x - b.x).abs() <= tol {
|
||||
GuideTransform::Ruler { vertical: true, pos: (a.x + b.x) / 2.0 }
|
||||
} else if (a.y - b.y).abs() <= tol {
|
||||
GuideTransform::Ruler { vertical: false, pos: (a.y + b.y) / 2.0 }
|
||||
} else {
|
||||
GuideTransform::Path(a, b)
|
||||
})
|
||||
}
|
||||
|
||||
/// Apply `xf` to the ruler guides selected in `sel`, each as the line [`Self::guide_line`]
|
||||
/// 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. 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) {
|
||||
Some(GuideTransform::Ruler { vertical, pos }) => {
|
||||
self.edit_ruler_guide(id, |g| (g.vertical, g.pos) = (vertical, pos));
|
||||
continue;
|
||||
}
|
||||
Some(GuideTransform::Path(a, b)) => (a, b),
|
||||
None => continue,
|
||||
};
|
||||
let Some(layer) = self.parent_of(id) else { continue };
|
||||
let path = self.alloc_id();
|
||||
let look = crate::Appearance::basic(vectorcraft_color::Paint::None, vectorcraft_color::Paint::None, 0.0);
|
||||
let mut n = Node::path(path, vectorcraft_geom::shapes::line(a, b), look);
|
||||
if let NodeKind::Path { guide, .. } = &mut n.kind {
|
||||
*guide = true;
|
||||
}
|
||||
n.name = g.name.clone();
|
||||
if self.insert(Some(layer), usize::MAX, n).is_err() {
|
||||
continue;
|
||||
}
|
||||
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.
|
||||
fn guide_node(&self, g: &Guide) -> Option<NodeId> {
|
||||
g.id.filter(|id| self.node(*id).is_some_and(Node::is_ruler_guide))
|
||||
|
||||
@@ -731,6 +731,152 @@ fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: O
|
||||
tops
|
||||
}
|
||||
|
||||
/// The most hits [`leaves_at`] lists.
|
||||
pub const MAX_LEAVES_AT: usize = 256;
|
||||
|
||||
/// The hits under `p`, topmost first, at most [`MAX_LEAVES_AT`]: one for each object a click with
|
||||
/// Direct Selection picks there (a path, a compound path or an image, also inside a group), each
|
||||
/// found by a hit test ([`hit_test`]) that passes over the ones found before it. In isolation mode
|
||||
/// (`opt.scope`) only what is inside the isolated group or object is hit. Cmd/Ctrl-clicks with the
|
||||
/// Selection tool step through them (Select Behind).
|
||||
pub fn leaves_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<Hit> {
|
||||
let _walk = ArtWalk::open();
|
||||
// A clipping mask, or a group drawn with its own geometry effects, hits by rules the single
|
||||
// traversal leaves to the hit test: the repeated hit test finds the rest, after the hits found
|
||||
// above them, which the art walked for them already counted against.
|
||||
leaves_at_once(doc, p, opt).unwrap_or_else(|above| leaves_at_repeated_after(doc, p, opt, above))
|
||||
}
|
||||
|
||||
/// [`leaves_at`] by repeated hit tests, each passing over the objects found before it.
|
||||
#[cfg(test)]
|
||||
fn leaves_at_repeated(doc: &Document, p: Point, opt: HitOptions) -> Vec<Hit> {
|
||||
leaves_at_repeated_after(doc, p, opt, vec![])
|
||||
}
|
||||
|
||||
/// [`leaves_at`] by repeated hit tests after `hits`, the topmost hits already found.
|
||||
fn leaves_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, mut hits: Vec<Hit>) -> Vec<Hit> {
|
||||
let mut found: HashSet<NodeId> = hits.iter().map(|h| h.leaf).collect();
|
||||
while hits.len() < MAX_LEAVES_AT
|
||||
&& let Some(h) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true)
|
||||
{
|
||||
if !found.insert(h.leaf) {
|
||||
break;
|
||||
}
|
||||
hits.push(h);
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
/// [`leaves_at`] in one traversal of the document, in the order repeated hit tests
|
||||
/// ([`hit_test_skipping`]) find them. `Err` with the hits found above it when a container under
|
||||
/// `p` clips or draws its art with its own geometry effects ([`leaves_in`]).
|
||||
fn leaves_at_once(doc: &Document, p: Point, opt: HitOptions) -> Result<Vec<Hit>, Vec<Hit>> {
|
||||
let finish = |mut h: Hit| {
|
||||
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
|
||||
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
|
||||
h
|
||||
};
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let on_locked = |id: NodeId| {
|
||||
!locks.is_empty() && doc.parent_of(id).and_then(|l| doc.node(l)).is_some_and(Node::is_layer) && doc.node(id).is_some_and(|n| locks.holds(n))
|
||||
};
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
let mut hits = Vec::new();
|
||||
if let Some(scope) = opt.scope
|
||||
&& let Some(isolated) = doc.node(scope)
|
||||
&& let Some(mut chain) = doc.ancestry(scope)
|
||||
{
|
||||
if !doc.is_editable_with(&locks, scope) {
|
||||
return Ok(hits);
|
||||
}
|
||||
let whole = if isolated.is_container() {
|
||||
leaves_in(isolated, p, opt, &symbols, &on_locked, &mut chain, &mut hits)
|
||||
} else {
|
||||
// A single object isolated: only it hits, among its siblings.
|
||||
chain.pop();
|
||||
let Some(parent) = chain.last().and_then(|id| doc.node(*id)) else { return Ok(hits) };
|
||||
leaves_in(parent, p, opt, &symbols, &|id| id != scope || on_locked(id), &mut chain, &mut hits)
|
||||
};
|
||||
let hits = hits.into_iter().map(finish).collect();
|
||||
return if whole { Ok(hits) } else { Err(hits) };
|
||||
}
|
||||
let mut chain = Vec::new();
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
chain.push(layer.id);
|
||||
let opt = if !opt.ignore_layer_preview && previews_off(layer) { HitOptions { outline: true, ..opt } } else { opt };
|
||||
if !leaves_in(layer, p, opt, &symbols, &on_locked, &mut chain, &mut hits) {
|
||||
return Err(hits.into_iter().map(finish).collect());
|
||||
}
|
||||
chain.pop();
|
||||
if hits.len() >= MAX_LEAVES_AT {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(hits.into_iter().map(finish).collect())
|
||||
}
|
||||
|
||||
/// Every editable hit under `p` in `parent`, topmost first, added to `hits` up to
|
||||
/// [`MAX_LEAVES_AT`]: what [`hit_children`] finds first, then what it finds passing over each hit
|
||||
/// found before. `false` when `parent` or a container in it under `p` clips or draws its art with
|
||||
/// its own geometry effects, which [`hit_children`] hits by rules of their own.
|
||||
fn leaves_in(
|
||||
parent: &Node,
|
||||
p: Point,
|
||||
opt: HitOptions,
|
||||
symbols: &SymbolBoxes,
|
||||
skip: &dyn Fn(NodeId) -> bool,
|
||||
chain: &mut Vec<NodeId>,
|
||||
hits: &mut Vec<Hit>,
|
||||
) -> bool {
|
||||
let Some(children) = parent.children() else { return true };
|
||||
if parent.clips() || drawn_art(symbols, parent, opt.outline).is_some() {
|
||||
return false;
|
||||
}
|
||||
for i in hit_order(parent, children, p) {
|
||||
if hits.len() >= MAX_LEAVES_AT {
|
||||
return true;
|
||||
}
|
||||
let Some(c) = children.get(i) else { continue };
|
||||
if !may_hit(parent, i, c, p, opt, symbols, true) || skip(c.id) {
|
||||
continue;
|
||||
}
|
||||
chain.push(c.id);
|
||||
let leaf = |hits: &mut Vec<Hit>, chain: &[NodeId]| {
|
||||
if let Some(kind) = hit_leaf(c, p, opt, symbols) {
|
||||
hits.push(Hit { leaf: c.id, ancestry: chain.to_vec(), kind, contents_of: None, layers: 1 });
|
||||
}
|
||||
};
|
||||
let whole = match &c.kind {
|
||||
NodeKind::Layer { preview: false, .. } if !opt.ignore_layer_preview => {
|
||||
leaves_in(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, hits)
|
||||
}
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } | NodeKind::Envelope { editing: true, .. } => {
|
||||
leaves_in(c, p, opt, symbols, skip, chain, hits)
|
||||
}
|
||||
// A blend's key objects first; its steps hit as the blend.
|
||||
NodeKind::Blend { .. } => {
|
||||
let whole = leaves_in(c, p, opt, symbols, skip, chain, hits);
|
||||
if whole && hits.len() < MAX_LEAVES_AT {
|
||||
leaf(hits, chain);
|
||||
}
|
||||
whole
|
||||
}
|
||||
_ => {
|
||||
leaf(hits, chain);
|
||||
true
|
||||
}
|
||||
};
|
||||
chain.pop();
|
||||
if !whole {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The most objects [`locked_objects_at`] lists.
|
||||
pub const MAX_LOCKED_AT: usize = 20;
|
||||
|
||||
|
||||
@@ -1992,10 +1992,58 @@ fn objects_at_matches_repeated_hits_on_random_documents() {
|
||||
let p = Point::new(f64::from(next(120)), f64::from(next(120)));
|
||||
let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() };
|
||||
assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None), "round {round}, {p:?}, {opt:?}");
|
||||
assert_eq!(leaf_chains(leaves_at(&d, p, opt)), leaf_chains(leaves_at_repeated(&d, p, opt)), "leaves: round {round}, {p:?}, {opt:?}");
|
||||
// Isolated in a group of the document, now and then.
|
||||
let groups: Vec<NodeId> =
|
||||
d.layers[0].children().into_iter().flatten().filter(|n| n.is_container() && !n.is_layer()).map(|n| n.id).collect();
|
||||
if let Some(&g) = groups.first().filter(|_| next(3) == 0) {
|
||||
let opt = HitOptions { scope: Some(g), ..opt };
|
||||
assert_eq!(leaf_chains(leaves_at(&d, p, opt)), leaf_chains(leaves_at_repeated(&d, p, opt)), "isolated: round {round}, {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A hit's leaf, ancestry, kind, layer count and edited envelope.
|
||||
type LeafChain = (NodeId, Vec<NodeId>, HitKind, usize, Option<NodeId>);
|
||||
|
||||
/// Each hit's [`LeafChain`], to compare two lists.
|
||||
fn leaf_chains(hits: Vec<Hit>) -> Vec<LeafChain> {
|
||||
hits.into_iter().map(|h| (h.leaf, h.ancestry, h.kind, h.layers, h.contents_of)).collect()
|
||||
}
|
||||
|
||||
/// Select Behind steps through the members of groups one by one, front to back, in one traversal
|
||||
/// for a large stack, as the hit test repeated over what is left finds them.
|
||||
#[test]
|
||||
fn leaves_at_lists_group_members_one_by_one() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let layer = d.layers[0].id;
|
||||
let square = |d: &mut Document| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art());
|
||||
let below = square(&mut d);
|
||||
let below_id = below.id;
|
||||
d.insert(Some(layer), usize::MAX, below).unwrap();
|
||||
let members: Vec<Node> = (0..300).map(|_| square(&mut d)).collect();
|
||||
let mut ids: Vec<NodeId> = members.iter().map(|n| n.id).collect();
|
||||
let g = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap();
|
||||
ids.reverse();
|
||||
ids.push(below_id);
|
||||
let p = Point::new(25.0, 25.0);
|
||||
let hits = leaves_at(&d, p, HitOptions::default());
|
||||
assert_eq!(hits.len(), MAX_LEAVES_AT, "the list stops at its limit");
|
||||
assert_eq!(hits.iter().map(|h| h.leaf).collect::<Vec<_>>(), ids[..MAX_LEAVES_AT], "the group's members, topmost first");
|
||||
assert!(hits.iter().all(|h| h.ancestry.contains(&g)));
|
||||
assert_eq!(leaf_chains(hits), leaf_chains(leaves_at_repeated(&d, p, HitOptions::default())));
|
||||
// Hidden past the limit, the object below the group comes after the members that are left.
|
||||
for id in &ids[3..300] {
|
||||
d.node_mut(*id).unwrap().visible = false;
|
||||
}
|
||||
let shown: Vec<NodeId> = leaves_at(&d, p, HitOptions::default()).iter().map(|h| h.leaf).collect();
|
||||
assert_eq!(shown, [ids[0], ids[1], ids[2], below_id]);
|
||||
let isolated = leaves_at(&d, p, HitOptions { scope: Some(g), ..Default::default() });
|
||||
assert!(!isolated.iter().any(|h| h.leaf == below_id), "isolated: only the group's members");
|
||||
}
|
||||
|
||||
/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the
|
||||
/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times.
|
||||
fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
|
||||
@@ -2322,6 +2370,40 @@ fn select_behind_keeps_one_art_limit_when_it_falls_back() {
|
||||
assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked");
|
||||
}
|
||||
|
||||
/// [`leaves_at`] falls back to repeated hit tests at a clip group, after the hits its single
|
||||
/// traversal found above it: an instance hit by its art, with the limit of symbol art then used
|
||||
/// up, stays in the list.
|
||||
#[test]
|
||||
fn leaves_at_keeps_the_hits_above_a_clip_group_it_falls_back_at() {
|
||||
let p = Point::new(150.0, 50.0);
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
clipped_symbol(&mut d, false);
|
||||
// A clip group at the bottom of the layer, its art under (150, 50).
|
||||
let square = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art()));
|
||||
let (mask, art) = (d.alloc_id(), d.alloc_id());
|
||||
let mut clip_group = Node::group(d.alloc_id(), vec![square(mask), square(art)]);
|
||||
clip_group.set_clips(true);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, clip_group).unwrap();
|
||||
let (mut shown_mask, shown_art) = half_clipped(&mut d);
|
||||
shown_mask.appearance.effects.push(test_move());
|
||||
let mut shown = Node::group(d.alloc_id(), vec![Arc::new(shown_mask), Arc::new(shown_art)]);
|
||||
shown.set_clips(true);
|
||||
group_symbol(&mut d, "Shown", vec![Arc::new(shown)]);
|
||||
let hit = instance_of(&mut d, "Shown");
|
||||
let hit_id = hit.id;
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap();
|
||||
for _ in 0..32 {
|
||||
let inst = instance_of(&mut d, "Clipped");
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
}
|
||||
let (hits, _, arts) = with_art_limit(100, || leaves_at(&d, p, HitOptions::default()));
|
||||
let leaves: Vec<NodeId> = hits.iter().map(|h| h.leaf).collect();
|
||||
assert_eq!(leaves.first(), Some(&hit_id), "hit before the fallback: {leaves:?}");
|
||||
assert!(leaves.contains(&art), "the clipped art after it: {leaves:?}");
|
||||
assert!(arts <= 34, "{arts} instances' art walked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_skip() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
|
||||
@@ -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;
|
||||
@@ -168,6 +168,7 @@ pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, Retire
|
||||
pub use canvas_range::BeyondCanvas;
|
||||
#[cfg(test)]
|
||||
use document_ext::free_id;
|
||||
pub use document_guides::GuideTransform;
|
||||
pub use graphic_style::{DEFAULT_GRAPHIC_STYLE, GraphicStyle};
|
||||
pub use guides::{GridPrefs, Guide, RulerMode};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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=
|
||||
|
||||
@@ -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 } => {
|
||||
|
||||
@@ -469,6 +469,35 @@ fn visual_bounds_include_stroke() {
|
||||
assert_eq!(p.visual_bounds(), Some(Rect::new(-0.5, -0.5, 10.5, 10.5)));
|
||||
}
|
||||
|
||||
/// A lone anchor 20 points right of a stroked square widens the path's geometric box, and its
|
||||
/// visual box only where the stroke draws it: as the dot of a round or projecting cap on a closed
|
||||
/// subpath. An open lone anchor, or a closed one under a butt cap, draws nothing.
|
||||
#[test]
|
||||
fn a_lone_anchor_widens_the_visual_box_only_where_its_cap_draws_a_dot() {
|
||||
use crate::appearance::LineCap;
|
||||
use vectorcraft_geom::{Point, SubPath};
|
||||
let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let node = |closed: bool, cap: LineCap| {
|
||||
let mut subpaths = square.subpaths.clone();
|
||||
subpaths.push(SubPath::polyline(&[Point::new(30.0, 5.0)], closed));
|
||||
let mut p = Node::path(NodeId(2), PathData::new(subpaths), Appearance::default_art());
|
||||
let s = p.appearance.stroke_mut().unwrap();
|
||||
(s.cap, s.join) = (cap, crate::appearance::LineJoin::Round);
|
||||
p
|
||||
};
|
||||
for closed in [false, true] {
|
||||
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
|
||||
let p = node(closed, cap);
|
||||
let geometric = p.geometric_bounds().unwrap();
|
||||
let visual = p.visual_bounds().unwrap();
|
||||
assert!(geometric.x1 >= 30.0, "{closed} {cap:?}: the geometric box {geometric:?} leaves out the lone anchor");
|
||||
let dot = closed && cap != LineCap::Butt;
|
||||
assert_eq!(visual.x1 > 30.0, dot, "{closed} {cap:?}: the visual box {visual:?}");
|
||||
assert!(dot || visual.x1 < 11.0, "{closed} {cap:?}: the visual box {visual:?} reaches toward the lone anchor");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's box from its members' boxes grows by the group's own strokes, leaves out members
|
||||
/// without a box, and is `None` when none has one.
|
||||
#[test]
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -435,6 +435,142 @@ fn art_on_artboard_tolerates_roundoff_at_each_edge() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_for_artboard_copy_takes_artwork_larger_than_artboard_or_with_bleed() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
d.setup.bleed = [9.0; 4];
|
||||
let layer = d.layers[0].id;
|
||||
// An oversized background (250x250 centered on the 200x200 artboard, #4479).
|
||||
let bg = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(bg, shapes::rectangle(Rect::new(-25.0, -25.0, 225.0, 225.0)), Appearance::default_art())).unwrap();
|
||||
// A shape with 5pt bleed over the top-right corner.
|
||||
let bleed = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(bleed, shapes::rectangle(Rect::new(150.0, -5.0, 205.0, 50.0)), Appearance::default_art())).unwrap();
|
||||
// A shape lying entirely in the bleed margin without touching the artboard itself (-8..-2 vs 0..200).
|
||||
let bleed_margin_only = d.alloc_id();
|
||||
d.insert(
|
||||
Some(layer),
|
||||
usize::MAX,
|
||||
Node::path(bleed_margin_only, shapes::rectangle(Rect::new(-8.0, 50.0, -2.0, 100.0)), Appearance::default_art()),
|
||||
)
|
||||
.unwrap();
|
||||
// A small shape hanging 20pt over the left edge (center outside, more than bleed).
|
||||
let hanging = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(hanging, shapes::rectangle(Rect::new(-20.0, 90.0, 10.0, 120.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
// A straight line hanging 60pt over the left edge (center outside, no area): it lies on the
|
||||
// artboard for 40pt, so it is copied as a thin rectangle there would be.
|
||||
let line = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(line, shapes::line(Point::new(-60.0, 150.0), Point::new(40.0, 150.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
// A shape completely outside the artboard.
|
||||
let outside = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(outside, shapes::rectangle(Rect::new(300.0, 300.0, 400.0, 400.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
|
||||
// Standard art_on_artboard keeps strict containment: none of the overhanging shapes are on it.
|
||||
let strict_art = d.art_on_artboard(Rect::new(0.0, 0.0, 200.0, 200.0), false);
|
||||
assert!(!strict_art.contains(&bg), "strict art_on_artboard excludes oversized background");
|
||||
assert!(!strict_art.contains(&bleed), "strict art_on_artboard excludes bleed shape");
|
||||
assert!(!strict_art.contains(&bleed_margin_only), "strict art_on_artboard excludes bleed-margin-only shape");
|
||||
assert!(!strict_art.contains(&hanging), "strict art_on_artboard excludes hanging shape");
|
||||
assert!(!strict_art.contains(&outside), "strict art_on_artboard excludes outside shape");
|
||||
|
||||
// Copying the artboard takes the artwork touching this artboard that belongs to it, or within bleed.
|
||||
let copy_art = d.art_for_artboard_copy(0, false);
|
||||
assert!(copy_art.contains(&bg), "oversized background is copied with artboard: {copy_art:?}");
|
||||
assert!(copy_art.contains(&bleed), "bleed shape is copied with artboard: {copy_art:?}");
|
||||
assert!(copy_art.contains(&bleed_margin_only), "bleed-margin-only shape is copied with artboard: {copy_art:?}");
|
||||
assert!(copy_art.contains(&hanging), "touching shape owned by artboard 0 is copied: {copy_art:?}");
|
||||
assert!(copy_art.contains(&line), "a line hanging over the edge is copied: {copy_art:?}");
|
||||
assert!(!copy_art.contains(&outside), "outside shape is not copied: {copy_art:?}");
|
||||
|
||||
// If Artboard 1 is added next to Artboard 0, art primarily on Artboard 1 is not copied with Artboard 0:
|
||||
d.artboards.push(Artboard {
|
||||
id: 2,
|
||||
name: "Artboard 2".into(),
|
||||
rect: Rect::new(200.0, 0.0, 400.0, 200.0),
|
||||
locked: false,
|
||||
show_center_mark: false,
|
||||
show_cross_hairs: false,
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
guide_label: None,
|
||||
});
|
||||
// Shape spanning (190..300) x (50..150): 10pt on Artboard 0, 100pt on Artboard 1.
|
||||
let neighbor_art = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(neighbor_art, shapes::rectangle(Rect::new(190.0, 50.0, 300.0, 150.0)), Appearance::default_art()))
|
||||
.unwrap();
|
||||
|
||||
let copy_art0 = d.art_for_artboard_copy(0, false);
|
||||
assert!(!copy_art0.contains(&neighbor_art), "art owned by neighboring Artboard 1 is not copied with Artboard 0");
|
||||
let copy_art1 = d.art_for_artboard_copy(1, false);
|
||||
assert!(copy_art1.contains(&neighbor_art), "art owned by Artboard 1 is copied with Artboard 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artboard_for_bounds_edge_cases_and_tie_breaks() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
// Artboard 0: (0, 0, 100, 100)
|
||||
// Artboard 1: (200, 0, 300, 100)
|
||||
d.artboards.push(Artboard {
|
||||
id: 2,
|
||||
name: "Artboard 2".into(),
|
||||
rect: Rect::new(200.0, 0.0, 300.0, 100.0),
|
||||
locked: false,
|
||||
show_center_mark: false,
|
||||
show_cross_hairs: false,
|
||||
show_video_safe_areas: false,
|
||||
video_ruler_pixel_aspect_ratio: 1.0,
|
||||
color: None,
|
||||
guide_label: None,
|
||||
});
|
||||
|
||||
// 1. Artwork whose center is outside all boards, but overlaps Artboard 0 most:
|
||||
// Bounds: (50, -100, 150, 50) -> Center: (100, -25) which is outside all artboards.
|
||||
// Overlap with Board 0: 50x50 = 2500; Board 1: 0.
|
||||
let b_center_outside = Rect::new(50.0, -100.0, 150.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_center_outside), Some(0));
|
||||
|
||||
// 2. Equal overlap on two boards (defined tie-break: the lower index, board 0):
|
||||
// Bounds: (50, -50, 250, 50) -> Center: (150, 0) outside all boards.
|
||||
// Overlap with Board 0: (50..100) x (0..50) = 2500; Board 1: (200..250) x (0..50) = 2500.
|
||||
let b_equal_overlap = Rect::new(50.0, -50.0, 250.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_equal_overlap), Some(0), "equal overlap picks lower index");
|
||||
|
||||
// 3. No overlap at all: returns None.
|
||||
let b_no_overlap = Rect::new(500.0, 500.0, 600.0, 600.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_no_overlap), None);
|
||||
|
||||
// 4. Rotated object bounds (bounds, not the inner geometry):
|
||||
// A 40x40 square rotated 45 deg centered at (50, 50) has bounding box ~56.57x56.57.
|
||||
let b_rotated_bounds = Rect::new(50.0 - 28.28, 50.0 - 28.28, 50.0 + 28.28, 50.0 + 28.28);
|
||||
assert_eq!(d.artboard_for_bounds(b_rotated_bounds), Some(0));
|
||||
|
||||
// 5. Zero-size bounds (a point):
|
||||
// On board 0:
|
||||
let b_zero_on_board = Rect::new(50.0, 50.0, 50.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_zero_on_board), Some(0));
|
||||
// Outside all boards:
|
||||
let b_zero_outside = Rect::new(150.0, 50.0, 150.0, 50.0);
|
||||
assert_eq!(d.artboard_for_bounds(b_zero_outside), None);
|
||||
|
||||
// 6. Straight lines whose center is outside every board: owned by the board they lie on most,
|
||||
// as a rectangle of any thickness would be (they have no area to compare).
|
||||
// Horizontal, from x = -100 to 50 on board 0: center (-25, 50).
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.0)), Some(0));
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 50.0, 50.0, 50.1)), Some(0), "the same as a thin rectangle");
|
||||
// Vertical, from y = -100 to 50 on board 1: center (250, -25).
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(250.0, -100.0, 250.0, 50.0)), Some(1));
|
||||
// Below both boards.
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 120.0, 260.0, 120.0)), None);
|
||||
// Across the gap between the boards, 20 pt on board 0 and 60 on board 1.
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(80.0, 50.0, 260.0, 50.0)), Some(1), "center (170, 50) in the gap: board 1 holds more of it");
|
||||
// Only touching a board's corner from outside: no overlap.
|
||||
assert_eq!(d.artboard_for_bounds(Rect::new(-100.0, 0.0, 0.0, 0.0)), None);
|
||||
}
|
||||
|
||||
/// The art on a locked artboard (each object of a layer whose bounds overlap it, a group as one
|
||||
/// object) can't be edited, and Select All, a click and a marquee pass over it; art flush with
|
||||
/// the artboard from outside isn't on it, a layer is on no artboard, and new art isn't on one.
|
||||
|
||||
@@ -291,3 +291,15 @@ fn q_and_ha_suffixes_do_not_take_other_units_suffixes() {
|
||||
// A suffix after math covers the whole expression, as for the other units.
|
||||
assert!((Unit::Points.parse("26/2 q").unwrap() - Unit::Q.to_pt(13.0)).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_area_formats_and_trims_cleanly() {
|
||||
assert_eq!(Unit::Points.format_area(100.0), "100 pt²");
|
||||
assert_eq!(Unit::Inches.format_area(4.5 * 72.0 * 72.0), "4.5 in²");
|
||||
let mm_side = Unit::Millimeters.to_pt(1.0);
|
||||
assert_eq!(Unit::Millimeters.format_area(12.5 * mm_side * mm_side), "12.5 mm²");
|
||||
assert_eq!(Unit::Points.format_area(0.0), "0 pt²");
|
||||
assert_eq!(Unit::Points.format_area(-10.0), "0 pt²");
|
||||
assert_eq!(Unit::Points.format_area(f64::NAN), "0 pt²");
|
||||
assert_eq!(Unit::Points.format_area(f64::INFINITY), "0 pt²");
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -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::*;
|
||||
|
||||
@@ -166,6 +166,19 @@ impl Unit {
|
||||
pub fn format(self, pt: f64) -> String {
|
||||
format!("{} {}", self.number(pt), self.suffix())
|
||||
}
|
||||
/// Format an area in square points into this unit (e.g. `12.5 mm²`, `4.5 in²`, `100 pt²`).
|
||||
pub fn format_area(self, pt2: f64) -> String {
|
||||
if !pt2.is_finite() || pt2 <= 0.0 {
|
||||
return format!("0 {}²", self.suffix());
|
||||
}
|
||||
let side = self.from_pt(1.0);
|
||||
let val = pt2 * side * side;
|
||||
let decimals = if matches!(self, Unit::Points | Unit::Pixels | Unit::Picas | Unit::Q | Unit::Ha) { 3 } else { 4 };
|
||||
let s = format!("{:.*}", decimals, val);
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
let s = if s == "-0" || s.is_empty() { "0" } else { s };
|
||||
format!("{s} {}²", self.suffix())
|
||||
}
|
||||
/// [`Unit::format`] without the suffix (`12.5`), for narrow fields.
|
||||
pub fn number(self, pt: f64) -> String {
|
||||
// Three decimals for the small units (`595.276 pt`), four for the large ones (`8.2677 in`,
|
||||
@@ -196,6 +209,15 @@ impl Unit {
|
||||
}
|
||||
parse_measure(×_as_asterisks(s), self).filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// Parse a measurement with decimal points or commas and no input locale. Refuse a
|
||||
/// number that looks like a grouped integer, even when it is part of an expression.
|
||||
pub fn parse_with_decimal_comma(self, text: &str) -> Option<f64> {
|
||||
if text.contains(',') && times_as_asterisks(text).split(['+', '-', '*', '/']).any(thousands_operand) {
|
||||
return None;
|
||||
}
|
||||
self.parse(&decimal_point(text))
|
||||
}
|
||||
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
|
||||
/// `feetInches`).
|
||||
pub const fn key(self) -> &'static str {
|
||||
@@ -397,6 +419,19 @@ pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() }
|
||||
}
|
||||
|
||||
/// Does the operand contain a thousands comma? Check both parts of a compact pica value and
|
||||
/// read a percentage's number without its percent sign.
|
||||
fn thousands_operand(operand: &str) -> bool {
|
||||
let operand = operand.trim();
|
||||
if let Some((picas, points)) = operand.split_once('p')
|
||||
&& !points.trim().is_empty()
|
||||
&& points.trim().bytes().all(|b| b.is_ascii_digit() || matches!(b, b'.' | b','))
|
||||
{
|
||||
return thousands(picas) || thousands(points);
|
||||
}
|
||||
thousands(operand.strip_suffix('%').unwrap_or(operand))
|
||||
}
|
||||
|
||||
/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or
|
||||
/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at
|
||||
/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -66,7 +66,7 @@ pub const PATHFINDER_EFFECT_PRECISION: std::ops::RangeInclusive<f64> = 0.001..=1
|
||||
/// The documentation of [`PATHFINDER_OPTION_KEYS`], as a literal for `concat!`.
|
||||
macro_rules! options_doc {
|
||||
() => {
|
||||
"precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing; results are refit to within it and pieces thinner than it are dropped), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, a compound shape's area going by the shape's own fill, except that Divide keeps every piece when the group or compound shape has a visible fill of its own; the other operations ignore it)"
|
||||
"precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing, and a stored value that is not a number evaluates as 0.01; results are refit to within it and pieces thinner than it are dropped; Outline treats crossings closer together than precision / 10000 as one point, or than the tolerance for the art's size when that is larger), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, a compound shape's area going by the shape's own fill, except that Divide keeps every piece when the group or compound shape has a visible fill of its own; the other operations ignore it)"
|
||||
};
|
||||
}
|
||||
|
||||
@@ -102,14 +102,21 @@ impl Default for PathfinderEffectOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `precision` stored in a Pathfinder effect's parameters `p`, out of range or not, when it is a
|
||||
/// JSON number. A value of another type (`true`, `"1 pt"`) is not a precision.
|
||||
pub(crate) fn stored_precision(p: &Value) -> Option<f64> {
|
||||
p.get("precision").and_then(Value::as_f64).filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
impl PathfinderEffectOptions {
|
||||
/// The options in `p`: a missing or non-numeric value takes its default and a precision out of
|
||||
/// range its nearest bound, so a live effect always evaluates.
|
||||
/// The options in `p`: a missing value, or one of the wrong type (a precision that is not a
|
||||
/// number), takes its default, and a precision out of range its nearest bound, so a live effect
|
||||
/// always evaluates.
|
||||
pub fn from_params(p: &Value) -> Self {
|
||||
let d = PathfinderEffectOptions::default();
|
||||
let (lo, hi) = (*PATHFINDER_EFFECT_PRECISION.start(), *PATHFINDER_EFFECT_PRECISION.end());
|
||||
PathfinderEffectOptions {
|
||||
precision: crate::util::num(p, "precision", d.precision).clamp(lo, hi),
|
||||
precision: stored_precision(p).unwrap_or(d.precision).clamp(lo, hi),
|
||||
remove_redundant_points: crate::util::flag(p, "removeRedundantPoints", d.remove_redundant_points),
|
||||
remove_unpainted: crate::util::flag(p, "removeUnpainted", d.remove_unpainted),
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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) {
|
||||
@@ -131,9 +153,12 @@ pub fn scale_effect(e: &mut Effect, s: f64) {
|
||||
let mut keys: Vec<&str> = info.lengths.keys(relative).collect();
|
||||
keys.extend(merged.as_object().into_iter().flat_map(|m| m.keys()).map(String::as_str).filter(|k| crate::raster_px_range(&e.id, k).is_some()));
|
||||
for k in keys {
|
||||
let missing =
|
||||
if k == "precision" && crate::takes_pathfinder_options(&e.id) { crate::PathfinderEffectOptions::default().precision } else { f64::NAN };
|
||||
let v = util::num(&merged, k, missing);
|
||||
// A Pathfinder effect's precision that is not a number scales the precision it evaluates with.
|
||||
let v = if k == "precision" && crate::takes_pathfinder_options(&e.id) {
|
||||
crate::group::stored_precision(&merged).unwrap_or(crate::PathfinderEffectOptions::default().precision)
|
||||
} else {
|
||||
util::num(&merged, k, f64::NAN)
|
||||
};
|
||||
if v.is_finite() {
|
||||
if !e.params.is_object() {
|
||||
e.params = Value::Object(Map::new());
|
||||
|
||||
@@ -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);
|
||||
@@ -2186,3 +2186,23 @@ fn a_pathfinder_effects_precision_is_a_distance_that_scales_with_the_object() {
|
||||
assert_eq!(e.params["precision"].as_f64(), Some(8.0), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pathfinder_effects_stored_precision_that_is_not_a_number_is_the_default() {
|
||||
let d = PathfinderEffectOptions::default().precision;
|
||||
for v in [json!(true), json!(false), json!("1abc"), json!("5 pt"), json!(null), json!([2.0])] {
|
||||
assert_eq!(PathfinderEffectOptions::from_params(&json!({ "precision": v })).precision, d, "{v}");
|
||||
}
|
||||
// A number out of range takes its nearest bound.
|
||||
assert_eq!(PathfinderEffectOptions::from_params(&json!({"precision": 50.0})).precision, *PATHFINDER_EFFECT_PRECISION.end());
|
||||
assert_eq!(PathfinderEffectOptions::from_params(&json!({"precision": 0})).precision, *PATHFINDER_EFFECT_PRECISION.start());
|
||||
// Scale Strokes & Effects scales the precision such an effect evaluates with.
|
||||
for (id, _, _) in PATHFINDER_EFFECTS {
|
||||
for v in [json!(true), json!("1abc")] {
|
||||
let mut e = crate::new_effect(id, &json!({ "precision": v })).unwrap();
|
||||
crate::scale_effect(&mut e, 3.0);
|
||||
let scaled = e.params["precision"].as_f64().unwrap_or(f64::NAN);
|
||||
assert!((scaled - d * 3.0).abs() < 1e-12, "{id} {v}: {scaled}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -105,8 +122,9 @@ proptest = { workspace = true }
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
# How many times an open reads a PDF.
|
||||
vectorcraft-pdf = { workspace = true, features = ["read-count"] }
|
||||
# How many times the symbol list is read to find symbols by name.
|
||||
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
|
||||
# How many times the symbol list is read to find symbols by name, and how many objects are
|
||||
# measured against locked artboards.
|
||||
vectorcraft-doc = { workspace = true, features = ["symbol-read-count", "locked-artboard-count"] }
|
||||
wat = { workspace = true }
|
||||
# Zstandard streams for the Illustrator editing data fuzz tests.
|
||||
ruzstd = { workspace = true }
|
||||
|
||||
@@ -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};
|
||||
@@ -855,7 +858,7 @@ pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
|
||||
pub use object::{reflect_axis, scale_factors, shear_tangent};
|
||||
pub(crate) use paint::{LIVE_PAINT_BUCKET, asks_defaults_only};
|
||||
pub(crate) use paint::{asks_defaults_only, painting_tool_of};
|
||||
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
|
||||
pub use select::SIMILAR;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,13 +4,16 @@
|
||||
//! (`vectorcraft_tools::addons::parametric_shape`), which SVG export leaves out.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{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::{CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection};
|
||||
use crate::{EngineError, Result, Session};
|
||||
use super::super::super::menucmds::whole_or;
|
||||
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.
|
||||
const CONVERT: &str = "Convert to Parametric Shape";
|
||||
@@ -31,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?} 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 none, or the same ones, nothing changes → {id, shape (its numbers now)}",
|
||||
"{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
|
||||
),
|
||||
@@ -60,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"))
|
||||
@@ -95,15 +117,60 @@ 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),
|
||||
_ => return Err(bad(C, "`reference` must be from 0 to 8")),
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let shape = apply(old, p).map_err(|e| bad(C, e))?;
|
||||
if shape != old {
|
||||
let path = outline(&shape, C)?;
|
||||
// Without a center, the reference point of the bounding box (as the Transform panel and
|
||||
// `object.setBounds` measure it; the geometric box where the preview leaves none) keeps
|
||||
// its place: the new outline moves onto it. The box after the edit is measured the same way
|
||||
// as the box before it.
|
||||
let how = s.bounds_measure();
|
||||
let geometric = effects::preview::Measure { preview: false, ..how };
|
||||
let boxed = |d: &Document, m: effects::preview::Measure| effects::preview::oriented_bounds_with(d, &[id], m).map(|b| (m, b));
|
||||
let keep = match reference.filter(|_| p.get("center").is_none_or(Value::is_null)) {
|
||||
Some(i) => {
|
||||
let d = &s.doc()?.doc;
|
||||
let (m, b) = boxed(d, how).or_else(|| boxed(d, geometric)).ok_or_else(|| EngineError::Other("no bounds".into()))?;
|
||||
Some((i, m, b.reference_point(i)))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
// 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;
|
||||
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.
|
||||
if !crate::sanity::objects_in_range(d, &[id]) {
|
||||
return Err(bad(C, format!("coordinate out of range (limit ±{MAX_COORD} pt)")));
|
||||
}
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
Ok(())
|
||||
})?;
|
||||
// The numbers the edit committed (an object attached to a path is put back on it); none
|
||||
// when snapping to the pixel grid left a plain path.
|
||||
let committed = s.doc()?.doc.node(id).and_then(read);
|
||||
return Ok(json!({ "id": id.0, "shape": committed.map_or(Value::Null, |c| to_json(&c)) }));
|
||||
}
|
||||
Ok(json!({ "id": id.0, "shape": to_json(&shape) }))
|
||||
}
|
||||
|
||||
@@ -476,6 +476,136 @@ fn set_changes_the_numbers_in_one_step_and_nothing_without_a_change() {
|
||||
assert_eq!(path(&s, id).anchor_count(), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_keeps_the_reference_point_of_the_bounding_box_in_place() {
|
||||
let mut s = session();
|
||||
let corner = |s: &Session, id: NodeId, i: usize| s.transform_box(&[id]).unwrap().reference_point(i);
|
||||
// (kind, its own rotation, a turn with object.rotate, which turns its bounding box too)
|
||||
for (kind, rotation, turn) in [
|
||||
("rectangle", 0.0, 0.0),
|
||||
("rectangle", 30.0, 0.0),
|
||||
("rectangle", 180.0, 0.0),
|
||||
("rectangle", 0.0, 30.0),
|
||||
("star", 0.0, 0.0),
|
||||
("heart", 0.0, 0.0),
|
||||
] {
|
||||
let r = s.execute("addon.pathtools.shape.create", &json!({"kind": kind, "center": [200, 150], "rotation": rotation})).unwrap();
|
||||
let id = id_of(&r);
|
||||
if turn != 0.0 {
|
||||
s.execute("object.rotate", &json!({"angle": turn, "origin": [200, 150]})).unwrap();
|
||||
assert!(s.transform_box(&[id]).unwrap().angle != 0.0, "the box turns with the object");
|
||||
}
|
||||
// Each of the 9 points of the box the Transform panel shows stays where it was while the
|
||||
// width and then the height change, as `object.setBounds` keeps it.
|
||||
for refi in 0..9 {
|
||||
for key in ["width", "height"] {
|
||||
let (before, was) = (shape_of(&s, id).unwrap(), corner(&s, id, refi));
|
||||
let grown = if key == "width" { before.width } else { before.height } + 10.0;
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, key: grown, "reference": refi})).unwrap();
|
||||
let moved = corner(&s, id, refi).distance(was);
|
||||
assert!(moved < 1e-6, "{kind} at {rotation}°, reference {refi}, {key}: the point moved {moved} pt");
|
||||
let after = shape_of(&s, id).unwrap();
|
||||
assert!((if key == "width" { after.width } else { after.height } - grown).abs() < 1e-9, "{kind}, {key}: the new size");
|
||||
}
|
||||
}
|
||||
// Without a reference point, and with an explicit center, the old rules hold.
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 80})).unwrap();
|
||||
let c = shape_of(&s, id).unwrap().center;
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 120})).unwrap();
|
||||
assert!(shape_of(&s, id).unwrap().center.distance(c) < 1e-9, "the center stays by default");
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 60, "center": [10, 20], "reference": 0})).unwrap();
|
||||
assert!(shape_of(&s, id).unwrap().center.distance(Point::new(10.0, 20.0)) < 1e-9, "a center given wins");
|
||||
}
|
||||
let id = star(&mut s);
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.pathtools.shape.set",
|
||||
&[
|
||||
json!({"id": id.0, "width": 50, "reference": -1}),
|
||||
json!({"id": id.0, "width": 50, "reference": 1.5}),
|
||||
json!({"id": id.0, "width": 50, "reference": 9}),
|
||||
json!({"id": id.0, "width": 50, "reference": 9.0}),
|
||||
],
|
||||
);
|
||||
// A whole number written with a decimal point picks the same point.
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 50, "reference": 8.0})).unwrap();
|
||||
let written_whole = shape_of(&s, id).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 50, "reference": 8})).unwrap();
|
||||
assert!(shape_of(&s, id).unwrap().center.distance(written_whole.center) < 1e-9, "`8.0` and `8` pick the same point");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// With Use Preview Bounds the point is on the box as drawn: a star's stroked tips reach past
|
||||
// its anchors by more as the star is stretched, so the drawn box and the anchors' box move apart.
|
||||
s.prefs.use_preview_bounds = true;
|
||||
let stroked = id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": "star", "center": [300, 300], "count": 5})).unwrap());
|
||||
s.execute("paint.setStroke", &json!({"ids": [stroked.0], "color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [stroked.0], "weight": 12})).unwrap();
|
||||
let geometric = |s: &Session, i: usize| s.doc().unwrap().doc.oriented_bounds(&[stroked], false).unwrap().reference_point(i);
|
||||
for refi in [0, 2, 6, 8] {
|
||||
let (was, anchors_were) = (corner(&s, stroked, refi), geometric(&s, refi));
|
||||
let wide = shape_of(&s, stroked).unwrap().width * 2.5;
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": stroked.0, "width": wide, "reference": refi})).unwrap();
|
||||
let moved = corner(&s, stroked, refi).distance(was);
|
||||
assert!(moved < 1e-6, "stroked star, reference {refi}: the drawn box's point moved {moved} pt");
|
||||
assert!(geometric(&s, refi).distance(anchors_were) > 1e-3, "reference {refi}: the anchors' box is not the one kept");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
s.prefs.use_preview_bounds = false;
|
||||
// A shape set by id, not selected, that the edit would take past the coordinate limit.
|
||||
let edge = id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": "rectangle", "center": [3_999_900, 100]})).unwrap());
|
||||
select(&mut s, &[]);
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.pathtools.shape.set",
|
||||
&[json!({"id": edge.0, "width": 180, "reference": 0}), json!({"id": edge.0, "center": [3_999_990, 100]})],
|
||||
);
|
||||
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();
|
||||
@@ -1086,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()
|
||||
}
|
||||
|
||||
@@ -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(())
|
||||
})?;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Unit Converter (`addon.units.*`), a built-in add-on that shows one length in every unit at once.
|
||||
//! `addon.units.convert` reads a length as a number field reads it ([`Unit::parse`]: units and
|
||||
//! arithmetic) and gives it in each unit of Preferences › Units › East Asian Type
|
||||
//! `addon.units.convert` reads a length with units and arithmetic ([`Unit::parse`]) and gives
|
||||
//! it in each unit of Preferences › Units › East Asian Type
|
||||
//! ([`Unit::EAST_ASIAN`]), written as the fields write it ([`Unit::number`], [`Unit::format`]).
|
||||
//! `addon.units.selectionSize` gives the selection's width and height, measured as the Transform
|
||||
//! panel measures them, in the same units. Its panel and its place in Object › Plug-ins are the
|
||||
@@ -10,7 +10,7 @@
|
||||
mod tests;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit};
|
||||
use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, finite_in_every_unit};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::{CommandSpec, always, bad, cmd, has_selection};
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert Units",
|
||||
[],
|
||||
None,
|
||||
"{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
"{value: a length (a number, or text with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point in \"0,5 mm\", but a thousands-shaped number is refused even in arithmetic, as in \"1,500+2\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}",
|
||||
always,
|
||||
convert
|
||||
),
|
||||
@@ -76,7 +76,7 @@ fn convert(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(CONVERT, "missing `value`"));
|
||||
};
|
||||
let pt = match v {
|
||||
Value::String(s) if readable(s) => unit.parse(&decimal_point(s)),
|
||||
Value::String(s) if readable(s) => unit.parse_with_decimal_comma(s),
|
||||
Value::Number(n) => n.as_f64().map(|n| unit.to_pt(n)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
@@ -50,7 +50,7 @@ fn a_length_comes_back_in_every_unit_in_order() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_read_as_number_fields_read_them() {
|
||||
fn values_accept_units_arithmetic_and_decimal_commas() {
|
||||
let mut s = session();
|
||||
let pt = |s: &mut Session, p: Value| convert(s, p)["points"].as_f64().unwrap();
|
||||
assert!(near(pt(&mut s, json!({"value": "1in/2"})), 36.0));
|
||||
@@ -72,8 +72,9 @@ fn values_read_as_number_fields_read_them() {
|
||||
assert!(near(pt(&mut s, json!({"value": "1,5", "unit": "in"})), 108.0));
|
||||
// Each number of a sum reads its own separator.
|
||||
assert!(near(pt(&mut s, json!({"value": "100.5 mm-0,5", "unit": "mm"})), 100.0 * 72.0 / 25.4));
|
||||
// A comma in a sum is a decimal comma, as in the number fields: 1,500+2 is 3.5.
|
||||
assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4));
|
||||
assert!(near(pt(&mut s, json!({"value": "2x0,125 px"})), 0.25));
|
||||
assert!(near(pt(&mut s, json!({"value": "0,125p6+2"})), 9.5));
|
||||
assert!(near(pt(&mut s, json!({"value": "2p0,5+1"})), 25.5));
|
||||
// A sum of 128 signs still reads.
|
||||
assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0));
|
||||
// x, X and × multiply as * does, and each counts toward the 128 signs.
|
||||
@@ -84,6 +85,15 @@ fn values_read_as_number_fields_read_them() {
|
||||
assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thousands_comma_in_an_arithmetic_operand_is_refused() {
|
||||
let mut s = session();
|
||||
for value in ["1,500+2", "1,000 px+2", "2+-1,000", "2/1,000", "2×1,000 in", "1,000'X2", "5pt+1,000%", "1,000p6+2", "2p1,000+2"] {
|
||||
let result = s.execute("addon.units.convert", &json!({"value": value}));
|
||||
assert!(matches!(result, Err(EngineError::BadParams { .. })), "{value}: {result:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_the_commands_do_not_take_are_refused() {
|
||||
let s = session();
|
||||
|
||||
@@ -322,35 +322,52 @@ impl ItemTarget {
|
||||
/// targets have. In a target without an equal item, and for any other target, the row stands
|
||||
/// for itself. Every entry is `Some`.
|
||||
pub(crate) fn per_target(self, s: &Session, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
|
||||
let ItemTarget::Item { index, explicit, aligned: true } = self else { return vec![Some(self); ids.len()] };
|
||||
let Some(st) = s.active().filter(|_| ids.len() >= 2) else { return vec![Some(self); ids.len()] };
|
||||
let k = self.anchor(s, ids);
|
||||
let Some(first) = ids.get(k).and_then(|id| st.doc.node(*id)) else { return vec![Some(self); ids.len()] };
|
||||
ids.iter()
|
||||
.enumerate()
|
||||
.map(|(j, id)| match st.doc.node(*id) {
|
||||
self.each_target(s, ids).collect()
|
||||
}
|
||||
|
||||
/// [`ItemTarget::per_target`], one target at a time: a caller that stops at the first answer
|
||||
/// matches only the targets it reads against the anchor's stack.
|
||||
pub(crate) fn each_target<'a>(self, s: &'a Session, ids: &'a [NodeId]) -> impl Iterator<Item = Option<ItemTarget>> + 'a {
|
||||
let anchor = match self {
|
||||
ItemTarget::Item { aligned: true, .. } if ids.len() >= 2 => s.active().and_then(|st| {
|
||||
let k = self.anchor(s, ids);
|
||||
Some((&st.doc, k, ids.get(k).and_then(|id| st.doc.node(*id))?))
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
ids.iter().enumerate().map(move |(j, id)| {
|
||||
let (ItemTarget::Item { index, explicit, .. }, Some((d, k, first))) = (self, anchor) else { return Some(self) };
|
||||
match d.node(*id) {
|
||||
Some(n) if j != k => {
|
||||
let at = SharedStack::of(&[&*first.appearance, &*n.appearance]).item_in(index, 1);
|
||||
let at = shared_stack(&first.appearance, &n.appearance).item_in(index, 1);
|
||||
Some(at.map_or(self, |index| ItemTarget::Item { index, explicit, aligned: true }))
|
||||
}
|
||||
_ => Some(self),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// [`ItemTarget::per_target`], with an explicit aligned item a row of the stack of `of` (see [`design_reference`]),
|
||||
/// which is not among `ids`, when there is one: each target edits the item equal to it there, and a target without
|
||||
/// an equal item is left out (`None`).
|
||||
pub(crate) fn per_target_of(self, s: &Session, of: Option<NodeId>, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
|
||||
let ItemTarget::Item { index, explicit: true, aligned: true } = self else { return self.per_target(s, ids) };
|
||||
let Some(d) = s.active().map(|st| &st.doc) else { return self.per_target(s, ids) };
|
||||
let Some(r) = of.and_then(|of| d.node(of)) else { return self.per_target(s, ids) };
|
||||
ids.iter()
|
||||
.map(|id| {
|
||||
let index = SharedStack::of(&[&*r.appearance, &*d.node(*id)?.appearance]).item_in(index, 1)?;
|
||||
self.each_target_of(s, of, ids).collect()
|
||||
}
|
||||
|
||||
/// [`ItemTarget::per_target_of`], one target at a time (see [`ItemTarget::each_target`]).
|
||||
pub(crate) fn each_target_of<'a>(self, s: &'a Session, of: Option<NodeId>, ids: &'a [NodeId]) -> impl Iterator<Item = Option<ItemTarget>> + 'a {
|
||||
let reference = match self {
|
||||
ItemTarget::Item { index, explicit: true, aligned: true } => s.active().map(|st| &st.doc).and_then(|d| Some((d, d.node(of?)?, index))),
|
||||
_ => None,
|
||||
};
|
||||
let own = reference.is_none().then(|| self.each_target(s, ids));
|
||||
let shared = reference.map(|(d, r, index)| {
|
||||
ids.iter().map(move |id| {
|
||||
let index = shared_stack(&r.appearance, &d.node(*id)?.appearance).item_in(index, 1)?;
|
||||
Some(ItemTarget::Item { index, explicit: true, aligned: true })
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
own.into_iter().flatten().chain(shared.into_iter().flatten())
|
||||
}
|
||||
|
||||
/// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of
|
||||
@@ -392,6 +409,26 @@ impl ItemTarget {
|
||||
}
|
||||
}
|
||||
|
||||
/// The stack that `a` and `b` share ([`SharedStack::of`]), which [`ItemTarget::each_target`] and
|
||||
/// [`ItemTarget::each_target_of`] match each target's rows in.
|
||||
fn shared_stack(a: &Appearance, b: &Appearance) -> SharedStack {
|
||||
#[cfg(test)]
|
||||
STACKS_MATCHED.set(STACKS_MATCHED.get() + 1);
|
||||
SharedStack::of(&[a, b])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// [`stacks_matched`] of this thread.
|
||||
static STACKS_MATCHED: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many shared stacks [`shared_stack`] has built on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn stacks_matched() -> u64 {
|
||||
STACKS_MATCHED.get()
|
||||
}
|
||||
|
||||
/// Does `p` say its item and effect indices are rows of the first target's stack (`aligned`),
|
||||
/// which each other target edits where it has them (see [`ItemTarget::per_target`])?
|
||||
pub(crate) fn aligned(p: &Value, cmd: &str) -> Result<bool> {
|
||||
@@ -865,7 +902,7 @@ fn edit_items_writing_then(
|
||||
/// The first of `ids` that [`edit_items`] aimed at `item` with `of` changes, and the item it changes there. Read it
|
||||
/// before the edit: once edited, a row that was equal to a row of the art of `of` no longer is.
|
||||
pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option<NodeId>, ids: &[NodeId]) -> Option<(NodeId, ItemTarget)> {
|
||||
ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
|
||||
ids.iter().zip(item.each_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
|
||||
}
|
||||
|
||||
/// Keep the object rows of the graph labels among `ids` for every label of their kind
|
||||
|
||||
@@ -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), 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
|
||||
),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -14,7 +14,8 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::cms::Model;
|
||||
use vectorcraft_color::harmony::{self, Guide, GuideOptions, Harmony};
|
||||
use vectorcraft_color::{Color, Paint, keep_model};
|
||||
use vectorcraft_color::wcag::{self, Category};
|
||||
use vectorcraft_color::{BlendMode, Color, Paint, keep_model};
|
||||
use vectorcraft_doc::live::lerp_color;
|
||||
use vectorcraft_doc::pattern::PatternDef;
|
||||
pub(crate) use vectorcraft_doc::recolor::map_paint;
|
||||
@@ -135,6 +136,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
harmony
|
||||
),
|
||||
cmd!(
|
||||
query "color.contrast",
|
||||
"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` 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
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -701,8 +711,15 @@ impl Indexing {
|
||||
v.as_f64().filter(|x| (0.0..=100.0).contains(x)).ok_or_else(|| bad(C, "`ditherAmount` must be a number from 0 to 100"))?.round() as u8
|
||||
}
|
||||
};
|
||||
let options =
|
||||
|r: Reduction| PaletteOptions { colors: colors.unwrap_or(256), reduction: r, dither, dither_amount, transparency: true, matte: None };
|
||||
let options = |r: Reduction| PaletteOptions {
|
||||
colors: colors.unwrap_or(256),
|
||||
reduction: r,
|
||||
dither,
|
||||
dither_amount,
|
||||
transparency: true,
|
||||
matte: None,
|
||||
..PaletteOptions::default()
|
||||
};
|
||||
let refuse_colors = |name: &str| match colors {
|
||||
Some(_) => Err(bad(C, format!("`colors` does not apply to the {name} reduction"))),
|
||||
None => Ok(()),
|
||||
@@ -984,3 +1001,626 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hex = |cs: &[Color]| cs.iter().map(Color::to_hex).collect::<Vec<_>>();
|
||||
Ok(json!({ "rule": rule.id(), "colors": hex(&g.colors), "grid": g.grid.iter().map(|r| hex(r)).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// The side, in points, of the square [`color_below`] renders.
|
||||
const BELOW_SIDE: f64 = 1.0;
|
||||
/// The pixels per point [`color_below`] renders at.
|
||||
const BELOW_SCALE: f64 = 4.0;
|
||||
|
||||
fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.contrast";
|
||||
check_numbers(p, &["opacity"], C)?;
|
||||
let opacity = match p.get("opacity").and_then(Value::as_f64) {
|
||||
Some(o) if (0.0..=100.0).contains(&o) => Some(o as f32 / 100.0),
|
||||
Some(_) => {
|
||||
let key = "opacity";
|
||||
return Err(bad(C, format!("`{key}` must be from 0 to 100")));
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below"));
|
||||
let (color, drawn) = match p.get("color") {
|
||||
None | Some(Value::Null) => proxy_color(s, opacity.is_some(), below).map_err(|e| bad(C, e))?,
|
||||
Some(v) => (color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?, Drawn::default()),
|
||||
};
|
||||
let rich_black = s.prefs.black_on_screen == "rich";
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let shown = |c: &Color| match *c {
|
||||
Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
|
||||
_ => cms.display_rgb(c),
|
||||
};
|
||||
let to_8bit = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
|
||||
// The background in display sRGB, and as the working RGB `#rrggbb` a given `against` reads as.
|
||||
let (against, written) = match p.get("against").filter(|_| !below) {
|
||||
None => {
|
||||
// The sample in working RGB, rounded to 8 bits: the background the answer writes is the
|
||||
// one the ratio uses, and giving it back answers the same ratio.
|
||||
let working = to_8bit(cms.srgb_to_rgb(color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?.0));
|
||||
(cms.rgb_to_srgb(working.map(|v| f32::from(v) / 255.0)), working)
|
||||
}
|
||||
Some(v) => {
|
||||
let key = "against";
|
||||
let shown = shown(&color_value(v).ok_or_else(|| bad(C, format!("`{key}` must be a color or {}", "\"below\"")))?);
|
||||
(shown, to_8bit(cms.srgb_to_rgb(shown)))
|
||||
}
|
||||
};
|
||||
// Innermost first: the row (inside the object), the object, then its groups and layer. A given
|
||||
// opacity takes the place of the object's and of its groups' and layer's.
|
||||
let row = drawn.row.map(|(blend, o)| Step {
|
||||
blend,
|
||||
opacity: if opacity.is_some() { 1.0 } else { o },
|
||||
isolate: false,
|
||||
hide: Some(Part::Rows),
|
||||
within: Part::Rows,
|
||||
});
|
||||
let object = Step { blend: drawn.blend, opacity: opacity.unwrap_or(drawn.opacity), isolate: drawn.isolate, hide: None, within: Part::Object };
|
||||
let groups = drawn.around.iter().map(|l| Step {
|
||||
blend: l.blend,
|
||||
opacity: if opacity.is_some() { 1.0 } else { l.opacity },
|
||||
isolate: l.isolate,
|
||||
hide: Some(l.part.clone()),
|
||||
within: l.part.clone(),
|
||||
});
|
||||
let steps = row.into_iter().chain([object]).chain(groups).collect::<Vec<_>>();
|
||||
// With the background sampled and no opacity given, each level blends with and draws over the
|
||||
// art below it inside the levels around it, as the canvas composites groups; otherwise the
|
||||
// background stands for that art. Inside an object, group or layer that isolates its blending,
|
||||
// the art below is only what that level holds (nothing, for a given background).
|
||||
let sampled = below && opacity.is_none();
|
||||
// A level with a blend mode that does not isolate draws what is inside it over the art below it,
|
||||
// then takes that art back out by the alpha of what it holds drawn alone, and blends the rest:
|
||||
// `alone` is the alpha of what the next level out holds drawn alone. Each level's opacity
|
||||
// applies to what it holds, and the art beside it in the level around it adds to the alpha once.
|
||||
let blends = |a: &Step| a.blend != BlendMode::Normal && !a.isolate;
|
||||
let mut x = (shown(&color), 1.0f32);
|
||||
let mut alone = 1.0f32;
|
||||
for (k, step) in steps.iter().enumerate() {
|
||||
if step.blend == BlendMode::Normal && step.opacity >= 1.0 && x.1 >= 1.0 && alone >= 1.0 {
|
||||
continue;
|
||||
}
|
||||
let above = &steps[k + 1..];
|
||||
let scope = above.iter().find(|a| a.isolate);
|
||||
let full = above.iter().filter(|a| a.blend != BlendMode::Normal || a.opacity < 1.0).map(|a| &a.within).collect::<Vec<_>>();
|
||||
let read = |scope: Option<&Part>| color_below(s, rich_black, step.hide.as_ref(), &full, scope).map_err(|e| bad(C, e));
|
||||
let backdrop = match scope {
|
||||
Some(_) if !sampled => ([0.0; 3], 0.0),
|
||||
None if !sampled => (against, 1.0),
|
||||
// The background itself, as the answer writes it.
|
||||
None if step.hide.is_none() && full.is_empty() => (against, 1.0),
|
||||
_ => read(scope.map(|a| &a.within))?,
|
||||
};
|
||||
// The alpha of the art below the level inside the level around it, while a blending level
|
||||
// lies further out (none for a given background).
|
||||
let inner = match above.first() {
|
||||
Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1,
|
||||
_ => 0.0,
|
||||
};
|
||||
let source = if !blends(step) {
|
||||
x
|
||||
} else if alone <= 0.0 {
|
||||
(x.0, 0.0)
|
||||
} else {
|
||||
(std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * backdrop.0[i] * backdrop.1) / alone).clamp(0.0, 1.0)), alone)
|
||||
};
|
||||
// A level that isolates its blending carries out the alpha of what it holds composited on
|
||||
// its own.
|
||||
let drawn = if step.isolate { x.1 } else { alone } * step.opacity.clamp(0.0, 1.0);
|
||||
x = composite(step.blend, source, step.opacity, backdrop);
|
||||
alone = drawn + inner * (1.0 - drawn);
|
||||
}
|
||||
let front = if x.1 >= 1.0 { x.0 } else { wcag::over(x.0, x.1, against) };
|
||||
let ratio = wcag::contrast_ratio(front, against);
|
||||
let levels = |c: Category| {
|
||||
let (aa, aaa) = c.passes(ratio);
|
||||
match aaa {
|
||||
Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
|
||||
None => json!({ "aa": aa }),
|
||||
}
|
||||
};
|
||||
let [r, g, b] = written;
|
||||
Ok(json!({
|
||||
"ratio": ratio,
|
||||
"against": format!("#{r:02x}{g:02x}{b:02x}"),
|
||||
"normalText": levels(Category::NormalText),
|
||||
"largeText": levels(Category::LargeText),
|
||||
"graphics": levels(Category::Graphics),
|
||||
}))
|
||||
}
|
||||
|
||||
/// An object around the proxy's object: one in the document, or a group of the picked object's
|
||||
/// dynamic symbol instance's art, by its path in the art (the art's root for an empty path). For
|
||||
/// [`color_below`], also the objects the proxy's color comes from, or their rows from the one the
|
||||
/// proxy shows up.
|
||||
#[derive(Clone, PartialEq)]
|
||||
enum Part {
|
||||
Doc(NodeId),
|
||||
Art(Vec<u32>),
|
||||
Object,
|
||||
Rows,
|
||||
}
|
||||
|
||||
/// An object around the proxy's object that draws it: its opacity, blend mode, whether it isolates
|
||||
/// the blending inside it, and which object it is.
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct Level {
|
||||
opacity: f32,
|
||||
blend: BlendMode,
|
||||
isolate: bool,
|
||||
part: Part,
|
||||
/// Whether it has an opacity mask that is not disabled.
|
||||
masked: bool,
|
||||
}
|
||||
|
||||
/// Whether object `n` has an opacity mask that is not disabled.
|
||||
fn masked(n: &Node) -> bool {
|
||||
n.extras().mask.as_ref().is_some_and(|m| !m.disabled)
|
||||
}
|
||||
|
||||
/// How the proxy's color is drawn: the object's opacity, its fill or stroke row's blend mode and
|
||||
/// opacity (none for type's character paint or a colorize color), each times that of a stop or
|
||||
/// point when it holds the paint, the object's blend mode and whether it isolates its blending, and
|
||||
/// the groups and layer around the object, innermost first.
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct Drawn {
|
||||
opacity: f32,
|
||||
row: Option<(BlendMode, f32)>,
|
||||
blend: BlendMode,
|
||||
isolate: bool,
|
||||
around: Vec<Level>,
|
||||
/// The object's shown fill and stroke rows with paint below the row, which the row draws over.
|
||||
lower: Vec<vectorcraft_doc::AppearanceItem>,
|
||||
}
|
||||
|
||||
impl Default for Drawn {
|
||||
fn default() -> Self {
|
||||
Self { opacity: 1.0, row: None, blend: BlendMode::Normal, isolate: false, around: vec![], lower: vec![] }
|
||||
}
|
||||
}
|
||||
|
||||
/// One level [`contrast`] draws the color through: the row, the object, or a [`Level`]. `hide` is
|
||||
/// what [`color_below`] hides to read the art below it (`None`: the selection), and `within` the
|
||||
/// object whose art is read inside it.
|
||||
struct Step {
|
||||
blend: BlendMode,
|
||||
opacity: f32,
|
||||
isolate: bool,
|
||||
hide: Option<Part>,
|
||||
within: Part,
|
||||
}
|
||||
|
||||
/// `x` (a display sRGB color and its alpha) drawn at `opacity` with blend mode `mode` over `backdrop`
|
||||
/// (likewise), as the PDF compositing formulas give it: the mode applies where the backdrop is
|
||||
/// drawn, and over nothing the color stays as it is.
|
||||
fn composite(mode: BlendMode, x: ([f32; 3], f32), opacity: f32, backdrop: ([f32; 3], f32)) -> ([f32; 3], f32) {
|
||||
let (b, ab) = backdrop;
|
||||
let a = x.1 * if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 1.0 };
|
||||
let mixed = vectorcraft_color::blend::blend_rgb(mode, b, x.0);
|
||||
let out = a + ab * (1.0 - a);
|
||||
if out <= 0.0 {
|
||||
return (b, 0.0);
|
||||
}
|
||||
(std::array::from_fn(|i| (a * ((1.0 - ab) * x.0[i] + ab * mixed[i]) + ab * (1.0 - a) * b[i]) / out), out)
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` draw a color alike: the same blend modes and isolation, and unless
|
||||
/// `given_opacity` (which takes the place of their opacities) the same opacities. With `below`, the
|
||||
/// levels that change what they draw must be the same objects too, since the art below each one is
|
||||
/// read with that object hidden, and the object's opacity must be the same apart from its row's,
|
||||
/// since the row draws over the object's rows below it and the object over the art behind it, and a
|
||||
/// row that blends or is translucent must lie over the same shown rows.
|
||||
fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
|
||||
let counts = |l: &&Level| l.blend != BlendMode::Normal || l.isolate || (!given_opacity && l.opacity < 1.0);
|
||||
let level = |x: &Level, y: &Level| {
|
||||
x.blend == y.blend
|
||||
&& x.isolate == y.isolate
|
||||
&& (given_opacity || (x.opacity - y.opacity).abs() < 1e-6)
|
||||
&& (!below || given_opacity || x.part == y.part)
|
||||
};
|
||||
let (la, lb) = (a.around.iter().filter(counts).collect::<Vec<_>>(), b.around.iter().filter(counts).collect::<Vec<_>>());
|
||||
// A row in Normal mode draws as type's character paint does, and an object's isolation only
|
||||
// changes a row's blending.
|
||||
let row = |d: &Drawn| d.row.map(|r| r.0).filter(|m| *m != BlendMode::Normal);
|
||||
let total = |d: &Drawn| d.opacity * d.row.map_or(1.0, |r| r.1);
|
||||
// A row that blends or lets art through draws over the rows below it, read at one point.
|
||||
let over_rows = |d: &Drawn| d.row.is_some_and(|(m, o)| m != BlendMode::Normal || o < 1.0);
|
||||
row(a) == row(b)
|
||||
&& (given_opacity || !below || !(over_rows(a) || over_rows(b)) || a.lower == b.lower)
|
||||
&& a.blend == b.blend
|
||||
&& (row(a).is_none() || a.isolate == b.isolate)
|
||||
&& (given_opacity || (total(a) - total(b)).abs() < 1e-6)
|
||||
&& (given_opacity || (row(a).is_none() && !below) || (a.opacity - b.opacity).abs() < 1e-6)
|
||||
&& la.len() == lb.len()
|
||||
&& la.iter().zip(&lb).all(|(x, y)| level(x, y))
|
||||
}
|
||||
|
||||
/// The active proxy's color (its selected gradient stop or freeform point, else the first, or a
|
||||
/// gradient mesh's first picked point, each at its own opacity) and how
|
||||
/// it is drawn ([`Drawn`]). With `given_opacity`, the opacities of the selected objects are not
|
||||
/// compared, since the given opacity takes their place; with `below` (the background is sampled),
|
||||
/// objects in different translucent or blending groups or layers differ, since the art below each
|
||||
/// such level is read with it hidden.
|
||||
fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Color, Drawn), String> {
|
||||
let stroke = !s.fill_active;
|
||||
let (fill_mixed, stroke_mixed) = s.proxy_mixed();
|
||||
if if stroke { stroke_mixed } else { fill_mixed } {
|
||||
return Err("the selected objects' colors differ: give `color`".into());
|
||||
}
|
||||
let (fill, stroke_paint) = s.proxy_paints();
|
||||
// The Fill proxy shows a gradient mesh's picked points, each drawn at its own opacity.
|
||||
let points = if stroke { vec![] } else { s.fill_mesh_points() };
|
||||
let source = || {
|
||||
s.proxy_source(stroke)
|
||||
.map(|(n, item)| {
|
||||
let d = drawn_settings(s, &n, item, stroke)?;
|
||||
Ok::<_, String>(match picked_opacities(&n, &points).first() {
|
||||
Some(o) => at(&d, *o),
|
||||
None => d,
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
};
|
||||
let drawing;
|
||||
// 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
|
||||
// one gives the opacity and blend modes the answer uses.
|
||||
let shown = |id: NodeId| st.doc.ancestry(id).unwrap_or_default().iter().all(|a| st.doc.node(*a).is_some_and(|x| x.visible));
|
||||
let mut drawn = vec![];
|
||||
for n in st.selection.subjects().iter().filter_map(|id| st.doc.node(*id)) {
|
||||
for (n, item) in shown_sources(n, item, stroke).into_iter().filter(|(c, _)| shown(c.id)) {
|
||||
let d = drawn_settings(s, n, item, stroke)?;
|
||||
let picked = picked_opacities(n, &points);
|
||||
if picked.is_empty() {
|
||||
drawn.push(d);
|
||||
} else {
|
||||
drawn.extend(picked.into_iter().map(|o| at(&d, o)));
|
||||
}
|
||||
}
|
||||
}
|
||||
drawing = match drawn.first() {
|
||||
Some(first) => first.clone(),
|
||||
None => source()?.unwrap_or_default(),
|
||||
};
|
||||
if !drawn.iter().all(|d| draws_alike(d, &drawing, given_opacity, below)) {
|
||||
// With `opacity` given, the opacities are not compared and the background stands for the
|
||||
// art below.
|
||||
if !given_opacity && drawn.iter().all(|d| draws_alike(d, &drawing, true, below)) {
|
||||
return Err("the selected objects' colors differ: give `opacity` or `color`".into());
|
||||
}
|
||||
return Err("the selected objects' colors differ: give `color`".into());
|
||||
}
|
||||
} else {
|
||||
drawing = source()?.unwrap_or_default();
|
||||
}
|
||||
let no_color = || "the active fill or stroke has no color: give `color`".to_string();
|
||||
match if stroke { stroke_paint } else { fill } {
|
||||
Paint::Solid { color, .. } => Ok((stained(s, color), drawing)),
|
||||
Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform => {
|
||||
let f = g.freeform_on(vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0));
|
||||
let i = s.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0);
|
||||
f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity))).ok_or_else(no_color)
|
||||
}
|
||||
Paint::Gradient(g) => {
|
||||
let i = s.selected_stop().unwrap_or(0).min(g.gradient.stops.len().saturating_sub(1));
|
||||
g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity))).ok_or_else(no_color)
|
||||
}
|
||||
Paint::None | Paint::Pattern { .. } => Err(no_color()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `drawing` with a stop's or point's `opacity`, which applies where its paint is drawn: in its
|
||||
/// row, else in the object.
|
||||
fn at(drawing: &Drawn, opacity: f32) -> Drawn {
|
||||
match drawing.row {
|
||||
Some((m, o)) => Drawn { row: Some((m, o * opacity)), ..drawing.clone() },
|
||||
None => Drawn { opacity: drawing.opacity * opacity, ..drawing.clone() },
|
||||
}
|
||||
}
|
||||
|
||||
/// The opacities of the picked points of gradient mesh `n` ([`Session::fill_mesh_points`]), whose
|
||||
/// colors the Fill proxy shows for it: empty for another object or with no points picked.
|
||||
fn picked_opacities(n: &Node, points: &[(NodeId, Vec<usize>)]) -> Vec<f32> {
|
||||
match (&n.kind, points.iter().find(|(id, _)| *id == n.id)) {
|
||||
(NodeKind::Mesh(m), Some((_, v))) => v.iter().filter_map(|i| m.points.get(*i)).map(|q| q.opacity).collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects whose fill or stroke the proxy shows for selected object `n`, with the appearance
|
||||
/// item each shows: `n` itself when it holds such an item, else every painted object inside it
|
||||
/// ([`Session::proxy_source`] shows the first).
|
||||
fn shown_sources(n: &Node, item: Option<usize>, stroke: bool) -> Vec<(&Node, Option<usize>)> {
|
||||
if n.appearance.item_of_kind(item, !stroke).is_some() {
|
||||
return vec![(n, item)];
|
||||
}
|
||||
let mut nodes = vec![];
|
||||
super::paint::painted(n, true, stroke, &mut nodes);
|
||||
nodes.into_iter().map(|c| (c, None)).collect()
|
||||
}
|
||||
|
||||
/// How object `n` draws its fill or stroke (`item`, else the proxy's row), as [`Drawn`] gives it. An
|
||||
/// error for a hidden row.
|
||||
fn drawn_settings(s: &Session, n: &Node, item: Option<usize>, stroke: bool) -> std::result::Result<Drawn, String> {
|
||||
let item = n.appearance.item_of_kind(item, !stroke);
|
||||
// Without a targeted row, type shows its characters' paint and a colorized image its
|
||||
// colorize color, which no fill or stroke row's opacity applies to.
|
||||
let own_paint = item.is_none() && (matches!(n.kind, NodeKind::Text(_)) || (!stroke && n.extras().colorize.is_some()));
|
||||
let own = match (own_paint, stroke) {
|
||||
(true, _) => None,
|
||||
(false, true) => n.appearance.stroke_at(item).map(|l| (l.opacity, l.blend, l.visible)),
|
||||
(false, false) => n.appearance.fill_at(item).map(|l| (l.opacity, l.blend, l.visible)),
|
||||
};
|
||||
if own.is_some_and(|o| !o.2) {
|
||||
return Err("the active fill or stroke is hidden: give `color`".to_string());
|
||||
}
|
||||
// The groups and layer the object is in draw it too (`enclosing` lists the outermost first).
|
||||
let mut around = enclosing(s, n.id);
|
||||
around.reverse();
|
||||
// An opacity mask sets how much of the color shows at each point, which no one opacity gives.
|
||||
if masked(n) || around.iter().any(|l| l.masked) {
|
||||
return Err("the active fill or stroke is drawn through an opacity mask: give `color`".to_string());
|
||||
}
|
||||
// The rows below the row that draw, as `hide_rows` leaves them shown.
|
||||
let rows = &n.appearance.items;
|
||||
let at_row = item.or_else(|| rows.iter().rposition(|r| r.is_fill() != stroke));
|
||||
let lower = match (own, at_row) {
|
||||
(Some(_), Some(i)) => rows.iter().take(i).filter(|r| r.visible() && !r.paint().is_none()).cloned().collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
Ok(Drawn { opacity: n.opacity, row: own.map(|o| (o.1, o.0)), blend: n.blend, isolate: n.isolate, around, lower })
|
||||
}
|
||||
|
||||
/// `color` as the canvas draws the picked object of a dynamic symbol instance that a fill stains
|
||||
/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill);
|
||||
/// `color` itself otherwise.
|
||||
fn stained(s: &Session, color: Color) -> Color {
|
||||
let stain = s.active().and_then(|st| {
|
||||
let sp = st.selection.symbol_part.as_ref()?;
|
||||
st.selected_symbol_part()?;
|
||||
vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?)
|
||||
});
|
||||
match stain {
|
||||
Some((c, amount)) => color.lerp(&c, amount.clamp(0.0, 1.0)),
|
||||
None => color,
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects that draw the proxy's object `id` ([`Level`]), outermost first: its groups and
|
||||
/// layer, and for a picked object of a dynamic symbol instance, the instance, its groups and layer,
|
||||
/// and the groups of the symbol's art around the object.
|
||||
fn enclosing(s: &Session, id: NodeId) -> Vec<Level> {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
let doc = &st.doc;
|
||||
let level = |n: &Node, part: Part| Level { opacity: n.opacity, blend: n.blend, isolate: n.isolate, part, masked: masked(n) };
|
||||
// `ancestry` lists the object itself last.
|
||||
let in_doc = |id: NodeId, own: bool| {
|
||||
let ids = doc.ancestry(id).unwrap_or_default();
|
||||
let nodes = ids.into_iter().filter(|a| own || *a != id).filter_map(|a| doc.node(a));
|
||||
nodes.map(|a| level(a, Part::Doc(a.id))).collect::<Vec<_>>()
|
||||
};
|
||||
let Some(sp) = st.selection.symbol_part.as_ref() else { return in_doc(id, false) };
|
||||
let art = doc.node(sp.instance).and_then(|inst| {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &inst.kind else { return None };
|
||||
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
Some(vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst))
|
||||
});
|
||||
// Without the picked object, the proxy shows the selected object itself (`proxy_source`).
|
||||
let Some(art) = art.filter(|a| vectorcraft_doc::symbol_overrides::part(a, &sp.path).is_some()) else { return in_doc(id, false) };
|
||||
let mut out = in_doc(sp.instance, true);
|
||||
if let Some((_, groups)) = sp.path.split_last() {
|
||||
// The art's root and each group on the way to the object, not the object itself.
|
||||
let mut n = &art;
|
||||
out.push(level(n, Part::Art(vec![])));
|
||||
for (k, &i) in groups.iter().enumerate() {
|
||||
let Some(c) = n.children().and_then(|c| c.get(usize::try_from(i).ok()?)) else { break };
|
||||
n = c;
|
||||
out.push(level(n, Part::Art(groups[..=k].to_vec())));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The display sRGB VectorCraft draws at the center of the selection's bounds with the selected
|
||||
/// objects hidden: the average of a small square rendered as the canvas renders it (artboards, the
|
||||
/// on-screen Appearance of Black, no proof, no template layers or guides), over white where nothing
|
||||
/// is drawn, with its alpha. With `hide`, that object (a group or layer around the selection) is
|
||||
/// hidden in place of the selection, or for [`Part::Rows`], the proxy's row and the rows above it;
|
||||
/// the objects of `full` draw at full opacity in Normal mode; and with `scope` (a group or layer
|
||||
/// around the selection, or the proxy's objects), only the art inside it is drawn, over nothing,
|
||||
/// without artboards.
|
||||
fn color_below(
|
||||
s: &Session,
|
||||
rich_black: bool,
|
||||
hide: Option<&Part>,
|
||||
full: &[&Part],
|
||||
scope: Option<&Part>,
|
||||
) -> std::result::Result<([f32; 3], f32), String> {
|
||||
super::has_selection(s)?;
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
let ids = st.selection.objects.clone();
|
||||
// A picked object of a dynamic symbol instance hides only itself: the rest of the instance
|
||||
// stays in the sample, measured at the object's center.
|
||||
let picked = st.selection.symbol_part.as_ref().and_then(|sp| {
|
||||
let inst = st.doc.node(sp.instance)?;
|
||||
let center = kurbo::Shape::bounding_box(&vectorcraft_doc::hit::symbol_part_outline(&st.doc, inst, &sp.path)?).center();
|
||||
vectorcraft_doc::symbol_overrides::part(inst_art(&st.doc, sp.instance)?, &sp.path)?;
|
||||
Some((sp, center))
|
||||
});
|
||||
let center = match picked {
|
||||
Some((_, center)) => center,
|
||||
None => st.doc.bounds_of(&ids, false).ok_or("nothing selected")?.center(),
|
||||
};
|
||||
// The objects the proxy's color comes from, with the row each shows (`proxy_color`); for a picked
|
||||
// object, the object itself at `sp.path`, with its topmost row of the kind.
|
||||
let (stroke, item) = (!s.fill_active, s.appearance_item());
|
||||
let shown = |id: NodeId| st.doc.ancestry(id).unwrap_or_default().iter().all(|a| st.doc.node(*a).is_some_and(|x| x.visible));
|
||||
let painted = match picked {
|
||||
Some(_) => vec![],
|
||||
None => {
|
||||
let nodes = st.selection.subjects().iter().filter_map(|id| st.doc.node(*id));
|
||||
nodes.flat_map(|n| shown_sources(n, item, stroke)).filter(|(c, _)| shown(c.id)).map(|(c, item)| (c.id, item)).collect::<Vec<_>>()
|
||||
}
|
||||
};
|
||||
let own = |p: Option<&Part>| matches!(p, Some(Part::Art(_) | Part::Object | Part::Rows));
|
||||
let art_edits = picked.is_some() && (hide.is_none() || own(hide) || full.iter().any(|p| own(Some(p))) || own(scope));
|
||||
let mut copy = (art_edits || !full.is_empty() || hide == Some(&Part::Rows)).then(|| Document::clone(&st.doc));
|
||||
let mut hidden = HashSet::new();
|
||||
// The art of the picked object's instance in `copy`, as a copy of its symbol that only this
|
||||
// instance draws, so other instances of the symbol keep it.
|
||||
let symbol = match (picked, copy.as_mut()) {
|
||||
(Some((sp, _)), Some(doc)) if art_edits => Some(own_symbol(doc, sp.instance).ok_or("the picked object is not found")?),
|
||||
_ => None,
|
||||
};
|
||||
let lost = || "the picked object is not found".to_string();
|
||||
match (hide, picked) {
|
||||
(None, Some((sp, _))) => art_mut(copy.as_mut(), symbol, &sp.path).ok_or_else(lost)?.visible = false,
|
||||
(None, None) => hidden.extend(ids),
|
||||
(Some(Part::Doc(id)), _) => hidden.extend([*id]),
|
||||
// The art's root is all the instance draws.
|
||||
(Some(Part::Art(path)), Some((sp, _))) if path.is_empty() => hidden.extend([sp.instance]),
|
||||
(Some(Part::Art(path)), _) => art_mut(copy.as_mut(), symbol, path).ok_or_else(lost)?.visible = false,
|
||||
(Some(Part::Rows), Some((sp, _))) => hide_rows(art_mut(copy.as_mut(), symbol, &sp.path).ok_or_else(lost)?, None, stroke),
|
||||
(Some(Part::Rows), None) => {
|
||||
for (id, item) in &painted {
|
||||
if let Some(n) = copy.as_mut().and_then(|d| d.node_mut(*id)) {
|
||||
hide_rows(n, *item, stroke);
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(Part::Object), _) => return Err(lost()),
|
||||
}
|
||||
// The levels around the one read draw what is inside them as it is. An instance's override of
|
||||
// an object of its art's opacity or blend mode is dropped with it.
|
||||
let plain = |n: &mut Node| {
|
||||
n.opacity = 1.0;
|
||||
n.blend = BlendMode::Normal;
|
||||
};
|
||||
let plain_art = |copy: &mut Option<Document>, path: &[u32]| -> std::result::Result<(), String> {
|
||||
plain(art_mut(copy.as_mut(), symbol, path).ok_or_else(lost)?);
|
||||
let sp = picked.ok_or_else(lost)?.0;
|
||||
if let Some(e) = copy.as_mut().and_then(|d| d.node_mut(sp.instance)).and_then(Node::extras_if_any) {
|
||||
for o in e.symbol_overrides.iter_mut().filter(|o| o.path == path) {
|
||||
(o.opacity, o.blend) = (None, None);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
for p in full {
|
||||
let ids = match (p, picked) {
|
||||
(Part::Doc(id), _) => vec![*id],
|
||||
(Part::Art(path), _) => {
|
||||
plain_art(&mut copy, path)?;
|
||||
continue;
|
||||
}
|
||||
(Part::Object, Some((sp, _))) => {
|
||||
plain_art(&mut copy, &sp.path)?;
|
||||
continue;
|
||||
}
|
||||
(Part::Object, None) => painted.iter().map(|p| p.0).collect(),
|
||||
(Part::Rows, _) => continue,
|
||||
};
|
||||
for id in ids {
|
||||
if let Some(n) = copy.as_mut().and_then(|d| d.node_mut(id)) {
|
||||
plain(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Inside a level, only the art that level holds is drawn, over nothing.
|
||||
if let Some(scope) = scope {
|
||||
let (keep, path) = match (scope, picked) {
|
||||
(Part::Doc(id), _) => (vec![*id], &[][..]),
|
||||
(Part::Art(path), Some((sp, _))) => (vec![sp.instance], &path[..]),
|
||||
(Part::Object, Some((sp, _))) => (vec![sp.instance], &sp.path[..]),
|
||||
(Part::Object, None) => (painted.iter().map(|p| p.0).collect(), &[][..]),
|
||||
_ => return Err(lost()),
|
||||
};
|
||||
// Everything that is neither on the way to a kept object nor inside one is hidden.
|
||||
let on_way = keep.iter().flat_map(|k| st.doc.ancestry(*k).unwrap_or_default()).collect::<HashSet<_>>();
|
||||
let parents = std::iter::once(None).chain(on_way.iter().filter(|a| !keep.contains(a)).map(|a| Some(*a)));
|
||||
for parent in parents {
|
||||
hidden.extend(st.doc.children(parent).into_iter().flatten().map(|n| n.id).filter(|n| !on_way.contains(n)));
|
||||
}
|
||||
for (k, &keep) in path.iter().enumerate() {
|
||||
let group = art_mut(copy.as_mut(), symbol, &path[..k]).and_then(Node::children_mut).ok_or_else(lost)?;
|
||||
for (i, c) in group.iter_mut().enumerate() {
|
||||
if u32::try_from(i).ok() != Some(keep) {
|
||||
Arc::make_mut(c).visible = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let h = BELOW_SIDE / 2.0;
|
||||
let region = vectorcraft_geom::Rect::new(center.x - h, center.y - h, center.x + h, center.y + h);
|
||||
// Template layers and guides are aids to drawing, not artwork: left out as exports leave them.
|
||||
let opts = vectorcraft_render::RenderOptions {
|
||||
background: scope.is_none().then_some([255, 255, 255, 255]),
|
||||
artboards: scope.is_none(),
|
||||
hidden,
|
||||
rich_black,
|
||||
skip_templates: true,
|
||||
..Default::default()
|
||||
};
|
||||
let img = vectorcraft_render::Renderer::new().render_region_with(copy.as_ref().unwrap_or(&st.doc), region, BELOW_SCALE, &opts);
|
||||
let px = img.pixels.as_chunks::<4>().0;
|
||||
if px.is_empty() {
|
||||
return Ok(if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) });
|
||||
}
|
||||
// The pixels are premultiplied: the average color is their sum over their alpha's.
|
||||
let mut sum = [0.0f64; 4];
|
||||
for p in px {
|
||||
for (s, v) in sum.iter_mut().zip(p) {
|
||||
*s += f64::from(*v);
|
||||
}
|
||||
}
|
||||
let alpha = sum[3] / (px.len() as f64 * 255.0);
|
||||
if alpha <= 0.0 {
|
||||
return Ok(([0.0; 3], 0.0));
|
||||
}
|
||||
let rgb = [0, 1, 2].map(|i| (sum[i] / (px.len() as f64 * 255.0) / alpha).clamp(0.0, 1.0) as f32);
|
||||
Ok((rgb, alpha as f32))
|
||||
}
|
||||
|
||||
/// Hides fill or stroke row `item` of `n` (else its topmost row of the kind) and every row above it.
|
||||
fn hide_rows(n: &mut Node, item: Option<usize>, stroke: bool) {
|
||||
let a = &mut n.appearance;
|
||||
let Some(i) = a.item_of_kind(item, !stroke).or_else(|| a.items.iter().rposition(|r| r.is_fill() != stroke)) else { return };
|
||||
for r in a.items.iter_mut().skip(i) {
|
||||
match r {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => f.visible = false,
|
||||
vectorcraft_doc::AppearanceItem::Stroke(s) => s.visible = false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The art the symbol instance `inst` of `doc` draws, as its symbol holds it.
|
||||
fn inst_art(doc: &Document, inst: NodeId) -> Option<&Arc<Node>> {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &doc.node(inst)?.kind else { return None };
|
||||
doc.symbols.iter().find(|s| s.name == *symbol).map(|s| &s.art)
|
||||
}
|
||||
|
||||
/// The object at `path` in the art of `doc`'s symbol at index `symbol` (the art's root for an empty
|
||||
/// path).
|
||||
fn art_mut<'a>(doc: Option<&'a mut Document>, symbol: Option<usize>, path: &[u32]) -> Option<&'a mut Node> {
|
||||
let mut n = Arc::make_mut(&mut doc?.symbols.get_mut(symbol?)?.art);
|
||||
for &i in path {
|
||||
n = Arc::make_mut(n.children_mut()?.get_mut(usize::try_from(i).ok()?)?);
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// Makes the symbol instance `inst` of `doc` draw a copy of its symbol, so that a change to the copy
|
||||
/// leaves other instances as they are. Returns the copy's index in the document's symbols.
|
||||
fn own_symbol(doc: &mut Document, inst: NodeId) -> Option<usize> {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &doc.node(inst)?.kind else { return None };
|
||||
let mut sym = doc.symbols.iter().find(|s| s.name == *symbol)?.clone();
|
||||
sym.name = unique_name(&sym.name, |name| doc.symbols.iter().any(|s| s.name == name));
|
||||
let name = sym.name.clone();
|
||||
doc.symbols.push(sym);
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &mut doc.node_mut(inst)?.kind {
|
||||
*symbol = name;
|
||||
}
|
||||
Some(doc.symbols.len() - 1)
|
||||
}
|
||||