Merge main into feat/scripts-doc-defaults
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": "main",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"release_branch": "release",
|
||||
"signer_tooling_revision": "main",
|
||||
"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,69 @@ jobs:
|
||||
test-shards: 5
|
||||
shard-command: cargo xtask ci shard
|
||||
warm-command: cargo xtask ci warm
|
||||
# The dependency cache also keeps the compiled workspace crates and test executables, so a
|
||||
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
|
||||
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
|
||||
# `cache-prune` below deletes the one it replaced. The nightly run restores nothing and
|
||||
# builds everything from source.
|
||||
cache-workspace-crates: true
|
||||
cold-build: ${{ github.event_name == 'schedule' }}
|
||||
packages: >-
|
||||
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev
|
||||
libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
|
||||
libgl1-mesa-dev
|
||||
|
||||
# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache
|
||||
# budget. It runs beside the gate and prunes each time the `cache warm` leg finishes saving. A
|
||||
# failed prune warns instead of failing the run, and cache-prune.yml prunes again after every
|
||||
# attempt, re-runs of failed jobs included. `watch-minutes` is longer than the gate's
|
||||
# `timeout-minutes`, so the watch outlasts a cold `cache warm` leg.
|
||||
cache-prune:
|
||||
name: cache prune
|
||||
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 170
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Prune replaced cache entries
|
||||
uses: storytold/craft-common-actions/actions/cache-prune@main
|
||||
continue-on-error: true
|
||||
with:
|
||||
watch: true
|
||||
watch-minutes: 160
|
||||
saving-jobs: |
|
||||
^gate( / cache warm \(.*\))?$
|
||||
|
||||
# The nightly cold run never restores the rolling crates entry, so the old entry is only overlap
|
||||
# while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the
|
||||
# 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes
|
||||
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
|
||||
# When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run
|
||||
# failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a
|
||||
# free runner: the script fails when the leg has not started within 120 minutes, and then waits
|
||||
# up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the
|
||||
# script reports a leg that starts late with its own error before the job times out.
|
||||
cold-cache-clear:
|
||||
name: cold cache clear
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 290
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Delete the old rolling entries before the save
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: python3 scripts/ci-clear-rolling-cache.py
|
||||
@@ -3,13 +3,14 @@ name: Nightly check
|
||||
# The app-side Nightly pieces, checked without a feed run: the Python suites that read the archive,
|
||||
# plist and signing scripts, the workflow contracts, and (on Windows) the packaging and signing
|
||||
# PowerShell suites. The producer itself is .github/workflows/nightly.yml; the Apple-silicon bundle
|
||||
# is built and verified by nightly-macos.yml behind the `full-ci` label.
|
||||
# is built and verified by nightly-macos.yml behind the `full-ci` label. The same job also runs the
|
||||
# suite for scripts/ci-clear-rolling-cache.py, which ci.yml's nightly cold run calls.
|
||||
on:
|
||||
push:
|
||||
branches: [main, release]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"]
|
||||
pull_request:
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
|
||||
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -34,6 +35,8 @@ jobs:
|
||||
persist-credentials: false
|
||||
- name: Run the synthetic suites
|
||||
run: python3 packaging/nightly-tests.py
|
||||
- name: Run the cold cache clear suite
|
||||
run: python3 scripts/ci-clear-rolling-cache-tests.py
|
||||
- name: Parse every nightly shell script
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -0,0 +1,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,37 @@ 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@main
|
||||
with:
|
||||
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
|
||||
tooling-revision: main
|
||||
app-name: vectorcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
# 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,14 @@ 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@main
|
||||
with:
|
||||
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
|
||||
tooling-revision: main
|
||||
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"]'
|
||||
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
|
||||
@@ -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).
|
||||
@@ -24,7 +33,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
|
||||
**Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay.
|
||||
|
||||
**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=<craft-fonts checkout>` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-<family>.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them.
|
||||
**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=<craft-fonts checkout>` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-<family>.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. Desktop builds with a checkout whose opt-in `fonts/latin-manifest.txt` lists Noto Sans Condensed SemiBold (The Noto Project Authors, SIL Open Font License 1.1, from the [notofonts/latin-greek-cyrillic NotoSans-v2.015 release](https://github.com/notofonts/latin-greek-cyrillic/releases/tag/NotoSans-v2.015)) also embed that face, for document tab titles.
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
@@ -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,46 @@ 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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["interpret", "write"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# 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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile.
|
||||
craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["pcraft-pixels"] }
|
||||
# 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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# 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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# 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 = "610c86792a02aa3d416926ee44e3ec3788dea853", features = ["tree"] }
|
||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# 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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# 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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# 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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", default-features = false, features = ["read", "write"] }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# 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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# 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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
vectorcraft-color = { path = "crates/color" }
|
||||
@@ -191,25 +193,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 = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
@@ -45,6 +45,8 @@ fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.m
|
||||
Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC and Noto Sans Arabic in the current manifest;
|
||||
web builds BIZ UDPGothic Regular only) under the SIL
|
||||
Open Font License 1.1. Their license texts ship with the release packages as OFL-<family>.txt.
|
||||
Desktop builds with a craft-fonts checkout whose fonts/latin-manifest.txt lists Noto Sans Condensed
|
||||
SemiBold (Copyright 2022 The Noto Project Authors, SIL Open Font License 1.1) also embed that face.
|
||||
|
||||
PDF import decodes CJK text with Adobe's CMap resources (https://github.com/adobe-type-tools/cmap-resources),
|
||||
compiled into the app through the hayro-cmap crate under the BSD 3-Clause License:
|
||||
@@ -152,6 +154,17 @@ Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option.
|
||||
Original copyright and full license notices are preserved in each hyph-*.tex file.
|
||||
Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5.
|
||||
|
||||
FOGRA51 and FOGRA52 characterization data (crates/color/data/):
|
||||
Source: Fogra Forschungsgesellschaft Druck e.V., www.fogra.org,
|
||||
https://fogra.org/en/downloads/work-tools/characterisation-data. The files are distributed
|
||||
unmodified. Fogra's terms: "Free use and redistribution of the Fogra characterisation data is
|
||||
permitted, including redistribution as part of commercial and non-commercial software, provided
|
||||
that the data are distributed unmodified and Fogra is identified as the source. The designation
|
||||
FOGRAxx may be used solely to identify the respective reference data. Such use does not imply
|
||||
certification, approval or endorsement by Fogra." VectorCraft's Coated CMYK (FOGRA51) and
|
||||
Uncoated CMYK (FOGRA52) working spaces are computed from this data by VectorCraft's own code;
|
||||
they are not Fogra profiles.
|
||||
|
||||
|
||||
JPEG encoder dependency notices
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -168,6 +174,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and, with Measurement Labels on, its radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-28: The Three-Point Arc tool joins an arc to the open paths whose ends its ends are placed on, with Join to Open Path Ends (Tool Options, or J while drawing; `shape.threePointArc` `join`), and in direction mode snaps the third point to where the arc carries an open path on, the same way or turned back (Snap Where the Arc Continues a Path, on by default). Headline numbers unchanged.
|
||||
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
|
||||
@@ -251,6 +258,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. |
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//! vectorcraft-cli commands
|
||||
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
|
||||
//! vectorcraft-cli info FILE
|
||||
//! vectorcraft-cli thumbnail [--size 256] IN OUT
|
||||
//! vectorcraft-cli bench FILE [--size 2880x1800] [--iters 5]
|
||||
//! vectorcraft-cli perf [--paths 50000] [--deep]
|
||||
//! ```
|
||||
@@ -145,6 +146,15 @@ USAGE:
|
||||
read from its preview and why), title, colour mode, units, artboards, object counts by
|
||||
kind, fonts.
|
||||
|
||||
vectorcraft-cli thumbnail [--size N] IN OUT
|
||||
Open IN (any readable format) and write OUT as a PNG of its first artboard (else the art),
|
||||
N pixels on its longer side (1 to 1024, default 256), with a transparent background. Linux
|
||||
file managers run it for .vectorcraft, .drawcraft and .vctemplate files through
|
||||
share/thumbnailers/ai.storyteller.vectorcraft.thumbnailer, and the Windows thumbnail
|
||||
handler (vectorcraft_thumbnail_handler.dll) runs it for Explorer. It exits with an error
|
||||
and writes nothing when IN is larger than 256 MiB, can't be opened, shows nothing, or takes
|
||||
longer than 20 seconds.
|
||||
|
||||
vectorcraft-cli bench FILE [--size WxH] [--iters N]
|
||||
Render FILE (any readable format) fitted to WxH (default 2880x1800) and print ms per frame
|
||||
(warm), multithreaded and single-threaded.
|
||||
@@ -217,6 +227,7 @@ fn main() -> ExitCode {
|
||||
Some("commands") => commands(),
|
||||
Some("convert") => convert(&args[1..]),
|
||||
Some("info") => info(&args[1..]),
|
||||
Some("thumbnail") => thumbnail(&args[1..]),
|
||||
Some("bench") => bench(&args[1..]),
|
||||
Some("perf") => perf::run(&args[1..]),
|
||||
Some("-h" | "--help" | "help") | None => help(),
|
||||
@@ -238,11 +249,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);
|
||||
@@ -519,6 +532,83 @@ fn info(args: &[String]) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Largest file `thumbnail` opens, in bytes on disk.
|
||||
const THUMBNAIL_MAX_FILE: u64 = 256 << 20;
|
||||
/// Largest `--size` of `thumbnail`: the thumbnail standard's largest size, xx-large.
|
||||
const THUMBNAIL_MAX_SIZE: u32 = 1024;
|
||||
/// `--size` when it isn't given: the thumbnail standard's large size.
|
||||
const THUMBNAIL_DEFAULT_SIZE: u32 = 256;
|
||||
/// Longest `thumbnail` runs before it exits without writing OUT.
|
||||
const THUMBNAIL_TIME: std::time::Duration = std::time::Duration::from_secs(20);
|
||||
|
||||
/// `thumbnail`: the PNG a Linux file manager shows for a document, run through the
|
||||
/// `.thumbnailer` entry in `packaging/linux`
|
||||
/// (<https://specifications.freedesktop.org/thumbnail-spec/latest/creation.html>), and the
|
||||
/// picture the Windows thumbnail handler (`apps/vectorcraft-thumbnail-handler`) gives Explorer.
|
||||
fn thumbnail(args: &[String]) -> Result<(), String> {
|
||||
if help_requested(args, &["--size", "-s"]) {
|
||||
return help();
|
||||
}
|
||||
let mut files = vec![];
|
||||
let mut size = THUMBNAIL_DEFAULT_SIZE;
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
match a.as_str() {
|
||||
"--size" | "-s" => {
|
||||
size = it
|
||||
.next()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.filter(|n| (1..=THUMBNAIL_MAX_SIZE).contains(n))
|
||||
.ok_or_else(|| format!("--size needs a number of pixels from 1 to {THUMBNAIL_MAX_SIZE}"))?;
|
||||
}
|
||||
other if other.starts_with('-') => return Err(format!("unknown thumbnail option `{other}`")),
|
||||
f => files.push(f),
|
||||
}
|
||||
}
|
||||
let [input, output] = <[&str; 2]>::try_from(files).map_err(|_| "thumbnail needs IN and OUT")?;
|
||||
// The process ends when the time is up, wherever the work is: OUT is written whole or not at all.
|
||||
std::thread::spawn(|| {
|
||||
std::thread::sleep(THUMBNAIL_TIME);
|
||||
eprintln!("vectorcraft-cli: thumbnail: took longer than {} seconds", THUMBNAIL_TIME.as_secs());
|
||||
std::process::exit(1);
|
||||
});
|
||||
let len = std::fs::metadata(input).map_err(|e| format!("{input}: {e}"))?.len();
|
||||
if len > THUMBNAIL_MAX_FILE {
|
||||
return Err(format!("{input}: larger than {} MiB", THUMBNAIL_MAX_FILE >> 20));
|
||||
}
|
||||
// Opened as the app opens it: the fonts it carries, its type measured, its linked files read.
|
||||
let mut h = Headless::new();
|
||||
h.call("app.open", json!({"path": input})).map_err(|e| format!("{input}: {e}"))?;
|
||||
let doc = &h.session.doc().map_err(|e| e.to_string())?.doc;
|
||||
// A picture without a visible pixel is an error, and the file manager keeps the file's icon.
|
||||
let img = vectorcraft_render::encode::first_artboard(doc, size)
|
||||
.filter(|img| img.pixels.as_chunks::<4>().0.iter().any(|px| px[3] != 0))
|
||||
.ok_or_else(|| format!("{input}: the document shows nothing"))?;
|
||||
let png = img.to_png().map_err(|e| format!("{input}: {e}"))?;
|
||||
write_whole(Path::new(output), &png, |tmp, out| std::fs::rename(tmp, out)).map_err(|e| format!("{output}: {e}"))
|
||||
}
|
||||
|
||||
/// Writes `bytes` to a temporary file beside `out` and moves it over `out` with `rename`. When the
|
||||
/// temporary file can't be written or `rename` fails, this returns the error, removes the temporary
|
||||
/// file and leaves `out` unchanged; it never copies into `out`.
|
||||
fn write_whole(out: &Path, bytes: &[u8], rename: impl FnOnce(&Path, &Path) -> std::io::Result<()>) -> std::io::Result<()> {
|
||||
let name = out.file_name().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "not a file name"))?;
|
||||
let mut tmp_name = std::ffi::OsString::from(".");
|
||||
tmp_name.push(name);
|
||||
tmp_name.push(format!(".{}.tmp", std::process::id()));
|
||||
let tmp = out.with_file_name(tmp_name);
|
||||
// A file already at `tmp` is not this run's: the error leaves it in place.
|
||||
let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)?;
|
||||
let written = f.write_all(bytes).and_then(|()| vectorcraft_format::sync_file(&f));
|
||||
drop(f);
|
||||
let written = written.and_then(|()| rename(&tmp, out));
|
||||
if written.is_err() {
|
||||
// Best effort: the temporary file is all there is to clean up.
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
written
|
||||
}
|
||||
|
||||
enum Step {
|
||||
Cmd(String, Value),
|
||||
Export(String),
|
||||
@@ -768,3 +858,41 @@ fn bench(args: &[String]) -> Result<(), String> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod write_whole_tests {
|
||||
use super::write_whole;
|
||||
|
||||
#[test]
|
||||
fn a_failed_rename_leaves_out_unchanged_and_no_temporary_file() {
|
||||
let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
|
||||
let out = dir.path().join("out.png");
|
||||
std::fs::write(&out, b"old").unwrap_or_else(|e| panic!("{e}"));
|
||||
let refused = write_whole(&out, b"new picture", |_, _| Err(std::io::Error::other("refused")));
|
||||
assert!(refused.is_err());
|
||||
assert_eq!(std::fs::read(&out).unwrap_or_else(|e| panic!("{e}")), b"old");
|
||||
let names: Vec<_> = std::fs::read_dir(dir.path()).unwrap_or_else(|e| panic!("{e}")).flatten().map(|e| e.file_name()).collect();
|
||||
assert_eq!(names, ["out.png"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_already_at_the_temporary_name_is_kept() {
|
||||
let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
|
||||
let out = dir.path().join("out.png");
|
||||
let tmp = dir.path().join(format!(".out.png.{}.tmp", std::process::id()));
|
||||
std::fs::write(&tmp, b"someone else's").unwrap_or_else(|e| panic!("{e}"));
|
||||
assert!(write_whole(&out, b"new picture", |tmp, out| std::fs::rename(tmp, out)).is_err());
|
||||
assert_eq!(std::fs::read(&tmp).unwrap_or_else(|e| panic!("{e}")), b"someone else's");
|
||||
assert!(!out.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_replaces_out() {
|
||||
let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
|
||||
let out = dir.path().join("out.png");
|
||||
std::fs::write(&out, b"old").unwrap_or_else(|e| panic!("{e}"));
|
||||
write_whole(&out, b"new picture", |tmp, out| std::fs::rename(tmp, out)).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(std::fs::read(&out).unwrap_or_else(|e| panic!("{e}")), b"new picture");
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap_or_else(|e| panic!("{e}")).count(), 1);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ mod cli;
|
||||
mod fileio;
|
||||
mod mcp_e2e;
|
||||
mod script;
|
||||
mod thumbnail;
|
||||
|
||||
/// Nextest relocates archived binaries; Cargo's compile-time path still names the build runner.
|
||||
fn bin() -> std::path::PathBuf {
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
//! `thumbnail` and the Linux `.thumbnailer` entry that runs it for file managers.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
const THUMBNAILER: &str = include_str!("../../../../packaging/linux/ai.storyteller.vectorcraft.thumbnailer");
|
||||
const MIME: &str = include_str!("../../../../packaging/linux/ai.storyteller.vectorcraft.mime.xml");
|
||||
const PACKAGE: &str = include_str!("../../../../packaging/linux/package.sh");
|
||||
|
||||
/// Returns a new empty folder in the temp folder, removed with everything in it when the guard drops.
|
||||
fn tmp() -> tempfile::TempDir {
|
||||
tempfile::tempdir().unwrap()
|
||||
}
|
||||
|
||||
fn cli(args: &[&str]) -> Output {
|
||||
Command::new(crate::bin()).args(args).output().unwrap()
|
||||
}
|
||||
|
||||
/// Saves a `width`×`height` document with a rectangle on its artboard as `name` in `dir` and returns its path.
|
||||
fn document(dir: &Path, name: &str, width: u32, height: u32) -> PathBuf {
|
||||
save(dir, name, width, height, &["--cmd", "shape.rectangle", "--params", r#"{"x":10,"y":10,"width":40,"height":20}"#])
|
||||
}
|
||||
|
||||
/// Saves a new `width`×`height` document as `name` in `dir` after the `run` arguments `steps`.
|
||||
fn save(dir: &Path, name: &str, width: u32, height: u32, steps: &[&str]) -> PathBuf {
|
||||
let path = dir.join(name);
|
||||
let size = format!(r#"{{"width":{width},"height":{height}}}"#);
|
||||
let mut args = vec!["run", "--cmd", "file.new", "--params", &size];
|
||||
args.extend_from_slice(steps);
|
||||
args.extend(["--export", path.to_str().unwrap()]);
|
||||
let out = cli(&args);
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
path
|
||||
}
|
||||
|
||||
/// The width and height in a PNG's IHDR chunk, after checking that it is the 8-bit, non-interlaced
|
||||
/// RGBA a thumbnail must be (<https://specifications.freedesktop.org/thumbnail-spec/latest/creation.html>).
|
||||
fn png_size(png: &[u8]) -> (u32, u32) {
|
||||
assert!(png.starts_with(b"\x89PNG\r\n\x1a\n") && &png[12..16] == b"IHDR", "not a PNG");
|
||||
assert_eq!((png[24], png[25], png[28]), (8, 6, 0), "bit depth, color type (RGBA) and interlacing");
|
||||
let be = |b: &[u8]| u32::from_be_bytes([b[0], b[1], b[2], b[3]]);
|
||||
(be(&png[16..20]), be(&png[20..24]))
|
||||
}
|
||||
|
||||
/// The value of `key` in the entry's `[Thumbnailer Entry]` group.
|
||||
fn entry(key: &str) -> &'static str {
|
||||
assert_eq!(THUMBNAILER.lines().next(), Some("[Thumbnailer Entry]"));
|
||||
THUMBNAILER.lines().find_map(|l| l.strip_prefix(key)?.strip_prefix('=')).unwrap_or_else(|| panic!("no {key} key"))
|
||||
}
|
||||
|
||||
/// The file manager's command for the entry: `Exec` split at spaces, `%s` the size, `%i` the
|
||||
/// input path and `%o` the output path (the codes the thumbnail factories expand).
|
||||
fn exec(size: u32, input: &Path, output: &Path) -> Vec<String> {
|
||||
entry("Exec")
|
||||
.split(' ')
|
||||
.map(|arg| match arg {
|
||||
"%s" => size.to_string(),
|
||||
"%i" => input.to_string_lossy().into_owned(),
|
||||
"%o" => output.to_string_lossy().into_owned(),
|
||||
other => {
|
||||
assert!(!other.contains('%'), "a field code the CLI doesn't take: {other}");
|
||||
other.to_string()
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The entry runs the CLI with the size, the document and the PNG to write, as a file manager
|
||||
/// does: with no environment, and the PNG is the first artboard at that size, drawn by the
|
||||
/// renderer that embeds a native file's preview.
|
||||
#[test]
|
||||
fn the_thumbnailer_entry_writes_the_first_artboard() {
|
||||
let dir = tmp();
|
||||
let doc = document(dir.path(), "wide.vectorcraft", 200, 100);
|
||||
let out = dir.path().join("wide.png");
|
||||
let command = exec(128, &doc, &out);
|
||||
assert_eq!(command[0], entry("TryExec"));
|
||||
assert_eq!(command[0], "vectorcraft-cli");
|
||||
let run = Command::new(crate::bin()).args(&command[1..]).env_clear().output().unwrap();
|
||||
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
|
||||
let png = std::fs::read(&out).unwrap();
|
||||
assert_eq!(png_size(&png), (128, 64));
|
||||
let saved = vectorcraft_format::load(&std::fs::read(&doc).unwrap()).unwrap();
|
||||
assert_eq!(Some(png), vectorcraft_render::encode::first_artboard_png(&saved, 128).unwrap(), "the renderer's picture");
|
||||
}
|
||||
|
||||
/// Each type the entry lists is a native document type the app's MIME package declares, and the
|
||||
/// packages install the entry where the thumbnail factories look.
|
||||
#[test]
|
||||
fn the_thumbnailer_entry_covers_the_native_types() {
|
||||
let types: Vec<&str> = entry("MimeType").split(';').filter(|t| !t.is_empty()).collect();
|
||||
assert_eq!(types, ["application/x-vectorcraft", "application/x-vectorcraft-template"]);
|
||||
for t in types {
|
||||
assert!(MIME.contains(&format!("<mime-type type=\"{t}\">")), "the MIME package doesn't declare {t}");
|
||||
}
|
||||
assert!(
|
||||
PACKAGE.contains(r#"install -Dm644 "$HERE/$APP_ID.thumbnailer" "$STAGE/usr/share/thumbnailers/$APP_ID.thumbnailer""#),
|
||||
"package.sh doesn't install the entry"
|
||||
);
|
||||
}
|
||||
|
||||
/// The size defaults to 256 pixels on the longer side, and a tall artboard is fitted by its height.
|
||||
#[test]
|
||||
fn thumbnail_fits_the_longer_side() {
|
||||
let dir = tmp();
|
||||
let doc = document(dir.path(), "tall.vectorcraft", 100, 400);
|
||||
let out = dir.path().join("tall.png");
|
||||
let run = cli(&["thumbnail", doc.to_str().unwrap(), out.to_str().unwrap()]);
|
||||
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
|
||||
assert_eq!(png_size(&std::fs::read(&out).unwrap()), (64, 256));
|
||||
}
|
||||
|
||||
/// A size outside 1 to 1024 pixels, a missing file name and an unknown option are errors, and no
|
||||
/// PNG is written.
|
||||
#[test]
|
||||
fn thumbnail_refuses_bad_arguments() {
|
||||
let dir = tmp();
|
||||
let doc = document(dir.path(), "args.vectorcraft", 100, 100);
|
||||
let out = dir.path().join("args.png");
|
||||
let (d, o) = (doc.to_str().unwrap(), out.to_str().unwrap());
|
||||
for (args, says) in [
|
||||
(vec!["thumbnail", "--size", "0", d, o], "--size"),
|
||||
(vec!["thumbnail", "--size", "1025", d, o], "--size"),
|
||||
(vec!["thumbnail", "--size", "big", d, o], "--size"),
|
||||
(vec!["thumbnail", "--size"], "--size"),
|
||||
(vec!["thumbnail", d], "IN and OUT"),
|
||||
(vec!["thumbnail", "--quality", "9", d, o], "--quality"),
|
||||
] {
|
||||
let run = cli(&args);
|
||||
assert!(!run.status.success(), "{args:?}");
|
||||
assert!(String::from_utf8_lossy(&run.stderr).contains(says), "{args:?}: {}", String::from_utf8_lossy(&run.stderr));
|
||||
assert!(!out.exists(), "{args:?} wrote a PNG");
|
||||
}
|
||||
}
|
||||
|
||||
/// A file that isn't a document, a damaged one, one larger than the CLI opens, a missing one and
|
||||
/// an empty document get an error and no PNG, so the file manager shows the file's icon.
|
||||
#[test]
|
||||
fn thumbnail_writes_nothing_for_files_it_cannot_read() {
|
||||
let dir = tmp();
|
||||
let text = dir.path().join("notes.vectorcraft");
|
||||
std::fs::write(&text, b"not a document").unwrap();
|
||||
let saved = std::fs::read(document(dir.path(), "whole.vectorcraft", 100, 100)).unwrap();
|
||||
let damaged = dir.path().join("damaged.vectorcraft");
|
||||
std::fs::write(&damaged, &saved[..saved.len() / 2]).unwrap();
|
||||
// Sparse where the file system allows it: its size is checked before anything is read.
|
||||
let large = dir.path().join("large.vectorcraft");
|
||||
std::fs::File::create(&large).unwrap().set_len((256 << 20) + 1).unwrap();
|
||||
let missing = dir.path().join("missing.vectorcraft");
|
||||
let empty = save(dir.path(), "empty.vectorcraft", 100, 100, &[]);
|
||||
for (input, says) in
|
||||
[(&text, None), (&damaged, None), (&large, Some("larger than 256 MiB")), (&missing, None), (&empty, Some("the document shows nothing"))]
|
||||
{
|
||||
let out = dir.path().join("unreadable.png");
|
||||
let run = cli(&["thumbnail", input.to_str().unwrap(), out.to_str().unwrap()]);
|
||||
assert!(!run.status.success(), "{input:?}");
|
||||
let err = String::from_utf8_lossy(&run.stderr);
|
||||
assert!(err.contains(input.to_str().unwrap()), "{input:?}: {err}");
|
||||
assert!(says.is_none_or(|s| err.contains(s)), "{input:?}: {err}");
|
||||
assert!(!out.exists(), "{input:?} wrote a PNG");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "vectorcraft-plugin-worker"
|
||||
description = "The web build's plug-in worker: checks plug-in modules being installed and runs filters off the page"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "vectorcraft-plugin-worker"
|
||||
path = "src/main.rs"
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
vectorcraft-plugins = { workspace = true }
|
||||
wasm-bindgen = "0.2"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["DedicatedWorkerGlobalScope", "MessageEvent"] }
|
||||
@@ -0,0 +1,37 @@
|
||||
//! The web build's plug-in worker ([`vectorcraft_plugins::worker`]). Trunk builds it beside the
|
||||
//! app (`data-type="worker"` in `apps/vectorcraft-web/index.html`), and the page starts one for each
|
||||
//! module it checks and each filter it runs, through the loader Trunk writes for it
|
||||
//! (`vectorcraft-plugin-worker_loader.js`). Each message, both ways, is one `Uint8Array`.
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn main() {
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::prelude::Closure;
|
||||
use web_sys::{DedicatedWorkerGlobalScope, MessageEvent};
|
||||
|
||||
let scope: DedicatedWorkerGlobalScope = js_sys::global().unchecked_into();
|
||||
let poster = scope.clone();
|
||||
let post = Rc::new(move |msg: Vec<u8>| {
|
||||
let bytes = js_sys::Uint8Array::from(msg.as_slice());
|
||||
// A message that can't be posted leaves the page waiting, and its time budget ends the run.
|
||||
let _ = poster.post_message_with_transfer(&bytes, &js_sys::Array::of1(&bytes.buffer()));
|
||||
});
|
||||
let worker = Rc::new(RefCell::new(vectorcraft_plugins::worker::Worker::new(post)));
|
||||
let handler = Rc::clone(&worker);
|
||||
let on_message = Closure::<dyn FnMut(MessageEvent)>::new(move |e: MessageEvent| {
|
||||
let msg = js_sys::Uint8Array::new(&e.data()).to_vec();
|
||||
handler.borrow_mut().handle(&msg);
|
||||
});
|
||||
scope.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
|
||||
// The handler lives as long as the worker.
|
||||
on_message.forget();
|
||||
worker.borrow().ready();
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn main() {
|
||||
eprintln!("vectorcraft-plugin-worker only runs in the browser, as the web build's plug-in worker");
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
[package]
|
||||
name = "vectorcraft-thumbnail-handler"
|
||||
description = "Windows Explorer thumbnail handler for VectorCraft documents and templates"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
# A COM server DLL that Explorer loads; on other systems it builds the parts the tests check.
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
# PNG decoding of the picture `vectorcraft-cli thumbnail` writes. MIT OR Apache-2.0.
|
||||
[dependencies]
|
||||
png = "0.18"
|
||||
|
||||
# IThumbnailProvider, IInitializeWithStream, the class factory, DIB sections and the registry.
|
||||
# MIT OR Apache-2.0.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows = { version = "0.62", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_LibraryLoader",
|
||||
"Win32_System_Registry",
|
||||
"Win32_System_SystemServices",
|
||||
"Win32_UI_Shell",
|
||||
"Win32_UI_Shell_PropertiesSystem",
|
||||
] }
|
||||
windows-core = "0.62"
|
||||
@@ -0,0 +1,345 @@
|
||||
//! The COM server: the thumbnail provider, its class factory and the functions the DLL exports
|
||||
//! (`DllGetClassObject`, `DllCanUnloadNow`, `DllRegisterServer` and `DllUnregisterServer`).
|
||||
//!
|
||||
//! COM, GDI and the registry are C APIs with no safe binding, hence the scoped `unsafe_code`
|
||||
//! allowance.
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::io::{self, Read};
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr::null_mut;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
|
||||
|
||||
use windows::Win32::Foundation::{
|
||||
CLASS_E_CLASSNOTAVAILABLE, CLASS_E_NOAGGREGATION, E_FAIL, E_POINTER, ERROR_ALREADY_INITIALIZED, ERROR_FILE_NOT_FOUND, HINSTANCE, HMODULE,
|
||||
S_FALSE, S_OK,
|
||||
};
|
||||
use windows::Win32::Graphics::Gdi::{BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateDIBSection, DIB_RGB_COLORS, DeleteObject, HBITMAP};
|
||||
use windows::Win32::System::Com::{CoTaskMemFree, IClassFactory, IClassFactory_Impl, IStream};
|
||||
use windows::Win32::System::LibraryLoader::GetModuleFileNameW;
|
||||
use windows::Win32::System::Registry::{HKEY_CURRENT_USER, REG_SZ, RRF_RT_REG_SZ, RegDeleteTreeW, RegGetValueW, RegSetKeyValueW};
|
||||
use windows::Win32::System::SystemServices::DLL_PROCESS_ATTACH;
|
||||
use windows::Win32::UI::Shell::PropertiesSystem::{IInitializeWithStream, IInitializeWithStream_Impl};
|
||||
use windows::Win32::UI::Shell::{
|
||||
FOLDERID_LocalAppDataLow, IThumbnailProvider, IThumbnailProvider_Impl, KNOWN_FOLDER_FLAG, SHCNE_ASSOCCHANGED, SHCNF_IDLIST, SHChangeNotify,
|
||||
SHGetKnownFolderPath, WTS_ALPHATYPE, WTSAT_ARGB,
|
||||
};
|
||||
use windows::core::{BOOL, Error, GUID, HRESULT, HSTRING, IUnknown, Interface, PCWSTR, Ref, Result, implement};
|
||||
|
||||
use crate::{CLI, CLSID_VALUE, DEADLINE, Document, MAX_FILE, Picture, RegistryValue};
|
||||
|
||||
/// The handler's class id ([`crate::CLSID`]).
|
||||
const CLASS_ID: GUID = GUID::from_u128(CLSID_VALUE);
|
||||
/// The registry key the values of [`crate::registry_values`] go under.
|
||||
const CLASSES: &str = "Software\\Classes";
|
||||
/// The longest DLL path read, in UTF-16 units (Windows' own limit).
|
||||
const MAX_PATH: usize = 32_767;
|
||||
|
||||
/// The DLL's module handle, from `DllMain`.
|
||||
static MODULE: AtomicPtr<c_void> = AtomicPtr::new(null_mut());
|
||||
/// Providers and class factories alive plus `LockServer` locks held; the DLL can be unloaded at 0.
|
||||
static LIVE: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// The thumbnail provider: Explorer hands it the file's stream, then asks for the picture.
|
||||
#[implement(IInitializeWithStream, IThumbnailProvider)]
|
||||
struct Provider {
|
||||
document: Mutex<Option<Document<StreamReader>>>,
|
||||
}
|
||||
|
||||
impl Provider {
|
||||
fn new() -> Self {
|
||||
LIVE.fetch_add(1, Ordering::SeqCst);
|
||||
Self { document: Mutex::new(None) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Provider {
|
||||
fn drop(&mut self) {
|
||||
LIVE.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl IInitializeWithStream_Impl for Provider_Impl {
|
||||
fn Initialize(&self, stream: Ref<IStream>, _mode: u32) -> Result<()> {
|
||||
let stream = stream.ok()?.clone();
|
||||
let mut slot = self.document.lock().map_err(|_| Error::from(E_FAIL))?;
|
||||
if slot.is_some() {
|
||||
return Err(ERROR_ALREADY_INITIALIZED.to_hresult().into());
|
||||
}
|
||||
*slot = Some(Document::new(StreamReader(stream)));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl IThumbnailProvider_Impl for Provider_Impl {
|
||||
fn GetThumbnail(&self, cx: u32, bitmap: *mut HBITMAP, alpha: *mut WTS_ALPHATYPE) -> Result<()> {
|
||||
if bitmap.is_null() || alpha.is_null() {
|
||||
return Err(E_POINTER.into());
|
||||
}
|
||||
let mut slot = self.document.lock().map_err(|_| Error::from(E_FAIL))?;
|
||||
let document = slot.as_mut().ok_or_else(|| Error::new(E_FAIL, "not initialized"))?;
|
||||
// A panic must not unwind into Explorer's process.
|
||||
let picture = match std::panic::catch_unwind(AssertUnwindSafe(|| thumbnail(document, cx))) {
|
||||
Ok(Ok(picture)) => picture,
|
||||
Ok(Err(e)) => return Err(Error::new(E_FAIL, e)),
|
||||
Err(_) => return Err(Error::new(E_FAIL, "the thumbnail could not be made")),
|
||||
};
|
||||
drop(slot);
|
||||
let made = dib_section(&picture)?;
|
||||
// SAFETY: both pointers were checked for null above, and Explorer passes them writable.
|
||||
unsafe {
|
||||
*bitmap = made;
|
||||
*alpha = WTSAT_ARGB;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The class factory COM asks for the provider.
|
||||
#[implement(IClassFactory)]
|
||||
struct Factory;
|
||||
|
||||
impl Factory {
|
||||
fn new() -> Self {
|
||||
LIVE.fetch_add(1, Ordering::SeqCst);
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Factory {
|
||||
fn drop(&mut self) {
|
||||
LIVE.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl IClassFactory_Impl for Factory_Impl {
|
||||
fn CreateInstance(&self, outer: Ref<IUnknown>, iid: *const GUID, object: *mut *mut c_void) -> Result<()> {
|
||||
if iid.is_null() || object.is_null() {
|
||||
return Err(E_POINTER.into());
|
||||
}
|
||||
// SAFETY: `object` was checked for null above.
|
||||
unsafe { *object = null_mut() };
|
||||
if !outer.is_null() {
|
||||
return Err(CLASS_E_NOAGGREGATION.into());
|
||||
}
|
||||
let provider: IUnknown = Provider::new().into();
|
||||
// SAFETY: both pointers were checked for null above.
|
||||
unsafe { provider.query(iid, object) }.ok()
|
||||
}
|
||||
|
||||
fn LockServer(&self, lock: BOOL) -> Result<()> {
|
||||
if lock.as_bool() {
|
||||
LIVE.fetch_add(1, Ordering::SeqCst);
|
||||
} else {
|
||||
LIVE.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// `IStream` as [`Read`].
|
||||
struct StreamReader(IStream);
|
||||
|
||||
impl Read for StreamReader {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
let len = u32::try_from(buf.len()).unwrap_or(u32::MAX);
|
||||
let mut read = 0u32;
|
||||
// SAFETY: `buf` holds at least `len` writable bytes, and `read` outlives the call.
|
||||
unsafe { self.0.Read(buf.as_mut_ptr().cast(), len, Some(&mut read)) }.ok().map_err(io::Error::other)?;
|
||||
usize::try_from(read).map_err(io::Error::other)
|
||||
}
|
||||
}
|
||||
|
||||
/// The picture of `document`, at most `cx` pixels on its longer side.
|
||||
fn thumbnail(document: &mut Document<StreamReader>, cx: u32) -> std::result::Result<Picture, String> {
|
||||
let size = crate::request_size(cx).ok_or("a thumbnail of 0 pixels")?;
|
||||
let bytes = document.bytes(MAX_FILE).map_err(|e| e.to_string())?;
|
||||
let dll = module_path()?;
|
||||
let cli = PathBuf::from(dll).parent().ok_or("the DLL's folder is unknown")?.join(CLI);
|
||||
let png = crate::render(&cli, bytes, size, &staging_folder(), DEADLINE)?;
|
||||
crate::picture(&png, size)
|
||||
}
|
||||
|
||||
/// Creates the thumbnail staging folder in LocalLow, falling back to the temp folder.
|
||||
fn staging_folder() -> PathBuf {
|
||||
// SAFETY: the folder ID is valid, and no token means the current user.
|
||||
let Ok(folder) = (unsafe { SHGetKnownFolderPath(&FOLDERID_LocalAppDataLow, KNOWN_FOLDER_FLAG(0), None) }) else {
|
||||
return std::env::temp_dir();
|
||||
};
|
||||
// SAFETY: the call returned a NUL-terminated path allocated by COM; copy it before freeing it.
|
||||
let path = unsafe {
|
||||
let path = PathBuf::from(std::ffi::OsString::from_wide(folder.as_wide()));
|
||||
CoTaskMemFree(Some(folder.0.cast()));
|
||||
path
|
||||
};
|
||||
let path = path.join("VectorCraft").join("Thumbnails");
|
||||
if std::fs::create_dir_all(&path).is_ok() { path } else { std::env::temp_dir() }
|
||||
}
|
||||
|
||||
/// `picture` as a top-down 32-bit DIB section.
|
||||
fn dib_section(picture: &Picture) -> Result<HBITMAP> {
|
||||
let bad = || Error::new(E_FAIL, "the picture's size is wrong");
|
||||
let width = i32::try_from(picture.width).map_err(|_| bad())?;
|
||||
let height = i32::try_from(picture.height).map_err(|_| bad())?;
|
||||
let len = usize::try_from(u64::from(picture.width) * u64::from(picture.height) * 4).map_err(|_| bad())?;
|
||||
if picture.bgra.len() != len {
|
||||
return Err(bad());
|
||||
}
|
||||
let info = BITMAPINFO {
|
||||
bmiHeader: BITMAPINFOHEADER {
|
||||
biSize: size_of::<BITMAPINFOHEADER>() as u32,
|
||||
biWidth: width,
|
||||
// A negative height: the rows go from top to bottom.
|
||||
biHeight: -height,
|
||||
biPlanes: 1,
|
||||
biBitCount: 32,
|
||||
biCompression: BI_RGB.0,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let mut bits: *mut c_void = null_mut();
|
||||
// SAFETY: `info` describes a 32-bit picture and `bits` outlives the call.
|
||||
let bitmap = unsafe { CreateDIBSection(None, &info, DIB_RGB_COLORS, &mut bits, None, 0) }?;
|
||||
if bits.is_null() {
|
||||
// SAFETY: `bitmap` was just made and nothing else holds it.
|
||||
unsafe {
|
||||
let _ = DeleteObject(bitmap.into());
|
||||
}
|
||||
return Err(Error::new(E_FAIL, "the bitmap has no pixels"));
|
||||
}
|
||||
// SAFETY: the DIB section holds `width * height * 4` bytes, `len`, and `bgra` holds `len` bytes.
|
||||
unsafe { std::ptr::copy_nonoverlapping(picture.bgra.as_ptr(), bits.cast::<u8>(), len) };
|
||||
Ok(bitmap)
|
||||
}
|
||||
|
||||
/// The path of this DLL.
|
||||
fn module_path() -> std::result::Result<String, String> {
|
||||
let module = HMODULE(MODULE.load(Ordering::SeqCst));
|
||||
if module.0.is_null() {
|
||||
return Err("the DLL's module handle is unknown".into());
|
||||
}
|
||||
let mut buf = vec![0u16; MAX_PATH];
|
||||
// SAFETY: `module` is this DLL's handle, which stays valid while the DLL is loaded.
|
||||
let len = unsafe { GetModuleFileNameW(Some(module), &mut buf) };
|
||||
let path = usize::try_from(len).ok().filter(|&n| n > 0 && n < buf.len()).and_then(|n| buf.get(..n)).ok_or("the DLL's path is unknown")?;
|
||||
String::from_utf16(path).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Writes `value` under `Software\Classes` of the current user.
|
||||
fn set(value: &RegistryValue) -> Result<()> {
|
||||
let key = HSTRING::from(format!("{CLASSES}\\{}", value.key));
|
||||
let name = value.name.map(HSTRING::from);
|
||||
let name = name.as_ref().map_or(PCWSTR::null(), |n| PCWSTR(n.as_ptr()));
|
||||
let data: Vec<u16> = value.data.encode_utf16().chain([0]).collect();
|
||||
let bytes = u32::try_from(data.len() * 2).map_err(|_| Error::from(E_FAIL))?;
|
||||
// SAFETY: `data` holds `bytes` bytes of a NUL-terminated string, and the names outlive the call.
|
||||
unsafe { RegSetKeyValueW(HKEY_CURRENT_USER, &key, name, REG_SZ.0, Some(data.as_ptr().cast()), bytes) }.ok()
|
||||
}
|
||||
|
||||
/// The default value of `key` under `Software\Classes` of the current user, when it is a string.
|
||||
fn default_value(key: &str) -> Option<String> {
|
||||
let key = HSTRING::from(format!("{CLASSES}\\{key}"));
|
||||
let mut buf = [0u16; 128];
|
||||
let mut bytes = u32::try_from(buf.len() * 2).ok()?;
|
||||
// SAFETY: `buf` holds `bytes` writable bytes, and `bytes` outlives the call.
|
||||
unsafe { RegGetValueW(HKEY_CURRENT_USER, &key, PCWSTR::null(), RRF_RT_REG_SZ, None, Some(buf.as_mut_ptr().cast()), Some(&mut bytes)) }
|
||||
.ok()
|
||||
.ok()?;
|
||||
let units = buf.get(..usize::try_from(bytes / 2).ok()?)?;
|
||||
String::from_utf16(units).ok().map(|s| s.trim_end_matches('\0').to_owned())
|
||||
}
|
||||
|
||||
/// Removes `key` under `Software\Classes` of the current user with its subkeys; a key that isn't
|
||||
/// there is no error.
|
||||
fn remove(key: &str) -> Result<()> {
|
||||
let key = HSTRING::from(format!("{CLASSES}\\{key}"));
|
||||
// SAFETY: `key` outlives the call.
|
||||
match unsafe { RegDeleteTreeW(HKEY_CURRENT_USER, &key) } {
|
||||
ERROR_FILE_NOT_FOUND => Ok(()),
|
||||
e => e.ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Tells Explorer that file associations changed, so it asks for thumbnails again.
|
||||
fn associations_changed() {
|
||||
// SAFETY: SHCNE_ASSOCCHANGED takes no items.
|
||||
unsafe { SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, None, None) };
|
||||
}
|
||||
|
||||
/// Registers the handler for the current user ([`crate::registry_values`]).
|
||||
fn register() -> Result<()> {
|
||||
let dll = module_path().map_err(|e| Error::new(E_FAIL, e))?;
|
||||
crate::registry_values(&dll).iter().try_for_each(set)
|
||||
}
|
||||
|
||||
/// Removes the class key and each extension's thumbnail handler key that names this handler.
|
||||
fn unregister() -> Result<()> {
|
||||
for ext in crate::EXTENSIONS {
|
||||
let key = crate::shell_ex_key(ext);
|
||||
if default_value(&key).is_some_and(|v| crate::names_this_handler(&v)) {
|
||||
remove(&key)?;
|
||||
}
|
||||
}
|
||||
remove(&crate::class_key())
|
||||
}
|
||||
|
||||
/// Keeps the DLL's module handle for [`module_path`].
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn DllMain(module: HINSTANCE, reason: u32, _reserved: *mut c_void) -> BOOL {
|
||||
if reason == DLL_PROCESS_ATTACH {
|
||||
MODULE.store(module.0, Ordering::SeqCst);
|
||||
}
|
||||
true.into()
|
||||
}
|
||||
|
||||
/// COM's request for the class factory of class `class`.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `class` and `iid` point to GUIDs and `object` to writable memory for an interface pointer, as
|
||||
/// COM passes them.
|
||||
#[unsafe(no_mangle)]
|
||||
unsafe extern "system" fn DllGetClassObject(class: *const GUID, iid: *const GUID, object: *mut *mut c_void) -> HRESULT {
|
||||
if class.is_null() || iid.is_null() || object.is_null() {
|
||||
return E_POINTER;
|
||||
}
|
||||
// SAFETY: the caller passes valid pointers, checked for null above.
|
||||
unsafe {
|
||||
*object = null_mut();
|
||||
if *class != CLASS_ID {
|
||||
return CLASS_E_CLASSNOTAVAILABLE;
|
||||
}
|
||||
let factory: IClassFactory = Factory::new().into();
|
||||
factory.query(iid, object)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether COM may unload the DLL: no provider or class factory is alive and no lock is held.
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn DllCanUnloadNow() -> HRESULT {
|
||||
if LIVE.load(Ordering::SeqCst) == 0 { S_OK } else { S_FALSE }
|
||||
}
|
||||
|
||||
/// `regsvr32`: registers the handler for the current user.
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn DllRegisterServer() -> HRESULT {
|
||||
let result = register();
|
||||
if result.is_err() {
|
||||
let _ = unregister();
|
||||
}
|
||||
associations_changed();
|
||||
result.map_or_else(|e| e.code(), |()| S_OK)
|
||||
}
|
||||
|
||||
/// `regsvr32 /u`: removes the current user's registration.
|
||||
#[unsafe(no_mangle)]
|
||||
extern "system" fn DllUnregisterServer() -> HRESULT {
|
||||
let result = unregister();
|
||||
associations_changed();
|
||||
result.map_or_else(|e| e.code(), |()| S_OK)
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
//! Windows: the thumbnail handler that Explorer and the file dialogs run for `.vectorcraft`,
|
||||
//! `.drawcraft` and `.vctemplate` files. It is a COM server DLL whose class implements
|
||||
//! `IThumbnailProvider` and `IInitializeWithStream`
|
||||
//! (<https://learn.microsoft.com/windows/win32/shell/thumbnail-providers>,
|
||||
//! <https://learn.microsoft.com/windows/win32/api/thumbcache/nn-thumbcache-ithumbnailprovider>).
|
||||
//!
|
||||
//! Explorer gives the handler the file's bytes as a stream. The handler writes them to a new file
|
||||
//! in `%USERPROFILE%\AppData\LocalLow\VectorCraft\Thumbnails` (falling back to the temp folder),
|
||||
//! runs `vectorcraft-cli thumbnail --size N IN OUT` from the DLL's folder on
|
||||
//! it, and returns the PNG that command writes (the first artboard, else the art, drawn by
|
||||
//! `vectorcraft_render::encode::first_artboard`) as a 32-bit DIB section with alpha. A file larger
|
||||
//! than 256 MiB, a document that can't be opened or shows nothing, and a `vectorcraft-cli` run
|
||||
//! longer than [`DEADLINE`] give Explorer an error, and Explorer shows the file's icon. Rendering
|
||||
//! runs in the `vectorcraft-cli` process, so a file that makes it fail or hang ends that process.
|
||||
//! The handler is not given the file's path (`IInitializeWithStream` is the only initialization
|
||||
//! an isolated handler gets), so a linked image found only relative to the document's folder
|
||||
//! shows the preview saved with it.
|
||||
//!
|
||||
//! `regsvr32 vectorcraft_thumbnail_handler.dll` registers the handler for the current user, and
|
||||
//! `regsvr32 /u` removes it ([`registry_values`]). The COM parts build on Windows only; the parts
|
||||
//! in this file build everywhere and their tests run on every system.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::fs::File;
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[cfg(windows)]
|
||||
mod com;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// The handler's class id: the key under `CLSID`, and the value of each extension's `ShellEx` key.
|
||||
pub const CLSID: &str = "{1971F5DA-D761-4655-AB25-6B3825BD1748}";
|
||||
/// [`CLSID`] as a number, the form COM compares.
|
||||
pub const CLSID_VALUE: u128 = 0x1971_f5da_d761_4655_ab25_6b38_25bd_1748;
|
||||
/// The `ShellEx` subkey that names an extension's thumbnail handler, the interface id of
|
||||
/// `IThumbnailProvider` (<https://learn.microsoft.com/windows/win32/shell/thumbnail-providers>).
|
||||
pub const THUMBNAIL_SHELL_EX: &str = "{e357fccd-a995-4576-b01f-234630154e96}";
|
||||
/// The extensions the handler is registered for: documents, documents under their former
|
||||
/// extension, and templates (the globs of `packaging/linux/ai.storyteller.vectorcraft.mime.xml`).
|
||||
pub const EXTENSIONS: &[&str] = &[".vectorcraft", ".drawcraft", ".vctemplate"];
|
||||
/// The description in the class key.
|
||||
pub const DESCRIPTION: &str = "VectorCraft document thumbnail handler";
|
||||
/// The largest file the handler reads, in bytes, the limit `vectorcraft-cli thumbnail` applies.
|
||||
pub const MAX_FILE: u64 = 256 << 20;
|
||||
/// The largest `--size` `vectorcraft-cli thumbnail` takes. Explorer asks for sizes up to 1024.
|
||||
pub const MAX_SIDE: u32 = 1024;
|
||||
/// The largest PNG the handler reads back, in bytes: an uncompressed 1024 by 1024 RGBA picture
|
||||
/// with room for the chunks around it.
|
||||
pub const MAX_PNG: u64 = 8 << 20;
|
||||
/// How long the handler waits for `vectorcraft-cli` before it ends the process: the command's
|
||||
/// own 20-second limit and 5 seconds to start.
|
||||
pub const DEADLINE: Duration = Duration::from_secs(25);
|
||||
/// How often the handler checks whether `vectorcraft-cli` has exited.
|
||||
const POLL: Duration = Duration::from_millis(10);
|
||||
/// The program the handler runs, in the DLL's folder.
|
||||
pub const CLI: &str = "vectorcraft-cli.exe";
|
||||
|
||||
/// A picture in the layout Explorer takes: rows from top to bottom, 4 bytes per pixel in blue,
|
||||
/// green, red and alpha order, with the colors premultiplied by alpha.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Picture {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub bgra: Vec<u8>,
|
||||
}
|
||||
|
||||
/// One registry value the handler writes, under `Software\Classes` of the current user.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RegistryValue {
|
||||
/// The key, relative to `Software\Classes`.
|
||||
pub key: String,
|
||||
/// The value's name; `None` is the key's default value.
|
||||
pub name: Option<&'static str>,
|
||||
/// The string the value holds.
|
||||
pub data: String,
|
||||
}
|
||||
|
||||
/// The class key, relative to `Software\Classes`.
|
||||
pub fn class_key() -> String {
|
||||
format!("CLSID\\{CLSID}")
|
||||
}
|
||||
|
||||
/// The key that names `extension`'s thumbnail handler, relative to `Software\Classes`.
|
||||
pub fn shell_ex_key(extension: &str) -> String {
|
||||
format!("{extension}\\ShellEx\\{THUMBNAIL_SHELL_EX}")
|
||||
}
|
||||
|
||||
/// The values that register the handler in the DLL at path `dll`: the class with its server and
|
||||
/// threading model, and the class as the thumbnail handler of each of [`EXTENSIONS`], as
|
||||
/// <https://learn.microsoft.com/windows/win32/shell/thumbnail-providers> describes.
|
||||
pub fn registry_values(dll: &str) -> Vec<RegistryValue> {
|
||||
let class = class_key();
|
||||
let server = format!("{class}\\InprocServer32");
|
||||
let mut values = vec![
|
||||
RegistryValue { key: class, name: None, data: DESCRIPTION.into() },
|
||||
RegistryValue { key: server.clone(), name: None, data: dll.into() },
|
||||
RegistryValue { key: server, name: Some("ThreadingModel"), data: "Apartment".into() },
|
||||
];
|
||||
values.extend(EXTENSIONS.iter().map(|ext| RegistryValue { key: shell_ex_key(ext), name: None, data: CLSID.into() }));
|
||||
values
|
||||
}
|
||||
|
||||
/// Whether `value`, the default value of an extension's `ShellEx` key, names this handler: class
|
||||
/// ids are compared without regard to letter case. `regsvr32 /u` removes only such keys.
|
||||
pub fn names_this_handler(value: &str) -> bool {
|
||||
value.trim().eq_ignore_ascii_case(CLSID)
|
||||
}
|
||||
|
||||
/// Reads all of `r` when it holds at most `max` bytes, else returns an error.
|
||||
pub fn read_bounded(r: impl Read, max: u64) -> io::Result<Vec<u8>> {
|
||||
let mut bytes = Vec::new();
|
||||
r.take(max.saturating_add(1)).read_to_end(&mut bytes)?;
|
||||
if u64::try_from(bytes.len()).map_or(true, |n| n > max) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, format!("larger than {max} bytes")));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// The document Explorer passed as a stream. Its bytes are read on the first request and kept, so
|
||||
/// a later request on the same handler, at another size for example, gets the same document.
|
||||
pub struct Document<R> {
|
||||
stream: Option<R>,
|
||||
bytes: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl<R: Read> Document<R> {
|
||||
pub fn new(stream: R) -> Self {
|
||||
Self { stream: Some(stream), bytes: None }
|
||||
}
|
||||
|
||||
/// The document's bytes, read from the stream when it holds at most `max` bytes. When the
|
||||
/// first read fails, this call and every later one return an error.
|
||||
pub fn bytes(&mut self, max: u64) -> io::Result<&[u8]> {
|
||||
if let Some(stream) = self.stream.take() {
|
||||
self.bytes = Some(read_bounded(stream, max)?);
|
||||
}
|
||||
self.bytes.as_deref().ok_or_else(|| io::Error::other("the document's stream could not be read"))
|
||||
}
|
||||
}
|
||||
|
||||
/// The `--size` for Explorer's request of a picture `cx` pixels on its longer side: `cx`, at most
|
||||
/// [`MAX_SIDE`]; `None` for 0.
|
||||
pub fn request_size(cx: u32) -> Option<u32> {
|
||||
(cx > 0).then(|| cx.min(MAX_SIDE))
|
||||
}
|
||||
|
||||
/// The arguments of `vectorcraft-cli` that write the thumbnail of `input` to `output`, `size`
|
||||
/// pixels on its longer side.
|
||||
pub fn arguments(size: u32, input: &Path, output: &Path) -> Vec<OsString> {
|
||||
vec!["thumbnail".into(), "--size".into(), size.to_string().into(), input.into(), output.into()]
|
||||
}
|
||||
|
||||
/// A file the handler made in the temp folder, removed when dropped.
|
||||
struct TempFile(PathBuf);
|
||||
|
||||
impl Drop for TempFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `bytes` to a new file `vectorcraft-thumbnail-<pid>-<n>.vectorcraft` in `dir`, with the
|
||||
/// first `n` whose name no file has.
|
||||
fn write_input(dir: &Path, bytes: &[u8]) -> io::Result<TempFile> {
|
||||
use std::io::Write;
|
||||
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
loop {
|
||||
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let path = dir.join(format!("vectorcraft-thumbnail-{}-{n}.vectorcraft", std::process::id()));
|
||||
match File::options().write(true).create_new(true).open(&path) {
|
||||
Ok(mut file) => {
|
||||
let temp = TempFile(path);
|
||||
file.write_all(bytes)?;
|
||||
return Ok(temp);
|
||||
}
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `cli thumbnail --size SIZE IN OUT` with `bytes` written to a new file IN in `dir` and
|
||||
/// returns the PNG it writes to OUT, IN's name with `.png`. The process is ended when it runs
|
||||
/// longer than `deadline`. IN and OUT are removed before this returns.
|
||||
pub fn render(cli: &Path, bytes: &[u8], size: u32, dir: &Path, deadline: Duration) -> Result<Vec<u8>, String> {
|
||||
let input = write_input(dir, bytes).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let output = TempFile(input.0.with_extension("png"));
|
||||
let mut command = Command::new(cli);
|
||||
command.args(arguments(size, &input.0, &output.0)).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
|
||||
no_console_window(&mut command);
|
||||
let mut child = command.spawn().map_err(|e| format!("{}: {e}", cli.display()))?;
|
||||
let end = Instant::now() + deadline;
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait().map_err(|e| format!("{}: {e}", cli.display()))? {
|
||||
break status;
|
||||
}
|
||||
if Instant::now() >= end {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(format!("{} ran longer than {} seconds", cli.display(), deadline.as_secs()));
|
||||
}
|
||||
std::thread::sleep(POLL);
|
||||
};
|
||||
if !status.success() {
|
||||
return Err(format!("{} exited with {status}", cli.display()));
|
||||
}
|
||||
let png = File::open(&output.0).and_then(|f| read_bounded(f, MAX_PNG)).map_err(|e| format!("{}: {e}", output.0.display()))?;
|
||||
Ok(png)
|
||||
}
|
||||
|
||||
/// Starts `command` without a console window (`CREATE_NO_WINDOW`,
|
||||
/// <https://learn.microsoft.com/windows/win32/procthread/process-creation-flags>).
|
||||
#[cfg(windows)]
|
||||
fn no_console_window(command: &mut Command) {
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn no_console_window(_: &mut Command) {}
|
||||
|
||||
/// The 8-bit RGBA PNG `png` (what `vectorcraft-cli thumbnail` writes, with straight alpha) as a
|
||||
/// [`Picture`]. An error
|
||||
/// when it can't be decoded, has another pixel format, or is empty or larger than `max_side`
|
||||
/// pixels on a side.
|
||||
pub fn picture(png: &[u8], max_side: u32) -> Result<Picture, String> {
|
||||
let mut reader = png::Decoder::new(io::Cursor::new(png)).read_info().map_err(|e| e.to_string())?;
|
||||
let (width, height) = (reader.info().width, reader.info().height);
|
||||
if width == 0 || height == 0 || width > max_side || height > max_side {
|
||||
return Err(format!("a {width} by {height} picture, not 1 to {max_side} pixels on each side"));
|
||||
}
|
||||
let mut buf = vec![0; reader.output_buffer_size().ok_or("the picture is too large")?];
|
||||
let frame = reader.next_frame(&mut buf).map_err(|e| e.to_string())?;
|
||||
if (frame.color_type, frame.bit_depth) != (png::ColorType::Rgba, png::BitDepth::Eight) {
|
||||
return Err(format!("a {:?} {:?} picture, not 8-bit RGBA", frame.bit_depth, frame.color_type));
|
||||
}
|
||||
let rgba = buf.get(..frame.buffer_size()).ok_or("the picture is cut short")?;
|
||||
let bgra = rgba.as_chunks::<4>().0.iter().flat_map(|&[r, g, b, a]| [premultiply(b, a), premultiply(g, a), premultiply(r, a), a]).collect();
|
||||
Ok(Picture { width, height, bgra })
|
||||
}
|
||||
|
||||
/// Color `c` multiplied by alpha `a`, both 0 to 255, rounded to the nearest value.
|
||||
fn premultiply(c: u8, a: u8) -> u8 {
|
||||
u8::try_from((u16::from(c) * u16::from(a) + 127) / 255).unwrap_or(u8::MAX)
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
use std::path::Path;
|
||||
|
||||
use super::*;
|
||||
|
||||
const MIME: &str = include_str!("../../../packaging/linux/ai.storyteller.vectorcraft.mime.xml");
|
||||
|
||||
/// A PNG of `width`×`height` pixels with `data` as its samples.
|
||||
fn png_of(width: u32, height: u32, color: png::ColorType, data: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut encoder = png::Encoder::new(&mut out, width, height);
|
||||
encoder.set_color(color);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
let mut writer = encoder.write_header().unwrap();
|
||||
writer.write_image_data(data).unwrap();
|
||||
writer.finish().unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
/// An empty folder `vectorcraft-thumbnail-handler-<pid>-<name>` in the temp folder.
|
||||
#[cfg(unix)]
|
||||
fn folder(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-thumbnail-handler-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// The names of the files in `dir`.
|
||||
#[cfg(unix)]
|
||||
fn files_in(dir: &Path) -> Vec<String> {
|
||||
let mut names: Vec<String> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_class_id_string_and_number_are_the_same_id() {
|
||||
let hex = format!("{CLSID_VALUE:032X}");
|
||||
let grouped = format!("{{{}-{}-{}-{}-{}}}", &hex[..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..]);
|
||||
assert_eq!(grouped, CLSID);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registration_names_the_dll_and_the_handler_of_every_extension() {
|
||||
let values = registry_values("C:\\Program Files\\VectorCraft\\vectorcraft_thumbnail_handler.dll");
|
||||
let class = format!("CLSID\\{CLSID}");
|
||||
let server = format!("{class}\\InprocServer32");
|
||||
let want = vec![
|
||||
RegistryValue { key: class, name: None, data: DESCRIPTION.into() },
|
||||
RegistryValue { key: server.clone(), name: None, data: "C:\\Program Files\\VectorCraft\\vectorcraft_thumbnail_handler.dll".into() },
|
||||
RegistryValue { key: server, name: Some("ThreadingModel"), data: "Apartment".into() },
|
||||
RegistryValue { key: format!(".vectorcraft\\ShellEx\\{THUMBNAIL_SHELL_EX}"), name: None, data: CLSID.into() },
|
||||
RegistryValue { key: format!(".drawcraft\\ShellEx\\{THUMBNAIL_SHELL_EX}"), name: None, data: CLSID.into() },
|
||||
RegistryValue { key: format!(".vctemplate\\ShellEx\\{THUMBNAIL_SHELL_EX}"), name: None, data: CLSID.into() },
|
||||
];
|
||||
assert_eq!(values, want);
|
||||
assert_eq!(THUMBNAIL_SHELL_EX.to_ascii_uppercase(), "{E357FCCD-A995-4576-B01F-234630154E96}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_extensions_are_the_globs_of_the_document_and_template_types() {
|
||||
let mut globs = Vec::new();
|
||||
let mut in_type = false;
|
||||
for line in MIME.lines().map(str::trim) {
|
||||
if let Some(rest) = line.strip_prefix("<mime-type type=\"") {
|
||||
in_type = matches!(rest.split('"').next(), Some("application/x-vectorcraft" | "application/x-vectorcraft-template"));
|
||||
} else if in_type && let Some(rest) = line.strip_prefix("<glob pattern=\"*") {
|
||||
globs.push(rest.split('"').next().unwrap().to_owned());
|
||||
}
|
||||
}
|
||||
assert_eq!(globs, EXTENSIONS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_this_class_id_names_this_handler() {
|
||||
assert!(names_this_handler(CLSID));
|
||||
assert!(names_this_handler(&CLSID.to_ascii_lowercase()));
|
||||
assert!(!names_this_handler("{C7657C4A-9F68-40FA-A4DF-96BC08EB3551}"));
|
||||
assert!(!names_this_handler(""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_larger_than_the_limit_is_refused() {
|
||||
assert_eq!(read_bounded(&[7u8; 10][..], 10).unwrap(), vec![7; 10]);
|
||||
assert_eq!(read_bounded(&[][..], 10).unwrap(), Vec::<u8>::new());
|
||||
assert_eq!(read_bounded(&[7u8; 11][..], 10).unwrap_err().kind(), io::ErrorKind::InvalidData);
|
||||
assert!(read_bounded(&[7u8; 11][..], u64::MAX).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_request_gets_the_same_document() {
|
||||
let mut document = Document::new(io::Cursor::new(vec![1u8, 2, 3]));
|
||||
assert_eq!(document.bytes(10).unwrap(), [1, 2, 3]);
|
||||
assert_eq!(document.bytes(10).unwrap(), [1, 2, 3]);
|
||||
|
||||
let mut large = Document::new(&[7u8; 11][..]);
|
||||
assert_eq!(large.bytes(10).unwrap_err().kind(), io::ErrorKind::InvalidData);
|
||||
assert!(large.bytes(10).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_size_asked_of_the_command_is_at_most_its_limit() {
|
||||
assert_eq!(request_size(0), None);
|
||||
assert_eq!(request_size(1), Some(1));
|
||||
assert_eq!(request_size(256), Some(256));
|
||||
assert_eq!(request_size(MAX_SIDE), Some(MAX_SIDE));
|
||||
assert_eq!(request_size(2048), Some(MAX_SIDE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_line_is_thumbnail_size_input_output() {
|
||||
let args = arguments(96, Path::new("in.vectorcraft"), Path::new("out.png"));
|
||||
assert_eq!(args, ["thumbnail", "--size", "96", "in.vectorcraft", "out.png"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_rgba_png_becomes_top_down_premultiplied_bgra() {
|
||||
// Two rows: opaque red and half-transparent blue, then 20% white and a clear white pixel.
|
||||
let rgba = [255, 0, 0, 255, 0, 0, 255, 128, 255, 255, 255, 51, 255, 255, 255, 0];
|
||||
let picture = picture(&png_of(2, 2, png::ColorType::Rgba, &rgba), 2).unwrap();
|
||||
assert_eq!((picture.width, picture.height), (2, 2));
|
||||
assert_eq!(picture.bgra, [0, 0, 255, 255, 128, 0, 0, 128, 51, 51, 51, 51, 0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_png_that_is_not_an_rgba_thumbnail_is_refused() {
|
||||
assert!(picture(&png_of(1, 1, png::ColorType::Rgb, &[1, 2, 3]), 8).is_err());
|
||||
assert!(picture(&png_of(3, 1, png::ColorType::Rgba, &[0; 12]), 2).is_err(), "wider than asked");
|
||||
assert!(picture(&png_of(1, 3, png::ColorType::Rgba, &[0; 12]), 2).is_err(), "taller than asked");
|
||||
assert!(picture(b"not a picture", 8).is_err());
|
||||
let png = png_of(2, 2, png::ColorType::Rgba, &[9; 16]);
|
||||
assert!(picture(&png[..png.len() - 20], 8).is_err(), "cut short");
|
||||
}
|
||||
|
||||
/// `render` runs the program with the thumbnail arguments, returns what it writes to OUT, gives
|
||||
/// an error for a failed or overlong run, and leaves no file behind. The stand-ins are shell
|
||||
/// scripts, all written before the first one runs.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn render_runs_the_command_and_removes_its_files() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::time::Duration;
|
||||
let dir = folder("render");
|
||||
let temp = dir.join("temp");
|
||||
std::fs::create_dir(&temp).unwrap();
|
||||
let png = png_of(1, 1, png::ColorType::Rgba, &[1, 2, 3, 4]);
|
||||
std::fs::write(dir.join("picture.png"), &png).unwrap();
|
||||
std::fs::write(dir.join("document"), b"document bytes").unwrap();
|
||||
let script = |name: &str, body: &str| {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
path
|
||||
};
|
||||
let d = dir.display();
|
||||
let writes = script(
|
||||
"writes",
|
||||
&format!(
|
||||
"[ \"$1 $2 $3\" = \"thumbnail --size 64\" ] || exit 4\ncase \"$4\" in *.vectorcraft) ;; *) exit 5 ;; esac\n\
|
||||
cmp -s \"$4\" '{d}/document' || exit 3\ncp '{d}/picture.png' \"$5\""
|
||||
),
|
||||
);
|
||||
let fails = script("fails", "echo broken >&2\nexit 1");
|
||||
let silent = script("silent", "exit 0");
|
||||
let hangs = script("hangs", "exec sleep 30");
|
||||
|
||||
assert_eq!(render(&writes, b"document bytes", 64, &temp, DEADLINE).unwrap(), png);
|
||||
assert!(render(&fails, b"x", 64, &temp, DEADLINE).unwrap_err().contains("exited with"));
|
||||
assert!(render(&silent, b"x", 64, &temp, DEADLINE).is_err(), "no OUT written");
|
||||
assert!(render(&hangs, b"x", 64, &temp, Duration::ZERO).unwrap_err().contains("ran longer than"));
|
||||
assert!(render(&dir.join("missing"), b"x", 64, &temp, DEADLINE).is_err());
|
||||
assert_eq!(files_in(&temp), Vec::<String>::new());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -27,10 +27,10 @@ log = { workspace = true }
|
||||
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "6fcf61c816c399508a60c7029a59e2c7b6139e0b", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "610c86792a02aa3d416926ee44e3ec3788dea853", version = "0.1.0" }
|
||||
|
||||
wasm-bindgen = "0.2"
|
||||
serde_json = { workspace = true }
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "0.3"
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlInputElement", "KeyboardEvent", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlInputElement", "KeyboardEvent", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal", "Node", "Worker", "MessageEvent", "ErrorEvent", "Performance"] }
|
||||
@@ -17,6 +17,8 @@
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="icons/32/ai.storyteller.vectorcraft.png">
|
||||
<link rel="apple-touch-icon" href="icons/256/ai.storyteller.vectorcraft.png">
|
||||
<link data-trunk rel="rust" data-bin="vectorcraft-web" data-wasm-opt="z" data-weak-refs />
|
||||
<!-- The plug-in worker: checks plug-ins being installed and runs filters off the page (apps/vectorcraft-plugin-worker). -->
|
||||
<link data-trunk rel="rust" href="../vectorcraft-plugin-worker/Cargo.toml" data-bin="vectorcraft-plugin-worker" data-type="worker" data-loader-shim data-wasm-opt="z" />
|
||||
<style>
|
||||
/* iPad: no page scroll, bounce, pinch zoom, text selection or callout; the app takes the gestures. */
|
||||
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #262626;
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
//! - no TCP control server (browsers can't listen on sockets);
|
||||
//! - File → Open uses the browser file picker, through the host's file service (`BrowserFiles`);
|
||||
//! - Save / Export trigger a browser download;
|
||||
//! - plug-ins are checked when installed, and filters run, in Web Workers of their own
|
||||
//! (`plugin_workers`, the `vectorcraft-plugin-worker` build), so a plug-in never runs on the page;
|
||||
//! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox;
|
||||
//! - pen and finger input is read from Pointer Events by `pencil` (Apple Pencil pressure and
|
||||
//! hover, palm rejection, fingers navigate once a pen has been seen, the pen's eraser end
|
||||
@@ -28,6 +30,8 @@ mod keys;
|
||||
mod locks;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod pencil;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod plugin_workers;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod saved_files;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -53,6 +53,20 @@ pub struct Pointers {
|
||||
/// The pen's pressure and end for the canvas, the source the install reads.
|
||||
// PLAN: named `source`, not `pen`: `pen` is the pressing pen's pointer id above.
|
||||
source: PenSource,
|
||||
/// The pen whose finger wheel is read ([`Pointers::wheel`]).
|
||||
wheel: Option<Wheel>,
|
||||
/// Every reading written into the source, in order.
|
||||
#[cfg(test)]
|
||||
readings: Vec<PointerSample>,
|
||||
}
|
||||
|
||||
/// A pen, by pointer id and the end it is turned to, and whether it has reported a tangential
|
||||
/// pressure other than 0 since it came near.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Wheel {
|
||||
id: i32,
|
||||
eraser: bool,
|
||||
reads: bool,
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -64,6 +78,11 @@ struct Input<'a> {
|
||||
id: i32,
|
||||
button: i16,
|
||||
pressure: f32,
|
||||
/// Pointer Events' `tangentialPressure`, −1..1: an airbrush pen's finger wheel.
|
||||
tangential: f32,
|
||||
/// Whether the event names an element the pointer moved onto (`relatedTarget`): a pen leaving
|
||||
/// one element for another is still in its hover range.
|
||||
entered: bool,
|
||||
modifiers: egui::Modifiers,
|
||||
}
|
||||
|
||||
@@ -90,11 +109,29 @@ impl Pointers {
|
||||
self.source.clone()
|
||||
}
|
||||
|
||||
/// A pen moved or pressed with `pressure`, with the end it last pressed with.
|
||||
fn pen_sample(&self, pressure: f32) {
|
||||
/// A pen pressed, moved or lifted with `pressure` and `wheel`, with the end it last pressed
|
||||
/// with. The source queues each reading, and the runtime pairs the readings with the frame's
|
||||
/// pointer moves, so each move written after its own reading keeps that reading's wheel.
|
||||
fn pen_sample(&mut self, pressure: f32, wheel: Option<f32>) {
|
||||
let mut sample = PointerSample::new(pressure);
|
||||
sample.eraser = self.eraser;
|
||||
sample.wheel = wheel;
|
||||
self.source.set(Some(sample));
|
||||
#[cfg(test)]
|
||||
self.readings.push(sample);
|
||||
}
|
||||
|
||||
/// The finger wheel of pen `id`, turned to the end it last pressed with, for a sample with
|
||||
/// Pointer Events' `tangentialPressure` (−1..1,
|
||||
/// <https://www.w3.org/TR/pointerevents3/#dom-pointerevent-tangentialpressure>): a wheel of
|
||||
/// 0..1, −1 at 0 and 1 at 1, a value past either end clamped. Pointer Events give 0 for a pen
|
||||
/// without a wheel, so 0 reads as none until that pen, with that end, has reported a value
|
||||
/// other than 0 since it came near. A value that is not a number is none.
|
||||
fn wheel(&mut self, id: i32, tangential: f32) -> Option<f32> {
|
||||
let known = self.wheel.is_some_and(|w| w.id == id && w.eraser == self.eraser && w.reads);
|
||||
let reads = known || (tangential.is_finite() && tangential != 0.0);
|
||||
self.wheel = Some(Wheel { id, eraser: self.eraser, reads });
|
||||
(reads && tangential.is_finite()).then(|| (tangential.clamp(-1.0, 1.0) + 1.0) / 2.0)
|
||||
}
|
||||
|
||||
fn touch(&mut self, device: TouchDeviceId, id: i32, phase: TouchPhase, pos: Pos2, force: Option<f32>) {
|
||||
@@ -134,7 +171,10 @@ impl Pointers {
|
||||
}
|
||||
|
||||
/// Follow one pointer event; `true` if it was the pen's or a finger's (taken from eframe).
|
||||
fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32)], on_canvas: bool) -> bool {
|
||||
///
|
||||
/// `coalesced` holds the positions the pen reported since the last event, each with its
|
||||
/// pressure and tangential pressure, the last one at `pos`.
|
||||
fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32, f32)], on_canvas: bool) -> bool {
|
||||
let id = e.id;
|
||||
if e.pointer_type != "pen" && self.pen.is_none() && matches!(kind, "pointerdown" | "pointermove") {
|
||||
// Another pointer moved while no pen presses (a palm under a pen pressing is
|
||||
@@ -163,19 +203,24 @@ impl Pointers {
|
||||
if let Some(end) = end {
|
||||
self.eraser = end;
|
||||
}
|
||||
self.pen_sample(e.pressure);
|
||||
let wheel = self.wheel(id, e.tangential);
|
||||
self.pen_sample(e.pressure, wheel);
|
||||
self.pen = Some(id);
|
||||
self.touch(PEN_DEVICE, id, TouchPhase::Start, pos, force);
|
||||
self.press(id, pos, button, e.modifiers);
|
||||
}
|
||||
"pointermove" if self.pen == Some(id) => {
|
||||
self.pen_sample(e.pressure);
|
||||
// The positions the pen reported between two events (up to 240 a second
|
||||
// on an iPad), each with its pressure, so fast strokes keep their curve.
|
||||
for c in coalesced.iter().take(coalesced.len().saturating_sub(1)) {
|
||||
self.touch(PEN_DEVICE, id, TouchPhase::Move, c.0, Some(c.1));
|
||||
self.events.push(Event::PointerMoved(c.0));
|
||||
// on an iPad), each with its pressure and wheel, so fast strokes keep
|
||||
// their curve.
|
||||
for &(at, pressure, tangential) in coalesced.iter().take(coalesced.len().saturating_sub(1)) {
|
||||
let wheel = self.wheel(id, tangential);
|
||||
self.pen_sample(pressure, wheel);
|
||||
self.touch(PEN_DEVICE, id, TouchPhase::Move, at, Some(pressure));
|
||||
self.events.push(Event::PointerMoved(at));
|
||||
}
|
||||
let wheel = self.wheel(id, e.tangential);
|
||||
self.pen_sample(e.pressure, wheel);
|
||||
self.touch(PEN_DEVICE, id, TouchPhase::Move, pos, force);
|
||||
self.events.push(Event::PointerMoved(pos));
|
||||
}
|
||||
@@ -189,12 +234,19 @@ impl Pointers {
|
||||
}
|
||||
// Pointer Events report no end while a pen hovers: it keeps the end it
|
||||
// last pressed with.
|
||||
self.pen_sample(e.pressure);
|
||||
let wheel = self.wheel(id, e.tangential);
|
||||
self.pen_sample(e.pressure, wheel);
|
||||
self.events.push(Event::PointerMoved(pos));
|
||||
}
|
||||
"pointerup" | "pointercancel" if self.pen == Some(id) => {
|
||||
let phase = if kind == "pointerup" { TouchPhase::End } else { TouchPhase::Cancel };
|
||||
self.pen_sample(0.0);
|
||||
let (phase, wheel) = if kind == "pointerup" {
|
||||
// Lifted, the pen hovers on and keeps what it read of its wheel.
|
||||
(TouchPhase::End, self.wheel(id, e.tangential))
|
||||
} else {
|
||||
self.wheel = None;
|
||||
(TouchPhase::Cancel, None)
|
||||
};
|
||||
self.pen_sample(0.0, wheel);
|
||||
self.pen = None;
|
||||
self.touch(PEN_DEVICE, id, phase, pos, None);
|
||||
self.release(pos, e.modifiers);
|
||||
@@ -204,6 +256,13 @@ impl Pointers {
|
||||
if kind == "pointerleave" && self.primary.is_none() && on_canvas {
|
||||
self.events.push(Event::PointerGone);
|
||||
}
|
||||
// Left the hover range (a leave onto no element, on the canvas or off it)
|
||||
// or canceled: the pen reads its wheel afresh. Moving onto another element
|
||||
// keeps what it read.
|
||||
let gone = (kind == "pointerleave" && !e.entered && self.pen.is_none()) || kind == "pointercancel";
|
||||
if gone && self.wheel.is_some_and(|w| w.id == id) {
|
||||
self.wheel = None;
|
||||
}
|
||||
return self.pen.is_some();
|
||||
}
|
||||
}
|
||||
@@ -276,7 +335,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement,
|
||||
let z = runner.egui_ctx().zoom_factor();
|
||||
let pos = egui::pos2((e.client_x() as f32 - rect.left() as f32) / z, (e.client_y() as f32 - rect.top() as f32) / z);
|
||||
let at = |x: i32, y: i32| egui::pos2((x as f32 - rect.left() as f32) / z, (y as f32 - rect.top() as f32) / z);
|
||||
let coalesced: Vec<(Pos2, f32)> = if kind == "pointermove"
|
||||
let coalesced: Vec<(Pos2, f32, f32)> = if kind == "pointermove"
|
||||
&& e.pointer_type() == "pen"
|
||||
// Safari before 17 hasn't it, and calling a missing method would abort the app.
|
||||
&& js_sys::Reflect::has(&e, &"getCoalescedEvents".into()).unwrap_or(false)
|
||||
@@ -284,7 +343,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement,
|
||||
e.get_coalesced_events()
|
||||
.iter()
|
||||
.filter_map(|c| c.dyn_into::<web_sys::PointerEvent>().ok())
|
||||
.map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0)))
|
||||
.map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0), c.tangential_pressure()))
|
||||
.collect()
|
||||
} else {
|
||||
vec![]
|
||||
@@ -295,6 +354,8 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement,
|
||||
id: e.pointer_id(),
|
||||
button: e.button(),
|
||||
pressure: e.pressure(),
|
||||
tangential: e.tangential_pressure(),
|
||||
entered: e.related_target().is_some(),
|
||||
// Same semantics as eframe's modifiers_from_mouse_event.
|
||||
modifiers: egui::Modifiers {
|
||||
alt: e.alt_key(),
|
||||
@@ -343,7 +404,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn input(pointer_type: &str, button: i16) -> Input<'_> {
|
||||
Input { pointer_type, id: 7, button, pressure: 0.6, modifiers: egui::Modifiers::default() }
|
||||
Input { pointer_type, id: 7, button, pressure: 0.6, tangential: 0.0, entered: false, modifiers: egui::Modifiers::default() }
|
||||
}
|
||||
|
||||
fn reset() {
|
||||
@@ -505,6 +566,128 @@ mod tests {
|
||||
reset();
|
||||
}
|
||||
|
||||
fn pen_at(button: i16, tangential: f32) -> Input<'static> {
|
||||
Input { pointer_type: "pen", id: 7, button, pressure: 0.6, tangential, entered: false, modifiers: egui::Modifiers::default() }
|
||||
}
|
||||
|
||||
/// The wheels of the readings written since the last call, in order.
|
||||
fn wheels(p: &mut Pointers) -> Vec<Option<f32>> {
|
||||
p.readings.drain(..).map(|s| s.wheel).collect()
|
||||
}
|
||||
|
||||
/// The wheel of the source's latest reading.
|
||||
fn current_wheel(p: &Pointers) -> Option<f32> {
|
||||
p.pen().current().and_then(|s| s.wheel)
|
||||
}
|
||||
|
||||
/// An airbrush pen's finger wheel (Pointer Events' `tangentialPressure`, −1..1) reaches the
|
||||
/// source as 0..1 with each move, once the pen has reported a value other than 0.
|
||||
#[test]
|
||||
fn an_airbrush_wheel_goes_into_the_feed() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
assert!(p.feed("pointerdown", &pen_at(0, 0.0), Pos2::ZERO, &[], true));
|
||||
for t in [0.0, -1.0, 0.5, 0.0, 3.0, f32::NAN, -0.5] {
|
||||
assert!(p.feed("pointermove", &pen_at(-1, t), Pos2::ZERO, &[], true));
|
||||
}
|
||||
assert_eq!(
|
||||
wheels(&mut p),
|
||||
[None, None, Some(0.0), Some(0.75), Some(0.5), Some(1.0), None, Some(0.25)],
|
||||
"none until reported; then 0 is half way, past the ends is clamped and not a number is none"
|
||||
);
|
||||
assert!(p.feed("pointerup", &pen_at(0, 0.0), Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), Some(0.5), "the lift keeps the wheel");
|
||||
reset();
|
||||
}
|
||||
|
||||
/// The positions a fast stroke's event coalesced each get a reading with their own wheel and
|
||||
/// pressure, in order, before their move, and the event's own position comes last with its own.
|
||||
#[test]
|
||||
fn coalesced_moves_keep_their_wheel() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
let (a, b, c) = (Pos2::new(1.0, 2.0), Pos2::new(3.0, 4.0), Pos2::new(5.0, 6.0));
|
||||
assert!(p.feed("pointerdown", &pen_at(0, -1.0), Pos2::ZERO, &[], true));
|
||||
let coalesced = [(a, 0.3, -0.5), (b, 0.4, 0.5), (c, 0.5, 0.75)];
|
||||
assert!(p.feed("pointermove", &pen_at(-1, 1.0), c, &coalesced, true));
|
||||
let moved: Vec<Pos2> = p.take().into_iter().filter_map(|e| if let Event::PointerMoved(at) = e { Some(at) } else { None }).collect();
|
||||
let kept = std::mem::take(&mut p.readings);
|
||||
assert_eq!(moved, [Pos2::ZERO, a, b, c]);
|
||||
assert_eq!(kept.iter().map(|s| s.wheel).collect::<Vec<_>>(), [Some(0.0), Some(0.25), Some(0.75), Some(1.0)]);
|
||||
assert_eq!(kept.iter().map(|s| s.pressure).collect::<Vec<_>>(), [0.6, 0.3, 0.4, 0.6], "each move keeps its pressure too");
|
||||
reset();
|
||||
}
|
||||
|
||||
/// A pen that leaves the hover range, a canceled press, another pen and the other end each
|
||||
/// read the wheel afresh; a lift into hover does not. A mouse or a finger reads no wheel.
|
||||
#[test]
|
||||
fn the_wheel_is_read_afresh_for_each_pen_and_end() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
let feed = p.pen();
|
||||
let learn = |p: &mut Pointers, button: i16| {
|
||||
assert!(p.feed("pointerdown", &pen_at(button, 0.5), Pos2::ZERO, &[], true));
|
||||
assert!(p.feed("pointerup", &pen_at(button, 0.5), Pos2::ZERO, &[], true));
|
||||
};
|
||||
let hover = |p: &mut Pointers, id: i32| {
|
||||
let mut e = pen_at(-1, 0.0);
|
||||
e.id = id;
|
||||
e.pressure = 0.0;
|
||||
assert!(p.feed("pointermove", &e, Pos2::ZERO, &[], true));
|
||||
};
|
||||
learn(&mut p, 0);
|
||||
hover(&mut p, 7);
|
||||
assert_eq!(current_wheel(&p), Some(0.5), "a lift into hover keeps it");
|
||||
p.feed("pointerleave", &pen_at(-1, 0.0), Pos2::ZERO, &[], true);
|
||||
hover(&mut p, 7);
|
||||
assert_eq!(current_wheel(&p), None, "left the hover range");
|
||||
learn(&mut p, 0);
|
||||
assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true));
|
||||
assert!(p.feed("pointercancel", &pen_at(0, 0.5), Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), None, "a canceled press");
|
||||
hover(&mut p, 7);
|
||||
assert_eq!(current_wheel(&p), None, "after a canceled press");
|
||||
learn(&mut p, 0);
|
||||
hover(&mut p, 8);
|
||||
assert_eq!(current_wheel(&p), None, "another pen");
|
||||
learn(&mut p, 0);
|
||||
assert!(p.feed("pointerdown", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), None, "the other end");
|
||||
assert!(p.feed("pointerup", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true));
|
||||
p.readings.clear();
|
||||
for (pointer_type, kind) in [("mouse", "pointermove"), ("touch", "pointerdown"), ("touch", "pointermove")] {
|
||||
let mut other = pen_at(0, 0.5);
|
||||
(other.pointer_type, other.id) = (pointer_type, 10);
|
||||
p.feed(kind, &other, Pos2::ZERO, &[], true);
|
||||
assert_eq!(feed.current(), None, "{pointer_type} {kind}");
|
||||
assert!(p.readings.is_empty(), "{pointer_type} {kind}");
|
||||
}
|
||||
reset();
|
||||
}
|
||||
|
||||
/// A hovering pen that moves off the canvas onto another element and back keeps what it read
|
||||
/// of its wheel; one that leaves the hover range off the canvas reads it afresh.
|
||||
#[test]
|
||||
fn the_wheel_survives_crossing_the_canvas_edge() {
|
||||
reset();
|
||||
let mut p = Pointers::default();
|
||||
assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true));
|
||||
assert!(p.feed("pointerup", &pen_at(0, 0.5), Pos2::ZERO, &[], true));
|
||||
let mut hover = pen_at(-1, 0.0);
|
||||
hover.pressure = 0.0;
|
||||
let mut onto = pen_at(-1, 0.0);
|
||||
(onto.pressure, onto.entered) = (0.0, true);
|
||||
p.feed("pointerleave", &onto, Pos2::ZERO, &[], true);
|
||||
assert!(!p.feed("pointermove", &hover, Pos2::ZERO, &[], false));
|
||||
assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), Some(0.5), "moved onto another element and back");
|
||||
p.feed("pointerleave", &onto, Pos2::ZERO, &[], true);
|
||||
p.feed("pointerleave", &hover, Pos2::ZERO, &[], false);
|
||||
assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true));
|
||||
assert_eq!(current_wheel(&p), None, "left the hover range off the canvas");
|
||||
reset();
|
||||
}
|
||||
|
||||
/// A palm that lands or moves while the eraser end presses is rejected, and the feed keeps the
|
||||
/// eraser end for the canvas's next frame.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! The plug-in workers ([`vectorcraft_ui_egui::plugin_runs::Workers`]): each one a Web Worker that
|
||||
//! runs `vectorcraft-plugin-worker`, which Trunk builds beside the app (`index.html`), started from
|
||||
//! the loader file Trunk writes for it next to `index.html`.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use vectorcraft_ui_egui::plugin_runs::{SharedInbox, WorkerLink, Workers};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::prelude::Closure;
|
||||
|
||||
/// The loader Trunk writes for the worker (`data-loader-shim`), beside `index.html`.
|
||||
const LOADER: &str = "vectorcraft-plugin-worker_loader.js";
|
||||
|
||||
/// Starts the workers; each message or failure asks for a frame, which reads it.
|
||||
pub(crate) struct PageWorkers {
|
||||
pub(crate) ctx: egui::Context,
|
||||
}
|
||||
|
||||
/// One worker and its message and error handlers.
|
||||
struct PageWorker {
|
||||
worker: web_sys::Worker,
|
||||
_on_message: Closure<dyn FnMut(web_sys::MessageEvent)>,
|
||||
_on_error: Closure<dyn FnMut(web_sys::Event)>,
|
||||
}
|
||||
|
||||
/// The text of a browser error value.
|
||||
fn js_err(e: wasm_bindgen::JsValue) -> String {
|
||||
e.as_string().unwrap_or_else(|| format!("{e:?}"))
|
||||
}
|
||||
|
||||
impl Workers for PageWorkers {
|
||||
fn start(&self, inbox: SharedInbox) -> Result<Box<dyn WorkerLink>, String> {
|
||||
let document = web_sys::window().and_then(|w| w.document()).ok_or_else(|| "no document".to_string())?;
|
||||
let base = document.base_uri().map_err(js_err)?.ok_or_else(|| "no document".to_string())?;
|
||||
let url = web_sys::Url::new_with_base(LOADER, &base).map_err(js_err)?.href();
|
||||
let worker = web_sys::Worker::new(&url).map_err(js_err)?;
|
||||
let (to, ctx) = (Rc::clone(&inbox), self.ctx.clone());
|
||||
let on_message = Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |e: web_sys::MessageEvent| {
|
||||
to.borrow_mut().push(&js_sys::Uint8Array::new(&e.data()).to_vec());
|
||||
ctx.request_repaint();
|
||||
});
|
||||
let ctx = self.ctx.clone();
|
||||
// A worker that fails to load, panics or posts a message that can't be read.
|
||||
let on_error = Closure::<dyn FnMut(web_sys::Event)>::new(move |e: web_sys::Event| {
|
||||
let why = e.dyn_ref::<web_sys::ErrorEvent>().map_or_else(|| e.type_(), web_sys::ErrorEvent::message);
|
||||
inbox.borrow_mut().fail(why);
|
||||
ctx.request_repaint();
|
||||
});
|
||||
worker.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
|
||||
worker.set_onerror(Some(on_error.as_ref().unchecked_ref()));
|
||||
worker.set_onmessageerror(Some(on_error.as_ref().unchecked_ref()));
|
||||
Ok(Box::new(PageWorker { worker, _on_message: on_message, _on_error: on_error }))
|
||||
}
|
||||
|
||||
fn now_ms(&self) -> f64 {
|
||||
web_sys::window().and_then(|w| w.performance()).map_or(0.0, |p| p.now())
|
||||
}
|
||||
}
|
||||
|
||||
impl WorkerLink for PageWorker {
|
||||
fn post(&mut self, msg: Vec<u8>) -> Result<(), String> {
|
||||
let bytes = js_sys::Uint8Array::from(msg.as_slice());
|
||||
self.worker.post_message_with_transfer(&bytes, &js_sys::Array::of1(&bytes.buffer())).map_err(js_err)
|
||||
}
|
||||
|
||||
fn terminate(&mut self) {
|
||||
self.worker.set_onmessage(None);
|
||||
self.worker.set_onerror(None);
|
||||
self.worker.set_onmessageerror(None);
|
||||
self.worker.terminate();
|
||||
}
|
||||
}
|
||||
@@ -156,7 +156,7 @@ async fn run(host: Host, canvas: web_sys::HtmlCanvasElement, moving: Option<Movi
|
||||
.jobs(Arc::new(InlineJobs))
|
||||
.files(Arc::new(files))
|
||||
.install(ctx);
|
||||
let services = services(host.inbox.clone(), host.place_inbox.clone(), host.locks.clone());
|
||||
let services = services(host.inbox.clone(), host.place_inbox.clone(), host.locks.clone(), ctx.clone());
|
||||
let mut app = match taken.borrow_mut().take() {
|
||||
Some(mut app) => {
|
||||
// The old services asked the old context for frames.
|
||||
@@ -461,8 +461,10 @@ impl eframe::App for WebShell {
|
||||
}
|
||||
}
|
||||
|
||||
fn services(inbox: OpenInboxes, place_inbox: PlaceInbox, locks: Option<WebLocks>) -> Services {
|
||||
fn services(inbox: OpenInboxes, place_inbox: PlaceInbox, locks: Option<WebLocks>, ctx: egui::Context) -> Services {
|
||||
Services {
|
||||
// Plug-ins are checked and filters run in workers of their own, off the page.
|
||||
plugin_workers: vectorcraft_ui_egui::plugin_runs::workers(Box::new(crate::plugin_workers::PageWorkers { ctx })),
|
||||
// A download that couldn't be started fails the save or export it is for (#1693).
|
||||
download: Some(Box::new(|name: &str, bytes: &[u8]| download(name, bytes).inspect_err(|e| log::error!("download of {name} failed: {e}")))),
|
||||
inbox: Some(inbox.dropped),
|
||||
|
||||
@@ -61,14 +61,15 @@ 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 }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2 = "0.6"
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSpace", "NSControl", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSpace", "NSControl", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSView", "NSWindow"] }
|
||||
# Files opened from Finder and the Dock (src/open_documents.rs) and pasted bitmaps (src/clipboard.rs); both already come with winit.
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] }
|
||||
block2 = "0.6"
|
||||
@@ -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" {
|
||||
@@ -238,14 +243,3 @@ pub(crate) fn open_files(app: &mut VectorcraftApp, files: Vec<String>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tell the macOS input method to drop its composition (the Type tool kept the marked text as
|
||||
/// typed). winit's IME toggle only clears its own copy, so the IME would type it again.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn discard_marked_text() {
|
||||
if let Some(mtm) = objc2::MainThreadMarker::new()
|
||||
&& let Some(ic) = objc2_app_kit::NSTextInputContext::currentInputContext(mtm)
|
||||
{
|
||||
ic.discardMarkedText();
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
@@ -7,11 +7,17 @@
|
||||
//! fails in a Flatpak sandbox (`XCURSOR_PATH` unset, no cursor theme in the runtime) and where the
|
||||
//! `default` theme is a dangling symlink; the desktop's own setting names a theme that loads.
|
||||
//!
|
||||
//! Where no cursor theme can be found at all (KDE or sway without gsettings), the env fix does
|
||||
//! nothing: [`shell_caps`] leaves out [`Caps::SYSTEM_CURSOR`], and the framework keeps the system
|
||||
//! pointer and paints no tool cursor beside it (#5311).
|
||||
//!
|
||||
//! This reads the desktop's cursor theme and size and sets what the user left unset, once, before
|
||||
//! any thread starts and before the window opens.
|
||||
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
|
||||
use craft::host::target::Caps;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Where a Flatpak sandbox mounts the host's cursor themes (user and system).
|
||||
const FLATPAK_HOST_ICONS: [&str; 2] = ["/run/host/user-share/icons", "/run/host/share/icons"];
|
||||
@@ -48,6 +54,74 @@ pub fn plan(var: impl Fn(&str) -> Option<OsString>, host_icons: &[&str], desktop
|
||||
out
|
||||
}
|
||||
|
||||
/// Xcursor's default search path when `XCURSOR_PATH` is unset (relative entries are in `$HOME`).
|
||||
const DEFAULT_ICON_DIRS: [&str; 5] = ["~/.local/share/icons", "~/.icons", "/usr/share/icons", "/usr/share/pixmaps", "/usr/X11R6/lib/X11/icons"];
|
||||
|
||||
/// The themes `index.theme` lists after `Inherits=`.
|
||||
fn inherits(index: &str) -> Vec<String> {
|
||||
index
|
||||
.lines()
|
||||
.find_map(|l| l.trim().strip_prefix("Inherits="))
|
||||
.map(|v| v.split([',', ';']).map(|t| t.trim().to_owned()).filter(|t| !t.is_empty()).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Can Xcursor load a pointer for the environment's theme (`XCURSOR_THEME`, else `default`)? It does
|
||||
/// when the theme, or one it inherits from, has a `default` or `left_ptr` cursor file in a folder of
|
||||
/// `XCURSOR_PATH` (else Xcursor's default folders). `read` returns a file's text, `exists` tells
|
||||
/// whether a file is there.
|
||||
pub fn theme_usable(
|
||||
var: impl Fn(&str) -> Option<OsString>,
|
||||
home: Option<&Path>,
|
||||
read: impl Fn(&Path) -> Option<String>,
|
||||
exists: impl Fn(&Path) -> bool,
|
||||
) -> bool {
|
||||
let dirs: Vec<PathBuf> = match var("XCURSOR_PATH").filter(|v| !v.is_empty()) {
|
||||
Some(v) => std::env::split_paths(&v).collect(),
|
||||
None => DEFAULT_ICON_DIRS
|
||||
.iter()
|
||||
.filter_map(|d| match d.strip_prefix("~/") {
|
||||
Some(rest) => home.map(|h| h.join(rest)),
|
||||
None => Some(PathBuf::from(d)),
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let first = var("XCURSOR_THEME").and_then(|v| v.into_string().ok()).filter(|t| !t.is_empty()).unwrap_or_else(|| "default".into());
|
||||
let mut todo = vec![first];
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
while let Some(theme) = todo.pop() {
|
||||
// Bounded: themes inherit in short chains, and a cycle must end.
|
||||
if seen.contains(&theme) || seen.len() >= 16 {
|
||||
continue;
|
||||
}
|
||||
for dir in &dirs {
|
||||
let base = dir.join(&theme);
|
||||
if ["default", "left_ptr"].iter().any(|c| exists(&base.join("cursors").join(c))) {
|
||||
return true;
|
||||
}
|
||||
if let Some(index) = read(&base.join("index.theme")) {
|
||||
todo.extend(inherits(&index));
|
||||
}
|
||||
}
|
||||
seen.push(theme);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// On this machine, after [`apply`]: is there no cursor theme Xcursor can load? Then winit never
|
||||
/// sets a pointer, and a hidden system pointer does not come back (#2450).
|
||||
pub fn theme_missing() -> bool {
|
||||
let home = std::env::var_os("HOME").filter(|h| !h.is_empty()).map(PathBuf::from);
|
||||
!theme_usable(|n| std::env::var_os(n), home.as_deref(), |p| std::fs::read_to_string(p).ok(), |p| p.exists())
|
||||
}
|
||||
|
||||
/// The shell's capabilities `caps`, without [`Caps::SYSTEM_CURSOR`] when the window opens on
|
||||
/// Wayland and `theme_missing` finds no cursor theme. The framework then keeps the system pointer
|
||||
/// and paints no tool cursor beside it (#5311). `theme_missing` runs only on Wayland.
|
||||
pub fn shell_caps(caps: Caps, wayland: bool, theme_missing: impl FnOnce() -> bool) -> Caps {
|
||||
if wayland && theme_missing() { caps.difference(Caps::SYSTEM_CURSOR) } else { caps }
|
||||
}
|
||||
|
||||
/// The value of a `gsettings get` line: `'Adwaita'` becomes `Adwaita`, `24` stays `24`.
|
||||
fn gsettings_value(output: &str) -> &str {
|
||||
output.trim().trim_matches('\'')
|
||||
@@ -113,6 +187,43 @@ mod tests {
|
||||
assert!(plan(env(&[("WAYLAND_DISPLAY", "wayland-0")]), &[], odd).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_theme_is_usable_directly_or_through_inherits_and_missing_otherwise() {
|
||||
let files = ["/i/Bibata/cursors/left_ptr", "/i/Breeze/index.theme", "/i/Loop/index.theme"];
|
||||
// Compared as paths, so the joins match on Windows too, where they use `\`.
|
||||
let exists = |p: &Path| files.iter().any(|f| Path::new(f) == p);
|
||||
let read = |p: &Path| {
|
||||
if p == Path::new("/i/Breeze/index.theme") {
|
||||
Some("[Icon Theme]\nInherits=Other, Bibata\n".to_owned())
|
||||
} else if p == Path::new("/i/Loop/index.theme") {
|
||||
Some("Inherits=Loop\n".to_owned())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
let with = |theme: &'static str| {
|
||||
move |n: &str| (n == "XCURSOR_PATH").then(|| OsString::from("/i")).or((n == "XCURSOR_THEME").then(|| OsString::from(theme)))
|
||||
};
|
||||
assert!(theme_usable(with("Bibata"), None, read, exists));
|
||||
assert!(theme_usable(with("Breeze"), None, read, exists));
|
||||
// No such theme, a theme without cursors, an inheritance loop: nothing to load.
|
||||
assert!(!theme_usable(with("Nope"), None, read, exists));
|
||||
assert!(!theme_usable(with("Loop"), None, read, exists));
|
||||
// Unset: Xcursor's default folders and the `default` theme.
|
||||
assert!(!theme_usable(|_| None, Some(Path::new("/home/u")), read, exists));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_cursor_theme_on_wayland_the_system_pointer_stays_alone() {
|
||||
let native = Caps::native(craft::host::target::Os::Linux);
|
||||
assert!(native.contains(Caps::SYSTEM_CURSOR));
|
||||
let without = shell_caps(native, true, || true);
|
||||
assert!(!without.contains(Caps::SYSTEM_CURSOR), "Wayland with no cursor theme: no painted cursor beside the system pointer");
|
||||
assert_eq!(without.union(Caps::SYSTEM_CURSOR), native, "only the system cursor is left out");
|
||||
assert_eq!(shell_caps(native, true, || false), native, "Wayland with a theme");
|
||||
assert_eq!(shell_caps(native, false, || panic!("the theme is looked up only on Wayland")), native, "X11 and XWayland");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gsettings_output_is_unquoted() {
|
||||
assert_eq!(gsettings_value("'Adwaita'\n"), "Adwaita");
|
||||
|
||||
@@ -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 {
|
||||
@@ -604,6 +629,15 @@ struct StartFile {
|
||||
record: StartRecord,
|
||||
}
|
||||
|
||||
impl Drop for StartFile {
|
||||
/// Frees the lock when the start releases the file. A child process that any thread starts holds
|
||||
/// a copy of the file's handle until it runs its program, and the lock is only freed by closing
|
||||
/// every copy or by unlocking.
|
||||
fn drop(&mut self) {
|
||||
let _ = self.file.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
impl StartFile {
|
||||
/// Open `dir`'s [`START_FILE`], with the record the last start left in it (`None` when there is
|
||||
/// none or it can't be read). `Ok(None)` when another copy of the app holds it.
|
||||
@@ -845,10 +879,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 +905,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();
|
||||
|
||||
@@ -613,9 +613,7 @@ fn a_normal_exit_or_another_failure_does_not_restart() {
|
||||
assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into()));
|
||||
}
|
||||
|
||||
/// A log folder of its own for each test, and the guard that keeps other tests from starting a
|
||||
/// program while it runs: the test releases the start file's lock and takes it again, and a child
|
||||
/// starting meanwhile would keep it held (`crate::no_spawns`).
|
||||
/// A log folder of its own for each test.
|
||||
struct TestDir(tempfile::TempDir);
|
||||
|
||||
impl std::ops::Deref for TestDir {
|
||||
@@ -632,10 +630,23 @@ impl AsRef<std::path::Path> for TestDir {
|
||||
}
|
||||
}
|
||||
|
||||
fn start_dir(tag: &str) -> (TestDir, std::sync::RwLockReadGuard<'static, ()>) {
|
||||
let spawns = crate::no_spawns();
|
||||
let dir = tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap();
|
||||
(TestDir(dir), spawns)
|
||||
fn start_dir(tag: &str) -> TestDir {
|
||||
TestDir(tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap())
|
||||
}
|
||||
|
||||
/// A start that ends frees the start file even while another handle to it is open, as a child
|
||||
/// process that is starting holds one: the next start reads the file instead of taking it for
|
||||
/// another copy of the app that is starting.
|
||||
#[test]
|
||||
fn an_ended_start_frees_the_start_file_while_a_copy_of_its_handle_is_open() {
|
||||
let dir = start_dir("copy");
|
||||
let starting = Startup::default();
|
||||
starting.track(&dir, None, false);
|
||||
let copy = starting.start.lock().unwrap().as_ref().map(|start| start.file.try_clone().unwrap());
|
||||
assert!(copy.is_some(), "the start holds the file");
|
||||
starting.ended();
|
||||
assert!(StartFile::open(&dir).unwrap().is_some(), "an ended start frees the start file");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
/// What a start in `dir` leaves out; it then ends without crashing.
|
||||
@@ -661,7 +672,7 @@ fn issue_2243() -> Vec<Candidate> {
|
||||
/// it, without a status-bar note.
|
||||
#[test]
|
||||
fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
|
||||
let (dir, _spawns) = start_dir("crash");
|
||||
let dir = start_dir("crash");
|
||||
let c = issue_2243();
|
||||
let first = Startup::default();
|
||||
assert_eq!(first.track(&dir, None, false), LeftOut::default());
|
||||
@@ -691,7 +702,7 @@ fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() {
|
||||
/// an error, a restart on another adapter), leaves nothing out of the next.
|
||||
#[test]
|
||||
fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
|
||||
let (dir, _spawns) = start_dir("shown");
|
||||
let dir = start_dir("shown");
|
||||
let c = issue_2243();
|
||||
for end in [Startup::presented as fn(&Startup), Startup::ended] {
|
||||
let first = Startup::default();
|
||||
@@ -714,7 +725,7 @@ fn a_start_that_showed_its_first_frame_or_ended_is_cleared() {
|
||||
/// macOS, where wgpu has none.
|
||||
#[test]
|
||||
fn a_crash_while_listing_lists_opengl_alone() {
|
||||
let (dir, _spawns) = start_dir("listing");
|
||||
let dir = start_dir("listing");
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
drop(first);
|
||||
@@ -740,7 +751,7 @@ fn a_crash_while_listing_lists_opengl_alone() {
|
||||
/// start shows its first frame on the adapter that crashed, the adapter counts again.
|
||||
#[test]
|
||||
fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
|
||||
let (dir, _spawns) = start_dir("explicit");
|
||||
let dir = start_dir("explicit");
|
||||
let c = issue_2243();
|
||||
let first = Startup::default();
|
||||
first.track(&dir, None, false);
|
||||
@@ -760,7 +771,7 @@ fn wgpu_backend_or_adapter_name_ignores_the_crashes() {
|
||||
/// are ignored: the start goes on with nothing left out.
|
||||
#[test]
|
||||
fn a_damaged_or_unreadable_start_file_is_ignored() {
|
||||
let (dir, _spawns) = start_dir("damaged");
|
||||
let dir = start_dir("damaged");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let damaged: [&[u8]; 9] = [
|
||||
b"",
|
||||
@@ -827,3 +838,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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,10 +124,13 @@ pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: O
|
||||
/// The arguments a child of this process starts with: a nightly launch hands its profile on, so the
|
||||
/// child opens the same private profile instead of being refused ("Open VectorCraft Nightly…"), and
|
||||
/// `--` keeps a file whose name starts with '-' a file. Stable's child arguments are unchanged.
|
||||
/// Only `single_instance` starts a child, and macOS does not build it.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub fn child_args(files: &[String]) -> Vec<OsString> {
|
||||
child_args_for(current(), files)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn child_args_for(profile: &Profile, files: &[String]) -> Vec<OsString> {
|
||||
let mut args: Vec<OsString> = match profile {
|
||||
Profile::Stable => Vec::new(),
|
||||
@@ -245,12 +248,14 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[test]
|
||||
fn a_stable_child_gets_the_file_delimiter_only() {
|
||||
let child = child_args_for(&Profile::Stable, &["a file.svg".to_string(), "--looks-like-a-flag".to_string()]);
|
||||
assert_eq!(child, args(&["--", "a file.svg", "--looks-like-a-flag"]));
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[test]
|
||||
fn a_nightly_child_inherits_the_selected_profile() {
|
||||
let root = PathBuf::from(absolute());
|
||||
|
||||
@@ -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
|
||||
@@ -660,6 +667,11 @@ fn main() -> std::process::ExitCode {
|
||||
// framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and
|
||||
// Preferences › User Interface › System Title Bar.
|
||||
let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() };
|
||||
// On Wayland with no cursor theme, the system pointer stays and no tool cursor is painted
|
||||
// beside it (#2450, #5311).
|
||||
let wayland = !forced_to_x11 && Backend::from_env() == Backend::Wayland;
|
||||
let caps = cursor_theme::shell_caps(shell_info.caps, wayland, cursor_theme::theme_missing);
|
||||
let shell_info = shell_info.caps(caps);
|
||||
let titlebar_pref =
|
||||
if engine_pref("systemTitleBar").and_then(|v| v.as_bool()).unwrap_or(false) { TitleBarPref::System } else { TitleBarPref::Integrated };
|
||||
let decision = decide_for(Prefix::new("VECTORCRAFT"), shell_info.backend, titlebar_pref);
|
||||
@@ -817,6 +829,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 +984,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 +1006,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,
|
||||
@@ -1021,19 +1039,5 @@ fn main() -> std::process::ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests only: while a test starts another program, the child briefly holds a copy of every file
|
||||
/// this process has open, until it runs that program. A file lock held through such a copy outlives
|
||||
/// its own handle, so a GPU start test that released the start file and opened it again found it
|
||||
/// still locked, as if another copy of the app were running, and failed. A test that starts a
|
||||
/// program holds its write side; a test that depends on the start file's lock holds [`no_spawns`].
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
static CHILD_SPAWN: std::sync::RwLock<()> = std::sync::RwLock::new(());
|
||||
|
||||
/// Held by a test that releases a locked file and opens it again (see [`CHILD_SPAWN`]).
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
fn no_spawns() -> std::sync::RwLockReadGuard<'static, ()> {
|
||||
CHILD_SPAWN.read().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
mod tests;
|
||||
@@ -16,12 +16,38 @@ static SESSION: Mutex<Option<Session>> = Mutex::new(None);
|
||||
static NOTICE_SHOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
pub struct Session {
|
||||
_lease: File,
|
||||
_lease: Lease,
|
||||
path: PathBuf,
|
||||
own_record: Vec<u8>,
|
||||
previous_unclean: bool,
|
||||
}
|
||||
|
||||
/// The profile's [`LEASE`], open and locked.
|
||||
struct Lease(File);
|
||||
|
||||
impl Lease {
|
||||
/// Lock `root`'s [`LEASE`]: `None` when another window of the same profile holds it.
|
||||
fn take(root: &Path) -> io::Result<Option<Self>> {
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => Ok(Some(Self(lease))),
|
||||
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Lease {
|
||||
/// Frees the lease when the session ends, or when a session could not be started after the lock
|
||||
/// was taken. A child process that any thread starts holds a copy of the lease's handle until it
|
||||
/// runs its program, and the lock is only freed by closing every copy or by unlocking.
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
fn regular_or_missing(path: &Path) -> io::Result<bool> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
|
||||
@@ -73,14 +99,13 @@ impl Session {
|
||||
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
|
||||
}
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => return Err(error),
|
||||
}
|
||||
let Some(lease) = Lease::take(root)? else { return Ok(None) };
|
||||
Self::record(lease, root, version, commit).map(Some)
|
||||
}
|
||||
|
||||
/// Write this launch's record while `lease` is held. On an error `lease` is dropped, which
|
||||
/// unlocks it.
|
||||
fn record(lease: Lease, root: &Path, version: &str, commit: Option<&str>) -> io::Result<Self> {
|
||||
let path = root.join(RECORD);
|
||||
let previous_unclean = regular_or_missing(&path)?;
|
||||
let own_record = serde_json::to_vec(&serde_json::json!({
|
||||
@@ -90,7 +115,7 @@ impl Session {
|
||||
"commit": commit.filter(|value| !value.is_empty()),
|
||||
}))?;
|
||||
atomic_write_no_follow(&path, &own_record)?;
|
||||
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
|
||||
Ok(Self { _lease: lease, path, own_record, previous_unclean })
|
||||
}
|
||||
|
||||
pub fn previous_unclean(&self) -> bool {
|
||||
@@ -258,6 +283,54 @@ mod tests {
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a controlled return clears its record");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ended_session_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
let first = Session::begin(Some(&fixture.0), "first", None).unwrap().unwrap();
|
||||
// A child process that is starting holds such a copy.
|
||||
let first_copy = first._lease.0.try_clone().unwrap();
|
||||
first.complete().unwrap();
|
||||
let second = Session::begin(Some(&fixture.0), "second", None).unwrap();
|
||||
assert!(second.is_some(), "a completed session frees the lease");
|
||||
let second_copy = second.as_ref().map(|session| session._lease.0.try_clone().unwrap());
|
||||
drop(second);
|
||||
assert!(Session::begin(Some(&fixture.0), "third", None).unwrap().is_some(), "a dropped session frees the lease");
|
||||
drop((first_copy, second_copy));
|
||||
}
|
||||
|
||||
/// `root`'s lease, locked as [`Session::begin`] locks it, and a copy of its handle such as a
|
||||
/// child process that is starting holds.
|
||||
fn locked_with_a_copy(root: &Path) -> (Lease, File) {
|
||||
let lease = Lease::take(root).unwrap().unwrap();
|
||||
let copy = lease.0.try_clone().unwrap();
|
||||
(lease, copy)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_cannot_check_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
std::fs::create_dir(fixture.0.join(RECORD)).unwrap();
|
||||
let (lease, copy) = locked_with_a_copy(&fixture.0);
|
||||
assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "a folder is not a record");
|
||||
std::fs::remove_dir(fixture.0.join(RECORD)).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to check its record frees the lease");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_cannot_write_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() {
|
||||
let fixture = Fixture::new();
|
||||
// A folder at the temporary file's name makes the write fail after the record was checked.
|
||||
let temporary = fixture.0.join(format!(".{RECORD}.{}.tmp", std::process::id()));
|
||||
std::fs::create_dir(&temporary).unwrap();
|
||||
let (lease, copy) = locked_with_a_copy(&fixture.0);
|
||||
assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "the record cannot be written");
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
std::fs::remove_dir(&temporary).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to write its record frees the lease");
|
||||
drop(copy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_never_removes_an_unknown_changed_record() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
@@ -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) {
|
||||
@@ -136,6 +145,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_font_scans_read_the_fonts_folder_next_to_the_settings() {
|
||||
// No test installs a launch's root in this process, so the settings folder stays the same here.
|
||||
assert_eq!(profile::data_root(), None, "a test installed a launch's root beside the others");
|
||||
install_fonts();
|
||||
let fonts = prefs_dir().map(|dir| dir.join("Fonts"));
|
||||
assert!(fonts.is_some(), "a home folder to keep the settings in");
|
||||
|
||||
@@ -457,10 +457,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs the process-wide root: the one test that may, since a `OnceLock` is set once per
|
||||
/// process (nextest gives every test its own).
|
||||
/// Runs the test `name` of this module again in a child process of the test binary → whether
|
||||
/// this is that child. For a test that installs the process-wide root, which every test running
|
||||
/// beside it would then read as the settings folder.
|
||||
fn in_own_process(name: &str) -> bool {
|
||||
const CHILD: &str = "VECTORCRAFT_TEST_OWN_PROCESS";
|
||||
if std::env::var_os(CHILD).is_some() {
|
||||
return true;
|
||||
}
|
||||
// The test's path without the crate's name: the desktop app and `vectorcraft-cli` both build this file.
|
||||
let module = module_path!().split_once("::").map_or(module_path!(), |(_, path)| path);
|
||||
let path = format!("{module}::{name}");
|
||||
let output =
|
||||
std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact", &path, "--nocapture"]).env(CHILD, "1").output().unwrap();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
|
||||
"{path} failed in its own process:\n{stdout}\n{}",
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
false
|
||||
}
|
||||
|
||||
/// Installs the process-wide root, which a `OnceLock` holds once per process, so the test runs in
|
||||
/// a process of its own.
|
||||
#[test]
|
||||
fn the_installed_root_is_used_once_and_must_be_absolute() {
|
||||
if !in_own_process("the_installed_root_is_used_once_and_must_be_absolute") {
|
||||
return;
|
||||
}
|
||||
let dir = temp("installed-root");
|
||||
assert!(install_data_root(PathBuf::from("relative/root")).is_err(), "a relative root is refused");
|
||||
install_data_root(dir.to_path_buf()).unwrap();
|
||||
|
||||
@@ -175,7 +175,16 @@ fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>,
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
let target = chosen.join(name);
|
||||
match std::fs::symlink_metadata(&target) {
|
||||
Ok(metadata) if !metadata.is_dir() => {
|
||||
return Err(format!("the nightly {label} must be a directory inside its selected profile"));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
|
||||
}
|
||||
let child = canonical_future(&target)?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
@@ -192,11 +201,86 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() && !folder_only {
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(all(windows, feature = "wgpu"))]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT) || info.dwFileAttributes.has(co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(all(windows, not(feature = "wgpu")))]
|
||||
{
|
||||
use std::os::windows::fs::MetadataExt as _;
|
||||
const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
|
||||
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
|
||||
if metadata.file_attributes() & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const PROFILE_FOLDERS: [&str; 18] = [
|
||||
"Data Recovery",
|
||||
"Fonts",
|
||||
"logs",
|
||||
"Launch",
|
||||
"Color Profiles",
|
||||
"Plug-ins",
|
||||
"Scripts",
|
||||
"Startup Scripts",
|
||||
"Metadata Templates",
|
||||
"New Document Profiles",
|
||||
"Proof Setups",
|
||||
"Script Data",
|
||||
"PDF Presets",
|
||||
"Swatches",
|
||||
"Graphic Styles",
|
||||
"Symbols",
|
||||
"Brushes",
|
||||
"Libraries",
|
||||
];
|
||||
|
||||
/// Recognise the shared portable data namespace in both the supplied and the resolved path. Up to
|
||||
/// the chosen folder itself, a marker only counts beside a VectorCraft executable, so an unrelated
|
||||
/// `portable.txt` higher up (in a user folder or at a drive root) does not refuse the profile.
|
||||
@@ -557,6 +641,31 @@ mod tests {
|
||||
assert!(result.unwrap_err().contains("not writable"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in PLATFORMS {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
for name in ["config.toml", "instance.json", "Color Settings.json", "app.ron"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("config.toml")).unwrap(), b"saved profile data");
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_platform_case_rules_are_the_file_systems_ones() {
|
||||
let fixture = Fixture::new();
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Invalid roots must exit before desktop initialization on every platform, including a CI
|
||||
/// machine with no display. A regression must fail rather than hang with a window open.
|
||||
@@ -7,9 +6,14 @@ fn rejects(args: &[&str], message: &str) {
|
||||
rejects_with_env(args, &[], message);
|
||||
}
|
||||
|
||||
/// Runs the desktop binary without a display, so on Linux a regression exits with a display
|
||||
/// error, which the exact stderr check rejects, instead of opening a window.
|
||||
fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) {
|
||||
let mut child = Command::new(crate::bin())
|
||||
let child = Command::new(crate::bin())
|
||||
.args(args)
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WAYLAND_SOCKET")
|
||||
.env_remove("VECTORCRAFT_CONTROL_PORT")
|
||||
.env_remove("VECTORCRAFT_AUTOMATION_READ_ROOT")
|
||||
.env_remove("VECTORCRAFT_AUTOMATION_WRITE_ROOT")
|
||||
@@ -20,21 +24,7 @@ fn rejects_with_env(args: &[&str], env: &[(&str, &str)], message: &str) {
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
// Long enough for the binary to start on a loaded machine (the workspace's other tests run
|
||||
// meanwhile), short enough to catch a desktop that started instead of exiting.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let timed_out = loop {
|
||||
if child.try_wait().unwrap().is_some() {
|
||||
break false;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
child.kill().unwrap();
|
||||
break true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
let out = child.wait_with_output().unwrap();
|
||||
assert!(!timed_out, "{args:?}: desktop started or did not exit promptly");
|
||||
let out = crate::exit_output(child, &format!("{args:?}: the desktop started instead of exiting"));
|
||||
assert!(!out.status.success(), "{args:?}");
|
||||
assert!(out.stdout.is_empty(), "{args:?}: {:?}", out.stdout);
|
||||
// Exact stderr excludes unrelated startup warnings or display errors that could otherwise
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
//! `vectorcraft --help` prints the usage and exits before the app starts (#2110): run from a
|
||||
//! terminal, SSH or an agent's shell it used to open the window (or hang without a display).
|
||||
|
||||
use std::io::Read;
|
||||
use std::process::{Command, Output, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Runs the desktop binary without a display and with a control port it cannot parse, so a
|
||||
/// regression exits with that error instead of opening a window.
|
||||
fn run(args: &[&str], env: &[(&str, &str)]) -> Output {
|
||||
let mut child = Command::new(crate::bin())
|
||||
let child = Command::new(crate::bin())
|
||||
.args(args)
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
@@ -22,28 +19,7 @@ fn run(args: &[&str], env: &[(&str, &str)]) -> Output {
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
// Both pipes end when the binary exits, however long a loaded machine takes to start it. The
|
||||
// deadline only stops a binary that is still running.
|
||||
let deadline = Instant::now() + Duration::from_secs(120);
|
||||
let stdout = read_to_end(child.stdout.take().unwrap());
|
||||
let stderr = read_to_end(child.stderr.take().unwrap());
|
||||
let recv = |rx: &mpsc::Receiver<Vec<u8>>| rx.recv_timeout(deadline.saturating_duration_since(Instant::now()));
|
||||
let (Ok(stdout), Ok(stderr)) = (recv(&stdout), recv(&stderr)) else {
|
||||
child.kill().unwrap();
|
||||
panic!("{args:?}: the app started instead of printing its usage");
|
||||
};
|
||||
Output { status: child.wait().unwrap(), stdout, stderr }
|
||||
}
|
||||
|
||||
/// Reads `pipe` to its end on another thread.
|
||||
fn read_to_end(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver<Vec<u8>> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
let _ = tx.send(buf);
|
||||
});
|
||||
rx
|
||||
crate::exit_output(child, &format!("{args:?}: the app started instead of printing its usage"))
|
||||
}
|
||||
|
||||
fn prints_usage(args: &[&str], env: &[(&str, &str)]) {
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::io::Read;
|
||||
use std::process::{Child, Output};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
mod automation_args;
|
||||
mod help;
|
||||
|
||||
@@ -12,3 +17,70 @@ fn bin() -> std::path::PathBuf {
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| env!("CARGO_BIN_EXE_vectorcraft").into())
|
||||
}
|
||||
|
||||
/// Waits for `child`, spawned with piped stdout and stderr, to exit and returns its output. Both
|
||||
/// pipes end when the binary exits, however long a loaded machine takes to start it. The deadline
|
||||
/// only stops a binary that is still running: the test then fails with `started`.
|
||||
fn exit_output(child: Child, started: &str) -> Output {
|
||||
exit_output_by(child, started, Instant::now() + Duration::from_secs(120))
|
||||
}
|
||||
|
||||
/// [`exit_output`] with the deadline given. A binary that has exited by the deadline passes even
|
||||
/// when its output arrives after it; the output then has 10 seconds more to arrive.
|
||||
fn exit_output_by(mut child: Child, started: &str, deadline: Instant) -> Output {
|
||||
let stdout = read_to_end(child.stdout.take().unwrap());
|
||||
let stderr = read_to_end(child.stderr.take().unwrap());
|
||||
let (mut out, mut err) = (None, None);
|
||||
if !receive([(&stdout, &mut out), (&stderr, &mut err)], deadline) && child.try_wait().unwrap().is_none() {
|
||||
child.kill().unwrap();
|
||||
child.wait().unwrap();
|
||||
panic!("{started}");
|
||||
}
|
||||
receive([(&stdout, &mut out), (&stderr, &mut err)], Instant::now() + Duration::from_secs(10));
|
||||
let (Some(stdout), Some(stderr)) = (out, err) else {
|
||||
panic!("{started}: the binary exited, but its output pipes stayed open");
|
||||
};
|
||||
Output { status: child.wait().unwrap(), stdout, stderr }
|
||||
}
|
||||
|
||||
/// A pipe's reader and the slot that holds its output once it arrives.
|
||||
type Pipe<'a> = (&'a mpsc::Receiver<Vec<u8>>, &'a mut Option<Vec<u8>>);
|
||||
|
||||
/// Fills each empty slot from its reader, waiting until `until` at the latest. Returns whether
|
||||
/// every slot is filled.
|
||||
fn receive(pipes: [Pipe<'_>; 2], until: Instant) -> bool {
|
||||
let mut filled = true;
|
||||
for (rx, slot) in pipes {
|
||||
if slot.is_none() {
|
||||
*slot = rx.recv_timeout(until.saturating_duration_since(Instant::now())).ok();
|
||||
}
|
||||
filled &= slot.is_some();
|
||||
}
|
||||
filled
|
||||
}
|
||||
|
||||
/// Reads `pipe` to its end on another thread.
|
||||
fn read_to_end(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver<Vec<u8>> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
let _ = tx.send(buf);
|
||||
});
|
||||
rx
|
||||
}
|
||||
|
||||
/// A binary that exits before the deadline passes even when a process it started keeps its
|
||||
/// output pipes open past the deadline.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn exit_output_accepts_an_exit_whose_output_arrives_after_the_deadline() {
|
||||
use std::process::{Command, Stdio};
|
||||
let mut child =
|
||||
Command::new("sh").args(["-c", "sleep 1 & exit 0"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
// `sh` has exited; the `sleep` it started still holds both pipes for about a second.
|
||||
child.wait().unwrap();
|
||||
let out = exit_output_by(child, "an exited binary was reported as running", Instant::now());
|
||||
assert!(out.status.success());
|
||||
assert!(out.stdout.is_empty() && out.stderr.is_empty());
|
||||
}
|
||||
@@ -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 |
@@ -121,14 +121,125 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) {
|
||||
/// and a copy's size, spacing, scatter and rotation stay as they were without hue jitter.
|
||||
const HUE_JITTER_SALT: u64 = 0x6875_655f_6a69_7474;
|
||||
|
||||
/// Turn the hue of each of `copies` (a scatter brush's copies, in order along the path) by its
|
||||
/// own amount between −`amount` and `amount` degrees, drawn from `seed` (the stroke's
|
||||
/// [`crate::track::seed_of`]).
|
||||
pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) {
|
||||
let mut rng = crate::track::Rng::new(seed ^ HUE_JITTER_SALT);
|
||||
/// Mixed into a stroke's seed for its saturation jitter, so its amounts do not follow the hue
|
||||
/// jitter's and the hue jitter's amounts stay as they were without it.
|
||||
const SATURATION_JITTER_SALT: u64 = 0x7361_745f_6a69_7474;
|
||||
|
||||
/// Mixed into a stroke's seed for its brightness jitter, so its amounts follow neither the hue
|
||||
/// jitter's nor the saturation jitter's, and theirs stay as they were without it.
|
||||
const BRIGHTNESS_JITTER_SALT: u64 = 0x6272_695f_6a69_7474;
|
||||
|
||||
/// Recolor each of `copies` (a scatter brush's copies, in order along the path) with `adjust`,
|
||||
/// given that copy's own amount between −`amount` and `amount`, drawn from `seed` (the stroke's
|
||||
/// [`crate::track::seed_of`]) mixed with `salt`. `adjust` gives `None` for a color it leaves as it
|
||||
/// is.
|
||||
fn jitter_copies(copies: &mut [Node], amount: f64, seed: u64, salt: u64, adjust: fn(&Color, f32) -> Option<Color>) {
|
||||
let mut rng = crate::track::Rng::new(seed ^ salt);
|
||||
for n in copies {
|
||||
let turn = rng.range(-amount, amount) as f32;
|
||||
turn_hues(n, turn);
|
||||
let by = rng.range(-amount, amount) as f32;
|
||||
recolor_solids(n, &|c| adjust(c, by));
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn the hue of each of `copies` by its own amount between −`amount` and `amount` degrees (see
|
||||
/// [`jitter_copies`]).
|
||||
pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) {
|
||||
jitter_copies(copies, amount, seed, HUE_JITTER_SALT, turned);
|
||||
}
|
||||
|
||||
/// Move the saturation of each of `copies` by its own amount between −`amount` and `amount`
|
||||
/// percentage points (see [`jitter_copies`]).
|
||||
pub(crate) fn jitter_saturations(copies: &mut [Node], amount: f64, seed: u64) {
|
||||
jitter_copies(copies, amount, seed, SATURATION_JITTER_SALT, saturated);
|
||||
}
|
||||
|
||||
/// Move the brightness of each of `copies` by its own amount between −`amount` and `amount`
|
||||
/// percentage points (see [`jitter_copies`]).
|
||||
pub(crate) fn jitter_brightnesses(copies: &mut [Node], amount: f64, seed: u64) {
|
||||
jitter_copies(copies, amount, seed, BRIGHTNESS_JITTER_SALT, brightened);
|
||||
}
|
||||
|
||||
/// `c` with its brightness moved by `points` percentage points, worked out on its own components
|
||||
/// so its hue and saturation stay: RGB in HSB of its values, Gray by taking that much ink off or
|
||||
/// adding it, CMYK by changing its K over the brightness its C, M and Y leave (C, M and Y change
|
||||
/// only to go brighter than they show with no K), Lab by moving its lightness by `points` units
|
||||
/// with a and b kept. The result stays between black and full brightness. White, black and grays
|
||||
/// move too. `None` when the brightness stays as it is.
|
||||
fn brightened(c: &Color, points: f32) -> Option<Color> {
|
||||
if !points.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let by = points / 100.0;
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => {
|
||||
let [h, s, v] = vectorcraft_color::rgb_to_hsb([r, g, b]);
|
||||
let to = (v + by).clamp(0.0, 1.0);
|
||||
(to != v).then(|| {
|
||||
let [r, g, b] = vectorcraft_color::hsb_to_rgb([h, s, to]);
|
||||
Color::rgb(r, g, b)
|
||||
})
|
||||
}
|
||||
Color::Gray { k } => {
|
||||
let to = (k - by).clamp(0.0, 1.0);
|
||||
(to != k).then_some(Color::gray(to))
|
||||
}
|
||||
Color::Cmyk { c, m, y, k } => {
|
||||
// `v` is the brightness C, M and Y leave; with its K the color shows `v` × (1 − K).
|
||||
let [h, s, v] = vectorcraft_color::rgb_to_hsb([1.0 - c, 1.0 - m, 1.0 - y]);
|
||||
let shown = v * (1.0 - k);
|
||||
let to = (shown + by).clamp(0.0, 1.0);
|
||||
if to == shown {
|
||||
None
|
||||
} else if to <= v {
|
||||
// v > 0 here: to < shown would need shown > 0, and to > shown leaves to > 0.
|
||||
Some(Color::cmyk(c, m, y, (1.0 - to / v).clamp(0.0, 1.0)))
|
||||
} else {
|
||||
let [r, g, b] = vectorcraft_color::hsb_to_rgb([h, s, to]);
|
||||
Some(Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, 0.0))
|
||||
}
|
||||
}
|
||||
Color::Lab { l, a, b } => {
|
||||
let to = (l + points).clamp(0.0, 100.0);
|
||||
(to != l).then_some(Color::lab(to, a, b))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest a or b a Lab color takes.
|
||||
const LAB_AB_MAX: f64 = 127.0;
|
||||
|
||||
/// `c` with its saturation moved by `points` percentage points, worked out on its own components
|
||||
/// so its hue and brightness stay: RGB in HSB of its values, CMYK over C, M and Y with K kept, Lab
|
||||
/// by moving its chroma (the length of a and b) by `points` with its lightness and hue angle kept.
|
||||
/// The result stays between no saturation and full. `None` for a color without a hue (white,
|
||||
/// black and grays, which have no saturation to move) and for one whose saturation stays as it is
|
||||
/// (already at the end it would move past), so such a color keeps its swatch link.
|
||||
fn saturated(c: &Color, points: f32) -> Option<Color> {
|
||||
if !points.is_finite() || vectorcraft_color::recolor::Neutral::of(c).is_some() {
|
||||
return None;
|
||||
}
|
||||
let by = points / 100.0;
|
||||
let move_by = |v: [f32; 3]| {
|
||||
let [h, s, b] = vectorcraft_color::rgb_to_hsb(v);
|
||||
let to = (s + by).clamp(0.0, 1.0);
|
||||
(s > 0.0 && to != s).then(|| vectorcraft_color::hsb_to_rgb([h, to, b]))
|
||||
};
|
||||
match *c {
|
||||
Color::Rgb { r, g, b } => move_by([r, g, b]).map(|[r, g, b]| Color::rgb(r, g, b)),
|
||||
Color::Cmyk { c, m, y, k } => move_by([1.0 - c, 1.0 - m, 1.0 - y]).map(|[r, g, b]| Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, k)),
|
||||
Color::Gray { .. } => None,
|
||||
Color::Lab { l, a, b } => {
|
||||
let (a, b) = (f64::from(a), f64::from(b));
|
||||
let chroma = a.hypot(b);
|
||||
if chroma <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
// A longer chroma is cut back along the same hue angle until a and b fit; one that
|
||||
// already reaches past that does not grow.
|
||||
let fit = (LAB_AB_MAX / a.abs().max(b.abs())).max(1.0);
|
||||
let scale = ((chroma + f64::from(points)).max(0.0) / chroma).min(fit);
|
||||
(scale != 1.0).then(|| Color::lab(l, (a * scale) as f32, (b * scale) as f32))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,32 +267,36 @@ fn turned(c: &Color, degrees: f32) -> Option<Color> {
|
||||
}
|
||||
}
|
||||
|
||||
fn turn_paint(p: &mut Paint, degrees: f32) {
|
||||
/// Replace a solid paint's color with what `adjust` gives for it, dropping its swatch link. A
|
||||
/// color that comes back unchanged (an amount too small to move its components) keeps the paint
|
||||
/// and its link.
|
||||
fn recolor_paint(p: &mut Paint, adjust: &dyn Fn(&Color) -> Option<Color>) {
|
||||
if let Paint::Solid { color, .. } = p
|
||||
&& let Some(c) = turned(color, degrees)
|
||||
&& let Some(c) = adjust(color)
|
||||
&& c != *color
|
||||
{
|
||||
*p = Paint::solid(c);
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn the hue of the solid fills and strokes under `n`, its type's characters included. A
|
||||
/// Recolor the solid fills and strokes under `n` with `adjust`, its type's characters included. A
|
||||
/// mask's colors are its values, so they stay.
|
||||
fn turn_hues(n: &mut Node, degrees: f32) {
|
||||
fn recolor_solids(n: &mut Node, adjust: &dyn Fn(&Color) -> Option<Color>) {
|
||||
for it in &mut n.appearance.items {
|
||||
match it {
|
||||
AppearanceItem::Fill(f) => turn_paint(&mut f.paint, degrees),
|
||||
AppearanceItem::Stroke(s) => turn_paint(&mut s.paint, degrees),
|
||||
AppearanceItem::Fill(f) => recolor_paint(&mut f.paint, adjust),
|
||||
AppearanceItem::Stroke(s) => recolor_paint(&mut s.paint, adjust),
|
||||
}
|
||||
}
|
||||
if let NodeKind::Text(t) = &mut n.kind {
|
||||
for r in &mut t.runs {
|
||||
turn_paint(&mut r.style.fill, degrees);
|
||||
turn_paint(&mut r.style.stroke, degrees);
|
||||
recolor_paint(&mut r.style.fill, adjust);
|
||||
recolor_paint(&mut r.style.stroke, adjust);
|
||||
}
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
turn_hues(Arc::make_mut(c), degrees);
|
||||
recolor_solids(Arc::make_mut(c), adjust);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,6 +173,8 @@ pub fn defaults() -> &'static [Brush] {
|
||||
rotation_relative_to_path: false,
|
||||
colorization: Colorization::Tints,
|
||||
hue_jitter: 0.0,
|
||||
saturation_jitter: 0.0,
|
||||
brightness_jitter: 0.0,
|
||||
modes: None,
|
||||
}),
|
||||
},
|
||||
@@ -187,6 +189,8 @@ pub fn defaults() -> &'static [Brush] {
|
||||
rotation_relative_to_path: true,
|
||||
colorization: Colorization::None,
|
||||
hue_jitter: 0.0,
|
||||
saturation_jitter: 0.0,
|
||||
brightness_jitter: 0.0,
|
||||
modes: None,
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -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),
|
||||
@@ -324,6 +324,22 @@ pub struct Scatter {
|
||||
/// 0 (brushes saved before there was hue jitter) leaves the colors as they are.
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub hue_jitter: f64,
|
||||
/// Saturation jitter in percent, 0 to 100: each copy moves the saturation of the solid colors it
|
||||
/// draws, after the colorization and the hue jitter, by its own amount between
|
||||
/// −`saturation_jitter` and `saturation_jitter` percentage points, keeping their hue and
|
||||
/// brightness. The stroke's path and the brush name fix the amounts, so a stroke draws the same
|
||||
/// colors every time. 0 (brushes saved before there was saturation jitter) leaves the colors as
|
||||
/// they are.
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub saturation_jitter: f64,
|
||||
/// Brightness jitter in percent, 0 to 100: each copy moves the brightness of the solid colors
|
||||
/// it draws, after the colorization and the hue and saturation jitter, by its own amount
|
||||
/// between −`brightness_jitter` and `brightness_jitter` percentage points, keeping their hue
|
||||
/// and saturation. White, black and grays move too. The stroke's path and the brush name fix
|
||||
/// the amounts, so a stroke draws the same colors every time. 0 (brushes saved before there
|
||||
/// was brightness jitter) leaves the colors as they are.
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub brightness_jitter: f64,
|
||||
/// How size, spacing, scatter and rotation vary between their two values: Fixed takes the
|
||||
/// first, Random any value between them, Pressure the first at the lightest pen pressure and
|
||||
/// the second at the heaviest, Tilt the first with the pen lying flat and the second upright,
|
||||
@@ -346,6 +362,8 @@ impl Default for Scatter {
|
||||
rotation_relative_to_path: false,
|
||||
colorization: Colorization::None,
|
||||
hue_jitter: 0.0,
|
||||
saturation_jitter: 0.0,
|
||||
brightness_jitter: 0.0,
|
||||
modes: None,
|
||||
}
|
||||
}
|
||||
@@ -356,6 +374,10 @@ impl Scatter {
|
||||
pub const RANGES: [(f64, f64); 4] = [(1.0, 10000.0), (1.0, 10000.0), (-1000.0, 1000.0), (-180.0, 180.0)];
|
||||
/// The range of [`Scatter::hue_jitter`] (°).
|
||||
pub const HUE_JITTER_RANGE: (f64, f64) = (0.0, 180.0);
|
||||
/// The range of [`Scatter::saturation_jitter`] (%).
|
||||
pub const SATURATION_JITTER_RANGE: (f64, f64) = (0.0, 100.0);
|
||||
/// The range of [`Scatter::brightness_jitter`] (%).
|
||||
pub const BRIGHTNESS_JITTER_RANGE: (f64, f64) = (0.0, 100.0);
|
||||
|
||||
/// Size, spacing, scatter and rotation, each as its (first, second) values.
|
||||
pub fn values(&self) -> [(f64, f64); 4] {
|
||||
@@ -549,6 +571,15 @@ pub struct PatternBrush {
|
||||
pub end_swatch: Option<String>,
|
||||
/// Scale in percent.
|
||||
pub scale: f64,
|
||||
/// How the scale varies along a stroke: `None` (Fixed) always `scale`; a mode that follows the
|
||||
/// pen goes from `scale` to [`Self::scale_max`] over the ranges [`Variation`] gives, as an Art
|
||||
/// brush's width does ([`ArtBrush::width_mode`]).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub scale_mode: Option<Variation>,
|
||||
/// The second scale (%) of a mode that follows the pen: at the heaviest pressure, upright, at
|
||||
/// 180° or at the wheel's far end (`scale` without one).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub scale_max: Option<f64>,
|
||||
/// Space between tiles in percent of the tile width.
|
||||
pub spacing: f64,
|
||||
pub fit: PatternFit,
|
||||
@@ -561,6 +592,15 @@ impl PatternBrush {
|
||||
/// The ranges of the scale and of the spacing (%).
|
||||
pub const SCALE_RANGE: (f64, f64) = (1.0, 10000.0);
|
||||
pub const SPACING_RANGE: (f64, f64) = (0.0, 10000.0);
|
||||
|
||||
/// The scales (%) where the pen reads 0 and 1 for the scale's mode (the lightest and the
|
||||
/// heaviest pressure, for Pressure): `scale` for both unless the scale follows the pen.
|
||||
pub fn scale_range(&self) -> (f64, f64) {
|
||||
match self.scale_mode {
|
||||
Some(m) if m.follows_pen() => (self.scale, self.scale_max.unwrap_or(self.scale)),
|
||||
_ => (self.scale, self.scale),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PatternBrush {
|
||||
@@ -584,6 +624,8 @@ impl Default for PatternBrush {
|
||||
end_frame: None,
|
||||
end_swatch: None,
|
||||
scale: 100.0,
|
||||
scale_mode: None,
|
||||
scale_max: None,
|
||||
spacing: 0.0,
|
||||
fit: PatternFit::Stretch,
|
||||
flip_along: false,
|
||||
@@ -750,6 +792,8 @@ impl Brush {
|
||||
s.scatter = within_pair(s.scatter, scatter, 0.0);
|
||||
s.rotation = within_pair(s.rotation, rotation, 0.0);
|
||||
s.hue_jitter = within(s.hue_jitter, Scatter::HUE_JITTER_RANGE, 0.0);
|
||||
s.saturation_jitter = within(s.saturation_jitter, Scatter::SATURATION_JITTER_RANGE, 0.0);
|
||||
s.brightness_jitter = within(s.brightness_jitter, Scatter::BRIGHTNESS_JITTER_RANGE, 0.0);
|
||||
s.colorization.sanitize();
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
@@ -767,6 +811,11 @@ impl Brush {
|
||||
}
|
||||
BrushKind::Pattern(p) => {
|
||||
p.scale = within(p.scale, PatternBrush::SCALE_RANGE, 100.0);
|
||||
// The scale follows the pen (its pressure, tilt, bearing, rotation or wheel) or stays fixed.
|
||||
if !p.scale_mode.is_some_and(Variation::follows_pen) {
|
||||
p.scale_mode = None;
|
||||
}
|
||||
p.scale_max = p.scale_max.map(|s| within(s, PatternBrush::SCALE_RANGE, p.scale));
|
||||
p.spacing = within(p.spacing, PatternBrush::SPACING_RANGE, 0.0);
|
||||
for frame in [&mut p.side_frame, &mut p.outer_corner_frame, &mut p.inner_corner_frame, &mut p.start_frame, &mut p.end_frame] {
|
||||
if frame.is_some_and(|f| !valid_tile_frame(f)) {
|
||||
@@ -801,6 +850,9 @@ struct ScatterOptions {
|
||||
modes: Option<[Variation; 4]>,
|
||||
rotation_relative_to_path: bool,
|
||||
colorization: Colorization,
|
||||
hue_jitter: f64,
|
||||
saturation_jitter: f64,
|
||||
brightness_jitter: f64,
|
||||
}
|
||||
|
||||
/// The Art brush fields a stroke can set for itself.
|
||||
@@ -819,6 +871,8 @@ struct ArtOptions {
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct PatternOptions {
|
||||
scale: f64,
|
||||
scale_mode: Option<Variation>,
|
||||
scale_max: Option<f64>,
|
||||
spacing: f64,
|
||||
fit: PatternFit,
|
||||
flip_along: bool,
|
||||
@@ -833,9 +887,20 @@ impl BrushKind {
|
||||
pub fn stroke_option_keys(&self) -> &'static [&'static str] {
|
||||
match self {
|
||||
BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"],
|
||||
BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"],
|
||||
BrushKind::Scatter(_) => &[
|
||||
"size",
|
||||
"spacing",
|
||||
"scatter",
|
||||
"rotation",
|
||||
"modes",
|
||||
"rotation_relative_to_path",
|
||||
"colorization",
|
||||
"hue_jitter",
|
||||
"saturation_jitter",
|
||||
"brightness_jitter",
|
||||
],
|
||||
BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"],
|
||||
BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"],
|
||||
BrushKind::Pattern(_) => &["scale", "scale_mode", "scale_max", "spacing", "fit", "flip_along", "flip_across", "colorization"],
|
||||
BrushKind::Bristle(_) => &[],
|
||||
}
|
||||
}
|
||||
@@ -858,6 +923,9 @@ impl BrushKind {
|
||||
modes: s.modes,
|
||||
rotation_relative_to_path: s.rotation_relative_to_path,
|
||||
colorization: s.colorization,
|
||||
hue_jitter: s.hue_jitter,
|
||||
saturation_jitter: s.saturation_jitter,
|
||||
brightness_jitter: s.brightness_jitter,
|
||||
}),
|
||||
BrushKind::Art(a) => serde_json::to_value(ArtOptions {
|
||||
width: a.width,
|
||||
@@ -870,6 +938,8 @@ impl BrushKind {
|
||||
}),
|
||||
BrushKind::Pattern(p) => serde_json::to_value(PatternOptions {
|
||||
scale: p.scale,
|
||||
scale_mode: p.scale_mode,
|
||||
scale_max: p.scale_max,
|
||||
spacing: p.spacing,
|
||||
fit: p.fit,
|
||||
flip_along: p.flip_along,
|
||||
@@ -890,6 +960,7 @@ impl BrushKind {
|
||||
let o: ScatterOptions = serde_json::from_value(v)?;
|
||||
(s.size, s.spacing, s.scatter, s.rotation, s.modes) = (o.size, o.spacing, o.scatter, o.rotation, o.modes);
|
||||
(s.rotation_relative_to_path, s.colorization) = (o.rotation_relative_to_path, o.colorization);
|
||||
(s.hue_jitter, s.saturation_jitter, s.brightness_jitter) = (o.hue_jitter, o.saturation_jitter, o.brightness_jitter);
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
let o: ArtOptions = serde_json::from_value(v)?;
|
||||
@@ -898,8 +969,8 @@ impl BrushKind {
|
||||
}
|
||||
BrushKind::Pattern(p) => {
|
||||
let o: PatternOptions = serde_json::from_value(v)?;
|
||||
(p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) =
|
||||
(o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization);
|
||||
(p.scale, p.scale_mode, p.scale_max, p.spacing) = (o.scale, o.scale_mode, o.scale_max, o.spacing);
|
||||
(p.fit, p.flip_along, p.flip_across, p.colorization) = (o.fit, o.flip_along, o.flip_across, o.colorization);
|
||||
}
|
||||
BrushKind::Bristle(_) => {}
|
||||
}
|
||||
@@ -1123,17 +1194,23 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
|
||||
BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name),
|
||||
BrushKind::Art(a) => warp::art(a, bp, w, stroke),
|
||||
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name),
|
||||
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
|
||||
BrushKind::Pattern(p) => warp::pattern(p, bp, w, stroke),
|
||||
};
|
||||
let colorization = brush.kind.colorization();
|
||||
for n in &mut out {
|
||||
colorize(n, colorization, &stroke.paint);
|
||||
}
|
||||
// One piece per copy, in the order the copies run along the path.
|
||||
if let BrushKind::Scatter(s) = &brush.kind
|
||||
&& s.hue_jitter > 0.0
|
||||
{
|
||||
colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name));
|
||||
if let BrushKind::Scatter(s) = &brush.kind {
|
||||
if s.hue_jitter > 0.0 {
|
||||
colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name));
|
||||
}
|
||||
if s.saturation_jitter > 0.0 {
|
||||
colorize::jitter_saturations(&mut out, s.saturation_jitter, track::seed_of(bp, &brush.name));
|
||||
}
|
||||
if s.brightness_jitter > 0.0 {
|
||||
colorize::jitter_brightnesses(&mut out, s.brightness_jitter, track::seed_of(bp, &brush.name));
|
||||
}
|
||||
}
|
||||
leave_out_brushed(doc, &mut out, &mut Known::new());
|
||||
out
|
||||
|
||||
@@ -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 {
|
||||
@@ -1233,6 +1249,380 @@ fn hue_jitter_turns_type_every_colorization_and_linked_colors() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke's own hue, saturation and brightness jitter replace the brush's, as its other scatter
|
||||
/// settings do, and are kept within their ranges.
|
||||
#[test]
|
||||
fn a_strokes_own_jitter_replaces_the_brushs() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
let pink = Color::rgb(0.8, 0.4, 0.4);
|
||||
let b = sat_jittered(pink, Colorization::None, 0.0, 0.0);
|
||||
let own =
|
||||
stroke_pieces(&doc, &b, &path, &with_options(serde_json::json!({"hue_jitter": 30.0, "saturation_jitter": 40.0, "brightness_jitter": 20.0})));
|
||||
let brushed = stroke_pieces(&doc, &bri_jittered(sat_jittered(pink, Colorization::None, 30.0, 40.0), 20.0), &path, &stroke(1.0));
|
||||
assert_eq!(fill_colors(&own), fill_colors(&brushed));
|
||||
assert!(fill_colors(&own).iter().any(|c| *c != pink));
|
||||
// The brightness is part of what the stroke's own options give.
|
||||
let without = stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 30.0, 40.0), &path, &stroke(1.0));
|
||||
assert_ne!(fill_colors(&own), fill_colors(&without));
|
||||
for (key, given, kept) in [("saturation_jitter", 500.0, 100.0), ("brightness_jitter", 500.0, 100.0)] {
|
||||
let options = serde_json::Map::from_iter([(key.to_string(), serde_json::json!(given))]);
|
||||
assert_eq!(b.stroke_options_that_differ(&options).unwrap(), serde_json::Map::from_iter([(key.to_string(), serde_json::json!(kept))]));
|
||||
}
|
||||
// A stroke that sets 0 on a jittered brush draws the art's own color.
|
||||
let still =
|
||||
stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 40.0), &path, &with_options(serde_json::json!({"saturation_jitter": 0.0})));
|
||||
assert!(!still.is_empty() && fill_colors(&still).iter().all(|c| *c == pink));
|
||||
}
|
||||
|
||||
/// A scatter brush of rectangles filled `fill`, with `colorization`, `hue_jitter` and
|
||||
/// `saturation_jitter`.
|
||||
fn sat_jittered(fill: Color, colorization: Colorization, hue_jitter: f64, saturation_jitter: f64) -> Brush {
|
||||
let mut b = jittered(fill, colorization, hue_jitter);
|
||||
if let BrushKind::Scatter(s) = &mut b.kind {
|
||||
s.saturation_jitter = saturation_jitter;
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// The HSB of an RGB color's own values.
|
||||
fn rgb_hsb(c: &Color) -> [f32; 3] {
|
||||
let Color::Rgb { r, g, b } = *c else { panic!("not RGB: {c:?}") };
|
||||
vectorcraft_color::rgb_to_hsb([r, g, b])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saturation_jitter_moves_each_copy_the_same_every_time() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
// A red at 50% saturation and 80% brightness.
|
||||
let pink = Color::rgb(0.8, 0.4, 0.4);
|
||||
let b = sat_jittered(pink, Colorization::None, 0.0, 40.0);
|
||||
let out = stroke_pieces(&doc, &b, &path, &stroke(1.0));
|
||||
assert_eq!(out.len(), 20);
|
||||
assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors");
|
||||
let colors = fill_colors(&out);
|
||||
let hsb: Vec<[f32; 3]> = colors.iter().map(rgb_hsb).collect();
|
||||
// Each copy's saturation is within 40 points of 50%; its hue and brightness stay.
|
||||
assert!(hsb.iter().all(|[h, s, v]| hue_gap(*h, 0.0) < 1e-3 && (s - 0.5).abs() <= 0.4001 && near(f64::from(*v), 0.8, 1e-4)), "{hsb:?}");
|
||||
assert!(hsb.iter().any(|[_, s, _]| *s > 0.55) && hsb.iter().any(|[_, s, _]| *s < 0.45), "the copies move both ways: {hsb:?}");
|
||||
let distinct: std::collections::HashSet<String> = colors.iter().map(Color::to_hex).collect();
|
||||
assert!(distinct.len() > 10, "each copy moves by its own amount: {distinct:?}");
|
||||
// The copies stay where they were, at their size and angle.
|
||||
let plain = stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 0.0), &path, &stroke(1.0));
|
||||
let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::<Vec<_>>();
|
||||
assert_eq!(boxes(&out), boxes(&plain));
|
||||
// Another path draws other amounts.
|
||||
let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0)));
|
||||
assert_ne!(other, colors);
|
||||
// At 100 the copies reach gray or full saturation and go no further.
|
||||
let full: Vec<f32> = fill_colors(&stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 100.0), &path, &stroke(1.0)))
|
||||
.iter()
|
||||
.map(|c| rgb_hsb(c)[1])
|
||||
.collect();
|
||||
assert!(full.iter().all(|s| (0.0..=1.0).contains(s)), "{full:?}");
|
||||
assert!(full.iter().any(|s| *s < 1e-6) && full.iter().any(|s| *s > 1.0 - 1e-6), "{full:?}");
|
||||
// Saturation jitter leaves the hue jitter's amounts as they were.
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
let hue_only = fill_colors(&stroke_pieces(&doc, &sat_jittered(red, Colorization::None, 90.0, 0.0), &path, &stroke(1.0)));
|
||||
let both = fill_colors(&stroke_pieces(&doc, &sat_jittered(red, Colorization::None, 90.0, 50.0), &path, &stroke(1.0)));
|
||||
assert_eq!(both.len(), hue_only.len());
|
||||
assert_ne!(both, hue_only);
|
||||
for (b, h) in both.iter().zip(&hue_only) {
|
||||
assert!(hue_gap(rgb_hsb(b)[0], rgb_hsb(h)[0]) < 0.01, "{b:?} from {h:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saturation_jitter_of_zero_changes_nothing() {
|
||||
let pink = Color::rgb(0.8, 0.4, 0.4);
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &sat_jittered(pink, Colorization::None, 0.0, 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0));
|
||||
assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == pink));
|
||||
// A brush without saturation jitter is saved as before, and one saved before reads as 0.
|
||||
let v = serde_json::to_value(sat_jittered(pink, Colorization::None, 0.0, 0.0)).unwrap();
|
||||
assert!(v.get("saturation_jitter").is_none(), "{v}");
|
||||
let mut old = serde_json::to_value(sat_jittered(pink, Colorization::None, 0.0, 25.0)).unwrap();
|
||||
assert_eq!(old.as_object_mut().unwrap().remove("saturation_jitter"), Some(serde_json::json!(25.0)));
|
||||
let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.saturation_jitter, 0.0, "a brush saved without the key reads as 0");
|
||||
let mut with = v.clone();
|
||||
with["saturation_jitter"] = serde_json::json!(25.0);
|
||||
let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.saturation_jitter, 25.0);
|
||||
// Values outside 0..100 are clamped.
|
||||
for (given, kept) in [(250.0, 100.0), (-5.0, 0.0)] {
|
||||
let mut v = v.clone();
|
||||
v["saturation_jitter"] = serde_json::json!(given);
|
||||
let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.saturation_jitter, kept, "{given}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saturation_jitter_moves_after_the_colorization_in_each_model() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
// Tints: black art takes the blue stroke color, whose saturation then moves.
|
||||
let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
|
||||
let hsb: Vec<[f32; 3]> =
|
||||
fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::BLACK, Colorization::Tints, 0.0, 30.0), &path, &blue)).iter().map(rgb_hsb).collect();
|
||||
assert!(!hsb.is_empty() && hsb.iter().all(|[h, s, _]| hue_gap(*h, 240.0) < 1e-3 && *s >= 0.6999), "{hsb:?}");
|
||||
assert!(hsb.iter().any(|[_, s, _]| *s < 0.97), "{hsb:?}");
|
||||
// Black, white and grays have no saturation to move, in every model.
|
||||
for key in
|
||||
[Color::rgb(0.5, 0.5, 0.5), Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 0.0, 0.0, 0.5), Color::gray(0.4), Color::lab(60.0, 0.0, 0.0)]
|
||||
{
|
||||
let key = StrokeLayer::new(Paint::solid(key), 1.0);
|
||||
let moved = stroke_pieces(&doc, &sat_jittered(Color::BLACK, Colorization::Tints, 0.0, 100.0), &path, &key);
|
||||
let still = stroke_pieces(&doc, &sat_jittered(Color::BLACK, Colorization::Tints, 0.0, 0.0), &path, &key);
|
||||
assert_eq!(fill_colors(&moved), fill_colors(&still), "{key:?}");
|
||||
}
|
||||
// A process color stays a process color with its K kept, moved over its C, M and Y.
|
||||
let cmyk = fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::cmyk(0.0, 0.6, 0.6, 0.25), Colorization::None, 0.0, 30.0), &path, &stroke(1.0)));
|
||||
assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 0.6, 0.6, 0.25)), "{cmyk:?}");
|
||||
for c in &cmyk {
|
||||
let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") };
|
||||
// No cyan, as before, and magenta equal to yellow: the hue stays; the ink is within 30 points.
|
||||
assert!(k == 0.25 && near(f64::from(c), 0.0, 1e-5) && near(f64::from(m), f64::from(y), 1e-5), "{c} {m} {y} {k}");
|
||||
assert!((m - 0.6).abs() <= 0.3001, "{m}");
|
||||
}
|
||||
// A Lab color keeps its lightness and hue angle; its chroma moves within 20 of its 50.
|
||||
let lab = fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::lab(50.0, 40.0, 30.0), Colorization::None, 0.0, 20.0), &path, &stroke(1.0)));
|
||||
assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}");
|
||||
for c in &lab {
|
||||
let Color::Lab { l, a, b } = *c else { panic!("not Lab: {c:?}") };
|
||||
let chroma = f64::from(a.hypot(b));
|
||||
assert!(l == 50.0 && (chroma - 50.0).abs() <= 20.001 && near(f64::from(b.atan2(a)), 30f64.atan2(40.0), 1e-4), "{c:?}");
|
||||
}
|
||||
// A chroma that grows stops where a and b reach their largest.
|
||||
let vivid = fill_colors(&stroke_pieces(&doc, &sat_jittered(Color::lab(50.0, 120.0, 0.0), Colorization::None, 0.0, 100.0), &path, &stroke(1.0)));
|
||||
assert!(vivid.iter().all(|c| matches!(*c, Color::Lab { a, b, .. } if (0.0..=127.0001).contains(&a) && b.abs() < 1e-4)), "{vivid:?}");
|
||||
assert!(vivid.iter().any(|c| matches!(*c, Color::Lab { a, .. } if a > 126.999)), "{vivid:?}");
|
||||
}
|
||||
|
||||
/// Saturation jitter moves type's characters and a color linked to a swatch (which loses the
|
||||
/// link); a pattern paint stays.
|
||||
#[test]
|
||||
fn saturation_jitter_moves_type_and_linked_colors() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let typed = |saturation_jitter| Brush {
|
||||
name: "s".into(),
|
||||
kind: BrushKind::Scatter(Scatter { art: type_art(red.clone(), red.clone()), saturation_jitter, ..Default::default() }),
|
||||
};
|
||||
let still = run_paints(&stroke_pieces(&doc, &typed(0.0), &path, &stroke(1.0)));
|
||||
let moved = run_paints(&stroke_pieces(&doc, &typed(60.0), &path, &stroke(1.0)));
|
||||
assert!(!still.is_empty() && still.iter().all(|p| *p == (red.clone(), red.clone())), "{still:?}");
|
||||
assert_eq!(moved.len(), still.len());
|
||||
assert!(moved.iter().any(|p| *p != (red.clone(), red.clone())), "the characters move: {moved:?}");
|
||||
assert!(moved.iter().all(|(f, s)| f == s), "a copy's character fill and stroke move by the same amount: {moved:?}");
|
||||
let linked = Paint::Solid { color: Color::rgb(0.8, 0.4, 0.4), swatch: Some("Rose".into()), tint: 1.0 };
|
||||
let pattern = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY };
|
||||
let mut art = rect_art(10.0, 4.0);
|
||||
art.appearance.set_fill(linked.clone());
|
||||
art.appearance.set_stroke(pattern.clone());
|
||||
let b = |saturation_jitter| Brush {
|
||||
name: "s".into(),
|
||||
kind: BrushKind::Scatter(Scatter { art: art.clone(), saturation_jitter, ..Default::default() }),
|
||||
};
|
||||
let moved = stroke_pieces(&doc, &b(50.0), &path, &stroke(1.0));
|
||||
assert!(!moved.is_empty());
|
||||
assert!(moved.iter().any(|n| n.appearance.fill_paint().color() != Some(Color::rgb(0.8, 0.4, 0.4))), "the linked color moves");
|
||||
for n in &moved {
|
||||
assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint());
|
||||
assert_eq!(n.appearance.stroke().map(|s| &s.paint), Some(&pattern));
|
||||
}
|
||||
}
|
||||
|
||||
/// `b` (a scatter brush) with `brightness_jitter`.
|
||||
fn bri_jittered(mut b: Brush, brightness_jitter: f64) -> Brush {
|
||||
if let BrushKind::Scatter(s) = &mut b.kind {
|
||||
s.brightness_jitter = brightness_jitter;
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brightness_jitter_moves_each_copy_the_same_every_time() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
// A red at 50% saturation and 80% brightness.
|
||||
let pink = Color::rgb(0.8, 0.4, 0.4);
|
||||
let b = bri_jittered(sat_jittered(pink, Colorization::None, 0.0, 0.0), 15.0);
|
||||
let out = stroke_pieces(&doc, &b, &path, &stroke(1.0));
|
||||
assert_eq!(out.len(), 20);
|
||||
assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors");
|
||||
let colors = fill_colors(&out);
|
||||
let hsb: Vec<[f32; 3]> = colors.iter().map(rgb_hsb).collect();
|
||||
// Each copy's brightness is within 15 points of 80%; its hue and saturation stay.
|
||||
assert!(hsb.iter().all(|[h, s, v]| hue_gap(*h, 0.0) < 1e-3 && near(f64::from(*s), 0.5, 1e-4) && (v - 0.8).abs() <= 0.1501), "{hsb:?}");
|
||||
assert!(hsb.iter().any(|[_, _, v]| *v > 0.85) && hsb.iter().any(|[_, _, v]| *v < 0.75), "the copies move both ways: {hsb:?}");
|
||||
let distinct: std::collections::HashSet<String> = colors.iter().map(Color::to_hex).collect();
|
||||
assert!(distinct.len() > 10, "each copy moves by its own amount: {distinct:?}");
|
||||
// The copies stay where they were, at their size and angle.
|
||||
let plain = stroke_pieces(&doc, &sat_jittered(pink, Colorization::None, 0.0, 0.0), &path, &stroke(1.0));
|
||||
let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::<Vec<_>>();
|
||||
assert_eq!(boxes(&out), boxes(&plain));
|
||||
// Another path draws other amounts.
|
||||
let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0)));
|
||||
assert_ne!(other, colors);
|
||||
// At 100 the copies reach black or full brightness and go no further.
|
||||
let full: Vec<f32> =
|
||||
fill_colors(&stroke_pieces(&doc, &bri_jittered(sat_jittered(pink, Colorization::None, 0.0, 0.0), 100.0), &path, &stroke(1.0)))
|
||||
.iter()
|
||||
.map(|c| rgb_hsb(c)[2])
|
||||
.collect();
|
||||
assert!(full.iter().all(|v| (0.0..=1.0).contains(v)), "{full:?}");
|
||||
assert!(full.iter().any(|v| *v < 1e-6) && full.iter().any(|v| *v > 1.0 - 1e-6), "{full:?}");
|
||||
// Brightness jitter leaves the hue and saturation jitter's amounts as they were.
|
||||
let red = Color::rgb(1.0, 0.0, 0.0);
|
||||
let hue_sat = fill_colors(&stroke_pieces(&doc, &sat_jittered(red, Colorization::None, 90.0, 50.0), &path, &stroke(1.0)));
|
||||
let all = fill_colors(&stroke_pieces(&doc, &bri_jittered(sat_jittered(red, Colorization::None, 90.0, 50.0), 30.0), &path, &stroke(1.0)));
|
||||
assert_eq!(all.len(), hue_sat.len());
|
||||
assert_ne!(all, hue_sat);
|
||||
for (a, h) in all.iter().zip(&hue_sat) {
|
||||
let ([ha, sa, _], [hh, sh, _]) = (rgb_hsb(a), rgb_hsb(h));
|
||||
assert!(hue_gap(ha, hh) < 0.01 && (sa - sh).abs() < 1e-4, "{a:?} from {h:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brightness_jitter_of_zero_changes_nothing() {
|
||||
let pink = Color::rgb(0.8, 0.4, 0.4);
|
||||
let plain = sat_jittered(pink, Colorization::None, 0.0, 0.0);
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &bri_jittered(plain.clone(), 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0));
|
||||
assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == pink));
|
||||
// A brush without brightness jitter is saved as before, and one saved before reads as 0.
|
||||
let v = serde_json::to_value(&plain).unwrap();
|
||||
assert!(v.get("brightness_jitter").is_none(), "{v}");
|
||||
let mut old = serde_json::to_value(bri_jittered(plain.clone(), 25.0)).unwrap();
|
||||
assert_eq!(old.as_object_mut().unwrap().remove("brightness_jitter"), Some(serde_json::json!(25.0)));
|
||||
let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.brightness_jitter, 0.0, "a brush saved without the key reads as 0");
|
||||
let mut with = v.clone();
|
||||
with["brightness_jitter"] = serde_json::json!(25.0);
|
||||
let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.brightness_jitter, 25.0);
|
||||
// Values outside 0..100 are clamped.
|
||||
for (given, kept) in [(250.0, 100.0), (-5.0, 0.0)] {
|
||||
let mut v = v.clone();
|
||||
v["brightness_jitter"] = serde_json::json!(given);
|
||||
let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert_eq!(s.brightness_jitter, kept, "{given}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brightness_jitter_moves_after_the_colorization_in_each_model() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
let jittered_fills = |art: Color, colorization: Colorization, amount: f64, key: &StrokeLayer| {
|
||||
fill_colors(&stroke_pieces(&doc, &bri_jittered(sat_jittered(art, colorization, 0.0, 0.0), amount), &path, key))
|
||||
};
|
||||
// Tints: black art takes the blue stroke color, whose brightness then moves.
|
||||
let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
|
||||
let hsb: Vec<[f32; 3]> = jittered_fills(Color::BLACK, Colorization::Tints, 30.0, &blue).iter().map(rgb_hsb).collect();
|
||||
assert!(!hsb.is_empty() && hsb.iter().all(|[h, s, v]| hue_gap(*h, 240.0) < 1e-3 && near(f64::from(*s), 1.0, 1e-4) && *v >= 0.6999), "{hsb:?}");
|
||||
assert!(hsb.iter().any(|[_, _, v]| *v < 0.97), "{hsb:?}");
|
||||
// White, black and grays move too, and stay neutral. RGB white gets darker.
|
||||
let white: Vec<[f32; 3]> = jittered_fills(Color::WHITE, Colorization::None, 30.0, &stroke(1.0)).iter().map(rgb_hsb).collect();
|
||||
assert!(white.iter().all(|[_, s, v]| *s == 0.0 && *v >= 0.6999) && white.iter().any(|[_, _, v]| *v < 0.95), "{white:?}");
|
||||
// A gray's ink moves within 20 points of its 40%.
|
||||
let gray = StrokeLayer::new(Paint::solid(Color::gray(0.4)), 1.0);
|
||||
let grays = jittered_fills(Color::BLACK, Colorization::Tints, 20.0, &gray);
|
||||
assert!(grays.iter().all(|c| matches!(*c, Color::Gray { k } if (k - 0.4).abs() <= 0.2001)), "{grays:?}");
|
||||
assert!(grays.iter().any(|c| *c != Color::gray(0.4)), "{grays:?}");
|
||||
// Black ink alone stays black ink alone, lighter by its K.
|
||||
let k_only = jittered_fills(Color::cmyk(0.0, 0.0, 0.0, 1.0), Colorization::None, 30.0, &stroke(1.0));
|
||||
assert!(k_only.iter().all(|c| matches!(*c, Color::Cmyk { c, m, y, k } if c == 0.0 && m == 0.0 && y == 0.0 && k >= 0.6999)), "{k_only:?}");
|
||||
assert!(k_only.iter().any(|c| matches!(*c, Color::Cmyk { k, .. } if k < 0.97)), "{k_only:?}");
|
||||
// A process color with room in its K moves by its K and keeps its C, M and Y.
|
||||
let cmyk = jittered_fills(Color::cmyk(0.0, 0.6, 0.6, 0.25), Colorization::None, 20.0, &stroke(1.0));
|
||||
assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 0.6, 0.6, 0.25)), "{cmyk:?}");
|
||||
for c in &cmyk {
|
||||
let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") };
|
||||
assert!(c == 0.0 && m == 0.6 && y == 0.6 && (k - 0.25).abs() <= 0.2001, "{c} {m} {y} {k}");
|
||||
}
|
||||
// One brighter than its C, M and Y show with no K loses its K and takes less ink, its hue and
|
||||
// saturation kept (full magenta and yellow, cyan the brightness).
|
||||
let deep = jittered_fills(Color::cmyk(0.4, 1.0, 1.0, 0.0), Colorization::None, 30.0, &stroke(1.0));
|
||||
let mut ways = (false, false);
|
||||
for c in &deep {
|
||||
let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") };
|
||||
assert!(near(f64::from(m), 1.0, 1e-5) && near(f64::from(y), 1.0, 1e-5), "{c} {m} {y} {k}");
|
||||
if k > 0.0 {
|
||||
assert!(c == 0.4 && k <= 0.5001, "darker: {c} {k}");
|
||||
ways.0 = true;
|
||||
} else {
|
||||
assert!((0.0999..=0.4).contains(&c), "brighter: {c}");
|
||||
ways.1 |= c < 0.4;
|
||||
}
|
||||
}
|
||||
assert!(ways.0 && ways.1, "the copies move both ways: {deep:?}");
|
||||
// A Lab color keeps its a and b; its lightness moves within 20 of its 50.
|
||||
let lab = jittered_fills(Color::lab(50.0, 40.0, 30.0), Colorization::None, 20.0, &stroke(1.0));
|
||||
assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}");
|
||||
assert!(lab.iter().all(|c| matches!(*c, Color::Lab { l, a, b } if a == 40.0 && b == 30.0 && (l - 50.0).abs() <= 20.001)), "{lab:?}");
|
||||
}
|
||||
|
||||
/// A swatch-linked color already at the end a copy's saturation or brightness moves toward stays as
|
||||
/// it is and keeps its link; the copies that move it lose the link.
|
||||
#[test]
|
||||
fn jitter_at_a_limit_keeps_the_swatch_link() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let path = line(0.0, 0.0, 200.0, 0.0);
|
||||
// Full red (full saturation and brightness), full magenta and yellow ink, and a Lab red whose a
|
||||
// is at its largest: saturation that grows and brightness that grows leave them as they are.
|
||||
for (color, saturation_jitter, brightness_jitter) in [
|
||||
(Color::rgb(1.0, 0.0, 0.0), 50.0, 0.0),
|
||||
(Color::cmyk(0.0, 1.0, 1.0, 0.0), 50.0, 0.0),
|
||||
(Color::lab(50.0, 127.0, 0.0), 50.0, 0.0),
|
||||
(Color::rgb(1.0, 0.0, 0.0), 0.0, 50.0),
|
||||
(Color::lab(100.0, 20.0, 10.0), 0.0, 50.0),
|
||||
] {
|
||||
let linked = Paint::Solid { color, swatch: Some("Spot".into()), tint: 1.0 };
|
||||
let mut art = rect_art(10.0, 4.0);
|
||||
art.appearance.set_fill(linked.clone());
|
||||
let mut s = Scatter { art, saturation_jitter, ..Default::default() };
|
||||
s.brightness_jitter = brightness_jitter;
|
||||
let out = stroke_pieces(&doc, &Brush { name: "s".into(), kind: BrushKind::Scatter(s) }, &path, &stroke(1.0));
|
||||
let (mut kept, mut moved) = (0, 0);
|
||||
for n in &out {
|
||||
match n.appearance.fill_paint() {
|
||||
p if p == linked => kept += 1,
|
||||
Paint::Solid { color: c, swatch: None, .. } if c != color => moved += 1,
|
||||
p => panic!("{color:?}: {p:?}"),
|
||||
}
|
||||
}
|
||||
assert!(kept > 0 && moved > 0, "{color:?}: {kept} kept, {moved} moved");
|
||||
}
|
||||
}
|
||||
|
||||
/// A hue or saturation jitter too small to move a Lab color's components gives each copy the color
|
||||
/// it had, and the copies keep the swatch link.
|
||||
#[test]
|
||||
fn jitter_too_small_to_change_a_color_keeps_the_swatch_link() {
|
||||
let linked = Paint::Solid { color: Color::lab(50.0, 64.0, 0.0), swatch: Some("Spot".into()), tint: 1.0 };
|
||||
// 1e-50 degrees turns a and b by less than an f32 holds; 1e-6 points scales the chroma by
|
||||
// 1 + 1.6e-8, which rounds back to the same f32 components.
|
||||
type Jitter = fn(&mut [Node], f64, u64);
|
||||
let jitters: [(&str, Jitter, f64); 2] = [("hue", crate::colorize::jitter_hues, 1e-50), ("saturation", crate::colorize::jitter_saturations, 1e-6)];
|
||||
for (name, jitter, amount) in jitters {
|
||||
let mut copies: Vec<Node> = (0..8)
|
||||
.map(|_| {
|
||||
let mut art = rect_art(10.0, 4.0);
|
||||
art.appearance.set_fill(linked.clone());
|
||||
art
|
||||
})
|
||||
.collect();
|
||||
jitter(&mut copies, amount, 7);
|
||||
for n in &copies {
|
||||
assert_eq!(n.appearance.fill_paint(), linked, "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its
|
||||
/// swatch links.
|
||||
#[test]
|
||||
@@ -2015,6 +2405,374 @@ fn art_brush_width_follows_tilt_bearing_and_rotation() {
|
||||
assert_eq!(modes, [Some(Variation::Tilt), Some(Variation::Bearing), Some(Variation::Rotation), None]);
|
||||
}
|
||||
|
||||
/// A pattern brush with `scale`, `scale_mode` and `scale_max`, its 10 × 4 pt side tile on `fit`.
|
||||
fn scaled_pattern(fit: PatternFit, corners: bool, scale: f64, mode: Option<Variation>, max: Option<f64>) -> Brush {
|
||||
let mut b = pattern_brush(fit, corners);
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
(p.scale, p.scale_mode, p.scale_max) = (scale, mode, max);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// The bounds of each piece, left to right.
|
||||
fn piece_spans(out: &[Node]) -> Vec<Rect> {
|
||||
let mut spans: Vec<Rect> = out.iter().filter_map(Node::geometric_bounds).collect();
|
||||
spans.sort_by(|a, b| a.x0.total_cmp(&b.x0));
|
||||
spans
|
||||
}
|
||||
|
||||
/// Pattern Brush Options: with Scale on Pressure the tiles go from Scale at the lightest pen
|
||||
/// pressure to the second scale at the heaviest, taller and longer along the stroke where the pen
|
||||
/// pressed harder, and each Fit still fits them to the path.
|
||||
#[test]
|
||||
fn pattern_brush_scale_follows_the_pressure() {
|
||||
let bp = line(0.0, 0.0, 200.0, 0.0);
|
||||
let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st);
|
||||
let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]);
|
||||
// 4 pt tall tiles at 50 %: 1 pt either side at the lightest; at 300 %: 6 pt at the heaviest.
|
||||
let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp);
|
||||
assert!(near(half_width(&out, 0.0, 1.0), 1.0, 0.1), "{}", half_width(&out, 0.0, 1.0));
|
||||
assert!(near(half_width(&out, 199.0, 200.0), 6.0, 0.2), "{}", half_width(&out, 199.0, 200.0));
|
||||
assert!(near(half_width(&out, 99.0, 101.0), 3.5, 0.2), "{}", half_width(&out, 99.0, 101.0));
|
||||
// Stretch to Fit fills the path, and the tiles grow longer along it.
|
||||
let spans = piece_spans(&out);
|
||||
assert!(near(bounds(&out).x0, 0.0, 1e-6) && near(bounds(&out).x1, 200.0, 1e-6), "{:?}", bounds(&out));
|
||||
assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{spans:?}");
|
||||
assert!(spans.last().unwrap().width() > 4.0 * spans[0].width(), "{spans:?}");
|
||||
// The stroke weight scales it.
|
||||
let out =
|
||||
draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &StrokeLayer { width: 2.0, ..ramp.clone() });
|
||||
assert!(near(half_width(&out, 199.0, 200.0), 12.0, 0.4), "{}", half_width(&out, 199.0, 200.0));
|
||||
// Without recorded pressure, half way between the two scales.
|
||||
let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &stroke(1.0));
|
||||
assert!(near(bounds(&out).height(), 7.0, 1e-6), "{:?}", bounds(&out));
|
||||
// With an even pressure, Add Space with spacing places as many tiles as the one scale that
|
||||
// pressure gives: the spacing counts when the tiles are counted again.
|
||||
let even = pressed(vec![(0.0, 0.5), (1.0, 0.5)]);
|
||||
let spaced = |mode: Option<Variation>, max: Option<f64>| {
|
||||
let mut b = scaled_pattern(PatternFit::AddSpace, false, if max.is_some() { 50.0 } else { 100.0 }, mode, max);
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
p.spacing = 100.0;
|
||||
}
|
||||
piece_spans(&draw(&b, &even)).len()
|
||||
};
|
||||
assert_eq!(spaced(Some(Variation::Pressure), Some(150.0)), spaced(None, None));
|
||||
// With spacing, Stretch to Fit still fills the path and Approximate Path still centers the
|
||||
// tiles, with the gaps between them counted and none after the last.
|
||||
for fit in [PatternFit::Stretch, PatternFit::Approximate] {
|
||||
let mut b = scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
p.spacing = 50.0;
|
||||
}
|
||||
let spans = piece_spans(&draw(&b, &ramp));
|
||||
let (first, last) = (spans[0], spans[spans.len() - 1]);
|
||||
assert!(spans.len() > 1 && near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{fit:?}: {spans:?}");
|
||||
if fit == PatternFit::Stretch {
|
||||
assert!(near(first.x0, 0.0, 1e-6) && near(last.x1, 200.0, 1e-6), "{spans:?}");
|
||||
}
|
||||
}
|
||||
// Add Space to Fit keeps the tiles apart within the path; Approximate Path centers them on it.
|
||||
for fit in [PatternFit::AddSpace, PatternFit::Approximate] {
|
||||
let out = draw(&scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp);
|
||||
let spans = piece_spans(&out);
|
||||
assert!(spans.len() > 1 && spans.windows(2).all(|w| w[1].x0 >= w[0].x1 - 1e-6), "{fit:?}: {spans:?}");
|
||||
assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{fit:?}: {spans:?}");
|
||||
let (first, last) = (spans[0], spans[spans.len() - 1]);
|
||||
if fit == PatternFit::AddSpace {
|
||||
assert!(first.x0 >= -1e-6 && last.x1 <= 200.0 + 1e-6, "{spans:?}");
|
||||
} else {
|
||||
assert!(near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{spans:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Pattern Brush Options: Scale on Tilt, Bearing, Rotation or Stylus Wheel reads only its own
|
||||
/// input, half way without it; Fixed, a mode without a second scale and equal scales draw as a
|
||||
/// brush without the setting does.
|
||||
#[test]
|
||||
fn pattern_brush_scale_follows_tilt_bearing_rotation_and_the_wheel() {
|
||||
let bp = line(0.0, 0.0, 100.0, 0.0);
|
||||
let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st);
|
||||
let brush = |mode: Variation| scaled_pattern(PatternFit::Stretch, false, 50.0, Some(mode), Some(300.0));
|
||||
let wheel = |v: f64| StrokeLayer { wheel: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, v), (1.0, v)] }), ..stroke(1.0) };
|
||||
// 4 pt tiles: 2 pt tall at 50 %, 12 pt at 300 %.
|
||||
for (mode, st, height) in [
|
||||
(Variation::Tilt, posed(Some(0.0), None, None), 12.0),
|
||||
(Variation::Tilt, posed(Some(1.0), None, None), 2.0),
|
||||
(Variation::Bearing, posed(Some(0.5), Some(90.0), None), 9.5),
|
||||
(Variation::Rotation, posed(None, None, Some(-90.0)), 4.5),
|
||||
(Variation::StylusWheel, wheel(1.0), 12.0),
|
||||
(Variation::StylusWheel, wheel(0.0), 2.0),
|
||||
// Without its own input, half way.
|
||||
(Variation::Tilt, posed(None, Some(90.0), Some(90.0)), 7.0),
|
||||
(Variation::Bearing, posed(Some(0.0), None, Some(90.0)), 7.0),
|
||||
(Variation::Rotation, posed(Some(0.0), Some(90.0), None), 7.0),
|
||||
(Variation::StylusWheel, pressed(vec![(0.0, 1.0), (1.0, 1.0)]), 7.0),
|
||||
(Variation::Pressure, posed(Some(0.0), Some(90.0), Some(90.0)), 7.0),
|
||||
] {
|
||||
let h = bounds(&draw(&brush(mode), &st)).height();
|
||||
assert!(near(h, height, 1e-6), "{mode:?}: {h}");
|
||||
}
|
||||
// Fixed, a mode without a second scale, and a second scale equal to the first draw what the
|
||||
// brush draws without them.
|
||||
let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]);
|
||||
let plain = draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &ramp);
|
||||
for (mode, max) in [(None, Some(300.0)), (Some(Variation::Pressure), None), (Some(Variation::Pressure), Some(50.0))] {
|
||||
assert_eq!(draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, mode, max), &ramp), plain, "{mode:?} {max:?}");
|
||||
}
|
||||
let saved = serde_json::to_value(scaled_pattern(PatternFit::Stretch, false, 50.0, None, None)).unwrap();
|
||||
assert!(saved.get("scale_mode").is_none() && saved.get("scale_max").is_none(), "{saved}");
|
||||
// A mode the scale does not take is read as Fixed, and the second scale is kept within range.
|
||||
let lib = parse_library(&serde_json::json!([
|
||||
{"name": "a", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "random", "scale_max": 1e308},
|
||||
{"name": "b", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "stylusWheel", "scale_max": 0.0},
|
||||
]));
|
||||
let [BrushKind::Pattern(a), BrushKind::Pattern(b)] = [&lib[0].kind, &lib[1].kind] else { panic!("{lib:?}") };
|
||||
assert_eq!((a.scale_mode, a.scale_max, b.scale_mode, b.scale_max), (None, Some(10000.0), Some(Variation::StylusWheel), Some(1.0)));
|
||||
// A stroke sets its own mode and second scale.
|
||||
let mut own = serde_json::Map::new();
|
||||
own.insert("scale_mode".into(), serde_json::json!("pressure"));
|
||||
own.insert("scale_max".into(), serde_json::json!(300.0));
|
||||
let edited = scaled_pattern(PatternFit::Stretch, false, 100.0, None, None).with_stroke_options(&own).unwrap();
|
||||
assert!(matches!(&edited.kind, BrushKind::Pattern(p) if p.scale_range() == (100.0, 300.0)), "{edited:?}");
|
||||
}
|
||||
|
||||
/// A pattern brush whose scale follows the pen keeps its start, end and corner tiles at the scale
|
||||
/// where they are, on open and closed paths, and stays finite at the ends of the scale's range.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_places_start_end_and_corner_tiles() {
|
||||
let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]);
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
// Start and end tiles, 6 × 4 pt: the start tile at the light end is smaller than the end tile.
|
||||
let mut ends = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
if let BrushKind::Pattern(p) = &mut ends.kind {
|
||||
(p.start, p.end) = (Some(rect_art(6.0, 4.0)), Some(rect_art(6.0, 4.0)));
|
||||
}
|
||||
let out = stroke_pieces(&doc, &ends, &line(0.0, 0.0, 200.0, 0.0), &ramp);
|
||||
let (start, end) = (out[0].geometric_bounds().unwrap(), out[1].geometric_bounds().unwrap());
|
||||
assert!(near(start.x0, 0.0, 1e-6) && near(end.x1, 200.0, 1e-6), "{start:?} {end:?}");
|
||||
assert!(start.width() < 3.5 && end.width() > 17.0 && start.height() < end.height() / 4.0, "{start:?} {end:?}");
|
||||
// A closed rectangle with corner tiles, on each Fit, and the scale's range at its ends.
|
||||
let mut rect = BezPath::new();
|
||||
rect.move_to((0.0, 0.0));
|
||||
rect.line_to((100.0, 0.0));
|
||||
rect.line_to((100.0, 60.0));
|
||||
rect.line_to((0.0, 60.0));
|
||||
rect.close_path();
|
||||
for fit in [PatternFit::Stretch, PatternFit::AddSpace, PatternFit::Approximate] {
|
||||
for (scale, max) in [(50.0, 300.0), (1.0, 10000.0), (10000.0, 1.0)] {
|
||||
for bp in [&rect, &line(0.0, 0.0, 3.0, 0.0)] {
|
||||
let b = scaled_pattern(fit, true, scale, Some(Variation::Pressure), Some(max));
|
||||
let out = stroke_pieces(&doc, &b, bp, &ramp);
|
||||
assert!(!out.is_empty(), "{fit:?} {scale} {max}");
|
||||
let r = bounds(&out);
|
||||
assert!([r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()), "{fit:?} {scale} {max}: {r:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// On the rectangle the corner tiles grow with the pressure: the first corner's tile is smaller
|
||||
// than the last one's.
|
||||
let b = scaled_pattern(PatternFit::Stretch, true, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
let out = stroke_pieces(&doc, &b, &rect, &ramp);
|
||||
let fixed = stroke_pieces(&doc, &scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &rect, &ramp);
|
||||
assert_ne!(out, fixed);
|
||||
let corner = |n: &Node| n.geometric_bounds().map_or(0.0, |r| r.width().max(r.height()));
|
||||
let corners: Vec<f64> = out.iter().take(4).map(corner).collect();
|
||||
assert!(corners[0] < corners[3], "{corners:?}");
|
||||
// The side tiles start half the corner tile beside them away from the corner: 1.5 pt from the
|
||||
// first corner, where the 6 pt corner tile is drawn at 50 %, not half the largest corner tile.
|
||||
let first_side = out.get(4).and_then(Node::geometric_bounds);
|
||||
assert!(first_side.is_some_and(|r| near(r.x0, 1.5, 1e-3)), "{first_side:?}");
|
||||
}
|
||||
|
||||
/// A start or end tile whose scale follows the pen is placed where it is as long as the scale at
|
||||
/// its middle, even when the scale rises again further along and the tile would not fit at the
|
||||
/// whole run's length.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_fits_start_and_end_tiles_where_the_scale_falls_back() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let bp = line(0.0, 0.0, 100.0, 0.0);
|
||||
// From 100 % to 10000 %: 300 % from 5 to 20 pt, 10000 % from 50 pt on; mirrored for the end.
|
||||
let q = 2.0 / 99.0;
|
||||
for (start, points, span) in [
|
||||
(true, vec![(0.0, 0.0), (0.05, q), (0.2, q), (0.5, 1.0), (1.0, 1.0)], (0.0, 18.0)),
|
||||
(false, vec![(0.0, 1.0), (0.5, 1.0), (0.8, q), (0.95, q), (1.0, 0.0)], (82.0, 100.0)),
|
||||
] {
|
||||
let mut b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(10000.0));
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
let tile = Some(rect_art(6.0, 4.0));
|
||||
(p.start, p.end) = if start { (tile, None) } else { (None, tile) };
|
||||
}
|
||||
// The 6 pt tile at 300 %: 18 pt long, its middle where the scale is 300 %.
|
||||
let out = stroke_pieces(&doc, &b, &bp, &pressed(points));
|
||||
let r = out.first().and_then(Node::geometric_bounds);
|
||||
assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}");
|
||||
}
|
||||
// 400 % at the start, 100 % from 15 to 20 pt, 400 % from 40 pt on, mirrored for the end: a 30 pt
|
||||
// tile at 100 % fits at its middle, although at the scale at its first length's middle it is as
|
||||
// long as that length.
|
||||
for (start, points, span) in [
|
||||
(true, vec![(0.0, 1.0), (0.15, 0.0), (0.2, 0.0), (0.4, 1.0), (1.0, 1.0)], (0.0, 30.0)),
|
||||
(false, vec![(0.0, 1.0), (0.6, 1.0), (0.8, 0.0), (0.85, 0.0), (1.0, 1.0)], (70.0, 100.0)),
|
||||
] {
|
||||
let mut b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(400.0));
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
let tile = Some(rect_art(30.0, 4.0));
|
||||
(p.start, p.end) = if start { (tile, None) } else { (None, tile) };
|
||||
}
|
||||
let out = stroke_pieces(&doc, &b, &bp, &pressed(points));
|
||||
let r = out.first().and_then(Node::geometric_bounds);
|
||||
assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// How far from y = 0 the outlines under `nodes` reach where they cross the vertical line at `x`.
|
||||
fn reach_at(nodes: &[Node], x: f64) -> f64 {
|
||||
let mut reach = 0.0f64;
|
||||
for n in nodes {
|
||||
n.walk(&mut |c| {
|
||||
for sp in c.path_data().into_iter().flat_map(|p| &p.subpaths) {
|
||||
for i in 0..sp.segment_count() {
|
||||
let s = sp.segment(i);
|
||||
let (a, b, c, d) = (s.p0.x, s.p1.x, s.p2.x, s.p3.x);
|
||||
let roots = kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (c - 2.0 * b + a), d - 3.0 * c + 3.0 * b - a);
|
||||
for t in roots.into_iter().filter(|t| (-1e-9..=1.0 + 1e-9).contains(t)) {
|
||||
reach = reach.max(kurbo::ParamCurve::eval(&s, t.clamp(0.0, 1.0)).y.abs());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
reach
|
||||
}
|
||||
|
||||
/// A pattern tile whose scale follows the pen is as tall as the scale at a short peak of the
|
||||
/// pressure, even where the peak falls between the positions the bent outline is checked at.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_keeps_a_short_peak() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(300.0));
|
||||
// One 10 × 4 pt tile on a 10 pt path: 100 % (2 pt either side) but for a peak at 2.2 pt, where
|
||||
// the scale reaches 300 % (6 pt either side).
|
||||
let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]);
|
||||
let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 10.0, 0.0), &peak);
|
||||
// At the peak 300 %, half way up it 200 %, and 100 % on either side of it.
|
||||
for (x, want) in [(2.2, 6.0), (2.15, 4.0), (2.25, 4.0), (1.0, 2.0), (2.05, 2.0), (2.4, 2.0), (8.0, 2.0)] {
|
||||
assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x));
|
||||
}
|
||||
}
|
||||
|
||||
/// An art brush whose width follows the pen is as wide as the pen gives at a short peak of the
|
||||
/// pressure, even where the peak falls between the positions the bent outline is checked at.
|
||||
#[test]
|
||||
fn art_brush_width_from_the_pen_keeps_a_short_peak() {
|
||||
let mut b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut b.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (100.0, Some(Variation::Pressure), Some(300.0));
|
||||
}
|
||||
// 4 pt art on a 100 pt path: 2 pt either side but for a peak at 22 pt, where it is 6 pt.
|
||||
let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]);
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 100.0, 0.0), &peak);
|
||||
for (x, want) in [(22.0, 6.0), (21.5, 4.0), (22.5, 4.0), (10.0, 2.0), (20.5, 2.0), (24.0, 2.0), (80.0, 2.0)] {
|
||||
assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x));
|
||||
}
|
||||
}
|
||||
|
||||
/// A pen recording sampled many times along a straight ramp draws as many anchors as the ramp's
|
||||
/// two ends do: samples that leave the scale on the same straight course are not split at.
|
||||
#[test]
|
||||
fn pen_samples_on_a_straight_ramp_add_no_anchors() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let bp = line(0.0, 0.0, 1000.0, 0.0);
|
||||
let ramp = |n: usize| pressed((0..=n).map(|i| (i as f64 / n as f64, i as f64 / n as f64)).collect());
|
||||
let anchors = |out: &[Node]| {
|
||||
let mut count = 0;
|
||||
for n in out {
|
||||
n.walk(&mut |c| count += c.path_data().map_or(0, |p| p.subpaths.iter().map(|s| s.anchors.len()).sum::<usize>()));
|
||||
}
|
||||
count
|
||||
};
|
||||
let pattern = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
let mut art = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
|
||||
if let BrushKind::Art(a) = &mut art.kind {
|
||||
(a.width, a.width_mode, a.width_max) = (50.0, Some(Variation::Pressure), Some(300.0));
|
||||
}
|
||||
for b in [&pattern, &art] {
|
||||
let (few, many) = (stroke_pieces(&doc, b, &bp, &ramp(1)), stroke_pieces(&doc, b, &bp, &ramp(2000)));
|
||||
assert_eq!(anchors(&many), anchors(&few), "{}", b.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// On a closed path, a tile that Approximate Path starts before the path's start takes the scale
|
||||
/// recorded at the end of the stroke there, where the tile is drawn.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_wraps_before_a_closed_paths_start() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let b = scaled_pattern(PatternFit::Approximate, false, 50.0, Some(Variation::Pressure), Some(300.0));
|
||||
// Light over the first 90 % of the stroke, heavy at its end.
|
||||
let st = pressed(vec![(0.0, 0.0), (0.9, 0.0), (1.0, 1.0)]);
|
||||
let mut before = 0;
|
||||
for r in (100..=120).map(f64::from) {
|
||||
// A circle of radius `r` as 720 sides, from (r, 0) on towards +y.
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((r, 0.0));
|
||||
for i in 1..720 {
|
||||
let a = std::f64::consts::TAU * f64::from(i) / 720.0;
|
||||
bp.line_to((r * a.cos(), r * a.sin()));
|
||||
}
|
||||
bp.close_path();
|
||||
let out = stroke_pieces(&doc, &b, &bp, &st);
|
||||
let Some(first) = out.first().and_then(Node::geometric_bounds) else { panic!("{r}: no tiles") };
|
||||
if first.y0 < -0.5 {
|
||||
// The 4 pt tall tile is 2 pt tall at the light 50 % and nearly 12 pt at the heavy end.
|
||||
before += 1;
|
||||
assert!(first.x1 > r + 3.0, "{r}: {first:?}");
|
||||
}
|
||||
}
|
||||
assert!(before > 0, "no first tile starts before the path's start");
|
||||
}
|
||||
|
||||
/// On a closed path, a tile over the path's start follows the scale on both sides of the start,
|
||||
/// even when the scale is the same at the tile's ends, its middle and every pen sample within it.
|
||||
#[test]
|
||||
fn pattern_brush_scale_from_the_pen_changes_where_a_closed_path_wraps_round() {
|
||||
let doc = Document::new(1.0, 1.0);
|
||||
let mut b = scaled_pattern(PatternFit::Approximate, false, 100.0, Some(Variation::Pressure), Some(300.0));
|
||||
if let BrushKind::Pattern(p) = &mut b.kind {
|
||||
p.side = rect_art(54.0, 4.0);
|
||||
}
|
||||
// A closed path 256 pt long without corners, from (0, 0) along +x: its sides in each quarter
|
||||
// turn, and the same turned three more times.
|
||||
let quarter = [(28.0, 0.0), (12.0, 5.0), (4.0, 3.0), (3.0, 4.0), (5.0, 12.0)];
|
||||
let mut bp = BezPath::new();
|
||||
let mut at = (0.0, 0.0);
|
||||
bp.move_to(at);
|
||||
for turn in 0..4 {
|
||||
for &(x, y) in &quarter {
|
||||
let (dx, dy) = match turn {
|
||||
0 => (x, y),
|
||||
1 => (-y, x),
|
||||
2 => (-x, -y),
|
||||
_ => (y, -x),
|
||||
};
|
||||
at = (at.0 + dx, at.1 + dy);
|
||||
if at != (0.0, 0.0) {
|
||||
bp.line_to(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
bp.close_path();
|
||||
// 100 % up to 4 pt before the end, rising to 300 % at the end. Approximate Path places five
|
||||
// 54 pt tiles, the first from 7 pt before the start: at 100 % at both its ends, its middle and
|
||||
// the samples at 4 pt before the start and at the start, but larger from 4 pt before it.
|
||||
let st = pressed(vec![(0.0, 0.0), (252.0 / 256.0, 0.0), (1.0, 1.0)]);
|
||||
let out = stroke_pieces(&doc, &b, &bp, &st);
|
||||
let Some(first) = out.first().and_then(Node::geometric_bounds) else { panic!("no tiles") };
|
||||
// The 4 pt tall tile is 2 pt either side of the path at 100 %, and 5 pt at 1 pt before the
|
||||
// start, where the scale is 250 %.
|
||||
assert!(first.y0 < -3.5, "{first:?}");
|
||||
}
|
||||
|
||||
/// Definitions from files and commands are kept within their ranges.
|
||||
#[test]
|
||||
fn sanitize_keeps_values_within_their_ranges() {
|
||||
|
||||
@@ -40,23 +40,32 @@ const MASK_STEPS: usize = 32;
|
||||
/// through the bend to within [`fit_tol`] of `doc_tol`, the flattening tolerance in document
|
||||
/// space, so the art keeps its curves (#3926). Where that cannot be done in no more anchors than
|
||||
/// chords would take, the path is flattened with `flat_tol` (art space) and subdivided so no chord
|
||||
/// is longer than `max_du` along x, as it always was. Stroke widths scale by `width_scale`.
|
||||
/// Text, images and symbol instances can't bend and are dropped. The art of a linked opacity mask
|
||||
/// bends with the object it masks.
|
||||
pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, doc_tol: f64, width_scale: f64) -> Option<Node> {
|
||||
/// is longer than `max_du` along x, as it always was. Both routes also split the art where it
|
||||
/// crosses each of `breaks` (art x, in order), so a turn of the map there is not stepped over.
|
||||
/// Stroke widths scale by `width_scale`. Text, images and symbol instances can't bend and are
|
||||
/// dropped. The art of a linked opacity mask bends with the object it masks.
|
||||
pub(crate) fn warp_node(
|
||||
n: &Node,
|
||||
f: &dyn Fn(Point) -> Point,
|
||||
flat_tol: f64,
|
||||
max_du: f64,
|
||||
doc_tol: f64,
|
||||
width_scale: f64,
|
||||
breaks: &[f64],
|
||||
) -> Option<Node> {
|
||||
let mut out = n.clone();
|
||||
out.appearance.scale_strokes(width_scale);
|
||||
match &mut out.kind {
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
*live = None;
|
||||
*path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol));
|
||||
*path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol), breaks);
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } => {
|
||||
let kids: Vec<Arc<Node>> =
|
||||
children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale)).map(Arc::new).collect();
|
||||
children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale, breaks)).map(Arc::new).collect();
|
||||
if kids.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -64,7 +73,7 @@ pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale));
|
||||
map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale, breaks));
|
||||
Some(out)
|
||||
}
|
||||
|
||||
@@ -80,12 +89,13 @@ fn map_mask(n: &mut Node, map: impl FnOnce(&Node) -> Option<Node>) {
|
||||
}
|
||||
|
||||
/// Each subpath of `p` through `f`: fitted cubics when they take no more anchors than the chords
|
||||
/// would, else the chords. Points `f` cannot place (not finite) are left out of the chords.
|
||||
fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64) -> PathData {
|
||||
/// would, else the chords, both split at `breaks` ([`warp_node`]). Points `f` cannot place (not
|
||||
/// finite) are left out of the chords.
|
||||
fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64, breaks: &[f64]) -> PathData {
|
||||
let mut subs = vec![];
|
||||
for sp in &p.subpaths {
|
||||
let Some(dense) = densified(sp, flat_tol, max_du) else { continue };
|
||||
if let Some(fit) = fitted(sp, f, fit_tol, dense.len()) {
|
||||
let Some(dense) = densified(sp, flat_tol, max_du, breaks) else { continue };
|
||||
if let Some(fit) = fitted(sp, f, fit_tol, dense.len(), breaks) {
|
||||
subs.push(fit);
|
||||
continue;
|
||||
}
|
||||
@@ -98,8 +108,9 @@ fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f6
|
||||
}
|
||||
|
||||
/// `sp` flattened with `flat_tol` and its chords subdivided so none is longer than `max_du` along
|
||||
/// x, in art space: the points the chord route maps. `None` below two points.
|
||||
fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
|
||||
/// x, in art space, with a point where a chord crosses each of `breaks` (art x, in order): the
|
||||
/// points the chord route maps. `None` below two points.
|
||||
fn densified(sp: &SubPath, flat_tol: f64, max_du: f64, breaks: &[f64]) -> Option<Vec<Point>> {
|
||||
let mut bp = BezPath::new();
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
let mut pts = vec![];
|
||||
@@ -118,16 +129,57 @@ fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option<Vec<Point>> {
|
||||
let mut dense = vec![*pts.first()?];
|
||||
for (i, (&a, &b)) in pts.iter().zip(pts.iter().cycle().skip(1)).take(segs).enumerate() {
|
||||
let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB);
|
||||
// The breaks the chord crosses, as parameters along it in order, go in among the even ones.
|
||||
let mut cuts: Vec<f64> = crossed(breaks, a.x, b.x).iter().map(|&x| (x - a.x) / (b.x - a.x)).collect();
|
||||
cuts.sort_by(f64::total_cmp);
|
||||
let mut cuts = cuts.into_iter().peekable();
|
||||
for j in 1..=k {
|
||||
let even = j as f64 / k as f64;
|
||||
while let Some(t) = cuts.next_if(|&t| t < even) {
|
||||
dense.push(a.lerp(b, t));
|
||||
}
|
||||
if sp.closed && i == segs - 1 && j == k {
|
||||
break;
|
||||
}
|
||||
dense.push(a.lerp(b, j as f64 / k as f64));
|
||||
dense.push(a.lerp(b, even));
|
||||
}
|
||||
}
|
||||
Some(dense)
|
||||
}
|
||||
|
||||
/// The values of `breaks` (in order) strictly between `a` and `b`, either way round.
|
||||
fn crossed(breaks: &[f64], a: f64, b: f64) -> &[f64] {
|
||||
let (lo, hi) = (a.min(b), a.max(b));
|
||||
let from = breaks.partition_point(|&x| x <= lo);
|
||||
let to = from + breaks[from..].partition_point(|&x| x < hi);
|
||||
&breaks[from..to]
|
||||
}
|
||||
|
||||
/// The parameters of `c` (in order, strictly between its ends) where its x is one of `breaks`;
|
||||
/// `line` when `c` is a line with its handles at thirds, whose x runs evenly.
|
||||
fn crossings(c: &CubicBez, line: bool, breaks: &[f64]) -> Vec<f64> {
|
||||
let xs = [c.p0.x, c.p1.x, c.p2.x, c.p3.x];
|
||||
let (lo, hi) = xs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &x| (lo.min(x), hi.max(x)));
|
||||
let inside = crossed(breaks, lo, hi);
|
||||
if inside.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let [a, b, cc, d] = xs;
|
||||
let mut ts: Vec<f64> = vec![];
|
||||
for &x in inside {
|
||||
if line {
|
||||
ts.push((x - a) / (d - a));
|
||||
} else {
|
||||
ts.extend(kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (cc - 2.0 * b + a), d - 3.0 * cc + 3.0 * b - a));
|
||||
}
|
||||
}
|
||||
// Pieces are no shorter than the step the fit reads their ends' directions over.
|
||||
ts.retain(|t| t.is_finite() && *t > FIT_DT && *t < 1.0 - FIT_DT);
|
||||
ts.sort_by(f64::total_cmp);
|
||||
ts.dedup_by(|t, prev| *t - *prev <= FIT_DT);
|
||||
ts
|
||||
}
|
||||
|
||||
/// Times an art segment is halved at most while looking for cubics that fit it.
|
||||
const FIT_DEPTH: u32 = 12;
|
||||
/// Parameter step of the finite differences that stand in for the bend's derivative.
|
||||
@@ -156,7 +208,10 @@ fn fit_tol(doc_tol: f64) -> f64 {
|
||||
/// bend at the same parameters, so the distance measured is never less than the true one. The
|
||||
/// halving is our own rather than kurbo's `fit_to_bezpath`, which halves until the floats run out
|
||||
/// on a map that never fits; the depth and the anchor count bound this one.
|
||||
fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Option<SubPath> {
|
||||
///
|
||||
/// A segment is first split where its x crosses one of `breaks` (art x, in order), so a turn of
|
||||
/// the map there lands on an anchor rather than between the checked positions.
|
||||
fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize, breaks: &[f64]) -> Option<SubPath> {
|
||||
if !(tol.is_finite() && tol > 0.0) {
|
||||
return None;
|
||||
}
|
||||
@@ -174,7 +229,11 @@ fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Op
|
||||
// A line's handles sit on its ends, which stalls its parameter there; thirds keep it even.
|
||||
let c = if line { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c };
|
||||
let at = |t: f64| Some(f(c.eval(t))).filter(|q| q.is_finite());
|
||||
fit_into(&at, (0.0, 1.0), line, tol, FIT_DEPTH, &mut bp, &mut room)?;
|
||||
let mut t0 = 0.0;
|
||||
for t1 in crossings(&c, line, breaks).into_iter().chain([1.0]) {
|
||||
fit_into(&at, (t0, t1), line, tol, FIT_DEPTH, &mut bp, &mut room)?;
|
||||
t0 = t1;
|
||||
}
|
||||
}
|
||||
if sp.closed {
|
||||
bp.close_path();
|
||||
@@ -316,6 +375,16 @@ impl AlongMap {
|
||||
fn max_scale(&self) -> f64 {
|
||||
(0..3).map(|i| self.slope(i).abs()).fold(1e-6, f64::max)
|
||||
}
|
||||
|
||||
/// The art x (offset from the art's left edge) that [`AlongMap::at`] takes to arc length `s`,
|
||||
/// when a piece with width spans it.
|
||||
fn x_at(&self, s: f64) -> Option<f64> {
|
||||
(0..3).find_map(|i| {
|
||||
let ((x0, x1), (s0, s1)) = ((self.xs[i], self.xs[i + 1]), (self.ss[i], self.ss[i + 1]));
|
||||
let spans = x1 - x0 > 1e-12 && (s1 - s0).abs() > 1e-12 && s0.min(s1) <= s && s <= s0.max(s1);
|
||||
spans.then(|| x0 + (s - s0) / (s1 - s0) * (x1 - x0))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The affine that reproduces `f` over `b` to within `tol`, if one does.
|
||||
@@ -414,12 +483,14 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option<N
|
||||
{
|
||||
return affine_node(art, a, cross.abs());
|
||||
}
|
||||
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs())
|
||||
warp_node(art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs(), &[])
|
||||
}
|
||||
|
||||
/// [`bend`], with the cross scale at arc length `s` multiplied by `widen(s)` (0..=1). The strokes
|
||||
/// of each object in the art take the factor at the middle of the object.
|
||||
fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64) -> Option<Node> {
|
||||
/// of each object in the art take the factor at the middle of the object. `marks` are the arc
|
||||
/// lengths (in order) of the recorded pen samples `widen` runs in a straight line between; the art
|
||||
/// is split where `widen` turns at one by more than the bent outline's tolerance ([`pen_breaks`]).
|
||||
fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64, marks: &[f64]) -> Option<Node> {
|
||||
let cy = b.center().y;
|
||||
let x0 = b.x0;
|
||||
let f = move |p: Point| {
|
||||
@@ -430,7 +501,45 @@ fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, wid
|
||||
let art = widen_strokes(art, &factor);
|
||||
let scale = along.max_scale().max(cross.abs()).max(1e-6);
|
||||
let flat_tol = tolerance(b.height().max(b.width()) * scale) / scale;
|
||||
warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs())
|
||||
// A change of `dw` in `widen` moves the art's top and bottom edges `dw × reach` across.
|
||||
let reach = b.height() / 2.0 * cross.abs();
|
||||
let mut breaks: Vec<f64> =
|
||||
pen_breaks(marks, along.span(), widen, fit_tol(flat_tol * scale) / reach).into_iter().filter_map(|s| along.x_at(s)).map(|x| x + x0).collect();
|
||||
breaks.sort_by(f64::total_cmp);
|
||||
breaks.dedup();
|
||||
warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs(), &breaks)
|
||||
}
|
||||
|
||||
/// The arc lengths among `marks` (in order) strictly within `(s0, s1)` at which the art is split:
|
||||
/// those where `widen` is more than `tol` from the straight line between the ones kept on either
|
||||
/// side (the span's ends to begin with), chosen by splitting at the farthest one until every
|
||||
/// sample left out is within `tol` of that line. `widen` runs straight between samples, so it
|
||||
/// is then within `tol` of the line between kept samples all along, and samples on a straight
|
||||
/// course add no splits.
|
||||
fn pen_breaks(marks: &[f64], (s0, s1): (f64, f64), widen: &dyn Fn(f64) -> f64, tol: f64) -> Vec<f64> {
|
||||
if !(s1 > s0 && tol > 0.0) {
|
||||
return vec![];
|
||||
}
|
||||
let inside = {
|
||||
let from = marks.partition_point(|&s| s <= s0);
|
||||
&marks[from..from + marks[from..].partition_point(|&s| s < s1)]
|
||||
};
|
||||
if inside.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let pts: Vec<(f64, f64)> = std::iter::once(s0).chain(inside.iter().copied()).chain([s1]).map(|s| (s, widen(s))).collect();
|
||||
let mut keep = vec![false; pts.len()];
|
||||
let mut spans = vec![(0, pts.len() - 1)];
|
||||
while let Some((i, j)) = spans.pop() {
|
||||
let ((sa, wa), (sb, wb)) = (pts[i], pts[j]);
|
||||
let off = |&(s, w): &(f64, f64)| (w - if sb > sa { wa + (wb - wa) * (s - sa) / (sb - sa) } else { wa }).abs();
|
||||
let far = (i + 1..j).map(|k| (k, off(&pts[k]))).filter(|&(_, d)| d > tol).max_by(|a, b| a.1.total_cmp(&b.1));
|
||||
if let Some((k, _)) = far {
|
||||
keep[k] = true;
|
||||
spans.extend([(i, k), (k, j)]);
|
||||
}
|
||||
}
|
||||
pts.iter().zip(keep).filter(|&(_, k)| k).map(|(p, _)| p.0).collect()
|
||||
}
|
||||
|
||||
/// `n` with the strokes of it and of everything inside it scaled by `factor` of the object they
|
||||
@@ -465,8 +574,17 @@ fn art_runs(t: &Track) -> Vec<(f64, f64)> {
|
||||
bounds.windows(2).map(|w| (w[0], w[1])).collect()
|
||||
}
|
||||
|
||||
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1.
|
||||
fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, Rect), cross: f64, widen: &dyn Fn(f64) -> f64) -> Option<Node> {
|
||||
/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1 (`marks`
|
||||
/// as [`bend_widened`] takes them).
|
||||
fn art_on_run(
|
||||
t: &Track,
|
||||
(s0, s1): (f64, f64),
|
||||
a: &ArtBrush,
|
||||
(art, b): (&Node, Rect),
|
||||
cross: f64,
|
||||
widen: &dyn Fn(f64) -> f64,
|
||||
marks: &[f64],
|
||||
) -> Option<Node> {
|
||||
let l = s1 - s0;
|
||||
if l <= 1e-9 {
|
||||
return None;
|
||||
@@ -489,7 +607,7 @@ fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, R
|
||||
}
|
||||
}
|
||||
};
|
||||
bend_widened(t, art, b, along, cross, widen)
|
||||
bend_widened(t, art, b, along, cross, widen, marks)
|
||||
}
|
||||
|
||||
/// An art brush's art along `bp`. With a width that follows the pen (its pressure, tilt, bearing
|
||||
@@ -515,9 +633,13 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer)
|
||||
let p = a.width_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5);
|
||||
(light + (heavy - light) * p) / width
|
||||
};
|
||||
let marks = match a.width_mode {
|
||||
Some(m) if light != heavy && width > 0.0 => pen_marks(stroke, m, l),
|
||||
_ => vec![],
|
||||
};
|
||||
let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] };
|
||||
for run in runs {
|
||||
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen) {
|
||||
if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen, &marks) {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
@@ -540,7 +662,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();
|
||||
@@ -646,6 +771,253 @@ fn tile_on(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, cross: f64) -> Opti
|
||||
bend(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), cross)
|
||||
}
|
||||
|
||||
/// A tile placed on [s0, s1] of the track, `k(s)` across at arc length `s` when the scale varies
|
||||
/// (`marks`: the arc lengths of the recorded pen samples in order, between which the scale runs
|
||||
/// in a straight line), else `k` at the middle of the span across all of it ([`tile_on`]), as it
|
||||
/// is too when the scale is the same at both ends of the span, at every sample within it and, at
|
||||
/// a closed track's start within it, on both sides of the start.
|
||||
fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64) -> f64, marks: Option<&[f64]>) -> Option<Node> {
|
||||
let mid = k((s0 + s1) / 2.0);
|
||||
// Only the samples within the span are looked at.
|
||||
let within = |marks: &[f64]| {
|
||||
let from = marks.partition_point(|&s| s <= s0);
|
||||
let to = from + marks[from..].partition_point(|&s| s < s1);
|
||||
marks[from..to].iter().all(|&s| k(s) == mid)
|
||||
};
|
||||
// A closed track's scale goes from the one at its end to the one at its start where it wraps
|
||||
// round, so a span over its start (or a track's length before or after it) takes both.
|
||||
let l = t.len();
|
||||
let seam = t.closed && l > 0.0 && (s0 / l).ceil() <= (s1 / l).floor();
|
||||
let ends = || !seam || (k(0.0) == mid && k(l) == mid);
|
||||
let even = |marks: &[f64]| k(s0) == mid && k(s1) == mid && within(marks) && ends();
|
||||
if mid <= 0.0 || marks.is_none_or(even) {
|
||||
return tile_on(t, tile, s0, s1, mid);
|
||||
}
|
||||
bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid, marks.unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The most side tiles a run of a pattern brush places.
|
||||
const MAX_TILES: usize = 20000;
|
||||
|
||||
/// How many times a pattern brush whose scale varies measures its side tiles again where the fit
|
||||
/// puts them.
|
||||
const REFITS: usize = 3;
|
||||
|
||||
/// How many times a pattern brush whose scale varies halves the range a start or end tile's
|
||||
/// length lies in.
|
||||
const END_SOLVE_STEPS: usize = 48;
|
||||
|
||||
/// How many evenly spaced lengths a pattern brush whose scale varies tries for a start or end
|
||||
/// tile before it halves the range the tile's length lies in.
|
||||
const END_SCAN_STEPS: usize = 64;
|
||||
|
||||
/// The side tiles of a pattern brush on a run `avail` long from `a` when the scale varies along
|
||||
/// it: each tile's length and the gap after it, as `natural` gives them at the tile's start, and
|
||||
/// how many tiles fit whole and what fraction of the next one fits after them. The tiles include
|
||||
/// that next one when there is room for part of it.
|
||||
fn varied_tiles(a: f64, avail: f64, natural: &dyn Fn(f64) -> (f64, f64)) -> (Vec<(f64, f64)>, f64) {
|
||||
let mut tiles = vec![];
|
||||
let mut pos = 0.0;
|
||||
while tiles.len() < MAX_TILES {
|
||||
let (w, g) = natural(a + pos);
|
||||
if !(w > 1e-9 && w.is_finite() && g.is_finite() && g >= 0.0) {
|
||||
break;
|
||||
}
|
||||
tiles.push((w, g));
|
||||
if pos + w > avail {
|
||||
let whole = (tiles.len() - 1) as f64;
|
||||
return (tiles, whole + ((avail - pos + g) / (w + g)).clamp(0.0, 1.0));
|
||||
}
|
||||
pos += w + g;
|
||||
}
|
||||
let whole = tiles.len() as f64;
|
||||
(tiles, whole)
|
||||
}
|
||||
|
||||
/// The size factor of a pattern brush's tiles at `weight` where its scale's pen input is `p`
|
||||
/// (0 at the first scale, 1 at the second).
|
||||
fn pattern_scale_at(pb: &PatternBrush, weight: f64, p: f64) -> f64 {
|
||||
let (light, heavy) = pb.scale_range();
|
||||
weight * (light + (heavy - light) * p).max(1.0) / 100.0
|
||||
}
|
||||
|
||||
/// A pattern brush's size factor on `stroke` at `weight`, and whether it varies along the stroke.
|
||||
/// A stroke with no recording of the input the scale follows is drawn at one scale, the one that
|
||||
/// input's missing value gives.
|
||||
fn pattern_scale(pb: &PatternBrush, weight: f64, stroke: &StrokeLayer) -> (f64, bool) {
|
||||
let (light, heavy) = pb.scale_range();
|
||||
match pb.scale_mode {
|
||||
Some(m) if light != heavy && pen_recorded(stroke, m) => (weight * pb.scale.max(1.0) / 100.0, true),
|
||||
Some(m) if light != heavy => (pattern_scale_at(pb, weight, PenAt::of(stroke, 0.0).control(m).unwrap_or(0.5)), false),
|
||||
_ => (weight * pb.scale.max(1.0) / 100.0, false),
|
||||
}
|
||||
}
|
||||
|
||||
/// The length of a start or end tile `width` wide at its art's size, at the scale `k_mid(w)` at
|
||||
/// the middle of the tile when it is `w` long: the shortest length that is as long as the scale at
|
||||
/// its own middle. The scale can rise and fall along the stroke, so the lengths up to `room` are
|
||||
/// tried in order (evenly spaced ones, and `breaks`, the lengths whose middle falls on a recorded
|
||||
/// pen sample), and the range between the last one the tile is too long for and the first one it
|
||||
/// fits is halved. A tile that fits at no length up to `room` gets the length it needs at `room`,
|
||||
/// longer than `room`. `breaks` is `None` when the scale is the same along the whole track, and
|
||||
/// the tile then takes its length at that scale.
|
||||
fn end_tile_length(width: f64, room: f64, k_mid: &dyn Fn(f64) -> f64, breaks: Option<&[f64]>) -> f64 {
|
||||
let length = |w: f64| width * k_mid(w);
|
||||
let first = length(0.0);
|
||||
let Some(breaks) = breaks.filter(|_| !room.is_nan() && room > 0.0) else {
|
||||
return first;
|
||||
};
|
||||
let mut tries: Vec<f64> = (1..=END_SCAN_STEPS).map(|i| room * i as f64 / END_SCAN_STEPS as f64).collect();
|
||||
tries.extend(breaks.iter().copied().filter(|&w| w > 0.0 && w < room));
|
||||
tries.sort_by(f64::total_cmp);
|
||||
let Some(i) = tries.iter().position(|&w| length(w) <= w) else {
|
||||
return length(room);
|
||||
};
|
||||
let (mut short, mut long) = (if i == 0 { 0.0 } else { tries[i - 1] }, tries[i]);
|
||||
for _ in 0..END_SOLVE_STEPS {
|
||||
let mid = (short + long) / 2.0;
|
||||
if length(mid) > mid {
|
||||
short = mid;
|
||||
} else {
|
||||
long = mid;
|
||||
}
|
||||
}
|
||||
long
|
||||
}
|
||||
|
||||
/// Where along a track `l` long `stroke` recorded the pen input `mode` follows: each sample at its
|
||||
/// arc length, and again a track's length before and after it, for tiles of a closed track that
|
||||
/// wrap round, in order.
|
||||
fn pen_marks(stroke: &StrokeLayer, mode: Variation, l: f64) -> Vec<f64> {
|
||||
let points = match mode {
|
||||
Variation::Fixed | Variation::Random => None,
|
||||
Variation::Pressure => stroke.pressure.as_ref().map(|p| &p.points),
|
||||
Variation::Tilt => stroke.tilt.as_ref().map(|p| &p.points),
|
||||
Variation::Bearing => stroke.bearing.as_ref().map(|p| &p.points),
|
||||
Variation::Rotation => stroke.rotation.as_ref().map(|p| &p.points),
|
||||
Variation::StylusWheel => stroke.wheel.as_ref().map(|p| &p.points),
|
||||
};
|
||||
let mut marks: Vec<f64> = points.into_iter().flatten().flat_map(|&(f, _)| [f * l - l, f * l, f * l + l]).collect();
|
||||
marks.sort_by(f64::total_cmp);
|
||||
marks
|
||||
}
|
||||
|
||||
/// Whether `stroke` recorded the pen input `mode` follows.
|
||||
fn pen_recorded(stroke: &StrokeLayer, mode: Variation) -> bool {
|
||||
match mode {
|
||||
Variation::Fixed | Variation::Random => false,
|
||||
Variation::Pressure => stroke.pressure.is_some(),
|
||||
Variation::Tilt => stroke.tilt.is_some(),
|
||||
Variation::Bearing => stroke.bearing.is_some(),
|
||||
Variation::Rotation => stroke.rotation.is_some(),
|
||||
Variation::StylusWheel => stroke.wheel.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Leaves out or adds tiles at the end of `tiles` (each a length and the gap after it) once they
|
||||
/// have been measured again: with `add_space` as many as fit in `avail` with the gaps between
|
||||
/// them, at least one, otherwise the count whose lengths and gaps between them come nearest to
|
||||
/// `avail`. An added tile is
|
||||
/// `natural(s)` long at `s` from the run's start.
|
||||
fn recount(tiles: &mut Vec<(f64, f64)>, avail: f64, add_space: bool, natural: &dyn Fn(f64) -> (f64, f64)) {
|
||||
let mut length: f64 = tiles.iter().map(|t| t.0).sum();
|
||||
let mut gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum());
|
||||
// How much of the run the tiles and the spacing between them take.
|
||||
let run = |length: f64, gaps: f64| length + gaps;
|
||||
while let [.., (_, before), (w, _)] = tiles.as_slice() {
|
||||
let (w, before) = (*w, *before);
|
||||
let (now, without) = (run(length, gaps), run(length - w, gaps - before));
|
||||
let drop = if add_space { now > avail } else { (without - avail).abs() < (now - avail).abs() };
|
||||
if !drop {
|
||||
break;
|
||||
}
|
||||
tiles.pop();
|
||||
length -= w;
|
||||
gaps -= before;
|
||||
}
|
||||
while tiles.len() < MAX_TILES {
|
||||
let last_gap = tiles.last().map_or(0.0, |t| t.1);
|
||||
let now = run(length, gaps);
|
||||
let (w, g) = natural(run(length, gaps + last_gap));
|
||||
if w.is_nan() || w <= 1e-9 {
|
||||
break;
|
||||
}
|
||||
let with = run(length + w, gaps + last_gap);
|
||||
let add = if add_space { with <= avail } else { (with - avail).abs() < (now - avail).abs() };
|
||||
if !add {
|
||||
break;
|
||||
}
|
||||
tiles.push((w, g));
|
||||
length += w;
|
||||
gaps += last_gap;
|
||||
}
|
||||
}
|
||||
|
||||
/// A pattern brush's side tiles on the run `avail` long from `a` of `t` (`marks` as
|
||||
/// [`tile_scaled`] takes them), at the scale `k(s)` at
|
||||
/// arc length `s` ([`varied_tiles`]), fitted as `pb.fit` says: Stretch scales the lengths and gaps
|
||||
/// to fill the run, Add Space keeps the lengths and shares out what is left between the tiles
|
||||
/// (around a lone tile), and Approximate keeps both and centers the tiles on the run.
|
||||
fn varied_side_tiles(
|
||||
out: &mut Budget,
|
||||
t: &Track,
|
||||
pb: &PatternBrush,
|
||||
side: &(Node, Rect),
|
||||
(a, avail): (f64, f64),
|
||||
k: &dyn Fn(f64) -> f64,
|
||||
marks: &[f64],
|
||||
) {
|
||||
let tw = side.1.width();
|
||||
// Each side tile and the gap after it as long as the scale at the tile's middle.
|
||||
let natural = |s: f64| {
|
||||
let w = tw * k(s + tw * k(s) / 2.0);
|
||||
(w, w * pb.spacing.max(0.0) / 100.0)
|
||||
};
|
||||
let (tiles, count) = varied_tiles(a, avail, &natural);
|
||||
let n = match pb.fit {
|
||||
PatternFit::AddSpace => count.floor(),
|
||||
PatternFit::Stretch | PatternFit::Approximate => count.round(),
|
||||
}
|
||||
.max(1.0) as usize;
|
||||
let mut tiles = tiles[..n.min(tiles.len())].to_vec();
|
||||
// How far the fit stretches the tiles and gaps, where the first tile starts, and the space
|
||||
// between tiles when the fit sets it.
|
||||
let fitted = |tiles: &[(f64, f64)]| {
|
||||
let length: f64 = tiles.iter().map(|t| t.0).sum();
|
||||
// The gaps between the tiles: after every tile but the last.
|
||||
let gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum());
|
||||
match pb.fit {
|
||||
PatternFit::Stretch => (avail / (length + gaps), 0.0, None),
|
||||
PatternFit::AddSpace if tiles.len() > 1 => (1.0, 0.0, Some(((avail - length) / (tiles.len() - 1) as f64).max(0.0))),
|
||||
PatternFit::AddSpace => (1.0, (avail - tiles.first().map_or(0.0, |t| t.0)) / 2.0, None),
|
||||
PatternFit::Approximate => (1.0, (avail - length - gaps) / 2.0, None),
|
||||
}
|
||||
};
|
||||
// The fit moves the tiles from where they were measured, so each is measured again at the
|
||||
// middle of where the fit puts it, and the fit worked out again, a few times over.
|
||||
for _ in 0..REFITS {
|
||||
let (stretch, lead, space) = fitted(&tiles);
|
||||
let mut s0 = a + lead;
|
||||
for tile in &mut tiles {
|
||||
let placed = tile.0 * stretch;
|
||||
let w = tw * k(s0 + placed / 2.0);
|
||||
s0 += placed + space.unwrap_or(tile.1 * stretch);
|
||||
*tile = (w, w * pb.spacing.max(0.0) / 100.0);
|
||||
}
|
||||
recount(&mut tiles, avail, pb.fit == PatternFit::AddSpace, &|s| natural(a + s));
|
||||
}
|
||||
let (stretch, lead, space) = fitted(&tiles);
|
||||
let mut s0 = a + lead;
|
||||
for &(w, g) in &tiles {
|
||||
let w = w * stretch;
|
||||
out.take(tile_scaled(t, side, s0, s0 + w, k, Some(marks)));
|
||||
if out.full() {
|
||||
break;
|
||||
}
|
||||
s0 += w + space.unwrap_or(g * stretch);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a pattern brush draws at a corner: corner tile art (oriented, with its bounds), or what
|
||||
/// [`CornerSource`] gives.
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -716,7 +1088,7 @@ fn auto_corner(t: &Track, i: usize, source: CornerSource, side: &(Node, Rect), k
|
||||
}
|
||||
let s = if tw > 1e-9 { len / tw } else { 1.0 };
|
||||
let max_du = MAX_SEG / (2.0 * k * s.max(1.0));
|
||||
let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k);
|
||||
let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k, &[]);
|
||||
// Art point → (distance along from the left edge, stretched to `len`, and offset across).
|
||||
let along = move |q: Point| {
|
||||
let (x, y) = local(q);
|
||||
@@ -800,10 +1172,15 @@ fn masked(n: Node, quad: &[Point], p: Point, towards: Vec2) -> Option<Node> {
|
||||
Some(Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(mask), Arc::new(n)], clip: true }))
|
||||
}
|
||||
|
||||
pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node> {
|
||||
/// A pattern brush's tiles along `bp`. With a scale that follows the pen (its pressure, tilt,
|
||||
/// bearing, rotation or wheel), the tiles are as tall as what `stroke` recorded at each point gives
|
||||
/// (half way without a recording), each tile and the gap after it as long as the scale at its
|
||||
/// middle, and each corner tile at the scale at its corner.
|
||||
pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) -> Vec<Node> {
|
||||
let orient = |n: &Node, frame| oriented_tile(n, frame, pb.flip_along, pb.flip_across);
|
||||
let Some(side) = orient(&pb.side, pb.side_frame) else { return vec![] };
|
||||
let k = weight * pb.scale.max(1.0) / 100.0;
|
||||
let scale_at = |p: f64| pattern_scale_at(pb, weight, p);
|
||||
let (k, varies) = pattern_scale(pb, weight, stroke);
|
||||
let outer = pb.outer_corner.as_ref().and_then(|n| orient(n, pb.outer_corner_frame));
|
||||
let inner = pb.inner_corner.as_ref().and_then(|n| orient(n, pb.inner_corner_frame));
|
||||
let start = pb.start.as_ref().and_then(|n| orient(n, pb.start_frame));
|
||||
@@ -822,6 +1199,17 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
if l <= 1e-9 {
|
||||
continue;
|
||||
}
|
||||
// The scale at arc length `s` of the track; on a closed track a point before its start or
|
||||
// past its end wraps round as `Track::frame` places it (its end itself keeps the scale at
|
||||
// the end), and on an open track a point past either end takes the scale at that end.
|
||||
let ks = |s: f64| {
|
||||
if !varies {
|
||||
return k;
|
||||
}
|
||||
let at = if t.closed && !(0.0..=l).contains(&s) { s.rem_euclid(l) } else { s.clamp(0.0, l) };
|
||||
scale_at(pb.scale_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5))
|
||||
};
|
||||
let marks = pb.scale_mode.filter(|_| varies).map(|m| pen_marks(stroke, m, l));
|
||||
let corners = t.corner_positions();
|
||||
// Corner tiles, centred on the corner and turned to the bisector. The path on each side of
|
||||
// a corner is shortened by `trims` (`None`: half the widest corner tile art).
|
||||
@@ -845,17 +1233,18 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
};
|
||||
before.min(after)
|
||||
};
|
||||
for (ci, &(i, _)) in corners.iter().enumerate() {
|
||||
for (ci, &(i, at)) in corners.iter().enumerate() {
|
||||
if out.full() {
|
||||
break;
|
||||
}
|
||||
let kc = ks(at);
|
||||
let (a, b) = t.in_out(i);
|
||||
// Turning towards the left normal puts the tile's +y side on the inside.
|
||||
let tile = if a.cross(b) > 0.0 { inner_tile.or(outer.as_ref().map(Corner::Art)) } else { outer_tile.or(inner.as_ref().map(Corner::Art)) };
|
||||
let (art, bb) = match tile {
|
||||
Some(Corner::Art(tile)) => tile,
|
||||
Some(Corner::Source(source)) => {
|
||||
let (pieces, trim) = auto_corner(&t, i, source, &side, k, room(ci));
|
||||
let (pieces, trim) = auto_corner(&t, i, source, &side, kc, room(ci));
|
||||
for n in pieces {
|
||||
out.take(Some(n));
|
||||
}
|
||||
@@ -867,8 +1256,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
continue;
|
||||
}
|
||||
};
|
||||
trims.push(None);
|
||||
corner_half = corner_half.max(bb.width() * k / 2.0);
|
||||
// With a scale that varies, each corner's tile is its own size, so the path beside it
|
||||
// is shortened by half of that tile.
|
||||
trims.push(varies.then_some(bb.width() * kc / 2.0));
|
||||
corner_half = corner_half.max(bb.width() * kc / 2.0);
|
||||
// Inner and outer corner art is the corner that joins a side tile on its right to one
|
||||
// below it, so its arms point along +x and +y (as the flips leave them). The tile is
|
||||
// turned so that the line halving its arms lies on the line halving the sides at the
|
||||
@@ -878,7 +1269,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
let arms = Vec2::new(if pb.flip_along { -1.0 } else { 1.0 }, if pb.flip_across { -1.0 } else { 1.0 });
|
||||
let sides = b - a;
|
||||
let angle = sides.y.atan2(sides.x) - arms.y.atan2(arms.x);
|
||||
let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(k) * Affine::translate(-bb.center().to_vec2());
|
||||
let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(kc) * Affine::translate(-bb.center().to_vec2());
|
||||
let mut n = art.clone();
|
||||
n.transform(xf, true);
|
||||
out.take(Some(n));
|
||||
@@ -911,9 +1302,11 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
&& ri == 0
|
||||
&& let Some(st) = &start
|
||||
{
|
||||
let w = st.1.width() * k;
|
||||
// As long as the scale at its middle.
|
||||
let breaks: Option<Vec<f64>> = marks.as_ref().map(|m| m.iter().map(|&m| 2.0 * (m - a)).collect());
|
||||
let w = end_tile_length(st.1.width(), b - a, &|w| ks(a + w / 2.0), breaks.as_deref());
|
||||
if b - a > w {
|
||||
out.take(tile_on(&t, st, a, a + w, k));
|
||||
out.take(tile_scaled(&t, st, a, a + w, &ks, marks.as_deref()));
|
||||
a += w;
|
||||
}
|
||||
}
|
||||
@@ -921,9 +1314,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
&& ri + 1 == nruns
|
||||
&& let Some(en) = &end
|
||||
{
|
||||
let w = en.1.width() * k;
|
||||
let breaks: Option<Vec<f64>> = marks.as_ref().map(|m| m.iter().map(|&m| 2.0 * (b - m)).collect());
|
||||
let w = end_tile_length(en.1.width(), b - a, &|w| ks(b - w / 2.0), breaks.as_deref());
|
||||
if b - a > w {
|
||||
out.take(tile_on(&t, en, b - w, b, k));
|
||||
out.take(tile_scaled(&t, en, b - w, b, &ks, marks.as_deref()));
|
||||
b -= w;
|
||||
}
|
||||
}
|
||||
@@ -931,6 +1325,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec<Node>
|
||||
if avail <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
if let Some(marks) = &marks {
|
||||
varied_side_tiles(&mut out, &t, pb, &side, (a, avail), &ks, marks);
|
||||
continue;
|
||||
}
|
||||
let unit = tw + gap;
|
||||
match pb.fit {
|
||||
PatternFit::Stretch => {
|
||||
@@ -1117,7 +1515,7 @@ mod tests {
|
||||
let f = |p: Point| t.map(along.at(p.x - x0), p.y - cy);
|
||||
let tol = tolerance(b.height().max(b.width()));
|
||||
let exact = traced(art, &f, 1000);
|
||||
let chords: Vec<Point> = densified(art, tol, MAX_SEG).expect("the tile flattens").into_iter().map(f).collect();
|
||||
let chords: Vec<Point> = densified(art, tol, MAX_SEG, &[]).expect("the tile flattens").into_iter().map(f).collect();
|
||||
let curves = traced(sp, &|p| p, 200);
|
||||
let (e_curves, e_chords) = (apart(&curves, &exact), apart(&chords, &exact));
|
||||
// Checked at eight points a piece, so a little room between them.
|
||||
@@ -1129,11 +1527,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 +1557,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"),
|
||||
@@ -1198,7 +1613,7 @@ mod tests {
|
||||
let mask = out.extras().mask.as_ref().expect("the mask is kept");
|
||||
assert_eq!(*mask.art, stroked(1), "{name} run: an unlinked mask stays where it was");
|
||||
|
||||
let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5).expect("the art is drawn");
|
||||
let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5, &[]).expect("the art is drawn");
|
||||
let mask = out.extras().mask.as_ref().expect("the mask is kept");
|
||||
assert_eq!(mask.art.kind, out.kind, "{name} run, widened: the mask's art bends with the art");
|
||||
assert_eq!(mask.art.appearance, out.appearance, "{name} run, widened: the mask's strokes narrow with the art's");
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
use std::cell::Cell;
|
||||
|
||||
thread_local! {
|
||||
static USED: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
pub(crate) fn initial_used() -> u64 {
|
||||
USED.with(Cell::get)
|
||||
}
|
||||
|
||||
pub(crate) fn with_used<T>(used: u64, action: impl FnOnce() -> T) -> T {
|
||||
struct Reset<'a>(&'a Cell<u64>, u64);
|
||||
impl Drop for Reset<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.set(self.1);
|
||||
}
|
||||
}
|
||||
USED.with(|value| {
|
||||
let _reset = Reset(value, value.replace(used));
|
||||
action()
|
||||
})
|
||||
}
|
||||
@@ -588,6 +588,9 @@ impl<'a> Walk<'a> {
|
||||
clip_tests: 0,
|
||||
warnings: vec![],
|
||||
nest: 0,
|
||||
#[cfg(test)]
|
||||
symbol_nodes: crate::expansion_test::initial_used(),
|
||||
#[cfg(not(test))]
|
||||
symbol_nodes: 0,
|
||||
generated: 0,
|
||||
scratch: None,
|
||||
@@ -740,7 +743,6 @@ impl<'a> Walk<'a> {
|
||||
}
|
||||
Some(None) => {}
|
||||
None => {
|
||||
self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
self.warn(SYMBOLS_LEFT_OUT);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -870,6 +870,31 @@ fn symbols_nested_too_deep_are_left_out_with_a_warning() {
|
||||
assert_eq!(text(&out), "IN;PU;SP0;");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_symbol_keeps_the_budget_for_a_later_fitting_symbol() {
|
||||
let mut d = doc_with(|_| vec![]);
|
||||
let leaf = stroked(&mut d, rect(10.0, 10.0, 60.0, 40.0), Color::BLACK);
|
||||
let big = Node::group(d.alloc_id(), vec![Arc::new(leaf.clone()), Arc::new(leaf.clone())]);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "big".into(), art: Arc::new(big) });
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "small".into(), art: Arc::new(leaf) });
|
||||
let mut first = None;
|
||||
for name in ["big", "small"] {
|
||||
let id = d.alloc_id();
|
||||
first.get_or_insert(id);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap();
|
||||
}
|
||||
let mut expected = d.clone();
|
||||
expected.remove(first.unwrap()).unwrap();
|
||||
crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1, || {
|
||||
let actual = plot(&d, &opts(&d));
|
||||
let control = plot(&expected, &opts(&expected));
|
||||
assert!(actual.warnings.iter().any(|w| w == SYMBOLS_LEFT_OUT), "{:?}", actual.warnings);
|
||||
assert_ne!(text(&control), "IN;PU;SP0;");
|
||||
assert_eq!(text(&actual), text(&control), "HP-GL keeps the later fitting instance");
|
||||
});
|
||||
}
|
||||
|
||||
/// A symbol instance stained by its fill draws in the stained color.
|
||||
#[test]
|
||||
fn a_stained_symbol_instance_takes_its_stain() {
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
|
||||
|
||||
mod aci;
|
||||
#[cfg(test)]
|
||||
mod expansion_test;
|
||||
pub mod hpgl;
|
||||
pub mod import;
|
||||
mod scene;
|
||||
|
||||
@@ -561,8 +561,10 @@ impl<'a> Scene<'a> {
|
||||
extents: None,
|
||||
opacity: 1.0,
|
||||
nest: 0,
|
||||
// Tests spend all but a million of it up front.
|
||||
symbol_nodes: if cfg!(test) { vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000 } else { 0 },
|
||||
#[cfg(test)]
|
||||
symbol_nodes: crate::expansion_test::initial_used(),
|
||||
#[cfg(not(test))]
|
||||
symbol_nodes: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -711,7 +713,6 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
Some(None) => {}
|
||||
None => {
|
||||
self.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
self.warn(SYMBOLS_LEFT_OUT);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1503,11 +1503,36 @@ fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() {
|
||||
let art = Node::group(d.alloc_id(), children);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(art) });
|
||||
}
|
||||
let out = export(&d, &opts(&d)).unwrap();
|
||||
let out = crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1_000_000, || export(&d, &opts(&d)).unwrap());
|
||||
assert!(entities(&out).is_empty());
|
||||
assert!(out.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", out.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_symbol_keeps_the_budget_for_a_later_fitting_symbol() {
|
||||
let mut d = doc_with(|_| vec![]);
|
||||
let leaf = path(&mut d, shapes::rectangle(Rect::new(10.0, 10.0, 60.0, 40.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
|
||||
let big = Node::group(d.alloc_id(), vec![Arc::new(leaf.clone()), Arc::new(leaf.clone())]);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "big".into(), art: Arc::new(big) });
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "small".into(), art: Arc::new(leaf) });
|
||||
let mut first = None;
|
||||
for name in ["big", "small"] {
|
||||
let id = d.alloc_id();
|
||||
first.get_or_insert(id);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY })).unwrap();
|
||||
}
|
||||
let mut expected = d.clone();
|
||||
expected.remove(first.unwrap()).unwrap();
|
||||
crate::expansion_test::with_used(vectorcraft_doc::MAX_SYMBOL_NODES - 1, || {
|
||||
let actual = export(&d, &opts(&d)).unwrap();
|
||||
let control = export(&expected, &opts(&expected)).unwrap();
|
||||
assert!(actual.warnings.iter().any(|w| w.contains("symbols placed inside symbols")), "{:?}", actual.warnings);
|
||||
assert!(!entities(&control).is_empty());
|
||||
assert_eq!(kinds(&actual), kinds(&control), "DXF keeps the later fitting instance");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_bytes_match_shared_writer_goldens() {
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
//! Color text in the forms CSS Color 4 defines: hex colors with or without an alpha
|
||||
//! (<https://www.w3.org/TR/css-color-4/#hex-notation>), `rgb()` and `rgba()`
|
||||
//! (<https://www.w3.org/TR/css-color-4/#rgb-functions>), `hsl()` and `hsla()`
|
||||
//! (<https://www.w3.org/TR/css-color-4/#the-hsl-notation>) and `oklch()`
|
||||
//! (<https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch>). The functions take the
|
||||
//! space-separated form with an optional `/ alpha`, and `rgb()`, `rgba()`, `hsl()` and `hsla()` also
|
||||
//! take the comma-separated legacy form (<https://www.w3.org/TR/css-color-4/#legacy-color-syntax>).
|
||||
//! Hues take the angle units of CSS Values 4 (<https://www.w3.org/TR/css-values-4/#angles>). A hex
|
||||
//! color may leave out its `#`.
|
||||
//!
|
||||
//! The module reads a subset of CSS. A function's arguments are literal numbers, percentages,
|
||||
//! angles and `none`. A parenthesis inside the arguments makes the text invalid, so `calc()`,
|
||||
//! `var()`, `color-mix()`, relative color syntax and every other nested function are refused, as are
|
||||
//! named colors and the other color spaces and functions (`hwb()`, `lab()`, `oklab()`, `color()`).
|
||||
|
||||
use crate::oklab::{self, CHROMA_FULL};
|
||||
|
||||
/// The most characters a color text may have, spaces around it not counted.
|
||||
pub const MAX_CHARS: usize = 48;
|
||||
|
||||
/// The space a parsed color's red, green and blue are in.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Space {
|
||||
/// The numbers as written: a hex color, `rgb()` or `hsl()`.
|
||||
Srgb,
|
||||
/// sRGB converted from `oklch()`.
|
||||
Oklch,
|
||||
}
|
||||
|
||||
/// A color read from CSS text.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct CssColor {
|
||||
/// Red, green and blue from 0 to 1.
|
||||
pub rgb: [f32; 3],
|
||||
/// The alpha from 0 to 1, when the text gives one (CSS reads a missing alpha as 1).
|
||||
pub alpha: Option<f32>,
|
||||
pub space: Space,
|
||||
}
|
||||
|
||||
/// The color `text` gives, or `None` when it is not one of the module's forms or has more than
|
||||
/// [`MAX_CHARS`] characters. Values are clamped where CSS clamps them when it parses them: red, green
|
||||
/// and blue to 0..=255 (0..=100 %), alpha to 0..=1, a negative HSL saturation to 0, OKLCH lightness
|
||||
/// to 0..=1 and chroma to 0 or more. `none` reads as 0, as CSS reads a missing component when it
|
||||
/// converts a color. Spaces, tabs, line breaks and form feeds may surround the text and its
|
||||
/// arguments; other whitespace is not CSS whitespace and makes the text invalid. An `hsl()` color whose red, green or
|
||||
/// blue falls outside 0..=1 has that channel clipped, and an `oklch()` color outside sRGB keeps its
|
||||
/// lightness and hue and takes the largest chroma that fits ([`oklab::from_oklch`]); CSS maps such
|
||||
/// colors into the gamut by its own rules instead. An `hsl()` color whose saturation and lightness
|
||||
/// are so large that a channel overflows to an infinity is refused.
|
||||
pub fn parse(text: &str) -> Option<CssColor> {
|
||||
let text = css_trim(text);
|
||||
if text.chars().nth(MAX_CHARS).is_some() {
|
||||
return None;
|
||||
}
|
||||
match text.find('(') {
|
||||
None => hex(text),
|
||||
Some(open) => {
|
||||
// CSS allows no space between a function's name and its `(`.
|
||||
let name = text.get(..open)?.to_ascii_lowercase();
|
||||
let args = text.get(open + 1..)?.strip_suffix(')')?;
|
||||
if args.contains(['(', ')']) {
|
||||
return None;
|
||||
}
|
||||
match name.as_str() {
|
||||
"rgb" | "rgba" => rgb(args),
|
||||
"hsl" | "hsla" => hsl(args),
|
||||
"oklch" => oklch(args),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `s` without the CSS whitespace (spaces, tabs, line breaks and form feeds, which CSS reads as line
|
||||
/// breaks) around it (<https://www.w3.org/TR/css-syntax-3/#whitespace>,
|
||||
/// <https://www.w3.org/TR/css-syntax-3/#input-preprocessing>).
|
||||
fn css_trim(s: &str) -> &str {
|
||||
s.trim_matches(|c: char| c.is_ascii_whitespace())
|
||||
}
|
||||
|
||||
/// `#rrggbb` of red, green and blue from 0 to 1, each rounded to the nearest of 256 steps.
|
||||
pub fn hex_of(rgb: [f32; 3]) -> String {
|
||||
let [r, g, b] = rgb.map(byte);
|
||||
format!("#{r:02x}{g:02x}{b:02x}")
|
||||
}
|
||||
|
||||
/// `v` (0 to 1) as one of 256 steps.
|
||||
fn byte(v: f32) -> u8 {
|
||||
(v.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}
|
||||
|
||||
/// A hex color of 3, 4, 6 or 8 digits, with or without `#`.
|
||||
fn hex(text: &str) -> Option<CssColor> {
|
||||
let digits = text.strip_prefix('#').unwrap_or(text);
|
||||
if !digits.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let nibbles: Vec<u8> = digits.bytes().filter_map(|b| (b as char).to_digit(16)).map(|d| d as u8).collect();
|
||||
let values: Vec<u8> = match nibbles.len() {
|
||||
3 | 4 => nibbles.iter().map(|n| n * 17).collect(),
|
||||
6 | 8 => nibbles.chunks(2).map(|p| p.iter().fold(0, |v, n| v * 16 + n)).collect(),
|
||||
_ => return None,
|
||||
};
|
||||
let unit = |i: usize| values.get(i).map(|v| f32::from(*v) / 255.0);
|
||||
Some(CssColor { rgb: [unit(0)?, unit(1)?, unit(2)?], alpha: unit(3), space: Space::Srgb })
|
||||
}
|
||||
|
||||
/// One argument of a color function.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Arg {
|
||||
Number(f64),
|
||||
Percent(f64),
|
||||
/// An angle, in degrees.
|
||||
Angle(f64),
|
||||
None,
|
||||
}
|
||||
|
||||
/// The arguments of a color function, `args` being the text inside its parentheses: the three
|
||||
/// components and the alpha, if any, and whether they were separated by commas (the legacy form).
|
||||
fn split(args: &str, legacy_allowed: bool) -> Option<([Arg; 3], Option<Arg>, bool)> {
|
||||
let (parts, alpha, legacy): (Vec<&str>, Option<&str>, bool) = if args.contains(',') {
|
||||
if !legacy_allowed || args.contains('/') {
|
||||
return None;
|
||||
}
|
||||
let mut parts: Vec<&str> = args.split(',').map(css_trim).collect();
|
||||
let alpha = if parts.len() == 4 { parts.pop() } else { None };
|
||||
(parts, alpha, true)
|
||||
} else {
|
||||
let mut halves = args.split('/');
|
||||
let colors = halves.next().unwrap_or_default();
|
||||
let alpha = halves.next();
|
||||
if halves.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
(colors.split_ascii_whitespace().collect(), alpha.map(css_trim), false)
|
||||
};
|
||||
let [a, b, c] = parts.as_slice() else { return None };
|
||||
let one = |s: &str| {
|
||||
let arg = arg(s)?;
|
||||
// The legacy form has no `none`.
|
||||
(!(legacy && arg == Arg::None)).then_some(arg)
|
||||
};
|
||||
let alpha = match alpha {
|
||||
Some(s) => Some(one(s)?),
|
||||
None => None,
|
||||
};
|
||||
Some(([one(a)?, one(b)?, one(c)?], alpha, legacy))
|
||||
}
|
||||
|
||||
/// One argument: `none`, a number, a percentage or an angle (`deg`, `grad`, `rad`, `turn`), with no
|
||||
/// spaces inside it.
|
||||
fn arg(s: &str) -> Option<Arg> {
|
||||
if s.eq_ignore_ascii_case("none") {
|
||||
return Some(Arg::None);
|
||||
}
|
||||
let end = number_end(s)?;
|
||||
let n: f64 = s.get(..end)?.parse().ok().filter(|n: &f64| n.is_finite())?;
|
||||
let unit = s.get(end..)?.to_ascii_lowercase();
|
||||
let arg = match unit.as_str() {
|
||||
"" => Arg::Number(n),
|
||||
"%" => Arg::Percent(n),
|
||||
"deg" => Arg::Angle(n),
|
||||
"grad" => Arg::Angle(n * 0.9),
|
||||
"rad" => Arg::Angle(n.to_degrees()),
|
||||
"turn" => Arg::Angle(n * 360.0),
|
||||
_ => return None,
|
||||
};
|
||||
match arg {
|
||||
Arg::Angle(a) if !a.is_finite() => None,
|
||||
_ => Some(arg),
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte length of the CSS number at the start of `s`: an optional sign, digits with an
|
||||
/// optional fraction (at least one digit, and digits after a `.`), and an optional exponent.
|
||||
fn number_end(s: &str) -> Option<usize> {
|
||||
let b = s.as_bytes();
|
||||
let digits = |from: usize| b.get(from..).map_or(0, |rest| rest.iter().take_while(|c| c.is_ascii_digit()).count());
|
||||
let mut i = usize::from(matches!(b.first(), Some(b'+' | b'-')));
|
||||
let whole = digits(i);
|
||||
i += whole;
|
||||
let mut fraction = 0;
|
||||
if b.get(i) == Some(&b'.') {
|
||||
fraction = digits(i + 1);
|
||||
if fraction == 0 {
|
||||
return None;
|
||||
}
|
||||
i += 1 + fraction;
|
||||
}
|
||||
if whole + fraction == 0 {
|
||||
return None;
|
||||
}
|
||||
if matches!(b.get(i), Some(b'e' | b'E')) {
|
||||
let sign = usize::from(matches!(b.get(i + 1), Some(b'+' | b'-')));
|
||||
let exp = digits(i + 1 + sign);
|
||||
if exp > 0 {
|
||||
i += 1 + sign + exp;
|
||||
}
|
||||
}
|
||||
Some(i)
|
||||
}
|
||||
|
||||
/// The alpha argument from 0 to 1.
|
||||
fn alpha(a: Option<Arg>) -> Option<Option<f32>> {
|
||||
let v = match a {
|
||||
None => return Some(None),
|
||||
Some(Arg::Number(n)) => n,
|
||||
Some(Arg::Percent(p)) => p / 100.0,
|
||||
Some(Arg::None) => 0.0,
|
||||
Some(Arg::Angle(_)) => return None,
|
||||
};
|
||||
Some(Some(v.clamp(0.0, 1.0) as f32))
|
||||
}
|
||||
|
||||
/// A hue argument in degrees from 0 to 360.
|
||||
fn hue(a: Arg) -> Option<f64> {
|
||||
match a {
|
||||
Arg::Number(d) | Arg::Angle(d) => Some(d.rem_euclid(360.0)).filter(|d| d.is_finite()),
|
||||
Arg::None => Some(0.0),
|
||||
Arg::Percent(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn rgb(args: &str) -> Option<CssColor> {
|
||||
let (comps, a, legacy) = split(args, true)?;
|
||||
let percents = comps.iter().filter(|c| matches!(c, Arg::Percent(_))).count();
|
||||
if legacy && percents != 0 && percents != 3 {
|
||||
return None;
|
||||
}
|
||||
let unit = |c: Arg| match c {
|
||||
Arg::Number(n) => Some(n / 255.0),
|
||||
Arg::Percent(p) => Some(p / 100.0),
|
||||
Arg::None => Some(0.0),
|
||||
Arg::Angle(_) => None,
|
||||
};
|
||||
let [r, g, b] = comps;
|
||||
let rgb = [unit(r)?, unit(g)?, unit(b)?].map(|v| v.clamp(0.0, 1.0) as f32);
|
||||
Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Srgb })
|
||||
}
|
||||
|
||||
fn hsl(args: &str) -> Option<CssColor> {
|
||||
let (comps, a, legacy) = split(args, true)?;
|
||||
let [h, s, l] = comps;
|
||||
let percent = |c: Arg| match c {
|
||||
Arg::Percent(v) => Some(v),
|
||||
Arg::Number(v) if !legacy => Some(v),
|
||||
Arg::None => Some(0.0),
|
||||
_ => None,
|
||||
};
|
||||
// CSS clamps a negative saturation to 0 and nothing else.
|
||||
let (h, s, l) = (hue(h)?, percent(s)?.max(0.0) / 100.0, percent(l)? / 100.0);
|
||||
// CSS Color 4's hslToRgb (https://www.w3.org/TR/css-color-4/#hsl-to-rgb); a channel outside
|
||||
// 0..=1 is clipped.
|
||||
let f = |n: f64| {
|
||||
let k = (n + h / 30.0) % 12.0;
|
||||
let amount = s * l.min(1.0 - l);
|
||||
l - amount * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0)
|
||||
};
|
||||
// Huge saturation and lightness values overflow to an infinity or NaN, which is refused.
|
||||
let rgb = [f(0.0), f(8.0), f(4.0)];
|
||||
if rgb.iter().any(|v| !v.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let rgb = rgb.map(|v| v.clamp(0.0, 1.0) as f32);
|
||||
Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Srgb })
|
||||
}
|
||||
|
||||
fn oklch(args: &str) -> Option<CssColor> {
|
||||
let (comps, a, _) = split(args, false)?;
|
||||
let [l, c, h] = comps;
|
||||
let l = match l {
|
||||
Arg::Number(v) => v,
|
||||
Arg::Percent(p) => p / 100.0,
|
||||
Arg::None => 0.0,
|
||||
Arg::Angle(_) => return None,
|
||||
};
|
||||
let c = match c {
|
||||
Arg::Number(v) => v,
|
||||
Arg::Percent(p) => p / 100.0 * CHROMA_FULL,
|
||||
Arg::None => 0.0,
|
||||
Arg::Angle(_) => return None,
|
||||
};
|
||||
let (rgb, _) = oklab::from_oklch(l.clamp(0.0, 1.0), c.max(0.0), hue(h)?);
|
||||
Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Oklch })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use proptest::prelude::*;
|
||||
|
||||
fn bytes(text: &str) -> ([u8; 3], Option<u8>) {
|
||||
let c = parse(text).unwrap_or_else(|| panic!("{text} should parse"));
|
||||
(c.rgb.map(byte), c.alpha.map(|a| (a * 255.0).round() as u8))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_colors_take_three_four_six_or_eight_digits_with_or_without_the_hash() {
|
||||
assert_eq!(bytes("#336699"), ([0x33, 0x66, 0x99], None));
|
||||
assert_eq!(bytes("33669980"), ([0x33, 0x66, 0x99], Some(0x80)));
|
||||
assert_eq!(bytes("#369"), ([0x33, 0x66, 0x99], None));
|
||||
assert_eq!(bytes("#3698"), ([0x33, 0x66, 0x99], Some(0x88)));
|
||||
assert_eq!(bytes(" #AbCdEf "), ([0xab, 0xcd, 0xef], None));
|
||||
for bad in ["", "#", "#12", "#12345", "#1234567", "#123456789", "#ggg", "##123", "#+12", "#12 3", "123"] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rgb_reads_the_modern_and_the_legacy_forms() {
|
||||
assert_eq!(bytes("rgb(51 102 153)"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("rgb(51 102 153 / 50%)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("RGBA(51 102 153/0.5)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("rgb(20% 40% 60%)"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("rgb(20% 102 none)"), ([51, 102, 0], None), "the modern form mixes numbers and percentages");
|
||||
assert_eq!(bytes("rgb(51, 102, 153)"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("rgba(51,102,153,.5)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("rgb(51, 102, 153, 50%)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("rgb(300 -20 1e2)"), ([255, 0, 100], None), "components are clamped");
|
||||
assert_eq!(bytes("rgb(0 0 0 / 2)"), ([0, 0, 0], Some(255)), "the alpha is clamped");
|
||||
assert_eq!(bytes("rgb(0 0 0 / none)"), ([0, 0, 0], Some(0)));
|
||||
for bad in [
|
||||
"rgb(51, 102%, 153)",
|
||||
"rgb(51, 102, none)",
|
||||
"rgb(51 102)",
|
||||
"rgb(51 102 153 0.5)",
|
||||
"rgb(51, 102 153)",
|
||||
"rgb(51, 102, 153 / 0.5)",
|
||||
"rgb(51 102 153 / 0.5 / 1)",
|
||||
"rgb(51 102 153deg)",
|
||||
"rgb(1. 2 3)",
|
||||
"rgb(1e999 0 0)",
|
||||
"rgb(51 102 153",
|
||||
"rgb(51 102 153))",
|
||||
"rgb(51 102 153) x",
|
||||
"rgb(calc(1) 2 3)",
|
||||
"rgb(,,)",
|
||||
"rgb (1 2 3)",
|
||||
"rgb()",
|
||||
"rgbx(1 2 3)",
|
||||
] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_spaces_tabs_and_line_breaks_are_whitespace() {
|
||||
assert_eq!(bytes("\t rgb(51,\n102 ,\t153)\r\n"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("rgb(51 102 153 /\t0.5 )"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("\u{c}#336699\u{c}"), ([51, 102, 153], None), "CSS reads a form feed as a line break");
|
||||
assert_eq!(bytes("rgb(51\u{c}102\u{c}153)"), ([51, 102, 153], None));
|
||||
for bad in ["rgb(51,\u{a0}102,153)", "rgb(51,102,153\u{3000})", "\u{a0}#336699", "#336699\u{2003}", "rgb(0 0 0 /\u{a0}1)", "\u{b}#336699"] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hsl_reads_hues_in_every_angle_unit() {
|
||||
assert_eq!(bytes("hsl(210 50% 40%)"), ([51, 102, 153], None));
|
||||
assert_eq!(bytes("hsl(210deg 50 40 / 25%)"), ([51, 102, 153], Some(64)));
|
||||
assert_eq!(bytes("hsla(210, 50%, 40%, 0.5)"), ([51, 102, 153], Some(128)));
|
||||
assert_eq!(bytes("hsl(-150 50% 40%)"), ([51, 102, 153], None), "a hue is normalized");
|
||||
assert_eq!(bytes("hsl(0.5turn 100% 50%)"), ([0, 255, 255], None));
|
||||
assert_eq!(bytes("hsl(200grad 100% 50%)"), ([0, 255, 255], None));
|
||||
assert_eq!(bytes("hsl(3.14159265rad 100% 50%)"), ([0, 255, 255], None));
|
||||
assert_eq!(bytes("hsl(120 -20% 50%)"), ([128, 128, 128], None), "a negative saturation is 0");
|
||||
assert_eq!(bytes("hsl(15 150% 50%)"), ([255, 32, 0], None), "a saturation over 100 % is kept and the channels are clipped");
|
||||
assert_eq!(bytes("hsl(0 50% 150%)"), ([255, 255, 255], None));
|
||||
assert_eq!(bytes("hsl(none 0% 100%)"), ([255, 255, 255], None));
|
||||
for bad in
|
||||
["hsl(210, 50, 40)", "hsl(210% 50% 40%)", "hsl(210 50% 40% 1)", "hsl(210deg, 50%, none)", "hsl(1e999deg 0% 0%)", "hsl(1e306turn 0% 0%)"]
|
||||
{
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
// Saturation and lightness this large overflow to an infinity or NaN.
|
||||
for bad in ["hsl(90 1e308% 1e308%)", "hsl(90 1e308 -1e308)"] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oklch_converts_through_srgb_and_has_no_legacy_form() {
|
||||
let c = parse("oklch(62.8% 0.2577 29.23)").unwrap();
|
||||
assert_eq!((c.rgb.map(byte), c.alpha, c.space), ([255, 0, 0], None, Space::Oklch));
|
||||
let c = parse("oklch(0.628 64.4% 29.23 / 0.5)").unwrap();
|
||||
assert_eq!((c.rgb.map(byte), c.alpha), ([255, 0, 0], Some(0.5)));
|
||||
assert_eq!(parse("oklch(1 0 0)").map(|c| c.rgb.map(byte)), Some([255, 255, 255]));
|
||||
assert_eq!(parse("oklch(2 -1 none)").map(|c| c.rgb.map(byte)), Some([255, 255, 255]), "L and C are clamped");
|
||||
let wide = parse("oklch(0.7 0.4 150)").unwrap();
|
||||
assert!(wide.rgb.iter().all(|v| (0.0..=1.0).contains(v)), "a color outside sRGB is brought inside: {:?}", wide.rgb);
|
||||
let huge = parse("oklch(0.5 1e308 30)").unwrap();
|
||||
assert!(huge.rgb.iter().all(|v| (0.0..=1.0).contains(v)), "a huge chroma is brought inside: {:?}", huge.rgb);
|
||||
for bad in ["oklch(0.6, 0.1, 30)", "oklch(0.6 0.1 30% )", "oklch(0.6deg 0.1 30)", "oklch(0.6 0.1)"] {
|
||||
assert_eq!(parse(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_longer_than_the_limit_is_refused() {
|
||||
let at_limit = format!("rgb(51 102 153{})", " ".repeat(MAX_CHARS - 15));
|
||||
assert_eq!(at_limit.chars().count(), MAX_CHARS);
|
||||
assert!(parse(&at_limit).is_some());
|
||||
let over = format!("rgb(51 102 153{})", " ".repeat(MAX_CHARS - 14));
|
||||
assert_eq!(parse(&over), None);
|
||||
assert_eq!(parse(&format!(" {at_limit} ")).map(|c| c.rgb.map(byte)), Some([51, 102, 153]), "spaces around it are not counted");
|
||||
assert_eq!(parse(&"(".repeat(100_000)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_of_rounds_each_component() {
|
||||
assert_eq!(hex_of([0.2, 0.4, 0.6]), "#336699");
|
||||
assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00");
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn random_text_never_panics(text in "\\PC{0,60}") {
|
||||
// `contains` is false for NaN, so these also check that every channel is finite.
|
||||
if let Some(c) = parse(&text) {
|
||||
prop_assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v)));
|
||||
prop_assert!(c.alpha.is_none_or(|a| (0.0..=1.0).contains(&a)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_shaped_text_never_panics(
|
||||
name in "(rgb|rgba|hsl|hsla|oklch|RGB)",
|
||||
args in "[-+0-9.eE%a-z ,/]{0,40}",
|
||||
) {
|
||||
if let Some(c) = parse(&format!("{name}({args})")) {
|
||||
prop_assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eight_digit_hex_round_trips(r: u8, g: u8, b: u8, a: u8) {
|
||||
let c = parse(&format!("#{r:02x}{g:02x}{b:02x}{a:02x}")).unwrap();
|
||||
prop_assert_eq!(c.rgb.map(byte), [r, g, b]);
|
||||
prop_assert_eq!(c.alpha.map(|v| (v * 255.0).round() as u8), Some(a));
|
||||
prop_assert_eq!(hex_of(c.rgb), format!("#{r:02x}{g:02x}{b:02x}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
pub mod blend;
|
||||
pub mod cms;
|
||||
pub mod css;
|
||||
pub mod freeform;
|
||||
pub mod gradient;
|
||||
pub mod harmony;
|
||||
@@ -14,6 +15,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]);
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,8 @@ tiff = { workspace = true }
|
||||
craft-stream-codecs = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
# The hash of a generated art object's art, which its file holds (`generated`).
|
||||
sha2 = { version = "0.10", default-features = false }
|
||||
thiserror = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
|
||||
|
||||
@@ -192,14 +192,18 @@ pub enum Arrowhead {
|
||||
/// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as
|
||||
/// the other heads.
|
||||
LineArrow,
|
||||
/// A slender filled head, a little over half as wide as it is long, whose sides bend in
|
||||
/// halfway back, with a V-shaped notch in its back: the arrow of mathematical diagrams.
|
||||
NotchedArrow,
|
||||
/// A head the user drew, with its art.
|
||||
Custom(Arc<CustomArrowhead>),
|
||||
}
|
||||
|
||||
impl Arrowhead {
|
||||
/// Every arrowhead, in menu order (arrows, then outlined shapes, then bars and marks).
|
||||
pub const ALL: [Arrowhead; 41] = [
|
||||
pub const ALL: [Arrowhead; 42] = [
|
||||
Arrowhead::Arrow,
|
||||
Arrowhead::NotchedArrow,
|
||||
Arrowhead::ArrowOpen,
|
||||
Arrowhead::LineArrow,
|
||||
Arrowhead::Barbed,
|
||||
@@ -322,6 +326,7 @@ impl Arrowhead {
|
||||
Arrowhead::TriangleBar => "Triangle to Bar",
|
||||
Arrowhead::Oval => "Oval",
|
||||
Arrowhead::LineArrow => "Line Arrow",
|
||||
Arrowhead::NotchedArrow => "Notched Arrow",
|
||||
Arrowhead::Custom(_) => "Custom",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -316,7 +316,7 @@ fn profile_presets_round_trip_their_ids() {
|
||||
#[test]
|
||||
fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
|
||||
// Saved files store these names: they may only ever be appended to.
|
||||
const SAVED: [&str; 41] = [
|
||||
const SAVED: [&str; 42] = [
|
||||
"Triangle",
|
||||
"TriangleOpen",
|
||||
"Circle",
|
||||
@@ -358,6 +358,7 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
|
||||
"TriangleBar",
|
||||
"Oval",
|
||||
"LineArrow",
|
||||
"NotchedArrow",
|
||||
];
|
||||
for name in SAVED {
|
||||
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
|
||||
|
||||
@@ -394,6 +394,11 @@ pub enum DimensionSource {
|
||||
/// it is vertical. Versions without this source do not open the file.
|
||||
Extent {
|
||||
node: NodeId,
|
||||
/// Placed with Use Preview Bounds on: the points are moved out to the outside of the
|
||||
/// strokes the path paints ([`preview_extents`]), the width or height that W and H show.
|
||||
/// Versions without it measure between the outermost points themselves.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
preview: bool,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -402,7 +407,7 @@ impl DimensionSource {
|
||||
match self {
|
||||
Self::Segment { edge } | Self::Arc { edge } => vec![edge.node],
|
||||
Self::Angle { first, second } => vec![first.node, second.node],
|
||||
Self::Circle { node } | Self::Extent { node } => vec![*node],
|
||||
Self::Circle { node } | Self::Extent { node, .. } => vec![*node],
|
||||
Self::Points { a, b, vertex, free_a, free_b } => [a, b, vertex]
|
||||
.into_iter()
|
||||
.filter_map(|p| p.as_ref().map(|r| r.node))
|
||||
@@ -425,10 +430,18 @@ impl DimensionSource {
|
||||
})
|
||||
}
|
||||
/// Whether a path it measures differs between `before` and `after`, or is in only one of them.
|
||||
/// A node without a path, or missing from both, counts as changed.
|
||||
/// A node without a path, or missing from both, counts as changed. For a dimension of a whole
|
||||
/// path placed with Use Preview Bounds on, so does a change to the strokes the path paints
|
||||
/// ([`stroked_by`]): their appearance, the node they come from, or which arrowheads they draw
|
||||
/// on it, and the path being made into a guide or released from one.
|
||||
pub fn art_changed(&self, before: &Document, after: &Document) -> bool {
|
||||
let strokes = matches!(self, Self::Extent { preview: true, .. });
|
||||
self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) {
|
||||
(Some(old), Some(new)) => old.path_data().is_none() || (!std::ptr::eq(old, new) && old.path_data() != new.path_data()),
|
||||
(Some(old), Some(new)) => {
|
||||
old.path_data().is_none()
|
||||
|| (!std::ptr::eq(old, new) && old.path_data() != new.path_data())
|
||||
|| (strokes && (old.is_guide() != new.is_guide() || stroked_by(before, id) != stroked_by(after, id)))
|
||||
}
|
||||
_ => true,
|
||||
})
|
||||
}
|
||||
@@ -845,7 +858,9 @@ impl Dimension {
|
||||
let (a, b) = (self.a.to_vec2().dot(n), self.b.to_vec2().dot(n));
|
||||
let (low, high) = (a.min(b), a.max(b));
|
||||
match (doc, &self.source) {
|
||||
(Some(doc), Some(DimensionSource::Extent { node })) => reach(doc, *node, n).map_or((low, high), |(l, h)| (low.min(l), high.max(h))),
|
||||
(Some(doc), Some(DimensionSource::Extent { node, preview })) => {
|
||||
reach(doc, *node, n, *preview).map_or((low, high), |(l, h)| (low.min(l), high.max(h)))
|
||||
}
|
||||
_ => (low, high),
|
||||
}
|
||||
}
|
||||
@@ -891,8 +906,8 @@ impl Dimension {
|
||||
};
|
||||
}
|
||||
next.orientation = orientation;
|
||||
if let Some(DimensionSource::Extent { node }) = &next.source {
|
||||
(next.a, next.b) = extent(doc, *node, orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?;
|
||||
if let Some(DimensionSource::Extent { node, preview }) = &next.source {
|
||||
(next.a, next.b) = extent(doc, *node, orientation == Orientation::Vertical, *preview).ok_or("Measured path no longer exists")?;
|
||||
}
|
||||
// Along the new normal, relative to the new first point, so that the result is the offset.
|
||||
let n = next.normal();
|
||||
@@ -1020,8 +1035,8 @@ impl Dimension {
|
||||
let (center, radius) = arc(doc, edge).ok_or("Choose a circle or a perfect arc")?;
|
||||
self.set_radial(center, radius);
|
||||
}
|
||||
Some(DimensionSource::Extent { node }) => {
|
||||
let (a, b) = extent(doc, *node, self.orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?;
|
||||
Some(DimensionSource::Extent { node, preview }) => {
|
||||
let (a, b) = extent(doc, *node, self.orientation == Orientation::Vertical, *preview).ok_or("Measured path no longer exists")?;
|
||||
self.a = a;
|
||||
self.b = b;
|
||||
self.length = self.measured();
|
||||
@@ -1176,14 +1191,86 @@ fn same_extents(before: &Document, after: &Document, id: NodeId) -> bool {
|
||||
}
|
||||
|
||||
/// [`extents`] along one axis: the leftmost and the rightmost points, or with `vertical` the
|
||||
/// topmost and the bottommost.
|
||||
pub fn extent(doc: &Document, id: NodeId, vertical: bool) -> Option<(Point, Point)> {
|
||||
extents(doc, id).map(|ends| ends[usize::from(vertical)])
|
||||
/// topmost and the bottommost. With `preview`, the points of [`preview_extents`].
|
||||
pub fn extent(doc: &Document, id: NodeId, vertical: bool, preview: bool) -> Option<(Point, Point)> {
|
||||
let ends = if preview { preview_extents(doc, id) } else { extents(doc, id) };
|
||||
ends.map(|ends| ends[usize::from(vertical)])
|
||||
}
|
||||
|
||||
/// [`extents`] moved out to the box the path paints, its strokes included ([`painted_box`]), as Use
|
||||
/// Preview Bounds measures it: the leftmost and the rightmost points move out to that box's left
|
||||
/// and right sides at the same height, and the topmost and the bottommost to its top and bottom at
|
||||
/// the same place across. A path that paints no stroke keeps the points of [`extents`]. None for a
|
||||
/// node without a path or without segments.
|
||||
pub fn preview_extents(doc: &Document, id: NodeId) -> Option<[(Point, Point); 2]> {
|
||||
let [(left, right), (top, bottom)] = extents(doc, id)?;
|
||||
let Some(b) = painted_box(doc, id) else { return Some([(left, right), (top, bottom)]) };
|
||||
Some([
|
||||
(Point::new(left.x.min(b.x0), left.y), Point::new(right.x.max(b.x1), right.y)),
|
||||
(Point::new(top.x, top.y.min(b.y0)), Point::new(bottom.x, bottom.y.max(b.y1))),
|
||||
])
|
||||
}
|
||||
|
||||
/// The node whose strokes a path paints with: the compound path that holds it, or the path itself.
|
||||
fn painter(doc: &Document, id: NodeId) -> Option<&crate::Node> {
|
||||
let n = doc.node(id)?;
|
||||
match doc.parent_of(id).and_then(|p| doc.node(p)) {
|
||||
Some(c) if matches!(c.kind, crate::NodeKind::Compound { .. }) => Some(c),
|
||||
_ => Some(n),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the strokes a path paints with depend on, besides its own shape: the node they come from
|
||||
/// ([`painter`]), its appearance, and which arrowheads they draw on the path ([`heads_on`]).
|
||||
fn stroked_by(doc: &Document, id: NodeId) -> Option<(NodeId, &crate::Appearance, (bool, bool))> {
|
||||
painter(doc, id).map(|p| (p.id, &*p.appearance, heads_on(p, id)))
|
||||
}
|
||||
|
||||
/// The box a path paints, its strokes included, measured along its own shape as
|
||||
/// [`crate::Node::visual_bounds`] measures a path: a member of a compound path is stroked with the
|
||||
/// compound path's strokes, with only the arrowheads the compound path paints on it. None for a
|
||||
/// node without a path or without anything drawn, and for a path made into a guide, which paints
|
||||
/// no strokes.
|
||||
fn painted_box(doc: &Document, id: NodeId) -> Option<vectorcraft_geom::Rect> {
|
||||
let n = doc.node(id)?;
|
||||
if n.is_guide() {
|
||||
return None;
|
||||
}
|
||||
let path = n.path_data()?;
|
||||
let painter = painter(doc, id)?;
|
||||
let a = &painter.appearance;
|
||||
// A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath.
|
||||
let dots = a.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square));
|
||||
let b = path.drawn_bounds(dots).or_else(|| n.geometric_bounds())?;
|
||||
let (start, end) = heads_on(painter, id);
|
||||
let mut shape = None;
|
||||
Some(a.stroked_bounds_by(b, |s| {
|
||||
let bp = shape.get_or_insert_with(|| n.stroke_path().unwrap_or_default());
|
||||
if (s.start_arrow.is_some() && !start) || (s.end_arrow.is_some() && !end) {
|
||||
let mut s = s.clone();
|
||||
s.start_arrow = s.start_arrow.filter(|_| start);
|
||||
s.end_arrow = s.end_arrow.filter(|_| end);
|
||||
s.bounds_on(bp, b)
|
||||
} else {
|
||||
s.bounds_on(bp, b)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
/// Whether the start and the end arrowheads of `painter`'s strokes can be drawn on its member
|
||||
/// `id`. A compound path's strokes put the start head on its first subpath and the end head on its
|
||||
/// last, so a member gets the start head only when it holds the first subpath with anchors and
|
||||
/// the end head only when it holds the last one. A path that is its own painter gets both.
|
||||
fn heads_on(painter: &crate::Node, id: NodeId) -> (bool, bool) {
|
||||
let Some(members) = painter.children().filter(|_| painter.id != id) else { return (true, true) };
|
||||
let drawn = |c: &&std::sync::Arc<crate::Node>| c.path_data().is_some_and(|p| p.subpaths.iter().any(|sp| !sp.anchors.is_empty()));
|
||||
(members.iter().find(drawn).is_some_and(|c| c.id == id), members.iter().rfind(drawn).is_some_and(|c| c.id == id))
|
||||
}
|
||||
|
||||
/// How far a path's outline reaches along the unit direction `u`: the lowest and the highest
|
||||
/// `p · u` over the points of its segments. None for a node without a path or without segments.
|
||||
pub fn reach(doc: &Document, id: NodeId, u: Vec2) -> Option<(f64, f64)> {
|
||||
/// `p · u` over the points of its segments, and with `preview` over the corners of the box it
|
||||
/// paints too ([`painted_box`]). None for a node without a path or without segments.
|
||||
pub fn reach(doc: &Document, id: NodeId, u: Vec2, preview: bool) -> Option<(f64, f64)> {
|
||||
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveExtrema};
|
||||
let path = doc.node(id)?.path_data()?;
|
||||
// Turns `u` onto the x axis, so the turned curve's extrema include those along `u`.
|
||||
@@ -1204,6 +1291,15 @@ pub fn reach(doc: &Document, id: NodeId, u: Vec2) -> Option<(f64, f64)> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if preview
|
||||
&& let Some((low, high)) = span.as_mut()
|
||||
&& let Some(b) = painted_box(doc, id)
|
||||
{
|
||||
for corner in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)] {
|
||||
let v = corner.to_vec2().dot(u);
|
||||
(*low, *high) = (low.min(v), high.max(v));
|
||||
}
|
||||
}
|
||||
span
|
||||
}
|
||||
|
||||
|
||||
@@ -314,8 +314,14 @@ impl Document {
|
||||
self.renumber_stored_duplicates();
|
||||
}
|
||||
|
||||
/// Find a node anywhere in the tree.
|
||||
/// Find a node anywhere in the tree. With the lookup cache built, the node comes from the place the cache has for
|
||||
/// it, read once and without copying its index path; otherwise, and when that place no longer holds it, as
|
||||
/// [`Document::index_path`] finds it.
|
||||
pub fn node(&self, id: NodeId) -> Option<&Node> {
|
||||
if let Some(n) = self.index.get().and_then(|cached| cached.node_in(&self.layers, id)) {
|
||||
crate::id_index::note_path_lookup();
|
||||
return Some(n);
|
||||
}
|
||||
self.index_path(id).and_then(|p| self.node_at(&p))
|
||||
}
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -0,0 +1,597 @@
|
||||
//! Generated art objects: a group whose children a generator plug-in drew from its parameters
|
||||
//! (`plugin.generate`). The group keeps the plug-in's id and name, the parameters it was drawn with
|
||||
//! and the transform its art has had since, so `plugin.editGenerated` can run the plug-in again and
|
||||
//! replace the art. Its children are ordinary objects for every renderer and exporter, so the art
|
||||
//! draws, prints and exports whether or not the plug-in is installed.
|
||||
//!
|
||||
//! A file holds the fields beside a SHA-256 of the art as it was written ([`art_hash`]). Reading
|
||||
//! never runs a plug-in. A field that can't be read (an id that is not a plug-in id, parameters
|
||||
//! that are not an object or are past [`MAX_PARAMS_BYTES`], a transform that is not one) marks the
|
||||
//! object [`State::Damaged`], and art that doesn't match the hash marks it [`State::Changed`]: the
|
||||
//! art stays as it was read either way. A damaged object is saved with `damaged: true`, so it stays
|
||||
//! damaged when the file is opened again.
|
||||
//!
|
||||
//! A generated art object inside another one's art (anywhere in its children or their opacity
|
||||
//! masks) is written and read as plain art: its settings are left out of the file, and a file that
|
||||
//! has them there anyway loses them when it is read, its outer object marked [`State::Changed`]
|
||||
//! without hashing. So each object's art is written and hashed once, whatever the nesting.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::{Map, Value};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
use crate::Effect;
|
||||
use crate::node::{Node, NodeKind, Scaling};
|
||||
|
||||
/// Most bytes a generated art object's parameters take, written as JSON.
|
||||
pub const MAX_PARAMS_BYTES: usize = 64 << 10;
|
||||
|
||||
/// Most bytes the art of a generated art object takes when a generator draws it, written as JSON.
|
||||
pub const MAX_ART_BYTES: usize = 16 << 20;
|
||||
|
||||
/// Longest plug-in id, in bytes, as plug-in manifests limit it.
|
||||
pub const MAX_ID: usize = 64;
|
||||
|
||||
/// Longest plug-in name kept, in characters, as plug-in manifests limit it.
|
||||
pub const MAX_NAME: usize = 64;
|
||||
|
||||
/// How the fields of a generated art object were read.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum State {
|
||||
/// Made in this session, or read with every field and the art's hash intact.
|
||||
#[default]
|
||||
Intact,
|
||||
/// A field could not be read: the plug-in id is not one, or the parameters or the transform
|
||||
/// are not usable. The art can't be drawn again.
|
||||
Damaged,
|
||||
/// The fields were read, but the art doesn't match the hash the file gave for it.
|
||||
Changed,
|
||||
}
|
||||
|
||||
/// The settings of a generated art object ([`crate::NodeExtras::generated`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct GeneratedArt {
|
||||
/// The id of the plug-in that drew it.
|
||||
pub plugin: String,
|
||||
/// The plug-in's name when it drew it, to name the plug-in while it is not installed.
|
||||
pub name: String,
|
||||
/// The plug-in's parameters it was drawn with, each one given.
|
||||
pub params: Map<String, Value>,
|
||||
/// The transform its art has had since it was drawn (moves, scales, rotations, reflections
|
||||
/// and shears).
|
||||
pub transform: Affine,
|
||||
/// What its art's stroke weights and dashes have been scaled by since it was drawn (the
|
||||
/// transforms made with Scale Strokes & Effects on).
|
||||
pub stroke_scale: f64,
|
||||
/// What its art's effect distances have been scaled by since it was drawn.
|
||||
pub effect_scale: f64,
|
||||
/// The transform its art's pattern tiles have had since it was drawn (the transforms made with
|
||||
/// Transform Patterns on).
|
||||
pub pattern_transform: Affine,
|
||||
/// How it was read; not written to files.
|
||||
pub state: State,
|
||||
}
|
||||
|
||||
impl GeneratedArt {
|
||||
/// The settings of art drawn by plug-in `plugin` (named `name`) with `params`, not transformed
|
||||
/// since.
|
||||
pub fn new(plugin: &str, name: &str, params: Map<String, Value>) -> Self {
|
||||
Self {
|
||||
plugin: plugin.into(),
|
||||
name: name.chars().take(MAX_NAME).collect(),
|
||||
params,
|
||||
transform: Affine::IDENTITY,
|
||||
stroke_scale: 1.0,
|
||||
effect_scale: 1.0,
|
||||
pattern_transform: Affine::IDENTITY,
|
||||
state: State::Intact,
|
||||
}
|
||||
}
|
||||
|
||||
/// Its art transformed by `a`, with what `sc` says scales besides its geometry.
|
||||
pub fn transform(&mut self, a: Affine, sc: &Scaling) {
|
||||
self.transform = a * self.transform;
|
||||
if let Some(k) = Scaling::factor(a)
|
||||
&& sc.strokes
|
||||
{
|
||||
self.stroke_scale *= k;
|
||||
if sc.effects.is_some() {
|
||||
self.effect_scale *= k;
|
||||
}
|
||||
}
|
||||
if sc.patterns {
|
||||
self.pattern_transform = a * self.pattern_transform;
|
||||
}
|
||||
}
|
||||
|
||||
/// Places `art`, drawn by the generator as it is drawn untransformed, as the object's art has
|
||||
/// been transformed since it was drawn: its geometry, stroke weights, effect distances and
|
||||
/// pattern tiles. `scale` scales an effect's distance parameters (the effects catalogue's).
|
||||
pub fn place(&self, art: &mut Node, scale: fn(&mut Effect, f64)) {
|
||||
if self.transform != Affine::IDENTITY {
|
||||
art.transform(self.transform, false);
|
||||
}
|
||||
self.restyle(art, scale);
|
||||
}
|
||||
|
||||
/// Scales the strokes and effects of `n` and its descendants, and transforms their pattern
|
||||
/// tiles, as [`Self::place`] says.
|
||||
fn restyle(&self, n: &mut Node, scale: fn(&mut Effect, f64)) {
|
||||
if self.stroke_scale != 1.0 {
|
||||
n.appearance.scale_strokes(self.stroke_scale);
|
||||
}
|
||||
if self.effect_scale != 1.0 {
|
||||
n.appearance.scale_effects(self.effect_scale, scale);
|
||||
}
|
||||
if self.pattern_transform != Affine::IDENTITY {
|
||||
crate::pattern::transform_pattern_paints(n, self.pattern_transform);
|
||||
}
|
||||
if let Some(ch) = n.children_mut() {
|
||||
for c in ch.iter_mut() {
|
||||
self.restyle(std::sync::Arc::make_mut(c), scale);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Can its art be drawn again: are its fields intact or only its art changed?
|
||||
pub fn redrawable(&self) -> bool {
|
||||
self.state != State::Damaged
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `id` shaped as a plug-in id: 1 to [`MAX_ID`] characters from `A-Z a-z 0-9 . _ -`?
|
||||
pub fn valid_id(id: &str) -> bool {
|
||||
(1..=MAX_ID).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
|
||||
}
|
||||
|
||||
std::thread_local! {
|
||||
/// Is a generated art object's art being written on this thread ([`Inside`])?
|
||||
static INSIDE: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
/// The bytes [`art_hash`] has hashed on this thread.
|
||||
static HASHED: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// While it lives, objects written on this thread are part of a generated art object's art, and
|
||||
/// the generated art objects among them are written as plain art ([`written`]).
|
||||
pub(crate) struct Inside(bool);
|
||||
|
||||
impl Inside {
|
||||
pub(crate) fn enter() -> Self {
|
||||
Self(INSIDE.with(|i| i.replace(true)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Inside {
|
||||
fn drop(&mut self) {
|
||||
INSIDE.with(|i| i.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings `g` an object writes: none while a generated art object's art is being written.
|
||||
pub(crate) fn written(g: Option<&GeneratedArt>) -> Option<&GeneratedArt> {
|
||||
g.filter(|_| !INSIDE.with(Cell::get))
|
||||
}
|
||||
|
||||
/// The SHA-256 of `children` written as JSON, in lower-case hexadecimal: what a file holds as the
|
||||
/// hash of a generated art object's art. Generated art objects among them are written as plain
|
||||
/// art.
|
||||
pub fn art_hash(children: &[Arc<Node>]) -> String {
|
||||
use sha2::{Digest, Sha256};
|
||||
let bytes = {
|
||||
let _inside = Inside::enter();
|
||||
serde_json::to_vec(children).unwrap_or_default()
|
||||
};
|
||||
#[cfg(test)]
|
||||
HASHED.with(|h| h.set(h.get() + bytes.len()));
|
||||
Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// The bytes `children` take written as JSON, generated art objects among them as plain art
|
||||
/// ([`MAX_ART_BYTES`]).
|
||||
pub fn art_bytes(children: &[Arc<Node>]) -> usize {
|
||||
let _inside = Inside::enter();
|
||||
serde_json::to_vec(children).map_or(usize::MAX, |b| b.len())
|
||||
}
|
||||
|
||||
/// Drops the settings of the generated art objects in `nodes`, among their descendants and in
|
||||
/// their opacity masks' art, which become plain art; returns whether there were any. It doesn't
|
||||
/// look among the children of such an object, which reading it already made plain art, only at
|
||||
/// its opacity mask's art.
|
||||
fn plain_art(nodes: &mut [Arc<Node>]) -> bool {
|
||||
let mut found = false;
|
||||
for a in nodes {
|
||||
let generated = a.extras().generated.is_some();
|
||||
if !generated && a.children().is_none_or(Vec::is_empty) && a.extras().mask.is_none() {
|
||||
continue;
|
||||
}
|
||||
let n = Arc::make_mut(a);
|
||||
if generated {
|
||||
n.extras_mut().generated = None;
|
||||
found = true;
|
||||
} else if let Some(ch) = n.children_mut() {
|
||||
found |= plain_art(ch);
|
||||
}
|
||||
if n.extras().mask.is_some()
|
||||
&& let Some(m) = n.extras_mut().mask.as_mut()
|
||||
{
|
||||
found |= plain_art(std::slice::from_mut(&mut m.art));
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// How a file holds a generated art object's settings, borrowed from the node.
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct Wire<'a> {
|
||||
plugin: &'a str,
|
||||
name: &'a str,
|
||||
params: &'a Map<String, Value>,
|
||||
#[serde(skip_serializing_if = "is_identity")]
|
||||
transform: &'a Affine,
|
||||
#[serde(rename = "strokeScale", skip_serializing_if = "is_one")]
|
||||
stroke_scale: f64,
|
||||
#[serde(rename = "effectScale", skip_serializing_if = "is_one")]
|
||||
effect_scale: f64,
|
||||
#[serde(rename = "patternTransform", skip_serializing_if = "is_identity")]
|
||||
pattern_transform: &'a Affine,
|
||||
hash: String,
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
damaged: bool,
|
||||
}
|
||||
|
||||
fn is_identity(a: &&Affine) -> bool {
|
||||
**a == Affine::IDENTITY
|
||||
}
|
||||
|
||||
fn is_one(k: &f64) -> bool {
|
||||
*k == 1.0
|
||||
}
|
||||
|
||||
impl<'a> Wire<'a> {
|
||||
/// The settings `g` of node `n`, with the hash of its art.
|
||||
pub(crate) fn of(g: &'a GeneratedArt, n: &Node) -> Self {
|
||||
let hash = art_hash(n.children().map_or(&[][..], Vec::as_slice));
|
||||
Wire {
|
||||
plugin: &g.plugin,
|
||||
name: &g.name,
|
||||
params: &g.params,
|
||||
transform: &g.transform,
|
||||
stroke_scale: g.stroke_scale,
|
||||
effect_scale: g.effect_scale,
|
||||
pattern_transform: &g.pattern_transform,
|
||||
hash,
|
||||
damaged: g.state == State::Damaged,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A saved transform `t` (absent: none): `None` when it is not six finite numbers.
|
||||
fn read_affine(t: Option<Value>) -> Option<Affine> {
|
||||
match t {
|
||||
None => Some(Affine::IDENTITY),
|
||||
Some(t) => serde_json::from_value::<Affine>(t).ok().filter(|a| a.as_coeffs().iter().all(|c| c.is_finite())),
|
||||
}
|
||||
}
|
||||
|
||||
/// A saved scale `k` (absent: 1): `None` when it is not a finite number of 0 or more. A transform
|
||||
/// that flattens the art to a line or a point scales its strokes and effects by 0.
|
||||
fn read_scale(k: Option<Value>) -> Option<f64> {
|
||||
match k {
|
||||
None => Some(1.0),
|
||||
Some(k) => k.as_f64().filter(|k| k.is_finite() && *k >= 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings a file gives (`v`, its `generated` field) for a node of `kind`: `None` for anything
|
||||
/// but a group, else what could be read, marked [`State::Damaged`] or [`State::Changed`] when a
|
||||
/// field or the art's hash doesn't hold up. A field that can't be read is kept empty: an id is
|
||||
/// kept only when it is a plug-in id, a name at most [`MAX_NAME`] characters long. Generated art
|
||||
/// objects in the group's art become plain art ([`plain_art`]), and the art is then not hashed.
|
||||
pub(crate) fn read(v: Value, kind: &mut NodeKind) -> Option<Box<GeneratedArt>> {
|
||||
let NodeKind::Group { children, .. } = kind else { return None };
|
||||
let nested = plain_art(children);
|
||||
let Value::Object(mut o) = v else {
|
||||
return Some(Box::new(GeneratedArt { state: State::Damaged, ..GeneratedArt::new("", "", Map::new()) }));
|
||||
};
|
||||
let mut damaged = !matches!(o.remove("damaged"), None | Some(Value::Bool(false)));
|
||||
let plugin = match o.remove("plugin") {
|
||||
Some(Value::String(id)) if valid_id(&id) => id,
|
||||
_ => {
|
||||
damaged = true;
|
||||
String::new()
|
||||
}
|
||||
};
|
||||
let name: String = match o.remove("name") {
|
||||
Some(Value::String(n)) => n.chars().filter(|c| !c.is_control()).take(MAX_NAME).collect(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let params = match o.remove("params") {
|
||||
Some(Value::Object(p)) if serde_json::to_vec(&p).is_ok_and(|b| b.len() <= MAX_PARAMS_BYTES) => p,
|
||||
_ => {
|
||||
damaged = true;
|
||||
Map::new()
|
||||
}
|
||||
};
|
||||
let mut affine = |key: &str| {
|
||||
read_affine(o.remove(key)).unwrap_or_else(|| {
|
||||
damaged = true;
|
||||
Affine::IDENTITY
|
||||
})
|
||||
};
|
||||
let transform = affine("transform");
|
||||
let pattern_transform = affine("patternTransform");
|
||||
let mut scale = |key: &str| {
|
||||
read_scale(o.remove(key)).unwrap_or_else(|| {
|
||||
damaged = true;
|
||||
1.0
|
||||
})
|
||||
};
|
||||
let stroke_scale = scale("strokeScale");
|
||||
let effect_scale = scale("effectScale");
|
||||
let intact = !nested && matches!(o.get("hash"), Some(Value::String(h)) if *h == art_hash(children));
|
||||
let state = if damaged {
|
||||
State::Damaged
|
||||
} else if intact {
|
||||
State::Intact
|
||||
} else {
|
||||
State::Changed
|
||||
};
|
||||
Some(Box::new(GeneratedArt { plugin, name, params, transform, stroke_scale, effect_scale, pattern_transform, state }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::node::NodeId;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
fn art() -> Node {
|
||||
let square = Node::path(NodeId(2), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Default::default());
|
||||
let mut g = Node::group(NodeId(1), vec![Arc::new(square)]);
|
||||
let mut params = Map::new();
|
||||
params.insert("size".into(), json!(10));
|
||||
g.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", params)));
|
||||
g
|
||||
}
|
||||
|
||||
fn reread(v: &Value) -> Node {
|
||||
serde_json::from_value(v.clone()).unwrap()
|
||||
}
|
||||
|
||||
/// `depth` generated art objects, each the only child of the one around it, the innermost
|
||||
/// [`art`].
|
||||
fn nested(depth: usize) -> Node {
|
||||
let mut n = art();
|
||||
for i in 1..depth {
|
||||
let mut g = Node::group(NodeId(10 + i as u64), vec![Arc::new(n)]);
|
||||
g.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", Map::new())));
|
||||
n = g;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// The bytes [`art_hash`] hashes while `f` runs.
|
||||
fn hashed<T>(f: impl FnOnce() -> T) -> (T, usize) {
|
||||
HASHED.with(|h| h.set(0));
|
||||
let out = f();
|
||||
(out, HASHED.with(Cell::get))
|
||||
}
|
||||
|
||||
/// The generated art objects in `n` and below it, outermost first, as (depth, state).
|
||||
fn generated_in(n: &Node) -> Vec<(usize, State)> {
|
||||
let mut out = vec![];
|
||||
let mut at = Some((n, 0));
|
||||
while let Some((n, d)) = at {
|
||||
if let Some(g) = &n.extras().generated {
|
||||
out.push((d, g.state));
|
||||
}
|
||||
at = n.children().and_then(|c| c.first()).map(|c| (&**c, d + 1));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Generated art objects nested in one another are written with the outermost one's settings
|
||||
/// alone, so writing and reading them hash each object's art once, however deep they nest; a
|
||||
/// file that has settings on the inner ones anyway loses them, without hashing.
|
||||
#[test]
|
||||
fn nested_generated_art_is_written_and_read_with_its_art_hashed_once() {
|
||||
crate::depth::with_deep_stack(|| {
|
||||
for depth in [16, 200] {
|
||||
let n = nested(depth);
|
||||
let (bytes, writing) = hashed(|| serde_json::to_vec(&n).unwrap());
|
||||
assert!(writing <= bytes.len(), "{depth} deep: {writing} bytes hashed to write {}", bytes.len());
|
||||
assert_eq!(String::from_utf8_lossy(&bytes).matches("\"generated\"").count(), 1, "{depth} deep");
|
||||
let v = serde_json::to_value(&n).unwrap();
|
||||
let (back, reading) = hashed(|| reread(&v));
|
||||
assert!(reading <= bytes.len(), "{depth} deep: {reading} bytes hashed to read {}", bytes.len());
|
||||
assert_eq!(generated_in(&back), vec![(0, State::Intact)], "{depth} deep");
|
||||
// Settings on every level, each with a hash: none is hashed, the inner ones are
|
||||
// dropped, and the outermost reads as changed.
|
||||
let mut crafted = v.clone();
|
||||
let settings = v["generated"].clone();
|
||||
let mut at = crafted.pointer_mut("/kind/children/0");
|
||||
while let Some(c) = at {
|
||||
if c.pointer("/kind/children/0").is_some() {
|
||||
c["generated"] = settings.clone();
|
||||
}
|
||||
at = c.pointer_mut("/kind/children/0");
|
||||
}
|
||||
let (crafted_back, reading) = hashed(|| reread(&crafted));
|
||||
assert!(reading <= bytes.len(), "{depth} deep, crafted: {reading} bytes hashed to read {}", bytes.len());
|
||||
assert_eq!(generated_in(&crafted_back), vec![(0, State::Changed)], "{depth} deep, crafted");
|
||||
assert_eq!(crafted_back.children(), back.children(), "{depth} deep, crafted");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A generated art object inside another one's art, whose opacity mask's art is a generated art
|
||||
/// object too, reads as plain art with plain mask art.
|
||||
#[test]
|
||||
fn a_nested_generated_art_objects_mask_art_reads_as_plain_art() {
|
||||
let mut inner = art();
|
||||
inner.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(art(), true)));
|
||||
let mut outer = Node::group(NodeId(20), vec![Arc::new(inner)]);
|
||||
outer.extras_mut().generated = Some(Box::new(GeneratedArt::new("org.example.gen", "Squares", Map::new())));
|
||||
let v = serde_json::to_value(&outer).unwrap();
|
||||
assert!(v.pointer("/kind/children/0/generated").is_none() && v.pointer("/kind/children/0/mask/art/generated").is_none());
|
||||
let mut crafted = v.clone();
|
||||
let settings = v["generated"].clone();
|
||||
crafted["kind"]["children"][0]["generated"] = settings.clone();
|
||||
crafted["kind"]["children"][0]["mask"]["art"]["generated"] = settings;
|
||||
let back = reread(&crafted);
|
||||
assert_eq!(back.extras().generated.as_ref().map(|g| g.state), Some(State::Changed));
|
||||
let inner = &back.children().unwrap()[0];
|
||||
assert!(inner.extras().generated.is_none());
|
||||
assert!(inner.extras().mask.as_ref().is_some_and(|m| m.art.extras().generated.is_none()));
|
||||
assert_eq!(back.children(), reread(&v).children());
|
||||
}
|
||||
|
||||
/// A generated art object inside plain groups is still checked against its hash: intact as
|
||||
/// written, changed when its art is tampered with.
|
||||
#[test]
|
||||
fn a_generated_art_object_deep_in_plain_groups_keeps_its_hash_check() {
|
||||
crate::depth::with_deep_stack(|| {
|
||||
let mut n = art();
|
||||
for i in 1..200 {
|
||||
n = Node::group(NodeId(10 + i as u64), vec![Arc::new(n)]);
|
||||
}
|
||||
let v = serde_json::to_value(&n).unwrap();
|
||||
let state = |v: &Value| generated_in(&reread(v)).into_iter().map(|(_, s)| s).collect::<Vec<_>>();
|
||||
assert_eq!(state(&v), vec![State::Intact]);
|
||||
let mut tampered = v.clone();
|
||||
let mut at = tampered.pointer_mut("/kind/children/0");
|
||||
while let Some(c) = at {
|
||||
if c.get("generated").is_some() {
|
||||
c["kind"]["children"][0]["name"] = json!("tampered");
|
||||
break;
|
||||
}
|
||||
at = c.pointer_mut("/kind/children/0");
|
||||
}
|
||||
assert_eq!(state(&tampered), vec![State::Changed]);
|
||||
});
|
||||
}
|
||||
|
||||
/// A generated art object writes its plug-in, name, parameters and the hash of its art, and
|
||||
/// reads back the same, intact.
|
||||
#[test]
|
||||
fn a_generated_art_object_round_trips_with_the_hash_of_its_art() {
|
||||
let g = art();
|
||||
let v = serde_json::to_value(&g).unwrap();
|
||||
let saved = &v["generated"];
|
||||
assert_eq!((&saved["plugin"], &saved["name"], &saved["params"]), (&json!("org.example.gen"), &json!("Squares"), &json!({"size": 10})));
|
||||
assert_eq!(saved["hash"], json!(art_hash(g.children().unwrap())));
|
||||
assert!(saved.get("transform").is_none());
|
||||
let back = reread(&v);
|
||||
assert_eq!(back, g);
|
||||
assert_eq!(back.extras().generated.as_ref().map(|a| a.state), Some(State::Intact));
|
||||
// A moved object keeps its transform.
|
||||
let mut moved = g.clone();
|
||||
moved.transform(Affine::translate((5.0, 0.0)), false);
|
||||
let back = reread(&serde_json::to_value(&moved).unwrap());
|
||||
assert_eq!(back.extras().generated.as_ref().map(|a| (a.transform, a.state)), Some((Affine::translate((5.0, 0.0)), State::Intact)));
|
||||
// A scale with Scale Strokes & Effects and Transform Patterns keeps what it scaled.
|
||||
let mut scaled = g.clone();
|
||||
let sc = Scaling { strokes: true, patterns: true, ..Scaling::default() };
|
||||
scaled.transform(Affine::scale(2.0), sc);
|
||||
scaled.transform(Affine::scale(3.0), false);
|
||||
let back = reread(&serde_json::to_value(&scaled).unwrap());
|
||||
let a = back.extras().generated.as_deref().unwrap();
|
||||
assert_eq!((a.stroke_scale, a.effect_scale, a.pattern_transform, a.state), (2.0, 1.0, Affine::scale(2.0), State::Intact));
|
||||
assert_eq!(a.transform, Affine::scale(6.0));
|
||||
// A transform that flattens it to a point, with Scale Strokes & Effects on, scales its
|
||||
// strokes and effects by 0, and it reads back intact with those scales.
|
||||
let mut flat = g.clone();
|
||||
flat.transform(Affine::new([0.0; 6]), Scaling { strokes: true, effects: Some(|_, _| {}), ..Scaling::default() });
|
||||
let back = reread(&serde_json::to_value(&flat).unwrap());
|
||||
let a = back.extras().generated.as_deref().unwrap();
|
||||
assert_eq!((a.stroke_scale, a.effect_scale, a.state), (0.0, 0.0, State::Intact));
|
||||
}
|
||||
|
||||
/// Art that doesn't match the file's hash, and fields that can't be read, keep the art and say
|
||||
/// how the object was read; a garbled id is never kept.
|
||||
#[test]
|
||||
fn damaged_fields_and_changed_art_keep_the_art() {
|
||||
let g = art();
|
||||
let v = serde_json::to_value(&g).unwrap();
|
||||
let state = |v: &Value| reread(v).extras().generated.as_ref().map(|a| (a.plugin.clone(), a.state));
|
||||
// The art edited, with the hash of the art before.
|
||||
let mut edited = g.clone();
|
||||
if let Some(c) = edited.children_mut().and_then(|c| c.first_mut()) {
|
||||
Arc::make_mut(c).transform(Affine::translate((1.0, 0.0)), false);
|
||||
}
|
||||
let mut changed = serde_json::to_value(&edited).unwrap();
|
||||
changed["generated"]["hash"] = v["generated"]["hash"].clone();
|
||||
assert_eq!(state(&changed), Some(("org.example.gen".into(), State::Changed)));
|
||||
let mut no_hash = v.clone();
|
||||
no_hash["generated"].as_object_mut().unwrap().remove("hash");
|
||||
assert_eq!(state(&no_hash), Some(("org.example.gen".into(), State::Changed)));
|
||||
for (field, bad) in [
|
||||
("plugin", json!("../evil")),
|
||||
("plugin", json!("x".repeat(65))),
|
||||
("plugin", json!("")),
|
||||
("plugin", json!("a\u{0}b")),
|
||||
("plugin", json!(7)),
|
||||
("params", json!([1, 2])),
|
||||
("params", json!({"blob": "x".repeat(MAX_PARAMS_BYTES)})),
|
||||
("transform", json!("sideways")),
|
||||
("transform", Value::Null),
|
||||
("strokeScale", json!(-2.0)),
|
||||
("strokeScale", Value::Null),
|
||||
("strokeScale", json!("big")),
|
||||
("effectScale", json!(-0.5)),
|
||||
("patternTransform", json!([1, 0, 0, 1, 0])),
|
||||
("patternTransform", Value::Null),
|
||||
("effectScale", Value::Null),
|
||||
("damaged", json!(true)),
|
||||
("damaged", json!("no")),
|
||||
] {
|
||||
let mut w = v.clone();
|
||||
w["generated"][field] = bad;
|
||||
let back = reread(&w);
|
||||
let a = back.extras().generated.as_ref().unwrap();
|
||||
assert_eq!(a.state, State::Damaged, "{field}");
|
||||
assert!(a.plugin.is_empty() || a.plugin == "org.example.gen", "{field}: {}", a.plugin);
|
||||
assert_eq!(back.children(), g.children(), "{field}");
|
||||
// Saved again and read back, it stays damaged.
|
||||
let again = reread(&serde_json::to_value(&back).unwrap());
|
||||
assert_eq!(again.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged), "{field} saved again");
|
||||
}
|
||||
// Not an object at all.
|
||||
let mut w = v.clone();
|
||||
w["generated"] = json!("art");
|
||||
assert_eq!(state(&w), Some((String::new(), State::Damaged)));
|
||||
// A null field is read as a field that can't be read, not as an absent one, from a value
|
||||
// and from a file's text; the art stays, and saved again the object stays damaged.
|
||||
let mut w = v.clone();
|
||||
w["generated"] = Value::Null;
|
||||
assert_eq!(state(&w), Some((String::new(), State::Damaged)));
|
||||
let back: Node = serde_json::from_str(&w.to_string()).unwrap();
|
||||
assert_eq!(back.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged));
|
||||
assert_eq!(back.children(), g.children());
|
||||
let again = reread(&serde_json::to_value(&back).unwrap());
|
||||
assert_eq!(again.extras().generated.as_ref().map(|a| a.state), Some(State::Damaged));
|
||||
// On a path the field is dropped, and the path stays as it was.
|
||||
let path = g.children().unwrap()[0].clone();
|
||||
let mut p = serde_json::to_value(&*path).unwrap();
|
||||
p["generated"] = v["generated"].clone();
|
||||
let back = reread(&p);
|
||||
assert!(back.extras().generated.is_none());
|
||||
assert_eq!(back, *path);
|
||||
// A name is cut to its limit and loses control characters.
|
||||
let mut w = v.clone();
|
||||
w["generated"]["name"] = json!(format!("A\u{202e}\n{}", "n".repeat(100)));
|
||||
let back = reread(&w);
|
||||
let name = &back.extras().generated.as_ref().unwrap().name;
|
||||
assert_eq!(name.chars().count(), MAX_NAME);
|
||||
assert!(!name.chars().any(char::is_control));
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,11 @@ pub struct HitOptions {
|
||||
/// The point hit tests ([`hit_test`], [`hit_test_visible`] and [`hit_test_visible_skipping`])
|
||||
/// hit the art on a layer whose Preview is off as painted, not in outline.
|
||||
pub ignore_layer_preview: bool,
|
||||
/// The selection tools: where a click hits nothing else, a closed path or compound path with
|
||||
/// no fill is hit inside its closed subpaths, the topmost first, as a filled one is. Off with
|
||||
/// [`Self::path_only`] and in outline. Clipping paths and guides are still hit on their
|
||||
/// outline only. [`hit_test`] and [`objects_at`] try every other object first.
|
||||
pub unfilled_interiors: bool,
|
||||
}
|
||||
|
||||
impl Default for HitOptions {
|
||||
@@ -94,6 +99,7 @@ impl Default for HitOptions {
|
||||
clip_outlines: false,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
unfilled_interiors: false,
|
||||
scope: None,
|
||||
}
|
||||
}
|
||||
@@ -417,11 +423,35 @@ impl Drop for DrawnOff {
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Whether a clipping path is being tested ([`InMask`]).
|
||||
static IN_MASK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// While a guard lives, a clipping path is tested: it is not hit inside by its interior alone
|
||||
/// ([`takes_interior`]).
|
||||
struct InMask {
|
||||
was: bool,
|
||||
}
|
||||
|
||||
impl InMask {
|
||||
fn set() -> Self {
|
||||
Self { was: IN_MASK.replace(true) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for InMask {
|
||||
fn drop(&mut self) {
|
||||
IN_MASK.set(self.was);
|
||||
}
|
||||
}
|
||||
|
||||
/// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a
|
||||
/// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to
|
||||
/// the region it clips to.
|
||||
/// the region it clips to. It is also under an [`InMask`] guard.
|
||||
fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T {
|
||||
let _off = mask.then(DrawnOff::set);
|
||||
let _mask = mask.then(InMask::set);
|
||||
f()
|
||||
}
|
||||
|
||||
@@ -636,17 +666,23 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) {
|
||||
// An envelope in Edit Contents may expose objects *within* a top-level group.
|
||||
// The repeated traversal handles that mixed hierarchy precisely. The objects found
|
||||
// so far lie above the envelope and stay first; the repeated traversal finds the
|
||||
// rest with what is left of the limit of symbol art to walk.
|
||||
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
|
||||
break;
|
||||
// As [`hit_test`] does: the objects hit by what they paint first, then those hit only inside
|
||||
// an unfilled closed path ([`HitOptions::unfilled_interiors`]).
|
||||
let painted = HitOptions { unfilled_interiors: false, ..opt };
|
||||
let interiors = opt.unfilled_interiors && !opt.path_only && !opt.outline;
|
||||
'passes: for pass in [Some(painted), interiors.then_some(opt)].into_iter().flatten() {
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
if !objects_at_layer(layer, p, pass, &symbols, &mut tops, &mut seen) {
|
||||
// An envelope in Edit Contents may expose objects *within* a top-level group.
|
||||
// The repeated traversal handles that mixed hierarchy precisely. The objects found
|
||||
// so far lie above the envelope and stay first; the repeated traversal finds the
|
||||
// rest with what is left of the limit of symbol art to walk.
|
||||
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
|
||||
break 'passes;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them.
|
||||
@@ -731,6 +767,152 @@ fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: O
|
||||
tops
|
||||
}
|
||||
|
||||
/// The most hits [`leaves_at`] lists.
|
||||
pub const MAX_LEAVES_AT: usize = 256;
|
||||
|
||||
/// The hits under `p`, topmost first, at most [`MAX_LEAVES_AT`]: one for each object a click with
|
||||
/// Direct Selection picks there (a path, a compound path or an image, also inside a group), each
|
||||
/// found by a hit test ([`hit_test`]) that passes over the ones found before it. In isolation mode
|
||||
/// (`opt.scope`) only what is inside the isolated group or object is hit. Cmd/Ctrl-clicks with the
|
||||
/// Selection tool step through them (Select Behind).
|
||||
pub fn leaves_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<Hit> {
|
||||
let _walk = ArtWalk::open();
|
||||
// A clipping mask, or a group drawn with its own geometry effects, hits by rules the single
|
||||
// traversal leaves to the hit test: the repeated hit test finds the rest, after the hits found
|
||||
// above them, which the art walked for them already counted against.
|
||||
leaves_at_once(doc, p, opt).unwrap_or_else(|above| leaves_at_repeated_after(doc, p, opt, above))
|
||||
}
|
||||
|
||||
/// [`leaves_at`] by repeated hit tests, each passing over the objects found before it.
|
||||
#[cfg(test)]
|
||||
fn leaves_at_repeated(doc: &Document, p: Point, opt: HitOptions) -> Vec<Hit> {
|
||||
leaves_at_repeated_after(doc, p, opt, vec![])
|
||||
}
|
||||
|
||||
/// [`leaves_at`] by repeated hit tests after `hits`, the topmost hits already found.
|
||||
fn leaves_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, mut hits: Vec<Hit>) -> Vec<Hit> {
|
||||
let mut found: HashSet<NodeId> = hits.iter().map(|h| h.leaf).collect();
|
||||
while hits.len() < MAX_LEAVES_AT
|
||||
&& let Some(h) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true)
|
||||
{
|
||||
if !found.insert(h.leaf) {
|
||||
break;
|
||||
}
|
||||
hits.push(h);
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
/// [`leaves_at`] in one traversal of the document, in the order repeated hit tests
|
||||
/// ([`hit_test_skipping`]) find them. `Err` with the hits found above it when a container under
|
||||
/// `p` clips or draws its art with its own geometry effects ([`leaves_in`]).
|
||||
fn leaves_at_once(doc: &Document, p: Point, opt: HitOptions) -> Result<Vec<Hit>, Vec<Hit>> {
|
||||
let finish = |mut h: Hit| {
|
||||
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
|
||||
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
|
||||
h
|
||||
};
|
||||
let locks = doc.locked_artboards_kept();
|
||||
let on_locked = |id: NodeId| {
|
||||
!locks.is_empty() && doc.parent_of(id).and_then(|l| doc.node(l)).is_some_and(Node::is_layer) && doc.node(id).is_some_and(|n| locks.holds(n))
|
||||
};
|
||||
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
|
||||
let mut hits = Vec::new();
|
||||
if let Some(scope) = opt.scope
|
||||
&& let Some(isolated) = doc.node(scope)
|
||||
&& let Some(mut chain) = doc.ancestry(scope)
|
||||
{
|
||||
if !doc.is_editable_with(&locks, scope) {
|
||||
return Ok(hits);
|
||||
}
|
||||
let whole = if isolated.is_container() {
|
||||
leaves_in(isolated, p, opt, &symbols, &on_locked, &mut chain, &mut hits)
|
||||
} else {
|
||||
// A single object isolated: only it hits, among its siblings.
|
||||
chain.pop();
|
||||
let Some(parent) = chain.last().and_then(|id| doc.node(*id)) else { return Ok(hits) };
|
||||
leaves_in(parent, p, opt, &symbols, &|id| id != scope || on_locked(id), &mut chain, &mut hits)
|
||||
};
|
||||
let hits = hits.into_iter().map(finish).collect();
|
||||
return if whole { Ok(hits) } else { Err(hits) };
|
||||
}
|
||||
let mut chain = Vec::new();
|
||||
for layer in doc.layers.iter().rev() {
|
||||
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
|
||||
continue;
|
||||
}
|
||||
chain.push(layer.id);
|
||||
let opt = if !opt.ignore_layer_preview && previews_off(layer) { HitOptions { outline: true, ..opt } } else { opt };
|
||||
if !leaves_in(layer, p, opt, &symbols, &on_locked, &mut chain, &mut hits) {
|
||||
return Err(hits.into_iter().map(finish).collect());
|
||||
}
|
||||
chain.pop();
|
||||
if hits.len() >= MAX_LEAVES_AT {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(hits.into_iter().map(finish).collect())
|
||||
}
|
||||
|
||||
/// Every editable hit under `p` in `parent`, topmost first, added to `hits` up to
|
||||
/// [`MAX_LEAVES_AT`]: what [`hit_children`] finds first, then what it finds passing over each hit
|
||||
/// found before. `false` when `parent` or a container in it under `p` clips or draws its art with
|
||||
/// its own geometry effects, which [`hit_children`] hits by rules of their own.
|
||||
fn leaves_in(
|
||||
parent: &Node,
|
||||
p: Point,
|
||||
opt: HitOptions,
|
||||
symbols: &SymbolBoxes,
|
||||
skip: &dyn Fn(NodeId) -> bool,
|
||||
chain: &mut Vec<NodeId>,
|
||||
hits: &mut Vec<Hit>,
|
||||
) -> bool {
|
||||
let Some(children) = parent.children() else { return true };
|
||||
if parent.clips() || drawn_art(symbols, parent, opt.outline).is_some() {
|
||||
return false;
|
||||
}
|
||||
for i in hit_order(parent, children, p) {
|
||||
if hits.len() >= MAX_LEAVES_AT {
|
||||
return true;
|
||||
}
|
||||
let Some(c) = children.get(i) else { continue };
|
||||
if !may_hit(parent, i, c, p, opt, symbols, true) || skip(c.id) {
|
||||
continue;
|
||||
}
|
||||
chain.push(c.id);
|
||||
let leaf = |hits: &mut Vec<Hit>, chain: &[NodeId]| {
|
||||
if let Some(kind) = hit_leaf(c, p, opt, symbols) {
|
||||
hits.push(Hit { leaf: c.id, ancestry: chain.to_vec(), kind, contents_of: None, layers: 1 });
|
||||
}
|
||||
};
|
||||
let whole = match &c.kind {
|
||||
NodeKind::Layer { preview: false, .. } if !opt.ignore_layer_preview => {
|
||||
leaves_in(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, hits)
|
||||
}
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } | NodeKind::Envelope { editing: true, .. } => {
|
||||
leaves_in(c, p, opt, symbols, skip, chain, hits)
|
||||
}
|
||||
// A blend's key objects first; its steps hit as the blend.
|
||||
NodeKind::Blend { .. } => {
|
||||
let whole = leaves_in(c, p, opt, symbols, skip, chain, hits);
|
||||
if whole && hits.len() < MAX_LEAVES_AT {
|
||||
leaf(hits, chain);
|
||||
}
|
||||
whole
|
||||
}
|
||||
_ => {
|
||||
leaf(hits, chain);
|
||||
true
|
||||
}
|
||||
};
|
||||
chain.pop();
|
||||
if !whole {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The most objects [`locked_objects_at`] lists.
|
||||
pub const MAX_LOCKED_AT: usize = 20;
|
||||
|
||||
@@ -834,7 +1016,18 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
|
||||
/// `editable_only` over the objects of layers and sublayers on a locked artboard, and over all of
|
||||
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
|
||||
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
|
||||
/// With [`HitOptions::unfilled_interiors`], a second walk looks inside the unfilled closed paths
|
||||
/// only when the first, without it, hits nothing.
|
||||
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let painted = hit_test_walk(doc, p, HitOptions { unfilled_interiors: false, ..opt }, skip, editable_only);
|
||||
if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline {
|
||||
return painted;
|
||||
}
|
||||
hit_test_walk(doc, p, opt, skip, editable_only)
|
||||
}
|
||||
|
||||
/// One walk of [`hit_test_skipping`], with `opt` as given.
|
||||
fn hit_test_walk(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
|
||||
let _walk = ArtWalk::open();
|
||||
let finish = |mut h: Hit| {
|
||||
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
|
||||
@@ -1378,7 +1571,10 @@ fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: &
|
||||
return false;
|
||||
}
|
||||
}
|
||||
hit_order(n, children, p).any(|i| children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept)))
|
||||
hit_order(n, children, p).any(|i| {
|
||||
let _mask = (i == 0 && n.clips()).then(InMask::set);
|
||||
children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept))
|
||||
})
|
||||
}
|
||||
_ => hit_leaf(n, p, opt, symbols).is_some_and(|kind| accept(n.id, kind)),
|
||||
}
|
||||
@@ -1417,6 +1613,15 @@ fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64)
|
||||
let decoration_sq = decoration_reach * decoration_reach;
|
||||
let mut near_decoration = false;
|
||||
for sp in &path.subpaths {
|
||||
// A closed lone anchor has no segment, and a cap can draw a dot on it: the full check
|
||||
// decides a click near it.
|
||||
if sp.closed
|
||||
&& sp.segment_count() == 0
|
||||
&& let Some(a) = sp.anchors.first()
|
||||
&& (a.p - p).hypot2() <= radius_sq.max(decoration_sq)
|
||||
{
|
||||
near_decoration = true;
|
||||
}
|
||||
for i in 0..sp.segment_count() {
|
||||
let c = sp.segment(i);
|
||||
if decoration_reach > 0.0 && !near_decoration && ([c.p0, c.p3].iter().any(|q| (*q - p).hypot2() <= decoration_sq)) {
|
||||
@@ -1467,6 +1672,8 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => {
|
||||
let has_fill = n.appearance.has_visible_fill();
|
||||
let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed) && takes_interior(n, opt);
|
||||
let inside = || (interior && fill_contains(&closed_subpaths_at([path], p), *rule, p)).then_some(HitKind::Fill);
|
||||
if opt.outline
|
||||
&& let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0)
|
||||
{
|
||||
@@ -1501,7 +1708,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
return Some(HitKind::Stroke);
|
||||
}
|
||||
if !near_decoration {
|
||||
return None;
|
||||
return inside();
|
||||
}
|
||||
}
|
||||
let bp = path.to_bezpath();
|
||||
@@ -1511,7 +1718,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) {
|
||||
return Some(HitKind::Fill);
|
||||
}
|
||||
None
|
||||
inside()
|
||||
}
|
||||
NodeKind::Compound { children, rule } => {
|
||||
// Painted strokes follow the whole compound path (alignment, dashes, width profiles):
|
||||
@@ -1529,7 +1736,11 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol {
|
||||
return Some(HitKind::Outline);
|
||||
}
|
||||
(!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill)
|
||||
if n.appearance.has_visible_fill() {
|
||||
return (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill);
|
||||
}
|
||||
let closed = || closed_subpaths_at(children.iter().filter_map(|m| m.path_data()), p);
|
||||
(takes_interior(n, opt) && fill_contains(&closed(), *rule, p)).then_some(HitKind::Fill)
|
||||
}
|
||||
// The type path lies within the bounds: they rule out the rest before it is measured.
|
||||
NodeKind::Text(t) if opt.type_path_only => {
|
||||
@@ -1601,6 +1812,30 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
|
||||
}
|
||||
}
|
||||
|
||||
/// Is path or compound path `n`, which has no visible fill, hit inside its closed subpaths
|
||||
/// ([`HitOptions::unfilled_interiors`])? Not a clipping path ([`InMask`]) or a guide.
|
||||
fn takes_interior(n: &Node, opt: HitOptions) -> bool {
|
||||
opt.unfilled_interiors
|
||||
&& !opt.outline
|
||||
&& !opt.path_only
|
||||
&& !IN_MASK.get()
|
||||
&& !matches!(n.kind, NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
/// The closed subpaths of `paths` whose control points' box holds `p`, as one path. A path outside
|
||||
/// that box winds zero times round `p`, so this path's fill holds `p` as all the closed subpaths'
|
||||
/// fill does. Open subpaths are left out: they bound no area.
|
||||
fn closed_subpaths_at<'a>(paths: impl IntoIterator<Item = &'a PathData>, p: Point) -> BezPath {
|
||||
let holds = |b: Rect| b.x0 <= p.x && p.x <= b.x1 && b.y0 <= p.y && p.y <= b.y1;
|
||||
let mut bp = BezPath::new();
|
||||
for pd in paths.into_iter().filter(|pd| pd.control_bounds().is_some_and(holds)) {
|
||||
for sp in pd.subpaths.iter().filter(|sp| sp.closed) {
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
}
|
||||
}
|
||||
bp
|
||||
}
|
||||
|
||||
/// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a
|
||||
/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a
|
||||
/// stroke along its shape, a fill inside it except with Selection by Path Only.
|
||||
@@ -1877,13 +2112,23 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
/// (blends, envelopes, repeats) are tested without those effects. `None` when `inst` is not a
|
||||
/// symbol instance or no editable object of its art is under `p`.
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
let _walk = ArtWalk::open();
|
||||
let walk = ArtWalk::open();
|
||||
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
let art = InstanceArt::drawn(doc, inst, outline)?;
|
||||
let symbols = doc.kept_symbol_boxes();
|
||||
let mut path = vec![];
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
let pick = |opt: HitOptions| {
|
||||
let mut path = vec![];
|
||||
let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true };
|
||||
find.find(&art.art, &mut path, None, outline).map(|_| path)
|
||||
};
|
||||
// As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit.
|
||||
pick(HitOptions { unfilled_interiors: false, ..opt }).or_else(|| {
|
||||
if !opt.unfilled_interiors || opt.path_only || outline {
|
||||
return None;
|
||||
}
|
||||
walk.restart();
|
||||
pick(opt)
|
||||
})
|
||||
}
|
||||
|
||||
/// The walk of a symbol instance's placed art that [`symbol_part_at`] and [`instance_art_hit`] make.
|
||||
|
||||
@@ -38,6 +38,168 @@ fn unfilled_interior_misses() {
|
||||
assert!(hit_test(&d, Point::new(50.5, 25.0), HitOptions::default()).is_some());
|
||||
}
|
||||
|
||||
/// The selection tools' options with unfilled closed paths hit inside.
|
||||
const INTERIORS: HitOptions = HitOptions { unfilled_interiors: true, ..SELECTING };
|
||||
|
||||
/// A path of `points` with a black stroke and no fill, inserted at the top of the first layer.
|
||||
fn stroked(d: &mut Document, points: &[(f64, f64)], closed: bool) -> NodeId {
|
||||
let l = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let pts: Vec<Point> = points.iter().map(|&(x, y)| Point::new(x, y)).collect();
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pts, closed));
|
||||
d.insert(Some(l), 99, Node::path(id, path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
const FRAME: [(f64, f64); 4] = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
|
||||
|
||||
#[test]
|
||||
fn an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let frame = stroked(&mut d, &FRAME, true);
|
||||
let at = |opt: HitOptions| hit_test(&d, Point::new(50.0, 50.0), opt).map(|h| h.leaf);
|
||||
assert_eq!(at(INTERIORS), Some(frame));
|
||||
assert_eq!(at(SELECTING), None, "without the option, the interior misses");
|
||||
assert_eq!(at(HitOptions { path_only: true, ..INTERIORS }), None, "Object Selection by Path Only");
|
||||
assert_eq!(at(HitOptions { outline: true, ..INTERIORS }), None, "Outline view");
|
||||
assert_eq!(objects_at(&d, Point::new(50.0, 50.0), INTERIORS, None), vec![frame]);
|
||||
assert!(objects_at(&d, Point::new(150.0, 50.0), INTERIORS, None).is_empty(), "outside it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_path_is_not_hit_inside() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
stroked(&mut d, &FRAME, false);
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 50.0), INTERIORS), None);
|
||||
}
|
||||
|
||||
/// What a click paints over comes first: an object drawn inside an unfilled frame above it is hit
|
||||
/// where it paints, and the frame elsewhere inside; Select Behind lists the frame after it.
|
||||
#[test]
|
||||
fn art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let dot = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::path(dot, shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), Appearance::default_art())).unwrap();
|
||||
let frame = stroked(&mut d, &FRAME, true);
|
||||
let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(&d, 50.0), Some(dot));
|
||||
assert_eq!(at(&d, 20.0), Some(frame));
|
||||
assert_eq!(objects_at(&d, Point::new(50.0, 50.0), INTERIORS, None), vec![dot, frame]);
|
||||
// The topmost of two unfilled frames is hit inside both.
|
||||
let inner = stroked(&mut d, &[(10.0, 10.0), (90.0, 10.0), (90.0, 90.0), (10.0, 90.0)], true);
|
||||
assert_eq!(at(&d, 20.0), Some(inner));
|
||||
assert_eq!(at(&d, 5.0), Some(frame));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let (id, outer, hole) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let members = vec![ring(outer, Rect::new(0.0, 0.0, 100.0, 100.0)), ring(hole, Rect::new(30.0, 30.0, 70.0, 70.0))];
|
||||
let mut compound = Node::new(id, NodeKind::Compound { children: members, rule: FillRule::EvenOdd });
|
||||
compound.appearance = look().into();
|
||||
d.insert(Some(l), 0, compound).unwrap();
|
||||
let at = |x: f64| hit_test(&d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(15.0), Some(id));
|
||||
assert_eq!(at(50.0), None, "in the hole");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_and_clipping_paths_are_not_hit_inside() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let guide = stroked(&mut d, &FRAME, true);
|
||||
if let Some(NodeKind::Path { guide: g, .. }) = d.node_mut(guide).map(|n| &mut n.kind) {
|
||||
*g = true;
|
||||
}
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 50.0), INTERIORS), None, "a guide");
|
||||
// A clip group whose art covers only part of its unfilled clipping path.
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (g, clip, art) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let mut mask = Node::path(clip, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::None, Paint::None, 0.0));
|
||||
if let NodeKind::Path { clipping, .. } = &mut mask.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let picture = Node::path(art, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 100.0)), Appearance::default_art());
|
||||
d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(mask), Arc::new(picture)], clip: true })).unwrap();
|
||||
let at = |x: f64| hit_test(&d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf);
|
||||
assert_eq!(at(25.0), Some(art));
|
||||
assert_eq!(at(75.0), None, "inside the mask where no art paints");
|
||||
assert!(objects_at(&d, Point::new(75.0, 50.0), INTERIORS, None).is_empty());
|
||||
}
|
||||
|
||||
/// A repeat's copies of an unfilled frame are hit inside, and the copies of a clip group's unfilled
|
||||
/// compound clipping path are not.
|
||||
#[test]
|
||||
fn a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks() {
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let kind = crate::pattern::RepeatKind::Grid {
|
||||
h_spacing: 20.0,
|
||||
v_spacing: 20.0,
|
||||
rows: 1,
|
||||
cols: 2,
|
||||
grid_type: crate::pattern::TileType::Grid,
|
||||
flip_rows: false,
|
||||
flip_cols: false,
|
||||
};
|
||||
let repeat = |d: &mut Document, source: Node| {
|
||||
let r = d.alloc_id();
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, Node::new(r, NodeKind::Repeat(crate::pattern::RepeatSpec { kind: kind.clone(), source: vec![Arc::new(source)] })))
|
||||
.unwrap();
|
||||
r
|
||||
};
|
||||
// Copies at 0..40 and 60..100.
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), look());
|
||||
let r = repeat(&mut d, frame);
|
||||
assert_eq!(hit_test(&d, Point::new(80.0, 20.0), INTERIORS).map(|h| h.leaf), Some(r));
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 20.0), INTERIORS), None, "between the copies");
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let members = vec![ring(d.alloc_id(), Rect::new(0.0, 0.0, 40.0, 40.0)), ring(d.alloc_id(), Rect::new(5.0, 5.0, 35.0, 35.0))];
|
||||
let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
mask.appearance = look().into();
|
||||
let picture = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 40.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(picture)]);
|
||||
clip.set_clips(true);
|
||||
let r = repeat(&mut d, clip);
|
||||
assert_eq!(hit_test(&d, Point::new(65.0, 20.0), INTERIORS).map(|h| h.leaf), Some(r), "on the clipped art");
|
||||
assert_eq!(hit_test(&d, Point::new(80.0, 20.0), INTERIORS), None, "inside the mask where no art paints");
|
||||
}
|
||||
|
||||
/// Direct Selection in a dynamic symbol's art picks parts as a click on the document does: what
|
||||
/// paints first, then an unfilled frame inside; an unfilled compound clipping path by its outline.
|
||||
#[test]
|
||||
fn symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), Appearance::default_art());
|
||||
let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look());
|
||||
let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look()));
|
||||
let (mask_id, a, b) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let members = vec![ring(a, Rect::new(150.0, 0.0, 250.0, 100.0)), ring(b, Rect::new(160.0, 10.0, 240.0, 90.0))];
|
||||
let mut mask = Node::new(mask_id, NodeKind::Compound { children: members, rule: FillRule::NonZero });
|
||||
mask.appearance = look().into();
|
||||
let picture = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(150.0, 0.0, 180.0, 100.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(picture)]);
|
||||
clip.set_clips(true);
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(dot), Arc::new(frame), Arc::new(clip)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Framed".into(), art: Arc::new(root) });
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Framed".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
let n = d.node(inst).unwrap();
|
||||
let at = |x: f64| symbol_part_at(&d, n, Point::new(x, 50.0), INTERIORS);
|
||||
assert_eq!(at(50.0), Some(vec![0]), "the dot under the frame");
|
||||
assert_eq!(at(20.0), Some(vec![1]), "inside the frame");
|
||||
assert_eq!(at(220.0), None, "inside the clipping path where no art paints");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_plain_stroke_hits_its_middle_and_curved_end() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
@@ -1464,6 +1626,7 @@ const SELECTING: HitOptions = HitOptions {
|
||||
clip_outlines: true,
|
||||
area_type_interior: false,
|
||||
ignore_layer_preview: false,
|
||||
unfilled_interiors: false,
|
||||
scope: None,
|
||||
};
|
||||
|
||||
@@ -1992,10 +2155,58 @@ fn objects_at_matches_repeated_hits_on_random_documents() {
|
||||
let p = Point::new(f64::from(next(120)), f64::from(next(120)));
|
||||
let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() };
|
||||
assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None), "round {round}, {p:?}, {opt:?}");
|
||||
assert_eq!(leaf_chains(leaves_at(&d, p, opt)), leaf_chains(leaves_at_repeated(&d, p, opt)), "leaves: round {round}, {p:?}, {opt:?}");
|
||||
// Isolated in a group of the document, now and then.
|
||||
let groups: Vec<NodeId> =
|
||||
d.layers[0].children().into_iter().flatten().filter(|n| n.is_container() && !n.is_layer()).map(|n| n.id).collect();
|
||||
if let Some(&g) = groups.first().filter(|_| next(3) == 0) {
|
||||
let opt = HitOptions { scope: Some(g), ..opt };
|
||||
assert_eq!(leaf_chains(leaves_at(&d, p, opt)), leaf_chains(leaves_at_repeated(&d, p, opt)), "isolated: round {round}, {p:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A hit's leaf, ancestry, kind, layer count and edited envelope.
|
||||
type LeafChain = (NodeId, Vec<NodeId>, HitKind, usize, Option<NodeId>);
|
||||
|
||||
/// Each hit's [`LeafChain`], to compare two lists.
|
||||
fn leaf_chains(hits: Vec<Hit>) -> Vec<LeafChain> {
|
||||
hits.into_iter().map(|h| (h.leaf, h.ancestry, h.kind, h.layers, h.contents_of)).collect()
|
||||
}
|
||||
|
||||
/// Select Behind steps through the members of groups one by one, front to back, in one traversal
|
||||
/// for a large stack, as the hit test repeated over what is left finds them.
|
||||
#[test]
|
||||
fn leaves_at_lists_group_members_one_by_one() {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let layer = d.layers[0].id;
|
||||
let square = |d: &mut Document| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art());
|
||||
let below = square(&mut d);
|
||||
let below_id = below.id;
|
||||
d.insert(Some(layer), usize::MAX, below).unwrap();
|
||||
let members: Vec<Node> = (0..300).map(|_| square(&mut d)).collect();
|
||||
let mut ids: Vec<NodeId> = members.iter().map(|n| n.id).collect();
|
||||
let g = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap();
|
||||
ids.reverse();
|
||||
ids.push(below_id);
|
||||
let p = Point::new(25.0, 25.0);
|
||||
let hits = leaves_at(&d, p, HitOptions::default());
|
||||
assert_eq!(hits.len(), MAX_LEAVES_AT, "the list stops at its limit");
|
||||
assert_eq!(hits.iter().map(|h| h.leaf).collect::<Vec<_>>(), ids[..MAX_LEAVES_AT], "the group's members, topmost first");
|
||||
assert!(hits.iter().all(|h| h.ancestry.contains(&g)));
|
||||
assert_eq!(leaf_chains(hits), leaf_chains(leaves_at_repeated(&d, p, HitOptions::default())));
|
||||
// Hidden past the limit, the object below the group comes after the members that are left.
|
||||
for id in &ids[3..300] {
|
||||
d.node_mut(*id).unwrap().visible = false;
|
||||
}
|
||||
let shown: Vec<NodeId> = leaves_at(&d, p, HitOptions::default()).iter().map(|h| h.leaf).collect();
|
||||
assert_eq!(shown, [ids[0], ids[1], ids[2], below_id]);
|
||||
let isolated = leaves_at(&d, p, HitOptions { scope: Some(g), ..Default::default() });
|
||||
assert!(!isolated.iter().any(|h| h.leaf == below_id), "isolated: only the group's members");
|
||||
}
|
||||
|
||||
/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the
|
||||
/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times.
|
||||
fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
|
||||
@@ -2322,6 +2533,40 @@ fn select_behind_keeps_one_art_limit_when_it_falls_back() {
|
||||
assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked");
|
||||
}
|
||||
|
||||
/// [`leaves_at`] falls back to repeated hit tests at a clip group, after the hits its single
|
||||
/// traversal found above it: an instance hit by its art, with the limit of symbol art then used
|
||||
/// up, stays in the list.
|
||||
#[test]
|
||||
fn leaves_at_keeps_the_hits_above_a_clip_group_it_falls_back_at() {
|
||||
let p = Point::new(150.0, 50.0);
|
||||
let mut d = Document::new(600.0, 400.0);
|
||||
clipped_symbol(&mut d, false);
|
||||
// A clip group at the bottom of the layer, its art under (150, 50).
|
||||
let square = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art()));
|
||||
let (mask, art) = (d.alloc_id(), d.alloc_id());
|
||||
let mut clip_group = Node::group(d.alloc_id(), vec![square(mask), square(art)]);
|
||||
clip_group.set_clips(true);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, clip_group).unwrap();
|
||||
let (mut shown_mask, shown_art) = half_clipped(&mut d);
|
||||
shown_mask.appearance.effects.push(test_move());
|
||||
let mut shown = Node::group(d.alloc_id(), vec![Arc::new(shown_mask), Arc::new(shown_art)]);
|
||||
shown.set_clips(true);
|
||||
group_symbol(&mut d, "Shown", vec![Arc::new(shown)]);
|
||||
let hit = instance_of(&mut d, "Shown");
|
||||
let hit_id = hit.id;
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap();
|
||||
for _ in 0..32 {
|
||||
let inst = instance_of(&mut d, "Clipped");
|
||||
d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap();
|
||||
}
|
||||
let (hits, _, arts) = with_art_limit(100, || leaves_at(&d, p, HitOptions::default()));
|
||||
let leaves: Vec<NodeId> = hits.iter().map(|h| h.leaf).collect();
|
||||
assert_eq!(leaves.first(), Some(&hit_id), "hit before the fallback: {leaves:?}");
|
||||
assert!(leaves.contains(&art), "the clipped art after it: {leaves:?}");
|
||||
assert!(arts <= 34, "{arts} instances' art walked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_and_hidden_skip() {
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
|
||||
@@ -82,6 +82,7 @@ impl Paths {
|
||||
/// isn't in the table or it, or a node it is in, was removed.
|
||||
pub(crate) fn get(&self, id: &NodeId) -> Option<Option<Vec<usize>>> {
|
||||
let e = (*self.table.ids.get(id)?)?;
|
||||
note_path_copy();
|
||||
let mut path = Vec::new();
|
||||
let mut cur = e;
|
||||
// Each step goes to a parent entry, made before its children: at most `at.len()` steps.
|
||||
@@ -96,6 +97,29 @@ impl Paths {
|
||||
}
|
||||
Some(None)
|
||||
}
|
||||
/// The node with `id` in `layers` at the place the table has for it, found without copying its index path: `None`
|
||||
/// when the table does not have one place for `id`, its path is deeper than [`NODE_IN_DEPTH`], or the node there
|
||||
/// does not have the id (the tree changed). The caller then looks it up as [`crate::Document::index_path`] does.
|
||||
pub(crate) fn node_in<'a>(&self, layers: &'a [Arc<Node>], id: NodeId) -> Option<&'a Node> {
|
||||
let mut cur = (*self.table.ids.get(&id)?)?;
|
||||
let mut steps = [0u32; NODE_IN_DEPTH];
|
||||
let mut depth = 0;
|
||||
loop {
|
||||
let &(parent, i) = self.table.at.get(cur as usize)?;
|
||||
*steps.get_mut(depth)? = self.shifted(parent, i)?;
|
||||
depth += 1;
|
||||
if parent == u32::MAX {
|
||||
break;
|
||||
}
|
||||
cur = parent;
|
||||
}
|
||||
let mut path = steps[..depth].iter().rev();
|
||||
let mut node: &Node = layers.get(*path.next()? as usize)?;
|
||||
for &i in path {
|
||||
node = node.children()?.get(i as usize)?;
|
||||
}
|
||||
(node.id == id).then_some(node)
|
||||
}
|
||||
/// Where the table has `id` as it was built: its parent's entry and its index among its
|
||||
/// siblings then; `None` when the id isn't in the table or appears more than once.
|
||||
pub(crate) fn table_place(&self, id: &NodeId) -> Option<(u32, u32)> {
|
||||
@@ -170,6 +194,25 @@ pub(crate) fn note_path_lookup() {
|
||||
PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// The deepest index path [`Paths::node_in`] follows without copying it.
|
||||
const NODE_IN_DEPTH: usize = 32;
|
||||
|
||||
thread_local! {
|
||||
/// [`path_copies`] of this thread.
|
||||
static PATH_COPIES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many index paths the lookup cache has copied out on this thread, one for each [`crate::Document::index_path`]
|
||||
/// that it answered. [`crate::Document::node`] reads the node from the cache without one.
|
||||
pub fn path_copies() -> u64 {
|
||||
PATH_COPIES.get()
|
||||
}
|
||||
|
||||
/// Adds one to [`path_copies`].
|
||||
fn note_path_copy() {
|
||||
PATH_COPIES.set(PATH_COPIES.get().saturating_add(1));
|
||||
}
|
||||
|
||||
/// The cache, shared by clones of a document (each checks every path it uses against its own tree),
|
||||
/// the lookups that missed it, and the nodes removed from the tree since it was built.
|
||||
#[derive(Default)]
|
||||
|
||||
@@ -18,12 +18,13 @@ pub mod decode;
|
||||
pub mod depth;
|
||||
pub mod dimension;
|
||||
pub mod flare;
|
||||
pub mod generated;
|
||||
pub mod graph;
|
||||
mod halftone_radii;
|
||||
pub mod hit;
|
||||
mod id_index;
|
||||
pub mod image_quad;
|
||||
pub use id_index::{path_lookups, tree_walks};
|
||||
pub use id_index::{path_copies, path_lookups, tree_walks};
|
||||
pub mod inks;
|
||||
mod inline;
|
||||
pub mod intertwine;
|
||||
@@ -116,7 +117,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 +169,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)]
|
||||
|
||||
@@ -54,8 +54,8 @@ pub use blend_spec::{BlendDefaults, BlendEase, BlendEaseType, BlendOrientation,
|
||||
use blend_spec::{blend_color_shift, blend_ramp};
|
||||
pub use envelope::{
|
||||
EnvelopeKind, EnvelopeMap, EnvelopeOptions, H_DOWN, H_LEFT, H_RIGHT, H_UP, PreserveShape, TypeInk, envelope_bounds, envelope_content_bounds,
|
||||
envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of,
|
||||
envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid,
|
||||
envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_margin_lengths,
|
||||
envelope_of, envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid,
|
||||
};
|
||||
pub use expand::{
|
||||
Hooks, MAX_GENERATED, Outliner, PatternTiles, affine_near, expand_deep, expand_deep_hooks, expand_live, expand_live_hooks, expand_live_with,
|
||||
@@ -975,6 +975,17 @@ mod tests {
|
||||
assert_eq!(margin(&turned, frame).map(|m| (m * 1000.0).round()), before.map(|m| (m * 1000.0).round()));
|
||||
// Margins an `f32` can't hold are none.
|
||||
assert_eq!(envelope_stroke_margin(Rect::new(-5e41, 0.0, 100.0, 100.0), Rect::new(0.0, 0.0, 100.0, 100.0)), None);
|
||||
// A straight line along an axis has margins across it, as shares of its length, and maps
|
||||
// from its box with them; a point has none.
|
||||
let line =
|
||||
Node::path(NodeId(4), vectorcraft_geom::shapes::line(Point::new(10.0, 20.0), Point::new(110.0, 20.0)), crate::Appearance::default_art());
|
||||
let line = [Arc::new(line)];
|
||||
let stroked_line = Rect::new(10.0, 15.0, 110.0, 25.0);
|
||||
let across = envelope_stroke_margin(stroked_line, Rect::new(10.0, 20.0, 110.0, 20.0)).unwrap();
|
||||
assert!(across[0] > 0.0 && across[1] > 0.0 && across[2] == 0.0 && across[3] == 0.0, "{across:?}");
|
||||
let from = src(&line, Affine::IDENTITY, EnvelopeOptions { bounds_margin: across, ..on });
|
||||
assert!((from.y0 - 15.0).abs() + (from.y1 - 25.0).abs() + (from.x0 - 10.0).abs() + (from.x1 - 110.0).abs() < 1e-4, "{from:?}");
|
||||
assert_eq!(envelope_stroke_margin(stroked_line, Rect::new(60.0, 20.0, 60.0, 20.0)), None);
|
||||
|
||||
assert!(serde_json::to_value(EnvelopeOptions::default()).unwrap().get("boundsMargin").is_none());
|
||||
let saved = serde_json::to_value(on).unwrap();
|
||||
|
||||
@@ -95,7 +95,9 @@ pub struct EnvelopeOptions {
|
||||
/// Distort Pattern Fills (with Distort Appearance): pattern tiles bend with the art.
|
||||
pub distort_pattern_fills: bool,
|
||||
/// With Distort Appearance, how far the box the content maps from reaches past its geometric
|
||||
/// bounds at the top, bottom, left and right, as shares of their height and width. An envelope
|
||||
/// bounds at the top, bottom, left and right, as shares of their height and width; when the
|
||||
/// height or width is shorter than 1e-6 pt, the margins along that side are shares of the other side
|
||||
/// ([`envelope_margin_lengths`]). An envelope
|
||||
/// opened from a `.ai` whose saved size includes its strokes has these margins. New envelopes
|
||||
/// have none. Leaving Edit Contents measures them again when the strokes reach differently.
|
||||
#[serde(skip_serializing_if = "crate::skip::is_default")]
|
||||
@@ -140,7 +142,8 @@ impl EnvelopeOptions {
|
||||
if !self.distort_appearance || !self.bounds_margin.iter().all(|m| m.is_finite() && *m >= 0.0) {
|
||||
return r;
|
||||
}
|
||||
let grown = crate::marks::outset(r, [top * r.height(), bottom * r.height(), left * r.width(), right * r.width()]);
|
||||
let Some([v, _, h, _]) = envelope_margin_lengths(r) else { return r };
|
||||
let grown = crate::marks::outset(r, [top * v, bottom * v, left * h, right * h]);
|
||||
if grown.is_finite() { grown } else { r }
|
||||
}
|
||||
}
|
||||
@@ -382,26 +385,53 @@ fn find_type(n: &Node, typed: &mut std::collections::HashSet<usize>) -> bool {
|
||||
/// those axes. A character's strokes reach as far past its glyphs as past the laid-out box. Type
|
||||
/// that draws nothing has its laid-out box with `blank_type_box`, and no box without it.
|
||||
fn content_box(n: &Arc<Node>, stroked: bool, to: Affine, blank_type_box: bool) -> Option<Rect> {
|
||||
let mut typed = std::collections::HashSet::new();
|
||||
find_type(n, &mut typed);
|
||||
let mut typed = Typed::default();
|
||||
find_type(n, &mut typed.holds);
|
||||
content_box_in(n, stroked, to, &typed, blank_type_box)
|
||||
}
|
||||
|
||||
/// [`content_box`], with the addresses of the objects in `n` that hold type ([`find_type`]).
|
||||
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collections::HashSet<usize>, blank_type_box: bool) -> Option<Rect> {
|
||||
// `n` in the axes of `to`.
|
||||
let moved = || {
|
||||
if to == Affine::IDENTITY {
|
||||
return std::borrow::Cow::Borrowed(&**n);
|
||||
}
|
||||
let mut m = (**n).clone();
|
||||
m.transform(to, true);
|
||||
std::borrow::Cow::Owned(m)
|
||||
};
|
||||
let own = |m: &Node| if stroked { m.visual_bounds() } else { m.geometric_bounds() };
|
||||
if !typed.contains(&(Arc::as_ptr(n) as usize)) {
|
||||
return own(&moved());
|
||||
/// The objects in an envelope's contents that hold type ([`find_type`]), by address, and the
|
||||
/// boxes [`content_box_in`] has measured for them with their strokes, so that measuring a
|
||||
/// container's own strokes along its members ([`container_strokes_in`]) does not measure them
|
||||
/// again.
|
||||
#[derive(Default)]
|
||||
struct Typed {
|
||||
holds: std::collections::HashSet<usize>,
|
||||
stroked: std::cell::RefCell<std::collections::HashMap<usize, Option<Rect>>>,
|
||||
}
|
||||
|
||||
/// `n` in the axes of `to`, with its strokes scaled as [`Node::transform`] scales them.
|
||||
fn moved_into(n: &Node, to: Affine) -> std::borrow::Cow<'_, Node> {
|
||||
if to == Affine::IDENTITY {
|
||||
return std::borrow::Cow::Borrowed(n);
|
||||
}
|
||||
let mut m = n.clone();
|
||||
m.transform(to, true);
|
||||
std::borrow::Cow::Owned(m)
|
||||
}
|
||||
|
||||
/// [`content_box`], with the objects in `n` that hold type ([`Typed`]).
|
||||
fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &Typed, blank_type_box: bool) -> Option<Rect> {
|
||||
let key = Arc::as_ptr(n) as usize;
|
||||
if !typed.holds.contains(&key) {
|
||||
let m = moved_into(n, to);
|
||||
return if stroked { m.visual_bounds() } else { m.geometric_bounds() };
|
||||
}
|
||||
if !stroked {
|
||||
return typed_box_in(n, false, to, typed, blank_type_box);
|
||||
}
|
||||
if let Some(b) = typed.stroked.borrow().get(&key) {
|
||||
return *b;
|
||||
}
|
||||
let b = typed_box_in(n, true, to, typed, blank_type_box);
|
||||
typed.stroked.borrow_mut().insert(key, b);
|
||||
b
|
||||
}
|
||||
|
||||
/// [`content_box_in`] of `n`, which holds type.
|
||||
fn typed_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &Typed, blank_type_box: bool) -> Option<Rect> {
|
||||
let moved = || moved_into(n, to);
|
||||
let own = |m: &Node| if stroked { m.visual_bounds() } else { m.geometric_bounds() };
|
||||
match &n.kind {
|
||||
NodeKind::Text(t) => {
|
||||
// Type in perspective: its outlines as its projection draws them.
|
||||
@@ -442,11 +472,16 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
|
||||
let members = n.editing_children().iter();
|
||||
if stroked {
|
||||
// The container's own strokes, scaled by `to` as `Node::transform` scales them,
|
||||
// without copying its members.
|
||||
// measured along its members as in `Node::visual_bounds`.
|
||||
let mut own_strokes = Node::new(n.id, NodeKind::Group { children: Vec::new(), clip: false });
|
||||
own_strokes.appearance = n.appearance.clone();
|
||||
own_strokes.transform(to, true);
|
||||
own_strokes.visual_of_members(members.map(|c| content_box_in(c, true, to, typed, blank_type_box)))
|
||||
let painted = own_strokes.appearance.painted_strokes().next().is_some();
|
||||
members.fold(None, |acc, c| {
|
||||
let b = content_box_in(c, true, to, typed, blank_type_box);
|
||||
let own = if painted { container_strokes_in(c, &own_strokes.appearance, Some(b), to, typed, blank_type_box) } else { None };
|
||||
vectorcraft_geom::union_opt(vectorcraft_geom::union_opt(acc, b), own)
|
||||
})
|
||||
} else {
|
||||
members
|
||||
.filter(|c| c.visible || !layer)
|
||||
@@ -457,19 +492,66 @@ fn content_box_in(n: &Arc<Node>, stroked: bool, to: Affine, typed: &std::collect
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`. `None` for
|
||||
/// content with no width or no height, or for margins an `f32` can't hold.
|
||||
pub fn envelope_stroke_margin(stroked: Rect, plain: Rect) -> Option<[f32; 4]> {
|
||||
if plain.width() < 1e-6 || plain.height() < 1e-6 {
|
||||
/// The box the strokes of `appearance`, the appearance of a group or layer that holds `n` scaled
|
||||
/// by `to`, paint along `n` in the axes of `to`, as [`Node::painted_by_container`] measures them;
|
||||
/// `measured` is the box [`content_box_in`] gives `n` with its strokes, when known. Type, alone or
|
||||
/// in a clip group, has that box grown by the farthest the strokes can reach
|
||||
/// ([`crate::Appearance::outset`]); the strokes paint nothing round hidden members and guides.
|
||||
fn container_strokes_in(
|
||||
n: &Arc<Node>,
|
||||
appearance: &crate::Appearance,
|
||||
measured: Option<Option<Rect>>,
|
||||
to: Affine,
|
||||
typed: &Typed,
|
||||
blank_type_box: bool,
|
||||
) -> Option<Rect> {
|
||||
if !n.visible || n.is_guide() {
|
||||
return None;
|
||||
}
|
||||
let margin = [
|
||||
(plain.y0 - stroked.y0) / plain.height(),
|
||||
(stroked.y1 - plain.y1) / plain.height(),
|
||||
(plain.x0 - stroked.x0) / plain.width(),
|
||||
(stroked.x1 - plain.x1) / plain.width(),
|
||||
]
|
||||
.map(|m| m as f32);
|
||||
if !typed.holds.contains(&(Arc::as_ptr(n) as usize)) {
|
||||
if to == Affine::IDENTITY {
|
||||
return n.painted_by_container(appearance, None);
|
||||
}
|
||||
// Moved with its own strokes scaled, as `content_box_in` moves it, for a member measured
|
||||
// by its visual box.
|
||||
let mut m = (**n).clone();
|
||||
m.transform(to, true);
|
||||
return m.painted_by_container(appearance, None);
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { clip: false, .. } | NodeKind::Layer { clip: false, .. } if !n.is_compound_shape() => n
|
||||
.editing_children()
|
||||
.iter()
|
||||
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, container_strokes_in(c, appearance, None, to, typed, blank_type_box))),
|
||||
_ => {
|
||||
let o = appearance.outset();
|
||||
measured.unwrap_or_else(|| content_box_in(n, true, to, typed, blank_type_box)).map(|b| b.inflate(o, o))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lengths the top, bottom, left and right [`EnvelopeOptions::bounds_margin`] of content with
|
||||
/// geometric bounds `plain` are shares of: its height for the top and bottom and its width for the
|
||||
/// left and right. A side shorter than 1e-6 pt takes the other side's length, so a stroked straight
|
||||
/// line along an axis has margins across it. `None` when neither side has a length.
|
||||
pub fn envelope_margin_lengths(plain: Rect) -> Option<[f64; 4]> {
|
||||
let long = |l: f64| l.is_finite() && l >= 1e-6;
|
||||
let (h, w) = match (long(plain.height()), long(plain.width())) {
|
||||
(true, true) => (plain.height(), plain.width()),
|
||||
(false, true) => (plain.width(), plain.width()),
|
||||
(true, false) => (plain.height(), plain.height()),
|
||||
(false, false) => return None,
|
||||
};
|
||||
Some([h, h, w, w])
|
||||
}
|
||||
|
||||
/// The [`EnvelopeOptions::bounds_margin`] of content with bounds `stroked` and `plain`, as shares
|
||||
/// of [`envelope_margin_lengths`]. `None` for content with neither a width nor a height, or for
|
||||
/// margins an `f32` can't hold.
|
||||
pub fn envelope_stroke_margin(stroked: Rect, plain: Rect) -> Option<[f32; 4]> {
|
||||
let [v, _, h, _] = envelope_margin_lengths(plain)?;
|
||||
let margin =
|
||||
[(plain.y0 - stroked.y0) / v, (stroked.y1 - plain.y1) / v, (plain.x0 - stroked.x0) / h, (stroked.x1 - plain.x1) / h].map(|m| m as f32);
|
||||
margin.iter().all(|m| m.is_finite()).then_some(margin)
|
||||
}
|
||||
|
||||
@@ -869,6 +951,57 @@ mod tests {
|
||||
assert!(content_box(&nested, false, Affine::IDENTITY, true).is_some());
|
||||
}
|
||||
|
||||
/// A group of type and a square with its own 10 pt miter-joined stroke reaches 5 pt past the
|
||||
/// square in a scaled frame, as the group moved into the frame does ([`Node::visual_bounds`]),
|
||||
/// not the 50 pt a miter spike could reach. Round a clip group they reach that far past its
|
||||
/// box, with the clipping path's own stroke scaled into the frame, and in nested groups too.
|
||||
#[test]
|
||||
fn a_groups_own_miter_stroke_is_measured_along_its_members_with_type() {
|
||||
let paint = |fill, stroke, w| crate::Appearance::basic(fill, stroke, w);
|
||||
let path = |id, r: Rect| {
|
||||
let square = vectorcraft_geom::shapes::rectangle(r);
|
||||
Arc::new(Node::path(NodeId(id), square, paint(vectorcraft_color::Paint::solid(Color::BLACK), vectorcraft_color::Paint::None, 0.0)))
|
||||
};
|
||||
let text = type_node(1, "Type");
|
||||
let mut group = Node::group(NodeId(2), vec![text, path(3, Rect::new(100.0, 100.0, 200.0, 200.0))]);
|
||||
group.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 10.0).into();
|
||||
assert_eq!(group.appearance.outset(), 50.0, "a 10 pt miter-joined stroke can reach 50 pt");
|
||||
let group = Arc::new(group);
|
||||
let to = Affine::scale(0.5);
|
||||
let mut moved = (*group).clone();
|
||||
moved.transform(to, true);
|
||||
let want = moved.visual_bounds();
|
||||
// The square's lower right corner, 100 pt in the frame, with half the 5 pt scaled stroke.
|
||||
assert_eq!(want.map(|b| (b.x1, b.y1)), Some((102.5, 102.5)));
|
||||
assert_eq!(content_box(&group, true, to, true), want);
|
||||
// A clip group whose clipping path has a 40 pt stroke, which the group's own strokes grow
|
||||
// by their reach, measured with that stroke scaled into the frame.
|
||||
let mut clip = (*path(5, Rect::new(300.0, 300.0, 400.0, 400.0))).clone();
|
||||
clip.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 40.0).into();
|
||||
let clipped =
|
||||
Node::new(NodeId(4), NodeKind::Group { children: vec![Arc::new(clip), path(6, Rect::new(320.0, 320.0, 380.0, 380.0))], clip: true });
|
||||
let mut group = Node::group(NodeId(2), vec![type_node(1, "Type"), Arc::new(clipped)]);
|
||||
group.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 10.0).into();
|
||||
let group = Arc::new(group);
|
||||
let mut moved = (*group).clone();
|
||||
moved.transform(to, true);
|
||||
let want = moved.visual_bounds();
|
||||
// 200 pt in the frame, with half the 20 pt scaled clip stroke and the 25 pt scaled reach.
|
||||
assert_eq!(want.map(|b| (b.x1, b.y1)), Some((235.0, 235.0)));
|
||||
assert_eq!(content_box(&group, true, to, true), want);
|
||||
// Stroked groups of type nested in plain groups, each measured once.
|
||||
let mut nested = group;
|
||||
for i in 0..50 {
|
||||
let plain = Arc::new(Node::group(NodeId(100 + 2 * i), vec![nested]));
|
||||
let mut stroked = Node::group(NodeId(101 + 2 * i), vec![type_node(1, "Type"), plain]);
|
||||
stroked.appearance = paint(vectorcraft_color::Paint::None, vectorcraft_color::Paint::solid(Color::BLACK), 10.0).into();
|
||||
nested = Arc::new(stroked);
|
||||
}
|
||||
let mut moved = (*nested).clone();
|
||||
moved.transform(to, true);
|
||||
assert_eq!(content_box(&nested, true, to, true), moved.visual_bounds());
|
||||
}
|
||||
|
||||
/// A warp envelope of `style` at `bend` with map `version` around a 200×100 rectangle at
|
||||
/// (100, 50).
|
||||
fn warp_node(style: &str, bend: f64, h: f64, version: u32) -> Node {
|
||||
|
||||