Merge remote-tracking branch 'upstream/main' into cursor/properties-quick-actions-groups
# Conflicts: # docs/gaps.md # docs/roadmap.md # docs/target-app-parity.md # docs/ui-parity.md Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
No files matched your search
@@ -0,0 +1,16 @@
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
|
||||
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
|
||||
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
|
||||
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
|
||||
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
|
||||
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
|
||||
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
|
||||
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
|
||||
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
|
||||
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
|
||||
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
|
||||
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
|
||||
ga/qCA==
|
||||
=3wGQ
|
||||
-----END PGP PUBLIC KEY BLOCK-----
|
||||
@@ -2,13 +2,13 @@
|
||||
"schema": "craft-nightly-release-policy/v3",
|
||||
"repository": "storytold/vectorcraft",
|
||||
"repository_id": 1398097510,
|
||||
"producer_workflow_id": null,
|
||||
"producer_workflow_id": 430275079,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
|
||||
"release_branch": "release",
|
||||
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
"dylanmtaylor",
|
||||
@@ -79,7 +79,14 @@
|
||||
"issue_types": [
|
||||
"VULNERABILITY"
|
||||
],
|
||||
"accepted_conditions": [],
|
||||
"accepted_conditions": [
|
||||
{
|
||||
"metric": "new_security_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1",
|
||||
"maximum": "5"
|
||||
}
|
||||
],
|
||||
"required_conditions": [
|
||||
{
|
||||
"metric": "new_reliability_rating",
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
name: Dispatch release-ref nightly
|
||||
|
||||
# Transport only, never authorization. No checkout, payload parsing or release environment.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [VectorCraft unsigned nightly]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
|
||||
if: >-
|
||||
false && github.repository == 'storytold/vectorcraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Dispatch only the exact completed producer run and attempt
|
||||
shell: python
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise RuntimeError(message)
|
||||
|
||||
# These filters reduce noise; the protected signer-branch validator repeats admission
|
||||
# against authenticated API metadata and required attestation/quality evidence.
|
||||
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/vectorcraft', 'wrong repository')
|
||||
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
|
||||
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
|
||||
event = json.load(stream)
|
||||
require(event.get('action') == 'completed', 'producer is not complete')
|
||||
require(event.get('repository', {}).get('full_name') == 'storytold/vectorcraft', 'wrong event repository')
|
||||
producer = event.get('workflow_run', {})
|
||||
require(producer.get('head_repository', {}).get('full_name') == 'storytold/vectorcraft', 'foreign producer')
|
||||
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
|
||||
require(producer.get('head_branch') == 'main', 'wrong producer branch')
|
||||
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
|
||||
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
|
||||
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
|
||||
run_id, attempt = producer.get('id'), producer.get('run_attempt')
|
||||
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
|
||||
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
|
||||
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
|
||||
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
|
||||
}}).encode('utf-8')
|
||||
request = urllib.request.Request(
|
||||
'https://api.github.com/repos/storytold/vectorcraft/actions/workflows/nightly-sign.yml/dispatches',
|
||||
data=body, method='POST', headers={
|
||||
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'User-Agent': 'vectorcraft-nightly-dispatch'
|
||||
})
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise RuntimeError('dispatch redirects are forbidden')
|
||||
# One bounded request, no retry: duplicate transport is not publication authority.
|
||||
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
|
||||
require(response.status == 204, 'dispatch was not accepted')
|
||||
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
|
||||
@@ -1,7 +1,8 @@
|
||||
name: VectorCraft release-ref nightly signer
|
||||
|
||||
# Enabled for supervised manual dispatch on release. Main/release contents must match.
|
||||
# A reusable callee does not change context; this must be a real top-level release dispatch.
|
||||
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
|
||||
# fast-forwards to reviewed main commits (never the stable release branch).
|
||||
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
@@ -22,21 +23,23 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
release:
|
||||
# Actual context guards: official repository, manual dispatch, real release branch.
|
||||
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
|
||||
if: >-
|
||||
github.repository == 'storytold/vectorcraft' &&
|
||||
github.event_name == 'workflow_dispatch' &&
|
||||
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
|
||||
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
|
||||
permissions:
|
||||
contents: write
|
||||
actions: read
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
with:
|
||||
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
app-name: vectorcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the existing release environment and export keys in its signing step.
|
||||
# callee job may bind the release environment and export its keys; that environment must
|
||||
# admit nightly-signer alongside release before the first dispatch.
|
||||
@@ -22,13 +22,13 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
with:
|
||||
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
app-name: vectorcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
|
||||
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
|
||||
# Linux/macOS signer (#342).
|
||||
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
|
||||
# #369 and #364).
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
@@ -16,6 +16,15 @@
|
||||
| `crates/text/patterns/hyph-or.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-or.tex | MIT (selected option) | Unmodified; full license in file |
|
||||
| `crates/text/patterns/hyph-as.tex` | Santhosh Thottingal | https://github.com/hyphenation/tex-hyphen/blob/5684c0f51c0b81133db2efbe60a408b4155a3ff5/hyph-utf8/tex/generic/hyph-utf8/patterns/tex/hyph-as.tex | MIT (selected option) | Unmodified; full license in file |
|
||||
|
||||
## Printing-condition characterization data
|
||||
|
||||
Fogra's terms (https://fogra.org/en/downloads/work-tools/characterisation-data): "Free use and redistribution of the Fogra characterisation data is permitted, including redistribution as part of commercial and non-commercial software, provided that the data are distributed unmodified and Fogra is identified as the source. The designation FOGRAxx may be used solely to identify the respective reference data. Such use does not imply certification, approval or endorsement by Fogra." VectorCraft computes its Coated CMYK (FOGRA51) and Uncoated CMYK (FOGRA52) working spaces from these files at run time; the files themselves are not changed.
|
||||
|
||||
| Asset | Author | Source | Licence | Notes |
|
||||
|---|---|---|---|---|
|
||||
| `crates/color/data/FOGRA51.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5`, checked by a test) |
|
||||
| `crates/color/data/FOGRA52.txt` | Fogra Forschungsgesellschaft Druck e.V. (www.fogra.org) | https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip | Fogra characterization data terms (above): redistribution of the unmodified data with Fogra named as the source | Unmodified, byte for byte (SHA-256 `be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6`, checked by a test) |
|
||||
|
||||
Every non-code asset in this repository (icons, images, fonts, example art, colour profiles, presets) is listed here with its author, source and licence. `cargo xtask assets` (part of `cargo xtask ci`) fails if an asset file is missing from this table.
|
||||
|
||||
**Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
|
||||
@@ -141,6 +150,8 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-arrow-down.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-arrow-extend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-arrow-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Selection and Direct Selection arrows' fill, painted black or white under their outline |
|
||||
| `assets/icons/dc-arrow-left.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-arrow-right.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-arrow-tip.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-arrow-up.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-artboard.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
@@ -213,6 +224,8 @@ Generated-in-code art is original and has no file to list. This covers the defau
|
||||
| `assets/icons/dc-graphic-styles.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-grid-view.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-group-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-guide-horizontal.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a ruler down the left with a line across) | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-guide-vertical.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a ruler along the top with a line down) | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-help.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a question mark in a circle) | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-join-bevel.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
| `assets/icons/dc-join-miter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
|
||||
|
||||
@@ -123,10 +123,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cipher 0.4.4",
|
||||
"cpufeatures 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aes"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1"
|
||||
dependencies = [
|
||||
"cipher 0.5.2",
|
||||
"cpubits",
|
||||
"cpufeatures 0.3.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.12"
|
||||
@@ -247,6 +258,17 @@ version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "apple-native-keyring-store"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02e465454e78fda6f7cd9dab7eb47518ca28c59b1bc392ca865af61452741dd3"
|
||||
dependencies = [
|
||||
"keyring-core",
|
||||
"log",
|
||||
"security-framework",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arboard"
|
||||
version = "3.7.0"
|
||||
@@ -606,6 +628,24 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-padding"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
@@ -718,6 +758,12 @@ dependencies = [
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "byteorder"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||
|
||||
[[package]]
|
||||
name = "byteorder-lite"
|
||||
version = "0.1.0"
|
||||
@@ -808,6 +854,15 @@ dependencies = [
|
||||
"winx",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cbc"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
|
||||
dependencies = [
|
||||
"cipher 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.9.0"
|
||||
@@ -902,8 +957,18 @@ version = "0.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"inout",
|
||||
"crypto-common 0.1.7",
|
||||
"inout 0.1.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
|
||||
dependencies = [
|
||||
"crypto-common 0.2.2",
|
||||
"inout 0.2.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -935,6 +1000,12 @@ dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmov"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
|
||||
|
||||
[[package]]
|
||||
name = "cmpv2"
|
||||
version = "0.2.0"
|
||||
@@ -953,7 +1024,7 @@ version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"spki",
|
||||
"x509-cert",
|
||||
@@ -1029,6 +1100,12 @@ version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
|
||||
|
||||
[[package]]
|
||||
name = "cookie-factory"
|
||||
version = "0.3.3"
|
||||
@@ -1113,6 +1190,12 @@ dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpubits"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
@@ -1216,12 +1299,12 @@ dependencies = [
|
||||
"craft-ui",
|
||||
"egui",
|
||||
"getrandom 0.3.4",
|
||||
"hmac",
|
||||
"hmac 0.12.1",
|
||||
"log",
|
||||
"png 0.17.16",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"thiserror 2.0.21",
|
||||
"web-time",
|
||||
]
|
||||
@@ -1447,7 +1530,7 @@ dependencies = [
|
||||
"ruzstd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"skrifa 0.47.0",
|
||||
"tar",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2154,7 +2237,7 @@ dependencies = [
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"tar",
|
||||
"tempfile",
|
||||
"ureq",
|
||||
@@ -2317,6 +2400,24 @@ dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctutils"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
|
||||
dependencies = [
|
||||
"cmov",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cursor-icon"
|
||||
version = "1.2.0"
|
||||
@@ -2335,7 +2436,7 @@ version = "0.7.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der_derive",
|
||||
"flagset",
|
||||
"pem-rfc7468",
|
||||
@@ -2378,11 +2479,23 @@ version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"block-buffer 0.10.4",
|
||||
"crypto-common 0.1.7",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.1",
|
||||
"const-oid 0.10.3",
|
||||
"crypto-common 0.2.2",
|
||||
"ctutils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs"
|
||||
version = "7.0.0"
|
||||
@@ -3597,13 +3710,31 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hkdf"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
|
||||
dependencies = [
|
||||
"hmac 0.13.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
|
||||
dependencies = [
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3645,6 +3776,15 @@ version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "hybrid-array"
|
||||
version = "0.4.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.12.0"
|
||||
@@ -4101,6 +4241,16 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
|
||||
dependencies = [
|
||||
"block-padding",
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inventory"
|
||||
version = "0.3.25"
|
||||
@@ -4458,6 +4608,15 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "keyring-core"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "281c851dbae0de36d405299dd463126df4826dc32665c1314e931696b8cdee77"
|
||||
dependencies = [
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "khronos-egl"
|
||||
version = "6.0.0"
|
||||
@@ -4721,7 +4880,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4952,12 +5111,75 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-complex",
|
||||
"num-integer",
|
||||
"num-iter",
|
||||
"num-rational",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-complex"
|
||||
version = "0.4.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-iter"
|
||||
version = "0.1.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-rational"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -6684,6 +6906,25 @@ dependencies = [
|
||||
"tiny-skia 0.11.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "secret-service"
|
||||
version = "5.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8"
|
||||
dependencies = [
|
||||
"aes 0.9.4",
|
||||
"cbc",
|
||||
"futures-util",
|
||||
"getrandom 0.4.3",
|
||||
"hkdf",
|
||||
"hybrid-array",
|
||||
"num",
|
||||
"once_cell",
|
||||
"serde",
|
||||
"sha2 0.11.1",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "security-framework"
|
||||
version = "3.7.0"
|
||||
@@ -6823,7 +7064,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6834,7 +7075,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6894,12 +7146,12 @@ checksum = "da90c3d9af638898a5fdc347479b18f950bb0dde11ecf2244f94cd28135da53b"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"base64 0.22.1",
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
"pem",
|
||||
"rand_core 0.10.1",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"signature",
|
||||
"sigstore-types",
|
||||
"spki",
|
||||
@@ -6968,7 +7220,7 @@ dependencies = [
|
||||
"chrono",
|
||||
"cmpv2",
|
||||
"cms",
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"hex",
|
||||
"rand",
|
||||
@@ -7007,7 +7259,7 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"cms",
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"hex",
|
||||
"pem",
|
||||
"rustls-pki-types",
|
||||
@@ -8228,6 +8480,7 @@ dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
@@ -8277,6 +8530,7 @@ dependencies = [
|
||||
name = "vectorcraft-engine"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"apple-native-keyring-store",
|
||||
"cfb",
|
||||
"chrono",
|
||||
"craft-cdr",
|
||||
@@ -8290,12 +8544,15 @@ dependencies = [
|
||||
"crc32fast",
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"hayro-ccitt",
|
||||
"heic-rs",
|
||||
"hmac 0.12.1",
|
||||
"image",
|
||||
"jxl-color",
|
||||
"jxl-grid",
|
||||
"jxl-oxide",
|
||||
"keyring-core",
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
"proptest",
|
||||
@@ -8305,6 +8562,7 @@ dependencies = [
|
||||
"same-file",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"skrifa 0.47.0",
|
||||
"thiserror 2.0.21",
|
||||
"tiff",
|
||||
@@ -8331,6 +8589,8 @@ dependencies = [
|
||||
"vectorcraft-tools",
|
||||
"vectorcraft-trace",
|
||||
"wat",
|
||||
"windows-native-keyring-store",
|
||||
"zbus-secret-service-keyring-store",
|
||||
"zune-core",
|
||||
"zune-jpegxl",
|
||||
]
|
||||
@@ -8479,7 +8739,7 @@ dependencies = [
|
||||
name = "vectorcraft-pdf"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"aes 0.8.4",
|
||||
"chrono",
|
||||
"craft",
|
||||
"craft-image-codecs",
|
||||
@@ -8497,7 +8757,7 @@ dependencies = [
|
||||
"objc2-core-graphics",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"siphasher",
|
||||
"skrifa 0.47.0",
|
||||
"smallvec",
|
||||
@@ -8522,11 +8782,12 @@ dependencies = [
|
||||
"rustix 1.1.6",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"thiserror 2.0.21",
|
||||
"vectorcraft-color",
|
||||
"vectorcraft-doc",
|
||||
"vectorcraft-geom 0.24.1",
|
||||
"vectorcraft-js",
|
||||
"wasmi",
|
||||
"wasmparser 0.228.0",
|
||||
"wat",
|
||||
@@ -8671,6 +8932,7 @@ dependencies = [
|
||||
"vectorcraft-geom 0.24.1",
|
||||
"vectorcraft-pathops 0.24.1",
|
||||
"vectorcraft-text",
|
||||
"vectorcraft-tools",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9464,6 +9726,19 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-native-keyring-store"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"keyring-core",
|
||||
"regex",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-numerics"
|
||||
version = "0.3.1"
|
||||
@@ -9821,7 +10096,7 @@ version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"const-oid 0.9.6",
|
||||
"der",
|
||||
"sha1",
|
||||
"signature",
|
||||
@@ -10041,6 +10316,17 @@ dependencies = [
|
||||
"zvariant",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus-secret-service-keyring-store"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a"
|
||||
dependencies = [
|
||||
"keyring-core",
|
||||
"secret-service",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zbus_macros"
|
||||
version = "5.19.0"
|
||||
|
||||
@@ -152,6 +152,17 @@ Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option.
|
||||
Original copyright and full license notices are preserved in each hyph-*.tex file.
|
||||
Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5.
|
||||
|
||||
FOGRA51 and FOGRA52 characterization data (crates/color/data/):
|
||||
Source: Fogra Forschungsgesellschaft Druck e.V., www.fogra.org,
|
||||
https://fogra.org/en/downloads/work-tools/characterisation-data. The files are distributed
|
||||
unmodified. Fogra's terms: "Free use and redistribution of the Fogra characterisation data is
|
||||
permitted, including redistribution as part of commercial and non-commercial software, provided
|
||||
that the data are distributed unmodified and Fogra is identified as the source. The designation
|
||||
FOGRAxx may be used solely to identify the respective reference data. Such use does not imply
|
||||
certification, approval or endorsement by Fogra." VectorCraft's Coated CMYK (FOGRA51) and
|
||||
Uncoated CMYK (FOGRA52) working spaces are computed from this data by VectorCraft's own code;
|
||||
they are not Fogra profiles.
|
||||
|
||||
|
||||
JPEG encoder dependency notices
|
||||
|
||||
|
||||
@@ -142,14 +142,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.
|
||||
|
||||
@@ -238,11 +238,13 @@ fn main() -> ExitCode {
|
||||
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
|
||||
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
|
||||
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
|
||||
/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's
|
||||
/// (`script.listInstalled`) and finds its Startup Scripts folder (`script.startup.run`, never run on its own), keeps each
|
||||
/// script's `Folder.userData` in the Script Data folder there, keeps File Info's
|
||||
/// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
|
||||
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
|
||||
fn with_stores(mut h: Headless) -> Headless {
|
||||
prefs_dir::attach_scripts_dir(&mut h.session);
|
||||
prefs_dir::attach_startup_scripts_dir(&mut h.session);
|
||||
prefs_dir::attach_script_data(&mut h.session);
|
||||
prefs_dir::attach_metadata_templates_dir(&mut h.session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut h.session);
|
||||
|
||||
@@ -61,8 +61,9 @@ pollster = "1"
|
||||
# which src/host_services.rs uses to read the path PhotoCraft registers under App Paths.
|
||||
# Win32_Devices_Display has `QueryDisplayConfig`, Win32_UI_ColorSystem the display's ICC profile and
|
||||
# Win32_System_LibraryLoader `GetProcAddress`, which src/display_profile.rs uses to read the
|
||||
# display's color profile for the canvas.
|
||||
windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Foundation", "Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_ColorSystem", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
|
||||
# display's color profile for the canvas. Win32_UI_HiDpi has `GetDpiForMonitor`, which
|
||||
# src/windows_display_size.rs uses to read a monitor's raw density for Display Print Size.
|
||||
windows = { version = "0.62", features = ["Win32_Devices_Display", "Win32_Foundation", "Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_Threading", "Win32_UI_ColorSystem", "Win32_UI_HiDpi", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
|
||||
# The renderer's worker count follows those cores (src/windows_cores.rs).
|
||||
vectorcraft-render = { workspace = true }
|
||||
|
||||
@@ -83,7 +84,8 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std"
|
||||
# The windows' Metal layers and the sRGB color space they are tagged with (src/mac_color_space.rs).
|
||||
# Zlib OR Apache-2.0 OR MIT, already in the build through wgpu with these features.
|
||||
objc2-quartz-core = { version = "0.3", default-features = false, features = ["std", "objc2-core-foundation", "objc2-core-graphics", "CALayer", "CAMetalLayer"] }
|
||||
objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGColorSpace"] }
|
||||
# CGDisplayScreenSize gives a display's physical size for Display Print Size (src/screen_density.rs).
|
||||
objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGColorSpace", "CGDirectDisplay", "CGDisplayConfiguration"] }
|
||||
# Waits for the answer of a file dialog shown as a sheet (src/main.rs, #867). MIT OR Apache-2.0,
|
||||
# already in the build through eframe.
|
||||
pollster = "1"
|
||||
|
||||
@@ -184,6 +184,11 @@ impl App {
|
||||
let now = ctx.input(|i| i.time);
|
||||
if let Some(w) = &self.winit_window {
|
||||
self.display_profile.tick(w, now, self.app.session.prefs.monitor_profile_display, &self.app.display_profile, ctx);
|
||||
if let Some(read) = self.screen_density.tick(w, self.app.session.prefs.display_print_size, ctx) {
|
||||
self.app.services.screens = read.screens;
|
||||
self.app.set_screen_reading(read.main);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
self.app.tick(ctx);
|
||||
if self.app.ui.status == "quit" {
|
||||
|
||||
@@ -189,6 +189,10 @@ pub(crate) fn services(window: Parent) -> Services {
|
||||
open_in_application: Some(Box::new(open_in_application)),
|
||||
// File → Print: the system's printers and print queue.
|
||||
print: Some(Box::new(printing::SystemPrint)),
|
||||
// The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens
|
||||
// only while the active tool uses the wheel.
|
||||
#[cfg(all(windows, not(target_vendor = "win7")))]
|
||||
stylus_wheel: Some(Box::new(super::windows_wintab::set_wheel_used)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,7 @@ mod process_identity;
|
||||
mod profile_root;
|
||||
#[cfg(not(any(target_os = "macos", windows)))]
|
||||
mod quit_windows;
|
||||
mod screen_density;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
mod single_instance;
|
||||
#[cfg(windows)]
|
||||
@@ -69,8 +70,11 @@ mod window_frame;
|
||||
mod windows_alt_codes;
|
||||
#[cfg(windows)]
|
||||
mod windows_cores;
|
||||
#[cfg(windows)]
|
||||
mod windows_display_size;
|
||||
mod windows_stylus;
|
||||
mod windows_symbol_chars;
|
||||
mod windows_wintab;
|
||||
mod xwayland;
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
@@ -206,6 +210,9 @@ struct App {
|
||||
held_files: Vec<String>,
|
||||
/// Reads the profile of the display that shows the main window, for the canvas.
|
||||
display_profile: display_profile::Reader,
|
||||
/// Measures the density of the display that shows the main window, for Display Print Size at
|
||||
/// 100% Zoom.
|
||||
screen_density: screen_density::Tracker,
|
||||
/// When this frame's input hook started, for the hang report's frame times (`hang_watch`).
|
||||
frame_start: Option<std::time::Instant>,
|
||||
/// The shortest time between the starts of two frames, while the window presents without vsync
|
||||
@@ -817,6 +824,8 @@ fn main() -> std::process::ExitCode {
|
||||
prefs_dir::attach_plugin_store(&mut session);
|
||||
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
|
||||
prefs_dir::attach_scripts_dir(&mut session);
|
||||
// The startup scripts are in the Startup Scripts folder next to the preferences.
|
||||
prefs_dir::attach_startup_scripts_dir(&mut session);
|
||||
// File Info's metadata templates live in their own folder next to the preferences.
|
||||
prefs_dir::attach_metadata_templates_dir(&mut session);
|
||||
prefs_dir::attach_new_doc_profiles(&mut session);
|
||||
@@ -970,6 +979,9 @@ fn main() -> std::process::ExitCode {
|
||||
single_instance::set_ui(&cc.egui_ctx);
|
||||
}
|
||||
let held_files = file_access::unconfined(|| open_or_hold(&mut app, command_line_files));
|
||||
// With General › Run Startup Scripts on and Safe Mode off, the startup scripts run
|
||||
// now, as the person's own; in Safe Mode they wait for the choice that ends it.
|
||||
file_access::unconfined(|| vectorcraft_ui_egui::script_runs::run_at_launch(&mut app));
|
||||
// The first frame is due from now (`gpu::watch_first_frame`).
|
||||
#[cfg(feature = "wgpu")]
|
||||
created.ready();
|
||||
@@ -989,6 +1001,7 @@ fn main() -> std::process::ExitCode {
|
||||
winit_window,
|
||||
held_files,
|
||||
display_profile: Default::default(),
|
||||
screen_density: Default::default(),
|
||||
frame_start: None,
|
||||
min_frame,
|
||||
last_frame_began: None,
|
||||
|
||||
@@ -50,9 +50,10 @@ pub fn attach_color_settings(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
|
||||
/// Install the plug-ins Install Plug-in kept in the `Plug-ins` folder (#2541), and keep the ones
|
||||
/// installed from now on there.
|
||||
/// installed from now on there. The key of the grants kept there is in the system's key store.
|
||||
pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(dir) = store_dir("Plug-ins") {
|
||||
vectorcraft_engine::store::grant_keys::use_os_grant_keys();
|
||||
session.attach_plugin_store(dir);
|
||||
}
|
||||
}
|
||||
@@ -65,6 +66,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Have `script.startup.run` run the scripts of the `Startup Scripts` folder. The folder is only
|
||||
/// read: the user makes it.
|
||||
pub fn attach_startup_scripts_dir(session: &mut vectorcraft_engine::Session) {
|
||||
if let Some(dir) = store_dir("Startup Scripts") {
|
||||
session.attach_startup_scripts_dir(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template
|
||||
/// makes.
|
||||
pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) {
|
||||
|
||||
@@ -0,0 +1,817 @@
|
||||
//! The densities of the connected displays, in points (at each display's scale factor) per inch,
|
||||
//! for Preferences › General › Display Print Size at 100% Zoom (`Services::screen_ppi` for the
|
||||
//! display that shows most of the main window, `Services::screens` for every display): a
|
||||
//! display's size in points divided by the physical size the system reports for it.
|
||||
//!
|
||||
//! - macOS: `CGDisplayScreenSize`.
|
||||
//! - Windows: `GetDpiForMonitor`'s raw density (`windows_display_size`).
|
||||
//! - X11 on Linux, XWayland included: the RandR output's width and height in millimeters.
|
||||
//! - Wayland on Linux: the physical width and height of the compositor's `wl_output` for the display.
|
||||
//! - Other systems: no size, so an inch takes 96 points.
|
||||
//!
|
||||
//! A display that reports no size, or a size no display has, gives `None`, and an inch then takes
|
||||
//! 96 points. While the preference is on, the displays are listed once a second while the app
|
||||
//! draws. When the list changes, a background thread reads every display's size, and a later
|
||||
//! frame takes the result. A reading that fails is tried again after [`RETRY_AFTER`] seconds, and
|
||||
//! the displays are read again [`READ_AGAIN_AFTER`] seconds after the last reading; the app draws a
|
||||
//! frame for each of these when nothing else makes it draw.
|
||||
|
||||
use std::sync::mpsc::{Receiver, TryRecvError};
|
||||
|
||||
use vectorcraft_ui_egui::{ScreenDensity, ScreenPpi};
|
||||
use winit::dpi::{PhysicalPosition, PhysicalSize};
|
||||
use winit::monitor::MonitorHandle;
|
||||
|
||||
/// Seconds between two listings of the displays.
|
||||
const LOOK_EVERY: f64 = 1.0;
|
||||
|
||||
/// Seconds after a failed reading before the same displays are read again.
|
||||
const RETRY_AFTER: f64 = 10.0;
|
||||
|
||||
/// Seconds after a reading before the same displays are read again: a display can be replaced by
|
||||
/// one the listing cannot tell apart (the same connector, resolution and scale).
|
||||
const READ_AGAIN_AFTER: f64 = 60.0;
|
||||
|
||||
/// Millimeters in an inch.
|
||||
const MM_PER_INCH: f64 = 25.4;
|
||||
|
||||
/// How far the horizontal and vertical densities of one display may differ, as a fraction of the
|
||||
/// larger: square pixels on a display that reports its true size give two densities this close.
|
||||
const AXES_AGREE: f64 = 0.1;
|
||||
|
||||
/// A connected display as winit lists it: what a reading needs, and what tells two lists apart.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Display {
|
||||
name: Option<String>,
|
||||
position: PhysicalPosition<i32>,
|
||||
size: PhysicalSize<u32>,
|
||||
/// The display's scale factor, as its bits.
|
||||
scale: u64,
|
||||
/// The system's id of the display ([`native_id`]).
|
||||
id: i64,
|
||||
}
|
||||
|
||||
impl Display {
|
||||
fn of(m: &MonitorHandle) -> Self {
|
||||
Self { name: m.name(), position: m.position(), size: m.size(), scale: m.scale_factor().to_bits(), id: native_id(m) }
|
||||
}
|
||||
}
|
||||
|
||||
/// One display's physical size in millimeters: `None` when the system reports none, an error when
|
||||
/// asking for it failed.
|
||||
type Size = Result<Option<[f64; 2]>, String>;
|
||||
|
||||
/// The physical sizes of displays, one for each display read, or why none could be read.
|
||||
type Reading = Result<Vec<Size>, String>;
|
||||
|
||||
/// What the host hands the app: the density of the main window's display, unread while that
|
||||
/// display is unknown or has not answered yet, and every display's that answered.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Densities {
|
||||
pub(crate) main: ScreenPpi,
|
||||
pub(crate) screens: Vec<ScreenDensity>,
|
||||
}
|
||||
|
||||
/// What a display answered: its physical size (`Some(None)` for none), or `None` while it has not
|
||||
/// answered.
|
||||
type Answer = Option<Option<[f64; 2]>>;
|
||||
|
||||
/// What a listing gives: the displays, the one that shows most of the main window, and the main
|
||||
/// window's scale factor.
|
||||
type Listing = (Vec<Display>, Option<Display>, f64);
|
||||
|
||||
/// Keeps the densities current from the main window's frames.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Tracker {
|
||||
/// When the displays were last listed.
|
||||
looked: Option<f64>,
|
||||
/// The display that showed most of the main window at the last listing, and the window's scale
|
||||
/// factor then.
|
||||
current: Option<(Display, f64)>,
|
||||
/// The displays of the last reading that finished, each with what it answered.
|
||||
read: Option<Vec<(Display, Answer)>>,
|
||||
/// The displays of the last reading that failed, and when it failed.
|
||||
failed: Option<(Vec<Display>, f64)>,
|
||||
/// The reading in progress: the displays it reads, and where its result arrives.
|
||||
running: Option<(Vec<Display>, Receiver<Reading>)>,
|
||||
/// The reading in progress started before the preference was last turned off: its result is
|
||||
/// dropped when it arrives, and no other reading starts until then.
|
||||
obsolete: bool,
|
||||
/// What [`Self::tick`] returned last.
|
||||
reported: Option<Densities>,
|
||||
/// The displays of the last listing.
|
||||
listed: Option<Vec<Display>>,
|
||||
/// When the last reading that finished ended.
|
||||
read_at: f64,
|
||||
/// When the first tick ran: the tracker's clock, which runs while the window draws nothing.
|
||||
origin: Option<std::time::Instant>,
|
||||
}
|
||||
|
||||
impl Tracker {
|
||||
/// Lists the displays when a listing is due and Display Print Size is `enabled`, starts a
|
||||
/// reading on a background thread when they changed, and returns the densities when they
|
||||
/// differ from what it returned before. The thread asks `ctx` for a frame when its reading is
|
||||
/// ready.
|
||||
pub(crate) fn tick(&mut self, window: &winit::window::Window, enabled: bool, ctx: &egui::Context) -> Option<Densities> {
|
||||
let now = self.origin.get_or_insert_with(std::time::Instant::now).elapsed().as_secs_f64();
|
||||
let list = || {
|
||||
// winit stops on a display that went away while it is being asked about (Windows); that
|
||||
// listing is dropped, and the next one is made a second later.
|
||||
let listing = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
let current = window.current_monitor().map(|m| Display::of(&m));
|
||||
(window.available_monitors().map(|m| Display::of(&m)).collect::<Vec<_>>(), current, window.scale_factor())
|
||||
}));
|
||||
listing.map_err(|_| log::debug!("a display went away while the displays were listed")).ok()
|
||||
};
|
||||
let wayland = is_wayland(window);
|
||||
let start = |displays: Vec<Display>| {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let ctx = ctx.clone();
|
||||
let spawned = std::thread::Builder::new().name("display size".into()).spawn(move || {
|
||||
// The app may have quit, and dropped the receiver, before the reading ends.
|
||||
let _ = tx.send(read_all(&displays, wayland));
|
||||
ctx.request_repaint();
|
||||
});
|
||||
spawned.map(|_| rx).map_err(|e| format!("couldn't start reading the displays' sizes: {e}"))
|
||||
};
|
||||
let densities = self.update(now, enabled, list, start);
|
||||
// A failed reading is tried again at a listing RETRY_AFTER seconds later, also in an app
|
||||
// that is not drawing. A reading in progress asks for a frame when it ends.
|
||||
if enabled
|
||||
&& self.running.is_none()
|
||||
&& let Some((_, at)) = &self.failed
|
||||
{
|
||||
let due = (at + RETRY_AFTER).max(self.looked.map_or(0.0, |l| l + LOOK_EVERY));
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64((due - now).clamp(0.0, RETRY_AFTER)));
|
||||
} else if enabled && self.running.is_none() && self.read.is_some() {
|
||||
// An app that is not drawing still lists and reads the displays READ_AGAIN_AFTER seconds
|
||||
// after the last reading.
|
||||
let due = (self.read_at + READ_AGAIN_AFTER).max(self.looked.map_or(0.0, |l| l + LOOK_EVERY));
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64((due - now).clamp(0.0, READ_AGAIN_AFTER)));
|
||||
}
|
||||
densities
|
||||
}
|
||||
|
||||
/// [`Self::tick`] with the listing (`list`) and the start of a reading (`start`) passed in.
|
||||
fn update(
|
||||
&mut self,
|
||||
now: f64,
|
||||
enabled: bool,
|
||||
list: impl FnOnce() -> Option<Listing>,
|
||||
start: impl FnOnce(Vec<Display>) -> Result<Receiver<Reading>, String>,
|
||||
) -> Option<Densities> {
|
||||
let was_running = self.running.is_some();
|
||||
if let Some((displays, rx)) = self.running.take() {
|
||||
match rx.try_recv() {
|
||||
Err(TryRecvError::Empty) => self.running = Some((displays, rx)),
|
||||
_ if self.obsolete => self.obsolete = false,
|
||||
Ok(Ok(sizes)) => {
|
||||
// A display whose size could not be read keeps what an earlier reading gave it,
|
||||
// or stays unanswered, until the reading is tried again.
|
||||
let mut failed = false;
|
||||
let read: Vec<_> = displays
|
||||
.iter()
|
||||
.zip(sizes.into_iter().chain(std::iter::repeat(Ok(None))))
|
||||
.map(|(d, s)| {
|
||||
let mm = s.map(Some).unwrap_or_else(|e| {
|
||||
log::debug!("couldn't read a display's physical size: {e}");
|
||||
failed = true;
|
||||
self.earlier(d)
|
||||
});
|
||||
(d.clone(), mm)
|
||||
})
|
||||
.collect();
|
||||
self.failed = failed.then_some((displays, now));
|
||||
self.read = Some(read);
|
||||
self.read_at = now;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
log::debug!("couldn't read the displays' physical sizes: {e}");
|
||||
self.fail(displays, now);
|
||||
}
|
||||
Err(TryRecvError::Disconnected) => {
|
||||
log::debug!("the reading of the displays' physical sizes stopped without a result");
|
||||
self.fail(displays, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
// When a reading ends, the displays are listed again at once: they may have changed while
|
||||
// it ran, and the frame its end asked for may be the last one for a while.
|
||||
if was_running && self.running.is_none() {
|
||||
self.looked = None;
|
||||
}
|
||||
if !enabled {
|
||||
// Turned on again, the displays are read and the densities reported anew: a display
|
||||
// may have been replaced meanwhile by one that lists the same.
|
||||
self.reported = None;
|
||||
self.read = None;
|
||||
self.failed = None;
|
||||
self.looked = None;
|
||||
self.obsolete = self.running.is_some();
|
||||
return None;
|
||||
}
|
||||
// The densities change only at a listing, and one follows the end of every reading.
|
||||
let listing = !self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now));
|
||||
if !listing && self.reported.is_some() {
|
||||
return None;
|
||||
}
|
||||
if listing {
|
||||
self.looked = Some(now);
|
||||
}
|
||||
if let Some((displays, current, scale)) = listing.then(list).flatten() {
|
||||
// winit can give the window's display as it was before a change of resolution: the
|
||||
// display is found in the listing by its id and name.
|
||||
let current = current.map(|c| displays.iter().find(|d| d.id == c.id && d.name == c.name).cloned().unwrap_or(c));
|
||||
self.current = current.map(|c| (c, scale));
|
||||
self.listed = Some(displays.clone());
|
||||
// These displays are read once, and again RETRY_AFTER seconds after a reading of them
|
||||
// failed in whole or in part.
|
||||
let known = self.read.as_ref().is_some_and(|r| r.iter().map(|(d, _)| d).eq(displays.iter()));
|
||||
let due = match &self.failed {
|
||||
Some((d, at)) if *d == displays => !(*at..*at + RETRY_AFTER).contains(&now),
|
||||
_ => !known || now - self.read_at >= READ_AGAIN_AFTER,
|
||||
};
|
||||
if self.running.is_none() && due {
|
||||
match start(displays.clone()) {
|
||||
Ok(rx) => self.running = Some((displays, rx)),
|
||||
Err(e) => {
|
||||
log::warn!("{e}");
|
||||
self.fail(displays, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let read = self.read.as_ref()?;
|
||||
// The main window counts in its own scale factor, which on Wayland can be a fraction where
|
||||
// the display gives a whole number. A window on no display (a Wayland window before it is
|
||||
// shown, or after its display went), or on one that is being read or has not answered, has
|
||||
// its density unread.
|
||||
let main = match &self.current {
|
||||
Some((c, scale)) => match read.iter().find(|(d, _)| d == c) {
|
||||
Some((d, Some(mm))) => ScreenPpi::Read(mm.and_then(|mm| points_per_inch(d.size, *scale, mm))),
|
||||
_ => ScreenPpi::Unread,
|
||||
},
|
||||
None => ScreenPpi::Unread,
|
||||
};
|
||||
// The displays where the last listing has them, each with what the reading of it gave; a
|
||||
// display the readings have not reached yet is unread.
|
||||
let listed = self.listed.as_deref().unwrap_or_default();
|
||||
let screens = listed
|
||||
.iter()
|
||||
.map(|d| {
|
||||
let [w, h] = [d.size.width, d.size.height].map(|v| i32::try_from(v).unwrap_or(i32::MAX));
|
||||
let scale = f64::from_bits(d.scale);
|
||||
let mm = read.iter().find(|(e, _)| e == d).and_then(|(_, mm)| *mm);
|
||||
let ppi = mm.map_or(ScreenPpi::Unread, |mm| ScreenPpi::Read(mm.and_then(|mm| points_per_inch(d.size, scale, mm))));
|
||||
ScreenDensity { rect: [d.position.x, d.position.y, w, h], scale, ppi }
|
||||
})
|
||||
.collect();
|
||||
let densities = Densities { main, screens };
|
||||
if self.reported.as_ref() == Some(&densities) {
|
||||
return None;
|
||||
}
|
||||
match main {
|
||||
ScreenPpi::Read(Some(p)) => log::info!("the window's display has {p:.1} points to an inch"),
|
||||
ScreenPpi::Read(None) => log::info!("the window's display reports no physical size; an inch is 96 points"),
|
||||
ScreenPpi::Unread => log::info!("the window's display has not been read; an inch is 96 points"),
|
||||
}
|
||||
self.reported = Some(densities.clone());
|
||||
Some(densities)
|
||||
}
|
||||
}
|
||||
|
||||
impl Tracker {
|
||||
/// What the last reading gave display `d`, when it answered.
|
||||
fn earlier(&self, d: &Display) -> Answer {
|
||||
self.read.as_ref()?.iter().find(|(e, _)| e == d)?.1
|
||||
}
|
||||
|
||||
/// Records that reading `displays` failed at `now`; they are read again after [`RETRY_AFTER`]
|
||||
/// seconds. After an earlier reading, they become the displays known, each with what that
|
||||
/// reading gave it, if anything. Before any reading, nothing is reported yet.
|
||||
fn fail(&mut self, displays: Vec<Display>, now: f64) {
|
||||
if self.read.is_some() {
|
||||
let read = displays.iter().map(|d| (d.clone(), self.earlier(d))).collect();
|
||||
self.read = Some(read);
|
||||
}
|
||||
self.failed = Some((displays, now));
|
||||
}
|
||||
}
|
||||
|
||||
/// The density, in points per inch, of a display `size` physical pixels wide and high, drawn at
|
||||
/// `scale` pixels to a point, that the system says is `mm` millimeters wide and high. `None` for a
|
||||
/// size that is no display's: zero or less, an aspect ratio given in place of the size (16 × 9,
|
||||
/// 160 × 90 and the like), axes whose densities disagree in either orientation, or a pixel density
|
||||
/// outside [`vectorcraft_ui_egui::state::SCREEN_PPI_RANGE`]. The range applies to the pixels, before
|
||||
/// the scale divides them into points. A display turned a quarter turn may report the size of its
|
||||
/// panel upright, so the axes are also tried swapped.
|
||||
pub(crate) fn points_per_inch(size: PhysicalSize<u32>, scale: f64, mm: [f64; 2]) -> Option<f64> {
|
||||
if !(scale.is_finite() && scale > 0.0) || mm.iter().any(|v| !(v.is_finite() && *v > 0.0)) || aspect_as_size(mm) {
|
||||
return None;
|
||||
}
|
||||
let pixels = [f64::from(size.width), f64::from(size.height)];
|
||||
let density = |[w, h]: [f64; 2]| [pixels[0] / (w / MM_PER_INCH), pixels[1] / (h / MM_PER_INCH)];
|
||||
let agree = |[x, y]: [f64; 2]| (x - y).abs() <= AXES_AGREE * x.max(y);
|
||||
let [x, y] = [density(mm), density([mm[1], mm[0]])].into_iter().find(|d| agree(*d))?;
|
||||
let ppi = (x + y) / 2.0;
|
||||
vectorcraft_ui_egui::state::SCREEN_PPI_RANGE.contains(&ppi).then_some(ppi / scale)
|
||||
}
|
||||
|
||||
/// Whether `mm` is an aspect ratio that a display's EDID gave in place of its size: 16:9, 16:10
|
||||
/// or 4:3, in centimeters or tenths of them.
|
||||
fn aspect_as_size(mm: [f64; 2]) -> bool {
|
||||
const RATIOS: [[f64; 2]; 3] = [[16.0, 9.0], [16.0, 10.0], [4.0, 3.0]];
|
||||
let sorted = if mm[0] >= mm[1] { mm } else { [mm[1], mm[0]] };
|
||||
RATIOS.iter().any(|r| [1.0, 10.0].iter().any(|k| sorted == [r[0] * k, r[1] * k]))
|
||||
}
|
||||
|
||||
/// Whether `window` is a Wayland window, whose displays the compositor describes.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn is_wayland(window: &winit::window::Window) -> bool {
|
||||
use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle};
|
||||
window.window_handle().ok().is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Wayland(_)))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn is_wayland(_: &winit::window::Window) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The system's id of `monitor`: the display id on macOS, the monitor handle on Windows, the RandR
|
||||
/// CRTC on X11.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn native_id(monitor: &MonitorHandle) -> i64 {
|
||||
use winit::platform::macos::MonitorHandleExtMacOS as _;
|
||||
i64::from(monitor.native_id())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn native_id(monitor: &MonitorHandle) -> i64 {
|
||||
use winit::platform::windows::MonitorHandleExtWindows as _;
|
||||
monitor.hmonitor() as i64
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn native_id(monitor: &MonitorHandle) -> i64 {
|
||||
use winit::platform::x11::MonitorHandleExtX11 as _;
|
||||
i64::from(monitor.native_id())
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", windows, target_os = "linux")))]
|
||||
fn native_id(_: &MonitorHandle) -> i64 {
|
||||
0
|
||||
}
|
||||
|
||||
/// The physical width and height, in millimeters, the system reports for each of `displays`.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn read_all(displays: &[Display], _: bool) -> Reading {
|
||||
Ok(displays
|
||||
.iter()
|
||||
.map(|d| {
|
||||
Ok(u32::try_from(d.id).ok().map(|id| {
|
||||
let size = objc2_core_graphics::CGDisplayScreenSize(id);
|
||||
[size.width, size.height]
|
||||
}))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn read_all(displays: &[Display], _: bool) -> Reading {
|
||||
Ok(displays
|
||||
.iter()
|
||||
.map(|d| {
|
||||
let dpi = crate::windows_display_size::raw_dpi(d.id as isize)?;
|
||||
Ok(dpi.map(|[x, y]| [f64::from(d.size.width) / x * MM_PER_INCH, f64::from(d.size.height) / y * MM_PER_INCH]))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn read_all(displays: &[Display], wayland: bool) -> Reading {
|
||||
if wayland { wayland::read_all(displays) } else { x11::read_all(displays) }
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", windows, target_os = "linux")))]
|
||||
fn read_all(displays: &[Display], _: bool) -> Reading {
|
||||
Ok(displays.iter().map(|_| Ok(None)).collect())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod x11 {
|
||||
use x11rb::CURRENT_TIME;
|
||||
use x11rb::protocol::randr;
|
||||
|
||||
use super::{Display, Reading, Size};
|
||||
|
||||
/// The millimeters RandR reports for the first output of each display's CRTC.
|
||||
pub(super) fn read_all(displays: &[Display]) -> Reading {
|
||||
let (conn, _) = x11rb::connect(None).map_err(|e| format!("couldn't connect to the X11 display: {e}"))?;
|
||||
let ask = |e: x11rb::errors::ConnectionError| format!("couldn't ask the X11 display: {e}");
|
||||
// RandR answers only a client that gave the version it speaks; 1.2 has CRTCs and outputs.
|
||||
randr::query_version(&conn, 1, 2).map_err(ask)?.reply().map_err(|e| format!("the X11 display has no RandR 1.2: {e}"))?;
|
||||
let size = |d: &Display| -> Size {
|
||||
let Ok(crtc) = u32::try_from(d.id) else { return Ok(None) };
|
||||
let info = randr::get_crtc_info(&conn, crtc, CURRENT_TIME)
|
||||
.map_err(ask)?
|
||||
.reply()
|
||||
.map_err(|e| format!("the X11 display has no such CRTC: {e}"))?;
|
||||
let Some(output) = info.outputs.first() else { return Ok(None) };
|
||||
let info = randr::get_output_info(&conn, *output, CURRENT_TIME)
|
||||
.map_err(ask)?
|
||||
.reply()
|
||||
.map_err(|e| format!("the X11 display has no such output: {e}"))?;
|
||||
Ok(Some([f64::from(info.mm_width), f64::from(info.mm_height)]))
|
||||
};
|
||||
Ok(displays.iter().map(size).collect())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod wayland {
|
||||
use wayland_client::globals::{GlobalListContents, registry_queue_init};
|
||||
use wayland_client::protocol::wl_output::{self, WlOutput};
|
||||
use wayland_client::protocol::wl_registry::{self, WlRegistry};
|
||||
use wayland_client::{Connection, Dispatch, QueueHandle};
|
||||
|
||||
use super::{Display, Reading};
|
||||
|
||||
/// The physical size the compositor gives for the output of each display's name, asked on a
|
||||
/// connection of its own; with no name, or a compositor that names no outputs, the only
|
||||
/// output's.
|
||||
pub(super) fn read_all(displays: &[Display]) -> Reading {
|
||||
let conn = Connection::connect_to_env().map_err(|e| format!("no Wayland compositor: {e}"))?;
|
||||
let (globals, mut queue) = registry_queue_init::<Outputs>(&conn).map_err(|e| e.to_string())?;
|
||||
let qh = queue.handle();
|
||||
let mut state = Outputs::default();
|
||||
for global in globals.contents().clone_list().into_iter().filter(|g| g.interface == "wl_output") {
|
||||
// Version 4 names the output; older ones give its size only.
|
||||
let output: WlOutput = globals.registry().bind(global.name, global.version.min(4), &qh, state.outputs.len());
|
||||
state.outputs.push((output, Output::default()));
|
||||
}
|
||||
// The compositor sends each output's geometry, name and `done` in reply to the bind.
|
||||
queue.roundtrip(&mut state).map_err(|e| e.to_string())?;
|
||||
let found: Vec<&Output> = state.outputs.iter().map(|(_, o)| o).collect();
|
||||
let named = found.iter().any(|o| o.name.is_some());
|
||||
Ok(displays
|
||||
.iter()
|
||||
.map(|d| {
|
||||
let pick = match d.name.as_deref() {
|
||||
Some(name) if named => found.iter().find(|o| o.name.as_deref() == Some(name)),
|
||||
_ if found.len() == 1 => found.first(),
|
||||
_ => None,
|
||||
};
|
||||
Ok(pick.and_then(|o| o.mm))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// One output's name and physical size.
|
||||
#[derive(Default)]
|
||||
struct Output {
|
||||
name: Option<String>,
|
||||
mm: Option<[f64; 2]>,
|
||||
}
|
||||
|
||||
/// The outputs bound, each with what its events gave.
|
||||
#[derive(Default)]
|
||||
struct Outputs {
|
||||
outputs: Vec<(WlOutput, Output)>,
|
||||
}
|
||||
|
||||
impl Dispatch<WlRegistry, GlobalListContents> for Outputs {
|
||||
fn event(_: &mut Self, _: &WlRegistry, _: wl_registry::Event, _: &GlobalListContents, _: &Connection, _: &QueueHandle<Self>) {}
|
||||
}
|
||||
|
||||
impl Dispatch<WlOutput, usize> for Outputs {
|
||||
fn event(state: &mut Self, _: &WlOutput, event: wl_output::Event, index: &usize, _: &Connection, _: &QueueHandle<Self>) {
|
||||
let Some((_, output)) = state.outputs.get_mut(*index) else { return };
|
||||
match event {
|
||||
wl_output::Event::Geometry { physical_width, physical_height, .. } => {
|
||||
output.mm = Some([f64::from(physical_width), f64::from(physical_height)]);
|
||||
}
|
||||
wl_output::Event::Name { name } => output.name = Some(name),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::cell::Cell;
|
||||
use std::sync::mpsc::{Sender, channel};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A 14-inch laptop panel at twice its points: 3024 × 1964 pixels, 302 × 196 mm, draws 127
|
||||
/// points to an inch, more than the 96 a fixed inch assumes.
|
||||
#[test]
|
||||
fn a_laptop_panel_has_more_points_to_an_inch_than_the_reference() {
|
||||
let ppi = points_per_inch(PhysicalSize::new(3024, 1964), 2.0, [302.0, 196.0]);
|
||||
assert!(ppi.is_some_and(|p| p > 96.0 && (p - 1512.0 / (302.0 / MM_PER_INCH)).abs() < 1.0), "{ppi:?}");
|
||||
}
|
||||
|
||||
/// The same display in a scaled mode (more points on the same glass) draws more points to an
|
||||
/// inch, and at a higher scale factor fewer: the density counts the window's points.
|
||||
#[test]
|
||||
fn the_density_counts_points_at_the_windows_scale() {
|
||||
let at = |w, h, scale| points_per_inch(PhysicalSize::new(w, h), scale, [527.0, 296.0]).unwrap_or(0.0);
|
||||
assert!(at(1920, 1080, 1.0) > 0.0);
|
||||
assert!(at(2560, 1440, 1.0) > at(1920, 1080, 1.0), "more pixels on the same glass");
|
||||
assert!(at(3840, 2160, 2.0) < at(3840, 2160, 1.5), "a larger scale factor makes each point larger");
|
||||
}
|
||||
|
||||
/// A display turned a quarter turn whose system reports its panel's size upright still
|
||||
/// measures; axes that disagree either way do not.
|
||||
#[test]
|
||||
fn a_turned_display_measures_and_disagreeing_axes_do_not() {
|
||||
let upright = points_per_inch(PhysicalSize::new(1920, 1080), 1.0, [527.0, 296.0]);
|
||||
let turned = points_per_inch(PhysicalSize::new(1080, 1920), 1.0, [527.0, 296.0]);
|
||||
assert!(upright.is_some() && turned.is_some());
|
||||
assert!((upright.unwrap_or(0.0) - turned.unwrap_or(1.0)).abs() < 1e-9);
|
||||
assert_eq!(points_per_inch(PhysicalSize::new(1920, 1080), 1.0, [527.0, 527.0]), None);
|
||||
}
|
||||
|
||||
/// Sizes no display has give no density: none, an aspect ratio in place of the size, and
|
||||
/// densities past the range a display can have.
|
||||
#[test]
|
||||
fn reports_that_are_no_displays_size_give_no_density() {
|
||||
let at = |mm| points_per_inch(PhysicalSize::new(1920, 1080), 1.0, mm);
|
||||
for mm in [[0.0, 0.0], [-1.0, 300.0], [f64::NAN, 300.0], [160.0, 90.0], [16.0, 9.0], [160.0, 100.0], [40.0, 30.0], [9.0, 16.0]] {
|
||||
assert_eq!(at(mm), None, "{mm:?}");
|
||||
}
|
||||
assert_eq!(points_per_inch(PhysicalSize::new(1920, 1080), 0.0, [527.0, 296.0]), None, "no scale");
|
||||
assert_eq!(points_per_inch(PhysicalSize::new(100, 56), 1.0, [5270.0, 2960.0]), None, "under the range");
|
||||
assert_eq!(points_per_inch(PhysicalSize::new(7680, 4320), 1.0, [53.0, 30.0]), None, "over it");
|
||||
}
|
||||
|
||||
/// The range applies to the display's pixels: a 1920 × 1080 display of 527 × 296 mm drawn at
|
||||
/// scale 4 has about 23 points to an inch, which is a real density.
|
||||
#[test]
|
||||
fn a_large_scale_factor_does_not_put_a_display_out_of_range() {
|
||||
let ppi = points_per_inch(PhysicalSize::new(1920, 1080), 4.0, [527.0, 296.0]);
|
||||
let pixels = points_per_inch(PhysicalSize::new(1920, 1080), 1.0, [527.0, 296.0]).unwrap_or(0.0);
|
||||
assert!(ppi.is_some_and(|p| p < 30.0 && (p - pixels / 4.0).abs() < 1e-9), "{ppi:?}");
|
||||
let print = vectorcraft_ui_egui::state::print_ppi(true, ppi);
|
||||
assert_eq!(print, ppi, "Actual Size counts from it, not from 96");
|
||||
}
|
||||
|
||||
/// A 1920 × 1080 display at scale 1 and position `x`, named `name`.
|
||||
fn display(name: &str, x: i32) -> Display {
|
||||
Display {
|
||||
name: Some(name.into()),
|
||||
position: PhysicalPosition::new(x, 0),
|
||||
size: PhysicalSize::new(1920, 1080),
|
||||
scale: 1.0f64.to_bits(),
|
||||
id: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The sizes of a 24-inch display (about 92 points to an inch) and a 27-inch one (about 82).
|
||||
const SIZES: [[f64; 2]; 2] = [[531.0, 299.0], [598.0, 336.0]];
|
||||
|
||||
/// A reading that gives every display one of [`SIZES`], in turn.
|
||||
fn sizes(n: usize) -> Reading {
|
||||
Ok((0..n).map(|i| Ok(Some(SIZES[i % SIZES.len()]))).collect())
|
||||
}
|
||||
|
||||
/// Drives a tracker: counts its listings and readings, and hands out the sender of the reading
|
||||
/// it started last.
|
||||
struct Rig {
|
||||
tracker: Tracker,
|
||||
displays: Vec<Display>,
|
||||
current: usize,
|
||||
/// The window's display as winit last gave it, when that lags behind the listing.
|
||||
lagging: Option<Display>,
|
||||
window_scale: f64,
|
||||
lists: Cell<usize>,
|
||||
reads: Cell<usize>,
|
||||
sender: Option<Sender<Reading>>,
|
||||
fail_to_start: bool,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
tracker: Tracker::default(),
|
||||
displays: vec![display("left", 0), display("right", 1920)],
|
||||
current: 0,
|
||||
lagging: None,
|
||||
window_scale: 1.0,
|
||||
lists: Cell::new(0),
|
||||
reads: Cell::new(0),
|
||||
sender: None,
|
||||
fail_to_start: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn tick(&mut self, now: f64, enabled: bool) -> Option<Densities> {
|
||||
let current = self.lagging.clone().or_else(|| self.displays.get(self.current).cloned());
|
||||
let (displays, scale) = (self.displays.clone(), self.window_scale);
|
||||
let (lists, reads, fail) = (&self.lists, &self.reads, self.fail_to_start);
|
||||
let mut sender = None;
|
||||
let out = self.tracker.update(
|
||||
now,
|
||||
enabled,
|
||||
|| {
|
||||
lists.set(lists.get() + 1);
|
||||
Some((displays, current, scale))
|
||||
},
|
||||
|_| {
|
||||
reads.set(reads.get() + 1);
|
||||
if fail {
|
||||
return Err("no thread".into());
|
||||
}
|
||||
let (tx, rx) = channel();
|
||||
sender = Some(tx);
|
||||
Ok(rx)
|
||||
},
|
||||
);
|
||||
if sender.is_some() {
|
||||
self.sender = sender;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn finish(&mut self, reading: Reading) {
|
||||
if let Some(tx) = self.sender.take() {
|
||||
tx.send(reading).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The first listing starts a reading, and the densities arrive once the reading ends, without
|
||||
/// a frame waiting for it. The main window's density is its display's, and every display gets
|
||||
/// its own.
|
||||
#[test]
|
||||
fn the_densities_arrive_when_the_reading_ends() {
|
||||
let mut rig = Rig::new();
|
||||
assert_eq!(rig.tick(0.0, true), None, "the reading runs in the background");
|
||||
assert_eq!(rig.reads.get(), 1);
|
||||
assert_eq!(rig.tick(2.0, true), None, "still running: no second reading");
|
||||
assert_eq!(rig.reads.get(), 1);
|
||||
rig.finish(sizes(2));
|
||||
let got = rig.tick(2.1, true).unwrap_or_else(|| panic!("the densities"));
|
||||
let ppi = got.screens.iter().map(|s| s.ppi.ppi().unwrap_or(0.0)).collect::<Vec<_>>();
|
||||
assert!(ppi[0] > ppi[1] && ppi[1] > 0.0, "the smaller display is denser: {ppi:?}");
|
||||
assert_eq!(got.main, ScreenPpi::Read(Some(ppi[0])), "the main window is on the left display");
|
||||
assert_eq!(got.screens[1].rect, [1920, 0, 1920, 1080]);
|
||||
assert_eq!(rig.tick(5.0, true), None, "nothing changed");
|
||||
assert_eq!(rig.reads.get(), 1, "the same displays are not read again");
|
||||
assert_eq!(rig.tick(5.2, false), None, "off, nothing is reported");
|
||||
assert_eq!(rig.tick(5.4, true), None, "turned on again, the displays are read again at once");
|
||||
assert_eq!(rig.reads.get(), 2);
|
||||
rig.finish(sizes(2));
|
||||
assert_eq!(rig.tick(5.5, true), Some(got), "and the densities reported anew");
|
||||
}
|
||||
|
||||
/// The displays are listed at most once a second, and not at all with the preference off.
|
||||
#[test]
|
||||
fn the_displays_are_listed_once_a_second_while_the_preference_is_on() {
|
||||
let mut rig = Rig::new();
|
||||
rig.tick(0.0, true);
|
||||
rig.tick(0.5, true);
|
||||
assert_eq!(rig.lists.get(), 1);
|
||||
rig.tick(1.0, true);
|
||||
assert_eq!(rig.lists.get(), 2);
|
||||
rig.tick(5.0, false);
|
||||
assert_eq!(rig.lists.get(), 2, "off, nothing is asked of the system");
|
||||
}
|
||||
|
||||
/// The main window moving to the other display reports that display's density without a new
|
||||
/// reading; a display joining the list is read again, and while a display that changed is
|
||||
/// read, the densities reported before stay.
|
||||
#[test]
|
||||
fn a_change_of_display_is_reported() {
|
||||
let mut rig = Rig::new();
|
||||
rig.tick(0.0, true);
|
||||
rig.finish(sizes(2));
|
||||
let left = rig.tick(0.1, true).and_then(|d| d.main.ppi());
|
||||
rig.current = 1;
|
||||
let right = rig.tick(1.5, true).and_then(|d| d.main.ppi());
|
||||
assert!(left.is_some() && right.is_some() && left != right, "{left:?} then {right:?}");
|
||||
assert_eq!(rig.reads.get(), 1);
|
||||
// A window drawn at 1.5 pixels a point (a fractional scale the display does not list)
|
||||
// has fewer points to an inch than the display's own scale of 1 gives.
|
||||
rig.window_scale = 1.5;
|
||||
let scaled = rig.tick(2.6, true).and_then(|d| d.main.ppi());
|
||||
assert!(scaled.zip(right).is_some_and(|(s, r)| (s * 1.5 - r).abs() < 1e-9), "{scaled:?} at 1.5, {right:?} at 1");
|
||||
rig.window_scale = 1.0;
|
||||
rig.displays.push(display("third", 3840));
|
||||
rig.tick(4.0, true);
|
||||
assert_eq!(rig.reads.get(), 2, "a new display is read");
|
||||
rig.finish(sizes(3));
|
||||
rig.tick(4.5, true);
|
||||
// The window's display changes resolution: until it is read again its density is unread.
|
||||
rig.displays[1].size = PhysicalSize::new(2560, 1440);
|
||||
assert_eq!(rig.tick(6.0, true).map(|d| d.main), Some(ScreenPpi::Unread), "the display is being read");
|
||||
assert_eq!(rig.reads.get(), 3);
|
||||
rig.finish(sizes(3));
|
||||
let sharper = rig.tick(6.1, true).and_then(|d| d.main.ppi());
|
||||
assert!(sharper.zip(right).is_some_and(|(s, r)| s > r), "more pixels on the same glass: {sharper:?}, {right:?}");
|
||||
// winit still gives the window's display at its old resolution: it is found by its name.
|
||||
let mut old = rig.displays[1].clone();
|
||||
old.size = PhysicalSize::new(1920, 1080);
|
||||
rig.lagging = Some(old);
|
||||
rig.window_scale = 1.25;
|
||||
let lagging = rig.tick(7.2, true).and_then(|d| d.main.ppi());
|
||||
assert!(lagging.zip(sharper).is_some_and(|(l, s)| (l * 1.25 - s).abs() < 1e-9), "{lagging:?} from {sharper:?}");
|
||||
rig.lagging = None;
|
||||
// It changes again and this time the reading fails: its density is unread.
|
||||
rig.displays[1].size = PhysicalSize::new(3840, 2160);
|
||||
let reading = rig.tick(8.5, true).unwrap_or_else(|| panic!("a report"));
|
||||
assert_eq!(reading.main, ScreenPpi::Unread, "the display is being read: {reading:?}");
|
||||
assert!(reading.screens.iter().any(|s| s.rect[2] == 3840 && s.ppi == ScreenPpi::Unread), "listed where it is now, unread: {reading:?}");
|
||||
rig.finish(Err("the display server went away".into()));
|
||||
assert_eq!(rig.tick(8.6, true), None, "the failed reading leaves it unread");
|
||||
}
|
||||
|
||||
/// A display that changes while a reading runs is read as soon as that reading ends.
|
||||
#[test]
|
||||
fn a_change_during_a_reading_is_read_when_it_ends() {
|
||||
let mut rig = Rig::new();
|
||||
rig.tick(0.0, true);
|
||||
rig.displays[1].size = PhysicalSize::new(2560, 1440);
|
||||
rig.tick(1.0, true);
|
||||
assert_eq!(rig.reads.get(), 1, "one reading at a time");
|
||||
rig.finish(sizes(2));
|
||||
rig.tick(1.2, true);
|
||||
assert_eq!(rig.reads.get(), 2, "the changed display is read at once");
|
||||
}
|
||||
|
||||
/// A display whose size could not be read does not hold back the others, and the displays are
|
||||
/// read again after a while.
|
||||
#[test]
|
||||
fn one_display_that_fails_leaves_the_others() {
|
||||
let mut rig = Rig::new();
|
||||
rig.tick(0.0, true);
|
||||
rig.finish(Ok(vec![Ok(Some(SIZES[0])), Err("no answer".into())]));
|
||||
let got = rig.tick(0.1, true).unwrap_or_else(|| panic!("the densities"));
|
||||
assert!(got.main.ppi().is_some() && got.screens[1].ppi == ScreenPpi::Unread, "the display that did not answer is unread: {got:?}");
|
||||
rig.tick(5.0, true);
|
||||
assert_eq!(rig.reads.get(), 1, "not again at once");
|
||||
rig.tick(0.1 + RETRY_AFTER, true);
|
||||
assert_eq!(rig.reads.get(), 2, "tried again");
|
||||
rig.finish(sizes(2));
|
||||
let full = rig.tick(11.0, true).unwrap_or_else(|| panic!("the densities"));
|
||||
assert!(full.screens.iter().all(|s| s.ppi.ppi().is_some()), "{full:?}");
|
||||
rig.tick(30.0, true);
|
||||
assert_eq!(rig.reads.get(), 2, "and left alone once every display was read");
|
||||
// A display joins, and the window's display, unchanged, fails to answer: it keeps its size.
|
||||
rig.displays.push(display("third", 3840));
|
||||
rig.tick(32.0, true);
|
||||
rig.finish(Ok(vec![Err("no answer".into()), Ok(Some(SIZES[1])), Ok(Some(SIZES[0]))]));
|
||||
let kept = rig.tick(32.1, true).unwrap_or_else(|| panic!("the densities"));
|
||||
assert!(kept.main.ppi().is_some() && kept.main == full.main, "{kept:?}");
|
||||
// A window on no display has its density unread.
|
||||
rig.current = 9;
|
||||
assert_eq!(rig.tick(34.0, true).map(|d| d.main), Some(ScreenPpi::Unread));
|
||||
// The window's display fails to answer the first reading: its density is unread, not a
|
||||
// display without a size.
|
||||
let mut rig = Rig::new();
|
||||
rig.tick(0.0, true);
|
||||
rig.finish(Ok(vec![Err("no answer".into()), Ok(Some(SIZES[1]))]));
|
||||
let first = rig.tick(0.1, true).unwrap_or_else(|| panic!("the densities"));
|
||||
assert_eq!((first.main, first.screens[0].ppi), (ScreenPpi::Unread, ScreenPpi::Unread), "{first:?}");
|
||||
}
|
||||
|
||||
/// A reading that fails, or a thread that cannot start, is tried again after a while; the
|
||||
/// same displays are not read on every listing until then.
|
||||
#[test]
|
||||
fn a_failed_reading_is_tried_again() {
|
||||
let mut rig = Rig::new();
|
||||
rig.tick(0.0, true);
|
||||
rig.finish(Err("the display server went away".into()));
|
||||
assert_eq!(rig.tick(1.0, true), None);
|
||||
assert_eq!(rig.reads.get(), 1, "not again at once");
|
||||
rig.tick(5.0, true);
|
||||
assert_eq!(rig.reads.get(), 1);
|
||||
rig.tick(1.0 + RETRY_AFTER, true);
|
||||
assert_eq!(rig.reads.get(), 2, "tried again");
|
||||
rig.finish(sizes(2));
|
||||
assert!(rig.tick(12.0, true).is_some_and(|d| d.main.ppi().is_some()), "and read");
|
||||
let mut rig = Rig::new();
|
||||
rig.fail_to_start = true;
|
||||
rig.tick(0.0, true);
|
||||
rig.tick(1.0 + RETRY_AFTER, true);
|
||||
assert_eq!(rig.reads.get(), 2, "a thread that did not start is tried again too");
|
||||
}
|
||||
|
||||
/// Displays that list the same are read again a while after the last reading, so a display
|
||||
/// replaced by one on the same connector at the same resolution and scale gets its own size.
|
||||
#[test]
|
||||
fn displays_that_list_the_same_are_read_again_after_a_while() {
|
||||
let mut rig = Rig::new();
|
||||
rig.tick(0.0, true);
|
||||
rig.finish(sizes(2));
|
||||
let first = rig.tick(0.1, true).unwrap_or_else(|| panic!("the densities"));
|
||||
rig.tick(0.1 + READ_AGAIN_AFTER - 1.0, true);
|
||||
assert_eq!(rig.reads.get(), 1, "not before the time is up");
|
||||
rig.tick(0.1 + READ_AGAIN_AFTER, true);
|
||||
assert_eq!(rig.reads.get(), 2, "read again");
|
||||
rig.finish(Ok(vec![Ok(Some(SIZES[1])), Ok(Some(SIZES[0]))]));
|
||||
let replaced = rig.tick(0.2 + READ_AGAIN_AFTER, true).unwrap_or_else(|| panic!("the densities"));
|
||||
assert!(replaced.main.ppi().is_some() && replaced.main != first.main, "the new panel's density: {first:?} then {replaced:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! Windows: a monitor's raw density, the pixels per inch of the screen itself as Windows reads it
|
||||
//! from the monitor, for Display Print Size at 100% Zoom (`crate::screen_density`).
|
||||
//!
|
||||
//! `GetDpiForMonitor` is a C API with no safe binding, hence the scoped `unsafe_code` allowance.
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use windows::Win32::Graphics::Gdi::HMONITOR;
|
||||
use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MDT_RAW_DPI};
|
||||
|
||||
/// The horizontal and vertical pixels per inch of the monitor winit's handle `monitor` names:
|
||||
/// `None` when Windows reports no density for it, an error when the call fails.
|
||||
pub(crate) fn raw_dpi(monitor: isize) -> Result<Option<[f64; 2]>, String> {
|
||||
let (mut x, mut y) = (0u32, 0u32);
|
||||
// SAFETY: `monitor` is a handle winit got from Windows for a connected monitor; a handle that
|
||||
// has gone stale makes the call fail, which returns an error. Both pointers point at live
|
||||
// `u32`s for the length of the call.
|
||||
unsafe { GetDpiForMonitor(HMONITOR(monitor as *mut core::ffi::c_void), MDT_RAW_DPI, &mut x, &mut y) }
|
||||
.map_err(|e| format!("couldn't read a monitor's density: {e}"))?;
|
||||
Ok((x > 0 && y > 0).then(|| [f64::from(x), f64::from(y)]))
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Windows pen tablets: with Windows Ink, winit reports a pen in contact as a touch and drops its
|
||||
//! barrel button and which end of the pen is down. For each pointer message of a pen,
|
||||
//! [`msg_hook`] reads the pen's `POINTER_PEN_INFO` before winit handles the message and writes its
|
||||
//! pressure, end, tilt and rotation into the framework's [`PenSource`] ([`start`]):
|
||||
//! pressure, end, tilt and rotation, and an airbrush pen's finger wheel, into the framework's
|
||||
//! [`PenSource`] ([`start`]):
|
||||
//! `PEN_FLAG_INVERTED` ("The pen is inverted") or `PEN_FLAG_ERASER` ("The eraser button is
|
||||
//! pressed") is the eraser end
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/pen-flags-constants>). Pointer
|
||||
@@ -24,9 +25,12 @@
|
||||
//! `rotation` in degrees 0..359 clockwise
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-pointer_pen_info>).
|
||||
//! Toward the user is down the screen, so they are the sample's axes and direction as they come,
|
||||
//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel.
|
||||
//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel, which
|
||||
//! comes from the tablet driver's Wintab interface instead, when it has one
|
||||
//! ([`crate::windows_wintab`]).
|
||||
#![cfg_attr(not(windows), allow(dead_code))]
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use craft::behavior::PointerSample;
|
||||
@@ -38,6 +42,8 @@ const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020;
|
||||
/// `POINTER_MESSAGE_FLAG_INRANGE` (`winuser.h`): not set on the message of a pointer that has left
|
||||
/// detection range.
|
||||
const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002;
|
||||
/// `POINTER_MESSAGE_FLAG_CANCELED` (`winuser.h`): the pointer's input was canceled.
|
||||
const POINTER_MESSAGE_FLAG_CANCELED: usize = 0x8000;
|
||||
/// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`.
|
||||
const PEN_FLAG_INVERTED: u32 = 0x0002;
|
||||
const PEN_FLAG_ERASER: u32 = 0x0004;
|
||||
@@ -65,6 +71,13 @@ const WM_POINTERLEAVE: u32 = 0x024A;
|
||||
/// A pen's tilt along x and y and its barrel rotation, in radians.
|
||||
type Pose = ([f32; 2], f32);
|
||||
|
||||
thread_local! {
|
||||
/// The pointer id of the pen whose leaving starts the Wintab wheel readings afresh: the pen that
|
||||
/// took them, or the pen whose message last asked for the wheel when none has
|
||||
/// ([`crate::windows_wintab::wheel_pen`]).
|
||||
static WHEEL_PEN: Cell<Option<u32>> = const { Cell::new(None) };
|
||||
}
|
||||
|
||||
/// The pen source [`msg_hook`] writes, once [`start`] has made it.
|
||||
static FEED: OnceLock<PenSource> = OnceLock::new();
|
||||
|
||||
@@ -89,14 +102,22 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
|
||||
let Some(pen) = FEED.get() else {
|
||||
return false;
|
||||
};
|
||||
crate::windows_wintab::msg_hook(msg);
|
||||
if forgets_wheel(msg.message, msg.wParam.0, WHEEL_PEN.get()) {
|
||||
crate::windows_wintab::forget();
|
||||
}
|
||||
let read_pen = || {
|
||||
let mut info = POINTER_PEN_INFO::default();
|
||||
let id = (msg.wParam.0 & 0xffff) as u32;
|
||||
// SAFETY: `info` is a `POINTER_PEN_INFO` that lives for the call. The call fails for a
|
||||
// pointer that is not a pen.
|
||||
unsafe { GetPointerPenInfo((msg.wParam.0 & 0xffff) as u32, &mut info) }.ok()?;
|
||||
unsafe { GetPointerPenInfo(id, &mut info) }.ok()?;
|
||||
let in_contact = info.pointerInfo.pointerFlags.0 & POINTER_FLAG_INCONTACT.0 != 0;
|
||||
let eraser = info.penFlags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0;
|
||||
let wheel = crate::windows_wintab::pen_wheel(msg.hwnd, msg.time, id, eraser);
|
||||
WHEEL_PEN.set(Some(crate::windows_wintab::wheel_pen(id)));
|
||||
let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation);
|
||||
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose))
|
||||
Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose, wheel))
|
||||
};
|
||||
// SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message.
|
||||
let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32);
|
||||
@@ -111,8 +132,10 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
|
||||
/// What a pen whose `POINTER_PEN_INFO` holds `pressure` (0..1024), `pen_mask` and `pen_flags`
|
||||
/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen
|
||||
/// in contact that reports none; the eraser end while it is inverted or its eraser button is
|
||||
/// pressed; and how it is held, `pose` ([`pen_pose`]).
|
||||
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose) -> PointerSample {
|
||||
/// pressed; how it is held, `pose` ([`pen_pose`]); and `wheel`, the airbrush finger wheel the tablet
|
||||
/// driver's Wintab interface reported for the message, if any ([`crate::windows_wintab`]), kept
|
||||
/// within 0..1 and none when it is not a number.
|
||||
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose, wheel: Option<f32>) -> PointerSample {
|
||||
let pressure = match pressure {
|
||||
1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0,
|
||||
_ if in_contact => 1.0,
|
||||
@@ -122,6 +145,7 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (t
|
||||
sample.tilt = tilt;
|
||||
sample.rotation = rotation;
|
||||
sample.eraser = pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0;
|
||||
sample.wheel = wheel.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 1.0));
|
||||
sample
|
||||
}
|
||||
|
||||
@@ -134,6 +158,43 @@ fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> Pose {
|
||||
([along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)], turn)
|
||||
}
|
||||
|
||||
/// Whether a message with this `wParam` starts the Wintab wheel readings afresh: a pointer message
|
||||
/// of a pointer that has left detection range or whose press was canceled, or a pointer leaving the
|
||||
/// window, when the pointer is `pen`, the pen whose leaving starts them afresh. A touch or another
|
||||
/// pen leaving keeps the readings.
|
||||
fn forgets_wheel(message: u32, wparam: usize, pen: Option<u32>) -> bool {
|
||||
if pen != Some((wparam & 0xffff) as u32) {
|
||||
return false;
|
||||
}
|
||||
let flags = wparam >> 16;
|
||||
match message {
|
||||
WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP => {
|
||||
flags & POINTER_MESSAGE_FLAG_INRANGE == 0 || flags & POINTER_MESSAGE_FLAG_CANCELED != 0
|
||||
}
|
||||
WM_POINTERLEAVE => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a pointer message that Windows sends to the window procedure, so that winit's message hook
|
||||
/// never sees it, starts the Wintab wheel readings afresh ([`forgets_wheel`]): `WM_POINTERENTER` and
|
||||
/// `WM_POINTERLEAVE` are sent
|
||||
/// (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/wm-pointerleave>); the posted pointer
|
||||
/// messages are left to [`msg_hook`].
|
||||
fn sent_forgets_wheel(message: u32, wparam: usize, pen: Option<u32>) -> bool {
|
||||
matches!(message, WM_POINTERENTER | WM_POINTERLEAVE) && forgets_wheel(message, wparam, pen)
|
||||
}
|
||||
|
||||
/// A message Windows sent to a window procedure of the thread, from the Wintab reader's hook on
|
||||
/// them ([`crate::windows_wintab`]): a pen leaving the window starts the wheel readings afresh, as
|
||||
/// [`msg_hook`] does for the messages it sees.
|
||||
#[cfg(windows)]
|
||||
pub fn sent_message(message: u32, wparam: usize) {
|
||||
if sent_forgets_wheel(message, wparam, WHEEL_PEN.get()) {
|
||||
crate::windows_wintab::forget();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse,
|
||||
/// not from a pen or a touch.
|
||||
fn is_mouse(extra_info: u32) -> bool {
|
||||
@@ -175,7 +236,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() {
|
||||
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT).eraser;
|
||||
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT, None).eraser;
|
||||
assert!(!eraser(0), "the tip");
|
||||
assert!(!eraser(PEN_FLAG_BARREL), "the barrel button");
|
||||
assert!(eraser(PEN_FLAG_INVERTED), "turned over");
|
||||
@@ -194,19 +255,77 @@ mod tests {
|
||||
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), ([0.0, 0.0], deg(359.0)), "a 6D Art Pen's barrel");
|
||||
assert_eq!(pen_pose(all, 400, i32::MIN, 720), ([deg(90.0), deg(-90.0)], 0.0), "kept within the ranges");
|
||||
let pose = pen_pose(all, 10, 20, 180);
|
||||
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose);
|
||||
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose, None);
|
||||
assert_eq!((sample.tilt, sample.rotation), pose);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_airbrush_wheel_goes_into_the_sample() {
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, Some(0.25)).wheel, Some(0.25));
|
||||
let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION;
|
||||
let pose = pen_pose(all, 10, 20, 180);
|
||||
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose, Some(0.75));
|
||||
assert_eq!((sample.tilt, sample.rotation, sample.wheel), (pose.0, pose.1, Some(0.75)), "with the tilt and rotation");
|
||||
assert_eq!(sample.pressure, 0.5, "the pressure as before");
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).wheel, None, "no wheel");
|
||||
assert_eq!(pen_sample(0, 0, 0, false, UPRIGHT, Some(f32::NAN)).wheel, None, "not a number");
|
||||
assert_eq!(pen_sample(0, 0, 0, false, UPRIGHT, Some(1.5)).wheel, Some(1.0), "kept within 0..1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_range_or_the_window_and_a_cancel_forget_the_wheel() {
|
||||
let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7;
|
||||
let canceled = ((POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_CANCELED) << 16) | 7;
|
||||
let pen = Some(7);
|
||||
for m in [WM_POINTERENTER, WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] {
|
||||
assert!(!forgets_wheel(m, in_range, pen), "{m:#x}");
|
||||
assert!(forgets_wheel(m, 7, pen), "out of range: {m:#x}");
|
||||
assert!(forgets_wheel(m, canceled, pen), "canceled: {m:#x}");
|
||||
}
|
||||
assert!(forgets_wheel(WM_POINTERLEAVE, in_range, pen));
|
||||
// WM_MOUSEMOVE and WT_PACKET.
|
||||
assert!(!forgets_wheel(0x0200, 0, Some(0)));
|
||||
assert!(!forgets_wheel(0x7FF0, 7, pen));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_pointer_leaving_keeps_the_wheel() {
|
||||
// A touch, pointer 9, leaves the window and detection range while pen 7 hovers.
|
||||
let touch_leaves = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9;
|
||||
assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, Some(7)));
|
||||
assert!(!forgets_wheel(WM_POINTERUPDATE, 9, Some(7)), "out of range");
|
||||
let canceled = (POINTER_MESSAGE_FLAG_CANCELED << 16) | 9;
|
||||
assert!(!forgets_wheel(WM_POINTERUP, canceled, Some(7)), "canceled");
|
||||
assert!(!forgets_wheel(WM_POINTERLEAVE, touch_leaves, None), "no pen has read the wheel");
|
||||
assert!(forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7, Some(7)), "the pen itself");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sent_leave_of_the_wheel_pen_forgets_the_wheel() {
|
||||
let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7;
|
||||
let pen = Some(7);
|
||||
assert!(sent_forgets_wheel(WM_POINTERLEAVE, in_range, pen), "the pen leaves the window");
|
||||
assert!(sent_forgets_wheel(WM_POINTERLEAVE, 7, pen), "or detection range");
|
||||
assert!(!sent_forgets_wheel(WM_POINTERLEAVE, (POINTER_MESSAGE_FLAG_INRANGE << 16) | 9, pen), "another pointer leaves");
|
||||
assert!(!sent_forgets_wheel(WM_POINTERLEAVE, in_range, None), "no pen has read the wheel");
|
||||
assert!(!sent_forgets_wheel(WM_POINTERENTER, in_range, pen), "the pen comes over the window");
|
||||
// Posted messages, which the message hook already sees.
|
||||
for m in [WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] {
|
||||
assert!(!sent_forgets_wheel(m, 7, pen), "{m:#x}");
|
||||
}
|
||||
// WT_CTXCLOSE.
|
||||
assert!(!sent_forgets_wheel(0x7FF2, 7, pen));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pens_pressure_is_the_one_winit_gives_its_touch() {
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 0.5);
|
||||
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0);
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT), eraser_sample(0.0), "hovering");
|
||||
assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
|
||||
assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT).pressure, 1.0, "a pressure without the pressure mask is not one");
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0, "as winit, which gives no force for 0");
|
||||
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT).pressure, 0.0);
|
||||
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 0.5);
|
||||
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0);
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT, None), eraser_sample(0.0), "hovering");
|
||||
assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
|
||||
assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT, None).pressure, 1.0, "a pressure without the pressure mask is not one");
|
||||
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT, None).pressure, 1.0, "as winit, which gives no force for 0");
|
||||
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT, None).pressure, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M19 12H5M10.5 6.5L5 12L10.5 17.5" stroke-width="1.6" /></svg>
|
||||
|
After Width: | Height: | Size: 253 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M5 12H19M13.5 6.5L19 12L13.5 17.5" stroke-width="1.6" /></svg>
|
||||
|
After Width: | Height: | Size: 254 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3" y="8" width="13" height="8" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M16 4V20" stroke-width="1" /></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="2" y="7" width="11" height="10" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>
|
||||
|
Before Width: | Height: | Size: 321 B After Width: | Height: | Size: 323 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M3 8H12A4 4 0 0 1 12 16H3Z" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M12 4V20" stroke-width="1" /></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M2 7H13A5 5 0 0 1 13 17H2Z" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>
|
||||
|
Before Width: | Height: | Size: 318 B After Width: | Height: | Size: 319 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="3" y="8" width="17" height="8" fill="currentColor" fill-opacity="1.0" stroke="none"/><path d="M16 4V20" stroke-width="1" /></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><rect x="2" y="7" width="16" height="10" fill="currentColor" fill-opacity="0.55" stroke="none"/><path d="M13 3V21" stroke-width="1" /></svg>
|
||||
|
Before Width: | Height: | Size: 321 B After Width: | Height: | Size: 323 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="4" height="18"/><path d="M5 6.5h2M5 9.5h2M5 14.5h2M5 17.5h2"/><path d="M9.5 12H21"/></svg>
|
||||
|
After Width: | Height: | Size: 299 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="4"/><path d="M6.5 5v2M9.5 5v2M14.5 5v2M17.5 5v2"/><path d="M12 9.5V21"/></svg>
|
||||
|
After Width: | Height: | Size: 299 B |
@@ -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] {
|
||||
@@ -1315,3 +1348,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
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
use super::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// The data files ship exactly as Fogra publishes them in
|
||||
/// https://fogra.org/fileadmin/files/7_downloads/Charakterisierungsdaten/F51-52.zip.
|
||||
#[test]
|
||||
fn characterization_data_is_the_published_files() {
|
||||
let want = [
|
||||
("FOGRA51", "ad472a1c0bdafd558597ff93eeda5175805086565af814cb6346e910e2f25aa5", 57_111),
|
||||
("FOGRA52", "be4f0732328ed62ade63ec7f317d3b9e9dad6bbe2430fefddaf0f901d5ba13d6", 56_781),
|
||||
];
|
||||
for (c, (reference, sha, len)) in measured::CONDITIONS.iter().zip(want) {
|
||||
assert_eq!(c.reference, reference);
|
||||
assert_eq!((c.data.len(), hex(c.data).as_str()), (len, sha), "{reference}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_data_parses_into_its_patches() {
|
||||
for c in &measured::CONDITIONS {
|
||||
let patches = measured::parse(c.data).unwrap();
|
||||
assert_eq!(patches.len(), 1617, "{}", c.reference);
|
||||
assert_eq!(patches[0].cmyk, [0.0; 4]);
|
||||
}
|
||||
let p = measured::parse(measured::CONDITIONS[0].data).unwrap();
|
||||
assert_eq!(p[0].lab, Lab::new(95.0, 1.5, -6.0));
|
||||
assert_eq!(p[1].cmyk, [0.0, 0.1, 0.0, 0.0]);
|
||||
assert_eq!(p[1].lab, Lab::new(90.08, 8.15, -7.42));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_data_is_refused() {
|
||||
let file = |format: &str, rows: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{format}\nEND_DATA_FORMAT\nBEGIN_DATA\n{rows}\nEND_DATA\n");
|
||||
let fields = "SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B";
|
||||
let good = file(fields, "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50");
|
||||
assert_eq!(measured::parse(good.as_bytes()).map(|p| p.len()), Some(2));
|
||||
for bad in [
|
||||
file("SAMPLE_ID CMYK_C CMYK_M CMYK_Y LAB_L LAB_A LAB_B", "1 0 0 0 95 1 -6"),
|
||||
file(fields, "1 0 0 0 0 95 1"),
|
||||
file(fields, "1 0 0 0 0 95 NaN -6"),
|
||||
file(fields, "1 0 0 0 0 95 x -6"),
|
||||
file(fields, "1 0 0 0 101 95 1 -6"),
|
||||
file(fields, "1 -1 0 0 0 95 1 -6"),
|
||||
file(fields, ""),
|
||||
"BEGIN_DATA\n1 0 0 0 0 95 1 -6\nEND_DATA\n".into(),
|
||||
] {
|
||||
assert_eq!(measured::parse(bad.as_bytes()), None, "{bad}");
|
||||
}
|
||||
assert_eq!(measured::parse(&[0xff, 0xfe, 0x00]), None);
|
||||
// The rows end with END_DATA, and a NUMBER_OF_SETS in the header counts them.
|
||||
let rows = "1 0 0 0 0 95 1 -6\n2 100 0 0 0 55 -37 -50";
|
||||
let header = |sets: &str| format!("ISO28178\nBEGIN_DATA_FORMAT\n{fields}\nEND_DATA_FORMAT\n{sets}\nBEGIN_DATA\n{rows}\n");
|
||||
assert_eq!(measured::parse(header("NUMBER_OF_SETS\t2").as_bytes()), None, "no END_DATA");
|
||||
for (sets, len) in [
|
||||
("NUMBER_OF_SETS\t2", Some(2)),
|
||||
("NUMBER_OF_SETS\t3", None),
|
||||
("NUMBER_OF_SETS\t1", None),
|
||||
("NUMBER_OF_SETS\tx", None),
|
||||
("NUMBER_OF_SETS", None),
|
||||
] {
|
||||
assert_eq!(measured::parse(format!("{}END_DATA\n", header(sets)).as_bytes()).map(|p| p.len()), len, "{sets}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A paper measured as black has no XYZ to make the other patches relative to.
|
||||
#[test]
|
||||
fn a_paper_without_light_is_refused() {
|
||||
let c = &measured::CONDITIONS[0];
|
||||
let mut patches = measured::parse(c.data).unwrap();
|
||||
for p in patches.iter_mut().filter(|p| p.cmyk == [0.0; 4]) {
|
||||
p.lab = Lab::new(0.0, 0.0, 0.0);
|
||||
}
|
||||
assert!(measured::fit(c, &patches, measured::SMOOTHING).is_none());
|
||||
}
|
||||
|
||||
/// ΔE2000 between each measured patch and the model's absolute Lab for its inks: (mean, max).
|
||||
fn accuracy(g: &GenericCmyk, patches: &[measured::Patch]) -> (f32, f32) {
|
||||
let errors: Vec<f32> = patches.iter().map(|p| delta_e2000(g.to_lab_abs(p.cmyk), p.lab)).collect();
|
||||
(errors.iter().sum::<f32>() / errors.len() as f32, errors.iter().copied().fold(0.0, f32::max))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_working_spaces_reproduce_the_measured_patches() {
|
||||
for c in &measured::CONDITIONS {
|
||||
let patches = measured::parse(c.data).unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
let g = measured::model(c).unwrap();
|
||||
let took = start.elapsed();
|
||||
let (mean, max) = accuracy(&g, &patches);
|
||||
println!("{}: computed in {took:?}, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference);
|
||||
assert!(mean < 0.1 && max < 0.6, "{}: mean {mean}, max {max}", c.reference);
|
||||
// The paper is the measured blank patch.
|
||||
assert!(delta_e2000(g.to_lab_abs([0.0; 4]), patches[0].lab) < 0.05);
|
||||
}
|
||||
}
|
||||
|
||||
/// A model fitted without every fourth patch (the paper and the solids and overprints stay in)
|
||||
/// predicts the patches it left out. The data repeats some builds, and every row of a build is
|
||||
/// on the side of the build's first row, so the fit never sees a left-out build.
|
||||
#[test]
|
||||
fn the_fit_predicts_patches_it_left_out() {
|
||||
for c in &measured::CONDITIONS {
|
||||
let patches = measured::parse(c.data).unwrap();
|
||||
let corner = |p: &measured::Patch| p.cmyk.iter().all(|v| *v == 0.0 || *v == 1.0);
|
||||
let first = |p: &measured::Patch| patches.iter().position(|q| q.cmyk == p.cmyk).unwrap_or(0);
|
||||
let (kept, left): (Vec<&measured::Patch>, Vec<_>) = patches.iter().partition(|p| first(p) % 4 != 3 || corner(p));
|
||||
assert!(left.iter().all(|l| kept.iter().all(|k| k.cmyk != l.cmyk)), "{}", c.reference);
|
||||
let kept: Vec<measured::Patch> = kept.into_iter().copied().collect();
|
||||
let left: Vec<measured::Patch> = left.into_iter().copied().collect();
|
||||
let g = measured::fit(c, &kept, measured::SMOOTHING).unwrap();
|
||||
let (mean, max) = accuracy(&g, &left);
|
||||
println!("{}: {} patches left out, mean ΔE2000 {mean:.3}, max {max:.3}", c.reference, left.len());
|
||||
assert!(mean < 0.3 && max < 2.5, "{}: mean {mean}, max {max}", c.reference);
|
||||
}
|
||||
}
|
||||
|
||||
/// More of any ink makes a build lighter by less than 0.3 L*, also where the data has few patches
|
||||
/// (black above 60%, and builds over the ink limit).
|
||||
#[test]
|
||||
fn more_ink_lightens_a_build_by_less_than_0_3_l() {
|
||||
let steps: Vec<f32> = (0..=20).map(|i| i as f32 / 20.0).collect();
|
||||
let coarse = [0.0, 0.25, 0.5, 0.75, 1.0];
|
||||
for c in &measured::CONDITIONS {
|
||||
let g = measured::model(c).unwrap();
|
||||
let mut worst = 0f32;
|
||||
for ink in 0..4 {
|
||||
for a in coarse {
|
||||
for b in coarse {
|
||||
for d in coarse {
|
||||
let mut others = [a, b, d].into_iter();
|
||||
let mut build = [0f32; 4];
|
||||
for (i, slot) in build.iter_mut().enumerate() {
|
||||
if i != ink {
|
||||
*slot = others.next().unwrap();
|
||||
}
|
||||
}
|
||||
let mut last = f32::INFINITY;
|
||||
for &v in &steps {
|
||||
build[ink] = v;
|
||||
let l = g.to_lab_rel(build).l;
|
||||
worst = worst.max(l - last);
|
||||
last = l;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("{}: largest L* rise with more ink {worst:.3}", c.reference);
|
||||
assert!(worst < 0.3, "{}: {worst}", c.reference);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_working_spaces_follow_generic_cmyk_in_the_list() {
|
||||
let cmyk: Vec<String> = profiles().into_iter().filter(|p| p.kind == ProfileKind::Cmyk && p.builtin).map(|p| p.name).collect();
|
||||
assert_eq!(cmyk, [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK, DEVICE_CMYK]);
|
||||
assert_eq!(ColorSettings::default().cmyk, GENERIC_CMYK);
|
||||
assert_eq!(characterization(FOGRA51_CMYK), Some(("FOGRA51", "http://www.color.org")));
|
||||
assert_eq!(characterization(FOGRA52_CMYK), Some(("FOGRA52", "http://www.color.org")));
|
||||
assert_eq!(characterization(GENERIC_CMYK), None);
|
||||
assert!(matches!(register_icc(&icc_bytes(FOGRA51_CMYK).unwrap(), None), Err(CmsError::Unsupported(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_separate_and_come_back_in_the_measured_spaces() {
|
||||
for name in [FOGRA51_CMYK, FOGRA52_CMYK] {
|
||||
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap();
|
||||
// A 50% gray (L* 53) lies well inside both measured gamuts (the darkest patches measure
|
||||
// L* 11.43 and 26.36), so it comes back whatever the gamut check says.
|
||||
let gray = [0.5, 0.5, 0.5];
|
||||
for srgb in [[0.8, 0.3, 0.2], [0.2, 0.5, 0.7], gray, [0.9, 0.85, 0.6], [0.1, 0.1, 0.1]] {
|
||||
let inks = cms.srgb_to_cmyk(srgb, Intent::RelativeColorimetric);
|
||||
assert!(inks.iter().sum::<f32>() <= 3.0 + 1e-3, "{name} {srgb:?}: {inks:?}");
|
||||
if srgb == gray || cms.gamut_error(&Color::Rgb { r: srgb[0], g: srgb[1], b: srgb[2] }) < GAMUT_THRESHOLD {
|
||||
let back = cms.cmyk_to_srgb(inks, false);
|
||||
let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(back));
|
||||
assert!(de < 1.5, "{name} {srgb:?}: {inks:?} -> {back:?} (ΔE {de})");
|
||||
}
|
||||
}
|
||||
// White is paper with no ink, and black is the darkest build within the ink limit.
|
||||
assert_eq!(cms.srgb_to_cmyk([1.0; 3], Intent::RelativeColorimetric), [0.0; 4]);
|
||||
let black = cms.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric);
|
||||
assert!(black[3] > 0.8 && black.iter().sum::<f32>() <= 3.0 + 1e-3, "{name}: {black:?}");
|
||||
}
|
||||
// The coated paper prints a larger gamut than the uncoated one.
|
||||
let blue = Color::Rgb { r: 0.1, g: 0.2, b: 0.6 };
|
||||
let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap();
|
||||
let uncoated = Cms::new(&ColorSettings { cmyk: FOGRA52_CMYK.into(), ..ColorSettings::default() }).unwrap();
|
||||
assert!(coated.gamut_error(&blue) < uncoated.gamut_error(&blue));
|
||||
}
|
||||
|
||||
/// Absolute Lab of `cmyk` in a context whose CMYK space is one of the Generic-type spaces.
|
||||
fn absolute_lab(cms: &Cms, cmyk: [f32; 4]) -> Lab {
|
||||
match &cms.cmyk {
|
||||
CmykSpace::Generic(g) => g.to_lab_abs(cmyk),
|
||||
CmykSpace::Device | CmykSpace::Icc(_) => panic!("not a Generic-type CMYK space"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_cmyk_to_rgb_shows_the_paper() {
|
||||
for name in [GENERIC_CMYK, FOGRA51_CMYK, FOGRA52_CMYK] {
|
||||
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() }).unwrap();
|
||||
let paper = cms.cmyk_to_rgb([0.0; 4], Intent::AbsoluteColorimetric);
|
||||
assert_eq!(paper, cms.srgb_to_rgb(cms.cmyk_to_srgb([0.0; 4], true)), "{name}");
|
||||
assert_ne!(paper, cms.cmyk_to_rgb([0.0; 4], Intent::RelativeColorimetric), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_cmyk_conversion_keeps_the_source_paper() {
|
||||
// Generic CMYK's paper (L* 93, b* 2.5) is darker and yellower than FOGRA51's (L* 95, b* -6),
|
||||
// so printing it on FOGRA51 paper takes ink.
|
||||
let generic = Cms::new(&ColorSettings { cmyk: GENERIC_CMYK.into(), ..ColorSettings::default() }).unwrap();
|
||||
let coated = Cms::new(&ColorSettings { cmyk: FOGRA51_CMYK.into(), ..ColorSettings::default() }).unwrap();
|
||||
let Color::Cmyk { c, m, y, k } = generic.convert_into(&coated, &Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 0.0 }, Intent::AbsoluteColorimetric)
|
||||
else {
|
||||
panic!("a CMYK colour converts to CMYK");
|
||||
};
|
||||
let inks = [c, m, y, k];
|
||||
assert!(inks.iter().sum::<f32>() > 0.01, "{inks:?}");
|
||||
let de = delta_e2000(absolute_lab(&coated, inks), absolute_lab(&generic, [0.0; 4]));
|
||||
assert!(de < 2.0, "{inks:?}: ΔE {de}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_profiles_carry_the_paper_and_the_data_source() {
|
||||
for c in &measured::CONDITIONS {
|
||||
let start = std::time::Instant::now();
|
||||
let bytes = icc_bytes(c.name).unwrap();
|
||||
println!("{}: {} bytes in {:?}", c.reference, bytes.len(), start.elapsed());
|
||||
let p = moxcms::ColorProfile::new_from_slice(&bytes).unwrap();
|
||||
assert_eq!(
|
||||
(p.profile_class, p.color_space, p.pcs),
|
||||
(moxcms::ProfileClass::OutputDevice, moxcms::DataColorSpace::Cmyk, moxcms::DataColorSpace::Lab)
|
||||
);
|
||||
assert!(p.lut_a_to_b_perceptual.is_some() && p.lut_b_to_a_perceptual.is_some() && p.lut_a_to_b_colorimetric.is_some());
|
||||
let paper = lab::lab_to_xyz(measured::parse(c.data).unwrap()[0].lab);
|
||||
let white = p.media_white_point.unwrap();
|
||||
for (got, want) in [white.x, white.y, white.z].iter().zip(paper) {
|
||||
assert!((*got - f64::from(want)).abs() < 2e-3, "{}: {white:?} vs {paper:?}", c.reference);
|
||||
}
|
||||
let text = format!("{:?}", p.copyright);
|
||||
assert!(text.contains(c.reference) && text.contains("Fogra"), "{text}");
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ pub mod oklab;
|
||||
pub mod palette_io;
|
||||
pub mod recolor;
|
||||
pub mod swatch;
|
||||
pub mod wcag;
|
||||
|
||||
pub use blend::BlendMode;
|
||||
pub use freeform::{Freeform, FreeformMode, FreeformPoint};
|
||||
|
||||
@@ -12,7 +12,7 @@ pub const CHROMA_FULL: f64 = 0.4;
|
||||
pub const POWERLESS_CHROMA: f64 = 0.000_004;
|
||||
|
||||
/// How far outside 0..=1 an sRGB component may be and still count as inside the gamut.
|
||||
const GAMUT_SLACK: f64 = 1e-4;
|
||||
const GAMUT_SLACK: f64 = 1e-5;
|
||||
|
||||
/// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they
|
||||
/// are. The hue is in 0..360, and 0 while the chroma is powerless.
|
||||
@@ -46,7 +46,7 @@ pub fn max_chroma(l: f64, h: f64) -> f64 {
|
||||
///
|
||||
/// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of
|
||||
/// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313,
|
||||
/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic
|
||||
/// and the ray can leave and return near black as well. Each linear sRGB channel is a cubic
|
||||
/// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The
|
||||
/// search finds each such chroma between the cubic's turning points and takes the largest one that
|
||||
/// fits.
|
||||
@@ -69,8 +69,7 @@ fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 {
|
||||
let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)];
|
||||
let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)];
|
||||
let mut ends = vec![0.0];
|
||||
for ch in 0..3 {
|
||||
let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]];
|
||||
for (((y0, y1), y2), y3) in y[0].into_iter().zip(y[1]).zip(y[2]).zip(y[3]) {
|
||||
let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0);
|
||||
let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0];
|
||||
let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0];
|
||||
@@ -113,11 +112,16 @@ fn turning_points(a: f64, b: f64, c: f64) -> Vec<f64> {
|
||||
|
||||
/// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered:
|
||||
/// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that
|
||||
/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more.
|
||||
/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. Lightness 0 gives exactly black and
|
||||
/// lightness 1 exactly white, as CSS Color 4 specifies, and a positive chroma there counts as
|
||||
/// lowered.
|
||||
pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) {
|
||||
let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) };
|
||||
let c = if c.is_nan() { 0.0 } else { c.max(0.0) };
|
||||
let h = if h.is_finite() { h } else { 0.0 };
|
||||
if l == 0.0 || l == 1.0 {
|
||||
return ([l as f32; 3], c > 0.0);
|
||||
}
|
||||
let exact = oklch_to_srgb(l, c, h);
|
||||
let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) };
|
||||
(rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered)
|
||||
@@ -240,12 +244,10 @@ mod tests {
|
||||
}
|
||||
|
||||
/// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at
|
||||
/// every hue and at lightnesses near black too, where the ray can come back into sRGB away from
|
||||
/// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012).
|
||||
/// every hue and at lightnesses near black too.
|
||||
#[test]
|
||||
fn the_largest_chroma_is_never_below_a_scan_of_the_ray() {
|
||||
let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max);
|
||||
assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0));
|
||||
for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] {
|
||||
for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) {
|
||||
let max = max_chroma(l, h);
|
||||
@@ -263,4 +265,26 @@ mod tests {
|
||||
assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]);
|
||||
assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]);
|
||||
}
|
||||
|
||||
/// The lightness endpoints give exactly black and white at any chroma and hue, and report a
|
||||
/// positive chroma as lowered. A rounded 8-bit comparison would hide a small leftover channel.
|
||||
#[test]
|
||||
fn the_lightness_endpoints_give_exact_black_and_white() {
|
||||
assert_eq!(from_oklch(0.0, 0.04, 0.0), ([0.0; 3], true));
|
||||
assert_eq!(from_oklch(0.0, 0.0, 120.0), ([0.0; 3], false));
|
||||
assert_eq!(from_oklch(1.0, 0.1, 250.0), ([1.0; 3], true));
|
||||
assert_eq!(from_oklch(1.0, 0.0, 0.0), ([1.0; 3], false));
|
||||
}
|
||||
|
||||
/// A color whose green is 0.000024 below sRGB is outside it: it is lowered to the chroma that
|
||||
/// fits, not clipped at its own chroma.
|
||||
#[test]
|
||||
fn a_channel_just_below_zero_is_outside_the_gamut() {
|
||||
assert!(!in_srgb(oklch_to_srgb(0.01, 0.01, 0.0)));
|
||||
let (rgb, lowered) = from_oklch(0.01, 0.01, 0.0);
|
||||
assert!(lowered, "{rgb:?}");
|
||||
let [_, c, _] = to_oklch(rgb);
|
||||
assert!(c < 0.01, "{c}");
|
||||
assert!(in_srgb(oklch_to_srgb(0.01, max_chroma(0.01, 0.0), 0.0)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//! Contrast between two colors as WCAG 2 measures it (<https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio>):
|
||||
//! the relative luminance of display sRGB with the 0.04045 threshold, the ratio
|
||||
//! (L1 + 0.05) / (L2 + 0.05) from 1 to 21, and the minimum ratios of success criteria 1.4.3
|
||||
//! (Contrast (Minimum), AA), 1.4.6 (Contrast (Enhanced), AAA) and 1.4.11 (Non-text Contrast, AA).
|
||||
|
||||
/// What the content in front is, which sets the ratio it needs.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Category {
|
||||
/// Text below the large-scale size: AA 4.5:1, AAA 7:1.
|
||||
#[default]
|
||||
NormalText,
|
||||
/// Large-scale text (at least 18 pt, or 14 pt bold): AA 3:1, AAA 4.5:1.
|
||||
LargeText,
|
||||
/// User interface components and graphical objects: AA 3:1, no AAA level.
|
||||
Graphics,
|
||||
}
|
||||
|
||||
impl Category {
|
||||
pub const ALL: [Category; 3] = [Category::NormalText, Category::LargeText, Category::Graphics];
|
||||
|
||||
/// The id commands and settings use.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Category::NormalText => "normalText",
|
||||
Category::LargeText => "largeText",
|
||||
Category::Graphics => "graphics",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|c| c.id() == s)
|
||||
}
|
||||
|
||||
/// The English name shown in menus.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Category::NormalText => "Normal Text",
|
||||
Category::LargeText => "Large Text",
|
||||
Category::Graphics => "Graphics",
|
||||
}
|
||||
}
|
||||
|
||||
/// The minimum ratio for AA, and for AAA where the category has that level.
|
||||
pub fn minimums(self) -> (f64, Option<f64>) {
|
||||
match self {
|
||||
Category::NormalText => (4.5, Some(7.0)),
|
||||
Category::LargeText => (3.0, Some(4.5)),
|
||||
Category::Graphics => (3.0, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `ratio` meets AA, and AAA where the category has that level. The unrounded ratio
|
||||
/// is compared, so 4.499:1 fails 4.5:1.
|
||||
pub fn passes(self, ratio: f64) -> (bool, Option<bool>) {
|
||||
let (aa, aaa) = self.minimums();
|
||||
(ratio >= aa, aaa.map(|m| ratio >= m))
|
||||
}
|
||||
}
|
||||
|
||||
/// The relative luminance of display sRGB `srgb` (each channel 0 to 1), from 0 for black to 1
|
||||
/// for white.
|
||||
pub fn relative_luminance(srgb: [f32; 3]) -> f64 {
|
||||
let lin = |v: f32| {
|
||||
let v = f64::from(v.clamp(0.0, 1.0));
|
||||
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
|
||||
};
|
||||
0.2126 * lin(srgb[0]) + 0.7152 * lin(srgb[1]) + 0.0722 * lin(srgb[2])
|
||||
}
|
||||
|
||||
/// The contrast ratio of display sRGB colors `a` and `b`, from 1 to 21, whichever is lighter.
|
||||
pub fn contrast_ratio(a: [f32; 3], b: [f32; 3]) -> f64 {
|
||||
let (la, lb) = (relative_luminance(a), relative_luminance(b));
|
||||
(la.max(lb) + 0.05) / (la.min(lb) + 0.05)
|
||||
}
|
||||
|
||||
/// Display sRGB `fg` drawn at `opacity` (0 to 1) over the opaque `bg`, mixed per channel as the
|
||||
/// canvas mixes a translucent color.
|
||||
pub fn over(fg: [f32; 3], opacity: f32, bg: [f32; 3]) -> [f32; 3] {
|
||||
let a = if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 1.0 };
|
||||
std::array::from_fn(|i| fg[i] * a + bg[i] * (1.0 - a))
|
||||
}
|
||||
|
||||
/// `ratio` as text with two decimals, cut off rather than rounded, so a ratio just under a
|
||||
/// minimum never reads as the minimum: 4.4963 is "4.49:1".
|
||||
pub fn ratio_text(ratio: f64) -> String {
|
||||
let r = if ratio.is_finite() { ratio.clamp(1.0, 21.0) } else { 1.0 };
|
||||
format!("{:.2}:1", (r * 100.0).floor() / 100.0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn hex(s: &str) -> [f32; 3] {
|
||||
let v = |i: usize| u8::from_str_radix(&s[i..i + 2], 16).map_or(0.0, |b| f32::from(b) / 255.0);
|
||||
[v(0), v(2), v(4)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_on_white_is_21_and_a_color_on_itself_is_1() {
|
||||
assert!((contrast_ratio(hex("000000"), hex("ffffff")) - 21.0).abs() < 1e-9);
|
||||
assert!((contrast_ratio(hex("ffffff"), hex("000000")) - 21.0).abs() < 1e-9);
|
||||
assert!((contrast_ratio(hex("355f78"), hex("355f78")) - 1.0).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ratios_near_a_minimum_are_compared_unrounded_and_cut_off_in_text() {
|
||||
let r = contrast_ratio(hex("fdc96e"), hex("355f78"));
|
||||
assert!((r - 4.4963).abs() < 1e-3, "{r}");
|
||||
assert_eq!(ratio_text(r), "4.49:1");
|
||||
assert_eq!(Category::NormalText.passes(r), (false, Some(false)));
|
||||
assert_eq!(Category::LargeText.passes(r), (true, Some(false)));
|
||||
let gray = contrast_ratio(hex("767676"), hex("ffffff"));
|
||||
assert!((gray - 4.542).abs() < 1e-3, "{gray}");
|
||||
assert_eq!(ratio_text(gray), "4.54:1");
|
||||
assert!(Category::NormalText.passes(gray).0);
|
||||
let lighter = contrast_ratio(hex("777777"), hex("ffffff"));
|
||||
assert!((lighter - 4.478).abs() < 1e-3, "{lighter}");
|
||||
assert_eq!(ratio_text(lighter), "4.47:1");
|
||||
assert!(!Category::NormalText.passes(lighter).0);
|
||||
assert_eq!(ratio_text(21.0), "21.00:1");
|
||||
assert_eq!(ratio_text(f64::NAN), "1.00:1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphics_have_no_aaa_level() {
|
||||
assert_eq!(Category::Graphics.passes(3.0), (true, None));
|
||||
assert_eq!(Category::Graphics.passes(2.99), (false, None));
|
||||
assert_eq!(Category::LargeText.passes(4.5), (true, Some(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn category_ids_parse_back() {
|
||||
for c in Category::ALL {
|
||||
assert_eq!(Category::parse(c.id()), Some(c));
|
||||
}
|
||||
assert_eq!(Category::parse("NormalText"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_opaque_black_over_white_is_mid_gray() {
|
||||
assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]);
|
||||
assert_eq!(over([0.2; 3], f32::NAN, [1.0; 3]), [0.2; 3]);
|
||||
assert_eq!(over([0.2; 3], 2.0, [1.0; 3]), [0.2; 3]);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,15 @@ use super::node::{held_guides, map_held, strip_held};
|
||||
use super::{Affine, Arc, Document, Node, NodeId, NodeKind, PatternDef, Point, Rect, Selection, SymbolBoxes, Vec2, artboard_holds};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
/// What a transform makes of a ruler guide ([`Document::transformed_guide`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum GuideTransform {
|
||||
/// It stays a ruler guide: vertical at x `pos`, or horizontal at y `pos`.
|
||||
Ruler { vertical: bool, pos: f64 },
|
||||
/// It becomes a guide path along the line between the two points.
|
||||
Path(Point, Point),
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Union of the geometric bounds of `ids` (their visual bounds when `visual`), with symbol
|
||||
/// instances measured by their art ([`Node::geometric_bounds_with`]).
|
||||
@@ -369,6 +378,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))
|
||||
|
||||
@@ -116,7 +116,7 @@ pub use metadata::{CopyrightStatus, DocMetadata};
|
||||
pub use node::Knockout;
|
||||
pub use node::Scaling;
|
||||
pub use node::{Extras, ExtrasMut, ImageObject, LAYER_COLORS, LayerColor, LiveShape, Node, NodeExtras, NodeId, NodeKind, OpacityMask};
|
||||
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS};
|
||||
pub use node::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
pub use orient::OrientedBox;
|
||||
pub use pattern::{Overlap, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType};
|
||||
pub use perspective::PerspectiveAttachment;
|
||||
@@ -168,6 +168,7 @@ pub use artboard::{ARTBOARD_GAP, Artboard, ArtboardSide, LockedArtboards, Retire
|
||||
pub use canvas_range::BeyondCanvas;
|
||||
#[cfg(test)]
|
||||
use document_ext::free_id;
|
||||
pub use document_guides::GuideTransform;
|
||||
pub use graphic_style::{DEFAULT_GRAPHIC_STYLE, GraphicStyle};
|
||||
pub use guides::{GridPrefs, Guide, RulerMode};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -278,6 +278,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
|
||||
if let Some(e) = n.extras_box() {
|
||||
b += ALLOC + size_of::<NodeExtras>();
|
||||
b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective);
|
||||
b += e.attrs.as_deref().map_or(0, attrs_bytes);
|
||||
b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize);
|
||||
b += e
|
||||
.color_mask
|
||||
@@ -404,6 +405,22 @@ fn swatches_bytes(s: &[Swatch]) -> usize {
|
||||
ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap_bytes(&w.paint)).sum::<usize>()
|
||||
}
|
||||
|
||||
/// The heap an object's attributes own: their text, data, events, classes, foreign attributes and
|
||||
/// tags.
|
||||
fn attrs_bytes(a: &crate::ObjectAttributes) -> usize {
|
||||
let pairs = |v: &Vec<(String, String)>| vec_bytes(v) + v.iter().map(|(k, v)| k.capacity() + v.capacity()).sum::<usize>();
|
||||
a.url.capacity()
|
||||
+ a.note.capacity()
|
||||
+ pairs(&a.data)
|
||||
+ pairs(&a.events)
|
||||
+ vec_bytes(&a.classes)
|
||||
+ a.classes.iter().map(String::capacity).sum::<usize>()
|
||||
+ vec_bytes(&a.foreign)
|
||||
+ a.foreign.iter().map(|f| f.ns.capacity() + f.prefix.capacity() + f.name.capacity() + f.value.capacity()).sum::<usize>()
|
||||
+ vec_bytes(&a.tags)
|
||||
+ a.tags.iter().map(|t| t.name.capacity() + t.value.capacity()).sum::<usize>()
|
||||
}
|
||||
|
||||
/// A vector's buffer (not what its elements own).
|
||||
fn vec_bytes<T>(v: &Vec<T>) -> usize {
|
||||
if v.capacity() == 0 { 0 } else { ALLOC + v.capacity() * size_of::<T>() }
|
||||
@@ -490,6 +507,21 @@ mod tests {
|
||||
assert!((400..1200).contains(&per), "{per} bytes per moved rectangle");
|
||||
}
|
||||
|
||||
/// An object's attributes count with their text: a version of a rectangle with a long tag and
|
||||
/// a long note keeps both.
|
||||
#[test]
|
||||
fn tags_and_notes_count() {
|
||||
let before = doc_with_rects(1);
|
||||
let mut after = before.clone();
|
||||
let id = after.layers[0].children().unwrap()[0].id;
|
||||
after.node_mut(id).unwrap().edit_attrs(|a| {
|
||||
a.note = "n".repeat(30_000);
|
||||
a.tags.push(crate::ObjectTag { id: 1, name: "size".into(), value: "v".repeat(60_000) });
|
||||
});
|
||||
let bytes = after.retained_bytes(&before);
|
||||
assert!(bytes >= 90_000, "{bytes} bytes for a rectangle with 90,000 bytes of attributes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grouped_object_is_found_shared() {
|
||||
let before = doc_with_rects(100);
|
||||
|
||||
@@ -24,7 +24,7 @@ mod opacity;
|
||||
mod ops;
|
||||
mod wire;
|
||||
|
||||
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, ObjectAttributes, SVG_EVENTS};
|
||||
pub use attributes::{ForeignAttribute, ImageMap, MAX_SVG_SCRIPTS, MAX_TAG_TEXT, MAX_TAGS, ObjectAttributes, ObjectTag, SVG_EVENTS};
|
||||
pub use clip::{ClipPaint, Uniter};
|
||||
pub use extras::{Extras, ExtrasMut, NodeExtras};
|
||||
pub use ids::{LAYER_COLORS, LayerColor, NodeId};
|
||||
|
||||
@@ -38,6 +38,141 @@ pub struct ObjectAttributes {
|
||||
/// with it.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub foreign: Vec<ForeignAttribute>,
|
||||
/// The object's tags, in order: name and value pairs that scripts read and write
|
||||
/// (`object.tag.add`). Names may be empty or repeated. At most [`MAX_TAGS`], each name and
|
||||
/// value at most [`MAX_TAG_TEXT`] bytes.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub tags: Vec<ObjectTag>,
|
||||
}
|
||||
|
||||
/// The most tags one object has.
|
||||
pub const MAX_TAGS: usize = 64;
|
||||
|
||||
/// The longest name or value a tag has, in bytes.
|
||||
pub const MAX_TAG_TEXT: usize = 64 * 1024;
|
||||
|
||||
/// A tag on an object: a name and a value, with an id that tells it apart from the object's other
|
||||
/// tags while its name and value change.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ObjectTag {
|
||||
/// Distinct among the object's tags: a new tag takes an id from
|
||||
/// [`crate::Document::alloc_tag_id`], and deleting a tag raises the next node id above its id,
|
||||
/// so a deleted tag's id is not given out again.
|
||||
#[serde(default, deserialize_with = "lenient_tag_id")]
|
||||
pub id: u64,
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
/// Reading a native file never fails over a tag id that is not a whole number from 0 to
|
||||
/// `u64::MAX` (a negative one, a fraction, text): it reads as 0, and
|
||||
/// [`crate::Document::tidy_tags`] gives the tag a new id.
|
||||
fn lenient_tag_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
|
||||
Ok(serde_json::Value::deserialize(d)?.as_u64().unwrap_or(0))
|
||||
}
|
||||
|
||||
impl ObjectAttributes {
|
||||
/// Keeps the tags within the limits: the first [`MAX_TAGS`] whose name and value are at most
|
||||
/// [`MAX_TAG_TEXT`] bytes. → whether any was dropped.
|
||||
pub fn tidy_tags(&mut self) -> bool {
|
||||
let before = self.tags.len();
|
||||
self.tags.retain(|t| t.name.len() <= MAX_TAG_TEXT && t.value.len() <= MAX_TAG_TEXT);
|
||||
self.tags.truncate(MAX_TAGS);
|
||||
self.tags.len() != before
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Document {
|
||||
/// Keeps every object's tags within the limits ([`ObjectAttributes::tidy_tags`]) in the art of
|
||||
/// the layers, symbols, graph designs and pattern swatches (opacity-mask art included). A tag
|
||||
/// keeps its id when the id is from 1 to below [`crate::limits::MAX_NEXT_ID`] and no earlier
|
||||
/// tag of the object has it. Every other tag gets a new id: from the next node id on, above
|
||||
/// every kept id, when those ids stay below that limit; otherwise the smallest id the object's
|
||||
/// other tags do not have. The next node id is then raised past every tag id below the limit.
|
||||
/// It recurses through the art: call it on a document no deeper than
|
||||
/// [`crate::depth::MAX_DEPTH`].
|
||||
pub fn tidy_tags(&mut self) {
|
||||
fn keeps(t: &ObjectTag, earlier: &[ObjectTag]) -> bool {
|
||||
(1..crate::limits::MAX_NEXT_ID).contains(&t.id) && !earlier.iter().any(|o| o.id == t.id)
|
||||
}
|
||||
// The limits, the largest kept id and the number of new ids first, so that a new id never
|
||||
// meets a kept one.
|
||||
let mut next = self.peek_next_id();
|
||||
let mut fresh = 0u64;
|
||||
self.each_tagged(&mut |a| {
|
||||
a.tidy_tags();
|
||||
for (i, t) in a.tags.iter().enumerate() {
|
||||
if keeps(t, &a.tags[..i]) {
|
||||
next = next.max(t.id.saturating_add(1));
|
||||
} else {
|
||||
fresh = fresh.saturating_add(1);
|
||||
}
|
||||
}
|
||||
});
|
||||
if fresh == 0 {
|
||||
self.raise_next_id(next);
|
||||
return;
|
||||
}
|
||||
let in_range = next.saturating_add(fresh) <= crate::limits::MAX_NEXT_ID;
|
||||
self.each_tagged(&mut |a| {
|
||||
let kept: Vec<bool> = (0..a.tags.len()).map(|i| keeps(&a.tags[i], &a.tags[..i])).collect();
|
||||
let mut used: Vec<u64> = a.tags.iter().zip(&kept).filter(|(_, k)| **k).map(|(t, _)| t.id).collect();
|
||||
for (i, k) in kept.iter().enumerate() {
|
||||
if *k {
|
||||
continue;
|
||||
}
|
||||
let id = if in_range {
|
||||
next = next.saturating_add(1);
|
||||
next - 1
|
||||
} else {
|
||||
(1..).find(|c| !used.contains(c)).unwrap_or(1)
|
||||
};
|
||||
a.tags[i].id = id;
|
||||
used.push(id);
|
||||
}
|
||||
});
|
||||
self.raise_next_id(next);
|
||||
}
|
||||
|
||||
/// A new tag id for object `id`, which none of its tags has: the next node id. `None` once the
|
||||
/// next node id has reached [`crate::limits::MAX_NEXT_ID`] (a file with ids at the top of the
|
||||
/// range), since an id from there would be outside the range [`Self::tidy_tags`] keeps and an
|
||||
/// id below it could be a deleted tag's.
|
||||
pub fn alloc_tag_id(&mut self, id: crate::NodeId) -> Option<u64> {
|
||||
let used: Vec<u64> =
|
||||
self.node(id).map(|n| n.extras().attrs.as_deref().map_or(Vec::new(), |a| a.tags.iter().map(|t| t.id).collect())).unwrap_or_default();
|
||||
for _ in 0..=used.len() {
|
||||
if self.peek_next_id() >= crate::limits::MAX_NEXT_ID {
|
||||
return None;
|
||||
}
|
||||
let tag = self.alloc_id().0;
|
||||
if !used.contains(&tag) {
|
||||
return Some(tag);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Calls `f` with the attributes of every object with tags in the art [`Self::tidy_tags`] reads.
|
||||
fn each_tagged(&mut self, f: &mut impl FnMut(&mut ObjectAttributes)) {
|
||||
let mut fix = |n: &mut Node| {
|
||||
if n.extras().attrs.as_deref().is_some_and(|a| !a.tags.is_empty()) {
|
||||
n.edit_attrs(&mut *f);
|
||||
}
|
||||
};
|
||||
let roots = self
|
||||
.layers
|
||||
.iter_mut()
|
||||
.chain(self.symbols.iter_mut().map(|s| &mut s.art))
|
||||
.chain(self.graph_designs.iter_mut().map(|g| &mut g.art))
|
||||
.chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut()))
|
||||
.chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut()));
|
||||
for root in roots {
|
||||
crate::placed_document::each_mut(std::sync::Arc::make_mut(root), &mut fix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute in another application's XML namespace: `plotter:pen="2"` with `xmlns:plotter=
|
||||
|
||||
@@ -131,6 +131,13 @@ impl Node {
|
||||
matches!(self.kind, NodeKind::Layer { template: true, .. })
|
||||
}
|
||||
|
||||
/// Whether a view that hides template layers (`templates`) or guides (`guides`) leaves this
|
||||
/// object out: a template layer while templates are hidden, or a path made into a guide while
|
||||
/// guides are hidden. The canvas draws ruler guides apart from the art.
|
||||
pub fn hidden_by_view(&self, templates: bool, guides: bool) -> bool {
|
||||
(templates && self.is_template()) || (guides && matches!(self.kind, NodeKind::Path { guide: true, .. }))
|
||||
}
|
||||
|
||||
/// The art objects of this container: its children, looking through sublayers, which are not
|
||||
/// objects (bottom first). With `editable`, only the visible, unlocked objects in visible,
|
||||
/// unlocked, non-template sublayers.
|
||||
@@ -360,17 +367,32 @@ impl Node {
|
||||
self.geometric(Some(symbols))
|
||||
}
|
||||
|
||||
/// Children that contribute to a container's editing bounds and selection highlights. A live trace retains a
|
||||
/// hidden bitmap for re-tracing/release; only source-image views measure that bitmap.
|
||||
/// Children that contribute to a container's editing bounds. A live trace retains a hidden bitmap for
|
||||
/// re-tracing/release; only source-image views measure that bitmap. Selection highlights outline
|
||||
/// [`Node::drawn_children`].
|
||||
pub fn editing_children(&self) -> &[Arc<Node>] {
|
||||
let children = self.children().map(Vec::as_slice).unwrap_or_default();
|
||||
let trace_source = self.extras().trace.is_some()
|
||||
&& !self.trace_view().shows_source()
|
||||
&& children.first().is_some_and(|n| !n.visible && matches!(n.kind, NodeKind::Image(_)));
|
||||
let trace_source = !self.trace_view().shows_source() && self.trace_source().is_some_and(|n| !n.visible);
|
||||
let skip = usize::from(self.extras().shaper.is_some() || trace_source);
|
||||
children.get(skip..).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The children a selection highlight outlines: [`Node::editing_children`] without the hidden
|
||||
/// members, which the canvas does not draw. An Image Trace object's hidden source image stays
|
||||
/// when the object's view shows it, and every path of a compound path stays, since the compound
|
||||
/// path draws all of them.
|
||||
pub fn drawn_children(&self) -> impl Iterator<Item = &Arc<Node>> {
|
||||
let members = !matches!(self.kind, NodeKind::Compound { .. });
|
||||
let source = self.trace_source().filter(|_| self.trace_view().shows_source());
|
||||
self.editing_children().iter().filter(move |c| !members || c.visible || source.is_some_and(|s| Arc::ptr_eq(s, c)))
|
||||
}
|
||||
|
||||
/// The first child of an Image Trace object when it is an image: the bitmap the trace keeps.
|
||||
fn trace_source(&self) -> Option<&Arc<Node>> {
|
||||
self.extras().trace.as_ref()?;
|
||||
self.children()?.first().filter(|n| matches!(n.kind, NodeKind::Image(_)))
|
||||
}
|
||||
|
||||
/// The box of [`Node::geometric_bounds`], or of [`Node::geometric_bounds_with`] when `symbols`
|
||||
/// is given.
|
||||
pub(crate) fn geometric(&self, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
|
||||
|
||||
@@ -5,9 +5,10 @@
|
||||
//! stay attached and deleted objects leave nothing stale behind.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use vectorcraft_geom::{Homography, Rect};
|
||||
use vectorcraft_geom::{Homography, Point, Rect};
|
||||
|
||||
use crate::{Node, NodeKind};
|
||||
use crate::symbols::SYMBOL_SQUARE;
|
||||
use crate::{Node, NodeKind, SymbolBoxes};
|
||||
|
||||
/// The plane an object in perspective lies on.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
@@ -58,6 +59,33 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// The corners of the box a symbol instance or type is drawn in, on the page (top left, top
|
||||
/// right, bottom right, bottom left): an instance's art box (measured from `symbols`, or
|
||||
/// `SYMBOL_SQUARE` when it has none) placed by its transform, and type's flat bounds, both
|
||||
/// through the projection of type or an instance in perspective. Joined by straight lines,
|
||||
/// they outline the box as drawn. When the projection sends a corner to infinity the corners
|
||||
/// stay flat, as the flat box is kept for [`Node::geometric_bounds_with`]. `None` for other
|
||||
/// objects and for type without bounds.
|
||||
pub fn drawn_corners(&self, symbols: &SymbolBoxes) -> Option<[Point; 4]> {
|
||||
let flat = match &self.kind {
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
let art = symbols.art(symbol).map_or(SYMBOL_SQUARE, |a| a.geometric);
|
||||
[(art.x0, art.y0), (art.x1, art.y0), (art.x1, art.y1), (art.x0, art.y1)].map(|(x, y)| *xf * Point::new(x, y))
|
||||
}
|
||||
NodeKind::Text(t) => {
|
||||
let b = t.bounds()?;
|
||||
[(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| Point::new(x, y))
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let Some(h) = self.projection() else { return Some(flat) };
|
||||
let [a, b, c, d] = flat.map(|p| h.apply(p));
|
||||
Some(match (a, b, c, d) {
|
||||
(Some(a), Some(b), Some(c), Some(d)) => [a, b, c, d],
|
||||
_ => flat,
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep a projection drawing the same picture moved by `a` (the flat art moves by `a` too). An
|
||||
/// invertible `a` that the projection cannot follow removes it, and the art is drawn flat.
|
||||
pub(crate) fn transform_projection(&mut self, a: vectorcraft_geom::Affine) {
|
||||
|
||||
@@ -7,6 +7,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Vec2};
|
||||
use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeAlign, StrokeLayer};
|
||||
|
||||
mod area;
|
||||
mod attr_ranges;
|
||||
mod char_style;
|
||||
mod composite;
|
||||
mod file_fonts;
|
||||
@@ -18,6 +19,9 @@ mod tabs_lists;
|
||||
mod wrap;
|
||||
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
pub use attr_ranges::{
|
||||
AttrRangeError, CHAR_MITER_LIMIT, CHAR_ROTATION, CHAR_SCALE, CHAR_SPACING, FONT_SIZE, LEADING, MAX_BASELINE_SHIFT, MAX_PARA_DISTANCE,
|
||||
};
|
||||
use char_style::yes;
|
||||
pub use char_style::{
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_DIACRITIC_POSITION, MAX_TSUME,
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
//! The ranges the character and paragraph style commands keep each numeric attribute to, checked
|
||||
//! in one place: the style commands check the attributes a call changes, and type a plug-in
|
||||
//! returns has every attribute checked.
|
||||
|
||||
use std::fmt;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use super::{CharStyle, JustificationOptions, ParaStyle, TabStop};
|
||||
|
||||
/// Font size ([`CharStyle::size`]), in points.
|
||||
pub const FONT_SIZE: RangeInclusive<f64> = 0.1..=1296.0;
|
||||
/// Leading ([`CharStyle::leading`]) other than Auto, in points.
|
||||
pub const LEADING: RangeInclusive<f64> = 0.1..=5000.0;
|
||||
/// Horizontal and vertical scale ([`CharStyle::h_scale`], [`CharStyle::v_scale`]), in percent.
|
||||
pub const CHAR_SCALE: RangeInclusive<f64> = 1.0..=10000.0;
|
||||
/// Tracking, kerning and the space before a line's first character ([`CharStyle::tracking`],
|
||||
/// [`CharStyle::kerning`], [`CharStyle::kerning_before`]), in 1/1000 em.
|
||||
pub const CHAR_SPACING: RangeInclusive<f64> = -1000.0..=10000.0;
|
||||
/// The largest baseline shift and Tate-chu-yoko Up/Down and Left/Right either way, in points.
|
||||
pub const MAX_BASELINE_SHIFT: f64 = 1296.0;
|
||||
/// Character rotation ([`CharStyle::rotation`]), in degrees.
|
||||
pub const CHAR_ROTATION: RangeInclusive<f64> = -360.0..=360.0;
|
||||
/// The miter limit of a character stroke ([`CharStyle::stroke_miter_limit`]).
|
||||
pub const CHAR_MITER_LIMIT: RangeInclusive<f64> = 1.0..=500.0;
|
||||
/// The largest paragraph indent, space before or after and Hyphenation Zone either way, in points.
|
||||
pub const MAX_PARA_DISTANCE: f64 = 1296.0;
|
||||
|
||||
/// An attribute outside the range the style commands keep it to.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AttrRangeError {
|
||||
/// The attribute's JSON name, a nested field after a dot (`hyphenation.zone`).
|
||||
pub key: String,
|
||||
/// What is wrong, naming the attribute.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl fmt::Display for AttrRangeError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AttrRangeError {}
|
||||
|
||||
fn out(key: &str, message: String) -> AttrRangeError {
|
||||
AttrRangeError { key: key.to_string(), message }
|
||||
}
|
||||
|
||||
/// `value` within `lo..=hi`, or the error naming `key` (a value that is not a number is outside).
|
||||
fn within(key: &str, value: f64, lo: f64, hi: f64) -> Result<(), AttrRangeError> {
|
||||
if (lo..=hi).contains(&value) { Ok(()) } else { Err(out(key, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
}
|
||||
|
||||
impl CharStyle {
|
||||
/// Checks each numeric attribute `check` names, by its JSON key, against the range the
|
||||
/// character style commands keep it to: size, leading, scales, tracking, kerning, baseline
|
||||
/// shift, rotation, the character stroke's weight, miter limit and dashes, Small Caps, Insert
|
||||
/// Aki, Tsume, diacritic positions, the Tate-chu-yoko offsets, the Warichu settings and the
|
||||
/// variable font axes. The first attribute out of its range is the error.
|
||||
pub fn check_ranges(&self, check: impl Fn(&str) -> bool) -> Result<(), AttrRangeError> {
|
||||
for (key, value, range) in [("size", self.size, FONT_SIZE), ("h_scale", self.h_scale, CHAR_SCALE), ("v_scale", self.v_scale, CHAR_SCALE)] {
|
||||
if check(key) {
|
||||
within(key, value, *range.start(), *range.end())?;
|
||||
}
|
||||
}
|
||||
if check("leading") && self.leading.is_some_and(|value| !LEADING.contains(&value)) {
|
||||
let (lo, hi) = (LEADING.start(), LEADING.end());
|
||||
return Err(out("leading", format!("`leading` must be from {lo} to {hi}, or null for Auto")));
|
||||
}
|
||||
let shift = MAX_BASELINE_SHIFT;
|
||||
for (key, value) in [("baseline_shift", self.baseline_shift), ("tcyUpDown", self.tcy_up_down), ("tcyLeftRight", self.tcy_left_right)] {
|
||||
if check(key) {
|
||||
within(key, value, -shift, shift)?;
|
||||
}
|
||||
}
|
||||
let spacing = [("tracking", Some(self.tracking)), ("kerning", self.kerning), ("kerningBefore", Some(self.kerning_before))];
|
||||
for (key, value) in spacing {
|
||||
if check(key)
|
||||
&& let Some(value) = value
|
||||
{
|
||||
within(key, value, *CHAR_SPACING.start(), *CHAR_SPACING.end())?;
|
||||
}
|
||||
}
|
||||
if check("rotation") {
|
||||
within("rotation", self.rotation, *CHAR_ROTATION.start(), *CHAR_ROTATION.end())?;
|
||||
}
|
||||
for (key, value) in [("akiLeft", self.aki_left), ("akiRight", self.aki_right)] {
|
||||
if check(key) {
|
||||
within(key, value, 0.0, super::MAX_AKI)?;
|
||||
}
|
||||
}
|
||||
if check("tsume") {
|
||||
within("tsume", self.tsume, 0.0, super::MAX_TSUME)?;
|
||||
}
|
||||
let hi = super::MAX_DIACRITIC_POSITION;
|
||||
for (key, value) in [("diacriticHorizontal", self.diacritic_horizontal), ("diacriticVertical", self.diacritic_vertical)] {
|
||||
if check(key) {
|
||||
within(key, value, -hi, hi)?;
|
||||
}
|
||||
}
|
||||
let lines = super::WARICHU_LINES;
|
||||
if check("warichuLines") && !lines.contains(&self.warichu_lines) {
|
||||
return Err(out("warichuLines", format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end())));
|
||||
}
|
||||
let scale = super::WARICHU_SCALE;
|
||||
for (key, value, lo, hi) in
|
||||
[("warichuGap", self.warichu_gap, 0.0, super::MAX_WARICHU_GAP), ("warichuScale", self.warichu_scale, *scale.start(), *scale.end())]
|
||||
{
|
||||
if check(key) {
|
||||
within(key, value, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if check("stroke_width") {
|
||||
within("stroke_width", self.stroke_width, 0.0, crate::MAX_COORD)?;
|
||||
}
|
||||
if check("stroke_miter_limit") {
|
||||
within("stroke_miter_limit", self.stroke_miter_limit, *CHAR_MITER_LIMIT.start(), *CHAR_MITER_LIMIT.end())?;
|
||||
}
|
||||
if check("stroke_dash")
|
||||
&& let Some(dash) = &self.stroke_dash
|
||||
{
|
||||
for value in &dash.pattern {
|
||||
within("stroke_dash.pattern", *value, 0.0, crate::MAX_COORD)?;
|
||||
}
|
||||
within("stroke_dash.offset", dash.offset, -crate::MAX_COORD, crate::MAX_COORD)?;
|
||||
}
|
||||
if check("small_caps")
|
||||
&& let Some(value) = self.small_caps
|
||||
{
|
||||
within("small_caps", value, 1.0, crate::setup::MAX_SMALL_CAPS)?;
|
||||
}
|
||||
if check("fontAxes")
|
||||
&& let Some((tag, _)) = self.font_axes.iter().find(|(_, v)| !v.is_finite())
|
||||
{
|
||||
return Err(out("fontAxes", format!("`fontAxes`: the setting of axis `{tag}` must be a number")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl ParaStyle {
|
||||
/// Checks each paragraph attribute `check` names, by its JSON key and for a nested option its
|
||||
/// field, against the range the paragraph style commands keep it to: the indents and the space
|
||||
/// before and after, each Hyphenation option, each Justification option in `justification`
|
||||
/// (the options as given, since reading a paragraph style brings them into range) with
|
||||
/// Minimum, Desired and Maximum in order, and the number of tab stops with the position and
|
||||
/// leader of each stop that is not in `kept_tabs`. The first attribute out of its range is the
|
||||
/// error.
|
||||
pub fn check_ranges(
|
||||
&self,
|
||||
justification: Option<&JustificationOptions>,
|
||||
kept_tabs: &[TabStop],
|
||||
check: impl Fn(&str, Option<&str>) -> bool,
|
||||
) -> Result<(), AttrRangeError> {
|
||||
for (key, value) in [
|
||||
("left_indent", self.left_indent),
|
||||
("right_indent", self.right_indent),
|
||||
("first_line_indent", self.first_line_indent),
|
||||
("space_before", self.space_before),
|
||||
("space_after", self.space_after),
|
||||
] {
|
||||
if check(key, None) {
|
||||
within(key, value, -MAX_PARA_DISTANCE, MAX_PARA_DISTANCE)?;
|
||||
}
|
||||
}
|
||||
let h = &self.hyphenation;
|
||||
for (field, value, lo, hi) in [
|
||||
("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0),
|
||||
("after_first", f64::from(h.after_first), 1.0, 15.0),
|
||||
("before_last", f64::from(h.before_last), 1.0, 15.0),
|
||||
("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0),
|
||||
("zone", h.zone, 0.0, MAX_PARA_DISTANCE),
|
||||
] {
|
||||
if check("hyphenation", Some(field)) {
|
||||
within(&format!("hyphenation.{field}"), value, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if let Some(j) = justification {
|
||||
for (field, values, (lo, hi)) in [
|
||||
("word_spacing", j.word_spacing, JustificationOptions::WORD_SPACING),
|
||||
("letter_spacing", j.letter_spacing, JustificationOptions::LETTER_SPACING),
|
||||
("glyph_scaling", j.glyph_scaling, JustificationOptions::GLYPH_SCALING),
|
||||
] {
|
||||
if !check("justification", Some(field)) {
|
||||
continue;
|
||||
}
|
||||
let name = format!("justification.{field}");
|
||||
for value in values {
|
||||
within(&name, value, lo, hi)?;
|
||||
}
|
||||
if !(values[0] <= values[1] && values[1] <= values[2]) {
|
||||
return Err(out(&name, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")));
|
||||
}
|
||||
}
|
||||
if check("justification", Some("auto_leading")) {
|
||||
let (lo, hi) = JustificationOptions::AUTO_LEADING;
|
||||
within("justification.auto_leading", j.auto_leading, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if check("tabs", None) {
|
||||
let max = TabStop::MAX_STOPS;
|
||||
if self.tabs.len() > max.max(kept_tabs.len()) {
|
||||
return Err(out("tabs", format!("at most {max} tab stops")));
|
||||
}
|
||||
for stop in self.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
|
||||
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
|
||||
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
|
||||
if stop.leader.chars().count() > max {
|
||||
return Err(out("tabs.leader", format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -802,6 +802,45 @@ fn auto_alignment_saves_readable_by_older_builds() {
|
||||
assert_eq!(serde_json::from_str::<ParaStyle>(r#"{"justify":"Center"}"#).unwrap().justify, Justify::Center);
|
||||
}
|
||||
|
||||
/// The default character and paragraph styles are in range, and each number outside its range,
|
||||
/// one that is not a number included, is the error naming its attribute; an attribute the check
|
||||
/// is not asked about is not checked.
|
||||
#[test]
|
||||
fn style_ranges_name_the_attribute_out_of_range() {
|
||||
let all = |_: &str| true;
|
||||
assert_eq!(CharStyle::default().check_ranges(all), Ok(()));
|
||||
let key = |s: CharStyle| s.check_ranges(all).map_err(|e| e.key);
|
||||
let d = CharStyle::default();
|
||||
assert_eq!(key(CharStyle { baseline_shift: f64::NAN, ..d.clone() }), Err("baseline_shift".into()));
|
||||
assert_eq!(key(CharStyle { leading: Some(1e9), ..d.clone() }), Err("leading".into()));
|
||||
assert_eq!(key(CharStyle { v_scale: 0.0, ..d.clone() }), Err("v_scale".into()));
|
||||
assert_eq!(key(CharStyle { kerning: Some(f64::INFINITY), ..d.clone() }), Err("kerning".into()));
|
||||
assert_eq!(key(CharStyle { rotation: 720.0, ..d.clone() }), Err("rotation".into()));
|
||||
assert_eq!(key(CharStyle { warichu_lines: 9, ..d.clone() }), Err("warichuLines".into()));
|
||||
assert_eq!(key(CharStyle { stroke_miter_limit: 0.0, ..d.clone() }), Err("stroke_miter_limit".into()));
|
||||
assert_eq!(key(CharStyle { small_caps: Some(0.0), ..d.clone() }), Err("small_caps".into()));
|
||||
let axes = std::iter::once(("wght".to_string(), f64::NAN)).collect();
|
||||
assert_eq!(key(CharStyle { font_axes: axes, ..d.clone() }), Err("fontAxes".into()));
|
||||
let dash = Some(Dash { pattern: vec![2.0, -1.0], offset: 0.0, align_corners: false });
|
||||
assert_eq!(key(CharStyle { stroke_dash: dash, ..d.clone() }), Err("stroke_dash.pattern".into()));
|
||||
assert_eq!(CharStyle { size: 0.0, ..d.clone() }.check_ranges(|k| k != "size"), Ok(()));
|
||||
|
||||
let all = |_: &str, _: Option<&str>| true;
|
||||
let p = ParaStyle::default();
|
||||
assert_eq!(p.check_ranges(Some(&JustificationOptions::default()), &[], all), Ok(()));
|
||||
let key = |s: ParaStyle, j: Option<&JustificationOptions>| s.check_ranges(j, &[], all).map_err(|e| e.key);
|
||||
assert_eq!(key(ParaStyle { first_line_indent: f64::NAN, ..p.clone() }, None), Err("first_line_indent".into()));
|
||||
let stop = TabStop { position: 1.0, align: TabAlign::Left, leader: String::new(), align_on: '.' };
|
||||
assert_eq!(key(ParaStyle { tabs: vec![stop.clone(); TabStop::MAX_STOPS + 1], ..p.clone() }, None), Err("tabs".into()));
|
||||
let far = TabStop { position: -1.0, ..stop.clone() };
|
||||
assert_eq!(key(ParaStyle { tabs: vec![far.clone()], ..p.clone() }, None), Err("tabs.position".into()));
|
||||
assert_eq!(ParaStyle { tabs: vec![far.clone()], ..p.clone() }.check_ranges(None, &[far], all), Ok(()), "a kept stop");
|
||||
let hyphenation = HyphenationOptions { hyphen_limit: 99, ..HyphenationOptions::default() };
|
||||
assert_eq!(key(ParaStyle { hyphenation, ..p.clone() }, None), Err("hyphenation.hyphen_limit".into()));
|
||||
let reversed = JustificationOptions { word_spacing: [133.0, 100.0, 80.0], ..JustificationOptions::default() };
|
||||
assert_eq!(key(p.clone(), Some(&reversed)), Err("justification.word_spacing".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_fonts_draw_type_only_while_its_text_is_the_files() {
|
||||
use super::file_fonts::*;
|
||||
|
||||
@@ -326,21 +326,21 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"stylize.dropShadow",
|
||||
"Drop Shadow…",
|
||||
STYLIZE,
|
||||
"{mode: blend mode (\"multiply\"), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)",
|
||||
"{mode: blend mode (\"multiply\"; normal, darken, multiply, colorBurn, lighten, screen, colorDodge, overlay, softLight, hardLight, difference, exclusion, hue, saturation, color or luminosity, in any letter case), opacity: % (75), x: pt (7), y: pt (7), blur: pt (5), shade: \"color\"|\"darkness\" (\"color\"), color: \"#rrggbb\" (\"#000000\"), darkness: % (100)} (shade \"darkness\": use d = darkness / 100 on the source colors before document color conversion and blur; RGB channels become max(0, channel - d), CMYK keeps C/M/Y and sets K to min(1, K + d), and Gray sets its black component to min(1, K + d). The near-100% endpoint is gray black. Shadow opacity remains separate)",
|
||||
json!({"mode": "multiply", "opacity": 75.0, "x": 7.0, "y": 7.0, "blur": 5.0, "shade": "color", "color": "#000000", "darkness": 100.0}),
|
||||
),
|
||||
r(
|
||||
"stylize.innerGlow",
|
||||
"Inner Glow…",
|
||||
STYLIZE,
|
||||
"{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}",
|
||||
"{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffffff\"), source: \"center\"|\"edge\" (\"edge\")}",
|
||||
json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffffff", "source": "edge"}),
|
||||
),
|
||||
r(
|
||||
"stylize.outerGlow",
|
||||
"Outer Glow…",
|
||||
STYLIZE,
|
||||
"{mode: blend mode (\"screen\"), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}",
|
||||
"{mode: blend mode (\"screen\"; one of Drop Shadow's modes), opacity: % (75), blur: pt (5), color: \"#rrggbb\" (\"#ffff00\")}",
|
||||
json!({"mode": "screen", "opacity": 75.0, "blur": 5.0, "color": "#ffff00"}),
|
||||
),
|
||||
r("stylize.feather", "Feather…", STYLIZE, "{radius: pt (5)}", json!({"radius": 5.0})),
|
||||
@@ -875,6 +875,12 @@ pub(crate) fn catalog_index() -> &'static std::collections::HashMap<&'static str
|
||||
INDEX.get_or_init(|| effect_catalog().into_iter().map(|e| (e.id, e)).collect())
|
||||
}
|
||||
|
||||
/// The id and menu label of built-in effect `id`, as the catalog holds them (no plug-in
|
||||
/// effects).
|
||||
pub fn built_in_effect(id: &str) -> Option<(&'static str, &'static str)> {
|
||||
catalog_index().get(id).map(|e| (e.id, e.label))
|
||||
}
|
||||
|
||||
/// Catalogue entry for `id` (built-in, or an installed plug-in effect).
|
||||
pub fn effect_info(id: &str) -> Option<EffectInfo> {
|
||||
catalog_index().get(id).cloned().or_else(|| plugin_info(id))
|
||||
|
||||
@@ -66,7 +66,7 @@ pub const PATHFINDER_EFFECT_PRECISION: std::ops::RangeInclusive<f64> = 0.001..=1
|
||||
/// The documentation of [`PATHFINDER_OPTION_KEYS`], as a literal for `concat!`.
|
||||
macro_rules! options_doc {
|
||||
() => {
|
||||
"precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing; results are refit to within it and pieces thinner than it are dropped), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, a compound shape's area going by the shape's own fill, except that Divide keeps every piece when the group or compound shape has a visible fill of its own; the other operations ignore it)"
|
||||
"precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing, and a stored value that is not a number evaluates as 0.01; results are refit to within it and pieces thinner than it are dropped; Outline treats crossings closer together than precision / 10000 as one point, or than the tolerance for the art's size when that is larger), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, a compound shape's area going by the shape's own fill, except that Divide keeps every piece when the group or compound shape has a visible fill of its own; the other operations ignore it)"
|
||||
};
|
||||
}
|
||||
|
||||
@@ -102,14 +102,21 @@ impl Default for PathfinderEffectOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `precision` stored in a Pathfinder effect's parameters `p`, out of range or not, when it is a
|
||||
/// JSON number. A value of another type (`true`, `"1 pt"`) is not a precision.
|
||||
pub(crate) fn stored_precision(p: &Value) -> Option<f64> {
|
||||
p.get("precision").and_then(Value::as_f64).filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
impl PathfinderEffectOptions {
|
||||
/// The options in `p`: a missing or non-numeric value takes its default and a precision out of
|
||||
/// range its nearest bound, so a live effect always evaluates.
|
||||
/// The options in `p`: a missing value, or one of the wrong type (a precision that is not a
|
||||
/// number), takes its default, and a precision out of range its nearest bound, so a live effect
|
||||
/// always evaluates.
|
||||
pub fn from_params(p: &Value) -> Self {
|
||||
let d = PathfinderEffectOptions::default();
|
||||
let (lo, hi) = (*PATHFINDER_EFFECT_PRECISION.start(), *PATHFINDER_EFFECT_PRECISION.end());
|
||||
PathfinderEffectOptions {
|
||||
precision: crate::util::num(p, "precision", d.precision).clamp(lo, hi),
|
||||
precision: stored_precision(p).unwrap_or(d.precision).clamp(lo, hi),
|
||||
remove_redundant_points: crate::util::flag(p, "removeRedundantPoints", d.remove_redundant_points),
|
||||
remove_unpainted: crate::util::flag(p, "removeUnpainted", d.remove_unpainted),
|
||||
}
|
||||
|
||||
@@ -82,11 +82,12 @@ pub use group::{
|
||||
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
|
||||
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
|
||||
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
|
||||
pub use params::{blend_mode_id, parse_blend_mode, takes_blend_mode};
|
||||
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
|
||||
pub use placement::pinned_gradient_item;
|
||||
pub use raster::{
|
||||
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects,
|
||||
without_geometry,
|
||||
RASTERIZE, RasterFx, Rasterize, blend_mode, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps,
|
||||
staged_effects, without_geometry,
|
||||
};
|
||||
pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, add_instance_row_effects_to_parts, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster,
|
||||
@@ -124,7 +125,9 @@ mod catalog;
|
||||
mod geometry;
|
||||
mod params;
|
||||
|
||||
pub use catalog::{EffectInfo, Lengths, WARP_STYLES, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range};
|
||||
pub use catalog::{
|
||||
EffectInfo, Lengths, WARP_STYLES, built_in_effect, effect_catalog, effect_info, is_length, length_range, plugin_effects, raster_px_range,
|
||||
};
|
||||
pub(crate) use geometry::{Budget, apply_one};
|
||||
pub use geometry::{
|
||||
Carry, GeomContext, apply_geometry, apply_geometry_bez, apply_geometry_bez_carrying, apply_geometry_carrying, apply_geometry_with,
|
||||
|
||||
@@ -1,6 +1,28 @@
|
||||
use vectorcraft_doc::color::BlendMode;
|
||||
|
||||
use super::catalog::{catalog_index, plugin_info};
|
||||
use super::{CROP_MARKS, Effect, Map, Node, PIXEL_EFFECTS, RASTERIZE, Value, is_adjustment, is_pathfinder, is_three_d, json, util};
|
||||
|
||||
/// Whether parameter `key` of effect `effect` is the blend mode the effect draws in.
|
||||
pub fn takes_blend_mode(effect: &str, key: &str) -> bool {
|
||||
key == "mode" && matches!(effect, "stylize.dropShadow" | "stylize.innerGlow" | "stylize.outerGlow")
|
||||
}
|
||||
|
||||
/// Read a blend mode name as the effect renderer does. Case and punctuation do not change the mode.
|
||||
pub fn parse_blend_mode(s: &str) -> Option<BlendMode> {
|
||||
let name: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
|
||||
BlendMode::parse(&name)
|
||||
}
|
||||
|
||||
/// The name an effect stores for blend mode `mode`, such as `normal`, `multiply`, or `colorBurn`.
|
||||
pub fn blend_mode_id(mode: BlendMode) -> String {
|
||||
let mut name = format!("{mode:?}");
|
||||
if let Some(first) = name.get_mut(..1) {
|
||||
first.make_ascii_lowercase();
|
||||
}
|
||||
name
|
||||
}
|
||||
|
||||
/// Dialog defaults for `id` (`None` for unknown effects).
|
||||
pub fn default_params(id: &str) -> Option<Value> {
|
||||
match catalog_index().get(id) {
|
||||
@@ -131,9 +153,12 @@ pub fn scale_effect(e: &mut Effect, s: f64) {
|
||||
let mut keys: Vec<&str> = info.lengths.keys(relative).collect();
|
||||
keys.extend(merged.as_object().into_iter().flat_map(|m| m.keys()).map(String::as_str).filter(|k| crate::raster_px_range(&e.id, k).is_some()));
|
||||
for k in keys {
|
||||
let missing =
|
||||
if k == "precision" && crate::takes_pathfinder_options(&e.id) { crate::PathfinderEffectOptions::default().precision } else { f64::NAN };
|
||||
let v = util::num(&merged, k, missing);
|
||||
// A Pathfinder effect's precision that is not a number scales the precision it evaluates with.
|
||||
let v = if k == "precision" && crate::takes_pathfinder_options(&e.id) {
|
||||
crate::group::stored_precision(&merged).unwrap_or(crate::PathfinderEffectOptions::default().precision)
|
||||
} else {
|
||||
util::num(&merged, k, f64::NAN)
|
||||
};
|
||||
if v.is_finite() {
|
||||
if !e.params.is_object() {
|
||||
e.params = Value::Object(Map::new());
|
||||
|
||||
@@ -2186,3 +2186,23 @@ fn a_pathfinder_effects_precision_is_a_distance_that_scales_with_the_object() {
|
||||
assert_eq!(e.params["precision"].as_f64(), Some(8.0), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pathfinder_effects_stored_precision_that_is_not_a_number_is_the_default() {
|
||||
let d = PathfinderEffectOptions::default().precision;
|
||||
for v in [json!(true), json!(false), json!("1abc"), json!("5 pt"), json!(null), json!([2.0])] {
|
||||
assert_eq!(PathfinderEffectOptions::from_params(&json!({ "precision": v })).precision, d, "{v}");
|
||||
}
|
||||
// A number out of range takes its nearest bound.
|
||||
assert_eq!(PathfinderEffectOptions::from_params(&json!({"precision": 50.0})).precision, *PATHFINDER_EFFECT_PRECISION.end());
|
||||
assert_eq!(PathfinderEffectOptions::from_params(&json!({"precision": 0})).precision, *PATHFINDER_EFFECT_PRECISION.start());
|
||||
// Scale Strokes & Effects scales the precision such an effect evaluates with.
|
||||
for (id, _, _) in PATHFINDER_EFFECTS {
|
||||
for v in [json!(true), json!("1abc")] {
|
||||
let mut e = crate::new_effect(id, &json!({ "precision": v })).unwrap();
|
||||
crate::scale_effect(&mut e, 3.0);
|
||||
let scaled = e.params["precision"].as_f64().unwrap_or(f64::NAN);
|
||||
assert!((scaled - d * 3.0).abs() < 1e-12, "{id} {v}: {scaled}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,11 +80,28 @@ rustix = { workspace = true, features = ["std", "process"] }
|
||||
# (walkdir), so this adds no new crate.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
same-file = "1.0.6"
|
||||
# Credential Manager, the system key store of grant_keys.rs on Windows (see keyring-core below).
|
||||
windows-native-keyring-store = "1.1"
|
||||
|
||||
# The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true }
|
||||
rayon = { version = "1.12", optional = true }
|
||||
# The MAC that `grants.json` carries (grant_keys.rs) and the random key it is made with, which the
|
||||
# user's key store keeps: Keychain on macOS, Credential Manager on Windows, the Secret Service on
|
||||
# Linux. All MIT OR Apache-2.0.
|
||||
hmac = "0.12.1"
|
||||
sha2 = { version = "0.10", default-features = false }
|
||||
getrandom = "0.4"
|
||||
keyring-core = "1.1"
|
||||
|
||||
# The system key store of grant_keys.rs on each platform, connected through keyring-core: the same
|
||||
# store crates and features that keyring 4.2 uses. All MIT OR Apache-2.0.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
apple-native-keyring-store = { version = "1.0.2", features = ["keychain"] }
|
||||
|
||||
[target.'cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))'.dependencies]
|
||||
zbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-rust"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# JPEG XL files for the `.jxl` open and place tests.
|
||||
@@ -105,8 +122,9 @@ proptest = { workspace = true }
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
# How many times an open reads a PDF.
|
||||
vectorcraft-pdf = { workspace = true, features = ["read-count"] }
|
||||
# How many times the symbol list is read to find symbols by name.
|
||||
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
|
||||
# How many times the symbol list is read to find symbols by name, and how many objects are
|
||||
# measured against locked artboards.
|
||||
vectorcraft-doc = { workspace = true, features = ["symbol-read-count", "locked-artboard-count"] }
|
||||
wat = { workspace = true }
|
||||
# Zstandard streams for the Illustrator editing data fuzz tests.
|
||||
ruzstd = { workspace = true }
|
||||
|
||||
@@ -102,6 +102,7 @@ pub mod swatchlib;
|
||||
pub(crate) mod symboledit;
|
||||
pub mod symbollib;
|
||||
pub(crate) mod tabs;
|
||||
pub(crate) mod tags;
|
||||
mod textedit;
|
||||
|
||||
pub use textedit::effective_kerning;
|
||||
@@ -376,6 +377,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(library::specs());
|
||||
v.extend(expand::specs());
|
||||
v.extend(attributes::specs());
|
||||
v.extend(tags::specs());
|
||||
v.extend(interactivity::specs());
|
||||
v.extend(spelling::specs());
|
||||
v.extend(svgfilter::specs());
|
||||
@@ -845,7 +847,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
|
||||
|
||||
pub(crate) use addons::{DecodedImages, refresh_color_masks};
|
||||
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
|
||||
pub use addons::{fold_source, print_hidden};
|
||||
pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
|
||||
/// Document Info's category titles, the Objects category's count labels, and how its image rows
|
||||
/// write a resolution and a number of bytes.
|
||||
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
|
||||
@@ -855,7 +857,7 @@ pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
|
||||
pub use object::{reflect_axis, scale_factors, shear_tangent};
|
||||
pub(crate) use paint::{LIVE_PAINT_BUCKET, asks_defaults_only};
|
||||
pub(crate) use paint::{asks_defaults_only, painting_tool_of};
|
||||
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
|
||||
pub use select::SIMILAR;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
@@ -924,6 +926,9 @@ pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYT
|
||||
/// An Image Trace made off the UI thread, and what it traced (#3098).
|
||||
pub use buildcmds::{TraceRun, Traced, image_trace_target};
|
||||
|
||||
/// Retype's search of the installed fonts, made off the UI thread.
|
||||
pub use retype::{RetypeFound, RetypeRun, RetypeSearch};
|
||||
|
||||
/// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them).
|
||||
pub(crate) use buildcmds::TracePresetChanges;
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ mod typetools;
|
||||
mod units;
|
||||
|
||||
pub(crate) use image::{DecodedImages, refresh_color_masks};
|
||||
pub use packaging::{fold_source, print_hidden};
|
||||
pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
|
||||
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
use super::CommandSpec;
|
||||
|
||||
@@ -173,7 +173,7 @@ fn filter(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let label = effects::effect_info(id).map_or("Apply as Filter", |e| e.label.trim_end_matches('…'));
|
||||
let kinds = effects::addons::duotone::swatch_kinds(&s.doc()?.doc);
|
||||
let swatches = |name: &str| kinds.get(name).copied();
|
||||
recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches))
|
||||
s.edit_effect(id, |s| recolor_links(s, &given, C, label, &|c| map.apply(c), &|c, link, tint| map.apply_link(c, link, tint, &swatches)))
|
||||
}
|
||||
|
||||
/// Apply Fill to Stroke (`to_stroke`) or Apply Stroke to Fill: each target copies one of its own
|
||||
|
||||
@@ -2,13 +2,16 @@
|
||||
//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line
|
||||
//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each
|
||||
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold
|
||||
//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu
|
||||
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
|
||||
//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Set
|
||||
//! Fold Angle ([`angle`]) gives a fold line its own angle. Its submenu (Object › Plug-ins ›
|
||||
//! Packaging Tools) and its Fold Lines panel are the UI's.
|
||||
|
||||
mod angle;
|
||||
mod check;
|
||||
mod fold;
|
||||
mod roles;
|
||||
|
||||
pub use angle::{FoldAngles, selection_fold_angles, selection_fold_lines};
|
||||
pub use fold::{fold_source, print_hidden};
|
||||
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
|
||||
|
||||
@@ -17,6 +20,7 @@ use super::super::CommandSpec;
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = roles::specs();
|
||||
v.extend(check::specs());
|
||||
v.extend(angle::specs());
|
||||
v.extend(fold::specs());
|
||||
v
|
||||
}
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
//! Set Fold Angle (`addon.packaging.setFoldAngle`): the angle each fold line folds at. A Crease,
|
||||
//! Partial Cut or Perforation line keeps its own angle in its data under [`KEY`], as a number of
|
||||
//! degrees from -180 to 180; without one it folds at its role's angle (90° for a Crease or a
|
||||
//! Perforation, -90° for a Partial Cut). A positive angle folds away from the printed side.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_three_d::fold::kept_angle;
|
||||
|
||||
use super::super::super::edit::refuse_symbol_part;
|
||||
use super::super::super::overprint::edit_counted;
|
||||
use super::super::super::pathops::number_given;
|
||||
use super::super::super::{CommandSpec, bad, cmd, switch_or};
|
||||
use super::check::kind;
|
||||
use super::roles::{Role, RoleTable, editable_members, role_targets, taken_roots};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// Object data key: a fold line's own fold angle, in degrees. Native save keeps it; SVG export
|
||||
/// leaves `vc-` keys out.
|
||||
pub(crate) const KEY: &str = "vc-fold-angle";
|
||||
|
||||
const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle";
|
||||
|
||||
/// The range a fold angle may take, in degrees.
|
||||
const RANGE: std::ops::RangeInclusive<f64> = -180.0..=180.0;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"addon.packaging.setFoldAngle",
|
||||
"Set Fold Angle…",
|
||||
["Object", "Plug-ins", "Packaging Tools"],
|
||||
None,
|
||||
"{angle?: degrees -180..180, reset?: bool (false), ids?: [id…] (default: the selection)} give each Crease, Partial Cut and Perforation line among the objects (addon.packaging.roles; through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) its own fold angle, rounded to the millionth of a degree, or with reset: true take it away, so the line folds at its role's angle again: 90° for a Crease or a Perforation, -90° for a Partial Cut. A positive angle folds the panel away from the printed side, a negative one toward it; addon.packaging.fold and the Fold Preview window fold each hinge at the angle of the line with the most length in it. Cut lines and objects without a role are skipped and counted. Give exactly one of angle and reset: true. One undo step, none when nothing changes → {ids (the fold lines changed or kept), changed, skipped}",
|
||||
has_fold_line,
|
||||
set_fold_angle
|
||||
)]
|
||||
}
|
||||
|
||||
/// Why Set Fold Angle has nothing to change.
|
||||
const NO_FOLD_LINE: &str = "select a crease, partial cut or perforation line that is neither locked nor hidden";
|
||||
|
||||
/// The last answer of [`has_fold_line`], with what it was for.
|
||||
struct Answer {
|
||||
/// The document (a weak reference keeps another document from taking the same address).
|
||||
doc: Weak<Document>,
|
||||
revision: u64,
|
||||
/// The objects looked at: the selection, or the `ids` a command was given in its place.
|
||||
objects: Vec<NodeId>,
|
||||
found: bool,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Menus ask [`has_fold_line`] on every refresh, and its answer changes only with the
|
||||
/// document, its revision and the objects looked at.
|
||||
static LAST_ANSWER: std::cell::RefCell<Option<Answer>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// The selection holds a line that folds and that Set Fold Angle can change, or an id of no object.
|
||||
fn has_fold_line(s: &Session) -> std::result::Result<(), String> {
|
||||
refuse_symbol_part(s).map_err(|e| e.to_string())?;
|
||||
let st = s.doc().map_err(|e| e.to_string())?;
|
||||
let objects = &st.selection.objects;
|
||||
let kept = LAST_ANSWER.with_borrow(|last| match last {
|
||||
Some(a) if a.revision == st.revision && a.objects == *objects && Weak::ptr_eq(&a.doc, &Arc::downgrade(&st.doc)) => Some(a.found),
|
||||
_ => None,
|
||||
});
|
||||
let found = kept.unwrap_or_else(|| {
|
||||
// An id of no object (given as `ids`) is left to the command, which names it.
|
||||
let found = objects.iter().any(|id| st.doc.node(*id).is_none()) || any_fold_line(&st.doc, objects);
|
||||
LAST_ANSWER.set(Some(Answer { doc: Arc::downgrade(&st.doc), revision: st.revision, objects: objects.clone(), found }));
|
||||
found
|
||||
});
|
||||
if found { Ok(()) } else { Err(NO_FOLD_LINE.into()) }
|
||||
}
|
||||
|
||||
/// Whether the objects `roots` of `d` hold a line that folds and can be changed, looking through
|
||||
/// groups and clip groups as [`role_targets`] does and stopping at the first. As [`taken_roots`]
|
||||
/// takes them, an object inside another one given is left out (a crease in a selected layer counts
|
||||
/// no more than the layer does), a layer is left out, and a path of a compound path stands for the
|
||||
/// compound path, which holds its role, unless it is locked or hidden.
|
||||
fn any_fold_line(d: &Document, roots: &[NodeId]) -> bool {
|
||||
fn find(n: &Node, hit: &dyn Fn(&Node) -> bool) -> bool {
|
||||
match &n.kind {
|
||||
// A group's clipping path draws no stroke.
|
||||
NodeKind::Group { children, .. } => children.iter().any(|c| !matches!(c.kind, NodeKind::Path { clipping: true, .. }) && find(c, hit)),
|
||||
_ => hit(n),
|
||||
}
|
||||
}
|
||||
let table = RoleTable::of(d);
|
||||
let editable = d.editable();
|
||||
let hit = |n: &Node| table.role_of(n).is_some_and(folds) && editable(n.id);
|
||||
let given: HashSet<NodeId> = roots.iter().copied().collect();
|
||||
// Each object's place, from the document's lookup of ids.
|
||||
let outer = |id: NodeId| -> Option<NodeId> {
|
||||
let a = d.ancestry(id)?;
|
||||
let (_, up) = a.split_last()?;
|
||||
if up.iter().any(|p| given.contains(p)) {
|
||||
return None;
|
||||
}
|
||||
match up.last().copied().filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))) {
|
||||
// A locked or hidden path of a compound path is left out, as `editable_members` leaves it.
|
||||
Some(_) if !editable(id) => None,
|
||||
Some(compound) => Some(compound),
|
||||
None => Some(id),
|
||||
}
|
||||
};
|
||||
// An object given twice is looked through once.
|
||||
let mut seen = HashSet::new();
|
||||
roots
|
||||
.iter()
|
||||
.filter_map(|id| outer(*id))
|
||||
.filter(|id| seen.insert(*id))
|
||||
.filter_map(|id| d.node(id))
|
||||
.filter(|n| !n.is_layer())
|
||||
.any(|n| find(n, &hit))
|
||||
}
|
||||
|
||||
/// The text `n`'s data holds under [`KEY`], if any.
|
||||
fn stored(n: &Node) -> Option<&str> {
|
||||
n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
/// `n`'s own fold angle: the number its data holds under [`KEY`], when it is a finite number from
|
||||
/// -180 to 180, to the millionth of a degree it folds at ([`kept_angle`]). Anything else reads as
|
||||
/// no angle of its own.
|
||||
pub(super) fn own_angle(n: &Node) -> Option<f64> {
|
||||
stored(n)?.trim().parse::<f64>().ok().filter(|a| a.is_finite() && RANGE.contains(a)).map(kept_angle)
|
||||
}
|
||||
|
||||
/// Whether a line with `role` folds: every role but Cut.
|
||||
pub(super) fn folds(role: Role) -> bool {
|
||||
kind(role).fold_angle().is_some()
|
||||
}
|
||||
|
||||
/// Writes `angle` (`None`: takes it away) into object `id`'s data → whether its data changed.
|
||||
fn store(d: &mut Document, id: NodeId, angle: Option<f64>) -> bool {
|
||||
// `+ 0.0` turns -0 into 0, so a line set to 0° reads "0".
|
||||
let text = angle.map(|a| format!("{}", a + 0.0));
|
||||
// Read first: taking the node to change it copies it, its geometry included. An angle stored
|
||||
// as other text for the same number ("45.0") is kept; a reset removes any stored text.
|
||||
let same = |n: &Node| match angle {
|
||||
Some(a) => own_angle(n) == Some(a),
|
||||
None => stored(n).is_none(),
|
||||
};
|
||||
if d.node(id).is_none_or(same) {
|
||||
return false;
|
||||
}
|
||||
let Some(n) = d.node_mut(id) else { return false };
|
||||
n.edit_attrs(|a| match text {
|
||||
Some(text) => match a.data.iter_mut().find(|(k, _)| k == KEY) {
|
||||
Some(e) => e.1 = text,
|
||||
None => a.data.push((KEY.into(), text)),
|
||||
},
|
||||
None => a.data.retain(|(k, _)| k != KEY),
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
fn set_fold_angle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let angle = number_given(p, "angle", SET_FOLD_ANGLE)?;
|
||||
let reset = switch_or(p, "reset", false, SET_FOLD_ANGLE)?;
|
||||
let angle = match (angle, reset) {
|
||||
(Some(_), true) => return Err(bad(SET_FOLD_ANGLE, "give `angle` or `reset: true`, not both")),
|
||||
(None, false) => return Err(bad(SET_FOLD_ANGLE, "missing `angle`")),
|
||||
(Some(a), false) if !RANGE.contains(&a) => return Err(bad(SET_FOLD_ANGLE, "`angle` must be from -180 to 180 degrees")),
|
||||
// Kept to the millionth of a degree, the angle the line folds at.
|
||||
(a, _) => a.map(kept_angle),
|
||||
};
|
||||
let (roots, named) = taken_roots(s, p, SET_FOLD_ANGLE)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let (targets, skipped) = role_targets(d, &roots, false);
|
||||
let mut skipped = skipped + named;
|
||||
let mut ids = folding(d, &RoleTable::of(d), &targets);
|
||||
{
|
||||
let editable = d.editable();
|
||||
ids.retain(|id| editable(*id));
|
||||
}
|
||||
skipped += targets.len() - ids.len();
|
||||
if ids.is_empty() {
|
||||
return Err(bad(SET_FOLD_ANGLE, NO_FOLD_LINE));
|
||||
}
|
||||
let label = if angle.is_some() { "Set Fold Angle" } else { "Reset Fold Angle" };
|
||||
let changed = edit_counted(s, label, |d| Ok(ids.iter().filter(|id| store(d, **id, angle)).count()))?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "changed": changed, "skipped": skipped }))
|
||||
}
|
||||
|
||||
/// The lines among `ids` of `d` that fold (Crease, Partial Cut, Perforation), in order.
|
||||
fn folding(d: &Document, table: &RoleTable, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
ids.iter().copied().filter(|id| d.node(*id).and_then(|n| table.role_of(n)).is_some_and(folds)).collect()
|
||||
}
|
||||
|
||||
/// What Set Fold Angle can change among the objects `roots` of `d` (through groups and clip
|
||||
/// groups, leaving out what is locked or hidden, as `addon.packaging.setFoldAngle` does).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct FoldAngles {
|
||||
/// How many lines that fold it can change.
|
||||
pub lines: usize,
|
||||
/// The angle they all fold at (their own or their role's); `None` when they differ or there
|
||||
/// are none.
|
||||
pub angle: Option<f64>,
|
||||
/// How many of them have an angle of their own.
|
||||
pub own: usize,
|
||||
/// How many of them hold text under [`KEY`], an angle or not: what `reset: true` takes away.
|
||||
pub stored: usize,
|
||||
}
|
||||
|
||||
/// The [`FoldAngles`] of the selected objects of the active document, as Set Fold Angle reads them
|
||||
/// with no `ids` (nothing, while it would refuse the selection).
|
||||
pub fn selection_fold_angles(s: &Session) -> FoldAngles {
|
||||
match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) {
|
||||
(Ok((roots, _)), Ok(st)) => fold_angles(&st.doc, &roots),
|
||||
_ => FoldAngles::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines Set Fold Angle changes among the selected objects of the active document, as it takes
|
||||
/// them with no `ids` (none, while it would refuse the selection). Given back as `ids`, they are the
|
||||
/// lines it changes.
|
||||
pub fn selection_fold_lines(s: &Session) -> Vec<NodeId> {
|
||||
match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) {
|
||||
(Ok((roots, _)), Ok(st)) => changeable(&st.doc, &roots).into_iter().map(|(n, _)| n.id).collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`FoldAngles`] of the outermost objects `roots` of `d`.
|
||||
pub(super) fn fold_angles(d: &Document, roots: &[NodeId]) -> FoldAngles {
|
||||
let mut f = FoldAngles::default();
|
||||
for (n, role) in changeable(d, roots) {
|
||||
f.add(n, role);
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
/// The lines that fold among the outermost objects `roots` of `d` that Set Fold Angle can change,
|
||||
/// with their roles, in order.
|
||||
fn changeable<'a>(d: &'a Document, roots: &[NodeId]) -> Vec<(&'a Node, Role)> {
|
||||
let table = RoleTable::of(d);
|
||||
let editable = d.editable();
|
||||
let targets = role_targets(d, &editable_members(d, roots.to_vec()).0, false).0;
|
||||
// The role first: whether an object can be edited can take its bounds to find out.
|
||||
targets
|
||||
.iter()
|
||||
.filter_map(|id| d.node(*id))
|
||||
.filter_map(|n| table.role_of(n).filter(|r| folds(*r)).filter(|_| editable(n.id)).map(|r| (n, r)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl FoldAngles {
|
||||
/// Counts line `n`, which has `role` and can be changed; a line that does not fold is left out.
|
||||
pub(super) fn add(&mut self, n: &Node, role: Role) {
|
||||
let Some(default) = kind(role).fold_angle() else { return };
|
||||
let own = own_angle(n);
|
||||
let a = own.unwrap_or(default);
|
||||
self.angle = if self.lines == 0 { Some(a) } else { self.angle.filter(|b| *b == a) };
|
||||
self.lines += 1;
|
||||
self.own += usize::from(own.is_some());
|
||||
self.stored += usize::from(stored(n).is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,409 @@
|
||||
//! Tests for Set Fold Angle: a fold line's own angle, where it is kept, and how the fold uses it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{KEY, fold_angles, own_angle};
|
||||
use crate::*;
|
||||
|
||||
const SET: &str = "addon.packaging.setFoldAngle";
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn path(s: &mut Session, d: &str) -> u64 {
|
||||
s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn role(s: &mut Session, role: &str, ids: &[u64]) {
|
||||
s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap();
|
||||
}
|
||||
|
||||
fn steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn err(s: &mut Session, p: Value) -> String {
|
||||
s.execute(SET, &p).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
/// The text object `id`'s data holds under the fold angle key.
|
||||
fn stored(s: &Session, id: u64) -> Option<String> {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let n = d.node(NodeId(id)).unwrap();
|
||||
n.extras().attrs.as_deref().and_then(|a| a.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.clone()))
|
||||
}
|
||||
|
||||
/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side →
|
||||
/// (outline, creases: top, right, bottom, left).
|
||||
fn tray(s: &mut Session) -> (u64, Vec<u64>) {
|
||||
let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
|
||||
let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")];
|
||||
role(s, "cut", &[outline]);
|
||||
role(s, "crease", &creases);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
(outline, creases)
|
||||
}
|
||||
|
||||
/// Whether panel `p` of a fold is the tray's top wall (y 100 to 140): the middle of the bounds of
|
||||
/// its outline's points (absolute moves and lines only) is above the base.
|
||||
fn top_wall(p: &Value) -> bool {
|
||||
let d = p["outline"].as_str().unwrap();
|
||||
let n: Vec<f64> = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect();
|
||||
let ys = n.iter().skip(1).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t)));
|
||||
(ys.0 + ys.1) / 2.0 < 140.0
|
||||
}
|
||||
|
||||
fn vector(v: &Value) -> [f64; 3] {
|
||||
let a = v.as_array().unwrap();
|
||||
[a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_fold_angle_keeps_the_angle_on_the_line_and_reset_takes_it_away() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
let before = steps(&s);
|
||||
let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(0), &json!([creases[0]])), "{r}");
|
||||
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
|
||||
assert_eq!(steps(&s), before + 1, "one undo step");
|
||||
// The same angle again changes nothing and records no undo step.
|
||||
let r = s.execute(SET, &json!({"angle": 45.0, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!(r["changed"].as_u64(), Some(0));
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
// An angle is kept to the millionth of a degree, so one closer to 45 than that is 45.
|
||||
let r = s.execute(SET, &json!({"angle": 45.00000001, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before + 1), "{r}");
|
||||
s.execute(SET, &json!({"angle": 179.99999998, "ids": [creases[3]]})).unwrap();
|
||||
assert_eq!(stored(&s, creases[3]).as_deref(), Some("180"));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// A number as text, and the selection when ids is left out; -0 is kept as 0.
|
||||
s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap();
|
||||
let r = s.execute(SET, &json!({"angle": "-0"})).unwrap();
|
||||
assert_eq!(r["changed"].as_u64(), Some(2), "{r}");
|
||||
assert_eq!(stored(&s, creases[1]).as_deref(), Some("0"));
|
||||
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0], creases[1], creases[3]]})).unwrap();
|
||||
assert_eq!(r["changed"].as_u64(), Some(2), "the line without an angle of its own is unchanged: {r}");
|
||||
assert_eq!((stored(&s, creases[0]), stored(&s, creases[1])), (None, None));
|
||||
// Nothing left to reset: no undo step.
|
||||
let at = steps(&s);
|
||||
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), at));
|
||||
// Undo brings the angle back.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_angles_and_targets_are_refused() {
|
||||
let mut s = session();
|
||||
let (outline, creases) = tray(&mut s);
|
||||
let plain = path(&mut s, "M10 10 L50 50");
|
||||
let before = steps(&s);
|
||||
let ids = json!([creases[0]]);
|
||||
assert!(err(&mut s, json!({"ids": ids})).contains("missing `angle`"));
|
||||
assert!(err(&mut s, json!({"angle": 30, "reset": true, "ids": ids})).contains("not both"));
|
||||
assert!(err(&mut s, json!({"angle": 180.5, "ids": ids})).contains("from -180 to 180"));
|
||||
assert!(err(&mut s, json!({"angle": -181, "ids": ids})).contains("from -180 to 180"));
|
||||
assert!(err(&mut s, json!({"angle": "wide", "ids": ids})).contains("must be a number"));
|
||||
assert!(err(&mut s, json!({"angle": true, "ids": ids})).contains("must be a number"));
|
||||
assert!(err(&mut s, json!({"reset": "yes", "ids": ids})).contains("true or false"));
|
||||
// A cut line and a path without a role do not fold.
|
||||
assert!(err(&mut s, json!({"angle": 30, "ids": [outline, plain]})).contains("crease, partial cut or perforation"));
|
||||
// An id of no object is named as such, alone or beside a crease.
|
||||
assert!(err(&mut s, json!({"angle": 30, "ids": [999_999]})).contains("no such object id 999999"));
|
||||
assert!(err(&mut s, json!({"angle": 30, "ids": [creases[0], 999_999]})).contains("no such object id 999999"));
|
||||
assert_eq!(steps(&s), before, "no refusal records an undo step");
|
||||
// The ends of the range are allowed; cut lines and plain paths among fold lines are skipped.
|
||||
let r = s.execute(SET, &json!({"angle": -180, "ids": [creases[0], outline, plain]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(2), &json!([creases[0]])), "{r}");
|
||||
s.execute(SET, &json!({"angle": 180, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!(stored(&s, creases[0]).as_deref(), Some("180"));
|
||||
assert_eq!(stored(&s, outline), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_fold_angle_is_dimmed_without_a_line_it_can_change() {
|
||||
let mut s = session();
|
||||
let (outline, creases) = tray(&mut s);
|
||||
let enabled = |s: &Session| (find_command(SET).unwrap().enabled)(s).is_ok();
|
||||
assert!(!enabled(&s), "nothing selected");
|
||||
s.execute("select.set", &json!({"ids": [outline]})).unwrap();
|
||||
assert!(!enabled(&s), "a cut line does not fold");
|
||||
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
|
||||
s.execute("select.set", &json!({"ids": [creases[0]]})).unwrap();
|
||||
assert!(enabled(&s));
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(creases[0])]).lines, 0, "a locked crease can't be changed");
|
||||
// A group holding a crease is enough.
|
||||
s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
assert!(enabled(&s));
|
||||
// A layer selected with a crease in it: the crease is inside the layer, which is left out, as
|
||||
// Set Fold Angle itself leaves them out.
|
||||
let layer = s.doc().unwrap().doc.layer_of(NodeId(creases[3])).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [layer.0, creases[3]]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "both are selected");
|
||||
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
|
||||
assert!(!enabled(&s), "dimmed as the command refuses it");
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}");
|
||||
// With nothing selected the counts are the document's, but Set Fold Angle takes no line.
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
assert!(s.execute(SET, &json!({"angle": 30})).is_err());
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
assert_eq!(r["scope"].as_str(), Some("document"), "{r}");
|
||||
assert_eq!(r["roles"][1]["count"].as_u64(), Some(4), "{r}");
|
||||
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crease_named_in_ids_is_set_after_the_menu_found_none_in_the_selection() {
|
||||
let mut s = session();
|
||||
let (outline, creases) = tray(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [outline]})).unwrap();
|
||||
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "a cut line does not fold");
|
||||
let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!(r["changed"].as_u64(), Some(1), "{r}");
|
||||
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "the selection is still the cut line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_s_fold_angles_count_a_crease_and_its_selected_group_once() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let group = s.doc().unwrap().selection.objects[0].0;
|
||||
s.execute("select.set", &json!({"ids": [group, creases[0]]})).unwrap();
|
||||
let f = crate::cmd::selection_fold_angles(&s);
|
||||
assert_eq!((f.lines, f.angle, f.own), (2, None, 1), "{f:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_locked_crease_is_skipped() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0], creases[1]]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)), "{r}");
|
||||
assert_eq!(stored(&s, creases[1]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_locked_path_of_a_compound_crease_named_by_id_is_skipped() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
let (a, b) = (path(&mut s, "M300 300 L400 300"), path(&mut s, "M300 320 L400 320"));
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
role(&mut s, "crease", &[compound]);
|
||||
s.edit("Test", |d, _| {
|
||||
if let Some(n) = d.node_mut(NodeId(a)) {
|
||||
n.locked = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(err(&mut s, json!({"angle": 30, "ids": [a]})).contains("crease, partial cut or perforation"));
|
||||
// Named twice, it is skipped once.
|
||||
let r = s.execute(SET, &json!({"angle": 30, "ids": [a, a, creases[0]]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(1), &json!([creases[0]])), "{r}");
|
||||
assert_eq!(stored(&s, compound), None);
|
||||
assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(a)]).lines, 0);
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap();
|
||||
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}");
|
||||
// The same with the locked path selected.
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "dimmed");
|
||||
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
|
||||
assert_eq!(crate::cmd::selection_fold_angles(&s).lines, 0);
|
||||
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
|
||||
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}");
|
||||
assert_eq!(stored(&s, compound), None);
|
||||
// With its compound, given or selected, the locked path is part of the compound, not skipped.
|
||||
let r = s.execute(SET, &json!({"angle": 20, "ids": [compound, a]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}");
|
||||
s.execute("select.set", &json!({"ids": [compound, a]})).unwrap();
|
||||
let r = s.execute(SET, &json!({"angle": 25})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}");
|
||||
s.execute(SET, &json!({"reset": true, "ids": [compound]})).unwrap();
|
||||
// The compound named by id takes the angle; its other path, not locked, names it too.
|
||||
let r = s.execute(SET, &json!({"angle": 30, "ids": [b]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), &r["ids"]), (Some(1), &json!([compound])), "{r}");
|
||||
assert_eq!(stored(&s, compound).as_deref(), Some("30"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_damaged_angle_reads_as_none_of_its_own() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
let mut n = s.doc().unwrap().doc.node(NodeId(creases[0])).cloned().unwrap();
|
||||
for (text, want) in [("45", Some(45.0)), (" -30.5 ", Some(-30.5)), ("wide", None), ("NaN", None), ("inf", None), ("181", None), ("", None)] {
|
||||
n.edit_attrs(|a| {
|
||||
a.data.retain(|(k, _)| k != KEY);
|
||||
a.data.push((KEY.into(), text.into()));
|
||||
});
|
||||
assert_eq!(own_angle(&n), want, "{text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_angle_stored_as_other_text_for_the_same_number_is_unchanged() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
let id = NodeId(creases[0]);
|
||||
s.edit("Test", |d, _| {
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
n.edit_attrs(|a| a.data.push((KEY.into(), "45.0".into())));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = steps(&s);
|
||||
let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before), "{r}");
|
||||
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45.0"));
|
||||
s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!(stored(&s, creases[0]), None);
|
||||
// A reset also removes text that is not an angle.
|
||||
s.edit("Test", |d, _| {
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
n.edit_attrs(|a| a.data.push((KEY.into(), "wide".into())));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), stored(&s, creases[0])), (Some(1), None), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_keeps_its_own_angle_through_a_role_change() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
|
||||
role(&mut s, "partialCut", &[creases[0]]);
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap();
|
||||
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}");
|
||||
role(&mut s, "none", &[creases[0]]);
|
||||
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
|
||||
role(&mut s, "crease", &[creases[0]]);
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap();
|
||||
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_save_and_preserve_editing_keep_the_angle_and_svg_leaves_it_out() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
s.execute(SET, &json!({"angle": 120, "ids": [creases[0]]})).unwrap();
|
||||
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
|
||||
let svg = svg["text"]
|
||||
.as_str()
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| String::from_utf8_lossy(&vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).into_owned());
|
||||
assert!(svg.contains("<svg"), "{svg}");
|
||||
assert!(!svg.contains("fold-angle"), "{svg}");
|
||||
// An SVG with Preserve Editing reopens as the document it carries, the angle with it.
|
||||
let editing = s.execute("document.serialize", &json!({"format": "svg", "preserveEditing": true})).unwrap();
|
||||
let editing = editing["text"].as_str().unwrap().to_string();
|
||||
let mut t = Session::new();
|
||||
t.execute("document.open", &json!({"name": "box.svg", "dataBase64": vectorcraft_format::base64_encode(editing.as_bytes())})).unwrap();
|
||||
assert_eq!(stored(&t, creases[0]).as_deref(), Some("120"));
|
||||
let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap();
|
||||
s.execute("document.open", &json!({"name": "box.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
|
||||
assert_eq!(stored(&s, creases[0]).as_deref(), Some("120"));
|
||||
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
|
||||
let angles: Vec<f64> = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect();
|
||||
assert!(angles.contains(&120.0), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tray_wall_with_its_own_angle_stands_at_that_angle() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
// The top wall (y 100 to 140) folds at 45°.
|
||||
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
|
||||
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
|
||||
let base = r["base"].as_u64().unwrap() as usize;
|
||||
let mut angles: Vec<f64> = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect();
|
||||
angles.sort_by(f64::total_cmp);
|
||||
assert_eq!(angles, [45.0, 90.0, 90.0, 90.0]);
|
||||
for (i, p) in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base) {
|
||||
let z = vector(&p["frame"]["z"]);
|
||||
let top = top_wall(p);
|
||||
let tilt = if top { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 };
|
||||
assert!((z[2] - tilt).abs() < 1e-9, "panel {i}: {p}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_negative_angle_folds_a_crease_toward_the_print() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
s.execute(SET, &json!({"angle": -90, "ids": [creases[0]]})).unwrap();
|
||||
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
|
||||
let base = r["base"].as_u64().unwrap() as usize;
|
||||
let mut up = 0;
|
||||
for p in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base).map(|(_, p)| p) {
|
||||
// The top wall folds toward the print, so its printed side faces back over the base
|
||||
// (toward -y in the y-up frame); the other walls stand square to the base as before.
|
||||
let top = top_wall(p);
|
||||
let z = vector(&p["frame"]["z"]);
|
||||
if top {
|
||||
assert!((z[1] + 1.0).abs() < 1e-9, "the top wall's print faces the base: {p}");
|
||||
up += 1;
|
||||
} else {
|
||||
assert!(z[2].abs() < 1e-9, "{p}");
|
||||
}
|
||||
}
|
||||
assert_eq!(up, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roles_reports_the_angle_the_selected_fold_lines_share() {
|
||||
let mut s = session();
|
||||
let (outline, creases) = tray(&mut s);
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap();
|
||||
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(90.0), Some(0)), "the role's angle: {r}");
|
||||
s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap();
|
||||
assert_eq!((r["foldAngle"].clone(), r["ownAngles"].as_u64()), (Value::Null, Some(1)), "they differ: {r}");
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], outline]})).unwrap();
|
||||
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(30.0), Some(1)), "a cut line has no angle: {r}");
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [outline]})).unwrap();
|
||||
assert!(r["foldAngle"].is_null(), "{r}");
|
||||
// A partial cut folds at -90° unless it has an angle of its own.
|
||||
role(&mut s, "partialCut", &[creases[2]]);
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[2]]})).unwrap();
|
||||
assert_eq!((r["foldAngle"].as_f64(), r["foldLines"].as_u64()), (Some(-90.0), Some(1)), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roles_leaves_locked_fold_lines_out_of_the_angle_as_set_fold_angle_does() {
|
||||
let mut s = session();
|
||||
let (_, creases) = tray(&mut s);
|
||||
s.execute(SET, &json!({"angle": 45, "ids": [creases[1]]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let group = s.doc().unwrap().selection.objects[0].0;
|
||||
s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap();
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
let r = s.execute("addon.packaging.roles", &json!({"ids": [group]})).unwrap();
|
||||
assert_eq!(r["roles"][1]["count"].as_u64(), Some(2), "both are counted: {r}");
|
||||
assert_eq!((r["foldLines"].as_u64(), r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(1), Some(90.0), Some(0)), "{r}");
|
||||
// So Reset has nothing to change, as the panel shows it.
|
||||
let r = s.execute(SET, &json!({"reset": true, "ids": [group]})).unwrap();
|
||||
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}");
|
||||
let (lines, angle, own) = {
|
||||
let f = fold_angles(&s.doc().unwrap().doc, &[NodeId(group)]);
|
||||
(f.lines, f.angle, f.own)
|
||||
};
|
||||
assert_eq!((lines, angle, own), (1, Some(90.0), 0));
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX
|
||||
|
||||
use super::super::super::pathops::length_given;
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
|
||||
use super::angle::own_angle;
|
||||
use super::roles::{Role, RoleTable, can_carry, role_targets};
|
||||
use crate::{Result, Session};
|
||||
|
||||
@@ -92,7 +93,8 @@ fn on_non_printing_layer(d: &Document, id: NodeId) -> bool {
|
||||
d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. }))
|
||||
}
|
||||
|
||||
fn kind(role: Role) -> LineKind {
|
||||
/// The kind of fold line a line with `role` is.
|
||||
pub(super) fn kind(role: Role) -> LineKind {
|
||||
match role {
|
||||
Role::Cut => LineKind::Cut,
|
||||
Role::Crease => LineKind::Crease,
|
||||
@@ -155,7 +157,7 @@ fn lines_of(d: &Document, scope: &'static str, targets: Vec<NodeId>) -> Lines {
|
||||
non_printing.push(id.0);
|
||||
}
|
||||
segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum());
|
||||
lines.push(FoldLine { path, kind: kind(role), key: id.0 });
|
||||
lines.push(FoldLine { path, kind: kind(role), key: id.0, angle: own_angle(n) });
|
||||
}
|
||||
Lines { scope, lines, non_printing }
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fold",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
|
||||
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true when the gap is within the larger of tolerance and 0.5% of the distance between the hinge's two ends. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
|
||||
has_doc,
|
||||
fold_command
|
||||
)]
|
||||
|
||||
@@ -10,6 +10,7 @@ use vectorcraft_color::swatch::REGISTRATION;
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::super::super::edit::{outermost, refuse_symbol_part, roots_of};
|
||||
use super::super::super::overprint::edit_counted;
|
||||
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
|
||||
use crate::{Result, Session};
|
||||
@@ -194,6 +195,41 @@ pub(super) fn can_carry(n: &Node) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects a command that changes roles or angles takes for params `p`: `ids` (the outermost of
|
||||
/// them), or else the selection (as `selected_roots` takes it), with a path of a compound path that
|
||||
/// is locked or hidden, or in a locked or hidden group or layer, or on a locked artboard, left out
|
||||
/// before it stands for its compound, and how many such paths were left out, each once.
|
||||
pub(super) fn taken_roots(s: &Session, p: &Value, command: &str) -> Result<(Vec<NodeId>, usize)> {
|
||||
if p.get("ids").is_some_and(|v| !v.is_null()) {
|
||||
let roots = checked_ids_or_selection(s, p, command)?;
|
||||
return Ok(editable_members(&s.doc()?.doc, roots));
|
||||
}
|
||||
refuse_symbol_part(s)?;
|
||||
let st = s.doc()?;
|
||||
// An object inside another selected one is left out first, as it is from `ids`.
|
||||
let (kept, left) = editable_members(&st.doc, outermost(&st.doc, st.selection.in_paint_order(&st.doc)));
|
||||
Ok((roots_of(&st.doc, kept), left))
|
||||
}
|
||||
|
||||
/// `ids` less the paths of compound paths among them that are locked or hidden (or in a locked or
|
||||
/// hidden group or layer, or on a locked artboard), and how many different ones were left out.
|
||||
pub(super) fn editable_members(d: &Document, ids: Vec<NodeId>) -> (Vec<NodeId>, usize) {
|
||||
let ok = d.editable();
|
||||
let member = |id: NodeId| d.parent_of(id).is_some_and(|p| matches!(d.node(p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
|
||||
let mut left = std::collections::HashSet::new();
|
||||
let kept = ids
|
||||
.into_iter()
|
||||
.filter(|id| {
|
||||
let out = member(*id) && !ok(*id);
|
||||
if out {
|
||||
left.insert(*id);
|
||||
}
|
||||
!out
|
||||
})
|
||||
.collect();
|
||||
(kept, left.len())
|
||||
}
|
||||
|
||||
/// The objects under the outermost objects `roots` that can carry a role, through groups and clip
|
||||
/// groups, each once, and
|
||||
/// how many of `roots` and their members can't (text, images, symbol instances and other objects).
|
||||
@@ -257,7 +293,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make Fold Line",
|
||||
["Object", "Plug-ins", "Packaging Tools"],
|
||||
None,
|
||||
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
|
||||
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. A line keeps its own fold angle (addon.packaging.setFoldAngle) through a role change and through none. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
|
||||
has_selection,
|
||||
set_role
|
||||
),
|
||||
@@ -266,7 +302,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fold Lines",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out",
|
||||
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected), foldLines, foldAngle, ownAngles, storedAngles}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out. foldLines is how many of the Crease, Partial Cut and Perforation lines among them addon.packaging.setFoldAngle can change (those not locked or hidden; none while nothing is selected and ids is left out, or while the selection holds only a layer and objects in it), foldAngle the angle in degrees they all fold at (their own or their role's), null when they fold at different angles or there are none, ownAngles how many of them have an angle of their own, and storedAngles how many hold stored angle text, an angle or not, which setFoldAngle's reset: true removes",
|
||||
has_doc,
|
||||
roles
|
||||
),
|
||||
@@ -382,8 +418,9 @@ fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Pai
|
||||
fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let role = role_param(p, SET_ROLE, true)?;
|
||||
let overprint = switch_or(p, "overprint", true, SET_ROLE)?;
|
||||
let roots = checked_ids_or_selection(s, p, SET_ROLE)?;
|
||||
let (roots, left) = taken_roots(s, p, SET_ROLE)?;
|
||||
let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true);
|
||||
let skipped = skipped + left;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role"));
|
||||
}
|
||||
@@ -403,19 +440,38 @@ fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn roles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let given = p.get("ids").is_some_and(|v| !v.is_null());
|
||||
let roots = checked_ids_or_selection(s, p, ROLES)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// The objects Set Fold Angle takes: a locked or hidden path of a compound path does not stand
|
||||
// for its compound there. They are the objects the counts are of unless such a path was left
|
||||
// out, and only then are those found apart.
|
||||
let (taken, left) = taken_roots(s, p, ROLES)?;
|
||||
let (roots, angle_roots) = if left == 0 { (taken, vec![]) } else { (checked_ids_or_selection(s, p, ROLES)?, taken) };
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let (scope, ids) = match (given, roots.is_empty()) {
|
||||
(true, _) => ("ids", role_targets(d, &roots, false).0),
|
||||
(false, false) => ("selection", role_targets(d, &roots, false).0),
|
||||
(false, true) => ("document", document_targets(d)),
|
||||
};
|
||||
let whole = scope == "document";
|
||||
// The lines Set Fold Angle can change are those of the objects it takes: with nothing selected,
|
||||
// or a selection that holds no such object (only a layer and what is in it), it takes none,
|
||||
// though the counts are the document's.
|
||||
let angles_of_all = given || !roots.is_empty();
|
||||
let table = RoleTable::of(d);
|
||||
let mut counts = [0usize; 4];
|
||||
for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) {
|
||||
let editable = d.editable();
|
||||
let mut angles = super::angle::FoldAngles::default();
|
||||
for n in ids.iter().filter_map(|id| d.node(*id)) {
|
||||
let Some(r) = table.role_of(n) else { continue };
|
||||
if let Some(c) = counts.get_mut(r.index()) {
|
||||
*c += 1;
|
||||
}
|
||||
if left == 0 && angles_of_all && super::angle::folds(r) && editable(n.id) {
|
||||
angles.add(n, r);
|
||||
}
|
||||
}
|
||||
if !whole && left > 0 {
|
||||
angles = super::angle::fold_angles(d, &angle_roots);
|
||||
}
|
||||
let rows: Vec<Value> = Role::ALL
|
||||
.into_iter()
|
||||
@@ -425,7 +481,10 @@ fn roles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count })
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() }))
|
||||
Ok(json!({
|
||||
"roles": rows, "scope": scope, "selected": roots.len(),
|
||||
"foldLines": angles.lines, "foldAngle": angles.angle, "ownAngles": angles.own, "storedAngles": angles.stored,
|
||||
}))
|
||||
}
|
||||
|
||||
fn set_role_swatch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -537,4 +537,20 @@ fn compound_paths_carry_a_role() {
|
||||
let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1)));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
|
||||
// A locked member named by id is skipped, and its compound keeps its role.
|
||||
s.edit("Test", |d, _| {
|
||||
if let Some(n) = d.node_mut(a) {
|
||||
n.locked = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0]})).contains("neither locked nor hidden"));
|
||||
// The same with the locked path selected.
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut"})).contains("neither locked nor hidden"));
|
||||
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
|
||||
// Named twice, it is skipped once.
|
||||
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, a.0, b.0]}));
|
||||
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([c.0]), Some(1)), "{r}");
|
||||
}
|
||||
@@ -4,13 +4,15 @@
|
||||
//! (`vectorcraft_tools::addons::parametric_shape`), which SVG export leaves out.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
use vectorcraft_doc::{Document, Node, NodeKind};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point};
|
||||
use vectorcraft_pathops::addons::pathtools::shapes::{ParametricShape, ShapeKind, recognise};
|
||||
use vectorcraft_render::effects;
|
||||
use vectorcraft_tools::addons::parametric_shape::{CREATE, EDIT, KEY, apply, read, stored, to_json};
|
||||
|
||||
use super::super::super::menucmds::whole_or;
|
||||
use super::super::super::{CommandSpec, bad, checked_id, checked_ids_or_selection, cmd, has_doc, has_selection};
|
||||
use crate::{EngineError, Result, Session};
|
||||
use crate::{EngineError, MAX_COORD, Result, Session};
|
||||
|
||||
/// The undo step's name and the command's label.
|
||||
const CONVERT: &str = "Convert to Parametric Shape";
|
||||
@@ -31,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Parametric Shape",
|
||||
[],
|
||||
None,
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with none, or the same ones, nothing changes → {id, shape (its numbers now)}",
|
||||
"{id, kind?, center?, width?, height?, rotation?: degrees clockwise (0: upright), count?, a?, b?, radius?, reference?: 0..8 (a point on the 9-point grid of the bounding box as object.setBounds measures it, rotated with rotated objects)} change a parametric shape's numbers (as addon.pathtools.shape.create takes them; a new kind takes its own defaults for the values not given), as one undo step; with `reference` and no `center`, that point of the bounding box keeps its place (as the Transform panel's W and H do; snapping to the pixel grid and an attachment to a path apply afterwards), with `center` the shape's center moves to it, otherwise the center stays; with none, or the same ones, nothing changes → {id, shape (its numbers now; null when snapping to the pixel grid left a plain path)}",
|
||||
has_doc,
|
||||
set
|
||||
),
|
||||
@@ -95,15 +97,55 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "the path is locked or hidden"));
|
||||
}
|
||||
let old = d.node(id).and_then(read).ok_or_else(|| bad(C, "the object is not an editable parametric shape"))?;
|
||||
let reference = match p.get("reference").filter(|v| !v.is_null()) {
|
||||
Some(_) => match whole_or(p, "reference", 4, C)? {
|
||||
i @ 0..=8 => Some(i as usize),
|
||||
_ => return Err(bad(C, "`reference` must be from 0 to 8")),
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let shape = apply(old, p).map_err(|e| bad(C, e))?;
|
||||
if shape != old {
|
||||
// Without a center, the reference point of the bounding box (as the Transform panel and
|
||||
// `object.setBounds` measure it; the geometric box where the preview leaves none) keeps
|
||||
// its place: the new outline moves onto it. The box after the edit is measured the same way
|
||||
// as the box before it.
|
||||
let how = s.bounds_measure();
|
||||
let geometric = effects::preview::Measure { preview: false, ..how };
|
||||
let boxed = |d: &Document, m: effects::preview::Measure| effects::preview::oriented_bounds_with(d, &[id], m).map(|b| (m, b));
|
||||
let keep = match reference.filter(|_| p.get("center").is_none_or(Value::is_null)) {
|
||||
Some(i) => {
|
||||
let d = &s.doc()?.doc;
|
||||
let (m, b) = boxed(d, how).or_else(|| boxed(d, geometric)).ok_or_else(|| EngineError::Other("no bounds".into()))?;
|
||||
Some((i, m, b.reference_point(i)))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let path = outline(&shape, C)?;
|
||||
s.edit(EDIT, |d, sel| {
|
||||
shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &shape, path);
|
||||
if let Some((i, m, was)) = keep
|
||||
&& let Some(now) = boxed(d, m).map(|(_, b)| b.reference_point(i))
|
||||
&& now != was
|
||||
{
|
||||
let mut moved = shape;
|
||||
moved.center += was - now;
|
||||
let path = outline(&moved, C)?;
|
||||
shape_node(d.node_mut(id).ok_or(EngineError::NoNode(id))?, &moved, path);
|
||||
}
|
||||
// A shape named by `id` and not selected is not checked after the edit: one the edit
|
||||
// takes past the coordinate limit is an error here, and nothing changes.
|
||||
if !crate::sanity::objects_in_range(d, &[id]) {
|
||||
return Err(bad(C, format!("coordinate out of range (limit ±{MAX_COORD} pt)")));
|
||||
}
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
Ok(())
|
||||
})?;
|
||||
// The numbers the edit committed (an object attached to a path is put back on it); none
|
||||
// when snapping to the pixel grid left a plain path.
|
||||
let committed = s.doc()?.doc.node(id).and_then(read);
|
||||
return Ok(json!({ "id": id.0, "shape": committed.map_or(Value::Null, |c| to_json(&c)) }));
|
||||
}
|
||||
Ok(json!({ "id": id.0, "shape": to_json(&shape) }))
|
||||
}
|
||||
|
||||
@@ -476,6 +476,92 @@ fn set_changes_the_numbers_in_one_step_and_nothing_without_a_change() {
|
||||
assert_eq!(path(&s, id).anchor_count(), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_keeps_the_reference_point_of_the_bounding_box_in_place() {
|
||||
let mut s = session();
|
||||
let corner = |s: &Session, id: NodeId, i: usize| s.transform_box(&[id]).unwrap().reference_point(i);
|
||||
// (kind, its own rotation, a turn with object.rotate, which turns its bounding box too)
|
||||
for (kind, rotation, turn) in [
|
||||
("rectangle", 0.0, 0.0),
|
||||
("rectangle", 30.0, 0.0),
|
||||
("rectangle", 180.0, 0.0),
|
||||
("rectangle", 0.0, 30.0),
|
||||
("star", 0.0, 0.0),
|
||||
("heart", 0.0, 0.0),
|
||||
] {
|
||||
let r = s.execute("addon.pathtools.shape.create", &json!({"kind": kind, "center": [200, 150], "rotation": rotation})).unwrap();
|
||||
let id = id_of(&r);
|
||||
if turn != 0.0 {
|
||||
s.execute("object.rotate", &json!({"angle": turn, "origin": [200, 150]})).unwrap();
|
||||
assert!(s.transform_box(&[id]).unwrap().angle != 0.0, "the box turns with the object");
|
||||
}
|
||||
// Each of the 9 points of the box the Transform panel shows stays where it was while the
|
||||
// width and then the height change, as `object.setBounds` keeps it.
|
||||
for refi in 0..9 {
|
||||
for key in ["width", "height"] {
|
||||
let (before, was) = (shape_of(&s, id).unwrap(), corner(&s, id, refi));
|
||||
let grown = if key == "width" { before.width } else { before.height } + 10.0;
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, key: grown, "reference": refi})).unwrap();
|
||||
let moved = corner(&s, id, refi).distance(was);
|
||||
assert!(moved < 1e-6, "{kind} at {rotation}°, reference {refi}, {key}: the point moved {moved} pt");
|
||||
let after = shape_of(&s, id).unwrap();
|
||||
assert!((if key == "width" { after.width } else { after.height } - grown).abs() < 1e-9, "{kind}, {key}: the new size");
|
||||
}
|
||||
}
|
||||
// Without a reference point, and with an explicit center, the old rules hold.
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 80})).unwrap();
|
||||
let c = shape_of(&s, id).unwrap().center;
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 120})).unwrap();
|
||||
assert!(shape_of(&s, id).unwrap().center.distance(c) < 1e-9, "the center stays by default");
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 60, "center": [10, 20], "reference": 0})).unwrap();
|
||||
assert!(shape_of(&s, id).unwrap().center.distance(Point::new(10.0, 20.0)) < 1e-9, "a center given wins");
|
||||
}
|
||||
let id = star(&mut s);
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.pathtools.shape.set",
|
||||
&[
|
||||
json!({"id": id.0, "width": 50, "reference": -1}),
|
||||
json!({"id": id.0, "width": 50, "reference": 1.5}),
|
||||
json!({"id": id.0, "width": 50, "reference": 9}),
|
||||
json!({"id": id.0, "width": 50, "reference": 9.0}),
|
||||
],
|
||||
);
|
||||
// A whole number written with a decimal point picks the same point.
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 50, "reference": 8.0})).unwrap();
|
||||
let written_whole = shape_of(&s, id).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "width": 50, "reference": 8})).unwrap();
|
||||
assert!(shape_of(&s, id).unwrap().center.distance(written_whole.center) < 1e-9, "`8.0` and `8` pick the same point");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// With Use Preview Bounds the point is on the box as drawn: a star's stroked tips reach past
|
||||
// its anchors by more as the star is stretched, so the drawn box and the anchors' box move apart.
|
||||
s.prefs.use_preview_bounds = true;
|
||||
let stroked = id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": "star", "center": [300, 300], "count": 5})).unwrap());
|
||||
s.execute("paint.setStroke", &json!({"ids": [stroked.0], "color": "#000000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [stroked.0], "weight": 12})).unwrap();
|
||||
let geometric = |s: &Session, i: usize| s.doc().unwrap().doc.oriented_bounds(&[stroked], false).unwrap().reference_point(i);
|
||||
for refi in [0, 2, 6, 8] {
|
||||
let (was, anchors_were) = (corner(&s, stroked, refi), geometric(&s, refi));
|
||||
let wide = shape_of(&s, stroked).unwrap().width * 2.5;
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": stroked.0, "width": wide, "reference": refi})).unwrap();
|
||||
let moved = corner(&s, stroked, refi).distance(was);
|
||||
assert!(moved < 1e-6, "stroked star, reference {refi}: the drawn box's point moved {moved} pt");
|
||||
assert!(geometric(&s, refi).distance(anchors_were) > 1e-3, "reference {refi}: the anchors' box is not the one kept");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
s.prefs.use_preview_bounds = false;
|
||||
// A shape set by id, not selected, that the edit would take past the coordinate limit.
|
||||
let edge = id_of(&s.execute("addon.pathtools.shape.create", &json!({"kind": "rectangle", "center": [3_999_900, 100]})).unwrap());
|
||||
select(&mut s, &[]);
|
||||
refuses(
|
||||
&mut s,
|
||||
"addon.pathtools.shape.set",
|
||||
&[json!({"id": edge.0, "width": 180, "reference": 0}), json!({"id": edge.0, "center": [3_999_990, 100]})],
|
||||
);
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": edge.0, "width": 180, "reference": 2})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_shape_params_are_refused() {
|
||||
let mut s = session();
|
||||
@@ -1086,6 +1172,64 @@ fn the_tangent_circle_tool_keeps_its_first_segment_when_drawing_fails() {
|
||||
assert!(!shown(&mut s), "the first segment is forgotten once the circle is drawn");
|
||||
}
|
||||
|
||||
/// With Add Points to Existing Paths on, the Tangent Circle tool's circle and an anchor point where
|
||||
/// it touches each line are one undo step; the lines keep their shape, and one Undo takes all of it
|
||||
/// back.
|
||||
#[test]
|
||||
fn the_tangent_circle_tool_adds_points_where_the_circle_touches_in_one_step() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false);
|
||||
let b = line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false);
|
||||
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
|
||||
s.select_tool("tangentCircle", view).unwrap();
|
||||
s.set_tool_option("addPoints", &json!(true));
|
||||
let n = steps(&s);
|
||||
for (kind, x, y) in
|
||||
[(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)]
|
||||
{
|
||||
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
|
||||
}
|
||||
assert_eq!(steps(&s), n + 1, "one undo step");
|
||||
let points = |s: &Session, id| path(s, id).subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::<Vec<_>>();
|
||||
let near = |got: Vec<(f64, f64)>, want: &[(f64, f64)]| {
|
||||
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6)
|
||||
};
|
||||
assert!(near(points(&s, a), &[(100.0, 100.0), (150.0, 100.0), (300.0, 100.0)]), "{:?}", points(&s, a));
|
||||
assert!(near(points(&s, b), &[(100.0, 140.0), (150.0, 140.0), (300.0, 140.0)]), "{:?}", points(&s, b));
|
||||
let st = s.doc().unwrap();
|
||||
let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) };
|
||||
let r = st.doc.node(circle).and_then(|c| c.path_data()).and_then(|pd| pd.bounds()).unwrap();
|
||||
assert!((r.x0 - 130.0).abs() < 1e-6 && (r.y0 - 100.0).abs() < 1e-6 && (r.width() - 40.0).abs() < 1e-6, "{r:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((steps(&s), points(&s, a).len(), points(&s, b).len()), (n, 2, 2));
|
||||
assert!(s.doc().unwrap().doc.node(circle).is_none(), "the circle is gone too");
|
||||
}
|
||||
|
||||
/// In Draw Behind, the Tangent Circle tool's circle goes behind the object selected before the
|
||||
/// clicks, also when Add Points to Existing Paths adds anchors to lines that were not selected.
|
||||
#[test]
|
||||
fn the_tangent_circle_tool_adding_points_draws_behind_the_selection() {
|
||||
let mut s = session();
|
||||
line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false);
|
||||
line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false);
|
||||
let other = line(&mut s, &[(100.0, 400.0), (300.0, 400.0)], false);
|
||||
select(&mut s, &[other]);
|
||||
s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap();
|
||||
let view = ViewInfo { smart_guides: false, ..ViewInfo::default() };
|
||||
s.select_tool("tangentCircle", view).unwrap();
|
||||
s.set_tool_option("addPoints", &json!(true));
|
||||
for (kind, x, y) in
|
||||
[(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0), (PointerKind::Up, 200.0, 139.0)]
|
||||
{
|
||||
s.pointer(&PointerEvent::new(kind, x, y), view).unwrap();
|
||||
}
|
||||
let st = s.doc().unwrap();
|
||||
let [circle] = st.selection.objects[..] else { panic!("{:?}", st.selection.objects) };
|
||||
let at = |id| st.doc.position(id).map(|(parent, index, _)| (parent, index));
|
||||
let (Some((p, c)), Some((q, o))) = (at(circle), at(other)) else { panic!("not placed") };
|
||||
assert!(p == q && c + 1 == o, "the circle is right behind the selected line: {c} and {o}");
|
||||
}
|
||||
|
||||
fn ids(v: &Value) -> Vec<NodeId> {
|
||||
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ use vectorcraft_text::edit;
|
||||
use super::super::menucmds::whole_or;
|
||||
use super::super::object::choice;
|
||||
use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges};
|
||||
use super::super::typecmd::refresh_bounds;
|
||||
use super::super::typecmd::{refresh_bounds, refresh_with_given_leading};
|
||||
use super::super::typemenu::{bake_dynamic_text, text_ids};
|
||||
use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets};
|
||||
use crate::{EngineError, Result, Session};
|
||||
@@ -170,7 +170,11 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for (id, changes) in &plans {
|
||||
let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?;
|
||||
t.runs = tweak(std::mem::take(&mut t.runs), changes);
|
||||
refresh_bounds(t);
|
||||
// With Block on, the first changed character's leading goes to the frame's line gap.
|
||||
match changes.first().filter(|_| key == "leading") {
|
||||
Some(&(at, _)) => refresh_with_given_leading(t, at),
|
||||
None => refresh_bounds(t),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill Area",
|
||||
[],
|
||||
None,
|
||||
"{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, only the paths of the listed objects that are in it), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}",
|
||||
"{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too; a path a clipping mask clips bounds areas only where every mask around it shows it), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, the paths of the listed objects that are in it, and all of its paths when a listed layer or group holds it or is it; other listed objects are ignored), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}",
|
||||
has_doc,
|
||||
sb_copy_region
|
||||
),
|
||||
|
||||
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Swatch Conflicts",
|
||||
[],
|
||||
None,
|
||||
"{profileMismatch?: as edit.paste} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours",
|
||||
"{profileMismatch?: as edit.paste, allArtboards?: false (true: for edit.pasteOnAllArtboards, which leaves the background colors of copied artboards behind)} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours",
|
||||
has_doc,
|
||||
conflicts
|
||||
),
|
||||
@@ -568,9 +568,12 @@ fn import_svg(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn conflicts(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hex = |w: &Swatch| w.paint.color().map(|c| c.to_hex());
|
||||
// The swatches as the paste brings them: converted from another profile when it converts.
|
||||
let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?;
|
||||
const CMD: &str = "clipboard.conflicts";
|
||||
let profile = super::colormgmt::PasteProfile::param(p, CMD)?;
|
||||
// Paste on All Artboards leaves the copied artboards, and so their backgrounds, behind.
|
||||
let all_artboards = super::switch_or(p, "allArtboards", false, CMD)?;
|
||||
let st = s.doc()?;
|
||||
let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, true);
|
||||
let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, !all_artboards);
|
||||
let list: Vec<Value> = converted
|
||||
.as_ref()
|
||||
.unwrap_or(&s.clipboard)
|
||||
|
||||
@@ -14,7 +14,8 @@ use std::sync::Arc;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::cms::Model;
|
||||
use vectorcraft_color::harmony::{self, Guide, GuideOptions, Harmony};
|
||||
use vectorcraft_color::{Color, Paint, keep_model};
|
||||
use vectorcraft_color::wcag::{self, Category};
|
||||
use vectorcraft_color::{BlendMode, Color, Paint, keep_model};
|
||||
use vectorcraft_doc::live::lerp_color;
|
||||
use vectorcraft_doc::pattern::PatternDef;
|
||||
pub(crate) use vectorcraft_doc::recolor::map_paint;
|
||||
@@ -135,6 +136,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
harmony
|
||||
),
|
||||
cmd!(
|
||||
query "color.contrast",
|
||||
"Contrast",
|
||||
[],
|
||||
None,
|
||||
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
|
||||
always,
|
||||
contrast
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -701,8 +711,15 @@ impl Indexing {
|
||||
v.as_f64().filter(|x| (0.0..=100.0).contains(x)).ok_or_else(|| bad(C, "`ditherAmount` must be a number from 0 to 100"))?.round() as u8
|
||||
}
|
||||
};
|
||||
let options =
|
||||
|r: Reduction| PaletteOptions { colors: colors.unwrap_or(256), reduction: r, dither, dither_amount, transparency: true, matte: None };
|
||||
let options = |r: Reduction| PaletteOptions {
|
||||
colors: colors.unwrap_or(256),
|
||||
reduction: r,
|
||||
dither,
|
||||
dither_amount,
|
||||
transparency: true,
|
||||
matte: None,
|
||||
..PaletteOptions::default()
|
||||
};
|
||||
let refuse_colors = |name: &str| match colors {
|
||||
Some(_) => Err(bad(C, format!("`colors` does not apply to the {name} reduction"))),
|
||||
None => Ok(()),
|
||||
@@ -984,3 +1001,626 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let hex = |cs: &[Color]| cs.iter().map(Color::to_hex).collect::<Vec<_>>();
|
||||
Ok(json!({ "rule": rule.id(), "colors": hex(&g.colors), "grid": g.grid.iter().map(|r| hex(r)).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// The side, in points, of the square [`color_below`] renders.
|
||||
const BELOW_SIDE: f64 = 1.0;
|
||||
/// The pixels per point [`color_below`] renders at.
|
||||
const BELOW_SCALE: f64 = 4.0;
|
||||
|
||||
fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "color.contrast";
|
||||
check_numbers(p, &["opacity"], C)?;
|
||||
let opacity = match p.get("opacity").and_then(Value::as_f64) {
|
||||
Some(o) if (0.0..=100.0).contains(&o) => Some(o as f32 / 100.0),
|
||||
Some(_) => {
|
||||
let key = "opacity";
|
||||
return Err(bad(C, format!("`{key}` must be from 0 to 100")));
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below"));
|
||||
let (color, drawn) = match p.get("color") {
|
||||
None | Some(Value::Null) => proxy_color(s, opacity.is_some(), below).map_err(|e| bad(C, e))?,
|
||||
Some(v) => (color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?, Drawn::default()),
|
||||
};
|
||||
let rich_black = s.prefs.black_on_screen == "rich";
|
||||
let cms = vectorcraft_color::cms::active();
|
||||
let shown = |c: &Color| match *c {
|
||||
Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
|
||||
_ => cms.display_rgb(c),
|
||||
};
|
||||
let to_8bit = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
|
||||
// The background in display sRGB, and as the working RGB `#rrggbb` a given `against` reads as.
|
||||
let (against, written) = match p.get("against").filter(|_| !below) {
|
||||
None => {
|
||||
// The sample in working RGB, rounded to 8 bits: the background the answer writes is the
|
||||
// one the ratio uses, and giving it back answers the same ratio.
|
||||
let working = to_8bit(cms.srgb_to_rgb(color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?.0));
|
||||
(cms.rgb_to_srgb(working.map(|v| f32::from(v) / 255.0)), working)
|
||||
}
|
||||
Some(v) => {
|
||||
let key = "against";
|
||||
let shown = shown(&color_value(v).ok_or_else(|| bad(C, format!("`{key}` must be a color or {}", "\"below\"")))?);
|
||||
(shown, to_8bit(cms.srgb_to_rgb(shown)))
|
||||
}
|
||||
};
|
||||
// Innermost first: the row (inside the object), the object, then its groups and layer. A given
|
||||
// opacity takes the place of the object's and of its groups' and layer's.
|
||||
let row = drawn.row.map(|(blend, o)| Step {
|
||||
blend,
|
||||
opacity: if opacity.is_some() { 1.0 } else { o },
|
||||
isolate: false,
|
||||
hide: Some(Part::Rows),
|
||||
within: Part::Rows,
|
||||
});
|
||||
let object = Step { blend: drawn.blend, opacity: opacity.unwrap_or(drawn.opacity), isolate: drawn.isolate, hide: None, within: Part::Object };
|
||||
let groups = drawn.around.iter().map(|l| Step {
|
||||
blend: l.blend,
|
||||
opacity: if opacity.is_some() { 1.0 } else { l.opacity },
|
||||
isolate: l.isolate,
|
||||
hide: Some(l.part.clone()),
|
||||
within: l.part.clone(),
|
||||
});
|
||||
let steps = row.into_iter().chain([object]).chain(groups).collect::<Vec<_>>();
|
||||
// With the background sampled and no opacity given, each level blends with and draws over the
|
||||
// art below it inside the levels around it, as the canvas composites groups; otherwise the
|
||||
// background stands for that art. Inside an object, group or layer that isolates its blending,
|
||||
// the art below is only what that level holds (nothing, for a given background).
|
||||
let sampled = below && opacity.is_none();
|
||||
// A level with a blend mode that does not isolate draws what is inside it over the art below it,
|
||||
// then takes that art back out by the alpha of what it holds drawn alone, and blends the rest:
|
||||
// `alone` is the alpha of what the next level out holds drawn alone. Each level's opacity
|
||||
// applies to what it holds, and the art beside it in the level around it adds to the alpha once.
|
||||
let blends = |a: &Step| a.blend != BlendMode::Normal && !a.isolate;
|
||||
let mut x = (shown(&color), 1.0f32);
|
||||
let mut alone = 1.0f32;
|
||||
for (k, step) in steps.iter().enumerate() {
|
||||
if step.blend == BlendMode::Normal && step.opacity >= 1.0 && x.1 >= 1.0 && alone >= 1.0 {
|
||||
continue;
|
||||
}
|
||||
let above = &steps[k + 1..];
|
||||
let scope = above.iter().find(|a| a.isolate);
|
||||
let full = above.iter().filter(|a| a.blend != BlendMode::Normal || a.opacity < 1.0).map(|a| &a.within).collect::<Vec<_>>();
|
||||
let read = |scope: Option<&Part>| color_below(s, rich_black, step.hide.as_ref(), &full, scope).map_err(|e| bad(C, e));
|
||||
let backdrop = match scope {
|
||||
Some(_) if !sampled => ([0.0; 3], 0.0),
|
||||
None if !sampled => (against, 1.0),
|
||||
// The background itself, as the answer writes it.
|
||||
None if step.hide.is_none() && full.is_empty() => (against, 1.0),
|
||||
_ => read(scope.map(|a| &a.within))?,
|
||||
};
|
||||
// The alpha of the art below the level inside the level around it, while a blending level
|
||||
// lies further out (none for a given background).
|
||||
let inner = match above.first() {
|
||||
Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1,
|
||||
_ => 0.0,
|
||||
};
|
||||
let source = if !blends(step) {
|
||||
x
|
||||
} else if alone <= 0.0 {
|
||||
(x.0, 0.0)
|
||||
} else {
|
||||
(std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * backdrop.0[i] * backdrop.1) / alone).clamp(0.0, 1.0)), alone)
|
||||
};
|
||||
// A level that isolates its blending carries out the alpha of what it holds composited on
|
||||
// its own.
|
||||
let drawn = if step.isolate { x.1 } else { alone } * step.opacity.clamp(0.0, 1.0);
|
||||
x = composite(step.blend, source, step.opacity, backdrop);
|
||||
alone = drawn + inner * (1.0 - drawn);
|
||||
}
|
||||
let front = if x.1 >= 1.0 { x.0 } else { wcag::over(x.0, x.1, against) };
|
||||
let ratio = wcag::contrast_ratio(front, against);
|
||||
let levels = |c: Category| {
|
||||
let (aa, aaa) = c.passes(ratio);
|
||||
match aaa {
|
||||
Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
|
||||
None => json!({ "aa": aa }),
|
||||
}
|
||||
};
|
||||
let [r, g, b] = written;
|
||||
Ok(json!({
|
||||
"ratio": ratio,
|
||||
"against": format!("#{r:02x}{g:02x}{b:02x}"),
|
||||
"normalText": levels(Category::NormalText),
|
||||
"largeText": levels(Category::LargeText),
|
||||
"graphics": levels(Category::Graphics),
|
||||
}))
|
||||
}
|
||||
|
||||
/// An object around the proxy's object: one in the document, or a group of the picked object's
|
||||
/// dynamic symbol instance's art, by its path in the art (the art's root for an empty path). For
|
||||
/// [`color_below`], also the objects the proxy's color comes from, or their rows from the one the
|
||||
/// proxy shows up.
|
||||
#[derive(Clone, PartialEq)]
|
||||
enum Part {
|
||||
Doc(NodeId),
|
||||
Art(Vec<u32>),
|
||||
Object,
|
||||
Rows,
|
||||
}
|
||||
|
||||
/// An object around the proxy's object that draws it: its opacity, blend mode, whether it isolates
|
||||
/// the blending inside it, and which object it is.
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct Level {
|
||||
opacity: f32,
|
||||
blend: BlendMode,
|
||||
isolate: bool,
|
||||
part: Part,
|
||||
/// Whether it has an opacity mask that is not disabled.
|
||||
masked: bool,
|
||||
}
|
||||
|
||||
/// Whether object `n` has an opacity mask that is not disabled.
|
||||
fn masked(n: &Node) -> bool {
|
||||
n.extras().mask.as_ref().is_some_and(|m| !m.disabled)
|
||||
}
|
||||
|
||||
/// How the proxy's color is drawn: the object's opacity, its fill or stroke row's blend mode and
|
||||
/// opacity (none for type's character paint or a colorize color), each times that of a stop or
|
||||
/// point when it holds the paint, the object's blend mode and whether it isolates its blending, and
|
||||
/// the groups and layer around the object, innermost first.
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct Drawn {
|
||||
opacity: f32,
|
||||
row: Option<(BlendMode, f32)>,
|
||||
blend: BlendMode,
|
||||
isolate: bool,
|
||||
around: Vec<Level>,
|
||||
/// The object's shown fill and stroke rows with paint below the row, which the row draws over.
|
||||
lower: Vec<vectorcraft_doc::AppearanceItem>,
|
||||
}
|
||||
|
||||
impl Default for Drawn {
|
||||
fn default() -> Self {
|
||||
Self { opacity: 1.0, row: None, blend: BlendMode::Normal, isolate: false, around: vec![], lower: vec![] }
|
||||
}
|
||||
}
|
||||
|
||||
/// One level [`contrast`] draws the color through: the row, the object, or a [`Level`]. `hide` is
|
||||
/// what [`color_below`] hides to read the art below it (`None`: the selection), and `within` the
|
||||
/// object whose art is read inside it.
|
||||
struct Step {
|
||||
blend: BlendMode,
|
||||
opacity: f32,
|
||||
isolate: bool,
|
||||
hide: Option<Part>,
|
||||
within: Part,
|
||||
}
|
||||
|
||||
/// `x` (a display sRGB color and its alpha) drawn at `opacity` with blend mode `mode` over `backdrop`
|
||||
/// (likewise), as the PDF compositing formulas give it: the mode applies where the backdrop is
|
||||
/// drawn, and over nothing the color stays as it is.
|
||||
fn composite(mode: BlendMode, x: ([f32; 3], f32), opacity: f32, backdrop: ([f32; 3], f32)) -> ([f32; 3], f32) {
|
||||
let (b, ab) = backdrop;
|
||||
let a = x.1 * if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 1.0 };
|
||||
let mixed = vectorcraft_color::blend::blend_rgb(mode, b, x.0);
|
||||
let out = a + ab * (1.0 - a);
|
||||
if out <= 0.0 {
|
||||
return (b, 0.0);
|
||||
}
|
||||
(std::array::from_fn(|i| (a * ((1.0 - ab) * x.0[i] + ab * mixed[i]) + ab * (1.0 - a) * b[i]) / out), out)
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` draw a color alike: the same blend modes and isolation, and unless
|
||||
/// `given_opacity` (which takes the place of their opacities) the same opacities. With `below`, the
|
||||
/// levels that change what they draw must be the same objects too, since the art below each one is
|
||||
/// read with that object hidden, and the object's opacity must be the same apart from its row's,
|
||||
/// since the row draws over the object's rows below it and the object over the art behind it, and a
|
||||
/// row that blends or is translucent must lie over the same shown rows.
|
||||
fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
|
||||
let counts = |l: &&Level| l.blend != BlendMode::Normal || l.isolate || (!given_opacity && l.opacity < 1.0);
|
||||
let level = |x: &Level, y: &Level| {
|
||||
x.blend == y.blend
|
||||
&& x.isolate == y.isolate
|
||||
&& (given_opacity || (x.opacity - y.opacity).abs() < 1e-6)
|
||||
&& (!below || given_opacity || x.part == y.part)
|
||||
};
|
||||
let (la, lb) = (a.around.iter().filter(counts).collect::<Vec<_>>(), b.around.iter().filter(counts).collect::<Vec<_>>());
|
||||
// A row in Normal mode draws as type's character paint does, and an object's isolation only
|
||||
// changes a row's blending.
|
||||
let row = |d: &Drawn| d.row.map(|r| r.0).filter(|m| *m != BlendMode::Normal);
|
||||
let total = |d: &Drawn| d.opacity * d.row.map_or(1.0, |r| r.1);
|
||||
// A row that blends or lets art through draws over the rows below it, read at one point.
|
||||
let over_rows = |d: &Drawn| d.row.is_some_and(|(m, o)| m != BlendMode::Normal || o < 1.0);
|
||||
row(a) == row(b)
|
||||
&& (given_opacity || !below || !(over_rows(a) || over_rows(b)) || a.lower == b.lower)
|
||||
&& a.blend == b.blend
|
||||
&& (row(a).is_none() || a.isolate == b.isolate)
|
||||
&& (given_opacity || (total(a) - total(b)).abs() < 1e-6)
|
||||
&& (given_opacity || (row(a).is_none() && !below) || (a.opacity - b.opacity).abs() < 1e-6)
|
||||
&& la.len() == lb.len()
|
||||
&& la.iter().zip(&lb).all(|(x, y)| level(x, y))
|
||||
}
|
||||
|
||||
/// The active proxy's color (its selected gradient stop or freeform point, else the first, or a
|
||||
/// gradient mesh's first picked point, each at its own opacity) and how
|
||||
/// it is drawn ([`Drawn`]). With `given_opacity`, the opacities of the selected objects are not
|
||||
/// compared, since the given opacity takes their place; with `below` (the background is sampled),
|
||||
/// objects in different translucent or blending groups or layers differ, since the art below each
|
||||
/// such level is read with it hidden.
|
||||
fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Color, Drawn), String> {
|
||||
let stroke = !s.fill_active;
|
||||
let (fill_mixed, stroke_mixed) = s.proxy_mixed();
|
||||
if if stroke { stroke_mixed } else { fill_mixed } {
|
||||
return Err("the selected objects' colors differ: give `color`".into());
|
||||
}
|
||||
let (fill, stroke_paint) = s.proxy_paints();
|
||||
// The Fill proxy shows a gradient mesh's picked points, each drawn at its own opacity.
|
||||
let points = if stroke { vec![] } else { s.fill_mesh_points() };
|
||||
let source = || {
|
||||
s.proxy_source(stroke)
|
||||
.map(|(n, item)| {
|
||||
let d = drawn_settings(s, &n, item, stroke)?;
|
||||
Ok::<_, String>(match picked_opacities(&n, &points).first() {
|
||||
Some(o) => at(&d, *o),
|
||||
None => d,
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
};
|
||||
let drawing;
|
||||
// Selected objects that share a color but draw it differently have no one answer. While the
|
||||
// active tool paints with the proxy's color, the selection does not draw it.
|
||||
if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none() && !s.tool_paints(stroke)) {
|
||||
let item = s.appearance_item();
|
||||
// Every painted object inside a selected group counts, as the proxy's color comes from all,
|
||||
// except hidden ones and those inside a hidden group, which draw nothing. The first shown
|
||||
// one gives the opacity and blend modes the answer uses.
|
||||
let shown = |id: NodeId| st.doc.ancestry(id).unwrap_or_default().iter().all(|a| st.doc.node(*a).is_some_and(|x| x.visible));
|
||||
let mut drawn = vec![];
|
||||
for n in st.selection.subjects().iter().filter_map(|id| st.doc.node(*id)) {
|
||||
for (n, item) in shown_sources(n, item, stroke).into_iter().filter(|(c, _)| shown(c.id)) {
|
||||
let d = drawn_settings(s, n, item, stroke)?;
|
||||
let picked = picked_opacities(n, &points);
|
||||
if picked.is_empty() {
|
||||
drawn.push(d);
|
||||
} else {
|
||||
drawn.extend(picked.into_iter().map(|o| at(&d, o)));
|
||||
}
|
||||
}
|
||||
}
|
||||
drawing = match drawn.first() {
|
||||
Some(first) => first.clone(),
|
||||
None => source()?.unwrap_or_default(),
|
||||
};
|
||||
if !drawn.iter().all(|d| draws_alike(d, &drawing, given_opacity, below)) {
|
||||
// With `opacity` given, the opacities are not compared and the background stands for the
|
||||
// art below.
|
||||
if !given_opacity && drawn.iter().all(|d| draws_alike(d, &drawing, true, below)) {
|
||||
return Err("the selected objects' colors differ: give `opacity` or `color`".into());
|
||||
}
|
||||
return Err("the selected objects' colors differ: give `color`".into());
|
||||
}
|
||||
} else {
|
||||
drawing = source()?.unwrap_or_default();
|
||||
}
|
||||
let no_color = || "the active fill or stroke has no color: give `color`".to_string();
|
||||
match if stroke { stroke_paint } else { fill } {
|
||||
Paint::Solid { color, .. } => Ok((stained(s, color), drawing)),
|
||||
Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform => {
|
||||
let f = g.freeform_on(vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0));
|
||||
let i = s.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0);
|
||||
f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity))).ok_or_else(no_color)
|
||||
}
|
||||
Paint::Gradient(g) => {
|
||||
let i = s.selected_stop().unwrap_or(0).min(g.gradient.stops.len().saturating_sub(1));
|
||||
g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity))).ok_or_else(no_color)
|
||||
}
|
||||
Paint::None | Paint::Pattern { .. } => Err(no_color()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `drawing` with a stop's or point's `opacity`, which applies where its paint is drawn: in its
|
||||
/// row, else in the object.
|
||||
fn at(drawing: &Drawn, opacity: f32) -> Drawn {
|
||||
match drawing.row {
|
||||
Some((m, o)) => Drawn { row: Some((m, o * opacity)), ..drawing.clone() },
|
||||
None => Drawn { opacity: drawing.opacity * opacity, ..drawing.clone() },
|
||||
}
|
||||
}
|
||||
|
||||
/// The opacities of the picked points of gradient mesh `n` ([`Session::fill_mesh_points`]), whose
|
||||
/// colors the Fill proxy shows for it: empty for another object or with no points picked.
|
||||
fn picked_opacities(n: &Node, points: &[(NodeId, Vec<usize>)]) -> Vec<f32> {
|
||||
match (&n.kind, points.iter().find(|(id, _)| *id == n.id)) {
|
||||
(NodeKind::Mesh(m), Some((_, v))) => v.iter().filter_map(|i| m.points.get(*i)).map(|q| q.opacity).collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects whose fill or stroke the proxy shows for selected object `n`, with the appearance
|
||||
/// item each shows: `n` itself when it holds such an item, else every painted object inside it
|
||||
/// ([`Session::proxy_source`] shows the first).
|
||||
fn shown_sources(n: &Node, item: Option<usize>, stroke: bool) -> Vec<(&Node, Option<usize>)> {
|
||||
if n.appearance.item_of_kind(item, !stroke).is_some() {
|
||||
return vec![(n, item)];
|
||||
}
|
||||
let mut nodes = vec![];
|
||||
super::paint::painted(n, true, stroke, &mut nodes);
|
||||
nodes.into_iter().map(|c| (c, None)).collect()
|
||||
}
|
||||
|
||||
/// How object `n` draws its fill or stroke (`item`, else the proxy's row), as [`Drawn`] gives it. An
|
||||
/// error for a hidden row.
|
||||
fn drawn_settings(s: &Session, n: &Node, item: Option<usize>, stroke: bool) -> std::result::Result<Drawn, String> {
|
||||
let item = n.appearance.item_of_kind(item, !stroke);
|
||||
// Without a targeted row, type shows its characters' paint and a colorized image its
|
||||
// colorize color, which no fill or stroke row's opacity applies to.
|
||||
let own_paint = item.is_none() && (matches!(n.kind, NodeKind::Text(_)) || (!stroke && n.extras().colorize.is_some()));
|
||||
let own = match (own_paint, stroke) {
|
||||
(true, _) => None,
|
||||
(false, true) => n.appearance.stroke_at(item).map(|l| (l.opacity, l.blend, l.visible)),
|
||||
(false, false) => n.appearance.fill_at(item).map(|l| (l.opacity, l.blend, l.visible)),
|
||||
};
|
||||
if own.is_some_and(|o| !o.2) {
|
||||
return Err("the active fill or stroke is hidden: give `color`".to_string());
|
||||
}
|
||||
// The groups and layer the object is in draw it too (`enclosing` lists the outermost first).
|
||||
let mut around = enclosing(s, n.id);
|
||||
around.reverse();
|
||||
// An opacity mask sets how much of the color shows at each point, which no one opacity gives.
|
||||
if masked(n) || around.iter().any(|l| l.masked) {
|
||||
return Err("the active fill or stroke is drawn through an opacity mask: give `color`".to_string());
|
||||
}
|
||||
// The rows below the row that draw, as `hide_rows` leaves them shown.
|
||||
let rows = &n.appearance.items;
|
||||
let at_row = item.or_else(|| rows.iter().rposition(|r| r.is_fill() != stroke));
|
||||
let lower = match (own, at_row) {
|
||||
(Some(_), Some(i)) => rows.iter().take(i).filter(|r| r.visible() && !r.paint().is_none()).cloned().collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
Ok(Drawn { opacity: n.opacity, row: own.map(|o| (o.1, o.0)), blend: n.blend, isolate: n.isolate, around, lower })
|
||||
}
|
||||
|
||||
/// `color` as the canvas draws the picked object of a dynamic symbol instance that a fill stains
|
||||
/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill);
|
||||
/// `color` itself otherwise.
|
||||
fn stained(s: &Session, color: Color) -> Color {
|
||||
let stain = s.active().and_then(|st| {
|
||||
let sp = st.selection.symbol_part.as_ref()?;
|
||||
st.selected_symbol_part()?;
|
||||
vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?)
|
||||
});
|
||||
match stain {
|
||||
Some((c, amount)) => color.lerp(&c, amount.clamp(0.0, 1.0)),
|
||||
None => color,
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects that draw the proxy's object `id` ([`Level`]), outermost first: its groups and
|
||||
/// layer, and for a picked object of a dynamic symbol instance, the instance, its groups and layer,
|
||||
/// and the groups of the symbol's art around the object.
|
||||
fn enclosing(s: &Session, id: NodeId) -> Vec<Level> {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
let doc = &st.doc;
|
||||
let level = |n: &Node, part: Part| Level { opacity: n.opacity, blend: n.blend, isolate: n.isolate, part, masked: masked(n) };
|
||||
// `ancestry` lists the object itself last.
|
||||
let in_doc = |id: NodeId, own: bool| {
|
||||
let ids = doc.ancestry(id).unwrap_or_default();
|
||||
let nodes = ids.into_iter().filter(|a| own || *a != id).filter_map(|a| doc.node(a));
|
||||
nodes.map(|a| level(a, Part::Doc(a.id))).collect::<Vec<_>>()
|
||||
};
|
||||
let Some(sp) = st.selection.symbol_part.as_ref() else { return in_doc(id, false) };
|
||||
let art = doc.node(sp.instance).and_then(|inst| {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &inst.kind else { return None };
|
||||
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
Some(vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst))
|
||||
});
|
||||
// Without the picked object, the proxy shows the selected object itself (`proxy_source`).
|
||||
let Some(art) = art.filter(|a| vectorcraft_doc::symbol_overrides::part(a, &sp.path).is_some()) else { return in_doc(id, false) };
|
||||
let mut out = in_doc(sp.instance, true);
|
||||
if let Some((_, groups)) = sp.path.split_last() {
|
||||
// The art's root and each group on the way to the object, not the object itself.
|
||||
let mut n = &art;
|
||||
out.push(level(n, Part::Art(vec![])));
|
||||
for (k, &i) in groups.iter().enumerate() {
|
||||
let Some(c) = n.children().and_then(|c| c.get(usize::try_from(i).ok()?)) else { break };
|
||||
n = c;
|
||||
out.push(level(n, Part::Art(groups[..=k].to_vec())));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The display sRGB VectorCraft draws at the center of the selection's bounds with the selected
|
||||
/// objects hidden: the average of a small square rendered as the canvas renders it (artboards, the
|
||||
/// on-screen Appearance of Black, no proof, no template layers or guides), over white where nothing
|
||||
/// is drawn, with its alpha. With `hide`, that object (a group or layer around the selection) is
|
||||
/// hidden in place of the selection, or for [`Part::Rows`], the proxy's row and the rows above it;
|
||||
/// the objects of `full` draw at full opacity in Normal mode; and with `scope` (a group or layer
|
||||
/// around the selection, or the proxy's objects), only the art inside it is drawn, over nothing,
|
||||
/// without artboards.
|
||||
fn color_below(
|
||||
s: &Session,
|
||||
rich_black: bool,
|
||||
hide: Option<&Part>,
|
||||
full: &[&Part],
|
||||
scope: Option<&Part>,
|
||||
) -> std::result::Result<([f32; 3], f32), String> {
|
||||
super::has_selection(s)?;
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
let ids = st.selection.objects.clone();
|
||||
// A picked object of a dynamic symbol instance hides only itself: the rest of the instance
|
||||
// stays in the sample, measured at the object's center.
|
||||
let picked = st.selection.symbol_part.as_ref().and_then(|sp| {
|
||||
let inst = st.doc.node(sp.instance)?;
|
||||
let center = kurbo::Shape::bounding_box(&vectorcraft_doc::hit::symbol_part_outline(&st.doc, inst, &sp.path)?).center();
|
||||
vectorcraft_doc::symbol_overrides::part(inst_art(&st.doc, sp.instance)?, &sp.path)?;
|
||||
Some((sp, center))
|
||||
});
|
||||
let center = match picked {
|
||||
Some((_, center)) => center,
|
||||
None => st.doc.bounds_of(&ids, false).ok_or("nothing selected")?.center(),
|
||||
};
|
||||
// The objects the proxy's color comes from, with the row each shows (`proxy_color`); for a picked
|
||||
// object, the object itself at `sp.path`, with its topmost row of the kind.
|
||||
let (stroke, item) = (!s.fill_active, s.appearance_item());
|
||||
let shown = |id: NodeId| st.doc.ancestry(id).unwrap_or_default().iter().all(|a| st.doc.node(*a).is_some_and(|x| x.visible));
|
||||
let painted = match picked {
|
||||
Some(_) => vec![],
|
||||
None => {
|
||||
let nodes = st.selection.subjects().iter().filter_map(|id| st.doc.node(*id));
|
||||
nodes.flat_map(|n| shown_sources(n, item, stroke)).filter(|(c, _)| shown(c.id)).map(|(c, item)| (c.id, item)).collect::<Vec<_>>()
|
||||
}
|
||||
};
|
||||
let own = |p: Option<&Part>| matches!(p, Some(Part::Art(_) | Part::Object | Part::Rows));
|
||||
let art_edits = picked.is_some() && (hide.is_none() || own(hide) || full.iter().any(|p| own(Some(p))) || own(scope));
|
||||
let mut copy = (art_edits || !full.is_empty() || hide == Some(&Part::Rows)).then(|| Document::clone(&st.doc));
|
||||
let mut hidden = HashSet::new();
|
||||
// The art of the picked object's instance in `copy`, as a copy of its symbol that only this
|
||||
// instance draws, so other instances of the symbol keep it.
|
||||
let symbol = match (picked, copy.as_mut()) {
|
||||
(Some((sp, _)), Some(doc)) if art_edits => Some(own_symbol(doc, sp.instance).ok_or("the picked object is not found")?),
|
||||
_ => None,
|
||||
};
|
||||
let lost = || "the picked object is not found".to_string();
|
||||
match (hide, picked) {
|
||||
(None, Some((sp, _))) => art_mut(copy.as_mut(), symbol, &sp.path).ok_or_else(lost)?.visible = false,
|
||||
(None, None) => hidden.extend(ids),
|
||||
(Some(Part::Doc(id)), _) => hidden.extend([*id]),
|
||||
// The art's root is all the instance draws.
|
||||
(Some(Part::Art(path)), Some((sp, _))) if path.is_empty() => hidden.extend([sp.instance]),
|
||||
(Some(Part::Art(path)), _) => art_mut(copy.as_mut(), symbol, path).ok_or_else(lost)?.visible = false,
|
||||
(Some(Part::Rows), Some((sp, _))) => hide_rows(art_mut(copy.as_mut(), symbol, &sp.path).ok_or_else(lost)?, None, stroke),
|
||||
(Some(Part::Rows), None) => {
|
||||
for (id, item) in &painted {
|
||||
if let Some(n) = copy.as_mut().and_then(|d| d.node_mut(*id)) {
|
||||
hide_rows(n, *item, stroke);
|
||||
}
|
||||
}
|
||||
}
|
||||
(Some(Part::Object), _) => return Err(lost()),
|
||||
}
|
||||
// The levels around the one read draw what is inside them as it is. An instance's override of
|
||||
// an object of its art's opacity or blend mode is dropped with it.
|
||||
let plain = |n: &mut Node| {
|
||||
n.opacity = 1.0;
|
||||
n.blend = BlendMode::Normal;
|
||||
};
|
||||
let plain_art = |copy: &mut Option<Document>, path: &[u32]| -> std::result::Result<(), String> {
|
||||
plain(art_mut(copy.as_mut(), symbol, path).ok_or_else(lost)?);
|
||||
let sp = picked.ok_or_else(lost)?.0;
|
||||
if let Some(e) = copy.as_mut().and_then(|d| d.node_mut(sp.instance)).and_then(Node::extras_if_any) {
|
||||
for o in e.symbol_overrides.iter_mut().filter(|o| o.path == path) {
|
||||
(o.opacity, o.blend) = (None, None);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
for p in full {
|
||||
let ids = match (p, picked) {
|
||||
(Part::Doc(id), _) => vec![*id],
|
||||
(Part::Art(path), _) => {
|
||||
plain_art(&mut copy, path)?;
|
||||
continue;
|
||||
}
|
||||
(Part::Object, Some((sp, _))) => {
|
||||
plain_art(&mut copy, &sp.path)?;
|
||||
continue;
|
||||
}
|
||||
(Part::Object, None) => painted.iter().map(|p| p.0).collect(),
|
||||
(Part::Rows, _) => continue,
|
||||
};
|
||||
for id in ids {
|
||||
if let Some(n) = copy.as_mut().and_then(|d| d.node_mut(id)) {
|
||||
plain(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Inside a level, only the art that level holds is drawn, over nothing.
|
||||
if let Some(scope) = scope {
|
||||
let (keep, path) = match (scope, picked) {
|
||||
(Part::Doc(id), _) => (vec![*id], &[][..]),
|
||||
(Part::Art(path), Some((sp, _))) => (vec![sp.instance], &path[..]),
|
||||
(Part::Object, Some((sp, _))) => (vec![sp.instance], &sp.path[..]),
|
||||
(Part::Object, None) => (painted.iter().map(|p| p.0).collect(), &[][..]),
|
||||
_ => return Err(lost()),
|
||||
};
|
||||
// Everything that is neither on the way to a kept object nor inside one is hidden.
|
||||
let on_way = keep.iter().flat_map(|k| st.doc.ancestry(*k).unwrap_or_default()).collect::<HashSet<_>>();
|
||||
let parents = std::iter::once(None).chain(on_way.iter().filter(|a| !keep.contains(a)).map(|a| Some(*a)));
|
||||
for parent in parents {
|
||||
hidden.extend(st.doc.children(parent).into_iter().flatten().map(|n| n.id).filter(|n| !on_way.contains(n)));
|
||||
}
|
||||
for (k, &keep) in path.iter().enumerate() {
|
||||
let group = art_mut(copy.as_mut(), symbol, &path[..k]).and_then(Node::children_mut).ok_or_else(lost)?;
|
||||
for (i, c) in group.iter_mut().enumerate() {
|
||||
if u32::try_from(i).ok() != Some(keep) {
|
||||
Arc::make_mut(c).visible = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let h = BELOW_SIDE / 2.0;
|
||||
let region = vectorcraft_geom::Rect::new(center.x - h, center.y - h, center.x + h, center.y + h);
|
||||
// Template layers and guides are aids to drawing, not artwork: left out as exports leave them.
|
||||
let opts = vectorcraft_render::RenderOptions {
|
||||
background: scope.is_none().then_some([255, 255, 255, 255]),
|
||||
artboards: scope.is_none(),
|
||||
hidden,
|
||||
rich_black,
|
||||
skip_templates: true,
|
||||
..Default::default()
|
||||
};
|
||||
let img = vectorcraft_render::Renderer::new().render_region_with(copy.as_ref().unwrap_or(&st.doc), region, BELOW_SCALE, &opts);
|
||||
let px = img.pixels.as_chunks::<4>().0;
|
||||
if px.is_empty() {
|
||||
return Ok(if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) });
|
||||
}
|
||||
// The pixels are premultiplied: the average color is their sum over their alpha's.
|
||||
let mut sum = [0.0f64; 4];
|
||||
for p in px {
|
||||
for (s, v) in sum.iter_mut().zip(p) {
|
||||
*s += f64::from(*v);
|
||||
}
|
||||
}
|
||||
let alpha = sum[3] / (px.len() as f64 * 255.0);
|
||||
if alpha <= 0.0 {
|
||||
return Ok(([0.0; 3], 0.0));
|
||||
}
|
||||
let rgb = [0, 1, 2].map(|i| (sum[i] / (px.len() as f64 * 255.0) / alpha).clamp(0.0, 1.0) as f32);
|
||||
Ok((rgb, alpha as f32))
|
||||
}
|
||||
|
||||
/// Hides fill or stroke row `item` of `n` (else its topmost row of the kind) and every row above it.
|
||||
fn hide_rows(n: &mut Node, item: Option<usize>, stroke: bool) {
|
||||
let a = &mut n.appearance;
|
||||
let Some(i) = a.item_of_kind(item, !stroke).or_else(|| a.items.iter().rposition(|r| r.is_fill() != stroke)) else { return };
|
||||
for r in a.items.iter_mut().skip(i) {
|
||||
match r {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => f.visible = false,
|
||||
vectorcraft_doc::AppearanceItem::Stroke(s) => s.visible = false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The art the symbol instance `inst` of `doc` draws, as its symbol holds it.
|
||||
fn inst_art(doc: &Document, inst: NodeId) -> Option<&Arc<Node>> {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &doc.node(inst)?.kind else { return None };
|
||||
doc.symbols.iter().find(|s| s.name == *symbol).map(|s| &s.art)
|
||||
}
|
||||
|
||||
/// The object at `path` in the art of `doc`'s symbol at index `symbol` (the art's root for an empty
|
||||
/// path).
|
||||
fn art_mut<'a>(doc: Option<&'a mut Document>, symbol: Option<usize>, path: &[u32]) -> Option<&'a mut Node> {
|
||||
let mut n = Arc::make_mut(&mut doc?.symbols.get_mut(symbol?)?.art);
|
||||
for &i in path {
|
||||
n = Arc::make_mut(n.children_mut()?.get_mut(usize::try_from(i).ok()?)?);
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// Makes the symbol instance `inst` of `doc` draw a copy of its symbol, so that a change to the copy
|
||||
/// leaves other instances as they are. Returns the copy's index in the document's symbols.
|
||||
fn own_symbol(doc: &mut Document, inst: NodeId) -> Option<usize> {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &doc.node(inst)?.kind else { return None };
|
||||
let mut sym = doc.symbols.iter().find(|s| s.name == *symbol)?.clone();
|
||||
sym.name = unique_name(&sym.name, |name| doc.symbols.iter().any(|s| s.name == name));
|
||||
let name = sym.name.clone();
|
||||
doc.symbols.push(sym);
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &mut doc.node_mut(inst)?.kind {
|
||||
*symbol = name;
|
||||
}
|
||||
Some(doc.symbols.len() - 1)
|
||||
}
|
||||
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Color Settings…",
|
||||
["Edit"],
|
||||
Some("Cmd+Shift+K"),
|
||||
"{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
|
||||
"{rgb?: profile, cmyk?: profile (built in: \"VectorCraft Generic CMYK (SWOP-like)\" (default), \"VectorCraft Coated CMYK (FOGRA51)\" and \"VectorCraft Uncoated CMYK (FOGRA52)\" (computed from Fogra's characterization data), \"Device CMYK (uncalibrated)\"), intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults",
|
||||
always,
|
||||
color_settings
|
||||
),
|
||||
@@ -704,7 +704,7 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co
|
||||
/// from. → a note for each profile, and whether `d` changed.
|
||||
pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec<String>, bool) {
|
||||
// Without a choice nothing can fail.
|
||||
apply_open_policies_choosing(d, None).unwrap_or_default()
|
||||
apply_open_policies_choosing(d, None, &cms::working_settings()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What opening a document can ask about its profile (Edit › Color Settings' Ask When Opening
|
||||
@@ -879,10 +879,14 @@ impl ProfileQuestion {
|
||||
/// mismatch choice takes the place of the policy of the document's color mode, and a missing
|
||||
/// choice tags the document after the policies ran. A choice for the other kind of question, or
|
||||
/// for a document with none, is not used. → as [`apply_open_policies`]; an error when the profile
|
||||
/// to assign is not a profile of that model.
|
||||
pub(crate) fn apply_open_policies_choosing(d: &mut vectorcraft_doc::Document, choice: Option<&ProfileChoice>) -> Result<(Vec<String>, bool)> {
|
||||
let working = cms::working_settings();
|
||||
let question = ProfileQuestion::of(d, &working);
|
||||
/// to assign is not a profile of that model. `working` is the settings snapshot the question is
|
||||
/// built from and the policies are read from.
|
||||
pub(crate) fn apply_open_policies_choosing(
|
||||
d: &mut vectorcraft_doc::Document,
|
||||
choice: Option<&ProfileChoice>,
|
||||
working: &ColorSettings,
|
||||
) -> Result<(Vec<String>, bool)> {
|
||||
let question = ProfileQuestion::of(d, working);
|
||||
let choice = choice.filter(|c| question.as_ref().is_some_and(|q| q.issue == c.issue()));
|
||||
// A mismatch answer stands in for the policy of the document's color mode.
|
||||
let chosen = |model: ColorMode, policy: Policy| -> (Policy, bool) {
|
||||
@@ -1596,3 +1600,22 @@ fn set_spot(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(json!({"name": name, "spot": spot}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The policies come from the settings snapshot the question was built from, not from the
|
||||
/// working settings as they are when the policies run.
|
||||
#[test]
|
||||
fn open_policies_use_the_snapshot_they_are_given() {
|
||||
let tagged = |d: &mut vectorcraft_doc::Document| d.color_profiles.rgb = Some(cms::canonical_name(cms::WIDE_GAMUT_RGB).to_string());
|
||||
let snapshot = ColorSettings { rgb_policy: Policy::Off, ..ColorSettings::default() };
|
||||
let mut d = vectorcraft_doc::Document::new(100.0, 100.0);
|
||||
tagged(&mut d);
|
||||
let (notes, changed) = apply_open_policies_choosing(&mut d, None, &snapshot).unwrap();
|
||||
assert!(changed, "the Off policy of the snapshot takes the profile off");
|
||||
assert_eq!(d.color_profiles.rgb, None);
|
||||
assert!(notes.iter().any(|n| n.contains("policy is")), "{notes:?}");
|
||||
}
|
||||
}
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Circle Through Points",
|
||||
[],
|
||||
None,
|
||||
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
|
||||
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), center?: [x, y] (the circle's center; `points` then holds the one point its edge passes through, [[x, y]]), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, a point on `center`, three on one line, a circle reaching past the canvas, or one too small for its edges to differ at its coordinates are an error, and nothing is drawn",
|
||||
has_doc,
|
||||
circle_through_points
|
||||
),
|
||||
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Curvature Circle",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?=0, segment, t: 0..1, convex?=false} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn",
|
||||
"{id, subpath?=0, segment, t: 0..1, convex?=false, constantRadius?=true, anchors?: \"standard\"|\"touch\" (default standard: a live ellipse with four anchors at 0°, 90°, 180° and 270°; touch: a path with an anchor where the circle touches the path and one every 90° from there)} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; with constantRadius, a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle, and with constantRadius false the cubic's own curvature at `t`; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn",
|
||||
has_doc,
|
||||
curvature_circle
|
||||
),
|
||||
@@ -449,9 +449,33 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Ellipse tool drag is.
|
||||
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.circleThroughPoints";
|
||||
let points = match p.get("points").filter(|v| !v.is_null()) {
|
||||
Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?,
|
||||
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?,
|
||||
const SAME: &str = "no circle passes through these points: two are the same or all three lie on one line";
|
||||
let (center, radius, points) = match p.get("center") {
|
||||
// From a center: the circle at `center` whose edge passes through the one point. A null
|
||||
// `center` is refused, as a null `points` with a center is.
|
||||
Some(c) => {
|
||||
let one = p.get("points").and_then(Value::as_array).and_then(|v| match v.as_slice() {
|
||||
[q] => pair(q),
|
||||
_ => None,
|
||||
});
|
||||
let (c, q) = pair(c).zip(one).ok_or_else(|| bad(C, "`center` must be an [x, y] pair of numbers, with one [x, y] pair in `points`"))?;
|
||||
let r = c.distance(q);
|
||||
if r == 0.0 {
|
||||
return Err(bad(C, "the point in `points` is on `center`"));
|
||||
}
|
||||
if !r.is_finite() {
|
||||
return Err(bad(C, "result would exceed the canvas (coordinates out of range)"));
|
||||
}
|
||||
(c, r, vec![q])
|
||||
}
|
||||
None => {
|
||||
let points = match p.get("points").filter(|v| !v.is_null()) {
|
||||
Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?,
|
||||
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?,
|
||||
};
|
||||
let (c, r) = shapes::circle_through_points(&points).ok_or_else(|| bad(C, SAME))?;
|
||||
(c, r, points)
|
||||
}
|
||||
};
|
||||
let key = "anchors";
|
||||
let at_points = match p.get(key).map(Value::as_str) {
|
||||
@@ -459,13 +483,15 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Some("points")) => true,
|
||||
Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, points"))),
|
||||
};
|
||||
let (center, radius) = shapes::circle_through_points(&points)
|
||||
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
// A radius below the step between doubles at the center leaves opposite edges on one number.
|
||||
if !(r.width() > 0.0 && r.height() > 0.0) {
|
||||
return Err(bad(C, "the circle is too small to draw at these coordinates"));
|
||||
}
|
||||
// Not pixel-aligned: the circle stays through the points.
|
||||
let mut out = if at_points {
|
||||
add_art_unaligned(s, "Ellipse", path_kind(shapes::circle_with_anchors_at(center, radius, &points), None))?
|
||||
} else {
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?
|
||||
};
|
||||
@@ -475,13 +501,17 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The point an `[x, y]` pair of finite numbers gives.
|
||||
fn pair(v: &Value) -> Option<Point> {
|
||||
match v.as_array().map(Vec::as_slice) {
|
||||
Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The two or three points `[[x, y], [x, y]]` or `[[x, y], [x, y], [x, y]]` holds, each pair two
|
||||
/// finite numbers.
|
||||
fn two_or_three_points(v: &Value) -> Option<Vec<Point>> {
|
||||
let pair = |v: &Value| match v.as_array().map(Vec::as_slice) {
|
||||
Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)),
|
||||
_ => None,
|
||||
};
|
||||
match v.as_array() {
|
||||
Some(pairs) if matches!(pairs.len(), 2 | 3) => pairs.iter().map(pair).collect(),
|
||||
_ => None,
|
||||
@@ -518,7 +548,8 @@ fn selected_anchor_points(s: &Session) -> Result<Option<Vec<Point>>> {
|
||||
}
|
||||
|
||||
/// A live ellipse that touches a path at a point with the path's curvature there
|
||||
/// ([`curvature::curvature_circle_on`]). One undo step, named as an Ellipse tool drag is.
|
||||
/// ([`curvature::curvature_circle_on_with`]); with `anchors: "touch"`, a plain path with an anchor
|
||||
/// at the point it touches and one every 90° from there ([`shapes::circle_with_anchors_at`]). One undo step, named as an Ellipse tool drag is.
|
||||
fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "shape.curvatureCircle";
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
@@ -529,6 +560,13 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "`t` must be from 0 to 1"));
|
||||
}
|
||||
let convex = switch_or(p, "convex", false, C)?;
|
||||
let arcs = switch_or(p, "constantRadius", true, C)?;
|
||||
let key = "anchors";
|
||||
let at_touch = match p.get(key).map(Value::as_str) {
|
||||
None | Some(Some("standard")) => false,
|
||||
Some(Some("touch")) => true,
|
||||
Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, touch"))),
|
||||
};
|
||||
let found = {
|
||||
let st = s.doc()?;
|
||||
let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
@@ -540,7 +578,7 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if seg >= sp.segment_count() {
|
||||
return Err(bad(C, "no such segment"));
|
||||
}
|
||||
curvature::curvature_circle_on(sp, seg, t, convex)
|
||||
curvature::curvature_circle_on_with(sp, seg, t, convex, arcs)
|
||||
};
|
||||
let circle = found.map_err(|e| match e {
|
||||
NoCircle::Straight => bad(C, "the path is straight there, so no circle matches its curvature"),
|
||||
@@ -549,12 +587,19 @@ fn curvature_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
let (center, radius) = (circle.center, circle.radius);
|
||||
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
|
||||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.abs() <= MAX_COORD) {
|
||||
let (path, live) = if at_touch {
|
||||
(shapes::circle_with_anchors_at(center, radius, &[circle.at]), None)
|
||||
} else {
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
(live.to_path(), Some(live))
|
||||
};
|
||||
// The bounds of the path drawn: started where it touches, its cubics reach a little past the
|
||||
// circle.
|
||||
if path.bounds().is_none_or(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= MAX_COORD)) {
|
||||
return Err(bad(C, "the circle that matches the path there would reach past the canvas"));
|
||||
}
|
||||
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
|
||||
// Not pixel-aligned: the circle stays on the path.
|
||||
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
|
||||
let mut out = add_art_unaligned(s, "Ellipse", path_kind(path, live))?;
|
||||
out["cx"] = json!(center.x);
|
||||
out["cy"] = json!(center.y);
|
||||
out["radius"] = json!(radius);
|
||||
|
||||
@@ -14,8 +14,8 @@ use super::panelcmds::artboard_at;
|
||||
use super::pathops::Beside;
|
||||
use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Point, Result, Session, bad, checked_ids_param, cmd, f64_req, has_doc, has_selection, id_param, number_or, ok,
|
||||
str_param, switch_or, text_param,
|
||||
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, f64_req, has_doc, has_selection, id_param, number_or, ok, str_param,
|
||||
switch_or, text_param,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -730,13 +730,10 @@ fn release_guides(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
// Find each ruler guide's line and its parent: the guide's layer, else where new art goes.
|
||||
let st = s.doc()?;
|
||||
let artboards = st.doc.artboards.iter().map(|a| a.rect).reduce(|a, b| a.union(b));
|
||||
let mut lines = Vec::with_capacity(rulers.len());
|
||||
for &i in &rulers {
|
||||
let Some(g) = st.doc.ruler_guide(i) else { continue };
|
||||
let span = st.doc.guide_span(&g).or_else(|| artboards.map(|r| if g.vertical { (r.y0, r.y1) } else { (r.x0, r.x1) }));
|
||||
let Some((a, b)) = span else { continue };
|
||||
let (a, b) = if g.vertical { (Point::new(g.pos, a), Point::new(g.pos, b)) } else { (Point::new(a, g.pos), Point::new(b, g.pos)) };
|
||||
let Some((a, b)) = st.doc.guide_line(&g) else { continue };
|
||||
let parent = match g.layer.filter(|l| st.doc.node(*l).is_some_and(Node::is_layer)) {
|
||||
Some(l) => Some(l),
|
||||
None => st.target_parent()?,
|
||||
|
||||
@@ -12,7 +12,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), leaveSelection?: bool (false; true with keepSelected false: a new path leaves the selection as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one that leaves the bigger shape; on an open one the way the stroke runs along it at each end decides: it replaces the part it runs along where it starts and joins the part it runs into where it lands, so it replaces the part between, keeps it and closes the path along the stroke, or, when its ends disagree, ends where it is lifted; an end that leaves or meets the path squarely follows the other end, and when both do it closes only if it goes round both pieces beyond), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), preview?: bool (false; true: the stroke is drawn as a new path on top, as with Draw Normal, and the selection stays as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one that leaves the bigger shape; on an open one the way the stroke runs along it at each end decides: it replaces the part it runs along where it starts and joins the part it runs into where it lands, so it replaces the part between, keeps it and closes the path along the stroke, or, when its ends disagree, ends where it is lifted; an end that leaves or meets the path squarely follows the other end, and when both do it closes only if it goes round both pieces beyond), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
|
||||
has_doc,
|
||||
freehand
|
||||
),
|
||||
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Smooth",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12; from 0.001 to 1000), fidelity?: pt (2.5; from 0.000078125 to about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom, kept within the range)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side, and leaving a subpath as it is when the result would not be smoother (docs/mcp.md) → {ids, before, after}. A radius or fidelity outside its range is refused with an error, and nothing changes",
|
||||
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12; from 0.001 to 1000), fidelity?: pt (2.5; from 0.000078125 to about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom, kept within the range), smoothness?: % (50; 0 to 100: how far along the path each point is averaged before the refit, in proportion: none at 0, twice as far as at 50 at 100)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side, and leaving a subpath as it is when the result would not be smoother (docs/mcp.md) → {ids, before, after}. A radius, fidelity or smoothness outside its range is refused with an error, and nothing changes",
|
||||
has_selection,
|
||||
smooth_region
|
||||
),
|
||||
@@ -147,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Blob Brush",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}. An angle, roundness or fidelity outside its range is rejected with an error, and nothing changes",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1, finger wheel 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" | \"stylusWheel\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest; set to Stylus Wheel: size − sizeVariation wide at one end of an airbrush pen's finger wheel travel, size at the middle and size + sizeVariation at the other end; at least 0.1 pt; a stroke without that reading, and a point without a wheel on Stylus Wheel, keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}. An unknown sizeMode, or an angle, roundness or fidelity outside its range, is rejected with an error, and nothing changes",
|
||||
has_doc,
|
||||
blob
|
||||
),
|
||||
|
||||
@@ -236,22 +236,27 @@ impl PenRecord {
|
||||
}
|
||||
}
|
||||
|
||||
/// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`, with
|
||||
/// `sizeVariation` in points, 0..1000): the stroke's pen pressure along it and the variation, `None`
|
||||
/// for Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the
|
||||
/// size. A `sizeVariation` outside its range is an error with Fixed too.
|
||||
pub(super) fn size_pressure(p: &Value, samples: &[Sample], cmd: &str) -> Result<Option<(PressureProfile, f64)>> {
|
||||
/// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`) or, for the
|
||||
/// Blob Brush, Stylus Wheel (`sizeMode: "stylusWheel"`), with `sizeVariation` in points, 0..1000:
|
||||
/// the stroke's pen pressure or airbrush finger wheel along it (0..1, the size less the variation
|
||||
/// at 0 and plus it at 1) and the variation. `None` for Fixed (the default), no variation or a
|
||||
/// stroke without that reading (a mouse, a pen without a wheel), which keeps the size. A
|
||||
/// `sizeVariation` outside its range is an error with Fixed too.
|
||||
pub(super) fn size_profile(p: &Value, samples: &[Sample], cmd: &str) -> Result<Option<(PressureProfile, f64)>> {
|
||||
const MODES: &str = "\"fixed\", \"pressure\" or \"stylusWheel\"";
|
||||
let variation = ranged(p, "sizeVariation", 0.0, SIZE_VARIATIONS, cmd)?;
|
||||
match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) {
|
||||
None | Some(Ok("fixed")) => Ok(None),
|
||||
Some(Ok("pressure")) => Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation))),
|
||||
Some(Ok(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not `{other}`"))),
|
||||
Some(Err(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not {other}"))),
|
||||
}
|
||||
let read = match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) {
|
||||
None | Some(Ok("fixed")) => return Ok(None),
|
||||
Some(Ok("pressure")) => stroke_pressure(samples),
|
||||
Some(Ok("stylusWheel")) => stroke_wheel(samples),
|
||||
Some(Ok(other)) => return Err(bad(cmd, format!("sizeMode is {MODES}, not `{other}`"))),
|
||||
Some(Err(other)) => return Err(bad(cmd, format!("sizeMode is {MODES}, not {other}"))),
|
||||
};
|
||||
Ok(read.filter(|_| variation > 0.0).map(|prof| (prof, variation)))
|
||||
}
|
||||
|
||||
/// The area a stroke along `spine` covers with Size set to Pressure: as wide at each point as
|
||||
/// [`vectorcraft_tools::draw2::pressure_size`] gives for the pressure `prof` records there, with
|
||||
/// The area a stroke along `spine` covers with Size set to Pressure or Stylus Wheel: as wide at
|
||||
/// each point as [`vectorcraft_tools::draw2::pressure_size`] gives for the reading `prof` records there, with
|
||||
/// round ends and joins, its overlaps united into one outline.
|
||||
pub(super) fn pressure_region(spine: &PathData, size: f64, variation: f64, prof: &PressureProfile) -> Result<PathData> {
|
||||
let widest = size + variation;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::common::{
|
||||
PenRecord, SIZE_VARIATIONS, SIZES, Sample, center_strokes, dist_to_polyline, fill_targets, has_fill, has_painted_ancestor_stroke,
|
||||
has_painted_stroke, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, ranged, replace_with_pieces, samples_param,
|
||||
set_geometry, sibling_with, size_pressure, target_paths, usize_opt,
|
||||
set_geometry, sibling_with, size_profile, target_paths, usize_opt,
|
||||
};
|
||||
use super::{
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, Document, EngineError, FillRule, Join, NodeId, NodeKind, Paint, ParamCurve, PathData, Point,
|
||||
@@ -314,7 +314,7 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if varies_beyond_size_pressure(&vary) {
|
||||
return erase_varied(s, &samples, [angle, roundness, size], vary);
|
||||
}
|
||||
let pressure = if vary[2].0 == Variation::Pressure { size_pressure(p, &samples, C)? } else { None };
|
||||
let pressure = if vary[2].0 == Variation::Pressure { size_profile(p, &samples, C)? } else { None };
|
||||
let pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
|
||||
let r = size / 2.0;
|
||||
// The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::common::{
|
||||
PenRecord, SIZES, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, ranged, samples_param, size_pressure,
|
||||
PenRecord, SIZES, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, ranged, samples_param, size_profile,
|
||||
stroke_paint, subpath_len, target_paths, within_input_bound,
|
||||
};
|
||||
use super::{
|
||||
@@ -130,8 +130,9 @@ fn fit_from(a: Point, pts: &[Point], tol: Option<f64>, reach: f64) -> Vec<Anchor
|
||||
/// and the stroke behind it less and less, to not at all `reach` along it (Edit selected paths
|
||||
/// within), so a stroke that starts or ends near the path joins it smoothly instead of with a
|
||||
/// straight piece. A stroke shorter than `reach` bends over its own length, so each end still
|
||||
/// lands on its target and the other end's bend doesn't move it off.
|
||||
fn bend_ends(stroke: &mut [Point], a: Option<Point>, b: Option<Point>, reach: f64) {
|
||||
/// lands on its target and the other end's bend doesn't move it off. Where a bend stops between two
|
||||
/// points far apart, a point is added there, so the stroke beyond `reach` stays as drawn.
|
||||
fn bend_ends(stroke: &mut Vec<Point>, a: Option<Point>, b: Option<Point>, reach: f64) {
|
||||
let (Some(&first), Some(&last)) = (stroke.first(), stroke.last()) else { return };
|
||||
// How far along the stroke each point lies, measured before anything moves.
|
||||
let mut along = Vec::with_capacity(stroke.len());
|
||||
@@ -153,6 +154,39 @@ fn bend_ends(stroke: &mut [Point], a: Option<Point>, b: Option<Point>, reach: f6
|
||||
}
|
||||
return;
|
||||
}
|
||||
// A point where each bend stops, when that falls between two points (strokes sent by a script
|
||||
// can have few, far apart): without it, the straight piece to the next point would tilt beyond
|
||||
// `reach`.
|
||||
let (mut c0, mut c1) = (a.map(|_| reach), b.map(|_| total - reach));
|
||||
if let (Some(x), Some(y)) = (c0, c1)
|
||||
&& x > y
|
||||
{
|
||||
(c0, c1) = (Some(y), Some(x));
|
||||
}
|
||||
// Both bends stop at the same place (a stroke twice `reach` long): one point there.
|
||||
if let (Some(x), Some(y)) = (c0, c1)
|
||||
&& (y - x).abs() < 1e-9
|
||||
{
|
||||
c1 = None;
|
||||
}
|
||||
let mut points = Vec::with_capacity(stroke.len() + 2);
|
||||
let mut dists = Vec::with_capacity(stroke.len() + 2);
|
||||
let mut before: Option<(Point, f64)> = None;
|
||||
for (&p, &d) in stroke.iter().zip(&along) {
|
||||
if let Some((q, e)) = before {
|
||||
for c in [c0, c1].into_iter().flatten() {
|
||||
if e + 1e-9 < c && c < d - 1e-9 {
|
||||
points.push(q.lerp(p, (c - e) / (d - e)));
|
||||
dists.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
points.push(p);
|
||||
dists.push(d);
|
||||
before = Some((p, d));
|
||||
}
|
||||
*stroke = points;
|
||||
let along = dists;
|
||||
let weight = |d: f64| (1.0 - d / reach).max(0.0);
|
||||
let (shift_a, shift_b) = (a.map(|a| a - first), b.map(|b| b - last));
|
||||
for (p, &d) in stroke.iter_mut().zip(&along) {
|
||||
@@ -528,7 +562,7 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
|
||||
let keep_selected = switch_or(p, "keepSelected", true, C)?;
|
||||
// The Pencil's preview of a stroke that redraws a path draws it as a new path but leaves the
|
||||
// selection as it is: the path being redrawn stays selected until the release redraws it.
|
||||
let leave_selection = switch_or(p, "leaveSelection", false, C)?;
|
||||
let preview = switch_or(p, "preview", false, C)?;
|
||||
let filled = switch_or(p, "fill", false, C)?;
|
||||
let extend = p.get("extend").filter(|v| !v.is_null());
|
||||
if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) {
|
||||
@@ -779,8 +813,13 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
|
||||
st.brush = Some(name.to_string());
|
||||
}
|
||||
}
|
||||
let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected)?;
|
||||
if !keep_selected && !leave_selection {
|
||||
// A preview goes on top as Draw Normal places it: Draw Inside would put it in the selected
|
||||
// path's clip group, clipped, and Draw Behind behind the path.
|
||||
let mode = if preview { std::mem::replace(&mut s.draw_mode, crate::DrawMode::Normal) } else { s.draw_mode };
|
||||
let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected && !preview);
|
||||
s.draw_mode = mode;
|
||||
let out = out?;
|
||||
if !keep_selected && !preview {
|
||||
// A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke
|
||||
// by dropping the earlier selection, it does not keep it (#5752).
|
||||
s.select(|_, sel| sel.clear())?;
|
||||
@@ -843,8 +882,8 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let tip = vectorcraft_tools::draw2::blob_tip(angle, roundness);
|
||||
let squash = tip.inverse();
|
||||
// Width profiles use distance along the spine, so measure pressure on the same squashed
|
||||
// points that the outline reads for a non-round tip.
|
||||
// Width profiles use distance along the spine, so measure the pressure or wheel on the same
|
||||
// squashed points that the outline reads for a non-round tip.
|
||||
let mapped_samples: Vec<Sample> = if roundness < 100.0 {
|
||||
samples
|
||||
.iter()
|
||||
@@ -857,7 +896,7 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
samples.clone()
|
||||
};
|
||||
let pressure = size_pressure(p, &mapped_samples, C)?;
|
||||
let pressure = size_profile(p, &mapped_samples, C)?;
|
||||
let pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
|
||||
let mapped_pts: Vec<Point> = mapped_samples.into_iter().map(|s| s.pt).collect();
|
||||
// The widest the brush gets: the area merges look in.
|
||||
@@ -875,12 +914,15 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(tol) => Some(pressure_region(&spine(Some(tol)), size, *variation, prof)?).filter(|r| !r.is_empty()),
|
||||
None => None,
|
||||
};
|
||||
let dab = || brush_region(&mapped_pts[..1], vectorcraft_tools::draw2::pressure_size(size, *variation, prof.at(0.0)));
|
||||
match fitted {
|
||||
Some(r) => r,
|
||||
None => pressure_region(&spine(None), size, *variation, prof)?,
|
||||
// Samples that all lie at one point give a spine with no length: one dab from the
|
||||
// first reading, as a click paints.
|
||||
None => Some(pressure_region(&spine(None), size, *variation, prof)?).filter(|r| !r.is_empty()).unwrap_or_else(dab),
|
||||
}
|
||||
}
|
||||
// A click: one dab as wide as the pen pressed.
|
||||
// A click: one dab as wide as the pen pressed or the wheel was set.
|
||||
(Some((prof, variation)), false) => brush_region(&mapped_pts, vectorcraft_tools::draw2::pressure_size(size, *variation, prof.at(0.0))),
|
||||
(None, _) => {
|
||||
let fitted = fidelity
|
||||
@@ -975,4 +1017,23 @@ mod bend_tests {
|
||||
assert_eq!(pts[2], Point::new(48.0, 0.0), "{pts:?}");
|
||||
assert_eq!(pts[1], Point::new(44.0, 0.0), "halfway, half of each end's shift: {pts:?}");
|
||||
}
|
||||
|
||||
/// With points far apart (a stroke sent by a script), the bend still stops `reach` along the
|
||||
/// stroke: a point is added there, and the stroke beyond it stays as drawn.
|
||||
#[test]
|
||||
fn bend_ends_stops_at_the_reach_between_points_far_apart() {
|
||||
let mut pts = vec![Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(200.0, 0.0)];
|
||||
bend_ends(&mut pts, Some(Point::new(0.0, 10.0)), Some(Point::new(200.0, 0.0)), 40.0);
|
||||
assert_eq!(pts.first(), Some(&Point::new(0.0, 10.0)), "{pts:?}");
|
||||
assert!(pts.contains(&Point::new(40.0, 0.0)), "a point where the bend stops: {pts:?}");
|
||||
assert!(pts.iter().filter(|p| p.x >= 40.0).all(|p| p.y == 0.0), "beyond the reach, as drawn: {pts:?}");
|
||||
}
|
||||
|
||||
/// Where both bends stop at the same place, one point is added there, not two.
|
||||
#[test]
|
||||
fn bend_ends_adds_one_point_where_both_bends_stop() {
|
||||
let mut pts = vec![Point::new(0.0, 0.0), Point::new(100.0, 0.0)];
|
||||
bend_ends(&mut pts, Some(Point::new(0.0, 10.0)), Some(Point::new(100.0, 10.0)), 50.0);
|
||||
assert_eq!(pts, [Point::new(0.0, 10.0), Point::new(50.0, 0.0), Point::new(100.0, 10.0)]);
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,16 @@ use super::{
|
||||
// ---------- Smooth ----------
|
||||
|
||||
/// The spread (points) of the Gaussian the Smooth tool smooths a path along its length with before
|
||||
/// refitting it, as a share of the tool's reach: a third, so each point is averaged with the stretch
|
||||
/// of path within the reach on either side of it. VectorCraft's own value.
|
||||
/// refitting it at the default Smoothness ([`SMOOTH_SMOOTHNESS`]), as a share of the tool's reach: a
|
||||
/// third, so each point is averaged with the stretch of path within the reach on either side of it.
|
||||
/// The spread grows in proportion to the Smoothness, from none at 0% to twice this at 100%.
|
||||
/// VectorCraft's own value.
|
||||
const SMOOTH_SPREAD: f64 = 1.0 / 3.0;
|
||||
|
||||
/// The Smoothness (percent) `path.smoothRegion` smooths with when the drag leaves it out. VectorCraft's
|
||||
/// own value.
|
||||
const SMOOTH_SMOOTHNESS: f64 = 50.0;
|
||||
|
||||
/// The degrees by which a path must turn at an anchor, and over the tool's reach and twice its reach
|
||||
/// on either side of it, for the Smooth tool to keep the anchor as a corner ([`smooth_corners`]): a
|
||||
/// turn of more than 57.5°, an angle inside the corner of less than 122.5°. VectorCraft's own value,
|
||||
@@ -929,7 +935,11 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !(lo..=hi).contains(&tol) {
|
||||
return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt")));
|
||||
}
|
||||
let sigma = radius * SMOOTH_SPREAD;
|
||||
let smoothness = number_or(p, "smoothness", SMOOTH_SMOOTHNESS, C)?;
|
||||
if !(0.0..=100.0).contains(&smoothness) {
|
||||
return Err(bad(C, "`smoothness` must be from 0 to 100"));
|
||||
}
|
||||
let sigma = radius * SMOOTH_SPREAD * smoothness / SMOOTH_SMOOTHNESS;
|
||||
let st = s.doc()?;
|
||||
let mut plan = vec![];
|
||||
let (mut before, mut after) = (0, 0);
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New…",
|
||||
["File"],
|
||||
None,
|
||||
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
|
||||
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
|
||||
always,
|
||||
super::newdoc::file_new
|
||||
),
|
||||
@@ -225,7 +225,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear",
|
||||
["Edit"],
|
||||
Some("Delete"),
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too); without ids, refused while an object of a symbol instance's art is selected",
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); without ids, refused while an object of a symbol instance's art is selected",
|
||||
has_selection_or_guides,
|
||||
clear
|
||||
),
|
||||
@@ -809,6 +809,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let selection = shared_selection(selection, st.history.redo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
turned.named = e.named;
|
||||
turned.effect = e.effect;
|
||||
let paints = e.color_mode_paints.clone();
|
||||
turned.color_mode_paints = e.color_mode_paints;
|
||||
turned.recost_paints();
|
||||
@@ -845,6 +846,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let selection = shared_selection(selection, st.history.undo.last());
|
||||
let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs);
|
||||
turned.named = e.named;
|
||||
turned.effect = e.effect;
|
||||
let paints = e.color_mode_paints.clone();
|
||||
turned.color_mode_paints = e.color_mode_paints;
|
||||
turned.recost_paints();
|
||||
@@ -1224,6 +1226,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let guides = switch_or(p, "guides", false, "edit.clear")?;
|
||||
let keep_empty = switch_or(p, "keepEmpty", false, "edit.clear")?;
|
||||
switch_or(p, "keepJoined", false, "edit.clear")?;
|
||||
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
|
||||
// An object of a symbol instance's art can't be removed from the instance alone.
|
||||
@@ -1257,8 +1260,11 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Clear", |d, sel| {
|
||||
let parents: Vec<_> =
|
||||
ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect();
|
||||
let parents: Vec<_> = if keep_empty {
|
||||
Vec::new()
|
||||
} else {
|
||||
ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect()
|
||||
};
|
||||
d.remove_many(&ids)?;
|
||||
for p in parents {
|
||||
if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) {
|
||||
|
||||
@@ -453,12 +453,17 @@ pub fn pathfinder_effect_options(s: &Session) -> effects::PathfinderEffectOption
|
||||
}
|
||||
}
|
||||
|
||||
/// The effect an apply request names, including the older `id` parameter.
|
||||
pub(crate) fn requested_effect(p: &Value) -> Option<&str> {
|
||||
str_param(p, "effect").or_else(|| str_param(p, "id"))
|
||||
}
|
||||
|
||||
/// `effect.apply`: adds effect `effect` (or `id`) with `params`, its defaults filled in, to the
|
||||
/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one;
|
||||
/// a Pathfinder effect on loose objects groups them first. → `{ids, index, item}`.
|
||||
/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one.
|
||||
/// A Pathfinder effect on loose objects groups them first. → `{ids, index, item}`.
|
||||
pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.apply";
|
||||
let id = str_param(p, "effect").or_else(|| str_param(p, "id")).ok_or_else(|| bad(C, "missing `effect` id"))?;
|
||||
let id = requested_effect(p).ok_or_else(|| bad(C, "missing `effect` id"))?;
|
||||
// An effect given as `id` names no objects: the targets are read with that `id` as null.
|
||||
let effect_as_id;
|
||||
let p = if str_param(p, "effect").is_none() {
|
||||
@@ -509,11 +514,13 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let label = effects::effect_info(id).map(|e| e.label.trim_end_matches('…').to_string()).unwrap_or_default();
|
||||
aligned(p, C)?;
|
||||
if let Some(loose) = loose_for_pathfinder(s, p, id)? {
|
||||
let gid = s.edit(&label, |d, sel| {
|
||||
let gid = super::object::group_nodes(d, &loose)?;
|
||||
d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone());
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
let gid = s.edit_effect(id, |s| {
|
||||
s.edit(&label, |d, sel| {
|
||||
let gid = super::object::group_nodes(d, &loose)?;
|
||||
d.node_mut(gid).ok_or(EngineError::NoNode(gid))?.appearance.effects.push(effect.clone());
|
||||
sel.set([gid]);
|
||||
Ok(gid)
|
||||
})
|
||||
})?;
|
||||
return Ok(json!({ "ids": [gid.0], "index": 0, "item": null, "grouped": true }));
|
||||
}
|
||||
@@ -544,9 +551,11 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| {
|
||||
fx.push(effect.clone());
|
||||
true
|
||||
let ids = s.edit_effect(id, |s| {
|
||||
edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| {
|
||||
fx.push(effect.clone());
|
||||
true
|
||||
})
|
||||
})?;
|
||||
// The item the effect landed on in the object whose row the item is (the first selected object
|
||||
// for the active item, which applies where it fits), and the effect's index in that object.
|
||||
@@ -887,32 +896,37 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let ids = edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| {
|
||||
let Some(e) = fx.get_mut(index) else { return false };
|
||||
if let Some(id) = &warp_id {
|
||||
e.id.clone_from(id);
|
||||
}
|
||||
if let Some(to) = kind
|
||||
&& e.id != to
|
||||
{
|
||||
e.params = effects::three_d_params_as(&e.id, &e.params, to);
|
||||
e.id = to.to_string();
|
||||
}
|
||||
if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) {
|
||||
if !cur.is_object() {
|
||||
*cur = effects::merged_params(&e.id, &Value::Null);
|
||||
// The effect edited, when every target has one at `index` and all are the same: a dialog's
|
||||
// preview names its step after it.
|
||||
let one = edited.first().filter(|e| edited.len() == targets.len() && edited.iter().all(|other| other == *e)).cloned().unwrap_or_default();
|
||||
let ids = s.edit_effect(&one, |s| {
|
||||
edit_effects(s, p, item, C, "Effect Options", &format!("{C}: no effect at index {index}"), index, |fx, index| {
|
||||
let Some(e) = fx.get_mut(index) else { return false };
|
||||
if let Some(id) = &warp_id {
|
||||
e.id.clone_from(id);
|
||||
}
|
||||
// Earlier parameters (a Perspective strength, a light by azimuth and elevation) take
|
||||
// their current form first, so the new values replace them and the rest is kept.
|
||||
*cur = effects::upgrade_params(&e.id, cur);
|
||||
if let Value::Object(m) = cur {
|
||||
m.extend(new);
|
||||
if let Some(to) = kind
|
||||
&& e.id != to
|
||||
{
|
||||
e.params = effects::three_d_params_as(&e.id, &e.params, to);
|
||||
e.id = to.to_string();
|
||||
}
|
||||
}
|
||||
if let Some(v) = visible {
|
||||
e.visible = v;
|
||||
}
|
||||
true
|
||||
if let (Value::Object(new), cur) = (effects::upgrade_params(&e.id, ¶ms), &mut e.params) {
|
||||
if !cur.is_object() {
|
||||
*cur = effects::merged_params(&e.id, &Value::Null);
|
||||
}
|
||||
// Earlier parameters (a Perspective strength, a light by azimuth and elevation) take
|
||||
// their current form first, so the new values replace them and the rest is kept.
|
||||
*cur = effects::upgrade_params(&e.id, cur);
|
||||
if let Value::Object(m) = cur {
|
||||
m.extend(new);
|
||||
}
|
||||
}
|
||||
if let Some(v) = visible {
|
||||
e.visible = v;
|
||||
}
|
||||
true
|
||||
})
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ mod encode;
|
||||
pub mod eps;
|
||||
mod export;
|
||||
pub(crate) mod imagemap;
|
||||
mod importer;
|
||||
pub(crate) mod importer;
|
||||
pub mod jxlread;
|
||||
mod legacy_ai;
|
||||
mod load;
|
||||
@@ -167,8 +167,8 @@ use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable};
|
||||
pub use formats::{
|
||||
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters,
|
||||
export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters, open_extensions,
|
||||
open_filters, opens_as_other, opens_with_importer, place_filters, plugin_formats, read_extensions, readable_format, readable_format_for_name,
|
||||
titled_for_export, writable_format,
|
||||
open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_filters, places_with_importer, plugin_formats, read_extensions,
|
||||
readable_format, readable_format_for_name, titled_for_export, writable_format,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-b
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (with transparency: as document.exportForWeb), transparencyDitherAmount?: 100 (0–100: the diffusion transparency dither's strength), matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), d
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"File Formats",
|
||||
[],
|
||||
None,
|
||||
"{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.<plug-in id>; see plugin.list)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PageMaker, with what to use instead)}",
|
||||
"{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in (write only) or importer plug-in (read only) that adds the format (its id is plugin.<plug-in id>; see plugin.list), place?: true (an importer's format whose files file.place also reads, see file.place's importer)}], readable: [id…], writable: [id…], openExtensions: [ext…] (the importers' extensions that no built-in format reads included), unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PageMaker, with what to use instead)}",
|
||||
always,
|
||||
formats
|
||||
),
|
||||
|
||||
@@ -256,6 +256,11 @@ struct RasterOptions {
|
||||
dither: Option<String>,
|
||||
dither_amount: Option<u8>,
|
||||
transparency: Option<bool>,
|
||||
/// GIF and PNG-8 with `transparency`: none, diffusion, pattern or noise, read by
|
||||
/// [`RasterOptions::transparency_dither`] (other formats do not check it).
|
||||
transparency_dither: Option<Value>,
|
||||
/// The diffusion transparency dither's strength, 0–100, read as `transparency_dither` is.
|
||||
transparency_dither_amount: Option<Value>,
|
||||
matte: Option<Value>,
|
||||
lossless: Option<bool>,
|
||||
lzw: Option<bool>,
|
||||
@@ -295,6 +300,26 @@ impl RasterOptions {
|
||||
}
|
||||
}
|
||||
|
||||
/// GIF and PNG-8: `transparencyDither` (absent: none, which cuts at half opacity, not
|
||||
/// `Dither`'s own default) and `transparencyDitherAmount` (0–100, default 100), or an error.
|
||||
fn transparency_dither(&self) -> Result<(Dither, u8)> {
|
||||
const IDS: &str = "none, diffusion, pattern or noise";
|
||||
let method = match &self.transparency_dither {
|
||||
None | Some(Value::Null) => PaletteOptions::default().transparency_dither,
|
||||
Some(Value::String(s)) => parse(Some(s), Dither::from_id, "transparencyDither", IDS)?,
|
||||
Some(v) => return Err(bad(C, format!("transparencyDither must be {IDS}, not {v}"))),
|
||||
};
|
||||
let amount = match &self.transparency_dither_amount {
|
||||
None | Some(Value::Null) => 100,
|
||||
Some(v) => v
|
||||
.as_u64()
|
||||
.filter(|n| *n <= 100)
|
||||
.and_then(|n| u8::try_from(n).ok())
|
||||
.ok_or_else(|| bad(C, format!("transparencyDitherAmount must be a whole number from 0 to 100, not {v}")))?,
|
||||
};
|
||||
Ok((method, amount))
|
||||
}
|
||||
|
||||
/// The pixel size each file is scaled to: `width`, else `height`; `None` when neither is set.
|
||||
fn pixel_size(&self) -> Result<Option<ScreenSize>> {
|
||||
let checked = |key: &str, n: f64| {
|
||||
@@ -348,6 +373,7 @@ impl RasterOptions {
|
||||
Some(v) => background(v).map_err(|e| bad(C, format!("matte: {e}")))?,
|
||||
None => Some([255; 3]),
|
||||
},
|
||||
..PaletteOptions::default()
|
||||
},
|
||||
tiff: TiffOptions {
|
||||
color_model,
|
||||
@@ -1158,6 +1184,9 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
{
|
||||
return Err(bad(C, format!("quality {q}: WebP quality is 0–100")));
|
||||
}
|
||||
if matches!(format, RasterFormat::Gif | RasterFormat::Png8) {
|
||||
(settings.palette.transparency_dither, settings.palette.transparency_dither_amount) = o.transparency_dither()?;
|
||||
}
|
||||
check_options(format, &settings)?;
|
||||
// Use Artboards: one file per chosen artboard (default all); else the one chosen.
|
||||
let chosen = match use_artboards {
|
||||
|
||||
@@ -195,6 +195,20 @@ const TRANSPARENCY: FormatOption = FormatOption {
|
||||
description: "pixels under half opacity become one transparent entry (false: everything is blended over the matte)",
|
||||
};
|
||||
|
||||
const TRANSPARENCY_DITHER: FormatOption = FormatOption {
|
||||
name: "transparencyDither",
|
||||
ty: "string",
|
||||
default: "\"none\"",
|
||||
description: "with transparency, how partly transparent pixels are split between the transparent entry and their color: none (cut at half opacity), diffusion, pattern (8×8 ordered) or noise",
|
||||
};
|
||||
|
||||
const TRANSPARENCY_DITHER_AMOUNT: FormatOption = FormatOption {
|
||||
name: "transparencyDitherAmount",
|
||||
ty: "integer",
|
||||
default: "100",
|
||||
description: "the diffusion transparency dither's strength 0–100 (0 cuts at half opacity; more than 100 is refused)",
|
||||
};
|
||||
|
||||
const MATTE: FormatOption = FormatOption {
|
||||
name: "matte",
|
||||
ty: "string",
|
||||
@@ -235,6 +249,8 @@ const PALETTE_OPTIONS: &[FormatOption] = &[
|
||||
DITHER,
|
||||
DITHER_AMOUNT,
|
||||
TRANSPARENCY,
|
||||
TRANSPARENCY_DITHER,
|
||||
TRANSPARENCY_DITHER_AMOUNT,
|
||||
MATTE,
|
||||
];
|
||||
|
||||
@@ -737,11 +753,26 @@ fn format_filters() -> impl Iterator<Item = (&'static str, &'static [&'static st
|
||||
FORMATS.iter().filter(|f| f.read).map(|f| (f.label, read_extensions(f)))
|
||||
}
|
||||
|
||||
/// Whether a file named `name` can only be read by an importer plug-in: an installed importer lists
|
||||
/// its extension and File › Place does not read that extension.
|
||||
/// Whether a file named `name` can only be opened, by an importer plug-in: an installed importer lists
|
||||
/// its extension, File › Place does not read that extension, and no installed importer that places
|
||||
/// its files lists it ([`places_with_importer`]).
|
||||
pub fn opens_with_importer(name: &str) -> bool {
|
||||
let ext = extension(name);
|
||||
!ext.is_empty() && !PLACE_EXTS.contains(&ext.as_str()) && !vectorcraft_plugins::import::for_extension(&ext).is_empty()
|
||||
!ext.is_empty()
|
||||
&& !PLACE_EXTS.contains(&ext.as_str())
|
||||
&& !vectorcraft_plugins::import::for_extension(&ext).is_empty()
|
||||
&& !places_with_importer(name)
|
||||
}
|
||||
|
||||
/// Whether File › Place places a file named `name` with an importer plug-in when no built-in format
|
||||
/// reads its content: no built-in format reads its extension, and an installed importer whose manifest
|
||||
/// sets `place` lists it.
|
||||
pub fn places_with_importer(name: &str) -> bool {
|
||||
let ext = extension(name);
|
||||
!ext.is_empty()
|
||||
&& readable_format(&ext).is_none()
|
||||
&& !PLACE_EXTS.contains(&ext.as_str())
|
||||
&& !vectorcraft_plugins::import::placing(&ext).is_empty()
|
||||
}
|
||||
|
||||
/// Whether File › Open opens a file of extension `ext` (lower case) as something other than a
|
||||
@@ -871,6 +902,53 @@ pub fn place_filters() -> impl Iterator<Item = (&'static str, &'static [&'static
|
||||
.chain(std::iter::once(("Word", WORD_EXTS)))
|
||||
}
|
||||
|
||||
/// File › Place's part for the installed importer plug-ins whose manifests set `place`: the
|
||||
/// extensions of "All placeable files" ([`PLACE_EXTS`], then theirs in plug-in id order) and one
|
||||
/// filter per such importer that has extensions left, under its name. An importer's extensions leave
|
||||
/// out those a built-in format reads, which File › Place reads with that format. Made once for each
|
||||
/// set of installed plug-ins, so it lives as long as the dialogs that hold it.
|
||||
fn importer_place_part() -> ImporterPart {
|
||||
use vectorcraft_plugins::{import, registry};
|
||||
static MADE: std::sync::Mutex<Option<(u64, ImporterPart)>> = std::sync::Mutex::new(None);
|
||||
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let revision = registry::revision();
|
||||
if let Some((r, part)) = made.as_ref()
|
||||
&& *r == revision
|
||||
{
|
||||
return part.clone();
|
||||
}
|
||||
let mut exts: Vec<&'static str> = PLACE_EXTS.to_vec();
|
||||
let mut filters = Vec::new();
|
||||
for p in import::installed().into_iter().filter(|p| p.manifest().place) {
|
||||
let m = p.manifest();
|
||||
let own: Vec<&'static str> =
|
||||
m.extensions.iter().filter(|e| readable_format(e).is_none() && !PLACE_EXTS.contains(&e.as_str())).map(|e| registry::intern(e)).collect();
|
||||
if own.is_empty() {
|
||||
continue;
|
||||
}
|
||||
for &e in &own {
|
||||
if !exts.contains(&e) {
|
||||
exts.push(e);
|
||||
}
|
||||
}
|
||||
let own: &'static [&'static str] = Box::leak(own.into_boxed_slice());
|
||||
filters.push((registry::intern(&m.name), own));
|
||||
}
|
||||
let exts: &'static [&'static str] = if exts.len() == PLACE_EXTS.len() { PLACE_EXTS } else { Box::leak(exts.into_boxed_slice()) };
|
||||
let part = (exts, filters);
|
||||
*made = Some((revision, part.clone()));
|
||||
part
|
||||
}
|
||||
|
||||
/// File › Place's own dialog filters: [`place_filters`], with the extensions of the installed
|
||||
/// importer plug-ins that place their files in "All placeable files" and one filter per such
|
||||
/// importer after the others, under its name ([`places_with_importer`]). Pickers that relink an
|
||||
/// image use [`place_filters`].
|
||||
pub fn place_dialog_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
let (all, importers) = importer_place_part();
|
||||
std::iter::once(("All placeable files", all)).chain(place_filters().skip(1)).chain(importers)
|
||||
}
|
||||
|
||||
/// A format by id or extension (any case, leading dot allowed; `jpeg` finds `jpg`): a built-in
|
||||
/// one, else one a plug-in adds ([`plugin_formats`]), an exporter's before an importer's for an
|
||||
/// extension both list. A built-in format keeps its extension, so an exporter or importer that
|
||||
@@ -1021,6 +1099,9 @@ pub(super) fn formats(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
let mut v = f.to_json();
|
||||
if let Some(id) = vectorcraft_plugins::export::plugin_id(f.id) {
|
||||
v["plugin"] = json!(id);
|
||||
if vectorcraft_plugins::import::by_format(f.id).is_some_and(|p| p.manifest().place) {
|
||||
v["place"] = json!(true);
|
||||
}
|
||||
}
|
||||
v
|
||||
};
|
||||
|
||||
@@ -1,58 +1,118 @@
|
||||
//! `document.open` of the files importer plug-ins read ([`vectorcraft_plugins::import`]).
|
||||
//! `document.open` and `file.place` of the files importer plug-ins read
|
||||
//! ([`vectorcraft_plugins::import`]).
|
||||
//!
|
||||
//! A file opens with an importer when `importer` names one (its format id, `plugin.<id>`), which
|
||||
//! must list the file's extension, or when no built-in format reads the file, by its content or by
|
||||
//! its extension, and an importer lists its extension (the one whose id sorts first, when several
|
||||
//! do). A built-in format that can't read a damaged file reports its own error: the file is not
|
||||
//! handed to an importer instead. Place reads only the built-in formats.
|
||||
//! handed to an importer instead. File › Place uses an importer by the same rules, among the
|
||||
//! importers whose manifests set `place` ([`named_for_place`], [`for_place`]).
|
||||
//!
|
||||
//! The importer is given the file's bytes, at most [`import::MAX_INPUT_BYTES`] of them: a file
|
||||
//! named by `path` that only an importer can read is read no further than that. Its objects become
|
||||
//! a new document whose artboard is their bounds, and nothing opens when the importer fails,
|
||||
//! declines, is cancelled or returns objects that don't pass the checks a filter's output does.
|
||||
//! a new document whose artboard is their bounds (or, to place, the art of one group), and nothing
|
||||
//! opens or is placed when the importer fails, declines, is cancelled or returns objects that don't
|
||||
//! pass the checks a filter's output does.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::{Document, MAX_COORD};
|
||||
use vectorcraft_doc::{Document, MAX_COORD, NodeId};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_plugins::{Plugin, export, import, objects};
|
||||
use vectorcraft_plugins::import::Mode;
|
||||
use vectorcraft_plugins::{Manifest, Plugin, export, import, objects};
|
||||
|
||||
use super::super::{Result, bad, str_param};
|
||||
use super::load::{Loaded, detect, file_name};
|
||||
use super::{err, extension, file_stem, format};
|
||||
use super::load::{Loaded, Source, detect, file_name};
|
||||
use super::{Format, err, extension, file_stem, format};
|
||||
use crate::EngineError;
|
||||
|
||||
const C: &str = "document.open";
|
||||
|
||||
/// The importer `document.open`'s params `p` name (`importer`), if any; a value that isn't a
|
||||
/// string is an error.
|
||||
fn named(p: &Value) -> Result<Option<&str>> {
|
||||
/// The importer command `cmd`'s params `p` name (`importer`), if any; a value that isn't a string
|
||||
/// is an error.
|
||||
fn named<'a>(p: &'a Value, cmd: &str) -> Result<Option<&'a str>> {
|
||||
match p.get("importer").filter(|v| !v.is_null()) {
|
||||
None => Ok(None),
|
||||
Some(v) => v.as_str().map(Some).ok_or_else(|| bad(C, "`importer` must be a plug-in format id (see document.formats)")),
|
||||
Some(v) => v.as_str().map(Some).ok_or_else(|| bad(cmd, "`importer` must be a plug-in format id (see document.formats)")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks that importer `m` lists the extension of the file `name`: else command `cmd`'s error,
|
||||
/// which names the extensions it lists.
|
||||
fn check_extension(cmd: &str, m: &Manifest, name: &str) -> Result<()> {
|
||||
if m.extensions.contains(&extension(name)) {
|
||||
return Ok(());
|
||||
}
|
||||
let shown = vectorcraft_plugins::permissions::display_text(&m.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME);
|
||||
let exts: Vec<String> = m.extensions.iter().map(|e| format!(".{e}")).collect();
|
||||
Err(bad(cmd, format!("“{shown}” opens {} files, not `{}`", exts.join(", "), file_name(name))))
|
||||
}
|
||||
|
||||
/// The importer that opens the file `name` holding `bytes` with `document.open`'s params `p`: the
|
||||
/// one `importer` names, which must list the file's extension; else, when no built-in format reads
|
||||
/// the file, the first installed importer that lists its extension; else `None`.
|
||||
pub(super) fn pick(name: &str, bytes: &[u8], p: &Value) -> Result<Option<Arc<Plugin>>> {
|
||||
let ext = extension(name);
|
||||
if let Some(id) = named(p)? {
|
||||
if let Some(id) = named(p, C)? {
|
||||
let plugin = import::named(id).map_err(|e| bad(C, e.to_string()))?;
|
||||
let m = plugin.manifest();
|
||||
if !m.extensions.contains(&ext) {
|
||||
let shown = vectorcraft_plugins::permissions::display_text(&m.name, vectorcraft_plugins::permissions::MAX_SHOWN_NAME);
|
||||
let exts: Vec<String> = m.extensions.iter().map(|e| format!(".{e}")).collect();
|
||||
return Err(bad(C, format!("“{shown}” opens {} files, not `{}`", exts.join(", "), file_name(name))));
|
||||
}
|
||||
check_extension(C, plugin.manifest(), name)?;
|
||||
return Ok(Some(plugin));
|
||||
}
|
||||
if detect(name, bytes).is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(import::for_extension(&ext).into_iter().next())
|
||||
Ok(import::for_extension(&extension(name)).into_iter().next())
|
||||
}
|
||||
|
||||
/// The importer `file.place`'s params `p` name (`importer`) for the file `name`, which must set
|
||||
/// `place` in its manifest and list the file's extension (errors of command `cmd`); `None` when `p`
|
||||
/// names none.
|
||||
pub(crate) fn named_for_place(name: &str, p: &Value, cmd: &str) -> Result<Option<Arc<Plugin>>> {
|
||||
let Some(id) = named(p, cmd)? else { return Ok(None) };
|
||||
let plugin = import::named(id).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
let m = plugin.manifest();
|
||||
if !m.place {
|
||||
return Err(match import::not_placing(m) {
|
||||
vectorcraft_plugins::Error::Params(why) => bad(cmd, why),
|
||||
e => bad(cmd, e.to_string()),
|
||||
});
|
||||
}
|
||||
check_extension(cmd, m, name)?;
|
||||
Ok(Some(plugin))
|
||||
}
|
||||
|
||||
/// The importer File › Place uses for the file `name` when no built-in format reads it: the first
|
||||
/// installed importer, by plug-in id, whose manifest sets `place` and that lists its extension.
|
||||
pub(crate) fn for_place(name: &str) -> Option<Arc<Plugin>> {
|
||||
import::placing(&extension(name)).into_iter().next()
|
||||
}
|
||||
|
||||
/// Whether an importer may read a file of extension `ext` for `mode` when none is named: no
|
||||
/// built-in format reads the extension (for Place, as text, RTF or Word either) and an importer
|
||||
/// that reads for `mode` lists it.
|
||||
fn importer_reads(ext: &str, mode: Mode) -> bool {
|
||||
super::readable_format(ext).is_none()
|
||||
&& match mode {
|
||||
Mode::Import => !import::for_extension(ext).is_empty(),
|
||||
Mode::Place => !super::PLACE_EXTS.contains(&ext) && !import::placing(ext).is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The error of the file `name`, past [`import::MAX_INPUT_BYTES`], which an importer would read
|
||||
/// for `mode`.
|
||||
fn too_large(name: &str, mode: Mode) -> EngineError {
|
||||
match mode {
|
||||
Mode::Import => err(format!("can't open `{}`: {}", file_name(name), import::too_large())),
|
||||
Mode::Place => failed(Mode::Place, name, import::too_large()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The error of the file `name`, which importer `e` couldn't read for `mode`.
|
||||
fn failed(mode: Mode, name: &str, e: impl std::fmt::Display) -> EngineError {
|
||||
match mode {
|
||||
Mode::Import => err(format!("can't open `{}`: {e}", file_name(name))),
|
||||
Mode::Place => err(format!("can't place `{}`: {e}", file_name(name))),
|
||||
}
|
||||
}
|
||||
|
||||
/// How much of a file [`detect`] is given: more than its content checks read.
|
||||
@@ -61,14 +121,17 @@ const SNIFF_BYTES: usize = 64 << 10;
|
||||
/// Refuses `document.open`'s `dataBase64` in `p` before it is decoded when it holds a file past
|
||||
/// [`import::MAX_INPUT_BYTES`] that only an importer reads, by the rule of `read_path`.
|
||||
pub(super) fn check_data(p: &Value) -> Result<()> {
|
||||
check_data_for(p, Mode::Import, C)
|
||||
}
|
||||
|
||||
/// [`check_data`] for `mode` and command `cmd`: `file.place`'s params with [`Mode::Place`].
|
||||
fn check_data_for(p: &Value, mode: Mode, cmd: &str) -> Result<()> {
|
||||
let Some(b64) = str_param(p, "dataBase64") else {
|
||||
return Ok(());
|
||||
};
|
||||
let name = str_param(p, "name").unwrap_or("Untitled");
|
||||
let ext = extension(name);
|
||||
let explicit = named(p)?.is_some();
|
||||
let built_in = !explicit && (super::readable_format(&ext).is_some() || import::for_extension(&ext).is_empty());
|
||||
if built_in || vectorcraft_format::base64_decoded_len(b64) <= import::MAX_INPUT_BYTES as u64 {
|
||||
let explicit = named(p, cmd)?.is_some();
|
||||
if (!explicit && !importer_reads(&extension(name), mode)) || vectorcraft_format::base64_decoded_len(b64) <= import::MAX_INPUT_BYTES as u64 {
|
||||
return Ok(());
|
||||
}
|
||||
if !explicit {
|
||||
@@ -78,79 +141,121 @@ pub(super) fn check_data(p: &Value) -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(err(format!("can't open `{}`: {}", file_name(name), import::too_large())))
|
||||
Err(too_large(name, mode))
|
||||
}
|
||||
|
||||
/// The file at `path` for `document.open`'s params `p`. A file that only an importer reads (one
|
||||
/// `importer` names, or an extension no built-in format reads that an importer lists) is read up
|
||||
/// to [`import::MAX_INPUT_BYTES`]: past that, it is an error, unless the start of the file shows a
|
||||
/// built-in format and no importer was named, which is read whole as any other file is. A file past
|
||||
/// the limit that isn't read whole is reported from its size, without reading it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// the limit that isn't read whole is reported from its size: with `importer` named, before any of
|
||||
/// it is read, and otherwise after the start of it is read to look for a built-in format.
|
||||
pub(super) fn read_path(path: &str, p: &Value) -> Result<Vec<u8>> {
|
||||
let ext = extension(path);
|
||||
let explicit = named(p)?.is_some();
|
||||
if !explicit && (super::readable_format(&ext).is_some() || import::for_extension(&ext).is_empty()) {
|
||||
read_path_for(path, p, Mode::Import, C)
|
||||
}
|
||||
|
||||
/// [`read_path`] for `mode` and command `cmd`: `file.place`'s params with [`Mode::Place`].
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn read_path_for(path: &str, p: &Value, mode: Mode, cmd: &str) -> Result<Vec<u8>> {
|
||||
let explicit = named(p, cmd)?.is_some();
|
||||
if explicit {
|
||||
return read_for_importer(path, mode);
|
||||
}
|
||||
if !importer_reads(&extension(path), mode) {
|
||||
return super::read_file(path);
|
||||
}
|
||||
let head = super::read_file_head(path, SNIFF_BYTES)?;
|
||||
if head.len() < SNIFF_BYTES {
|
||||
return Ok(head);
|
||||
}
|
||||
if !explicit && detect(path, &head).is_some() {
|
||||
if detect(path, &head).is_some() {
|
||||
return super::read_file(path);
|
||||
}
|
||||
let too_large = || err(format!("can't open `{}`: {}", file_name(path), import::too_large()));
|
||||
let size = std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.len();
|
||||
if size > import::MAX_INPUT_BYTES as u64 {
|
||||
return Err(too_large());
|
||||
read_for_importer(path, mode)
|
||||
}
|
||||
|
||||
/// The file at `path` for an importer: refused from its size, before any of it is read, when it is
|
||||
/// past [`import::MAX_INPUT_BYTES`].
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn read_for_importer(path: &str, mode: Mode) -> Result<Vec<u8>> {
|
||||
super::may_read(path)?;
|
||||
let meta = std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
if meta.is_file() && meta.len() > import::MAX_INPUT_BYTES as u64 {
|
||||
return Err(too_large(path, mode));
|
||||
}
|
||||
// The file can grow after the size is read.
|
||||
// The file can grow after the size is read; anything but a regular file is refused here.
|
||||
let file = super::read_file_head(path, import::MAX_INPUT_BYTES + 1)?;
|
||||
if file.len() > import::MAX_INPUT_BYTES {
|
||||
return Err(too_large());
|
||||
return Err(too_large(path, mode));
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(super) fn read_path(path: &str, _: &Value) -> Result<Vec<u8>> {
|
||||
fn read_path_for(path: &str, _: &Value, _: Mode, _: &str) -> Result<Vec<u8>> {
|
||||
super::read_file(path)
|
||||
}
|
||||
|
||||
/// The file `file.place`'s params `p` name, as [`super::source`] reads it for command `cmd`, except
|
||||
/// that a file an importer would place (one `importer` names, or an extension no built-in format
|
||||
/// reads that an importer which places its files lists) is read, or decoded, only when it is at
|
||||
/// most [`import::MAX_INPUT_BYTES`] long.
|
||||
pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str) -> Result<Source<'a>> {
|
||||
match str_param(p, "path") {
|
||||
Some(path) => Ok(Source { name: path, bytes: read_path_for(path, p, Mode::Place, cmd)?, path: Some(path) }),
|
||||
None => {
|
||||
check_data_for(p, Mode::Place, cmd)?;
|
||||
super::source(p, cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The file `name` holding `bytes` read by importer `plugin` for `mode` with command `cmd`'s params
|
||||
/// `p` (`params`: the importer's own parameters) → the importer's format, a new document holding its
|
||||
/// objects on its first layer, their ids, and its warnings.
|
||||
fn read(
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
plugin: &Plugin,
|
||||
p: &Value,
|
||||
cmd: &str,
|
||||
mode: Mode,
|
||||
) -> Result<(&'static Format, Document, Vec<NodeId>, Vec<String>)> {
|
||||
let m = plugin.manifest();
|
||||
let format = format(&export::format_id(&m.id)).filter(|f| f.read).ok_or_else(|| err(vectorcraft_plugins::Error::NotFound(m.id.clone())))?;
|
||||
let (ext, stem) = (extension(name), file_stem(name));
|
||||
let source = import::Source { extension: &ext, name: &stem };
|
||||
let params = p.get("params").cloned().unwrap_or(Value::Null);
|
||||
let imported = import::run_as(plugin, bytes, ¶ms, source, mode).map_err(|e| match e {
|
||||
vectorcraft_plugins::Error::Cancelled => EngineError::Cancelled,
|
||||
vectorcraft_plugins::Error::Params(why) => bad(cmd, why),
|
||||
e => failed(mode, name, e),
|
||||
})?;
|
||||
let mut doc = Document::new(1.0, 1.0);
|
||||
let layer = doc.layers.first().map(|l| l.id);
|
||||
let admit = |fx: &[vectorcraft_doc::Effect], n: &vectorcraft_doc::Node| crate::cmd::plugin::admit_effects_for(cmd, fx, n);
|
||||
let ids = objects::apply_output(&mut doc, &[], imported.objects, layer, &admit).map_err(|e| failed(mode, name, e))?;
|
||||
Ok((format, doc, ids, imported.warnings))
|
||||
}
|
||||
|
||||
/// The file `name` holding `bytes` read by importer `plugin` to place it, with `file.place`'s params
|
||||
/// `p` (errors of command `cmd`) → the importer's format, the document holding its objects on its
|
||||
/// first layer, and its warnings. Importer `plugin`'s manifest must set `place`.
|
||||
pub(crate) fn read_for_place(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value, cmd: &str) -> Result<(&'static Format, Document, Vec<String>)> {
|
||||
let (format, doc, _, warnings) = read(name, bytes, plugin, p, cmd, Mode::Place)?;
|
||||
Ok((format, doc, warnings))
|
||||
}
|
||||
|
||||
/// The file `name` holding `bytes` read by importer `plugin` with `document.open`'s params `p`
|
||||
/// (`params`: the importer's own parameters) into a new document, its artboard the bounds of what
|
||||
/// the importer returned.
|
||||
pub(super) fn load(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value) -> Result<Loaded> {
|
||||
let m = plugin.manifest();
|
||||
let format = format(&export::format_id(&m.id)).filter(|f| f.read).ok_or_else(|| err(vectorcraft_plugins::Error::NotFound(m.id.clone())))?;
|
||||
let (ext, stem) = (extension(name), file_stem(name));
|
||||
let source = import::Source { extension: &ext, name: &stem };
|
||||
let params = p.get("params").cloned().unwrap_or(Value::Null);
|
||||
let imported = import::run(plugin, bytes, ¶ms, source).map_err(|e| match e {
|
||||
vectorcraft_plugins::Error::Cancelled => EngineError::Cancelled,
|
||||
vectorcraft_plugins::Error::Params(why) => bad(C, why),
|
||||
e => err(format!("can't open `{}`: {e}", file_name(name))),
|
||||
})?;
|
||||
let mut doc = Document::new(1.0, 1.0);
|
||||
let layer = doc.layers.first().map(|l| l.id);
|
||||
let admit = |fx: &[vectorcraft_doc::Effect], n: &vectorcraft_doc::Node| crate::cmd::plugin::admit_effects_for(C, fx, n);
|
||||
let ids =
|
||||
objects::apply_output(&mut doc, &[], imported.objects, layer, &admit).map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?;
|
||||
let (format, mut doc, ids, warnings) = read(name, bytes, plugin, p, C, Mode::Import)?;
|
||||
if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) {
|
||||
board.rect = artboard_rect(bounds);
|
||||
}
|
||||
doc.title = file_name(name);
|
||||
Ok(Loaded {
|
||||
doc,
|
||||
format,
|
||||
warnings: imported.warnings,
|
||||
restored: false,
|
||||
converted: false,
|
||||
preview_only: false,
|
||||
editing_data: false,
|
||||
native_pdf_compatible: None,
|
||||
})
|
||||
Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None })
|
||||
}
|
||||
|
||||
/// The artboard of art with bounds `r`: `r` within ±[`MAX_COORD`], at least 1 pt wide and high
|
||||
|
||||
@@ -884,14 +884,16 @@ impl ReadFile {
|
||||
if self.rest.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
// One snapshot of the working settings serves the reply and the policies.
|
||||
let working = vectorcraft_color::cms::working_settings();
|
||||
// The question the answer was given to, for the reply's `profileChoice`.
|
||||
let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings());
|
||||
let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &working);
|
||||
let answered = match (&self.choice, &question) {
|
||||
(Some(c), Some(q)) if c.issue() == q.issue => Some(json!({ "issue": q.issue.id(), "model": q.to_json()["model"], "choice": c.id() })),
|
||||
_ => None,
|
||||
};
|
||||
// A failure leaves the file waiting, unchanged.
|
||||
let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref())?;
|
||||
let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref(), &working)?;
|
||||
let Some(rest) = self.rest.take() else { return Ok(()) };
|
||||
self.answered = answered;
|
||||
self.loaded.warnings.extend(notes);
|
||||
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export PDF",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in
Line truncated
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in
Line truncated
|
||||
has_doc,
|
||||
export_pdf
|
||||
),
|
||||
|
||||
@@ -86,6 +86,80 @@ fn png8_and_gif_export_palettes() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The shares of opaque pixels in the left and right halves of a 40×30 image file.
|
||||
fn opaque_halves(file: &[u8]) -> [f64; 2] {
|
||||
let img = craft_image_codecs::decode(file).unwrap();
|
||||
assert_eq!(img.dimensions(), (40, 30));
|
||||
let alpha: Vec<u8> = img.to_rgba8().chunks(4).map(|p| p[3]).collect();
|
||||
[0, 20].map(|x0| (0..30).flat_map(|y| (x0..x0 + 20).map(move |x| y * 40 + x)).filter(|&i| alpha[i] == 255).count() as f64 / 600.0)
|
||||
}
|
||||
|
||||
/// GIF and PNG-8 exports take Save for Web's `transparencyDither` and `transparencyDitherAmount`.
|
||||
#[test]
|
||||
fn palette_exports_take_the_transparency_dither() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 40, "height": 30})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 25})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 20, "height": 30})).unwrap();
|
||||
s.execute("transparency.set", &json!({"opacity": 75})).unwrap();
|
||||
for format in ["gif", "png8"] {
|
||||
let mut file = |extra: Value| {
|
||||
let p = merge(json!({"format": format, "background": "transparent", "antiAlias": "none"}), extra);
|
||||
b64(&s.execute("document.export", &p).unwrap())
|
||||
};
|
||||
// By default the pixels under half opacity are transparent and the others opaque.
|
||||
let none = file(json!({}));
|
||||
assert_eq!(opaque_halves(&none), [0.0, 1.0], "{format}");
|
||||
assert_eq!(file(json!({"transparencyDither": "none"})), none, "{format}");
|
||||
assert_eq!(file(json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 0})), none, "{format}");
|
||||
for method in ["diffusion", "pattern", "noise"] {
|
||||
let dithered = file(json!({"transparencyDither": method}));
|
||||
let [left, right] = opaque_halves(&dithered);
|
||||
assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}");
|
||||
assert_eq!(file(json!({"transparencyDither": method})), dithered, "{format} {method}: the same art gives the same file");
|
||||
// Without transparency the dither does nothing.
|
||||
let opaque = file(json!({"transparencyDither": method, "transparency": false}));
|
||||
assert_eq!(opaque, file(json!({"transparency": false})), "{format} {method}");
|
||||
}
|
||||
let weaker = opaque_halves(&file(json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 40})));
|
||||
assert!(weaker[0] < 0.25 && weaker[1] > 0.75, "{format}: {weaker:?}");
|
||||
// null is the same as leaving a key out.
|
||||
assert_eq!(file(json!({"transparencyDither": null, "transparencyDitherAmount": null})), none, "{format}");
|
||||
for bad in [
|
||||
json!({"transparencyDither": "spray"}),
|
||||
json!({"transparencyDither": 3}),
|
||||
json!({"transparencyDitherAmount": 101}),
|
||||
json!({"transparencyDitherAmount": -1}),
|
||||
json!({"transparencyDitherAmount": "50"}),
|
||||
json!({"transparencyDitherAmount": 50.5}),
|
||||
] {
|
||||
assert!(s.execute("document.export", &merge(json!({"format": format}), bad.clone())).is_err(), "{format} {bad}");
|
||||
}
|
||||
let e = s.execute("document.export", &json!({"format": format, "transparencyDitherAmount": 101})).unwrap_err().to_string();
|
||||
assert!(e.contains("transparencyDitherAmount must be a whole number from 0 to 100, not 101"), "{e}");
|
||||
let e = s.execute("document.export", &json!({"format": format, "transparencyDither": "spray"})).unwrap_err().to_string();
|
||||
assert!(e.contains("transparencyDither `spray`: none, diffusion, pattern or noise"), "{e}");
|
||||
let e = s.execute("document.export", &json!({"format": format, "transparencyDither": 3})).unwrap_err().to_string();
|
||||
assert!(e.contains("transparencyDither must be none, diffusion, pattern or noise, not 3"), "{e}");
|
||||
}
|
||||
// Formats without a palette do not read the keys: their values are not checked, and the
|
||||
// warnings name them.
|
||||
for format in ["png", "jpg", "tiff"] {
|
||||
for keys in [
|
||||
json!({"transparencyDither": "spray", "transparencyDitherAmount": 101}),
|
||||
json!({"transparencyDither": 3, "transparencyDitherAmount": "50"}),
|
||||
] {
|
||||
let r = s.execute("document.export", &merge(json!({"format": format}), keys.clone()));
|
||||
let w = r.unwrap_or_else(|e| panic!("{format} {keys}: {e}"))["warnings"].to_string();
|
||||
assert!(w.contains("`transparencyDither` was not used") && w.contains("`transparencyDitherAmount` was not used"), "{format}: {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn palette_formats_reach_export_as_and_screens() {
|
||||
let mut s = session();
|
||||
@@ -94,7 +168,9 @@ fn palette_formats_reach_export_as_and_screens() {
|
||||
let f = |id: &str| r["formats"].as_array().unwrap().iter().find(|f| f["id"] == id).unwrap().clone();
|
||||
assert_eq!((f("png8")["extensions"][0].as_str(), f("png8")["read"].as_bool()), (Some("png"), Some(false)));
|
||||
assert_eq!(f("gif")["write"], true);
|
||||
for k in ["colors", "reduction", "dither", "ditherAmount", "transparency", "matte", "interlaced"] {
|
||||
for k in
|
||||
["colors", "reduction", "dither", "ditherAmount", "transparency", "transparencyDither", "transparencyDitherAmount", "matte", "interlaced"]
|
||||
{
|
||||
assert!(f("gif")["options"].get(k).is_some() && f("png8")["options"].get(k).is_some(), "{k}");
|
||||
}
|
||||
assert_eq!(format_for_name("a.png").unwrap().id, "png");
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}",
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {index}",
|
||||
has_doc,
|
||||
add_point
|
||||
),
|
||||
@@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}",
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {index}",
|
||||
has_doc,
|
||||
set_point
|
||||
),
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}",
|
||||
"{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {index}",
|
||||
has_doc,
|
||||
delete_point
|
||||
),
|
||||
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Line",
|
||||
[],
|
||||
None,
|
||||
"{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {line}",
|
||||
"{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {line}",
|
||||
has_doc,
|
||||
add_line
|
||||
),
|
||||
@@ -55,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Split Freeform Line",
|
||||
[],
|
||||
None,
|
||||
"{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}",
|
||||
"{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it; an error while the proxy shows the colors the active tool paints with (the Live Paint Bucket's, the Shape Builder's fill) and no ids, id or item are given → {index}",
|
||||
has_doc,
|
||||
split_line
|
||||
),
|
||||
@@ -64,7 +64,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's; an index is an error while the proxies show the Live Paint Bucket's colors): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}",
|
||||
"{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's; an index is an error while the proxy shows the colors the active tool paints with: the Live Paint Bucket's, the Shape Builder's fill): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}",
|
||||
has_doc,
|
||||
select_point
|
||||
),
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Freeform Gradient",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object (an error while the proxies show the Live Paint Bucket's colors) → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}",
|
||||
"{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object (an error while the proxy shows the colors the active tool paints with: the Live Paint Bucket's, the Shape Builder's fill) → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}",
|
||||
has_doc,
|
||||
get
|
||||
),
|
||||
@@ -81,13 +81,21 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
const NOT_FREEFORM: &str = "the paint is not a freeform gradient (apply one with paint.editGradient {kind: \"freeform\"})";
|
||||
const BUCKET_NOT_FREEFORM: &str = "the Live Paint Bucket's colors have no freeform points (give ids, id or item to edit an object's)";
|
||||
const BUCKET_NO_POINTS: &str = "the Live Paint Bucket's colors have no freeform points";
|
||||
|
||||
/// "<the colors> have no freeform points" for the tool whose colors the fill (or stroke, `stroke`)
|
||||
/// proxy shows ([`Session::painting_tool`]): the Live Paint Bucket's colors, the Shape Builder's
|
||||
/// fill. None when the proxy shows the selection's paint.
|
||||
fn tool_no_points(s: &Session, stroke: bool) -> Option<&'static str> {
|
||||
s.painting_tool(stroke).map(|id| match id {
|
||||
"shapeBuilder" => "the Shape Builder's fill has no freeform points",
|
||||
_ => "the Live Paint Bucket's colors have no freeform points",
|
||||
})
|
||||
}
|
||||
|
||||
/// The error of `paint.freeform.get` and `paint.freeform.selectPoint` when the active proxy shows no freeform gradient:
|
||||
/// while the Live Paint Bucket paints, the proxies show its colors, which have none.
|
||||
fn no_proxy_freeform(s: &Session) -> &'static str {
|
||||
if s.bucket_paints() { BUCKET_NO_POINTS } else { NOT_FREEFORM }
|
||||
/// while the active tool paints with the chosen colors of that kind, the proxy shows them, which have none.
|
||||
fn no_proxy_freeform(s: &Session, stroke: bool) -> &'static str {
|
||||
tool_no_points(s, stroke).unwrap_or(NOT_FREEFORM)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -187,13 +195,16 @@ pub(crate) fn parse_mode(m: &str) -> std::result::Result<FreeformMode, String> {
|
||||
/// as one undo step; returns what it returned for the first. An unplaced gradient gets the
|
||||
/// automatic points it shows first, and the stops follow the points' colours.
|
||||
fn edit<R>(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freeform, Space) -> std::result::Result<R, String>) -> Result<R> {
|
||||
// While the Live Paint Bucket paints, the proxies show its colors, which have no freeform points
|
||||
// (paint.freeform.get finds none): an edit that names no target is refused. A bad `aligned` or
|
||||
// `target` is refused first, as it is without the bucket.
|
||||
if super::paint::for_bucket(s, p) {
|
||||
// While the active tool paints with the chosen colors (the Live Paint Bucket's, the Shape
|
||||
// Builder's fill), the proxy shows them, and they have no freeform points (paint.freeform.get
|
||||
// finds none): an edit that names no target is refused. A bad `aligned`, `target` or `stroke`
|
||||
// is refused first, as it is otherwise.
|
||||
let kind = super::paint::tool_gradient_kind(s, p, cmd)?;
|
||||
if super::paint::for_tool(s, p, kind) {
|
||||
super::appearance::aligned(p, cmd)?;
|
||||
super::appearance::targets_contents(p)?;
|
||||
return Err(bad(cmd, BUCKET_NOT_FREEFORM));
|
||||
let none = tool_no_points(s, kind).unwrap_or(NOT_FREEFORM);
|
||||
return Err(bad(cmd, format!("{none} (give ids, id or item to edit an object's)")));
|
||||
}
|
||||
let item = item_target(s, p, cmd)?;
|
||||
let stroke = edits_stroke(s, p, item, !s.fill_active, cmd)?;
|
||||
@@ -347,7 +358,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`index` must be a whole number or null"))?;
|
||||
let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, no_proxy_freeform(s)))?;
|
||||
let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, no_proxy_freeform(s, !s.fill_active)))?;
|
||||
check_index(&f, i).map_err(|e| bad(C, e))?;
|
||||
Some(i)
|
||||
}
|
||||
@@ -359,7 +370,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "paint.freeform.get";
|
||||
let stroke = switch_or(p, "stroke", !s.fill_active, C)?;
|
||||
let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, no_proxy_freeform(s)))?;
|
||||
let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, no_proxy_freeform(s, stroke)))?;
|
||||
let selected = if stroke != s.fill_active { s.selected_freeform_point().filter(|i| *i < f.points.len()) } else { None };
|
||||
let mut v = vectorcraft_tools::params::freeform_json(&f);
|
||||
v["selected"] = json!(selected);
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
["Window", "Gradient"],
|
||||
None,
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, defaultsOnly?: bool (as paint.setFill), strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucke
Line truncated
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, the Shape Builder's fill, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, defaultsOnly?: bool (as paint.setFill), strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label.
Line truncated
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select Gradient Stop",
|
||||
[],
|
||||
None,
|
||||
"{index: stop index (0 = the start) | null to clear} select a stop of the gradient behind the active proxy (the first selected object's, else the default paint; the default paint's while the Live Paint Bucket is the active tool): the stop the Gradient tool's annotator, the Gradient and Color panels and Delete/arrow keys act on; refused while an object of a symbol instance's art is selected, except while the Live Paint Bucket is the active tool → {index}",
|
||||
"{index: stop index (0 = the start) | null to clear} select a stop of the gradient behind the active proxy (the first selected object's, else the default paint; the default paint's while the Live Paint Bucket, or with the Fill proxy in front the Shape Builder, is the active tool): the stop the Gradient tool's annotator, the Gradient and Color panels and Delete/arrow keys act on; refused while an object of a symbol instance's art is selected, except while the proxy in front shows the default paint that way → {index}",
|
||||
always,
|
||||
select_stop
|
||||
),
|
||||
@@ -61,9 +61,9 @@ pub(crate) fn active_gradient(s: &Session) -> Option<GradientPaint> {
|
||||
fn select_stop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "gradient.selectStop";
|
||||
// No document is needed for the default paint's gradient, so this does not use `refuse_symbol_part`.
|
||||
// While the Live Paint Bucket is active the proxies show the default paint, whose stops can be
|
||||
// selected with a part picked.
|
||||
if !s.bucket_paints() && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) {
|
||||
// While the Live Paint Bucket is active the proxies show the default paint (the Shape Builder's
|
||||
// Fill proxy does too), whose stops can be selected with a part picked.
|
||||
if !s.tool_paints(!s.fill_active) && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) {
|
||||
return Err(super::brushsym::part_only());
|
||||
}
|
||||
let index = match p.get("index") {
|
||||
@@ -84,13 +84,15 @@ fn select_stop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// Whose gradient a selected stop belongs to: the active document, its first selected object
|
||||
/// (None: the default paint), whether a part of a symbol instance's art is picked, the proxy in
|
||||
/// front, the Appearance panel's active item and whether the Live Paint Bucket is the active tool
|
||||
/// (its proxies show the default paint). Selecting other art, picking a part of the instance,
|
||||
/// toggling the proxy, picking another item or choosing the bucket or leaving it leaves no stop
|
||||
/// selected.
|
||||
/// front, the Appearance panel's active item and the tool the proxy in front shows the default
|
||||
/// paint for (the Live Paint Bucket, or the Shape Builder's Fill proxy). Selecting other art,
|
||||
/// picking a part of the instance, toggling the proxy, picking another item or choosing such a
|
||||
/// tool or leaving it leaves no stop selected. The Gradient panel keys its selected midpoint
|
||||
/// diamond by it as well ([`Session::gradient_owner`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct StopOwner {
|
||||
doc: Option<usize>,
|
||||
pub struct StopOwner {
|
||||
/// The active document's uid, which stays the same when its tab moves.
|
||||
doc: Option<u64>,
|
||||
object: Option<NodeId>,
|
||||
/// The object whose paint the active proxy shows: a Live Paint group without faces (or edges)
|
||||
/// first in the selection shows the next object's.
|
||||
@@ -98,32 +100,38 @@ pub(crate) struct StopOwner {
|
||||
part: bool,
|
||||
fill: bool,
|
||||
item: Option<usize>,
|
||||
bucket: bool,
|
||||
/// The tool whose color the proxy in front stood for ([`Session::painting_tool`]).
|
||||
painter: Option<&'static str>,
|
||||
}
|
||||
|
||||
impl StopOwner {
|
||||
pub(crate) fn of(s: &Session) -> Self {
|
||||
let st = s.active();
|
||||
Self {
|
||||
doc: s.active,
|
||||
doc: st.map(|d| d.uid),
|
||||
object: st.and_then(|d| d.selection.objects.first().copied()),
|
||||
source: s.proxy_source(!s.fill_active).map(|(n, _)| n.id),
|
||||
part: st.is_some_and(|d| d.selection.symbol_part.is_some()),
|
||||
fill: s.fill_active,
|
||||
item: s.appearance_item(),
|
||||
bucket: s.bucket_paints(),
|
||||
painter: s.painting_tool(!s.fill_active),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool whose gradient the stop is on; None for the selection's paint.
|
||||
pub(crate) fn painter(&self) -> Option<&'static str> {
|
||||
self.painter
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Does `paint.editGradient` without `ids` edit objects on the fill (or the stroke, `stroke`)? It does not
|
||||
/// while the Live Paint Bucket is active or when nothing it can paint is selected (a Live Paint group stands
|
||||
/// only for its faces in a fill edit and its edges in a stroke edit): it then edits no object and takes no
|
||||
/// `aspect`.
|
||||
/// while the active tool paints with the chosen fill (or stroke: [`Session::tool_paints`]) or when nothing it
|
||||
/// can paint is selected (a Live Paint group stands only for its faces in a fill edit and its edges in a stroke
|
||||
/// edit): it then edits no object and takes no `aspect`.
|
||||
pub fn gradient_edit_has_objects(&self, stroke: bool) -> bool {
|
||||
let p = json!({ "stroke": stroke });
|
||||
!super::paint::for_bucket(self, &p)
|
||||
!super::paint::for_tool(self, &p, stroke)
|
||||
&& item_target(self, &p, "paint.editGradient")
|
||||
.is_ok_and(|item| item.of_kind(self, !stroke).targets_for(self, &p, !stroke).is_ok_and(|ids| !ids.is_empty()))
|
||||
}
|
||||
@@ -134,6 +142,11 @@ impl Session {
|
||||
pub fn selected_stop(&self) -> Option<usize> {
|
||||
self.gradient_stop.filter(|(_, owner)| *owner == StopOwner::of(self)).map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// Whose gradient the active proxy shows now, as a selected stop keeps it ([`StopOwner`]).
|
||||
pub fn gradient_owner(&self) -> StopOwner {
|
||||
StopOwner::of(self)
|
||||
}
|
||||
}
|
||||
|
||||
type Parsed<T> = std::result::Result<T, String>;
|
||||
@@ -526,9 +539,10 @@ fn apply_gradient_edit_in_model(
|
||||
if let Some(b) = bounds {
|
||||
gp.seed_freeform(b, if switched { inside } else { &|_| true });
|
||||
}
|
||||
// Without points (the default gradient's, placed on no object yet) the stops are the colors.
|
||||
if recolor
|
||||
&& !switched
|
||||
&& let Some(f) = &mut gp.freeform
|
||||
&& let Some(f) = gp.freeform.as_mut().filter(|f| !f.points.is_empty())
|
||||
{
|
||||
f.recolor(&gp.gradient);
|
||||
gp.gradient.stops = f.stops();
|
||||
@@ -546,9 +560,10 @@ fn apply_gradient_edit_in_model(
|
||||
|
||||
fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "paint.editGradient";
|
||||
// While the Live Paint Bucket is active, the gradient it paints with changes; the selection keeps its own.
|
||||
let bucket = super::paint::bucket_color_params(s, p, C)?;
|
||||
let p = bucket.as_ref().unwrap_or(p);
|
||||
// While the active tool paints with the chosen fill or stroke, the gradient it paints with changes; the
|
||||
// selection keeps its own.
|
||||
let for_tool = super::paint::tool_gradient_params(s, p, C)?;
|
||||
let p = for_tool.as_ref().unwrap_or(p);
|
||||
let item = item_target(s, p, C)?;
|
||||
let stroke = edits_stroke(s, p, item, !s.fill_active, C)?;
|
||||
check_switches(p, &["reverse", "dither"], C)?;
|
||||
@@ -649,7 +664,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
if let Some(m) = mode
|
||||
&& !selected
|
||||
&& (bucket.is_some() || p.get("ids").is_none())
|
||||
&& (for_tool.is_some() || p.get("ids").is_none())
|
||||
&& let Some(st) = s.new_art_stroke_mut()
|
||||
{
|
||||
st.gradient_mode = m;
|
||||
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Apply Gradient Preset",
|
||||
[],
|
||||
None,
|
||||
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, defaultsOnly?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}",
|
||||
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, defaultsOnly?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -207,10 +207,10 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "gradient.presets.apply";
|
||||
let name = name_param(p, C)?;
|
||||
let preset = s.gradient_preset(name).ok_or_else(|| bad(C, format!("no gradient preset `{name}` (see gradient.presets.list)")))?;
|
||||
// While the Live Paint Bucket is active, the gradient it paints with changes, chosen by the
|
||||
// active proxy rather than the selection's Appearance row (as paint.editGradient chooses).
|
||||
let bucket = super::paint::bucket_color_params(s, p, C)?;
|
||||
let p = bucket.as_ref().unwrap_or(p);
|
||||
// While the active tool paints with the chosen fill or stroke, the gradient it paints with
|
||||
// changes (as paint.editGradient chooses).
|
||||
let for_tool = super::paint::tool_gradient_params(s, p, C)?;
|
||||
let p = for_tool.as_ref().unwrap_or(p);
|
||||
let stroke = edits_stroke(s, p, item_target(s, p, C)?, !s.fill_active, C)?;
|
||||
let g = &preset.gradient;
|
||||
let mut edit = p.clone();
|
||||
|
||||
@@ -66,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Current Layer",
|
||||
[],
|
||||
None,
|
||||
"{id} click a row: it alone is highlighted, and the layer it is (or the layer it is in) becomes the current layer, where new art goes. Not an undo step → {id, layer}",
|
||||
"{id, keepRows?: bool} click a row: it alone is highlighted, and the layer it is (or the layer it is in) becomes the current layer, where new art goes. `keepRows` true leaves the highlighted rows as they are. Not an undo step → {id, layer}",
|
||||
has_doc,
|
||||
set_current
|
||||
),
|
||||
@@ -102,10 +102,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select Art",
|
||||
[],
|
||||
None,
|
||||
"{id, add?: bool} the Layers panel's selection column: select the visible, unlocked art of a layer (its sublayers' too), or the object itself; `add` (Shift-click) adds it to the selection, or removes it when it is all selected already → {selected: [..]}",
|
||||
"{id, add?: bool} or {range: [id…], add?: bool} the Layers panel's selection column: select the visible, unlocked art of a layer (its sublayers' too), or the object itself; `add` (Shift-click with no square clicked before, or Ctrl/Cmd-click) adds it to the selection, or removes it when it is all selected already. `range` (Shift-click, the rows from the last square clicked to this one): the art of every listed row that is visible, unlocked and inside the isolated art is selected, or added to the selection with `add` (Shift+Ctrl/Cmd-click); a range with no such row is an error. Not an undo step; the highlighted rows stay → {selected: [..]} (with `range`: {range, selected})",
|
||||
has_doc,
|
||||
select_art
|
||||
),
|
||||
cmd!(
|
||||
"layer.selectHighlighted",
|
||||
"Select Art of Highlighted Rows",
|
||||
[],
|
||||
None,
|
||||
"{add?: bool} select the art of the Layers panel's highlighted rows, as clicking each row's selection square does: a layer's or sublayer's visible, unlocked art (its sublayers' too), or the group or object itself; hidden and locked rows and rows outside the isolated art are left out. `add` adds the art to the selection. No highlighted row, or none that is visible and unlocked, is an error. Not an undo step; the highlighted rows stay → {rows, selected: [..]}",
|
||||
has_doc,
|
||||
select_highlighted
|
||||
),
|
||||
cmd!(
|
||||
"layer.move",
|
||||
"Move Rows",
|
||||
@@ -633,10 +642,13 @@ fn duplicate_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn set_current(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "layer.setCurrent";
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let keep_rows = switch_or(p, "keepRows", false, C)?;
|
||||
let st = s.doc_mut()?;
|
||||
let layer = st.doc.layer_containing(id).ok_or(EngineError::NoNode(id))?;
|
||||
st.active_layer = Some(layer);
|
||||
st.layer_rows = vec![id];
|
||||
if !keep_rows {
|
||||
st.layer_rows = vec![id];
|
||||
}
|
||||
st.revision += 1;
|
||||
Ok(json!({ "id": id.0, "layer": layer.0 }))
|
||||
}
|
||||
@@ -753,6 +765,11 @@ fn in_isolation(doc: &Document, isolation: Option<NodeId>, id: NodeId) -> bool {
|
||||
/// The selection column: select a row's art.
|
||||
fn select_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "layer.selectAll";
|
||||
if let Some(ids) = ids_param(p, "range", C)? {
|
||||
let add = switch_or(p, "add", false, C)?;
|
||||
let (range, selected) = select_rows_art(s, ids, add, C, "no row in the range is visible, unlocked and inside the isolated art")?;
|
||||
return Ok(json!({ "range": range, "selected": selected }));
|
||||
}
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let add = switch_or(p, "add", false, C)?;
|
||||
let st = s.doc()?;
|
||||
@@ -789,6 +806,51 @@ fn select_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "selected": st.selection.objects.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// Select Art of Highlighted Rows: the art of the highlighted rows, as their selection squares
|
||||
/// select it.
|
||||
fn select_highlighted(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "layer.selectHighlighted";
|
||||
let add = switch_or(p, "add", false, C)?;
|
||||
let rows = s.doc()?.highlighted_rows();
|
||||
if rows.is_empty() {
|
||||
return Err(bad(C, "no row is highlighted"));
|
||||
}
|
||||
let (rows, selected) = select_rows_art(s, rows, add, C, "no highlighted row is visible, unlocked and inside the isolated art")?;
|
||||
Ok(json!({ "rows": rows, "selected": selected }))
|
||||
}
|
||||
|
||||
/// Selects the art of the Layers panel rows `ids` (at most [`MAX_ROWS`]), or adds it to the
|
||||
/// selection with `add`: each row that is visible, unlocked and inside the isolated art (or is the
|
||||
/// isolated layer) gives what its selection square selects, a layer's visible, unlocked art (its
|
||||
/// sublayers' too) or the group or object itself, as [`Selection::target_range`] gathers it for a
|
||||
/// range of target circles. Nothing is targeted and the highlighted rows stay. Without such a row it
|
||||
/// is the error `none`. Returns the rows used and the selected objects.
|
||||
///
|
||||
/// [`Selection::target_range`]: vectorcraft_doc::Selection::target_range
|
||||
fn select_rows_art(s: &mut Session, mut ids: Vec<NodeId>, add: bool, c: &str, none: &str) -> Result<(Vec<u64>, Vec<u64>)> {
|
||||
ids.truncate(MAX_ROWS);
|
||||
let rows = {
|
||||
let st = s.doc()?;
|
||||
// Measures the locked artboards once for every row, not once per row.
|
||||
let editable = st.doc.editable();
|
||||
ids.retain(|id| {
|
||||
st.doc.node(*id).is_some_and(|n| {
|
||||
let isolated_layer = st.isolation == Some(*id) && n.is_layer();
|
||||
!n.is_ruler_guide() && editable(*id) && (isolated_layer || in_isolation(&st.doc, st.isolation, *id))
|
||||
})
|
||||
});
|
||||
st.layer_rows.clone()
|
||||
};
|
||||
if ids.is_empty() {
|
||||
return Err(bad(c, none));
|
||||
}
|
||||
s.select(|d, sel| sel.target_range(d, &ids, add))?;
|
||||
let st = s.doc_mut()?;
|
||||
// The selection column leaves the highlighted rows as they are.
|
||||
st.layer_rows = rows;
|
||||
Ok((ids.iter().map(|i| i.0).collect(), st.selection.objects.iter().map(|i| i.0).collect()))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Place {
|
||||
Above,
|
||||
|
||||
@@ -1247,7 +1247,7 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Kind::FillColor | Kind::StrokeColor => {
|
||||
let stroke = to_stroke(p, kind)?;
|
||||
let only = super::paint::defaults_only(s, p, C)?;
|
||||
let only = super::paint::defaults_only(s, p, C, stroke)?;
|
||||
let color = data.get("color").cloned().ok_or_else(|| bad(C, "no colour"))?;
|
||||
let set = if stroke { "paint.setStroke" } else { "paint.setFill" };
|
||||
match str_param(&data, "spot").map(str::trim).filter(|n| !n.is_empty()) {
|
||||
@@ -1260,7 +1260,7 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Kind::FillGradient | Kind::StrokeGradient => {
|
||||
let stroke = to_stroke(p, kind)?;
|
||||
let only = super::paint::defaults_only(s, p, C)?;
|
||||
let only = super::paint::defaults_only(s, p, C, stroke)?;
|
||||
let damaged = || bad(C, "the library item is damaged");
|
||||
let mut g: GradientPaint = data.get("gradient").cloned().and_then(|v| serde_json::from_value(v).ok()).ok_or_else(damaged)?;
|
||||
if !clean_gradient(&mut g) {
|
||||
@@ -1275,7 +1275,7 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Kind::FillPattern | Kind::StrokePattern => {
|
||||
let stroke = to_stroke(p, kind)?;
|
||||
let only = super::paint::defaults_only(s, p, C)?;
|
||||
let only = super::paint::defaults_only(s, p, C, stroke)?;
|
||||
let pattern = use_pattern(s, &data, stroke, only)?;
|
||||
Ok(json!({ "kind": if stroke { "strokePattern" } else { "fillPattern" }, "pattern": pattern }))
|
||||
}
|
||||
|
||||
@@ -224,9 +224,11 @@ impl Session {
|
||||
/// the first selected object (so the last selection's once nothing is selected). Not while the
|
||||
/// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with. Nor
|
||||
/// after a command that changed only them (`defaultsOnly`), unless a later step of a batch
|
||||
/// changed what new art would take ([`Session::new_art_source`]).
|
||||
/// changed what new art would take ([`Session::new_art_source`]). While the Shape Builder is
|
||||
/// active, the fill it paints with stays ([`Session::tool_paints`]).
|
||||
pub(crate) fn inherit_new_art(&mut self) {
|
||||
if self.prefs.new_art_basic || self.bucket_paints() {
|
||||
let (fill, stroke) = (self.tool_paints(false), self.tool_paints(true));
|
||||
if self.prefs.new_art_basic || (fill && stroke) {
|
||||
return;
|
||||
}
|
||||
let Some(source) = self.new_art_source() else { return };
|
||||
@@ -234,7 +236,20 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
let NewArtSource { appearance, opacity, blend, style, .. } = source;
|
||||
let kept_fill = fill.then(|| self.paint.fill.clone());
|
||||
let kept_stroke = stroke.then(|| (self.paint.stroke.clone(), self.paint.stroke_width));
|
||||
self.take_new_art(appearance, opacity, blend, style, true);
|
||||
let p = &mut self.paint;
|
||||
// New art whose kept paint differs from the selection's is not linked to its graphic style.
|
||||
if kept_fill.as_ref().is_some_and(|f| *f != p.fill) || kept_stroke.as_ref().is_some_and(|(s, w)| *s != p.stroke || *w != p.stroke_width) {
|
||||
p.style = None;
|
||||
}
|
||||
if let Some(f) = kept_fill {
|
||||
p.fill = f;
|
||||
}
|
||||
if let Some((s, w)) = kept_stroke {
|
||||
(p.stroke, p.stroke_width) = (s, w);
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`Session::inherit_new_art`] gives new art: the appearance of the active document's
|
||||
@@ -275,13 +290,14 @@ impl Session {
|
||||
let (fill, stroke) = self.proxy_paints();
|
||||
let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed);
|
||||
let weight = self.shown_stroke().filter(|st| st.paint != Paint::None && !weight_mixed).map(|st| st.width);
|
||||
if !fill_mixed {
|
||||
// A proxy that shows the color the active tool paints with (the Shape Builder's fill) keeps it.
|
||||
if !fill_mixed && !self.tool_paints(false) {
|
||||
self.paint.fill = unplaced(&fill);
|
||||
}
|
||||
if !stroke_mixed {
|
||||
if !stroke_mixed && !self.tool_paints(true) {
|
||||
self.paint.stroke = unplaced(&stroke);
|
||||
}
|
||||
if let Some(width) = weight {
|
||||
if let Some(width) = weight.filter(|_| !self.tool_paints(true)) {
|
||||
self.paint.stroke_width = width;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Document Presets",
|
||||
[],
|
||||
None,
|
||||
"{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode, alignNewObjectsToPixelGrid (on in the Mobile and Web presets)}]}]}; file.new {preset: name} starts from one",
|
||||
"{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, rows? (a grid by column made with rows), spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode, alignNewObjectsToPixelGrid (on in the Mobile and Web presets)}]}]}; file.new {preset: name} starts from one",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -146,6 +146,11 @@ fn de_ppi<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<f64, D:
|
||||
Ok(Some(f64::deserialize(d)?).filter(|v| v.is_finite()).unwrap_or(72.0).clamp(1.0, 2400.0))
|
||||
}
|
||||
|
||||
#[allow(clippy::trivially_copy_pass_by_ref)]
|
||||
fn is_zero(n: &u32) -> bool {
|
||||
*n == 0
|
||||
}
|
||||
|
||||
/// Everything New Document sets: a preset (built-in, saved or recent) or `file.new`'s params.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -166,6 +171,9 @@ pub struct DocSettings {
|
||||
pub layout: ArtboardLayout,
|
||||
/// Columns of a grid layout.
|
||||
pub columns: u32,
|
||||
/// Rows of a grid by column, in place of `columns` when more than 0.
|
||||
#[serde(skip_serializing_if = "is_zero")]
|
||||
pub rows: u32,
|
||||
/// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value
|
||||
/// outside that range is read as the nearer end).
|
||||
#[serde(deserialize_with = "de_spacing")]
|
||||
@@ -203,6 +211,7 @@ impl Default for DocSettings {
|
||||
artboards: 1,
|
||||
layout: ArtboardLayout::GridByRow,
|
||||
columns: 0,
|
||||
rows: 0,
|
||||
spacing: 20.0,
|
||||
right_to_left: false,
|
||||
bleed: [0.0; 4],
|
||||
@@ -222,9 +231,17 @@ pub const MAX_ARTBOARDS: u32 = 1000;
|
||||
pub const RASTER_PPI: [(f64, &str); 3] = [(72.0, "Screen (72 ppi)"), (150.0, "Medium (150 ppi)"), (300.0, "High (300 ppi)")];
|
||||
|
||||
impl DocSettings {
|
||||
/// The rows a grid by column with `rows` uses, at most one for each artboard.
|
||||
fn grid_rows(&self) -> Option<usize> {
|
||||
(self.layout == ArtboardLayout::GridByColumn && self.rows > 0).then(|| (self.rows as usize).min(self.artboards.max(1) as usize))
|
||||
}
|
||||
|
||||
/// The columns a grid actually uses (0 or more than the artboards: one row).
|
||||
pub fn grid_columns(&self) -> usize {
|
||||
let n = self.artboards.max(1) as usize;
|
||||
if let Some(rows) = self.grid_rows() {
|
||||
return n.div_ceil(rows);
|
||||
}
|
||||
match self.layout {
|
||||
ArtboardLayout::Row => n,
|
||||
ArtboardLayout::Column => 1,
|
||||
@@ -246,6 +263,12 @@ impl DocSettings {
|
||||
|
||||
/// As `file.newPresets` lists it (and `file.new` takes it back).
|
||||
pub fn to_json(&self) -> Value {
|
||||
let mut layout =
|
||||
json!({"layout": self.layout.id(), "columns": self.grid_columns(), "spacing": self.spacing, "rightToLeft": self.right_to_left});
|
||||
// The rows as set, also when there are fewer artboards than rows.
|
||||
if let Some(o) = layout.as_object_mut().filter(|_| self.grid_rows().is_some()) {
|
||||
o.insert("rows".into(), json!(self.rows));
|
||||
}
|
||||
json!({
|
||||
"name": self.name,
|
||||
"size": self.size_label(),
|
||||
@@ -254,7 +277,7 @@ impl DocSettings {
|
||||
"units": self.units.label(),
|
||||
"orientation": self.orientation(),
|
||||
"artboards": self.artboards,
|
||||
"artboardLayout": {"layout": self.layout.id(), "columns": self.grid_columns(), "spacing": self.spacing, "rightToLeft": self.right_to_left},
|
||||
"artboardLayout": layout,
|
||||
"bleed": self.bleed,
|
||||
"backgroundContents": self.background.id(),
|
||||
"colorMode": color_mode_id(self.color_mode),
|
||||
@@ -337,25 +360,23 @@ impl DocSettings {
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// `artboardLayout: {layout?, columns?, spacing?, rightToLeft?}` or just a layout id.
|
||||
/// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id.
|
||||
fn layout_params(&mut self, l: &Value, cmd: &str) -> Result<()> {
|
||||
let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column");
|
||||
if let Some(id) = l.as_str() {
|
||||
self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?;
|
||||
if self.layout != ArtboardLayout::GridByColumn {
|
||||
self.rows = 0;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?;
|
||||
let count = |v: &Value| v.as_f64().filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u32);
|
||||
for (k, v) in o {
|
||||
match k.as_str() {
|
||||
"layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?,
|
||||
"columns" => {
|
||||
self.columns = v
|
||||
.as_f64()
|
||||
.filter(|c| c.is_finite() && *c >= 1.0)
|
||||
.ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?
|
||||
.round()
|
||||
.min(MAX_ARTBOARDS as f64) as u32
|
||||
}
|
||||
"columns" => self.columns = count(v).ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?,
|
||||
"rows" => self.rows = count(v).ok_or_else(|| bad(cmd, "artboardLayout.rows must be 1 or more"))?,
|
||||
"spacing" => {
|
||||
self.spacing = v
|
||||
.as_f64()
|
||||
@@ -366,18 +387,30 @@ impl DocSettings {
|
||||
_ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft)"))),
|
||||
}
|
||||
}
|
||||
if o.contains_key("rows") && self.layout != ArtboardLayout::GridByColumn {
|
||||
return Err(bad(cmd, "artboardLayout.rows needs the gridByColumn layout"));
|
||||
}
|
||||
// Columns without rows, or another layout, replace a preset's rows.
|
||||
if (o.contains_key("columns") && !o.contains_key("rows")) || self.layout != ArtboardLayout::GridByColumn {
|
||||
self.rows = 0;
|
||||
}
|
||||
if self.grid_rows().is_some() {
|
||||
self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The artboard rectangles, the first at the origin's side.
|
||||
/// The artboard rectangles, the first at the origin's side. A grid by column with `rows` has
|
||||
/// that many rows (at most one for each artboard).
|
||||
pub fn boards(&self) -> Vec<Rect> {
|
||||
let n = self.artboards.max(1) as usize;
|
||||
let sizes = vec![(self.width, self.height); n];
|
||||
let by_column = self.layout == ArtboardLayout::GridByColumn;
|
||||
grid_origins(&sizes, Point::ZERO, self.grid_columns(), self.spacing, by_column, self.right_to_left)
|
||||
.into_iter()
|
||||
.map(|o| Rect::from_origin_size(o, (self.width, self.height)))
|
||||
.collect()
|
||||
let origins = match self.grid_rows() {
|
||||
Some(rows) => grid_origins_rc(&sizes, Point::ZERO, (rows, n.div_ceil(rows)), self.spacing, true, self.right_to_left),
|
||||
None => grid_origins(&sizes, Point::ZERO, self.grid_columns(), self.spacing, by_column, self.right_to_left),
|
||||
};
|
||||
origins.into_iter().map(|o| Rect::from_origin_size(o, (self.width, self.height))).collect()
|
||||
}
|
||||
|
||||
/// The new document (title and swatches set by `file.new`).
|
||||
@@ -528,7 +561,7 @@ pub(crate) fn side_error(cmd: &str, units: Unit) -> crate::EngineError {
|
||||
bad(cmd, format!("width and height must be more than 0 and at most {limit}"))
|
||||
}
|
||||
/// Largest artboard spacing, points.
|
||||
const MAX_SPACING: f64 = 1.0e5;
|
||||
pub(crate) const MAX_SPACING: f64 = 1.0e5;
|
||||
|
||||
pub fn color_mode_id(m: ColorMode) -> &'static str {
|
||||
match m {
|
||||
@@ -968,20 +1001,29 @@ impl Session {
|
||||
|
||||
/// Profile `name`'s document, its file's path and a warning for each color profile the file
|
||||
/// carries that can't be used: `None` when it has no file (the shipped profile, the defaults),
|
||||
/// the reason when the request being served may not read it, or its file can't be read, is
|
||||
/// larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft reads.
|
||||
/// the reason when the request being served may not read it, or its file is a link or a folder,
|
||||
/// can't be read, is larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft
|
||||
/// reads.
|
||||
fn read_profile(&self, name: &str) -> std::result::Result<Option<ReadProfile>, String> {
|
||||
let Some(path) = self.profile_path(name) else { return Ok(None) };
|
||||
let file = path.to_string_lossy().to_string();
|
||||
// Checked before the file is looked for, so a request that may not read the folder learns
|
||||
// nothing of its files, nor where the folder is.
|
||||
// A script's gate does not apply to reads of the app's own folder; the automation roots in
|
||||
// force still do.
|
||||
let denied = |_| PROFILE_DENIED.to_string();
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) {
|
||||
return Ok(None);
|
||||
}
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?;
|
||||
let read = crate::file_access::app_folder_read(|| {
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
// A link is refused: the script's gate does not check where it leads.
|
||||
Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()),
|
||||
_ => {}
|
||||
}
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some)
|
||||
})?;
|
||||
let Some(bytes) = read else { return Ok(None) };
|
||||
// The color profiles the file carries are installed where missing, as opening it installs
|
||||
// them, so the new document's assigned profiles draw and are saved with it.
|
||||
let (mut doc, _, mut warnings) = super::fileio::decode_native_file(&bytes).map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -34,8 +34,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rotate…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), angle: deg (counter-clockwise), absolute?: bool (angle is the bounding box's new angle, not an amount), origin?: [x,y] (default: the bounding box centre), copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)} → {ids}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
has_selection,
|
||||
"{ids?: [id…] (selected first; default: the selection), angle: deg (counter-clockwise), absolute?: bool (angle is the bounding box's new angle, not an amount), origin?: [x,y] (default: the bounding box centre), copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)} → {ids}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box. Selected ruler guides that can be edited rotate too (without ids), each as the line view.guides.release makes of it, and the default origin is the center of the objects' box and those lines together: a guide that ends up vertical or horizontal stays a ruler guide, and one at any other angle becomes a selected guide path along its line. absolute with only ruler guides selected is an error.",
|
||||
has_selection_or_guides,
|
||||
rotate
|
||||
),
|
||||
cmd!(
|
||||
@@ -71,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
["Object", "Transform"],
|
||||
Some("Cmd+D"),
|
||||
"{copy?, strokes?, corners?, patterns?, typeAreas?, interpolate?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)",
|
||||
has_selection,
|
||||
has_selection_or_guides,
|
||||
transform_again
|
||||
),
|
||||
cmd!(
|
||||
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Shape Properties",
|
||||
[],
|
||||
None,
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
has_selection,
|
||||
set_live_shape
|
||||
),
|
||||
|
||||
@@ -99,6 +99,12 @@ fn corners_param(p: &Value) -> Result<Option<BTreeSet<usize>>> {
|
||||
list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::<Result<_>>().map(Some)
|
||||
}
|
||||
|
||||
/// Whether `relativeRadii` applies to a path with live shape `live`: a live rectangle, a live
|
||||
/// polygon or a path with Live Corners. A plain path, an ellipse and a line stay as they are.
|
||||
fn takes_rounding(live: Option<&LiveShape>) -> bool {
|
||||
matches!(live, Some(LiveShape::Rectangle { .. } | LiveShape::Polygon { .. } | LiveShape::Path { .. }))
|
||||
}
|
||||
|
||||
/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about
|
||||
/// its midpoint; a line whose ends meet has none to turn), or None when neither changes it.
|
||||
fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<LiveShape> {
|
||||
@@ -277,7 +283,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(l @ LiveShape::Rectangle { .. }) if rectangle_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => return false,
|
||||
_ => {}
|
||||
}
|
||||
if relative_radii.is_some_and(|on| live.as_deref().map(|l| l.radii_relative()) != Some(on)) {
|
||||
if relative_radii.is_some_and(|on| takes_rounding(live.as_deref()) && live.as_deref().is_some_and(LiveShape::radii_relative) != on) {
|
||||
return false;
|
||||
}
|
||||
if radius.is_none() && kind.is_none() {
|
||||
@@ -291,10 +297,17 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& picked.iter().all(|k| {
|
||||
*k < c.base.anchor_count()
|
||||
// A radius stored in document units can be larger than it draws; a relative
|
||||
// one is a fraction, so it is compared as drawn.
|
||||
// one is compared as the fraction `set_corners` would store for it, to a
|
||||
// precision of 1e-9 pt on a corner whose maximum is 1 pt or more.
|
||||
&& radius.is_none_or(|r| {
|
||||
let now = if c.radii_relative() { c.drawn_radius(*k) } else { c.radius(*k) };
|
||||
(now - r.max(0.0)).abs() < 1e-9
|
||||
let r = r.max(0.0);
|
||||
if c.radii_relative() {
|
||||
let max = c.corner(*k).map_or(0.0, |c| c.max_radius());
|
||||
let fraction = if max > 1e-12 { (r / max).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(c.radius(*k) - fraction).abs() * max.max(1.0) < 1e-9
|
||||
} else {
|
||||
(c.radius(*k) - r).abs() < 1e-9
|
||||
}
|
||||
})
|
||||
&& kind.is_none_or(|kd| c.kind(*k) == kd)
|
||||
})
|
||||
|
||||
@@ -16,7 +16,27 @@ fn origin_of(s: &Session, p: &Value, ids: &[NodeId]) -> Result<Point> {
|
||||
{
|
||||
return Ok(b.center());
|
||||
}
|
||||
s.transform_box(ids).map(|b| b.center()).ok_or_else(|| EngineError::Other("selection has no bounds".into()))
|
||||
// Selected ruler guides transform with the selection (not with objects named by `ids`, nor
|
||||
// with Transform Objects off), so the center is that of the objects' box and the guides'
|
||||
// lines together.
|
||||
let guides = if p.get("ids").is_none_or(Value::is_null) && transforms_objects(p) { editable_guides(s)? } else { vec![] };
|
||||
let boxed = s.transform_box(ids);
|
||||
if guides.is_empty() {
|
||||
return boxed.map(|b| b.center()).ok_or_else(|| EngineError::Other("selection has no bounds".into()));
|
||||
}
|
||||
let objects = boxed.map(|b| {
|
||||
let c = b.corners();
|
||||
c.iter().fold(Rect::from_points(c[0], c[0]), |r, p| r.union_pt(*p))
|
||||
});
|
||||
let lines = guides.into_iter().filter_map(|g| st.doc.guide_line(&g)).map(|(a, b)| Rect::from_points(a, b));
|
||||
let b = lines.fold(objects, |acc, r| Some(acc.map_or(r, |acc| acc.union(r))));
|
||||
b.map(|b| b.center()).ok_or_else(|| EngineError::Other("selection has no bounds".into()))
|
||||
}
|
||||
|
||||
/// The selected ruler guides that a transform changes: those that can be edited.
|
||||
fn editable_guides(s: &Session) -> Result<Vec<vectorcraft_doc::Guide>> {
|
||||
let st = s.doc()?;
|
||||
Ok(st.selection.guides.iter().filter_map(|id| st.doc.ruler_guide(*id)).filter(|g| st.doc.guide_editable(g)).collect())
|
||||
}
|
||||
|
||||
/// What a transform command scales besides geometry: Scale Strokes & Effects and Scale Corners from
|
||||
@@ -125,8 +145,18 @@ fn apply_transform_moving_guides(
|
||||
let c = xf.as_coeffs();
|
||||
let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9;
|
||||
let delta = guides.unwrap_or(Vec2::new(c[4], c[5]));
|
||||
let with_guides = objects && p.get("ids").is_none_or(Value::is_null) && is_translation;
|
||||
let has_guides = with_guides && !s.doc()?.selection.guides.is_empty();
|
||||
// The selected ruler guides transform with the selection: a move moves them, and any other
|
||||
// transform maps the line each one stands for ([`Document::transform_ruler_guides`]).
|
||||
let with_guides = objects && p.get("ids").is_none_or(Value::is_null);
|
||||
// A transform that leaves every guide where it is (a scale of a guide along its own line)
|
||||
// changes no guide; with a copy, the guides are copied all the same.
|
||||
let has_guides = with_guides && {
|
||||
let d = &s.doc()?.doc;
|
||||
let same = |g: &vectorcraft_doc::Guide| {
|
||||
d.transformed_guide(g, xf) == Some(vectorcraft_doc::GuideTransform::Ruler { vertical: g.vertical, pos: g.pos })
|
||||
};
|
||||
editable_guides(s)?.iter().any(|g| is_translation || copy || !same(g))
|
||||
};
|
||||
// A transform of ids that name no object, or an identity transform without a copy, moves
|
||||
// nothing: the document and its undo history stay as they are, and Transform Again repeats it.
|
||||
// With a copy, the reply lists the copies, and there are none.
|
||||
@@ -142,8 +172,9 @@ fn apply_transform_moving_guides(
|
||||
if c[..4] == [1.0, 0.0, 0.0, 1.0] {
|
||||
interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?);
|
||||
}
|
||||
let mut ids = ids;
|
||||
if xf != Affine::IDENTITY {
|
||||
crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?;
|
||||
ids.extend(crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?);
|
||||
}
|
||||
ids
|
||||
} else if none || (!copy && xf == Affine::IDENTITY) {
|
||||
@@ -151,7 +182,7 @@ fn apply_transform_moving_guides(
|
||||
} else {
|
||||
let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None };
|
||||
s.edit(label, |d, sel| {
|
||||
let targets = match &kept {
|
||||
let mut targets = match &kept {
|
||||
// The document becomes the snapshot with the kept copies, untransformed, and the
|
||||
// loop below transforms only the copies.
|
||||
Some(k) => {
|
||||
@@ -196,10 +227,14 @@ fn apply_transform_moving_guides(
|
||||
crate::cmd::patterncmds::move_tile_with_art(d, &targets, before);
|
||||
}
|
||||
}
|
||||
if with_guides && (delta.x != 0.0 || delta.y != 0.0) {
|
||||
if with_guides && is_translation && (delta.x != 0.0 || delta.y != 0.0) {
|
||||
for i in sel.guides.clone() {
|
||||
d.edit_ruler_guide(i, |g| *g = g.moved(delta));
|
||||
}
|
||||
} else if with_guides && !is_translation {
|
||||
// The guide paths are made already transformed, so they join the reply after the
|
||||
// loop above.
|
||||
targets.extend(d.transform_ruler_guides(sel, xf));
|
||||
}
|
||||
Ok(targets)
|
||||
})?
|
||||
@@ -388,6 +423,10 @@ pub(super) fn rotate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.rotate")?;
|
||||
check_switches(p, &["absolute"], "object.rotate")?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
// A bounding box angle is that of objects; ruler guides selected alone have none.
|
||||
if bool_or(p, "absolute", false) && ids.is_empty() {
|
||||
return Err(bad("object.rotate", "absolute needs objects selected: ruler guides have no bounding box angle"));
|
||||
}
|
||||
let o = origin_of(s, p, &ids)?;
|
||||
let mut angle = f64_or(p, "angle", 0.0);
|
||||
if bool_or(p, "absolute", false) {
|
||||
|
||||
@@ -20,6 +20,21 @@ use crate::{DocState, EngineError};
|
||||
/// object in particular is the color it paints with ([`apply_paint`]).
|
||||
pub(crate) const LIVE_PAINT_BUCKET: &str = "livePaintBucket";
|
||||
|
||||
/// The Shape Builder's tool id. While it is active, a fill chosen for no object in particular is
|
||||
/// the current fill only, which merges fill with when Pick Color From is Color Swatches; a stroke
|
||||
/// chosen then still paints the selection.
|
||||
const SHAPE_BUILDER: &str = "shapeBuilder";
|
||||
|
||||
/// Tool `id`'s id when it paints with the fill (or the stroke, `stroke`) chosen while it is
|
||||
/// active: the Live Paint Bucket with both, the Shape Builder with the fill.
|
||||
pub(crate) fn painting_tool_of(id: &str, stroke: bool) -> Option<&'static str> {
|
||||
match id {
|
||||
LIVE_PAINT_BUCKET => Some(LIVE_PAINT_BUCKET),
|
||||
SHAPE_BUILDER if !stroke => Some(SHAPE_BUILDER),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -27,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row o
Line truncated
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row o
Line truncated
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
@@ -36,7 +51,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Stroke",
|
||||
[],
|
||||
None,
|
||||
"{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill), opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
|
||||
"{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill), opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke (while the Shape Builder is the active tool, the selection still takes the stroke); without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
|
||||
has_doc,
|
||||
|s, p| { set_paint(s, p, false) }
|
||||
),
|
||||
@@ -45,7 +60,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Swap Fill and Stroke",
|
||||
[],
|
||||
Some("Shift+X"),
|
||||
"{ids?|id?, defaultsOnly?: bool} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change",
|
||||
"{ids?|id?, defaultsOnly?: bool} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket or the Shape Builder is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change (with the Shape Builder, the default fill takes the stroke the Stroke proxy shows, the selection's)",
|
||||
has_doc,
|
||||
swap
|
||||
),
|
||||
@@ -54,7 +69,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Default Fill and Stroke",
|
||||
[],
|
||||
Some("D"),
|
||||
"{ids?|id?, defaultsOnly?: bool} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change",
|
||||
"{ids?|id?, defaultsOnly?: bool} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket or the Shape Builder is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change",
|
||||
has_doc,
|
||||
default_paint
|
||||
),
|
||||
@@ -75,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"None",
|
||||
[],
|
||||
Some("/"),
|
||||
"{defaultsOnly?: bool} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket is the active tool, or with `defaultsOnly: true`, only the default changes) → {objects}",
|
||||
"{defaultsOnly?: bool} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool, or with `defaultsOnly: true`, only the default changes) → {objects}",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let f = s.fill_active;
|
||||
@@ -103,7 +118,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Invert",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
|
||||
has_doc,
|
||||
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
|
||||
),
|
||||
@@ -112,7 +127,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Complement",
|
||||
[],
|
||||
None,
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, the default; no undo step when no color changes → {changed}",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, the default; no undo step when no color changes → {changed}",
|
||||
has_doc,
|
||||
|s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model())
|
||||
),
|
||||
@@ -121,7 +136,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Apply Last Color",
|
||||
[],
|
||||
Some(","),
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, to the default only) → {objects} (as paint.setFill)",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, to the default only) → {objects} (as paint.setFill)",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let paint = Paint::solid(s.last_solid);
|
||||
@@ -133,7 +148,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Apply Last Gradient",
|
||||
[],
|
||||
Some("."),
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, to the default only) → {objects} (as paint.setFill)",
|
||||
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, to the default only) → {objects} (as paint.setFill)",
|
||||
has_doc,
|
||||
|s, p| {
|
||||
let paint = super::gradient::unplaced(&Paint::Gradient(Box::new(s.last_gradient.clone())));
|
||||
@@ -161,7 +176,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
|
||||
"Fill and Stroke",
|
||||
[],
|
||||
None,
|
||||
"{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill item that paint.setFill {opacity} sets (the stroke item that paint.setStroke {opacity} sets), from the first selected object (or painted object in a selected group; a selected path of a compound path stands for its compound, and a Live Paint group for its faces' fills and its edges' strokes) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Live Paint Bucket is the active tool, while the Type tool has characters selected, and when only type characters or objects without that item are selected}",
|
||||
"{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill item that paint.setFill {opacity} sets (the stroke item that paint.setStroke {opacity} sets), from the first selected object (or painted object in a selected group; a selected path of a compound path stands for its compound, and a Live Paint group for its faces' fills and its edges' strokes) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Live Paint Bucket is the active tool (for fillOpacity, also the Shape Builder), while the Type tool has characters selected, and when only type characters or objects without that item are selected}",
|
||||
always,
|
||||
proxies
|
||||
),
|
||||
@@ -204,11 +219,11 @@ impl Session {
|
||||
/// The object whose fill (or stroke) the proxy shows, with the Appearance panel's active item
|
||||
/// when it stands for it (see [`Session::proxy_paints`]); None: the defaults for new art. With
|
||||
/// an object of a dynamic symbol instance selected ([`DocState::selected_symbol_part`]), that
|
||||
/// object as the instance draws it. None while the Live Paint Bucket is the active tool (or
|
||||
/// another tool works for it, [`Session::bucket_paints`]): the proxies show the colors it
|
||||
/// paints with.
|
||||
/// object as the instance draws it. None while the active tool paints with the chosen fill (or
|
||||
/// stroke), or another tool works for it ([`Session::tool_paints`]): the proxy shows the color
|
||||
/// it paints with.
|
||||
pub(crate) fn proxy_source(&self, stroke: bool) -> Option<(Cow<'_, Node>, Option<usize>)> {
|
||||
if self.bucket_paints() {
|
||||
if self.tool_paints(stroke) {
|
||||
return None;
|
||||
}
|
||||
let st = self.active()?;
|
||||
@@ -243,16 +258,16 @@ impl Session {
|
||||
/// `paint.setStroke {opacity}` sets): the item's, or for a gradient mesh with points picked the
|
||||
/// first picked point's. The rows the command would edit are read in order (a group without an
|
||||
/// active Appearance row stands for its contents), and the first that exists answers. `None`
|
||||
/// with nothing selected, for an object selected in a symbol instance, while the Live Paint
|
||||
/// Bucket is the active tool (or another tool works for it, [`Session::bucket_paints`]), while
|
||||
/// with nothing selected, for an object selected in a symbol instance, while the active tool
|
||||
/// paints with the chosen fill (or stroke), or another tool works for it ([`Session::tool_paints`]), while
|
||||
/// the Type tool has characters selected, and when only type
|
||||
/// characters, objects without that item or the art of graph designs in a graph series are
|
||||
/// selected.
|
||||
pub fn proxy_opacity(&self, stroke: bool) -> Option<f32> {
|
||||
let st = self.active()?;
|
||||
// The Live Paint Bucket takes a fill or stroke chosen as the color it paints with, and the
|
||||
// selection keeps its own (for_bucket).
|
||||
if st.selection.symbol_part.is_some() || self.bucket_paints() {
|
||||
// Such a tool takes a fill or stroke chosen as the color it paints with, and the selection
|
||||
// keeps its own (for_tool).
|
||||
if st.selection.symbol_part.is_some() || self.tool_paints(stroke) {
|
||||
return None;
|
||||
}
|
||||
// The command would give the opacity to the characters, which have none of their own.
|
||||
@@ -516,25 +531,40 @@ impl DocState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `t` the Live Paint Bucket, or a tool armed to switch back to it after its pick?
|
||||
fn works_for_bucket(t: &dyn vectorcraft_tools::Tool) -> bool {
|
||||
t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET)
|
||||
/// The id of tool `t`, or of the tool its armed pick switches back to, when that tool paints with
|
||||
/// the chosen fill or stroke ([`painting_tool_of`]).
|
||||
fn painter_of(t: &dyn vectorcraft_tools::Tool) -> Option<&'static str> {
|
||||
let of = |id: &str| painting_tool_of(id, false).or_else(|| painting_tool_of(id, true));
|
||||
of(t.id()).or_else(|| t.returns_to().and_then(of))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Did the Live Paint Bucket, or the Eyedropper armed for it, lend the active tool (a Cmd+click)?
|
||||
pub(crate) fn lent_by_bucket(&self) -> bool {
|
||||
self.lender.as_deref().is_some_and(works_for_bucket)
|
||||
/// The tool that lent the active tool (a Cmd+click) when it paints with the chosen colors, or
|
||||
/// the Eyedropper armed for such a tool did ([`painter_of`]).
|
||||
pub(crate) fn lent_by_painter(&self) -> Option<&'static str> {
|
||||
self.lender.as_deref().and_then(painter_of)
|
||||
}
|
||||
|
||||
/// Do the fill and stroke proxies, and the paint commands that name no objects, stand for the
|
||||
/// colors the Live Paint Bucket paints with? They do while the bucket is the active tool, while
|
||||
/// a Cmd+click with the bucket uses the Selection tool, and while the Eyedropper samples into a
|
||||
/// stop of the bucket's gradient for the Gradient panel's eyedropper, up to and including the
|
||||
/// sample its click takes before it switches back to the bucket.
|
||||
pub fn bucket_paints(&self) -> bool {
|
||||
// A Cmd+click lends the Selection tool to the bucket, or to the Eyedropper armed for it.
|
||||
self.back_to_bucket || works_for_bucket(self.tool.as_ref()) || self.lent_by_bucket()
|
||||
/// Do the fill proxy (the stroke proxy, with `stroke`), and the fill (stroke) commands that
|
||||
/// name no objects, stand for the color the active tool paints with ([`painting_tool_of`]: the
|
||||
/// Live Paint Bucket's fill and stroke, the Shape Builder's fill)? They do while such a tool is
|
||||
/// active, while a Cmd+click with it uses the Selection tool, and while the Eyedropper samples
|
||||
/// into a stop of its gradient for the Gradient panel's eyedropper, up to and including the
|
||||
/// sample its click takes before it switches back to that tool.
|
||||
pub fn tool_paints(&self, stroke: bool) -> bool {
|
||||
self.painting_tool(stroke).is_some()
|
||||
}
|
||||
|
||||
/// The id of the tool whose fill (or stroke, `stroke`) the proxy stands for
|
||||
/// ([`Session::tool_paints`]); None when it stands for the selection's.
|
||||
pub(crate) fn painting_tool(&self, stroke: bool) -> Option<&'static str> {
|
||||
let of =
|
||||
|t: &dyn vectorcraft_tools::Tool| painting_tool_of(t.id(), stroke).or_else(|| t.returns_to().and_then(|id| painting_tool_of(id, stroke)));
|
||||
// A Cmd+click lends the Selection tool to such a tool, or to the Eyedropper armed for it.
|
||||
self.back_to_painter
|
||||
.and_then(|id| painting_tool_of(id, stroke))
|
||||
.or_else(|| of(self.tool.as_ref()))
|
||||
.or_else(|| self.lender.as_deref().and_then(of))
|
||||
}
|
||||
|
||||
/// The tool the active tool's armed one-shot pick switches back to after its click
|
||||
@@ -545,12 +575,14 @@ impl Session {
|
||||
|
||||
/// [`DocState::proxy_mixed`] of the active document for the Appearance panel's active item.
|
||||
/// A gradient mesh with points picked ([`Session::fill_mesh_points`]) counts with their colors.
|
||||
/// Neither is mixed while the Live Paint Bucket is the active tool ([`Session::proxy_source`]).
|
||||
/// A proxy that stands for the color the active tool paints with ([`Session::tool_paints`]) is
|
||||
/// not mixed ([`Session::proxy_source`]).
|
||||
pub fn proxy_mixed(&self) -> (bool, bool) {
|
||||
if self.bucket_paints() {
|
||||
if self.tool_paints(false) && self.tool_paints(true) {
|
||||
return (false, false);
|
||||
}
|
||||
self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points()))
|
||||
let (fill, stroke) = self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points()));
|
||||
(fill && !self.tool_paints(false), stroke && !self.tool_paints(true))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -735,8 +767,8 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
|
||||
/// characters, to an object selected in a symbol instance, or to no target at all is an error.
|
||||
fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option<Paint>, opacity: Option<f32>, fill: bool) -> Result<Value> {
|
||||
let cmd = if fill { "paint.setFill" } else { "paint.setStroke" };
|
||||
let bucket = bucket_color_params(s, p, cmd)?;
|
||||
let p = bucket.as_ref().unwrap_or(p);
|
||||
let for_tool = tool_color_params(s, p, cmd, !fill)?;
|
||||
let p = for_tool.as_ref().unwrap_or(p);
|
||||
let focus = switch_or(p, "focus", true, cmd)?;
|
||||
// An opacity alone places no gradient, so `span` may only be "object" with it.
|
||||
let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?;
|
||||
@@ -1033,12 +1065,13 @@ fn names_no_target(p: &Value) -> bool {
|
||||
["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none()
|
||||
}
|
||||
|
||||
/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]), or does `p` give
|
||||
/// Does the active tool paint with the chosen fill (or stroke, `stroke`: [`Session::tool_paints`],
|
||||
/// the Live Paint Bucket's fill and stroke, the Shape Builder's fill), or does `p` give
|
||||
/// `defaultsOnly: true`, while `p` names no `ids`, `id` or `item`? A fill, stroke or stroke weight
|
||||
/// chosen then is what the bucket paints with, so it goes to the defaults and the selection keeps
|
||||
/// its paint.
|
||||
pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool {
|
||||
names_no_target(p) && (s.bucket_paints() || asks_defaults_only(p))
|
||||
/// of that kind chosen then is what the tool paints with, so it goes to the defaults and the
|
||||
/// selection keeps its paint.
|
||||
pub(crate) fn for_tool(s: &Session, p: &Value, stroke: bool) -> bool {
|
||||
names_no_target(p) && (s.tool_paints(stroke) || asks_defaults_only(p))
|
||||
}
|
||||
|
||||
/// Does `p` give `defaultsOnly: true`?
|
||||
@@ -1046,17 +1079,18 @@ pub(crate) fn asks_defaults_only(p: &Value) -> bool {
|
||||
p.get("defaultsOnly") == Some(&Value::Bool(true))
|
||||
}
|
||||
|
||||
/// `p` with `ids: []` (and without `defaultsOnly`) when [`for_bucket`]: the paint goes to the
|
||||
/// defaults only. None otherwise. A bad `target` or `aligned` is refused first, as it is without
|
||||
/// the bucket, and so is a `defaultsOnly` that is not a bool or comes with `ids`, `id` or `item`.
|
||||
/// When the bucket routed the command, the journal entry notes `defaultsOnly: true`, so replaying
|
||||
/// it with another tool active changes the defaults only as well.
|
||||
pub(crate) fn bucket_color_params(s: &mut Session, p: &Value, cmd: &str) -> Result<Option<Value>> {
|
||||
/// `p` with `ids: []` (and without `defaultsOnly`) when [`for_tool`] for the fill (or stroke,
|
||||
/// `stroke`): the paint goes to the defaults only. None otherwise. A bad `target` or `aligned` is
|
||||
/// refused first, as it is when the selection takes the paint, and so is a `defaultsOnly` that is
|
||||
/// not a bool or comes with `ids`, `id` or `item`. When the active tool routed the command, the
|
||||
/// journal entry notes `defaultsOnly: true`, so replaying it with another tool active changes the
|
||||
/// defaults only as well.
|
||||
pub(crate) fn tool_color_params(s: &mut Session, p: &Value, cmd: &str, stroke: bool) -> Result<Option<Value>> {
|
||||
let only = switch_or(p, "defaultsOnly", false, cmd)?;
|
||||
if only && !names_no_target(p) {
|
||||
return Err(bad(cmd, "`defaultsOnly` cannot be combined with `ids`, `id` or `item`"));
|
||||
}
|
||||
if !for_bucket(s, p) {
|
||||
if !for_tool(s, p, stroke) {
|
||||
return Ok(None);
|
||||
}
|
||||
super::appearance::aligned(p, cmd)?;
|
||||
@@ -1071,28 +1105,62 @@ pub(crate) fn bucket_color_params(s: &mut Session, p: &Value, cmd: &str) -> Resu
|
||||
Ok(Some(Value::Object(v)))
|
||||
}
|
||||
|
||||
/// Whether the paint commands that `cmd` runs with params of its own change only the defaults:
|
||||
/// `p` gives `defaultsOnly: true`, or the Live Paint Bucket paints ([`Session::bucket_paints`]),
|
||||
/// which the journal entry of `cmd` notes for a replay.
|
||||
pub(crate) fn defaults_only(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
|
||||
/// The kind of gradient `p` of a gradient command (`cmd`) edits when the active tool can paint
|
||||
/// with it: the kind `stroke` names, else the proxy in front's when the tool paints with it, else
|
||||
/// the kind `p` edits on the selection (the Appearance panel's active row's).
|
||||
pub(crate) fn tool_gradient_kind(s: &Session, p: &Value, cmd: &str) -> Result<bool> {
|
||||
check_switches(p, &["stroke"], cmd)?;
|
||||
// A tool that paints with both kinds (the Live Paint Bucket), or with neither, needs no kind.
|
||||
Ok(if s.tool_paints(false) == s.tool_paints(true) || p.get("stroke").is_some_and(Value::is_boolean) {
|
||||
p.get("stroke").and_then(Value::as_bool).unwrap_or(!s.fill_active)
|
||||
} else if s.tool_paints(!s.fill_active) {
|
||||
!s.fill_active
|
||||
} else {
|
||||
// A null `ids` or `id` names no target, as `for_tool` reads it.
|
||||
let mut q = p.clone();
|
||||
if let Some(o) = q.as_object_mut() {
|
||||
o.retain(|k, v| !(matches!(k.as_str(), "ids" | "id") && v.is_null()));
|
||||
}
|
||||
super::appearance::edits_stroke(s, &q, item_target(s, &q, cmd)?, !s.fill_active, cmd)?
|
||||
})
|
||||
}
|
||||
|
||||
/// [`tool_color_params`] for `paint.editGradient` or `gradient.presets.apply` (`cmd`), for the kind
|
||||
/// [`tool_gradient_kind`] gives. The params name that kind as their `stroke` when `p` gives none,
|
||||
/// since the selection's Appearance row no longer picks it.
|
||||
pub(crate) fn tool_gradient_params(s: &mut Session, p: &Value, cmd: &str) -> Result<Option<Value>> {
|
||||
let stroke = tool_gradient_kind(s, p, cmd)?;
|
||||
Ok(tool_color_params(s, p, cmd, stroke)?.map(|mut v| {
|
||||
if p.get("stroke").is_none_or(Value::is_null) {
|
||||
v["stroke"] = json!(stroke);
|
||||
}
|
||||
v
|
||||
}))
|
||||
}
|
||||
|
||||
/// Whether the paint commands that `cmd` runs with params of its own for the fill (or the stroke,
|
||||
/// `stroke`) change only the defaults: `p` gives `defaultsOnly: true`, or the active tool paints
|
||||
/// with that kind ([`Session::tool_paints`]), which the journal entry of `cmd` notes for a replay.
|
||||
pub(crate) fn defaults_only(s: &mut Session, p: &Value, cmd: &str, stroke: bool) -> Result<bool> {
|
||||
if switch_or(p, "defaultsOnly", false, cmd)? {
|
||||
s.note_defaults_only();
|
||||
return Ok(true);
|
||||
}
|
||||
let bucket = s.bucket_paints();
|
||||
if bucket {
|
||||
let tool = s.tool_paints(stroke);
|
||||
if tool {
|
||||
s.note_journal("defaultsOnly", json!(true));
|
||||
s.note_defaults_only();
|
||||
}
|
||||
Ok(bucket)
|
||||
Ok(tool)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Note that the running command changed only the paint defaults, with the appearance new art
|
||||
/// takes from the selection now ([`Session::inherit_new_art`]). No appearance is captured
|
||||
/// while inheritance does not run (New Art Has Basic Appearance on, or the bucket painting).
|
||||
/// while inheritance does not run (New Art Has Basic Appearance on, or the active tool painting
|
||||
/// with both the fill and the stroke).
|
||||
fn note_defaults_only(&mut self) {
|
||||
let inherits = !self.prefs.new_art_basic && !self.bucket_paints();
|
||||
let inherits = !self.prefs.new_art_basic && !(self.tool_paints(false) && self.tool_paints(true));
|
||||
self.defaults_only_ran = Some(if inherits { self.new_art_source() } else { None });
|
||||
}
|
||||
}
|
||||
@@ -1534,8 +1602,17 @@ fn shared_paint(d: &Document, parts: &[NodeId], fill: bool) -> Option<Paint> {
|
||||
}
|
||||
|
||||
fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let bucket = bucket_color_params(s, p, "paint.swap")?;
|
||||
let p = bucket.as_ref().unwrap_or(p);
|
||||
// The swap changes a fill, so it goes to the defaults only while the active tool paints with the chosen fill.
|
||||
let for_tool = tool_color_params(s, p, "paint.swap", false)?;
|
||||
let p = for_tool.as_ref().unwrap_or(p);
|
||||
// A tool that paints with the fill only (the Shape Builder): the Stroke proxy shows the
|
||||
// selection's stroke, which the current fill takes unless the proxy shows mixed strokes. With
|
||||
// nothing selected it shows the stroke for new art, which the swap moves as it is.
|
||||
// A swap with `defaultsOnly` and no such tool swaps the defaults alone.
|
||||
let fill_only = s.tool_paints(false) && !s.tool_paints(true);
|
||||
let shown_stroke = (for_tool.is_some() && fill_only && !s.proxy_mixed().1)
|
||||
.then(|| s.proxy_source(true).map(|(n, item)| super::gradient::unplaced(&proxy_paint(&n, true, item))))
|
||||
.flatten();
|
||||
let targets = paint_targets(s, p)?;
|
||||
let given = !targets.is_empty();
|
||||
// A whole Live Paint group: its faces take the stroke its edges share and its edges the fill its faces share.
|
||||
@@ -1599,6 +1676,9 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.paint.stroke_width = 1.0;
|
||||
}
|
||||
std::mem::swap(&mut s.paint.fill, &mut s.paint.stroke);
|
||||
if let Some(stroke) = shown_stroke {
|
||||
s.paint.fill = stroke;
|
||||
}
|
||||
ok()
|
||||
}
|
||||
|
||||
@@ -1606,8 +1686,9 @@ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const LIVE_PAINT_DEFAULT_WEIGHT: f64 = 0.5;
|
||||
|
||||
fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let bucket = bucket_color_params(s, p, "paint.default")?;
|
||||
let p = bucket.as_ref().unwrap_or(p);
|
||||
// As with paint.swap, the new fill decides whether only the defaults change.
|
||||
let for_tool = tool_color_params(s, p, "paint.default", false)?;
|
||||
let p = for_tool.as_ref().unwrap_or(p);
|
||||
let targets = paint_targets(s, p)?;
|
||||
let given = !targets.is_empty();
|
||||
// A whole Live Paint group: its faces lose their fill and its edges take a black 0.5 pt stroke.
|
||||
@@ -1687,9 +1768,9 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// default when there are none) and remember the first target's new paint. The Appearance panel's
|
||||
/// active item of the proxy's kind is recoloured in each selected object's own stack instead.
|
||||
fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
|
||||
let bucket = bucket_color_params(s, p, cmd)?;
|
||||
let p = bucket.as_ref().unwrap_or(p);
|
||||
let stroke = stroke_param(s, p, cmd)?;
|
||||
let for_tool = tool_color_params(s, p, cmd, stroke)?;
|
||||
let p = for_tool.as_ref().unwrap_or(p);
|
||||
// An object of a dynamic symbol instance's art selected with Direct Selection: the solid color
|
||||
// it shows is recolored for this instance only. A gradient or pattern is refused, and so is type
|
||||
// whose characters differ in that paint, since one change holds one paint.
|
||||
|
||||
@@ -420,7 +420,7 @@ pub(crate) fn push_artboard_copy(d: &mut vectorcraft_doc::Document, src: &vector
|
||||
// ---------- text ----------
|
||||
|
||||
/// Largest indent or paragraph spacing (points; Illustrator's limit).
|
||||
const MAX_PARA: f64 = 1296.0;
|
||||
const MAX_PARA: f64 = vectorcraft_doc::text::MAX_PARA_DISTANCE;
|
||||
|
||||
/// `text.setFormat`'s `bullet` values and the bullets they pick.
|
||||
const BULLETS: [(&str, vectorcraft_doc::text::Bullet); 4] = [
|
||||
|
||||