diff --git a/.github/nightly-linux-signing-key.asc b/.github/nightly-linux-signing-key.asc new file mode 100644 index 0000000000..a1c1f31e8d --- /dev/null +++ b/.github/nightly-linux-signing-key.asc @@ -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----- diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index f59894c462..d60a898fd1 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -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", diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml new file mode 100644 index 0000000000..dd4a4a02da --- /dev/null +++ b/.github/workflows/nightly-dispatch.yml @@ -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.') diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 38cb6b24a9..3b79c61ba5 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -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. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 1139f67f9b..989d6974dd 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -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"]' diff --git a/ASSETS.md b/ASSETS.md index 76a3d41962..9220086fa7 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -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 | | diff --git a/Cargo.lock b/Cargo.lock index 14d5119325..e6d867905b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/NOTICE b/NOTICE index 434cd3e524..99d05d6235 100644 --- a/NOTICE +++ b/NOTICE @@ -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 diff --git a/ROADMAP.md b/ROADMAP.md index 4d415cc0ba..c8c020dcd3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 6b4e0b8344..2416b17b89 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -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); diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 61a4ba381a..bc9945e513 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -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" diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index c8b4f370ad..83d488a243 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -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" { diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 06be570630..47813f192e 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -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() } } diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 9bfb5ea3d2..8907fe4bd1 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -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, /// 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, /// 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, diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index d4dc0e8cb0..8f1b50dd58 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -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) { diff --git a/apps/vectorcraft/src/screen_density.rs b/apps/vectorcraft/src/screen_density.rs new file mode 100644 index 0000000000..4a8c91ec76 --- /dev/null +++ b/apps/vectorcraft/src/screen_density.rs @@ -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, + position: PhysicalPosition, + size: PhysicalSize, + /// 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, String>; + +/// The physical sizes of displays, one for each display read, or why none could be read. +type Reading = Result, 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, +} + +/// What a display answered: its physical size (`Some(None)` for none), or `None` while it has not +/// answered. +type Answer = Option>; + +/// 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, Option, 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, + /// 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>, + /// The displays of the last reading that failed, and when it failed. + failed: Option<(Vec, f64)>, + /// The reading in progress: the displays it reads, and where its result arrives. + running: Option<(Vec, Receiver)>, + /// 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, + /// The displays of the last listing. + listed: Option>, + /// 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, +} + +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 { + 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::>(), 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| { + 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, + start: impl FnOnce(Vec) -> Result, String>, + ) -> Option { + 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, 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, scale: f64, mm: [f64; 2]) -> Option { + 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::(&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, + mm: Option<[f64; 2]>, + } + + /// The outputs bound, each with what its events gave. + #[derive(Default)] + struct Outputs { + outputs: Vec<(WlOutput, Output)>, + } + + impl Dispatch for Outputs { + fn event(_: &mut Self, _: &WlRegistry, _: wl_registry::Event, _: &GlobalListContents, _: &Connection, _: &QueueHandle) {} + } + + impl Dispatch for Outputs { + fn event(state: &mut Self, _: &WlOutput, event: wl_output::Event, index: &usize, _: &Connection, _: &QueueHandle) { + 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, + current: usize, + /// The window's display as winit last gave it, when that lags behind the listing. + lagging: Option, + window_scale: f64, + lists: Cell, + reads: Cell, + sender: Option>, + 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 { + 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::>(); + 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:?}"); + } +} diff --git a/apps/vectorcraft/src/windows_display_size.rs b/apps/vectorcraft/src/windows_display_size.rs new file mode 100644 index 0000000000..fc7041ebd6 --- /dev/null +++ b/apps/vectorcraft/src/windows_display_size.rs @@ -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, 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)])) +} diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index 745a5046f5..b8e6b88ee1 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -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 //! (). Pointer @@ -24,9 +25,12 @@ //! `rotation` in degrees 0..359 clockwise //! (). //! 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> = const { Cell::new(None) }; +} + /// The pen source [`msg_hook`] writes, once [`start`] has made it. static FEED: OnceLock = 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) -> 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) -> 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 +/// (); the posted pointer +/// messages are left to [`msg_hook`]. +fn sent_forgets_wheel(message: u32, wparam: usize, pen: Option) -> 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] diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs new file mode 100644 index 0000000000..31da32a1ff --- /dev/null +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -0,0 +1,1595 @@ +//! Windows: an airbrush pen's finger wheel. `POINTER_PEN_INFO` has no field for it +//! (), so +//! [`crate::windows_stylus`] keeps reading the pressure, end, tilt and rotation from pointer +//! messages, and this module reads only the wheel from the tablet driver's Wintab interface, as +//! its tangential pressure (`pkTangentPressure`), when the driver installs one. The Wintab +//! reference describes the context, packet and message calls used here +//! (), and the +//! Windows Ink comparison says the wheel comes only through Wintab +//! (). +//! +//! - Nothing here runs until the active tool draws with a brush or tip that varies with the +//! finger wheel (Stylus Wheel), as the app says through [`set_wheel_used`]: until then pen +//! messages load no library, install no hook and open no context, and when the tool stops +//! using the wheel the context closes ([`unused_context`]). +//! - `Wintab32.dll` is loaded at run time from the system directory only, the first time a pen +//! comes over a window while the wheel is used. Without it, without one of its exports, or when +//! a call fails, the pens read no wheel and draw as before; the user sees no error. +//! - The context is opened from the driver's default context for the window that owns the pen's +//! window ([`configure`]), with packet messages on and the system cursor off: it moves no cursor +//! and makes no press. When the pen comes over another top-level window, such as a separate +//! document window, the context closes and opens again for that window, and the readings start +//! afresh ([`next_context`]). Each `WT_PACKET` for that window and context is read with `WTPacket` into +//! a buffer larger than any packet, and decoded from the fields the context asked for +//! ([`decode`]). +//! - Only a cursor the driver reports as an airbrush (`(CSR_TYPE & 0x0F06) == 0x0902`, from the +//! Wintab basics page: ) +//! whose packets carry the tangential pressure, on a device whose `DVC_TPRESSURE` range is valid, +//! reads a wheel ([`wheel_axis`]). The wheel is the value's place in that range, 0..1 +//! ([`Axis::wheel`]); a value outside it reads as none. +//! - A pointer message of a pen takes the wheel of the airbrush whose latest packet came within +//! [`MAX_SKEW_MS`] of the message, and none when two are that recent or none is +//! ([`Readings::wheel_for`]). The first pen to read a wheel that way after the readings start +//! afresh takes the readings: other pens read none until they start afresh, and that pen keeps +//! reading the one airbrush read, however long ago its last packet came, since a pen held still +//! sends none. As on +//! macOS, 0 counts as no wheel until the pen has reported another value since it came near: the +//! readings start afresh when a cursor +//! comes near or leaves (`WT_PROXIMITY`), another cursor comes (`WT_CSRCHANGE`), the pen turns +//! to its other end, a press of the pen is canceled, the pen leaves the window or detection +//! range, or the context closes. These rules are VectorCraft's own. +//! +//! The context is dropped when the driver closes it (`WT_CTXCLOSE`), closed when the driver's +//! information changes (`WT_INFOCHANGE`) unless the driver closed it too, and dropped when its +//! window no longer exists; a later pen message opens it again. The driver sends those two notices +//! to the window procedure, where a sent message does not pass winit's message hook, so the +//! context's window gets a window procedure in front of its own that notes them ([`Notices`]). +//! When that procedure cannot be put in front, no context is opened for the window +//! ([`hooked_open`]). An open that leaves no context is tried again for the same window by a pen +//! message [`RETRY_MS`] or more later ([`next_context`]). A hook on the messages Windows sends to +//! the thread's windows passes a pen's `WM_POINTERLEAVE` to [`crate::windows_stylus`], and closes +//! the context when another app becomes the active one (`WM_ACTIVATEAPP`). No pen message opens a +//! context while this app is not active, so the context does not sit in front of another app's in +//! the driver's overlap order. A packet that `WTPacket` cannot read starts the readings afresh +//! ([`Readings::read`]), and so does a packet sent after the context's queue overflowed +//! (`TPS_QUEUE_ERR`, [`Readings::packet`]). +#![cfg_attr(not(windows), allow(dead_code))] + +/// Wintab's default message base (`WT_DEFBASE`, `wintab.h`), which [`configure`] sets. +const WT_DEFBASE: u32 = 0x7FF0; +/// `WT_PACKET`, `WT_CTXCLOSE`, `WT_PROXIMITY`, `WT_INFOCHANGE` and `WT_CSRCHANGE` at that base. +const WT_PACKET: u32 = WT_DEFBASE; +const WT_CTXCLOSE: u32 = WT_DEFBASE + 2; +const WT_PROXIMITY: u32 = WT_DEFBASE + 5; +const WT_INFOCHANGE: u32 = WT_DEFBASE + 6; +const WT_CSRCHANGE: u32 = WT_DEFBASE + 7; + +/// `CXO_SYSTEM`, `CXO_PEN`, `CXO_MESSAGES` and `CXO_CSRMESSAGES` (`wintab.h`), in `lcOptions`. +const CXO_SYSTEM: u32 = 0x0001; +const CXO_PEN: u32 = 0x0002; +const CXO_MESSAGES: u32 = 0x0004; +const CXO_CSRMESSAGES: u32 = 0x0008; + +/// The packet fields (`PK_*`, `pktdef.h`) in the order a packet holds them, each with its size in +/// bytes: `pkContext` is a handle, `pkOrientation` and `pkRotation` three 32-bit values each, and +/// the others one 32-bit value. +const PK_CONTEXT: u32 = 0x0001; +const PK_STATUS: u32 = 0x0002; +const PK_TIME: u32 = 0x0004; +const PK_CHANGED: u32 = 0x0008; +const PK_SERIAL_NUMBER: u32 = 0x0010; +const PK_CURSOR: u32 = 0x0020; +const PK_BUTTONS: u32 = 0x0040; +const PK_X: u32 = 0x0080; +const PK_Y: u32 = 0x0100; +const PK_Z: u32 = 0x0200; +const PK_NORMAL_PRESSURE: u32 = 0x0400; +const PK_TANGENT_PRESSURE: u32 = 0x0800; +const PK_ORIENTATION: u32 = 0x1000; +const PK_ROTATION: u32 = 0x2000; +const FIELDS: [(u32, usize); 14] = [ + (PK_CONTEXT, std::mem::size_of::()), + (PK_STATUS, 4), + (PK_TIME, 4), + (PK_CHANGED, 4), + (PK_SERIAL_NUMBER, 4), + (PK_CURSOR, 4), + (PK_BUTTONS, 4), + (PK_X, 4), + (PK_Y, 4), + (PK_Z, 4), + (PK_NORMAL_PRESSURE, 4), + (PK_TANGENT_PRESSURE, 4), + (PK_ORIENTATION, 12), + (PK_ROTATION, 12), +]; + +/// The fields the context asks for (`lcPktData`), all absolute: the status, the cursor, the +/// position and the tangential pressure. +const PACKET_DATA: u32 = PK_STATUS | PK_CURSOR | PK_X | PK_Y | PK_TANGENT_PRESSURE; +/// The changes that make a packet (`lcMoveMask`): a move, or a turn of the wheel in place. +const MOVE_MASK: u32 = PK_X | PK_Y | PK_TANGENT_PRESSURE; +/// The bytes `WTPacket` writes into: more than a packet of every field. +const PACKET_BUFFER: usize = 256; + +/// `TPS_PROXIMITY` and `TPS_QUEUE_ERR` (`wintab.h`), in `pkStatus`: the cursor is out of the +/// context, and the queue overflowed. +const TPS_PROXIMITY: u32 = 0x0001; +const TPS_QUEUE_ERR: u32 = 0x0002; + +/// The `LOGCONTEXTW` (`wintab.h`) as 32-bit words: a 40-character name, then `lcOptions`, +/// `lcStatus`, `lcLocks`, `lcMsgBase`, `lcDevice`, `lcPktRate`, `lcPktData`, `lcPktMode`, +/// `lcMoveMask`, `lcBtnDnMask` and `lcBtnUpMask`, and 22 words of extents and sensitivities. +const LOGCONTEXT_WORDS: usize = 53; +const _: () = assert!(LOGCONTEXT_WORDS * 4 == 212, "sizeof(LOGCONTEXTW)"); +const LC_OPTIONS: usize = 20; +const LC_MSG_BASE: usize = 23; +const LC_PKT_DATA: usize = 26; +const LC_PKT_MODE: usize = 27; +const LC_MOVE_MASK: usize = 28; +const LC_BTN_DN_MASK: usize = 29; +const LC_BTN_UP_MASK: usize = 30; + +/// `WTInfoW` categories and indexes (`wintab.h`): the interface's device count, the default +/// context, a device's first cursor, cursor count and tangential-pressure range, and a cursor's +/// packet fields and type. +const WTI_INTERFACE: u32 = 1; +const IFC_NDEVICES: u32 = 4; +const WTI_DEFCONTEXT: u32 = 3; +const WTI_DEVICES: u32 = 100; +const DVC_NCSRTYPES: u32 = 3; +const DVC_FIRSTCSR: u32 = 4; +const DVC_TPRESSURE: u32 = 16; +const WTI_CURSORS: u32 = 200; +const CSR_PKTDATA: u32 = 3; +const CSR_TYPE: u32 = 20; +/// Cursor and device numbers stay below the next category's base. +const MAX_INDEX: u32 = 100; +/// At most this many devices are looked through for a cursor's device. +const MAX_DEVICES: u32 = 16; + +/// A packet and a pointer message at most this far apart, in the message clock's milliseconds, +/// belong together. +const MAX_SKEW_MS: u32 = 200; +/// At most this many cursors' readings are kept. +const MAX_READINGS: usize = 4; +/// At most this many pens' ends are kept. +const MAX_PENS: usize = 16; + +/// Sets up the driver's default context, `words`, for the wheel: packet and cursor messages on, +/// the system cursor and pen messages off, the [`PACKET_DATA`] fields in absolute mode, packets on +/// a move or a turn of the wheel, and no button events. +fn configure(words: &mut [u32; LOGCONTEXT_WORDS]) { + words[LC_OPTIONS] = (words[LC_OPTIONS] | CXO_MESSAGES | CXO_CSRMESSAGES) & !(CXO_SYSTEM | CXO_PEN); + words[LC_MSG_BASE] = WT_DEFBASE; + words[LC_PKT_DATA] = PACKET_DATA; + words[LC_PKT_MODE] = 0; + words[LC_MOVE_MASK] = MOVE_MASK; + words[LC_BTN_DN_MASK] = 0; + words[LC_BTN_UP_MASK] = 0; +} + +/// The size in bytes of a packet holding the fields of `mask`. +fn packet_size(mask: u32) -> usize { + FIELDS.iter().filter(|(f, _)| mask & f != 0).map(|(_, n)| n).sum() +} + +/// The 32-bit field `field` of a packet holding the fields of `mask`, or `None` when the mask +/// leaves it out, it is not a 32-bit field, or `bytes` is too short. +fn field(bytes: &[u8], mask: u32, field: u32) -> Option { + if mask & field == 0 || bytes.len() < packet_size(mask) { + return None; + } + let mut at = 0; + for &(f, n) in &FIELDS { + if f == field { + let word = bytes.get(at..at + 4).filter(|_| n == 4)?; + return Some(u32::from_ne_bytes(word.try_into().ok()?)); + } + if mask & f != 0 { + at += n; + } + } + None +} + +/// What a packet says about the wheel. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Packet { + status: u32, + cursor: u32, + tangent: u32, +} + +/// The status, cursor and tangential pressure of a packet holding the fields of `mask`. +fn decode(bytes: &[u8], mask: u32) -> Option { + Some(Packet { status: field(bytes, mask, PK_STATUS)?, cursor: field(bytes, mask, PK_CURSOR)?, tangent: field(bytes, mask, PK_TANGENT_PRESSURE)? }) +} + +/// A device's tangential-pressure range (`AXIS`'s `axMin` and `axMax`). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Axis { + min: i32, + max: i32, +} + +impl Axis { + /// The wheel, 0..1, for the absolute value `raw`: 0 at `axMin`, 1 at `axMax`. `pktdef.h` gives + /// an absolute tangential pressure as unsigned; with a range below 0 it is read as signed. A + /// value outside the range reads as none. + fn wheel(self, raw: u32) -> Option { + let (min, max) = (i64::from(self.min), i64::from(self.max)); + if min >= max { + return None; + } + let v = if min < 0 { i64::from(raw as i32) } else { i64::from(raw) }; + (min..=max).contains(&v).then(|| ((v - min) as f64 / (max - min) as f64) as f32) + } +} + +/// Whether a cursor of this `CSR_TYPE` is an airbrush. +fn is_airbrush(csr_type: u32) -> bool { + csr_type & 0x0F06 == 0x0902 +} + +/// The wheel range of a cursor of `csr_type` whose packets carry the fields of `csr_pktdata`, on a +/// device whose `DVC_TPRESSURE` reads as `axis` (`axMin`, `axMax`, `axUnits`, `axResolution`): +/// `None` unless it is an airbrush with a tangential pressure and the range is not empty. +fn wheel_axis(csr_type: u32, csr_pktdata: u32, axis: Option<[u32; 4]>) -> Option { + let [min, max, ..] = axis?; + let axis = Axis { min: min as i32, max: max as i32 }; + (is_airbrush(csr_type) && csr_pktdata & PK_TANGENT_PRESSURE != 0 && axis.min < axis.max).then_some(axis) +} + +/// The device of `cursor`, from each device's first cursor and cursor count (`DVC_FIRSTCSR`, +/// `DVC_NCSRTYPES`), or `None` when no device or more than one has it. +fn device_of(cursor: u32, devices: &[(u32, u32)]) -> Option { + let mut found = devices.iter().enumerate().filter(|(_, (first, n))| first.checked_add(*n).is_some_and(|end| (*first..end).contains(&cursor))); + let (d, _) = found.next()?; + found.next().is_none().then_some(d) +} + +/// What the driver said about a cursor's wheel range. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Lookup { + /// The range, or `None` for a cursor the driver describes without a wheel. + Known(Option), + /// A `WTInfoW` call failed at this message time. + Failed { at: u32 }, +} + +/// Each cursor's wheel range, as the driver reported it, until the driver's information changes. +#[derive(Clone, Debug, Default)] +struct Cursors(Vec<(u32, Lookup)>); + +impl Cursors { + /// The wheel range of `cursor` for a packet at the message time `time`, asking the driver with + /// `query` the first time, or again once [`retry_due`] after a query that failed (`Err`). + /// Until then a cursor whose query failed reads no wheel. + fn axis(&mut self, cursor: u32, time: u32, query: impl FnOnce() -> Result, ()>) -> Option { + if let Some(i) = self.0.iter().position(|(c, _)| *c == cursor) { + match self.0[i].1 { + Lookup::Known(axis) => return axis, + Lookup::Failed { at } if !retry_due(at, time) => return None, + Lookup::Failed { .. } => { + self.0.remove(i); + } + } + } + let lookup = match query() { + Ok(axis) => Lookup::Known(axis), + Err(()) => Lookup::Failed { at: time }, + }; + if self.0.len() >= MAX_READINGS * 4 { + self.0.remove(0); + } + self.0.push((cursor, lookup)); + match lookup { + Lookup::Known(axis) => axis, + Lookup::Failed { .. } => None, + } + } + + fn clear(&mut self) { + self.0.clear(); + } +} + +/// Whether two times of the message clock, which wraps, are at most [`MAX_SKEW_MS`] apart. +fn near(a: u32, b: u32) -> bool { + (a.wrapping_sub(b) as i32).unsigned_abs() <= MAX_SKEW_MS +} + +/// The latest packet of a cursor near the context. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Reading { + cursor: u32, + /// The cursor's wheel range, `None` for a cursor without a wheel. + axis: Option, + raw: u32, + /// The message time of the packet. + time: u32, + /// The cursor has reported a value other than 0 since the readings started afresh. + moved: bool, +} + +/// The latest packet of each cursor near the context, until the readings start afresh. +#[derive(Clone, Debug, Default)] +struct Readings { + list: Vec, + /// The pointer id of each pen whose pointer messages were read since the readings started + /// afresh, with the end its last message read (`true` for the eraser end), at most + /// [`MAX_PENS`] of them. + ends: Vec<(u32, bool)>, + /// The pointer id of the pen whose message first read the wheel since the readings started + /// afresh; another pen's messages read none. + pen: Option, + /// The cursor whose wheel that pen read; the pen reads no other cursor's wheel until the + /// readings start afresh. + cursor: Option, +} + +impl Readings { + /// A packet of `p.cursor`, whose wheel range is `axis`, at the message time `time`. A packet of + /// a cursor out of the context drops that cursor's reading. A packet sent after the context's + /// queue overflowed starts every reading afresh, until the next packet. + fn packet(&mut self, p: Packet, axis: Option, time: u32) { + if p.status & TPS_QUEUE_ERR != 0 { + self.forget(); + return; + } + let at = self.list.iter().position(|r| r.cursor == p.cursor); + if p.status & TPS_PROXIMITY != 0 { + if let Some(i) = at { + self.list.remove(i); + } + return; + } + let moved = at.is_some_and(|i| self.list[i].moved && self.list[i].axis == axis) || p.tangent != 0; + let reading = Reading { cursor: p.cursor, axis, raw: p.tangent, time, moved }; + match at { + Some(i) => self.list[i] = reading, + None => { + if self.list.len() >= MAX_READINGS { + self.list.remove(0); + } + self.list.push(reading); + } + } + } + + /// A `WT_PACKET` read at the message time `time`: the packet with its cursor's wheel range, or + /// `None` when `WTPacket` failed or the packet could not be decoded. Then no reading is known to + /// be current, and the readings start afresh until the next packet. + fn read(&mut self, read: Option<(Packet, Option)>, time: u32) { + match read { + Some((p, axis)) => self.packet(p, axis, time), + None => self.forget(), + } + } + + /// Start afresh: the pen came near or left, another cursor came, a press was canceled, a packet + /// could not be read, the context's queue overflowed, or the context closed. + fn forget(&mut self) { + self.list.clear(); + self.ends.clear(); + self.pen = None; + self.cursor = None; + } + + /// The pen whose leaving starts the readings afresh, for a message of `pen`: the pen that took + /// the readings, or `pen` when none has. + fn owner_or(&self, pen: u32) -> u32 { + self.pen.unwrap_or(pen) + } + + /// The wheel for a pointer message of the pen with the pointer id `pen` at the message time + /// `time` with its `eraser` end, if the cursor it comes from is an airbrush: the one cursor whose + /// latest packet is within [`MAX_SKEW_MS`] of the message, or, for the pen that took the + /// readings, the latest packet of the cursor whose wheel it read, however long ago it came (a + /// pen held still sends none) and whatever other cursors were read since. `None` when no cursor, + /// or more than one, is that recent, or the cursor has read only 0 since the readings started + /// afresh, or another pen's message read a wheel first since then. The same pen's turn to its + /// other end starts them afresh first; another pen's message with another end does not. + fn wheel_for(&mut self, time: u32, pen: u32, eraser: bool) -> Option { + if self.pen.is_some_and(|p| p != pen) { + return None; + } + if self.ends.iter().any(|&(p, e)| p == pen && e != eraser) { + self.forget(); + } + match self.ends.iter_mut().find(|(p, _)| *p == pen) { + Some(end) => end.1 = eraser, + None => { + if self.ends.len() >= MAX_PENS { + self.ends.remove(0); + } + self.ends.push((pen, eraser)); + } + } + let r = if self.pen == Some(pen) { + let cursor = self.cursor?; + self.list.iter().find(|r| r.cursor == cursor)? + } else { + let mut near_time = self.list.iter().filter(|r| near(time, r.time)); + let r = near_time.next()?; + if near_time.next().is_some() { + return None; + } + r + }; + if !r.moved { + return None; + } + let wheel = r.axis?.wheel(r.raw)?; + self.pen = Some(pen); + self.cursor = Some(r.cursor); + Some(wheel) + } +} + +/// What a pen message does to the open context before it is opened for the pen's window. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Current { + /// Nothing is open, or the context is the pen window's. + Keep, + /// The context's window is gone: drop the handle without a call on it. + Drop, + /// The context is another window's: close it with `WTClose`. + Close, +} + +/// After an open that left no context, the same window is tried again by the first pen message at +/// least this many milliseconds of the message clock later. +const RETRY_MS: u32 = 2000; + +/// The context step for a pen message to a window owned by `owner` at the message time `time`: +/// what happens to the open context, whose window is `current` with whether that window still +/// exists, and whether a context is opened for `owner`. The context follows the window the pen +/// draws in. While no context is open, the window and time of the last open tried (`tried`) keep +/// pen messages to that window from trying again until [`RETRY_MS`] have passed; another window, +/// or the driver closing or changing the context, tries at once. +/// A pen message to a window of an app that is not the active one (`active` false) opens none, so +/// the context never sits in front of the active app's own in the driver's overlap order. +fn next_context(current: Option<(usize, bool)>, tried: Option<(usize, u32)>, owner: usize, time: u32, active: bool) -> (Current, bool) { + let step = match current { + Some((_, false)) => Current::Drop, + Some((w, true)) if w == owner => return (Current::Keep, false), + Some(_) => Current::Close, + None => Current::Keep, + }; + let due = match tried { + Some((w, at)) if w == owner => retry_due(at, time), + _ => true, + }; + (step, active && (due || step != Current::Keep)) +} + +/// The context step for a pen message while the active tool reads no wheel ([`Wheel::Unused`]): +/// an open context closes, or is dropped when its window is gone (`current` as for +/// [`next_context`]), and none opens. +fn unused_context(current: Option<(usize, bool)>) -> Current { + match current { + Some((_, false)) => Current::Drop, + Some(_) => Current::Close, + None => Current::Keep, + } +} + +/// Whether the active tool draws with a brush or tip that varies with the finger wheel, as the +/// app last said ([`set_wheel_used`]). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Wheel { + /// No pen message loads `Wintab32.dll`, installs the thread's hook or opens a context, and a + /// context still open closes. + #[default] + Unused, + /// Pen messages open the context as [`next_context`] says. + Used, +} + +/// Whether a pen message calls the driver at all: while the wheel is used, or to close a context +/// still open after it stopped being used. +fn calls_driver(wheel: Wheel, open: bool) -> bool { + wheel == Wheel::Used || open +} + +/// Whether a step that failed at the message time `at` is tried again at `time`: [`RETRY_MS`] or +/// more later, on the message clock, which wraps. +fn retry_due(at: u32, time: u32) -> bool { + time.wrapping_sub(at) >= RETRY_MS +} + +/// At most this many contexts' closing notices wait for [`Notices::take`]. +const MAX_NOTICES: usize = 8; + +/// The driver's notices about contexts (`WT_CTXCLOSE`, `WT_INFOCHANGE`), and another app becoming +/// the active one (`WM_ACTIVATEAPP`), since they were last taken. The driver sends them to the window procedure, at times while the reader is in a driver +/// call of its own, so they are noted here and acted on at the next Wintab or pen message. +#[derive(Clone, Debug, Default, PartialEq)] +struct Notices { + /// The contexts the driver closed or is about to close. + closed: Vec, + /// The driver's information changed. + info_changed: bool, + /// The readings were to start afresh while they were in use ([`Notices::forget_later`]). + forget: bool, + /// Another app became the active one. + deactivated: bool, +} + +/// What the driver's notices do to the open context. Both can come in one batch. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Notice { + /// The driver closed it: drop the handle without `WTClose`, and open a context again at the + /// next pen message. + closed: bool, + /// The driver's information changed: close it if it is still open, forget each cursor's wheel + /// range, and open a context again at the next pen message. + info_changed: bool, + /// Start the readings afresh. + forget: bool, + /// Another app became the active one: close the context, and open one again at the next pen + /// message once this app is active again. + deactivated: bool, +} + +impl Notices { + /// Notes `message` if it is a closing, information-change or deactivation notice. + fn note(&mut self, message: Message) { + match message { + Message::Closed { ctx } if !self.closed.contains(&ctx) => { + if self.closed.len() >= MAX_NOTICES { + self.closed.remove(0); + } + self.closed.push(ctx); + } + Message::InfoChange => self.info_changed = true, + Message::Deactivated => self.deactivated = true, + _ => {} + } + } + + /// The reader closed `ctx` itself: its closing notice is not the driver's, and a context opened + /// later with the same handle value stays open. + fn closed_by_reader(&mut self, ctx: usize) { + self.closed.retain(|&c| c != ctx); + } + + /// The readings are to start afresh, at a time they are in use, for example when the pen leaves + /// the window during a driver call: the next [`Notices::take`] says so. + fn forget_later(&mut self) { + self.forget = true; + } + + /// Takes the notices: what they do to the open context `current`. + fn take(&mut self, current: Option) -> Notice { + let notices = std::mem::take(self); + Notice { + closed: current.is_some_and(|c| notices.closed.contains(&c)), + info_changed: notices.info_changed, + forget: notices.forget, + deactivated: notices.deactivated, + } + } +} + +/// Opens a context with `open` only when `hook` put the window procedure that notes the driver's +/// notices in front of the window's own and, asked after every other driver call, this app is +/// still the active one (`active`); otherwise opens none, and the window is tried again as +/// [`next_context`] says. +fn hooked_open(hook: impl FnOnce() -> bool, active: impl FnOnce() -> bool, open: impl FnOnce() -> Option) -> Option { + if hook() && active() { open() } else { None } +} + +/// What a message does to the readings and the context. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Message { + /// A packet with this serial number is waiting for the context `lparam` names. + Packet { + serial: u32, + ctx: usize, + }, + /// The readings start afresh for the context it names. + Forget { + ctx: usize, + }, + /// The context it names has closed. + Closed { + ctx: usize, + }, + /// The driver's information changed: the context closes and opens again. + InfoChange, + /// Another app became the active one: the context closes. + Deactivated, + Other, +} + +/// `WM_ACTIVATEAPP` (`winuser.h`): sent to the app's top-level windows when another app's window +/// is activated (`wParam` false) or one of the app's own is (true) +/// (). +const WM_ACTIVATEAPP: u32 = 0x001C; + +/// What the message `message` with `wparam` and `lparam` is to the Wintab reader. `WT_PACKET` +/// and `WT_CSRCHANGE` name the context in `lParam`, `WT_PROXIMITY` and `WT_CTXCLOSE` in `wParam`. +fn message(message: u32, wparam: usize, lparam: isize) -> Message { + match message { + WM_ACTIVATEAPP if wparam == 0 => Message::Deactivated, + WT_PACKET => Message::Packet { serial: wparam as u32, ctx: lparam as usize }, + WT_CSRCHANGE => Message::Forget { ctx: lparam as usize }, + WT_PROXIMITY => Message::Forget { ctx: wparam }, + WT_CTXCLOSE => Message::Closed { ctx: wparam }, + WT_INFOCHANGE => Message::InfoChange, + _ => Message::Other, + } +} + +#[cfg(windows)] +pub use win::{forget, msg_hook, pen_wheel, set_wheel_used, wheel_pen}; + +#[cfg(windows)] +#[allow(unsafe_code)] +mod win { + use std::cell::{Cell, RefCell}; + use std::ffi::c_void; + use std::sync::OnceLock; + + use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, WPARAM}; + use windows::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}; + use windows::Win32::System::Threading::GetCurrentThreadId; + use windows::Win32::UI::WindowsAndMessaging::{ + CWPSTRUCT, CallNextHookEx, CallWindowProcW, DefWindowProcW, GA_ROOTOWNER, GWLP_WNDPROC, GetAncestor, GetForegroundWindow, GetPropW, + GetWindowLongPtrW, GetWindowThreadProcessId, IsWindow, MSG, RemovePropW, SetPropW, SetWindowLongPtrW, SetWindowsHookExW, WH_CALLWNDPROC, + WM_NCDESTROY, WNDPROC, + }; + use windows::core::{PCWSTR, s, w}; + + use super::{ + Axis, CSR_PKTDATA, CSR_TYPE, Current, Cursors, DVC_FIRSTCSR, DVC_NCSRTYPES, DVC_TPRESSURE, IFC_NDEVICES, LOGCONTEXT_WORDS, MAX_DEVICES, + MAX_INDEX, Message, Notice, Notices, PACKET_BUFFER, PACKET_DATA, PK_TANGENT_PRESSURE, Readings, WTI_CURSORS, WTI_DEFCONTEXT, WTI_DEVICES, + WTI_INTERFACE, Wheel, calls_driver, configure, decode, device_of, hooked_open, is_airbrush, message, next_context, retry_due, unused_context, + wheel_axis, + }; + + /// `WTInfoW`, `WTOpenW`, `WTClose` and `WTPacket` (`wintab.h`). + type WtInfo = unsafe extern "system" fn(u32, u32, *mut c_void) -> u32; + type WtOpen = unsafe extern "system" fn(*mut c_void, *mut c_void, i32) -> *mut c_void; + type WtClose = unsafe extern "system" fn(*mut c_void) -> i32; + type WtPacket = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32; + + #[derive(Clone, Copy)] + struct Api { + info: WtInfo, + open: WtOpen, + close: WtClose, + packet: WtPacket, + } + + /// The bytes a packet is read into. + #[repr(C, align(8))] + struct PacketBuffer([u8; PACKET_BUFFER]); + + /// An open context and the window that owns it. + struct Context { + handle: *mut c_void, + hwnd: *mut c_void, + } + + #[derive(Default)] + struct State { + context: Option, + /// The window an open was last tried for, and the message time it was tried at + /// ([`next_context`]). + tried: Option<(*mut c_void, u32)>, + cursors: Cursors, + readings: Readings, + } + + thread_local! { + static STATE: RefCell = RefCell::new(State::default()); + /// Kept apart from [`STATE`], so the window procedure can note a notice the driver sends + /// while [`STATE`] is borrowed for a driver call. + static NOTICES: RefCell = RefCell::new(Notices::default()); + /// Whether the active tool uses the wheel ([`set_wheel_used`]), kept apart from [`STATE`] so + /// the app can say so while [`STATE`] is borrowed. + static WHEEL: Cell = const { Cell::new(Wheel::Unused) }; + } + + /// The window property that holds the window procedure [`wnd_proc`] passes messages on to. + const PREV_PROC: PCWSTR = w!("VectorCraft.Wintab.PrevProc"); + + /// Notes `what` for the next [`State::take_notices`] when it is a notice about contexts. + fn note(what: Message) { + if !matches!(what, Message::Closed { .. } | Message::InfoChange | Message::Deactivated) { + return; + } + NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.note(what); + } + }); + } + + /// The window procedure put in front of the context window's own: the driver sends + /// `WT_CTXCLOSE` and `WT_INFOCHANGE` (), + /// and a sent message reaches the window procedure without passing winit's message hook. It + /// notes them and passes every message on. + unsafe extern "system" fn wnd_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + note(message(msg, wparam.0, lparam.0)); + // SAFETY: `GetPropW` takes any handle value and a NUL-terminated name. + let prev = unsafe { GetPropW(hwnd, PREV_PROC) }.0; + if msg == WM_NCDESTROY { + // SAFETY: as above; the window is being destroyed. + let _ = unsafe { RemovePropW(hwnd, PREV_PROC) }; + } + if prev.is_null() { + // SAFETY: the default procedure takes any message of a window of this thread. + return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }; + } + // SAFETY: the property holds the window procedure `subclass` replaced, which stays valid + // while the window exists. + let prev = unsafe { std::mem::transmute::<*mut c_void, WNDPROC>(prev) }; + // SAFETY: `prev` is the window's own procedure, called with the message it was sent. + unsafe { CallWindowProcW(prev, hwnd, msg, wparam, lparam) } + } + + /// Another app became the active one: closes the context now, unless the reader is in a call of + /// its own, when the noted [`Message::Deactivated`] closes it at the next Wintab or pen message. + /// No pen messages come while another app is active, so waiting for one would leave the context + /// in front of that app's own. + fn deactivate() { + let Some(api) = api() else { return }; + STATE.with(|s| { + if let Ok(mut s) = s.try_borrow_mut() { + s.take_notices(api); + } + }); + } + + /// Whether this app is the active one: the foreground window belongs to this thread, which + /// runs every window of the app. + fn is_active() -> bool { + // SAFETY: `GetForegroundWindow` takes no arguments. + let foreground = unsafe { GetForegroundWindow() }; + // SAFETY: `GetWindowThreadProcessId` takes any handle value, and no process id is asked for. + !foreground.0.is_null() && unsafe { GetWindowThreadProcessId(foreground, None) } == unsafe { GetCurrentThreadId() } + } + + /// The thread's hook on the messages Windows sends to its windows' procedures, which winit's + /// message hook does not see: another app becoming the active one (`WM_ACTIVATEAPP`, sent to a + /// top-level window of the app, ) + /// closes the context ([`deactivate`]), and a pen's `WM_POINTERENTER` and `WM_POINTERLEAVE` + /// () go to + /// [`crate::windows_stylus::sent_message`]. The hook sees them whichever of the app's windows + /// they are sent to (). + unsafe extern "system" fn call_wnd_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + if code >= 0 { + // SAFETY: for `HC_ACTION` (0), `lParam` points to the message's `CWPSTRUCT`, which + // lives for the call; `as_ref` gives `None` for a null pointer. + if let Some(cwp) = unsafe { (lparam.0 as *const CWPSTRUCT).as_ref() } { + if message(cwp.message, cwp.wParam.0, cwp.lParam.0) == Message::Deactivated { + note(Message::Deactivated); + deactivate(); + } + crate::windows_stylus::sent_message(cwp.message, cwp.wParam.0); + } + } + // SAFETY: every hook procedure passes the call on, with what it was given. + unsafe { CallNextHookEx(None, code, wparam, lparam) } + } + + /// Installs [`call_wnd_proc`] for this thread, for a pen message at the message time `time`, + /// unless it is installed, and returns whether it is. It stays for the life of the thread. After + /// a failed install, a pen message tries again once [`retry_due`]. + fn hook_thread(time: u32) -> bool { + thread_local! { + /// Installed, or the message time of the last failed install. + static HOOK: std::cell::Cell>> = const { std::cell::Cell::new(Err(None)) }; + } + match HOOK.get() { + Ok(()) => return true, + Err(Some(at)) if !retry_due(at, time) => return false, + Err(_) => {} + } + // SAFETY: a hook of this thread, whose procedure is in this executable, so no module + // handle is passed. + let hooked = unsafe { SetWindowsHookExW(WH_CALLWNDPROC, Some(call_wnd_proc), None, GetCurrentThreadId()) }.is_ok(); + HOOK.set(if hooked { Ok(()) } else { Err(Some(time)) }); + hooked + } + + /// Closes the context for a deactivation noted while the reader was in a call of its own + /// ([`deactivate`]), once that call has ended. + fn settle() { + if NOTICES.with(|n| n.try_borrow().is_ok_and(|n| n.deactivated)) { + deactivate(); + } + } + + /// Puts [`wnd_proc`] in front of the window procedure of `hwnd`, once per window, and returns + /// whether it is there. The window's property holds the procedure it replaced, and goes with the + /// window. + fn subclass(hwnd: *mut c_void) -> bool { + let hwnd = HWND(hwnd); + // SAFETY: `GetPropW` and `GetWindowLongPtrW` take any handle value and read no caller memory. + if !unsafe { GetPropW(hwnd, PREV_PROC) }.0.is_null() { + return true; + } + // SAFETY: as above. + let prev = unsafe { GetWindowLongPtrW(hwnd, GWLP_WNDPROC) } as isize; + if prev == 0 { + return false; + } + // SAFETY: the window is this thread's (winit's), and the property's value is a procedure + // address, not memory the system frees. + if unsafe { SetPropW(hwnd, PREV_PROC, Some(HANDLE(prev as *mut c_void))) }.is_err() { + return false; + } + type Proc = unsafe extern "system" fn(HWND, u32, WPARAM, LPARAM) -> LRESULT; + // SAFETY: `wnd_proc` is a window procedure, and the window is this thread's. + if unsafe { SetWindowLongPtrW(hwnd, GWLP_WNDPROC, wnd_proc as Proc as usize as _) } as isize == 0 { + // SAFETY: as for `SetPropW`. + let _ = unsafe { RemovePropW(hwnd, PREV_PROC) }; + return false; + } + true + } + + /// The Wintab exports, or `None` without the driver's `Wintab32.dll` in the system directory. + fn api() -> Option { + static API: OnceLock> = OnceLock::new(); + *API.get_or_init(|| { + // SAFETY: Wintab32.dll is loaded from the system directory only, and stays loaded for + // the process, so the function pointers below stay valid. + let module = unsafe { LoadLibraryExW(w!("Wintab32.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) }.ok()?; + // SAFETY: the names are NUL-terminated, and the module is loaded. + let (info, open, close, packet) = unsafe { + ( + GetProcAddress(module, s!("WTInfoW"))?, + GetProcAddress(module, s!("WTOpenW"))?, + GetProcAddress(module, s!("WTClose"))?, + GetProcAddress(module, s!("WTPacket"))?, + ) + }; + type Proc = unsafe extern "system" fn() -> isize; + // SAFETY: the exports have these signatures (`wintab.h`). + unsafe { + Some(Api { + info: std::mem::transmute::(info), + open: std::mem::transmute::(open), + close: std::mem::transmute::(close), + packet: std::mem::transmute::(packet), + }) + } + }) + } + + /// `WTInfoW`'s answer for `category` and `index`, when it is exactly `N` 32-bit words. + fn info(api: Api, category: u32, index: u32) -> Option<[u32; N]> { + // SAFETY: a null buffer asks for the size only. + let size = unsafe { (api.info)(category, index, std::ptr::null_mut()) } as usize; + if N > 128 || size != N * 4 { + return None; + } + // Room for more than asked, should the driver write more than it said. + let mut buf = [0u32; 128]; + // SAFETY: `buf` holds 512 bytes, more than the size the driver gave. + let wrote = unsafe { (api.info)(category, index, buf.as_mut_ptr().cast()) } as usize; + let mut out = [0u32; N]; + out.copy_from_slice(buf.get(..N)?); + (wrote == N * 4).then_some(out) + } + + /// The wheel range of `cursor`: `Ok(None)` for a cursor the driver describes without one, and + /// `Err` when a `WTInfoW` call it needs fails. + fn cursor_axis(api: Api, cursor: u32) -> Result, ()> { + if cursor >= MAX_INDEX { + return Ok(None); + } + let [csr_type] = info::<1>(api, WTI_CURSORS + cursor, CSR_TYPE).ok_or(())?; + let [csr_pktdata] = info::<1>(api, WTI_CURSORS + cursor, CSR_PKTDATA).ok_or(())?; + if !is_airbrush(csr_type) || csr_pktdata & PK_TANGENT_PRESSURE == 0 { + return Ok(None); + } + let [count] = info::<1>(api, WTI_INTERFACE, IFC_NDEVICES).ok_or(())?; + let mut devices = vec![]; + for d in 0..count.min(MAX_DEVICES) { + let [first] = info::<1>(api, WTI_DEVICES + d, DVC_FIRSTCSR).ok_or(())?; + let [n] = info::<1>(api, WTI_DEVICES + d, DVC_NCSRTYPES).ok_or(())?; + devices.push((first, n)); + } + let Some(device) = device_of(cursor, &devices).and_then(|d| u32::try_from(d).ok()) else { return Ok(None) }; + let range = info::<4>(api, WTI_DEVICES + device, DVC_TPRESSURE).ok_or(())?; + Ok(wheel_axis(csr_type, csr_pktdata, Some(range))) + } + + /// Whether a context is open, or may be: [`STATE`] is borrowed for a driver call. + fn context_open() -> bool { + STATE.with(|s| !s.try_borrow().is_ok_and(|s| s.context.is_none())) + } + + fn is_window(hwnd: *mut c_void) -> bool { + // SAFETY: `IsWindow` takes any handle value and reads no caller memory. + unsafe { IsWindow(Some(HWND(hwnd))) }.as_bool() + } + + impl State { + fn close(&mut self, api: Api) { + if let Some(c) = self.context.take() { + // SAFETY: the handle came from `WTOpenW` and has not been closed. + unsafe { (api.close)(c.handle) }; + NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.closed_by_reader(c.handle as usize); + } + }); + } + self.readings.forget(); + } + + /// Acts on the driver's notices since the last look ([`Notices::take`]). + fn take_notices(&mut self, api: Api) { + let current = self.context.as_ref().map(|c| c.handle as usize); + let notice = NOTICES.with(|n| n.try_borrow_mut().map_or(Notice::default(), |mut n| n.take(current))); + if notice.closed { + self.context = None; + self.tried = None; + self.readings.forget(); + } + if notice.info_changed { + self.close(api); + self.tried = None; + self.cursors.clear(); + } + if notice.forget { + self.readings.forget(); + } + if notice.deactivated { + self.close(api); + self.tried = None; + } + } + + /// Moves the context to the window that owns `hwnd`, for a pen message at the message time + /// `time` ([`next_context`]), or closes it when the active tool does not use the wheel + /// (`wheel`, [`unused_context`]). + fn open_for(&mut self, api: Api, hwnd: *mut c_void, time: u32, wheel: Wheel) { + // SAFETY: `GetAncestor` takes any handle value and reads no caller memory. + let owner = unsafe { GetAncestor(HWND(hwnd), GA_ROOTOWNER) }.0; + let owner = if owner.is_null() { hwnd } else { owner }; + let current = self.context.as_ref().map(|c| (c.hwnd as usize, is_window(c.hwnd))); + let tried = self.tried.map(|(w, at)| (w as usize, at)); + let (step, open) = match wheel { + Wheel::Used => next_context(current, tried, owner as usize, time, is_active()), + Wheel::Unused => (unused_context(current), false), + }; + match step { + Current::Keep => {} + Current::Drop => { + self.context = None; + self.readings.forget(); + } + Current::Close => self.close(api), + } + if !open { + return; + } + self.tried = Some((owner, time)); + let Some(mut words) = info::(api, WTI_DEFCONTEXT, 0) else { return }; + configure(&mut words); + // Whether the app is active is asked again here, after the close and `WTInfoW` above. + let handle = hooked_open( + || subclass(owner), + is_active, + || { + // SAFETY: `words` is a `LOGCONTEXTW` of the size `WTInfoW` gave, and lives for + // the call. + let handle = unsafe { (api.open)(owner, words.as_mut_ptr().cast(), 1) }; + (!handle.is_null()).then_some(handle) + }, + ); + if let Some(handle) = handle { + self.context = Some(Context { handle, hwnd: owner }); + } + } + + fn ours(&self, hwnd: *mut c_void, ctx: usize) -> Option<*mut c_void> { + self.context.as_ref().filter(|c| c.hwnd == hwnd && c.handle as usize == ctx).map(|c| c.handle) + } + + fn axis(&mut self, api: Api, cursor: u32, time: u32) -> Option { + self.cursors.axis(cursor, time, || cursor_axis(api, cursor)) + } + } + + /// winit's message hook for the Wintab messages: reads each packet of the context and starts + /// the readings afresh on a cursor's change or proximity. A closing or information-change + /// notice that comes through the queue is noted as [`wnd_proc`] notes a sent one. It never + /// consumes the message. + pub fn msg_hook(msg: &MSG) { + let what = message(msg.message, msg.wParam.0, msg.lParam.0); + if what == Message::Other { + return; + } + if !calls_driver(WHEEL.get(), context_open()) { + return; + } + let Some(api) = api() else { return }; + note(what); + STATE.with(|s| { + let Ok(mut s) = s.try_borrow_mut() else { return }; + s.take_notices(api); + match what { + Message::Packet { serial, ctx } => { + let Some(handle) = s.ours(msg.hwnd.0, ctx) else { return }; + let mut buf = PacketBuffer([0; PACKET_BUFFER]); + // SAFETY: the handle is the open context's, and `buf` holds more bytes than a + // packet of every field. + let read = unsafe { (api.packet)(handle, serial, buf.0.as_mut_ptr().cast()) } != 0; + let read = read.then(|| decode(&buf.0, PACKET_DATA)).flatten().map(|p| (p, s.axis(api, p.cursor, msg.time))); + s.readings.read(read, msg.time); + } + Message::Forget { ctx } => { + if s.ours(msg.hwnd.0, ctx).is_some() { + s.readings.forget(); + } + } + Message::Closed { .. } | Message::InfoChange | Message::Deactivated | Message::Other => {} + } + }); + settle(); + } + + /// The wheel for a pointer message of the pen with the pointer id `pen` to `hwnd` at the message + /// time `time`, with its `eraser` end ([`Readings::wheel_for`]), opening the context first when + /// none is open. While the active tool does not use the wheel ([`set_wheel_used`]), it reads + /// none and calls the driver only to close a context still open ([`calls_driver`]). The first + /// call that opens a context installs [`call_wnd_proc`] ([`hook_thread`]); until it is + /// installed, no context opens and the pens read no wheel. + pub fn pen_wheel(hwnd: HWND, time: u32, pen: u32, eraser: bool) -> Option { + let used = WHEEL.get(); + if !calls_driver(used, context_open()) { + return None; + } + let api = api()?; + if used == Wheel::Used && !hook_thread(time) { + return None; + } + let wheel = STATE.with(|s| { + let mut s = s.try_borrow_mut().ok()?; + s.take_notices(api); + s.open_for(api, hwnd.0, time, used); + s.readings.wheel_for(time, pen, eraser) + }); + settle(); + wheel.filter(|_| used == Wheel::Used) + } + + /// The app says whether the active tool draws with a brush or tip that varies with the finger + /// wheel (`used`). Until it says so, pen messages read no wheel and leave the driver alone; when + /// it stops, the context closes now, or at the next pen message while the reader is in a call + /// of its own. + pub fn set_wheel_used(used: bool) { + let wheel = if used { Wheel::Used } else { Wheel::Unused }; + if WHEEL.replace(wheel) == wheel { + return; + } + STATE.with(|s| { + let Ok(mut s) = s.try_borrow_mut() else { return }; + s.tried = None; + if wheel == Wheel::Unused + && s.context.is_some() + && let Some(api) = api() + { + // A context the driver closed is dropped without `WTClose`. + s.take_notices(api); + s.close(api); + } + }); + settle(); + } + + /// The pen whose leaving starts the readings afresh, for a message of the pen with the pointer + /// id `pen` ([`Readings::owner_or`]). + pub fn wheel_pen(pen: u32) -> u32 { + STATE.with(|s| s.try_borrow().map_or(pen, |s| s.readings.owner_or(pen))) + } + + /// Start the readings afresh: the pen left the window or detection range, or a press was + /// canceled. While the readings are in use, as in a driver call, they start afresh at the next + /// Wintab or pen message ([`Notices::forget_later`]). + pub fn forget() { + STATE.with(|s| match s.try_borrow_mut() { + Ok(mut s) => s.readings.forget(), + Err(_) => NOTICES.with(|n| { + if let Ok(mut n) = n.try_borrow_mut() { + n.forget_later(); + } + }), + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The pointer id of the pen in the tests that use one pen. + const PEN: u32 = 1; + + impl Readings { + fn wheel_at(&mut self, time: u32, eraser: bool) -> Option { + self.wheel_for(time, PEN, eraser) + } + } + + /// A packet of the fields of `mask`: each 32-bit field holds its value in `values`, or a filler + /// when it has none, and the wider fields hold filler bytes. + fn bytes(mask: u32, values: &[(u32, u32)]) -> Vec { + let mut out = vec![]; + for &(f, n) in &FIELDS { + if mask & f == 0 { + continue; + } + let v = values.iter().find(|(k, _)| *k == f).map_or(0xAAAA_AAAA, |&(_, v)| v); + if n == 4 { + out.extend(v.to_ne_bytes()); + } else { + out.extend(std::iter::repeat_n(0xEE, n)); + } + } + out + } + + #[test] + fn the_context_asks_for_the_wheel_without_the_system_cursor() { + let mut words = [0u32; LOGCONTEXT_WORDS]; + words[LC_OPTIONS] = CXO_SYSTEM | CXO_PEN | 0x8000; + words[LC_MSG_BASE] = 0x1234; + words[LC_BTN_DN_MASK] = !0; + words[LC_BTN_UP_MASK] = !0; + words[LC_PKT_MODE] = PK_TANGENT_PRESSURE; + words[31] = 77; + configure(&mut words); + assert_eq!(words[LC_OPTIONS], CXO_MESSAGES | CXO_CSRMESSAGES | 0x8000, "the driver's other options stay"); + assert_eq!(words[LC_MSG_BASE], WT_DEFBASE); + assert_eq!(words[LC_PKT_DATA], PK_STATUS | PK_CURSOR | PK_X | PK_Y | PK_TANGENT_PRESSURE); + assert_eq!(words[LC_PKT_MODE], 0, "absolute"); + assert_eq!(words[LC_MOVE_MASK] & PK_TANGENT_PRESSURE, PK_TANGENT_PRESSURE, "a turn in place makes a packet"); + assert_eq!((words[LC_BTN_DN_MASK], words[LC_BTN_UP_MASK]), (0, 0)); + assert_eq!(words[31], 77, "the extents stay the driver's"); + } + + #[test] + fn packets_are_read_in_the_order_of_their_fields() { + let want = Packet { status: 0, cursor: 3, tangent: 600 }; + let p = bytes(PACKET_DATA, &[(PK_STATUS, 0), (PK_CURSOR, 3), (PK_TANGENT_PRESSURE, 600)]); + assert_eq!(p.len(), 20); + assert_eq!(decode(&p, PACKET_DATA), Some(want)); + // Every field before the tangential pressure, the context handle and the orientation + // after it. + let all = FIELDS.iter().fold(0, |m, (f, _)| m | f); + let p = bytes(all, &[(PK_STATUS, 0), (PK_CURSOR, 3), (PK_TANGENT_PRESSURE, 600)]); + assert_eq!(p.len(), packet_size(all)); + assert_eq!(packet_size(all), std::mem::size_of::() + 4 * 11 + 24); + assert_eq!(decode(&p, all), Some(want)); + assert_eq!(decode(&p[..p.len() - 1], all), None, "a short packet"); + assert_eq!(decode(&p, PK_STATUS | PK_CURSOR), None, "no tangential pressure"); + assert_eq!(field(&p, all, PK_ORIENTATION), None, "not a 32-bit field"); + assert!(packet_size(all) <= PACKET_BUFFER); + } + + #[test] + fn only_an_airbrush_with_a_range_reads_a_wheel() { + let range = |min: i32, max: i32| Some([min as u32, max as u32, 0, 0]); + let airbrush = 0x0902; + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(0, 1023)), Some(Axis { min: 0, max: 1023 })); + assert_eq!(wheel_axis(0x090A, PK_TANGENT_PRESSURE, range(-1023, 1023)), Some(Axis { min: -1023, max: 1023 }), "its other end"); + assert_eq!(wheel_axis(0x0802, PACKET_DATA, range(0, 1023)), None, "a general stylus"); + assert_eq!(wheel_axis(0x0804, PACKET_DATA, range(0, 1023)), None, "an Art Pen"); + assert_eq!(wheel_axis(airbrush, PK_X | PK_Y, range(0, 1023)), None, "no tangential pressure"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, None), None, "no range"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(0, 0)), None, "an empty range"); + assert_eq!(wheel_axis(airbrush, PACKET_DATA, range(1023, 0)), None, "a falling range"); + } + + #[test] + fn the_wheel_is_its_place_in_the_range() { + let axis = Axis { min: 0, max: 1000 }; + assert_eq!(axis.wheel(0), Some(0.0)); + assert_eq!(axis.wheel(250), Some(0.25)); + assert_eq!(axis.wheel(1000), Some(1.0)); + assert_eq!(axis.wheel(1001), None, "past the end"); + assert_eq!(axis.wheel(u32::MAX), None); + let signed = Axis { min: -1000, max: 1000 }; + assert_eq!(signed.wheel(-1000i32 as u32), Some(0.0)); + assert_eq!(signed.wheel(0), Some(0.5)); + assert_eq!(signed.wheel(500), Some(0.75)); + assert_eq!(signed.wheel(i32::MIN as u32), None); + let wide = Axis { min: i32::MIN, max: i32::MAX }; + assert_eq!(wide.wheel(i32::MAX as u32), Some(1.0), "no overflow"); + assert_eq!(Axis { min: 5, max: 5 }.wheel(5), None); + } + + #[test] + fn a_cursor_belongs_to_one_device() { + let devices = [(0, 3), (3, 3)]; + assert_eq!(device_of(1, &devices), Some(0)); + assert_eq!(device_of(4, &devices), Some(1)); + assert_eq!(device_of(6, &devices), None); + assert_eq!(device_of(1, &[(0, 3), (1, 1)]), None, "two devices claim it"); + assert_eq!(device_of(u32::MAX, &[(u32::MAX - 1, 5)]), None, "a range past the end"); + assert_eq!(device_of(0, &[]), None); + } + + const AXIS: Option = Some(Axis { min: 0, max: 1000 }); + + fn packet(cursor: u32, tangent: u32) -> Packet { + Packet { status: 0, cursor, tangent } + } + + #[test] + fn a_pen_message_takes_the_wheel_of_the_recent_airbrush() { + let mut r = Readings::default(); + assert_eq!(r.wheel_at(1000, false), None, "no packet"); + r.packet(packet(1, 250), AXIS, 1000); + assert_eq!(r.wheel_at(1010, false), Some(0.25)); + assert_eq!(r.wheel_at(1000 - MAX_SKEW_MS, false), Some(0.25), "a packet read just after the message"); + assert_eq!(r.wheel_at(60_000, false), Some(0.25), "a pen held still before it presses sends no packet"); + r.forget(); + r.packet(packet(1, 1000), AXIS, u32::MAX - 5); + r.packet(packet(2, 500), None, u32::MAX); + assert_eq!(r.wheel_at(10, false), None, "two cursors at once, across the clock's wrap"); + assert_eq!(r.wheel_at(9000, false), None, "neither recent"); + r.packet(packet(1, 1000), AXIS, 5000); + assert_eq!(r.wheel_at(5010, false), Some(1.0), "the recent one of two"); + r.forget(); + r.packet(packet(2, 500), None, 100); + assert_eq!(r.wheel_at(100, false), None, "a cursor without a wheel"); + r.packet(packet(1, 2000), AXIS, 300); + assert_eq!(r.wheel_at(500, false), None, "a value past the range"); + } + + #[test] + fn a_pen_keeps_the_airbrush_whose_wheel_it_read() { + let mut r = Readings::default(); + r.packet(packet(1, 250), AXIS, 1000); + assert_eq!(r.wheel_at(1000, false), Some(0.25)); + // Another tablet's airbrush moves while the pen is held still. + r.packet(packet(2, 750), AXIS, 5000); + assert_eq!(r.wheel_at(5010, false), Some(0.25), "its own cursor's wheel, not the other's"); + assert_eq!(r.wheel_at(9000, false), Some(0.25), "however old both packets are"); + r.packet(packet(1, 500), AXIS, 6000); + assert_eq!(r.wheel_at(6010, false), Some(0.5), "its own cursor again"); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(1, 500) }, AXIS, 6100); + r.packet(packet(2, 750), AXIS, 6105); + assert_eq!(r.wheel_at(6110, false), None, "its own cursor left; the other's is not taken"); + r.forget(); + r.packet(packet(2, 750), AXIS, 7000); + assert_eq!(r.wheel_at(7010, false), Some(0.75), "after the readings started afresh"); + } + + #[test] + fn zero_is_no_wheel_until_the_pen_reports_another_value() { + let mut r = Readings::default(); + r.packet(packet(1, 0), AXIS, 100); + assert_eq!(r.wheel_at(100, false), None); + r.packet(packet(1, 300), AXIS, 110); + r.packet(packet(1, 0), AXIS, 120); + assert_eq!(r.wheel_at(120, false), Some(0.0), "a real 0 after another value"); + r.forget(); + r.packet(packet(1, 0), AXIS, 130); + assert_eq!(r.wheel_at(130, false), None, "afresh after the pen came near"); + } + + #[test] + fn the_readings_start_afresh_for_the_other_end_and_out_of_the_context() { + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + assert_eq!(r.wheel_at(100, false), Some(0.3)); + assert_eq!(r.wheel_at(100, true), None, "the other end"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(110, true), Some(0.3)); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(1, 300) }, AXIS, 120); + assert_eq!(r.wheel_at(120, true), None, "out of the context"); + r.packet(packet(1, 300), AXIS, 130); + r.packet(Packet { status: TPS_QUEUE_ERR, ..packet(1, 300) }, AXIS, 140); + assert_eq!(r.wheel_at(140, true), None, "the queue overflowed"); + // The eraser end leaves; the tip's first message after it keeps the tip's packet. + r.forget(); + r.packet(packet(1, 300), AXIS, 150); + assert_eq!(r.wheel_at(150, false), Some(0.3), "after the readings started afresh"); + r.forget(); + for c in 0..10 { + r.packet(packet(c, 300), AXIS, 1000 * c); + } + assert_eq!(r.list.len(), MAX_READINGS, "bounded"); + assert_eq!(r.wheel_at(9000, false), Some(0.3)); + } + + /// [`next_context`] while this app is the active one. + fn step(current: Option<(usize, bool)>, tried: Option<(usize, u32)>, owner: usize, time: u32) -> (Current, bool) { + next_context(current, tried, owner, time, true) + } + + #[test] + fn the_context_follows_the_window_the_pen_draws_in() { + let (main, doc) = (0x10, 0x20); + let t = 1000; + assert_eq!(step(None, None, main, t), (Current::Keep, true), "the first pen message opens it"); + assert_eq!(step(Some((main, true)), Some((main, t)), main, t), (Current::Keep, false), "the same window keeps it"); + assert_eq!(step(Some((main, true)), Some((main, t)), main, t + 60_000), (Current::Keep, false), "however long it is open"); + assert_eq!(step(Some((main, true)), Some((main, t)), doc, t), (Current::Close, true), "another document window"); + assert_eq!(step(Some((doc, true)), Some((doc, t)), main, t), (Current::Close, true), "and back"); + assert_eq!(step(Some((main, false)), Some((main, t)), doc, t), (Current::Drop, true), "a window that is gone"); + assert_eq!(step(Some((main, false)), Some((main, t)), main, t), (Current::Drop, true), "its handle reused"); + assert_eq!(step(None, Some((main, t)), main, t + 1), (Current::Keep, false), "an open that failed is not tried at once"); + assert_eq!(step(None, Some((main, t)), doc, t + 1), (Current::Keep, true), "but is for another window"); + } + + #[test] + fn a_window_whose_open_failed_is_tried_again_later() { + let main = 0x10; + let t = 1000; + for dt in [0, 1, 500, RETRY_MS - 1] { + assert_eq!(step(None, Some((main, t)), main, t + dt), (Current::Keep, false), "{dt} ms later"); + } + assert_eq!(step(None, Some((main, t)), main, t + RETRY_MS), (Current::Keep, true), "after the retry interval"); + assert_eq!(step(None, Some((main, t)), main, t + 60_000), (Current::Keep, true), "or long after"); + // The message clock wraps after about 49.7 days. + let late = u32::MAX - 100; + assert_eq!(step(None, Some((main, late)), main, late.wrapping_add(50)), (Current::Keep, false), "across the wrap"); + assert_eq!(step(None, Some((main, late)), main, late.wrapping_add(RETRY_MS)), (Current::Keep, true), "and due across it"); + } + + #[test] + fn a_failed_step_is_retried_after_the_interval() { + assert!(!retry_due(1000, 1000), "at once"); + assert!(!retry_due(1000, 1000 + RETRY_MS - 1)); + assert!(retry_due(1000, 1000 + RETRY_MS), "after the interval"); + assert!(retry_due(u32::MAX - 10, (u32::MAX - 10).wrapping_add(RETRY_MS)), "across the clock's wrap"); + assert!(!retry_due(u32::MAX - 10, 5), "and not early across it"); + } + + #[test] + fn no_context_opens_while_another_app_is_active() { + let (main, doc) = (0x10, 0x20); + let t = 1000; + assert_eq!(next_context(None, None, main, t, false), (Current::Keep, false), "a pen hovering over an inactive window"); + assert_eq!(next_context(None, Some((main, t)), main, t + RETRY_MS, false), (Current::Keep, false), "not even when a retry is due"); + assert_eq!(next_context(Some((main, true)), None, doc, t, false), (Current::Close, false), "another window's context closes"); + assert_eq!(next_context(Some((main, false)), None, main, t, false), (Current::Drop, false), "a gone window's is dropped"); + assert_eq!(next_context(None, None, main, t, true), (Current::Keep, true), "and the app's return opens it"); + } + + #[test] + fn the_driver_is_left_alone_until_the_wheel_is_used() { + assert!(!calls_driver(Wheel::Unused, false), "no brush or tip on Stylus Wheel"); + assert!(calls_driver(Wheel::Used, false), "one is: the context opens"); + assert!(calls_driver(Wheel::Unused, true), "none any more: the open context closes"); + assert_eq!(Wheel::default(), Wheel::Unused, "at start-up"); + let main = 0x10; + assert_eq!(unused_context(None), Current::Keep, "nothing open"); + assert_eq!(unused_context(Some((main, true))), Current::Close, "the pen window's context closes"); + assert_eq!(unused_context(Some((main, false))), Current::Drop, "a gone window's is dropped"); + } + + #[test] + fn another_app_becoming_active_closes_the_context() { + assert_eq!(message(WM_ACTIVATEAPP, 0, 0), Message::Deactivated); + assert_eq!(message(WM_ACTIVATEAPP, 1, 0), Message::Other, "this app becoming active"); + let ours = 0x5000; + let mut n = Notices::default(); + n.note(Message::Deactivated); + assert_eq!(n.take(Some(ours)), Notice { deactivated: true, ..Notice::default() }); + assert_eq!(n.take(Some(ours)), Notice::default(), "once"); + n.note(Message::Deactivated); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), Notice { closed: true, deactivated: true, ..Notice::default() }, "beside the driver's close"); + } + + #[test] + fn a_packet_that_cannot_be_read_starts_the_readings_afresh() { + let mut r = Readings::default(); + r.read(Some((packet(1, 750), AXIS)), 100); + assert_eq!(r.wheel_at(100, false), Some(0.75)); + r.read(None, 110); + assert_eq!(r.wheel_at(110, false), None, "the last reading is not kept after a failed read"); + r.read(Some((packet(1, 500), AXIS)), 120); + assert_eq!(r.wheel_at(120, false), Some(0.5), "the next packet reads again"); + } + + #[test] + fn the_drivers_notices_drop_or_reopen_the_context() { + let (ours, other) = (0x5000, 0x6000); + let keep = Notice::default(); + let closed = Notice { closed: true, ..Notice::default() }; + let reopen = Notice { info_changed: true, ..Notice::default() }; + let mut n = Notices::default(); + assert_eq!(n.take(Some(ours)), keep, "no notice"); + n.note(Message::Closed { ctx: other }); + assert_eq!(n.take(Some(ours)), keep, "another context closed"); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), closed, "the driver closed it"); + assert_eq!(n.take(Some(ours)), keep, "taken once"); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(None), keep, "nothing open"); + assert_eq!(n, Notices::default(), "and the notice is gone"); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), reopen); + n.note(Message::InfoChange); + assert_eq!(n.take(None), reopen, "cursor ranges are read again even with nothing open"); + // The reader closes its context, and the driver's notice of that arrives during the call; + // a context opened next under the same handle value stays open. + n.note(Message::Closed { ctx: ours }); + n.closed_by_reader(ours); + assert_eq!(n.take(Some(ours)), keep); + for ctx in 0..20 { + n.note(Message::Closed { ctx }); + n.note(Message::Closed { ctx }); + } + assert_eq!(n.closed.len(), MAX_NOTICES, "bounded, each context once"); + assert_eq!(n.take(Some(19)), closed, "the latest kept"); + n.note(Message::Packet { serial: 1, ctx: ours }); + n.note(Message::Forget { ctx: ours }); + n.note(Message::Other); + assert_eq!(n, Notices::default(), "other messages are not notices"); + } + + #[test] + fn a_close_and_an_information_change_in_one_batch_both_count() { + let ours = 0x5000; + let both = Notice { closed: true, info_changed: true, ..Notice::default() }; + let mut n = Notices::default(); + n.note(Message::Closed { ctx: ours }); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), both, "the closed handle is dropped, not closed again"); + n.note(Message::InfoChange); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), both, "in either order"); + n.note(Message::Closed { ctx: 0x6000 }); + n.note(Message::InfoChange); + assert_eq!(n.take(Some(ours)), Notice { info_changed: true, ..Notice::default() }, "another context's close"); + } + + #[test] + fn a_leave_while_the_readings_are_in_use_starts_them_afresh_next() { + let ours = 0x5000; + let mut n = Notices::default(); + n.forget_later(); + assert_eq!(n.take(Some(ours)), Notice { forget: true, ..Notice::default() }, "the next look starts the readings afresh"); + assert_eq!(n.take(Some(ours)), Notice::default(), "once"); + n.forget_later(); + assert_eq!(n.take(None), Notice { forget: true, ..Notice::default() }, "with nothing open too"); + n.forget_later(); + n.note(Message::Closed { ctx: ours }); + assert_eq!(n.take(Some(ours)), Notice { closed: true, forget: true, ..Notice::default() }, "beside a close"); + } + + #[test] + fn a_context_opens_only_behind_the_window_procedure() { + let opens = std::cell::Cell::new(0); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| true, || true, open), Some(7)); + assert_eq!(opens.get(), 1); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| false, || true, open), None, "no context without the procedure"); + assert_eq!(opens.get(), 1, "and the driver is not asked for one"); + assert_eq!(hooked_open(|| true, || true, || None::), None, "an open that fails"); + } + + #[test] + fn no_context_opens_when_another_app_became_active_before_the_open() { + let opens = std::cell::Cell::new(0); + let open = || { + opens.set(opens.get() + 1); + Some(7) + }; + assert_eq!(hooked_open(|| true, || false, open), None); + assert_eq!(opens.get(), 0, "the driver is not asked for one"); + } + + #[test] + fn another_pens_end_does_not_start_the_readings_afresh() { + let other = 2; + let mut r = Readings::default(); + assert_eq!(r.wheel_for(100, other, true), None, "an eraser end before any packet"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(120, false), Some(0.3), "another pen's tip still reads the packet"); + assert_eq!(r.wheel_at(130, true), None, "the same pen turned over starts them afresh"); + // Pen 1's tip, then pen 2's, then pen 1's eraser, before either reads a wheel. + r.forget(); + assert_eq!(r.wheel_at(200, false), None, "no packet yet"); + assert_eq!(r.wheel_for(210, other, false), None); + r.packet(packet(1, 300), AXIS, 220); + assert_eq!(r.wheel_at(230, true), None, "pen 1's turn is seen past pen 2's message"); + for pen in 10..40 { + r.wheel_for(5000, pen, false); + } + assert_eq!(r.ends.len(), MAX_PENS, "bounded"); + } + + #[test] + fn a_failed_cursor_lookup_is_asked_again_later() { + let asks = std::cell::Cell::new(0); + let failing = || { + asks.set(asks.get() + 1); + Err(()) + }; + let mut c = Cursors::default(); + assert_eq!(c.axis(1, 1000, failing), None); + assert_eq!(c.axis(1, 1000 + RETRY_MS - 1, || Ok(AXIS)), None, "not asked again before the interval"); + assert_eq!(asks.get(), 1); + assert_eq!(c.axis(1, 1000 + RETRY_MS, || Ok(AXIS)), AXIS, "asked again after it"); + assert_eq!(c.axis(1, 9000, || Ok(None)), AXIS, "a range the driver gave is kept"); + assert_eq!(c.axis(2, 9000, || Ok(None)), None, "a cursor without a wheel"); + assert_eq!(c.axis(2, 9000 + RETRY_MS, || Ok(AXIS)), None, "is not asked again"); + c.clear(); + assert_eq!(c.axis(2, 9000, || Ok(AXIS)), AXIS, "until the driver's information changes"); + for cursor in 10..40 { + c.axis(cursor, 9000, || Ok(None)); + } + assert_eq!(c.0.len(), MAX_READINGS * 4, "bounded"); + } + + #[test] + fn the_readings_belong_to_the_pen_that_took_them_first() { + let other = 2; + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + assert_eq!(r.wheel_for(5000, other, false), None, "a pen message long after the packet does not take them"); + assert_eq!(r.wheel_for(150, other, false), Some(0.3), "one near the packet does"); + assert_eq!(r.wheel_at(5010, false), None, "another pen with no packets of its own"); + assert_eq!(r.wheel_for(5020, other, false), Some(0.3), "and the pen that took them still reads them"); + r.forget(); + assert_eq!(r.wheel_at(5030, false), None, "no packet since the readings started afresh"); + r.packet(packet(1, 400), AXIS, 5040); + assert_eq!(r.wheel_at(5040, false), Some(0.4), "then another pen takes them"); + } + + #[test] + fn a_pen_takes_the_readings_only_when_it_reads_a_wheel() { + let other = 2; + let mut r = Readings::default(); + assert_eq!(r.wheel_for(100, other, false), None, "no packet yet"); + assert_eq!(r.owner_or(PEN), PEN, "and no pen took the readings"); + r.packet(packet(1, 300), AXIS, 110); + assert_eq!(r.wheel_at(110, false), Some(0.3), "the pen with the reading"); + assert_eq!(r.owner_or(other), PEN, "the pen whose leaving starts the readings afresh"); + r.forget(); + assert_eq!(r.owner_or(other), other); + } + + #[test] + fn a_queue_overflow_starts_every_reading_afresh() { + let mut r = Readings::default(); + r.packet(packet(1, 300), AXIS, 100); + r.packet(packet(2, 500), None, 110); + r.packet(Packet { status: TPS_QUEUE_ERR, ..packet(2, 500) }, None, 120); + assert!(r.list.is_empty(), "the queue is the context's, not the cursor's"); + assert_eq!(r.wheel_at(5000, false), None, "the airbrush's old wheel is not taken"); + r.packet(packet(1, 400), AXIS, 5000); + assert_eq!(r.wheel_at(5000, false), Some(0.4), "the next packet reads again"); + r.packet(packet(2, 500), None, 5010); + r.packet(Packet { status: TPS_PROXIMITY, ..packet(2, 500) }, None, 5020); + assert_eq!(r.list.len(), 1, "a cursor that leaves drops only its own reading"); + } + + #[test] + fn wintab_messages_name_their_context() { + assert_eq!(message(WT_PACKET, 42, 0x5000), Message::Packet { serial: 42, ctx: 0x5000 }); + assert_eq!(message(WT_CSRCHANGE, 42, 0x5000), Message::Forget { ctx: 0x5000 }); + assert_eq!(message(WT_PROXIMITY, 0x5000, 1), Message::Forget { ctx: 0x5000 }); + assert_eq!(message(WT_CTXCLOSE, 0x5000, 0), Message::Closed { ctx: 0x5000 }); + assert_eq!(message(WT_INFOCHANGE, 0, 0), Message::InfoChange); + // WM_POINTERUPDATE and the context-open message. + assert_eq!(message(0x0245, 0, 0), Message::Other); + assert_eq!(message(WT_DEFBASE + 1, 0, 0), Message::Other); + } +} diff --git a/assets/icons/dc-arrow-left.svg b/assets/icons/dc-arrow-left.svg new file mode 100644 index 0000000000..4d2ad158b6 --- /dev/null +++ b/assets/icons/dc-arrow-left.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-arrow-right.svg b/assets/icons/dc-arrow-right.svg new file mode 100644 index 0000000000..f53cc9e5ef --- /dev/null +++ b/assets/icons/dc-arrow-right.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-cap-butt.svg b/assets/icons/dc-cap-butt.svg index bf39a170a6..dee85e09a0 100644 --- a/assets/icons/dc-cap-butt.svg +++ b/assets/icons/dc-cap-butt.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-cap-round.svg b/assets/icons/dc-cap-round.svg index 06af9d07ea..bcf2e976c4 100644 --- a/assets/icons/dc-cap-round.svg +++ b/assets/icons/dc-cap-round.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-cap-square.svg b/assets/icons/dc-cap-square.svg index 4a82a10d9a..5fcb2e3c5d 100644 --- a/assets/icons/dc-cap-square.svg +++ b/assets/icons/dc-cap-square.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-guide-horizontal.svg b/assets/icons/dc-guide-horizontal.svg new file mode 100644 index 0000000000..941eba1f1d --- /dev/null +++ b/assets/icons/dc-guide-horizontal.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-guide-vertical.svg b/assets/icons/dc-guide-vertical.svg new file mode 100644 index 0000000000..3383fd4c22 --- /dev/null +++ b/assets/icons/dc-guide-vertical.svg @@ -0,0 +1 @@ + diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index 53fa68502a..f97d3db59d 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -22,3 +22,4 @@ moxcms = "0.8" [dev-dependencies] proptest = { workspace = true } serde_json = { workspace = true } +sha2 = { version = "0.10", default-features = false } diff --git a/crates/color/data/.gitattributes b/crates/color/data/.gitattributes new file mode 100644 index 0000000000..05b9b7ef3c --- /dev/null +++ b/crates/color/data/.gitattributes @@ -0,0 +1,2 @@ +# The characterization data files are kept byte for byte as published (CRLF line endings). +*.txt -text diff --git a/crates/color/data/FOGRA51.txt b/crates/color/data/FOGRA51.txt new file mode 100644 index 0000000000..1bf721cbbd --- /dev/null +++ b/crates/color/data/FOGRA51.txt @@ -0,0 +1,1641 @@ +ISO28178 +FILE_DESCRIPTOR "FOGRA51" +ORIGINATOR "Fogra, www.fogra.org, developed by GMG GmbH & Co. KG, Heidelberger Druckmaschinen AG" +CREATED "May 2015" +TARGET_TYPE "ISO12642-2" +INSTRUMENTATION "D50, 2 degree, geometry 45/0, no polarisation filter, white backing, according to ISO 13655:2009 M1" +PRINT_CONDITIONS "Offset printing, according to ISO 12647-2:2013, OFCOM, print substrate 1 = premium coated, fluorescence moderate (8-14 DeltaB according to ISO 15397), 115 g/m2, tone value increase curves A (CMYK)" +ILLUMINATION_NAME "D50" +OBSERVER_ANGLE "2" +FILTER "M1" +WEIGHTING_FUNCTION "ILLUMINANT, D50" +WEIGHTING_FUNCTION "OBSERVER, 2 degree" + +# The following flag is intended to improve compatibility with legacy devices. +KEYWORD "TRACEABILITY" +TRACEABILITY "NIST" + +NUMBER_OF_FIELDS 8 +BEGIN_DATA_FORMAT +SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B +END_DATA_FORMAT +NUMBER_OF_SETS 1617 +BEGIN_DATA +1 0 0 0 0 95.00 1.50 -6.00 +2 0 10 0 0 90.08 8.15 -7.42 +3 0 20 0 0 85.20 14.67 -8.29 +4 0 30 0 0 80.33 21.39 -8.87 +5 0 40 0 0 75.43 28.45 -9.24 +6 0 55 0 0 67.98 40.01 -9.56 +7 0 70 0 0 60.42 52.69 -9.17 +8 0 85 0 0 53.32 65.54 -7.71 +9 0 100 0 0 48.06 75.29 -5.18 +10 10 0 0 0 91.19 -2.28 -10.93 +11 10 10 0 0 86.47 4.14 -11.97 +12 10 20 0 0 81.74 10.48 -12.69 +13 10 30 0 0 77.05 17.05 -13.20 +14 10 40 0 0 72.39 23.71 -13.36 +15 10 55 0 0 65.04 35.29 -13.80 +16 10 70 0 0 57.69 47.54 -13.21 +17 10 85 0 0 50.64 60.42 -12.20 +18 10 100 0 0 45.36 70.44 -10.15 +19 20 0 0 0 87.20 -5.64 -15.58 +20 20 10 0 0 82.71 0.55 -16.41 +21 20 20 0 0 78.13 6.82 -17.10 +22 20 30 0 0 73.63 12.96 -17.21 +23 20 40 0 0 69.00 19.75 -17.58 +24 20 55 0 0 61.92 30.79 -17.90 +25 20 70 0 0 54.67 43.07 -17.59 +26 20 85 0 0 47.85 55.48 -16.64 +27 20 100 0 0 42.75 65.36 -14.76 +28 30 0 0 0 83.19 -9.04 -20.26 +29 30 10 0 0 78.86 -3.06 -21.03 +30 30 20 0 0 74.49 3.06 -21.47 +31 30 30 0 0 70.10 9.12 -21.61 +32 30 40 0 0 65.63 15.55 -21.84 +33 30 55 0 0 58.82 26.25 -21.96 +34 30 70 0 0 51.79 38.09 -21.59 +35 30 85 0 0 45.06 50.62 -20.96 +36 30 100 0 0 40.08 60.48 -19.61 +37 40 0 0 0 79.15 -12.57 -24.94 +38 40 10 0 0 74.98 -6.71 -25.60 +39 40 20 0 0 70.80 -0.81 -25.82 +40 40 30 0 0 66.54 5.13 -25.91 +41 40 40 0 0 62.24 11.37 -26.06 +42 40 55 0 0 55.70 21.88 -26.29 +43 40 70 0 0 48.86 33.45 -25.85 +44 40 85 0 0 42.31 45.45 -25.15 +45 40 100 0 0 37.42 55.26 -24.13 +46 55 0 0 0 72.95 -18.09 -32.32 +47 55 10 0 0 69.08 -12.46 -32.61 +48 55 20 0 0 65.15 -6.92 -32.53 +49 55 30 0 0 61.16 -1.28 -32.51 +50 55 40 0 0 57.13 4.79 -32.58 +51 55 55 0 0 50.88 15.11 -32.86 +52 55 70 0 0 44.47 25.94 -32.21 +53 55 85 0 0 38.22 37.55 -31.73 +54 55 100 0 0 33.61 47.12 -31.03 +55 70 0 0 0 66.57 -24.03 -39.84 +56 70 10 0 0 63.02 -18.76 -39.93 +57 70 20 0 0 59.38 -13.26 -39.73 +58 70 30 0 0 55.73 -8.01 -39.46 +59 70 40 0 0 51.98 -2.30 -39.36 +60 70 55 0 0 46.09 7.47 -39.17 +61 70 70 0 0 40.13 17.91 -38.49 +62 70 85 0 0 34.29 29.43 -38.42 +63 70 100 0 0 30.05 38.27 -37.82 +64 85 0 0 0 60.62 -30.20 -47.07 +65 85 10 0 0 57.34 -25.34 -47.00 +66 85 20 0 0 54.05 -20.11 -46.39 +67 85 30 0 0 50.67 -14.86 -46.05 +68 85 40 0 0 47.21 -9.60 -45.78 +69 85 55 0 0 41.82 -0.52 -45.22 +70 85 70 0 0 36.22 9.96 -44.61 +71 85 85 0 0 30.93 20.56 -44.00 +72 85 100 0 0 26.93 28.85 -43.51 +73 100 0 0 0 56.12 -34.90 -52.52 +74 100 10 0 0 53.12 -30.18 -52.18 +75 100 20 0 0 49.98 -25.20 -51.65 +76 100 30 0 0 46.82 -20.29 -51.01 +77 100 40 0 0 43.67 -14.81 -50.35 +78 100 55 0 0 38.75 -6.19 -49.58 +79 100 70 0 0 33.65 3.36 -48.78 +80 100 85 0 0 28.60 13.42 -48.00 +81 100 100 0 0 24.74 21.12 -47.45 +82 0 0 10 0 94.39 -0.05 3.02 +83 0 10 10 0 89.49 6.73 1.30 +84 0 20 10 0 84.62 13.27 0.10 +85 0 30 10 0 79.82 20.14 -0.92 +86 0 40 10 0 75.00 27.19 -1.77 +87 0 55 10 0 67.58 39.10 -2.81 +88 0 70 10 0 60.05 51.73 -2.96 +89 0 85 10 0 53.14 64.72 -2.17 +90 0 100 10 0 48.16 74.50 -0.60 +91 10 0 10 0 90.49 -4.02 -1.77 +92 10 10 10 0 85.82 2.56 -3.46 +93 10 20 10 0 81.12 9.05 -4.50 +94 10 30 10 0 76.46 15.71 -5.46 +95 10 40 10 0 71.79 22.68 -6.25 +96 10 55 10 0 64.57 34.21 -7.17 +97 10 70 10 0 57.26 46.86 -7.31 +98 10 85 10 0 50.43 59.66 -6.79 +99 10 100 10 0 45.39 69.49 -5.43 +100 20 0 10 0 86.44 -7.45 -6.60 +101 20 10 10 0 82.01 -1.17 -8.02 +102 20 20 10 0 77.49 5.15 -8.92 +103 20 30 10 0 72.97 11.64 -9.73 +104 20 40 10 0 68.44 18.44 -10.47 +105 20 55 10 0 61.44 29.71 -11.32 +106 20 70 10 0 54.31 42.07 -11.62 +107 20 85 10 0 47.62 54.54 -11.26 +108 20 100 10 0 42.65 64.50 -10.16 +109 30 0 10 0 82.42 -11.08 -11.48 +110 30 10 10 0 78.15 -5.00 -12.67 +111 30 20 10 0 73.82 1.16 -13.49 +112 30 30 10 0 69.44 7.49 -14.18 +113 30 40 10 0 65.05 14.11 -14.78 +114 30 55 10 0 58.30 25.08 -15.56 +115 30 70 10 0 51.40 37.07 -15.81 +116 30 85 10 0 44.85 49.58 -15.76 +117 30 100 10 0 40.03 59.14 -14.92 +118 40 0 10 0 78.34 -14.91 -16.35 +119 40 10 10 0 74.24 -8.90 -17.42 +120 40 20 10 0 70.09 -2.91 -17.98 +121 40 30 10 0 65.91 3.27 -18.54 +122 40 40 10 0 61.68 9.69 -19.12 +123 40 55 10 0 55.18 20.32 -19.84 +124 40 70 10 0 48.45 32.09 -20.21 +125 40 85 10 0 42.11 44.34 -20.15 +126 40 100 10 0 37.43 53.85 -19.55 +127 55 0 10 0 72.13 -20.88 -23.94 +128 55 10 10 0 68.33 -15.07 -24.69 +129 55 20 10 0 64.46 -9.33 -25.04 +130 55 30 10 0 60.56 -3.46 -25.47 +131 55 40 10 0 56.60 2.73 -25.84 +132 55 55 10 0 50.46 12.95 -26.33 +133 55 70 10 0 44.07 24.26 -26.67 +134 55 85 10 0 37.99 36.05 -26.83 +135 55 100 10 0 33.49 45.40 -26.61 +136 70 0 10 0 65.70 -27.36 -31.85 +137 70 10 10 0 62.29 -21.91 -32.17 +138 70 20 10 0 58.73 -16.35 -32.31 +139 70 30 10 0 55.11 -10.78 -32.46 +140 70 40 10 0 51.44 -4.87 -32.68 +141 70 55 10 0 45.66 4.96 -33.04 +142 70 70 10 0 39.72 15.80 -33.20 +143 70 85 10 0 34.08 27.07 -33.31 +144 70 100 10 0 29.85 36.13 -33.10 +145 85 0 10 0 59.68 -34.68 -39.35 +146 85 10 10 0 56.58 -29.13 -39.40 +147 85 20 10 0 53.35 -23.81 -39.27 +148 85 30 10 0 50.01 -18.41 -39.22 +149 85 40 10 0 46.60 -12.87 -39.27 +150 85 55 10 0 41.29 -3.48 -39.33 +151 85 70 10 0 35.80 6.88 -39.36 +152 85 85 10 0 30.60 17.60 -39.25 +153 85 100 10 0 26.69 26.51 -39.05 +154 100 0 10 0 55.09 -39.46 -45.04 +155 100 10 10 0 52.33 -34.67 -44.86 +156 100 20 10 0 49.27 -29.55 -44.55 +157 100 30 10 0 46.18 -24.31 -44.32 +158 100 40 10 0 43.11 -18.79 -44.05 +159 100 55 10 0 38.18 -9.90 -43.86 +160 100 70 10 0 33.15 -0.14 -43.50 +161 100 85 10 0 28.30 10.01 -43.28 +162 100 100 10 0 24.62 18.19 -43.14 +163 0 0 20 0 93.66 -1.17 11.88 +164 0 10 20 0 88.80 5.61 9.82 +165 0 20 20 0 83.99 12.38 8.29 +166 0 30 20 0 79.22 19.33 6.84 +167 0 40 20 0 74.45 26.49 5.48 +168 0 55 20 0 67.16 38.37 3.96 +169 0 70 20 0 59.71 51.18 3.25 +170 0 85 20 0 52.90 63.96 3.39 +171 0 100 20 0 48.12 73.47 4.61 +172 10 0 20 0 89.71 -5.18 6.94 +173 10 10 20 0 85.11 1.37 4.94 +174 10 20 20 0 80.48 7.98 3.55 +175 10 30 20 0 75.86 14.70 2.17 +176 10 40 20 0 71.22 21.76 0.95 +177 10 55 20 0 64.07 33.39 -0.52 +178 10 70 20 0 56.85 46.17 -1.38 +179 10 85 20 0 50.19 58.88 -1.37 +180 10 100 20 0 45.29 68.63 -0.38 +181 20 0 20 0 85.72 -8.99 2.17 +182 20 10 20 0 81.30 -2.54 0.32 +183 20 20 20 0 76.83 3.86 -1.11 +184 20 30 20 0 72.35 10.44 -2.33 +185 20 40 20 0 67.84 17.35 -3.39 +186 20 55 20 0 60.91 28.74 -4.79 +187 20 70 20 0 53.93 41.13 -5.60 +188 20 85 20 0 47.39 53.82 -5.87 +189 20 100 20 0 42.55 63.34 -5.04 +190 30 0 20 0 81.66 -12.79 -2.89 +191 30 10 20 0 77.44 -6.52 -4.62 +192 30 20 20 0 73.13 -0.29 -5.75 +193 30 30 20 0 68.80 6.12 -6.82 +194 30 40 20 0 64.43 12.85 -7.84 +195 30 55 20 0 57.77 23.97 -9.14 +196 30 70 20 0 50.99 36.22 -10.04 +197 30 85 20 0 44.59 48.53 -10.43 +198 30 100 20 0 39.88 58.18 -9.88 +199 40 0 20 0 77.55 -16.73 -7.99 +200 40 10 20 0 73.52 -10.68 -9.43 +201 40 20 20 0 69.39 -4.59 -10.41 +202 40 30 20 0 65.23 1.69 -11.32 +203 40 40 20 0 61.04 8.29 -12.27 +204 40 55 20 0 54.63 19.05 -13.50 +205 40 70 20 0 48.07 30.94 -14.39 +206 40 85 20 0 41.81 43.21 -15.01 +207 40 100 20 0 37.28 52.69 -14.60 +208 55 0 20 0 71.31 -23.09 -15.80 +209 55 10 20 0 67.58 -17.25 -16.84 +210 55 20 20 0 63.73 -11.42 -17.58 +211 55 30 20 0 59.85 -5.38 -18.43 +212 55 40 20 0 55.97 0.93 -19.08 +213 55 55 20 0 49.94 11.27 -20.01 +214 55 70 20 0 43.68 22.77 -20.85 +215 55 85 20 0 37.73 34.62 -21.62 +216 55 100 20 0 33.31 43.89 -21.69 +217 70 0 20 0 64.93 -30.24 -23.83 +218 70 10 20 0 61.50 -24.61 -24.57 +219 70 20 20 0 57.98 -18.95 -25.00 +220 70 30 20 0 54.40 -13.10 -25.57 +221 70 40 20 0 50.79 -7.11 -26.06 +222 70 55 20 0 45.17 2.77 -26.82 +223 70 70 20 0 39.33 13.82 -27.50 +224 70 85 20 0 33.74 25.26 -28.26 +225 70 100 20 0 29.61 34.33 -28.32 +226 85 0 20 0 58.88 -38.00 -31.58 +227 85 10 20 0 55.83 -32.55 -31.96 +228 85 20 20 0 52.62 -27.03 -32.09 +229 85 30 20 0 49.31 -21.43 -32.36 +230 85 40 20 0 45.93 -15.65 -32.81 +231 85 55 20 0 40.74 -6.29 -33.32 +232 85 70 20 0 35.38 4.26 -33.81 +233 85 85 20 0 30.26 15.11 -34.30 +234 85 100 20 0 26.54 23.88 -34.29 +235 100 0 20 0 54.45 -43.84 -37.25 +236 100 10 20 0 51.62 -38.86 -37.54 +237 100 20 20 0 48.62 -33.48 -37.55 +238 100 30 20 0 45.58 -28.05 -37.59 +239 100 40 20 0 42.45 -22.44 -37.78 +240 100 55 20 0 37.59 -13.09 -37.99 +241 100 70 20 0 32.60 -3.11 -38.23 +242 100 85 20 0 27.97 7.02 -38.33 +243 100 100 20 0 24.56 15.08 -38.49 +244 0 0 30 0 92.93 -2.11 20.82 +245 0 10 30 0 88.12 4.83 18.28 +246 0 20 30 0 83.36 11.75 16.24 +247 0 30 30 0 78.60 18.51 14.37 +248 0 40 30 0 73.91 25.86 12.81 +249 0 55 30 0 66.79 37.74 10.67 +250 0 70 30 0 59.48 50.64 9.35 +251 0 85 30 0 52.78 63.42 8.80 +252 0 100 30 0 48.13 72.82 9.76 +253 10 0 30 0 88.96 -6.25 15.64 +254 10 10 30 0 84.38 0.40 13.34 +255 10 20 30 0 79.79 7.05 11.44 +256 10 30 30 0 75.22 13.84 9.77 +257 10 40 30 0 70.66 20.96 8.20 +258 10 55 30 0 63.65 32.73 6.16 +259 10 70 30 0 56.56 45.35 4.71 +260 10 85 30 0 50.04 58.07 4.09 +261 10 100 30 0 45.28 67.61 4.74 +262 20 0 30 0 84.94 -10.13 10.68 +263 20 10 30 0 80.55 -3.72 8.48 +264 20 20 30 0 76.13 2.80 6.78 +265 20 30 30 0 71.71 9.46 5.24 +266 20 40 30 0 67.28 16.43 3.81 +267 20 55 30 0 60.45 27.89 1.78 +268 20 70 30 0 53.60 40.27 0.33 +269 20 85 30 0 47.22 53.05 -0.46 +270 20 100 30 0 42.46 62.48 0.00 +271 30 0 30 0 80.90 -14.17 5.54 +272 30 10 30 0 76.69 -7.84 3.48 +273 30 20 30 0 72.44 -1.53 1.92 +274 30 30 30 0 68.15 4.97 0.52 +275 30 40 30 0 63.83 11.80 -0.74 +276 30 55 30 0 57.26 22.97 -2.61 +277 30 70 30 0 50.59 35.16 -4.16 +278 30 85 30 0 44.35 47.52 -5.07 +279 30 100 30 0 39.76 57.01 -4.74 +280 40 0 30 0 76.82 -18.46 0.41 +281 40 10 30 0 72.77 -12.19 -1.43 +282 40 20 30 0 68.68 -6.06 -2.83 +283 40 30 30 0 64.56 0.33 -4.14 +284 40 40 30 0 60.43 6.99 -5.30 +285 40 55 30 0 54.10 17.91 -7.03 +286 40 70 30 0 47.63 29.88 -8.51 +287 40 85 30 0 41.55 42.11 -9.54 +288 40 100 30 0 37.11 51.53 -9.65 +289 55 0 30 0 70.50 -25.13 -7.66 +290 55 10 30 0 66.84 -19.26 -9.16 +291 55 20 30 0 62.99 -13.24 -10.21 +292 55 30 30 0 59.14 -7.08 -11.30 +293 55 40 30 0 55.33 -0.69 -12.30 +294 55 55 30 0 49.41 9.81 -13.81 +295 55 70 30 0 43.25 21.40 -15.18 +296 55 85 30 0 37.44 33.28 -16.35 +297 55 100 30 0 33.22 42.37 -16.72 +298 70 0 30 0 64.19 -32.83 -15.78 +299 70 10 30 0 60.75 -27.06 -16.96 +300 70 20 30 0 57.25 -21.23 -17.84 +301 70 30 30 0 53.69 -15.28 -18.64 +302 70 40 30 0 50.13 -9.20 -19.42 +303 70 55 30 0 44.66 0.84 -20.69 +304 70 70 30 0 38.92 12.02 -21.93 +305 70 85 30 0 33.50 23.44 -22.97 +306 70 100 30 0 29.46 32.47 -23.51 +307 85 0 30 0 58.20 -40.80 -23.80 +308 85 10 30 0 55.08 -35.60 -24.55 +309 85 20 30 0 51.91 -29.96 -25.06 +310 85 30 30 0 48.63 -24.28 -25.64 +311 85 40 30 0 45.31 -18.47 -26.30 +312 85 55 30 0 40.24 -8.71 -27.30 +313 85 70 30 0 34.98 1.95 -28.25 +314 85 85 30 0 29.96 12.75 -29.23 +315 85 100 30 0 26.31 21.41 -29.66 +316 100 0 30 0 53.75 -47.89 -29.55 +317 100 10 30 0 50.87 -42.60 -30.25 +318 100 20 30 0 47.88 -37.15 -30.69 +319 100 30 30 0 44.86 -31.58 -31.07 +320 100 40 30 0 41.80 -25.81 -31.46 +321 100 55 30 0 37.06 -16.36 -32.11 +322 100 70 30 0 32.17 -6.06 -32.78 +323 100 85 30 0 27.64 4.24 -33.30 +324 100 100 30 0 24.42 12.12 -33.86 +325 0 0 40 0 92.30 -2.85 30.21 +326 0 10 40 0 87.51 4.01 27.25 +327 0 20 40 0 82.77 11.08 24.69 +328 0 30 40 0 78.05 17.89 22.50 +329 0 40 40 0 73.41 25.29 20.43 +330 0 55 40 0 66.38 37.19 17.71 +331 0 70 40 0 59.22 49.87 15.87 +332 0 85 40 0 52.68 62.69 14.60 +333 0 100 40 0 48.17 72.08 14.73 +334 10 0 40 0 88.35 -7.18 24.87 +335 10 10 40 0 83.73 -0.45 22.05 +336 10 20 40 0 79.16 6.30 19.75 +337 10 30 40 0 74.64 13.16 17.72 +338 10 40 40 0 70.14 20.29 15.78 +339 10 55 40 0 63.25 32.11 13.18 +340 10 70 40 0 56.28 44.74 11.11 +341 10 85 40 0 49.91 57.53 9.88 +342 10 100 40 0 45.28 67.03 9.82 +343 20 0 40 0 84.26 -11.13 19.59 +344 20 10 40 0 79.86 -4.64 17.06 +345 20 20 40 0 75.48 1.93 14.90 +346 20 30 40 0 71.13 8.64 13.02 +347 20 40 40 0 66.77 15.64 11.23 +348 20 55 40 0 60.06 27.12 8.66 +349 20 70 40 0 53.30 39.52 6.57 +350 20 85 40 0 47.08 52.15 5.20 +351 20 100 40 0 42.48 61.62 5.11 +352 30 0 40 0 80.13 -15.20 14.20 +353 30 10 40 0 75.98 -9.00 11.91 +354 30 20 40 0 71.79 -2.59 9.96 +355 30 30 40 0 67.57 3.98 8.28 +356 30 40 40 0 63.34 10.85 6.55 +357 30 55 40 0 56.85 22.07 4.10 +358 30 70 40 0 50.28 34.34 2.00 +359 30 85 40 0 44.20 46.84 0.51 +360 30 100 40 0 39.73 56.15 0.27 +361 40 0 40 0 76.04 -19.68 8.86 +362 40 10 40 0 72.08 -13.55 6.80 +363 40 20 40 0 68.03 -7.37 5.09 +364 40 30 40 0 63.97 -0.88 3.41 +365 40 40 40 0 59.91 5.85 1.87 +366 40 55 40 0 53.66 16.87 -0.44 +367 40 70 40 0 47.28 28.91 -2.48 +368 40 85 40 0 41.35 41.02 -4.11 +369 40 100 40 0 37.09 50.34 -4.61 +370 55 0 40 0 69.75 -26.88 0.64 +371 55 10 40 0 66.15 -20.98 -1.12 +372 55 20 40 0 62.33 -14.93 -2.61 +373 55 30 40 0 58.52 -8.70 -3.96 +374 55 40 40 0 54.78 -2.19 -5.29 +375 55 55 40 0 48.96 8.44 -7.30 +376 55 70 40 0 42.92 20.09 -9.21 +377 55 85 40 0 37.27 31.98 -10.90 +378 55 100 40 0 33.15 41.15 -11.72 +379 70 0 40 0 63.35 -34.69 -7.90 +380 70 10 40 0 60.09 -29.24 -9.16 +381 70 20 40 0 56.60 -23.38 -10.36 +382 70 30 40 0 53.08 -17.39 -11.47 +383 70 40 40 0 49.63 -11.13 -12.58 +384 70 55 40 0 44.24 -0.96 -14.34 +385 70 70 40 0 38.63 10.30 -16.10 +386 70 85 40 0 33.31 21.83 -17.72 +387 70 100 40 0 29.38 30.77 -18.60 +388 85 0 40 0 57.58 -44.64 -15.60 +389 85 10 40 0 54.39 -38.45 -16.91 +390 85 20 40 0 51.21 -32.80 -17.83 +391 85 30 40 0 48.02 -26.95 -18.78 +392 85 40 40 0 44.78 -20.99 -19.67 +393 85 55 40 0 39.81 -11.13 -21.12 +394 85 70 40 0 34.65 -0.40 -22.60 +395 85 85 40 0 29.74 10.62 -24.04 +396 85 100 40 0 26.08 19.22 -25.01 +397 100 0 40 0 52.96 -51.61 -21.76 +398 100 10 40 0 50.06 -46.17 -22.89 +399 100 20 40 0 47.12 -40.58 -23.70 +400 100 30 40 0 44.18 -34.82 -24.39 +401 100 40 40 0 41.16 -29.04 -25.13 +402 100 55 40 0 36.59 -19.17 -26.07 +403 100 70 40 0 31.81 -8.79 -27.14 +404 100 85 40 0 27.38 1.57 -28.22 +405 100 100 40 0 24.35 9.47 -29.16 +406 0 0 55 0 91.32 -3.67 45.02 +407 0 10 55 0 86.60 3.32 41.44 +408 0 20 55 0 81.91 10.35 38.27 +409 0 30 55 0 77.28 17.36 35.23 +410 0 40 55 0 72.69 24.78 32.53 +411 0 55 55 0 65.75 36.53 28.96 +412 0 70 55 0 58.79 49.47 25.89 +413 0 85 55 0 52.49 61.80 23.63 +414 0 100 55 0 48.17 71.02 22.53 +415 10 0 55 0 87.33 -8.13 39.05 +416 10 10 55 0 82.76 -1.44 35.92 +417 10 20 55 0 78.26 5.40 32.96 +418 10 30 55 0 73.82 12.35 30.24 +419 10 40 55 0 69.36 19.58 27.72 +420 10 55 55 0 62.58 31.42 24.17 +421 10 70 55 0 55.80 44.02 21.11 +422 10 85 55 0 49.64 56.62 18.78 +423 10 100 55 0 45.26 65.78 17.66 +424 20 0 55 0 83.17 -12.28 33.49 +425 20 10 55 0 78.82 -5.81 30.49 +426 20 20 55 0 74.53 0.85 27.86 +427 20 30 55 0 70.27 7.62 25.37 +428 20 40 55 0 65.98 14.73 22.98 +429 20 55 55 0 59.38 26.33 19.51 +430 20 70 55 0 52.79 38.78 16.47 +431 20 85 55 0 46.77 51.10 14.01 +432 20 100 55 0 42.46 60.41 12.84 +433 30 0 55 0 79.08 -16.83 27.95 +434 30 10 55 0 74.93 -10.40 25.19 +435 30 20 55 0 70.84 -3.93 22.75 +436 30 30 55 0 66.74 2.75 20.39 +437 30 40 55 0 62.57 9.68 18.12 +438 30 55 55 0 56.19 21.01 14.74 +439 30 70 55 0 49.77 33.34 11.67 +440 30 85 55 0 43.92 45.47 9.21 +441 30 100 55 0 39.74 54.78 7.73 +442 40 0 55 0 74.94 -21.38 22.21 +443 40 10 55 0 71.05 -15.28 19.78 +444 40 20 55 0 67.11 -8.96 17.52 +445 40 30 55 0 63.13 -2.38 15.35 +446 40 40 55 0 59.14 4.42 13.19 +447 40 55 55 0 53.03 15.57 10.01 +448 40 70 55 0 46.84 27.72 7.05 +449 40 85 55 0 41.11 39.71 4.39 +450 40 100 55 0 37.05 48.72 2.84 +451 55 0 55 0 68.69 -29.37 13.83 +452 55 10 55 0 65.11 -23.16 11.48 +453 55 20 55 0 61.40 -17.05 9.50 +454 55 30 55 0 57.67 -10.69 7.59 +455 55 40 55 0 53.99 -4.11 5.73 +456 55 55 55 0 48.34 6.63 2.83 +457 55 70 55 0 42.50 18.45 -0.02 +458 55 85 55 0 37.02 30.29 -2.59 +459 55 100 55 0 33.06 39.36 -4.19 +460 70 0 55 0 62.29 -38.07 5.01 +461 70 10 55 0 59.01 -32.13 3.09 +462 70 20 55 0 55.59 -26.22 1.37 +463 70 30 55 0 52.17 -20.09 -0.28 +464 70 40 55 0 48.82 -13.71 -1.90 +465 70 55 55 0 43.60 -3.37 -4.48 +466 70 70 55 0 38.16 8.07 -7.13 +467 70 85 55 0 32.99 19.73 -9.60 +468 70 100 55 0 29.27 28.50 -11.05 +469 85 0 55 0 56.30 -48.22 -3.54 +470 85 10 55 0 53.32 -42.47 -5.11 +471 85 20 55 0 50.17 -36.82 -6.61 +472 85 30 55 0 47.07 -30.67 -8.01 +473 85 40 55 0 44.00 -24.40 -9.30 +474 85 55 55 0 39.12 -14.36 -11.59 +475 85 70 55 0 34.10 -3.35 -13.90 +476 85 85 55 0 29.38 7.83 -16.08 +477 85 100 55 0 25.90 16.32 -17.55 +478 100 0 55 0 51.74 -56.78 -9.82 +479 100 10 55 0 49.04 -51.08 -11.37 +480 100 20 55 0 46.18 -45.42 -12.66 +481 100 30 55 0 43.31 -39.42 -13.93 +482 100 40 55 0 40.36 -33.37 -15.04 +483 100 55 55 0 35.87 -23.24 -16.72 +484 100 70 55 0 31.27 -12.66 -18.78 +485 100 85 55 0 27.09 -2.18 -20.46 +486 100 100 55 0 24.21 5.65 -21.76 +487 0 0 70 0 90.44 -4.21 61.28 +488 0 10 70 0 85.77 2.80 56.87 +489 0 20 70 0 81.09 9.84 53.00 +490 0 30 70 0 76.48 16.91 49.31 +491 0 40 70 0 71.94 24.41 45.95 +492 0 55 70 0 65.15 36.37 41.18 +493 0 70 70 0 58.43 49.19 36.75 +494 0 85 70 0 52.34 61.38 33.02 +495 0 100 70 0 48.12 70.32 31.23 +496 10 0 70 0 86.46 -9.05 54.87 +497 10 10 70 0 81.91 -2.16 50.99 +498 10 20 70 0 77.44 4.73 47.51 +499 10 30 70 0 73.02 11.72 44.05 +500 10 40 70 0 68.62 19.03 40.88 +501 10 55 70 0 61.95 30.97 36.27 +502 10 70 70 0 55.36 43.55 31.94 +503 10 85 70 0 49.42 55.97 28.39 +504 10 100 70 0 45.20 65.01 26.02 +505 20 0 70 0 82.24 -13.32 48.89 +506 20 10 70 0 77.92 -6.70 45.51 +507 20 20 70 0 73.66 -0.06 42.17 +508 20 30 70 0 69.44 6.82 38.88 +509 20 40 70 0 65.21 14.02 35.84 +510 20 55 70 0 58.74 25.68 31.39 +511 20 70 70 0 52.33 38.11 27.14 +512 20 85 70 0 46.51 50.27 23.44 +513 20 100 70 0 42.41 59.29 21.01 +514 30 0 70 0 78.07 -17.87 43.09 +515 30 10 70 0 73.98 -11.48 39.78 +516 30 20 70 0 69.92 -4.97 36.83 +517 30 30 70 0 65.90 1.75 33.70 +518 30 40 70 0 61.82 8.78 30.68 +519 30 55 70 0 55.56 20.17 26.31 +520 30 70 70 0 49.35 32.36 22.15 +521 30 85 70 0 43.69 44.38 18.44 +522 30 100 70 0 39.68 53.47 15.90 +523 40 0 70 0 73.98 -22.90 37.12 +524 40 10 70 0 70.07 -16.58 34.00 +525 40 20 70 0 66.20 -10.17 31.17 +526 40 30 70 0 62.32 -3.58 28.33 +527 40 40 70 0 58.41 3.28 25.48 +528 40 55 70 0 52.40 14.45 21.22 +529 40 70 70 0 46.41 26.53 17.14 +530 40 85 70 0 40.89 38.51 13.44 +531 40 100 70 0 36.92 47.37 10.71 +532 55 0 70 0 67.60 -30.86 27.73 +533 55 10 70 0 64.09 -25.02 25.24 +534 55 20 70 0 60.47 -18.80 22.65 +535 55 30 70 0 56.83 -12.32 20.18 +536 55 40 70 0 53.21 -5.67 17.61 +537 55 55 70 0 47.69 5.15 13.72 +538 55 70 70 0 42.01 17.01 9.78 +539 55 85 70 0 36.68 28.82 6.07 +540 55 100 70 0 32.90 37.72 3.54 +541 70 0 70 0 61.29 -40.43 18.62 +542 70 10 70 0 58.04 -34.62 16.20 +543 70 20 70 0 54.66 -28.67 13.93 +544 70 30 70 0 51.30 -22.40 11.72 +545 70 40 70 0 48.01 -15.87 9.54 +546 70 55 70 0 42.93 -5.37 6.00 +547 70 70 70 0 37.56 6.18 2.28 +548 70 85 70 0 32.58 17.77 -1.13 +549 70 100 70 0 29.06 26.58 -3.37 +550 85 0 70 0 55.28 -51.54 9.65 +551 85 10 70 0 52.34 -46.03 7.48 +552 85 20 70 0 49.26 -40.18 5.39 +553 85 30 70 0 46.20 -33.94 3.49 +554 85 40 70 0 43.20 -27.44 1.61 +555 85 55 70 0 38.43 -17.14 -1.50 +556 85 70 70 0 33.50 -6.00 -4.84 +557 85 85 70 0 28.95 5.31 -7.80 +558 85 100 70 0 25.67 13.88 -9.72 +559 100 0 70 0 50.73 -61.02 2.60 +560 100 10 70 0 48.21 -55.39 0.72 +561 100 20 70 0 45.44 -49.63 -1.00 +562 100 30 70 0 42.62 -43.53 -2.73 +563 100 40 70 0 39.70 -37.18 -4.35 +564 100 55 70 0 35.23 -27.11 -7.09 +565 100 70 70 0 30.83 -16.11 -9.93 +566 100 85 70 0 26.73 -5.47 -12.46 +567 100 100 70 0 23.72 2.46 -14.35 +568 0 0 85 0 89.59 -4.30 78.11 +569 0 10 85 0 84.95 2.54 73.06 +570 0 20 85 0 80.31 9.68 68.63 +571 0 30 85 0 75.68 16.89 64.42 +572 0 40 85 0 71.16 24.60 60.45 +573 0 55 85 0 64.45 36.51 54.18 +574 0 70 85 0 57.96 49.04 48.36 +575 0 85 85 0 52.13 61.07 43.19 +576 0 100 85 0 47.99 69.68 39.86 +577 10 0 85 0 85.55 -9.23 71.49 +578 10 10 85 0 81.09 -2.42 66.99 +579 10 20 85 0 76.64 4.44 62.82 +580 10 30 85 0 72.24 11.56 58.76 +581 10 40 85 0 67.88 18.92 54.75 +582 10 55 85 0 61.33 30.85 48.95 +583 10 70 85 0 54.90 43.36 43.26 +584 10 85 85 0 49.13 55.47 38.08 +585 10 100 85 0 45.14 64.10 34.49 +586 20 0 85 0 81.36 -13.65 65.14 +587 20 10 85 0 77.09 -7.16 61.17 +588 20 20 85 0 72.84 -0.43 57.17 +589 20 30 85 0 68.64 6.47 53.13 +590 20 40 85 0 64.48 13.65 49.28 +591 20 55 85 0 58.18 25.27 43.67 +592 20 70 85 0 51.93 37.62 38.17 +593 20 85 85 0 46.26 49.68 33.02 +594 20 100 85 0 42.33 58.32 29.28 +595 30 0 85 0 77.18 -18.38 59.03 +596 30 10 85 0 73.12 -12.09 55.20 +597 30 20 85 0 69.08 -5.53 51.31 +598 30 30 85 0 65.10 1.21 47.44 +599 30 40 85 0 61.10 8.24 43.80 +600 30 55 85 0 55.02 19.58 38.24 +601 30 70 85 0 48.98 31.85 32.80 +602 30 85 85 0 43.45 43.87 27.73 +603 30 100 85 0 39.54 52.37 24.01 +604 40 0 85 0 73.06 -23.79 52.82 +605 40 10 85 0 69.17 -17.36 48.97 +606 40 20 85 0 65.31 -10.95 45.45 +607 40 30 85 0 61.54 -4.31 41.81 +608 40 40 85 0 57.71 2.53 38.22 +609 40 55 85 0 51.83 13.72 32.78 +610 40 70 85 0 45.95 25.74 27.38 +611 40 85 85 0 40.57 37.63 22.38 +612 40 100 85 0 36.75 46.47 18.73 +613 55 0 85 0 66.74 -32.47 42.68 +614 55 10 85 0 63.21 -26.14 39.43 +615 55 20 85 0 59.65 -19.87 36.28 +616 55 30 85 0 56.09 -13.45 33.04 +617 55 40 85 0 52.53 -6.79 29.71 +618 55 55 85 0 47.04 4.10 24.69 +619 55 70 85 0 41.46 16.00 19.59 +620 55 85 85 0 36.31 27.79 14.79 +621 55 100 85 0 32.71 36.31 11.24 +622 70 0 85 0 60.47 -42.45 32.73 +623 70 10 85 0 57.21 -36.32 29.79 +624 70 20 85 0 53.91 -30.40 26.81 +625 70 30 85 0 50.58 -24.08 23.94 +626 70 40 85 0 47.32 -17.50 21.06 +627 70 55 85 0 42.29 -6.82 16.47 +628 70 70 85 0 37.07 4.81 11.72 +629 70 85 85 0 32.23 16.31 7.26 +630 70 100 85 0 28.82 24.87 4.19 +631 85 0 85 0 54.46 -54.22 23.01 +632 85 10 85 0 51.57 -48.37 20.27 +633 85 20 85 0 48.53 -42.64 17.57 +634 85 30 85 0 45.48 -36.40 14.93 +635 85 40 85 0 42.49 -29.85 12.53 +636 85 55 85 0 37.83 -19.39 8.47 +637 85 70 85 0 33.00 -8.08 4.12 +638 85 85 85 0 28.57 3.18 0.18 +639 85 100 85 0 25.43 11.63 -2.39 +640 100 0 85 0 49.96 -64.51 15.36 +641 100 10 85 0 47.41 -58.78 12.75 +642 100 20 85 0 44.65 -52.99 10.45 +643 100 30 85 0 41.89 -46.75 8.26 +644 100 40 85 0 39.07 -40.33 6.10 +645 100 55 85 0 34.71 -30.16 2.55 +646 100 70 85 0 30.39 -18.98 -1.03 +647 100 85 85 0 26.30 -8.17 -4.54 +648 100 100 85 0 23.41 -0.06 -6.91 +649 0 0 100 0 88.94 -4.04 92.37 +650 0 10 100 0 84.35 2.93 87.22 +651 0 20 100 0 79.78 9.93 81.60 +652 0 30 100 0 75.21 17.28 76.85 +653 0 40 100 0 70.62 24.83 71.77 +654 0 55 100 0 63.88 36.93 64.40 +655 0 70 100 0 57.59 49.26 57.55 +656 0 85 100 0 52.01 61.00 50.67 +657 0 100 100 0 47.99 69.33 45.87 +658 10 0 100 0 84.88 -9.03 85.57 +659 10 10 100 0 80.46 -2.31 80.34 +660 10 20 100 0 76.04 4.64 75.42 +661 10 30 100 0 71.67 11.72 70.79 +662 10 40 100 0 67.35 19.15 65.96 +663 10 55 100 0 60.90 30.93 59.02 +664 10 70 100 0 54.64 43.31 51.96 +665 10 85 100 0 48.99 55.24 45.19 +666 10 100 100 0 45.04 63.72 40.42 +667 20 0 100 0 80.77 -13.83 78.87 +668 20 10 100 0 76.46 -7.14 74.05 +669 20 20 100 0 72.22 -0.38 69.36 +670 20 30 100 0 68.04 6.52 64.80 +671 20 40 100 0 63.93 13.74 60.16 +672 20 55 100 0 57.77 25.26 53.24 +673 20 70 100 0 51.60 37.64 46.37 +674 20 85 100 0 46.02 49.50 39.93 +675 20 100 100 0 42.23 57.82 34.97 +676 30 0 100 0 76.59 -18.60 71.99 +677 30 10 100 0 72.50 -12.16 67.57 +678 30 20 100 0 68.46 -5.64 63.14 +679 30 30 100 0 64.48 1.16 58.73 +680 30 40 100 0 60.55 8.16 54.27 +681 30 55 100 0 54.62 19.50 47.44 +682 30 70 100 0 48.58 31.69 40.86 +683 30 85 100 0 43.13 43.66 34.41 +684 30 100 100 0 39.46 52.01 29.54 +685 40 0 100 0 72.38 -23.80 65.39 +686 40 10 100 0 68.53 -17.53 60.92 +687 40 20 100 0 64.71 -11.10 56.67 +688 40 30 100 0 60.89 -4.52 52.46 +689 40 40 100 0 57.14 2.33 48.24 +690 40 55 100 0 51.41 13.38 41.88 +691 40 70 100 0 45.56 25.66 35.24 +692 40 85 100 0 40.29 37.45 29.13 +693 40 100 100 0 36.70 45.88 24.52 +694 55 0 100 0 65.91 -32.53 54.58 +695 55 10 100 0 62.59 -26.47 50.75 +696 55 20 100 0 59.11 -20.23 46.81 +697 55 30 100 0 55.54 -13.83 42.95 +698 55 40 100 0 52.01 -7.26 39.19 +699 55 55 100 0 46.59 3.64 32.94 +700 55 70 100 0 41.08 15.58 26.86 +701 55 85 100 0 36.08 27.28 21.06 +702 55 100 100 0 32.70 35.56 16.76 +703 70 0 100 0 59.63 -42.60 43.88 +704 70 10 100 0 56.60 -36.95 40.31 +705 70 20 100 0 53.43 -30.88 36.45 +706 70 30 100 0 50.19 -24.60 33.23 +707 70 40 100 0 46.91 -18.05 29.57 +708 70 55 100 0 41.84 -7.51 24.01 +709 70 70 100 0 36.68 4.08 18.30 +710 70 85 100 0 31.95 15.53 13.05 +711 70 100 100 0 28.80 23.72 9.51 +712 85 0 100 0 53.87 -54.67 33.22 +713 85 10 100 0 51.03 -49.29 29.89 +714 85 20 100 0 48.04 -43.53 26.60 +715 85 30 100 0 45.06 -37.12 23.67 +716 85 40 100 0 42.07 -30.62 20.53 +717 85 55 100 0 37.41 -20.56 15.59 +718 85 70 100 0 32.65 -9.17 10.53 +719 85 85 100 0 28.24 2.04 5.75 +720 85 100 100 0 25.19 10.15 2.41 +721 100 0 100 0 49.45 -65.93 24.34 +722 100 10 100 0 46.96 -60.39 21.27 +723 100 20 100 0 44.05 -54.48 18.55 +724 100 30 100 0 41.15 -48.29 15.72 +725 100 40 100 0 38.48 -41.98 13.33 +726 100 55 100 0 34.36 -31.57 9.17 +727 100 70 100 0 30.07 -20.37 4.97 +728 100 85 100 0 26.03 -9.33 0.89 +729 100 100 100 0 23.26 -1.43 -1.68 +730 0 0 0 20 82.71 0.94 -5.62 +731 0 10 0 20 78.45 6.47 -6.68 +732 0 20 0 20 74.25 12.01 -7.43 +733 0 40 0 20 65.83 23.80 -8.37 +734 0 70 0 20 52.56 45.08 -8.58 +735 0 100 0 20 41.55 65.30 -5.71 +736 10 0 0 20 79.36 -2.33 -9.67 +737 10 10 0 20 75.31 3.17 -10.70 +738 10 20 0 20 71.30 8.58 -11.24 +739 10 40 0 20 63.19 20.12 -11.99 +740 10 70 0 20 50.27 40.99 -12.23 +741 10 100 0 20 39.26 61.11 -9.78 +742 20 0 0 20 75.95 -5.23 -13.49 +743 20 10 0 20 72.11 0.09 -14.35 +744 20 20 0 20 68.25 5.43 -14.78 +745 20 40 0 20 60.40 16.65 -15.36 +746 20 70 0 20 47.87 36.80 -15.52 +747 20 100 0 20 37.04 57.03 -13.72 +748 40 0 0 20 69.10 -11.23 -21.56 +749 40 10 0 20 65.58 -6.21 -22.07 +750 40 20 0 20 62.05 -1.20 -22.23 +751 40 40 0 20 54.78 9.46 -22.46 +752 40 70 0 20 43.04 28.63 -22.45 +753 40 100 0 20 32.63 47.99 -21.35 +754 70 0 0 20 58.12 -21.50 -34.42 +755 70 10 0 20 55.16 -16.81 -34.55 +756 70 20 0 20 52.10 -12.14 -34.34 +757 70 40 0 20 45.77 -2.39 -34.02 +758 70 70 0 20 35.49 15.40 -33.51 +759 70 100 0 20 26.51 32.84 -32.87 +760 100 0 0 20 48.98 -31.63 -45.54 +761 100 10 0 20 46.34 -27.12 -45.42 +762 100 20 0 20 43.61 -22.59 -44.94 +763 100 40 0 20 38.05 -13.31 -44.04 +764 100 70 0 20 29.66 2.59 -42.50 +765 100 100 0 20 22.32 17.88 -41.00 +766 0 0 10 20 82.08 -0.43 2.12 +767 0 10 10 20 77.87 5.25 0.62 +768 0 20 10 20 73.70 10.89 -0.32 +769 0 40 10 20 65.36 22.88 -2.09 +770 0 70 10 20 52.24 44.24 -3.18 +771 0 100 10 20 41.50 64.41 -1.47 +772 10 0 10 20 78.75 -3.78 -2.02 +773 10 10 10 20 74.75 1.74 -3.29 +774 10 20 10 20 70.75 7.32 -4.27 +775 10 40 10 20 62.70 19.02 -5.73 +776 10 70 10 20 49.95 40.01 -6.79 +777 10 100 10 20 39.21 60.16 -5.49 +778 20 0 10 20 75.33 -6.75 -5.99 +779 20 10 10 20 71.53 -1.40 -7.15 +780 20 20 10 20 67.69 3.99 -7.90 +781 20 40 10 20 59.92 15.38 -9.14 +782 20 70 10 20 47.54 35.82 -10.26 +783 20 100 10 20 36.98 55.83 -9.42 +784 40 0 10 20 68.40 -13.14 -14.26 +785 40 10 10 20 64.96 -8.07 -15.10 +786 40 20 10 20 61.47 -2.98 -15.54 +787 40 40 10 20 54.32 7.85 -16.39 +788 40 70 10 20 42.71 27.36 -17.38 +789 40 100 10 20 32.59 46.75 -17.33 +790 70 0 10 20 57.44 -24.20 -27.58 +791 70 10 10 20 54.53 -19.46 -27.93 +792 70 20 10 20 51.55 -14.66 -28.01 +793 70 40 10 20 45.33 -4.69 -28.22 +794 70 70 10 20 35.23 13.33 -28.64 +795 70 100 10 20 26.30 31.00 -28.75 +796 100 0 10 20 48.23 -35.34 -39.06 +797 100 10 10 20 45.63 -30.85 -39.21 +798 100 20 10 20 43.02 -26.27 -38.96 +799 100 40 10 20 37.66 -16.66 -38.52 +800 100 70 10 20 29.27 -0.20 -37.91 +801 100 100 10 20 22.22 15.10 -37.07 +802 0 0 20 20 81.45 -1.38 9.64 +803 0 10 20 20 77.25 4.34 7.86 +804 0 20 20 20 73.12 10.06 6.49 +805 0 40 20 20 64.84 22.12 4.16 +806 0 70 20 20 51.91 43.69 2.07 +807 0 100 20 20 41.41 63.64 2.97 +808 10 0 20 20 78.11 -4.87 5.45 +809 10 10 20 20 74.12 0.73 3.79 +810 10 20 20 20 70.15 6.30 2.57 +811 10 40 20 20 62.16 18.17 0.46 +812 10 70 20 20 49.61 39.24 -1.60 +813 10 100 20 20 39.15 59.40 -1.24 +814 20 0 20 20 74.68 -8.04 1.44 +815 20 10 20 20 70.90 -2.56 -0.16 +816 20 20 20 20 67.10 2.82 -1.15 +817 20 40 20 20 59.38 14.41 -3.05 +818 20 70 20 20 47.21 35.03 -5.08 +819 20 100 20 20 36.90 54.86 -5.04 +820 40 0 20 20 67.71 -14.77 -7.13 +821 40 10 20 20 64.30 -9.60 -8.30 +822 40 20 20 20 60.84 -4.43 -9.06 +823 40 40 20 20 53.77 6.59 -10.44 +824 40 70 20 20 42.34 26.28 -12.30 +825 40 100 20 20 32.49 45.57 -12.97 +826 70 0 20 20 56.75 -26.54 -20.75 +827 70 10 20 20 53.86 -21.79 -21.34 +828 70 20 20 20 50.93 -16.89 -21.75 +829 70 40 20 20 44.78 -6.62 -22.48 +830 70 70 20 20 34.86 11.61 -23.78 +831 70 100 20 20 26.20 29.16 -24.51 +832 100 0 20 20 47.59 -38.93 -32.48 +833 100 10 20 20 45.04 -34.21 -32.90 +834 100 20 20 20 42.44 -29.59 -32.99 +835 100 40 20 20 37.19 -19.80 -33.02 +836 100 70 20 20 28.88 -2.84 -33.18 +837 100 100 20 20 22.16 12.41 -33.00 +838 0 0 40 20 80.14 -3.01 25.29 +839 0 10 40 20 76.01 2.86 22.83 +840 0 20 40 20 71.91 8.72 20.88 +841 0 40 40 20 63.81 21.02 17.21 +842 0 70 40 20 51.28 42.65 13.10 +843 0 100 40 20 41.30 61.99 12.09 +844 10 0 40 20 76.77 -6.66 20.81 +845 10 10 40 20 72.86 -0.97 18.54 +846 10 20 40 20 68.95 4.71 16.71 +847 10 40 40 20 61.17 16.76 13.44 +848 10 70 40 20 49.02 38.03 9.25 +849 10 100 40 20 39.06 57.64 7.80 +850 20 0 40 20 73.30 -10.02 16.38 +851 20 10 40 20 69.58 -4.54 14.35 +852 20 20 40 20 65.88 0.98 12.67 +853 20 40 40 20 58.41 12.76 9.72 +854 20 70 40 20 46.62 33.55 5.61 +855 20 100 40 20 36.79 53.11 3.81 +856 40 0 40 20 66.37 -17.46 7.35 +857 40 10 40 20 62.99 -12.21 5.73 +858 40 20 40 20 59.61 -6.95 4.41 +859 40 40 40 20 52.68 4.36 1.85 +860 40 70 40 20 41.62 24.36 -1.85 +861 40 100 40 20 32.33 43.36 -4.12 +862 70 0 40 20 55.45 -30.66 -6.92 +863 70 10 40 20 52.60 -25.78 -7.99 +864 70 20 40 20 49.69 -20.75 -8.84 +865 70 40 40 20 43.73 -10.19 -10.64 +866 70 70 40 20 34.11 8.50 -13.67 +867 70 100 40 20 25.99 26.13 -15.97 +868 100 0 40 20 46.29 -45.35 -19.06 +869 100 10 40 20 43.77 -40.52 -20.15 +870 100 20 40 20 41.27 -35.59 -20.78 +871 100 40 40 20 36.13 -25.27 -21.82 +872 100 70 40 20 28.13 -7.69 -23.54 +873 100 100 40 20 21.98 7.77 -24.64 +874 0 0 70 20 78.33 -4.36 52.11 +875 0 10 70 20 74.31 1.50 48.49 +876 0 20 70 20 70.31 7.50 45.34 +877 0 40 70 20 62.38 20.05 39.65 +878 0 70 70 20 50.42 41.66 31.53 +879 0 100 70 20 41.27 60.30 26.02 +880 10 0 70 20 74.92 -8.37 46.88 +881 10 10 70 20 71.08 -2.62 43.77 +882 10 20 70 20 67.27 3.20 40.93 +883 10 40 70 20 59.70 15.50 35.44 +884 10 70 70 20 48.08 36.88 27.54 +885 10 100 70 20 38.99 55.74 21.69 +886 20 0 70 20 71.38 -12.08 42.09 +887 20 10 70 20 67.75 -6.50 39.17 +888 20 20 70 20 64.15 -0.83 36.48 +889 20 40 70 20 56.91 11.18 31.35 +890 20 70 70 20 45.67 32.09 23.49 +891 20 100 70 20 36.72 50.81 17.58 +892 40 0 70 20 64.39 -20.27 32.26 +893 40 10 70 20 61.14 -14.96 29.58 +894 40 20 70 20 57.87 -9.56 27.24 +895 40 40 70 20 51.18 2.00 22.70 +896 40 70 70 20 40.75 22.13 15.28 +897 40 100 70 20 32.17 40.58 9.35 +898 70 0 70 20 53.50 -35.51 16.03 +899 70 10 70 20 50.76 -30.50 14.14 +900 70 20 70 20 47.97 -25.36 12.38 +901 70 40 70 20 42.28 -14.37 8.75 +902 70 70 70 20 33.17 4.78 2.36 +903 70 100 70 20 25.77 22.27 -2.65 +904 100 0 70 20 44.46 -53.40 1.85 +905 100 10 70 20 42.18 -48.36 0.30 +906 100 20 70 20 39.74 -43.26 -1.04 +907 100 40 70 20 34.83 -32.31 -3.86 +908 100 70 70 20 27.27 -13.76 -8.52 +909 100 100 70 20 21.35 1.97 -11.63 +910 0 0 100 20 76.87 -4.54 79.60 +911 0 10 100 20 72.83 1.43 74.97 +912 0 20 100 20 68.92 7.44 70.62 +913 0 40 100 20 61.20 20.10 61.93 +914 0 70 100 20 49.71 41.31 48.84 +915 0 100 100 20 41.18 59.22 38.07 +916 10 0 100 20 73.45 -8.73 74.00 +917 10 10 100 20 69.65 -2.93 69.64 +918 10 20 100 20 65.91 2.91 65.50 +919 10 40 100 20 58.54 15.23 57.36 +920 10 70 100 20 47.42 36.32 44.40 +921 10 100 100 20 38.84 54.38 33.77 +922 20 0 100 20 69.96 -12.68 68.26 +923 20 10 100 20 66.33 -7.02 64.24 +924 20 20 100 20 62.79 -1.30 60.34 +925 20 40 100 20 55.81 10.68 52.70 +926 20 70 100 20 45.00 31.40 40.12 +927 20 100 100 20 36.57 49.59 29.43 +928 40 0 100 20 62.91 -21.30 56.40 +929 40 10 100 20 59.71 -15.94 52.97 +930 40 20 100 20 56.52 -10.45 49.55 +931 40 40 100 20 50.09 0.97 42.51 +932 40 70 100 20 40.01 21.17 30.74 +933 40 100 100 20 32.07 39.11 20.63 +934 70 0 100 20 51.96 -37.71 37.64 +935 70 10 100 20 49.37 -32.65 34.74 +936 70 20 100 20 46.70 -27.43 31.79 +937 70 40 100 20 41.15 -16.27 25.96 +938 70 70 100 20 32.42 2.80 16.16 +939 70 100 100 20 25.44 19.59 8.23 +940 100 0 100 20 43.29 -57.56 20.62 +941 100 10 100 20 40.94 -52.67 18.23 +942 100 20 100 20 38.56 -47.34 15.65 +943 100 40 100 20 33.86 -36.19 11.18 +944 100 70 100 20 26.63 -17.39 4.15 +945 100 100 100 20 20.99 -1.62 -0.77 +946 0 0 0 40 69.76 0.49 -4.90 +947 0 20 0 40 62.52 9.75 -6.42 +948 0 40 0 40 55.49 19.69 -7.37 +949 0 70 0 40 44.14 37.55 -7.50 +950 0 100 0 40 34.72 54.79 -5.39 +951 20 0 0 40 63.98 -4.58 -11.33 +952 20 20 0 40 57.76 4.18 -12.29 +953 20 40 0 40 51.20 13.57 -12.79 +954 20 70 0 40 40.49 30.70 -12.92 +955 20 100 0 40 31.10 47.69 -11.55 +956 40 0 0 40 58.32 -9.67 -17.98 +957 40 20 0 40 52.62 -1.32 -18.41 +958 40 40 0 40 46.55 7.66 -18.54 +959 40 70 0 40 36.62 23.92 -18.55 +960 40 100 0 40 27.63 40.22 -17.89 +961 70 0 0 40 49.03 -18.54 -28.83 +962 70 20 0 40 44.15 -10.67 -28.60 +963 70 40 0 40 38.98 -2.29 -28.34 +964 70 70 0 40 30.42 12.73 -27.73 +965 70 100 0 40 22.75 27.22 -27.19 +966 100 0 0 40 41.19 -27.41 -38.38 +967 100 20 0 40 36.82 -19.61 -37.84 +968 100 40 0 40 32.22 -11.48 -37.07 +969 100 70 0 40 25.31 2.23 -35.53 +970 100 100 0 40 19.62 14.55 -33.73 +971 0 0 20 40 68.48 -1.48 7.70 +972 0 20 20 40 61.60 7.93 5.17 +973 0 40 20 40 54.61 18.06 3.27 +974 0 70 20 40 43.64 36.12 1.49 +975 0 100 20 40 34.63 53.16 2.14 +976 20 0 20 40 62.92 -7.02 0.95 +977 20 20 20 40 56.68 2.01 -1.02 +978 20 40 20 40 50.25 11.62 -2.51 +979 20 70 20 40 39.95 28.97 -4.21 +980 20 100 20 40 31.08 45.77 -4.40 +981 40 0 20 40 57.13 -12.61 -6.09 +982 40 20 20 40 51.60 -4.11 -7.49 +983 40 40 20 40 45.74 5.11 -8.49 +984 40 70 20 40 36.05 21.59 -10.01 +985 40 100 20 40 27.54 37.87 -10.67 +986 70 0 20 40 47.88 -22.76 -17.42 +987 70 20 20 40 43.15 -14.56 -18.18 +988 70 40 20 40 38.11 -5.86 -18.70 +989 70 70 20 40 29.84 9.42 -19.58 +990 70 100 20 40 22.58 23.94 -20.09 +991 100 0 20 40 40.09 -33.23 -27.46 +992 100 20 20 40 35.84 -25.12 -27.85 +993 100 40 20 40 31.60 -16.66 -27.78 +994 100 70 20 40 24.95 -2.44 -27.50 +995 100 100 20 40 19.60 9.81 -26.69 +996 0 0 40 40 67.34 -2.97 20.70 +997 0 20 40 40 60.49 6.72 17.16 +998 0 40 40 40 53.65 17.00 14.18 +999 0 70 40 40 43.08 35.13 10.76 +1000 0 100 40 40 34.42 51.63 9.58 +1001 20 0 40 40 61.72 -8.83 13.51 +1002 20 20 40 40 55.59 0.33 10.60 +1003 20 40 40 40 49.39 10.16 8.24 +1004 20 70 40 40 39.43 27.57 4.85 +1005 20 100 40 40 30.97 44.02 3.01 +1006 40 0 40 40 55.94 -14.96 6.09 +1007 40 20 40 40 50.51 -6.27 3.84 +1008 40 40 40 40 44.79 3.13 1.87 +1009 40 70 40 40 35.43 19.91 -1.18 +1010 40 100 40 40 27.45 35.74 -3.21 +1011 70 0 40 40 46.81 -26.12 -5.92 +1012 70 20 40 40 42.13 -17.78 -7.34 +1013 70 40 40 40 37.20 -8.87 -8.67 +1014 70 70 40 40 29.18 6.90 -10.97 +1015 70 100 40 40 22.53 21.10 -12.82 +1016 100 0 40 40 39.03 -38.48 -16.29 +1017 100 20 40 40 34.93 -30.04 -17.54 +1018 100 40 40 40 30.74 -21.21 -18.24 +1019 100 70 40 40 24.32 -6.31 -19.35 +1020 100 100 40 40 19.38 6.17 -19.49 +1021 0 0 70 40 65.58 -4.34 43.22 +1022 0 20 70 40 59.01 5.50 37.69 +1023 0 40 70 40 52.35 15.95 33.01 +1024 0 70 70 40 42.19 34.08 26.08 +1025 0 100 70 40 34.49 49.62 21.24 +1026 20 0 70 40 59.97 -10.70 35.00 +1027 20 20 70 40 54.07 -1.36 30.56 +1028 20 40 70 40 48.05 8.63 26.41 +1029 20 70 70 40 38.58 26.14 19.73 +1030 20 100 70 40 30.92 41.83 14.44 +1031 40 0 70 40 54.25 -17.46 26.83 +1032 40 20 70 40 48.93 -8.59 23.01 +1033 40 40 70 40 43.38 0.94 19.38 +1034 40 70 70 40 34.64 17.81 13.15 +1035 40 100 70 40 27.34 33.21 7.92 +1036 70 0 70 40 45.12 -30.22 13.41 +1037 70 20 70 40 40.64 -21.71 10.48 +1038 70 40 70 40 35.97 -12.44 7.61 +1039 70 70 70 40 28.46 3.51 2.52 +1040 70 100 70 40 22.34 17.67 -1.78 +1041 100 0 70 40 37.66 -44.89 1.47 +1042 100 20 70 40 33.71 -36.24 -1.01 +1043 100 40 70 40 29.67 -26.80 -3.12 +1044 100 70 70 40 23.55 -11.20 -6.77 +1045 100 100 70 40 18.98 1.43 -8.62 +1046 0 0 100 40 64.34 -4.61 66.28 +1047 0 20 100 40 57.63 5.32 58.83 +1048 0 40 100 40 51.26 15.71 51.46 +1049 0 70 100 40 41.55 33.60 39.83 +1050 0 100 100 40 34.41 48.54 30.21 +1051 20 0 100 40 58.63 -11.29 56.88 +1052 20 20 100 40 52.81 -1.95 50.58 +1053 20 40 100 40 47.05 8.03 44.11 +1054 20 70 100 40 37.96 25.36 33.13 +1055 20 100 100 40 30.81 40.60 23.75 +1056 40 0 100 40 52.92 -18.48 47.26 +1057 40 20 100 40 47.71 -9.52 41.60 +1058 40 40 100 40 42.45 0.10 35.78 +1059 40 70 100 40 33.93 16.86 25.64 +1060 40 100 100 40 27.31 31.57 16.97 +1061 70 0 100 40 43.72 -32.23 31.03 +1062 70 20 100 40 39.54 -23.58 26.64 +1063 70 40 100 40 35.03 -14.28 21.85 +1064 70 70 100 40 27.87 1.79 13.74 +1065 70 100 100 40 22.08 15.59 7.09 +1066 100 0 100 40 36.61 -48.49 16.76 +1067 100 20 100 40 32.70 -39.49 12.87 +1068 100 40 100 40 28.94 -29.96 8.97 +1069 100 70 100 40 23.06 -14.02 3.66 +1070 100 100 100 40 18.84 -1.48 0.17 +1071 0 0 0 60 55.11 0.16 -3.90 +1072 0 20 0 60 49.23 7.50 -5.02 +1073 0 40 0 60 43.70 15.24 -5.67 +1074 0 70 0 60 34.64 29.50 -5.70 +1075 0 100 0 60 27.25 42.69 -3.97 +1076 20 0 0 60 50.37 -3.85 -8.86 +1077 20 20 0 60 45.68 3.01 -9.52 +1078 20 40 0 60 40.52 10.45 -9.77 +1079 20 70 0 60 31.99 24.00 -9.64 +1080 20 100 0 60 24.71 36.96 -8.33 +1081 40 0 0 60 45.88 -7.92 -14.06 +1082 40 20 0 60 41.69 -1.34 -14.21 +1083 40 40 0 60 37.05 5.92 -14.19 +1084 40 70 0 60 29.25 18.74 -13.96 +1085 40 100 0 60 22.30 31.03 -13.17 +1086 70 0 0 60 38.53 -15.13 -22.51 +1087 70 20 0 60 34.83 -8.72 -22.31 +1088 70 40 0 60 31.15 -1.90 -21.87 +1089 70 70 0 60 24.56 9.92 -21.11 +1090 70 100 0 60 18.99 20.53 -20.02 +1091 100 0 0 60 32.32 -22.10 -30.18 +1092 100 20 0 60 29.16 -15.54 -29.66 +1093 100 40 0 60 25.87 -8.89 -28.81 +1094 100 70 0 60 20.64 2.09 -26.98 +1095 100 100 0 60 16.87 10.72 -24.84 +1096 0 0 20 60 53.73 -1.52 5.86 +1097 0 20 20 60 48.47 6.03 3.92 +1098 0 40 20 60 42.94 14.05 2.55 +1099 0 70 20 60 34.35 28.20 1.31 +1100 0 100 20 60 27.39 41.04 1.93 +1101 20 0 20 60 49.43 -5.78 0.64 +1102 20 20 20 60 44.77 1.35 -0.70 +1103 20 40 20 60 39.78 8.90 -1.76 +1104 20 70 20 60 31.68 22.45 -2.88 +1105 20 100 20 60 24.82 35.20 -2.86 +1106 40 0 20 60 44.94 -10.16 -4.74 +1107 40 20 20 60 40.87 -3.51 -5.71 +1108 40 40 20 60 36.39 3.73 -6.30 +1109 40 70 20 60 28.83 16.68 -7.24 +1110 40 100 20 60 22.27 28.94 -7.50 +1111 70 0 20 60 37.72 -18.19 -13.72 +1112 70 20 20 60 34.14 -11.65 -14.11 +1113 70 40 20 60 30.36 -4.71 -14.34 +1114 70 70 20 60 24.09 7.36 -14.52 +1115 70 100 20 60 18.86 17.97 -14.34 +1116 100 0 20 60 31.60 -26.33 -21.61 +1117 100 20 20 60 28.46 -19.57 -21.70 +1118 100 40 20 60 25.25 -12.54 -21.49 +1119 100 70 20 60 20.49 -1.37 -20.68 +1120 100 100 20 60 16.88 7.38 -19.20 +1121 0 0 40 60 52.68 -2.67 15.85 +1122 0 20 40 60 47.36 4.88 13.13 +1123 0 40 40 60 42.12 12.95 11.02 +1124 0 70 40 60 33.95 27.10 8.41 +1125 0 100 40 60 27.18 39.42 7.54 +1126 20 0 40 60 48.50 -7.28 10.40 +1127 20 20 40 60 43.81 -0.10 8.37 +1128 20 40 40 60 39.03 7.63 6.71 +1129 20 70 40 60 31.26 21.24 4.17 +1130 20 100 40 60 24.70 33.40 2.83 +1131 40 0 40 60 44.02 -12.08 4.67 +1132 40 20 40 60 39.95 -5.27 3.17 +1133 40 40 40 60 35.64 2.13 1.88 +1134 40 70 40 60 28.35 15.13 -0.31 +1135 40 100 40 60 22.18 26.92 -1.83 +1136 70 0 40 60 36.90 -20.87 -4.66 +1137 70 20 40 60 33.37 -14.28 -5.60 +1138 70 40 40 60 29.67 -6.99 -6.41 +1139 70 70 40 60 23.62 5.21 -7.78 +1140 70 100 40 60 18.91 15.47 -8.68 +1141 100 0 40 60 30.78 -30.24 -12.90 +1142 100 20 40 60 27.78 -23.12 -13.56 +1143 100 40 40 60 24.77 -15.96 -13.91 +1144 100 70 40 60 20.15 -4.47 -14.11 +1145 100 100 40 60 16.68 4.82 -13.41 +1146 0 0 70 60 51.15 -4.04 33.32 +1147 0 20 70 60 46.21 3.70 29.16 +1148 0 40 70 60 41.10 11.85 25.54 +1149 0 70 70 60 33.12 25.82 20.00 +1150 0 100 70 60 27.29 37.43 16.11 +1151 20 0 70 60 46.98 -8.95 27.14 +1152 20 20 70 60 42.58 -1.61 23.88 +1153 20 40 70 60 37.93 6.17 20.61 +1154 20 70 70 60 30.59 19.79 15.51 +1155 20 100 70 60 24.72 31.23 11.25 +1156 40 0 70 60 42.69 -14.23 20.77 +1157 40 20 70 60 38.67 -7.26 18.07 +1158 40 40 70 60 34.49 0.25 15.33 +1159 40 70 70 60 27.76 13.33 10.62 +1160 40 100 70 60 22.27 24.45 6.60 +1161 70 0 70 60 35.60 -24.15 10.44 +1162 70 20 70 60 32.21 -17.35 8.27 +1163 70 40 70 60 28.76 -9.97 6.18 +1164 70 70 70 60 23.18 2.47 2.77 +1165 70 100 70 60 18.79 12.57 -0.31 +1166 100 0 70 60 29.84 -34.93 1.13 +1167 100 20 70 60 26.91 -27.69 -0.65 +1168 100 40 70 60 23.97 -20.18 -2.17 +1169 100 70 70 60 19.64 -8.07 -4.26 +1170 100 100 70 60 16.55 1.20 -5.07 +1171 0 0 100 60 50.25 -4.33 50.82 +1172 0 20 100 60 45.01 3.42 44.96 +1173 0 40 100 60 40.03 11.41 39.03 +1174 0 70 100 60 32.56 25.13 29.69 +1175 0 100 100 60 27.15 36.15 22.32 +1176 20 0 100 60 45.86 -9.57 43.71 +1177 20 20 100 60 41.49 -2.22 38.85 +1178 20 40 100 60 37.06 5.50 33.68 +1179 20 70 100 60 30.07 18.85 25.03 +1180 20 100 100 60 24.72 30.00 17.63 +1181 40 0 100 60 41.53 -15.21 36.44 +1182 40 20 100 60 37.56 -8.14 31.96 +1183 40 40 100 60 33.65 -0.54 27.58 +1184 40 70 100 60 27.21 12.41 19.43 +1185 40 100 100 60 22.13 22.96 12.95 +1186 70 0 100 60 34.38 -25.71 23.46 +1187 70 20 100 60 31.39 -18.85 20.31 +1188 70 40 100 60 28.15 -11.44 16.90 +1189 70 70 100 60 22.81 0.83 10.97 +1190 70 100 100 60 18.77 10.78 6.27 +1191 100 0 100 60 29.06 -37.41 12.37 +1192 100 20 100 60 26.18 -29.92 9.60 +1193 100 40 100 60 23.44 -22.34 6.91 +1194 100 70 100 60 19.37 -10.23 3.34 +1195 100 100 100 60 16.60 -1.05 1.33 +1196 0 0 0 80 37.53 -0.06 -2.55 +1197 0 40 0 80 29.92 10.36 -3.35 +1198 0 70 0 80 24.18 19.69 -2.63 +1199 0 100 0 80 19.71 27.26 -0.61 +1200 40 0 0 80 31.21 -5.53 -9.39 +1201 40 40 0 80 25.70 3.89 -8.72 +1202 40 70 0 80 20.81 12.60 -7.88 +1203 40 100 0 80 16.94 19.73 -6.36 +1204 70 0 0 80 26.43 -10.25 -15.17 +1205 70 40 0 80 21.93 -0.93 -13.86 +1206 70 70 0 80 18.12 7.02 -12.31 +1207 70 100 0 80 15.10 13.10 -10.62 +1208 100 0 0 80 22.35 -14.40 -20.14 +1209 100 40 0 80 18.57 -4.80 -18.53 +1210 100 70 0 80 15.78 2.53 -16.01 +1211 100 100 0 80 14.02 7.64 -13.62 +1212 0 0 40 80 35.69 -2.21 10.26 +1213 0 40 40 80 28.86 8.37 7.46 +1214 0 70 40 80 23.82 17.54 6.14 +1215 0 100 40 80 19.89 24.54 5.88 +1216 40 0 40 80 30.03 -8.47 2.93 +1217 40 40 40 80 24.87 1.18 1.98 +1218 40 70 40 80 20.40 9.52 0.93 +1219 40 100 40 80 17.01 16.13 0.53 +1220 70 0 40 80 25.39 -14.08 -3.15 +1221 70 40 40 80 21.09 -4.40 -3.40 +1222 70 70 40 80 17.71 3.56 -3.40 +1223 70 100 40 80 15.25 9.27 -3.33 +1224 100 0 40 80 21.63 -19.32 -8.44 +1225 100 40 40 80 18.18 -9.24 -8.20 +1226 100 70 40 80 15.76 -1.62 -7.35 +1227 100 100 40 80 14.15 3.69 -6.09 +1228 0 0 70 80 34.66 -3.35 21.33 +1229 0 40 70 80 28.30 7.22 16.41 +1230 0 70 70 80 23.37 16.02 12.92 +1231 0 100 70 80 20.10 22.62 10.78 +1232 40 0 70 80 29.20 -10.17 13.43 +1233 40 40 70 80 24.18 -0.45 10.29 +1234 40 70 70 80 20.17 7.85 7.65 +1235 40 100 70 80 17.21 14.02 5.52 +1236 70 0 70 80 24.64 -16.37 6.71 +1237 70 40 70 80 20.69 -6.51 4.67 +1238 70 70 70 80 17.54 1.42 2.92 +1239 70 100 70 80 15.35 7.13 1.69 +1240 100 0 70 80 21.23 -22.25 0.82 +1241 100 40 70 80 17.92 -11.69 -0.54 +1242 100 70 70 80 15.68 -4.13 -1.03 +1243 100 100 70 80 14.29 1.16 -0.78 +1244 0 0 100 80 34.00 -3.83 31.57 +1245 0 40 100 80 27.55 6.53 23.99 +1246 0 70 100 80 23.10 15.17 18.22 +1247 0 100 100 80 20.01 21.33 14.10 +1248 40 0 100 80 28.36 -10.98 22.26 +1249 40 40 100 80 23.69 -1.21 17.17 +1250 40 70 100 80 19.95 6.78 12.47 +1251 40 100 100 80 17.19 12.64 9.00 +1252 70 0 100 80 23.93 -17.55 14.31 +1253 70 40 100 80 20.38 -7.77 10.86 +1254 70 70 100 80 17.44 -0.03 7.75 +1255 70 100 100 80 15.48 5.45 5.62 +1256 100 0 100 80 20.74 -23.54 7.57 +1257 100 40 100 80 17.65 -13.21 4.98 +1258 100 70 100 80 15.64 -5.73 3.47 +1259 100 100 100 80 14.42 -0.52 2.89 +1260 0 0 0 100 16.00 0.07 -0.33 +1261 0 40 0 100 14.59 3.91 1.23 +1262 0 100 0 100 13.30 8.89 4.27 +1263 40 0 0 100 14.54 -1.51 -2.60 +1264 40 40 0 100 13.68 2.52 -0.92 +1265 40 100 0 100 12.53 7.53 2.57 +1266 100 0 0 100 12.18 -3.46 -6.20 +1267 100 40 0 100 12.05 0.86 -4.11 +1268 100 100 0 100 11.43 5.76 0.01 +1269 0 0 40 100 15.58 -1.33 2.32 +1270 0 40 40 100 14.55 2.15 3.20 +1271 0 100 40 100 13.65 6.43 5.33 +1272 40 0 40 100 14.44 -3.26 0.64 +1273 40 40 40 100 13.71 0.53 1.73 +1274 40 100 40 100 12.97 5.05 3.95 +1275 100 0 40 100 12.48 -5.55 -2.32 +1276 100 40 40 100 12.36 -1.39 -0.48 +1277 100 100 40 100 12.10 3.27 2.10 +1278 0 0 100 100 15.37 -3.20 6.36 +1279 0 40 100 100 14.60 -0.40 6.20 +1280 0 100 100 100 14.07 3.45 7.04 +1281 40 0 100 100 14.40 -5.36 4.99 +1282 40 40 100 100 13.92 -2.03 5.32 +1283 40 100 100 100 13.45 1.98 6.07 +1284 100 0 100 100 12.95 -8.05 3.02 +1285 100 40 100 100 12.80 -3.87 3.65 +1286 100 100 100 100 12.71 0.53 4.89 +1287 100 0 0 0 56.12 -34.90 -52.52 +1288 98 0 0 0 56.57 -34.55 -51.98 +1289 95 0 0 0 57.50 -33.86 -50.97 +1290 90 0 0 0 58.99 -32.23 -49.17 +1291 85 0 0 0 60.62 -30.20 -47.07 +1292 80 0 0 0 62.52 -28.10 -44.74 +1293 75 0 0 0 64.50 -26.08 -42.35 +1294 70 0 0 0 66.57 -24.03 -39.84 +1295 60 0 0 0 70.86 -20.12 -34.85 +1296 50 0 0 0 75.02 -16.20 -29.84 +1297 40 0 0 0 79.15 -12.57 -24.94 +1298 30 0 0 0 83.19 -9.04 -20.26 +1299 25 0 0 0 85.18 -7.33 -17.89 +1300 20 0 0 0 87.20 -5.64 -15.58 +1301 15 0 0 0 89.19 -3.96 -13.25 +1302 10 0 0 0 91.19 -2.28 -10.93 +1303 7 0 0 0 92.40 -1.23 -9.48 +1304 5 0 0 0 93.14 -0.51 -8.50 +1305 3 0 0 0 93.93 0.25 -7.56 +1306 2 0 0 0 94.35 0.55 -7.24 +1307 0 100 0 0 48.06 75.29 -5.18 +1308 0 98 0 0 48.58 74.48 -5.81 +1309 0 95 0 0 49.56 72.84 -6.62 +1310 0 90 0 0 51.30 69.51 -7.29 +1311 0 85 0 0 53.32 65.54 -7.71 +1312 0 80 0 0 55.59 61.24 -8.19 +1313 0 75 0 0 57.94 56.95 -8.67 +1314 0 70 0 0 60.42 52.69 -9.17 +1315 0 60 0 0 65.44 44.19 -9.58 +1316 0 50 0 0 70.47 36.07 -9.54 +1317 0 40 0 0 75.43 28.45 -9.24 +1318 0 30 0 0 80.33 21.39 -8.87 +1319 0 25 0 0 82.76 18.02 -8.63 +1320 0 20 0 0 85.20 14.67 -8.29 +1321 0 15 0 0 87.63 11.40 -7.90 +1322 0 10 0 0 90.08 8.15 -7.42 +1323 0 7 0 0 91.57 6.24 -7.19 +1324 0 5 0 0 92.53 5.00 -7.00 +1325 0 3 0 0 93.54 3.67 -6.73 +1326 0 2 0 0 94.02 3.03 -6.59 +1327 0 0 100 0 88.94 -4.04 92.37 +1328 0 0 98 0 89.05 -4.12 91.02 +1329 0 0 95 0 89.18 -4.15 88.37 +1330 0 0 90 0 89.33 -4.25 83.43 +1331 0 0 85 0 89.59 -4.30 78.11 +1332 0 0 80 0 89.85 -4.20 72.40 +1333 0 0 75 0 90.11 -4.17 66.82 +1334 0 0 70 0 90.44 -4.21 61.28 +1335 0 0 60 0 91.03 -3.89 50.35 +1336 0 0 50 0 91.62 -3.44 39.94 +1337 0 0 40 0 92.30 -2.85 30.21 +1338 0 0 30 0 92.93 -2.11 20.82 +1339 0 0 25 0 93.40 -1.69 16.51 +1340 0 0 20 0 93.66 -1.17 11.88 +1341 0 0 15 0 93.99 -0.63 7.37 +1342 0 0 10 0 94.39 -0.05 3.02 +1343 0 0 7 0 94.60 0.34 0.33 +1344 0 0 5 0 94.73 0.66 -1.45 +1345 0 0 3 0 94.88 0.93 -3.22 +1346 0 0 2 0 94.95 1.09 -4.07 +1347 0 0 0 100 16.00 0.07 -0.33 +1348 0 0 0 98 18.05 0.02 -0.43 +1349 0 0 0 95 21.52 -0.02 -0.81 +1350 0 0 0 90 27.02 -0.06 -1.52 +1351 0 0 0 85 32.37 -0.07 -2.07 +1352 0 0 0 80 37.53 -0.06 -2.55 +1353 0 0 0 75 42.24 -0.02 -2.96 +1354 0 0 0 70 46.75 0.02 -3.25 +1355 0 0 0 60 55.11 0.16 -3.90 +1356 0 0 0 50 62.72 0.31 -4.44 +1357 0 0 0 40 69.76 0.49 -4.90 +1358 0 0 0 30 76.38 0.70 -5.30 +1359 0 0 0 25 79.55 0.81 -5.46 +1360 0 0 0 20 82.71 0.94 -5.62 +1361 0 0 0 15 85.80 1.07 -5.72 +1362 0 0 0 10 88.87 1.20 -5.84 +1363 0 0 0 7 90.74 1.29 -5.91 +1364 0 0 0 5 91.93 1.35 -5.95 +1365 0 0 0 3 93.17 1.44 -6.02 +1366 0 0 0 2 93.76 1.45 -6.05 +1367 0 0 0 0 95.00 1.50 -6.00 +1368 100 85 85 0 26.30 -8.17 -4.54 +1369 80 65 65 0 36.49 -4.67 -4.60 +1370 60 45 45 0 50.74 -2.08 -4.61 +1371 40 27 27 0 66.01 -1.20 -5.85 +1372 20 12 12 0 80.96 -0.21 -6.62 +1373 10 6 6 0 88.02 0.65 -6.52 +1374 5 3 3 0 91.58 1.10 -6.43 +1375 40 27 27 10 61.99 -1.45 -5.47 +1376 20 12 12 10 75.81 -0.43 -6.33 +1377 10 6 6 10 82.35 0.39 -6.28 +1378 60 45 45 20 44.69 -2.51 -3.66 +1379 40 27 27 20 57.98 -1.61 -5.04 +1380 20 12 12 20 70.61 -0.59 -5.97 +1381 10 6 6 20 76.63 0.17 -5.98 +1382 80 65 65 40 27.71 -3.78 -2.51 +1383 60 45 45 40 38.04 -2.45 -2.75 +1384 40 27 27 40 49.24 -1.73 -4.05 +1385 20 12 12 40 59.61 -0.81 -5.04 +1386 10 6 6 40 64.59 -0.13 -5.13 +1387 100 85 85 60 17.70 -4.01 -0.61 +1388 80 65 65 60 22.63 -2.96 -1.16 +1389 60 45 45 60 30.36 -2.12 -1.67 +1390 40 27 27 60 39.06 -1.68 -2.95 +1391 20 12 12 60 47.01 -0.85 -3.91 +1392 10 6 6 60 50.89 -0.32 -4.09 +1393 100 85 85 80 14.88 -2.17 1.75 +1394 80 65 65 80 17.21 -1.53 0.63 +1395 60 45 45 80 21.59 -1.41 -0.19 +1396 40 27 27 80 26.96 -1.27 -1.44 +1397 20 12 12 80 32.13 -0.70 -2.44 +1398 10 6 6 80 34.71 -0.35 -2.66 +1399 100 85 85 100 12.62 0.12 4.12 +1400 80 65 65 100 12.68 0.09 2.71 +1401 60 45 45 100 13.10 0.10 1.39 +1402 40 27 27 100 13.98 0.00 0.32 +1403 20 12 12 100 15.06 -0.10 -0.36 +1404 10 6 6 100 15.59 -0.04 -0.46 +1405 100 0 0 70 27.49 -18.64 -25.44 +1406 0 100 0 70 23.52 35.19 -2.30 +1407 0 0 100 70 42.49 -4.09 42.01 +1408 100 100 0 70 15.42 9.13 -19.40 +1409 100 0 100 70 24.95 -31.00 10.13 +1410 0 100 100 70 23.56 29.25 17.99 +1411 40 40 0 70 31.54 4.94 -11.63 +1412 40 0 40 70 37.27 -10.46 3.88 +1413 0 40 40 70 35.66 10.84 9.34 +1414 3 3 0 0 92.55 2.20 -7.96 +1415 3 0 3 0 93.78 -0.25 -4.84 +1416 0 3 3 0 93.40 3.06 -4.03 +1417 3 3 3 0 92.34 1.87 -5.54 +1418 3 0 0 3 92.13 0.09 -7.49 +1419 0 3 0 3 91.79 3.43 -6.42 +1420 3 3 0 3 90.71 2.20 -8.14 +1421 0 0 3 3 93.04 0.91 -3.30 +1422 3 0 3 3 91.97 -0.36 -4.85 +1423 0 3 3 3 91.61 3.01 -4.04 +1424 3 3 3 3 90.56 1.72 -5.52 +1425 7 7 0 0 89.04 3.48 -10.58 +1426 7 0 7 0 91.94 -2.39 -3.22 +1427 0 7 7 0 91.18 5.14 -1.04 +1428 7 7 7 0 88.64 2.29 -4.41 +1429 7 0 0 7 88.25 -1.37 -9.15 +1430 0 7 0 7 87.49 5.71 -6.87 +1431 7 7 0 7 85.04 3.07 -10.21 +1432 0 0 7 7 90.32 0.22 0.07 +1433 7 0 7 7 87.81 -2.46 -3.19 +1434 0 7 7 7 87.07 4.70 -1.17 +1435 7 7 7 7 84.66 1.96 -4.38 +1436 40 3 0 0 77.93 -10.75 -25.27 +1437 3 40 0 0 74.61 26.77 -10.39 +1438 40 0 3 0 78.92 -13.18 -22.40 +1439 40 3 3 0 77.72 -11.43 -22.75 +1440 0 40 3 0 75.34 28.07 -7.02 +1441 3 40 3 0 74.45 26.59 -8.37 +1442 40 40 3 0 62.13 10.79 -23.92 +1443 3 0 40 0 91.15 -4.19 28.42 +1444 0 3 40 0 90.86 -0.60 29.02 +1445 3 3 40 0 89.76 -2.05 27.45 +1446 40 3 40 0 74.85 -17.75 8.07 +1447 3 40 40 0 72.48 23.76 18.99 +1448 40 0 0 3 77.67 -12.47 -24.39 +1449 40 3 0 3 76.42 -10.55 -24.92 +1450 0 40 0 3 74.02 27.71 -9.10 +1451 3 40 0 3 73.15 26.27 -10.51 +1452 40 40 0 3 61.12 11.14 -25.64 +1453 40 0 3 3 77.48 -13.20 -21.84 +1454 40 3 3 3 76.26 -11.22 -22.41 +1455 0 40 3 3 73.92 27.37 -6.91 +1456 3 40 3 3 73.05 25.93 -8.34 +1457 40 40 3 3 61.00 10.54 -23.50 +1458 0 0 40 3 90.45 -2.80 29.34 +1459 3 0 40 3 89.37 -4.26 27.78 +1460 40 0 40 3 74.61 -19.37 8.58 +1461 0 3 40 3 89.07 -0.67 28.27 +1462 3 3 40 3 88.00 -2.07 26.74 +1463 40 3 40 3 73.44 -17.46 7.77 +1464 0 40 40 3 71.98 24.68 19.89 +1465 3 40 40 3 71.07 23.12 18.45 +1466 40 40 40 3 58.83 5.61 1.84 +1467 3 0 0 40 68.97 -0.47 -5.92 +1468 0 3 0 40 68.68 1.98 -5.31 +1469 3 3 0 40 67.90 1.02 -6.38 +1470 40 3 0 40 57.49 -8.36 -18.26 +1471 3 40 0 40 54.94 18.59 -8.20 +1472 0 0 3 40 69.62 0.07 -2.86 +1473 3 0 3 40 68.82 -0.89 -3.94 +1474 40 0 3 40 58.20 -10.26 -16.04 +1475 0 3 3 40 68.53 1.58 -3.41 +1476 3 3 3 40 67.76 0.63 -4.46 +1477 40 3 3 40 57.36 -8.89 -16.42 +1478 0 40 3 40 55.43 19.26 -5.61 +1479 3 40 3 40 54.84 18.24 -6.56 +1480 40 40 3 40 46.48 7.16 -16.97 +1481 3 0 40 40 66.57 -3.98 19.51 +1482 0 3 40 40 66.31 -1.41 19.93 +1483 3 3 40 40 65.56 -2.43 18.78 +1484 40 3 40 40 55.13 -13.59 5.51 +1485 3 40 40 40 53.07 15.89 13.30 +1486 0 0 0 10 88.87 1.20 -5.84 +1487 0 0 10 10 88.24 -0.22 2.54 +1488 0 0 20 10 87.54 -1.22 10.66 +1489 0 0 40 10 86.23 -2.89 27.68 +1490 0 0 70 10 84.38 -4.29 56.70 +1491 0 10 0 10 84.30 7.28 -7.06 +1492 0 10 10 10 83.70 5.91 0.98 +1493 0 10 20 10 83.04 4.96 8.82 +1494 0 10 40 10 81.79 3.42 25.08 +1495 0 10 70 10 80.06 2.07 52.70 +1496 0 20 0 10 79.78 13.27 -7.75 +1497 0 20 10 10 79.19 12.05 -0.09 +1498 0 20 20 10 78.57 11.20 7.35 +1499 0 20 40 10 77.36 9.84 22.78 +1500 0 20 70 10 75.72 8.57 49.29 +1501 0 40 0 10 70.66 26.17 -8.83 +1502 0 40 10 10 70.20 25.09 -2.01 +1503 0 40 20 10 69.66 24.31 4.85 +1504 0 40 40 10 68.63 23.17 18.78 +1505 0 40 70 10 67.18 22.19 42.85 +1506 0 70 0 10 56.54 48.71 -8.78 +1507 0 70 10 10 56.16 48.22 -3.01 +1508 0 70 20 10 55.82 47.41 2.66 +1509 0 70 40 10 55.25 46.37 14.45 +1510 0 70 70 10 54.42 45.45 34.15 +1511 10 0 0 10 85.30 -2.40 -10.30 +1512 10 0 10 10 84.64 -3.94 -1.90 +1513 10 0 20 10 83.94 -5.11 6.25 +1514 10 0 40 10 82.58 -6.97 22.88 +1515 10 0 70 10 80.69 -8.74 50.84 +1516 10 10 0 10 80.92 3.59 -11.37 +1517 10 10 10 10 80.31 2.16 -3.42 +1518 10 10 20 10 79.64 1.02 4.36 +1519 10 10 40 10 78.32 -0.75 20.31 +1520 10 10 70 10 76.52 -2.40 47.48 +1521 10 20 0 10 76.55 9.49 -12.01 +1522 10 20 10 10 75.96 8.13 -4.43 +1523 10 20 20 10 75.34 7.07 3.10 +1524 10 20 40 10 74.08 5.48 18.28 +1525 10 20 70 10 72.37 3.91 44.21 +1526 10 40 0 10 67.78 22.03 -12.78 +1527 10 40 10 10 67.26 20.88 -6.02 +1528 10 40 20 10 66.70 19.95 0.71 +1529 10 40 40 10 65.67 18.52 14.59 +1530 10 40 70 10 64.17 17.26 38.14 +1531 10 70 0 10 53.96 44.28 -12.87 +1532 10 70 10 10 53.60 43.38 -7.17 +1533 10 70 20 10 53.24 42.67 -1.51 +1534 10 70 40 10 52.65 41.55 10.21 +1535 10 70 70 10 51.72 40.18 29.77 +1536 20 0 0 10 81.61 -5.48 -14.56 +1537 20 0 10 10 80.91 -7.17 -6.30 +1538 20 0 20 10 80.21 -8.56 1.77 +1539 20 0 40 10 78.80 -10.64 18.04 +1540 20 0 70 10 76.83 -12.75 45.48 +1541 20 10 0 10 77.43 0.32 -15.46 +1542 20 10 10 10 76.80 -1.33 -7.59 +1543 20 10 20 10 76.12 -2.57 0.04 +1544 20 10 40 10 74.74 -4.63 15.66 +1545 20 10 70 10 72.86 -6.62 42.38 +1546 20 20 0 10 73.23 6.03 -15.93 +1547 20 20 10 10 72.61 4.53 -8.46 +1548 20 20 20 10 71.98 3.31 -1.11 +1549 20 20 40 10 70.70 1.43 13.78 +1550 20 20 70 10 68.92 -0.45 39.35 +1551 20 40 0 10 64.72 18.15 -16.53 +1552 20 40 10 10 64.19 16.90 -9.85 +1553 20 40 20 10 63.62 15.86 -3.18 +1554 20 40 40 10 62.59 14.17 10.46 +1555 20 40 70 10 61.07 12.57 33.64 +1556 20 70 0 10 51.28 39.93 -16.57 +1557 20 70 10 10 50.93 38.94 -10.90 +1558 20 70 20 10 50.57 38.10 -5.41 +1559 20 70 40 10 49.96 36.56 6.09 +1560 20 70 70 10 49.00 35.14 25.36 +1561 40 0 0 10 74.18 -12.07 -23.20 +1562 40 0 10 10 73.40 -14.10 -15.36 +1563 40 0 20 10 72.65 -15.78 -7.61 +1564 40 0 40 10 71.21 -18.63 8.10 +1565 40 0 70 10 69.18 -21.62 34.72 +1566 40 10 0 10 70.30 -6.51 -23.88 +1567 40 10 10 10 69.62 -8.55 -16.29 +1568 40 10 20 10 68.92 -10.17 -8.86 +1569 40 10 40 10 67.54 -12.92 6.29 +1570 40 10 70 10 65.62 -15.82 31.84 +1571 40 20 0 10 66.44 -0.99 -24.08 +1572 40 20 10 10 65.79 -3.00 -16.85 +1573 40 20 20 10 65.12 -4.53 -9.77 +1574 40 20 40 10 63.82 -7.18 4.70 +1575 40 20 70 10 62.04 -9.90 29.26 +1576 40 40 0 10 58.51 10.38 -24.34 +1577 40 40 10 10 58.01 8.75 -17.80 +1578 40 40 20 10 57.40 7.44 -11.40 +1579 40 40 40 10 56.29 5.08 1.86 +1580 40 40 70 10 54.79 2.64 24.08 +1581 40 70 0 10 45.93 31.07 -24.24 +1582 40 70 10 10 45.59 29.75 -18.80 +1583 40 70 20 10 45.20 28.62 -13.36 +1584 40 70 40 10 44.43 26.65 -2.21 +1585 40 70 70 10 43.56 24.36 16.26 +1586 70 0 0 10 62.40 -23.02 -37.07 +1587 70 0 10 10 61.58 -25.88 -29.74 +1588 70 0 20 10 60.85 -28.45 -22.33 +1589 70 0 40 10 59.42 -32.83 -7.37 +1590 70 0 70 10 57.39 -38.02 17.38 +1591 70 10 0 10 59.10 -17.72 -37.33 +1592 70 10 10 10 58.41 -20.70 -30.10 +1593 70 10 20 10 57.69 -23.19 -23.01 +1594 70 10 40 10 56.34 -27.56 -8.62 +1595 70 10 70 10 54.39 -32.60 15.20 +1596 70 20 0 10 55.73 -12.82 -37.04 +1597 70 20 10 10 55.15 -15.56 -30.18 +1598 70 20 20 10 54.45 -17.96 -23.43 +1599 70 20 40 10 53.13 -22.13 -9.64 +1600 70 20 70 10 51.30 -27.04 13.19 +1601 70 40 0 10 48.89 -2.37 -36.71 +1602 70 40 10 10 48.38 -4.80 -30.47 +1603 70 40 20 10 47.76 -6.91 -24.27 +1604 70 40 40 10 46.66 -10.68 -11.66 +1605 70 40 70 10 45.12 -15.17 9.13 +1606 70 70 0 10 37.75 16.76 -36.11 +1607 70 70 10 10 37.46 14.56 -30.89 +1608 70 70 20 10 37.07 12.70 -25.68 +1609 70 70 40 10 36.35 9.41 -14.88 +1610 70 70 70 10 35.34 5.51 2.36 +1611 50 40 40 0 56.52 0.52 -2.91 +1612 100 0 0 10 52.62 -33.38 -48.95 +1613 0 100 0 10 44.79 70.33 -5.59 +1614 0 0 100 10 82.93 -4.35 86.26 +1615 0 100 100 10 44.53 64.54 41.83 +1616 100 0 100 10 46.36 -61.85 22.67 +1617 100 100 0 10 23.48 19.48 -44.21 +END_DATA diff --git a/crates/color/data/FOGRA52.txt b/crates/color/data/FOGRA52.txt new file mode 100644 index 0000000000..229c5b1c5f --- /dev/null +++ b/crates/color/data/FOGRA52.txt @@ -0,0 +1,1641 @@ +ISO28178 +FILE_DESCRIPTOR "FOGRA52" +ORIGINATOR "Fogra, www.fogra.org, developed with GMG GmbH & Co. KG, Heidelberger Druckmaschinen AG" +CREATED "May 2015" +TARGET_TYPE "ISO12642-2" +INSTRUMENTATION "D50, 2 degree, geometry 45/0, no polarisation filter, white backing, according to ISO 13655:2009 M1" +PRINT_CONDITIONS "Offset printing, according to ISO 12647-2:2013, OFCOM, print substrate 5 = Wood-free uncoated, fluorescence high (> 14 DeltaB according to ISO 15397), 120 g/m2, tone value increase curves C (CMYK)" +ILLUMINATION_NAME "D50" +OBSERVER_ANGLE "2" +FILTER "M1" +WEIGHTING_FUNCTION "ILLUMINANT, D50" +WEIGHTING_FUNCTION "OBSERVER, 2 degree" + +# The following flag is intended to improve compatibility with legacy devices. +KEYWORD "TRACEABILITY" +TRACEABILITY "NIST" + +NUMBER_OF_FIELDS 8 +BEGIN_DATA_FORMAT +SAMPLE_ID CMYK_C CMYK_M CMYK_Y CMYK_K LAB_L LAB_A LAB_B +END_DATA_FORMAT +NUMBER_OF_SETS 1617 +BEGIN_DATA +1 0 0 0 0 93.50 2.50 -10.00 +2 0 10 0 0 87.84 10.05 -10.46 +3 0 20 0 0 82.74 17.07 -10.66 +4 0 30 0 0 78.06 23.70 -10.61 +5 0 40 0 0 73.74 30.00 -10.32 +6 0 55 0 0 67.80 39.21 -9.60 +7 0 70 0 0 62.30 47.89 -8.22 +8 0 85 0 0 57.60 55.31 -6.22 +9 0 100 0 0 54.54 60.07 -4.30 +10 10 0 0 0 88.67 -1.16 -15.51 +11 10 10 0 0 83.36 5.91 -15.71 +12 10 20 0 0 78.55 12.48 -15.69 +13 10 30 0 0 74.13 18.69 -15.49 +14 10 40 0 0 70.02 24.58 -15.08 +15 10 55 0 0 64.43 33.15 -14.16 +16 10 70 0 0 59.19 41.31 -12.69 +17 10 85 0 0 54.66 48.36 -10.74 +18 10 100 0 0 51.67 52.96 -8.93 +19 20 0 0 0 84.29 -4.47 -20.44 +20 20 10 0 0 79.29 2.17 -20.40 +21 20 20 0 0 74.76 8.33 -20.19 +22 20 30 0 0 70.57 14.15 -19.84 +23 20 40 0 0 66.67 19.68 -19.34 +24 20 55 0 0 61.40 27.65 -18.21 +25 20 70 0 0 56.42 35.28 -16.64 +26 20 85 0 0 52.07 41.96 -14.69 +27 20 100 0 0 49.17 46.36 -12.96 +28 30 0 0 0 80.24 -7.50 -24.94 +29 30 10 0 0 75.53 -1.25 -24.68 +30 30 20 0 0 71.25 4.53 -24.30 +31 30 30 0 0 67.29 9.98 -23.81 +32 30 40 0 0 63.58 15.17 -23.20 +33 30 55 0 0 58.63 22.56 -21.87 +34 30 70 0 0 53.91 29.68 -20.18 +35 30 85 0 0 49.75 35.95 -18.21 +36 30 100 0 0 46.94 40.15 -16.52 +37 40 0 0 0 76.45 -10.28 -29.09 +38 40 10 0 0 72.02 -4.41 -28.63 +39 40 20 0 0 67.98 1.02 -28.09 +40 40 30 0 0 64.23 6.14 -27.46 +41 40 40 0 0 60.71 10.99 -26.76 +42 40 55 0 0 56.06 17.83 -25.22 +43 40 70 0 0 51.61 24.43 -23.39 +44 40 85 0 0 47.65 30.29 -21.37 +45 40 100 0 0 44.95 34.24 -19.69 +46 55 0 0 0 71.16 -14.26 -34.98 +47 55 10 0 0 67.16 -8.79 -34.07 +48 55 20 0 0 63.52 -3.74 -33.13 +49 55 30 0 0 60.12 1.02 -32.16 +50 55 40 0 0 56.92 5.55 -31.14 +51 55 55 0 0 52.80 11.83 -29.39 +52 55 70 0 0 48.83 17.92 -27.40 +53 55 85 0 0 45.28 23.39 -25.30 +54 55 100 0 0 42.84 27.13 -23.62 +55 70 0 0 0 66.13 -17.82 -40.45 +56 70 10 0 0 62.55 -12.77 -39.12 +57 70 20 0 0 59.27 -8.11 -37.83 +58 70 30 0 0 56.21 -3.72 -36.53 +59 70 40 0 0 53.32 0.45 -35.22 +60 70 55 0 0 49.74 6.14 -33.24 +61 70 70 0 0 46.26 11.70 -31.09 +62 70 85 0 0 43.12 16.72 -28.88 +63 70 100 0 0 40.96 20.19 -27.16 +64 85 0 0 0 61.71 -20.66 -45.11 +65 85 10 0 0 58.47 -16.02 -43.45 +66 85 20 0 0 55.52 -11.74 -41.84 +67 85 30 0 0 52.76 -7.72 -40.26 +68 85 40 0 0 50.15 -3.88 -38.69 +69 85 55 0 0 47.05 1.23 -36.52 +70 85 70 0 0 44.04 6.24 -34.20 +71 85 85 0 0 41.32 10.80 -31.87 +72 85 100 0 0 39.43 13.98 -30.09 +73 100 0 0 0 58.70 -22.35 -48.12 +74 100 10 0 0 55.71 -18.02 -46.24 +75 100 20 0 0 52.98 -14.03 -44.44 +76 100 30 0 0 50.42 -10.26 -42.69 +77 100 40 0 0 48.01 -6.69 -40.95 +78 100 55 0 0 45.25 -2.00 -38.66 +79 100 70 0 0 42.57 2.62 -36.22 +80 100 85 0 0 40.15 6.83 -33.80 +81 100 100 0 0 38.47 9.76 -31.96 +82 0 0 10 0 92.65 0.82 0.84 +83 0 10 10 0 87.02 8.58 -0.61 +84 0 20 10 0 81.96 15.80 -1.70 +85 0 30 10 0 77.31 22.61 -2.48 +86 0 40 10 0 73.02 29.08 -2.98 +87 0 55 10 0 67.21 38.37 -3.29 +88 0 70 10 0 61.83 47.13 -2.94 +89 0 85 10 0 57.23 54.62 -1.90 +90 0 100 10 0 54.24 59.43 -0.66 +91 10 0 10 0 87.76 -3.15 -5.03 +92 10 10 10 0 82.49 4.15 -6.14 +93 10 20 10 0 77.74 10.93 -6.96 +94 10 30 10 0 73.37 17.34 -7.53 +95 10 40 10 0 69.31 23.43 -7.87 +96 10 55 10 0 63.85 32.11 -7.97 +97 10 70 10 0 58.74 40.38 -7.50 +98 10 85 10 0 54.33 47.53 -6.49 +99 10 100 10 0 51.42 52.21 -5.36 +100 20 0 10 0 83.32 -6.77 -10.27 +101 20 10 10 0 78.39 0.13 -11.09 +102 20 20 10 0 73.92 6.52 -11.67 +103 20 30 10 0 69.80 12.55 -12.06 +104 20 40 10 0 65.96 18.29 -12.24 +105 20 55 10 0 60.84 26.41 -12.11 +106 20 70 10 0 56.00 34.18 -11.54 +107 20 85 10 0 51.78 40.98 -10.52 +108 20 100 10 0 48.95 45.49 -9.45 +109 30 0 10 0 79.22 -10.10 -15.07 +110 30 10 10 0 74.59 -3.58 -15.62 +111 30 20 10 0 70.40 2.45 -15.98 +112 30 30 10 0 66.51 8.13 -16.17 +113 30 40 10 0 62.87 13.54 -16.22 +114 30 55 10 0 58.08 21.11 -15.87 +115 30 70 10 0 53.51 28.39 -15.16 +116 30 85 10 0 49.49 34.83 -14.11 +117 30 100 10 0 46.77 39.14 -13.07 +118 40 0 10 0 75.39 -13.19 -19.50 +119 40 10 10 0 71.05 -7.03 -19.79 +120 40 20 10 0 67.11 -1.34 -19.94 +121 40 30 10 0 63.44 4.03 -19.97 +122 40 40 10 0 60.00 9.13 -19.88 +123 40 55 10 0 55.53 16.17 -19.31 +124 40 70 10 0 51.24 22.97 -18.44 +125 40 85 10 0 47.43 29.01 -17.31 +126 40 100 10 0 44.83 33.10 -16.29 +127 55 0 10 0 70.17 -17.38 -25.68 +128 55 10 10 0 66.26 -11.60 -25.50 +129 55 20 10 0 62.70 -6.27 -25.25 +130 55 30 10 0 59.38 -1.25 -24.92 +131 55 40 10 0 56.27 3.52 -24.51 +132 55 55 10 0 52.29 10.03 -23.64 +133 55 70 10 0 48.44 16.37 -22.55 +134 55 85 10 0 45.00 22.06 -21.29 +135 55 100 10 0 42.64 25.93 -20.20 +136 70 0 10 0 65.19 -21.21 -31.44 +137 70 10 10 0 61.70 -15.83 -30.84 +138 70 20 10 0 58.51 -10.86 -30.21 +139 70 30 10 0 55.53 -6.19 -29.54 +140 70 40 10 0 52.72 -1.75 -28.83 +141 70 55 10 0 49.23 4.22 -27.67 +142 70 70 10 0 45.84 10.04 -26.34 +143 70 85 10 0 42.79 15.30 -24.89 +144 70 100 10 0 40.68 18.93 -23.72 +145 85 0 10 0 60.80 -24.35 -36.38 +146 85 10 10 0 57.67 -19.34 -35.43 +147 85 20 10 0 54.80 -14.73 -34.48 +148 85 30 10 0 52.12 -10.39 -33.53 +149 85 40 10 0 49.59 -6.27 -32.54 +150 85 55 10 0 46.55 -0.84 -31.12 +151 85 70 10 0 43.60 4.47 -29.55 +152 85 85 10 0 40.92 9.31 -27.94 +153 85 100 10 0 39.07 12.66 -26.66 +154 100 0 10 0 57.83 -26.26 -39.62 +155 100 10 10 0 54.93 -21.54 -38.43 +156 100 20 10 0 52.28 -17.18 -37.28 +157 100 30 10 0 49.81 -13.10 -36.12 +158 100 40 10 0 47.47 -9.21 -34.97 +159 100 55 10 0 44.75 -4.17 -33.38 +160 100 70 10 0 42.10 0.77 -31.65 +161 100 85 10 0 39.70 5.27 -29.89 +162 100 100 10 0 38.04 8.40 -28.52 +163 0 0 20 0 91.90 -0.46 10.79 +164 0 10 20 0 86.29 7.45 8.46 +165 0 20 20 0 81.25 14.82 6.55 +166 0 30 20 0 76.63 21.78 5.01 +167 0 40 20 0 72.37 28.37 3.80 +168 0 55 20 0 66.68 37.70 2.53 +169 0 70 20 0 61.40 46.50 1.95 +170 0 85 20 0 56.90 54.03 2.11 +171 0 100 20 0 53.96 58.87 2.71 +172 10 0 20 0 86.95 -4.72 4.61 +173 10 10 20 0 81.72 2.76 2.67 +174 10 20 20 0 77.01 9.71 1.08 +175 10 30 20 0 72.68 16.27 -0.21 +176 10 40 20 0 68.66 22.50 -1.22 +177 10 55 20 0 63.33 31.26 -2.24 +178 10 70 20 0 58.34 39.59 -2.71 +179 10 85 20 0 54.03 46.81 -2.56 +180 10 100 20 0 51.18 51.54 -2.06 +181 20 0 20 0 82.46 -8.61 -0.93 +182 20 10 20 0 77.58 -1.53 -2.53 +183 20 20 20 0 73.17 5.05 -3.83 +184 20 30 20 0 69.10 11.26 -4.88 +185 20 40 20 0 65.31 17.16 -5.70 +186 20 55 20 0 60.32 25.37 -6.49 +187 20 70 20 0 55.62 33.24 -6.82 +188 20 85 20 0 51.51 40.14 -6.66 +189 20 100 20 0 48.76 44.71 -6.20 +190 30 0 20 0 78.31 -12.23 -6.00 +191 30 10 20 0 73.76 -5.50 -7.28 +192 30 20 20 0 69.62 0.73 -8.31 +193 30 30 20 0 65.80 6.61 -9.14 +194 30 40 20 0 62.23 12.20 -9.78 +195 30 55 20 0 57.58 19.89 -10.33 +196 30 70 20 0 53.16 27.29 -10.51 +197 30 85 20 0 49.26 33.85 -10.29 +198 30 100 20 0 46.62 38.25 -9.87 +199 40 0 20 0 74.44 -15.60 -10.68 +200 40 10 20 0 70.19 -9.21 -11.66 +201 40 20 20 0 66.32 -3.30 -12.44 +202 40 30 20 0 62.73 2.28 -13.06 +203 40 40 20 0 59.36 7.57 -13.53 +204 40 55 20 0 55.05 14.75 -13.84 +205 40 70 20 0 50.91 21.70 -13.85 +206 40 85 20 0 47.23 27.89 -13.56 +207 40 100 20 0 44.72 32.08 -13.13 +208 55 0 20 0 69.28 -19.99 -17.11 +209 55 10 20 0 65.45 -13.96 -17.62 +210 55 20 20 0 61.97 -8.40 -17.99 +211 55 30 20 0 58.73 -3.16 -18.24 +212 55 40 20 0 55.68 1.82 -18.38 +213 55 55 20 0 51.82 8.51 -18.34 +214 55 70 20 0 48.09 15.02 -18.05 +215 55 85 20 0 44.76 20.87 -17.55 +216 55 100 20 0 42.46 24.87 -17.02 +217 70 0 20 0 64.35 -24.06 -23.14 +218 70 10 20 0 60.94 -18.40 -23.20 +219 70 20 20 0 57.82 -13.18 -23.19 +220 70 30 20 0 54.91 -8.27 -23.09 +221 70 40 20 0 52.17 -3.61 -22.92 +222 70 55 20 0 48.77 2.56 -22.52 +223 70 70 20 0 45.46 8.60 -21.94 +224 70 85 20 0 42.48 14.06 -21.20 +225 70 100 20 0 40.42 17.82 -20.54 +226 85 0 20 0 60.01 -27.46 -28.34 +227 85 10 20 0 56.95 -22.15 -28.03 +228 85 20 20 0 54.16 -17.26 -27.69 +229 85 30 20 0 51.55 -12.67 -27.29 +230 85 40 20 0 49.09 -8.30 -26.85 +231 85 55 20 0 46.10 -2.62 -26.12 +232 85 70 20 0 43.19 2.95 -25.25 +233 85 85 20 0 40.56 8.00 -24.28 +234 85 100 20 0 38.73 11.50 -23.47 +235 100 0 20 0 57.06 -29.59 -31.76 +236 100 10 20 0 54.25 -24.54 -31.22 +237 100 20 20 0 51.67 -19.89 -30.66 +238 100 30 20 0 49.27 -15.52 -30.06 +239 100 40 20 0 47.00 -11.38 -29.43 +240 100 55 20 0 44.30 -6.06 -28.50 +241 100 70 20 0 41.68 -0.84 -27.41 +242 100 85 20 0 39.30 3.90 -26.26 +243 100 100 20 0 37.65 7.20 -25.35 +244 0 0 30 0 91.22 -1.45 20.12 +245 0 10 30 0 85.62 6.59 16.96 +246 0 20 30 0 80.60 14.07 14.29 +247 0 30 30 0 76.01 21.13 12.04 +248 0 40 30 0 71.77 27.83 10.16 +249 0 55 30 0 66.18 37.17 8.02 +250 0 70 30 0 60.99 45.97 6.55 +251 0 85 30 0 56.58 53.50 5.90 +252 0 100 30 0 53.70 58.36 5.90 +253 10 0 30 0 86.21 -5.97 13.64 +254 10 10 30 0 81.02 1.65 10.92 +255 10 20 30 0 76.34 8.73 8.62 +256 10 30 30 0 72.04 15.42 6.67 +257 10 40 30 0 68.06 21.77 5.03 +258 10 55 30 0 62.84 30.56 3.15 +259 10 70 30 0 57.96 38.92 1.82 +260 10 85 30 0 53.75 46.18 1.15 +261 10 100 30 0 50.96 50.94 1.07 +262 20 0 30 0 81.67 -10.12 7.82 +263 20 10 30 0 76.84 -2.88 5.50 +264 20 20 30 0 72.47 3.84 3.54 +265 20 30 30 0 68.45 10.19 1.86 +266 20 40 30 0 64.71 16.23 0.44 +267 20 55 30 0 59.85 24.49 -1.18 +268 20 70 30 0 55.26 32.42 -2.37 +269 20 85 30 0 51.26 39.38 -3.00 +270 20 100 30 0 48.58 44.02 -3.13 +271 30 0 30 0 77.48 -14.00 2.50 +272 30 10 30 0 72.99 -7.10 0.55 +273 30 20 30 0 68.91 -0.70 -1.11 +274 30 30 30 0 65.15 5.33 -2.53 +275 30 40 30 0 61.63 11.07 -3.73 +276 30 55 30 0 57.12 18.83 -5.10 +277 30 70 30 0 52.83 26.32 -6.12 +278 30 85 30 0 49.04 32.96 -6.69 +279 30 100 30 0 46.48 37.43 -6.83 +280 40 0 30 0 73.58 -17.64 -2.41 +281 40 10 30 0 69.40 -11.06 -4.03 +282 40 20 30 0 65.60 -4.97 -5.40 +283 40 30 30 0 62.07 0.78 -6.57 +284 40 40 30 0 58.78 6.24 -7.56 +285 40 55 30 0 54.61 13.52 -8.68 +286 40 70 30 0 50.61 20.57 -9.52 +287 40 85 30 0 47.05 26.88 -10.00 +288 40 100 30 0 44.62 31.15 -10.13 +289 55 0 30 0 68.47 -22.20 -9.07 +290 55 10 30 0 64.72 -15.97 -10.21 +291 55 20 30 0 61.30 -10.21 -11.15 +292 55 30 30 0 58.12 -4.79 -11.95 +293 55 40 30 0 55.14 0.37 -12.61 +294 55 55 30 0 51.39 7.19 -13.32 +295 55 70 30 0 47.77 13.83 -13.81 +296 55 85 30 0 44.52 19.81 -14.03 +297 55 100 30 0 42.29 23.90 -14.01 +298 70 0 30 0 63.60 -26.48 -15.34 +299 70 10 30 0 60.25 -20.60 -16.02 +300 70 20 30 0 57.20 -15.17 -16.58 +301 70 30 30 0 54.35 -10.06 -17.02 +302 70 40 30 0 51.68 -5.22 -17.36 +303 70 55 30 0 48.35 1.13 -17.66 +304 70 70 30 0 45.11 7.33 -17.78 +305 70 85 30 0 42.20 12.94 -17.71 +306 70 100 30 0 40.18 16.81 -17.53 +307 85 0 30 0 59.29 -30.13 -20.77 +308 85 10 30 0 56.31 -24.56 -21.08 +309 85 20 30 0 53.58 -19.44 -21.28 +310 85 30 30 0 51.03 -14.63 -21.42 +311 85 40 30 0 48.63 -10.07 -21.48 +312 85 55 30 0 45.68 -4.18 -21.40 +313 85 70 30 0 42.82 1.58 -21.18 +314 85 85 30 0 40.22 6.81 -20.82 +315 85 100 30 0 38.42 10.44 -20.46 +316 100 0 30 0 56.37 -32.45 -24.37 +317 100 10 30 0 53.63 -27.12 -24.43 +318 100 20 30 0 51.12 -22.22 -24.42 +319 100 30 30 0 48.77 -17.62 -24.35 +320 100 40 30 0 46.56 -13.26 -24.21 +321 100 55 30 0 43.89 -7.71 -23.87 +322 100 70 30 0 41.29 -2.27 -23.41 +323 100 85 30 0 38.93 2.68 -22.84 +324 100 100 30 0 37.28 6.11 -22.33 +325 0 0 40 0 90.59 -2.19 28.94 +326 0 10 40 0 85.01 5.94 25.01 +327 0 20 40 0 80.00 13.50 21.63 +328 0 30 40 0 75.42 20.65 18.71 +329 0 40 40 0 71.21 27.42 16.20 +330 0 55 40 0 65.70 36.74 13.23 +331 0 70 40 0 60.61 45.53 10.95 +332 0 85 40 0 56.28 53.05 9.51 +333 0 100 40 0 53.46 57.91 8.95 +334 10 0 40 0 85.53 -6.96 22.17 +335 10 10 40 0 80.36 0.76 18.73 +336 10 20 40 0 75.71 7.95 15.78 +337 10 30 40 0 71.44 14.74 13.20 +338 10 40 40 0 67.49 21.18 10.97 +339 10 55 40 0 62.38 29.97 8.27 +340 10 70 40 0 57.60 38.34 6.13 +341 10 85 40 0 53.48 45.62 4.70 +342 10 100 40 0 50.75 50.40 4.06 +343 20 0 40 0 80.94 -11.35 16.10 +344 20 10 40 0 76.16 -3.99 13.10 +345 20 20 40 0 71.83 2.85 10.52 +346 20 30 40 0 67.85 9.32 8.26 +347 20 40 40 0 64.15 15.46 6.29 +348 20 55 40 0 59.40 23.74 3.87 +349 20 70 40 0 54.93 31.70 1.88 +350 20 85 40 0 51.02 38.70 0.49 +351 20 100 40 0 48.41 43.37 -0.18 +352 30 0 40 0 76.71 -15.48 10.54 +353 30 10 40 0 72.27 -8.44 7.96 +354 30 20 40 0 68.25 -1.91 5.71 +355 30 30 40 0 64.54 4.26 3.75 +356 30 40 40 0 61.07 10.12 2.03 +357 30 55 40 0 56.69 17.92 -0.13 +358 30 70 40 0 52.52 25.46 -1.93 +359 30 85 40 0 48.84 32.17 -3.25 +360 30 100 40 0 46.35 36.68 -3.92 +361 40 0 40 0 72.77 -19.38 5.41 +362 40 10 40 0 68.66 -12.63 3.20 +363 40 20 40 0 64.92 -6.38 1.28 +364 40 30 40 0 61.46 -0.49 -0.40 +365 40 40 40 0 58.22 5.11 -1.89 +366 40 55 40 0 54.19 12.45 -3.78 +367 40 70 40 0 50.32 19.57 -5.38 +368 40 85 40 0 46.88 25.94 -6.59 +369 40 100 40 0 44.54 30.29 -7.25 +370 55 0 40 0 67.72 -24.08 -1.46 +371 55 10 40 0 64.03 -17.68 -3.18 +372 55 20 40 0 60.68 -11.76 -4.67 +373 55 30 40 0 57.55 -6.18 -5.97 +374 55 40 40 0 54.63 -0.88 -7.12 +375 55 55 40 0 50.98 6.03 -8.55 +376 55 70 40 0 47.46 12.76 -9.75 +377 55 85 40 0 44.31 18.84 -10.65 +378 55 100 40 0 42.14 23.01 -11.12 +379 70 0 40 0 62.90 -28.55 -7.94 +380 70 10 40 0 59.62 -22.48 -9.20 +381 70 20 40 0 56.62 -16.88 -10.29 +382 70 30 40 0 53.84 -11.61 -11.24 +383 70 40 40 0 51.21 -6.60 -12.06 +384 70 55 40 0 47.95 -0.13 -13.02 +385 70 70 40 0 44.78 6.19 -13.81 +386 70 85 40 0 41.93 11.92 -14.37 +387 70 100 40 0 39.95 15.88 -14.64 +388 85 0 40 0 58.63 -32.41 -13.59 +389 85 10 40 0 55.71 -26.64 -14.46 +390 85 20 40 0 53.04 -21.33 -15.20 +391 85 30 40 0 50.55 -16.34 -15.82 +392 85 40 40 0 48.20 -11.61 -16.36 +393 85 55 40 0 45.30 -5.55 -16.90 +394 85 70 40 0 42.47 0.36 -17.29 +395 85 85 40 0 39.90 5.75 -17.51 +396 85 100 40 0 38.12 9.48 -17.57 +397 100 0 40 0 55.74 -34.91 -17.35 +398 100 10 40 0 53.06 -29.37 -17.96 +399 100 20 40 0 50.61 -24.25 -18.48 +400 100 30 40 0 48.32 -19.46 -18.89 +401 100 40 40 0 46.16 -14.92 -19.23 +402 100 55 40 0 43.51 -9.18 -19.47 +403 100 70 40 0 40.92 -3.55 -19.58 +404 100 85 40 0 38.57 1.56 -19.55 +405 100 100 40 0 36.94 5.12 -19.44 +406 0 0 55 0 89.71 -2.76 41.59 +407 0 10 55 0 84.13 5.50 36.52 +408 0 20 55 0 79.14 13.19 32.10 +409 0 30 55 0 74.58 20.47 28.21 +410 0 40 55 0 70.39 27.37 24.77 +411 0 55 55 0 65.07 36.48 20.75 +412 0 70 55 0 60.15 45.10 17.39 +413 0 85 55 0 55.95 52.49 14.92 +414 0 100 55 0 53.21 57.28 13.60 +415 10 0 55 0 84.63 -7.77 34.17 +416 10 10 55 0 79.47 0.07 29.68 +417 10 20 55 0 74.83 7.37 25.75 +418 10 30 55 0 70.58 14.27 22.27 +419 10 40 55 0 66.65 20.82 19.18 +420 10 55 55 0 61.68 29.48 15.50 +421 10 70 55 0 57.03 37.74 12.35 +422 10 85 55 0 53.02 44.93 9.97 +423 10 100 55 0 50.37 49.66 8.64 +424 20 0 55 0 80.03 -12.41 27.49 +425 20 10 55 0 75.25 -4.94 23.52 +426 20 20 55 0 70.93 2.00 20.05 +427 20 30 55 0 66.97 8.57 16.95 +428 20 40 55 0 63.29 14.81 14.18 +429 20 55 55 0 58.64 23.03 10.82 +430 20 70 55 0 54.27 30.94 7.90 +431 20 85 55 0 50.45 37.89 5.63 +432 20 100 55 0 47.90 42.54 4.32 +433 30 0 55 0 75.79 -16.78 21.37 +434 30 10 55 0 71.36 -9.65 17.89 +435 30 20 55 0 67.35 -3.02 14.82 +436 30 30 55 0 63.65 3.24 12.08 +437 30 40 55 0 60.20 9.19 9.61 +438 30 55 55 0 55.88 16.99 6.59 +439 30 70 55 0 51.78 24.53 3.91 +440 30 85 55 0 48.16 31.24 1.77 +441 30 100 55 0 45.72 35.77 0.50 +442 40 0 55 0 71.84 -20.92 15.69 +443 40 10 55 0 67.74 -14.09 12.66 +444 40 20 55 0 64.01 -7.76 9.99 +445 40 30 55 0 60.56 -1.78 7.58 +446 40 40 55 0 57.34 3.91 5.41 +447 40 55 55 0 53.34 11.29 2.71 +448 40 70 55 0 49.51 18.48 0.28 +449 40 85 55 0 46.10 24.91 -1.69 +450 40 100 55 0 43.78 29.31 -2.91 +451 55 0 55 0 66.74 -25.80 8.22 +452 55 10 55 0 63.08 -19.29 5.76 +453 55 20 55 0 59.74 -13.26 3.58 +454 55 30 55 0 56.64 -7.58 1.63 +455 55 40 55 0 53.73 -2.18 -0.14 +456 55 55 55 0 50.13 4.78 -2.30 +457 55 70 55 0 46.66 11.57 -4.25 +458 55 85 55 0 43.55 17.70 -5.83 +459 55 100 55 0 41.41 21.92 -6.80 +460 70 0 55 0 61.87 -30.47 1.14 +461 70 10 55 0 58.62 -24.26 -0.79 +462 70 20 55 0 55.65 -18.53 -2.49 +463 70 30 55 0 52.89 -13.14 -4.02 +464 70 40 55 0 50.30 -8.02 -5.40 +465 70 55 55 0 47.10 -1.49 -7.01 +466 70 70 55 0 43.99 4.89 -8.46 +467 70 85 55 0 41.19 10.67 -9.62 +468 70 100 55 0 39.26 14.68 -10.34 +469 85 0 55 0 57.57 -34.54 -5.06 +470 85 10 55 0 54.68 -28.61 -6.53 +471 85 20 55 0 52.04 -23.14 -7.82 +472 85 30 55 0 49.59 -18.00 -8.98 +473 85 40 55 0 47.27 -13.13 -10.01 +474 85 55 55 0 44.44 -7.04 -11.11 +475 85 70 55 0 41.68 -1.06 -12.09 +476 85 85 55 0 39.19 4.38 -12.85 +477 85 100 55 0 37.45 8.16 -13.30 +478 100 0 55 0 54.64 -37.20 -9.23 +479 100 10 55 0 52.00 -31.47 -10.39 +480 100 20 55 0 49.59 -26.18 -11.41 +481 100 30 55 0 47.34 -21.23 -12.30 +482 100 40 55 0 45.22 -16.54 -13.10 +483 100 55 55 0 42.65 -10.75 -13.85 +484 100 70 55 0 40.14 -5.06 -14.48 +485 100 85 55 0 37.87 0.10 -14.94 +486 100 100 55 0 36.28 3.71 -15.19 +487 0 0 70 0 88.89 -2.96 53.84 +488 0 10 70 0 83.30 5.39 47.71 +489 0 20 70 0 78.31 13.18 42.32 +490 0 30 70 0 73.77 20.54 37.50 +491 0 40 70 0 69.60 27.52 33.18 +492 0 55 70 0 64.45 36.39 28.16 +493 0 70 70 0 59.68 44.80 23.75 +494 0 85 70 0 55.62 52.02 20.29 +495 0 100 70 0 52.97 56.72 18.22 +496 10 0 70 0 83.78 -8.21 45.81 +497 10 10 70 0 78.62 -0.30 40.34 +498 10 20 70 0 73.98 7.07 35.50 +499 10 30 70 0 69.74 14.05 31.16 +500 10 40 70 0 65.83 20.68 27.24 +501 10 55 70 0 60.99 29.16 22.61 +502 10 70 70 0 56.47 37.27 18.50 +503 10 85 70 0 52.57 44.34 15.19 +504 10 100 70 0 49.99 49.01 13.17 +505 20 0 70 0 79.17 -13.09 38.58 +506 20 10 70 0 74.38 -5.56 33.70 +507 20 20 70 0 70.07 1.44 29.37 +508 20 30 70 0 66.11 8.07 25.46 +509 20 40 70 0 62.44 14.38 21.92 +510 20 55 70 0 57.90 22.49 17.67 +511 20 70 70 0 53.62 30.30 13.86 +512 20 85 70 0 49.88 37.19 10.72 +513 20 100 70 0 47.39 41.80 8.77 +514 30 0 70 0 74.92 -17.70 31.92 +515 30 10 70 0 70.48 -10.52 27.60 +516 30 20 70 0 66.48 -3.85 23.74 +517 30 30 70 0 62.78 2.47 20.25 +518 30 40 70 0 59.34 8.48 17.07 +519 30 55 70 0 55.09 16.23 13.20 +520 30 70 70 0 51.04 23.74 9.67 +521 30 85 70 0 47.48 30.43 6.73 +522 30 100 70 0 45.08 34.96 4.87 +523 40 0 70 0 70.96 -22.09 25.73 +524 40 10 70 0 66.86 -15.22 21.93 +525 40 20 70 0 63.13 -8.85 18.53 +526 40 30 70 0 59.69 -2.82 15.43 +527 40 40 70 0 56.47 2.91 12.60 +528 40 55 70 0 52.50 10.32 9.10 +529 40 70 70 0 48.70 17.52 5.88 +530 40 85 70 0 45.32 23.99 3.16 +531 40 100 70 0 43.03 28.40 1.41 +532 55 0 70 0 65.81 -27.13 17.71 +533 55 10 70 0 62.15 -20.56 14.54 +534 55 20 70 0 58.83 -14.47 11.70 +535 55 30 70 0 55.74 -8.72 9.12 +536 55 40 70 0 52.85 -3.26 6.74 +537 55 55 70 0 49.29 3.71 3.87 +538 55 70 70 0 45.86 10.53 1.21 +539 55 85 70 0 42.79 16.70 -1.06 +540 55 100 70 0 40.69 20.94 -2.52 +541 70 0 70 0 60.89 -32.00 10.06 +542 70 10 70 0 57.66 -25.70 7.49 +543 70 20 70 0 54.71 -19.89 5.20 +544 70 30 70 0 51.98 -14.40 3.10 +545 70 40 70 0 49.40 -9.19 1.16 +546 70 55 70 0 46.26 -2.67 -1.07 +547 70 70 70 0 43.21 3.74 -3.16 +548 70 85 70 0 40.46 9.56 -4.93 +549 70 100 70 0 38.56 13.59 -6.08 +550 85 0 70 0 56.54 -36.28 3.33 +551 85 10 70 0 53.68 -30.23 1.28 +552 85 20 70 0 51.07 -24.65 -0.54 +553 85 30 70 0 48.65 -19.41 -2.20 +554 85 40 70 0 46.36 -14.42 -3.73 +555 85 55 70 0 43.60 -8.32 -5.39 +556 85 70 70 0 40.91 -2.31 -6.92 +557 85 85 70 0 38.48 3.15 -8.21 +558 85 100 70 0 36.78 6.95 -9.05 +559 100 0 70 0 53.58 -39.11 -1.22 +560 100 10 70 0 50.98 -33.23 -2.91 +561 100 20 70 0 48.60 -27.83 -4.42 +562 100 30 70 0 46.38 -22.74 -5.79 +563 100 40 70 0 44.30 -17.93 -7.04 +564 100 55 70 0 41.81 -12.12 -8.29 +565 100 70 70 0 39.38 -6.41 -9.42 +566 100 85 70 0 37.17 -1.22 -10.36 +567 100 100 70 0 35.64 2.40 -10.95 +568 0 0 85 0 88.16 -2.85 64.82 +569 0 10 85 0 82.57 5.54 57.79 +570 0 20 85 0 77.57 13.39 51.55 +571 0 30 85 0 73.04 20.81 45.93 +572 0 40 85 0 68.89 27.84 40.84 +573 0 55 85 0 63.89 36.46 34.94 +574 0 70 85 0 59.27 44.62 29.61 +575 0 85 85 0 55.32 51.66 25.22 +576 0 100 85 0 52.75 56.25 22.49 +577 10 0 85 0 83.04 -8.32 56.29 +578 10 10 85 0 77.86 -0.38 49.96 +579 10 20 85 0 73.22 7.03 44.34 +580 10 30 85 0 68.98 14.06 39.23 +581 10 40 85 0 65.09 20.72 34.60 +582 10 55 85 0 60.37 29.01 29.13 +583 10 70 85 0 55.95 36.95 24.14 +584 10 85 85 0 52.15 43.88 20.00 +585 10 100 85 0 49.64 48.46 17.36 +586 20 0 85 0 78.40 -13.42 48.57 +587 20 10 85 0 73.61 -5.88 42.90 +588 20 20 85 0 69.29 1.15 37.83 +589 20 30 85 0 65.34 7.82 33.22 +590 20 40 85 0 61.68 14.16 29.00 +591 20 55 85 0 57.22 22.14 23.96 +592 20 70 85 0 53.02 29.84 19.32 +593 20 85 85 0 49.36 36.62 15.41 +594 20 100 85 0 46.91 41.18 12.89 +595 30 0 85 0 74.14 -18.25 41.45 +596 30 10 85 0 69.70 -11.06 36.39 +597 30 20 85 0 65.69 -4.38 31.86 +598 30 30 85 0 61.99 1.96 27.70 +599 30 40 85 0 58.56 8.00 23.89 +600 30 55 85 0 54.36 15.68 19.27 +601 30 70 85 0 50.37 23.12 14.97 +602 30 85 85 0 46.86 29.77 11.31 +603 30 100 85 0 44.49 34.26 8.92 +604 40 0 85 0 70.17 -22.87 34.83 +605 40 10 85 0 66.07 -16.00 30.34 +606 40 20 85 0 62.34 -9.61 26.31 +607 40 30 85 0 58.90 -3.58 22.60 +608 40 40 85 0 55.69 2.17 19.19 +609 40 55 85 0 51.73 9.56 14.98 +610 40 70 85 0 47.95 16.77 11.03 +611 40 85 85 0 44.60 23.23 7.62 +612 40 100 85 0 42.32 27.65 5.38 +613 55 0 85 0 64.97 -28.05 26.32 +614 55 10 85 0 61.32 -21.46 22.53 +615 55 20 85 0 58.00 -15.34 19.12 +616 55 30 85 0 54.93 -9.56 15.96 +617 55 40 85 0 52.05 -4.06 13.05 +618 55 55 85 0 48.52 2.89 9.54 +619 55 70 85 0 45.13 9.70 6.22 +620 55 85 85 0 42.09 15.86 3.35 +621 55 100 85 0 40.01 20.11 1.44 +622 70 0 85 0 60.01 -33.09 18.18 +623 70 10 85 0 56.79 -26.75 15.05 +624 70 20 85 0 53.86 -20.89 12.23 +625 70 30 85 0 51.14 -15.35 9.62 +626 70 40 85 0 48.58 -10.09 7.21 +627 70 55 85 0 45.49 -3.58 4.39 +628 70 70 85 0 42.49 2.81 1.74 +629 70 85 85 0 39.78 8.63 -0.58 +630 70 100 85 0 37.91 12.67 -2.14 +631 85 0 85 0 55.61 -37.57 10.99 +632 85 10 85 0 52.78 -31.45 8.43 +633 85 20 85 0 50.20 -25.79 6.13 +634 85 30 85 0 47.79 -20.47 4.01 +635 85 40 85 0 45.53 -15.42 2.04 +636 85 55 85 0 42.83 -9.34 -0.11 +637 85 70 85 0 40.20 -3.35 -2.15 +638 85 85 85 0 37.82 2.12 -3.93 +639 85 100 85 0 36.16 5.94 -5.13 +640 100 0 85 0 52.63 -40.56 6.11 +641 100 10 85 0 50.05 -34.58 3.95 +642 100 20 85 0 47.70 -29.08 2.00 +643 100 30 85 0 45.51 -23.90 0.20 +644 100 40 85 0 43.45 -19.00 -1.45 +645 100 55 85 0 41.03 -13.21 -3.15 +646 100 70 85 0 38.67 -7.52 -4.74 +647 100 85 85 0 36.53 -2.33 -6.13 +648 100 100 85 0 35.04 1.31 -7.04 +649 0 0 100 0 87.66 -2.65 72.38 +650 0 10 100 0 82.06 5.78 64.76 +651 0 20 100 0 77.06 13.65 57.96 +652 0 30 100 0 72.52 21.10 51.81 +653 0 40 100 0 68.39 28.16 46.22 +654 0 55 100 0 63.50 36.57 39.70 +655 0 70 100 0 58.97 44.55 33.74 +656 0 85 100 0 55.11 51.44 28.74 +657 0 100 100 0 52.59 55.96 25.52 +658 10 0 100 0 82.52 -8.27 63.50 +659 10 10 100 0 77.33 -0.31 56.64 +660 10 20 100 0 72.69 7.12 50.49 +661 10 30 100 0 68.45 14.16 44.88 +662 10 40 100 0 64.56 20.85 39.76 +663 10 55 100 0 59.92 28.98 33.72 +664 10 70 100 0 55.59 36.78 28.13 +665 10 85 100 0 51.85 43.59 23.41 +666 10 100 100 0 49.39 48.11 20.33 +667 20 0 100 0 77.88 -13.51 55.48 +668 20 10 100 0 73.07 -5.97 49.29 +669 20 20 100 0 68.75 1.07 43.73 +670 20 30 100 0 64.80 7.74 38.65 +671 20 40 100 0 61.14 14.10 33.97 +672 20 55 100 0 56.74 21.96 28.38 +673 20 70 100 0 52.59 29.56 23.18 +674 20 85 100 0 48.98 36.27 18.73 +675 20 100 100 0 46.58 40.78 15.80 +676 30 0 100 0 73.60 -18.50 48.07 +677 30 10 100 0 69.16 -11.32 42.52 +678 30 20 100 0 65.14 -4.63 37.52 +679 30 30 100 0 61.44 1.71 32.93 +680 30 40 100 0 58.01 7.75 28.68 +681 30 55 100 0 53.84 15.36 23.55 +682 30 70 100 0 49.88 22.76 18.72 +683 30 85 100 0 46.41 29.34 14.55 +684 30 100 100 0 44.07 33.81 11.79 +685 40 0 100 0 69.63 -23.27 41.16 +686 40 10 100 0 65.52 -16.42 36.22 +687 40 20 100 0 61.79 -10.04 31.75 +688 40 30 100 0 58.34 -4.01 27.62 +689 40 40 100 0 55.13 1.74 23.81 +690 40 55 100 0 51.19 9.11 19.10 +691 40 70 100 0 47.42 16.29 14.66 +692 40 85 100 0 44.08 22.75 10.78 +693 40 100 100 0 41.82 27.15 8.20 +694 55 0 100 0 64.40 -28.54 32.33 +695 55 10 100 0 60.75 -21.95 28.12 +696 55 20 100 0 57.43 -15.83 24.31 +697 55 30 100 0 54.36 -10.05 20.78 +698 55 40 100 0 51.48 -4.54 17.49 +699 55 55 100 0 47.98 2.39 13.54 +700 55 70 100 0 44.61 9.17 9.78 +701 55 85 100 0 41.59 15.33 6.47 +702 55 100 100 0 39.53 19.57 4.25 +703 70 0 100 0 59.40 -33.69 23.86 +704 70 10 100 0 56.19 -27.34 20.36 +705 70 20 100 0 53.27 -21.45 17.17 +706 70 30 100 0 50.55 -15.90 14.21 +707 70 40 100 0 48.01 -10.62 11.47 +708 70 55 100 0 44.95 -4.14 8.27 +709 70 70 100 0 41.97 2.22 5.20 +710 70 85 100 0 39.30 8.03 2.50 +711 70 100 100 0 37.45 12.07 0.66 +712 85 0 100 0 54.97 -38.30 16.35 +713 85 10 100 0 52.15 -32.15 13.46 +714 85 20 100 0 49.58 -26.46 10.83 +715 85 30 100 0 47.19 -21.10 8.40 +716 85 40 100 0 44.94 -16.01 6.12 +717 85 55 100 0 42.28 -9.96 3.63 +718 85 70 100 0 39.69 -4.00 1.22 +719 85 85 100 0 37.35 1.45 -0.90 +720 85 100 100 0 35.72 5.26 -2.34 +721 100 0 100 0 51.97 -41.41 11.25 +722 100 10 100 0 49.41 -35.38 8.77 +723 100 20 100 0 47.07 -29.82 6.51 +724 100 30 100 0 44.90 -24.59 4.44 +725 100 40 100 0 42.86 -19.64 2.49 +726 100 55 100 0 40.49 -13.89 0.49 +727 100 70 100 0 38.17 -8.23 -1.42 +728 100 85 100 0 36.08 -3.04 -3.11 +729 100 100 100 0 34.61 0.58 -4.25 +730 0 0 0 20 79.36 2.03 -8.10 +731 0 10 0 20 74.95 7.78 -8.31 +732 0 20 0 20 70.96 13.13 -8.35 +733 0 40 0 20 63.82 22.99 -7.97 +734 0 70 0 20 54.68 36.65 -6.96 +735 0 100 0 20 48.15 46.40 -4.82 +736 10 0 0 20 75.61 -0.90 -11.96 +737 10 10 0 20 71.48 4.53 -12.03 +738 10 20 0 20 67.73 9.57 -11.96 +739 10 40 0 20 60.99 18.87 -11.45 +740 10 70 0 20 52.36 31.76 -10.17 +741 10 100 0 20 46.12 41.09 -8.02 +742 20 0 0 20 72.20 -3.57 -15.43 +743 20 10 0 20 68.31 1.57 -15.37 +744 20 20 0 20 64.78 6.33 -15.20 +745 20 40 0 20 58.42 15.11 -14.56 +746 20 70 0 20 50.28 27.27 -13.02 +747 20 100 0 20 44.31 36.19 -10.83 +748 40 0 0 20 66.02 -8.34 -21.55 +749 40 10 0 20 62.60 -3.73 -21.26 +750 40 20 0 20 59.48 0.54 -20.92 +751 40 40 0 20 53.82 8.39 -20.06 +752 40 70 0 20 46.61 19.16 -17.97 +753 40 100 0 20 41.22 27.19 -15.62 +754 70 0 0 20 57.80 -14.52 -30.30 +755 70 10 0 20 55.00 -10.44 -29.37 +756 70 20 0 20 52.44 -6.68 -28.45 +757 70 40 0 20 47.78 0.22 -26.59 +758 70 70 0 20 42.21 9.42 -23.89 +759 70 100 0 20 37.99 16.42 -21.28 +760 100 0 0 20 51.73 -18.65 -36.40 +761 100 10 0 20 49.38 -15.03 -35.04 +762 100 20 0 20 47.23 -11.69 -33.73 +763 100 40 0 20 43.30 -5.57 -31.16 +764 100 70 0 20 39.05 2.29 -28.00 +765 100 100 0 20 35.81 8.33 -25.10 +766 0 0 10 20 78.61 0.63 0.22 +767 0 10 10 20 74.20 6.53 -0.75 +768 0 20 10 20 70.22 12.00 -1.49 +769 0 40 10 20 63.10 22.10 -2.40 +770 0 70 10 20 54.20 35.88 -2.90 +771 0 100 10 20 47.85 45.74 -1.97 +772 10 0 10 20 74.81 -2.45 -3.96 +773 10 10 10 20 70.71 3.13 -4.73 +774 10 20 10 20 66.99 8.30 -5.31 +775 10 40 10 20 60.32 17.85 -5.99 +776 10 70 10 20 51.92 30.89 -6.17 +777 10 100 10 20 45.84 40.35 -5.20 +778 20 0 10 20 71.36 -5.26 -7.72 +779 20 10 10 20 67.54 0.03 -8.31 +780 20 20 10 20 64.06 4.94 -8.74 +781 20 40 10 20 57.80 13.98 -9.21 +782 20 70 10 20 49.87 26.30 -9.08 +783 20 100 10 20 44.07 35.35 -8.04 +784 40 0 10 20 65.13 -10.34 -14.38 +785 40 10 10 20 61.81 -5.55 -14.65 +786 40 20 10 20 58.77 -1.13 -14.81 +787 40 40 10 20 53.28 7.01 -14.88 +788 40 70 10 20 46.27 17.96 -14.14 +789 40 100 10 20 41.03 26.15 -12.88 +790 70 0 10 20 57.01 -16.78 -23.58 +791 70 10 10 20 54.30 -12.51 -23.19 +792 70 20 10 20 51.82 -8.57 -22.76 +793 70 40 10 20 47.31 -1.32 -21.81 +794 70 70 10 20 41.84 8.15 -20.23 +795 70 100 10 20 37.68 15.37 -18.52 +796 100 0 10 20 51.02 -21.19 -30.07 +797 100 10 10 20 48.75 -17.33 -29.23 +798 100 20 10 20 46.67 -13.78 -28.39 +799 100 40 10 20 42.89 -7.28 -26.72 +800 100 70 10 20 38.65 0.95 -24.49 +801 100 100 10 20 35.42 7.26 -22.34 +802 0 0 20 20 77.93 -0.47 7.88 +803 0 10 20 20 73.52 5.52 6.20 +804 0 20 20 20 69.54 11.09 4.82 +805 0 40 20 20 62.44 21.36 2.73 +806 0 70 20 20 53.76 35.22 0.86 +807 0 100 20 20 47.57 45.16 0.68 +808 10 0 20 20 74.09 -3.70 3.40 +809 10 10 20 20 70.02 1.99 1.99 +810 10 20 20 20 66.32 7.27 0.82 +811 10 40 20 20 59.71 17.00 -0.95 +812 10 70 20 20 51.51 30.13 -2.48 +813 10 100 20 20 45.59 39.68 -2.59 +814 20 0 20 20 70.60 -6.65 -0.63 +815 20 10 20 20 66.83 -1.24 -1.81 +816 20 20 20 20 63.40 3.77 -2.79 +817 20 40 20 20 57.23 13.02 -4.26 +818 20 70 20 20 49.50 25.44 -5.44 +819 20 100 20 20 43.84 34.59 -5.46 +820 40 0 20 20 64.32 -12.01 -7.77 +821 40 10 20 20 61.08 -7.09 -8.54 +822 40 20 20 20 58.13 -2.54 -9.17 +823 40 40 20 20 52.79 5.84 -10.10 +824 40 70 20 20 45.97 16.91 -10.59 +825 40 100 20 20 40.85 25.21 -10.33 +826 70 0 20 20 56.30 -18.70 -17.39 +827 70 10 20 20 53.67 -14.26 -17.48 +828 70 20 20 20 51.26 -10.17 -17.51 +829 70 40 20 20 46.88 -2.65 -17.40 +830 70 70 20 20 41.50 7.04 -16.83 +831 70 100 20 20 37.41 14.43 -15.96 +832 100 0 20 20 50.38 -23.36 -24.22 +833 100 10 20 20 48.18 -19.31 -23.85 +834 100 20 20 20 46.17 -15.59 -23.46 +835 100 40 20 20 42.51 -8.76 -22.59 +836 100 70 20 20 38.28 -0.23 -21.22 +837 100 100 20 20 35.05 6.31 -19.78 +838 0 0 40 20 76.72 -2.07 21.88 +839 0 10 40 20 72.31 4.05 18.94 +840 0 20 40 20 68.32 9.74 16.39 +841 0 40 40 20 61.23 20.23 12.16 +842 0 70 40 20 52.94 34.12 7.79 +843 0 100 40 20 47.06 44.14 5.58 +844 10 0 40 20 72.81 -5.56 16.87 +845 10 10 40 20 68.78 0.27 14.29 +846 10 20 40 20 65.12 5.69 12.05 +847 10 40 40 20 58.59 15.68 8.31 +848 10 70 40 20 50.77 28.85 4.35 +849 10 100 40 20 45.11 38.50 2.25 +850 20 0 40 20 69.26 -8.78 12.35 +851 20 10 40 20 65.56 -3.20 10.10 +852 20 20 40 20 62.21 1.96 8.14 +853 20 40 40 20 56.19 11.51 4.85 +854 20 70 40 20 48.82 23.99 1.29 +855 20 100 40 20 43.41 33.25 -0.67 +856 40 0 40 20 62.86 -14.67 4.32 +857 40 10 40 20 59.79 -9.55 2.65 +858 40 20 40 20 56.98 -4.80 1.18 +859 40 40 40 20 51.90 3.93 -1.30 +860 40 70 40 20 45.41 15.11 -4.03 +861 40 100 40 20 40.53 23.55 -5.62 +862 70 0 40 20 55.04 -21.77 -6.01 +863 70 10 40 20 52.55 -17.10 -6.98 +864 70 20 40 20 50.26 -12.78 -7.84 +865 70 40 40 20 46.12 -4.86 -9.23 +866 70 70 40 20 40.89 5.14 -10.55 +867 70 100 40 20 36.90 12.75 -11.20 +868 100 0 40 20 49.25 -26.89 -13.46 +869 100 10 40 20 47.18 -22.55 -13.95 +870 100 20 40 20 45.29 -18.56 -14.36 +871 100 40 40 20 41.84 -11.25 -14.98 +872 100 70 40 20 37.61 -2.24 -15.17 +873 100 100 40 20 34.37 4.65 -15.02 +874 0 0 70 20 74.77 -3.06 40.37 +875 0 10 70 20 70.51 3.15 35.90 +876 0 20 70 20 66.66 8.94 31.92 +877 0 40 70 20 59.85 19.65 25.08 +878 0 70 70 20 52.01 32.82 17.49 +879 0 100 70 20 46.41 42.41 12.57 +880 10 0 70 20 70.92 -6.83 34.43 +881 10 10 70 20 66.99 -0.93 30.43 +882 10 20 70 20 63.44 4.57 26.87 +883 10 40 70 20 57.12 14.75 20.71 +884 10 70 70 20 49.72 27.43 13.77 +885 10 100 70 20 44.36 36.79 9.18 +886 20 0 70 20 67.42 -10.33 29.04 +887 20 10 70 20 63.80 -4.69 25.49 +888 20 20 70 20 60.53 0.55 22.30 +889 20 40 70 20 54.66 10.25 16.76 +890 20 70 70 20 47.67 22.45 10.45 +891 20 100 70 20 42.54 31.57 6.20 +892 40 0 70 20 61.14 -16.75 19.42 +893 40 10 70 20 58.08 -11.59 16.64 +894 40 20 70 20 55.29 -6.80 14.14 +895 40 40 70 20 50.26 2.04 9.75 +896 40 70 70 20 44.07 13.33 4.65 +897 40 100 70 20 39.44 21.90 1.13 +898 70 0 70 20 53.36 -24.18 7.46 +899 70 10 70 20 50.92 -19.43 5.59 +900 70 20 70 20 48.68 -15.03 3.91 +901 70 40 70 20 44.62 -6.96 0.94 +902 70 70 70 20 39.75 3.10 -2.24 +903 70 100 70 20 36.03 10.86 -4.43 +904 100 0 70 20 47.61 -29.64 -1.32 +905 100 10 70 20 45.61 -25.18 -2.54 +906 100 20 70 20 43.77 -21.08 -3.63 +907 100 40 70 20 40.45 -13.56 -5.53 +908 100 70 70 20 36.62 -4.51 -7.18 +909 100 100 70 20 33.68 2.47 -8.23 +910 0 0 100 20 73.29 -3.19 54.36 +911 0 10 100 20 69.13 3.02 48.81 +912 0 20 100 20 65.39 8.82 43.84 +913 0 40 100 20 58.78 19.57 35.09 +914 0 70 100 20 51.28 31.99 25.11 +915 0 100 100 20 45.90 41.12 18.09 +916 10 0 100 20 69.48 -7.20 47.79 +917 10 10 100 20 65.63 -1.31 42.78 +918 10 20 100 20 62.15 4.20 38.28 +919 10 40 100 20 55.99 14.40 30.33 +920 10 70 100 20 48.89 26.53 21.16 +921 10 100 100 20 43.75 35.54 14.67 +922 20 0 100 20 66.02 -10.92 41.81 +923 20 10 100 20 62.46 -5.31 37.31 +924 20 20 100 20 59.22 -0.07 33.24 +925 20 40 100 20 53.46 9.63 26.03 +926 20 70 100 20 46.76 21.46 17.64 +927 20 100 100 20 41.85 30.35 11.64 +928 40 0 100 20 59.83 -17.80 31.04 +929 40 10 100 20 56.77 -12.67 27.46 +930 40 20 100 20 53.99 -7.90 24.20 +931 40 40 100 20 48.98 0.92 18.37 +932 40 70 100 20 43.01 12.17 11.48 +933 40 100 100 20 38.56 20.76 6.46 +934 70 0 100 20 52.08 -25.47 17.93 +935 70 10 100 20 49.67 -20.72 15.39 +936 70 20 100 20 47.46 -16.32 13.08 +937 70 40 100 20 43.45 -8.23 8.93 +938 70 70 100 20 38.84 1.77 4.32 +939 70 100 100 20 35.34 9.53 0.93 +940 100 0 100 20 46.35 -31.21 8.19 +941 100 10 100 20 44.39 -26.72 6.41 +942 100 20 100 20 42.61 -22.59 4.81 +943 100 40 100 20 39.36 -15.00 1.93 +944 100 70 100 20 35.84 -6.03 -0.84 +945 100 100 100 20 33.14 0.95 -2.83 +946 0 0 0 40 66.75 1.60 -6.39 +947 0 20 0 40 60.42 9.67 -6.27 +948 0 40 0 40 54.96 16.86 -5.81 +949 0 70 0 40 47.98 26.68 -5.51 +950 0 100 0 40 42.76 33.96 -4.58 +951 20 0 0 40 61.38 -2.76 -11.01 +952 20 20 0 40 55.83 4.59 -10.77 +953 20 40 0 40 51.02 11.11 -10.30 +954 20 70 0 40 44.81 20.17 -9.61 +955 20 100 0 40 40.13 26.98 -8.53 +956 40 0 0 40 56.70 -6.57 -14.89 +957 40 20 0 40 51.84 0.17 -14.57 +958 40 40 0 40 47.61 6.13 -14.09 +959 40 70 0 40 42.12 14.49 -13.05 +960 40 100 0 40 37.93 20.83 -11.79 +961 70 0 0 40 50.38 -11.37 -21.24 +962 70 20 0 40 46.34 -5.23 -20.05 +963 70 40 0 40 42.81 0.16 -18.84 +964 70 70 0 40 38.57 7.48 -17.40 +965 70 100 0 40 35.31 13.10 -15.93 +966 100 0 0 40 45.61 -14.85 -25.81 +967 100 20 0 40 42.17 -9.20 -24.02 +968 100 40 0 40 39.16 -4.24 -22.28 +969 100 70 0 40 35.92 2.20 -20.53 +970 100 100 0 40 33.42 7.19 -18.88 +971 0 0 20 40 65.47 -0.48 5.38 +972 0 20 20 40 59.08 7.86 3.36 +973 0 40 20 40 53.58 15.25 1.93 +974 0 70 20 40 47.06 25.24 0.26 +975 0 100 20 40 42.20 32.70 -0.40 +976 20 0 20 40 60.00 -4.95 -0.33 +977 20 20 20 40 54.63 2.66 -1.83 +978 20 40 20 40 49.97 9.41 -2.90 +979 20 70 20 40 44.06 18.55 -4.01 +980 20 100 20 40 39.59 25.46 -4.39 +981 40 0 20 40 55.25 -8.86 -5.17 +982 40 20 20 40 50.76 -1.87 -6.25 +983 40 40 20 40 46.86 4.31 -7.01 +984 40 70 20 40 41.52 12.67 -7.58 +985 40 100 20 40 37.43 19.04 -7.65 +986 70 0 20 40 49.12 -13.93 -12.19 +987 70 20 20 40 45.39 -7.47 -12.37 +988 70 40 20 40 42.12 -1.78 -12.39 +989 70 70 20 40 37.93 5.67 -12.20 +990 70 100 20 40 34.69 11.41 -11.77 +991 100 0 20 40 44.49 -17.65 -17.31 +992 100 20 20 40 41.30 -11.61 -16.87 +993 100 40 20 40 38.53 -6.30 -16.34 +994 100 70 20 40 35.24 0.42 -15.56 +995 100 100 20 40 32.70 5.62 -14.72 +996 0 0 40 40 64.36 -1.94 15.73 +997 0 20 40 40 57.90 6.51 11.84 +998 0 40 40 40 52.36 14.01 8.75 +999 0 70 40 40 46.24 24.06 5.38 +1000 0 100 40 40 41.70 31.63 3.33 +1001 20 0 40 40 58.80 -6.53 9.08 +1002 20 20 40 40 53.58 1.20 6.07 +1003 20 40 40 40 49.05 8.07 3.65 +1004 20 70 40 40 43.39 17.20 0.98 +1005 20 100 40 40 39.11 24.15 -0.68 +1006 40 0 40 40 53.99 -10.57 3.41 +1007 40 20 40 40 49.82 -3.45 1.14 +1008 40 40 40 40 46.20 2.87 -0.72 +1009 40 70 40 40 40.99 11.16 -2.71 +1010 40 100 40 40 36.98 17.51 -3.96 +1011 70 0 40 40 48.02 -15.86 -4.18 +1012 70 20 40 40 44.55 -9.21 -5.56 +1013 70 40 40 40 41.52 -3.34 -6.65 +1014 70 70 40 40 37.36 4.18 -7.57 +1015 70 100 40 40 34.13 9.98 -8.06 +1016 100 0 40 40 43.51 -19.79 -9.78 +1017 100 20 40 40 40.55 -13.50 -10.51 +1018 100 40 40 40 37.97 -7.97 -11.04 +1019 100 70 40 40 34.64 -1.06 -11.13 +1020 100 100 40 40 32.05 4.27 -10.99 +1021 0 0 70 40 62.23 -3.04 28.54 +1022 0 20 70 40 56.29 5.38 22.83 +1023 0 40 70 40 51.20 12.89 18.08 +1024 0 70 70 40 45.35 22.29 12.39 +1025 0 100 70 40 40.98 29.42 8.38 +1026 20 0 70 40 56.93 -7.84 20.64 +1027 20 20 70 40 51.97 -0.15 16.08 +1028 20 40 70 40 47.68 6.72 12.26 +1029 20 70 70 40 42.41 15.57 7.65 +1030 20 100 70 40 38.41 22.37 4.38 +1031 40 0 70 40 52.35 -12.07 13.84 +1032 40 20 70 40 48.24 -4.98 10.27 +1033 40 40 70 40 44.66 1.32 7.26 +1034 40 70 70 40 39.91 9.65 3.65 +1035 40 100 70 40 36.28 16.10 1.08 +1036 70 0 70 40 46.63 -17.38 5.25 +1037 70 20 70 40 43.25 -10.82 2.83 +1038 70 40 70 40 40.30 -5.01 0.79 +1039 70 70 70 40 36.60 2.53 -1.37 +1040 70 100 70 40 33.74 8.40 -2.89 +1041 100 0 70 40 42.31 -21.38 -1.20 +1042 100 20 70 40 39.47 -15.19 -2.77 +1043 100 40 70 40 36.99 -9.75 -4.05 +1044 100 70 70 40 34.12 -2.84 -5.09 +1045 100 100 70 40 31.91 2.53 -5.72 +1046 0 0 100 40 60.56 -3.52 38.39 +1047 0 20 100 40 55.02 4.78 31.35 +1048 0 40 100 40 50.29 12.24 25.39 +1049 0 70 100 40 44.65 21.00 17.93 +1050 0 100 100 40 40.40 27.71 12.38 +1051 20 0 100 40 55.47 -8.52 29.61 +1052 20 20 100 40 50.71 -0.93 23.89 +1053 20 40 100 40 46.60 5.87 19.01 +1054 20 70 100 40 41.63 14.40 12.94 +1055 20 100 100 40 37.85 21.01 8.41 +1056 40 0 100 40 51.06 -12.93 22.00 +1057 40 20 100 40 46.98 -5.93 17.43 +1058 40 40 100 40 43.43 0.30 13.52 +1059 40 70 100 40 39.05 8.59 8.70 +1060 40 100 100 40 35.71 15.06 5.10 +1061 70 0 100 40 45.55 -18.28 12.67 +1062 70 20 100 40 42.23 -11.83 9.44 +1063 70 40 100 40 39.33 -6.12 6.68 +1064 70 70 100 40 36.00 1.38 3.57 +1065 70 100 100 40 33.43 7.26 1.25 +1066 100 0 100 40 41.38 -22.32 5.60 +1067 100 20 100 40 38.63 -16.27 3.38 +1068 100 40 100 40 36.21 -10.94 1.50 +1069 100 70 100 40 33.72 -4.11 -0.24 +1070 100 100 100 40 31.80 1.25 -1.49 +1071 0 0 0 60 54.52 1.49 -4.08 +1072 0 20 0 60 50.60 7.24 -3.86 +1073 0 40 0 60 47.18 12.39 -3.47 +1074 0 70 0 60 42.00 19.32 -3.15 +1075 0 100 0 60 38.02 24.59 -2.51 +1076 20 0 0 60 50.85 -1.53 -7.37 +1077 20 20 0 60 47.25 3.71 -7.07 +1078 20 40 0 60 44.10 8.38 -6.65 +1079 20 70 0 60 39.68 14.80 -5.95 +1080 20 100 0 60 36.25 19.73 -5.10 +1081 40 0 0 60 47.62 -4.19 -10.19 +1082 40 20 0 60 44.31 0.61 -9.82 +1083 40 40 0 60 41.41 4.88 -9.36 +1084 40 70 0 60 37.66 10.82 -8.34 +1085 40 100 0 60 34.75 15.43 -7.28 +1086 70 0 0 60 43.30 -7.63 -14.70 +1087 70 20 0 60 40.52 -3.23 -13.73 +1088 70 40 0 60 38.07 0.66 -12.77 +1089 70 70 0 60 35.16 5.91 -11.45 +1090 70 100 0 60 32.88 10.02 -10.20 +1091 100 0 0 60 39.97 -10.24 -18.06 +1092 100 20 0 60 37.58 -6.16 -16.67 +1093 100 40 0 60 35.49 -2.56 -15.34 +1094 100 70 0 60 33.24 2.14 -13.78 +1095 100 100 0 60 31.49 5.81 -12.36 +1096 0 0 20 60 53.78 -0.05 3.94 +1097 0 20 20 60 49.60 5.81 2.72 +1098 0 40 20 60 45.96 11.05 1.82 +1099 0 70 20 60 41.37 18.15 0.80 +1100 0 100 20 60 37.85 23.63 0.32 +1101 20 0 20 60 50.07 -3.14 -0.02 +1102 20 20 20 60 46.46 2.25 -0.90 +1103 20 40 20 60 43.31 7.05 -1.55 +1104 20 70 20 60 39.17 13.56 -2.11 +1105 20 100 20 60 35.97 18.58 -2.29 +1106 40 0 20 60 46.81 -5.86 -3.43 +1107 40 20 20 60 43.71 -0.87 -4.03 +1108 40 40 20 60 40.99 3.56 -4.45 +1109 40 70 20 60 37.27 9.49 -4.59 +1110 40 100 20 60 34.37 14.12 -4.49 +1111 70 0 20 60 42.46 -9.38 -8.40 +1112 70 20 20 60 39.90 -4.78 -8.38 +1113 70 40 20 60 37.65 -0.70 -8.27 +1114 70 70 20 60 34.72 4.62 -7.87 +1115 70 100 20 60 32.41 8.78 -7.38 +1116 100 0 20 60 39.10 -12.05 -12.15 +1117 100 20 20 60 36.96 -7.75 -11.68 +1118 100 40 20 60 35.07 -3.95 -11.17 +1119 100 70 20 60 32.76 0.88 -10.34 +1120 100 100 20 60 30.94 4.66 -9.53 +1121 0 0 40 60 53.14 -1.23 11.06 +1122 0 20 40 60 48.72 4.68 8.55 +1123 0 40 40 60 44.86 9.94 6.51 +1124 0 70 40 60 40.81 17.16 4.32 +1125 0 100 40 60 37.70 22.77 2.87 +1126 20 0 40 60 49.39 -4.39 6.51 +1127 20 20 40 60 45.77 1.09 4.58 +1128 20 40 40 60 42.59 5.97 3.00 +1129 20 70 40 60 38.72 12.48 1.33 +1130 20 100 40 60 35.72 17.56 0.23 +1131 40 0 40 60 46.10 -7.18 2.58 +1132 40 20 40 60 43.18 -2.08 1.13 +1133 40 40 40 60 40.62 2.47 -0.05 +1134 40 70 40 60 36.93 8.36 -1.23 +1135 40 100 40 60 34.03 12.96 -1.99 +1136 70 0 40 60 41.72 -10.76 -2.81 +1137 70 20 40 60 39.36 -6.02 -3.61 +1138 70 40 40 60 37.29 -1.83 -4.24 +1139 70 70 40 60 34.32 3.52 -4.66 +1140 70 100 40 60 31.99 7.70 -4.85 +1141 100 0 40 60 38.33 -13.49 -6.88 +1142 100 20 40 60 36.40 -9.04 -7.21 +1143 100 40 40 60 34.71 -5.10 -7.42 +1144 100 70 40 60 32.32 -0.20 -7.26 +1145 100 100 40 60 30.45 3.64 -6.99 +1146 0 0 70 60 51.70 -2.29 19.92 +1147 0 20 70 60 47.66 3.61 16.19 +1148 0 40 70 60 44.15 8.91 13.06 +1149 0 70 70 60 39.95 15.64 9.18 +1150 0 100 70 60 36.71 20.89 6.33 +1151 20 0 70 60 48.05 -5.53 14.50 +1152 20 20 70 60 44.63 -0.09 11.56 +1153 20 40 70 60 41.64 4.77 9.05 +1154 20 70 70 60 37.85 11.09 5.96 +1155 20 100 70 60 34.91 16.04 3.68 +1156 40 0 70 60 44.85 -8.38 9.78 +1157 40 20 70 60 41.98 -3.35 7.51 +1158 40 40 70 60 39.45 1.14 5.57 +1159 40 70 70 60 36.04 7.08 3.19 +1160 40 100 70 60 33.38 11.74 1.43 +1161 70 0 70 60 40.76 -11.97 3.82 +1162 70 20 70 60 38.43 -7.32 2.30 +1163 70 40 70 60 36.38 -3.18 1.02 +1164 70 70 70 60 33.67 2.21 -0.37 +1165 70 100 70 60 31.54 6.44 -1.34 +1166 100 0 70 60 37.61 -14.72 -0.75 +1167 100 20 70 60 35.69 -10.34 -1.70 +1168 100 40 70 60 34.00 -6.46 -2.48 +1169 100 70 70 60 31.85 -1.54 -3.05 +1170 100 100 70 60 30.15 2.35 -3.41 +1171 0 0 100 60 50.56 -2.90 26.86 +1172 0 20 100 60 46.82 2.94 22.22 +1173 0 40 100 60 43.58 8.21 18.25 +1174 0 70 100 60 39.26 14.50 13.05 +1175 0 100 100 60 35.91 19.39 9.09 +1176 20 0 100 60 46.98 -6.23 20.79 +1177 20 20 100 60 43.72 -0.88 17.06 +1178 20 40 100 60 40.87 3.93 13.86 +1179 20 70 100 60 37.15 10.04 9.65 +1180 20 100 100 60 34.26 14.83 6.43 +1181 40 0 100 60 43.85 -9.17 15.49 +1182 40 20 100 60 41.01 -4.24 12.56 +1183 40 40 100 60 38.51 0.18 10.03 +1184 40 70 100 60 35.33 6.11 6.71 +1185 40 100 100 60 32.85 10.80 4.17 +1186 70 0 100 60 40.01 -12.77 9.09 +1187 70 20 100 60 37.69 -8.20 7.00 +1188 70 40 100 60 35.65 -4.15 5.21 +1189 70 70 100 60 33.14 1.23 3.08 +1190 70 100 100 60 31.17 5.48 1.47 +1191 100 0 100 60 37.05 -15.55 4.15 +1192 100 20 100 60 35.13 -11.26 2.72 +1193 100 40 100 60 33.44 -7.46 1.49 +1194 100 70 100 60 31.47 -2.53 0.32 +1195 100 100 100 60 29.92 1.36 -0.52 +1196 0 0 0 80 42.14 1.38 -1.76 +1197 0 40 0 80 39.20 7.94 -1.09 +1198 0 70 0 80 35.92 11.91 -0.55 +1199 0 100 0 80 33.33 15.01 -0.01 +1200 40 0 0 80 38.37 -1.82 -5.43 +1201 40 40 0 80 35.03 3.64 -4.55 +1202 40 70 0 80 33.06 7.15 -3.49 +1203 40 100 0 80 31.52 9.93 -2.54 +1204 70 0 0 80 36.11 -3.79 -7.95 +1205 70 40 0 80 33.21 1.25 -6.53 +1206 70 70 0 80 31.62 4.44 -5.33 +1207 70 100 0 80 30.37 6.98 -4.26 +1208 100 0 0 80 34.33 -5.37 -9.91 +1209 100 40 0 80 31.76 -0.65 -8.07 +1210 100 70 0 80 30.49 2.29 -6.75 +1211 100 100 0 80 29.49 4.62 -5.58 +1212 0 0 40 80 41.75 -0.52 6.46 +1213 0 40 40 80 37.20 5.94 4.35 +1214 0 70 40 80 35.29 10.23 3.46 +1215 0 100 40 80 33.79 13.68 2.84 +1216 40 0 40 80 38.03 -3.84 1.81 +1217 40 40 40 80 34.84 2.05 0.69 +1218 40 70 40 80 32.71 5.54 0.36 +1219 40 100 40 80 31.02 8.31 0.19 +1220 70 0 40 80 35.27 -5.73 -1.27 +1221 70 40 40 80 32.90 -0.32 -1.70 +1222 70 70 40 80 31.16 2.85 -1.63 +1223 70 100 40 80 29.76 5.37 -1.49 +1224 100 0 40 80 33.09 -7.21 -3.66 +1225 100 40 40 80 31.37 -2.19 -3.56 +1226 100 70 40 80 29.93 0.74 -3.18 +1227 100 100 40 80 28.78 3.06 -2.80 +1228 0 0 70 80 41.00 -1.42 11.31 +1229 0 40 70 80 36.93 5.04 8.07 +1230 0 70 70 80 34.47 9.01 6.15 +1231 0 100 70 80 32.52 12.21 4.67 +1232 40 0 70 80 37.15 -4.71 5.72 +1233 40 40 70 80 34.05 0.97 3.88 +1234 40 70 70 80 32.03 4.49 2.78 +1235 40 100 70 80 30.42 7.29 1.95 +1236 70 0 70 80 34.75 -6.63 2.48 +1237 70 40 70 80 32.31 -1.37 1.31 +1238 70 70 70 80 30.61 1.86 0.72 +1239 70 100 70 80 29.24 4.44 0.31 +1240 100 0 70 80 32.84 -8.14 -0.07 +1241 100 40 70 80 30.93 -3.19 -0.73 +1242 100 70 70 80 29.48 -0.22 -0.89 +1243 100 100 70 80 28.32 2.16 -0.96 +1244 0 0 100 80 40.40 -2.08 15.17 +1245 0 40 100 80 36.72 4.36 11.06 +1246 0 70 100 80 33.81 8.06 8.30 +1247 0 100 100 80 31.49 11.01 6.15 +1248 40 0 100 80 36.45 -5.36 8.88 +1249 40 40 100 80 33.41 0.13 6.45 +1250 40 70 100 80 31.48 3.65 4.74 +1251 40 100 100 80 29.93 6.48 3.38 +1252 70 0 100 80 34.33 -7.31 5.50 +1253 70 40 100 80 31.83 -2.17 3.72 +1254 70 70 100 80 30.16 1.07 2.62 +1255 70 100 100 80 28.81 3.66 1.76 +1256 100 0 100 80 32.64 -8.84 2.85 +1257 100 40 100 80 30.57 -3.98 1.56 +1258 100 70 100 80 29.11 -0.97 0.96 +1259 100 100 100 80 27.93 1.44 0.49 +1260 0 0 0 100 32.69 1.24 0.11 +1261 0 40 0 100 33.02 4.60 0.85 +1262 0 100 0 100 29.84 7.72 2.31 +1263 40 0 0 100 31.27 -0.08 -1.70 +1264 40 40 0 100 30.06 2.72 -0.80 +1265 40 100 0 100 29.01 5.74 1.26 +1266 100 0 0 100 30.08 -1.53 -3.38 +1267 100 40 0 100 28.90 0.97 -2.30 +1268 100 100 0 100 27.93 3.85 -0.23 +1269 0 0 40 100 33.03 0.02 3.17 +1270 0 40 40 100 31.27 2.99 2.86 +1271 0 100 40 100 30.91 6.74 3.22 +1272 40 0 40 100 31.77 -1.40 1.34 +1273 40 40 40 100 30.32 1.70 1.32 +1274 40 100 40 100 28.67 4.75 2.00 +1275 100 0 40 100 29.11 -2.55 -0.93 +1276 100 40 40 100 28.78 0.03 -0.42 +1277 100 100 40 100 27.46 2.65 0.55 +1278 0 0 100 100 32.62 -1.23 6.32 +1279 0 40 100 100 31.43 1.66 5.61 +1280 0 100 100 100 28.21 4.77 4.26 +1281 40 0 100 100 30.73 -2.44 3.83 +1282 40 40 100 100 29.42 0.14 3.72 +1283 40 100 100 100 27.68 3.22 2.91 +1284 100 0 100 100 29.26 -3.87 1.98 +1285 100 40 100 100 28.33 -1.37 1.71 +1286 100 100 100 100 26.36 1.50 1.35 +1287 100 0 0 0 58.70 -22.35 -48.12 +1288 98 0 0 0 59.01 -22.19 -47.82 +1289 95 0 0 0 59.47 -21.94 -47.37 +1290 90 0 0 0 60.41 -21.42 -46.43 +1291 85 0 0 0 61.71 -20.66 -45.11 +1292 80 0 0 0 63.03 -19.85 -43.73 +1293 75 0 0 0 64.56 -18.87 -42.12 +1294 70 0 0 0 66.13 -17.82 -40.45 +1295 60 0 0 0 69.47 -15.49 -36.84 +1296 50 0 0 0 72.89 -12.97 -33.07 +1297 40 0 0 0 76.45 -10.28 -29.09 +1298 30 0 0 0 80.24 -7.50 -24.94 +1299 25 0 0 0 82.25 -6.00 -22.71 +1300 20 0 0 0 84.29 -4.47 -20.44 +1301 15 0 0 0 86.46 -2.83 -18.00 +1302 10 0 0 0 88.67 -1.16 -15.51 +1303 7 0 0 0 90.11 -0.07 -13.87 +1304 5 0 0 0 91.08 0.66 -12.77 +1305 3 0 0 0 92.04 1.39 -11.67 +1306 2 0 0 0 92.53 1.76 -11.12 +1307 0 100 0 0 54.54 60.07 -4.30 +1308 0 98 0 0 54.84 59.61 -4.52 +1309 0 95 0 0 55.31 58.89 -4.85 +1310 0 90 0 0 56.27 57.40 -5.47 +1311 0 85 0 0 57.60 55.31 -6.22 +1312 0 80 0 0 58.99 53.12 -6.91 +1313 0 75 0 0 60.61 50.56 -7.61 +1314 0 70 0 0 62.30 47.89 -8.22 +1315 0 60 0 0 65.93 42.15 -9.23 +1316 0 50 0 0 69.73 36.19 -9.91 +1317 0 40 0 0 73.74 30.00 -10.32 +1318 0 30 0 0 78.06 23.70 -10.61 +1319 0 25 0 0 80.38 20.40 -10.66 +1320 0 20 0 0 82.74 17.07 -10.66 +1321 0 15 0 0 85.26 13.57 -10.59 +1322 0 10 0 0 87.84 10.05 -10.46 +1323 0 7 0 0 89.52 7.78 -10.35 +1324 0 5 0 0 90.66 6.26 -10.26 +1325 0 3 0 0 91.79 4.76 -10.16 +1326 0 2 0 0 92.36 4.01 -10.11 +1327 0 0 100 0 87.66 -2.65 72.38 +1328 0 0 98 0 87.71 -2.67 71.61 +1329 0 0 95 0 87.79 -2.71 70.44 +1330 0 0 90 0 87.95 -2.77 68.05 +1331 0 0 85 0 88.16 -2.85 64.82 +1332 0 0 80 0 88.38 -2.91 61.53 +1333 0 0 75 0 88.63 -2.95 57.72 +1334 0 0 70 0 88.89 -2.96 53.84 +1335 0 0 60 0 89.43 -2.86 45.69 +1336 0 0 50 0 90.00 -2.61 37.42 +1337 0 0 40 0 90.59 -2.19 28.94 +1338 0 0 30 0 91.22 -1.45 20.12 +1339 0 0 25 0 91.55 -0.99 15.48 +1340 0 0 20 0 91.90 -0.46 10.79 +1341 0 0 15 0 92.27 0.15 5.84 +1342 0 0 10 0 92.65 0.82 0.84 +1343 0 0 7 0 92.90 1.29 -2.41 +1344 0 0 5 0 93.07 1.62 -4.58 +1345 0 0 3 0 93.24 1.96 -6.74 +1346 0 0 2 0 93.33 2.14 -7.83 +1347 0 0 0 100 32.69 1.24 0.11 +1348 0 0 0 98 33.41 1.25 -0.04 +1349 0 0 0 95 34.48 1.28 -0.28 +1350 0 0 0 90 36.58 1.31 -0.70 +1351 0 0 0 85 39.33 1.34 -1.23 +1352 0 0 0 80 42.14 1.38 -1.76 +1353 0 0 0 75 45.19 1.40 -2.33 +1354 0 0 0 70 48.31 1.44 -2.91 +1355 0 0 0 60 54.52 1.49 -4.08 +1356 0 0 0 50 60.65 1.55 -5.23 +1357 0 0 0 40 66.75 1.60 -6.39 +1358 0 0 0 30 72.92 1.81 -7.22 +1359 0 0 0 25 76.13 1.92 -7.66 +1360 0 0 0 20 79.36 2.03 -8.10 +1361 0 0 0 15 82.74 2.14 -8.55 +1362 0 0 0 10 86.16 2.25 -9.01 +1363 0 0 0 7 88.36 2.33 -9.31 +1364 0 0 0 5 89.84 2.38 -9.51 +1365 0 0 0 3 91.30 2.42 -9.70 +1366 0 0 0 2 92.03 2.45 -9.80 +1367 0 0 0 0 93.50 2.50 -10.00 +1368 100 85 85 0 36.53 -2.33 -6.13 +1369 80 65 65 0 42.78 -2.14 -7.05 +1370 60 45 45 0 51.99 -1.00 -7.01 +1371 40 27 27 0 63.31 -0.49 -8.22 +1372 20 12 12 0 77.32 1.07 -9.52 +1373 10 6 6 0 84.94 1.93 -9.69 +1374 5 3 3 0 89.15 2.29 -9.77 +1375 40 27 27 10 59.43 -0.41 -7.08 +1376 20 12 12 10 71.80 0.91 -8.28 +1377 10 6 6 10 78.56 1.68 -8.53 +1378 60 45 45 20 46.79 -0.60 -5.29 +1379 40 27 27 20 55.82 -0.34 -6.02 +1380 20 12 12 20 66.69 0.75 -7.12 +1381 10 6 6 20 72.66 1.46 -7.47 +1382 80 65 65 40 36.25 -0.61 -3.70 +1383 60 45 45 40 42.09 -0.28 -3.71 +1384 40 27 27 40 49.05 -0.22 -4.04 +1385 20 12 12 40 57.16 0.48 -4.97 +1386 10 6 6 40 61.67 1.04 -5.49 +1387 100 85 85 60 30.68 0.14 -1.47 +1388 80 65 65 60 33.43 0.03 -2.04 +1389 60 45 45 60 37.69 0.30 -2.11 +1390 40 27 27 60 42.56 0.29 -2.44 +1391 20 12 12 60 48.14 0.74 -3.13 +1392 10 6 6 60 51.18 1.12 -3.48 +1393 100 85 85 80 28.59 0.75 0.00 +1394 80 65 65 80 30.50 0.66 -0.29 +1395 60 45 45 80 33.13 0.84 -0.43 +1396 40 27 27 80 35.87 0.77 -0.77 +1397 20 12 12 80 38.92 0.98 -1.24 +1398 10 6 6 80 40.50 1.19 -1.45 +1399 100 85 85 100 26.92 1.19 1.21 +1400 80 65 65 100 28.18 1.11 1.17 +1401 60 45 45 100 29.54 1.21 0.94 +1402 40 27 27 100 30.65 1.11 0.58 +1403 20 12 12 100 31.80 1.11 0.29 +1404 10 6 6 100 32.30 1.20 0.20 +1405 100 0 0 70 37.13 -7.82 -14.02 +1406 0 100 0 70 35.65 19.79 -1.31 +1407 0 0 100 70 45.47 -2.51 20.99 +1408 100 100 0 70 30.49 5.19 -8.99 +1409 100 0 100 70 34.84 -12.16 3.48 +1410 0 100 100 70 33.68 15.17 7.55 +1411 40 40 0 70 38.22 4.25 -6.95 +1412 40 0 40 70 42.06 -5.49 2.18 +1413 0 40 40 70 41.03 7.91 5.42 +1414 3 3 0 0 90.36 3.61 -11.81 +1415 3 0 3 0 91.78 0.83 -8.44 +1416 0 3 3 0 91.53 4.24 -6.99 +1417 3 3 3 0 90.10 3.06 -8.67 +1418 3 0 0 3 89.89 1.35 -11.29 +1419 0 3 0 3 89.64 4.60 -9.85 +1420 3 3 0 3 88.27 3.49 -11.42 +1421 0 0 3 3 91.04 1.91 -6.56 +1422 3 0 3 3 89.63 0.81 -8.19 +1423 0 3 3 3 89.39 4.10 -6.80 +1424 3 3 3 3 88.01 2.96 -8.40 +1425 7 7 0 0 86.30 4.97 -14.09 +1426 7 0 7 0 89.48 -1.43 -6.45 +1427 0 7 7 0 88.94 6.68 -3.24 +1428 7 7 7 0 85.70 3.73 -7.13 +1429 7 0 0 7 85.25 -0.05 -12.76 +1430 0 7 0 7 84.70 7.15 -9.59 +1431 7 7 0 7 81.75 4.56 -12.93 +1432 0 0 7 7 87.79 1.20 -2.36 +1433 7 0 7 7 84.65 -1.31 -5.98 +1434 0 7 7 7 84.14 6.11 -3.09 +1435 7 7 7 7 81.17 3.40 -6.57 +1436 40 3 0 0 75.11 -8.52 -28.96 +1437 3 40 0 0 72.61 28.36 -11.77 +1438 40 0 3 0 76.13 -11.19 -26.21 +1439 40 3 3 0 74.80 -9.40 -26.15 +1440 0 40 3 0 73.52 29.71 -8.11 +1441 3 40 3 0 72.40 28.05 -9.57 +1442 40 40 3 0 60.49 10.41 -24.69 +1443 3 0 40 0 89.06 -3.62 26.89 +1444 0 3 40 0 88.90 0.24 27.73 +1445 3 3 40 0 87.40 -1.23 25.73 +1446 40 3 40 0 71.53 -17.36 4.73 +1447 3 40 40 0 70.08 25.54 14.61 +1448 40 0 0 3 74.83 -9.99 -27.91 +1449 40 3 0 3 73.54 -8.29 -27.79 +1450 0 40 0 3 72.20 28.90 -9.96 +1451 3 40 0 3 71.11 27.33 -11.34 +1452 40 40 0 3 59.64 10.58 -25.71 +1453 40 0 3 3 74.51 -10.84 -25.14 +1454 40 3 3 3 73.23 -9.12 -25.09 +1455 0 40 3 3 71.98 28.61 -7.83 +1456 3 40 3 3 70.90 27.01 -9.23 +1457 40 40 3 3 59.43 10.03 -23.73 +1458 0 0 40 3 88.43 -2.17 27.83 +1459 3 0 40 3 86.95 -3.55 25.86 +1460 40 0 40 3 71.23 -18.64 5.23 +1461 0 3 40 3 86.79 0.16 26.67 +1462 3 3 40 3 85.35 -1.24 24.75 +1463 40 3 40 3 70.04 -16.69 4.58 +1464 0 40 40 3 69.65 26.29 15.56 +1465 3 40 40 3 68.58 24.49 14.04 +1466 40 40 40 3 57.24 4.93 -1.80 +1467 3 0 0 40 65.91 0.92 -7.12 +1468 0 3 0 40 65.75 2.85 -6.39 +1469 3 3 0 40 64.93 2.16 -7.12 +1470 40 3 0 40 55.93 -5.52 -14.86 +1471 3 40 0 40 54.34 15.95 -6.52 +1472 0 0 3 40 66.55 1.24 -4.55 +1473 3 0 3 40 65.70 0.56 -5.31 +1474 40 0 3 40 56.47 -6.96 -13.37 +1475 0 3 3 40 65.55 2.51 -4.61 +1476 3 3 3 40 64.72 1.80 -5.36 +1477 40 3 3 40 55.72 -5.90 -13.37 +1478 0 40 3 40 54.75 16.59 -4.60 +1479 3 40 3 40 54.14 15.68 -5.32 +1480 40 40 3 40 47.49 5.84 -12.99 +1481 3 0 40 40 63.48 -2.65 14.68 +1482 0 3 40 40 63.34 -0.62 15.10 +1483 3 3 40 40 62.50 -1.36 14.07 +1484 40 3 40 40 53.33 -9.46 3.04 +1485 3 40 40 40 51.83 13.08 7.94 +1486 0 0 0 10 86.16 2.25 -9.01 +1487 0 0 10 10 85.35 0.72 0.51 +1488 0 0 20 10 84.64 -0.47 9.26 +1489 0 0 40 10 83.38 -2.13 25.25 +1490 0 0 70 10 81.55 -3.02 46.81 +1491 0 10 0 10 81.15 8.87 -9.35 +1492 0 10 10 10 80.36 7.51 -0.69 +1493 0 10 20 10 79.66 6.45 7.27 +1494 0 10 40 10 78.41 4.95 21.83 +1495 0 10 70 10 76.65 4.21 41.55 +1496 0 20 0 10 76.62 15.01 -9.46 +1497 0 20 10 10 75.86 13.81 -1.60 +1498 0 20 20 10 75.17 12.87 5.64 +1499 0 20 40 10 73.93 11.53 18.88 +1500 0 20 70 10 72.26 10.95 36.89 +1501 0 40 0 10 68.59 26.34 -9.11 +1502 0 40 10 10 67.87 25.43 -2.69 +1503 0 40 20 10 67.22 24.71 3.22 +1504 0 40 40 10 66.02 23.66 14.08 +1505 0 40 70 10 64.53 23.40 28.94 +1506 0 70 0 10 58.33 42.04 -7.60 +1507 0 70 10 10 57.85 41.28 -2.96 +1508 0 70 20 10 57.41 40.64 1.33 +1509 0 70 40 10 56.61 39.59 9.25 +1510 0 70 70 10 55.67 38.56 20.44 +1511 10 0 0 10 81.89 -1.02 -13.66 +1512 10 0 10 10 81.04 -2.78 -4.48 +1513 10 0 20 10 80.27 -4.19 3.97 +1514 10 0 40 10 78.92 -6.23 19.40 +1515 10 0 70 10 77.10 -7.50 39.88 +1516 10 10 0 10 77.19 5.19 -13.79 +1517 10 10 10 10 76.38 3.62 -5.41 +1518 10 10 20 10 75.65 2.36 2.31 +1519 10 10 40 10 74.34 0.50 16.41 +1520 10 10 70 10 72.58 -0.64 35.18 +1521 10 20 0 10 72.93 10.96 -13.75 +1522 10 20 10 10 72.16 9.56 -6.11 +1523 10 20 20 10 71.46 8.43 0.94 +1524 10 20 40 10 70.21 6.76 13.83 +1525 10 20 70 10 68.51 5.76 31.00 +1526 10 40 0 10 65.34 21.60 -13.20 +1527 10 40 10 10 64.65 20.51 -6.90 +1528 10 40 20 10 64.01 19.63 -1.09 +1529 10 40 40 10 62.87 18.31 9.57 +1530 10 40 70 10 61.31 17.57 23.83 +1531 10 70 0 10 55.63 36.34 -11.41 +1532 10 70 10 10 55.19 35.44 -6.85 +1533 10 70 20 10 54.78 34.67 -2.63 +1534 10 70 40 10 54.04 33.40 5.17 +1535 10 70 70 10 52.94 32.14 16.00 +1536 20 0 0 10 78.01 -4.00 -17.83 +1537 20 0 10 10 77.11 -5.98 -8.95 +1538 20 0 20 10 76.31 -7.59 -0.78 +1539 20 0 40 10 74.88 -10.01 14.14 +1540 20 0 70 10 73.07 -11.66 33.61 +1541 20 10 0 10 73.59 1.86 -17.78 +1542 20 10 10 10 72.76 0.08 -9.65 +1543 20 10 20 10 72.00 -1.38 -2.16 +1544 20 10 40 10 70.66 -3.58 11.53 +1545 20 10 70 10 68.89 -5.12 29.42 +1546 20 20 0 10 69.58 7.29 -17.60 +1547 20 20 10 10 68.80 5.69 -10.15 +1548 20 20 20 10 68.10 4.39 -3.29 +1549 20 20 40 10 66.84 2.39 9.27 +1550 20 20 70 10 65.12 0.96 25.69 +1551 20 40 0 10 62.39 17.30 -16.86 +1552 20 40 10 10 61.73 16.04 -10.67 +1553 20 40 20 10 61.12 15.00 -4.96 +1554 20 40 40 10 60.02 13.40 5.53 +1555 20 40 70 10 58.40 12.21 19.23 +1556 20 70 0 10 53.23 31.12 -14.78 +1557 20 70 10 10 52.81 30.08 -10.29 +1558 20 70 20 10 52.44 29.18 -6.13 +1559 20 70 40 10 51.75 27.69 1.55 +1560 20 70 70 10 50.52 26.21 12.05 +1561 40 0 0 10 71.04 -9.28 -25.17 +1562 40 0 10 10 70.06 -11.70 -16.84 +1563 40 0 20 10 69.19 -13.73 -9.17 +1564 40 0 40 10 67.63 -16.91 4.83 +1565 40 0 70 10 65.86 -19.30 22.44 +1566 40 10 0 10 67.13 -4.06 -24.80 +1567 40 10 10 10 66.26 -6.26 -17.12 +1568 40 10 20 10 65.47 -8.10 -10.04 +1569 40 10 40 10 64.05 -11.02 2.90 +1570 40 10 70 10 62.30 -13.33 19.17 +1571 40 20 0 10 63.57 0.76 -24.36 +1572 40 20 10 10 62.78 -1.23 -17.28 +1573 40 20 20 10 62.07 -2.89 -10.75 +1574 40 20 40 10 60.80 -5.56 1.22 +1575 40 20 70 10 59.07 -7.78 16.24 +1576 40 40 0 10 57.14 9.63 -23.28 +1577 40 40 10 10 56.52 8.03 -17.29 +1578 40 40 20 10 55.96 6.67 -11.76 +1579 40 40 40 10 54.95 4.49 -1.59 +1580 40 40 70 10 53.26 2.46 11.12 +1581 40 70 0 10 49.01 21.69 -20.59 +1582 40 70 10 10 48.67 20.37 -16.22 +1583 40 70 20 10 48.35 19.21 -12.17 +1584 40 70 40 10 47.78 17.25 -4.69 +1585 40 70 70 10 46.30 15.34 5.23 +1586 70 0 0 10 61.80 -16.14 -35.18 +1587 70 0 10 10 60.94 -18.92 -27.36 +1588 70 0 20 10 60.17 -21.27 -20.16 +1589 70 0 40 10 58.82 -25.01 -6.95 +1590 70 0 70 10 56.98 -27.91 8.69 +1591 70 10 0 10 58.63 -11.59 -34.06 +1592 70 10 10 10 57.86 -14.12 -26.87 +1593 70 10 20 10 57.17 -16.25 -20.24 +1594 70 10 40 10 55.95 -19.67 -8.06 +1595 70 10 70 10 54.16 -22.42 6.49 +1596 70 20 0 10 55.72 -7.39 -32.96 +1597 70 20 10 10 55.04 -9.68 -26.35 +1598 70 20 20 10 54.42 -11.62 -20.24 +1599 70 20 40 10 53.33 -14.74 -9.02 +1600 70 20 70 10 51.59 -17.35 4.51 +1601 70 40 0 10 50.44 0.32 -30.74 +1602 70 40 10 10 49.91 -1.54 -25.19 +1603 70 40 20 10 49.43 -3.11 -20.06 +1604 70 40 40 10 48.58 -5.70 -10.60 +1605 70 40 70 10 46.93 -8.02 1.04 +1606 70 70 0 10 44.16 10.50 -27.36 +1607 70 70 10 10 43.77 9.05 -23.18 +1608 70 70 20 10 43.41 7.78 -19.30 +1609 70 70 40 10 42.77 5.64 -12.13 +1610 70 70 70 10 41.42 3.41 -2.69 +1611 50 40 40 0 55.80 1.09 -5.42 +1612 100 0 0 10 55.07 -20.50 -42.06 +1613 0 100 0 10 51.18 53.01 -4.66 +1614 0 0 100 10 80.18 -2.95 63.01 +1615 0 100 100 10 49.06 48.28 21.54 +1616 100 0 100 10 49.05 -36.09 9.64 +1617 100 100 0 10 37.09 9.00 -28.41 +END_DATA diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index 8122229b21..c74942fa5e 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -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 { 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, CmsError> { + static SPACES: [OnceLock>>; 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>> = 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> { } fn cmyk_space(name: &str) -> Result { - 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, 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; diff --git a/crates/color/src/cms/generic.rs b/crates/color/src/cms/generic.rs index 16f251054b..57d9d9d329 100644 --- a/crates/color/src/cms/generic.rs +++ b/crates/color/src/cms/generic.rs @@ -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, gbd: OnceLock, } @@ -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) -> 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)) diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index 8fc287ae23..e83b0c1449 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -432,10 +432,17 @@ fn text_tag(s: &str) -> Option { 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. diff --git a/crates/color/src/cms/measured.rs b/crates/color/src/cms/measured.rs new file mode 100644 index 0000000000..9394b69394 --- /dev/null +++ b/crates/color/src/cms/measured.rs @@ -0,0 +1,378 @@ +//! CMYK working spaces computed from published characterization data. +//! +//! Fogra publishes the measured colors of its reference printing conditions +//! () 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 +/// (). +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> { + 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::().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::().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 { + 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 { + 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 { + 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 { + 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::(); + 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 +} diff --git a/crates/color/src/cms/tests_measured.rs b/crates/color/src/cms/tests_measured.rs new file mode 100644 index 0000000000..7bf5735c7a --- /dev/null +++ b/crates/color/src/cms/tests_measured.rs @@ -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 = patches.iter().map(|p| delta_e2000(g.to_lab_abs(p.cmyk), p.lab)).collect(); + (errors.iter().sum::() / 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 = kept.into_iter().copied().collect(); + let left: Vec = 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 = (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 = 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::() <= 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::() <= 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::() > 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}"); + } +} diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index c3d74615ae..1fdcab123d 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -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}; diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs index 31500d1ac5..adf4e9ee47 100644 --- a/crates/color/src/oklab.rs +++ b/crates/color/src/oklab.rs @@ -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 { /// 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))); + } } diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs new file mode 100644 index 0000000000..ef42eec957 --- /dev/null +++ b/crates/color/src/wcag.rs @@ -0,0 +1,146 @@ +//! Contrast between two colors as WCAG 2 measures it (): +//! 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::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) { + 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) { + 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]); + } +} diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index ba203610d6..b5c993a865 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -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 { + 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 { + 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 { g.id.filter(|id| self.node(*id).is_some_and(Node::is_ruler_guide)) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 2ee96ec2f1..dfe6e22e73 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -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)] diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index 3519986512..a1bfaefe7d 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -278,6 +278,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet) -> u if let Some(e) = n.extras_box() { b += ALLOC + size_of::(); 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::() } +/// 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::(); + a.url.capacity() + + a.note.capacity() + + pairs(&a.data) + + pairs(&a.events) + + vec_bytes(&a.classes) + + a.classes.iter().map(String::capacity).sum::() + + vec_bytes(&a.foreign) + + a.foreign.iter().map(|f| f.ns.capacity() + f.prefix.capacity() + f.name.capacity() + f.value.capacity()).sum::() + + vec_bytes(&a.tags) + + a.tags.iter().map(|t| t.name.capacity() + t.value.capacity()).sum::() +} + /// A vector's buffer (not what its elements own). fn vec_bytes(v: &Vec) -> usize { if v.capacity() == 0 { 0 } else { ALLOC + v.capacity() * size_of::() } @@ -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); diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 79ce594212..87b9a375db 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -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}; diff --git a/crates/doc/src/node/attributes.rs b/crates/doc/src/node/attributes.rs index 6f573a61aa..67d3d02308 100644 --- a/crates/doc/src/node/attributes.rs +++ b/crates/doc/src/node/attributes.rs @@ -38,6 +38,141 @@ pub struct ObjectAttributes { /// with it. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub foreign: Vec, + /// 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, +} + +/// 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 { + 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 = (0..a.tags.len()).map(|i| keeps(&a.tags[i], &a.tags[..i])).collect(); + let mut used: Vec = 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 { + let used: Vec = + 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= diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 20dae6ec4b..cadfb6b7a6 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -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] { 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> { + 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> { + 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 { diff --git a/crates/doc/src/perspective.rs b/crates/doc/src/perspective.rs index ab347529e6..d1322de74f 100644 --- a/crates/doc/src/perspective.rs +++ b/crates/doc/src/perspective.rs @@ -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) { diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 25a2451968..073a0f2efd 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -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, diff --git a/crates/doc/src/text/attr_ranges.rs b/crates/doc/src/text/attr_ranges.rs new file mode 100644 index 0000000000..bce0098ac2 --- /dev/null +++ b/crates/doc/src/text/attr_ranges.rs @@ -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 = 0.1..=1296.0; +/// Leading ([`CharStyle::leading`]) other than Auto, in points. +pub const LEADING: RangeInclusive = 0.1..=5000.0; +/// Horizontal and vertical scale ([`CharStyle::h_scale`], [`CharStyle::v_scale`]), in percent. +pub const CHAR_SCALE: RangeInclusive = 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 = -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 = -360.0..=360.0; +/// The miter limit of a character stroke ([`CharStyle::stroke_miter_limit`]). +pub const CHAR_MITER_LIMIT: RangeInclusive = 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(()) + } +} diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index b3cff3aa47..9371947565 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -802,6 +802,45 @@ fn auto_alignment_saves_readable_by_older_builds() { assert_eq!(serde_json::from_str::(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::*; diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 9d9810c240..02cf4b6205 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -326,21 +326,21 @@ pub fn effect_catalog() -> Vec { "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 { catalog_index().get(id).cloned().or_else(|| plugin_info(id)) diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 55e3ad6fe3..74a24c2442 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -66,7 +66,7 @@ pub const PATHFINDER_EFFECT_PRECISION: std::ops::RangeInclusive = 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 { + 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), } diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 1b8067e91c..216e541caf 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -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, diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index ab588838a6..d97c16b554 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -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 { + 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 { 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()); diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 3b0acaa821..f916ee0d87 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -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}"); + } + } +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index cf21c25e46..6732c973f4 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -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 } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 56f955106b..587f60eb11 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -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; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 03fb17f436..9fa5806c52 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -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; diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 8bf1e00d16..c12eb2fa64 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -173,7 +173,7 @@ fn filter(s: &mut Session, p: &Value) -> Result { 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 diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 9de16ca200..a0efc6f265 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -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 { let mut v = roles::specs(); v.extend(check::specs()); + v.extend(angle::specs()); v.extend(fold::specs()); v } diff --git a/crates/engine/src/cmd/addons/packaging/angle.rs b/crates/engine/src/cmd/addons/packaging/angle.rs new file mode 100644 index 0000000000..f38645774f --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/angle.rs @@ -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 = -180.0..=180.0; + +pub fn specs() -> Vec { + 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, + revision: u64, + /// The objects looked at: the selection, or the `ids` a command was given in its place. + objects: Vec, + 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> = 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 = roots.iter().copied().collect(); + // Each object's place, from the document's lookup of ids. + let outer = |id: NodeId| -> Option { + 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 { + stored(n)?.trim().parse::().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) -> 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 { + 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::>(), "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 { + 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, + /// 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 { + 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; diff --git a/crates/engine/src/cmd/addons/packaging/angle/tests.rs b/crates/engine/src/cmd/addons/packaging/angle/tests.rs new file mode 100644 index 0000000000..20e3ce1195 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/angle/tests.rs @@ -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 { + 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) { + 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 = 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(" = 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 = 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)); +} diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs index 9507a17daa..244a32352d 100644 --- a/crates/engine/src/cmd/addons/packaging/check.rs +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -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) -> 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 } } diff --git a/crates/engine/src/cmd/addons/packaging/fold.rs b/crates/engine/src/cmd/addons/packaging/fold.rs index 068b2375c9..3543591944 100644 --- a/crates/engine/src/cmd/addons/packaging/fold.rs +++ b/crates/engine/src/cmd/addons/packaging/fold.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "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 )] diff --git a/crates/engine/src/cmd/addons/packaging/roles.rs b/crates/engine/src/cmd/addons/packaging/roles.rs index 2b3c7696f3..7cd5e90ba6 100644 --- a/crates/engine/src/cmd/addons/packaging/roles.rs +++ b/crates/engine/src/cmd/addons/packaging/roles.rs @@ -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, 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) -> (Vec, 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 { "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 { "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 { 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 { fn roles(s: &mut Session, p: &Value) -> Result { 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 = Role::ALL .into_iter() @@ -425,7 +481,10 @@ fn roles(s: &mut Session, p: &Value) -> Result { 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 { diff --git a/crates/engine/src/cmd/addons/packaging/tests.rs b/crates/engine/src/cmd/addons/packaging/tests.rs index 07a8bd3a30..1db9cd8e07 100644 --- a/crates/engine/src/cmd/addons/packaging/tests.rs +++ b/crates/engine/src/cmd/addons/packaging/tests.rs @@ -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}"); } diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs index fc88442997..135c9d964e 100644 --- a/crates/engine/src/cmd/addons/pathtools/shape.rs +++ b/crates/engine/src/cmd/addons/pathtools/shape.rs @@ -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 { "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 { 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) })) } diff --git a/crates/engine/src/cmd/addons/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 8cd83bacfd..12754ce6b6 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -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::>(); + 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 { v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() } diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index d0c5447c42..14a462d79f 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -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 { 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(()) })?; diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 692545d828..426f374a5c 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index c6c1da2980..610498f56a 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -47,7 +47,7 @@ pub fn specs() -> Vec { "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 { fn conflicts(s: &mut Session, p: &Value) -> Result { 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 = converted .as_ref() .unwrap_or(&s.clipboard) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 5f4b7b05f4..a7827e135b 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -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 { 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 { let hex = |cs: &[Color]| cs.iter().map(Color::to_hex).collect::>(); Ok(json!({ "rule": rule.id(), "colors": hex(&g.colors), "grid": g.grid.iter().map(|r| hex(r)).collect::>() })) } + +/// 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 { + 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::>(); + // 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::>(); + 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), + 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, + /// The object's shown fill and stroke rows with paint below the row, which the row draws over. + lower: Vec, +} + +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, + 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::>(), b.around.iter().filter(counts).collect::>()); + // 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)]) -> Vec { + 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, stroke: bool) -> Vec<(&Node, Option)> { + 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, stroke: bool) -> std::result::Result { + 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 { + 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::>() + }; + 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::>() + } + }; + 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, 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::>(); + 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, 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> { + 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, 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 { + 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) +} diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 54e7a3bbf4..0d25a6e57a 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "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, 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, 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, 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 { } 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:?}"); + } +} diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index e248f2bbc3..7a4a4dea07 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -73,7 +73,7 @@ pub fn specs() -> Vec { "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 { "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 { /// Ellipse tool drag is. fn circle_through_points(s: &mut Session, p: &Value) -> Result { 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 { 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 { Ok(out) } +/// The point an `[x, y]` pair of finite numbers gives. +fn pair(v: &Value) -> Option { + 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> { - 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>> { } /// 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 { 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 { 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 { 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 { })?; 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); diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 717c9cdc14..1cf7af0334 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -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 { @@ -730,13 +730,10 @@ fn release_guides(s: &mut Session, p: &Value) -> Result { }; // 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()?, diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 9a2ee80033..08404a3092 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -12,7 +12,7 @@ pub fn specs() -> Vec { "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 { "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 { "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 ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index 36280196b7..f69ac40822 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -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> { +/// 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> { + 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 { let widest = size + variation; diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index cc543f3e05..445a71b171 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -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 { 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 = 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. diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 5f281e2e34..da269286cd 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -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, reach: f64) -> Vec, b: Option, 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, a: Option, b: Option, 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, b: Option, 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 { } 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 = if roundness < 100.0 { samples .iter() @@ -857,7 +896,7 @@ pub(super) fn blob(s: &mut Session, p: &Value) -> Result { } else { samples.clone() }; - let pressure = size_pressure(p, &mapped_samples, C)?; + let pressure = size_profile(p, &mapped_samples, C)?; let pts: Vec = samples.into_iter().map(|s| s.pt).collect(); let mapped_pts: Vec = 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 { 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)]); + } } diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index b787bc5d0e..820572287f 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -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 { 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); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 80277d64b8..3922a8e1f0 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "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 { "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 { 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 { 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 { fn clear(s: &mut Session, p: &Value) -> Result { 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 { 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())) { diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index f29e2e3745..cc5c19adea 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -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 { 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 { 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 { } } } - 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 { } } } - 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) })) } diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 7aca68fd02..2c1ee412a6 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -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)] diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index a41831b200..5e756623f0 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "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., 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 .html / .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-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", + "{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., 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 .html / .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), 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-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", has_doc, export::export ), @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "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.; 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.; 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 ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 1ecb41290e..b308f874ab 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -256,6 +256,11 @@ struct RasterOptions { dither: Option, dither_amount: Option, transparency: Option, + /// 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, + /// The diffusion transparency dither's strength, 0–100, read as `transparency_dither` is. + transparency_dither_amount: Option, matte: Option, lossless: Option, lzw: Option, @@ -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> { 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 { { 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 { diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 0db990ad4c..2d6e459ece 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -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 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 ImporterPart { + use vectorcraft_plugins::{import, registry}; + static MADE: std::sync::Mutex> = 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 { + 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 { 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 }; diff --git a/crates/engine/src/cmd/fileio/importer.rs b/crates/engine/src/cmd/fileio/importer.rs index 3ba6c6fa19..d89cfa22b7 100644 --- a/crates/engine/src/cmd/fileio/importer.rs +++ b/crates/engine/src/cmd/fileio/importer.rs @@ -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.`), 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> { +/// 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> { 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 = 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>> { - 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 = 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>> { + 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> { + 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> { - 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> { + 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> { + 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> { +fn read_path_for(path: &str, _: &Value, _: Mode, _: &str) -> Result> { 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> { + 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, Vec)> { + 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)> { + 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 { - 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 diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 250fc98f9b..2b3613984a 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -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); diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 8e080e8d80..4dc5c5e75e 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "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 another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones not linked to a spot swatch at a tint above 0% knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{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 another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent; FOGRA51 or FOGRA52 for the built-in profiles computed from that data, with registry http://www.color.org unless registry is given), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones not linked to a spot swatch at a tint above 0% knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, export_pdf ), diff --git a/crates/engine/src/cmd/fileio/tests_palette.rs b/crates/engine/src/cmd/fileio/tests_palette.rs index e54aababec..d27166e5da 100644 --- a/crates/engine/src/cmd/fileio/tests_palette.rs +++ b/crates/engine/src/cmd/fileio/tests_palette.rs @@ -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 = 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"); diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rs index 548e5fade2..e31c21dd00 100644 --- a/crates/engine/src/cmd/freeform.rs +++ b/crates/engine/src/cmd/freeform.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "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 { "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 { "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 { "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 { "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 { "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 { "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 { } 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"; + +/// " 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 { /// 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(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freeform, Space) -> std::result::Result) -> Result { - // 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 { 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 { fn get(s: &mut Session, p: &Value) -> Result { 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); diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 2b14fdba2d..da5bbea659 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "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 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 (the paint the bucket paints with)", + "{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. 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 (the paint the tool paints with)", has_doc, edit_gradient ), @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "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 { fn select_stop(s: &mut Session, p: &Value) -> Result { 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 { /// 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, +pub struct StopOwner { + /// The active document's uid, which stays the same when its tab moves. + doc: Option, object: Option, /// 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, - 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 { 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 = std::result::Result; @@ -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 { 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 { })?; 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; diff --git a/crates/engine/src/cmd/gradpresets.rs b/crates/engine/src/cmd/gradpresets.rs index 89deda43ad..9b429beaa2 100644 --- a/crates/engine/src/cmd/gradpresets.rs +++ b/crates/engine/src/cmd/gradpresets.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "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 { 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(); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 1782e60f9c..5c7c75c610 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -66,7 +66,7 @@ pub fn specs() -> Vec { "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 { "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 { fn set_current(s: &mut Session, p: &Value) -> Result { 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, id: NodeId) -> bool { /// The selection column: select a row's art. fn select_art(s: &mut Session, p: &Value) -> Result { 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 { Ok(json!({ "selected": st.selection.objects.iter().map(|i| i.0).collect::>() })) } +/// 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 { + 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, add: bool, c: &str, none: &str) -> Result<(Vec, Vec)> { + 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, diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 80c4cbefb9..4f92220324 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -1247,7 +1247,7 @@ fn use_item(s: &mut Session, p: &Value) -> Result { } 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 { } 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 { } 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 })) } diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index b95134aa59..ffea03187d 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -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; } } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 4785816809..8272f7d8cb 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "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 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 { + (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 { 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, 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())?; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 8ce478ad97..47190a2cdf 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -34,8 +34,8 @@ pub fn specs() -> Vec { "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 { ["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 { "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 ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index a4cec6253c..12a92b9193 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -99,6 +99,12 @@ fn corners_param(p: &Value) -> Result>> { list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::>().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, angle: Option) -> Option { @@ -277,7 +283,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { 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 { && 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) }) diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 1ccd74d57f..527957f234 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -16,7 +16,27 @@ fn origin_of(s: &Session, p: &Value, ids: &[NodeId]) -> Result { { 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> { + 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 { 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) { diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index b09bc04d4b..25ca3a60ca 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -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 { vec![ cmd!( @@ -27,7 +42,7 @@ pub fn specs() -> Vec { "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 or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. 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 (the color the bucket paints with) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change the bucket made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{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 or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or 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 (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -36,7 +51,7 @@ pub fn specs() -> Vec { "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 { "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 { "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 { "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 { "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 { "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 { "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 { "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 { "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)> { - 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 { 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, opacity: Option, fill: bool) -> Result { 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> { +/// `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> { 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 { +/// 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 { + 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> { + 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 { 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 { } fn swap(s: &mut Session, p: &Value) -> Result { - 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 { 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 { const LIVE_PAINT_DEFAULT_WEIGHT: f64 = 0.5; fn default_paint(s: &mut Session, p: &Value) -> Result { - 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 { /// 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 { - 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. diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 13f7051223..77cdfdcb7d 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -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] = [ diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 64ce29e337..a93c4da50d 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -34,7 +34,8 @@ //! plays. A key a schema doesn't name passes there too, and the values of the parameters it names //! are still checked. Even there, an effect's `color` that the effect can't read and a Levels or Curves //! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams` -//! themselves ([`check_effect_color`], [`check_effect_channel`]). +//! themselves ([`check_effect_color`], [`check_effect_channel`]). A saved step may keep an unknown +//! shadow or glow blend mode, which the effect draws as Normal. use std::collections::HashMap; use std::sync::OnceLock; @@ -456,7 +457,8 @@ fn check_member_keys(id: &str, params: &Value) -> Result<()> { /// `params` of built-in effect `effect`, as command `id` was given them (#1592): only keys the /// effect takes (those of its dialog defaults and of its params description), each of the type /// the effect reads ([`check_effect_types`]), a `color` the effect can draw ([`check_effect_color`]) -/// and a Levels or Curves `channel` the effect has ([`check_effect_channel`]). Numbers out of range +/// a Levels or Curves `channel` the effect has ([`check_effect_channel`]) and a Drop Shadow's or +/// glow's `mode` that names a blend mode ([`check_effect_blend`]). Numbers out of range /// pass: the effect clamps them when it draws. An installed effect plug-in's are checked against its /// manifest, and an unknown effect is the command's to report. pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> { @@ -476,6 +478,7 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> if let Some(key) = given.keys().find(|k| !keys.contains(&k.as_str())) { return Err(unknown(id, key, &keys)); } + check_effect_blend(id, effect, params)?; check_effect_types(id, effect, params)?; // An SVG filter's XML is one drawable element. if effect == vectorcraft_render::effects::SVG_FILTER @@ -661,6 +664,20 @@ pub(crate) fn check_effect_channel(id: &str, effect: &str, params: &Value) -> Re Err(bad(id, format!("`{key}` must be one of {}", vectorcraft_render::effects::CHANNELS.join(", ")))) } +/// The `mode` in `params` of Drop Shadow, Inner Glow or Outer Glow (`effect`), as command `id` was +/// given it: a parameter error naming the blend modes unless the effect reads it as one +/// ([`vectorcraft_render::effects::parse_blend_mode`]); an older step with another value still replays in Normal. +fn check_effect_blend(id: &str, effect: &str, params: &Value) -> Result<()> { + use vectorcraft_render::effects; + let key = "mode"; + let Some(v) = params.get(key) else { return Ok(()) }; + if !effects::takes_blend_mode(effect, key) || v.as_str().and_then(effects::parse_blend_mode).is_some() { + return Ok(()); + } + let modes: Vec = vectorcraft_color::BlendMode::ALL.into_iter().map(effects::blend_mode_id).collect(); + Err(bad(id, format!("`{key}` must be one of {}", modes.join(", ")))) +} + /// The Blur Center (`centerX`, `centerY`) in `params` of Radial Blur (`effect`), as command `id` /// was given it: a parameter error unless each is a number from 0 to 1 (a share of the object's /// bounds). `effect.apply` and `effect.setParams` run this themselves before they edit, as they @@ -698,6 +715,7 @@ pub const UNCHECKED: &[&str] = &[ "document.exportForScreens", "document.exportForWeb", "document.exportForWeb.preview", + "document.exportForWeb.saveColorTable", "document.exportPdf", "document.find", "document.inspect", @@ -803,6 +821,7 @@ pub const UNCHECKED: &[&str] = &[ "transparency.setOpacityMask", "transparency.unlinkOpacityMask", "type.pathOptions", + "webExport.loadColorTable", "webExport.optimizeToFileSize", "webExport.presets.save", "webExport.settings", @@ -1067,7 +1086,7 @@ pub fn check_params(id: &str, params: &Value) -> Result<()> { fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> { let Some(spec) = find_command(id) else { return Ok(()) }; if let ("effect.apply" | "appearance.addEffect", Some(effect), Some(given)) = - (id, params.get("effect").or_else(|| params.get("id")).and_then(Value::as_str), params.get("params")) + (id, super::effectcmd::requested_effect(params), params.get("params")) { check_effect_params(id, effect, given)?; } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index b7df3dc467..525cef316a 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Delete Anchor Points", [], None, - "{} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key, unless the deleteKeepsPathsJoined preference is on)", + "{keepEmpty?: bool (keep a compound path left with no members)} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key, unless the deleteKeepsPathsJoined preference is on)", has_anchors, delete_anchors ), @@ -328,10 +328,18 @@ pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Res Ok(on) } -/// [`transform_selected`] on the active document's selection, as one undo step `label`. -pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { +/// [`transform_selected`] on the active document's selection, as one undo step `label`. A +/// transform other than a move also transforms the selected ruler guides +/// ([`Document::transform_ruler_guides`]). Returns the ids of the guide paths that adds. +pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result> { let sel = s.doc()?.selection.clone(); - s.edit(label, |doc, _| transform_selected(doc, &sel, xf, sc, interpolate)) + // As [`transform_selected`] tells a move apart, which moves the guides itself. + 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; + s.edit(label, |doc, live| { + transform_selected(doc, &sel, xf, sc, interpolate)?; + Ok(if is_translation { vec![] } else { doc.transform_ruler_guides(live, xf) }) + }) } /// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the @@ -1720,6 +1728,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: bool) -> Result { // `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step. let with_guides = switch_or(p, "guides", false, "path.deleteAnchors")?; + let keep_empty = switch_or(p, "keepEmpty", false, "path.deleteAnchors")?; let st = s.doc()?; let sel = st.selection.anchors.clone(); let segments = st.selection.segments.clone(); @@ -1737,12 +1746,16 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo .copied() .filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor))) .collect(); - // The compound paths that hold a deleted object; one left with no members goes too. - let compounds: BTreeSet = whole_ids - .iter() - .chain(sel.keys()) - .filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))) - .collect(); + // The compound paths that hold a deleted object; one left with no members goes too, unless `keepEmpty`. + let compounds: BTreeSet = if keep_empty { + BTreeSet::new() + } else { + whole_ids + .iter() + .chain(sel.keys()) + .filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))) + .collect() + }; if !whole_ids.is_empty() { d.remove_many(&whole_ids)?; } diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 1793f17d5c..b28cf537dc 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "Pathfinder Options…", ["Window", "Pathfinder"], None, - "{precision?: pt 0.001..10 (0.01; how closely the Pathfinder operations follow the paths: results are refit to within it and pieces thinner than it are dropped), removeRedundantPoints?: bool (false; the results lose the anchors that don't change their shape), removeUnpainted?: bool (false; Divide and Outline leave out the pieces of objects with no fill)} Pathfinder Options, kept in the preferences and used by every later Shape Mode and Pathfinder operation (not Trap); {} reads them → the options", + "{precision?: pt 0.001..10 (0.01; how closely the Pathfinder operations follow the paths: 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 (false; the results lose the anchors that don't change their shape), removeUnpainted?: bool (false; Divide and Outline leave out the pieces of objects with no fill)} Pathfinder Options, kept in the preferences and used by every later Shape Mode and Pathfinder operation (not Trap); {} reads them → the options", always, pathfinder_options ), @@ -610,8 +610,8 @@ impl Default for PathfinderOptions { } } -/// The range of Pathfinder Options › Precision (pt). -pub const PATHFINDER_PRECISION_RANGE: std::ops::RangeInclusive = 0.001..=10.0; +/// The range of Pathfinder Options › Precision (pt), which a Pathfinder effect's `precision` shares. +pub const PATHFINDER_PRECISION_RANGE: std::ops::RangeInclusive = vectorcraft_render::effects::PATHFINDER_EFFECT_PRECISION; impl PathfinderOptions { /// These options with those `p` names (`precision` in pt or a string with a unit), or why `p` diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index a1a42a9acd..e787899cd2 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -32,6 +32,9 @@ //! - A VectorCraft document placed from a file with Link (the default) becomes a placed document: //! one locked object showing the artboard `page`, linked to the file and read again when it //! changes ([`document`]); without Link, an editable copy of its art. +//! - A file an importer plug-in whose manifest sets `place` reads (the one `importer` names, else +//! the first by id that lists the extension of a file no built-in format reads) becomes one group +//! of the objects it returned, embedded ([`fileio::importer`]). //! //! The art lands centred on `at`, fitted into `rect`, or (Replace) where the replaced object was, //! with its transform; Template puts it on a new template layer. The images, symbols, patterns and @@ -82,7 +85,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its objects, guides left out, are placed as one group named after the file, in the order it returned them, embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -190,10 +193,14 @@ fn load_sliced(p: &Value, cmd: &str, board: Option, link_pdf: bool) -> Res /// The file `p` names, read into placeable art; a DXF drawing's Fit to Artboard fills `board` /// (unless the params name their own box). A PDF/.ai page or an EPS file read from a path is placed /// linked with Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB -/// file's slices go to `slices`. +/// file's slices go to `slices`. A file an importer plug-in places (the one `importer` names, or one +/// no built-in format reads) is read by it ([`plugin_art`]). fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_out: &mut Slices) -> Result { - let src = fileio::source(p, cmd)?; + let src = fileio::importer::place_source(p, cmd)?; let name = fileio::file_name(src.name); + if let Some(plugin) = fileio::importer::named_for_place(src.name, p, cmd)? { + return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd); + } // An Affinity file is recognised by its signature, whatever its name says. if fileio::TEXT_EXTS.contains(&fileio::extension(src.name).as_str()) && !vectorcraft_affinity::is_affinity(&src.bytes) { let text = text::import(&src.bytes, text::TextOptions::parse(p, cmd)?, cmd)?; @@ -228,8 +235,12 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o } return Ok(Loaded { name, format: &doc::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None }); } - let format = fileio::detect(src.name, &src.bytes) - .ok_or_else(|| bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)")))?; + let Some(format) = fileio::detect(src.name, &src.bytes) else { + return match fileio::importer::for_place(src.name) { + Some(plugin) => plugin_art(name, src.name, &src.bytes, &plugin, p, cmd), + None => Err(bad(cmd, format!("can't place `{name}`: not a format VectorCraft reads (see document.formats)"))), + }; + }; let page = match p.get("page") { None => 1, Some(v) => v.as_u64().filter(|n| (1..=100_000).contains(n)).ok_or_else(|| bad(cmd, "page must be a whole number from 1"))? as usize, @@ -385,6 +396,20 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o Ok(Loaded { name, format, art: Art::Vector { src: Box::new(doc), nodes, clip }, natural, warnings, link: None, board }) } +/// The file `src` (named `name`) holding `bytes`, read by importer plug-in `plugin` with `p`'s +/// `params`, as art to place: its objects in paint order, guides left out, in a group whose natural +/// box is the bounds of what they draw. It is embedded: an importer reads the file once, so there is +/// nothing to link to. +fn plugin_art(name: String, src: &str, bytes: &[u8], plugin: &vectorcraft_plugins::Plugin, p: &Value, cmd: &str) -> Result { + let (format, mut doc, warnings) = fileio::importer::read_for_place(src, bytes, plugin, p, cmd)?; + let layers = std::mem::take(&mut doc.layers); + let nodes = art_of(layer_art(&layers)); + let natural = shown_bounds(&doc.symbol_boxes(), &nodes) + .filter(|r| r.width() > 0.0 || r.height() > 0.0) + .ok_or_else(|| bad(cmd, format!("`{name}` has no art to place")))?; + Ok(Loaded { name, format, art: Art::Vector { src: Box::new(doc), nodes, clip: None }, natural, warnings, link: None, board: None }) +} + /// A PSD or PSB file's layers, read as `document.open` reads them into `doc`, as art to place: an /// image for each layer and a group for each layer group, bottom first, with the layer's name, /// visibility, opacity, blend mode and opacity mask. The art's natural box is the file's canvas, @@ -992,7 +1017,7 @@ fn read_queue(doc: u64, p: Value, queued: Vec) -> Result { let thumbnail = p.get("thumbnail").and_then(Value::as_f64); let (mut entries, mut files, mut skipped) = (vec![], vec![], vec![]); for mut q in queued { - for k in ["link", "template", "page", "crop", "text", "dxf", "layers", "hiddenLayers", "importSlices"] { + for k in ["link", "template", "page", "crop", "text", "dxf", "layers", "hiddenLayers", "importSlices", "importer", "params"] { if let Some(v) = p.get(k) { q[k] = v.clone(); } diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 30515fcb45..bb8d3372ae 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -42,18 +42,24 @@ //! //! A filter whose manifest lists `inputs` (plug-in API level 2) is also given the selected type, //! images or symbol instances of those kinds, to read only: its output must return each of them -//! unchanged ([`objects::decode_output_with`]). +//! unchanged ([`objects::decode_output_with`]). At level 3 its manifest's `writes` lists the kinds +//! among them it may change: type's runs and paragraph styles, an image's transform and opacity, +//! an instance's symbol and transform, and each one's name ([`objects::decode_output_writing`]). //! //! A filter, or a live effect's command, whose manifest lists `context` (plug-in API level 3) is //! also given the parts of the active document it names in `_context.document`, whether or not //! anything is selected: the settings, artboards, layers and swatches, as plain values //! ([`context`]). +//! +//! A filter may be written in JavaScript ([`vectorcraft_plugins::js`]): `plugin.install {path}` +//! takes its `.vcplugin` manifest and reads the `.js` file the manifest names beside it, and the +//! plug-in store keeps the two as one module. use std::collections::HashMap; use std::sync::{Arc, Mutex, RwLock}; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{Document, Effect, Node}; +use vectorcraft_doc::{Document, Effect, Node, NodeKind}; use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode}; use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or}; @@ -101,6 +107,9 @@ pub fn describe(p: &Plugin) -> Value { Kind::Exporter | Kind::Importer => { v["format"] = json!(export::format_id(&m.id)); v["extensions"] = json!(m.extensions); + if m.place { + v["place"] = json!(true); + } } Kind::Filter => {} } @@ -110,12 +119,19 @@ pub fn describe(p: &Plugin) -> Value { if !m.inputs.is_empty() { v["inputs"] = json!(m.inputs); } + if !m.writes.is_empty() { + v["writes"] = json!(m.writes); + } if !m.context.is_empty() { v["context"] = json!(m.context); } if m.paint_output { v["paintOutput"] = json!(true); } + if let Some(script) = p.script() { + v["runtime"] = json!(m.runtime.name()); + v["script"] = json!(script); + } if !m.command_allowlist.is_empty() { v["commandAllowlist"] = json!(m.command_allowlist); } @@ -147,7 +163,7 @@ pub fn describe(p: &Plugin) -> Value { /// The plug-in's own parameters from command params: `params` if given, else the top-level keys /// minus the ones the command itself uses. -fn plugin_params(p: &Value) -> Value { +pub fn plugin_params(p: &Value) -> Value { if let Some(v) = p.get("params") { return v.clone(); } @@ -374,7 +390,7 @@ impl FilterRun { fn finish(self, s: &mut Session, output: &[u8]) -> Result { let m = self.plugin.manifest(); let may = m.permissions(); - let out = objects::decode_output_with(output, &self.input, &self.read_only).map_err(err)?; + let out = objects::decode_output_writing(output, &self.input, &self.read_only, &m.write_kinds()).map_err(err)?; if out.document_data.is_some() && !may.contains(&Permission::State) { return Err(not_granted(&m.name, Permission::State)); } @@ -382,6 +398,7 @@ impl FilterRun { // A command's undo step is named after the command. let label = self.label(); let (inputs, parent) = (self.inputs, self.parent); + let notice = out.notice; // The output is applied to a copy of the document, as `colorcmds::edit_if_changed` applies // its pass: only a copy whose objects or kept data differ becomes the document, as one undo // step. Otherwise the document, its undo and redo steps and its saved state stay as they @@ -389,18 +406,52 @@ impl FilterRun { if s.script_running() { return Err(EngineError::Busy); } - if !s.previewing && super::typing_in_progress(s) { + // Typing whose text Real-time Drawing off left out of the document isn't in what the + // plug-in was given, and the output would replace it ([`keep_unapplied_typing`] keeps it + // before the run is prepared). + if unapplied_typing(s) { + return Err(err(vectorcraft_plugins::Error::Output( + "typing in progress isn't in what the plug-in was given: nothing was changed".into(), + ))); + } + let data = out.document_data; + // The output applied to `now`, with the checks that refuse it. + let build = |now: &Document, objects: Vec| -> Result<(Document, Vec)> { + let mut d = now.clone(); + let before = (!may_write).then(|| d.layers.clone()); + let ids = objects::apply_output(&mut d, &inputs, objects, parent, &admit_effects).map_err(err)?; + if before.is_some_and(|b| b != d.layers) { + return Err(not_granted(&m.name, Permission::DocWrite)); + } + // Type whose text the output changed is laid out again. + let retyped: Vec = ids + .iter() + .copied() + .filter(|&id| match (d.node(id).map(|n| &n.kind), now.node(id).map(|n| &n.kind)) { + (Some(NodeKind::Text(new)), Some(NodeKind::Text(old))) => new.runs != old.runs || new.paras != old.paras || new.para != old.para, + _ => false, + }) + .collect(); + super::typecmd::refresh_bounds_of(&mut d, &retyped); + if let Some(data) = data.clone() { + d.set_plugin_data(&m.id, data); + } + Ok((d, ids)) + }; + // Typing in progress, its text already in the document, is kept as `s.edit` keeps it once + // nothing can refuse the output, so a refused output leaves it in progress. Keeping it can + // change the document, and the output is then applied to the document as kept. + let typing = !s.previewing && super::typing_in_progress(s); + let again = typing.then(|| out.objects.clone()); + let mut now = s.doc()?.doc.clone(); + let (mut d, mut ids) = build(&now, out.objects)?; + if let Some(objects) = again { super::settle_interaction(s)?; - } - let now = s.doc()?.doc.clone(); - let mut d = (*now).clone(); - let before = (!may_write).then(|| d.layers.clone()); - let ids = objects::apply_output(&mut d, &inputs, out.objects, parent, &admit_effects).map_err(err)?; - if before.is_some_and(|b| b != d.layers) { - return Err(not_granted(&m.name, Permission::DocWrite)); - } - if let Some(data) = out.document_data { - d.set_plugin_data(&m.id, data); + let kept = s.doc()?.doc.clone(); + if !Arc::ptr_eq(&kept, &now) { + now = kept; + (d, ids) = build(&now, objects)?; + } } let selectable = |d: &Document| ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)).collect::>(); if same_art(&d.layers, &now.layers) && d.plugin_data(&m.id) == now.plugin_data(&m.id) { @@ -423,6 +474,11 @@ impl FilterRun { if let Some(cmd) = &self.command { out["command"] = json!(cmd.id); } + // Only an output that was applied reports its notice, with the name of the plug-in that ran. + if let Some(notice) = notice { + out["notice"] = json!(notice); + out["pluginName"] = json!(m.name); + } Ok(out) } } @@ -438,12 +494,30 @@ fn not_granted(name: &str, permission: Permission) -> EngineError { err(vectorcraft_plugins::Error::Output(format!("“{name}” wasn't granted `{p}`, which its output needs: nothing was changed"))) } +/// Is typing in progress whose text Real-time Drawing off left out of the document (not in a +/// preview's run)? A run prepared now isn't given that text. +pub fn unapplied_typing(s: &Session) -> bool { + !s.previewing && super::typing_in_progress(s) && s.unapplied_interaction_preview().is_some() +} + +/// Keeps typing in progress whose text Real-time Drawing off left out of the document +/// ([`super::settle_interaction`]) → whether there was any. A run prepared after it is given the +/// typed text; one prepared before it is prepared again. +pub fn keep_unapplied_typing(s: &mut Session) -> Result { + if !unapplied_typing(s) { + return Ok(false); + } + super::settle_interaction(s)?; + Ok(true) +} + /// `plugin.run`: runs filter `id` on `ids` (else the selected paths and compound paths) with its /// parameters and `_context` (what it keeps with the document included), and applies its output as /// one undo step ([`objects::apply_output`]; effect records as [`admit_effects`] admits them), with /// what it keeps with the document from now on: the output handed in for this very run when there -/// is one ([`FilterRun::hand_in`]), else the plug-in's, run now. → `{plugin, ids}`: what it made or -/// changed, which is then selected. +/// is one ([`FilterRun::hand_in`]), else the plug-in's, run now. → `{plugin, ids, notice?, +/// pluginName?}`: what it made or changed, which is then selected, and the output's `notice` once it +/// was applied, with the plug-in's name. fn run(s: &mut Session, p: &Value) -> Result { // An output handed in is for this run only (the app hands it in just before), whatever it does. let handed = s.plugin_output.take(); @@ -454,6 +528,8 @@ fn run(s: &mut Session, p: &Value) -> Result { let r = if super::plugin_call::settle(s)? { FilterRun::prepare(s, p)? } else { r }; return r.run_with_calls(s); } + // Typing Real-time Drawing off left out of the document is kept first, so the plug-in is given it. + let r = if keep_unapplied_typing(s)? { FilterRun::prepare(s, p)? } else { r }; // Handed in for this very run (the app ran it in the background), it is what running the // plug-in again would return. let handed = handed.filter(|h| (h.serial, &h.input, &h.params) == (r.plugin.serial(), &r.input, &r.params)); @@ -816,7 +892,7 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec { fields.push_str(own); } let params = format!( - "{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step, none when the run changes nothing → {{plugin, command, ids}}", + "{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step, none when the run changes nothing → {{plugin, command, ids, notice?, pluginName?}} (pluginName, the plug-in's name, comes with notice)", m.id, c.id ); let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); @@ -852,9 +928,9 @@ fn unrouted(_: &mut Session, _: &Value) -> Result { /// Runs plug-in command `id` (`plugin..`): a filter run of the plug-in on /// `ids` (else the selection) with the command's own parameters, checked before it runs, and /// `_context.command`, under the plug-in's permissions and budget, applied as one undo step named -/// after the command → `{plugin, command, ids}`. A run that fails (a trap, an exhausted budget, an -/// output it may not make) leaves the document as it was, and the error names the plug-in and the -/// command. +/// after the command → `{plugin, command, ids, notice?, pluginName?}`. A run that fails (a trap, an exhausted +/// budget, an output it may not make) leaves the document as it was, and the error names the +/// plug-in and the command. pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result { // An output handed in is for `plugin.run` alone. s.plugin_output = None; @@ -877,6 +953,13 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result }; return r.run_with_calls(s).map_err(failed); } + let r = match keep_unapplied_typing(s)? { + true => { + let (plugin, command) = command_of(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?; + FilterRun::prepare_with(s, plugin, Some(command), id, p)? + } + false => r, + }; let output = r.run().map_err(&failed)?; r.finish(s, &output).map_err(failed) } @@ -933,8 +1016,9 @@ pub(crate) fn admit_effects_for(cmd: &str, fx: &[Effect], n: &Node) -> std::resu /// Largest base64 payload `plugin.install` accepts (the module limit, encoded). const MAX_DATA_CHARS: usize = (32 << 20) / 3 * 4 + 4; -/// The `.wasm` extension plug-in files have (File › Open installs them). -pub const EXTS: &[&str] = &["wasm"]; +/// The extensions plug-in files have (File › Open installs them): a WebAssembly module, and a +/// JavaScript plug-in's manifest. +pub const EXTS: &[&str] = &["wasm", vectorcraft_plugins::js::PACKAGE_EXT]; /// The plug-in module command `c`'s params give, loaded and checked, and its bytes: `path` (a /// `.wasm` file) or `dataBase64` (the module, with `name` shown as its source). @@ -1314,12 +1398,23 @@ fn inspect(s: &mut Session, p: &Value) -> Result { }) } -/// The plug-in in the `.wasm` file `path`, and its module. +/// The plug-in in the `.wasm` file `path`, or in the `.vcplugin` manifest `path` and the `.js` file +/// it names, and its module: for a JavaScript plug-in, the manifest with the script's text +/// ([`registry::read_js_package`]). Under automation read roots the script must be inside them too. #[cfg(not(target_arch = "wasm32"))] fn load_path(path: &str) -> Result<(Plugin, Vec)> { crate::file_access::check_read(path).map_err(EngineError::Other)?; let limits = vectorcraft_plugins::Limits::default(); - let bytes = crate::store::read_capped(std::path::Path::new(path), limits.max_module_bytes as u64).map_err(EngineError::Other)?; + let file = std::path::Path::new(path); + let bytes = if registry::is_js_package(file) { + let allow = |script: &std::path::Path| match script.to_str() { + Some(script) => crate::file_access::check_read(script), + None => Err(format!("automation path rejected: {} isn't valid text", script.display())), + }; + registry::read_js_package(file, &allow).map_err(err)? + } else { + crate::store::read_capped(file, limits.max_module_bytes as u64).map_err(EngineError::Other)? + }; Ok((Plugin::load(&bytes, limits).map_err(err)?.with_source(path), bytes)) } @@ -1533,9 +1628,11 @@ fn start_folder(s: &Session, folder: &str, record: Option) -> FolderPending let allow = move |f: &std::path::Path| { scope.clone().run(|| match f.to_str() { Some(f) => crate::file_access::check_read(f), - // A lossy name would check another file than the one loaded. - None if crate::file_access::current().is_none() => Ok(()), - None => Err(format!("automation path rejected: {} isn't valid text", f.display())), + // A lossy name would check another file than the one loaded, so such a file loads only + // where no read is checked: without roots and outside a script's command. + None if crate::file_access::current().is_some() => Err(format!("automation path rejected: {} isn't valid text", f.display())), + None if crate::file_access::in_script_command() => Err(format!("Script file access denied: {} isn't valid text", f.display())), + None => Ok(()), }) }; // The modules start loading once the loads queued before them are done. @@ -1796,18 +1893,49 @@ fn remove(s: &mut Session, p: &Value) -> Result { let installed = registry::get(id).is_some(); // Settings and cache the store keeps for an id that isn't installed are deleted too. let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id); - // Installed again, it asks again. A grant that can't be removed still approves the module, and - // so may a grants file that can't be opened or read. One that is too large or doesn't hold a - // list approves nothing and doesn't stop the removal. - let forget = || s.store_grant_in(&turn, id, None) || !s.holds_plugin_grant(id); - // Its settings and cache are moved aside and its grant removed before anything is deleted: when - // either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove` - // tries again. + // A module stored for an id that isn't installed (one no grant covers is skipped at startup) + // counts as removed once its file is gone. + let module = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.holds_stored_plugin(id); + // An installed plug-in's stored module is deleted with its grant too, so that one that can't be + // deleted leaves the plug-in installed. Without a plug-in folder it has none. + let unstore = module || (installed && s.plugin_dir.is_some()); + // The grant the store keeps for an installed plug-in, which may differ from the one the session + // holds (an update whose module couldn't be stored): written back when its module can't be + // deleted, so that the stored module still loads at the next launch. + let kept_grant = if installed { s.stored_plugin_grant(id) } else { None }; + let module_left = std::cell::Cell::new(false); + let cant_delete = || format!("plugin.remove: can't delete {}", s.stored_plugin_file(id).unwrap_or_default()); + // Installed again, it asks again. A grant that can't be removed may still approve the module, and + // so may a grants file that can't be opened or read, or a signed copy of the file put back when + // the generation couldn't be raised (the key store can't be reached). Without a plug-in folder + // nothing keeps a grant. The stored module is deleted next, while its settings and cache can + // still be moved back. + let forget = || { + if !s.store_grant_in(&turn, id, None) && s.plugin_dir.is_some() { + return false; + } + let deleted = !unstore || s.unstore_plugin(&turn, id); + if !deleted + && let Some(grant) = kept_grant.clone() + && !s.store_grant_in(&turn, id, Some(grant)) + { + log::warn!("plugin.remove: can't keep the grant of {id}, whose module stays: it asks again at the next launch"); + } + module_left.set(!deleted); + deleted + }; + // Its settings and cache are moved aside, its grant removed and its stored module deleted before + // anything else is deleted: when one of them can't be done, the settings and cache are moved back, + // the plug-in stays installed, as it was, and a second `plugin.remove` tries again. An invalid id + // names no grant and no module. let failed = if installed || stored { s.remove_plugin_storage(&turn, id, forget).err().map(|e| e.to_string()) - } else { + } else if vectorcraft_plugins::manifest::valid_id(id) { (!forget()).then(|| crate::store::GRANT_NOT_REMOVED.to_string()) + } else { + None }; + let failed = failed.map(|e| if module_left.get() && e == crate::store::GRANT_NOT_REMOVED { cant_delete() } else { e }); if let Some(e) = failed { if installed { s.attach_plugin_storage(&turn, id); @@ -1815,8 +1943,10 @@ fn remove(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other(e)); } registry::revoke(id); - s.unstore_plugin(&turn, id); - if !stored && (!installed || !registry::remove(id)) { + if !s.unstore_plugin(&turn, id) && module { + return Err(EngineError::Other(cant_delete())); + } + if !stored && !module && (!installed || !registry::remove(id)) { return Err(err(vectorcraft_plugins::Error::NotFound(id.into()))); } Ok(json!({"removed": id})) @@ -1848,7 +1978,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", always, list ), @@ -1866,7 +1996,7 @@ pub fn specs() -> Vec { "Run Plug-in", [], None, - "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}", + "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given (an image may leave out opacity), or the run is refused and nothing changes. A filter at api 3 whose manifest lists some of those kinds in writes (with doc.write) may return an object of such a kind with only the fields it changes: name and transform (6 numbers within ±4,000,000 that don't flatten it), type's text.runs ({text, style, inline?} with the native character attributes; inline graphics stay as they were; at most 4,096 runs, 4,096 paragraphs and 256 KiB of text; every number of every run's style in the range charStyle.new takes, fills and strokes with only the keys their type reads, and a style of its own needs a font family) and text.paragraphs (one style per paragraph, also when given as they were next to changed runs, each number in the range paraStyle.new takes, a custom Kinsoku set only one of the document's by name), an image's opacity (0 to 1), an instance's symbolId (a symbol in the document); any other field changed, or a value out of range, refuses the run naming the object and the field, and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids, notice?, pluginName?} (notice: the text the output reports in its notice key once applied, escaped and cut at 200 characters; pluginName: the plug-in's name, with it)", has_doc, run ), @@ -1875,7 +2005,7 @@ pub fn specs() -> Vec { "Install Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", + "{path: a .wasm file or a JavaScript plug-in's .vcplugin manifest (read with the .js file its script names) (desktop) | dataBase64: the module or a JavaScript plug-in as one JSON object (its manifest, with the script's text in source) (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a plug-in for this session (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", always, install ), @@ -1884,7 +2014,7 @@ pub fn specs() -> Vec { "Inspect Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", + "{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", always, inspect ), @@ -1893,7 +2023,7 @@ pub fn specs() -> Vec { "Remove Plug-in", [], None, - "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}", + "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, or its stored module can't be deleted, the command fails and the plug-in stays installed, as it does when the system key store can't be reached to make sure no earlier copy of grants.json grants it again; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it and the module stored for it that didn't load, and reports it removed; it waits while another window or process changes the plug-in store, and when the store's disabled.lock can't be locked, the command fails and nothing is removed → {removed}", always, remove ), @@ -1911,7 +2041,7 @@ pub fn specs() -> Vec { "Reload Plug-ins", ["Object", "Plug-ins"], None, - "{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm files past the first 1,000, not tried}", + "{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm and *.vcplugin in it, the first 1,000 by file name (desktop; a bad module, one that isn't a regular file, and one disabled with plugin.setEnabled, is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted this very module, its bytes included; an error in Safe Mode) → {folder, loaded: [id], failed: [{file, error}], leftOut: the count of *.wasm and *.vcplugin files past the first 1,000, not tried}", always, reload ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index ec7d3ac989..3d5723b7d3 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -43,6 +43,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.packaging.check", "addon.packaging.fold", "addon.packaging.roles", + "addon.packaging.setFoldAngle", "addon.packaging.setRole", "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", @@ -243,6 +244,7 @@ pub(super) const ALLOWED: &[&str] = &[ "layer.releaseToLayersBuild", "layer.reverse", "layer.selectAll", + "layer.selectHighlighted", "layer.setCurrent", "layer.setProps", "layer.showAll", @@ -402,6 +404,11 @@ pub(super) const ALLOWED: &[&str] = &[ "object.slice.release", "object.slice.select", "object.slice.setRect", + "object.tag.add", + "object.tag.remove", + "object.tag.removeAll", + "object.tag.set", + "object.tags", "object.textWrap.make", "object.textWrap.options", "object.textWrap.release", @@ -741,6 +748,7 @@ pub(super) const DENIED: &[&str] = &[ "addon.cleanup.splitText", "addon.pathtools.movePointsTogether", "addon.pen.nextSegment", + "color.contrast", "effect.refreshDeferred", "graphicStyle.setOptions", "object.blend.createSpine", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 86c22d2776..27d38e158f 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -146,6 +146,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("showToolTips", "General", "Options", "Show Tool Tips", bool), p!("showToolCards", "General", "Options", "Show Tool Cards", bool), p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool), + p!("runStartupScripts", "General", "Options", "Run Startup Scripts", bool), p!("antiAliasedArtwork", "General", "Options", "Anti-aliased Artwork", bool), p!("selectSameTintPercent", "General", "Options", "Select Same Tint %", bool), p!("showHomeScreen", "General", "Options", "Show The Home Screen When No Documents Are Open", bool), @@ -710,6 +711,12 @@ impl Prefs { } impl Session { + /// Take the categories `prefs.reset` reset since the last call, each once, with `None` for a + /// reset of every category. A frontend resets the settings it keeps itself in them. + pub fn take_prefs_resets(&mut self) -> Vec> { + std::mem::take(&mut self.prefs_resets) + } + /// Replace the preferences and push the ones with engine-side consumers into open documents /// and the renderer (grid, history depth, render threads). pub fn apply_prefs(&mut self, mut p: Prefs) { @@ -817,7 +824,7 @@ pub fn specs() -> Vec { always, set ), - cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset), + cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?: string} reset one category (or everything, with category left out or null) to defaults; an unknown category or one that is not a string is an error", always, reset), cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference; under automation read roots a folder preference's value outside them is null", always, list), cmd!( query "prefs.export", @@ -1000,15 +1007,17 @@ fn set(s: &mut Session, p: &Value) -> Result { } fn reset(s: &mut Session, p: &Value) -> Result { - let cat = str_param(p, "category"); - if let Some(c) = cat - && !PREF_CATEGORIES.iter().any(|x| x.eq_ignore_ascii_case(c)) - { - return Err(bad("prefs.reset", format!("unknown category `{c}`"))); - } + let cat = text_param(p, "category", "prefs.reset")?; + let known = |c: &str| { + PREF_CATEGORIES.iter().copied().find(|x| x.eq_ignore_ascii_case(c)).ok_or_else(|| bad("prefs.reset", format!("unknown category `{c}`"))) + }; + let category = cat.map(known).transpose()?; let mut next = s.prefs.clone(); next.reset(cat); s.apply_prefs(next); + if !s.prefs_resets.contains(&category) { + s.prefs_resets.push(category); + } Ok(json!({ "prefs": shown_prefs(&s.prefs) })) } diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 8a68798aed..efbdb10a20 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only), installed?: bool} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; shapes none of those fonts match are then compared in the same way (the tolerance and the splitting included) with the installed fonts not loaded yet, unless installed is false (true, omitted or null: compared): their files are read smallest first, one at a time, until each such shape matches the fonts read, leaving out files over 256 MiB and the files and faces past 2 GiB read or 500,000 glyphs drawn in all, and a font whose glyphs match such a shape, or complete the glyphs of a split one with the fonts found before it, is loaded; a plain shape (one contour of up to four straight edges, such as a rectangle) starts no such reading and matches only a font the other shapes found; a cancel stops between files; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out), installed: {read (installed faces compared), skipped (installed faces those limits left out)}}; an error, with no unmatched list, when no shape becomes type, when tolerance is not a number from 0 to 0.05, or when installed is not true, false or null", has_selected_path, retype )] @@ -56,6 +56,10 @@ pub fn specs() -> Vec { #[path = "retype_fonts.rs"] pub(super) mod fonts; +#[path = "retype_installed.rs"] +mod installed; + +pub use installed::{RetypeFound, RetypeRun, RetypeSearch}; /// A shape to match: a path or compound path, in document space. struct Piece { @@ -141,7 +145,8 @@ fn type_can_paint(ap: &Appearance) -> bool { ap.is_basic() && ap.stroke().is_none_or(|s| s.start_arrow.is_none() && s.end_arrow.is_none() && s.profile.is_none() && s.brush.is_none()) } -/// The faces to match against: the families in `fonts`, the document's fonts, then every loaded face. +/// The faces to match against: the families in `fonts`, the document's fonts, the faces earlier +/// searches of the installed fonts loaded ([`installed::found`]), then every other loaded face. fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec> { let mut families: Vec = fonts.iter().take(MAX_FONT_PARAMS).cloned().collect(); d.walk(|n| { @@ -168,7 +173,8 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec= cap { break; } @@ -1357,6 +1363,48 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option { }) } +/// `type.retype`'s `fonts` param: the family names it lists. +fn fonts_param(p: &Value) -> Result> { + const C: &str = "type.retype"; + match p.get("fonts") { + None => Ok(vec![]), + Some(Value::Array(a)) => { + a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect() + } + Some(_) => Err(bad(C, "fonts must be a list of family names")), + } +} + +/// `type.retype`'s `tolerance` param: 0 (exact matches only) when omitted. +fn tolerance_param(p: &Value) -> Result { + const C: &str = "type.retype"; + match p.get("tolerance") { + None => Ok(0.0), + Some(v) => match v.as_f64() { + Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => Ok(t), + _ => Err(bad(C, "tolerance must be a number from 0 to 0.05")), + }, + } +} + +/// The shapes of the selected objects, in paint order, and whether shapes past the limits were +/// left out; an error when the selection holds none. +fn selected_pieces(s: &Session) -> Result<(Vec, bool)> { + let roots = selected_roots(s)?; + let d = &s.doc()?.doc; + let mut pieces = vec![]; + let (mut barrier, mut truncated) = (true, false); + for r in &roots { + if let Some(n) = d.node(*r) { + collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces); + } + } + if pieces.is_empty() { + return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); + } + Ok((pieces, truncated)) +} + /// The lines, by index, to drop so that no shape of several glyphs becomes type in part: each line /// is given by the shapes it sets, one per glyph, and `glyphs_of` says how many glyphs a shape /// is. A line setting a glyph of a shape not all of whose glyphs are set goes, and then so do the @@ -1675,26 +1723,70 @@ fn lookup_keys<'a>( (wanted, near_wanted) } +/// The candidates of `path` in `indexes`: the exact ones of every index (for a `part` of a split +/// shape, either way round), or, when there are none and `near` is set, the near ones within +/// `tolerance`. With `fill` (`Some(nonzero)`, for a shape with a visible fill), only glyphs that +/// paint the area `path` paints under that rule are kept. +fn candidates(indexes: &[&RetypeIndex], path: &BezPath, part: bool, near: bool, fill: Option, tolerance: f64) -> Vec { + let painted = |index: &RetypeIndex, ms: Vec, tol: f64| -> Vec { + match fill { + Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(), + None => ms, + } + }; + let exact: Vec = + indexes.iter().flat_map(|ix| painted(ix, if part { ix.matches_either_way(path) } else { ix.all_matches(path) }, 0.0)).collect(); + if exact.is_empty() && near { indexes.iter().flat_map(|ix| painted(ix, ix.near_matches(path, tolerance), tolerance)).collect() } else { exact } +} + +/// The parts of the shape `path` ([`parts`]: the whole shape, or the glyphs of its contour +/// `groups`), each with its [`candidates`] in `indexes`; empty when it matches nothing. `fill` is +/// as [`candidates`] takes it, and `once` is set when the shape paints its overlaps once, as +/// several objects would ([`paints_once`]). +fn shape_parts(path: &BezPath, groups: &[BezPath], fill: Option, once: bool, indexes: &[&RetypeIndex], tolerance: f64) -> Vec> { + let find = |p: &BezPath, part: bool, near: bool| candidates(indexes, p, part, near, fill, tolerance); + // Parts that all match exactly are checked at tolerance 0, in the near phase as in the exact + // one; only a part that matches nearly brings the tolerance in. The glyphs of a split may + // become separate objects: when the shape does not paint its overlaps as several objects + // would (translucent, another blend, a gradient or pattern fill, a stroke), its parts must not + // overlap, which the parts read by the even-odd rule against them all joined show. + let together = |runs: &[BezPath], near: bool| { + if fill.is_none() && once { + return true; + } + let nearly = near && runs.iter().any(|r| find(r, true, false).is_empty()); + let tol = if nearly { tolerance } else { 0.0 }; + fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(path, runs, nz, tol)) + && (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol)) + }; + parts(path, groups, &find, &together) +} + +/// Each of `pieces`' parts, as [`shape_parts`] finds them in `indexes`: none for a piece that +/// keeps its outline or matches nothing. `groups` holds each piece's contour groups. +fn match_pieces(pieces: &[Piece], groups: &[Vec], indexes: &[&RetypeIndex], tolerance: f64) -> Vec>> { + pieces + .iter() + .zip(groups) + .map(|(pc, g)| { + if pc.keeps_outline { + return vec![]; + } + shape_parts(&pc.path, g, pc.filled.then_some(pc.nonzero), paints_once(pc.opacity, pc.blend, &pc.appearance), indexes, tolerance) + }) + .collect() +} + fn retype(s: &mut Session, p: &Value) -> Result { const C: &str = "type.retype"; - let fonts: Vec = match p.get("fonts") { - None => vec![], - Some(Value::Array(a)) => { - a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::>()? - } - Some(_) => return Err(bad(C, "fonts must be a list of family names")), - }; - let tolerance = match p.get("tolerance") { - None => 0.0, - Some(v) => match v.as_f64() { - Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => t, - _ => return Err(bad(C, "tolerance must be a number from 0 to 0.05")), - }, - }; + let fonts = fonts_param(p)?; + let tolerance = tolerance_param(p)?; + let search_installed = installed::wanted(C, p)?; + let handed = installed::handed(s); let roots = selected_roots(s)?; let db = FontDb::global(); let system_layout = s.doc()?.doc.setup.system_layout; - let (lines, unmatched, truncated) = { + let (lines, unmatched, truncated, installed) = { let d = &s.doc()?.doc; let mut pieces = vec![]; let mut truncated = false; @@ -1725,52 +1817,69 @@ fn retype(s: &mut Session, p: &Value) -> Result { let (wanted, near_wanted) = lookup_keys(pieces.iter().zip(&groups).filter(|(pc, _)| !pc.keeps_outline).map(|(pc, g)| (&pc.path, g.as_slice())), tolerance); // Nothing to match (every shape stays an outline): no font is read. - let index = if wanted.is_empty() && near_wanted.is_empty() { - RetypeIndex::default() - } else { - RetypeIndex::build_near(db, candidate_faces(db, d, &fonts), &wanted, &near_wanted) + let keyed = !(wanted.is_empty() && near_wanted.is_empty()); + let cands = if keyed { candidate_faces(db, d, &fonts) } else { vec![] }; + let mut compared: Vec = cands.iter().map(|f| f.id()).collect(); + let build = |faces: Vec>| { + if keyed { RetypeIndex::build_near(db, faces, &wanted, &near_wanted) } else { RetypeIndex::default() } }; - // Exact matches first; near ones, when allowed, only for a path with none. - // With a visible fill, a glyph is kept only when it paints the area the shape paints under - // the shape's fill rule (`fill` is `Some(nonzero)`). - let find = |path: &BezPath, part: bool, near: bool, fill: Option| { - let painted = |ms: Vec, tol: f64| -> Vec { - match fill { - Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(), - None => ms, - } - }; - let exact = painted(if part { index.matches_either_way(path) } else { index.all_matches(path) }, 0.0); - if exact.is_empty() && near { painted(index.near_matches(path, tolerance), tolerance) } else { exact } - }; - // Each shape's parts (one, unless it holds several glyphs), each with its candidates. - let found: Vec>> = pieces - .iter() - .zip(&groups) - .map(|(pc, g)| { - if pc.keeps_outline { - return vec![]; - } - let fill = pc.filled.then_some(pc.nonzero); - // Parts that all match exactly are checked at tolerance 0, in the near phase as in - // the exact one; only a part that matches nearly brings the tolerance in. - // The glyphs of a split may become separate objects: when the shape does not paint - // its overlaps as several objects would (translucent, another blend, a gradient or - // pattern fill, a stroke), its parts must not overlap, which the parts read by the - // even-odd rule against them all joined show. - let once = paints_once(pc.opacity, pc.blend, &pc.appearance); - let together = |runs: &[BezPath], near: bool| { - if fill.is_none() && once { - return true; - } - let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty()); - let tol = if nearly { tolerance } else { 0.0 }; - fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tol)) - && (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol)) + let index = build(cands.clone()); + // Exact matches first; near ones, when allowed, only for a path with none. With a visible + // fill, a glyph is kept only when it paints the area the shape paints under the shape's + // fill rule. Each shape's parts (one, unless it holds several glyphs), each with its + // candidates. + let mut found = match_pieces(&pieces, &groups, &[&index], tolerance); + // Shapes no face matched are compared with the other loaded faces, then with the installed + // fonts not loaded yet; or with what a search made off the UI thread found for them. + let left = left_shapes(&pieces, &groups, &found); + // A split shape's glyphs may be spread over the candidates and the other faces. Near + // matching spends an index's comparison budget, so with a tolerance the candidates are + // indexed again for each search that has a split shape to look for. + let again = |needed: bool| (needed && tolerance > 0.0).then(|| build(cands.clone())); + let (more, installed) = match handed { + Some(handed) => { + let mut more = handed.faces.clone(); + compared.extend(handed.faces.iter().map(|f| f.id())); + // The shapes still left are compared with the loaded faces the search did not + // compare: none, unless a face was loaded after it looked. + compared.extend(handed.scanned.iter().copied()); + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + more.extend(installed::loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?.0); + (more, handed) + } + None => { + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let (mut more, done, kept) = installed::loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?; + let left: Vec = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect(); + let installed = if search_installed { + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let kept: Vec = if tolerance > 0.0 { kept.iter().map(|ix| build(ix.faces().to_vec())).collect() } else { kept }; + let beside: Vec<&RetypeIndex> = std::iter::once(fresh.as_ref().unwrap_or(&index)).chain(&kept).collect(); + installed::search_beside(db, &left, &beside, tolerance, false)? + } else { + installed::Installed::default() }; - parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together) - }) - .collect(); + more.extend(installed.faces.iter().cloned()); + (more, installed) + } + }; + // The faces found join the candidates, the way the loaded ones are matched (near matches + // and split shapes included), and every shape is matched again with them all, so a shape + // that matched already can take the face its neighbors found. + let mut extra: Vec> = vec![]; + for f in more { + if !cands.iter().chain(&extra).any(|k| k.id() == f.id()) { + extra.push(f); + } + } + if !extra.is_empty() { + // Near matching spends an index's comparison budget, so with a tolerance the + // candidates are indexed again for this pass. + let first = if tolerance > 0.0 { build(cands) } else { index }; + let others: Vec = extra.chunks(vectorcraft_text::retype::MAX_FACES).map(|g| build(g.to_vec())).collect(); + let all: Vec<&RetypeIndex> = std::iter::once(&first).chain(&others).collect(); + found = match_pieces(&pieces, &groups, &all, tolerance); + } // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. Among faces that as many shapes match, the one whose glyphs fit // them closest in all (the least leftover distance summed over those shapes), so every @@ -1916,7 +2025,7 @@ fn retype(s: &mut Session, p: &Value) -> Result { // Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room // for small blocks. let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256); - (blocks(lines, follows, system_layout, &mut budget), unmatched, truncated) + (blocks(lines, follows, system_layout, &mut budget), unmatched, truncated, installed) }; if lines.is_empty() { return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len()))); @@ -2050,9 +2159,27 @@ fn retype(s: &mut Session, p: &Value) -> Result { .collect::>(), "unmatched": unmatched.iter().map(|i| i.0).collect::>(), "truncated": truncated, + "installed": installed.json(), })) } +/// The shapes of `pieces` that may become type and that `found` holds no part for, each with its +/// contour groups from `groups`. +fn left_shapes<'a>(pieces: &'a [Piece], groups: &'a [Vec], found: &[Vec>]) -> Vec> { + pieces + .iter() + .zip(groups) + .zip(found) + .filter(|((pc, _), parts)| !pc.keeps_outline && parts.is_empty()) + .map(|((pc, g), _)| installed::Sought { + path: &pc.path, + groups: g, + fill: pc.filled.then_some(pc.nonzero), + once: paints_once(pc.opacity, pc.blend, &pc.appearance), + }) + .collect() +} + #[cfg(test)] #[path = "retype_tests.rs"] mod tests; diff --git a/crates/engine/src/cmd/retype_fonts.rs b/crates/engine/src/cmd/retype_fonts.rs index a901ac7e12..e0af549da6 100644 --- a/crates/engine/src/cmd/retype_fonts.rs +++ b/crates/engine/src/cmd/retype_fonts.rs @@ -3,22 +3,25 @@ //! (, //! ). //! The panel lists ten fonts and five more on request. Each selected glyph shape is compared with -//! the glyphs of up to 96 loaded fonts, those of the document's live type first, by the same -//! matching as `type.retype` (exact matches only). Of two versions of one font, only the version its +//! the glyphs of up to 96 loaded fonts, those of the document's live type first, and of the +//! installed fonts not loaded yet (`retype_installed.rs`), by the same matching as `type.retype` +//! (exact matches only). Of two versions of one font, only the version its //! family and style name gives is compared. The order is VectorCraft's own: a font ranks by how many -//! of the shapes it matches, then by how closely, on average, and then by name. The query changes -//! nothing. +//! of the shapes it matches, then by how closely, on average, and then by name. The query does not +//! change the document; the installed fonts that match are loaded. use std::collections::BTreeSet; use std::sync::Arc; +use kurbo::BezPath; use serde_json::{Value, json}; -use vectorcraft_text::FontDb; +use vectorcraft_doc::Document; use vectorcraft_text::retype::{RetypeIndex, shape_key}; +use vectorcraft_text::{FontDb, FontFace}; -use super::super::edit::selected_roots; -use super::super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path}; -use super::{candidate_faces, collect}; +use super::super::{CommandSpec, Result, Session, bad, cmd, has_selected_path}; +use super::installed::Installed; +use super::{candidate_faces, selected_pieces}; pub(in crate::cmd) fn specs() -> Vec { vec![cmd!( @@ -26,7 +29,7 @@ pub(in crate::cmd) fn specs() -> Vec { "Find Matching Fonts", [], None, - "{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed; of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error", + "{count?: 1..96 (default 10), installed?: bool} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed, and, unless installed is false (true, omitted or null: compared), with the installed fonts not loaded yet, within type.retype's limits on reading them (every file within them is read, and the fonts that match are loaded while the list holds fewer than 96 fonts, loaded ones included); of two versions of a font, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out), installed: {read, skipped} (as type.retype reports them)}; a count that is not a whole number from 1 to 96, or an installed that is not true, false or null, is an error", has_selected_path, retype_fonts )] @@ -38,7 +41,7 @@ pub(super) const DEFAULT_COUNT: usize = 10; pub(super) const MAX_COUNT: usize = vectorcraft_text::retype::MAX_FACES; /// One font that matched some of the shapes. -struct Ranked { +pub(super) struct Ranked { face: Arc, /// How many shapes it matched. matched: usize, @@ -49,62 +52,99 @@ struct Ranked { } impl Ranked { + /// The font. + pub(super) fn face(&self) -> &Arc { + &self.face + } + fn mean(&self) -> f64 { self.residual / self.matched.max(1) as f64 } } -pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result { - retype_fonts_in(s, p, FontDb::global()) -} - -/// [`retype_fonts`] with the fonts of `db`. -fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { - const C: &str = "type.retypeFonts"; - let count = match p.get("count") { - None | Some(Value::Null) => DEFAULT_COUNT, +/// The `count` param: how many fonts to list. +pub(super) fn count_param(p: &Value) -> Result { + match p.get("count") { + None | Some(Value::Null) => Ok(DEFAULT_COUNT), Some(v) => v .as_u64() .and_then(|n| usize::try_from(n).ok()) .filter(|n| (1..=MAX_COUNT).contains(n)) - .ok_or_else(|| bad(C, "`count` must be a whole number from 1 to 96"))?, - }; - let roots = selected_roots(s)?; - let d = &s.doc()?.doc; - let mut pieces = vec![]; - let (mut barrier, mut truncated) = (true, false); - for r in &roots { - if let Some(n) = d.node(*r) { - collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces); - } + .ok_or_else(|| bad("type.retypeFonts", "`count` must be a whole number from 1 to 96")), } - if pieces.is_empty() { - return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); - } - // Only glyphs with a selected shape's key (segments per contour) can match one. - let wanted: BTreeSet = pieces.iter().filter_map(|pc| shape_key(&pc.path)).collect(); - // A font is chosen by its family and style, which set the version the name gives: of two - // versions of one font, only that one is compared. The other versions do not take the places - // of fonts loaded after them. - let by_name = |f: &Arc| db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id()); - let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(by_name).collect(); +} + +/// Is `f` the version of its font that its family and style name gives? A font is chosen by its +/// family and style, which set that version: of two versions of one font, only that one is +/// compared, and the other versions do not take the places of fonts loaded after them. +fn by_name(db: &FontDb, f: &FontFace) -> bool { + db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id()) +} + +/// The loaded faces the list compares: those of the document's live type first, then the other +/// loaded faces, each the version its name gives, at most [`MAX_COUNT`]. +pub(super) fn listed_faces(db: &FontDb, d: &Document) -> Vec> { + let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(|f| by_name(db, f)).collect(); for f in db.loaded_faces() { - if faces.len() >= vectorcraft_text::retype::MAX_FACES { + if faces.len() >= MAX_COUNT { break; } - if by_name(&f) && !faces.iter().any(|k| k.id() == f.id()) { + if by_name(db, &f) && !faces.iter().any(|k| k.id() == f.id()) { faces.push(f); } } + faces +} + +/// The fonts of `faces` whose glyphs match `shapes`, unranked, and with `search_installed` those of +/// the installed fonts not loaded yet, for the places left of [`MAX_COUNT`] (loading the ones that +/// match), with what that search read. With `handed` (what a search made off the UI thread found, +/// [`super::installed::RetypeFound`]) its faces are ranked instead, and the installed fonts are not +/// read again. +pub(super) fn rank_fonts( + db: &FontDb, + faces: Vec>, + shapes: &[&BezPath], + search_installed: bool, + handed: Option, +) -> Result<(Vec, Installed)> { + // Only glyphs with a selected shape's key (segments per contour) can match one. + let wanted: BTreeSet = shapes.iter().filter_map(|s| shape_key(s)).collect(); // No shape has a key: no font is read. let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, faces, &wanted) }; - // A shape's paint does not change which glyph it is: shapes that would stay outlines count too. let mut ranked: Vec = vec![]; - for pc in &pieces { + rank(&index, shapes, &mut ranked); + // The installed fonts not loaded yet: those whose glyphs match a shape, of the version their + // family and style name gives, up to 96 fonts listed in all. A font that matches only as + // combining marks is not listed, so it takes no place. + let room = MAX_COUNT.saturating_sub(ranked.iter().filter(|r| r.character).count()); + let found = if let Some(handed) = handed { + handed + } else if !search_installed { + Installed::default() + } else if room == 0 { + // The list is full: the installed faces a search would compare count as skipped, none + // when no shape would start one. + let skipped = if super::installed::starts_search(shapes) { db.unloaded_installed_faces().len() } else { 0 }; + Installed { skipped, ..Default::default() } + } else { + super::installed::search_listed(db, shapes, room, &|f| by_name(db, f))? + }; + // A face found earlier (handed in) may be loaded and ranked already: it counts once. + let more: Vec<_> = found.faces.iter().filter(|f| !ranked.iter().any(|r| r.face.id() == f.id())).cloned().collect(); + if !more.is_empty() { + rank(&RetypeIndex::build(db, more, &wanted), shapes, &mut ranked); + } + Ok((ranked, found)) +} + +/// Adds to `ranked` the fonts of `index` that match `shapes`. +fn rank(index: &RetypeIndex, shapes: &[&BezPath], ranked: &mut Vec) { + for shape in shapes { // A shape can fit several glyphs or poses of one font: it counts once for the font, at its // closest fit. - let mut best: Vec<(Arc, f64, bool)> = vec![]; - for m in index.all_matches(&pc.path) { + let mut best: Vec<(Arc, f64, bool)> = vec![]; + for m in index.all_matches(shape) { let character = !vectorcraft_text::retype::is_combining_mark(m.ch); match best.iter_mut().find(|(f, _, _)| f.id() == m.face.id()) { Some(b) => { @@ -125,6 +165,23 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { } } } +} + +pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result { + retype_fonts_in(s, p, FontDb::global()) +} + +/// [`retype_fonts`] with the fonts of `db`. +fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { + const C: &str = "type.retypeFonts"; + let count = count_param(p)?; + let search_installed = super::installed::wanted(C, p)?; + let handed = super::installed::handed(s); + let (pieces, truncated) = selected_pieces(s)?; + let d = &s.doc()?.doc; + // A shape's paint does not change which glyph it is: shapes that would stay outlines count too. + let shapes: Vec<&BezPath> = pieces.iter().map(|pc| &pc.path).collect(); + let (mut ranked, found) = rank_fonts(db, listed_faces(db, d), &shapes, search_installed, handed)?; // A font whose glyphs match the shapes only as combining marks would retype none of them, as // type.retype starts no line with a mark: it is not listed. ranked.retain(|r| r.character); @@ -143,6 +200,7 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { "shapes": pieces.len(), "more": more, "truncated": truncated, + "installed": found.json(), })) } diff --git a/crates/engine/src/cmd/retype_fonts_tests.rs b/crates/engine/src/cmd/retype_fonts_tests.rs index ac7723d82a..60218b8b4a 100644 --- a/crates/engine/src/cmd/retype_fonts_tests.rs +++ b/crates/engine/src/cmd/retype_fonts_tests.rs @@ -99,7 +99,7 @@ fn shapes_that_are_no_glyph_list_no_font() { let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [rect]})).unwrap(); let r = query(&mut s, json!({}), bundled()); - assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false})); + assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}})); // Live type alone holds no shape to compare. let t = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "live"})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [t]})).unwrap(); @@ -113,7 +113,7 @@ fn a_font_that_matches_only_combining_marks_is_not_listed() { let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let r = query(&mut s, json!({}), bundled()); - assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false})); + assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false, "installed": {"read": 0, "skipped": 0}})); // After a base, the mark counts with it. let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); @@ -161,6 +161,64 @@ fn of_two_versions_only_the_one_the_name_gives_is_listed() { assert_eq!(names(&r).iter().filter(|f| f.0 == FAMILY).count(), 1, "version 1 matches and is listed once: {r}"); } +#[test] +fn installed_fonts_not_loaded_are_ranked_too_unless_left_out() { + use vectorcraft_text::test_fonts::named_copy; + let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed"); + let file = dir.join("RetypeListed-Regular.ttf"); + std::fs::write(&file, named_copy(true, ("Retype Listed", "Regular", "Version 1.000", "RetypeListed-Regular")).unwrap()).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let mut s = session(); + let inter = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Kgw", "size": 40, "font": "Inter", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [inter]})).unwrap(); + // Left out: the installed copy is not read, and stays unloaded. + let r = query(&mut s, json!({"count": 96, "installed": false}), &db); + assert!(!names(&r).iter().any(|f| f.0 == "Retype Listed"), "{r}"); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed")); + // Compared: the copy of Inter matches every shape, as Inter does, and is loaded. + let r = query(&mut s, json!({"count": 96}), &db); + let fonts = names(&r); + assert!(fonts.contains(&("Retype Listed".to_string(), "Regular".to_string(), 3)), "{r}"); + assert!(fonts.contains(&("Inter".to_string(), "Regular".to_string(), 3)), "{r}"); + assert_eq!(r["installed"], json!({"read": 1, "skipped": 0}), "{r}"); + assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Retype Listed")); +} + +#[test] +fn installed_fonts_fill_the_list_up_to_96_fonts_in_all() { + use vectorcraft_text::test_fonts::named_copy; + let copy = |family: &str| { + let postscript = format!("{}-Regular", family.replace(' ', "")); + (named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap(), postscript) + }; + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rg", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + // Loaded copies that match fill most of the list. + let loaded = FontDb::with_font_dirs(vec![]); + for i in 0..super::MAX_COUNT { + loaded.add_font(copy(&format!("Fullcopy {i:02}")).0); + } + let listed = names(&query(&mut s, json!({"count": 96, "installed": false}), &loaded)).len(); + assert!(listed < super::MAX_COUNT, "{listed}"); + // Installed copies, two more than the places left. + let dir = vectorcraft_testkit::temp_dir("retype-fonts-installed-full"); + for i in 0..super::MAX_COUNT - listed + 2 { + let (data, postscript) = copy(&format!("Installed {i:02}")); + std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir]); + for i in 0..super::MAX_COUNT { + db.add_font(copy(&format!("Fullcopy {i:02}")).0); + } + let r = query(&mut s, json!({"count": 96}), &db); + assert_eq!(names(&r).len(), super::MAX_COUNT, "the installed copies fill the places left: {r}"); + assert_eq!(r["more"], json!(false), "no font past the list is found: {r}"); + assert_eq!(r["installed"]["skipped"], json!(2), "{r}"); + assert_eq!(db.unloaded_installed_faces().len(), 2, "the two past the list stay unloaded"); +} + #[test] fn shapes_that_stay_outlines_still_name_their_font() { // A glyph with paint type cannot take (two fills) is not retyped, but it is still that font's glyph. diff --git a/crates/engine/src/cmd/retype_installed.rs b/crates/engine/src/cmd/retype_installed.rs new file mode 100644 index 0000000000..4c3aeff0b9 --- /dev/null +++ b/crates/engine/src/cmd/retype_installed.rs @@ -0,0 +1,773 @@ +//! Retype's installed fonts: the faces of installed fonts that nothing has loaded yet are +//! candidates too, as the fonts on the device are among the sources Retype suggests fonts from +//! (). +//! Each font file is read for the search and let go; a face whose glyphs match a shape is loaded +//! as it was read, without the family's other files. Files are read smallest first, within a budget +//! of bytes read and glyphs drawn, and the search stops between files when it is canceled. The app +//! runs it off the UI thread ([`RetypeRun`]), with a Cancel. A face read is matched as a loaded one +//! is: with Retype's tolerance, near matches count, and a compound path of several glyphs counts +//! when every glyph it splits into matches, in one face or in several. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use kurbo::BezPath; +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId}; +use vectorcraft_text::retype::{MAX_FACES, NearKey, RetypeIndex, encoded_glyphs, is_plain, shape_key}; +use vectorcraft_text::{FontDb, FontFace}; + +use super::super::{EngineError, Result, Session, bad}; + +/// How much one search reads. +#[derive(Clone, Copy)] +struct Limits { + /// Font files (a suitcase font's resource fork) longer than this are not read. + file: u64, + /// The bytes of font files read, in all. + read: u64, + /// The glyphs of installed faces drawn, in all, to tell which can match a shape. + glyphs: usize, + /// The faces found: the faces after the last one found are not compared. + faces: usize, +} + +const LIMITS: Limits = Limits { file: 256 << 20, read: 2 << 30, glyphs: 500_000, faces: MAX_FACES }; + +/// The `installed` param: whether to look in the installed fonts (default true). +pub(super) fn wanted(cmd: &str, p: &Value) -> Result { + match p.get("installed") { + None | Some(Value::Null) => Ok(true), + Some(Value::Bool(b)) => Ok(*b), + Some(_) => Err(bad(cmd, "`installed` must be true, false or null")), + } +} + +/// What a search of the installed fonts found and read. +#[derive(Default)] +pub(super) struct Installed { + /// The faces whose glyphs match a shape, loaded now, in the order they were read. + pub(super) faces: Vec>, + /// Faces read and compared. + pub(super) read: usize, + /// Faces left out by the limits ([`LIMITS`]). + pub(super) skipped: usize, + /// For a search made away from its command, the ids of the loaded faces it compared: the + /// command does not compare them again. + pub(super) scanned: Vec, +} + +impl Installed { + /// As a command's result reports it. + pub(super) fn json(&self) -> Value { + json!({"read": self.read, "skipped": self.skipped}) + } +} + +/// A shape to look for: its path, the contour groups it splits into when it may hold several +/// glyphs (none for a shape matched whole only), its fill rule when it has a visible fill +/// (`Some(nonzero)`) and whether it paints its overlaps once ([`super::paints_once`]), as +/// `type.retype` reads them. +#[derive(Clone, Copy)] +pub(super) struct Sought<'a> { + pub(super) path: &'a BezPath, + pub(super) groups: &'a [BezPath], + pub(super) fill: Option, + pub(super) once: bool, +} + +impl<'a> Sought<'a> { + /// `path` split into `groups`, with no paint check. + pub(super) fn unpainted(path: &'a BezPath, groups: &'a [BezPath]) -> Self { + Sought { path, groups, fill: None, once: true } + } +} + +/// `shapes`, each matched whole only. +fn whole<'a>(shapes: &[&'a BezPath]) -> Vec> { + shapes.iter().map(|path| Sought::unpainted(path, &[])).collect() +} + +/// The keys to look glyphs up by for `shapes`, at `tolerance` ([`super::lookup_keys`]). +fn keys_of(shapes: &[Sought], tolerance: f64) -> (BTreeSet, Vec) { + super::lookup_keys(shapes.iter().map(|s| (s.path, s.groups)), tolerance) +} + +/// Does a search look for `s`: is it not plain ([`is_plain`]: a rectangle, a triangle or a bar), +/// with a key to look glyphs up by? A shape without one matches no face. +fn starts(s: &Sought, tolerance: f64) -> bool { + if is_plain(s.path) { + return false; + } + let (keys, near) = keys_of(std::slice::from_ref(s), tolerance); + !keys.is_empty() || !near.is_empty() +} + +/// Is `s` found in `indexes` at `tolerance`: does its whole shape match a glyph there, or does +/// every glyph it splits into, painting the area `s` paints ([`super::shape_parts`])? +fn found_in(indexes: &[&RetypeIndex], s: &Sought, tolerance: f64) -> bool { + !super::shape_parts(s.path, s.groups, s.fill, s.once, indexes, tolerance).is_empty() +} + +/// [`search_for`] of `shapes` matched whole, exactly. +#[cfg(test)] +pub(super) fn search(db: &FontDb, shapes: &[&BezPath], every: bool) -> Result { + search_within(db, shapes, every, LIMITS, &|_| true) +} + +/// [`search_beside`] with no loaded faces. +#[cfg(test)] +pub(super) fn search_for(db: &FontDb, shapes: &[Sought], tolerance: f64, every: bool) -> Result { + search_beside(db, shapes, &[], tolerance, every) +} + +/// The installed faces nothing has loaded that `shapes` that are not plain ([`is_plain`]) are found +/// in at `tolerance` ([`found_in`]), each loaded into `db` as it was read. With `every` false, a +/// face is found when it matches such a shape, or completes the glyphs of a split one with the +/// loaded faces of `loaded` (the indexes of faces the command compares too) and the faces found or +/// read before it (a face read before whose glyphs it completes is found with it), and the search +/// stops once each such shape is found; with it, every face within the limits ([`LIMITS`]) is +/// compared, and found when it matches a shape on its own. No file is read when every shape is +/// plain. At most [`MAX_FACES`] faces are found; the faces not compared past that count as skipped. +/// The faces of `loaded` whose glyphs complete a split shape with a face found are among the faces +/// found too, so the command compares them with it. +pub(super) fn search_beside(db: &FontDb, shapes: &[Sought], loaded: &[&RetypeIndex], tolerance: f64, every: bool) -> Result { + search_sought(db, shapes, loaded, tolerance, every, LIMITS, &|_| true) +} + +/// [`search`] comparing every face within the limits, for a list of at most `faces` faces: a face +/// found that `listed` turns down is loaded and not listed, and takes no place of the `faces`. +pub(super) fn search_listed(db: &FontDb, shapes: &[&BezPath], faces: usize, listed: &dyn Fn(&FontFace) -> bool) -> Result { + search_sought(db, &whole(shapes), &[], 0.0, true, Limits { faces: faces.min(MAX_FACES), ..LIMITS }, listed) +} + +/// Would a search for `shapes`, matched whole and exactly, read any installed file: is one of them +/// not plain, with a glyph's key ([`shape_key`])? +pub(super) fn starts_search(shapes: &[&BezPath]) -> bool { + shapes.iter().any(|s| !is_plain(s) && shape_key(s).is_some()) +} + +/// [`loaded_rest_for`] of `shapes` matched whole, exactly: the faces only. +#[cfg(test)] +pub(super) fn loaded_rest(db: &FontDb, shapes: &[&BezPath], compared: &[u32]) -> Result>> { + Ok(loaded_rest_for(db, &whole(shapes), &[], 0.0, compared)?.0) +} + +/// The loaded faces that are not among `compared` (those past the [`MAX_FACES`] a Retype compares +/// first) that one of `shapes` that is not plain ([`is_plain`]) is found in at `tolerance` +/// ([`found_in`]), indexed [`MAX_FACES`] at a time: the faces of the glyphs it matches. The glyphs of +/// a split shape may be spread over those groups and the faces of `beside` (the indexes of faces +/// among `compared`). With them, whether each shape was found, and the indexes of the latest +/// groups that hold glyphs of the shapes while a split shape is not found (at most +/// [`MAX_KEPT_GROUPS`]), for the search of the installed fonts. A cancel stops it between those +/// groups. +pub(super) fn loaded_rest_for(db: &FontDb, shapes: &[Sought], beside: &[&RetypeIndex], tolerance: f64, compared: &[u32]) -> Result { + let mut done = vec![false; shapes.len()]; + let looked: Vec<(usize, &Sought)> = shapes.iter().enumerate().filter(|(_, s)| !is_plain(s.path)).collect(); + let (keys, near) = super::lookup_keys(looked.iter().map(|(_, s)| (s.path, s.groups)), tolerance); + let mut out: Vec> = vec![]; + if keys.is_empty() && near.is_empty() { + return Ok((out, done, vec![])); + } + let rest: Vec> = db.loaded_faces().into_iter().filter(|f| !compared.contains(&f.id())).collect(); + // The earlier groups' indexes that hold glyphs of the shapes, while a split shape is not found + // yet: the latest [`MAX_KEPT_GROUPS`]. + let mut kept: Vec = vec![]; + for group in rest.chunks(MAX_FACES) { + vectorcraft_doc::cancel::check()?; + let index = RetypeIndex::build_near(db, group.iter().cloned(), &keys, &near); + let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&kept).chain(std::iter::once(&index)).collect(); + for (k, s) in &looked { + // A split shape not found yet is matched with the faces before the group too (one pass, + // as near matching spends an index's budget); any other shape with the group alone. + let combined = !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true); + let indexes: &[&RetypeIndex] = if combined { &with } else { &[&index] }; + let parts = super::shape_parts(s.path, s.groups, s.fill, s.once, indexes, tolerance); + if parts.is_empty() { + continue; + } + if let Some(d) = done.get_mut(*k) { + *d = true; + } + for m in parts.into_iter().flatten() { + if !compared.contains(&m.face.id()) && !out.iter().any(|f| f.id() == m.face.id()) { + out.push(m.face); + } + } + } + let open = looked.iter().any(|(k, s)| !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true)); + if open && !index.is_empty() { + // The latest groups are kept: the oldest goes when the cap is reached. + if kept.len() >= MAX_KEPT_GROUPS { + kept.remove(0); + } + kept.push(index); + } + } + if !looked.iter().any(|(k, s)| !s.groups.is_empty() && !done.get(*k).copied().unwrap_or(true)) { + kept.clear(); + } + Ok((out, done, kept)) +} + +/// What [`loaded_rest_for`] finds: the faces, whether each shape was found, and the indexes kept +/// for the search of the installed fonts. +type LoadedRest = (Vec>, Vec, Vec); + +/// Earlier groups of [`MAX_FACES`] loaded faces past the ones compared first that a group's faces +/// complete a split shape's glyphs with, at most: the latest ones. +const MAX_KEPT_GROUPS: usize = 4; + +/// An installed font file: its path, its length and the (family, style) of the faces wanted from it. +type File = (std::path::PathBuf, u64, Vec<(String, String)>); + +/// [`search`] within `limits`, keeping in its faces only those `listed` accepts. +#[cfg(test)] +fn search_within(db: &FontDb, shapes: &[&BezPath], every: bool, limits: Limits, listed: &dyn Fn(&FontFace) -> bool) -> Result { + search_sought(db, &whole(shapes), &[], 0.0, every, limits, listed) +} + +/// [`search_beside`] within `limits`, keeping in its faces only those `listed` accepts. +fn search_sought( + db: &FontDb, + shapes: &[Sought], + beside: &[&RetypeIndex], + tolerance: f64, + every: bool, + limits: Limits, + listed: &dyn Fn(&FontFace) -> bool, +) -> Result { + let mut out = Installed::default(); + // A shape without a glyph's key matches no face: the search does not wait for it. + let shapes: Vec = shapes.iter().copied().filter(|s| starts(s, tolerance)).collect(); + let (keys, near) = keys_of(&shapes, tolerance); + if keys.is_empty() && near.is_empty() { + return Ok(out); + } + let (keys, near) = (&keys, near.as_slice()); + // The indexes of the faces found, which the glyphs of a split shape may be spread over. + let mut found: Vec = vec![]; + // The faces read, not loaded, that hold glyphs of the shapes without completing one, with their + // indexes: a later face may complete a split shape with them. The latest [`MAX_FACES`]. + let mut partial: Vec<(Arc, RetypeIndex)> = vec![]; + // The faces wanted from each file, smallest file first. + let mut files: Vec = vec![]; + let mut at: std::collections::HashMap = std::collections::HashMap::new(); + for f in db.unloaded_installed_faces() { + match at.get(&f.path).and_then(|i| files.get_mut(*i)) { + Some(file) => file.2.push((f.family, f.style)), + None => { + at.insert(f.path.clone(), files.len()); + files.push((f.path, f.len, vec![(f.family, f.style)])); + } + } + } + files.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0))); + let mut matched = vec![false; shapes.len()]; + // Is a split shape not found yet: only then are faces kept in `partial`. + let open = |matched: &[bool]| shapes.iter().zip(matched).any(|(s, m)| !*m && !s.groups.is_empty()); + let (mut bytes_left, mut glyphs_left) = (limits.read, limits.glyphs); + let total = files.len() as u64; + for (i, (path, len, styles)) in files.iter().enumerate() { + vectorcraft_doc::cancel::check()?; + vectorcraft_doc::cancel::progress(i as u64, total, "Retype: reading installed fonts"); + // A file too long for what is left, or read when no glyph is left to draw, is not read. + if *len > limits.file || *len > bytes_left || glyphs_left == 0 { + out.skipped += styles.len(); + continue; + } + // A file that grew since the scan is read only within what is left. + let file = db.read_unloaded_file(path, limits.file.min(bytes_left)); + // The bytes read, those of a file that grew past the limits too. + bytes_left = bytes_left.saturating_sub(file.bytes); + if file.too_long { + out.skipped += styles.len(); + continue; + } + let wanted = |f: &FontFace| styles.iter().any(|(family, style)| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style)); + let faces: Vec> = file.faces.into_iter().filter(|f| wanted(f)).collect(); + for (j, face) in faces.iter().enumerate() { + if out.faces.len() >= limits.faces { + // The faces not compared past the cap: the rest of this file's and the later files'. + out.skipped += styles.len().saturating_sub(j) + files.iter().skip(i + 1).map(|f| f.2.len()).sum::(); + return Ok(out); + } + let n = encoded_glyphs(face); + if n > glyphs_left { + out.skipped += 1; + continue; + } + glyphs_left -= n; + out.read += 1; + let index = RetypeIndex::build_unloaded_near(db, face.clone(), keys, near); + if index.is_empty() { + continue; + } + // With `every`, a face fits a shape it matches on its own; otherwise a shape not found + // yet that it completes with the loaded faces of `beside`, the faces found before it and + // the faces read before it that hold some of its glyphs (`partial`). + let parts: Vec<&RetypeIndex> = partial.iter().map(|(_, ix)| ix).collect(); + let parts_with = |extra: &[&RetypeIndex], ix: &RetypeIndex, k: usize| -> Vec> { + let Some(s) = shapes.get(k) else { return vec![] }; + if every { + return super::shape_parts(s.path, s.groups, s.fill, s.once, &[ix], tolerance); + } + if matched.get(k).copied().unwrap_or(true) { + return vec![]; + } + // A shape matched whole only takes one glyph: the faces read before it do not hold it. + let extra = if s.groups.is_empty() { &[] } else { extra }; + let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(extra.iter().copied()).chain(std::iter::once(ix)).collect(); + super::shape_parts(s.path, s.groups, s.fill, s.once, &with, tolerance) + }; + let fit_with = |extra: &[&RetypeIndex], ix: &RetypeIndex, k: usize| !parts_with(extra, ix, k).is_empty(); + let fit = |ix: &RetypeIndex, k: usize| fit_with(&parts, ix, k); + // Each shape it fits, with the glyphs it matches: one pass, as near matching spends an + // index's budget. + let first: Vec<(usize, Vec>)> = + (0..shapes.len()).map(|k| (k, parts_with(&parts, &index, k))).filter(|(_, p)| !p.is_empty()).collect(); + let fits: Vec = first.iter().map(|(k, _)| *k).collect(); + if fits.is_empty() { + // The face holds glyphs of a shape without completing one: a later face may, while + // a split shape is not found. The latest are kept: the oldest goes when the cap is + // reached. + if !every && open(&matched) { + #[cfg(test)] + KEPT_PARTIAL.with(|n| n.set(n.get() + 1)); + if partial.len() >= MAX_FACES { + partial.remove(0); + } + partial.push((face.clone(), index)); + } + continue; + } + let loaded = load(db, face); + let same = loaded.id() == face.id(); + let (mut fits, index) = still_fit(db, face, &loaded, index, keys, near, fits, &fit); + if fits.is_empty() { + continue; + } + // The faces read before whose glyphs the shapes it fits use, loaded with it: those + // that leave room under the cap, or else only the shapes it fits without them. A face + // loaded in place of the one read is matched again for them. + let matches: Vec> = if same { + first.into_iter().flat_map(|(_, p)| p).collect() + } else { + fits.iter().flat_map(|k| parts_with(&parts, &index, *k)).collect() + }; + let held: Vec<&Arc> = index.faces().iter().chain(found.iter().flat_map(|ix| ix.faces())).chain(&out.faces).collect(); + let (mut used, mut with_loaded) = companions(&matches, &held, beside, &partial); + if out.faces.len() + used.len() + with_loaded.len() >= limits.faces { + let alone: Vec<&RetypeIndex> = found.iter().chain(std::iter::once(&index)).collect(); + fits.retain(|k| shapes.get(*k).is_some_and(|s| found_in(&alone, s, tolerance))); + used.clear(); + with_loaded.clear(); + if fits.is_empty() { + continue; + } + } + let mut shadowed = false; + let mut promoted: Vec> = vec![]; + for at in used.into_iter().rev() { + let (read, ix) = partial.remove(at); + let loaded = load(db, &read); + let ix = if loaded.id() == read.id() { + ix + } else { + shadowed = true; + RetypeIndex::build_near(db, [loaded.clone()], keys, near) + }; + promoted.insert(0, loaded); + found.push(ix); + } + // A face loaded in place of one read may have other glyphs: the shapes are checked again. + if shadowed { + let with: Vec<&RetypeIndex> = beside.iter().copied().chain(&found).chain(std::iter::once(&index)).collect(); + fits.retain(|k| shapes.get(*k).is_some_and(|s| found_in(&with, s, tolerance))); + if fits.is_empty() { + continue; + } + } + // The faces it completes shapes with, once the match holds. + out.faces.extend(with_loaded); + for loaded in promoted { + if listed(&loaded) { + remember(db, &loaded); + if !out.faces.iter().any(|f| f.id() == loaded.id()) { + out.faces.push(loaded); + } + } + } + // A face `listed` turns down (another version shadows it) is not compared ahead of others. + if listed(&loaded) { + remember(db, &loaded); + if !out.faces.iter().any(|f| f.id() == loaded.id()) { + out.faces.push(loaded); + } + } + found.push(index); + for k in fits { + if let Some(m) = matched.get_mut(k) { + *m = true; + } + } + if !every && matched.iter().all(|m| *m) { + return Ok(out); + } + // With every split shape found, the faces kept for them are dropped. + if !open(&matched) { + partial.clear(); + } + } + // The cap reached with the file's last face: the later files are not compared. + if out.faces.len() >= limits.faces { + out.skipped += files.iter().skip(i + 1).map(|f| f.2.len()).sum::(); + return Ok(out); + } + } + Ok(out) +} + +#[cfg(test)] +thread_local! { + /// How many times a search on this thread kept a face it read in `partial`. + static KEPT_PARTIAL: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// For each of `parts` (each part's candidates) that none of the faces of `held` has a glyph of, +/// one face that does: a loaded face of `beside` (the command compares it with the face found), +/// or else a face of `partial`, read before. The places in `partial` of those, in order, and the +/// loaded faces. +fn companions( + parts: &[Vec], + held: &[&Arc], + beside: &[&RetypeIndex], + partial: &[(Arc, RetypeIndex)], +) -> (Vec, Vec>) { + let (mut used, mut loaded) = (BTreeSet::new(), Vec::>::new()); + for part in parts { + let has = |f: &Arc| part.iter().any(|m| m.face.id() == f.id()); + let chosen = used.iter().filter_map(|at: &usize| partial.get(*at).map(|(f, _)| f)); + if held.iter().copied().chain(&loaded).chain(chosen).any(has) { + continue; + } + let of_beside = part.iter().find(|m| beside.iter().any(|ix| ix.faces().iter().any(|f| f.id() == m.face.id()))); + if let Some(m) = of_beside { + loaded.push(m.face.clone()); + } else if let Some(at) = part.iter().find_map(|m| partial.iter().position(|(f, _)| Arc::ptr_eq(f, &m.face))) { + used.insert(at); + } + } + (used.into_iter().collect(), loaded) +} + +/// The faces searches loaded from installed files, by database ([`FontDb::id`]) and face id, the +/// latest first: at most [`MAX_FACES`]. +static FOUND: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Keep `face`, which a search loaded into `db`, among [`found`]'s faces. +fn remember(db: &FontDb, face: &FontFace) { + let mut kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let at = (db.id(), face.id()); + kept.retain(|k| *k != at); + kept.insert(0, at); + kept.truncate(MAX_FACES); +} + +/// The faces of `db` that searches of the installed fonts found and loaded, the latest first. A +/// later Retype compares them ahead of the other loaded faces. +pub(super) fn found(db: &FontDb) -> Vec> { + let kept = FOUND.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone(); + kept.into_iter().filter(|(d, _)| *d == db.id()).filter_map(|(_, id)| db.face_by_id(id)).collect() +} + +/// Of `fits` (the shapes `index`, the index of `read`, fits as `fit` tells), those that `loaded`, +/// the face loading `read` gave, fits too, with the index they fit in: all of them and `index` +/// when it is `read` itself. Another face of the same family, style and version, loaded from +/// another file, may have other glyphs; it is indexed by `keys` and `near`. +#[allow(clippy::too_many_arguments)] +fn still_fit( + db: &FontDb, + read: &FontFace, + loaded: &Arc, + index: RetypeIndex, + keys: &BTreeSet, + near: &[NearKey], + fits: Vec, + fit: &dyn Fn(&RetypeIndex, usize) -> bool, +) -> (Vec, RetypeIndex) { + if loaded.id() == read.id() { + return (fits, index); + } + let index = RetypeIndex::build_near(db, [loaded.clone()], keys, near); + let fits = fits.into_iter().filter(|k| fit(&index, *k)).collect(); + (fits, index) +} + +/// `face` (read from an installed file and not loaded) loaded into `db` as it was read +/// ([`FontDb::load_read_face`]): neither its file nor the family's other files are read again. +fn load(db: &FontDb, face: &Arc) -> Arc { + db.load_read_face(face.clone()) +} + +/// A search of the installed fonts made away from its command, so the app can run it off the UI +/// thread with a Cancel. [`RetypeRun::prepare`] takes the selected shapes and the document from the +/// session, checking the params as the command checks them; [`RetypeSearch::run`] picks the loaded +/// faces to compare, compares them and searches the installed fonts on any thread, loading the +/// faces that match; and +/// [`RetypeFound::hand_in`] gives what it found to the command, which then runs with +/// [`RetypeRun::params`] and compares those faces as its own search would, without reading the +/// installed fonts again. +pub struct RetypeRun { + params: Value, + /// The document ([`crate::DocState::uid`]), its content and the selection the search is for. + doc: u64, + content: Arc, + selection: Vec, + search: Arc, +} + +/// What a [`RetypeRun`] compares and searches, without the session: it can be sent to another +/// thread ([`RetypeRun::search`]). +pub struct RetypeSearch { + command: &'static str, + /// The document it is for ([`crate::DocState::uid`]). + doc: u64, + /// The shapes to match, and the loaded faces they are compared with first. + shapes: Vec, + faces: Faces, + /// `type.retype`'s tolerance (0 for `type.retypeFonts`). + tolerance: f64, +} + +/// The loaded faces a [`RetypeSearch`] compares first. +enum Faces { + /// These faces. + #[cfg(test)] + Given(Vec>), + /// Those the command picks in `doc`: with `fonts` (`type.retype`'s `fonts` param), the faces of + /// those families and of the document's live type ([`super::candidate_faces`]), and without, the + /// faces `type.retypeFonts` lists ([`super::fonts::listed_faces`]). They are picked on the + /// search's thread, since a family not loaded yet is read from its files. + Of { doc: Arc, fonts: Option> }, +} + +impl Faces { + fn get(&self, db: &FontDb) -> Vec> { + match self { + #[cfg(test)] + Faces::Given(faces) => faces.clone(), + Faces::Of { doc, fonts: Some(fonts) } => super::candidate_faces(db, doc, fonts), + Faces::Of { doc, fonts: None } => super::fonts::listed_faces(db, doc), + } + } +} + +/// A shape a [`RetypeSearch`] compares, as `type.retype` matches it ([`super::shape_parts`]): its +/// path, its contour groups when it may hold several glyphs, its fill rule when it has a visible +/// fill (`Some(nonzero)`), and whether it paints its overlaps once ([`super::paints_once`]). +struct Shape { + path: BezPath, + groups: Vec, + fill: Option, + once: bool, +} + +impl Shape { + /// `path`, matched whole, with no paint check. + fn whole(path: BezPath) -> Self { + Shape { path, groups: vec![], fill: None, once: true } + } + + fn sought(&self) -> Sought<'_> { + Sought { path: &self.path, groups: &self.groups, fill: self.fill, once: self.once } + } +} + +/// What a [`RetypeSearch`] found: for `type.retype`, the faces it compared first that match, the +/// loaded faces past those that match ([`loaded_rest`]), the installed faces whose glyphs match, +/// loaded, and the loaded faces it compared; and what it read of the installed fonts. +pub struct RetypeFound { + doc: u64, + installed: Installed, +} + +impl RetypeFound { + /// Hand it to the next `type.retype` or `type.retypeFonts`, which compares the faces found as + /// its own search of the installed fonts would, in the document the search was made for. Any + /// such command takes it; one in another document compares only what is loaded. + pub fn hand_in(self, s: &mut Session) { + s.retype_hand_off = Some(self); + } + + /// Drop what was handed in and no command took, as when the command failed before it took + /// it: a later command searches for itself. + pub fn drop_handed(s: &mut Session) { + s.retype_hand_off = None; + } + + /// What it read, as the commands report it. + pub fn json(&self) -> Value { + self.installed.json() + } +} + +/// What a search found for the active document of `s`, handed in for this command ([`RetypeFound`]). +/// It is taken whatever the document, so it is used once. +pub(super) fn handed(s: &mut Session) -> Option { + let found = s.retype_hand_off.take()?; + let doc = s.doc().ok()?.uid; + (found.doc == doc).then_some(found.installed) +} + +impl RetypeRun { + /// The search `command` (`type.retype` or `type.retypeFonts`) with params `p` makes in the + /// active document. None when it reads no installed font: `installed` is false, or no shape + /// starts a search ([`starts`]: each is plain or has no glyph's key). An error where the command fails on its params or on the selection. + /// The faces to compare are picked when the search runs. + pub fn prepare(s: &Session, command: &str, p: &Value) -> Result> { + let (command, fonts, tolerance) = match command { + "type.retype" => ("type.retype", Some(super::fonts_param(p)?), super::tolerance_param(p)?), + "type.retypeFonts" => { + super::fonts::count_param(p)?; + ("type.retypeFonts", None, 0.0) + } + other => return Err(EngineError::Other(format!("`{other}` doesn't search the installed fonts"))), + }; + // The keys the command refuses (an unknown one) fail here too, before any search. + s.check_params(command, p)?; + if !wanted(command, p)? { + return Ok(None); + } + let (pieces, _) = super::selected_pieces(s)?; + let st = s.doc()?; + // Retype compares the shapes that may become type, split as it splits them; the list + // compares every shape whole. + let shapes: Vec = if fonts.is_some() { + let mut budget = super::MAX_SPLIT_TOTAL_CONTOURS; + pieces + .into_iter() + .filter(|pc| !pc.keeps_outline) + .map(|pc| Shape { + groups: super::split_groups(&pc.path, &mut budget), + fill: pc.filled.then_some(pc.nonzero), + once: super::paints_once(pc.opacity, pc.blend, &pc.appearance), + path: pc.path, + }) + .collect() + } else { + pieces.into_iter().map(|pc| Shape::whole(pc.path)).collect() + }; + if !shapes.iter().any(|s| starts(&s.sought(), tolerance)) { + return Ok(None); + } + let faces = Faces::Of { doc: st.doc.clone(), fonts }; + Ok(Some(RetypeRun { + params: p.clone(), + doc: st.uid, + content: st.doc.clone(), + selection: st.selection.objects.clone(), + search: Arc::new(RetypeSearch { command, doc: st.uid, shapes, faces, tolerance }), + })) + } + + /// `type.retype` or `type.retypeFonts`. + pub fn command(&self) -> &'static str { + self.search.command + } + + /// What it compares and searches, for another thread. + pub fn search(&self) -> Arc { + self.search.clone() + } + + /// The command's params: those it was prepared with. + pub fn params(&self) -> &Value { + &self.params + } + + /// Does it still apply: is the document it was prepared in active, with the same content and + /// the same objects selected? + pub fn current(&self, s: &Session) -> bool { + s.doc().is_ok_and(|st| st.uid == self.doc && Arc::ptr_eq(&st.doc, &self.content) && st.selection.objects == self.selection) + } + + /// [`RetypeSearch::run`] with the fonts of `db`. + #[cfg(test)] + fn run_in(&self, db: &FontDb) -> Result { + self.search.run_in(db) + } +} + +impl RetypeSearch { + /// Compare the shapes with the loaded faces, then search the installed fonts as the command + /// would, loading the faces that match → what it found ([`EngineError::Cancelled`] when a + /// cancel stopped it). It touches no document, so it can run on any thread. + pub fn run(&self) -> Result { + self.run_in(FontDb::global()) + } + + /// [`RetypeSearch::run`] with the fonts of `db`. + fn run_in(&self, db: &FontDb) -> Result { + let picked = self.faces.get(db); + let installed = if self.command == "type.retypeFonts" { + let shapes: Vec<&BezPath> = self.shapes.iter().map(|s| &s.path).collect(); + let (ranked, mut found) = super::fonts::rank_fonts(db, picked, &shapes, true, None)?; + // The loaded faces that match are handed in too, ahead of the installed ones found: + // loading those can move a loaded face past the 96 the command lists. + let mut faces: Vec> = ranked.iter().map(|r| r.face().clone()).collect(); + for f in std::mem::take(&mut found.faces) { + if !faces.iter().any(|k| k.id() == f.id()) { + faces.push(f); + } + } + found.faces = faces; + found + } else { + // The shapes are matched as the command matches them first. + let tolerance = self.tolerance; + let sought: Vec = self.shapes.iter().map(Shape::sought).collect(); + let (keys, near) = keys_of(&sought, tolerance); + let index = RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near); + let parts: Vec>> = + self.shapes.iter().map(|s| super::shape_parts(&s.path, &s.groups, s.fill, s.once, &[&index], tolerance)).collect(); + let left: Vec = sought.iter().zip(&parts).filter(|(_, p)| p.is_empty()).map(|(s, _)| *s).collect(); + // The first faces that match are handed in too: loading the faces found can move one + // past the first 96 the command compares. + let mut first: Vec> = vec![]; + for m in parts.into_iter().flatten().flatten() { + if !first.iter().any(|f| f.id() == m.face.id()) { + first.push(m.face); + } + } + // The loaded faces past the ones compared first, then the installed fonts for what + // none of them matches; the command takes both from what is handed in. + let compared: Vec = picked.iter().map(|f| f.id()).collect(); + // Every face loaded now is compared, among the first ones or with the rest. + let scanned: Vec = compared.iter().copied().chain(db.loaded_faces().iter().map(|f| f.id())).collect(); + // A split shape's glyphs may be spread over the faces compared first and the others. + // Near matching spends an index's comparison budget, so with a tolerance the faces + // compared first are indexed again for each search that has a split shape to look for. + let again = |needed: bool| (needed && tolerance > 0.0).then(|| RetypeIndex::build_near(db, picked.iter().cloned(), &keys, &near)); + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let (rest, done, kept) = loaded_rest_for(db, &left, &[fresh.as_ref().unwrap_or(&index)], tolerance, &compared)?; + let left: Vec = left.into_iter().zip(done).filter(|(_, done)| !done).map(|(s, _)| s).collect(); + let fresh = again(left.iter().any(|s| !s.groups.is_empty())); + let kept: Vec = if tolerance > 0.0 { + kept.iter().map(|ix| RetypeIndex::build_near(db, ix.faces().iter().cloned(), &keys, &near)).collect() + } else { + kept + }; + let beside: Vec<&RetypeIndex> = std::iter::once(fresh.as_ref().unwrap_or(&index)).chain(&kept).collect(); + let mut found = search_beside(db, &left, &beside, tolerance, false)?; + found.faces.splice(0..0, first.into_iter().chain(rest)); + found.scanned = scanned; + found + }; + Ok(RetypeFound { doc: self.doc, installed }) + } +} + +#[cfg(test)] +#[path = "retype_installed_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/retype_installed_tests.rs b/crates/engine/src/cmd/retype_installed_tests.rs new file mode 100644 index 0000000000..4945d9c259 --- /dev/null +++ b/crates/engine/src/cmd/retype_installed_tests.rs @@ -0,0 +1,833 @@ +use std::collections::BTreeSet; +use std::path::PathBuf; + +use kurbo::{Affine, BezPath, Shape}; +use serde_json::json; +use vectorcraft_text::FontDb; +use vectorcraft_text::retype::shape_key; + +use super::{Limits, search, search_within}; +use crate::Session; + +/// A database whose installed fonts are copies of the bundled Source Sans 3 Regular named +/// `families`, one file each, in a folder of their own: they are installed and not loaded. +/// Returns the database and the files. +fn installed(tag: &str, families: &[&str]) -> (FontDb, Vec) { + let dir = vectorcraft_testkit::temp_dir(&format!("retype-installed-{tag}")); + let mut files = vec![]; + for family in families { + let postscript = format!("{}-Regular", family.replace(' ', "")); + let data = vectorcraft_text::test_fonts::named_copy(false, (family, "Regular", "Version 1.000", &postscript)).unwrap(); + let path = dir.join(format!("{postscript}.ttf")); + std::fs::write(&path, data).unwrap(); + files.push(path); + } + (FontDb::with_font_dirs(vec![dir]), files) +} + +/// The glyphs of `text` in the bundled Source Sans 3 Regular, as outlines at 30 pt. +fn glyphs(db: &FontDb, text: &str) -> Vec { + let face = db.face("Source Sans 3", "Regular").unwrap(); + text.chars() + .enumerate() + .map(|(i, c)| Affine::translate((40.0 + 30.0 * i as f64, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for(c))) + .collect() +} + +fn keys(shapes: &[BezPath]) -> BTreeSet { + shapes.iter().filter_map(shape_key).collect() +} + +/// `paths` as a search compares them, each matched whole. +fn whole(paths: Vec) -> Vec { + paths.into_iter().map(super::Shape::whole).collect() +} + +fn unloaded(db: &FontDb, family: &str) -> bool { + db.unloaded_installed_faces().iter().any(|f| f.family == family) +} + +#[test] +fn an_installed_face_whose_glyphs_match_is_found_and_loaded() { + let (db, files) = installed("found", &["Retype Copy A"]); + assert!(unloaded(&db, "Retype Copy A")); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.skipped), (1, 0)); + let face = found.faces.first().expect("the installed copy matches"); + assert_eq!((face.family.as_str(), face.style.as_str()), ("Retype Copy A", "Regular")); + assert_eq!(face.path(), Some(files[0].as_path())); + // Loaded now, as it was read. + assert!(db.loaded_faces().iter().any(|f| f.id() == face.id())); + assert!(!unloaded(&db, "Retype Copy A")); + assert_eq!(found.json(), json!({"read": 1, "skipped": 0})); + // A later Retype compares it ahead of the other loaded faces, however many are loaded. + assert_eq!(super::found(&db).first().map(|f| f.id()), Some(face.id())); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let candidates = super::super::candidate_faces(&db, &s.doc().unwrap().doc, &[]); + assert_eq!(candidates.first().map(|f| f.id()), Some(face.id())); + // Only this database's faces. + assert!(super::found(&FontDb::with_font_dirs(vec![])).is_empty()); +} + +#[test] +fn a_matching_face_loads_without_the_family_s_other_files() { + let dir = vectorcraft_testkit::temp_dir("retype-installed-family"); + for style in ["Regular", "Bold"] { + let data = + vectorcraft_text::test_fonts::named_copy(false, ("Retype Copy N", style, "Version 1.000", &format!("RetypeCopyN-{style}"))).unwrap(); + std::fs::write(dir.join(format!("RetypeCopyN-{style}.ttf")), data).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir]); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 1)); + let style = found.faces[0].style.clone(); + let loaded: Vec = db.loaded_faces().iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style.clone()).collect(); + assert_eq!(loaded, std::slice::from_ref(&style), "only the face that matched is loaded"); + let left: Vec = db.unloaded_installed_faces().into_iter().filter(|f| f.family == "Retype Copy N").map(|f| f.style).collect(); + assert_eq!(left.len(), 1); + assert_ne!(left[0], style); +} + +#[test] +fn a_loaded_face_of_the_same_names_counts_only_for_the_shapes_it_matches() { + use vectorcraft_text::test_fonts::named_copy; + let names = ("Retype Twin", "Regular", "Version 1.000", "RetypeTwin-Regular"); + let db = FontDb::with_font_dirs(vec![]); + // Inter's glyphs, loaded under the names a file of Source Sans 3's glyphs has too. + db.add_font(named_copy(true, names).unwrap()); + let dir = vectorcraft_testkit::temp_dir("retype-installed-twin"); + let path = dir.join("RetypeTwin-Regular.ttf"); + std::fs::write(&path, named_copy(false, names).unwrap()).unwrap(); + let read = db.read_unloaded_file(&path, u64::MAX).faces.into_iter().next().unwrap(); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let keys = keys(&shapes); + let loaded = super::load(&db, &read); + assert_ne!(loaded.id(), read.id(), "the face loaded first is kept"); + let fit = |ix: &super::super::RetypeIndex, k: usize| !ix.matches(refs[k]).is_empty(); + let index = || super::super::RetypeIndex::build_unloaded(&db, read.clone(), &keys); + let (fits, _) = super::still_fit(&db, &read, &loaded, index(), &keys, &[], vec![0, 1], &fit); + assert!(fits.is_empty(), "Inter's R and x are not these"); + let (fits, _) = super::still_fit(&db, &read, &read, index(), &keys, &[], vec![0, 1], &fit); + assert_eq!(fits, [0, 1]); +} + +#[test] +fn an_installed_face_no_shape_matches_is_read_and_not_loaded() { + let (db, _) = installed("none", &["Retype Copy B"]); + let shapes = [kurbo::Circle::new((40.0, 40.0), 20.0).to_path(0.1)]; + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 0)); + assert!(unloaded(&db, "Retype Copy B"), "a face that matches nothing stays unloaded"); + // No shape: no file is read. + let none = search(&db, &[], false).unwrap(); + assert_eq!((none.read, none.skipped), (0, 0)); +} + +#[test] +fn plain_shapes_alone_read_no_installed_font() { + // A hyphen is a bar: many fonts have a glyph of its shape, so it tells no font apart. + let (db, _) = installed("plain", &["Retype Copy L"]); + let mut shapes = glyphs(&db, "-"); + shapes.push(kurbo::Rect::new(0.0, 0.0, 80.0, 40.0).to_path(0.1)); + assert!(shapes.iter().all(vectorcraft_text::retype::is_plain)); + let refs: Vec<&BezPath> = shapes.iter().collect(); + for every in [false, true] { + let found = search(&db, &refs, every).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (0, 0, 0)); + } + assert!(unloaded(&db, "Retype Copy L")); + // Beside a shape that is not plain, the search reads the file for that shape. + shapes.extend(glyphs(&db, "q")); + let refs: Vec<&BezPath> = shapes.iter().collect(); + assert_eq!(search(&db, &refs, false).unwrap().faces.len(), 1); +} + +#[test] +fn a_shape_without_a_glyph_s_key_does_not_keep_the_search_going() { + let (db, _) = installed("keyless", &["Retype Copy Keyless A", "Retype Copy Keyless B"]); + let mut shapes = glyphs(&db, "k"); + // More contours than any glyph's key counts: no face can match it. + let mut dots = BezPath::new(); + for i in 0..49 { + dots.extend(kurbo::Circle::new((10.0 * f64::from(i), 300.0), 3.0).path_elements(0.1)); + } + assert!(shape_key(&dots).is_none() && !vectorcraft_text::retype::is_plain(&dots)); + shapes.push(dots); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 1), "the second file is not read"); +} + +#[test] +fn the_search_stops_once_every_shape_matches_unless_every_face_is_wanted() { + let (db, _) = installed("every", &["Retype Copy C", "Retype Copy D"]); + let shapes = glyphs(&db, "ab"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let first = search(&db, &refs, false).unwrap(); + assert_eq!((first.read, first.faces.len()), (1, 1), "the second file is not read"); + let (db, _) = installed("every-all", &["Retype Copy E", "Retype Copy F"]); + let all = search(&db, &refs, true).unwrap(); + assert_eq!((all.read, all.faces.len()), (2, 2)); + let mut families: Vec<&str> = all.faces.iter().map(|f| f.family.as_str()).collect(); + families.sort_unstable(); + assert_eq!(families, ["Retype Copy E", "Retype Copy F"]); +} + +#[test] +fn faces_read_are_kept_for_split_shapes_only() { + let (db, _) = installed("kept-whole", &["Retype Kept Whole A", "Retype Kept Whole B", "Retype Kept Whole C"]); + // The k matches in the first file and the circle in none, so every file is read; the later + // files hold the k's glyph without completing a shape. With every shape whole, none is kept. + let mut shapes = glyphs(&db, "k"); + shapes.push(kurbo::Circle::new((300.0, 100.0), 7.3).to_path(0.1)); + assert!(shape_key(&shapes[1]).is_some(), "the circle has a key to look glyphs up by"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + super::KEPT_PARTIAL.with(|n| n.set(0)); + let found = search(&db, &refs, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (3, 1)); + assert_eq!(super::KEPT_PARTIAL.with(std::cell::Cell::get), 0, "no face read is kept"); +} + +#[test] +fn faces_past_the_limits_are_skipped_and_counted() { + let (db, files) = installed("limits", &["Retype Copy G", "Retype Copy H"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let len = files.iter().map(|f| std::fs::metadata(f).unwrap().len()).max().unwrap(); + // Files longer than the limit for one file. + let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: usize::MAX, faces: usize::MAX }; + let all = |_: &vectorcraft_text::FontFace| true; + let small = search_within(&db, &refs, true, Limits { file: len / 2, ..open }, &all).unwrap(); + assert_eq!((small.read, small.skipped, small.faces.len()), (0, 2, 0)); + // Bytes for one file only. + let one = search_within(&db, &refs, true, Limits { read: len + len / 2, ..open }, &all).unwrap(); + assert_eq!((one.read, one.skipped, one.faces.len()), (1, 1, 1)); + // Glyphs for no face. + let (db, _) = installed("limits-glyphs", &["Retype Copy I"]); + let few = search_within(&db, &refs, true, Limits { glyphs: 10, ..open }, &all).unwrap(); + assert_eq!((few.read, few.skipped, few.faces.len()), (0, 1, 0)); + assert!(unloaded(&db, "Retype Copy I")); + // Faces found up to the cap: the faces after it are not compared, and count as skipped. + let (db, _) = installed("limits-faces", &["Retype Copy O", "Retype Copy P", "Retype Copy Q"]); + let capped = search_within(&db, &refs, true, Limits { faces: 1, ..open }, &all).unwrap(); + assert_eq!((capped.read, capped.skipped, capped.faces.len()), (1, 2, 1)); +} + +#[test] +fn a_file_that_grows_past_the_limits_after_the_listing_is_skipped_and_its_bytes_count() { + let (db, mut files) = installed("grown", &["Retype Copy Y", "Retype Copy Z"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // The order the search reads them in: smallest first. + let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len(); + files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b))); + let (first, second) = (len(&files[0]), len(&files[1])); + let grown = files[0].clone(); + // The first file grows past the limit for one file as its reading starts, after the listing. + let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| { + if done == 0 { + let mut data = std::fs::read(&grown).unwrap(); + data.resize(data.len() + second as usize + 1, 0); + std::fs::write(&grown, data).unwrap(); + } + }); + // Bytes for both files as listed: the grown file's reading takes one more than the limit for + // one file, which leaves too little for the second. + let limits = Limits { file: second, read: first + second, glyphs: usize::MAX, faces: usize::MAX }; + let token = vectorcraft_doc::cancel::CancelToken::new(); + let all = |_: &vectorcraft_text::FontFace| true; + let found = vectorcraft_doc::cancel::scope(&token, Some(sink), || search_within(&db, &refs, true, limits, &all)).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (0, 2, 0)); +} + +#[test] +fn the_glyph_budget_counts_the_glyphs_drawn() { + let (db, files) = installed("glyph-budget", &["Retype Copy Budget"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap(); + let mapped = face.mapped_chars().len(); + let drawn = vectorcraft_text::retype::encoded_glyphs(&face); + assert!(drawn < mapped, "{drawn} of {mapped}"); + // A budget below the face's characters and at the glyphs drawn: the face is compared. + let open = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX }; + let found = search_within(&db, &refs, true, open, &|_| true).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (1, 0, 1)); +} + +#[test] +fn a_run_away_from_the_list_hands_in_the_loaded_faces_that_match_with_the_installed_ones() { + let (db, _) = installed("list-run", &["Retype Copy List"]); + db.add_font( + vectorcraft_text::test_fonts::named_copy(false, ("Retype Loaded List", "Regular", "Version 1.000", "RetypeLoadedList-Regular")).unwrap(), + ); + let loaded: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Loaded List").collect(); + let search = super::RetypeSearch { + command: "type.retypeFonts", + doc: 1, + shapes: whole(glyphs(&db, "Rx")), + faces: super::Faces::Given(loaded.clone()), + tolerance: 0.0, + }; + let found = search.run_in(&db).unwrap(); + let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect(); + // The loaded face first, then the installed one, each once. + assert_eq!(families, ["Retype Loaded List", "Retype Copy List"]); + assert_eq!((found.installed.read, found.installed.skipped), (1, 0)); +} + +#[test] +fn faces_a_list_turns_down_are_loaded_and_take_no_place() { + let (db, _) = installed("listed", &["Retype Copy R", "Retype Copy S", "Retype Copy T"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // Two places, and the first face found is turned down: the next two are listed. + let found = super::search_listed(&db, &refs, 2, &|f| f.family != "Retype Copy R").unwrap(); + let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + families.sort_unstable(); + assert_eq!(families, ["Retype Copy S", "Retype Copy T"]); + assert_eq!((found.read, found.skipped), (3, 0)); + assert!(!unloaded(&db, "Retype Copy R"), "the face turned down was loaded"); + // Only the faces listed are compared ahead of the other loaded faces later. + let ahead: Vec = super::found(&db).iter().map(|f| f.family.clone()).collect(); + assert!(ahead.iter().any(|f| f == "Retype Copy S") && !ahead.iter().any(|f| f == "Retype Copy R"), "{ahead:?}"); +} + +#[test] +fn a_cancel_stops_the_search_between_files() { + let (db, _) = installed("cancel-between", &["Retype Copy U", "Retype Copy V", "Retype Copy W"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let token = vectorcraft_doc::cancel::CancelToken::new(); + let stop = token.clone(); + // The cancel comes as the second file starts: it is read, the third is not. + let sink: vectorcraft_doc::cancel::ProgressSink = std::rc::Rc::new(move |done, _, _| { + if done == 1 { + stop.cancel(); + } + }); + let r = vectorcraft_doc::cancel::scope(&token, Some(sink), || search(&db, &refs, true)); + assert!(matches!(r, Err(crate::EngineError::Cancelled))); + let left = ["Retype Copy U", "Retype Copy V", "Retype Copy W"].iter().filter(|f| unloaded(&db, f)).count(); + assert_eq!(left, 1, "two files were read and loaded, the third was not"); +} + +#[test] +fn a_run_away_from_the_command_loads_the_faces_it_finds() { + let (db, _) = installed("run", &["Retype Copy X"]); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let ids: Vec = + glyphs(&db, "Wk").iter().map(|p| s.execute("path.create", &json!({"d": p.to_svg()})).unwrap()["id"].as_u64().unwrap()).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + // Off: nothing to run. + for cmd in ["type.retype", "type.retypeFonts"] { + assert!(super::RetypeRun::prepare(&s, cmd, &json!({"installed": false})).unwrap().is_none()); + } + // The command's params are checked as it checks them. + assert!(super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 0})).is_err()); + assert!(super::RetypeRun::prepare(&s, "type.retype", &json!({"fonts": 1})).is_err()); + assert!(super::RetypeRun::prepare(&s, "type.text", &json!({})).is_err()); + // An unknown key fails before any search, as the command fails on it. + for cmd in ["type.retype", "type.retypeFonts"] { + let e = super::RetypeRun::prepare(&s, cmd, &json!({"typo": true})).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("typo"), "{cmd}: {e}"); + assert!(s.execute(cmd, &json!({"typo": true})).is_err()); + } + // Retype: the loaded Source Sans 3 matches both shapes, so no installed file is read. + let run = super::RetypeRun::prepare(&s, "type.retype", &json!({})).unwrap().unwrap(); + assert_eq!(run.command(), "type.retype"); + assert_eq!(run.params(), &json!({})); + assert_eq!(run.run_in(&db).unwrap().json(), json!({"read": 0, "skipped": 0})); + assert!(unloaded(&db, "Retype Copy X")); + // The list compares every installed face: the copy is read and loaded. + let run = super::RetypeRun::prepare(&s, "type.retypeFonts", &json!({"count": 5})).unwrap().unwrap(); + assert_eq!(run.params(), &json!({"count": 5})); + assert!(run.current(&s)); + let found = run.run_in(&db).unwrap(); + assert_eq!(found.json(), json!({"read": 1, "skipped": 0})); + // The loaded faces that match are handed in with it, ahead of it. + let families: Vec<&str> = found.installed.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families.last(), Some(&"Retype Copy X"), "{families:?}"); + assert_eq!(families.iter().filter(|f| **f == "Retype Copy X").count(), 1, "{families:?}"); + assert!(families.contains(&"Source Sans 3"), "{families:?}"); + assert!(!unloaded(&db, "Retype Copy X")); + // A change of selection or content: it no longer applies. + s.execute("select.set", &json!({"ids": [ids[0]]})).unwrap(); + assert!(!run.current(&s)); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + assert!(run.current(&s)); + s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); + assert!(!run.current(&s)); +} + +#[test] +fn plain_shapes_alone_start_no_run_away_from_the_command() { + // A rectangle and a bar are plain: the search reads no installed font for them, so the + // command runs at once. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let bar = s.execute("shape.rectangle", &json!({"x": 10, "y": 100, "width": 4, "height": 60})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [rect, bar]})).unwrap(); + for (cmd, p) in [("type.retype", json!({})), ("type.retype", json!({"tolerance": 0.05})), ("type.retypeFonts", json!({}))] { + assert!(super::RetypeRun::prepare(&s, cmd, &p).unwrap().is_none(), "{cmd} {p}"); + } +} + +#[test] +fn what_a_search_found_is_handed_to_the_next_command_in_its_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let uid = s.doc().unwrap().uid; + let handed = |doc| super::RetypeFound { doc, installed: super::Installed { read: 7, skipped: 3, ..Default::default() } }; + // Taken instead of a search of the installed fonts, also with installed false. + handed(uid).hand_in(&mut s); + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 7, "skipped": 3}), "{r}"); + // Used once. + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + // Another document's is dropped. + handed(uid + 1).hand_in(&mut s); + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); + assert!(s.retype_hand_off.is_none(), "taken"); + // Retype takes it too, whether or not a loaded font matches the rectangle. + handed(uid).hand_in(&mut s); + let _ = s.execute("type.retype", &json!({"installed": false})); + assert!(s.retype_hand_off.is_none()); +} + +#[test] +fn a_canceled_search_stops_before_reading_a_file() { + let (db, _) = installed("cancel", &["Retype Copy J"]); + let shapes = glyphs(&db, "z"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || search(&db, &refs, false)); + assert!(matches!(r, Err(crate::EngineError::Cancelled))); + assert!(unloaded(&db, "Retype Copy J"), "nothing was loaded"); +} + +/// The shapes of `text` set in Source Sans 3 and outlined, as `type.retype` collects them. +fn pieces(text: &str) -> Vec { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = + s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 30, "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let group = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let d = &s.doc().unwrap().doc; + let node = d.node(vectorcraft_doc::NodeId(group)).unwrap(); + let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]); + super::super::collect(node, None, 0, &mut barrier, &mut truncated, &mut pieces); + pieces +} + +#[test] +fn retype_fills_the_shapes_no_loaded_font_matches_from_the_installed_fonts() { + let (db, _) = installed("retype", &["Retype Copy K"]); + let pieces = pieces("Wk-"); + assert_eq!(pieces.len(), 3); + let groups = vec![vec![]; pieces.len()]; + // The first shape is taken as matched already: the others are looked for. + let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()])); + let found = super::super::match_pieces(&pieces, &groups, &[&keep], 0.0); + assert!(!found[0].is_empty() && found[1].is_empty() && found[2].is_empty()); + let left = super::super::left_shapes(&pieces, &groups, &found); + assert_eq!(left.len(), 2); + let installed = super::search_for(&db, &left, 0.0, false).unwrap(); + assert_eq!(installed.read, 1); + // The faces found join the index, and every shape is matched again. + let all_keys = keys(&pieces.iter().map(|pc| pc.path.clone()).collect::>()); + let extra = super::super::RetypeIndex::build(&db, installed.faces.iter().cloned(), &all_keys); + let found = super::super::match_pieces(&pieces, &groups, &[&keep, &extra], 0.0); + let whole = |k: usize| found[k].first().expect("one part").clone(); + assert_eq!(whole(0).first().map(|m| m.face.family.as_str()), Some("Source Sans 3"), "a matched shape keeps its match"); + // and gets the face found too, so its line can be set in the face the others match. + assert!(whole(0).iter().any(|m| m.face.family == "Retype Copy K" && m.ch == 'W'), "the W also matches the face found"); + let k = whole(1); + let m = k.first().expect("the installed copy matches the k"); + assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", 'k')); + assert!(db.loaded_faces().iter().any(|f| f.id() == m.face.id()), "the match is in a loaded face"); + // The hyphen, a plain shape, matches the font the k found. + let hyphen = whole(2); + let m = hyphen.first().expect("the installed copy matches the hyphen"); + assert_eq!((m.face.family.as_str(), m.ch), ("Retype Copy K", '-')); +} + +/// `path` flattened into lines `tol` from its curves, each contour started at its second point +/// and run backwards: an outline built nothing like the font's. +fn simplified(path: &BezPath, tol: f64) -> BezPath { + let mut contours: Vec> = vec![]; + kurbo::flatten(path.iter(), tol, |el| match el { + kurbo::PathEl::MoveTo(q) => contours.push(vec![q]), + kurbo::PathEl::LineTo(q) => contours.last_mut().unwrap().push(q), + _ => {} + }); + let mut out = BezPath::new(); + for mut c in contours { + if c.len() > 1 && c.first() == c.last() { + c.pop(); + } + c.rotate_left(1); + c.reverse(); + out.move_to(c[0]); + for q in &c[1..] { + out.line_to(*q); + } + out.close_path(); + } + out +} + +#[test] +fn an_installed_face_is_found_through_the_glyphs_of_a_split_shape_and_through_near_matches() { + // A word outlined as one compound path: the whole shape is no glyph, and its glyphs are. + let (db, _) = installed("split", &["Retype Copy Split"]); + let mut word = BezPath::new(); + for g in glyphs(&db, "Wk") { + word.extend(g.iter()); + } + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap(); + assert_eq!(found.read, 1); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Copy Split"], "the face the split's glyphs match is found"); + assert!(!unloaded(&db, "Retype Copy Split")); + // A simplified outline: no installed glyph matches it exactly, and one does within a tolerance. + let (db, _) = installed("near", &["Retype Copy Near"]); + let r = simplified(&glyphs(&db, "R")[0], 0.05); + let shape = [super::Sought::unpainted(&r, &[])]; + let exact = super::search_for(&db, &shape, 0.0, false).unwrap(); + assert_eq!((exact.read, exact.faces.len()), (1, 0)); + assert!(unloaded(&db, "Retype Copy Near")); + let near = super::search_for(&db, &shape, 0.02, false).unwrap(); + let families: Vec<&str> = near.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Copy Near"], "the face the outline nearly matches is found"); + assert!(!unloaded(&db, "Retype Copy Near")); +} + +#[test] +fn a_split_shape_whose_glyphs_are_in_different_installed_faces_finds_them_all() { + // A W of Source Sans 3 and a k of Inter, outlined as one compound path, with a copy of each + // font installed: neither face holds both glyphs. + let dir = vectorcraft_testkit::temp_dir("retype-installed-split-two"); + for (inter, family) in [(false, "Retype Mix S"), (true, "Retype Mix I")] { + let postscript = format!("{}-Regular", family.replace(' ', "")); + let data = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", "Version 1.000", &postscript)).unwrap(); + std::fs::write(dir.join(format!("{postscript}.ttf")), data).unwrap(); + } + let db = FontDb::with_font_dirs(vec![dir]); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap(); + assert_eq!(found.read, 2); + let mut families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + families.sort_unstable(); + assert_eq!(families, ["Retype Mix I", "Retype Mix S"], "the faces of both glyphs are found"); + assert!(!unloaded(&db, "Retype Mix S") && !unloaded(&db, "Retype Mix I")); +} + +#[test] +fn a_split_shape_completes_with_the_loaded_faces_it_is_searched_beside() { + // A W of Source Sans 3 and a k of Inter, outlined as one compound path. Source Sans 3 is the + // loaded face compared first; the only other face is an installed copy of Inter. + let dir = vectorcraft_testkit::temp_dir("retype-installed-beside"); + let data = vectorcraft_text::test_fonts::named_copy(true, ("Retype Beside I", "Regular", "Version 1.000", "RetypeBesideI-Regular")).unwrap(); + std::fs::write(dir.join("RetypeBesideI-Regular.ttf"), data).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (keys, near) = super::keys_of(&shapes, 0.0); + let first = super::super::RetypeIndex::build_near(&db, db.face("Source Sans 3", "Regular"), &keys, &near); + let found = super::search_beside(&db, &shapes, &[&first], 0.0, false).unwrap(); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Source Sans 3", "Retype Beside I"], "the installed face completes the loaded face's glyphs"); +} + +#[test] +fn one_loaded_face_per_glyph_completes_a_split_shape_however_many_hold_it() { + // A W of Source Sans 3 and a k of Inter in one compound path. More loaded copies of Source + // Sans 3 than a search finds faces hold the W; an installed copy of Inter holds the k. + let n = vectorcraft_text::retype::MAX_FACES + 4; + let dir = vectorcraft_testkit::temp_dir("retype-installed-many"); + let data = vectorcraft_text::test_fonts::named_copy(true, ("Retype Many I", "Regular", "Version 1.000", "RetypeManyI-Regular")).unwrap(); + std::fs::write(dir.join("RetypeManyI-Regular.ttf"), data).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + for i in 0..n { + let family = format!("Retype Many {i}"); + db.add_font( + vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("RetypeMany{i}-Regular"))).unwrap(), + ); + } + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (keys, near) = super::keys_of(&shapes, 0.0); + let copies: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Many ")).collect(); + assert_eq!(copies.len(), n); + let indexes: Vec = copies + .chunks(vectorcraft_text::retype::MAX_FACES) + .map(|g| super::super::RetypeIndex::build_near(&db, g.iter().cloned(), &keys, &near)) + .collect(); + let beside: Vec<&super::super::RetypeIndex> = indexes.iter().collect(); + let found = super::search_beside(&db, &shapes, &beside, 0.0, false).unwrap(); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families.len(), 2, "{families:?}"); + assert_eq!(families.last(), Some(&"Retype Many I")); +} + +#[test] +fn a_split_shape_completes_with_loaded_faces_past_the_first_and_installed_ones() { + // A W of Source Sans 3 and a k of Inter in one compound path. Past the faces compared first + // (the bundled ones), a loaded copy of Inter holds the k and an installed copy of Source Sans 3 + // the W. + let dir = vectorcraft_testkit::temp_dir("retype-installed-kept"); + let data = vectorcraft_text::test_fonts::named_copy(false, ("Retype Kept S", "Regular", "Version 1.000", "RetypeKeptS-Regular")).unwrap(); + std::fs::write(dir.join("RetypeKeptS-Regular.ttf"), data).unwrap(); + let db = FontDb::with_font_dirs(vec![dir]); + let compared: Vec = db.loaded_faces().iter().map(|f| f.id()).collect(); + db.add_font(vectorcraft_text::test_fonts::named_copy(true, ("Retype Kept I", "Regular", "Version 1.000", "RetypeKeptI-Regular")).unwrap()); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (rest, done, kept) = super::loaded_rest_for(&db, &shapes, &[], 0.0, &compared).unwrap(); + assert!(rest.is_empty() && done == [false]); + assert_eq!(kept.len(), 1, "the group with the k is kept for the installed fonts"); + let beside: Vec<&super::super::RetypeIndex> = kept.iter().collect(); + let found = super::search_beside(&db, &shapes, &beside, 0.0, false).unwrap(); + let families: Vec<&str> = found.faces.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Kept I", "Retype Kept S"], "the loaded copy's k and the installed copy's W"); +} + +#[test] +fn an_installed_face_whose_glyphs_paint_otherwise_than_the_shape_is_not_found() { + // Two o's moved onto each other in one compound path filled by the even-odd rule: the overlap + // is unpainted, and two glyphs set side by side would paint it. + let paths = |db: &FontDb| { + let face = db.face("Source Sans 3", "Regular").unwrap(); + let o = Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('o')); + let mut word = BezPath::new(); + for x in [40.0, 49.0] { + word.extend((Affine::translate((x, 100.0)) * o.clone()).iter()); + } + word + }; + let (db, _) = installed("paint", &["Retype Copy Paint"]); + let word = paths(&db); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let even_odd = super::Sought { path: &word, groups: &groups, fill: Some(false), once: true }; + let found = super::search_for(&db, &[even_odd], 0.0, false).unwrap(); + assert_eq!((found.read, found.faces.len()), (1, 0), "the o's paint the overlap"); + assert!(unloaded(&db, "Retype Copy Paint")); + // Without a fill to compare, the same glyphs are found. + let (db, _) = installed("paint-none", &["Retype Copy Unpainted"]); + let word = paths(&db); + let found = super::search_for(&db, &[super::Sought::unpainted(&word, &groups)], 0.0, false).unwrap(); + assert_eq!(found.faces.len(), 1); +} + +#[test] +fn retype_reads_no_installed_font_for_plain_shapes_alone() { + let (db, _) = installed("retype-plain", &["Retype Copy M"]); + let pieces = pieces("W-"); + let groups = vec![vec![]; pieces.len()]; + let keep = super::super::RetypeIndex::build(&db, db.face("Source Sans 3", "Regular"), &keys(&[pieces[0].path.clone()])); + let found = super::super::match_pieces(&pieces, &groups, &[&keep], 0.0); + let left = super::super::left_shapes(&pieces, &groups, &found); + assert_eq!(left.len(), 1, "the hyphen is left"); + let installed = super::search_for(&db, &left, 0.0, false).unwrap(); + assert_eq!((installed.read, installed.faces.len()), (0, 0)); + assert!(unloaded(&db, "Retype Copy M")); +} + +#[test] +fn installed_must_be_a_bool_or_null() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + for cmd in ["type.retype", "type.retypeFonts"] { + for bad in [json!(1), json!("yes"), json!([])] { + let e = s.execute(cmd, &json!({"installed": bad})).unwrap_err().to_string(); + assert!(e.contains("`installed` must be true, false or null"), "{cmd} {bad}: {e}"); + } + } + // false: no installed font is read, and the result says so. + let r = s.execute("type.retypeFonts", &json!({"installed": false})).unwrap(); + assert_eq!(r["installed"], json!({"read": 0, "skipped": 0}), "{r}"); +} + +/// A database with no installed fonts and `n` copies of the bundled Source Sans 3 Regular loaded, +/// named `{tag} 0` to `{tag} n-1`, after `inter` copies of Inter named `{tag} Inter 0` and on. +fn loaded_copies(tag: &str, inter: usize, n: usize) -> FontDb { + let db = FontDb::with_font_dirs(vec![]); + let copies = (0..inter).map(|i| (true, format!("{tag} Inter {i}"))).chain((0..n).map(|i| (false, format!("{tag} {i}")))); + for (inter, family) in copies { + let postscript = format!("{}-Regular", family.replace(' ', "")); + db.add_font(vectorcraft_text::test_fonts::named_copy(inter, (&family, "Regular", "Version 1.000", &postscript)).unwrap()); + } + db +} + +#[test] +fn loaded_faces_past_the_ones_compared_first_are_compared_too() { + let n = vectorcraft_text::retype::MAX_FACES + 4; + let db = loaded_copies("Retype Rest", 0, n); + let shapes = glyphs(&db, "Rx"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // Every loaded face that matches, more than one index takes. + let rest = super::loaded_rest(&db, &refs, &[]).unwrap(); + for i in 0..n { + assert!(rest.iter().any(|f| f.family == format!("Retype Rest {i}")), "copy {i} of {}", rest.len()); + } + // The faces compared already are left out. + let last = format!("Retype Rest {}", n - 1); + let compared: Vec = db.loaded_faces().iter().filter(|f| f.family != last).map(|f| f.id()).collect(); + let rest = super::loaded_rest(&db, &refs, &compared).unwrap(); + assert_eq!(rest.iter().map(|f| f.family.as_str()).collect::>(), [last.as_str()]); + // A plain shape alone compares none. + let bar = [kurbo::Rect::new(0.0, 0.0, 80.0, 10.0).to_path(0.1)]; + assert!(super::loaded_rest(&db, &[&bar[0]], &[]).unwrap().is_empty()); +} + +#[test] +fn a_split_shape_completes_with_loaded_faces_past_the_ones_compared_first() { + // A W of Source Sans 3 and a k of Inter in one compound path. Source Sans 3 and Inter are + // compared first; past them, a loaded copy of Inter holds the k. + let db = loaded_copies("Retype Rest Split", 1, 0); + let mut word = BezPath::new(); + word.extend(glyphs(&db, "W")[0].iter()); + let inter = db.face("Inter", "Regular").unwrap(); + let k = Affine::translate((70.0, 100.0)) * Affine::scale(0.03) * db.outline_uncached(&inter, inter.glyph_for('k')); + word.extend(k.iter()); + let mut budget = super::super::MAX_SPLIT_TOTAL_CONTOURS; + let groups = super::super::split_groups(&word, &mut budget); + assert_eq!(groups.len(), 2); + let shapes = [super::Sought::unpainted(&word, &groups)]; + let (keys, near) = super::keys_of(&shapes, 0.0); + let source = db.face("Source Sans 3", "Regular").unwrap(); + let compared = [source.id(), inter.id()]; + let first = super::super::RetypeIndex::build_near(&db, [source], &keys, &near); + let (rest, done, kept) = super::loaded_rest_for(&db, &shapes, &[&first], 0.0, &compared).unwrap(); + assert!(kept.is_empty(), "no split shape is left"); + let families: Vec<&str> = rest.iter().map(|f| f.family.as_str()).collect(); + assert_eq!(families, ["Retype Rest Split Inter 0"], "the copy completes the glyphs of the face compared first"); + assert_eq!(done, [true]); +} + +#[test] +fn files_past_the_glyph_budget_are_skipped_without_being_read() { + let (db, mut files) = installed("budget-spent", &["Retype Copy E1", "Retype Copy E2"]); + let shapes = glyphs(&db, "k"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + // The order the search reads them in: smallest first. + let len = |p: &PathBuf| std::fs::metadata(p).unwrap().len(); + files.sort_by(|a, b| len(a).cmp(&len(b)).then_with(|| a.cmp(b))); + assert_eq!(db.unloaded_installed_faces().len(), 2); + let face = db.read_unloaded_file(&files[0], u64::MAX).faces.into_iter().next().unwrap(); + let drawn = vectorcraft_text::retype::encoded_glyphs(&face); + // The second file holds no font after the listing: had it been read, it would give no face + // to skip. + std::fs::write(&files[1], vec![0u8; len(&files[1]) as usize]).unwrap(); + let limits = Limits { file: u64::MAX, read: u64::MAX, glyphs: drawn, faces: usize::MAX }; + let found = search_within(&db, &refs, true, limits, &|_| true).unwrap(); + assert_eq!((found.read, found.skipped, found.faces.len()), (1, 1, 1)); +} + +#[test] +fn a_run_away_from_the_command_hands_in_the_loaded_faces_past_the_ones_compared_first() { + let db = loaded_copies("Retype Run Rest", vectorcraft_text::retype::MAX_FACES, 1); + let shapes = glyphs(&db, "Rx"); + // The Inter copies are compared first: none matches, and the copy loaded after them does. + let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Run Rest Inter")).collect(); + assert_eq!(faces.len(), vectorcraft_text::retype::MAX_FACES); + let search = + super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes.clone()), faces: super::Faces::Given(faces), tolerance: 0.0 }; + let found = search.run_in(&db).unwrap(); + assert!(found.installed.faces.iter().any(|f| f.family == "Retype Run Rest 0"), "the loaded copy is handed in"); + assert_eq!((found.installed.read, found.installed.skipped), (0, 0), "no installed file is read for it"); + // Every loaded face was compared: the command does not compare them again. + assert!(db.loaded_faces().iter().all(|f| found.installed.scanned.contains(&f.id()))); + // A face compared first that matches is handed in too, as loading others may move it past + // the faces the command compares first. + let copy: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family == "Retype Run Rest 0").collect(); + let found = super::RetypeSearch { command: "type.retype", doc: 1, shapes: whole(shapes), faces: super::Faces::Given(copy), tolerance: 0.0 } + .run_in(&db) + .unwrap(); + assert_eq!(found.installed.faces.first().map(|f| f.family.as_str()), Some("Retype Run Rest 0")); +} + +#[test] +fn a_full_list_counts_skipped_installed_faces_only_when_a_shape_would_start_a_search() { + let (db, _) = installed("full-list", &["Retype Copy Full"]); + for i in 0..super::super::fonts::MAX_COUNT { + let family = format!("Retype Full {i}"); + let postscript = format!("RetypeFull{i}-Regular"); + db.add_font(vectorcraft_text::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &postscript)).unwrap()); + } + let faces: Vec<_> = db.loaded_faces().into_iter().filter(|f| f.family.starts_with("Retype Full ")).collect(); + // A hyphen is plain: it fills the list and would start no search, so nothing is skipped. + let hyphen = glyphs(&db, "-"); + let refs: Vec<&BezPath> = hyphen.iter().collect(); + let (ranked, found) = super::super::fonts::rank_fonts(&db, faces.clone(), &refs, true, None).unwrap(); + assert_eq!(ranked.len(), super::super::fonts::MAX_COUNT); + assert_eq!((found.read, found.skipped), (0, 0)); + // A shape that is not plain would: the installed face counts as skipped. + let shapes = glyphs(&db, "-q"); + let refs: Vec<&BezPath> = shapes.iter().collect(); + let (_, found) = super::super::fonts::rank_fonts(&db, faces, &refs, true, None).unwrap(); + assert_eq!((found.read, found.skipped), (0, 1)); + assert!(unloaded(&db, "Retype Copy Full")); +} + +#[test] +fn what_is_handed_in_and_not_taken_can_be_dropped() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let doc = s.doc().unwrap().uid; + super::RetypeFound { doc, installed: super::Installed::default() }.hand_in(&mut s); + assert!(s.retype_hand_off.is_some()); + super::RetypeFound::drop_handed(&mut s); + assert!(s.retype_hand_off.is_none()); +} diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 5e000d52ab..b386758690 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -123,11 +123,13 @@ fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() { #[test] fn a_combining_mark_starts_no_line() { // A combining mark on its own (a drawn dot, bar or ring is the same shape) stays an outline. + // The calls that leave a shape an outline leave the installed fonts out, so what this machine + // has installed does not change the result. let mut s = session(); let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("no selected shape matches"), "{e}"); assert!(s.doc().unwrap().doc == before, "nothing changes"); // A shape that is both a mark (tilde below) and a character (small tilde) starts its line as @@ -145,7 +147,7 @@ fn a_combining_mark_starts_no_line() { let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "\u{312}ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[0].id.0; s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["ab"]), "{r}"); assert_eq!(r["unmatched"], json!([mark])); // After a base, the mark is retyped with it. @@ -160,7 +162,7 @@ fn a_combining_mark_starts_no_line() { s.execute("select.set", &json!({"ids": [mark]})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yz"]), &json!([mark])), "{r}"); // A mark that is also another character (dot below, dot above) becomes that character there. let g = outlined(&mut s, json!({"x": 300, "y": 120, "text": "x\u{323}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); @@ -183,7 +185,7 @@ fn a_combining_mark_starts_no_line() { s.execute("select.set", &json!({"ids": [mark]})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yzw"]), &json!([mark])), "{r}"); assert_eq!(r["fonts"][1]["tracking"], json!(50.0), "{r}"); // A one-contour glyph after a mark that stays an outline (a bar, then a dot) is alone, and @@ -193,7 +195,7 @@ fn a_combining_mark_starts_no_line() { pair.sort_unstable(); let word = outlined(&mut s, json!({"x": 40, "y": 380, "text": "ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); s.execute("select.set", &json!({"ids": [dot, word]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["ab"]), "{r}"); let mut left: Vec = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); left.sort_unstable(); @@ -246,7 +248,8 @@ fn marks_first_after_a_split_leave_other_lines_their_tracking() { s.execute("select.set", &json!({"ids": moved})).unwrap(); s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); s.execute("select.set", &json!({"ids": [marks, tracked]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); let texts = r["texts"].as_array().unwrap(); let at = texts.iter().position(|t| t == "yzw").unwrap_or_else(|| panic!("yzw in {r}")); assert_eq!(r["fonts"][at]["tracking"], json!(50.0), "{r}"); @@ -374,7 +377,7 @@ fn an_open_path_along_a_glyph_is_not_a_glyph() { }) .unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - assert!(s.execute("type.retype", &json!({})).is_err(), "nothing matches"); + assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nothing matches"); } #[test] @@ -488,7 +491,8 @@ fn a_glyph_painted_beyond_what_type_takes_stays_an_outline() { }) .unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["B"]), "two fills: A stays an outline: {r}"); assert_eq!(r["unmatched"], json!([a])); } @@ -551,7 +555,8 @@ fn a_drawn_dot_or_bar_beside_type_stays_art() { // A bar that is exactly a hyphen of the font, somewhere else: the worst case. let bar = outlined(&mut s, json!({"x": 200, "y": 300, "text": "-", "size": 50})); s.execute("select.set", &json!({"ids": [g, dot, bar]})).unwrap(); - let r = s.execute("type.retype", &json!({})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})).unwrap(); assert_eq!(r["texts"], json!(["AB"]), "{r}"); let un = r["unmatched"].as_array().unwrap(); assert!(un.contains(&json!(dot)) && un.len() == 2, "the dot and the bar stay art: {r}"); @@ -754,7 +759,8 @@ fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() { simplify_every_path(&mut s, 0.05); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + // The installed fonts left out: what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("no selected shape matches"), "no exact match: {e}"); for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true), json!(null)] { let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string(); @@ -825,8 +831,9 @@ fn two_overlapping_lone_glyphs_beside_art_stay_outlines() { let b = outlined(&mut s, json!({"x": 49, "y": 100, "text": "M", "size": 30})); let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [a, b, dot]})).unwrap(); - // Nothing is left to retype: both stay outlines, as the lone bar beside art does. - let e = s.execute("type.retype", &json!({})).unwrap_err(); + // Nothing is left to retype: both stay outlines, as the lone bar beside art does. The installed + // fonts are left out, so what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err(); assert!(format!("{e:?}").contains("no selected shape matches"), "{e:?}"); } @@ -1363,7 +1370,8 @@ fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the period became type: {r}"), Err(e) => e.to_string(), }; @@ -1423,7 +1431,8 @@ fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + // The installed fonts left out: what this machine has installed does not change the result. + let e = s.execute("type.retype", &json!({"installed": false})).unwrap_err().to_string(); assert!(e.contains("(1 checked)"), "reported once: {e}"); assert!(s.doc().unwrap().doc == before, "nothing changes"); } @@ -1440,7 +1449,8 @@ fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() { let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the overlapping o's became type: {r}"), Err(e) => e.to_string(), }; @@ -1481,7 +1491,8 @@ fn a_translucent_compound_whose_glyphs_overlap_stays_an_outline() { }) .unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); - let r = s.execute("type.retype", &json!({})); + // The installed fonts left out: what this machine has installed does not change the result. + let r = s.execute("type.retype", &json!({"installed": false})); if opacity == 1.0 { let r = r.unwrap(); assert_eq!(r["texts"], json!(["i", "i"]), "opaque, the two lines become type: {r}"); @@ -1502,8 +1513,9 @@ fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() { s.execute("select.set", &json!({"ids": kids})).unwrap(); let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); + // The installed fonts left out: what this machine has installed does not change the result. for tolerance in [0.0, 0.05] { - if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance})) { + if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance, "installed": false})) { panic!("the overlapping o's became type at dx {dx}, tolerance {tolerance}: {r}"); } } @@ -1564,7 +1576,8 @@ fn a_glyph_with_only_some_contours_turned_in_an_even_odd_compound_still_becomes_ }) .unwrap(); s.execute("select.set", &json!({"ids": [c]})).unwrap(); - assert!(s.execute("type.retype", &json!({})).is_err(), "nonzero, contour {turned} turned paints the counter"); + // The installed fonts left out: what this machine has installed does not change the result. + assert!(s.execute("type.retype", &json!({"installed": false})).is_err(), "nonzero, contour {turned} turned paints the counter"); s.execute("path.setFillRule", &json!({"rule": "evenOdd", "ids": [c]})).unwrap(); let r = s.execute("type.retype", &json!({})).unwrap(); assert_eq!(r["texts"], json!(["do"]), "contour {turned} turned: {r}"); @@ -1591,7 +1604,8 @@ fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() { let r = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [c, r]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let e = match s.execute("type.retype", &json!({})) { + // The installed fonts left out: what this machine has installed does not change the result. + let e = match s.execute("type.retype", &json!({"installed": false})) { Ok(r) => panic!("the A became type without its period: {r}"), Err(e) => e.to_string(), }; diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 2640433606..4529cef221 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -90,6 +90,15 @@ pub fn specs() -> Vec { always, list_installed ), + cmd!( + query "script.startup.run", + "Run Startup Scripts", + [], + None, + "{reason: launch|menu (launch: the app starting; menu: before a script chosen from File › Scripts), then?: script.run's parameters (the script to run once the startup scripts have run; its source is read once and must compile before enabled startup scripts run), maxFuel?: whole number from 1 to 100000000000 (each startup script's instructions; default 1000000000)} run the .jsx files of the Startup Scripts folder next to the settings, one at a time, as script.run runs a file, each with the same limits as any script and its own undo step; nothing runs, and the reply says why, when the runStartupScripts preference is off (the default), in Safe Mode, or in a session without the folder (the web, and a run with VECTORCRAFT_NO_PREFS); only the folder's own .jsx files run, sorted by name without regard to case, then by name; links, hidden files, names starting with a dot, subfolders and other files are left out, and so is a script the Safe Mode choice disabled; a missing folder runs nothing; a script that cannot be read, is larger than 8 MiB, fails or is stopped is named in failed and in the Script Console, and the next one runs, then the script of then; while a startup script runs, the launch marker names it, so a launch that stops there offers to disable it; script.* commands are refused inside a script, so a startup script does not start another startup run. VectorCraft's own rules: the folder, the order, the limits of a listing (2048 folder entries, 512 scripts, 250 ms) and what a failure does → {reason, skipped: true, why: off|safeMode|noFolder, then?: script.run's reply} | {reason, skipped: false, ran: [names], failed: [{name, error}], disabled: [names], truncated, unreadable, then?: script.run's reply}, or, in the app, {reason, skipped: false, running, queued: the runs queued, then's included, failed: [{name, error}] (the runs that could not start before the first one did), disabled, truncated, unreadable, then?: script.run's reply when it ran to its end at once}, each run then reporting as script.run's do, and a later run that cannot start is named in the status bar, where the message of a startup script that fails or is stopped also stays; included files are read again when the chosen run starts; a preflight compilation failure clears the previous script report; each app queue pump processes at most one startup entry", + always, + startup_run + ), cmd!( query "script.grants", "List Script File Permissions", @@ -104,7 +113,7 @@ pub fn specs() -> Vec { "Revoke Script File Permissions", [], None, - "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", + "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as given, as script.grants lists it, or after its links are followed when no grant holds it as given (a path outside the automation read roots is matched as given only); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", always, grants_revoke ), @@ -149,6 +158,21 @@ const NOT_TEXT: &str = "the script is not UTF-8 text"; pub const TOO_LARGE: &str = "the script is too large to run"; fn run(s: &mut Session, p: &Value) -> Result { + let request = prepare(s, p)?; + run_prepared(s, request) +} + +fn run_prepared(s: &mut Session, request: script::Request) -> Result { + let name = s.script_start(request)?; + if s.script_frames { + return Ok(json!({"running": true, "name": name})); + } + s.script_run_to_end() +} + +/// The run `script.run`'s parameters `p` ask for, with its file read and checked, or the error that +/// keeps it from starting. +fn prepare(s: &Session, p: &Value) -> Result { let optional_str = |key: &str| match p.get(key) { None => Ok(None), Some(Value::String(t)) => Ok(Some(t.as_str())), @@ -207,7 +231,7 @@ fn run(s: &mut Session, p: &Value) -> Result { }; let name = given_name.map(str::to_string).or_else(|| path.map(super::fileio::file_name)).unwrap_or_else(|| "script".to_string()); let locale = script::dollar::ui_locale(s.ui_language.as_deref().unwrap_or(&s.prefs.interface_language)); - let request = script::Request { + Ok(script::Request { name, name_given: given_name.is_some(), file: path.map(str::to_string), @@ -217,12 +241,7 @@ fn run(s: &mut Session, p: &Value) -> Result { fuel, locale, answers, - }; - let name = s.script_start(request)?; - if s.script_frames { - return Ok(json!({"running": true, "name": name})); - } - s.script_run_to_end() + }) } fn stop(s: &mut Session, _: &Value) -> Result { @@ -342,6 +361,278 @@ impl Session { } } +/// The error of a startup script that is no longer a `.jsx` file of the Startup Scripts folder, or +/// cannot be read, when its turn comes. +pub const STARTUP_UNREADABLE: &str = "the startup script could not be read"; + +impl Session { + /// Have `script.startup.run` run the scripts of the folder `dir`. The folder is only read, and + /// never made. + pub fn attach_startup_scripts_dir(&mut self, dir: std::path::PathBuf) { + self.startup_scripts_dir = Some(dir); + } + + /// The Startup Scripts folder ([`Session::attach_startup_scripts_dir`]); none on the web. + pub fn startup_scripts_dir(&self) -> Option<&std::path::Path> { + self.startup_scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } + + /// Why `script.startup.run` runs nothing now: `off` (the `runStartupScripts` preference), + /// `safeMode`, or `noFolder` (no Startup Scripts folder); `None` when it runs the folder. + pub fn startup_skip(&self) -> Option<&'static str> { + if !self.prefs.run_startup_scripts { + Some("off") + } else if vectorcraft_plugins::safe_mode::active() { + Some("safeMode") + } else if self.startup_scripts_dir().is_none() { + Some("noFolder") + } else { + None + } + } + + /// The startup script that ran has ended: the launch marker no longer names it. + pub(crate) fn startup_ended(&mut self) { + if let Some(token) = self.startup_loading.take() { + vectorcraft_plugins::safe_mode::loaded(token); + } + } + + /// The running script is a startup script (`script.startup.run`), not the script queued after + /// them. + pub fn startup_script_running(&self) -> bool { + self.startup_loading.is_some() + } + + /// Begins a run of the startup script at `path`, read now and checked as `script.run` checks a + /// file, with the launch marker naming it while it runs. → the run's name, or the error that kept + /// it from starting, which the Script Console also shows. + fn start_startup(&mut self, path: &std::path::Path, fuel: u64) -> std::result::Result { + let name = file_name_of(path); + let text = self.startup_text(path); + let (text, real) = match text { + Ok(read) => read, + Err(message) => { + self.note_unread(&name, &message); + return Err(message); + } + }; + let item = startup_item(path); + self.startup_loading = Some(vectorcraft_plugins::safe_mode::loading(&item)); + let locale = script::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language)); + let request = script::Request { + name: name.clone(), + name_given: false, + file: Some(path.to_string_lossy().into_owned()), + checked_real: Some(real), + source: text, + args: serde_json::Map::new(), + fuel, + locale, + answers: vec![], + }; + let runs = self.script_runs; + self.script_start(request).map_err(|e| { + self.startup_ended(); + let message = e.to_string(); + // A run refused before it began, such as with an undo group open, has no console entry yet. + if self.script_runs == runs { + self.note_unread(&name, &message); + } + message + }) + } + + /// The text of the startup script at `path` and its real path, or the error that keeps it from + /// running. + fn startup_text(&self, path: &std::path::Path) -> std::result::Result<(String, std::path::PathBuf), String> { + let unreadable = || STARTUP_UNREADABLE.to_string(); + let root = self.startup_scripts_dir().ok_or_else(unreadable)?; + let mut real = std::fs::canonicalize(root).map_err(|_| unreadable())?; + real.push(path.file_name().ok_or_else(unreadable)?); + // One byte more than a script may have shows that the file is too large. + let bytes = script::startup::read(root, path, script::MAX_SOURCE_BYTES + 1).ok_or_else(unreadable)?; + if bytes.len() > script::MAX_SOURCE_BYTES { + return Err(TOO_LARGE.to_string()); + } + Ok((script_text(&bytes).map_err(|e| e.to_string())?, real)) + } + + /// With no script running, starts the next run `script.startup.run` queued: the next startup + /// script that starts, or the script queued after them. A run that cannot start is kept for + /// [`Self::take_startup_failures`], and the next one starts on a later pump. → the reply of the script queued + /// after them when it ran to its end at once. + pub(crate) fn start_queued(&mut self) -> Option { + // Held aside while a run starts, so that the queue does not count as a running script then. + let mut queue = std::mem::take(&mut self.script_queue); + // Each run starts in the file access scope of the request that queued it, which the run + // keeps, and not in the scope of the frame that starts it. + let scope = self.script_queue_scope.clone().unwrap_or_else(crate::file_access::ScopeHandle::capture); + let mut reply = None; + if self.script_key.is_none() + && let Some(next) = queue.pop_front() + { + match next { + script::startup::Queued::Startup { path, fuel } => { + if let Err(e) = scope.clone().run(|| self.start_startup(&path, fuel)) { + self.startup_failures.push((file_name_of(&path), e)); + } + } + script::startup::Queued::Then(params) => { + let prepared = self.script_queue_then.take(); + match scope.clone().run(|| match prepared { + Some(request) => run_prepared(self, request), + None => run(self, ¶ms), + }) { + Ok(_) if self.script_key.is_some() => {} + Ok(v) => reply = Some(v), + Err(e) => self.startup_failures.push((then_name(¶ms), e.to_string())), + } + } + } + } + if queue.is_empty() { + self.script_queue_scope = None; + self.script_queue_then = None; + } + self.script_queue = queue; + reply + } + + /// The runs `script.startup.run` queued that could not start since the last call, as (name, + /// error), in order. + pub fn take_startup_failures(&mut self) -> Vec<(String, String)> { + std::mem::take(&mut self.startup_failures) + } +} + +/// The file name of `path`, or the whole path when it has none. +fn file_name_of(path: &std::path::Path) -> String { + path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned()) +} + +/// The name a failure of the script `params` (`script.run`'s) names it by: `name`, else the file +/// name of `path`, else "script". +fn then_name(params: &Value) -> String { + let given = |key: &str| params.get(key).and_then(Value::as_str).filter(|v| !v.trim().is_empty()); + match (given("name"), given("path")) { + (Some(name), _) => name.to_string(), + (None, Some(path)) => file_name_of(std::path::Path::new(path)), + (None, None) => "script".to_string(), + } +} + +/// The launch marker's entry for the startup script at `path`: its file and its file name. +fn startup_item(path: &std::path::Path) -> vectorcraft_plugins::safe_mode::Item { + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()); + vectorcraft_plugins::safe_mode::Item { id: None, file: Some(path.to_string_lossy().into_owned()), name } +} + +fn startup_run(s: &mut Session, p: &Value) -> Result { + const C: &str = "script.startup.run"; + let reason = match p.get("reason").and_then(Value::as_str) { + Some(r @ ("launch" | "menu")) => r, + _ => { + let key = "reason"; + return Err(bad(C, format!("`{key}` must be one of {}", "launch, menu"))); + } + }; + let then = match p.get("then") { + None => None, + Some(v @ Value::Object(_)) => Some(v.clone()), + Some(_) => { + let key = "then"; + return Err(bad(C, format!("`{key}` must be an object"))); + } + }; + let fuel = match p.get("maxFuel") { + None => script::DEFAULT_FUEL, + Some(v) => v.as_u64().filter(|n| (1..=script::MAX_FUEL).contains(n)).ok_or_else(|| EngineError::BadParams { + cmd: C.into(), + msg: format!("`maxFuel` must be a whole number from 1 to {}", script::MAX_FUEL), + })?, + }; + if s.script_running() { + return Err(EngineError::Busy); + } + // A chosen script that cannot start ends the request before any startup script runs, and its + // parameters are checked as `script.run` checks them. + if let Some(then) = &then { + super::params::check_params("script.run", then)?; + } + let root = match (s.startup_skip(), s.startup_scripts_dir()) { + (None, Some(root)) => root.to_path_buf(), + (why, _) => { + let mut out = json!({"reason": reason, "skipped": true, "why": why.unwrap_or("noFolder")}); + if let Some(then) = then { + out["then"] = run(s, &then)?; + } + return Ok(out); + } + }; + let prepared = then.as_ref().map(|params| prepare(s, params)).transpose()?; + if let Some(request) = &prepared { + let mut preflight = Session::new(); + if let Err(error) = preflight.script_start(request.clone()) { + s.script_report = None; + return Err(error); + } + } + let folder = root.to_string_lossy().into_owned(); + // The folder is the app's: a refusal names it as the request may see it. + crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?; + let listing = script::startup::list(&root); + let name_of = |path: &std::path::Path| path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let (disabled, scripts): (Vec<_>, Vec<_>) = + listing.scripts.into_iter().partition(|path| vectorcraft_plugins::safe_mode::skipped(&startup_item(path))); + let disabled: Vec = disabled.iter().map(|p| name_of(p)).collect(); + if s.script_frames { + s.script_queue = + scripts.into_iter().map(|path| script::startup::Queued::Startup { path, fuel }).chain(then.map(script::startup::Queued::Then)).collect(); + s.script_queue_scope = Some(crate::file_access::ScopeHandle::capture()); + s.script_queue_then = prepared; + let queued = s.script_queue.len(); + s.startup_failures.clear(); + let then = s.start_queued(); + let failed: Vec = s.take_startup_failures().into_iter().map(|(name, error)| json!({"name": name, "error": error})).collect(); + let mut out = json!({ + "reason": reason, + "skipped": false, + "running": s.script_running(), + "queued": queued, + "failed": failed, + "disabled": disabled, + "truncated": listing.truncated, + "unreadable": listing.unreadable, + }); + if let Some(then) = then { + out["then"] = then; + } + return Ok(out); + } + let (mut ran, mut failed) = (vec![], vec![]); + for path in scripts { + let name = name_of(&path); + match s.start_startup(&path, fuel).map_err(EngineError::Other).and_then(|_| s.script_run_to_end()) { + Ok(_) => ran.push(name), + Err(e) => failed.push(json!({"name": name, "error": e.to_string()})), + } + } + let mut out = json!({ + "reason": reason, + "skipped": false, + "ran": ran, + "failed": failed, + "disabled": disabled, + "truncated": listing.truncated, + "unreadable": listing.unreadable, + }); + if let Some(request) = prepared { + out["then"] = run_prepared(s, request)?; + } + Ok(out) +} + /// The file name a reply names `path` by when the file is outside the automation read roots; `None` /// when a reply may name it whole. fn hidden_name(path: &str) -> Option { @@ -384,16 +675,19 @@ fn grants(s: &mut Session, _: &Value) -> Result { fn grants_revoke(s: &mut Session, p: &Value) -> Result { const C: &str = "script.grants.revoke"; + // A path is matched as given, or with its links followed when no grant holds it as given, so a + // grant whose path a link has since taken the place of is still removed. A path the request may not read (outside the + // automation read roots, a network path among them) is compared as written, without looking it up. let path_of = |key: &str| match p.get(key) { None => Ok(None), - // A path the request may not read (outside the automation read roots, a network path among - // them) is compared as written, without looking it up. - Some(Value::String(t)) if !t.is_empty() => Ok(Some( - crate::file_access::check_read(t) + Some(Value::String(t)) if !t.is_empty() => { + let real = crate::file_access::check_read(t) .ok() .and_then(|()| std::fs::canonicalize(t).ok()) - .map_or_else(|| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()), - )), + .map(|real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()) + .filter(|real| real != t); + Ok(Some([Some(t.clone()), real].into_iter().flatten().collect::>())) + } Some(_) => Err(bad(C, format!("`{key}` must be a path"))), }; let (script_path, path) = (path_of("script")?, path_of("path")?); diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 78e56e8f33..1718b37d7e 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -241,7 +241,7 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result { let change = StrokeChange::parse(p, C)?; // The stroke the Live Paint Bucket paints with changes; the selection keeps its own, and its // active Appearance row is not a target. - let bucket_p = super::paint::bucket_color_params(s, p, C)?; + let bucket_p = super::paint::tool_color_params(s, p, C, true)?; let bucket = bucket_p.is_some(); let p = bucket_p.as_ref().unwrap_or(p); let item = item_target(s, p, C)?.of_kind(s, false); @@ -397,7 +397,7 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result { let unit = s.stroke_unit(); // The weight the Live Paint Bucket paints with changes; the selection keeps its own, and its // active Appearance row is not a target. - let bucket_p = super::paint::bucket_color_params(s, p, c)?; + let bucket_p = super::paint::tool_color_params(s, p, c, true)?; let bucket = bucket_p.is_some(); let p = bucket_p.as_ref().unwrap_or(p); let item = item_target(s, p, c)?.of_kind(s, false); @@ -450,7 +450,7 @@ impl Session { /// selection's stroke. pub fn shown_stroke(&self) -> Option { let st = self.active()?; - if self.bucket_paints() { + if self.tool_paints(true) { return Some(self.new_art_stroke()); } if let Some(part) = st.selected_symbol_part() { @@ -497,6 +497,32 @@ impl Session { /// and with a target that has no stroke row, since `stroke.set` gives such a target a plain /// stroke. pub fn brushed_strokes_profiled(&self) -> Option { + let st = self.active()?; + let strokes: Vec<&StrokeLayer> = self.edited_strokes(false)?.into_iter().map(|s| s.filter(|s| s.brush.is_some())).collect::>()?; + if strokes.is_empty() { + return None; + } + // The library is read only when every stroke names a brush. + let lib = vectorcraft_brush::library(&st.doc); + strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some())) + } + + /// Does any of the strokes that `stroke.set` edits without `ids` or `item` have a width + /// profile? The strokes are the ones [`Session::brushed_strokes_profiled`] reads, with or without + /// a brush. Type without an active Appearance row is left out, since `stroke.set` gives its + /// characters no profile. False with nothing selected, with an object inside a symbol instance + /// selected, and with a target that has no stroke row, which a profile from `stroke.set` would + /// give a plain stroke. + pub fn edited_strokes_profiled(&self) -> bool { + self.edited_strokes(true) + .and_then(|strokes| strokes.into_iter().collect::>>()) + .is_some_and(|strokes| strokes.iter().any(|s| s.profile.is_some())) + } + + /// The strokes that `stroke.set` edits without `ids` or `item`, one for each target, `None` for + /// a target without a stroke row (see [`Session::brushed_strokes_profiled`]). Type without an + /// active Appearance row is skipped with `skip_type`, and makes the result `None` without it. + fn edited_strokes(&self, skip_type: bool) -> Option>> { const C: &str = "stroke.set"; let st = self.active()?; if st.selected_symbol_part().is_some() { @@ -514,16 +540,14 @@ impl Session { let n = st.doc.node(*id)?; let row = each?.resolve(&n.appearance, false, C).ok()?; if row.is_none() && matches!(n.kind, NodeKind::Text(_)) { + if skip_type { + continue; + } return None; } - strokes.push(n.appearance.stroke_at(row).filter(|s| s.brush.is_some())?); + strokes.push(n.appearance.stroke_at(row)); } - if strokes.is_empty() { - return None; - } - // The library is read only when every stroke names a brush. - let lib = vectorcraft_brush::library(&st.doc); - strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some())) + Some(strokes) } } @@ -622,7 +646,7 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result { if brush.is_some() && super::switch_or(p, "defaultsOnly", false, C)? { return Err(bad(C, "`defaultsOnly` cannot be combined with `brush`")); } - let bucket_p = if brush.is_none() { super::paint::bucket_color_params(s, p, C)? } else { None }; + let bucket_p = if brush.is_none() { super::paint::tool_color_params(s, p, C, true)? } else { None }; let bucket = bucket_p.is_some(); let p = bucket_p.as_ref().unwrap_or(p); let item = item_target(s, p, C)?.of_kind(s, false); diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index c4db83826e..1d4a57bde3 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -1585,7 +1585,7 @@ fn add(s: &mut Session, p: &Value) -> Result { let mut out = json!({"library": shown_library_id(s, &info.id), "added": added_names, "existing": names(&existing)}); if let (Some(cmd), Some((_, first))) = (apply, picked.first()) { let name = added.iter().chain(&existing).find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone()); - let only = super::paint::defaults_only(s, p, C)?; + let only = super::paint::defaults_only(s, p, C, cmd == "paint.setStroke")?; s.execute(cmd, &super::paint::with_defaults_only(json!({"swatch": name, "focus": focus}), only))?; // Adding and applying undo together. squash(s, undo_before, "Add to Swatches"); diff --git a/crates/engine/src/cmd/tags.rs b/crates/engine/src/cmd/tags.rs new file mode 100644 index 0000000000..2c5fbbeceb --- /dev/null +++ b/crates/engine/src/cmd/tags.rs @@ -0,0 +1,195 @@ +//! An object's tags: name and value pairs scripts keep on page items (`object.tags`, +//! `object.tag.add`, `object.tag.set`, `object.tag.remove`, `object.tag.removeAll`). The native file +//! keeps them; other formats do not write them. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, MAX_TAG_TEXT, MAX_TAGS, Node, ObjectTag}; + +use super::{CommandSpec, NodeId, Result, Session, bad, cmd, has_doc, ids_param, targets, text_param, u64_req}; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "object.tags", + "Attributes", + [], + None, + "{id} → {tags: [{tag, name, value}]} the object's tags in order; `tag` tells each apart from the others while its name and value change", + has_doc, + list + ), + cmd!( + "object.tag.add", + "Attributes", + [], + None, + "{id, name?: string, value?: string} adds a tag after the object's others (\"\" for a name or value left out), as one undo step; an object has at most 64 tags, each name and value at most 65,536 bytes → {tag}", + has_doc, + add + ), + cmd!( + "object.tag.set", + "Attributes", + [], + None, + "{id, tag, name?: string, value?: string} changes the tag's name or value, as one undo step; a value it already has changes nothing → {changed: bool}", + has_doc, + set + ), + cmd!("object.tag.remove", "Attributes", [], None, "{id, tag} deletes the tag, as one undo step → {}", has_doc, remove), + cmd!( + "object.tag.removeAll", + "Attributes", + [], + None, + "{ids?|id?} deletes every tag of the objects in ids or the selection, as one undo step → {changed: objects}", + has_doc, + remove_all + ), + ] +} + +/// The page item `p`'s `id` names: an object of the document, not a layer or a ruler guide. +fn object(s: &Session, p: &Value, c: &str) -> Result { + let id = NodeId(u64_req(p, "id", c)?); + let d = &s.doc()?.doc; + match d.node(id) { + Some(n) if is_page_item(n) => Ok(id), + Some(_) => Err(bad(c, format!("object {} is a layer or a ruler guide, which has no tags", id.0))), + None => Err(bad(c, format!("no object {}", id.0))), + } +} + +fn is_page_item(n: &Node) -> bool { + !matches!(n.kind, vectorcraft_doc::NodeKind::Layer { .. }) && !n.is_ruler_guide() +} + +/// The tags of `n`. +pub(crate) fn tags_of(n: &Node) -> &[ObjectTag] { + n.extras().attrs.as_deref().map_or(&[], |a| a.tags.as_slice()) +} + +/// The tag `p`'s `tag` names on object `id`: its index among the object's tags. +fn tag_index(d: &Document, id: NodeId, p: &Value, c: &str) -> Result { + let tag = u64_req(p, "tag", c)?; + let n = d.node(id).ok_or_else(|| bad(c, format!("no object {}", id.0)))?; + tags_of(n).iter().position(|t| t.id == tag).ok_or_else(|| bad(c, format!("object {} has no tag {tag}", id.0))) +} + +/// The text `p` gives for `key` (a tag's name or value), at most [`MAX_TAG_TEXT`] bytes. `None` +/// when `p` leaves it out; a null is an error. +fn tag_text<'a>(p: &'a Value, key: &str, c: &str) -> Result> { + if p.get(key).is_some_and(Value::is_null) { + return Err(bad(c, format!("`{key}` must be a string"))); + } + let t = text_param(p, key, c)?; + if t.is_some_and(|t| t.len() > MAX_TAG_TEXT) { + return Err(bad(c, format!("a tag's {key} is longer than 65,536 bytes"))); + } + Ok(t) +} + +fn list(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tags"; + let id = object(s, p, C)?; + let d = &s.doc()?.doc; + let tags = d.node(id).map(tags_of).unwrap_or_default(); + Ok(json!({"tags": tags.iter().map(|t| json!({"tag": t.id, "name": t.name, "value": t.value})).collect::>()})) +} + +fn add(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.add"; + let id = object(s, p, C)?; + let name = tag_text(p, "name", C)?.unwrap_or_default().to_string(); + let value = tag_text(p, "value", C)?.unwrap_or_default().to_string(); + let count = s.doc()?.doc.node(id).map_or(0, |n| tags_of(n).len()); + if count >= MAX_TAGS { + return Err(bad(C, format!("object {} has 64 tags, the most an object has", id.0))); + } + let tag = s.edit("Attributes", |d, _| { + // A document-wide id: a tag deleted earlier in the run never shares it. + let tag = d.alloc_tag_id(id).ok_or_else(|| bad(C, "the document has no tag ids left"))?; + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + n.edit_attrs(|a| a.tags.push(ObjectTag { id: tag, name, value })); + Ok(tag) + })?; + Ok(json!({"tag": tag})) +} + +fn set(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.set"; + let id = object(s, p, C)?; + let name = tag_text(p, "name", C)?; + let value = tag_text(p, "value", C)?; + if name.is_none() && value.is_none() { + return Err(bad(C, "give name or value")); + } + let at = tag_index(&s.doc()?.doc, id, p, C)?; + let same = s + .doc()? + .doc + .node(id) + .and_then(|n| tags_of(n).get(at)) + .is_some_and(|t| name.is_none_or(|v| t.name == v) && value.is_none_or(|v| t.value == v)); + if same { + return Ok(json!({"changed": false})); + } + s.edit("Attributes", |d, _| { + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + n.edit_attrs(|a| { + if let Some(t) = a.tags.get_mut(at) { + if let Some(v) = name { + v.clone_into(&mut t.name); + } + if let Some(v) = value { + v.clone_into(&mut t.value); + } + } + }); + Ok(()) + })?; + Ok(json!({"changed": true})) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.remove"; + let id = object(s, p, C)?; + let at = tag_index(&s.doc()?.doc, id, p, C)?; + s.edit("Attributes", |d, _| { + let n = d.node_mut(id).ok_or_else(|| bad(C, format!("no object {}", id.0)))?; + let gone = n.edit_attrs(|a| (at < a.tags.len()).then(|| a.tags.remove(at).id)); + if let Some(t) = gone { + d.raise_next_id(t.saturating_add(1)); + } + Ok(()) + })?; + Ok(json!({})) +} + +fn remove_all(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.tag.removeAll"; + ids_param(p, "ids", C)?; + let ids = targets(s, p)?; + let d = &s.doc()?.doc; + for id in &ids { + if d.node(*id).is_none() { + return Err(bad(C, format!("no object {}", id.0))); + } + } + let tagged: BTreeSet = ids.into_iter().filter(|id| d.node(*id).is_some_and(|n| !tags_of(n).is_empty())).collect(); + if !tagged.is_empty() { + s.edit("Attributes", |d, _| { + let mut last = 0; + for id in &tagged { + if let Some(n) = d.node_mut(*id) { + last = n.edit_attrs(|a| a.tags.drain(..).map(|t| t.id).fold(last, u64::max)); + } + } + d.raise_next_id(last.saturating_add(1)); + Ok(()) + })?; + } + Ok(json!({"changed": tagged.len()})) +} diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 734e7fd972..d220deac73 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; in vertical type an upright character is measured above and below its ink inside its cell down the column, a character lying on its side along its own width, and a tate-chu-yoko block's characters across the column, the block keeping its one em; 0 by default; a value that is not a number or is outside the range is refused), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options: the font's mark glyphs among the characters, those its GDEF table classes as marks such as Arabic harakat and Hebrew points, move right by a positive horizontal value and up by a positive vertical one, relative to their letters, in thousandths of the size; a harakat or Hebrew point styled apart from its letter takes its own values and stays attached to it, and another mark takes its letter's; letters and fonts without mark classes do not move; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; a form other than \"default\" takes away the characters' glyph choice (text.setGlyphAlternate); with fullWidth, halfWidth, thirdWidth or quarterWidth, proportionalMetrics is kept but `palt` is not applied, and the font's pair kerning is turned off; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\" (on area type with Dynamic Text (Block) on, a leading change sets the frame's line gap to the new leading less the size of the first character changed, within -1296..1296 pt, as text.setStyle), keepLineGap?: bool = false (as text.setStyle), tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", \"salt=2\", …] (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only; the range is shaped with its word, so a letter's alternate keeps it joined to its neighbours), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), warichu?: bool (Character panel menu › Warichu, with Show East Asian Options: the characters are set at warichuScale percent of their size and stacked on warichuLines lines inside their line, one above the other in horizontal type and side by side in vertical type, the first line above or to the right; a stretch of them is one block with the settings of its first character that stays whole on one line and may run past its end; type on a path sets them at their own size), warichuLines?: 1..6 (default 2), warichuGap?: pt 0..100 (the space between the lines, default 0), warichuScale?: % 10..100 (default 50), warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Warichu Settings: how the lines line up along the block, which is as long as its longest line; the justify values spread every line but the last, which is set left, centered or right, or spread with justifyAll; auto, the default, sets them as justifyLeft; left and right are top and bottom in vertical type; none of them turns warichu on), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options: space before and after each character in reading order, on its left and right in left-to-right type, on its right and left in right-to-left type, above and below it in vertical type; a ligature or a letter with its marks takes the values of its first character; line wrapping counts it, alignment keeps it at a line's ends and justification does not stretch or narrow it; 0 by default; a value that is not a number or is outside the range is refused, naming the key), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options: the share of the blank space on each side of each character's ink, inside its own width, that is taken away, the glyph keeping its shape; 100 sets the ink edge to edge; a color glyph's ink is its color art or bitmap; a character without ink, such as a space, keeps its width; a ligature or a letter with its marks takes the value of its first character; tracking, kerning and Insert Aki are added after it, and justification keeps it; in vertical type an upright character is measured above and below its ink inside its cell down the column, a character lying on its side along its own width, and a tate-chu-yoko block's characters across the column, the block keeping its one em; 0 by default; a value that is not a number or is outside the range is refused), diacriticHorizontal?, diacriticVertical?: 1/1000 em -1000..1000 (Character panel › Adjust Horizontal and Vertical Diacritic Position, with Show Indic Options: the font's mark glyphs among the characters, those its GDEF table classes as marks such as Arabic harakat and Hebrew points, move right by a positive horizontal value and up by a positive vertical one, relative to their letters, in thousandths of the size; a harakat or Hebrew point styled apart from its letter takes its own values and stays attached to it, and another mark takes its letter's; letters and fonts without mark classes do not move; 0 by default; a value that is not a number or is outside the range is refused, naming the key), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), glyphForm?: \"traditional\"|\"expert\"|\"jis04\"|\"jis90\"|\"jis78\"|\"jis83\"|\"fullWidth\"|\"halfWidth\"|\"thirdWidth\"|\"quarterWidth\"|\"default\" (Glyphs panel menu, with Show East Asian Options: the characters are drawn in that form of the font, the OpenType feature trad, expt, jp04, jp90, jp78, jp83, fwid, hwid, twid or qwid, one form at a time; a character the font has no such glyph for keeps its own; \"default\", Revert To Default Forms, draws the font's default glyphs; a form other than \"default\" takes away the characters' glyph choice (text.setGlyphAlternate); with fullWidth, halfWidth, thirdWidth or quarterWidth, proportionalMetrics is kept but `palt` is not applied, and the font's pair kerning is turned off; another value is refused), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes), glyphAlternate?: null (takes away the glyph choice text.setGlyphAlternate made on the characters, in the same undo step as the other attributes; any other value is refused)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -103,7 +103,7 @@ pub fn specs() -> Vec { "Step Type", [], None, - "{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object → {ids}", + "{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object. On area type with Dynamic Text (Block) on, a leading change sets the frame's line gap to the new leading less the size of the first character changed, within -1296..1296 pt, as text.setStyle → {ids}", has_doc, type_step ), @@ -1213,6 +1213,7 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { }, }; let story = switch_or(p, "story", false, C)?; + let keep_line_gap = switch_or(p, "keepLineGap", false, C)?; if story && ["start", "end"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { return Err(bad(C, "`story` styles the whole story: give no `start` or `end`")); } @@ -1256,7 +1257,11 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { let styled = if a == b { t.runs.clone() } else { unprotected_runs(&t.runs, a, b, &kept) }; set.extend(styled.iter().flat_map(super::fonts::run_fonts)); } - refresh_bounds(t); + // With Block on, the leading goes to the frame's line gap. + match change.leading.filter(|_| !keep_line_gap).and_then(|l| super::typecmd::styled_start(t, a, b).map(|at| (at, l))) { + Some((at, l)) => super::typecmd::refresh_with_leading(t, at, l), + None => refresh_bounds(t), + } n = if *f == id { t.runs.len() } else { n }; } Ok(n) @@ -2077,7 +2082,11 @@ fn type_step(s: &mut Session, p: &Value) -> Result { } } edit::replace_range_styled(&mut t.runs, a, b, &runs); - refresh_bounds(t); + // With Block on, the step goes to the frame's line gap. + match runs.first().filter(|_| matches!(step, Step::Leading)) { + Some(first) => super::typecmd::refresh_with_leading(t, a, first.style.leading), + None => refresh_bounds(t), + } } Ok(()) })?; diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index cde1456589..d7657df16e 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -157,13 +157,13 @@ pub fn specs() -> Vec { "charStyle", "Character Styles", "Character", - "; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt" + "; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings" ); v.push(spec( "charStyle.edit", "Edit Character Style", &[], - "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt", + "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt, tracking and kerning -1000..=10000, rotation -360..=360°, stroke miter limit 1..=500, Small Caps 1..=200%, finite stroke dashes and variable font axis settings", |s, p| edit_style(s, p, Kind::Char), true, )); @@ -500,13 +500,33 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map>(v.clone()).ok()); match kind { Kind::Char => { + let mut off = 0; for r in &mut t.runs { if r.style.style_name == target { + if let Some(l) = old_leading + .filter(|_| block_metrics.is_some_and(|(gap, minimum)| r.style.leading == Some((r.style.size + gap).max(minimum)))) + { + r.style.leading = l; + } + let was = r.style.leading; r.style = font_change(&r.style, restyle(&r.style, char_attrs, old, new, &base), new); changed = true; + if r.style.leading != was && leading_at.is_none() { + leading_at = Some(off); + } } + off += r.text.len(); } } Kind::Para => { @@ -519,7 +539,11 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map super::typecmd::refresh_with_given_leading(t, at), + None => refresh_bounds(t), + } } Ok(()) }) @@ -636,52 +660,7 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma } let mut st = with_attrs(&CharStyle::default(), m, &c)?; let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key); - for (key, value, lo, hi) in - [("size", st.size, 0.1, 1296.0), ("h_scale", st.h_scale, 1.0, 10000.0), ("v_scale", st.v_scale, 1.0, 10000.0)] - { - if changed(key) && !(lo..=hi).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - } - if changed("leading") && st.leading.is_some_and(|value| !(0.1..=5000.0).contains(&value)) { - return Err(bad(&c, "`leading` must be from 0.1 to 5000, or null for Auto")); - } - let shift_max = 1296.0; - for (key, value) in [("baseline_shift", st.baseline_shift), ("tcyUpDown", st.tcy_up_down), ("tcyLeftRight", st.tcy_left_right)] { - if changed(key) && !(-shift_max..=shift_max).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max))); - } - } - let (lo, hi) = (0.0, vectorcraft_doc::text::MAX_AKI); - for (key, value) in [("akiLeft", st.aki_left), ("akiRight", st.aki_right)] { - if changed(key) && !(lo..=hi).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - } - let (key, lo, hi) = ("tsume", 0.0, vectorcraft_doc::text::MAX_TSUME); - if changed(key) && !(lo..=hi).contains(&st.tsume) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - let hi = vectorcraft_doc::text::MAX_DIACRITIC_POSITION; - let lo = -hi; - for (key, value) in [("diacriticHorizontal", st.diacritic_horizontal), ("diacriticVertical", st.diacritic_vertical)] { - if changed(key) && !(lo..=hi).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - } - let lines = vectorcraft_doc::text::WARICHU_LINES; - if changed("warichuLines") && !lines.contains(&st.warichu_lines) { - return Err(bad(&c, format!("`warichuLines` must be a whole number from {} to {}", lines.start(), lines.end()))); - } - let scale = vectorcraft_doc::text::WARICHU_SCALE; - for (key, value, lo, hi) in [ - ("warichuGap", st.warichu_gap, 0.0, vectorcraft_doc::text::MAX_WARICHU_GAP), - ("warichuScale", st.warichu_scale, *scale.start(), *scale.end()), - ] { - if changed(key) && !(lo..=hi).contains(&value) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } - } + st.check_ranges(changed).map_err(|e| bad(&c, e.message))?; // A language of the list, stored as its tag (as text.setFormat takes it). if let Some(l) = &st.language && kept.and_then(|k| k.get("language")) != m.get("language") @@ -693,10 +672,6 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma style_paint(d, paint, key, &c)?; } } - let (key, lo, hi) = ("stroke_width", 0.0, vectorcraft_doc::MAX_COORD); - if changed(key) && !(lo..=hi).contains(&st.stroke_width) { - return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); - } if changed("features") { style_features(&st.features, kept, &c)?; } @@ -753,85 +728,20 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma } } -/// The range of a paragraph style's indents, space before and space after, and Hyphenation Zone (pt), -/// as `text.setFormat` keeps them. -const PARA_DISTANCE: f64 = 1296.0; - /// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the -/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each -/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as -/// `attrs` gives them), and the number of tab stops with the position and leader of each stop -/// `kept` does not hold. A value `kept` has is not checked. +/// ranges `text.setFormat` keeps them to ([`ParaStyle::check_ranges`]), the Justification options +/// as `attrs` gives them. A value `kept` has is not checked. fn para_ranges(st: &ParaStyle, attrs: &Map, kept: Option<&Map>, c: &str) -> Result<()> { - let within = |key: &str, value: f64, lo: f64, hi: f64| { - if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) } - }; let changed = |key: &str| attrs.contains_key(key) && kept.and_then(|k| k.get(key)) != attrs.get(key); - let nested_changed = |key: &str, field: &str| { - changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field)) + let check = |key: &str, field: Option<&str>| match field { + None => changed(key), + Some(field) => changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field)), }; - for (key, value) in [ - ("left_indent", st.left_indent), - ("right_indent", st.right_indent), - ("first_line_indent", st.first_line_indent), - ("space_before", st.space_before), - ("space_after", st.space_after), - ] { - if changed(key) { - within(key, value, -PARA_DISTANCE, PARA_DISTANCE)?; - } - } - let h = &st.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, PARA_DISTANCE), - ] { - if nested_changed("hyphenation", field) { - within(&format!("hyphenation.{field}"), value, lo, hi)?; - } - } // Read as given: a paragraph's attributes keep justification options in range as they load. - if let Some(given) = attrs.get("justification").filter(|_| changed("justification")) { - let j: vectorcraft_doc::JustificationOptions = serde_json::from_value(given.clone()).map_err(|e| bad(c, e.to_string()))?; - for (field, values, (lo, hi)) in [ - ("word_spacing", j.word_spacing, vectorcraft_doc::JustificationOptions::WORD_SPACING), - ("letter_spacing", j.letter_spacing, vectorcraft_doc::JustificationOptions::LETTER_SPACING), - ("glyph_scaling", j.glyph_scaling, vectorcraft_doc::JustificationOptions::GLYPH_SCALING), - ] { - if !nested_changed("justification", 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(bad(c, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum"))); - } - } - if nested_changed("justification", "auto_leading") { - let (lo, hi) = vectorcraft_doc::JustificationOptions::AUTO_LEADING; - within("justification.auto_leading", j.auto_leading, lo, hi)?; - } - } - if changed("tabs") { - let kept_tabs = kept_tab_stops(kept); - let max = TabStop::MAX_STOPS; - if st.tabs.len() > max.max(kept_tabs.len()) { - return Err(bad(c, format!("at most {max} tab stops"))); - } - for stop in st.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(bad(c, format!("{label} must be at most {max} characters"))); - } - } - } - Ok(()) + let given = attrs.get("justification").filter(|_| changed("justification")); + let justification: Option = + given.map(|g| serde_json::from_value(g.clone())).transpose().map_err(|e| bad(c, e.to_string()))?; + st.check_ranges(justification.as_ref(), &kept_tab_stops(kept), check).map_err(|e| bad(c, e.message)) } /// The tab stops `kept` holds, each as it reads (a stop that does not read is left out). @@ -971,6 +881,8 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { let attrs = kind.attrs(d, &name).ok_or_else(|| bad(&c, format!("no style `{name}`")))?; let normal = kind.attrs(d, kind.normal()).unwrap_or_default(); let clear = bool_or(p, "clearOverrides", false); + // The style sets a leading, or clearing overrides gives the text Normal's. + let sets_leading = kind == Kind::Char && (attrs.contains_key("leading") || (clear && normal.contains_key("leading"))); let style_name = (name != kind.normal()).then(|| name.clone()); // A Type tool range or whole text objects. let text_range = super::typecmd::TextRange::parse(p, &c)?; @@ -997,6 +909,8 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { s.edit_named("Apply {name}", &name, name == kind.normal(), |d, _| { for id in &ids { let Some(t) = text_mut(d, *id) else { continue }; + // The first character given the style's leading. + let mut leading_at = None; match kind { Kind::Char => { let len = vectorcraft_text::edit::runs_len(&t.runs); @@ -1017,6 +931,7 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { if let Some(e) = err { return Err(e); } + leading_at = sets_leading.then(|| super::typecmd::styled_start(t, a.min(b), a.max(b))).flatten(); } Kind::Para => { let mut v = t.paragraph_styles(); @@ -1030,7 +945,11 @@ fn apply(s: &mut Session, p: &Value, kind: Kind) -> Result { t.set_paragraph_styles(v); } } - refresh_bounds(t); + // With Block on, a leading the style sets goes to the frame's line gap. + match leading_at { + Some(at) => super::typecmd::refresh_with_given_leading(t, at), + None => refresh_bounds(t), + } } Ok(()) })?; @@ -1204,17 +1123,22 @@ fn unused(s: &mut Session, kind: Kind) -> Result { /// The styles of `kind` in `src` that load, with their source names so that art in the file keeps /// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes, -/// scales, leading, shifts, Insert Aki, Tsume, diacritic positions, Warichu Settings or stroke width are out of the range `charStyle.new` takes, whose +/// scales, leading, tracking, kerning, shifts, rotation, Insert Aki, Tsume, diacritic positions, Warichu Settings, Small Caps, +/// variable font axes or stroke weight, miter limit or dashes are out of the range `charStyle.new` takes ([`CharStyle::check_ranges`]), whose /// indents, spacing, Hyphenation or Justification options or tab stops are out of the range /// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in /// `src` of those skipped) fn loadable(src: &Document, kind: Kind) -> (Vec, Vec) { - const RANGED: [&str; 24] = [ + const RANGED: [&str; 32] = [ "size", "h_scale", "v_scale", "leading", + "tracking", + "kerning", + "kerningBefore", "baseline_shift", + "rotation", "akiLeft", "akiRight", "tsume", @@ -1226,6 +1150,10 @@ fn loadable(src: &Document, kind: Kind) -> (Vec, Vec) { "warichuGap", "warichuScale", "stroke_width", + "stroke_miter_limit", + "stroke_dash", + "small_caps", + "fontAxes", "left_indent", "right_indent", "first_line_indent", diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index e8f57aa14f..c0a92a20e3 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -401,6 +401,11 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() { json!({"tsume": 100.1}), json!({"diacriticHorizontal": -1000.1}), json!({"diacriticVertical": 1000.1}), + json!({"tracking": -1000.1}), + json!({"kerning": 10000.1}), + json!({"rotation": 360.1}), + json!({"stroke_miter_limit": 0.9}), + json!({"small_caps": 200.1}), ] { let key = attrs.as_object().unwrap().keys().next().unwrap(); for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] { @@ -425,7 +430,9 @@ fn character_style_dimensions_are_checked_before_a_definition_changes() { "tcyUpDown": 1296.0, "tcyLeftRight": -1296.0, "akiLeft": 0.0, "akiRight": 1000.0, "tsume": 100.0, - "diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0 + "diacriticHorizontal": -1000.0, "diacriticVertical": 1000.0, + "tracking": 10000.0, "kerning": -1000.0, "rotation": -360.0, + "stroke_miter_limit": 500.0, "small_caps": 200.0 }}), ) .unwrap(); @@ -830,8 +837,8 @@ fn load_all_styles_loads_both_kinds_in_one_step() { assert_eq!(s.doc().unwrap().doc, before); } -/// A loaded character style whose size, scale, leading, shift, warichu Line Gap or stroke width is -/// out of the range `charStyle.new` takes is skipped. +/// A loaded character style whose size, scale, leading, shift, warichu Line Gap, stroke width or +/// miter limit, tracking, kerning or rotation is out of the range `charStyle.new` takes is skipped. #[test] fn loaded_styles_out_of_range_are_skipped() { let (mut s, _) = session_with_text("Title"); @@ -841,11 +848,17 @@ fn loaded_styles_out_of_range_are_skipped() { ("Shifted", json!({"baseline_shift": 5000.0})), ("Thick", json!({"stroke_width": -2.0})), ("Gapped", json!({"warichuGap": 500.0})), + ("Spun", json!({"rotation": 720.0})), + ("Tracked", json!({"tracking": 50000.0})), + ("Kerned", json!({"kerning": -5000.0})), + ("Before", json!({"kerningBefore": 50000.0})), + ("Mitered", json!({"stroke_miter_limit": 0.5})), ("Fine", json!({"size": 12.0, "h_scale": 50.0})), ]; let data = styles_file(&file, &[]); let r = s.execute("charStyle.load", &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap(); - assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": ["Huge", "Flat", "Shifted", "Thick", "Gapped"]})); + let skipped = ["Huge", "Flat", "Shifted", "Thick", "Gapped", "Spun", "Tracked", "Kerned", "Before", "Mitered"]; + assert_eq!(r, json!({"added": ["Fine"], "existing": [], "skipped": skipped})); assert_eq!(listed(&mut s, "charStyle"), [NORMAL_CHAR, "Fine"]); } diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 2a62a46374..1c45d37f4c 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Area Type Options…", ["Type"], None, - "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", + "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error; a leading change on the text also sets lineGap, as type.dynamicText says) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", has_selection, area_options ), @@ -140,7 +140,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt 0.1..1296 (outside it: an error), leading?: pt|\"auto\", keepLineGap?: bool = false (true: Dynamic Text (Block) keeps the frame's line gap, as Reset Panel does), tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", \"salt=2\", …] OpenType (swsh, ss01–ss20, salt, titl, pnum, lnum, sups, subs, numr, dnom and aalt take the font's alternate number as `tag=N`, N 0–65535: \"salt=2\" draws the second alternate of each glyph that has one, \"salt\" is \"salt=1\", \"-salt\" and \"salt=0\" are off; \"hkna\" is H or V Style, kana in the font's forms for the writing direction, shaped as `vkna` in vertical type, and \"ital\" is Roman Italics, half-width alphanumerics in the font's italic forms, both on or off only), featureChanges?: [\"tnum\", \"-onum\", \"salt=2\", …] (OpenType features turned on, or with - off, on top of each character's own, a value replacing the feature's last one; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; on area type with Dynamic Text (Block) on, a leading change sets the frame's line gap (text.areaOptions lineGap) to the new leading less the size of the first character changed, within -1296..1296 pt, so every line spreads or tightens by the change, unless keepLineGap is true; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text; no undo step when no character, paragraph or graph label style changes) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_style ), @@ -335,6 +335,11 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) { // Edits that changed the paragraph count keep one paragraph style per paragraph. t.normalize_paras(); block::block_fit(t); + refresh_fitted(t); +} + +/// The part of [`refresh_bounds`] after Block has fitted the lines. +fn refresh_fitted(t: &mut TextObject) { auto_height(t); let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); t.cached_bounds = Some(lay.bounds); @@ -342,6 +347,36 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) { t.cached_ink = Some((lay.bounds, vectorcraft_render::effects::preview::laid_out_ink(&lay, t))); } +/// [`refresh_bounds`] after a change that set the leading of the character at `at` to `leading` +/// (in text space; None: Auto): on area type with Block on the change goes to the frame's line gap +/// ([`block::leading_to_line_gap`]), and the lines are fitted again only when the gap changed. +pub(crate) fn refresh_with_leading(t: &mut TextObject, at: usize, leading: Option) { + if block::leading_to_line_gap(t, at, leading) { + refresh_fitted(t); + } else { + refresh_bounds(t); + } +} + +/// The first character a style change over `a..b` of `t` reaches, with both ends on character +/// boundaries as [`vectorcraft_text::edit::style_range`] sets them; None when the range styles no +/// character (empty, or inside one character, in text that is not empty). +pub(crate) fn styled_start(t: &TextObject, a: usize, b: usize) -> Option { + let plain = t.plain_text(); + let (a, b) = (vectorcraft_text::edit::floor_char(&plain, a), vectorcraft_text::edit::floor_char(&plain, b)); + (a != b || plain.is_empty()).then_some(a.min(b)) +} + +/// [`refresh_with_leading`] with the leading the character at `at` was just given (a character +/// style, Text Tweaker). +pub(crate) fn refresh_with_given_leading(t: &mut TextObject, at: usize) { + if block::given_leading_to_line_gap(t, at) { + refresh_fitted(t); + } else { + refresh_bounds(t); + } +} + /// [`refresh_bounds`] for a document that is opening: the first frame takes the layout /// ([`vectorcraft_text::take_kept_layout`]) instead of laying the object out again. pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) { @@ -955,6 +990,7 @@ fn set_style(s: &mut Session, p: &Value) -> Result { { return Err(bad(C, "nothing to change")); } + let keep_line_gap = switch_or(p, "keepLineGap", false, C)?; let range = TextRange::parse(p, C)?; let ids = text_targets(s, p, C)?; let protect = s.prefs.missing_glyph_protection && (font.is_some() || style.is_some()); @@ -1032,7 +1068,14 @@ fn set_style(s: &mut Session, p: &Value) -> Result { let span = para_span(range, t); t.edit_paras(span, |pa| pa.justify = j); } - refresh_bounds(t); + // With Block on, the leading goes to the frame's line gap; an empty range styles nothing. + let changed = leading.filter(|_| !keep_line_gap).and_then(|l| { + range.map_or(Some(0), |r| Some(r.bytes(t)).filter(|(a, b)| a < b).and_then(|(a, b)| styled_start(t, a, b))).map(|at| (at, l)) + }); + match changed { + Some((at, l)) => refresh_with_leading(t, at, l), + None => refresh_bounds(t), + } } // Graph labels keep a change made to all of their text through the graph being drawn again (sizes as given, // not in a scaled label's own units). @@ -1478,6 +1521,8 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod area_tests; mod block; +pub(super) use block::SIZES as BLOCK_SIZES; +pub(super) use block::fit_metrics as block_fit_metrics; pub(crate) use block::needed_room; #[cfg(test)] mod block_tests; diff --git a/crates/engine/src/cmd/typecmd/block.rs b/crates/engine/src/cmd/typecmd/block.rs index ef14a57558..4c96d817bc 100644 --- a/crates/engine/src/cmd/typecmd/block.rs +++ b/crates/engine/src/cmd/typecmd/block.rs @@ -2,11 +2,11 @@ //! typed is set to the frame's width by changing its font size, after every edit //! ([`super::refresh_bounds`]). -use vectorcraft_doc::{TextKind, TextObject, TextRun}; +use vectorcraft_doc::{CharStyle, TextKind, TextObject, TextRun}; /// The font size range a line's first character is fitted within, in document points (the /// Character panel's). -const SIZES: (f64, f64) = (0.1, 1296.0); +pub(crate) const SIZES: (f64, f64) = (0.1, 1296.0); /// Most passes a refit runs to correct lines that still wrap after the first fit; each pass measures /// the lines and runs at most one more area layout. @@ -56,6 +56,19 @@ pub(crate) fn size_at(runs: &[TextRun], byte: usize) -> f64 { vectorcraft_text::edit::style_at(runs, byte).size } +/// The run that holds the character at `byte` (not the one before it), else the last run. +fn run_at(runs: &[TextRun], byte: usize) -> Option<&TextRun> { + let mut off = 0; + for r in runs { + let end = off + r.text.len(); + if (off..end).contains(&byte) { + return Some(r); + } + off = end; + } + runs.last() +} + /// The stored size of each line's first character, in one pass over the runs. fn first_sizes(runs: &[TextRun], lines: &[TypedLine]) -> Vec { let mut out = Vec::with_capacity(lines.len()); @@ -122,6 +135,71 @@ pub(crate) fn needed_room(t: &TextObject) -> Option<(f64, usize, usize)> { .reduce(|a, b| if b.0 > a.0 { b } else { a }) } +/// Whether every character's leading is the one Block gives it: its size plus the frame's line +/// gap (in text space, at least the least size), as [`block_fit`] sets it. +fn block_leadings(t: &TextObject, points: f64) -> bool { + let gap = t.area.block_gaps().1 / points; + let min_leading = SIZES.0 / points; + t.runs.iter().all(|r| r.style.leading == Some((r.style.size + gap).max(min_leading))) +} + +/// A leading change on area type with Block on ([`TextObject::dynamic_text`]), called after the +/// change is applied to the characters: Block sets each character's leading to its size plus the +/// frame's line gap, so the change goes to the line gap instead. The lines are fitted, so the +/// character at `at` has the size Block gives it (a size set by the same change included); the gap +/// is then the leading `leading` gives that character (in text space; None: Auto) less its size, in +/// document points and kept within [`vectorcraft_doc::AreaOptions::LINE_GAP`]. That moves the gap +/// by the change to the character's leading, so every line spreads or tightens by the same amount. +/// A new gap moves the lines, which in a shaped frame changes the room each one has and so the size +/// Block gives the character, so the lines are fitted again and the gap worked out again from the +/// new size, at most [`BLOCK_PASSES`] times. True when the lines are fitted for the final gap, so the +/// caller lays the text out without fitting it again. Point type, type on a path and area type with +/// Block off are left as they are. +pub(crate) fn leading_to_line_gap(t: &mut TextObject, at: usize, leading: Option) -> bool { + if !t.dynamic_text || !matches!(t.kind, TextKind::Area { .. }) { + return false; + } + let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false }; + t.normalize_paras(); + let para = t.plain_text().get(..at).map_or(0, |s| s.bytes().filter(|&c| c == b'\n').count()); + for _ in 0..BLOCK_PASSES { + block_fit(t); + // A frame Block could not fit leaves the characters as they were. + if !block_leadings(t, points) { + return false; + } + let Some(run) = run_at(&t.runs, at) else { return true }; + let size = run.style.size; + let new = match leading { + Some(l) => l, + None => { + // Auto leading as the layout sets it: the paragraph's Auto Leading share of the em size + // the font height reference gives the character. An inline graphic keeps its size. + let em = if run.inline.is_some() { size } else { vectorcraft_text::FontDb::global().em_size(&run.style, t.vertical) }; + t.para_at(para).effective_leading(&CharStyle { size: em, leading: None, ..run.style.clone() }) + } + }; + let gap = (new - size) * points; + if !gap.is_finite() { + return true; + } + let (lo, hi) = vectorcraft_doc::AreaOptions::LINE_GAP; + let next = gap.clamp(lo, hi); + if (next - t.area.line_gap).abs() <= 1e-9 { + return true; + } + t.area.line_gap = next; + } + false +} + +/// [`leading_to_line_gap`] with the leading the character at `at` was just given (a character +/// style, Text Tweaker), read before Block sets it again. +pub(crate) fn given_leading_to_line_gap(t: &mut TextObject, at: usize) -> bool { + let Some(leading) = run_at(&t.runs, at).map(|r| r.style.leading) else { return false }; + leading_to_line_gap(t, at, leading) +} + /// The size a line set at `size` points and `width` wide takes to fill `avail`, its width growing /// by `slope` a point of size (`width / size` when the whole line follows its size): rounded down /// to tenths and kept within [`SIZES`]. A line that fits and would not fit a tenth larger keeps its @@ -140,6 +218,21 @@ fn tenths(points: f64) -> f64 { ((points * 10.0 + 1e-6).floor() / 10.0).clamp(SIZES.0, SIZES.1) } +pub(crate) fn fit_metrics(t: &TextObject) -> Option<(f64, f64, f64)> { + if !t.dynamic_text { + return None; + } + let TextKind::Area { frame } = &t.kind else { return None }; + let (_, line_gap) = t.area.block_gaps(); + let b = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))?; + let points = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12)?; + let a = &t.area; + let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) }; + let cells = cells.max(1) as f64; + let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells; + (cell.is_finite() && cell > 1e-9).then_some((points, line_gap, cell)) +} + /// Fit area type with Dynamic Text (Block) on: with the word gap as every paragraph's Desired word /// spacing ([`TextObject::layout_justification`]; the paragraphs keep their own values), each line /// as typed gets the size (its first character's, in steps of 0.1 pt within 0.1 to @@ -150,24 +243,9 @@ fn tenths(points: f64) -> f64 { /// has no size. A line that still wraps at its first fit is made smaller, in at most /// [`BLOCK_PASSES`] more passes. True when the text changed. pub(crate) fn block_fit(t: &mut TextObject) -> bool { - if !t.dynamic_text { - return false; - } - let TextKind::Area { frame } = &t.kind else { return false }; - let (_, line_gap) = t.area.block_gaps(); - let Some(b) = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return false }; - let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false }; + let Some((points, line_gap, cell)) = fit_metrics(t) else { return false }; let before = t.runs.clone(); - // The room along a line in one cell of the frame, before indents. - let a = &t.area; - let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) }; - let cells = cells.max(1) as f64; - let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells; - if !(cell.is_finite() && cell > 1e-9) { - return t.runs != before; - } - let db = vectorcraft_text::FontDb::global(); let text = t.plain_text(); let lines = typed_lines(&text); diff --git a/crates/engine/src/cmd/typecmd/block_tests.rs b/crates/engine/src/cmd/typecmd/block_tests.rs index 0354a630b3..eb4afa3760 100644 --- a/crates/engine/src/cmd/typecmd/block_tests.rs +++ b/crates/engine/src/cmd/typecmd/block_tests.rs @@ -31,6 +31,29 @@ fn undo_len(s: &Session) -> usize { s.doc().unwrap().history.undo.len() } +#[test] +fn editing_a_character_style_keeps_manual_leading_when_block_has_no_room() { + for command in ["charStyle.setAttrs", "charStyle.edit"] { + for manual_leading in [42.0, 12.0] { + let mut s = session(); + let id = area(&mut s, 50.0, 400.0, "Inset"); + s.execute("text.areaOptions", &json!({"inset": 30})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"leading": 30}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": manual_leading})).unwrap(); + s.execute("type.dynamicText", &json!({"ids": [id], "on": true})).unwrap(); + assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading)); + let params = if command == "charStyle.edit" { + json!({"name": "Body", "to": "Body", "attrs": {"leading": 60}}) + } else { + json!({"name": "Body", "attrs": {"leading": 60}}) + }; + s.execute(command, ¶ms).unwrap(); + assert_eq!(text(&s, id).runs[0].style.leading, Some(manual_leading), "{command}: {manual_leading}"); + } + } +} + /// The size of the character at `byte`. fn size_at(t: &TextObject, byte: usize) -> f64 { super::block::size_at(&t.runs, byte) @@ -672,6 +695,109 @@ fn point_type_with_nothing_to_fit_is_left_as_it_is() { assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow); } +/// The distances between the baselines of `t`'s lines. +fn baseline_steps(t: &TextObject) -> Vec { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + lay.lines.windows(2).map(|w| w[1].baseline - w[0].baseline).collect() +} + +/// Block owns each character's leading (its size plus the line gap): a leading change from +/// `text.setStyle`, `text.setRangeStyle` or `type.step` on area type with Block on changes the +/// line gap by the difference from the first character's leading, in one undo step, and sticks. +#[test] +fn a_leading_change_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line\nmid one"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + let (first, second) = (t.runs[0].style.size, size_at(&t, 4)); + let steps = baseline_steps(&t); + let n = undo_len(&s); + + // The whole object: the first character's leading becomes the leading given. + s.execute("text.setStyle", &json!({"ids": [id], "leading": first + 6.0})).unwrap(); + assert_eq!(undo_len(&s), n + 1, "one undo step"); + let t = text(&s, id); + assert!((t.area.line_gap - 6.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 6.0).abs() < 1e-9)), "{:?}", t.runs); + assert_block(&t); + let wider = baseline_steps(&t); + assert!(wider.iter().zip(&steps).all(|(w, s)| (w - s - 6.0).abs() < 1e-6), "every line spreads: {steps:?} -> {wider:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, 0.0); + + // A range: measured from the leading of its first character. + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": second - 3.0})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap + 3.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(baseline_steps(&t).iter().zip(&steps).all(|(w, s)| w < s), "every line tightens"); + + // Alt+Up/Down steps by the Size/Leading increment. + let inc = s.prefs.type_size_increment; + s.execute("type.step", &json!({"attribute": "leading", "by": 1, "id": id, "start": 0, "end": 3})).unwrap(); + assert!((text(&s, id).area.line_gap - (inc - 3.0)).abs() < 1e-9); + + // Auto: the first character's Auto leading, 120% of its size. + s.execute("text.setStyle", &json!({"ids": [id], "leading": "auto"})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - t.runs[0].style.size * 0.2).abs() < 1e-6, "line gap {}", t.area.line_gap); + + // The leading the first character already has changes nothing. + let n = undo_len(&s); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": lead})).unwrap(); + assert_eq!(undo_len(&s), n, "no undo step"); + + // The gap stays within its range. + s.execute("text.setStyle", &json!({"ids": [id], "leading": 5000})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, vectorcraft_doc::AreaOptions::LINE_GAP.1); + // From a gap that holds every leading at its least, the leading given still applies. + s.execute("text.areaOptions", &json!({"lineGap": -1296})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": 1})).unwrap(); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + assert!((lead - 1.0).abs() < 1e-6, "leading {lead}"); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + // A size set with the leading: the gap follows the size Block gives the first character, on an + // empty line (whose size Block keeps) too. + s.execute("text.setStyle", &json!({"ids": [id], "size": 20, "leading": 50})).unwrap(); + let lead = text(&s, id).runs[0].style.leading.unwrap(); + assert!((lead - 50.0).abs() < 1e-6, "leading {lead}"); + s.execute("text.setText", &json!({"text": "\nwords"})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "size": 20, "leading": 30})).unwrap(); + let t = text(&s, id); + assert_eq!(size_at(&t, 0), 20.0, "the empty line keeps the size set"); + assert!((t.runs[0].style.leading.unwrap() - 30.0).abs() < 1e-6, "{:?}", t.runs[0].style); + s.execute("text.setText", &json!({"text": "BIG\na much longer second line\nmid one"})).unwrap(); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + + // Scaled type: the leading given and the line gap are in document points. + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + let points = text(&s, id).style_scale().unwrap().points; + s.execute("text.setStyle", &json!({"ids": [id], "leading": 150})).unwrap(); + let t = text(&s, id); + let (size, lead) = (t.runs[0].style.size * points, t.runs[0].style.leading.unwrap() * points); + assert!((lead - 150.0).abs() < 1e-6, "leading {lead}"); + assert!((t.area.line_gap - (150.0 - size)).abs() < 1e-6, "line gap {} for size {size}", t.area.line_gap); +} + +/// Without Block (point type, and area type with Block off) a leading change sets the +/// characters' leading and leaves the line gap. +#[test] +fn a_leading_change_without_block_sets_the_leading() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "one\ntwo"); + s.execute("text.areaOptions", &json!({"lineGap": 5})).unwrap(); + s.execute("text.setStyle", &json!({"ids": [id], "leading": 30})).unwrap(); + let t = text(&s, id); + assert_eq!(t.area.line_gap, 5.0); + assert!(t.runs.iter().all(|r| r.style.leading == Some(30.0))); + let id = point(&mut s, "one\ntwo", json!({})); + s.execute("type.step", &json!({"attribute": "leading", "by": 1, "id": id, "start": 0, "end": 3})).unwrap(); + let t = text(&s, id); + assert_eq!(t.area.line_gap, 0.0); + assert_eq!(t.runs[0].style.leading, Some(12.0 * 1.2 + s.prefs.type_size_increment)); +} + #[test] fn long_text_fits_in_a_bounded_number_of_layouts() { let mut s = session(); @@ -698,3 +824,155 @@ fn long_text_fits_in_a_bounded_number_of_layouts() { let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 8; assert!(used <= bound, "point type: {used} layouts"); } + +/// Area type with Block on, its lines at different sizes, and a line gap of 0. +fn block_text(s: &mut Session) -> u64 { + let id = area(s, 300.0, 400.0, "BIG\na much longer second line\nmid one"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_eq!(text(s, id).area.line_gap, 0.0); + id +} + +/// The leading of the one-byte character at `byte` (`style_at` reads the character before a run +/// end, so it is asked for the end of the character). +fn leading_at(t: &TextObject, byte: usize) -> Option { + vectorcraft_text::edit::style_at(&t.runs, byte + 1).leading +} + +/// `text.setRangeStyle {leading}` on a range of Block text moves the line gap by the change to +/// the leading of the range's first character, and the range keeps the leading given. +#[test] +fn a_range_leading_change_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + let second = vectorcraft_text::edit::style_at(&text(&s, id).runs, 5).size; + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": second + 5.0})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - 5.0).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 4).is_some_and(|l| (l - second - 5.0).abs() < 1e-9), "{:?}", leading_at(&t, 4)); + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - r.style.size - 5.0).abs() < 1e-9)), "every line spreads"); + // Reset Panel's form: the leading is set and Block keeps the line gap. + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 10, "leading": "auto", "keepLineGap": true})).unwrap(); + assert!((text(&s, id).area.line_gap - 5.0).abs() < 1e-9); + s.execute("text.setStyle", &json!({"ids": [id], "leading": "auto", "keepLineGap": true})).unwrap(); + assert!((text(&s, id).area.line_gap - 5.0).abs() < 1e-9); + assert!(s.execute("text.setStyle", &json!({"ids": [id], "leading": 30, "keepLineGap": 1})).is_err(), "keepLineGap takes a bool"); +} + +/// A range inside one character styles nothing, so it leaves the line gap. +#[test] +fn a_leading_on_a_range_inside_one_character_leaves_the_line_gap() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "\u{e9}t\u{e9}\nsecond line"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Loose", "attrs": {"leading": 50}})).unwrap(); + let gap = text(&s, id).area.line_gap; + let range = json!({"start": 0, "end": 1}); + let mut setstyle = json!({"ids": [id], "leading": 50}); + let mut setrange = json!({"id": id, "leading": 50}); + let mut apply = json!({"name": "Loose", "id": id}); + for p in [&mut setstyle, &mut setrange, &mut apply] { + p.as_object_mut().unwrap().extend(range.as_object().unwrap().clone()); + } + for (c, p) in [("text.setStyle", setstyle), ("text.setRangeStyle", setrange), ("charStyle.apply", apply)] { + s.execute(c, &p).unwrap_or_else(|e| panic!("{c}: {e}")); + assert_eq!(text(&s, id).area.line_gap, gap, "{c}"); + } +} + +/// `type.step {attribute: "leading"}` (Alt+Up/Down) on Block text moves the line gap by the step. +#[test] +fn a_leading_step_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + let inc = s.prefs.type_size_increment; + s.execute("type.step", &json!({"attribute": "leading", "by": -1, "id": id, "start": 0, "end": 3})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap + inc).abs() < 1e-9, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - t.runs[0].style.size + inc).abs() < 1e-9)); +} + +/// A character style edited to set a leading while Block text uses it moves the line gap; a style +/// without a leading leaves the gap. +#[test] +fn a_character_style_edited_to_a_leading_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("charStyle.new", &json!({"name": "Plain", "attrs": {"tracking": 0}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Plain", "id": id})).unwrap(); + assert_eq!(text(&s, id).area.line_gap, 0.0, "no leading in the style"); + s.execute("charStyle.edit", &json!({"name": "Plain", "to": "Plain", "attrs": {"tracking": 0, "leading": 60}})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (60.0 - t.runs[0].style.size)).abs() < 1e-6, "edit: line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 60.0).abs() < 1e-6)); + assert_spread(&t); + + // Once Block has given the characters other leadings than the style's (a new line gap here), a + // new leading in the style still applies: Block's leadings are not overrides. + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + let gap = text(&s, id).area.line_gap; + s.execute("charStyle.edit", &json!({"name": "Plain", "to": "Plain", "attrs": {"tracking": 0, "leading": 70}})).unwrap(); + let t = text(&s, id); + assert!(t.area.line_gap != gap, "the line gap moved"); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 70.0).abs() < 1e-6), "{:?}", leading_at(&t, 0)); + assert_spread(&t); +} + +/// Every character's leading is its size plus the frame's line gap (at least the least size), so +/// every line spread or tightened by the same amount. +fn assert_spread(t: &TextObject) { + let gap = t.area.line_gap; + let least = super::block::SIZES.0; + assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - (r.style.size + gap).max(least)).abs() < 1e-6)), "{:?}", t.runs); +} + +/// A character style that sets a leading, applied to Block text, moves the line gap. +#[test] +fn a_character_style_leading_applied_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("charStyle.new", &json!({"name": "Loose", "attrs": {"leading": 50}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Loose", "id": id})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (50.0 - t.runs[0].style.size)).abs() < 1e-6, "apply: line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 50.0).abs() < 1e-6)); + assert_spread(&t); + + // Clearing overrides gives the text the leading of the Normal style. + s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"leading": 44}})).unwrap(); + s.execute("charStyle.new", &json!({"name": "Plain", "attrs": {"tracking": 0}})).unwrap(); + s.execute("text.areaOptions", &json!({"lineGap": 0})).unwrap(); + s.execute("charStyle.apply", &json!({"name": "Plain", "id": id, "clearOverrides": true})).unwrap(); + let t = text(&s, id); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 44.0).abs() < 1e-6), "clear: {:?}", leading_at(&t, 0)); + assert!((t.area.line_gap - (44.0 - t.runs[0].style.size)).abs() < 1e-6, "clear: line gap {}", t.area.line_gap); + assert_spread(&t); +} + +/// Text Tweaker's leading ramp on Block text moves the line gap to its first character's value; +/// Block then gives every other character its size plus that gap. +#[test] +fn a_text_tweaker_leading_with_block_on_moves_the_line_gap() { + let mut s = session(); + let id = block_text(&mut s); + s.execute("addon.type.textTweaker", &json!({"attribute": "leading", "from": 40, "to": 45, "ids": [id]})).unwrap(); + let t = text(&s, id); + assert!((t.area.line_gap - (40.0 - t.runs[0].style.size)).abs() < 1e-6, "line gap {}", t.area.line_gap); + assert!(leading_at(&t, 0).is_some_and(|l| (l - 40.0).abs() < 1e-6)); + assert_spread(&t); +} + +/// The Eyedropper copies a whole character style, so the leading it copies onto Block text is not +/// a leading change: the line gap stays, and Block gives every character its size plus the gap. +#[test] +fn an_eyedropper_copy_onto_block_text_keeps_the_line_gap() { + let mut s = session(); + let source = point(&mut s, "source", json!({})); + s.execute("text.setStyle", &json!({"ids": [source], "leading": 33})).unwrap(); + let id = block_text(&mut s); + let gap = text(&s, id).area.line_gap; + s.execute("appearance.copyFrom", &json!({"source": source, "ids": [id]})).unwrap(); + let t = text(&s, id); + assert_eq!(t.area.line_gap, gap); + assert_spread(&t); +} diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index b66a50bc19..70aa0ee07c 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Dynamic Text", ["Type"], None, - "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", + "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type, or turn it on for point type (on omitted: the opposite of the first object's setting, point type counting as off, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap (a leading change on the text, from text.setStyle, text.setRangeStyle, type.step, a character style or Text Tweaker, sets lineGap to the new leading less the size of the first character changed), and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection, and no point type it turns into area type, is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Turning it on turns point type into area type with Block on, with the default Area Type Options but the gaps (options kept from an earlier frame do not carry over): the frame is as wide (along the lines) as the widest line as typed with its paragraph's indents, so that line keeps its size and sits where it was (by its own alignment), the other lines are set to that width (when negative indents take more than that line's width, the frame is as wide as the line, and Block makes it larger), and the frame then grows in depth (down, or to the left for vertical type) to hold every fitted line, around any Text Wrap objects above it; the gaps apply to it as to area type. Point type with no line to fit (empty, or only spaces and breaks) is left as it is, and so is point type when it is turned off; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", has_dynamic_type, dynamic_text ), diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index ea6647b7a4..db1a641f2f 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -23,7 +23,10 @@ use vectorcraft_doc::{DataSet, DataValue, Document, NodeId, NodeKind, Selection, use super::edit::selected_roots; use super::fileio::{absolute_path, read_file_head, write_file}; use super::textedit::set_story_text; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selection, links, str_param}; +use super::{ + CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_or_selection, checked_ids_param, cmd, has_doc, has_selection, links, + str_param, +}; mod csv; mod library; @@ -435,7 +438,8 @@ fn bind(s: &mut Session, p: &Value) -> Result { fn unbind(s: &mut Session, p: &Value) -> Result { const C: &str = "variable.unbind"; - let ids = checked_ids_or_selection(s, p, C)?; + // Explicit bindings can include both a group and its children; retain every supplied ID. + let ids = if p.get("ids").is_some_and(|v| !v.is_null()) { checked_ids_param(s, p, "ids", C)? } else { checked_ids_or_selection(s, p, C)? }; let name = defined_variable(s, p, C)?; let n = edit_variables(s, "Unbind Variable", |vars| { let mut n = 0; diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 5f2d2cbffd..5356f5b249 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -21,7 +21,7 @@ use vectorcraft_render::encode::quantize::{self, Dither, Indexed, PaletteOptions use vectorcraft_render::encode::web::{self, ColorSort}; use vectorcraft_render::encode::{gif, jpeg, png}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, unique_name_from}; +use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, f64_or, has_doc, str_param, text_param, unique_name_from}; const C: &str = "document.exportForWeb"; @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Save for Web", [], None, - "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together (the transparent pixels' slot when there are any), its shifted and then its locked colors kept first; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", + "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together (the transparent pixels' slot when there are any), its shifted and then its locked colors kept first; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), transparencyDither?: none (default: pixels under half opacity become transparent)|diffusion|pattern|noise (gif/png8 with transparency: partly transparent pixels become transparent or keep their color in a dither, about as many keeping it as their opacity says with pattern, noise or diffusion at amount 100; fully transparent and opaque pixels do not change), transparencyDitherAmount?: 100 (0–100: the diffusion dither's strength, a lower amount closer to none, 0 as none), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", has_doc, export ), @@ -45,6 +45,24 @@ pub fn specs() -> Vec { has_doc, preview ), + cmd!( + "document.exportForWeb.saveColorTable", + "Save Color Table", + [], + None, + "{path?: the .act file (.act is added to a name without an extension), …the settings of document.exportForWeb (preset?, format?: gif|png8…), slice?: n (1-based, from slice.list, among the slices `slices` names; default the whole image, whatever `slices` is)} write the GIF or PNG-8 color table the preview shows as a color table file: 772 bytes, the colors as written (red, green, blue) in file order, zero bytes up to 256 colors, then the number of colors and the transparent entry's index (65535 for none), two bytes each, most significant byte first → {path, colors (how many), transparentIndex (null for none), bytes, warnings}; no path → {dataBase64, colors, transparentIndex, bytes, warnings}. An empty path, jpg and png24 are an error; the document and the settings do not change", + has_doc, + save_color_table + ), + cmd!( + query "webExport.loadColorTable", + "Load Color Table", + [], + None, + "{path | dataBase64: a color table file (.act: 768 bytes of 256 colors, or 772 bytes with the number of colors used, 1–256, and the transparent entry's index), …the settings of document.exportForWeb (preset?, format?: gif|png8…)} the settings with the table loaded: its colors other than the transparent entry become colorTable.customPalette, colors becomes the number of colors it uses (at least 2), the table's other edits (locked, transparent, deleted, shifted, webShift and sort) are cleared and webSnap becomes 0 →{colors: [\"#rrggbb\"…] (the colors it uses, in file order), transparentIndex (null for none; an index past the colors used names none), settings}. Give exactly one of path and dataBase64; another file size, a count of 0 or above 256, jpg and png24 are errors; nothing is remembered", + always, + load_color_table + ), cmd!( query "webExport.optimizeToFileSize", "Optimize to File Size", @@ -403,6 +421,12 @@ pub struct WebSettings { pub dither_amount: u8, /// Keep transparent pixels transparent (GIF, PNG-8, PNG-24). pub transparency: bool, + /// GIF and PNG-8 with `transparency`: how partly transparent pixels are split between the + /// transparent entry and their color (`none`: under half opacity is transparent). + #[serde(serialize_with = "ser_key", deserialize_with = "de_key")] + pub transparency_dither: Dither, + /// 0–100: the strength of the `diffusion` transparency dither. + pub transparency_dither_amount: u8, /// What partly transparent edges blend into (JPEG and opaque PNG-24: the background): `white`, /// `black`, `none` or `#rrggbb`. pub matte: String, @@ -449,6 +473,8 @@ impl Default for WebSettings { dither: Dither::Diffusion, dither_amount: 100, transparency: true, + transparency_dither: Dither::None, + transparency_dither_amount: 100, matte: "white".into(), interlaced: false, web_snap: 0, @@ -497,6 +523,10 @@ impl WebSettings { fn checked(mut self) -> std::result::Result { self.colors = self.colors.clamp(2, 256); self.dither_amount = self.dither_amount.min(100); + if self.transparency_dither_amount > 100 { + let key = "transparencyDitherAmount"; + return Err(format!("`{key}` must be from 0 to 100")); + } self.web_snap = self.web_snap.min(100); self.lossy = self.lossy.min(100); self.quality = self.quality.min(100); @@ -804,6 +834,8 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 dither_amount: s.dither_amount, transparency: s.transparency, matte, + transparency_dither: s.transparency_dither, + transparency_dither_amount: s.transparency_dither_amount, }; let (mut ix, dropped) = reduced(rgba, w, h, s, &o, &kept)?; // Map to transparent works on the colours the reduction made. @@ -910,7 +942,7 @@ fn reduced( return Ok((quantize::quantize_to(rgba, w, h, o, &left), vec![])); } // A fixed palette holds at most `colors` entries, the transparent one included. - let has_clear = s.transparency && rgba.as_chunks::<4>().0.iter().any(|p| p[3] < 128); + let has_clear = quantize::clear_mask(rgba, w, o).contains(&true); let removed = custom.iter().any(|c| deleted.contains(c)); let mut left: Vec<[u8; 3]> = vec![]; for c in custom { @@ -977,12 +1009,13 @@ fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; return vec![]; } let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect(); + let width = ix.width; let Indexed { palette, transparent, indices, .. } = ix; // The entry such pixels take, looked up at the first of them. let mut entry: Option> = None; let mut taken = vec![false; dropped.len()]; let mut pixel = 0; - quantize::nearest_entries(rgba, o, &all, |n| { + quantize::nearest_entries(rgba, width, o, &all, |n| { if let Some(d) = n.and_then(|n| n.checked_sub(kept.len())) { let e = *entry.get_or_insert_with(|| { transparent.or_else(|| palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())).or_else(|| { @@ -1238,24 +1271,7 @@ fn preview(s: &mut Session, p: &Value) -> Result { if !(kbps.is_finite() && kbps > 0.0) { return Err(bad(P, format!("kbps must be a positive number, not {kbps}"))); } - let st = s.doc()?; - let doc = &st.doc; - let failed = vectorcraft_render::decode_failures(); - let r = render(doc, &settings).map_err(|e| bad(P, e))?; - let warnings = undecoded(failed); - let areas = doc.slice_layout(); - let selected = super::slices::selected_slices(doc, &st.selection); - let cells = cells(&areas, &selected, &settings, &r).map_err(|e| bad(P, e))?; - let images = cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1); - let o = match p.get("slice").and_then(Value::as_u64) { - Some(n) => { - let c = cells.iter().find(|c| c.area.number as u64 == n).ok_or_else(|| bad(P, format!("no slice {n} in the image (see slice.list)")))?; - let [x0, y0, x1, y1] = c.px; - optimize(doc, &crop(&r, c.px), x1 - x0, y1 - y0, &settings) - } - None => optimize(doc, &r.rgba, r.width, r.height, &settings), - } - .map_err(|e| bad(P, e))?; + let Shown { o, images, warnings } = shown(s, &settings, p, P, true)?; let mut out = json!({ "format": settings.format.id(), "width": o.width, "height": o.height, "bytes": o.bytes.len(), "seconds": download_seconds(o.bytes.len(), kbps), "kbps": kbps, "slices": images, "warnings": warnings, @@ -1279,6 +1295,195 @@ fn preview(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The file Save writes with some settings, as the preview shows it. +struct Shown { + o: Optimized, + /// The images an export writes (0 when they were not counted). + images: usize, + /// The export's warnings. + warnings: Vec<&'static str>, +} + +/// What Save writes with `settings` for the whole image, or for the slice `p.slice` names (1-based, +/// from `slice.list`), for the command `cmd`. A `slice` that is not a whole number from 1 up is an +/// error. With `count_images` false and no `slice`, the slices are not looked up: `images` is 0, +/// and selected slices with none selected are not an error. +fn shown(s: &mut Session, settings: &WebSettings, p: &Value, cmd: &str, count_images: bool) -> Result { + let slice = match p.get("slice") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().filter(|n| *n >= 1).ok_or_else(|| bad(cmd, "`slice` is a slice number from `slice.list`"))?), + }; + let st = s.doc()?; + let doc = &st.doc; + let failed = vectorcraft_render::decode_failures(); + let r = render(doc, settings).map_err(|e| bad(cmd, e))?; + let warnings = undecoded(failed); + let areas = doc.slice_layout(); + let cells = if count_images || slice.is_some() { + let selected = super::slices::selected_slices(doc, &st.selection); + cells(&areas, &selected, settings, &r).map_err(|e| bad(cmd, e))? + } else { + vec![] + }; + let images = if count_images { + cells.iter().filter(|c| c.area.id.and_then(|id| doc.slice_options(id)).is_none_or(|o| o.kind == SliceKind::Image)).count().max(1) + } else { + 0 + }; + let o = match slice { + Some(n) => { + let c = + cells.iter().find(|c| c.area.number as u64 == n).ok_or_else(|| bad(cmd, format!("no slice {n} in the image (see slice.list)")))?; + let [x0, y0, x1, y1] = c.px; + optimize(doc, &crop(&r, c.px), x1 - x0, y1 - y0, settings) + } + None => optimize(doc, &r.rgba, r.width, r.height, settings), + } + .map_err(|e| bad(cmd, e))?; + Ok(Shown { o, images, warnings }) +} + +// ---------- color table files ---------- + +/// The extension of a color table file. +pub const COLOR_TABLE_EXT: &str = "act"; +/// The size of a color table file with its color count and transparent entry: 256 RGB triples +/// (768 bytes), then the two numbers, each two bytes, most significant byte first. +pub const ACT_LEN: usize = 772; +/// The size of a color table file of 256 RGB triples alone. +const ACT_COLORS_LEN: usize = 768; +/// The transparent entry of a color table file that has none. +const ACT_NO_TRANSPARENT: u16 = 0xFFFF; + +/// The error for bytes that are not a color table file. +const NOT_A_TABLE: &str = "not a color table: an .act file is 768 or 772 bytes long and uses 1 to 256 colors"; + +/// A color table file (`.act`) of `colors`, a palette format's color table in file order: each +/// color as written, red, green and blue, one byte each; zero bytes up to 256 colors; the number +/// of colors and the index of the transparent entry (`0xFFFF` for none), two bytes each, most +/// significant byte first. Colors past the 256th are left out. +pub fn act_bytes(colors: &[TableColor]) -> Vec { + let colors = &colors[..colors.len().min(256)]; + let mut out = vec![0u8; ACT_LEN]; + for (slot, c) in out.as_chunks_mut::<3>().0.iter_mut().zip(colors) { + *slot = c.color; + } + // At most 256 colors: both numbers fit in two bytes. + let count = colors.len() as u16; + let transparent = colors.iter().position(|c| c.transparent).map_or(ACT_NO_TRANSPARENT, |i| i as u16); + out[ACT_COLORS_LEN..ACT_COLORS_LEN + 2].copy_from_slice(&count.to_be_bytes()); + out[ACT_COLORS_LEN + 2..].copy_from_slice(&transparent.to_be_bytes()); + out +} + +/// The colors of a color table file and its transparent entry. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ActTable { + /// The colors the file uses, in its order. + pub colors: Vec<[u8; 3]>, + /// The index of the transparent entry, when the file names one of `colors`. + pub transparent: Option, +} + +/// Read a color table file: 768 bytes are 256 colors; 772 bytes add the number of colors used +/// (1 to 256) and the transparent entry's index. A transparent index past the colors used names +/// no entry. Any other size, or a count of 0 or above 256, is an error. +pub fn read_act(bytes: &[u8]) -> std::result::Result { + let (count, transparent) = match bytes.len() { + ACT_COLORS_LEN => (256, None), + ACT_LEN => { + let at = |i: usize| usize::from(u16::from_be_bytes([bytes[i], bytes[i + 1]])); + (at(ACT_COLORS_LEN), Some(at(ACT_COLORS_LEN + 2))) + } + _ => return Err(NOT_A_TABLE.into()), + }; + if !(1..=256).contains(&count) { + return Err(NOT_A_TABLE.into()); + } + let colors: Vec<[u8; 3]> = bytes[..count * 3].as_chunks::<3>().0.to_vec(); + Ok(ActTable { colors, transparent: transparent.filter(|i| *i < count) }) +} + +/// `settings` with the color table `t` loaded: its colors other than the transparent entry become +/// the fixed palette (`colorTable.customPalette`), and `colors` becomes the number of colors the +/// file uses (at least 2). The table's other edits (locked, transparent, deleted, shifted and +/// web-shifted colors, and its sort) are cleared and Web Snap is set to 0, so every loaded color is +/// written as it is, in the file's order. A table whose only color is its transparent entry loads +/// that color. +pub fn with_table(settings: &WebSettings, t: &ActTable) -> WebSettings { + let mut s = settings.clone(); + let mut palette: Vec = t.colors.iter().enumerate().filter(|(i, _)| Some(*i) != t.transparent).map(|(_, c)| hex(*c)).collect(); + if palette.is_empty() { + palette = t.colors.iter().map(|c| hex(*c)).collect(); + } + s.colors = (t.colors.len() as u16).clamp(2, 256); + s.web_snap = 0; + s.color_table = ColorTable { custom_palette: palette, ..ColorTable::default() }; + s +} + +/// `cmd`'s error for a format without a color table. +fn no_table(cmd: &str, f: WebFormat) -> super::EngineError { + let format = f.id(); + bad(cmd, format!("`{format}` has no color table: use gif or png8")) +} + +fn save_color_table(s: &mut Session, p: &Value) -> Result { + const P: &str = "document.exportForWeb.saveColorTable"; + let settings = s.web_settings(p).map_err(|e| bad(P, e))?; + if !settings.format.palette() { + return Err(no_table(P, settings.format)); + } + let path = text_param(p, "path", P)?; + if path.is_some_and(|p| p.trim().is_empty()) { + return Err(bad(P, "`path` is empty: give a file path, or leave it out for `dataBase64`")); + } + let path = path.map(|p| if std::path::Path::new(p).extension().is_none() { format!("{p}.{COLOR_TABLE_EXT}") } else { p.to_string() }); + let Shown { o, warnings, .. } = shown(s, &settings, p, P, false)?; + let bytes = act_bytes(&o.colors); + let mut out = json!({ + "colors": o.colors.len().min(256), + "transparentIndex": o.colors.iter().position(|c| c.transparent), + "bytes": bytes.len(), + "warnings": warnings, + }); + match path { + Some(path) => { + super::fileio::write_file(&path, &bytes)?; + out["path"] = json!(path); + } + None => out["dataBase64"] = json!(vectorcraft_format::base64_encode(&bytes)), + } + Ok(out) +} + +fn load_color_table(s: &mut Session, p: &Value) -> Result { + const L: &str = "webExport.loadColorTable"; + let settings = s.web_settings(p).map_err(|e| bad(L, e))?; + if !settings.format.palette() { + return Err(no_table(L, settings.format)); + } + // One byte more than a color table shows a file that is too long. + let bytes = match (text_param(p, "path", L)?, text_param(p, "dataBase64", L)?) { + (Some(path), None) => super::fileio::read_file_head(path, ACT_LEN + 1)?, + (None, Some(b64)) => { + // Text past the base64 of the longest table makes the file too long. + if b64.bytes().filter(|b| !b.is_ascii_whitespace()).count() > ACT_LEN.div_ceil(3) * 4 { + return Err(bad(L, NOT_A_TABLE)); + } + super::scripts::decode_head(b64, ACT_LEN + 1).ok_or_else(|| bad(L, "bad dataBase64"))? + } + _ => return Err(bad(L, "give exactly one of `path` and `dataBase64`")), + }; + let t = read_act(&bytes).map_err(|e| bad(L, e))?; + let loaded = with_table(&settings, &t); + Ok(json!({ + "colors": t.colors.iter().map(|c| hex(*c)).collect::>(), + "transparentIndex": t.transparent, + "settings": loaded.to_json(), + })) +} + // ---------- Optimize to File Size ---------- /// The most trial settings `webExport.optimizeToFileSize` encodes. Each trial encodes every image diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index fcb176a793..f12df3f229 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Sample Color", [], None, - "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, defaultsOnly?: bool, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool or with `defaultsOnly: true` (refused with ids), `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); with `stop` and objects in `ids`, whatever tool is active, the stops come from the topmost fill (or stroke) of the first object that paint.editGradient edits for those ids (a compound path for its member); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", + "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, defaultsOnly?: bool, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket, or for a fill the Shape Builder, is the active tool or with `defaultsOnly: true` (refused with ids), `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); with `stop` and objects in `ids`, whatever tool is active, the stops come from the topmost fill (or stroke) of the first object that paint.editGradient edits for those ids (a compound path for its member); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", has_doc, sample_color ), diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index eef620521f..9c80d284ca 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -53,6 +53,9 @@ pub struct DocState { pub interaction: Option, /// Edits made while this is open are one undo step (a scrubbed numeric field). pub undo_group: Option, + /// The built-in effect the edit in progress applies ([`crate::Session::edit_effect`]): the + /// undo step it records keeps it ([`DocState::push_undo`]). + pub(crate) effect_step: Option<&'static str>, /// For Object → Transform → Transform Again (⌘D): what the last transformation was. A /// transform command keeps the `copy`, `typeAreas` and `patterns` it used, and `strokes` and /// `corners` when it scales; a drag keeps the params of its last preview with the values that @@ -410,6 +413,7 @@ impl DocState { symbol_edit_return: Default::default(), interaction: None, undo_group: None, + effect_step: None, last_transform: None, last_selection_cmd: None, recalled_selection: RecalledSelection::default(), @@ -593,7 +597,9 @@ impl DocState { Some(l) if l.selection == it.selection => l.selection.clone(), _ => it.selection, }; + let effect = std::mem::replace(&mut self.effect_step, it.effect); self.push_undo(it.label, it.doc, selection); + self.effect_step = effect; if let Some(paints) = it.color_mode_paints && let Some(e) = self.history.undo.last_mut() { @@ -609,8 +615,10 @@ impl DocState { } /// Record an undo step: `doc` and `selection` as they were before an edit (the document now is /// the one after it). In an undo group only the group's first edit records one: the edits - /// after it extend that step. + /// after it extend that step. A new step named after the effect in [`DocState::effect_step`] + /// keeps that effect ([`HistoryEntry::effect`]); a step an undo group names keeps none. pub(crate) fn push_undo(&mut self, mut label: String, doc: Arc, selection: Arc) { + let mut effect = self.effect_step; if let Some(g) = &mut self.undo_group { let recorded = |first: &Arc| self.history.undo.last().is_some_and(|l| Arc::ptr_eq(&l.doc, first)); if g.first.as_ref().is_some_and(recorded) { @@ -621,9 +629,11 @@ impl DocState { g.first = Some(doc.clone()); if let Some(l) = &g.label { label = l.clone(); + effect = None; } } - let e = HistoryEntry::kept(label, doc, selection, &self.doc); + let mut e = HistoryEntry::kept(label, doc, selection, &self.doc); + e.effect = effect.filter(|id| crate::history::effect_step_label(id) == Some(e.label.as_str())); self.history.undo.push(e); self.history.clear_redo(); self.history.trim(); diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 8f67677684..c5896ff817 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -207,9 +207,16 @@ pub fn unconfined(f: impl FnOnce() -> T) -> T { with_gate_reads_exempt(true, || with_scope(Some(Scope::Unconfined), f)) } +/// Run `f`, a read of a file in one of the app's own folders, with reads exempt from the gate of +/// the script command this thread runs. Unlike [`unconfined`], the roots in force still apply. +pub(crate) fn app_folder_read(f: impl FnOnce() -> T) -> T { + with_gate_reads_exempt(true, f) +} + thread_local! { /// Are reads on this thread exempt from the gate of the script command it runs? Only inside an - /// [`unconfined`] entered after the gate was put in force ([`with_script_gate`]). + /// [`unconfined`] or an [`app_folder_read`] entered after the gate was put in force + /// ([`with_script_gate`]). static GATE_READS_EXEMPT: std::cell::Cell = const { std::cell::Cell::new(false) }; } diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index d472ec760c..791143f53b 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -25,6 +25,9 @@ pub struct HistoryEntry { next: usize, /// The template and name `label` was made from ([`Session::edit_named`]). pub(crate) named: Option, + /// The built-in effect the step applied or edited, when the step is named after it + /// ([`Session::edit_effect`]). + pub(crate) effect: Option<&'static str>, /// A number no other step takes ([`History::step`]). serial: u64, /// Original and changed new-art paints, only for steps that change them: a document color mode @@ -49,6 +52,7 @@ impl Clone for HistoryEntry { next_bytes: self.next_bytes, next: self.next, named: self.named.clone(), + effect: self.effect, serial: self.serial, color_mode_paints: self.color_mode_paints.clone(), color_mode_bytes: self.color_mode_bytes, @@ -63,6 +67,12 @@ fn next_serial() -> u64 { NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } +/// The name of the undo step that applies or edits built-in effect `id`: its menu label without +/// the ellipsis. `None` for an id no built-in effect has. +pub(crate) fn effect_step_label(id: &str) -> Option<&'static str> { + vectorcraft_render::effects::built_in_effect(id).map(|(_, label)| label.trim_end_matches('…')) +} + /// A step name made by filling the `{name}` placeholder of a template with a name /// ([`Session::edit_named`]). #[derive(Clone, Debug, PartialEq, Eq)] @@ -95,6 +105,7 @@ impl HistoryEntry { next_bytes, next: std::ptr::from_ref(next) as usize, named: None, + effect: None, serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, @@ -109,6 +120,13 @@ impl HistoryEntry { self.named.as_ref().filter(|n| n.label() == self.label) } + /// The id of the built-in effect the step applied or edited, while the step's label is still + /// the effect's name: `None` for any other step, and for one whose label was changed since it + /// was recorded. + pub fn effect(&self) -> Option<&'static str> { + self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str())) + } + /// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the /// document before the undo, whose next state is now `now` (that step's document). Its figures /// are that step's the other way round when `doc` is still the document they were taken @@ -128,6 +146,7 @@ impl HistoryEntry { next_bytes: costs.bytes, next: Arc::as_ptr(now) as usize, named: None, + effect: None, serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, @@ -248,7 +267,7 @@ impl History { /// The document at row `row` of the History panel, `now` being the document now: the rows before /// it are the undo steps, oldest first, and the rows after it the redo steps, nearest first. - pub(crate) fn state<'a>(&'a self, now: &'a Arc, row: usize) -> Option<&'a Arc> { + pub fn state<'a>(&'a self, now: &'a Arc, row: usize) -> Option<&'a Arc> { let current = self.undo.len(); match row.cmp(¤t) { std::cmp::Ordering::Less => self.undo.get(row).map(|e| &e.doc), diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index f7f9197f1d..221106ec0d 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -4,6 +4,9 @@ use super::{Affine, Arc, Document, NodeId, Selection, Value}; #[derive(Clone, Debug)] pub struct Interaction { pub label: String, + /// The built-in effect the last preview applied or edited ([`crate::Session::edit_effect`]): + /// the step the interaction records keeps it when `label` is the effect's name. + pub(crate) effect: Option<&'static str>, pub doc: Arc, /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, @@ -22,6 +25,10 @@ pub struct Interaction { /// Conversion of new-art paints waits until a color-mode preview is accepted. pub(crate) deferred_color_mode: Option, pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, + /// A preview ran while the active tool painted with the chosen fill or stroke + /// ([`crate::Session::tool_paints`]): the next preview and a cancel put back the new-art paints + /// from before the interaction, whichever tool is active then. + pub(crate) tool_paints: bool, /// Per-document state restored on cancel (current layer, highlighted Layers panel rows, /// isolation). pub active_layer: Option, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5560c26fcc..b1a7d37277 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,6 +30,7 @@ pub use cmd::clipboard::{Clipboard, SourceLayer}; pub use cmd::create::constrain_click; pub use cmd::distortcmds::{perspective_click, width_point_pair}; pub use cmd::flare::flare_settings; +pub use cmd::gradient::StopOwner; pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; pub use cmd::params::{check_keys, check_params}; pub use cmd::pathops::auto_simplify_level; @@ -74,11 +75,16 @@ pub struct Session { /// While Cmd lends `tool` (a selection tool) for a drag: the tool it was lent to, which comes /// back as it was at the release ([`Session::pointer`]). pub(crate) lender: Option>, - /// Set while tool actions that end by switching back to the Live Paint Bucket are applied (the - /// Eyedropper's sample into a stop of the bucket's gradient), and while a tool the bucket lent - /// is deactivated as it goes back: their paint commands change the colors the bucket paints - /// with ([`Session::bucket_paints`]). - pub(crate) back_to_bucket: bool, + /// While tool actions that end by switching back to a tool that paints with the chosen colors + /// are applied (the Eyedropper's sample into a stop of the Live Paint Bucket's gradient), and + /// while a tool such a tool lent is deactivated as it goes back, that tool's id: their paint + /// commands change the colors it paints with ([`Session::tool_paints`]). + pub(crate) back_to_painter: Option<&'static str>, + /// Whose gradient the stop was on when the Eyedropper was last armed to sample into one + /// (`tool.setOption {stop}`), when it was the gradient a tool paints with + /// ([`Session::painting_tool`]); None for a stop of the selection's paint. A pick armed for + /// such a stop samples only into a stop selected on that gradient, and otherwise ends. + pub(crate) stop_pick: Option, /// Pointer and key input that came while the tool computed an edit on another thread, each with /// its number and view, made in order once the edit is applied. held_input: std::collections::VecDeque<(u64, tooling::HeldInput, ViewInfo)>, @@ -131,6 +137,8 @@ pub struct Session { /// Set when a command that draws a shape was journaled outside saved steps /// ([`Session::take_shape_drawn`]). shape_drawn: bool, + /// The categories `prefs.reset` reset, `None` for every one ([`Session::take_prefs_resets`]). + prefs_resets: Vec>, /// Set when the active tool panicked (see [`guard`]); reported by the next tool event. tool_panic: Option, /// How many times switching or closing documents, or replacing the active one, has started the @@ -211,6 +219,9 @@ pub struct Session { /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option, + /// The Startup Scripts folder, whose scripts `script.startup.run` runs; `None`: no folder + /// ([`Session::attach_startup_scripts_dir`]). + startup_scripts_dir: Option, /// The folder of File Info's metadata templates; `None`: no folder /// ([`Session::attach_metadata_templates_dir`]). metadata_templates_dir: Option, @@ -303,6 +314,9 @@ pub struct Session { /// What a [`cmd::TraceRun`] traced, until the next `imageTrace.make` or /// `imageTrace.makeAndExpand` takes it ([`cmd::Traced::hand_in`]). pub(crate) trace_hand_off: Option, + /// The installed fonts a [`cmd::RetypeSearch`] found, until the next `type.retype` or + /// `type.retypeFonts` takes it ([`cmd::RetypeFound::hand_in`]). + pub(crate) retype_hand_off: Option, /// Whether a click or drag of the place cursor asks the frontend to place its file /// ([`UiRequest::Place`]) instead of running `file.place`: the desktop app sets it to read the /// file off the UI thread. False: the file is placed at once. @@ -331,6 +345,19 @@ pub struct Session { /// `script.run` starts the job and returns, and the frontend advances it once per frame /// ([`Session::script_pump`]). Off, `script.run` advances it to its end. pub script_frames: bool, + /// The runs `script.startup.run` queued in the app, each started when the run before it ends + /// ([`Session::script_pump`]). + pub(crate) script_queue: std::collections::VecDeque, + /// The file access scope of the request that queued [`Self::script_queue`], in which each queued + /// run starts and is read. + pub(crate) script_queue_scope: Option, + pub(crate) script_queue_then: Option, + /// While a startup script runs: the launch marker's entry naming it + /// ([`vectorcraft_plugins::safe_mode::loading`]). + pub(crate) startup_loading: Option, + /// The queued runs that could not start, as (name, error), until the frontend takes them + /// ([`Session::take_startup_failures`]). + pub(crate) startup_failures: Vec<(String, String)>, /// Each open document's highest next id a run has seen, by [`DocState::uid`]. pub(crate) script_high_water: std::collections::HashMap, /// While a slice of a script runs in this session. diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 1e0edb076e..1a7b78a91b 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -71,6 +71,10 @@ pub struct Prefs { pub show_tool_cards: bool, /// Other Script… warns before it runs a chosen script. pub show_external_script_warning: bool, + /// General › Run Startup Scripts: the `.jsx` files of the Startup Scripts folder run when the + /// app starts and before each script chosen from File › Scripts (`script.startup.run`). Off by + /// default. + pub run_startup_scripts: bool, pub anti_aliased_artwork: bool, pub select_same_tint_percent: bool, pub show_home_screen: bool, @@ -93,6 +97,8 @@ pub struct Prefs { /// Artboard Options › Update While Dragging: the area outside the artboards stays darker while /// the Artboard tool moves or resizes an artboard; off, it draws as usual until the drag ends. pub artboard_update_while_dragging: bool, + /// General › Display Print Size at 100% Zoom (on by default): 100% shows an inch of the + /// document in an inch of the display. A preferences file without the key reads as on. pub display_print_size: bool, pub double_click_to_isolate: bool, pub transform_pattern_tiles: bool, @@ -494,6 +500,7 @@ impl Default for Prefs { show_tool_tips: true, show_tool_cards: false, show_external_script_warning: true, + run_startup_scripts: false, anti_aliased_artwork: true, select_same_tint_percent: false, show_home_screen: true, @@ -503,7 +510,7 @@ impl Default for Prefs { type_glyph_bounds: false, fade_region_outside_artboard: true, artboard_update_while_dragging: true, - display_print_size: false, + display_print_size: true, double_click_to_isolate: true, transform_pattern_tiles: false, scale_corners: false, diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs new file mode 100644 index 0000000000..46ca2824d4 --- /dev/null +++ b/crates/engine/src/script/dom.rs @@ -0,0 +1,2336 @@ +//! The script object model: the global `app`, the open documents, their selection and the art in +//! them, as the help pages , +//! , +//! , +//! and +//! describe them. +//! +//! The objects are host classes ([`vectorcraft_js::HostClass`]): each holds the run's number, the +//! document's [`crate::DocState::uid`] and, for art, the object's id, and every read looks the +//! document and the object up again. An object that was deleted, a document that was closed and an +//! object from an earlier run of a named engine throw an error on every member. Every change runs +//! a command, as `vc.run` does, so it joins the run's transaction and its one undo step for each +//! changed document; a change that changes nothing runs no command. A change to a document that is +//! not the active one makes it active for the command and makes the other one active again after. +//! +//! Collections are counted from 0, and `pageItems` lists art topmost first, as +//! reads the frontmost path as +//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName` +//! gives, and a script may name the application's members without `app.`, as +//! describes; here +//! that holds for `activeDocument`, `documents` and `selection`. +//! +//! VectorCraft's own rules: +//! - A document's selection lists the selected objects topmost first, as `pageItems` does, whatever +//! order they were selected or made in. The objectReferences page above says instead that the +//! first object is the one last added to the page; VectorCraft does not follow that sentence. +//! - A collection read with a name that nothing has throws `Not found`, and `"name" in pageItems` is +//! false then. Assigning to such a name throws the same error. +//! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the +//! active document's selection. A top-level `var selection = ...` does the same and does +//! not make a variable of the script. Assigning `documents` keeps its value. +//! - Collections list documents in tab order. The objectReferences page says `documents[0]` is +//! always the active document; VectorCraft does not follow that yet. +//! - `pageItems` lists every object, with the objects inside groups and compound paths after the +//! group or compound path, and leaves out layers and ruler guides. An index out of range gives +//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches. +//! - Script coordinates are points with Y up from the bottom of the first artboard +//! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of +//! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run. +//! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`. +//! - `app.activeDocument` with no document open throws `No active document`. +//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object +//! must be one of that document's that can be selected, or nothing changes. +//! - Members the help pages list that are not here yet throw an error that says so. +//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an +//! object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` and change +//! nothing, even for the value the object has. The exception is `opacity` given the value the +//! object has when that changes nothing; on a graph's mark or label whose series or kind keeps +//! another opacity it would still change the graph, so it is refused too. Its `name` and `note` +//! still change. An object that is hidden or locked itself, or is in a hidden or locked group, +//! takes them. +//! - `name` and `note` take a number or a Boolean as the text `String(value)` gives. +//! - A compound path whose last path `move` or `remove()` takes out stays, empty. +//! - An object with nothing in it, such as an empty group or a compound path whose paths moved out, +//! reads its bounds, `position`, `width` and `height` as zeros, and assigning them does nothing. + +use std::cell::{Cell, RefCell}; +use std::collections::{HashMap, HashSet}; +use std::rc::Rc; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts}; + +use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; +use crate::{DocState, Document, NodeId, NodeKind, Session}; + +mod tags; + +/// The error for a member read or called with no document open. +pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; +/// The error for an object that was deleted, or that came from an earlier run. +pub const STALE_ITEM: &str = "Stale page item"; +/// The error for a document that was closed, or that came from an earlier run. +pub const STALE_DOCUMENT: &str = "Stale document"; +/// The error of `index` and `getByName` when nothing matches. +pub const NOT_FOUND: &str = "Not found"; +/// The most objects one read of a selection gives, and the most a selection assignment takes. +pub const MAX_LISTED: usize = 10_000; +/// The longest name an object or a path query may have, in bytes. +pub const MAX_TEXT_BYTES: usize = 4096; +/// The most artboards `Documents.add` makes. +pub const MAX_ARTBOARDS: f64 = 100.0; +/// The largest width or height `Documents.add` takes, in points, as `file.new` takes them. +pub const MAX_SIZE: f64 = 3_999_856.0; + +/// The page item classes, with the typename of each kind of object ([`typename`]). +const ITEM_CLASSES: &[&str] = &[ + "PathItem", + "CompoundPathItem", + "GroupItem", + "GraphItem", + "TextFrame", + "PlacedItem", + "RasterItem", + "SymbolItem", + "MeshItem", + "BlendItem", + "EnvelopeItem", + "RepeatItem", + "PlacedDocumentItem", + "IntertwineItem", +]; + +/// `app.coordinateSystem`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum Coords { + #[default] + Document, + Artboard, +} + +const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; +const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; + +/// What the object model keeps for one run: its coordinate system, the lists of page items and the +/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read, +/// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is +/// open, and the settings of each `DocumentPreset` the run made. +#[derive(Default)] +pub(super) struct State { + coords: Cell, + items: RefCell>, + locked: RefCell>, + saving: Cell, + presets: RefCell>>, +} + +impl State { + /// Whether a call's own savepoint is open: its commands take none of their own. + pub(super) fn saving(&self) -> bool { + self.saving.get() + } +} + +/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every +/// document, the selection and the undo histories are as they were before it, with no undo step +/// and no change to the document's saved state. +fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { + if h.dom.saving.get() { + return f(h); + } + let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate"); + h.dom.saving.set(true); + let r = f(h); + h.dom.saving.set(false); + let mut s = h.session.borrow_mut(); + if r.is_ok() { + save.keep(&mut s); + } else if !save.restore(&mut s) { + return Err(HostError::Abort(HISTORY_LOST.to_string())); + } + r +} + +/// A document's uid, the document as it was, and the ids of its page items then. +type ItemList = (u64, Arc, Rc>); + +/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for +/// each object of a layer or sublayer asked about then, whether it was on a locked artboard. +type LockedList = (u64, Arc, Arc>, HashMap); + +/// How many documents' lists [`State`] keeps at once, of each kind. +const ITEM_LISTS: usize = 4; + +/// The kept list of the document `uid` as `doc` is, if there is one. +fn kept_items(lists: &[ItemList], uid: u64, doc: &Arc) -> Option>> { + lists.iter().find(|(u, d, _)| *u == uid && Arc::ptr_eq(d, doc)).map(|(_, _, ids)| ids.clone()) +} + +/// Keeps `list` in place of any earlier list of the same document, dropping the least recently +/// kept list beyond [`ITEM_LISTS`]. +fn keep_items(lists: &mut Vec, list: ItemList) { + lists.retain(|(u, _, _)| *u != list.0); + if lists.len() >= ITEM_LISTS { + lists.remove(0); + } + lists.push(list); +} + +/// Whether node `id` of `st` is on a locked artboard ([`Document::on_locked_artboard`]). Each +/// object of a layer or sublayer is measured once while the document and its new art stay as they +/// are, so the members of a group are answered with one measurement of the group. +fn on_locked_artboard(h: &Host, st: &DocState, id: NodeId) -> bool { + if !st.doc.artboards.iter().any(|a| a.locked) { + return false; + } + let Some(object) = st.doc.layer_object(id).map(|n| n.id) else { + return false; + }; + let new_art = st.doc.new_art.get(); + let mut lists = h.dom.locked.borrow_mut(); + let at = match lists.iter().position(|(u, d, n, _)| *u == st.uid && Arc::ptr_eq(d, &st.doc) && Arc::ptr_eq(n, &new_art)) { + Some(at) => at, + None => { + lists.retain(|(u, ..)| *u != st.uid); + if lists.len() >= ITEM_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), new_art, HashMap::new())); + lists.len() - 1 + } + }; + match lists.get_mut(at) { + Some((.., held)) => *held.entry(object).or_insert_with(|| st.doc.on_locked_artboard(object)), + None => st.doc.on_locked_artboard(object), + } +} + +type Answer = std::result::Result; + +/// A member function: the run's host and the call's arguments, `this` first. +type Member = fn(&Host, &[Data]) -> Answer; + +fn function(link: &Link, f: Member) -> HostFunction { + let l = link.clone(); + Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16 + a.iter().map(data_size).sum::())?; + f(&h, &a) + }) +} + +fn get(link: &Link, f: Member) -> HostMember { + HostMember::Get(function(link, f)) +} + +fn property(link: &Link, g: Member, s: Member) -> HostMember { + HostMember::Property { get: function(link, g), set: function(link, s) } +} + +fn method(link: &Link, f: Member) -> HostMember { + HostMember::Method(function(link, f)) +} + +/// A member the help pages list that is not available yet: reading or assigning it throws, after +/// the check that a document or page item `this` is still there. `hasOwnProperty` is false for it, +/// so a script that checks for the member first skips it. +fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { + let message = format!("{class}.{name} is not available yet"); + let l = link.clone(); + let f: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + match class { + "Document" => { + doc_of(&h, arg(&a, 0), "Document")?; + } + "PageItem" => { + item_of(&h, arg(&a, 0))?; + } + _ => {} + } + Err(HostError::Error(message.clone())) + }); + (name.to_string(), HostMember::Unavailable(f)) +} + +fn text(s: impl Into) -> Data { + Data::String(s.into()) +} + +fn num(n: f64) -> Data { + Data::Number(n) +} + +fn pair(p: [f64; 2]) -> Data { + Data::Array(vec![num(p[0]), num(p[1])]) +} + +fn arg(a: &[Data], i: usize) -> &Data { + a.get(i).unwrap_or(&Data::Undefined) +} + +/// A whole number from a handle or an argument, within 0 and 2^53. +#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] +fn whole(n: f64) -> Option { + (n.is_finite() && n.fract() == 0.0 && (0.0..=9_007_199_254_740_992.0).contains(&n)).then_some(n as u64) +} + +#[allow(clippy::cast_precision_loss)] +fn float(n: u64) -> f64 { + n as f64 +} + +/// A node id in a handle: its high and low 32 bits, each exact as a number. +fn id_parts(id: NodeId) -> [f64; 2] { + [float(id.0 >> 32), float(id.0 & 0xffff_ffff)] +} + +/// The node id [`id_parts`] gave as `high` and `low`. +fn id_of(high: f64, low: f64) -> Option { + let (high, low) = (whole(high)?, whole(low)?); + (high <= 0xffff_ffff && low <= 0xffff_ffff).then_some(NodeId((high << 32) | low)) +} + +/// A finite number argument, or a `TypeError` naming `what`. +fn number(d: &Data, what: &str) -> std::result::Result { + match d { + Data::Number(n) if n.is_finite() => Ok(*n), + _ => Err(HostError::Type(format!("{what} must be a finite number"))), + } +} + +/// A coordinate argument: a finite number within the canvas. +fn coordinate(d: &Data, what: &str) -> std::result::Result { + let n = number(d, what)?; + if n.abs() > crate::MAX_COORD * 2.0 { + return Err(HostError::Range(format!("{what} is outside the canvas"))); + } + Ok(n) +} + +/// A point argument `[x, y]`. +fn point(d: &Data, what: &str) -> std::result::Result<[f64; 2], HostError> { + match d { + Data::Array(a) if a.len() == 2 => Ok([coordinate(&a[0], what)?, coordinate(&a[1], what)?]), + _ => Err(HostError::Type(format!("{what} must be an array of two numbers"))), + } +} + +fn boolean(d: &Data, what: &str) -> std::result::Result { + match d { + Data::Bool(b) => Ok(*b), + _ => Err(HostError::Type(format!("{what} must be true or false"))), + } +} + +/// The handle of `d` when it is an object of `class` (or of a page item class, for `"PageItem"`). +fn handle_of(d: &Data, class: &str) -> Option> { + let (c, handle) = host_ref_parts(d)?; + let matches = if class == "PageItem" { ITEM_CLASSES.contains(&c) } else { c == class }; + matches.then_some(handle) +} + +/// A document an object of the model names: its index among the open documents and its uid. +#[derive(Clone, Copy)] +struct Doc { + index: usize, + uid: u64, +} + +/// A page item: its document and its id. +#[derive(Clone, Copy)] +struct Item { + doc: Doc, + id: NodeId, +} + +/// The open document with `uid`, when the run's number in a handle is this run's. +fn find_doc(h: &Host, run: f64, uid: f64) -> Option { + if whole(run) != Some(h.run) { + return None; + } + let uid = whole(uid)?; + let s = h.session.borrow(); + s.documents().iter().position(|d| d.uid == uid).map(|index| Doc { index, uid }) +} + +/// The document `d` names: a `Document` or a `PageItems` object. +fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result { + let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) }; + match handle.as_slice() { + [run, uid] => find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into())), + _ => Err(HostError::Type(format!("this is not a {class}"))), + } +} + +/// The page item `d` names, which must still be in its document. +fn item_of(h: &Host, d: &Data) -> std::result::Result { + let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let s = h.session.borrow(); + let st = &s.documents()[doc.index]; + if st.doc.node(id).is_none_or(|n| typename(n).is_none()) { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok(Item { doc, id }) +} + +/// The typename of a node, or `None` for one that is not a page item (a layer or a ruler guide). +fn typename(n: &crate::doc::Node) -> Option<&'static str> { + Some(match &n.kind { + NodeKind::Layer { .. } | NodeKind::RulerGuide { .. } => return None, + NodeKind::Group { .. } if n.extras().graph.is_some() => "GraphItem", + NodeKind::Group { .. } => "GroupItem", + NodeKind::Path { .. } => "PathItem", + NodeKind::Compound { .. } => "CompoundPathItem", + NodeKind::Text(_) => "TextFrame", + NodeKind::Image(image) if image.link.is_some() => "PlacedItem", + NodeKind::Image(_) => "RasterItem", + NodeKind::SymbolInstance { .. } => "SymbolItem", + NodeKind::Mesh(_) => "MeshItem", + NodeKind::Blend { .. } => "BlendItem", + NodeKind::Envelope { .. } => "EnvelopeItem", + NodeKind::Repeat(_) => "RepeatItem", + NodeKind::PlacedDocument(_) => "PlacedDocumentItem", + NodeKind::Intertwine { .. } => "IntertwineItem", + }) +} + +fn doc_ref(h: &Host, uid: u64) -> Data { + host_ref("Document", &[float(h.run), float(uid)]) +} + +fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { + match st.doc.node(id) { + Some(n) => match typename(n) { + Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + }, + None => Data::Null, + } +} + +/// The ids of a document's page items, topmost first, each group or compound path before the +/// objects in it ([`State`] keeps the lists of the last documents read). +fn page_items(h: &Host, st: &DocState) -> Rc> { + if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) { + return ids; + } + fn walk(nodes: &[Arc], out: &mut Vec) { + for n in nodes.iter().rev() { + match &n.kind { + NodeKind::Layer { children, .. } => walk(children, out), + NodeKind::RulerGuide { .. } => {} + _ => { + out.push(n.id); + if let Some(children) = n.children() { + walk(children, out); + } + } + } + } + } + let mut ids = Vec::new(); + walk(&st.doc.layers, &mut ids); + let ids = Rc::new(ids); + keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone())); + ids +} + +/// The objects directly in the layers and sublayers of a document: what deleting every page item +/// deletes. +fn top_items(d: &Document) -> Vec { + fn walk(nodes: &[Arc], out: &mut Vec) { + for n in nodes { + match &n.kind { + NodeKind::Layer { children, .. } => walk(children, out), + NodeKind::RulerGuide { .. } => {} + _ => out.push(n.id), + } + } + } + let mut out = Vec::new(); + walk(&d.layers, &mut out); + out +} + +/// Whether `n` and every object inside it are shown and unlocked. +fn all_editable(n: &crate::doc::Node) -> bool { + n.visible && !n.locked && n.children().is_none_or(|c| c.iter().all(|c| all_editable(c))) +} + +/// Whether the object and every layer and group it is in are shown and unlocked. +fn editable(d: &Document, id: NodeId) -> bool { + d.ancestry(id).is_some_and(|a| a.iter().chain(std::iter::once(&id)).all(|i| d.node(*i).is_some_and(|n| n.visible && !n.locked))) +} + +/// The two rectangles script coordinates are measured from. +struct Frame { + /// The first artboard's left edge and bottom edge. + left0: f64, + bottom0: f64, + /// The active artboard's left edge and top edge. + left: f64, + top: f64, +} + +/// The index of the active artboard of `st`, as the view keeps it. +fn active_artboard(st: &DocState) -> usize { + let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id); + st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0) +} + +fn frame(st: &DocState) -> std::result::Result { + let (Some(first), Some(active)) = (st.doc.artboards.first(), st.doc.artboards.get(active_artboard(st))) else { + return Err(HostError::Error("the document has no artboards".into())); + }; + Ok(Frame { left0: first.rect.x0, bottom0: first.rect.y1, left: active.rect.x0, top: active.rect.y0 }) +} + +impl Frame { + /// A point in document coordinates as the script sees it in `c`. + fn to_script(&self, c: Coords, p: Point) -> [f64; 2] { + match c { + Coords::Document => [p.x - self.left0, self.bottom0 - p.y], + Coords::Artboard => [p.x - self.left, p.y - self.top], + } + } + + /// A point the script gave in `c`, in document coordinates. + fn to_document(&self, c: Coords, p: [f64; 2]) -> Point { + match c { + Coords::Document => Point::new(p[0] + self.left0, self.bottom0 - p[1]), + Coords::Artboard => Point::new(p[0] + self.left, p[1] + self.top), + } + } + + /// `[left, top, right, bottom]` of `r` as the script sees it. + fn bounds(&self, c: Coords, r: Rect) -> Data { + let a = self.to_script(c, Point::new(r.x0, r.y0)); + let b = self.to_script(c, Point::new(r.x1, r.y1)); + Data::Array(vec![num(a[0]), num(a[1]), num(b[0]), num(b[1])]) + } +} + +fn coords_of(d: &Data) -> std::result::Result { + match d { + Data::String(s) if s == DOCUMENT_COORDS => Ok(Coords::Document), + Data::String(s) if s == ARTBOARD_COORDS => Ok(Coords::Artboard), + _ => Err(HostError::Type("give a CoordinateSystem value".into())), + } +} + +/// Selects `before` again in the active document `doc` with the selection commands, so that the +/// journal holds the change: a Layers panel target, a dynamic symbol instance's object or an Objects +/// on Path group's object with its own command, else the objects in their order with their +/// direct-selected anchors, then the segments, the ruler guides and the key object, guide or anchor. +/// Objects that are now deleted, hidden or locked are left out. +fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -> std::result::Result<(), HostError> { + // Slices selected with the Slice Selection tool are the whole selection when there are any. + let slices: Vec = before.slices.iter().filter(|i| doc.is_slice(**i)).map(|i| i.0).collect(); + if !slices.is_empty() { + command(h, "object.slice.select", &json!({"slices": slices}))?; + return Ok(()); + } + let keep = |id: &NodeId| editable(doc, *id); + // Each of these commands sets the whole selection. One that refuses (its object is no longer + // inside the isolated group, or a symbol's object is now hidden) changes nothing, and the + // objects are selected as below. + if let Some(t) = before.target.filter(keep) + && done_unless_refused(command(h, "layer.target", &json!({"id": t.0})))? + { + return Ok(()); + } + if let Some(p) = before.symbol_part.as_ref().filter(|p| keep(&p.instance)) + && done_unless_refused(command(h, "symbol.instance.selectPart", &json!({"id": p.instance.0, "path": p.path})))? + { + return Ok(()); + } + if let Some(m) = before.on_path_member.filter(keep) + && done_unless_refused(command(h, "object.objectsOnPath.selectMember", &json!({"member": m.0})))? + { + return Ok(()); + } + let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id); + let kept: Vec = before.objects.iter().copied().filter(keep).collect(); + if kept.is_empty() { + command(h, "select.none", &json!({}))?; + } else if !kept.iter().any(partial) { + command(h, "select.set", &json!({"ids": kept.iter().map(|i| i.0).collect::>()}))?; + } else { + // One `select.anchorsMany` selects every object in its order: a partly selected path with + // its anchors, a whole path with all of them and any other object with none. + let items: Vec = kept + .iter() + .map(|i| { + let anchors: Vec<[usize; 2]> = match before.anchors.get(i) { + Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(), + None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(), + }; + json!({"id": i.0, "anchors": anchors}) + }) + .collect(); + command(h, "select.anchorsMany", &json!({"items": items, "mode": "set"}))?; + } + for (i, segments) in before.segments.iter().filter(|(i, _)| keep(i)) { + let segments: Vec<[usize; 2]> = segments.iter().map(|(p, k)| [*p, *k]).collect(); + command(h, "select.segments", &json!({"id": i.0, "segments": segments, "mode": "add"}))?; + } + let guides: Vec = doc.ruler_guides().into_iter().filter_map(|g| g.id).collect(); + let index = |id: &NodeId| guides.iter().position(|g| g == id); + let picked: Vec = before.guides.iter().filter_map(index).collect(); + // Guides that are locked now, and a key that no longer qualifies (the objects beside it are + // gone), stay unselected: those commands refuse them and change nothing. + if !picked.is_empty() { + done_unless_refused(command(h, "guide.select", &json!({"indexes": picked, "toggle": true})))?; + } + let key = if let Some((id, (p, k))) = before.key_anchor.filter(|(id, _)| keep(id)) { + Some(json!({"id": id.0, "anchor": [p, k]})) + } else if let Some(id) = before.key.filter(keep) { + Some(json!({"id": id.0})) + } else { + before.key_guide.as_ref().and_then(index).map(|g| json!({"guide": g})) + }; + if let Some(key) = key { + done_unless_refused(command(h, "select.key", &key))?; + } + Ok(()) +} + +/// The result `r` of a selection command that [`restore_selection`] runs: `true` when it ran and +/// `false` when it refused (an `Error`, which changes nothing). Any other error, such as an +/// internal failure or a request to stop, is returned, so the run ends with it. +fn done_unless_refused(r: std::result::Result) -> std::result::Result { + match r { + Ok(_) => Ok(true), + Err(HostError::Error(_)) => Ok(false), + Err(e) => Err(e), + } +} + +/// Makes `layer` the current layer of the active document `uid` again, with `rows` the highlighted +/// Layers panel rows, after selecting objects made the layer of the last of them current and +/// cleared the rows. Nothing runs when `layer` is gone. `layer.highlight` puts the rows back when +/// they changed, and then `layer.setCurrent` with `keepRows` makes `layer` current when it is not. +fn restore_layer(h: &Host, uid: u64, layer: Option, rows: &[NodeId]) -> std::result::Result<(), HostError> { + let Some(layer) = layer else { return Ok(()) }; + let rows = { + let s = h.session.borrow(); + let Some(st) = s.active().filter(|st| st.uid == uid) else { return Ok(()) }; + if st.doc.node(layer).is_none() { + return Ok(()); + } + let rows: Vec = rows.iter().copied().filter(|r| st.doc.node(*r).is_some()).collect(); + (st.highlighted_rows() != rows).then(|| rows.iter().map(|r| r.0).collect::>()) + }; + if let Some(rows) = rows { + command(h, "layer.highlight", &json!({"ids": rows, "mode": "set"}))?; + } + let current = h.session.borrow().active().is_some_and(|st| st.active_layer == Some(layer)); + if !current { + command(h, "layer.setCurrent", &json!({"id": layer.0, "keepRows": true}))?; + } + Ok(()) +} + +/// Runs `f` with the document `uid` active, and makes the document that was active before active +/// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s +/// commands changed it (commands given ids select them first), direct-selected anchors, segments, +/// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic +/// symbol instance or an Objects on Path group included, less the objects that are now deleted, +/// hidden or locked. +fn on_doc( + h: &Host, + uid: u64, + keep_selection: bool, + f: impl FnOnce(&Host) -> std::result::Result, +) -> std::result::Result { + let (index, active, before, layer) = { + let s = h.session.borrow(); + let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let st = &s.documents()[index]; + (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows())) + }; + let switch = active != Some(index); + if switch { + command(h, "document.activate", &json!({"index": index}))?; + } + let r = f(h); + let mut restored = Ok(()); + if keep_selection { + let doc = { + let s = h.session.borrow(); + s.active().filter(|st| st.uid == uid && st.selection != before).map(|st| st.doc.clone()) + }; + if let Some(doc) = doc { + restored = restore_selection(h, &doc, &before); + } + if restored.is_ok() { + restored = restore_layer(h, uid, layer.0, &layer.1); + } + } + // The document that was active is active again before any error is given: `f`'s error first, + // then the selection's, then the switch back's. + let back = match active { + Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop), + _ => Ok(()), + }; + let v = r?; + restored?; + back?; + Ok(v) +} + +/// Runs `id` with `params` on the item's document, its selection kept. +fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { + on_doc(h, item.doc.uid, true, |h| command(h, id, params)) +} + +/// Reads the document of `doc` with `f`. +fn with_doc(h: &Host, doc: Doc, f: impl FnOnce(&Session, &DocState) -> T) -> T { + let s = h.session.borrow(); + f(&s, &s.documents()[doc.index]) +} + +// ---- Application ---- + +fn app_documents(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("Documents", &[])) +} + +fn app_active(h: &Host, _: &[Data]) -> Answer { + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) +} + +fn app_set_active(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 1), "Document")?; + if h.session.borrow().active_index() != Some(doc.index) { + command(h, "document.activate", &json!({"index": doc.index}))?; + } + Ok(Data::Undefined) +} + +fn app_selection(h: &Host, _: &[Data]) -> Answer { + let uid = h.session.borrow().active().map(|st| st.uid); + match uid { + Some(uid) => selection_of(h, uid), + None => Ok(Data::Null), + } +} + +/// `app.selection = objects`: the active document's selection, as `selection` of that document is +/// assigned. +fn app_set_selection(h: &Host, a: &[Data]) -> Answer { + let doc = { + let s = h.session.borrow(); + let active = s.active_index().and_then(|index| s.documents().get(index).map(|st| Doc { index, uid: st.uid })); + active.ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))? + }; + let ids = selection_ids(h, doc, arg(a, 1))?; + set_selection(h, doc, ids) +} + +fn app_coords(h: &Host, _: &[Data]) -> Answer { + Ok(text(if h.dom.coords.get() == Coords::Document { DOCUMENT_COORDS } else { ARTBOARD_COORDS })) +} + +fn app_set_coords(h: &Host, a: &[Data]) -> Answer { + h.dom.coords.set(coords_of(arg(a, 1))?); + Ok(Data::Undefined) +} + +/// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter +/// or a `\`) letters in one case. +fn path_key(p: &str) -> String { + let windows = p.contains('\\') || p.as_bytes().get(1) == Some(&b':'); + let p = p.replace('\\', "/"); + let p = p.trim_end_matches('/').to_string(); + if windows { p.to_lowercase() } else { p } +} + +/// `app.getIsFileOpen(path)`: whether a document open in the run has the file `path`. The path is +/// compared as text with the documents' files and is not resolved; a document whose file the +/// automation read roots do not allow does not count, and that check can look the file up on disk. +fn app_is_open(h: &Host, a: &[Data]) -> Answer { + let Data::String(path) = arg(a, 1) else { return Err(HostError::Type("getIsFileOpen needs a path, as a string".into())) }; + if path.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the path is too long".into())); + } + let unc = path.starts_with("\\\\") || path.starts_with("//"); + if path.is_empty() || path.contains('\0') || unc || path.split(['/', '\\']).any(|c| c == "..") { + return Err(HostError::Error("getIsFileOpen cannot check that path".into())); + } + let key = path_key(path); + let s = h.session.borrow(); + let open = s.documents().iter().filter_map(|d| d.path.as_deref()).any(|p| path_key(p) == key && crate::file_access::check_read(p).is_ok()); + Ok(Data::Bool(open)) +} + +/// The menu command strings `app.executeMenuCommand` takes, each with the command it runs. The +/// strings are the ones +/// +/// lists, and `Fit Artboard to artwork bounds` is the one +/// gives for Object › +/// Artboards › Fit to Artwork Bounds. +const MENU_COMMANDS: &[(&str, &str)] = &[ + ("selectall", "select.all"), + ("deselectall", "select.none"), + ("group", "object.group"), + ("ungroup", "object.ungroup"), + ("makeMask", "object.clippingMask.make"), + ("releaseMask", "object.clippingMask.release"), + ("compoundPath", "object.compoundPath.make"), + ("noCompoundPath", "object.compoundPath.release"), + ("Fit Artboard to artwork bounds", "artboard.fitToArt"), +]; + +/// `app.executeMenuCommand(name)`: runs the command of the menu item `name` names +/// ([`MENU_COMMANDS`]) on the active document, as +/// describes the method. A +/// name it does not list throws an error that names it. A menu item that is not available, with +/// no document open or nothing selected that it acts on, does nothing, as a dimmed menu item does +/// (VectorCraft's own rule). A menu item the menus show as available runs its command, and an error +/// that command returns throws. `Fit Artboard to artwork bounds` fits the active artboard, and does +/// nothing when that artboard is locked or has no art, as the canvas's right-click menu dims +/// the item then ([`DocState::any_art_to_fit`]). +fn app_menu_command(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("executeMenuCommand needs a menu command, as a string".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the menu command is too long".into())); + } + let Some(&(_, id)) = MENU_COMMANDS.iter().find(|(n, _)| n == name) else { + return Err(HostError::Error(format!("executeMenuCommand: unknown menu command \"{name}\""))); + }; + let params = { + let s = h.session.borrow(); + let Some(spec) = crate::find_command(id) else { return Err(HostError::Abort(format!("executeMenuCommand: no command {id}"))) }; + if (spec.enabled)(&s).is_err() { + return Ok(Data::Undefined); + } + match (id, s.active()) { + ("artboard.fitToArt", Some(st)) => { + let index = active_artboard(st); + if !st.any_art_to_fit(&[index]) { + return Ok(Data::Undefined); + } + json!({"index": index}) + } + _ => json!({}), + } + }; + command(h, id, ¶ms)?; + Ok(Data::Undefined) +} + +// ---- Documents ---- + +fn docs_length(h: &Host, _: &[Data]) -> Answer { + Ok(num(float(h.session.borrow().documents().len() as u64))) +} + +fn app_ref(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("Application", &[])) +} + +/// `documents[i]`, and `documents["name"]` as `getByName` reads it. +fn docs_at(h: &Host, a: &[Data]) -> Answer { + let s = h.session.borrow(); + let at = match arg(a, 1) { + Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)), + Data::String(name) => match s.documents().iter().find(|d| d.title() == *name) { + None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())), + found => found, + }, + _ => None, + }; + Ok(at.map_or(Data::Undefined, |st| doc_ref(h, st.uid))) +} + +fn docs_by_name(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.title() == *name).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?; + Ok(doc_ref(h, st.uid)) +} + +fn docs_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => docs_by_name(h, a), + Data::Number(_) => match docs_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `file.new`'s `artboardLayout.layout` and whether it runs right to left, for a +/// `DocumentArtboardLayout` value. +fn layout_of(d: &Data) -> std::result::Result<(&'static str, bool), HostError> { + let Data::String(s) = d else { return Err(HostError::Type("artboardLayout must be a DocumentArtboardLayout value".into())) }; + Ok(match s.strip_prefix("DocumentArtboardLayout.").unwrap_or("") { + "GridByRow" => ("gridByRow", false), + "GridByCol" => ("gridByColumn", false), + "Row" => ("row", false), + "Column" => ("column", false), + "RLGridByRow" => ("gridByRow", true), + "RLGridByCol" => ("gridByColumn", true), + "RLRow" => ("row", true), + _ => return Err(HostError::Type("artboardLayout must be a DocumentArtboardLayout value".into())), + }) +} + +/// The settings of a new document a script gives, each `None` when it was left out. +#[derive(Default)] +struct NewDoc<'a> { + color_space: Option<&'a Data>, + width: Option<&'a Data>, + height: Option<&'a Data>, + artboards: Option<&'a Data>, + layout: Option<&'a Data>, + spacing: Option<&'a Data>, + rows_or_cols: Option<&'a Data>, + units: Option<&'a Data>, + title: Option<&'a Data>, + preview: Option<&'a Data>, + resolution: Option<&'a Data>, +} + +/// `d`, unless it is `undefined`. +fn given(d: &Data) -> Option<&Data> { + (!matches!(d, Data::Undefined)).then_some(d) +} + +impl NewDoc<'_> { + /// `file.new`'s params for these settings, checked before anything is made. + fn params(&self) -> std::result::Result, HostError> { + let mut p = serde_json::Map::new(); + if let Some(d) = self.color_space { + let mode = match d { + Data::String(s) if s == "DocumentColorSpace.RGB" => "rgb", + Data::String(s) if s == "DocumentColorSpace.CMYK" => "cmyk", + _ => return Err(HostError::Type("colorSpace must be a DocumentColorSpace value".into())), + }; + p.insert("colorMode".into(), json!(mode)); + } + for (d, key) in [(self.width, "width"), (self.height, "height")] { + if let Some(d) = d { + let v = number(d, key)?; + if v <= 0.0 || v > MAX_SIZE { + return Err(HostError::Range(format!("{key} must be more than 0 and at most 3999856 points"))); + } + p.insert(key.into(), json!(v)); + } + } + let count = match self.artboards { + Some(d) => { + let n = number(d, "numArtBoards")?; + if n.fract() != 0.0 || !(1.0..=MAX_ARTBOARDS).contains(&n) { + return Err(HostError::Range("numArtBoards must be a whole number from 1 to 100".into())); + } + p.insert("artboards".into(), json!(n)); + n + } + None => 1.0, + }; + let mut layout = serde_json::Map::new(); + if let Some(d) = self.layout { + let (name, rtl) = layout_of(d)?; + layout.insert("layout".into(), json!(name)); + layout.insert("rightToLeft".into(), json!(rtl)); + } + if let Some(d) = self.spacing { + let v = number(d, "artboardSpacing")?; + if !(0.0..=crate::cmd::newdoc::MAX_SPACING).contains(&v) { + return Err(HostError::Range("artboardSpacing must be from 0 to 100000 points".into())); + } + layout.insert("spacing".into(), json!(v)); + } + if let Some(d) = self.rows_or_cols { + let n = number(d, "artboardRowsOrCols")?; + if n.fract() != 0.0 || n < 1.0 || n > count { + return Err(HostError::Range("artboardRowsOrCols must be a whole number from 1 to numArtBoards".into())); + } + // A grid filled by column takes the number of rows. + let by_column = layout.get("layout").is_some_and(|l| l == "gridByColumn"); + layout.insert((if by_column { "rows" } else { "columns" }).into(), json!(n)); + } + if !layout.is_empty() { + p.insert("artboardLayout".into(), Value::Object(layout)); + } + if let Some(d) = self.units { + let units = match d { + Data::String(s) => match s.strip_prefix("RulerUnits.").unwrap_or("") { + u @ ("Points" | "Picas" | "Inches" | "Millimeters" | "Centimeters" | "Pixels") => u, + "Qs" | "Unknown" => return Err(HostError::Range(format!("a new document cannot have the units {s}"))), + _ => return Err(HostError::Type("units must be a RulerUnits value".into())), + }, + _ => return Err(HostError::Type("units must be a RulerUnits value".into())), + }; + p.insert("units".into(), json!(units)); + } + if let Some(d) = self.title { + let Data::String(t) = d else { return Err(HostError::Type("title must be a string".into())) }; + if t.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the title is too long".into())); + } + p.insert("name".into(), json!(t)); + } + if let Some(d) = self.preview { + let mode = match d { + Data::String(s) if s == "DocumentPreviewMode.DefaultPreview" => "default", + // Pixel Preview is a setting of the app's view, which a script cannot turn on. + Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => { + return Err(HostError::Error("DocumentPreviewMode.PixelPreview is not available yet".into())); + } + Data::String(s) if s == "DocumentPreviewMode.OverprintPreview" => "overprint", + _ => return Err(HostError::Type("previewMode must be a DocumentPreviewMode value".into())), + }; + p.insert("previewMode".into(), json!(mode)); + } + if let Some(d) = self.resolution { + let ppi = match d { + Data::String(s) if s == "DocumentRasterResolution.ScreenResolution" => 72, + Data::String(s) if s == "DocumentRasterResolution.MediumResolution" => 150, + Data::String(s) if s == "DocumentRasterResolution.HighResolution" => 300, + _ => return Err(HostError::Type("rasterResolution must be a DocumentRasterResolution value".into())), + }; + p.insert("rasterEffectsPpi".into(), json!(ppi)); + } + Ok(p) + } +} + +/// Runs `file.new` with `p`. → the new document, which is the active one. +fn new_document(h: &Host, p: serde_json::Map) -> Answer { + command(h, "file.new", &Value::Object(p))?; + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) +} + +/// `documents.add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, +/// artboardRowsOrCols?)`: a new document from `file.new`, which becomes the active one. +fn docs_add(h: &Host, a: &[Data]) -> Answer { + let settings = NewDoc { + color_space: given(arg(a, 1)), + width: given(arg(a, 2)), + height: given(arg(a, 3)), + artboards: given(arg(a, 4)), + layout: given(arg(a, 5)), + spacing: given(arg(a, 6)), + rows_or_cols: given(arg(a, 7)), + ..NewDoc::default() + }; + new_document(h, settings.params()?) +} + +/// The error of `addDocument` with `showOptionsDialog` true: a script cannot open the New +/// Document dialog. +pub const DIALOG_UNAVAILABLE: &str = "Dialog unavailable"; + +/// The New Document profile a startup preset names (`None`: no profile), and the color mode the +/// basic presets give. +fn startup_preset(name: &str) -> Option<(Option<&'static str>, Option<&'static str>)> { + let name = name.strip_prefix("DocumentPresetType.").unwrap_or(name); + let squashed: String = name.chars().filter(|c| !c.is_whitespace()).collect::().to_ascii_lowercase(); + Some(match squashed.as_str() { + "basiccmyk" => (None, Some("cmyk")), + "basicrgb" => (None, Some("rgb")), + "video" | "film&video" => (Some("Film & Video"), None), + _ => { + let same = |p: &&str| p.chars().filter(|c| !c.is_whitespace()).collect::().eq_ignore_ascii_case(&squashed); + (Some(crate::cmd::newdoc::profile_names().find(same)?), None) + } + }) +} + +/// `documents.addDocument(startupPreset, presetSettings?, showOptionsDialog?)`: a new document from +/// the New Document profile `startupPreset` names, with the settings `presetSettings` gives in +/// place of the profile's. +fn docs_add_document(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("addDocument needs a startup preset's name".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the startup preset's name is too long".into())); + } + let (profile, mode) = startup_preset(name).ok_or_else(|| HostError::Error(format!("no startup preset called {name}")))?; + // Only an object `new DocumentPreset()` made: a plain object such as `{width: 500}` is refused. + let settings = match given(arg(a, 2)) { + None | Some(Data::Null) => Vec::new(), + Some(d) => { + let i = preset_of(h, d).ok_or_else(|| HostError::Type("presetSettings must be a DocumentPreset".into()))?; + // The settings are charged as data passed to the call before they are copied. + let bytes = h.dom.presets.borrow()[i].iter().map(|(k, v)| k.len() as u64 + 2 + data_size(v)).sum::(); + h.charge_call(bytes)?; + h.dom.presets.borrow()[i].clone() + } + }; + let field = |k: &str| settings.iter().find(|(n, _)| n == k).map(|(_, v)| v).and_then(given); + for k in ["documentBleedLink", "documentBleedOffsetRect", "transparencyGrid"] { + if field(k).is_some_and(|d| !matches!(d, Data::Null)) { + return Err(HostError::Error(format!("DocumentPreset.{k} is not available yet"))); + } + } + let new = NewDoc { + color_space: field("colorMode"), + width: field("width"), + height: field("height"), + artboards: field("numArtboards"), + layout: field("artboardLayout"), + spacing: field("artboardSpacing"), + rows_or_cols: field("artboardRowsOrCols"), + units: field("units"), + title: field("title"), + preview: field("previewMode"), + resolution: field("rasterResolution"), + }; + let mut p = new.params()?; + match given(arg(a, 3)) { + None => {} + Some(Data::Bool(false)) => {} + Some(Data::Bool(true)) => return Err(HostError::Error(DIALOG_UNAVAILABLE.into())), + Some(_) => return Err(HostError::Type("showOptionsDialog must be true or false".into())), + } + // The document starts from the first preset of the profile's category (Print: Letter). + let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next()); + if let Some(first) = first { + p.insert("preset".into(), json!(first.name)); + } + p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n))); + if let Some(m) = mode { + p.entry("colorMode").or_insert_with(|| json!(m)); + } + // A profile whose file could not be read throws, and the document `file.new` made with the + // defaults is put back, with the Recent sizes as they were. + atomically(h, |h| { + let (_, value) = command_value(h, "file.new", &Value::Object(p))?; + if let Some(e) = value.get("profileError") { + let profile = e["profile"].as_str().unwrap_or_default(); + let reason = e["reason"].as_str().unwrap_or_default(); + return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}"))); + } + // Each warning from reading the profile's file goes to the console. + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::each_line(&format!("addDocument: {w}"), |line, cut| h.line(super::console::Entry::Log(line), cut)); + } + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) + }) +} + +/// `new DocumentPreset()`: a record of new-document settings with the defaults the help page +/// gives; the other settings are +/// left out. The settings stay with the run, which hands the script an object of the +/// `DocumentPreset` class. +fn new_preset(h: &Host) -> Answer { + let mut presets = h.dom.presets.borrow_mut(); + if presets.len() >= MAX_PRESETS { + return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets"))); + } + let item = |k: &str, v: Data| (k.to_string(), v); + presets.push(vec![ + item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), + item("artboardRowsOrCols", num(1.0)), + item("artboardSpacing", num(20.0)), + item("height", num(792.0)), + item("numArtboards", num(1.0)), + item("width", num(612.0)), + ]); + Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) +} + +/// The most `DocumentPreset` objects one run can make. +const MAX_PRESETS: usize = 10_000; + +/// The settings a `DocumentPreset` has, each a property a script reads and assigns. +const PRESET_FIELDS: &[&str] = &[ + "artboardLayout", + "artboardRowsOrCols", + "artboardSpacing", + "colorMode", + "documentBleedLink", + "documentBleedOffsetRect", + "height", + "numArtboards", + "previewMode", + "rasterResolution", + "title", + "transparencyGrid", + "units", + "width", +]; + +/// The index in the run's presets of the `DocumentPreset` `d` is, when it is one this run made. +fn preset_of(h: &Host, d: &Data) -> Option { + let handle = handle_of(d, "DocumentPreset")?; + let [run, i] = handle.as_slice() else { return None }; + if whole(*run) != Some(h.run) { + return None; + } + let i = usize::try_from(whole(*i)?).ok()?; + (i < h.dom.presets.borrow().len()).then_some(i) +} + +/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`, and +/// a value is checked when `addDocument` uses it. +fn preset_field(link: &Link, key: &'static str) -> HostMember { + let not_preset = || HostError::Type("this is not a DocumentPreset".into()); + let l = link.clone(); + let get: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + // The value handed back is charged as the setter charges it, before it is copied. + let i = preset_of(&h, arg(&a, 0)); + let bytes = i.map_or(0, |i| h.dom.presets.borrow()[i].iter().find(|(k, _)| k == key).map_or(0, |(_, v)| data_size(v))); + h.charge_call(16 + bytes)?; + let i = i.ok_or_else(not_preset)?; + let presets = h.dom.presets.borrow(); + Ok(presets[i].iter().find(|(k, _)| k == key).map_or(Data::Undefined, |(_, v)| v.clone())) + }); + let l = link.clone(); + let set: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + let value = arg(&a, 1).clone(); + h.charge_call(16 + data_size(&value))?; + let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; + let mut presets = h.dom.presets.borrow_mut(); + let fields = &mut presets[i]; + match fields.iter_mut().find(|(k, _)| k == key) { + Some((_, v)) => *v = value, + None => fields.push((key.to_string(), value)), + } + Ok(Data::Undefined) + }); + HostMember::Property { get, set } +} + +// ---- Document ---- + +fn this_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Document") +} + +fn doc_typename(h: &Host, a: &[Data]) -> Answer { + this_doc(h, a)?; + Ok(text("Document")) +} + +fn doc_parent(h: &Host, a: &[Data]) -> Answer { + this_doc(h, a)?; + Ok(host_ref("Application", &[])) +} + +fn doc_name(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(text(with_doc(h, doc, |_, st| st.title()))) +} + +fn doc_size(h: &Host, a: &[Data], width: bool) -> Answer { + let doc = this_doc(h, a)?; + with_doc(h, doc, |_, st| { + let r = st.doc.artboards.first().map(|b| b.rect).ok_or_else(|| HostError::Error("the document has no artboards".into()))?; + Ok(num(if width { r.width() } else { r.height() })) + }) +} + +fn doc_width(h: &Host, a: &[Data]) -> Answer { + doc_size(h, a, true) +} + +fn doc_height(h: &Host, a: &[Data]) -> Answer { + doc_size(h, a, false) +} + +fn doc_units(h: &Host, a: &[Data]) -> Answer { + use crate::doc::Unit; + let doc = this_doc(h, a)?; + let unit = with_doc(h, doc, |_, st| st.doc.units); + Ok(text(match unit { + Unit::Points => "RulerUnits.Points", + Unit::Picas => "RulerUnits.Picas", + Unit::Inches => "RulerUnits.Inches", + Unit::Millimeters => "RulerUnits.Millimeters", + Unit::Centimeters => "RulerUnits.Centimeters", + Unit::Pixels => "RulerUnits.Pixels", + Unit::Q => "RulerUnits.Qs", + _ => "RulerUnits.Unknown", + })) +} + +fn doc_color_space(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let cmyk = with_doc(h, doc, |_, st| st.doc.color_mode == crate::doc::ColorMode::Cmyk); + Ok(text(if cmyk { "DocumentColorSpace.CMYK" } else { "DocumentColorSpace.RGB" })) +} + +fn doc_ruler_origin(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + with_doc(h, doc, |_, st| { + let f = frame(st)?; + Ok(pair(f.to_script(Coords::Document, st.doc.ruler_origin_for(active_artboard(st))))) + }) +} + +/// `rulerOrigin = [x, y]`, in document coordinates: `document.setRulerOrigin` for the active +/// artboard. The art stays where it is. +fn doc_set_ruler_origin(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let p = point(arg(a, 1), "rulerOrigin")?; + let (to, now, artboard) = with_doc(h, doc, |_, st| { + let f = frame(st)?; + let artboard = active_artboard(st); + Ok::<_, HostError>((f.to_document(Coords::Document, p), st.doc.ruler_origin_for(artboard), artboard)) + })?; + if to.distance(now) > 1e-9 { + on_doc(h, doc.uid, false, |h| command(h, "document.setRulerOrigin", &json!({"x": to.x, "y": to.y, "artboard": artboard})))?; + } + Ok(Data::Undefined) +} + +/// `convertCoordinate(point, source, destination)`: `point` from one coordinate system of the +/// document to another. Nothing changes. +fn doc_convert(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let p = point(arg(a, 1), "point")?; + let (from, to) = (coords_of(arg(a, 2))?, coords_of(arg(a, 3))?); + with_doc(h, doc, |_, st| { + let f = frame(st)?; + Ok(pair(f.to_script(to, f.to_document(from, p)))) + }) +} + +fn doc_page_items(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("PageItems", &[float(h.run), float(doc.uid)])) +} + +fn doc_selection(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + selection_of(h, doc.uid) +} + +/// The selection of the document `uid`: a new list of the selected objects, topmost first as +/// `pageItems` lists them, empty when nothing is selected. +fn selection_of(h: &Host, uid: u64) -> Answer { + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let picked: HashSet = st.selection.objects.iter().copied().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect(); + if picked.len() > MAX_LISTED { + return Err(HostError::Range(format!("the selection has more than {MAX_LISTED} objects"))); + } + // Only the selected objects are ordered, by their place in the tree, so the cost follows the + // size of the selection and not of the document. `pageItems` walks each list of children + // topmost first and puts a group before the objects in it: a higher index comes first, and an + // ancestor's path, a prefix of its descendants' paths, sorts before them. + let mut placed: Vec<(Vec>, NodeId)> = Vec::with_capacity(picked.len()); + let mut unplaced: Vec = Vec::new(); + let mut seen: HashSet = HashSet::with_capacity(picked.len()); + let mut steps = 0u64; + for id in st.selection.objects.iter().copied().filter(|i| picked.contains(i) && seen.insert(*i)) { + match st.doc.index_path(id) { + Some(path) => { + steps += path.len() as u64; + placed.push((path.into_iter().map(std::cmp::Reverse).collect(), id)); + } + // A selected object outside the tree's walk still comes last, in the order it was + // selected. + None => unplaced.push(id), + } + } + placed.sort(); + let ids: Vec = placed.into_iter().map(|(_, id)| id).chain(unplaced).collect(); + h.charge_call(steps + 16 * ids.len() as u64)?; + Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect())) +} + +/// The ids an assignment to a document's selection gives: one page item, a list of them, `null` or +/// `[]`. Every one must be an object of that document that can be selected. +fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result, HostError> { + let list: Vec<&Data> = match v { + Data::Null => Vec::new(), + Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))), + Data::Array(a) => a.iter().collect(), + d => vec![d], + }; + let mut ids: Vec = Vec::with_capacity(list.len()); + let mut seen: HashSet = HashSet::with_capacity(list.len()); + // The document is read once for every object: nothing changes it while the list is checked. + let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked())); + let locks = d.locked_artboards(); + for v in list { + let item = item_of(h, v)?; + // A path made into a guide is not selected while Lock Guides is on, as the selection + // commands leave it out. + let ok = item.doc.uid == doc.uid + && crate::cmd::select::is_selectable(&d, isolation, &locks, item.id) + && !(guides_locked && crate::is_guide_path(&d, item.id)); + if !ok { + let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); + return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); + } + if seen.insert(item.id) { + ids.push(item.id); + } + } + Ok(ids) +} + +fn doc_set_selection(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let ids = selection_ids(h, doc, arg(a, 1))?; + set_selection(h, doc, ids) +} + +/// Makes `ids` the selection of `doc`, with no command when it already is: the same objects, each +/// selected as a whole (no dynamic symbol instance's object or Objects on Path group's object +/// chosen in it), and no ruler guide, slice, key or Layers panel target. +fn set_selection(h: &Host, doc: Doc, ids: Vec) -> Answer { + let same = with_doc(h, doc, |_, st| { + let sel = &st.selection; + sel.objects == ids + && sel.target.is_none() + && sel.symbol_part.is_none() + && sel.on_path_member.is_none() + && sel.anchors.is_empty() + && sel.segments.is_empty() + && sel.guides.is_empty() + && sel.slices.is_empty() + && sel.key.is_none() + && sel.key_guide.is_none() + && sel.key_anchor.is_none() + }); + if same { + return Ok(Data::Undefined); + } + on_doc(h, doc.uid, false, |h| { + if ids.is_empty() { + command(h, "select.none", &json!({})) + } else { + command(h, "select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})) + } + })?; + Ok(Data::Undefined) +} + +// ---- PageItems ---- + +fn items_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "PageItems") +} + +fn items_length(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let n = with_doc(h, doc, |_, st| page_items(h, st).len()); + Ok(num(float(n as u64))) +} + +fn items_typename(h: &Host, a: &[Data]) -> Answer { + items_doc(h, a)?; + Ok(text("PageItems")) +} + +fn items_to_string(h: &Host, a: &[Data]) -> Answer { + items_doc(h, a)?; + Ok(text("[PageItems]")) +} + +fn items_parent(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +/// Whether an indexer was called for `name in collection` ([`vectorcraft_js::HostClass::index`]), +/// where a name nothing has gives `undefined` instead of the `Not found` error a read throws. +fn probing(a: &[Data]) -> bool { + matches!(arg(a, 2), Data::Bool(true)) +} + +/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. +fn items_at(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + if let Data::String(_) = arg(a, 1) { + return match items_by_name(h, a) { + Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), + r => r, + }; + } + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + Ok(with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn items_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = page_items(h, st); + h.charge_call(ids.len() as u64)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn items_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => items_by_name(h, a), + Data::Number(_) => match items_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `pageItems.removeAll()`: deletes every object of the document in one command. A hidden or +/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted, +/// and so does an object on a locked artboard. +fn items_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let ids = top_items(&st.doc); + let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); + let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) + }); + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); + } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +// ---- PageItem ---- + +fn this_item(h: &Host, a: &[Data]) -> std::result::Result { + item_of(h, arg(a, 0)) +} + +/// Reads the item `this` names with `f`, given its document and node. +fn read_item(h: &Host, a: &[Data], f: impl FnOnce(&DocState, &crate::doc::Node) -> Answer) -> Answer { + let item = this_item(h, a)?; + with_doc(h, item.doc, |_, st| match st.doc.node(item.id) { + Some(n) => f(st, n), + None => Err(HostError::Error(STALE_ITEM.into())), + }) +} + +fn item_typename(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(typename(n).unwrap_or("PageItem")))) +} + +fn item_parent(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).map_or(Data::Null, |p| item_ref(h, st, p)))) +} + +fn item_name(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(n.name.clone().unwrap_or_default()))) +} + +/// Runs `object.setProps` with `props` for the item, unless `unchanged` says the node has them. +fn set_props(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Node) -> bool, props: Value) -> Answer { + let item = this_item(h, a)?; + let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(unchanged)); + if !same { + let mut p = props; + if let Some(o) = p.as_object_mut() { + o.insert("ids".into(), json!([item.id.0])); + } + edit_item(h, item, "object.setProps", &p)?; + } + Ok(Data::Undefined) +} + +/// The text a string property such as `name` or `note` is given: a number or a Boolean becomes the +/// text `String(value)` gives, and any other value that is not a string is refused. +fn text_arg(v: &Data, what: &str) -> std::result::Result { + match v { + Data::String(s) => Ok(s.clone()), + Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)), + Data::Bool(b) => Ok(b.to_string()), + _ => Err(HostError::Type(format!("{what} must be a string"))), + } +} + +/// `name = value`: a number or a Boolean becomes the text `String(value)` gives. +fn item_set_name(h: &Host, a: &[Data]) -> Answer { + let name = &text_arg(arg(a, 1), "name")?; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + set_props(h, a, |n| n.name.as_deref().unwrap_or("") == name, json!({"name": name})) +} + +fn note_of(n: &crate::doc::Node) -> &str { + n.extras().attrs.as_deref().map_or("", |a| a.note.as_str()) +} + +fn item_note(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(note_of(n)))) +} + +/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number +/// or a Boolean becomes the text `String(value)` gives. +fn item_set_note(h: &Host, a: &[Data]) -> Answer { + let note = &text_arg(arg(a, 1), "note")?; + if note.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the note is too long".into())); + } + let item = this_item(h, a)?; + let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| note_of(n) == note.trim())); + if !same { + edit_item(h, item, "attributes.set", &json!({"ids": [item.id.0], "note": note}))?; + } + Ok(Data::Undefined) +} + +/// Refuses appearance, place, stacking order and size changes in hidden or locked layers and on +/// locked artboards. Names and notes may still change. +fn refuse_protected_edit(h: &Host, item: Item) -> std::result::Result<(), HostError> { + let refused = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked)); + let why = if d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)) { + Some("a layer it is in is hidden or locked") + } else if on_locked_artboard(h, st, item.id) { + Some("it is on a locked artboard") + } else { + None + }; + why.map(|why| (d.node(item.id).and_then(typename).unwrap_or("page item"), why)) + }); + match refused { + Some((name, why)) => Err(HostError::Error(format!("Cannot edit {name} {}: {why}", item.id.0))), + None => Ok(()), + } +} + +fn item_hidden(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(Data::Bool(!n.visible))) +} + +fn item_set_hidden(h: &Host, a: &[Data]) -> Answer { + let hidden = boolean(arg(a, 1), "hidden")?; + refuse_protected_edit(h, this_item(h, a)?)?; + set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden})) +} + +fn item_locked(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(Data::Bool(n.locked))) +} + +fn item_set_locked(h: &Host, a: &[Data]) -> Answer { + let locked = boolean(arg(a, 1), "locked")?; + refuse_protected_edit(h, this_item(h, a)?)?; + set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) +} + +fn item_opacity(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4))) +} + +fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "opacity")?; + if !(0.0..=100.0).contains(&v) { + return Err(HostError::Range("opacity must be from 0 to 100".into())); + } + // A value the getter reports for the item's opacity sends the opacity it has, and + // `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still + // replaces the one the graph keeps for its series or kind. + // The opacity the item already has may be assigned while its layer is hidden or locked, unless + // it would still replace the opacity a graph keeps for the item's series or kind. + let item = this_item(h, a)?; + let (now, keeps_other) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + // Only the exact number the getter reports counts as the same opacity. + let now = d.node(item.id).map(|n| f64::from(n.opacity) * 100.0).filter(|now| (now * 1e4).round() / 1e4 == v); + let keeps_other = + crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]); + (now, keeps_other) + }); + if now.is_none() || keeps_other { + refuse_protected_edit(h, item)?; + } + set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) +} + +fn item_selected(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(Data::Bool(with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id)))) +} + +fn item_set_selected(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let on = boolean(arg(a, 1), "selected")?; + if with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id)) == on { + return Ok(Data::Undefined); + } + // Adding or removing the one object keeps how the others are selected (their direct-selected + // anchors and segments, and the key object). + let ids = if on { selection_ids(h, item.doc, arg(a, 0))? } else { vec![item.id] }; + let id = if on { "select.add" } else { "select.toggle" }; + on_doc(h, item.doc.uid, false, |h| command(h, id, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + Ok(Data::Undefined) +} + +/// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the +/// document's [`Frame`]. An object with nothing in it, such as an empty group or a compound path +/// whose paths moved out, has no bounds: its bounds read as zeros, and moving or resizing it does +/// nothing. +fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Option, Frame), HostError> { + with_doc(h, item.doc, |_, st| Ok((st.doc.bounds_of(&[item.id], visual), frame(st)?))) +} + +fn bounds(h: &Host, a: &[Data], visual: bool) -> Answer { + let item = this_item(h, a)?; + match item_rect(h, item, visual)? { + (Some(r), f) => Ok(f.bounds(h.dom.coords.get(), r)), + (None, _) => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])), + } +} + +fn item_geometric(h: &Host, a: &[Data]) -> Answer { + bounds(h, a, false) +} + +fn item_visible(h: &Host, a: &[Data]) -> Answer { + bounds(h, a, true) +} + +fn item_position(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + match item_rect(h, item, false)? { + (Some(r), f) => Ok(pair(f.to_script(h.dom.coords.get(), Point::new(r.x0, r.y0)))), + (None, _) => Ok(pair([0.0, 0.0])), + } +} + +fn item_left(h: &Host, a: &[Data]) -> Answer { + match item_position(h, a)? { + Data::Array(p) => Ok(p.into_iter().next().unwrap_or(Data::Undefined)), + d => Ok(d), + } +} + +fn item_top(h: &Host, a: &[Data]) -> Answer { + match item_position(h, a)? { + Data::Array(p) => Ok(p.into_iter().nth(1).unwrap_or(Data::Undefined)), + d => Ok(d), + } +} + +fn item_width(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.width()))) +} + +fn item_height(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.height()))) +} + +/// Moves the item so its top-left corner is at `x` and `y` in script coordinates (`None`: that one +/// stays). +fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { + let item = this_item(h, a)?; + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; + let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; + let c = h.dom.coords.get(); + let now = f.to_script(c, Point::new(r.x0, r.y0)); + let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]); + let (dx, dy) = (to.x - r.x0, to.y - r.y0); + if dx.abs() > 1e-9 || dy.abs() > 1e-9 { + edit_item(h, item, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?; + } + Ok(Data::Undefined) +} + +fn item_set_position(h: &Host, a: &[Data]) -> Answer { + let p = point(arg(a, 1), "position")?; + move_to(h, a, Some(p[0]), Some(p[1])) +} + +fn item_set_left(h: &Host, a: &[Data]) -> Answer { + let x = coordinate(arg(a, 1), "left")?; + move_to(h, a, Some(x), None) +} + +fn item_set_top(h: &Host, a: &[Data]) -> Answer { + let y = coordinate(arg(a, 1), "top")?; + move_to(h, a, None, Some(y)) +} + +/// Scales the item about its top-left corner along the page's axes to `size` points wide (`width`) +/// or tall, so the page-aligned bounds that `width` and `height` read have that size, rotated +/// objects included. +fn resize(h: &Host, a: &[Data], width: bool) -> Answer { + let what = if width { "width" } else { "height" }; + let size = number(arg(a, 1), what)?; + if size <= 0.0 || size > MAX_SIZE { + return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points"))); + } + let item = this_item(h, a)?; + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; + let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; + let now = if width { r.width() } else { r.height() }; + if now <= 0.0 { + return Err(HostError::Error(format!("the object has no {what} to scale"))); + } + if (now - size).abs() < 1e-9 { + return Ok(Data::Undefined); + } + let pct = size / now * 100.0; + let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) }; + let p = json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}); + edit_item(h, item, "object.scale", &p)?; + Ok(Data::Undefined) +} + +fn item_set_width(h: &Host, a: &[Data]) -> Answer { + resize(h, a, true) +} + +fn item_set_height(h: &Host, a: &[Data]) -> Answer { + resize(h, a, false) +} + +/// `editable`: false for an object that is hidden or locked, in a hidden or locked layer or group, +/// or on a locked artboard. +fn item_editable(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && !on_locked_artboard(h, st, item.id)))) +} + +/// The item's place in its parent's stacking order, from 1 at the bottom. +fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let at = with_doc(h, item.doc, |_, st| st.doc.position(item.id).map(|(_, i, _)| i)); + at.map(|i| num(float(i as u64 + 1))).ok_or_else(|| HostError::Error(STALE_ITEM.into())) +} + +/// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or +/// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`] +/// refuses it. A compound path whose last path this is stays, empty. +fn item_remove(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (whole, on_locked) = with_doc(h, item.doc, |_, st| { + (editable(&st.doc, item.id) && st.doc.node(item.id).is_some_and(all_editable), st.doc.on_locked_artboard(item.id)) + }); + if !whole { + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {}", item.id.0))); + } + if on_locked { + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); + } + // A compound path whose last path this is stays, empty, as it does after `move`. + edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?; + Ok(Data::Undefined) +} + +/// The error of `remove()` and `removeAll()` for an object on a locked artboard. +const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; + +/// The error of `move` and `duplicate` given an object of another document. +pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; + +/// An `ElementPlacement` value. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Placement { + /// `INSIDE` and `PLACEATBEGINNING`: on top of the container's contents. + Top, + /// `PLACEATEND`: under the container's contents. + Bottom, + /// `PLACEBEFORE`: directly above the relative object, in its parent. + Above, + /// `PLACEAFTER`: directly below the relative object, in its parent. + Below, +} + +fn placement_of(d: &Data) -> std::result::Result { + match d { + Data::Undefined => Ok(Placement::Top), + Data::String(s) => match s.as_str() { + "ElementPlacement.INSIDE" | "ElementPlacement.PLACEATBEGINNING" => Ok(Placement::Top), + "ElementPlacement.PLACEATEND" => Ok(Placement::Bottom), + "ElementPlacement.PLACEBEFORE" => Ok(Placement::Above), + "ElementPlacement.PLACEAFTER" => Ok(Placement::Below), + _ => Err(HostError::Type("insertionLocation must be an ElementPlacement value".into())), + }, + _ => Err(HostError::Type("insertionLocation must be an ElementPlacement value".into())), + } +} + +/// Where `move` and `duplicate` put an object relative to `target`: the parent it goes into and +/// the target it goes beside, checked against the object `item` before anything changes. +struct Destination { + parent: NodeId, + beside: Option, + how: Placement, +} + +/// The object a relative object of `move` or `duplicate` names: a page item or a layer of the +/// same document as `item`. An object may go directly above or below itself: a copy goes there, as +/// `layer.move` puts copies, and a move there leaves the object where it is. +fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::Result { + let how = placement_of(how)?; + let beside = matches!(how, Placement::Above | Placement::Below); + let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); + let Some(&[run, uid, high, low]) = handle.as_deref() else { + if handle_of(target, "Document").is_some() { + return Err(HostError::Error("a document as the relative object is not available yet".into())); + } + return Err(HostError::Type("the relative object must be a page item or a layer".into())); + }; + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if doc.uid != item.doc.uid { + return Err(HostError::Error(CROSS_DOCUMENT.into())); + } + let target = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + with_doc(h, doc, |_, st| { + let d = &st.doc; + let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let inside = d.ancestry(target).is_some_and(|a| a.iter().any(|i| *i == item.id && *i != target)); + if inside || (target == item.id && !beside) { + return Err(HostError::Error("an object cannot go into itself".into())); + } + let (parent, beside) = match how { + Placement::Top | Placement::Bottom => { + if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) { + return Err(HostError::Error(format!("{} cannot hold objects", typename(t).unwrap_or("Layer")))); + } + (target, None) + } + Placement::Above | Placement::Below => { + let parent = d.parent_of(target).ok_or_else(|| HostError::Error("an object cannot go beside a top-level layer".into()))?; + (parent, Some(target)) + } + }; + if !editable(d, parent) { + return Err(HostError::Error("the layer or group is hidden or locked".into())); + } + // An object on a locked artboard is not moved, as `editable` reads false for it. + if !editable(d, item.id) || on_locked_artboard(h, st, item.id) { + let name = d.node(item.id).and_then(typename).unwrap_or("page item"); + return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0))); + } + Ok(Destination { parent, beside, how }) + }) +} + +/// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place. +fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> { + let index = with_doc(h, doc, |_, st| { + let d = &st.doc; + let from = d.position(id); + let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent))); + let clips = d.node(to.parent).is_some_and(crate::doc::Node::clips) && count > 0; + let at = match (to.how, to.beside) { + (Placement::Top, _) => count, + (Placement::Bottom, _) => 0, + (how, Some(b)) => { + let (_, mut i, _) = d.position(b).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if let Some((Some(p), j, _)) = from + && p == to.parent + && j < i + { + i -= 1; + } + if how == Placement::Above { i + 1 } else { i } + } + (_, None) => count, + }; + Ok::<_, HostError>(if clips { at.max(1) } else { at }) + })?; + let now = with_doc(h, doc, |_, st| st.doc.position(id)); + if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) { + return Ok(()); + } + on_doc(h, doc.uid, true, |h| command(h, "node.move", &json!({"id": id.0, "parent": to.parent.0, "index": index})))?; + Ok(()) +} + +/// `move(relativeObject, insertionLocation?)`: moves the item into or beside `relativeObject`, a +/// page item or a layer of its document (`insertionLocation` defaults to `PLACEATBEGINNING`). An +/// object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard +/// is refused. Moving an object directly above or below itself leaves it where it is, and a compound +/// path whose last path moves out stays, empty. +fn item_move(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + if matches!(arg(a, 1), Data::Undefined) { + return Err(HostError::Type("move needs a relative object".into())); + } + let to = destination(h, item, arg(a, 1), arg(a, 2))?; + if to.beside != Some(item.id) { + place(h, item.doc, item.id, &to)?; + } + Ok(arg(a, 0).clone()) +} + +/// The error of `duplicate` on a path inside a compound path. +pub const COMPOUND_MEMBER: &str = "Duplicating a path inside a compound path is not available yet"; + +/// The error of `zOrder` on a path inside a compound path. +pub const COMPOUND_MEMBER_ORDER: &str = "Reordering a path inside a compound path is not available yet"; + +/// Whether `item` is a path inside a compound path. +fn in_compound(h: &Host, item: Item) -> bool { + with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }))) +} + +/// `duplicate(relativeObject?, insertionLocation?)`: a copy of the item, directly above it as +/// Edit › Duplicate makes one, or into or beside `relativeObject` as `move` puts it. → the copy. +/// When `node.move` refuses the place, the copy and every change it made are put back, and the +/// error is thrown. +fn item_duplicate(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + if in_compound(h, item) { + return Err(HostError::Error(COMPOUND_MEMBER.into())); + } + // `edit.duplicate` copies only what it can select. + let refused = with_doc(h, item.doc, |_, st| { + (!editable(&st.doc, item.id) || on_locked_artboard(h, st, item.id)).then(|| st.doc.node(item.id).and_then(typename).unwrap_or("page item")) + }); + if let Some(name) = refused { + return Err(HostError::Error(format!("Cannot duplicate {name} {}", item.id.0))); + } + let to = match arg(a, 1) { + Data::Undefined => { + if !matches!(arg(a, 2), Data::Undefined) { + return Err(HostError::Type("duplicate needs a relative object for an insertionLocation".into())); + } + None + } + target => Some(destination(h, item, target, arg(a, 2))?), + }; + let id = atomically(h, |h| { + let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?; + let id = made["ids"].get(0).and_then(Value::as_u64).ok_or_else(|| HostError::Error("the copy was not made".into()))?; + if let Some(to) = to { + place(h, item.doc, NodeId(id), &to)?; + } + Ok(id) + })?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + Ok(item_ref(h, st, NodeId(id))) +} + +/// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a +/// compound path is refused. The item must be selectable and outside hidden or locked layers and +/// locked artboards. +fn item_z_order(h: &Host, a: &[Data]) -> Answer { + let id = match arg(a, 1) { + Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront", + Data::String(s) if s == "ZOrderMethod.BRINGFORWARD" => "object.arrange.bringForward", + Data::String(s) if s == "ZOrderMethod.SENDBACKWARD" => "object.arrange.sendBackward", + Data::String(s) if s == "ZOrderMethod.SENDTOBACK" => "object.arrange.sendToBack", + _ => return Err(HostError::Type("zOrder needs a ZOrderMethod value".into())), + }; + let item = this_item(h, a)?; + if in_compound(h, item) { + return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into())); + } + refuse_protected_edit(h, item)?; + selection_ids(h, item.doc, arg(a, 0))?; + let (before, after) = with_doc(h, item.doc, |_, st| { + let at = st.doc.position(item.id); + let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); + (at.map(|(_, i, _)| i), count) + }); + let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) }; + let top = i + 1 >= after; + let unchanged = match id { + "object.arrange.bringToFront" | "object.arrange.bringForward" => top, + _ => i == 0, + }; + if !unchanged { + edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; + } + Ok(Data::Undefined) +} + +fn layer_name(h: &Host, a: &[Data]) -> Answer { + let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX)); + with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) +} + +fn layer_typename(h: &Host, a: &[Data]) -> Answer { + layer_name(h, a)?; + Ok(text("Layer")) +} + +/// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name. +fn named_text(class: &str, name: Answer) -> Answer { + match name? { + Data::String(n) => Ok(text(format!("[{class} {n}]"))), + _ => Ok(text(format!("[{class} ]"))), + } +} + +fn item_to_string(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(format!("[{} {}]", typename(n).unwrap_or("PageItem"), n.name.as_deref().unwrap_or(""))))) +} + +fn doc_to_string(h: &Host, a: &[Data]) -> Answer { + named_text("Document", doc_name(h, a)) +} + +fn layer_to_string(h: &Host, a: &[Data]) -> Answer { + named_text("Layer", layer_name(h, a)) +} + +/// `toString()` of an object without a name: `[Class]`. +fn class_text(name: &'static str) -> HostMember { + HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]"))))) +} + +fn typename_of(name: &'static str) -> HostMember { + HostMember::Get(Rc::new(move |_| Ok(text(name)))) +} + +fn class(name: &str, parent: Option<&str>, members: Vec<(String, HostMember)>, index: Option) -> HostClass { + HostClass { name: name.into(), parent: parent.map(Into::into), members, index, construct: None } +} + +fn named(items: Vec<(&str, HostMember)>) -> Vec<(String, HostMember)> { + items.into_iter().map(|(n, m)| (n.to_string(), m)).collect() +} + +/// The enumerations, as frozen objects whose members are `"Name.MEMBER"` strings. +const ENUMS: &[(&str, &[&str])] = &[ + ("ElementPlacement", &["INSIDE", "PLACEAFTER", "PLACEATBEGINNING", "PLACEATEND", "PLACEBEFORE"]), + ("ZOrderMethod", &["BRINGFORWARD", "SENDBACKWARD", "BRINGTOFRONT", "SENDTOBACK"]), + ("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]), + ("DocumentColorSpace", &["CMYK", "RGB"]), + ("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]), + ("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]), + ("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]), + ("DocumentPreviewMode", &["DefaultPreview", "OverprintPreview", "PixelPreview"]), + ("DocumentRasterResolution", &["ScreenResolution", "HighResolution", "MediumResolution"]), + ( + "DocumentTransparencyGrid", + &[ + "TransparencyGridBlue", + "TransparencyGridDark", + "TransparencyGridGreen", + "TransparencyGridLight", + "TransparencyGridMedium", + "TransparencyGridNone", + "TransparencyGridOrange", + "TransparencyGridPurple", + "TransparencyGridRed", + ], + ), +]; + +/// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` +/// holds. +pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { + for (name, members) in ENUMS { + let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + realm.define_host_object(name, items)?; + } + let l = link; + let mut application = named(vec![ + ("typename", typename_of("Application")), + ("documents", get(l, app_documents)), + ("activeDocument", property(l, app_active, app_set_active)), + ("selection", property(l, app_selection, app_set_selection)), + ("coordinateSystem", property(l, app_coords, app_set_coords)), + ("getIsFileOpen", method(l, app_is_open)), + ("executeMenuCommand", method(l, app_menu_command)), + ("toString", class_text("Application")), + ]); + application.push(later(l, "Application", "beep")); + let preset = { + let l = link.clone(); + let f: HostFunction = Rc::new(move |_: Vec| { + let h = current(&l)?; + h.charge_call(64)?; + new_preset(&h) + }); + let mut members = vec![("typename".to_string(), typename_of("DocumentPreset")), ("toString".to_string(), class_text("DocumentPreset"))]; + members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k)))); + HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) } + }; + let mut classes = vec![ + class("Application", None, application, None), + preset, + class( + "Documents", + None, + named(vec![ + ("typename", typename_of("Documents")), + ("length", get(l, docs_length)), + ("parent", get(l, app_ref)), + ("index", method(l, docs_index)), + ("getByName", method(l, docs_by_name)), + ("add", method(l, docs_add)), + ("addDocument", method(l, docs_add_document)), + ("toString", class_text("Documents")), + ]), + Some(function(l, docs_at)), + ), + ]; + let mut document = named(vec![ + ("typename", get(l, doc_typename)), + ("parent", get(l, doc_parent)), + ("name", get(l, doc_name)), + ("width", get(l, doc_width)), + ("height", get(l, doc_height)), + ("rulerUnits", get(l, doc_units)), + ("documentColorSpace", get(l, doc_color_space)), + ("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin)), + ("convertCoordinate", method(l, doc_convert)), + ("pageItems", get(l, doc_page_items)), + ("selection", property(l, doc_selection, doc_set_selection)), + ("toString", method(l, doc_to_string)), + ]); + document.extend( + ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] + .into_iter() + .map(|m| later(l, "Document", m)), + ); + document.push(("tags".into(), get(l, tags::doc_tags))); + classes.push(class("Document", None, document, None)); + classes.push(class( + "PageItems", + None, + named(vec![ + ("typename", get(l, items_typename)), + ("length", get(l, items_length)), + ("parent", get(l, items_parent)), + ("index", method(l, items_index)), + ("getByName", method(l, items_by_name)), + ("removeAll", method(l, items_remove_all)), + ("toString", method(l, items_to_string)), + ]), + Some(function(l, items_at)), + )); + let mut page_item = named(vec![ + ("typename", get(l, item_typename)), + ("parent", get(l, item_parent)), + ("name", property(l, item_name, item_set_name)), + ("note", property(l, item_note, item_set_note)), + ("tags", get(l, tags::item_tags)), + ("hidden", property(l, item_hidden, item_set_hidden)), + ("locked", property(l, item_locked, item_set_locked)), + ("selected", property(l, item_selected, item_set_selected)), + ("opacity", property(l, item_opacity, item_set_opacity)), + ("position", property(l, item_position, item_set_position)), + ("left", property(l, item_left, item_set_left)), + ("top", property(l, item_top, item_set_top)), + ("width", property(l, item_width, item_set_width)), + ("height", property(l, item_height, item_set_height)), + ("geometricBounds", get(l, item_geometric)), + ("visibleBounds", get(l, item_visible)), + ("controlBounds", get(l, item_visible)), + ("editable", get(l, item_editable)), + ("zOrderPosition", get(l, item_z_order_position)), + ("duplicate", method(l, item_duplicate)), + ("move", method(l, item_move)), + ("remove", method(l, item_remove)), + ("zOrder", method(l, item_z_order)), + ("toString", method(l, item_to_string)), + ]); + page_item.extend( + [ + "artworkKnockout", + "blendingMode", + "isIsolated", + "layer", + "pixelAligned", + "sliced", + "uRL", + "uuid", + "visibilityVariable", + "wrapInside", + "wrapOffset", + "wrapped", + "bringInPerspective", + "resize", + "rotate", + "transform", + "translate", + ] + .into_iter() + .map(|m| later(l, "PageItem", m)), + ); + classes.push(class("PageItem", None, page_item, None)); + classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.push(class( + "Layer", + None, + named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name)), ("toString", method(l, layer_to_string))]), + None, + )); + classes.extend(tags::classes(l)); + realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?; + // The application's members a script may name without `app.`, assigned as `app.` is. + realm.define_host_globals(vec![ + ("activeDocument".into(), function(l, app_active), Some(function(l, app_set_active))), + ("documents".into(), function(l, app_documents), None), + ("selection".into(), function(l, app_selection), Some(function(l, app_set_selection))), + ]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn restoring_the_selection_falls_back_only_on_a_refusal() { + assert_eq!(done_unless_refused(Ok(Data::Undefined)), Ok(true)); + assert_eq!(done_unless_refused(Err(HostError::Error("refused".into()))), Ok(false)); + // An internal failure or a stop ends the run instead of being taken for a refusal. + assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into()))); + assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into()))); + } + + #[test] + fn page_item_lists_are_kept_for_several_documents() { + let docs: Vec> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect(); + let ids = |n: u64| Rc::new(vec![NodeId(n)]); + let mut lists = Vec::new(); + keep_items(&mut lists, (1, docs[0].clone(), ids(1))); + keep_items(&mut lists, (2, docs[1].clone(), ids(2))); + // Reading two documents in turn keeps both lists. + assert_eq!(kept_items(&lists, 1, &docs[0]), Some(ids(1))); + assert_eq!(kept_items(&lists, 2, &docs[1]), Some(ids(2))); + // A changed document has no kept list, and its new list replaces the old one. + let changed = Arc::new(Document::new(100.0, 100.0)); + assert_eq!(kept_items(&lists, 1, &changed), None); + keep_items(&mut lists, (1, changed.clone(), ids(3))); + assert_eq!(lists.len(), 2); + assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3))); + // Past the limit, the list kept longest ago goes. + for (uid, d) in (10..).zip(&docs[2..]) { + keep_items(&mut lists, (uid, d.clone(), ids(uid))); + } + assert_eq!(lists.len(), ITEM_LISTS); + assert_eq!(kept_items(&lists, 2, &docs[1]), None); + assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3))); + } +} diff --git a/crates/engine/src/script/dom/tags.rs b/crates/engine/src/script/dom/tags.rs new file mode 100644 index 0000000000..c62f5eae81 --- /dev/null +++ b/crates/engine/src/script/dom/tags.rs @@ -0,0 +1,306 @@ +//! `PageItem.tags`, `Document.tags` and the `Tag` objects in them, as the help pages +//! and +//! describe them: name and value pairs on a +//! page item, which the native file keeps. Each change runs one of the `object.tag.*` commands. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A `Tags` collection is live: it lists the tags in their order on the object, counted from 0. +//! `Document.tags` lists the tags of every page item, in the order `pageItems` lists the items, +//! and cannot add a tag, since a tag belongs to a page item. +//! - `add()` gives a tag with an empty name and value. Names may be empty or repeated, and +//! `getByName` gives the first tag with the name. +//! - `name` and `value` are strings of at most 65,536 bytes, and an object has at most 64 tags. +//! - A tag that was deleted, or whose page item was, throws an error on every member. + +use std::ops::ControlFlow; + +use vectorcraft_doc::{MAX_TAG_TEXT, ObjectTag}; + +use super::{ + Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_DOCUMENT, STALE_ITEM, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, get, + handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, text, typename, whole, with_doc, +}; +use crate::NodeId; +use serde_json::json; +use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref}; + +/// The error for a tag that was deleted, or that came from an earlier run. +pub const STALE_TAG: &str = "Stale tag"; +/// The error of `Document.tags.add()`. +pub const NO_OWNER: &str = "A tag is added to a page item's tags, not to the document's"; + +/// What a `Tags` collection lists the tags of. +#[derive(Clone, Copy)] +enum Owner { + Item(Item), + Doc(Doc), +} + +/// The owner of the `Tags` collection `d` names. +fn owner_of(h: &Host, d: &Data) -> std::result::Result { + let Some(handle) = handle_of(d, "Tags") else { return Err(HostError::Type("this is not a Tags collection".into())) }; + match handle.as_slice() { + [run, uid] => find_doc(h, *run, *uid).map(Owner::Doc).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into())), + [run, uid, high, low] => Ok(Owner::Item(resolve_item(h, *run, *uid, *high, *low)?)), + _ => Err(HostError::Type("this is not a Tags collection".into())), + } +} + +/// The page item a handle's run, document uid and id (as [`id_parts`] gave it) name, which must +/// still be in its document. +fn resolve_item(h: &Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result { + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let alive = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| typename(n).is_some())); + if !alive { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok(Item { doc, id }) +} + +/// Calls `f` with each tag `owner` lists, in order, and the page item it is on, until `f` breaks. +/// The tags are borrowed from the document, not copied. `Document.tags` charges the run by the +/// number of page items read. +fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> ControlFlow<()>) -> std::result::Result<(), HostError> { + match owner { + Owner::Item(item) => with_doc(h, item.doc, |_, st| { + if let Some(n) = st.doc.node(item.id) { + for t in crate::cmd::tags::tags_of(n) { + if f(item.id, t).is_break() { + break; + } + } + } + Ok(()) + }), + Owner::Doc(doc) => with_doc(h, doc, |_, st| { + let ids = page_items(h, st); + h.charge_call(ids.len() as u64)?; + for id in ids.iter() { + if let Some(n) = st.doc.node(*id) { + for t in crate::cmd::tags::tags_of(n) { + if f(*id, t).is_break() { + return Ok(()); + } + } + } + } + Ok(()) + }), + } +} + +/// The first tag `owner` lists for which `pick` holds: its page item and its id. +fn find(h: &Host, owner: Owner, mut pick: impl FnMut(&ObjectTag) -> bool) -> std::result::Result, HostError> { + let mut found = None; + each(h, owner, |id, t| { + if pick(t) { + found = Some((id, t.id)); + return ControlFlow::Break(()); + } + ControlFlow::Continue(()) + })?; + Ok(found) +} + +fn doc_of_owner(owner: Owner) -> Doc { + match owner { + Owner::Item(i) => i.doc, + Owner::Doc(d) => d, + } +} + +fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data { + let [high, low] = id_parts(id); + let [tag_high, tag_low] = id_parts(NodeId(tag)); + host_ref("Tag", &[float(h.run), float(doc.uid), high, low, tag_high, tag_low]) +} + +/// `PageItem.tags`. +pub(super) fn item_tags(h: &Host, a: &[Data]) -> Answer { + let item = item_of(h, arg(a, 0))?; + let [high, low] = id_parts(item.id); + Ok(host_ref("Tags", &[float(h.run), float(item.doc.uid), high, low])) +} + +/// `Document.tags`. +pub(super) fn doc_tags(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Tags", &[float(h.run), float(doc.uid)])) +} + +// ---- Tags ---- + +fn tags_length(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let mut count = 0u64; + each(h, owner, |_, _| { + count += 1; + ControlFlow::Continue(()) + })?; + Ok(num(float(count))) +} + +fn tags_parent(h: &Host, a: &[Data]) -> Answer { + match owner_of(h, arg(a, 0))? { + Owner::Item(item) => Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, item.id))), + Owner::Doc(doc) => Ok(doc_ref(h, doc.uid)), + } +} + +fn tags_at(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + let mut left = i; + let found = find(h, owner, |_| { + let here = left == 0; + left = left.wrapping_sub(1); + here + })?; + Ok(found.map_or(Data::Undefined, |(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag))) +} + +fn tags_by_name(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + let found = find(h, owner, |t| t.name == *name)?; + found.map(|(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) +} + +fn tags_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => tags_by_name(h, a), + Data::Number(_) => match tags_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `tags.add()`: a new tag with an empty name and value after the item's other tags. +fn tags_add(h: &Host, a: &[Data]) -> Answer { + let item = match owner_of(h, arg(a, 0))? { + Owner::Item(item) => item, + Owner::Doc(_) => return Err(HostError::Error(NO_OWNER.into())), + }; + edit_item(h, item, "object.tag.add", &json!({"id": item.id.0}))?; + // The new tag is the item's last. Its id is read from the document, since the command's answer + // gives it as a number, which is exact only up to 2^53. + let tag = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).last().map(|t| t.id))); + let tag = tag.ok_or_else(|| HostError::Error("the tag was not added".into()))?; + Ok(tag_ref(h, item.doc, item.id, tag)) +} + +/// `tags.removeAll()`: deletes every tag in the collection, in one command. +fn tags_remove_all(h: &Host, a: &[Data]) -> Answer { + let owner = owner_of(h, arg(a, 0))?; + let mut ids: Vec = Vec::new(); + each(h, owner, |id, _| { + if ids.last() != Some(&id.0) { + ids.push(id.0); + } + ControlFlow::Continue(()) + })?; + if !ids.is_empty() { + let doc = doc_of_owner(owner); + on_doc(h, doc.uid, true, |h| command(h, "object.tag.removeAll", &json!({"ids": ids})))?; + } + Ok(Data::Undefined) +} + +// ---- Tag ---- + +/// A tag: its page item and its id there. +#[derive(Clone, Copy)] +struct TagRef { + item: Item, + tag: u64, +} + +/// The tag `d` names, which must still be on its page item. +fn tag_of(h: &Host, d: &Data) -> std::result::Result<(TagRef, ObjectTag), HostError> { + let Some(handle) = handle_of(d, "Tag") else { return Err(HostError::Type("this is not a Tag".into())) }; + let [run, uid, high, low, tag_high, tag_low] = handle.as_slice() else { return Err(HostError::Type("this is not a Tag".into())) }; + let item = resolve_item(h, *run, *uid, *high, *low)?; + let tag = id_of(*tag_high, *tag_low).ok_or_else(|| HostError::Error(STALE_TAG.into()))?.0; + let found = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).iter().find(|t| t.id == tag).cloned())); + let t = found.ok_or_else(|| HostError::Error(STALE_TAG.into()))?; + Ok((TagRef { item, tag }, t)) +} + +fn tag_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(tag_of(h, arg(a, 0))?.1.name)) +} + +fn tag_value(h: &Host, a: &[Data]) -> Answer { + Ok(text(tag_of(h, arg(a, 0))?.1.value)) +} + +/// Sets the tag's `key` (`name` or `value`) to the string the script gives, with no command when +/// it already has it. +fn set_text(h: &Host, a: &[Data], key: &str) -> Answer { + let Data::String(v) = arg(a, 1) else { return Err(HostError::Type(format!("{key} must be a string"))) }; + if v.len() > MAX_TAG_TEXT { + return Err(HostError::Range(format!("a tag's {key} is longer than 65,536 bytes"))); + } + let (t, now) = tag_of(h, arg(a, 0))?; + let same = if key == "name" { now.name == *v } else { now.value == *v }; + if !same { + edit_item(h, t.item, "object.tag.set", &json!({"id": t.item.id.0, "tag": t.tag, key: v}))?; + } + Ok(Data::Undefined) +} + +fn tag_set_name(h: &Host, a: &[Data]) -> Answer { + set_text(h, a, "name") +} + +fn tag_set_value(h: &Host, a: &[Data]) -> Answer { + set_text(h, a, "value") +} + +fn tag_parent(h: &Host, a: &[Data]) -> Answer { + let (t, _) = tag_of(h, arg(a, 0))?; + Ok(with_doc(h, t.item.doc, |_, st| item_ref(h, st, t.item.id))) +} + +fn tag_remove(h: &Host, a: &[Data]) -> Answer { + let (t, _) = tag_of(h, arg(a, 0))?; + edit_item(h, t.item, "object.tag.remove", &json!({"id": t.item.id.0, "tag": t.tag}))?; + Ok(Data::Undefined) +} + +/// `Tags.typename`, which throws like every other member once the collection's owner is gone. +fn tags_typename(h: &Host, a: &[Data]) -> Answer { + owner_of(h, arg(a, 0))?; + Ok(text("Tags")) +} + +/// `Tag.typename`, which throws like every other member once the tag is gone. +fn tag_typename(h: &Host, a: &[Data]) -> Answer { + tag_of(h, arg(a, 0))?; + Ok(text("Tag")) +} + +/// The `Tags` and `Tag` classes. +pub(super) fn classes(l: &Link) -> Vec { + let tags: Vec<(String, HostMember)> = named(vec![ + ("typename", get(l, tags_typename)), + ("length", get(l, tags_length)), + ("parent", get(l, tags_parent)), + ("index", method(l, tags_index)), + ("getByName", method(l, tags_by_name)), + ("add", method(l, tags_add)), + ("removeAll", method(l, tags_remove_all)), + ]); + let tag = named(vec![ + ("typename", get(l, tag_typename)), + ("name", property(l, tag_name, tag_set_name)), + ("value", property(l, tag_value, tag_set_value)), + ("parent", get(l, tag_parent)), + ("remove", method(l, tag_remove)), + ]); + vec![class("Tags", None, tags, Some(super::function(l, tags_at))), class("Tag", None, tag, None)] +} diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 476fbde5ad..9d4c90aed4 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1080,14 +1080,28 @@ pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result, path: Option<&str>) -> std::io::Result { +/// The spellings of each are tried in order, the script's first, and the first pair that some grant +/// holds is the one removed, so a grant kept under the spellings given first is removed without the +/// grants of later ones. → how many were removed. +pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&[String]>, path: Option<&[String]>) -> std::io::Result { let store = data_dir.with_file_name(GRANTS_FILE); let _lock = lock_store(&store)?; let grants = try_read_store(&store)?; let before = grants.len(); - let kept: Vec = - grants.into_iter().filter(|g| !(script.is_none_or(|s| g["script"] == *s) && path.is_none_or(|p| g["path"] == *p))).collect(); + // `None` matches any value; `Some(name)` only that name. + fn spellings(names: Option<&[String]>) -> Vec> { + match names { + None => vec![None], + Some(names) => names.iter().map(|n| Some(n.as_str())).collect(), + } + } + let matches = |g: &serde_json::Value, (script, path): (Option<&str>, Option<&str>)| { + script.is_none_or(|s| g["script"] == s) && path.is_none_or(|p| g["path"] == p) + }; + let pairs = spellings(script).into_iter().flat_map(|s| spellings(path).into_iter().map(move |p| (s, p))); + let pair = pairs.into_iter().find(|&pair| grants.iter().any(|g| matches(g, pair))); + let Some(pair) = pair else { return Ok(0) }; + let kept: Vec = grants.into_iter().filter(|g| !matches(g, pair)).collect(); let removed = before - kept.len(); if removed > 0 { write_store(&store, kept)?; diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs index d071195df6..9ec36c2447 100644 --- a/crates/engine/src/script/folder.rs +++ b/crates/engine/src/script/folder.rs @@ -237,7 +237,7 @@ fn hidden(entry: &std::fs::DirEntry) -> bool { /// Does Windows mark the file or folder of `m` hidden or system? #[cfg(windows)] -fn hidden_meta(m: &std::fs::Metadata) -> bool { +pub(super) fn hidden_meta(m: &std::fs::Metadata) -> bool { use std::os::windows::fs::MetadataExt as _; const HIDDEN_OR_SYSTEM: u32 = 0x2 | 0x4; m.file_attributes() & HIDDEN_OR_SYSTEM != 0 @@ -245,13 +245,13 @@ fn hidden_meta(m: &std::fs::Metadata) -> bool { /// Elsewhere a hidden file is one whose name starts with a dot, which the listing leaves out by name. #[cfg(not(windows))] -fn hidden_meta(_: &std::fs::Metadata) -> bool { +pub(super) fn hidden_meta(_: &std::fs::Metadata) -> bool { false } /// Is `path` a folder (`folder`) or a file, and not a link? With `shown`, also not one Windows /// marks hidden or system, which a listing leaves out. -fn plain(path: &Path, folder: bool, shown: bool) -> bool { +pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool { std::fs::symlink_metadata(path) .is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m))) } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index fdec594f69..c5fffb6574 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -51,6 +51,7 @@ pub mod console; pub mod dialogs; pub mod dollar; +pub mod dom; pub mod include; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; @@ -71,6 +72,7 @@ use crate::{ pub mod files; pub mod folder; +pub mod startup; /// The most bytes of source a run takes, as a file or as `source`. pub const MAX_SOURCE_BYTES: usize = 8 << 20; @@ -185,6 +187,7 @@ pub(crate) fn refused_text(id: &str) -> String { } /// A request to run a script. +#[derive(Clone)] pub(crate) struct Request { /// The run's name; unless `name_given`, a `#script` line in the script replaces it. pub name: String, @@ -799,6 +802,8 @@ struct Host { dollar: dollar::RunState, /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. args: RefCell<(Data, u64)>, + /// The run's state of the script object model (`app`). + dom: dom::State, /// The documents open when the run began as the person last left them, each with its own file /// and the file it was read from ([`crate::DocState::as_person_left`], /// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files @@ -1072,7 +1077,7 @@ impl Host { } let bridge = self.bridge.get().saturating_add(bytes); self.bridge.set(bridge); - if bridge > MAX_BRIDGE_BYTES { + if bridge > bridge_bytes() { return Err(self.over(OVER_BRIDGE)); } let n = self.calls_this_slice.get() + 1; @@ -1263,7 +1268,8 @@ fn note_ids(s: &mut Session) { fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { raise_ids(s); let mutating = waits_for_tool_edit(id); - let save = mutating.then(|| Savepoint::take(s, id)); + // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. + let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; crate::file_access::start_recording_writes(); @@ -1332,6 +1338,20 @@ fn vc_run(host: &Rc, args: Vec) -> std::result::Result std::result::Result { + command_value(host, id, params).map(|(data, _)| data) +} + +/// [`command`], with the command's result as it gave it as well as the script's copy of it. +fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> { + let id = id.to_string(); + let params = params.clone(); let session = host.session.clone(); let started = clock(); let r = { @@ -1367,7 +1387,7 @@ fn vc_run(host: &Rc, args: Vec) -> std::result::Result &'static str { /// `e`'s message, with what to do about a failure that comes from a script written for another /// program. A message the script supplied itself ([`RunError::authored`]) is given as it is. fn explained(e: &RunError) -> String { - const HOST_OBJECTS: &[&str] = &["app", "Window", "BridgeTalk", "activeDocument", "documents"]; + const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"]; let message = &e.message; - let names_host_object = - message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o))); + let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next()); + let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f)); if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object { format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)") } else { @@ -1631,24 +1651,31 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option>) { /// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in, /// with that file's name unless it is the run's own script. fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option>) { - let map = |m: &include::SourceMap| { - let (index, file, line, column) = m.locate(e.line, e.column); - let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; - (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file) - }; // An error `$.evalFile` raised for a file it could not run, and no script caught, is at that // file's place. if let Some((file, line, column)) = realm.error_mark().and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) { let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; return (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, Some(file)); } + placed(host, e, realm.error_source(), realm.error_tag()) +} + +/// `e`, raised at its line and column of the source `source` with tag `tag` ([`Realm::source_of`] +/// and [`Realm::error_tag`]), at the line and column of the file it is in, with that file's name +/// unless it is the run's own script. +fn placed(host: &Host, e: &RunError, source: u32, tag: u32) -> (RunError, Option>) { + let map = |m: &include::SourceMap| { + let (index, file, line, column) = m.locate(e.line, e.column); + let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() }; + (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file) + }; if e.line == 0 { return (e.clone(), None); } // An error in code from a source whose map is not at hand, such as code that `eval` compiled, // is given without a place. let unplaced = || (RunError { line: 0, column: 0, ..e.clone() }, None); - match realm.error_source() { + match source { 0 => { let (e, index, file) = map(&host.script_map.borrow()); (e, (index > 0).then_some(file)) @@ -1665,7 +1692,7 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option { let kept = host.kept_maps.as_ref().map(|k| k.borrow()); - match kept.as_ref().and_then(|k| k.get(realm.error_tag())) { + match kept.as_ref().and_then(|k| k.get(tag)) { Some(kept) => { let (e, index, file) = map(&kept.map); let file = match &kept.script { @@ -1691,9 +1718,10 @@ fn relocated(message: &str, old_line: u32, old_column: u32, line: u32, column: u } impl Session { - /// Is a script running? While one is, the commands that change anything are refused. + /// Is a script running, or a run `script.startup.run` queued waiting to start at the next + /// [`Self::script_pump`]? While one is, the commands that change anything are refused. pub fn script_running(&self) -> bool { - self.script_key.is_some() + self.script_key.is_some() || !self.script_queue.is_empty() } /// The named engine of the running script. @@ -1906,9 +1934,10 @@ impl Session { } } - /// Asks the running script to stop; it is rolled back at the next slice. False with none running. + /// Asks the running script to stop; it is rolled back at the next slice. Between two runs + /// `script.startup.run` queued, the next one stops as it starts. False with none running. pub fn script_request_stop(&mut self) -> bool { - if self.script_key.is_none() { + if !self.script_running() { return false; } self.script_stop.set(); @@ -1916,9 +1945,16 @@ impl Session { } /// Stops the running script at once and puts everything back, with the report of a stopped run - /// ([`Self::script_report`]). False with none running. + /// ([`Self::script_report`]). Between two runs `script.startup.run` queued, the queued runs are + /// not started, and the report stays the last run's. False with none running or queued. pub fn script_abandon(&mut self) -> bool { - let Some(key) = self.script_key.take() else { return false }; + // The runs queued after it are not started. + let queued = !self.script_queue.is_empty(); + self.script_queue.clear(); + self.script_queue_scope = None; + self.script_queue_then = None; + self.startup_ended(); + let Some(key) = self.script_key.take() else { return queued }; let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else { self.script_gone(key, console::Ending::Stopped); return true; @@ -1950,6 +1986,16 @@ impl Session { cmd::compositefonts::sync(self); } + /// A script named `name` that did not start because its file could not be read as a script: + /// the Script Console gets a run with a start line, `message` as its error and an end line. + pub(crate) fn note_unread(&mut self, name: &str, message: &str) { + self.script_runs += 1; + let name = console::line_name(name); + for entry in [console::Entry::Start, console::Entry::Error(format!("{name}: {message}")), console::Entry::End(console::Ending::Error)] { + self.script_console.push(console::ConsoleLine { run: self.script_runs, name: name.clone(), entry }, false); + } + } + /// A script can't start while a document holds a drag in progress or an undo group, which its /// one undo step could not take in. fn settle_for_script(&mut self) -> Result<()> { @@ -2007,7 +2053,8 @@ impl Session { // from its first run, and they act for the run that calls them. let fresh = realm.is_none(); // A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read - // code the way the script does. + // code the way the script does. Its realm has `Promise`: a kept realm gets it at the first + // `.js` run that names it, and keeps it as it keeps its globals. let es2015 = include::es2015_script(request.file.as_deref()); let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() }; let strict = options.strict; @@ -2016,6 +2063,9 @@ impl Session { Some(mut realm) => { realm.set_limits(limits); realm.set_es2015(es2015); + if es2015 { + realm.add_es2015(); + } realm } None => { @@ -2084,6 +2134,7 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), + dom: dom::State::default(), run_docs: RefCell::new( self.docs .iter() @@ -2130,6 +2181,7 @@ impl Session { .and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) }) .and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) }) .and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) }) + .and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) }) .and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() }) .and_then(|()| { let r = realm.start(&expanded.source); @@ -2163,8 +2215,33 @@ impl Session { } /// Advances the running script by one slice. `None` while it is still running; otherwise the - /// run has ended: its report, or the error that ended it, with the documents put back. + /// run has ended: its report, or the error that ended it, with the documents put back. When + /// `script.startup.run` queued more runs, the next one starts at the pump after that, so the + /// ended run's report ([`Self::script_report`]) stays until then; a queued run that cannot start + /// is kept for [`Self::take_startup_failures`]. pub fn script_pump(&mut self) -> Option> { + if self.script_key.is_none() { + // A stop asked for between two runs stops the run that starts now, which clears it. + let stop = self.script_stop.is_set(); + self.start_queued(); + if stop && (self.script_key.is_some() || !self.script_queue.is_empty()) { + self.script_stop.set(); + } else { + self.script_stop.clear(); + } + return None; + } + // Held aside while the run ends, so that its commit does not see the queue as a running script. + let queue = std::mem::take(&mut self.script_queue); + let result = self.pump_one(); + self.script_queue = queue; + let result = result?; + self.startup_ended(); + Some(result) + } + + /// [`Self::script_pump`] for the running script alone. + fn pump_one(&mut self) -> Option> { let key = self.script_key.take()?; let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else { self.script_gone(key, console::Ending::Internal); @@ -2318,6 +2395,11 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); + let rejections = rejections_report(host, &job.realm); + if let (false, Some(o)) = (rejections.is_empty(), report.as_object_mut()) { + o.insert("unhandledRejections".into(), Value::Array(rejections)); + o.insert("unhandledRejectionCount".into(), json!(job.realm.unhandled_rejection_count())); + } close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); self.script_report = Some(report.clone()); @@ -2363,6 +2445,29 @@ const NO_RUN: &str = "this function's script run has ended"; const DROP_MAIN: &str = "the main script engine is new for each run and is never kept, so it cannot be dropped"; const NO_ENGINES_ON_WEB: &str = "named script engines (#targetengine) are not available on the web"; const ENGINE_BUSY: &str = "the script engine is in use by another run"; +const UNHANDLED_REJECTION: &str = "unhandled promise rejection"; +const UNHANDLED_REJECTIONS: &str = "unhandled promise rejections"; + +/// The promises `realm`'s run rejected and left without a handler, each with its reason and, when +/// known, the line, column and file it was rejected at. +fn rejections_report(host: &Host, realm: &Realm) -> Vec { + let mut out = Vec::new(); + for r in realm.unhandled_rejections() { + let e = RunError { kind: RunErrorKind::Thrown, message: r.message.clone(), line: r.line, column: r.column, authored: r.authored }; + let (e, file) = placed(host, &e, realm.source_of(r.tag), r.tag); + let mut o = json!({ + "message": e.message, + "messageOrigin": if e.authored { "script" } else { "built-in" }, + "line": e.line, + "column": e.column, + }); + if let (Some(file), Some(map)) = (file, o.as_object_mut()) { + map.insert("file".into(), json!(&*file)); + } + out.push(o); + } + out +} /// The report of a run that failed; `file` is the included file the error is in. fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fuel_left: u64, fuel_used: u64) -> Value { @@ -2443,6 +2548,18 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console:: if report["ok"] == false { each_line(&error_text(&host.name, report), |line, cut| line_to(s, host, console::Entry::Error(line), cut)); } + if let Some(rejections) = report["unhandledRejections"].as_array() { + for r in rejections { + let mut placed = r.clone(); + placed["message"] = json!(format!("{UNHANDLED_REJECTION}: {}", r["message"].as_str().unwrap_or_default())); + each_line(&error_text(&host.name, &placed), |line, cut| line_to(s, host, console::Entry::Error(line), cut)); + } + let more = report["unhandledRejectionCount"].as_u64().unwrap_or(0).saturating_sub(rejections.len() as u64); + if more > 0 { + let text = format!("{}: {more} more {UNHANDLED_REJECTIONS}", host.name); + each_line(&text, |line, cut| line_to(s, host, console::Entry::Error(line), cut)); + } + } let timing = clock().is_some(); let ms = millis(host.run_nanos.get()); let slow = slowest(&host.commands.borrow()); @@ -2537,6 +2654,15 @@ fn growth_objects() -> u64 { GROWTH_OBJECTS } +/// The data a run may pass to and from commands. +fn bridge_bytes() -> u64 { + #[cfg(test)] + if let Some(n) = TEST_BRIDGE_BYTES.with(Cell::get) { + return n; + } + MAX_BRIDGE_BYTES +} + /// The limits of a command's result on its way to the script. fn result_limits() -> DataLimits { #[cfg(test)] @@ -2554,6 +2680,8 @@ thread_local! { pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; + /// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`]. + pub(crate) static TEST_BRIDGE_BYTES: Cell> = const { Cell::new(None) }; /// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`]. pub(crate) static TEST_ENGINE_HEAP: Cell> = const { Cell::new(None) }; /// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`]. diff --git a/crates/engine/src/script/startup.rs b/crates/engine/src/script/startup.rs new file mode 100644 index 0000000000..e20e67de3f --- /dev/null +++ b/crates/engine/src/script/startup.rs @@ -0,0 +1,126 @@ +//! The Startup Scripts folder: the `.jsx` files `script.startup.run` runs, one after another, when +//! the app starts and before a script chosen from File › Scripts runs ([`list`]), and the read of +//! one of them when its turn comes ([`read`]). +//! +//! Only the folder's own files are taken, never its subfolders. A listing follows no link: a +//! symbolic link or a Windows junction is left out, and so is a folder that is itself a link. Names +//! that start with a dot, files Windows marks hidden or system, names that are not Unicode, names +//! longer than [`folder::MAX_NAME_BYTES`] and files whose extension is not `.jsx` are left out too. +//! The files are sorted by name without regard to case, then by name. +//! +//! The limits are the Scripts folder's ([`folder::MAX_ENTRIES`], [`folder::MAX_SCRIPTS`] and +//! [`folder::MAX_SCAN`]), VectorCraft's own values. A listing that reaches one keeps what it found +//! and says so ([`Listing::truncated`]). + +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use super::folder; + +/// What a Startup Scripts folder holds. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Listing { + /// The scripts, in the order they run. + pub scripts: Vec, + /// Some scripts may be missing: a limit was reached or an entry could not be read. + pub truncated: bool, + /// The folder is there and could not be read, or is a link. + pub unreadable: bool, +} + +/// Does the file name `name` name a startup script: a `.jsx` file (in any case) whose name does not +/// start with a dot and has at most [`folder::MAX_NAME_BYTES`] bytes? +pub fn takes(name: &str) -> bool { + !name.starts_with('.') + && name.len() <= folder::MAX_NAME_BYTES + && Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("jsx")) +} + +/// The startup scripts in `root`, within the Scripts folder's limits. A folder that does not exist +/// gives an empty listing. +pub fn list(root: &Path) -> Listing { + let start = std::time::Instant::now(); + list_with(root, &folder::Limits::default(), &mut || start.elapsed()) +} + +/// The startup scripts in `root`, within `limits` (the entries, scripts and time ones); +/// `elapsed` says how long the listing has taken. +pub fn list_with(root: &Path, limits: &folder::Limits, elapsed: &mut dyn FnMut() -> Duration) -> Listing { + let unreadable = Listing { unreadable: true, ..Listing::default() }; + match std::fs::symlink_metadata(root) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Listing::default(), + Err(_) => return unreadable, + Ok(m) if m.file_type().is_symlink() || !m.is_dir() => return unreadable, + Ok(_) => {} + } + if root.to_str().is_none() { + return unreadable; + } + let Ok(entries) = std::fs::read_dir(root) else { return unreadable }; + let mut listing = Listing::default(); + let mut names: Vec = vec![]; + for (visited, entry) in entries.enumerate() { + if visited >= limits.entries || elapsed() > limits.time { + listing.truncated = true; + break; + } + let Ok(entry) = entry else { + listing.truncated = true; + continue; + }; + let Ok(name) = entry.file_name().into_string() else { continue }; + if !takes(&name) { + continue; + } + let Ok(kind) = entry.file_type() else { + listing.truncated = true; + continue; + }; + if !kind.is_file() || kind.is_symlink() || entry.metadata().is_ok_and(|m| folder::hidden_meta(&m)) { + continue; + } + names.push(name); + } + names.sort_by(|a, b| (a.to_lowercase(), a).cmp(&(b.to_lowercase(), b))); + if names.len() > limits.scripts { + listing.truncated = true; + names.truncate(limits.scripts); + } + listing.scripts = names.into_iter().map(|n| root.join(n)).collect(); + listing +} + +/// Is `path` a startup script a listing of `root` can hold now: a file [`takes`] names, directly in +/// `root`, where neither `root` nor the file is a link and the file is not marked hidden or system? +pub fn holds(root: &Path, path: &Path) -> bool { + if path.parent() != Some(root) { + return false; + } + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return false }; + takes(name) && folder::plain(root, true, false) && folder::plain(path, false, true) +} + +/// The first `max` bytes of the startup script at `path`, or `None` when [`holds`] does not hold for +/// it before the read and again after it, or it cannot be read. +pub fn read(root: &Path, path: &Path, max: usize) -> Option> { + if !holds(root, path) { + return None; + } + let file = std::fs::File::open(path).ok()?; + if !file.metadata().is_ok_and(|m| m.is_file()) { + return None; + } + let mut bytes = vec![]; + file.take(max as u64).read_to_end(&mut bytes).ok()?; + holds(root, path).then_some(bytes) +} + +/// A run `script.startup.run` queued for the app, which starts it when the run before it ends. +#[derive(Clone, Debug, PartialEq)] +pub enum Queued { + /// A startup script, read when its turn comes, with its `maxFuel`. + Startup { path: PathBuf, fuel: u64 }, + /// The script that runs after the startup scripts, as `script.run`'s parameters. + Then(serde_json::Value), +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 770cfd2bea..2890618dd8 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -59,7 +59,8 @@ impl Session { histories_seen: None, tool: vectorcraft_tools::create("selection"), lender: None, - back_to_bucket: false, + back_to_painter: None, + stop_pick: None, held_input: Default::default(), input_count: 0, edit_started_by: None, @@ -77,6 +78,7 @@ impl Session { depth: 0, replaying: false, shape_drawn: false, + prefs_resets: Vec::new(), tool_panic: None, tool_resets: 0, tool_set_since_reset: false, @@ -109,6 +111,7 @@ impl Session { plugin_loads: Default::default(), plugin_loads_in_background: false, scripts_dir: None, + startup_scripts_dir: None, metadata_templates_dir: None, new_doc_profile_dir: None, proof_setup_dir: None, @@ -137,6 +140,7 @@ impl Session { place_queue_loads: 0, image_hand_off: None, trace_hand_off: None, + retype_hand_off: None, place_cursor_requests: false, package_hand_off: None, screens_hand_off: None, @@ -175,6 +179,11 @@ impl Session { script_console: Default::default(), script_runs: 0, script_frames: false, + script_queue: Default::default(), + script_queue_scope: None, + script_queue_then: None, + startup_loading: None, + startup_failures: vec![], script_high_water: Default::default(), script_in_run: false, script_copy_first: cfg!(target_arch = "wasm32"), diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index cc7af44898..e723be129b 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -200,6 +200,29 @@ impl Session { Ok(v) } + /// Run `f`, an edit that applies or edits built-in effect `effect`. The undo step it records, + /// when named after the effect, keeps the effect's id ([`crate::HistoryEntry::effect`]), so a + /// frontend names it as the Effect menu names the effect. Run as an interaction's preview + /// itself, not as one command of a batch the preview runs, the step the interaction records + /// keeps it instead, while that preview is the last one. A later edit of an undo group keeps + /// none. + pub(crate) fn edit_effect(&mut self, effect: &str, f: impl FnOnce(&mut Self) -> Result) -> Result { + let id = vectorcraft_render::effects::built_in_effect(effect).map(|(id, _)| id); + let previewed = self.previewing && self.depth == 1; + let outer = std::mem::replace(&mut self.doc_mut()?.effect_step, id); + let v = f(self); + if let Ok(st) = self.doc_mut() { + st.effect_step = outer; + if v.is_ok() + && previewed + && let Some(it) = &mut st.interaction + { + it.effect = id; + } + } + v + } + /// Change only the selection (not an undo step). pub fn select(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> { self.revealing(|s| s.select_unwatched(f)) @@ -510,6 +533,7 @@ impl Session { } st.interaction = Some(Interaction { label: label.to_string(), + effect: None, doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), preview: None, @@ -518,6 +542,7 @@ impl Session { used_defaults_only: false, preview_paint: None, color_mode_paints: None, + tool_paints: false, deferred_color_mode: None, active_layer: st.active_layer, layer_rows: st.layer_rows.clone(), @@ -538,10 +563,11 @@ impl Session { if self.script_running() { return Err(EngineError::Busy); } - // While the Live Paint Bucket is active, paint previews change only the bucket's colors, so - // each preview starts from the colors the interaction began with; so does a preview with + // While the active tool paints with the chosen fill or stroke (the Live Paint Bucket, the + // Shape Builder), paint previews of that kind change only the colors it paints with, so each + // preview starts from the colors the interaction began with; so does a preview with // `defaultsOnly: true`, and one after it. - let bucket = self.bucket_paints(); + let tool_paints = self.tool_paints(false) || self.tool_paints(true); let (paint, restore_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; @@ -556,7 +582,8 @@ impl Session { // A batch, or a preview that changed the new-art paints (a pattern rename), started from // the paints the interaction began with. it.used_defaults_only |= cmd::asks_defaults_only(params); - let restore_paint = bucket + it.tool_paints |= tool_paints; + let restore_paint = it.tool_paints || cmd == "command.batch" || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) @@ -566,6 +593,8 @@ impl Session { it.color_mode_paints = None; it.deferred_color_mode = None; it.plane_placed = false; + // The effect the preview below applies or edits marks the step, not an earlier one's. + it.effect = None; if selection_changed { st.selection.clone_from(&it.selection); } @@ -720,15 +749,17 @@ impl Session { self.clear_deferred_overlay_cache(); self.decoded_images.empty(); self.pending_paint = None; - // While the Live Paint Bucket is active, a previewed color is the bucket's color, which the - // cancel puts back as well, as it does a color previewed with `defaultsOnly: true`. - let bucket = self.bucket_paints(); + // A color previewed while the active tool painted with the chosen fill or stroke is the + // tool's color, which the cancel puts back as well, also after another tool was chosen, as + // it does a color previewed with `defaultsOnly: true`. + let tool_paints = self.tool_paints(false) || self.tool_paints(true); let used_defaults_only = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.used_defaults_only); if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) .filter(|it| { - bucket + tool_paints + || it.tool_paints || it.used_defaults_only || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some() diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 1a130d5cbc..85dcfcdf5f 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -92,7 +92,7 @@ impl Session { fn execute_unwatched(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?; // A clipboard import is a query that replaces the clipboard, which the end of a run sets too. - if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) { + if self.depth == 0 && self.script_running() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) { return Err(EngineError::Busy); } // A step of a batch a script runs is held to the same rule as the script's own commands. @@ -401,8 +401,18 @@ impl Session { // The params' own values win, except a null: it reads as a key left out, so the // noted value is the one the command resolved. A noted `defaultsOnly` wins too: the // Live Paint Bucket kept the command to the defaults although the params gave `false`. + // An object noted for an object the params give (`effect.apply`'s `params`) is merged + // by the same rule, so the keys the command filled in stay. Value::Object(m) if !note.is_empty() => { for (k, v) in m { + if let (Some(Value::Object(resolved)), Value::Object(given)) = (note.get_mut(k), v) { + for (gk, gv) in given { + if !gv.is_null() || !resolved.contains_key(gk) { + resolved.insert(gk.clone(), gv.clone()); + } + } + continue; + } if (!v.is_null() && k != "defaultsOnly") || !note.contains_key(k) { note.insert(k.clone(), v.clone()); } @@ -444,6 +454,7 @@ impl Session { st.doc = doc; st.selection = selection; st.interaction = interaction; + st.effect_step = None; if let Some(history) = history { st.history = history; } diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index a48795b910..29cd6f1bea 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -20,7 +20,10 @@ //! disabled, which `disabled.json` in the same folder lists (`plugin.setEnabled`). The Additional //! Plug-ins Folder preference is not copied: it is loaded from where it is. `grants.json` holds what the user granted the plug-ins //! stored there that list permissions (id, module hash, permissions); a stored plug-in whose -//! permissions it doesn't grant is skipped with a log record, and stays in the folder. +//! permissions it doesn't grant is skipped with a log record, and stays in the folder. The file +//! carries a generation and a MAC of its generation, grants and folder, made with a key the user's +//! key store keeps ([`grant_keys`]); a file without that MAC, or at another generation than the +//! one the key store keeps for the folder, grants nothing. //! * **Plug-in settings and caches**: `storage/id-/` in the plug-in store, the id written as //! [`case_safe`] writes it, holds what a plug-in //! keeps with the `settings` and `cache` permissions ([`PluginStorage`]): `settings.json` and a @@ -52,6 +55,8 @@ use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError}; use crate::Session; use crate::cmd::pdfcmds::{PRESET_FORMAT, PresetFile}; +pub mod grant_keys; + /// Files read from one store folder, at most (the rest are ignored). pub const MAX_STORE_FILES: usize = 1000; /// The largest PDF presets file read (a preset is a few kilobytes). @@ -463,6 +468,11 @@ fn put(dir: &Path, file: &str, bytes: &[u8]) -> bool { if std::fs::File::open(&path).is_ok_and(|old| holds(old, bytes)) { return true; } + #[cfg(test)] + if file == GRANTS_FILE && GRANTS_WRITE_FAILS.get() { + log::warn!("can't save {}: the test fails it", path.display()); + return false; + } let written = std::fs::create_dir_all(dir).and_then(|()| write_atomic(&path, bytes)); if let Err(e) = &written { log::warn!("can't save {}: {e}", path.display()); @@ -560,6 +570,9 @@ thread_local! { /// Tests: removing [`GRANTS_FILE`] fails on this thread while the file still reads, as when /// another program holds it open. pub(crate) static GRANTS_DELETE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: writing [`GRANTS_FILE`] fails on this thread and leaves the file as it was, as on a + /// full volume. + pub(crate) static GRANTS_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: [`Session::put_back_plugin`] writes the old module back on this thread and then /// reports a failure, as when the last flush of a copy fails. pub(crate) static PUT_BACK_FAILS_AFTER_WRITE: std::cell::Cell = const { std::cell::Cell::new(false) }; @@ -810,18 +823,10 @@ impl Session { } let dir = load.dir.clone(); // The grants file is read once for this turn. `written` holds whether it names each id - // whose grant this turn removed or put back. + // whose grant this turn removed or put back. Only a signed file grants anything + // ([`signed_grants`]). let file = read_grants(&dir); - let mut grants = self.counted( - &dir, - match &file { - Ok(file) => file.grants.clone(), - Err(e) => { - log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); - BTreeMap::new() - } - }, - ); + let mut grants = self.counted(&dir, signed_grants(&dir, &file)); let mut written: BTreeMap = BTreeMap::new(); let named = |written: &BTreeMap, id: &str| { written.get(id).copied().unwrap_or_else(|| match &file { @@ -1304,9 +1309,25 @@ impl Session { /// Record in the store what the user granted plug-in `id` (`None`: nothing), leaving the store's /// other grants as they are; with none left, remove the file. Entries this version can't use - /// are written back as they were, except one for `id`. A grants file that is too large, can't - /// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded; - /// so is one whose new content would be larger than `MAX_GRANTS_FILE`. The file is read and + /// are written back as they were, except one for `id`. The generation is raised, and the file is + /// written at the generation after the raised one with the MAC of its grants for this folder + /// ([`grant_keys`]), making the key when the key store holds none; the key store then keeps that + /// generation ([`put_grants`]). A signed file left empty is removed after raising the generation + /// ([`take_signed_grants`]). The generation is never lowered: when the file can't be written or + /// removed after the raise, the file in place grants nothing and its plug-ins ask again. A file + /// VectorCraft didn't write for this folder ([`Trust::Unsigned`]) grants nothing: a grant replaces it with a file that holds that grant alone, and removing one + /// raises the generation ([`raise_generation`]), then takes out the entry for `id` and leaves the + /// rest unsigned. Removing a grant when there is no file, or when the file grants nothing + /// (unsigned, too large or not a list) and has no entry to take out, also raises the generation + /// when the key store holds a key ([`retire_signed_copies`]), so that a signed copy put back + /// doesn't grant it again. The generation is never read from the file; when it can't be raised, + /// nothing is recorded. When the key store can't be reached ([`Trust::Unknown`], or + /// a key can't be made or kept), the file is left as it is and nothing is recorded, and an entry + /// for `id` stays; a removal then reports a failure, also when the file doesn't name `id`. A + /// grants file that is too large, can't be read or doesn't hold a list is left as it is, with a + /// log record, and nothing is recorded; so is one whose new content would be larger than + /// `MAX_GRANTS_FILE`. A removal still holds for a file that is too large or doesn't hold a list + /// once the generation is raised ([`retire_signed_copies`]). The file is read and /// written in `turn`. → whether the store now holds what was asked (`false` without a folder, /// and when `turn` isn't held). When it does, the grant kept for `id` counts again, for every /// session in the process attached to the store ([`Session::ignore_stored_grant`]). @@ -1364,13 +1385,33 @@ impl Session { Ok(file) => file, Err(e) => { log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); - return false; + // A file that is too large or doesn't hold a list grants nothing and is left as it + // is, but a signed copy made before it must not grant `id` again once it is put back: + // the removal holds once no such copy can. + return grant.is_none() && !e.unread && retire_signed_copies(dir); } }; #[cfg(test)] if let Some(between) = AFTER_GRANTS_READ.take() { between(); } + match (file.trust, &grant) { + // Nothing in the file can be checked, so nothing in it is rewritten: a grant holds for + // the session only, and one the file may still hold for `id` can't be removed. A file + // that doesn't name `id` may not be the one the kept generation was signed for, so the + // removal isn't known to hold either. + (Trust::Unknown, _) => return false, + // The file grants nothing. A new grant replaces it with a signed file that holds that + // grant alone; removing one takes its entry out and leaves the rest unsigned. + (Trust::Unsigned, Some(_)) => { + log::warn!("replacing the stored plug-in grants {}: VectorCraft didn't write them for this folder", dir.join(GRANTS_FILE).display()); + file.grants.clear(); + file.other.clear(); + } + (Trust::Unsigned | Trust::Signed, _) => {} + } + let signed = file.trust == Trust::Signed || grant.is_some(); + let removing = grant.is_none(); let others = file.other.len(); file.other.retain(|entry| entry.get("id").and_then(serde_json::Value::as_str) != Some(id)); let changed = match grant { @@ -1378,23 +1419,25 @@ impl Session { None => file.grants.remove(id).is_some(), } || file.other.len() != others; if !changed { - return true; + // Without a file, or with one that grants nothing, the last signed file may still be + // around as a copy at the kept generation: a removal raises the generation so that the + // copy doesn't grant `id` again once it is put back. A signed file that doesn't name `id` + // is the latest, so every copy that does is at an earlier generation already. The new + // generation is past every one a file was signed at, so the file left in place grants + // nothing either. + return !removing || (file.present && file.trust == Trust::Signed) || retire_signed_copies(dir); } let mut entries: Vec = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect(); entries.extend(file.other); - if entries.is_empty() { - return take(dir, GRANTS_FILE); + if signed { + return if entries.is_empty() { take_signed_grants(dir) } else { put_grants(dir, entries, true) }; } - // The file is read back only up to its cap: written compactly when pretty-printed is larger, - // and not at all when that is too. - let fits = |bytes: &Vec| bytes.len() as u64 <= MAX_GRANTS_FILE; - match serde_json::to_vec_pretty(&entries).ok().filter(fits).or_else(|| serde_json::to_vec(&entries).ok().filter(fits)) { - Some(bytes) => put(dir, GRANTS_FILE, &bytes), - None => { - log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), too_large(MAX_GRANTS_FILE)); - false - } + // An unsigned file loses an entry: the generation is raised first, so that no signed copy + // made before brings the entry back, nor the file itself when it can't be rewritten. + if raise_generation(dir).is_none() { + return false; } + if entries.is_empty() { take(dir, GRANTS_FILE) } else { put_grants(dir, entries, false) } } /// Whether the store holds, or may hold, an entry for the plug-in `id`, including one this @@ -1408,6 +1451,19 @@ impl Session { }) } + /// The grant the attached plug-in store's signed grants file holds for the plug-in `id` (`None` + /// without a folder, and when the file grants nothing: unsigned, unreadable or without an entry + /// for `id`). + pub(crate) fn stored_plugin_grant(&self, id: &str) -> Option { + self.plugin_dir.as_deref().and_then(|dir| stored_grants(dir).remove(id)) + } + + /// Does the attached plug-in store hold a module file for the plug-in `id`, loaded or not (one + /// that no grant covers is skipped at startup and stays in the folder)? + pub(crate) fn holds_stored_plugin(&self, id: &str) -> bool { + self.plugin_dir.as_deref().is_some_and(|dir| std::fs::symlink_metadata(dir.join(format!("{}.{PLUGIN_EXT}", file_stem(id)))).is_ok()) + } + /// Remove the plug-in `id` from the store in `turn` → whether its file is gone (`false` without a /// folder, and when `turn` isn't held). pub(crate) fn unstore_plugin(&self, turn: &StoreTurn, id: &str) -> bool { @@ -2049,10 +2105,16 @@ impl Storage for PluginStorage { /// What the grants file of a plug-in store holds. #[derive(Default)] struct GrantsFile { - /// The grants this version can use, by plug-in id. + /// The grants this version can use, by plug-in id. They grant something only when the file is + /// [`Trust::Signed`]. grants: BTreeMap, /// The entries it can't use (a permission it doesn't know, an invalid id), as they were. other: Vec, + /// Whether VectorCraft wrote the grants for this folder. + trust: Trust, + /// Whether there is a grants file: `false` when there is none, and the file is then empty and + /// [`Trust::Signed`]. + present: bool, } impl GrantsFile { @@ -2062,6 +2124,207 @@ impl GrantsFile { } } +/// Whether a grants file was written by VectorCraft for its folder ([`grant_keys`]). +#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)] +enum Trust { + /// There is no file, or it is at the generation kept for its folder and carries the MAC of that + /// generation, its grants and its folder made with the user's key. + #[default] + Signed, + /// It doesn't: an older version wrote it, another program wrote or changed it, it was copied + /// from another folder or machine, it is an earlier copy or a write whose generation wasn't kept + /// (its generation is not the one the key store keeps), or the key store holds no key. It grants + /// nothing. + Unsigned, + /// The key store can't be reached, so it is not known which. It grants nothing, and is left as + /// it is. + Unknown, +} + +/// The version of the grants file this version writes ([`SignedGrants::version`]). +const GRANTS_VERSION: u64 = 1; + +/// The grants file as this version writes it: its generation ([`grant_keys::current_generation`]), +/// the grants, and their MAC ([`grant_keys::sign`]) over the generation and the list written as +/// compact JSON. +#[derive(serde::Serialize, serde::Deserialize)] +struct SignedGrants { + version: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + generation: Option, + grants: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + mac: Option, +} + +/// Tests: a grants file for the plug-in store `dir` that holds `grants` (a JSON list, written as it +/// is) at the generation kept for `dir`, with their MAC made with the key in use, as VectorCraft +/// writes one. +#[cfg(test)] +pub(crate) fn signed_grants_file(dir: &Path, grants: &str) -> Vec { + let entries: Vec = serde_json::from_str(grants).unwrap_or_default(); + let key = grant_keys::signing_key().unwrap_or_else(|e| panic!("no key: {e}")); + let folder = plugin_store_key(dir); + let generation = grant_keys::current_generation(&folder).unwrap_or_else(|e| panic!("no generation: {e}")); + let canonical = serde_json::to_vec(&entries).unwrap_or_default(); + let mac = grant_keys::sign(&key, &folder, generation, &canonical).unwrap_or_default(); + format!(r#"{{"version":{GRANTS_VERSION},"generation":{generation},"grants":{grants},"mac":"{mac}"}}"#).into_bytes() +} + +/// Tests: the entries of the grants file `bytes`, signed or not. +#[cfg(test)] +pub(crate) fn grant_entries(bytes: &[u8]) -> Vec { + match serde_json::from_slice::(bytes) { + Ok(serde_json::Value::Array(entries)) => entries, + Ok(serde_json::Value::Object(mut file)) => match file.remove("grants") { + Some(serde_json::Value::Array(entries)) => entries, + _ => vec![], + }, + _ => vec![], + } +} + +/// Whether `signed`, read from the grants file of the plug-in store `dir`, is at the generation kept +/// for `dir` and carries the MAC of that generation, its grants and `dir` made with the user's key. +/// A file at another generation, one behind or one ahead of the kept one included, is +/// [`Trust::Unsigned`]. +fn trust_of(dir: &Path, signed: &SignedGrants) -> Trust { + let (Some(tag), Some(generation), true) = (&signed.mac, signed.generation, signed.version == GRANTS_VERSION) else { return Trust::Unsigned }; + let Ok(grants) = serde_json::to_vec(&signed.grants) else { return Trust::Unsigned }; + let folder = plugin_store_key(dir); + let kept = grant_keys::current_key().and_then(|key| key.map(|key| Ok((key, grant_keys::current_generation(&folder)?))).transpose()); + match kept { + Ok(Some((key, kept))) if generation == kept && grant_keys::verify(&key, &folder, generation, &grants, tag) => Trust::Signed, + Ok(_) => Trust::Unsigned, + Err(e) => { + log::warn!("can't check the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); + Trust::Unknown + } + } +} + +/// Write `entries` as the grants file of the plug-in store `dir`, pretty-printed, or compact when +/// that is larger than [`MAX_GRANTS_FILE`] → whether it went there; the file is not written when the +/// key or the generation can't be had or it is too large either way. When `signed`, the generation +/// is raised first ([`raise_generation`]), the file is written at the generation after the raised one +/// with its MAC, and the key store keeps that generation once the file is written. Every signed write +/// is then at a generation no file was signed at before, a write whose generation wasn't kept +/// included, since that one is at most one past the generation the key store kept. A file too large +/// either way is found before the raise, and then nothing changes. The kept generation only goes up: +/// when the file isn't written after the raise, the generation stays raised, so the file in place +/// grants nothing and its plug-ins ask again. When the file's generation can't be kept, the file is +/// at a generation the key store doesn't hold, so it grants nothing either. Both report a failure. +/// Call it in the store's turn ([`StoreTurn`]). +fn put_grants(dir: &Path, entries: Vec, signed: bool) -> bool { + let path = dir.join(GRANTS_FILE); + let folder = plugin_store_key(dir); + if !signed { + return match grants_bytes(serde_json::to_value(entries).ok()) { + Some(bytes) => put(dir, GRANTS_FILE, &bytes), + None => { + log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); + false + } + }; + } + let key = match grant_keys::signing_key() { + Ok(key) => key, + Err(e) => { + log::warn!("not updating the stored plug-in grants {}: {e}", path.display()); + return false; + } + }; + // A file too large to keep is found before the raise, at the generation it would be written at + // (three past the kept one, [`raise_generation`]) and a MAC of its length, so the file in place + // keeps its grants when nothing can be written. When the kept generation can't be read, the raise + // fails too. + let expected = grant_keys::current_generation(&folder).ok().and_then(|kept| kept.checked_add(3)).unwrap_or(u64::MAX); + let mut file = + SignedGrants { version: GRANTS_VERSION, generation: Some(expected), grants: entries, mac: Some("0".repeat(2 * grant_keys::KEY_LEN)) }; + if grants_bytes(serde_json::to_value(&file).ok()).is_none() { + log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); + return false; + } + let Some(raised) = raise_generation(dir) else { return false }; + let Some(next) = raised.checked_add(1) else { + log::warn!("not updating the stored plug-in grants {}: the generation can't be raised", path.display()); + return false; + }; + file.generation = Some(next); + file.mac = serde_json::to_vec(&file.grants).ok().and_then(|grants| grant_keys::sign(&key, &folder, next, &grants)); + let Some(bytes) = file.mac.as_ref().and_then(|_| grants_bytes(serde_json::to_value(&file).ok())) else { + log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); + return false; + }; + put(dir, GRANTS_FILE, &bytes) && keep_generation(dir, &folder, next) +} + +/// `file` written as the bytes of a grants file: pretty-printed, or compact when that is larger than +/// [`MAX_GRANTS_FILE`]; `None` when that is too, since the file is read back only up to its cap. +fn grants_bytes(file: Option) -> Option> { + let fits = |bytes: &Vec| bytes.len() as u64 <= MAX_GRANTS_FILE; + file.and_then(|file| serde_json::to_vec_pretty(&file).ok().filter(fits).or_else(|| serde_json::to_vec(&file).ok().filter(fits))) +} + +/// Keep `generation` for the grants file of the plug-in store `dir` (whose folder is `folder`) → +/// whether the key store kept it; a failure is logged. +fn keep_generation(dir: &Path, folder: &Path, generation: u64) -> bool { + match grant_keys::set_current_generation(folder, generation) { + Ok(()) => true, + Err(e) => { + log::warn!("the stored plug-in grants {} grant nothing: their generation wasn't kept ({e})", dir.join(GRANTS_FILE).display()); + false + } + } +} + +/// Remove the signed grants file of the plug-in store `dir` → whether it is gone. Its generation is +/// raised first, so that no copy of the file grants anything once it is gone. The generation stays +/// raised when the file can't be removed: the file left in place then grants nothing, and its +/// plug-ins ask again. The file holds no grant but the one being removed. Nothing is removed when +/// the generation can't be raised. Call it in the store's turn ([`StoreTurn`]). +fn take_signed_grants(dir: &Path) -> bool { + raise_generation(dir).is_some() && take(dir, GRANTS_FILE) +} + +/// Keep a generation two past the one kept for the grants file of the plug-in store `dir`, so that +/// no signed copy of the file made before grants anything → the generation kept now; `None`, with a +/// log record, when the key store can't read or keep it or the generation is within two of the +/// largest 64-bit value. A signed write whose generation wasn't kept is at the generation after the +/// kept one ([`put_grants`]), so the new generation is past it too. The generation comes from the +/// key store alone, never from a file, which anyone can edit, and it is never lowered again. +fn raise_generation(dir: &Path) -> Option { + let folder = plugin_store_key(dir); + let raised = grant_keys::current_generation(&folder).and_then(|generation| { + // A signed write goes one past the raised generation, so that one must fit too. + let next = generation.checked_add(3).and(generation.checked_add(2)); + let next = next.ok_or_else(|| grant_keys::KeyStoreError("the generation can't be raised".into()))?; + grant_keys::set_current_generation(&folder, next).map(|()| next) + }); + match raised { + Ok(generation) => Some(generation), + Err(e) => { + log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); + None + } + } +} + +/// Make sure no signed copy of an earlier grants file of the plug-in store `dir` grants anything → +/// whether none can: the generation is raised ([`raise_generation`]) when the key store holds a key, +/// and left as it is when it holds none, since no file is then signed. `false`, with a log record, +/// when the key store can't read or keep it. Call it in the store's turn ([`StoreTurn`]). +fn retire_signed_copies(dir: &Path) -> bool { + match grant_keys::current_key() { + Ok(None) => true, + Ok(Some(_)) => raise_generation(dir).is_some(), + Err(e) => { + log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); + false + } + } +} + /// Why the grants file of a plug-in store gave no grants. struct GrantsError { /// Opening or reading the file failed, so what it holds is unknown. When `false`, the file is @@ -2072,8 +2335,10 @@ struct GrantsError { } /// The grants file of the plug-in store `dir`: empty when there is none, an error when it is too -/// large, can't be read or doesn't hold a list. An entry that doesn't parse as a grant, or names an -/// invalid id, is kept in [`GrantsFile::other`] with a log record. +/// large, can't be read or doesn't hold a list. A list without a MAC (as an older version wrote it), +/// or with one the user's key didn't make for `dir`, is [`Trust::Unsigned`] ([`trust_of`]). An +/// entry that doesn't parse as a grant, or names an invalid id, is kept in [`GrantsFile::other`] +/// with a log record. fn read_grants(dir: &Path) -> Result { let path = dir.join(GRANTS_FILE); let bytes = match read_past_cap(&path, MAX_GRANTS_FILE) { @@ -2084,8 +2349,23 @@ fn read_grants(dir: &Path) -> Result { if bytes.len() as u64 > MAX_GRANTS_FILE { return Err(GrantsError { unread: false, why: too_large(MAX_GRANTS_FILE) }); } - let entries = serde_json::from_slice::>(&bytes).map_err(|e| GrantsError { unread: false, why: e.to_string() })?; - let mut file = GrantsFile::default(); + let not_a_list = |why: String| GrantsError { unread: false, why }; + let (entries, trust) = match serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))? { + serde_json::Value::Array(entries) => (entries, Trust::Unsigned), + serde_json::Value::Object(_) => { + let signed = serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))?; + let trust = trust_of(dir, &signed); + (signed.grants, trust) + } + _ => return Err(not_a_list("not a list of grants".into())), + }; + if trust == Trust::Unsigned { + log::warn!( + "the stored plug-in grants {} were not written by VectorCraft for this folder: the plug-ins that list permissions ask for them again", + path.display() + ); + } + let mut file = GrantsFile { trust, present: true, ..GrantsFile::default() }; let mut first_error = None; for entry in entries { let why = match serde_json::from_value::(entry.clone()) { @@ -2106,11 +2386,19 @@ fn read_grants(dir: &Path) -> Result { } /// The grants kept in the plug-in store `dir` that this version can use, by plug-in id: none when -/// there is no grants file, and none, with a log record, when it is too large, can't be read or -/// doesn't hold a list. +/// there is no grants file, when VectorCraft didn't write it for `dir` or that can't be checked +/// ([`Trust`]), and none, with a log record, when it is too large, can't be read or doesn't hold a +/// list. fn stored_grants(dir: &Path) -> BTreeMap { - match read_grants(dir) { - Ok(file) => file.grants, + signed_grants(dir, &read_grants(dir)) +} + +/// [`stored_grants`] from `file`, the grants file of the plug-in store `dir` as [`read_grants`] +/// read it. +fn signed_grants(dir: &Path, file: &Result) -> BTreeMap { + match file { + Ok(file) if file.trust == Trust::Signed => file.grants.clone(), + Ok(_) => BTreeMap::new(), Err(e) => { log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); BTreeMap::new() diff --git a/crates/engine/src/store/grant_keys.rs b/crates/engine/src/store/grant_keys.rs new file mode 100644 index 0000000000..151cd4055d --- /dev/null +++ b/crates/engine/src/store/grant_keys.rs @@ -0,0 +1,541 @@ +//! The key that marks a plug-in store's `grants.json` as written by VectorCraft. The file carries an +//! HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)) of the grants it holds and of +//! the plug-in folder it is in, made with a random 32-byte key that the user's key store keeps +//! ([`GrantKeyStore`]), never a file. A grants file without the MAC of that key for its folder (one +//! an older version wrote, one another program wrote or changed, one copied from another folder or +//! machine) grants nothing. +//! +//! The key store also keeps a generation for each plug-in folder, raised on every signed write of +//! its grants file and never lowered, and the file carries its generation inside the MAC. A file +//! whose generation is not the one kept (an earlier copy put back over the current file, or a write +//! whose generation the key store didn't keep or that failed after the raise) grants nothing either. +//! +//! The process uses one key store ([`set_grant_key_store`]); the apps use the system's +//! ([`use_os_grant_keys`]). In a process that sets none, every grants file counts as one whose key +//! store can't be reached: a grant holds for the session only. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, LazyLock, Mutex}; + +/// The length of a key, in bytes, and of the MAC. +pub const KEY_LEN: usize = 32; + +/// A key for the MAC of grants files. Its bytes are never shown: `{:?}` prints `GrantKey(..)`. +#[derive(Clone, PartialEq, Eq)] +pub struct GrantKey([u8; KEY_LEN]); + +impl GrantKey { + /// The key with the bytes `bytes`. + pub fn from_bytes(bytes: [u8; KEY_LEN]) -> Self { + GrantKey(bytes) + } + + /// A new key from the system's random source. + #[cfg(not(target_arch = "wasm32"))] + pub fn random() -> Result { + let mut bytes = [0u8; KEY_LEN]; + getrandom::fill(&mut bytes).map_err(|e| KeyStoreError(format!("no random numbers ({e})")))?; + Ok(GrantKey(bytes)) + } + + /// The browser keeps no grants file. + #[cfg(target_arch = "wasm32")] + pub fn random() -> Result { + Err(KeyStoreError("there is no key store".into())) + } +} + +impl std::fmt::Debug for GrantKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("GrantKey(..)") + } +} + +/// Why a key store gave no key or didn't keep one. The message never holds key bytes. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{0}")] +pub struct KeyStoreError(pub String); + +/// Where the key of grants files is kept. +pub trait GrantKeyStore: Send + Sync { + /// The key kept, `None` when there is none; an error when the store can't be reached or read. + fn key(&self) -> Result, KeyStoreError>; + /// Keep `key` in place of any kept before. + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError>; + /// The key kept, after making and keeping a new one when there is none. The key returned is the + /// one read back from the store, so a key another process kept first wins. + fn create_key(&self) -> Result { + if let Some(key) = self.key()? { + return Ok(key); + } + self.set_key(&GrantKey::random()?)?; + self.key()?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into())) + } + /// The generation kept for the grants file of the plug-in store whose folder is `folder` + /// ([`super::plugin_store_key`]), read from the store each time; `None` when none is kept. + fn generation(&self, folder: &Path) -> Result, KeyStoreError>; + /// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError>; +} + +/// A key store in memory: the key and the generations last as long as the store. For tests and +/// embedders. +#[derive(Default)] +pub struct MemoryGrantKeys { + key: Mutex>, + generations: Mutex>, +} + +impl MemoryGrantKeys { + /// A store that holds `key`. + pub fn with_key(key: GrantKey) -> Self { + MemoryGrantKeys { key: Mutex::new(Some(key)), ..MemoryGrantKeys::default() } + } +} + +impl GrantKeyStore for MemoryGrantKeys { + fn key(&self) -> Result, KeyStoreError> { + Ok(self.key.lock().unwrap_or_else(|e| e.into_inner()).clone()) + } + + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> { + *self.key.lock().unwrap_or_else(|e| e.into_inner()) = Some(key.clone()); + Ok(()) + } + + fn generation(&self, folder: &Path) -> Result, KeyStoreError> { + Ok(self.generations.lock().unwrap_or_else(|e| e.into_inner()).get(folder).copied()) + } + + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + self.generations.lock().unwrap_or_else(|e| e.into_inner()).insert(folder.to_path_buf(), generation); + Ok(()) + } +} + +/// The key store of the process ([`set_grant_key_store`]). +static PROCESS_STORE: Mutex>> = Mutex::new(None); + +/// The one memory store of [`keep_grant_keys_in_memory`]. +static SHARED_MEMORY: LazyLock> = LazyLock::new(Arc::default); + +#[cfg(test)] +thread_local! { + /// Tests: the key store this thread uses in place of the process's. + pub(crate) static THREAD_STORE: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Use `store` for the grants files of every plug-in store in the process from now on (`None`: no +/// key store, so grants hold for the session only). +pub fn set_grant_key_store(store: Option>) { + *PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()) = store; +} + +/// Keep the key in memory for the rest of the process, one key for every caller: grants files +/// written in the process count in it, and not in another process. For tests. +pub fn keep_grant_keys_in_memory() { + let shared: Arc = SHARED_MEMORY.clone(); + set_grant_key_store(Some(shared)); +} + +/// Keep the key in the system's key store: Keychain on macOS, Credential Manager on Windows, the +/// Secret Service on Linux and the BSDs, as the generic secret `hmac-sha256-v1` of the service +/// `org.storytold.vectorcraft.plugin-grants`. +#[cfg(not(target_arch = "wasm32"))] +pub fn use_os_grant_keys() { + set_grant_key_store(Some(Arc::new(OsGrantKeys::default()))); +} + +/// The key store in use: the thread's in tests, else the process's; in tests, the shared memory +/// store when the process set none. +fn current_store() -> Option> { + #[cfg(test)] + if let Some(store) = THREAD_STORE.with_borrow(Clone::clone) { + return Some(store); + } + let store = PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()).clone(); + #[cfg(test)] + let store = store.or_else(|| Some(SHARED_MEMORY.clone() as Arc)); + store +} + +/// The key kept for grants files: `None` when there is none yet, an error when there is no key +/// store or it can't be reached. +pub(crate) fn current_key() -> Result, KeyStoreError> { + current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.key() +} + +/// The key to sign a grants file with: the one kept, else a new one, kept first +/// ([`GrantKeyStore::create_key`]). +pub(crate) fn signing_key() -> Result { + let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?; + match store.key()? { + Some(key) => Ok(key), + None => store.create_key(), + } +} + +/// The generation kept for the grants file of the plug-in store whose folder is `folder`: 0 when +/// none is kept yet, an error when there is no key store or it can't be reached. +pub(crate) fn current_generation(folder: &Path) -> Result { + Ok(current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.generation(folder)?.unwrap_or(0)) +} + +/// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. The kept +/// generation only goes up: one lower than the kept one is an error, and the kept one stays, since a +/// lower one could match a file signed before. +pub(crate) fn set_current_generation(folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?; + if store.generation(folder)?.is_some_and(|kept| generation < kept) { + return Err(KeyStoreError("the key store keeps a later generation".into())); + } + store.set_generation(folder, generation) +} + +/// The start of every MAC input: what it is a MAC of, and the version of the file. +#[cfg(not(target_arch = "wasm32"))] +const DOMAIN: &[u8] = b"VectorCraft plug-in grants v1\0"; + +/// The MAC of `grants` (the grants list as compact JSON) at `generation` in the plug-in store whose +/// folder is `folder` ([`super::plugin_store_key`]), made with `key`. The folder and the generation +/// go in with their lengths first. +#[cfg(not(target_arch = "wasm32"))] +fn mac_of(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option> { + use hmac::Mac; + let mut mac = hmac::Hmac::::new_from_slice(&key.0).ok()?; + let folder = folder.as_os_str().as_encoded_bytes(); + let generation = generation.to_be_bytes(); + mac.update(DOMAIN); + mac.update(&(folder.len() as u64).to_be_bytes()); + mac.update(folder); + mac.update(&(generation.len() as u64).to_be_bytes()); + mac.update(&generation); + mac.update(grants); + Some(mac) +} + +/// The MAC of `grants` at `generation` in `folder` with `key`, as 64 lower-case hexadecimal digits. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn sign(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option { + use hmac::Mac; + Some(mac_of(key, folder, generation, grants)?.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect()) +} + +/// Whether `tag` is the whole MAC of `grants` at `generation` in `folder` with `key` ([`sign`]), +/// compared in constant time; a shorter or longer tag is not. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn verify(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8], tag: &str) -> bool { + use hmac::Mac; + let Some(tag) = from_hex(tag) else { return false }; + mac_of(key, folder, generation, grants).is_some_and(|mac| mac.verify_slice(&tag).is_ok()) +} + +/// The browser keeps no grants file. +#[cfg(target_arch = "wasm32")] +pub(crate) fn sign(_: &GrantKey, _: &Path, _: u64, _: &[u8]) -> Option { + None +} + +/// The browser keeps no grants file. +#[cfg(target_arch = "wasm32")] +pub(crate) fn verify(_: &GrantKey, _: &Path, _: u64, _: &[u8], _: &str) -> bool { + false +} + +/// The bytes written as lower-case hexadecimal digits in `tag`, at most twice [`KEY_LEN`] of them; +/// `None` for anything else. +#[cfg(not(target_arch = "wasm32"))] +fn from_hex(tag: &str) -> Option> { + let digits = tag.as_bytes(); + let (pairs, rest) = digits.as_chunks::<2>(); + if !rest.is_empty() || pairs.len() > KEY_LEN { + return None; + } + let digit = |d: u8| match d { + b'0'..=b'9' => Some(d - b'0'), + b'a'..=b'f' => Some(d - b'a' + 10), + _ => None, + }; + pairs.iter().map(|&[high, low]| Some((digit(high)? << 4) | digit(low)?)).collect() +} + +/// The system's key store, through `keyring-core` and the store crate of the platform. The key is +/// read from the store each time it is needed. The key and the generations are kept as lower-case +/// hexadecimal text, since some stores (KDE Wallet behind the Secret Service) keep only UTF-8. +#[cfg(not(target_arch = "wasm32"))] +struct OsGrantKeys { + /// Held while a key is kept, so that the threads of the process that make the first key at the + /// same time keep one. + making: Mutex<()>, + /// The connection to the system's key store, once one is made. A failed connection is not + /// kept, and a kept one is dropped when the key store can't be reached through it or fails + /// ([`OsGrantKeys::failed`]): the next call connects again, so a key store that starts after + /// VectorCraft, or restarts, is used. + store: Mutex>>, + /// How a connection is made ([`connect`]). + connect: fn() -> Result, keyring_core::Error>, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Default for OsGrantKeys { + fn default() -> Self { + OsGrantKeys { making: Mutex::default(), store: Mutex::default(), connect } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl OsGrantKeys { + const SERVICE: &str = "org.storytold.vectorcraft.plugin-grants"; + const ACCOUNT: &str = "hmac-sha256-v1"; + + /// The system's key store: the connection made before, else a new one. + fn store(&self) -> Result, KeyStoreError> { + let mut store = self.store.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(store) = store.as_ref() { + return Ok(store.clone()); + } + Ok(store.insert((self.connect)().map_err(store_error)?).clone()) + } + + /// What the key store error `e` says ([`store_error`]). When the key store can't be reached or + /// fails, the connection is dropped first, so the next call makes a new one: the Secret Service + /// loses the session of a connection when it restarts. An entry that isn't there keeps it. + fn failed(&self, e: keyring_core::Error) -> KeyStoreError { + if matches!(e, keyring_core::Error::NoStorageAccess(_) | keyring_core::Error::PlatformFailure(_)) { + *self.store.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + store_error(e) + } + + fn entry(&self, account: &str) -> Result { + self.store()?.build(Self::SERVICE, account, None).map_err(|e| self.failed(e)) + } + + fn key_entry(&self) -> Result { + self.entry(Self::ACCOUNT) + } + + /// The key the system's key store keeps, read from it. + fn stored(&self, entry: &keyring_core::Entry) -> Result, KeyStoreError> { + match entry.get_secret() { + // A secret that is not 64 hexadecimal digits is not a key this version made: there is none. + Ok(secret) => Ok(std::str::from_utf8(&secret) + .ok() + .and_then(from_hex) + .and_then(|bytes| <[u8; KEY_LEN]>::try_from(bytes.as_slice()).ok()) + .map(GrantKey)), + Err(keyring_core::Error::NoEntry) => Ok(None), + Err(e) => Err(self.failed(e)), + } + } + + /// The entry of the generation of the plug-in store whose folder is `folder`: the account + /// `generation-v1-` followed by the SHA-256 of the folder in hexadecimal digits. + fn generation_entry(&self, folder: &Path) -> Result { + use sha2::Digest; + let digest = sha2::Sha256::digest(folder.as_os_str().as_encoded_bytes()); + self.entry(&format!("generation-v1-{}", to_hex(&digest))) + } +} + +/// A connection to the system's key store: Keychain on macOS, Credential Manager on Windows, the +/// Secret Service on Linux and the BSDs. The same stores, made the same way, that `keyring` 4.2 +/// uses, so entries it kept are read. +#[cfg(not(target_arch = "wasm32"))] +fn connect() -> Result, keyring_core::Error> { + #[cfg(target_os = "macos")] + { + let store: Arc = apple_native_keyring_store::keychain::Store::new()?; + Ok(store) + } + #[cfg(windows)] + { + let store: Arc = windows_native_keyring_store::Store::new()?; + Ok(store) + } + #[cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))] + { + let store: Arc = zbus_secret_service_keyring_store::Store::new()?; + Ok(store) + } + #[cfg(not(any(target_os = "macos", windows, all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))))] + Err(keyring_core::Error::NoDefaultStore) +} + +/// `bytes` as lower-case hexadecimal digits. +#[cfg(not(target_arch = "wasm32"))] +fn to_hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +#[cfg(not(target_arch = "wasm32"))] +impl GrantKeyStore for OsGrantKeys { + /// Read from the key store each time, so that a key removed or replaced there is not used. + fn key(&self) -> Result, KeyStoreError> { + self.stored(&self.key_entry()?) + } + + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> { + let _making = self.making.lock().unwrap_or_else(|e| e.into_inner()); + self.key_entry()?.set_secret(to_hex(&key.0).as_bytes()).map_err(|e| self.failed(e)) + } + + /// Reads the key store again and makes the key only while holding [`creation_lock`], so that + /// processes of this user that make the first key at the same time all keep the first one made. + fn create_key(&self) -> Result { + let _making = self.making.lock().unwrap_or_else(|e| e.into_inner()); + let entry = self.key_entry()?; + if let Some(key) = self.stored(&entry)? { + return Ok(key); + } + let _turn = creation_lock()?; + match self.stored(&entry)? { + Some(key) => Ok(key), + None => { + entry.set_secret(to_hex(&GrantKey::random()?.0).as_bytes()).map_err(|e| self.failed(e))?; + self.stored(&entry)?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into())) + } + } + } + + /// Read from the key store each time, since another process on the folder may have raised it. + /// A kept value that is not 16 hexadecimal digits is an error, so that nothing counts as signed + /// with it. + fn generation(&self, folder: &Path) -> Result, KeyStoreError> { + match self.generation_entry(folder)?.get_secret() { + Ok(secret) => std::str::from_utf8(&secret) + .ok() + .and_then(from_hex) + .and_then(|bytes| <[u8; 8]>::try_from(bytes.as_slice()).ok()) + .map(|bytes| Some(u64::from_be_bytes(bytes))) + .ok_or_else(|| KeyStoreError("the key store holds a generation that is not 16 hexadecimal digits".into())), + Err(keyring_core::Error::NoEntry) => Ok(None), + Err(e) => Err(self.failed(e)), + } + } + + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + self.generation_entry(folder)?.set_secret(to_hex(&generation.to_be_bytes()).as_bytes()).map_err(|e| self.failed(e)) + } +} + +/// `vectorcraft-plugin-grant-key.lock` in a folder of this user's own, locked until the file is +/// dropped, waiting while another process holds it: `%LOCALAPPDATA%` on Windows, the temporary +/// folder on macOS, `$XDG_RUNTIME_DIR` elsewhere. An error when there is no such folder or the file +/// can't be locked: no key is made then. +#[cfg(not(target_arch = "wasm32"))] +fn creation_lock() -> Result { + #[cfg(windows)] + let (dir, variable) = (std::env::var_os("LOCALAPPDATA"), "%LOCALAPPDATA%"); + #[cfg(target_os = "macos")] + let (dir, variable) = (Some(std::env::temp_dir().into_os_string()), "$TMPDIR"); + #[cfg(not(any(windows, target_os = "macos")))] + let (dir, variable) = (std::env::var_os("XDG_RUNTIME_DIR"), "$XDG_RUNTIME_DIR"); + let dir = dir.map(std::path::PathBuf::from).filter(|dir| dir.is_absolute()); + let dir = dir.ok_or_else(|| KeyStoreError(format!("there is no folder for the key's lock ({variable} is not set)")))?; + let file = std::fs::File::options() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(dir.join("vectorcraft-plugin-grant-key.lock")) + .map_err(|e| KeyStoreError(format!("can't open the key's lock ({e})")))?; + file.lock().map_err(|e| KeyStoreError(format!("can't lock the key's lock ({e})")))?; + Ok(file) +} + +/// What a key store error says, without the secret some of them hold. +#[cfg(not(target_arch = "wasm32"))] +fn store_error(e: keyring_core::Error) -> KeyStoreError { + KeyStoreError(match e { + keyring_core::Error::NoStorageAccess(e) => format!("the key store is locked or can't be reached ({e})"), + keyring_core::Error::PlatformFailure(e) => format!("the key store failed ({e})"), + keyring_core::Error::NoDefaultStore => "there is no key store".into(), + _ => "the key store can't read or keep the key".into(), + }) +} + +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +mod tests { + use super::*; + use keyring_core::api::CredentialStoreApi; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Connections asked for from [`flaky`]. + static TRIES: AtomicUsize = AtomicUsize::new(0); + /// The store [`flaky`] connects to. + static MOCK: LazyLock> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap()); + + /// A key store that can't be reached on the first try and is reached on every later one. + fn flaky() -> Result, keyring_core::Error> { + if TRIES.fetch_add(1, Ordering::SeqCst) == 0 { + return Err(keyring_core::Error::NoDefaultStore); + } + let store: Arc = MOCK.clone(); + Ok(store) + } + + /// Connections asked for from [`restarting`]. + static RESTARTS: AtomicUsize = AtomicUsize::new(0); + /// The store [`restarting`] connects to first. + static BEFORE: LazyLock> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap()); + /// The store [`restarting`] connects to on every later try. + static AFTER: LazyLock> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap()); + + /// A key store that restarts after the first connection: later connections reach another store. + fn restarting() -> Result, keyring_core::Error> { + let store: Arc = if RESTARTS.fetch_add(1, Ordering::SeqCst) == 0 { BEFORE.clone() } else { AFTER.clone() }; + Ok(store) + } + + /// A connection that the key store can't be reached through is dropped, and the next call + /// connects again; an entry that isn't there keeps the connection. + #[test] + fn the_system_key_store_reconnects_after_it_restarts() { + let keys = OsGrantKeys { connect: restarting, ..OsGrantKeys::default() }; + assert_eq!(keys.key().unwrap(), None, "no key is kept yet"); + keys.set_key(&GrantKey::from_bytes([0xc1; KEY_LEN])).unwrap(); + assert_eq!(RESTARTS.load(Ordering::SeqCst), 1, "an entry that isn't there keeps the connection"); + + AFTER.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("d2".repeat(KEY_LEN).as_bytes()).unwrap(); + let entry = BEFORE.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap(); + let cred: &keyring_core::mock::Cred = entry.as_any().downcast_ref().unwrap(); + cred.set_error(keyring_core::Error::NoStorageAccess("the session is gone".into())); + assert!(keys.key().is_err(), "the connection fails"); + assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xd2; KEY_LEN])), "the next call reads the key through a new connection"); + assert_eq!(RESTARTS.load(Ordering::SeqCst), 2); + } + + /// The secret `MOCK` keeps for `account`, as it is kept. + fn kept(account: &str) -> Vec { + MOCK.build(OsGrantKeys::SERVICE, account, None).unwrap().get_secret().unwrap() + } + + /// The system key store is connected again after a connection fails, the key and the + /// generations are kept as hexadecimal text, and the key is read from the store each time; a + /// value kept as raw bytes is not read as a key or a generation. + #[test] + fn the_system_key_store_reconnects_and_keeps_text() { + let keys = OsGrantKeys { connect: flaky, ..OsGrantKeys::default() }; + assert!(keys.key().is_err(), "the first connection fails"); + let key = GrantKey::from_bytes([0xa7; KEY_LEN]); + keys.set_key(&key).unwrap(); + assert_eq!(kept(OsGrantKeys::ACCOUNT), "a7".repeat(KEY_LEN).into_bytes(), "the key is kept as text"); + assert_eq!(OsGrantKeys { connect: flaky, ..OsGrantKeys::default() }.key().unwrap(), Some(key), "and read back"); + + let folder = Path::new("/plug-ins"); + keys.set_generation(folder, 0x1_0000_0005).unwrap(); + let account = format!("generation-v1-{}", to_hex(&::digest(folder.as_os_str().as_encoded_bytes()))); + assert_eq!(kept(&account), b"0000000100000005", "the generation is kept as text"); + assert_eq!(keys.generation(folder).unwrap(), Some(0x1_0000_0005)); + + MOCK.build(OsGrantKeys::SERVICE, &account, None).unwrap().set_secret(&5u64.to_be_bytes()).unwrap(); + assert!(keys.generation(folder).is_err(), "a generation kept as raw bytes is an error"); + MOCK.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret(&[0xa7; KEY_LEN]).unwrap(); + assert_eq!(keys.key().unwrap(), None, "a key kept as raw bytes is none, also after a key was read"); + MOCK.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("b8".repeat(KEY_LEN).as_bytes()).unwrap(); + assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xb8; KEY_LEN])), "a key replaced in the key store is the one used"); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cd3ff27d5d..c87b51fddd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -32,6 +32,7 @@ mod clipflavours; mod clippaint; mod cmdsplit; mod cmykflatten; +mod colorcontrast; mod colorguide; mod colorguidelib; mod colorize; @@ -176,11 +177,13 @@ mod scalestrokes; mod script_console; mod script_dialogs; mod script_dollar; +mod script_dom; mod script_engines; mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_tags; mod scripts; mod segment_nudge; mod select_effects; diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 44b49f148d..b967e6e3ed 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -270,6 +270,39 @@ fn brushed_strokes_profiled_reads_the_strokes_stroke_set_edits() { assert_eq!(s.brushed_strokes_profiled(), None, "an object without a stroke row takes a plain stroke"); } +/// `edited_strokes_profiled` reads the same strokes, with or without a brush: one profiled member +/// counts, and a group's own uniform stroke, which `stroke.set` edits instead, hides its members' +/// profiles. With an object without a stroke row among the targets the answer is false, since a +/// profile from `stroke.set` would give that object a plain stroke. Type without an Appearance row +/// is left out. +#[test] +fn edited_strokes_profiled_reads_the_strokes_stroke_set_edits() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0)); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert!(!s.edited_strokes_profiled(), "neither has a profile"); + run(&mut s, "stroke.set", json!({"ids": [b.0], "profile": "lens"})); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert!(s.edited_strokes_profiled(), "the second one has a profile"); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert!(s.edited_strokes_profiled(), "a group without its own stroke: its members'"); + run(&mut s, "appearance.addStroke", json!({"ids": [g.0]})); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert!(!s.edited_strokes_profiled(), "the group's own uniform stroke"); + let c = rect(&mut s, 400.0); + run(&mut s, "appearance.removeItem", json!({"ids": [c.0], "index": 1})); + run(&mut s, "select.set", json!({"ids": [b.0]})); + assert!(s.edited_strokes_profiled(), "the profiled member alone"); + run(&mut s, "select.set", json!({"ids": [b.0, c.0]})); + assert!(!s.edited_strokes_profiled(), "an object without a stroke row"); + let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Hi"}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [t.0, b.0]})); + assert!(s.edited_strokes_profiled(), "type is left out"); + run(&mut s, "select.set", json!({"ids": []})); + assert!(!s.edited_strokes_profiled(), "nothing selected"); +} + /// A compound shape's own stroke is the one `stroke.set` edits: brushed members do not count. #[test] fn brushed_strokes_profiled_reads_a_compound_shapes_own_stroke() { diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 427def6754..7ac6b8c4e2 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1357,10 +1357,7 @@ fn brush_freehand_refuses_unknown_keys() { let spec = crate::cmd::find_command("brush.freehand").unwrap(); let mut keys = crate::cmd::params::accepted_keys(spec.params).expect("the description names every key"); keys.sort_unstable(); - assert_eq!( - keys, - ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "leaveSelection", "points", "redraw", "style"] - ); + assert_eq!(keys, ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "points", "preview", "redraw", "style"]); let mut s = session(); let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); select(&mut s, &[a]); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 22560e5568..320d6ba70f 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -1899,6 +1899,303 @@ fn shape_builder_arrow_keys_pass_swatches_of_the_same_color() { assert_eq!(s.paint.fill, after, "the swatch after Twin B"); } +/// While the Shape Builder is active, with either Pick Color From, a fill chosen without `ids`, +/// `id` or `item` (a swatch, a color, Swap, Default) changes only the current fill: the selected +/// paths keep their fills, no undo step is recorded and the Fill proxy shows the chosen fill. A +/// stroke chosen then still paints the selection, since a merge takes no stroke from it. +#[test] +fn shape_builder_fill_choice_leaves_the_selection_unpainted() { + let fills = |s: &Session, ids: [NodeId; 2]| ids.map(|id| node(s, id).appearance.fill_paint()); + for mode in ["artwork", "swatches"] { + let mut s = session(); + let (a, b) = two(&mut s); + s.execute("swatch.new", &json!({"name": "Leaf", "color": "#00ff00"})).unwrap(); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": mode}})).unwrap(); + let before = fills(&s, [a, b]); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("paint.setFill", &json!({"swatch": "Leaf"})).unwrap(); + assert_eq!(r["objects"], 0, "{mode}"); + let leaf = s.paint.fill.clone(); + assert_eq!(leaf.color(), Some(Color::from_hex("#00ff00").unwrap()), "{mode}"); + for cmd in ["paint.swap", "paint.swap", "paint.default"] { + s.execute(cmd, &json!({})).unwrap(); + } + s.execute("paint.setFill", &json!({"swatch": "Leaf"})).unwrap(); + assert_eq!(fills(&s, [a, b]), before, "{mode}: the selected paths keep their fills"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{mode}: no undo step"); + assert_eq!(s.proxy_paints().0, leaf, "{mode}: the Fill proxy shows the chosen fill"); + // A stroke goes to the selection, and the Stroke proxy shows the selection's. + let r = s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + assert!(r["objects"].as_u64().unwrap() > 0, "{mode}: {r}"); + let blue = Paint::solid(Color::from_hex("#0000ff").unwrap()); + assert_eq!(node(&s, a).appearance.stroke_paint(), blue, "{mode}"); + s.execute("stroke.set", &json!({"weight": 7})).unwrap(); + assert_eq!(node(&s, b).appearance.stroke_at(None).map(|l| l.width), Some(7.0), "{mode}: the selection takes the weight"); + assert_eq!(fills(&s, [a, b]), before, "{mode}"); + } +} + +/// While the Shape Builder is active, Swap Fill and Stroke gives the current fill the stroke the +/// Stroke proxy shows (the selection's), not a stroke for new art that no proxy shows, and the +/// selected path keeps its fill and stroke. With mixed strokes shown, the fill takes the stroke +/// for new art. +#[test] +fn shape_builder_swap_gives_the_fill_the_shown_stroke() { + let mut s = session(); + let (a, b) = two(&mut s); + s.execute("appearance.setNewArtBasic", &json!({"on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#00ff00"})).unwrap(); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + s.paint.stroke = Paint::solid(Color::from_hex("#0000ff").unwrap()); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + assert_eq!(s.proxy_paints().1, green, "the Stroke proxy shows the selection's stroke"); + // No stroke for new art: the old fill becomes a 1 pt stroke for new art, as without the tool. + (s.paint.stroke, s.paint.stroke_width) = (Paint::None, 0.0); + let before = node(&s, a).appearance; + s.execute("paint.swap", &json!({})).unwrap(); + assert_eq!(s.paint.fill, green, "the current fill takes the stroke the proxy showed"); + assert_eq!(s.paint.stroke_width, 1.0, "the old fill is a stroke that draws"); + assert_eq!(node(&s, a).appearance, before, "the selected path keeps its fill and stroke"); + // The Stroke proxy shows mixed strokes: the current fill takes the stroke for new art. + s.execute("paint.setStroke", &json!({"ids": [b.0], "color": "#ff00ff"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + assert!(s.proxy_mixed().1, "the selection's strokes differ"); + let blue = Paint::solid(Color::from_hex("#0000ff").unwrap()); + s.paint.stroke = blue.clone(); + s.execute("paint.swap", &json!({})).unwrap(); + assert_eq!(s.paint.fill, blue, "no stroke of the selection was shown"); + // With nothing selected, the stroke for new art (a freeform gradient drawn as lines) moves to + // the fill as it is. + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("paint.editGradient", &json!({"stroke": true, "kind": "freeform", "mode": "lines"})).unwrap(); + let stroke = s.paint.stroke.clone(); + assert!(matches!(&stroke, Paint::Gradient(g) if g.freeform.is_some()), "{stroke:?}"); + s.execute("paint.swap", &json!({})).unwrap(); + assert_eq!(s.paint.fill, stroke, "the stroke for new art, unchanged"); +} + +/// While the Shape Builder is active, the fill chosen for it stays the current fill when the +/// selection changes, with New Art Has Basic Appearance on or off (off, new art still takes the +/// rest of the new selection's appearance), and the freeform point commands refuse the fill's +/// gradient, which lies on no object, instead of editing the selection's. +#[test] +fn shape_builder_fill_stays_across_selections() { + for basic in [false, true] { + let mut s = session(); + let (a, b) = two(&mut s); + s.execute("appearance.setNewArtBasic", &json!({"on": basic})).unwrap(); + // B's own fill is a freeform gradient, whose points the commands could edit. + s.execute("paint.editGradient", &json!({"ids": [b.0], "stroke": false, "kind": "freeform"})).unwrap(); + // B is linked to a graphic style. + s.execute("graphicStyle.new", &json!({"id": b.0, "name": "Bee"})).unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Bee", "ids": [b.0]})).unwrap(); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + s.execute("paint.editGradient", &json!({"stroke": false, "kind": "freeform", "mode": "lines"})).unwrap(); + // The tool's freeform gradient has no points yet: its stops take the colors given. + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + s.execute("paint.editGradient", &json!({"stroke": false, "stops": stops})).unwrap(); + let Paint::Gradient(g) = &s.paint.fill else { panic!("the tool's fill is not a gradient") }; + assert_eq!(g.gradient.stops[0].color, Color::from_hex("#ff0000").unwrap(), "{basic}: the stop color given"); + let chosen = s.paint.fill.clone(); + assert!(matches!(&chosen, Paint::Gradient(_)), "{basic}"); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + assert_eq!(s.paint.fill, chosen, "basic {basic}: the chosen fill stays"); + assert_eq!(s.paint.inherited, !basic, "basic {basic}: whether new art takes the selection's appearance"); + // New art with the chosen fill does not look like B's style, so it is not linked to it. + assert_eq!(s.paint.style, None, "basic {basic}"); + let before = [a, b].map(|id| node(&s, id)); + let e = s.execute("paint.freeform.setPoint", &json!({"index": 0, "color": "#ff0000"})).unwrap_err().to_string(); + assert!(e.contains("Shape Builder"), "{basic}: {e}"); + assert_eq!([a, b].map(|id| node(&s, id)), before, "basic {basic}: the selection keeps its paint"); + } +} + +/// While the Shape Builder is active with the Fill proxy in front, a gradient preset or edit that +/// names no kind goes to the tool's fill, also while a stroke row of the selection is the +/// Appearance panel's active row; with the Stroke proxy in front, an active fill row still keeps +/// the edit off the selection. +#[test] +fn shape_builder_gradient_edits_follow_the_proxy_in_front() { + let mut s = session(); + let (a, _) = two(&mut s); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let row = |s: &Session, fill: bool| node(s, a).appearance.items.iter().position(|it| it.is_fill() == fill).unwrap(); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + let before = node(&s, a); + s.execute("appearance.setActiveItem", &json!({"index": row(&s, false)})).unwrap(); + s.fill_active = true; + s.execute("gradient.presets.apply", &json!({"name": "vignette"})).unwrap(); + assert!(matches!(s.paint.fill, Paint::Gradient(_)), "the tool's fill takes the preset"); + assert_eq!(node(&s, a).appearance, before.appearance, "the selection keeps its paint"); + s.execute("appearance.setActiveItem", &json!({"index": row(&s, true)})).unwrap(); + s.fill_active = false; + for (kind, ids) in [("diamond", None), ("linear", Some(Value::Null))] { + let tool_fill = s.paint.fill.clone(); + let mut p = json!({ "kind": kind }); + if let Some(ids) = ids { + p["ids"] = ids; + } + s.execute("paint.editGradient", &p).unwrap(); + assert_ne!(s.paint.fill, tool_fill, "{p}: the tool's fill takes the edit"); + assert_eq!(node(&s, a).appearance, before.appearance, "{p}: the selection keeps its paint"); + } + // A freeform stroke on the selection, its row active and the Fill proxy in front: a point + // edit without `stroke` is for the tool's fill, which has no points, and changes nothing. + s.execute("paint.editGradient", &json!({"ids": [a.0], "stroke": true, "kind": "freeform"})).unwrap(); + let stroked = node(&s, a); + s.execute("appearance.setActiveItem", &json!({"index": row(&s, false)})).unwrap(); + s.fill_active = true; + assert!(s.execute("paint.freeform.setPoint", &json!({"index": 0, "color": "#ff0000"})).is_err()); + assert_eq!(node(&s, a).appearance, stroked.appearance, "the selection's stroke keeps its points"); + // A `stroke` that is not a switch is reported as such. + let e = s.execute("paint.freeform.setPoint", &json!({"index": 0, "color": "#ff0000", "stroke": "true"})).unwrap_err(); + assert!(e.to_string().contains("stroke"), "{e}"); +} + +/// A fill previewed while the Shape Builder is active (a Color panel drag) is the tool's fill, +/// which a cancel puts back, also after another tool was chosen during the drag. +#[test] +fn shape_builder_fill_preview_is_put_back_by_a_cancel() { + let mut s = session(); + two(&mut s); + s.execute("appearance.setNewArtBasic", &json!({"on": true})).unwrap(); + s.select_tool("shapeBuilder", ViewInfo::default()).unwrap(); + let before = s.paint.fill.clone(); + s.begin_interaction("Color").unwrap(); + s.preview("paint.setFill", &json!({"color": "#ff00ff"})).unwrap(); + assert_eq!(s.paint.fill.color(), Some(Color::from_hex("#ff00ff").unwrap()), "the preview sets the tool's fill"); + s.select_tool("selection", ViewInfo::default()).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, before, "the cancel puts the fill back"); +} + +/// With Pick Color From Color Swatches, a merge fills with the fill chosen while the Shape Builder +/// is active, and the Gradient panel's eyedropper samples into a stop of that fill's gradient. +#[test] +fn shape_builder_merge_fills_with_the_chosen_fill() { + let mut s = session(); + let (a, b) = two(&mut s); + s.execute("swatch.new", &json!({"name": "Leaf", "color": "#00ff00"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("shapeBuilder", v).unwrap(); + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"pickColorFrom": "swatches"}})).unwrap(); + let (a0, b0) = (node(&s, a), node(&s, b)); + s.execute("paint.setFill", &json!({"swatch": "Leaf"})).unwrap(); + let leaf = s.paint.fill.clone(); + assert_eq!((node(&s, a), node(&s, b)), (a0, b0), "the selected paths keep their paint"); + // The tool's merge fills with the chosen swatch. + s.pointer(&PointerEvent::new(PointerKind::Down, 25.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 75.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 75.0, 50.0), v).unwrap(); + assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge"); + let d = &s.doc().unwrap().doc; + let fills: Vec = d.children(d.default_layer()).into_iter().flatten().map(|n| n.appearance.fill_paint()).collect(); + assert!(fills.contains(&leaf), "a merged shape filled with the swatch: {fills:?}"); + // A gradient and the Gradient panel's eyedropper sample into a stop of the gradient the tool + // paints with, and the art keeps its paint. + let art = |s: &Session| -> Vec { + let d = &s.doc().unwrap().doc; + d.children(d.default_layer()).into_iter().flatten().map(|n| Node::clone(n)).collect() + }; + let before = art(&s); + s.execute("paint.editGradient", &json!({"stroke": false, "kind": "linear"})).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + let Paint::Gradient(g) = &s.paint.fill else { panic!("the tool's fill is not a gradient") }; + assert_eq!(Paint::solid(g.gradient.stops[1].color), leaf, "the sampled stop"); + assert_eq!(art(&s), before, "the art keeps its paint"); + // Armed again, a pick whose stop went away when the Stroke proxy came to the front (the + // selection's stroke), also after the stop was cleared first, ends without copying an + // appearance onto the art. + for clear in [false, true] { + s.select_tool("shapeBuilder", v).unwrap(); + s.fill_active = true; + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + if clear { + s.execute("gradient.selectStop", &json!({"index": null})).unwrap(); + } + s.fill_active = false; + assert_eq!(s.selected_stop(), None); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(art(&s), before, "the art keeps its paint (cleared first: {clear})"); + } + // With the Stroke proxy in front, a stop of the selection's stroke gradient is the selection's, + // and the pick samples into it. + s.execute("paint.editGradient", &json!({"stroke": true, "kind": "linear"})).unwrap(); + assert_ne!(art(&s), before, "the selection takes the stroke gradient"); + s.execute("gradient.selectStop", &json!({"index": 0})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(s.journal.last().unwrap().0, "paint.sampleColor", "the pick samples into the selection's stop"); + // A pick armed for a stop of the tool's fill does not sample into a stop selected since on + // the selection's stroke: it ends. + s.select_tool("shapeBuilder", v).unwrap(); + s.fill_active = true; + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + s.fill_active = false; + let stops = json!([{"offset": 0, "color": "#0000ff"}, {"offset": 1, "color": "#000000"}]); + s.execute("paint.editGradient", &json!({"stroke": true, "stops": stops})).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 0})).unwrap(); + let armed = art(&s); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(art(&s), armed, "the selection's stroke keeps its stops"); + s.execute("gradient.selectStop", &json!({"index": null})).unwrap(); + // A pick armed for another tool is not that stop's: with no stop selected, its click copies + // the appearance as usual. + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("selection")); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(s.journal.last().unwrap().0, "appearance.copyFrom"); + // Choosing another tool drops the stop a pick was armed for. + s.select_tool("shapeBuilder", v).unwrap(); + s.fill_active = true; + s.execute("paint.editGradient", &json!({"stroke": false, "kind": "linear"})).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("shapeBuilder")); + assert!(s.stop_pick.is_some(), "the pick is armed for the tool's stop"); + s.select_tool("selection", v).unwrap(); + assert!(s.stop_pick.is_none(), "another tool was chosen"); + // Armed while the Eyedropper waits for a Cmd-drag it lent the Selection tool to, the pick + // still ends once the Stroke proxy comes to the front. + s.select_tool("shapeBuilder", v).unwrap(); + s.fill_active = true; + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + let lent = s.make_tool("selection"); + s.lender = Some(std::mem::replace(&mut s.tool, lent)); + s.set_tool_options(Some("eyedropper"), json!({"stop": "shapeBuilder"}).as_object().unwrap()); + s.give_back_tool(v).unwrap(); + assert_eq!(s.tool_id(), "eyedropper"); + s.fill_active = false; + let (armed, journal) = (art(&s), s.journal.len()); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 25.0, 50.0), v).unwrap(); + } + assert_eq!(art(&s), armed, "the art keeps its paint (armed during a loan)"); + let ran: Vec<&str> = s.journal.since(journal).iter().map(|j| j.0.as_str()).collect(); + assert!(!ran.contains(&"appearance.copyFrom"), "{ran:?}"); +} + /// The colors of the cursor swatch preview's chips, left to right, and which one is ringed. fn swatch_chips(s: &mut Session, v: ViewInfo) -> Vec<([u8; 4], bool)> { let mut chips: Vec<(f64, [u8; 4], bool)> = s diff --git a/crates/engine/src/tests/circle_through.rs b/crates/engine/src/tests/circle_through.rs index c9b66f9f06..fe85cb5822 100644 --- a/crates/engine/src/tests/circle_through.rs +++ b/crates/engine/src/tests/circle_through.rs @@ -123,6 +123,63 @@ fn two_points_are_the_ends_of_a_diameter() { assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); } +/// With `center`, the circle is centered there and its edge passes through the one point in +/// `points`: from the bottom-right corner (200, 200) of a 100 pt square through its top-left +/// corner (100, 100), the radius is the square's diagonal, in one undo step. A point on the center +/// and a circle past the canvas are refused, and so is a `center` (null included) or `points` that +/// is not one `[x, y]` pair of finite numbers; nothing is drawn and no undo step is recorded. +#[test] +fn a_center_and_a_point_on_the_edge_give_the_circle() { + let mut s = session(); + let undo = undo_len(&s); + let out = s.execute(C, &json!({"center": [200, 200], "points": [[100, 100]]})).unwrap(); + let r = 100.0 * std::f64::consts::SQRT_2; + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(200.0), Some(200.0)), "{out}"); + assert!((out["radius"].as_f64().unwrap() - r).abs() < 1e-12, "{out}"); + let id = id_of(&out); + assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(200.0 - r, 200.0 - r, 200.0 + r, 200.0 + r))); + assert!(farthest_from_path(&s, id, &[Point::new(100.0, 100.0)]) < r * 3e-4); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert_eq!(undo_len(&s), undo + 1); + let (undo, count) = (undo_len(&s), object_count(&s)); + let e = s.execute(C, &json!({"center": [30, 30], "points": [[30, 30]]})).unwrap_err().to_string(); + assert!(e.contains("the point in `points` is on `center`"), "{e}"); + // Past the canvas, and finite coordinates whose distance overflows to infinity. + for (center, point) in [(json!([0, 0]), json!([4_100_000, 0])), (json!([-1e308, -1e308]), json!([1e308, 1e308]))] { + let e = s.execute(C, &json!({ "center": center, "points": [point] })).unwrap_err().to_string(); + assert!(e.contains("result would exceed the canvas"), "{center} {point}: {e}"); + } + for (center, points) in [ + (json!([0, 0]), json!([[10, 0], [0, 10]])), + (json!([0, 0]), json!([])), + (json!([0, 0]), Value::Null), + (json!([0, 0]), json!([[10, "0"]])), + (json!([0]), json!([[10, 0]])), + (json!("0,0"), json!([[10, 0]])), + (json!([0, 0, 1]), json!([[10, 0]])), + (Value::Null, json!([[10, 0]])), + (Value::Null, json!([[10, 0], [20, 0]])), + ] { + let e = s.execute(C, &json!({ "center": center, "points": points })).unwrap_err().to_string(); + assert!(e.contains("`center` must be an [x, y] pair of numbers, with one [x, y] pair in `points`"), "{center} {points}: {e}"); + } + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + +/// A circle so small beside its coordinates that its left and right edges round to the same +/// number (radius 10⁻¹¹ pt at x = 1,048,576, where doubles step by about 2.3 × 10⁻¹⁰) is refused, +/// from a center and on a diameter alike; nothing is drawn and no undo step is recorded. +#[test] +fn a_circle_with_no_width_at_document_precision_is_refused() { + let mut s = session(); + let (undo, count) = (undo_len(&s), object_count(&s)); + for p in [json!({"center": [1_048_576, 0], "points": [[1_048_576, 1e-11]]}), json!({"points": [[1_048_576, 0], [1_048_576, 2e-11]]})] { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains("the circle is too small to draw at these coordinates"), "{p}: {e}"); + } + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + /// Points that are not two or three pairs of finite numbers are an error, not a fallback. #[test] fn malformed_points_are_refused() { @@ -243,6 +300,28 @@ fn click(s: &mut Session, mods: Mods, x: f64, y: f64) { } } +/// The Circle tool with From Center set through `tool.setOption`: a click on the center and a +/// click on the edge draw the circle, in one undo step. `fromCenter` must be true or false, and +/// the tool has no other option; a refused value changes nothing. +#[test] +fn the_circle_tool_draws_from_its_center() { + let mut s = session(); + s.select_tool("circle", view()).unwrap(); + let e = s.set_tool_option_cmd(&json!({"key": "fromCenter", "value": "yes"})).unwrap_err(); + assert!(e.contains("`fromCenter` must be true or false"), "{e}"); + assert!(s.set_tool_option_cmd(&json!({"key": "radius", "value": 5})).is_err()); + assert_eq!(s.tool_options()["fromCenter"], json!(false)); + s.set_tool_option_cmd(&json!({"key": "fromCenter", "value": true})).unwrap(); + assert_eq!(s.tool_options()["fromCenter"], json!(true)); + let undo = undo_len(&s); + click(&mut s, Mods::default(), 200.0, 200.0); + click(&mut s, Mods::default(), 100.0, 100.0); + assert_eq!(undo_len(&s), undo + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + let r = 100.0 * std::f64::consts::SQRT_2; + assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(200.0 - r, 200.0 - r, 200.0 + r, 200.0 + r))); +} + /// With the Ellipse tool, three Shift-clicks draw the circle through the three points, in one /// undo step; Escape drops the points placed so far. #[test] diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs new file mode 100644 index 0000000000..9b0147174e --- /dev/null +++ b/crates/engine/src/tests/colorcontrast.rs @@ -0,0 +1,879 @@ +//! `color.contrast`: the WCAG 2 contrast of a color against the color behind the selection. + +use serde_json::{Value, json}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s +} + +fn ratio(r: &Value) -> f64 { + r["ratio"].as_f64().unwrap() +} + +#[test] +fn a_pair_just_under_aa_fails_it() { + let mut s = Session::new(); + let r = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78"})).unwrap(); + assert!((ratio(&r) - 4.496).abs() < 1e-3, "{r}"); + assert_eq!(r["against"], "#355f78"); + assert_eq!(r["normalText"], json!({"aa": false, "aaa": false})); + assert_eq!(r["largeText"], json!({"aa": true, "aaa": false})); + assert_eq!(r["graphics"], json!({"aa": true}), "graphics have no AAA level"); + assert_eq!(vectorcraft_color::wcag::ratio_text(ratio(&r)), "4.49:1"); +} + +#[test] +fn black_on_white_is_21_and_grays_fall_either_side_of_aa() { + let mut s = Session::new(); + let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}"); + assert_eq!(r["normalText"], json!({"aa": true, "aaa": true})); + let pass = s.execute("color.contrast", &json!({"color": "#767676", "against": "#ffffff"})).unwrap(); + assert!((ratio(&pass) - 4.542).abs() < 1e-3 && pass["normalText"]["aa"] == true, "{pass}"); + let fail = s.execute("color.contrast", &json!({"color": "#777777", "against": "#ffffff"})).unwrap(); + assert!((ratio(&fail) - 4.478).abs() < 1e-3 && fail["normalText"]["aa"] == false, "{fail}"); +} + +#[test] +fn the_background_is_the_locked_art_behind_the_selected_type() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 80})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ffff00"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("text.create", &json!({"x": 60, "y": 70, "text": "Label", "size": 24, "color": "#000000"})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert_eq!(r["against"], "#ffff00", "{r}"); + let want = vectorcraft_color::wcag::contrast_ratio([0.0; 3], [1.0, 1.0, 0.0]); + assert!((ratio(&r) - want).abs() < 1e-3, "{r}"); +} + +#[test] +fn a_translucent_fill_counts_at_the_opacity_it_is_drawn_with() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert_eq!(r["against"], "#ffffff", "the selected rectangle is hidden: the artboard's white shows"); + let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]); + assert!((ratio(&r) - gray).abs() < 1e-3, "{r}"); + // A given opacity replaces it, and a given color is drawn fully opaque. + let full = s.execute("color.contrast", &json!({"opacity": 100})).unwrap(); + assert!((ratio(&full) - 21.0).abs() < 1e-3, "{full}"); + let given = s.execute("color.contrast", &json!({"color": "#000000"})).unwrap(); + assert!((ratio(&given) - 21.0).abs() < 1e-3, "{given}"); +} + +/// While the Live Paint Bucket is the active tool, the proxy shows the color it paints with, so the +/// selected objects' opacities and blend modes do not apply, and objects drawn differently are no +/// error. +#[test] +fn the_live_paint_bucket_color_is_measured_without_the_selections_drawing() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50, "blend": "multiply"})).unwrap(); + let selection = ratio(&s.execute("color.contrast", &json!({})).unwrap()); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + let bucket = s.execute("color.contrast", &json!({})).unwrap(); + assert!(ratio(&bucket) > selection, "the bucket's black is drawn opaque: {bucket} against {selection}"); + assert!((ratio(&bucket) - 21.0).abs() < 1e-3, "{bucket}"); + // A second selected object drawn at another opacity does not make the answer ambiguous. + s.select_tool("selection", ViewInfo::default()).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + let both = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&both) - ratio(&bucket)).abs() < 1e-3, "{both}"); +} + +#[test] +fn a_translucent_group_counts_for_the_art_inside_it() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]); + assert!((ratio(&r) - gray).abs() < 1e-3, "the group draws the black at 50 %: {r}"); +} + +#[test] +fn a_blend_mode_counts_as_it_draws_over_the_background() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert_eq!(r["against"], "#ff0000", "{r}"); + assert!((ratio(&r) - 1.0).abs() < 1e-3, "white multiplied over red draws red: {r}"); + // A group's blend mode counts for the art inside it, and a given color draws in Normal mode. + s.execute("transparency.set", &json!({"blend": "normal"})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&r) - 1.0).abs() < 1e-3, "{r}"); + let given = s.execute("color.contrast", &json!({"color": "#ffffff"})).unwrap(); + let want = vectorcraft_color::wcag::contrast_ratio([1.0; 3], [1.0, 0.0, 0.0]); + assert!((ratio(&given) - want).abs() < 1e-3, "{given}"); +} + +/// A selected blue square at (50, 50) over locked red art, with its fill row's blend mode set to +/// `row`. +fn blended_over_red(row: &str) -> Session { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#4080c0"})).unwrap(); + s.execute("transparency.set", &json!({"item": fill_index(&s), "blend": row})).unwrap(); + s +} + +/// The index of the selected object's fill row. +fn fill_index(s: &Session) -> usize { + let st = s.active().unwrap(); + let n = st.doc.node(st.selection.objects[0]).unwrap(); + n.appearance.items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap() +} + +/// The contrast against red of the color the canvas draws at the square's center. +fn drawn_ratio(s: &Session) -> f64 { + let doc = &s.doc().unwrap().doc; + let img = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(99.0, 99.0, 101.0, 101.0), 1.0, true); + let p = img.pixel(1, 1); + vectorcraft_color::wcag::contrast_ratio([p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0), [1.0, 0.0, 0.0]) +} + +#[test] +fn nested_blend_modes_count_as_the_canvas_draws_them() { + let mut s = blended_over_red("multiply"); + s.execute("transparency.set", &json!({"item": null, "blend": "screen"})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert_eq!(r["against"], "#ff0000", "{r}"); + let drawn = drawn_ratio(&s); + assert!((ratio(&r) - drawn).abs() < 0.02, "the fill multiplies, then the object screens: {r} against {drawn}"); + // A translucent row and object: the canvas takes the backdrop back out of a group that blends + // through before it blends the group, so the opacities multiply over the nested modes. + s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap(); + s.execute("transparency.set", &json!({"item": null, "blend": "overlay", "opacity": 70})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let drawn = drawn_ratio(&s); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); + s.execute("transparency.set", &json!({"item": null, "opacity": 100})).unwrap(); + // Grouped, the group's mode blends the result again. + s.execute("transparency.set", &json!({"item": null, "blend": "normal"})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("transparency.set", &json!({"blend": "difference"})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let drawn = drawn_ratio(&s); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// In a 50 % group, a black square over a white one draws black over the black outside: the group's +/// opacity applies to the white behind the square once, not again over it. +#[test] +fn a_translucent_group_draws_the_art_behind_the_object_once() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let white = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.group", &json!({"ids": [white.0, black.0]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.active_mut().unwrap().selection.objects = vec![black]; + let r = s.execute("color.contrast", &json!({})).unwrap(); + let doc = &s.doc().unwrap().doc; + let img = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(99.0, 99.0, 101.0, 101.0), 1.0, true); + let p = img.pixel(1, 1); + let behind = vectorcraft_color::Color::from_hex(r["against"].as_str().unwrap()).unwrap().to_rgb_uncalibrated(); + let drawn = vectorcraft_color::wcag::contrast_ratio([p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0), behind); + assert!(p[0] < 3, "the canvas draws black: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// The pixel the canvas draws at (100, 100), and its contrast against the answer's `against`. +fn canvas_ratio(s: &Session, r: &Value) -> ([u8; 4], f64) { + let doc = &s.doc().unwrap().doc; + let img = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(99.0, 99.0, 101.0, 101.0), 1.0, true); + let p = img.pixel(1, 1); + let behind = vectorcraft_color::Color::from_hex(r["against"].as_str().unwrap()).unwrap().to_rgb_uncalibrated(); + (p, vectorcraft_color::wcag::contrast_ratio([p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0), behind)) +} + +/// A selected white Multiply square over a white one in a 50 % group over black: the square +/// multiplies with the white inside the group, and the group's opacity applies once. +#[test] +fn a_blend_mode_in_a_translucent_group_blends_with_the_art_inside_it() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let back = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + let square = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap(); + s.execute("object.group", &json!({"ids": [back.0, square.0]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.active_mut().unwrap().selection.objects = vec![square]; + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!((i32::from(p[0]) - 128).abs() < 3, "the canvas draws half gray: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// In a dynamic symbol instance whose art is a 50 % group of a black square over a white one, over +/// black, the picked black square draws over the black outside the group, not over the group's +/// white. +#[test] +fn a_picked_symbol_object_in_a_translucent_group_of_the_art_draws_over_what_is_outside_it() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let white = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + let group = id(s.execute("object.group", &json!({"ids": [white.0, black.0]})).unwrap()); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [group.0], "type": "dynamic"})).unwrap()); + let doc = &s.doc().unwrap().doc; + let art = &doc.symbols.iter().find(|x| x.name == "Pair").unwrap().art; + let path = if vectorcraft_doc::symbol_overrides::part(art, &[0, 1]).is_some() { vec![0, 1] } else { vec![1] }; + let st = s.active_mut().unwrap(); + st.selection.objects = vec![inst]; + st.selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path }); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!(p[0] < 3, "the canvas draws black: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// As above with the group's 50 % set by the instance instead of the symbol, and the picked black +/// square itself at 50 %: the square draws over the group's white, read with the instance's +/// opacity for the group taken out, then the group's 50 % applies once over the black outside. +#[test] +fn an_instances_opacity_for_a_group_of_its_art_applies_once() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let white = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let group = id(s.execute("object.group", &json!({"ids": [white.0, black.0]})).unwrap()); + let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [group.0], "type": "dynamic"})).unwrap()); + let doc = &s.doc().unwrap().doc; + let art = &doc.symbols.iter().find(|x| x.name == "Pair").unwrap().art; + let path = if vectorcraft_doc::symbol_overrides::part(art, &[0, 1]).is_some() { vec![0, 1] } else { vec![1] }; + let st = s.active_mut().unwrap(); + let n = std::sync::Arc::make_mut(&mut st.doc).node_mut(inst).unwrap(); + let over = vectorcraft_doc::SymbolOverride { path: path[..path.len() - 1].to_vec(), opacity: Some(0.5), ..Default::default() }; + n.extras_mut().symbol_overrides = vec![over]; + st.selection.objects = vec![inst]; + st.selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path }); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!((i32::from(p[0]) - 64).abs() < 3, "the canvas draws a quarter gray: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// A selected 50 % black square in a 50 % group, over a 50 % white square, all in a Difference group +/// over gray: the inner group's opacity applies to the black square only, and the white beside the +/// inner group counts once in the alpha the Difference group takes the gray back out by. +#[test] +fn a_groups_opacity_leaves_out_the_art_beside_it_in_a_blending_group() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#8c8c8c"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let white = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let inner = id(s.execute("object.group", &json!({"ids": [black.0]})).unwrap()); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.execute("object.group", &json!({"ids": [white.0, inner.0]})).unwrap(); + s.execute("transparency.set", &json!({"blend": "difference"})).unwrap(); + s.active_mut().unwrap().selection.objects = vec![black]; + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + // The canvas pixel is rounded to 8 bits, which moves this dark gray's ratio by up to 0.04; with + // the white counted twice the answer is 3.15. + assert!((ratio(&r) - drawn).abs() < 0.05, "{r} against {drawn} ({p:?})"); +} + +/// An object that isolates its blending, with a white Multiply fill over a blue one, over red: the +/// white multiplies with the blue row below it. +#[test] +fn a_row_in_an_isolating_object_blends_with_the_rows_below_it() { + let mut s = blended_over_red("normal"); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.node(st.selection.objects[0]).unwrap().appearance.items; + let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "blend": "multiply"})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!(p[0] < 3 && p[2] > 252, "the canvas draws blue: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// An object that isolates its blending, in a Screen group over black: a 50 % white fill over an +/// opaque white one composites to opaque white inside the object, so the group screens opaque +/// white. With the lower fill removed, the object holds the white at 50 %. +#[test] +fn an_isolating_object_in_a_blending_group_carries_the_alpha_of_its_composite() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let square = id(s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.node(square).unwrap().appearance.items; + let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + let lower = items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("transparency.set", &json!({"blend": "screen"})).unwrap(); + s.active_mut().unwrap().selection.objects = vec![square]; + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!(p[0] > 252 && p[1] > 252 && p[2] > 252, "the canvas draws white: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); + assert_eq!(r["normalText"], json!({"aa": true, "aaa": true}), "{r}"); + s.execute("appearance.removeItem", &json!({"index": lower})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!((i32::from(p[0]) - 128).abs() < 3, "the canvas draws half gray: {p:?}"); + // The canvas pixel is rounded to 8 bits, which moves a ratio near half gray by up to 0.04. + assert!((ratio(&r) - drawn).abs() < 0.05, "{r} against {drawn}"); +} + +/// A 50 % white fill over an opaque blue one draws over the blue, not over the red art behind it. +#[test] +fn a_translucent_row_draws_over_the_rows_below_it() { + let mut s = blended_over_red("normal"); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.node(st.selection.objects[0]).unwrap().appearance.items; + let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!((i32::from(p[0]) - 128).abs() < 3 && p[2] > 252, "the canvas draws the white at 50 % over the blue: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// A path's Normal fill row and type's character paint draw one black alike. +#[test] +fn a_normal_fill_row_and_type_of_one_color_leave_one_answer() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + let t = id(s.execute("text.create", &json!({"x": 80, "y": 60, "text": "Label", "size": 24, "color": "#000000"})).unwrap()); + s.execute("select.set", &json!({"ids": [a, t]})).unwrap(); + let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}"); +} + +/// In a group that isolates its blending, a selected white Multiply square blends with the blue +/// art the group holds, and with nothing outside it. +#[test] +fn a_blend_mode_in_an_isolating_group_blends_with_the_art_inside_it_only() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let back = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + let square = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap(); + s.execute("object.group", &json!({"ids": [back.0, square.0]})).unwrap(); + s.execute("transparency.set", &json!({"isolate": true})).unwrap(); + s.active_mut().unwrap().selection.objects = vec![square]; + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!(p[0] < 3 && p[2] > 252, "the canvas draws blue: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); + // With the blue art out of the group, the square blends with nothing and draws white over red. + s.execute("select.set", &json!({"ids": [back.0]})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + s.active_mut().unwrap().selection.objects = vec![square]; + let r = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &r); + assert!(p[1] > 252, "the canvas draws white: {p:?}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +#[test] +fn template_layers_and_guides_are_left_out_of_the_background() { + let mut s = session(); + let first = s.doc().unwrap().doc.layers[0].id; + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("layer.setProps", &json!({"id": first.0, "template": true})).unwrap(); + s.execute("layer.new", &json!({"top": true})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert_eq!(r["against"], "#ffffff", "the artboard, without the template's red or the guide: {r}"); +} + +#[test] +fn objects_that_draw_one_color_differently_have_no_one_answer() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()); + let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}"); + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string(); + assert!(e.contains("the selected objects' colors differ: give `opacity` or `color`"), "{e}"); + s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap(); + // A given opacity takes the place of the objects' own. + let r = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}"); + // A blend mode that differs is not one a given opacity replaces. + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 100, "blend": "multiply"})).unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string(); + assert!(e.contains("the selected objects' colors differ: give `color`"), "{e}"); +} + +/// A 50 % white row over a blue row in an opaque object draws over the blue; an opaque white row in +/// a 50 % object draws over what is behind it, though both draw the white at 50 %. +#[test] +fn a_row_and_an_object_of_one_total_opacity_draw_differently_over_the_rows_below() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.node(st.selection.objects[0]).unwrap().appearance.items; + let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("the selected objects' colors differ: give `opacity` or `color`"), "{e}"); + // A given background stands for the rows below, so both draw the white at 50 % over it. + let r = s.execute("color.contrast", &json!({"against": "#000000"})).unwrap(); + let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]); + assert!((ratio(&r) - gray).abs() < 1e-3, "{r}"); +} + +/// Two squares with the same 50 % white top fill, one over an opaque black fill and one over an +/// opaque white one, draw the white over different rows: no one answer. Over the same lower fill +/// they leave one answer, also when one of them has a lower row with no paint. +#[test] +fn translucent_rows_over_different_lower_rows_have_no_one_answer() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let square = |s: &mut Session, x: i32, lower: &str| { + let n = id(s.execute("shape.rectangle", &json!({"x": x, "y": 50, "width": 50, "height": 100})).unwrap()); + s.execute("paint.setFill", &json!({"color": lower})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items; + let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + n + }; + let a = square(&mut s, 50, "#000000"); + let b = square(&mut s, 100, "#ffffff"); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("the selected objects' colors differ"), "{e}"); + let c = square(&mut s, 150, "#000000"); + s.execute("select.set", &json!({"ids": [a, c]})).unwrap(); + s.execute("color.contrast", &json!({})).unwrap(); + // A row with no paint draws nothing, so it does not count among the rows below. + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.node(vectorcraft_doc::NodeId(c)).unwrap().appearance.items; + let fills: Vec = items.iter().enumerate().filter(|(_, i)| i.is_fill()).map(|(k, _)| k).collect(); + let (middle, top) = (fills[fills.len() - 2], fills[fills.len() - 1]); + s.execute("appearance.setItem", &json!({"ids": [c], "index": top, "color": "#ffffff", "opacity": 50})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [c], "index": middle, "none": true})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + s.execute("select.set", &json!({"ids": [a, c]})).unwrap(); + s.execute("color.contrast", &json!({})).unwrap(); +} + +#[test] +fn a_selected_group_whose_objects_draw_one_color_differently_has_no_one_answer() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()); + let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap(); + let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap()); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}"); + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string(); + assert!(e.contains("the selected objects' colors differ: give `opacity` or `color`"), "{e}"); +} + +#[test] +fn a_hidden_object_in_a_selected_group_leaves_one_answer() { + let id = |v: Value| v["id"].as_u64().unwrap(); + // The first and then the second object hidden: the hidden one is neither compared nor measured. + for first in [false, true] { + let mut s = session(); + let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()); + let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap(); + let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap()); + s.execute("select.set", &json!({"ids": [if first { a } else { b }]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-6, "first hidden {first}: {r}"); + } +} + +#[test] +fn a_given_color_is_drawn_at_a_given_opacity() { + let mut s = Session::new(); + let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff", "opacity": 50})).unwrap(); + let opaque = s.execute("color.contrast", &json!({"color": "#808080", "against": "#ffffff"})).unwrap(); + assert!((ratio(&r) - ratio(&opaque)).abs() < 0.05, "{r} {opaque}"); + assert!(ratio(&r) < 5.0, "{r}"); +} + +#[test] +fn an_opaque_group_around_one_of_the_objects_leaves_one_answer() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()); + let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap(); + s.execute("object.group", &json!({"ids": [b]})).unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}"); +} + +#[test] +fn objects_in_two_groups_of_one_opacity_answer_against_a_given_color() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()); + let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap(); + for o in [a, b] { + let g = id(s.execute("object.group", &json!({"ids": [o]})).unwrap()); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + } + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap(); + // Sampled, each group is hidden in turn to read what is outside it, so the two differ. + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("the selected objects' colors differ: give `opacity` or `color`"), "{e}"); +} + +#[test] +fn a_hidden_fill_row_has_no_color_to_measure() { + let mut s = blended_over_red("normal"); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("appearance.setItem", &json!({"index": fill_index(&s), "visible": false})).unwrap(); + let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string(); + assert!(e.contains("the active fill or stroke is hidden: give `color`"), "{e}"); + let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap(); + assert!((ratio(&given) - 21.0).abs() < 1e-6, "{given}"); +} + +/// An opacity mask on the object, or on a group around it, sets how much of the color shows at each +/// point, so the color has no one opacity to measure; a disabled mask draws nothing. +#[test] +fn a_color_drawn_through_an_opacity_mask_has_no_one_answer() { + let mut s = session(); + let rect = |s: &mut Session, color: &str| { + let id = s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"color": color, "ids": [id]})).unwrap(); + id + }; + let masked = |s: &mut Session, owner: u64, color: &str| { + let m = rect(s, color); + s.execute("select.set", &json!({"ids": [owner, m]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [owner]})).unwrap(); + }; + let black = rect(&mut s, "#000000"); + masked(&mut s, black, "#000000"); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("drawn through an opacity mask: give `color`"), "{e}"); + let e = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap_err().to_string(); + assert!(e.contains("drawn through an opacity mask"), "{e}"); + let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap(); + assert!((ratio(&given) - 21.0).abs() < 1e-6, "{given}"); + s.execute("transparency.disableOpacityMask", &json!({})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-3, "a disabled mask leaves the black as it is: {r}"); + // A group's mask counts for the objects inside it. + let mut s = session(); + let inner = rect(&mut s, "#000000"); + let group = s.execute("object.group", &json!({"ids": [inner]})).unwrap()["id"].as_u64().unwrap(); + masked(&mut s, group, "#000000"); + s.execute("select.set", &json!({"ids": [inner]})).unwrap(); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("drawn through an opacity mask"), "{e}"); +} + +/// A background sampled across an edge averages two colors; the answer's `against` is exactly the +/// background the ratio used, so giving it back answers the same ratio. +#[test] +fn the_background_written_back_answers_the_same_ratio() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80.3, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#2050a0"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#808080"})).unwrap(); + let below = s.execute("color.contrast", &json!({})).unwrap(); + let hex = below["against"].as_str().unwrap(); + assert!(hex != "#ffffff" && hex != "#2050a0", "the sample straddles the edge: {below}"); + let given = s.execute("color.contrast", &json!({"against": hex})).unwrap(); + assert!((ratio(&below) - ratio(&given)).abs() < 1e-6, "{below} {given}"); +} + +/// In a 50 % group, a selected black square over a red one draws over the white outside the group, +/// while a given background stands for the art below every level, so giving the answer's `against` +/// back draws the black at 50 % over it instead. +#[test] +fn a_background_given_back_stands_for_the_art_outside_a_translucent_group() { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + let red = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.group", &json!({"ids": [red.0, black.0]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + s.active_mut().unwrap().selection.objects = vec![black]; + let below = s.execute("color.contrast", &json!({})).unwrap(); + let (_, drawn) = canvas_ratio(&s, &below); + assert!((ratio(&below) - drawn).abs() < 0.02, "{below} against {drawn}"); + let hex = below["against"].as_str().unwrap(); + let behind = vectorcraft_color::Color::from_hex(hex).unwrap().to_rgb_uncalibrated(); + let given = s.execute("color.contrast", &json!({"against": hex})).unwrap(); + let want = vectorcraft_color::wcag::contrast_ratio(vectorcraft_color::wcag::over([0.0; 3], 0.5, behind), behind); + assert!((ratio(&given) - want).abs() < 1e-3, "{given}"); + assert!((ratio(&below) - ratio(&given)).abs() > 0.1, "{below} {given}"); +} + +#[test] +fn an_object_that_isolates_its_blending_draws_its_fill_as_it_is() { + let mut s = blended_over_red("multiply"); + s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let drawn = drawn_ratio(&s); + let own = vectorcraft_color::wcag::contrast_ratio(vectorcraft_color::Color::from_hex("#4080c0").unwrap().to_rgb_uncalibrated(), [1.0, 0.0, 0.0]); + assert!((drawn - own).abs() < 0.02, "the canvas draws the fill unblended: {drawn} against {own}"); + assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}"); +} + +/// A dynamic symbol instance of a white square in front of a red one, at 50 % opacity, with its +/// white square picked. +fn picked_symbol_part() -> Session { + let mut s = session(); + let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + let back = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let front = id(s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [back.0, front.0], "type": "dynamic"})).unwrap()); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let st = s.active_mut().unwrap(); + st.selection.objects = vec![inst]; + st.selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] }); + s +} + +#[test] +fn a_picked_symbol_object_is_measured_against_the_rest_of_its_instance() { + let mut s = picked_symbol_part(); + let r = s.execute("color.contrast", &json!({"opacity": 100})).unwrap(); + // The red square at 50 % over the artboard's white (#ff7f7f or #ff8080 as the renderer rounds + // it), not the artboard alone. + let hex = r["against"].as_str().unwrap(); + let gb = vectorcraft_color::Color::from_hex(hex).unwrap().to_rgb_uncalibrated(); + assert!(hex.starts_with("#ff") && (gb[1] - 0.5).abs() < 0.01 && (gb[2] - 0.5).abs() < 0.01, "{r}"); +} + +#[test] +fn a_picked_symbol_object_is_measured_with_its_instances_stain() { + let mut s = picked_symbol_part(); + let inst = s.active().unwrap().selection.symbol_part.as_ref().unwrap().instance; + // The instance's fill stains its art half way to black. + s.active_mut().unwrap().selection.symbol_part = None; + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap(); + let n = s.doc().unwrap().doc.node(inst).unwrap().clone(); + assert!(vectorcraft_doc::symbol_overrides::stain(&n).is_some_and(|(_, a)| (a - 0.5).abs() < 1e-6)); + s.active_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] }); + let r = s.execute("color.contrast", &json!({"against": "#000000", "opacity": 100})).unwrap(); + let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]); + assert!((ratio(&r) - want).abs() < 1e-3, "white stained half way to black: {r}"); +} + +#[test] +fn a_picked_symbol_object_is_drawn_at_its_instances_opacity() { + let mut s = picked_symbol_part(); + let r = s.execute("color.contrast", &json!({"against": "#000000"})).unwrap(); + let gray = vectorcraft_color::wcag::contrast_ratio(vectorcraft_color::wcag::over([1.0; 3], 0.5, [0.0; 3]), [0.0; 3]); + assert!((ratio(&r) - gray).abs() < 1e-3, "the instance draws the white at 50 %: {r}"); +} + +#[test] +fn type_measures_its_characters_without_an_appearance_rows_opacity() { + let mut s = session(); + s.execute("text.create", &json!({"x": 40, "y": 100, "text": "Label", "size": 24, "color": "#000000"})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let index = s.doc().unwrap().doc.node(s.doc().unwrap().selection.objects[0]).unwrap().appearance.items.len() - 1; + s.execute("appearance.setItem", &json!({"index": index, "opacity": 0})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-3, "the characters stay opaque black: {r}"); +} + +#[test] +fn a_gradient_stop_counts_with_its_own_opacity() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + let stops = json!([{"offset": 0, "color": "#000000", "opacity": 0.5}, {"offset": 1, "color": "#ff0000"}]); + s.execute("paint.setFill", &json!({"gradient": {"stops": stops}})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]); + assert!((ratio(&r) - gray).abs() < 1e-3, "the first stop, black at 50 %: {r}"); +} + +/// Picks the points of the selected gradient mesh inside the box from `a` to `b` with the Lasso tool. +fn pick_points(s: &mut Session, a: (f64, f64), b: (f64, f64)) { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let v = ViewInfo::default(); + s.select_tool("lasso", v).unwrap(); + let pts = [(a.0, a.1), (b.0, a.1), (b.0, b.1), (a.0, b.1), (a.0, b.1)]; + for (i, (x, y)) in pts.iter().enumerate() { + let kind = match i { + 0 => PointerKind::Down, + 4 => PointerKind::Up, + _ => PointerKind::Drag, + }; + s.pointer(&PointerEvent::new(kind, *x, *y), v).unwrap(); + } +} + +#[test] +fn a_picked_mesh_point_counts_with_its_own_opacity() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap(); + // The top-left point at 50 %, the top-right one opaque. + pick_points(&mut s, (40.0, 40.0), (60.0, 60.0)); + assert_eq!(s.fill_mesh_points().first().map(|(_, v)| v.len()), Some(1), "one point is picked"); + s.execute("transparency.set", &json!({"opacity": 50})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]); + assert!((ratio(&r) - gray).abs() < 1e-3, "the picked point, black at 50 %: {r}"); + pick_points(&mut s, (140.0, 40.0), (160.0, 60.0)); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-3, "the opaque point: {r}"); + // Both picked: one color at two opacities has no one answer, unless `opacity` is given. + pick_points(&mut s, (40.0, 40.0), (160.0, 60.0)); + let both = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(both.contains("the selected objects' colors differ: give `opacity` or `color`"), "{both}"); + assert!(s.execute("color.contrast", &json!({"opacity": 100})).is_ok()); +} + +#[test] +fn below_needs_a_selection_and_bad_params_are_errors() { + let mut s = session(); + let none = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(none.contains("nothing selected"), "{none}"); + // A given background needs no selection: the proxy shows the defaults for new art. + assert!(s.execute("color.contrast", &json!({"against": "#ffffff"})).is_ok()); + for bad in [ + json!({"color": "#000000", "against": "behind"}), + json!({"color": "#000000", "against": 3}), + json!({"color": "#00000080", "against": "#ffffff"}), + json!({"color": "nope", "against": "#ffffff"}), + json!({"color": "#000000", "against": "#ffffff", "opacity": 101}), + json!({"color": "#000000", "against": "#ffffff", "opacity": -1}), + json!({"color": "#000000", "against": "#ffffff", "opacity": "50"}), + ] { + assert!(s.execute("color.contrast", &bad).is_err(), "{bad}"); + } +} + +#[test] +fn a_fill_of_none_has_no_color_to_measure() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("has no color"), "{e}"); + assert!(s.execute("color.contrast", &json!({"color": "#000000"})).is_ok()); +} diff --git a/crates/engine/src/tests/curvature_circle.rs b/crates/engine/src/tests/curvature_circle.rs index 028ffa6487..91a6b9e9ff 100644 --- a/crates/engine/src/tests/curvature_circle.rs +++ b/crates/engine/src/tests/curvature_circle.rs @@ -254,3 +254,86 @@ fn after_deselect_the_pointer_reaches_the_circle_the_tool_drew() { assert_eq!(drawn_on(&s), first, "the click hit the circle drawn first ({reselect})"); } } + +/// The anchors of `id`'s path. +fn anchors_of(s: &Session, id: NodeId) -> Vec { + let doc = &s.doc().unwrap().doc; + doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect() +} + +/// With `anchors: "touch"` the circle is a plain path with an anchor where it touches the path; +/// with the default, its anchors stay at 0°, 90°, 180° and 270° whatever General › Constrain Angle +/// is; anything else is an error that draws nothing. +#[test] +fn the_anchors_go_where_the_circle_touches_or_at_standard_positions() { + let mut s = session(); + let path = parabola(&mut s); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "anchors": "touch"})).unwrap(); + let id = id_of(&v); + let node = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(matches!(node.kind, vectorcraft_doc::NodeKind::Path { live: None, .. }), "{node:?}"); + let anchors = anchors_of(&s, id); + assert_eq!(anchors.len(), 4); + assert!(anchors.iter().any(|a| a.distance(Point::new(200.0, 200.0)) < 1e-6), "{anchors:?}"); + assert!(bounds_are(&s, id, Rect::new(100.0, 200.0, 300.0, 400.0))); + + let upright = id_of(&s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap()); + let upright = anchors_of(&s, upright); + s.execute("prefs.set", &json!({"key": "constrainAngle", "value": 30})).unwrap(); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap(); + assert_eq!(anchors_of(&s, id_of(&v)), upright); + + let count = object_count(&s); + for bad in [json!("points"), json!(4), json!(true)] { + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "anchors": bad})).is_err()); + } + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "constantRadius": "no"})).is_err()); + assert_eq!(object_count(&s), count); +} + +/// Near the edge of the canvas, the circle is refused only when the path drawn reaches past it: the +/// circle with standard anchors, or with its anchors where it touches at a standard position, fits, +/// while with an anchor where it touches about 20° from the right one, a cubic bulges past the edge. +#[test] +fn the_canvas_check_measures_the_path_drawn() { + let mut s = session(); + let edge = vectorcraft_doc::MAX_COORD - 0.05; + let v = s.execute("shape.ellipse", &json!({"x": edge - 2000.0, "y": 0, "width": 2000, "height": 2000})).unwrap(); + let path = id_of(&v); + let count = object_count(&s); + let near_right = json!({"id": path.0, "segment": 1, "t": 0.79}); + assert!(s.execute(C, &near_right).is_ok()); + assert!(s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.0, "anchors": "touch"})).is_ok()); + let e = s.execute(C, &json!({"id": path.0, "segment": 1, "t": 0.79, "anchors": "touch"})).unwrap_err(); + assert!(e.to_string().contains("past the canvas"), "{e}"); + assert_eq!(object_count(&s), count + 2); +} + +/// The tool's options are saved with the preferences and come back in the next session. +#[test] +fn the_tool_options_are_saved_with_the_preferences() { + let mut s = session(); + s.select_tool(vectorcraft_tools::curvature_circle::ID, ViewInfo::default()).unwrap(); + let changed = + json!({"snapTolerance": 12.0, "snapWithoutGuides": false, "annotateRadius": false, "standardAnchors": false, "constantRadius": false}); + for (k, v) in changed.as_object().unwrap() { + s.set_tool_option(k, v); + } + s.select_tool("selection", ViewInfo::default()).unwrap(); + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut next = session(); + next.apply_prefs(serde_json::from_str(&saved).unwrap()); + next.select_tool(vectorcraft_tools::curvature_circle::ID, ViewInfo::default()).unwrap(); + assert_eq!(next.tool_options(), changed); +} + +/// With `constantRadius: false`, a circle's segment gives the cubic's own curvature, smaller than +/// the circle's at an anchor, so a larger radius, and the result is not nominal. +#[test] +fn without_constant_radius_an_arc_gives_its_own_curvature() { + let mut s = session(); + let path = circle(&mut s); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.0, "constantRadius": false})).unwrap(); + assert_eq!(v["nominal"], json!(false)); + assert!(v["radius"].as_f64().unwrap() > 100.5, "{v}"); +} diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 5017316c44..6aec396704 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -3,7 +3,7 @@ use serde_json::json; use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_geom::{FillRule, PathData, Point}; -use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; +use vectorcraft_tools::{Mods, PenPose, PointerEvent, PointerKind, ToolKey}; use crate::tooling::{UiRequest, ViewInfo}; use crate::*; @@ -552,6 +552,28 @@ fn pencil_redraws_the_shorter_way_round_a_closed_path() { assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "redraw": {"id": id.0, "within": -1}})).is_err()); } +/// `preview` draws the stroke as a new path on top, beside the selected path, and leaves the +/// selection as it was, in Draw Behind and Draw Inside too, as the Pencil previews a stroke that +/// redraws a selected path. +#[test] +fn pencil_preview_draws_on_top_and_leaves_the_selection_as_it_was() { + for mode in ["normal", "behind", "inside"] { + let mut s = session(); + let r = rect(&mut s, 400.0, 400.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [r.0]})).unwrap(); + s.execute("view.drawMode", &json!({ "mode": mode })).unwrap(); + let (parent, _, _) = s.doc().unwrap().doc.position(r).unwrap(); + let out = + s.execute("path.freehand", &json!({"points": [[100, 200], [150, 220], [200, 200]], "keepSelected": false, "preview": true})).unwrap(); + let id = NodeId(out["id"].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let ((rp, ri, _), (np, ni, _)) = (d.position(r).unwrap(), d.position(id).unwrap()); + assert!(rp == parent && np == parent, "{mode}: beside the path, in no clip group"); + assert!(ni > ri, "{mode}: on top of the path"); + assert_eq!(s.doc().unwrap().selection.objects, vec![r], "{mode}: the selection as it was"); + } +} + /// With Keep selected off, a new stroke leaves nothing selected (the earlier selection goes too, /// as Illustrator starts the stroke by dropping it, #5752); a continued or redrawn path is /// deselected and the rest of the selection stays. The stroke is one undo step. @@ -617,8 +639,14 @@ fn freehand_with_fit_off_joins_the_points_with_straight_segments() { .unwrap(); let sp = path(&s, r).subpaths[0].clone(); assert!(corners(&sp), "{:?}", sp.anchors); + // Each end's bend stops `within` (4) along the stroke, at a point added on its first and last + // piece; the drawn points beyond stay as drawn. let inner: Vec<_> = at(&sp).into_iter().filter(|p| p.1 < 499.0).collect(); - assert_eq!(inner, [(125.0, 470.0), (150.0, 460.0), (175.0, 470.0)]); + let t = 4.0 / 25f64.hypot(31.0); + let near = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9; + assert_eq!(inner.len(), 5, "{inner:?}"); + assert!(near(inner[0], (100.0 + 25.0 * t, 501.0 - 31.0 * t)) && near(inner[4], (200.0 - 25.0 * t, 501.0 - 31.0 * t)), "{inner:?}"); + assert_eq!(inner[1..4], [(125.0, 470.0), (150.0, 460.0), (175.0, 470.0)]); assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "fit": "no"})).is_err()); } @@ -738,6 +766,76 @@ fn blob_brush_size_follows_the_pen_pressure() { assert!(inside(&s, drawn, 290.0, 707.0) && !inside(&s, drawn, 110.0, 703.0), "the tool's stroke follows the pen"); } +/// Blob Brush Tool Options' Size set to Stylus Wheel: the brush is Size − Variation wide where an +/// airbrush pen's finger wheel was at 0 and Size + Variation where it was at 1, in a drag, a click +/// and with a tip that is not round. A stroke without a wheel keeps the Size, pressure does not +/// change it, and an unknown mode or a wheel out of its range is refused with nothing painted. +#[test] +fn blob_brush_size_follows_the_stylus_wheel() { + let mut s = session(); + let inside = |s: &Session, id: NodeId, x: f64, y: f64| { + vectorcraft_geom::hit::fill_contains(&path(s, id).to_bezpath(), FillRule::NonZero, Point::new(x, y)) + }; + let blob = |s: &mut Session, p: serde_json::Value| NodeId(s.execute("path.blob", &p).unwrap()["id"].as_u64().unwrap()); + // The wheel at 0 at the left end and at 1 at the right: about 2 pt wide to 18 pt wide. + let wheeled = |y: f64, wheel: &dyn Fn(f64) -> serde_json::Value| { + (0..=20).map(|i| json!([100.0 + f64::from(i) * 10.0, y, null, null, null, null, wheel(f64::from(i) / 20.0)])).collect::>() + }; + let tip = json!({"size": 10, "sizeMode": "stylusWheel", "sizeVariation": 8, "merge": false}); + let a = blob(&mut s, with(&tip, json!({"points": wheeled(100.0, &|w| json!(w))}))); + assert!(inside(&s, a, 290.0, 107.0) && !inside(&s, a, 110.0, 103.0), "wide where the wheel was at 1, thin where at 0"); + let b = blob(&mut s, with(&tip, json!({"points": wheeled(200.0, &|w| json!(1.0 - w))}))); + assert!(inside(&s, b, 110.0, 207.0) && !inside(&s, b, 290.0, 203.0), "the other way round"); + // No wheel at any point, and pressure without a wheel: 10 pt wide all along. + let none = blob(&mut s, with(&tip, json!({"points": wheeled(300.0, &|_| json!(null))}))); + let pressed = (0..=20).map(|i| json!([100.0 + f64::from(i) * 10.0, 400.0, f64::from(i) / 20.0])).collect::>(); + let pressure = blob(&mut s, with(&tip, json!({"points": pressed}))); + for (id, y) in [(none, 300.0), (pressure, 400.0)] { + assert!(inside(&s, id, 110.0, y + 3.0) && inside(&s, id, 290.0, y + 3.0) && !inside(&s, id, 290.0, y + 7.0), "10 pt at y {y}"); + } + // A click paints one dab as wide as the wheel gives. + let wide = blob(&mut s, with(&tip, json!({"points": [[100, 500, null, null, null, null, 1]]}))); + let thin = blob(&mut s, with(&tip, json!({"points": [[300, 500, null, null, null, null, 0]]}))); + assert!(inside(&s, wide, 100.0, 508.0) && !inside(&s, thin, 300.0, 503.0), "a dab follows the wheel"); + // A stroke whose samples all lie at one point paints a dab sized from its first reading, with + // the wheel and with pressure. + let still = blob(&mut s, with(&tip, json!({"points": [[500, 500, null, null, null, null, 1], [500, 500, null, null, null, null, 0]]}))); + let pressed_still = blob(&mut s, with(&tip, json!({"sizeMode": "pressure", "points": [[700, 500, 1], [700, 500, 0]]}))); + for (id, x) in [(still, 500.0), (pressed_still, 700.0)] { + assert!(inside(&s, id, x, 508.0) && !inside(&s, id, x, 510.0), "a dab from the first reading at x {x}"); + } + // A 25% round tip lying level: about 0.5 pt tall at the left end to 4.5 pt at the right. + let flat = blob(&mut s, with(&tip, json!({"roundness": 25, "points": wheeled(600.0, &|w| json!(w))}))); + assert!(inside(&s, flat, 290.0, 601.9) && !inside(&s, flat, 110.0, 601.0), "a flat tip follows the wheel"); + // Refused, with the document and its undo steps as they were. + let (before, undo) = (paths(&s).len(), s.doc().unwrap().history.undo.len()); + for (bad, key) in [ + (json!({"points": wheeled(700.0, &|w| json!(w)), "sizeMode": "tilt", "sizeVariation": 8}), "sizeMode"), + (json!({"points": [[0, 700, null, null, null, null, 1.5], [10, 700]], "sizeMode": "stylusWheel", "sizeVariation": 8}), "wheel"), + ] { + let err = s.execute("path.blob", &bad).unwrap_err(); + assert!(err.to_string().contains(key), "{err}"); + } + assert_eq!((paths(&s).len(), s.doc().unwrap().history.undo.len()), (before, undo), "nothing changed"); + // The tool records the wheel while its Size varies with it. + let v = view(); + s.select_tool("blobBrush", v).unwrap(); + s.set_tool_option("sizeMode", &json!("stylusWheel")); + s.set_tool_option("sizeVariation", &json!(8)); + assert_eq!(s.tool_options()["sizeMode"], json!("stylusWheel")); + let ev = |kind, i: i32| PointerEvent { + pen: Some(PenPose { wheel: Some(i as f32 / 20.0), ..PenPose::default() }), + ..PointerEvent::new(kind, 100.0 + f64::from(i) * 10.0, 800.0) + }; + s.pointer(&ev(PointerKind::Down, 0), v).unwrap(); + for i in 1..20 { + s.pointer(&ev(PointerKind::Drag, i), v).unwrap(); + } + s.pointer(&ev(PointerKind::Up, 20), v).unwrap(); + let (drawn, _) = paths(&s).into_iter().find(|(_, p)| p.control_bounds().is_some_and(|b| b.y0 > 750.0)).unwrap(); + assert!(inside(&s, drawn, 290.0, 807.0) && !inside(&s, drawn, 110.0, 803.0), "the tool's stroke follows the wheel"); +} + /// Eraser Tool Options' Size set to Pressure (#3961): the tip is Size − Variation across where the /// pen pressed lightest and Size + Variation where it pressed hardest; Fixed erases at the Size. #[test] @@ -1802,6 +1900,64 @@ fn smooth_region_refits_at_the_tolerance_sent_at_any_zoom() { } } +/// A line from (100, 200) to (400, 200) jagged by up to 6 pt either way, the same every time. +fn jagged_line_anchors() -> Vec { + let mut seed = 7u64; + (0..=60) + .map(|i| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + let noise = ((seed >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0; + json!({"x": 100.0 + f64::from(i) * 5.0, "y": 200.0 + 6.0 * noise}) + }) + .collect() +} + +/// The path a `path.smoothRegion` drag along [`jagged_line_anchors`] leaves with `smoothness` (left +/// out for null), and the mean distance of its points from the line y = 200. +fn smoothed_jagged_line(smoothness: serde_json::Value) -> (PathData, f64) { + let mut s = session(); + let id = smooth_test_path(&mut s, &jagged_line_anchors(), false); + let drag: Vec<_> = (0..=64).map(|i| json!([90.0 + f64::from(i) * 5.0, 200.0])).collect(); + s.execute("path.smoothRegion", &json!({"points": drag, "radius": 12, "fidelity": 2.5, "smoothness": smoothness})).unwrap(); + let p = path(&s, id); + let samples = smooth_test_samples(&p); + let off = samples.iter().map(|q| (q.y - 200.0).abs()).sum::() / samples.len() as f64; + (p, off) +} + +/// Smooth Tool Options' Smoothness: the higher it is, the smoother the path a drag leaves, from +/// 0% to 100%. Left out, a drag smooths at 50%. +#[test] +fn a_higher_smoothness_leaves_a_smoother_path() { + let original = { + let mut s = session(); + let id = smooth_test_path(&mut s, &jagged_line_anchors(), false); + let samples = smooth_test_samples(&path(&s, id)); + samples.iter().map(|q| (q.y - 200.0).abs()).sum::() / samples.len() as f64 + }; + let offs: Vec = [0.0, 25.0, 50.0, 75.0, 100.0].iter().map(|&x| smoothed_jagged_line(json!(x)).1).collect(); + assert!(offs[0] < original, "even 0% refits within Fidelity: {offs:?}, {original} before"); + assert!(offs.windows(2).all(|w| w[1] < w[0]), "each step up smooths more: {offs:?}"); + assert_eq!(smoothed_jagged_line(json!(null)).0, smoothed_jagged_line(json!(50)).0, "left out is 50%"); +} + +/// `path.smoothRegion` refuses a Smoothness outside 0% to 100% and changes nothing. +#[test] +fn smooth_region_refuses_a_smoothness_outside_0_to_100() { + let mut s = session(); + let id = smooth_test_path(&mut s, &jagged_line_anchors(), false); + let drag = json!({"points": [[90, 200], [250, 200], [410, 200]], "radius": 12, "fidelity": 2.5}); + for x in [json!(-1), json!(-0.001), json!(100.5), json!(101), json!(1e300)] { + refuses_with(&mut s, "path.smoothRegion", &with(&drag, json!({"smoothness": x})), "`smoothness` must be from 0 to 100"); + } + for x in [json!(0), json!(100)] { + let before = path(&s, id); + s.execute("path.smoothRegion", &with(&drag, json!({"smoothness": x}))).unwrap_or_else(|e| panic!("smoothness {x}: {e}")); + assert_ne!(path(&s, id), before, "smoothness {x} smoothed nothing"); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + /// A drag of the Smooth tool along a line jagged by up to 6 pt leaves no corner between a curve and /// a line: every anchor between the path's ends turns by at most 1°. #[test] @@ -3484,7 +3640,7 @@ fn smooth_and_join_refuse_a_reach_or_fidelity_outside_its_range() { } /// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness, -/// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change +/// width, radius, fidelity, smoothness or tolerance given as text or as another value that is not a number, and change /// nothing; null is read as the key left out. #[test] fn drawing_commands_refuse_a_size_given_as_text() { @@ -3499,6 +3655,7 @@ fn drawing_commands_refuse_a_size_given_as_text() { ("path.eraseSegments", "width"), ("path.smoothRegion", "radius"), ("path.smoothRegion", "fidelity"), + ("path.smoothRegion", "smoothness"), ("path.joinScrub", "tolerance"), ("path.blob", "size"), ("path.blob", "fidelity"), diff --git a/crates/engine/src/tests/fill_area.rs b/crates/engine/src/tests/fill_area.rs index 6625c7e150..b0b511e661 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -189,6 +189,90 @@ fn fill_area_stacks_above_the_group_that_holds_the_paths() { assert_eq!(members(&s, clip), before); } +/// `ids` clipped by a new rectangle mask in front of them, as the clipping group's id. +fn clip_by(s: &mut Session, ids: &[NodeId], x: f64, y: f64, w: f64, h: f64) -> NodeId { + let mask = rect(s, x, y, w, h); + let ids: Vec = ids.iter().map(|i| i.0).chain([mask.0]).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()) +} + +/// Clipped art bounds areas only where its clipping mask shows it: a click in the part the mask +/// hides finds no area and changes nothing, and a click in the part it shows fills only that part. +#[test] +fn fill_area_takes_clipped_art_only_where_its_mask_shows_it() { + let mut s = session(); + let square = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + let clip = clip_by(&mut s, &[square], 0.0, -10.0, 100.0, 120.0); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [125, 50]})).is_err()); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [75, 50]})).unwrap(); + assert!((area(&s, id_of(&r)) - 5000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); + assert_eq!(stack(&s), vec![clip, id_of(&r)], "the new path goes above the clipping group"); + + // Without a fill only the outline shows, and the mask's edge does not close the part it shows. + let mut s = session(); + let square = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + clip_by(&mut s, &[square], 0.0, -10.0, 100.0, 120.0); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [75, 50]})).is_err()); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); + + // Lines the mask cuts bound no area where the parts that close it are hidden. + let mut s = session(); + let lines = triangle(&mut s); + clip_by(&mut s, &lines, -20.0, -20.0, 60.0, 140.0); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [30, 75]})).is_err()); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); +} + +/// Parts of an outline that lie on the mask's edge show: a square without a fill, clipped by a mask +/// of the same square, keeps all four sides and bounds its whole area. A square just outside the +/// mask is hidden and bounds nothing. +#[test] +fn fill_area_keeps_outline_parts_on_the_mask_edge() { + let mut s = session(); + let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + clip_by(&mut s, &[square], 0.0, 0.0, 100.0, 100.0); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).unwrap(); + assert!((area(&s, id_of(&r)) - 10000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); + + let mut s = session(); + let square = rect(&mut s, -0.005, -0.005, 100.01, 100.01); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + clip_by(&mut s, &[square], 0.0, 0.0, 100.0, 100.0); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).is_err()); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); +} + +/// In a clipping group inside another, clipped art shows only where both masks show it. +#[test] +fn fill_area_takes_art_in_nested_clipping_groups_only_where_every_mask_shows_it() { + let mut s = session(); + let square = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + let inner = clip_by(&mut s, &[square], 0.0, -10.0, 100.0, 120.0); + let outer = clip_by(&mut s, &[inner], 0.0, -20.0, 80.0, 140.0); + deselect(&mut s); + let (undo, kids) = (undo_len(&s), stack(&s)); + for p in [[125, 50], [90, 50]] { + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": p})).is_err(), "{p:?}"); + } + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [65, 50]})).unwrap(); + assert!((area(&s, id_of(&r)) - 3000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); + assert_eq!(stack(&s), vec![outer, id_of(&r)]); +} + /// In isolation mode only the isolated group's paths bound areas, for the command and the tool: a /// click in an area that art outside the group encloses adds nothing, and the new path goes inside /// the group, above the path along the area. @@ -244,6 +328,39 @@ fn fill_area_stays_inside_the_isolated_group() { assert_eq!(s.doc().unwrap().doc.parent_of(new), s.doc().unwrap().doc.default_layer()); } +/// In isolation mode, `ids` naming the isolated group, or the layer or a group that holds it, takes +/// every path of the isolated group. The other paths of that layer or group, and other listed +/// objects outside the isolated group, do not bound areas. +#[test] +fn fill_area_ids_naming_what_holds_the_isolated_group_take_its_paths() { + let mut s = session(); + let outside = + [line(&mut s, (200.0, 0.0), (300.0, 100.0)), line(&mut s, (300.0, 0.0), (200.0, 100.0)), line(&mut s, (190.0, 80.0), (310.0, 80.0))]; + let lines = triangle(&mut s); + let ids: Vec = lines.iter().map(|l| l.0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let outer = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + deselect(&mut s); + let layer = s.doc().unwrap().doc.default_layer().unwrap(); + let (undo, kids) = (undo_len(&s), stack(&s)); + for named in [vec![layer.0], vec![outer.0], vec![g.0], vec![layer.0, outside[0].0]] { + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [250, 70], "ids": named})); + assert!(r.is_err(), "the area outside the isolated group, ids {named:?}"); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids.clone())); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": named})).unwrap(); + let new = id_of(&r); + assert_eq!(s.doc().unwrap().doc.parent_of(new), Some(g), "ids {named:?}"); + assert!((area(&s, new) - 900.0).abs() < 1.0, "{}", area(&s, new)); + s.execute("edit.undo", &json!({})).unwrap(); + } + let named: Vec = outside.iter().map(|l| l.0).collect(); + assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": named})).is_err(), "only art outside it listed"); + assert_eq!((undo_len(&s), stack(&s)), (undo, kids)); +} + /// While a compound path is isolated, Fill Area finds no area, for the command and the tool, and /// changes nothing: the compound path cannot hold the new path. The same goes for an isolated /// Objects on Path group, a group with a Transform effect and a group that is a clipping mask. @@ -521,6 +638,40 @@ fn fill_area_fills_an_l_whose_empty_corner_holds_a_left_out_path() { assert!((area(&s, id_of(&r)) - 70_000.0).abs() < 1.0, "{}", area(&s, id_of(&r))); } +/// Draws a 100 pt square at the origin and, in front of it, an open path with too many segments +/// that runs from x -20 to 120 at `y` and up to 0.1 pt above it, then clicks at `click` with +/// `gap`. Gives the area of the new path, or None when the click finds no area. +fn square_beside_a_huge_line(y: f64, gap: f64, click: (f64, f64)) -> Option { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS; + let pts: Vec = (0..=n).map(|k| Point::new(-20.0 + 140.0 * k as f64 / n as f64, y - (k % 2) as f64 * 0.1)).collect(); + let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look); + deselect(&mut s); + let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [click.0, click.1], "gap": gap})).ok()?; + Some(area(&s, id_of(&r))) +} + +/// With Gap Detection off, a path with too many segments 0.75 pt outside a square is left out and +/// does not touch the square, so a click in the square fills it. One that crosses the square still +/// stops the fill. +#[test] +fn fill_area_fills_a_square_a_left_out_path_passes_close_to() { + let a = square_beside_a_huge_line(-0.75, 0.0, (50.0, 50.0)).expect("the square"); + assert!((a - 10_000.0).abs() < 1.0, "{a}"); + assert_eq!(square_beside_a_huge_line(60.0, 0.0, (50.0, 25.0)), None); +} + +/// With a gap, a path with too many segments farther from the square than the gap is left out and +/// does not stop the square from being filled. One that crosses the square still stops the fill. +#[test] +fn fill_area_gap_fills_a_square_a_left_out_path_passes_beyond_the_gap() { + let a = square_beside_a_huge_line(-2.75, 2.0, (50.0, 50.0)).expect("the square"); + assert!((a - 10_000.0).abs() < 1.0, "{a}"); + assert_eq!(square_beside_a_huge_line(60.0, 2.0, (50.0, 25.0)), None); +} + /// A filled contour with too many segments on a higher layer surrounds a small square, its outline /// far from it: it is left out of the map, and the new path still goes above it, since it covers /// the area. diff --git a/crates/engine/src/tests/history_mem.rs b/crates/engine/src/tests/history_mem.rs index 279020432d..56580097f2 100644 --- a/crates/engine/src/tests/history_mem.rs +++ b/crates/engine/src/tests/history_mem.rs @@ -2,7 +2,7 @@ //! shared between steps, and past a memory budget the oldest steps go (never the last few). use serde_json::json; -use vectorcraft_doc::{Appearance, Node}; +use vectorcraft_doc::{Appearance, Node, NodeId}; use vectorcraft_geom::shapes; use crate::*; @@ -461,3 +461,69 @@ fn color_mode_paint_snapshots_count_toward_the_history_budget() { original.appearance.unwrap().effects[0].params["retainedTemplateData"] ); } + +/// A step that applies an effect keeps the effect, through undo and redo too. A step named like an +/// effect by anything else keeps none: a plain edit, an undo group named like the effect, and a +/// group another command started that an effect only extends. +#[test] +fn only_steps_an_effect_records_keep_the_effect() { + let mut s = session_with_rects(2); + let last = |s: &Session| s.doc().unwrap().history.undo.last().map(|e| (e.label.clone(), e.effect())); + assert_eq!(last(&s), Some(("Add".into(), None)), "a plain edit named like Pathfinder › Add"); + s.execute("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather")))); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.redo.last().and_then(|e| e.effect()), Some("stylize.feather"), "an undone step"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "a redone step"); + s.begin_named_undo_group(Some("Feather".into())); + s.execute("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + s.end_undo_group(false); + assert_eq!(last(&s), Some(("Feather".into(), None)), "a group named like the effect"); + s.begin_undo_group(); + s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.transform"})).unwrap(); + s.end_undo_group(false); + assert_eq!(last(&s), Some(("Transform".into(), None)), "a group a transform started"); + // An interaction's step keeps the effect its last preview applied, and none when a later + // preview replaced it with another command. + s.begin_interaction("Feather").unwrap(); + s.preview("effect.apply", &json!({"effect": "stylize.feather"})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "a kept preview"); + s.begin_interaction("Transform").unwrap(); + s.preview("effect.apply", &json!({"effect": "distort.transform"})).unwrap(); + s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Transform".into(), None)), "a replaced preview"); + s.begin_interaction("Feather").unwrap(); + s.preview("command.batch", &json!({"commands": [{"command": "effect.apply", "params": {"effect": "stylize.feather"}}]})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), None)), "a batch the preview ran"); +} + +/// An `effect.setParams` step keeps the effect it edited only when every target has that effect at +/// the index: with one target lacking it, the step keeps none, and the target that has it is still +/// edited. +#[test] +fn effect_options_keep_the_effect_only_when_every_target_has_it() { + let mut s = session_with_rects(2); + let ids: Vec = s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [ids[0]], "item": null})).unwrap(); + let last = |s: &Session| s.doc().unwrap().history.undo.last().map(|e| (e.label.clone(), e.effect())); + let radius = |s: &Session| { + let d = &s.doc().unwrap().doc; + d.node(NodeId(ids[0])).unwrap().appearance.effects[0].params["radius"].as_f64() + }; + s.begin_interaction("Feather").unwrap(); + s.preview("effect.setParams", &json!({"ids": ids, "item": null, "index": 0, "params": {"radius": 7}})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), None)), "one target without the effect"); + assert_eq!(radius(&s), Some(7.0), "the target with the effect is edited"); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [ids[1]], "item": null})).unwrap(); + s.begin_interaction("Feather").unwrap(); + s.preview("effect.setParams", &json!({"ids": ids, "item": null, "index": 0, "params": {"radius": 9}})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(last(&s), Some(("Feather".into(), Some("stylize.feather"))), "every target with the effect"); + assert_eq!(radius(&s), Some(9.0)); +} diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index 22edfec458..65fa7951cd 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -157,6 +157,13 @@ fn clicking_rows_at_any_depth_highlights_them_and_sets_the_current_layer() { let n = rect(&mut s, 50.0); assert_eq!(parent(&s, n), Some(sub)); assert!(s.execute("layer.setCurrent", &json!({"id": 9999})).is_err()); + // `keepRows` makes the layer current and leaves the highlighted rows. + run(&mut s, "layer.setCurrent", json!({"id": b.0})); + run(&mut s, "layer.setCurrent", json!({"id": c.0, "keepRows": true})); + let st = s.doc().unwrap(); + assert_eq!((st.highlighted_rows(), st.current_layer()), (vec![b], Some(layer))); + assert!(s.execute("layer.setCurrent", &json!({"id": a.0, "keepRows": 1})).is_err()); + assert_eq!(s.doc().unwrap().current_layer(), Some(layer), "a bad keepRows changes nothing"); // Shift/Ctrl: several rows. run(&mut s, "layer.highlight", json!({"ids": [a.0, g.0], "mode": "set"})); run(&mut s, "layer.highlight", json!({"ids": [c.0], "mode": "add"})); @@ -390,6 +397,105 @@ fn the_selection_column_selects_a_rows_art_and_shift_adds_or_removes_it() { assert_eq!(ids_sel(&run(&mut s, "layer.target", json!({"id": layer.0}))), vec![c, a, g]); } +/// The selection as a sorted list. +fn sorted_sel(s: &Session) -> Vec { + let mut ids = s.doc().unwrap().selection.objects.clone(); + ids.sort(); + ids +} + +/// The art the selection squares of `rows` select, each clicked alone, put together and sorted. +/// Leaves nothing selected. +fn each_rows_art(s: &mut Session, rows: &[NodeId]) -> Vec { + run(s, "select.none", json!({})); + let mut art = vec![]; + for row in rows { + art.extend(ids_sel(&run(s, "layer.selectAll", json!({"id": row.0})))); + } + art.sort(); + art.dedup(); + run(s, "select.none", json!({})); + art +} + +/// `layer.selectAll` with `range` (a Shift-click from the last selection square clicked) selects +/// the art of every row in the range, across the sublayer and the group, as each row's square +/// selects it; hidden and locked rows are left out, and `add` adds to the selection. The +/// highlighted rows stay, and no undo step is recorded. +#[test] +fn the_selection_column_selects_the_art_of_a_range_of_rows() { + let mut s = session(); + let (layer, sub, a, g, b, c) = tree(&mut s); + run(&mut s, "layer.setCurrent", json!({"id": sub.0})); + let undo = undos(&s); + // The rows top down: the layer, the sublayer, the group, its rectangle, then a and c. + let range = [g, b, a, c]; + let want = each_rows_art(&mut s, &range); + let reply = run(&mut s, "layer.selectAll", json!({"range": range.map(|r| r.0)})); + assert_eq!(sorted_sel(&s), want, "the group, its member's row, the sublayer's rectangle and the top layer's rectangle"); + assert!(want.contains(&a) && want.contains(&c), "{want:?}"); + assert_eq!(ids_sel(&reply).len(), s.doc().unwrap().selection.objects.len()); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![sub], "the highlighted row stays"); + assert_eq!(undos(&s), undo, "a selection change is not an undo step"); + // A range given bottom up selects the same art. + run(&mut s, "layer.selectAll", json!({"range": [c.0, a.0, b.0, g.0]})); + assert_eq!(sorted_sel(&s), want); + // `add` keeps what was selected. + run(&mut s, "select.set", json!({"ids": [c.0]})); + run(&mut s, "layer.selectAll", json!({"range": [a.0], "add": true})); + let got = sorted_sel(&s); + assert!(got.len() == 2 && got.contains(&a) && got.contains(&c), "{got:?}"); + // A range holding a layer row takes that layer's art, its sublayer's too. + run(&mut s, "layer.selectAll", json!({"range": [layer.0, sub.0]})); + assert_eq!(sorted_sel(&s), each_rows_art(&mut s, &[layer])); + // Locked and hidden rows are left out. + run(&mut s, "layer.setProps", json!({"ids": [a.0], "locked": true})); + run(&mut s, "layer.setProps", json!({"ids": [c.0], "visible": false})); + run(&mut s, "layer.selectAll", json!({"range": range.map(|r| r.0)})); + let got = sorted_sel(&s); + assert!(!got.is_empty() && !got.contains(&a) && !got.contains(&c), "{got:?}"); + // A range of only hidden and locked rows changes nothing and says why. + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert!(s.execute("layer.selectAll", &json!({"range": [a.0, c.0]})).is_err()); + assert_eq!(sorted_sel(&s), vec![g]); +} + +/// `layer.selectHighlighted` selects the art of the highlighted rows, as their selection squares +/// do, leaving out hidden and locked rows; `add` adds it. The highlighted rows stay, no undo step is +/// recorded, and with no row highlighted it is an error. +#[test] +fn select_highlighted_selects_the_art_of_the_highlighted_rows() { + let mut s = session(); + let (_, _, a, g, _, c) = tree(&mut s); + let want = each_rows_art(&mut s, &[g, c]); + run(&mut s, "layer.highlight", json!({"ids": [g.0, c.0], "mode": "set"})); + let rows = s.doc().unwrap().highlighted_rows(); + let undo = undos(&s); + run(&mut s, "layer.selectHighlighted", json!({})); + assert_eq!(sorted_sel(&s), want); + assert_eq!(s.doc().unwrap().highlighted_rows(), rows, "the highlighted rows stay"); + assert_eq!(undos(&s), undo, "a selection change is not an undo step"); + // `add` keeps what was selected. + run(&mut s, "select.set", json!({"ids": [a.0]})); + // Selecting art in another layer let go of the highlighted rows. + run(&mut s, "layer.highlight", json!({"ids": [g.0, c.0], "mode": "set"})); + run(&mut s, "layer.selectHighlighted", json!({"add": true})); + let mut with_a = want.clone(); + with_a.push(a); + with_a.sort(); + assert_eq!(sorted_sel(&s), with_a); + // A hidden row is left out. + run(&mut s, "layer.setProps", json!({"ids": [c.0], "visible": false})); + run(&mut s, "layer.highlight", json!({"ids": [g.0, c.0], "mode": "set"})); + run(&mut s, "layer.selectHighlighted", json!({})); + assert!(!sorted_sel(&s).contains(&c)); + // With no row highlighted, nothing changes. + run(&mut s, "layer.highlight", json!({"ids": [], "mode": "set"})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + assert!(s.execute("layer.selectHighlighted", &json!({})).is_err()); + assert_eq!(sorted_sel(&s), vec![a]); +} + /// The rows of [`column_start`]: [`tree`]'s, plus a rectangle `o` on a second layer and an empty /// third layer `e`. #[derive(Clone, Copy)] diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 96a2aedff8..4641467aa4 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -910,6 +910,54 @@ fn relative_corner_rounding_keeps_fraction_on_resize() { assert!((c.drawn_radius(0) / drawn - 2.0).abs() < 0.05, "drawn radius doubled with the shape"); } +/// `relativeRadii` on a plain path or an ellipse, which have no Live Corners record, leaves them +/// as they are and adds no undo step. +#[test] +fn relative_rounding_without_live_corners_adds_no_undo_step() { + let (mut s, id) = session(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.expandShape", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "a plain path"); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let n = steps(&s); + run(&mut s, json!({"ids": [id.0], "relativeRadii": false})); + run(&mut s, json!({"ids": [id.0], "relativeRadii": true})); + assert_eq!(steps(&s), n, "a plain path: no change"); + assert!(s.doc().unwrap().doc.node(id).unwrap().live_shape().is_none(), "still a plain path"); + let e = s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 50, "height": 30})).unwrap()["id"].as_u64().unwrap(); + let n = steps(&s); + run(&mut s, json!({"ids": [e], "relativeRadii": true})); + assert_eq!(steps(&s), n, "an ellipse: no change"); +} + +/// With Relative rounding, a radius is compared as the fraction it would store: a radius past the +/// corner's maximum, typed again, and the maximum the field then shows add no undo step, while a +/// smaller one adds one. +#[test] +fn a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step() { + let (mut s, id) = session(); + run(&mut s, json!({"relativeRadii": true})); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let max = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap().corner(0).unwrap().max_radius(); + let n = steps(&s); + run(&mut s, json!({"corners": [0], "radius": max + 20.0})); + assert_eq!(steps(&s), n + 1, "past the maximum: one undo step"); + let c = LiveCorners::of(s.doc().unwrap().doc.node(id).unwrap()).unwrap(); + assert!((c.radius(0) - 1.0).abs() < 1e-9, "stored as the whole maximum: {}", c.radius(0)); + run(&mut s, json!({"corners": [0], "radius": max + 20.0})); + assert_eq!(steps(&s), n + 1, "the same radius again: no undo step"); + run(&mut s, json!({"corners": [0], "radius": max})); + assert_eq!(steps(&s), n + 1, "the maximum, as shown: no undo step"); + run(&mut s, json!({"corners": [0], "radius": max / 2.0})); + assert_eq!(steps(&s), n + 2, "a smaller radius: one undo step"); + // On a large shape a small radius is a fraction below 1e-9, and still a change. + let big = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 3_000_000, "height": 3_000_000})).unwrap()["id"].as_u64().unwrap(); + run(&mut s, json!({"ids": [big], "relativeRadii": true})); + let n = steps(&s); + run(&mut s, json!({"ids": [big], "corners": [0], "radius": 0.001})); + assert_eq!(steps(&s), n + 1, "a small radius on a large shape: one undo step"); +} + /// #2898: while a corner widget is pressed or dragged, Up and Down step the corners' kind (round, /// inverted round, chamfer, in turn) along with the radius, as one undo step with the drag. #[test] diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index a23fab2209..6f7fe9c581 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4535,6 +4535,156 @@ fn release_guides_turns_ruler_guides_into_paths() { assert_eq!(guides(&s).len(), 1); } +/// The direction of a two-anchor line, in degrees from the page's x axis (y down), from 0 to 180. +fn line_angle(ends: &[(f64, f64)]) -> f64 { + let [(x0, y0), (x1, y1)] = ends[..] else { panic!("not a line of two anchors") }; + (y1 - y0).atan2(x1 - x0).to_degrees().rem_euclid(180.0) +} + +/// A selected ruler guide rotates with `object.rotate` on its own, in one undo step, about the +/// middle of the line Release Guides makes of it. At 30° it becomes a selected guide path along +/// the turned line; Transform Again turns that path on, and undo gives the ruler guide back. +#[test] +fn rotating_a_ruler_guide_makes_an_angled_guide() { + let mut s = session(); + s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + let line = s.doc().unwrap().doc.guide_line(&s.doc().unwrap().doc.ruler_guides()[0]).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + let n = undo_len(&s); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + assert_eq!(undo_len(&s), n + 1); + assert!(guides(&s).is_empty(), "the ruler guide is replaced"); + let [path] = selected(&s)[..] else { panic!("one guide path selected") }; + assert!(selected_guides(&s).is_empty()); + let (ends, guide) = line_ends(&s, path); + assert!(guide, "the path is a guide"); + let (mid, len) = (line.0.midpoint(line.1), line.0.distance(line.1)); + let (a, b) = (vectorcraft_geom::Point::new(ends[0].0, ends[0].1), vectorcraft_geom::Point::new(ends[1].0, ends[1].1)); + assert!(a.midpoint(b).distance(mid) < 1e-6 && close(a.distance(b), len), "it turns about its middle"); + // Counter-clockwise on the page: the downward vertical line now points 30° toward the right. + assert!(close(line_angle(&ends), 60.0), "{ends:?}"); + s.execute("object.transformAgain", &json!({})).unwrap(); + assert!(close(line_angle(&line_ends(&s, path).0), 30.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(guides(&s), vec![(true, 100.0)]); + assert!(s.doc().unwrap().doc.node(path).is_none()); +} + +/// A ruler guide turned by a quarter turn stays a ruler guide, horizontal now, through the same +/// middle; a turn of 0 changes nothing and records no undo step; a copy leaves the guide where it +/// was; and locked guides cannot be rotated. +#[test] +fn ruler_guides_turned_square_stay_ruler_guides() { + let mut s = session(); + s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + let mid = { + let d = &s.doc().unwrap().doc; + let (a, b) = d.guide_line(&d.ruler_guides()[0]).unwrap(); + a.midpoint(b) + }; + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + let n = undo_len(&s); + s.execute("object.rotate", &json!({"angle": 0})).unwrap(); + assert_eq!((guides(&s), undo_len(&s)), (vec![(true, 100.0)], n)); + // Guides alone have no bounding box angle for `absolute` to set. + assert!(s.execute("object.rotate", &json!({"angle": 90, "absolute": true})).is_err()); + assert_eq!((guides(&s), undo_len(&s)), (vec![(true, 100.0)], n)); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let [(vertical, pos)] = guides(&s)[..] else { panic!("one ruler guide") }; + assert!(!vertical && close(pos, mid.y), "{pos}"); + assert_eq!((selected_guides(&s), undo_len(&s)), (vec![0], n + 1)); + // A copy at 45° adds a guide path and keeps the ruler guide. + s.execute("object.rotate", &json!({"angle": 45, "copy": true})).unwrap(); + assert_eq!(guides(&s).len(), 1); + let [path] = selected(&s)[..] else { panic!("the copy is selected") }; + assert!(line_ends(&s, path).1); + // Locked guides are deselected, and nothing is left to rotate. + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + assert!(s.execute("object.rotate", &json!({"angle": 30})).is_err()); + assert_eq!(guides(&s).len(), 1); +} + +/// Art and a ruler guide selected together rotate about the center of the art's box and the +/// guide's line together, and the angled guide survives a save and reopen as a guide path. +#[test] +fn a_ruler_guide_rotates_with_the_selected_art() { + let mut s = session(); + let a = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap(); + sel(&mut s, &[a]); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert_eq!((selected(&s), selected_guides(&s)), (vec![a], vec![0])); + let center = { + let d = &s.doc().unwrap().doc; + let (p, q) = d.guide_line(&d.ruler_guides()[0]).unwrap(); + Rect::from_points(p, q).union(bounds(&s, a)).center() + }; + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let [(vertical, pos)] = guides(&s)[..] else { panic!("one ruler guide") }; + assert!(vertical && close(pos, center.x + (50.0 - center.y)), "{pos}"); + let turned = bounds(&s, a); + assert!(close(turned.center().x, center.x + (150.0 - center.y)), "{turned:?}"); + s.execute("object.rotate", &json!({"angle": 20})).unwrap(); + let paths: Vec = selected(&s).into_iter().filter(|id| *id != a).collect(); + let [path] = paths[..] else { panic!("the guide path is selected with the art") }; + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let saved = back.node(path).unwrap(); + assert!(matches!(&saved.kind, NodeKind::Path { guide: true, path: p, .. } if *p == match &node(&s, path).kind { + NodeKind::Path { path, .. } => path.clone(), + _ => panic!("not a path"), + })); + // With anchors selected with Direct Selection, the selected guide turns with them. + s.execute("guide.add", &json!({"vertical": true, "pos": 600})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert!(!s.doc().unwrap().selection.anchors.is_empty()); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + assert!(!guides(&s)[0].0, "the vertical guide is horizontal now: {:?}", guides(&s)); +} + +/// The reply to a transform lists the guide paths it makes of ruler guides: for a guide alone, +/// with a copy, beside selected art and beside direct-selected anchors. +#[test] +fn a_transform_replies_with_the_guide_paths_it_makes() { + fn reply_ids(r: &Value) -> Vec { + r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect() + } + let mut s = session(); + s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + // A copy keeps the ruler guide and adds a guide path, the only new object. + let r = s.execute("object.rotate", &json!({"angle": 45, "copy": true})).unwrap(); + let [copy] = selected(&s)[..] else { panic!("the copy is selected") }; + assert_eq!(reply_ids(&r), vec![copy]); + // Without a copy the guide becomes a guide path. + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + let r = s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let [path] = selected(&s)[..] else { panic!("one guide path selected") }; + assert_ne!(path, copy); + assert_eq!(reply_ids(&r), vec![path]); + // With art selected, the reply lists the art and then the guide path. + let a = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + s.execute("guide.add", &json!({"vertical": false, "pos": 50})).unwrap(); + sel(&mut s, &[a]); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + let r = s.execute("object.rotate", &json!({"angle": 20})).unwrap(); + let paths: Vec = selected(&s).into_iter().filter(|id| *id != a).collect(); + let [mixed] = paths[..] else { panic!("the guide path is selected with the art") }; + assert_eq!(reply_ids(&r), vec![a, mixed]); + // With direct-selected anchors, the guide path joins the reply too. + s.execute("guide.add", &json!({"vertical": true, "pos": 600})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert!(!s.doc().unwrap().selection.anchors.is_empty()); + let r = s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let anchored: Vec = selected(&s).into_iter().filter(|id| *id != a).collect(); + let [made] = anchored[..] else { panic!("the guide path is selected with the path") }; + assert!(line_ends(&s, made).1, "it is a guide path"); + assert!(reply_ids(&r).contains(&made), "{r}"); +} + #[test] fn ruler_guides_and_lock() { let mut s = session(); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 53838c9bd7..b65d4a4b9a 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -160,7 +160,8 @@ fn ppi_overprint_preview_and_bad_params() { json!({"previewMode": "xray"}), json!({"artboardLayout": {"layout": "spiral"}}), json!({"artboardLayout": {"columns": 0}}), - json!({"artboardLayout": {"rows": 2}}), + json!({"artboardLayout": {"rows": 0}}), + json!({"artboardLayout": {"tiles": 2}}), json!({"units": "furlongs"}), json!({"width": 160000, "artboards": 1000}), ] { @@ -1001,6 +1002,22 @@ fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { let _ = std::fs::remove_dir_all(&dir); } +#[cfg(unix)] +#[test] +fn a_profile_that_is_a_link_is_not_followed() { + let (mut s, dir) = with_profiles("link"); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + // A profile the folder held, moved out and linked back in. + let outside = std::env::temp_dir().join(format!("vc-newdoc-profile-outside-{}.vectorcraft", std::process::id())); + std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap(); + std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap(); + let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}"); + assert!(r.get("profile").is_none(), "{r}"); + let _ = std::fs::remove_file(&outside); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn profile_names_are_checked_and_editing_needs_the_folder() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index c2e80f983a..8caada9e72 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -460,7 +460,7 @@ fn the_eyedropper_armed_for_the_bucket_answers_no_opacity() { s.select_tool("eyedropper", ViewInfo::default()).unwrap(); assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the Eyedropper alone shows the selection's"); s.set_tool_option("stop", &json!("livePaintBucket")); - assert!(s.bucket_paints()); + assert!(s.tool_paints(false) && s.tool_paints(true)); assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); assert_eq!(proxies(&mut s)["strokeOpacity"], Value::Null); } diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 60f223334c..6911059b0a 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1955,6 +1955,31 @@ fn a_pathfinder_effect_keeps_the_options_in_force_when_applied() { assert_eq!(mix, &json!({"mixingRate": 50.0, "precision": 0.5, "removeRedundantPoints": true, "removeUnpainted": true})); } +/// A Pathfinder effect given some of its options in `params` journals every option it used, so +/// replaying the journal with other preferences gives the same effect and art. +#[test] +fn a_pathfinder_effect_given_some_options_journals_every_option_it_used() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 99.5, "width": 100, "height": 50})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.prefs.pathfinder = PathfinderOptions { precision: 1.0, remove_redundant_points: true, remove_unpainted: true }; + s.execute("effect.apply", &json!({"effect": "pathfinder.divide", "params": {"precision": 0.25}})).unwrap(); + let all = json!({"precision": 0.25, "removeRedundantPoints": true, "removeUnpainted": true}); + assert_eq!(first_effect_params(&s), all); + let (id, p) = s.journal.last().unwrap().clone(); + assert_eq!((id.as_str(), &p["params"]), ("effect.apply", &all), "the journal entry gives every option the effect used"); + let mut replay = Session::new(); + for (id, p) in &s.journal { + replay.execute(id, p).unwrap(); + } + assert_eq!(replay.prefs.pathfinder, PathfinderOptions::default()); + let doc = |s: &Session| serde_json::to_value(&*s.doc().unwrap().doc).unwrap(); + assert_eq!(doc(&replay), doc(&s)); +} + /// A live Pathfinder effect evaluates with its own options as the panel's operations do with /// Pathfinder Options: a precision of 1 pt drops a 0.5 pt overlap, Divide leaves out an unfilled /// object's pieces, and Remove Redundant Points drops an anchor that shapes nothing. diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 855952fcb2..e47eb8377a 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -333,6 +333,59 @@ fn failing_plugins_leave_the_document_and_history_alone() { } } +/// A filter's output may report a `notice`, which `plugin.run` returns once the output is applied, +/// escaped and capped by the host, with the plug-in's name as `pluginName`. It needs no permission: a filter granted none reports one too. +/// A `notice` that is not a string refuses the output, and the document and history stay as they +/// were. +#[test] +fn a_filter_s_notice_is_returned_once_its_output_is_applied() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000").0; + let quiet = "test.engine.notice.none"; + install(&mut s, &asking(quiet, "[]", &json!({"objects": [], "notice": "Nothing to tidy"}))); + let r = run(&mut s, "plugin.run", json!({"id": quiet})); + assert_eq!((&r["plugin"], &r["notice"]), (&json!(quiet), &json!("Nothing to tidy"))); + assert_eq!(r["pluginName"], json!(format!("Test {quiet}"))); + let reading = |s: &mut Session, id: &str, output: &Value| { + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, output)); + run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true})) + }; + let noisy = "test.engine.notice.escaped"; + let long = format!("Done\u{202E}\n{}", "x".repeat(500)); + reading(&mut s, noisy, &json!({"objects": [{"id": id}], "notice": long})); + let shown = run(&mut s, "plugin.run", json!({"id": noisy, "ids": [id]}))["notice"].as_str().unwrap_or_default().to_string(); + assert!(shown.starts_with("Done\\u{202E}\\u{000A}xx") && shown.ends_with('…'), "{shown}"); + assert_eq!(shown.chars().count(), vectorcraft_plugins::objects::MAX_NOTICE_CHARS); + let plain = "test.engine.notice.plain"; + reading(&mut s, plain, &json!({"objects": [{"id": id}]})); + let r = run(&mut s, "plugin.run", json!({"id": plain, "ids": [id]})); + assert!(r.get("notice").is_none() && r.get("pluginName").is_none(), "{r}"); + let bad = "test.engine.notice.bad"; + install(&mut s, &asking(bad, "[]", &json!({"objects": [], "notice": 3}))); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let e = s.execute("plugin.run", &json!({"id": bad})).unwrap_err().to_string(); + assert!(e.contains("`notice` must be a string with visible text"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); +} + +/// A plug-in command's result carries its run's `notice` beside the command's id, and so does the +/// step of a batch that runs it. +#[test] +fn a_plugin_command_returns_its_run_s_notice() { + let mut s = session(); + let id = "test.engine.notice.command"; + let commands = r#"[{"id":"count","label":"Count"}]"#; + install_wat(&mut s, &tpl::returning(&with_commands(id, "filter", commands), r#"{"objects":[],"notice":"Counted 0 objects"}"#)); + let count = crate::cmd::plugin::command_id(id, "count"); + let r = run(&mut s, &count, json!({})); + assert_eq!((&r["command"], &r["notice"]), (&json!("count"), &json!("Counted 0 objects"))); + let batch = run(&mut s, "command.batch", json!({"commands": [{"command": count, "params": {}}]})); + assert!(batch.to_string().contains("Counted 0 objects"), "{batch}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + #[test] fn live_effect_plugins_reshape_editable_art_and_expand() { let mut s = session(); @@ -2126,6 +2179,42 @@ fn plugin_list_leaves_out_paths_outside_the_read_root() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A command a script runs loads a plug-in folder's files through the script's read gate also +/// without automation roots: a link in a folder the script may read, to a module outside it, is +/// refused whether or not its name is valid text. +#[cfg(unix)] +#[test] +fn a_script_loads_no_plugin_from_outside_its_folder_through_a_name_that_is_not_text() { + use crate::file_access::{ScriptGate, ScriptScope, with_script_gate}; + use std::os::unix::ffi::OsStrExt; + let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); + let base = crate::tests_links::Folder::new("plugin-script-name-not-text"); + let (inside, outside) = (base.0.join("in"), base.0.join("out")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let (text_id, bytes_id) = ("test.engine.script.textname", "test.engine.script.bytesname"); + for (id, file, link) in [(text_id, "text.wasm", &b"a.wasm"[..]), (bytes_id, "bytes.wasm", &b"b\xff.wasm"[..])] { + let src = tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#); + std::fs::write(outside.join(file), wat::parse_str(src).unwrap()).unwrap(); + std::os::unix::fs::symlink(outside.join(file), inside.join(std::ffi::OsStr::from_bytes(link))).unwrap(); + } + let gate = ScriptGate { + read: ScriptScope::of_folder(&inside), + write: ScriptScope::default(), + documents: vec![], + linked: Default::default(), + also: None, + }; + let mut s = session(); + let folder = inside.to_string_lossy().to_string(); + let r = with_script_gate(gate, || s.execute("plugin.reload", &json!({"path": folder}))); + let installed = [text_id, bytes_id].map(vectorcraft_plugins::registry::remove); + assert_eq!(installed, [false, false], "a script loaded a module from outside its folder: {r:?}"); + let r = r.unwrap(); + assert_eq!(r["loaded"], json!([]), "{r}"); + assert_eq!(r["failed"].as_array().map(Vec::len), Some(2), "{r}"); +} + /// Under automation read roots, a plug-in turned off for the next launch is listed with a file /// outside them named by its file name, and `plugin.setEnabled` turns it on by that name. #[test] @@ -2625,7 +2714,8 @@ fn a_grant_given_elsewhere_since_the_load_removed_one_is_kept() { let approved = asking(id, r#"["doc.read"]"#, &empty); std::fs::write(&later, &approved).unwrap(); let grants = folder.0.join("grants.json"); - let entry = |hash: String| serde_json::to_vec(&json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}])).unwrap(); + let entry = + |hash: String| crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}]).to_string()); std::fs::write(&grants, entry(sha256_hex(&approved))).unwrap(); let held = HeldLoad::new(later.clone()); let mut s = session(); @@ -2642,7 +2732,7 @@ fn a_grant_given_elsewhere_since_the_load_removed_one_is_kept() { s.finish_plugin_loads(); let source = vectorcraft_plugins::registry::get(id).and_then(|p| p.source().map(str::to_string)); assert!(vectorcraft_plugins::registry::remove(id)); - let listed: Vec = serde_json::from_slice(&std::fs::read(&grants).unwrap()).unwrap(); + let listed = crate::store::grant_entries(&std::fs::read(&grants).unwrap()); assert_eq!(source.as_deref(), Some(first.display().to_string().as_str()), "the later module installed"); assert_eq!(listed.iter().map(|e| e["hash"].clone()).collect::>(), [json!(sha256_hex(&other))], "{listed:?}"); } @@ -2661,7 +2751,11 @@ fn a_grant_that_cannot_be_put_back_leaves_the_later_module_uninstalled() { let approved = asking(id, r#"["doc.read"]"#, &empty); std::fs::write(&later, &approved).unwrap(); let grants = folder.0.join("grants.json"); - std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap(); + std::fs::write( + &grants, + crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]).to_string()), + ) + .unwrap(); // The first write removes the grant; the second, which puts it back, finds a folder where the // file goes and fails. let blocked = grants.clone(); @@ -2696,7 +2790,11 @@ fn a_grant_put_back_for_a_module_that_did_not_install_is_removed_again() { let approved = asking(id, r#"["doc.read"]"#, &empty); std::fs::write(&later, &approved).unwrap(); let grants = folder.0.join("grants.json"); - std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}])).unwrap()).unwrap(); + std::fs::write( + &grants, + crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}]).to_string()), + ) + .unwrap(); // The first write removes the grant; while the second puts it back, the id is installed // elsewhere. crate::store::AFTER_GRANTS_READ.set(Some(Box::new(move || { @@ -2711,7 +2809,14 @@ fn a_grant_put_back_for_a_module_that_did_not_install_is_removed_again() { assert!(vectorcraft_plugins::registry::remove(id)); // A grants file that went away holds no grant; one still there must read as a list. let listed: Vec = match std::fs::read(&grants) { - Ok(b) => serde_json::from_slice(&b).unwrap(), + Ok(b) => match serde_json::from_slice::(&b).unwrap() { + Value::Array(entries) => entries, + Value::Object(mut file) => match file.remove("grants") { + Some(Value::Array(entries)) => entries, + other => panic!("the grants file holds no list: {other:?}"), + }, + other => panic!("the grants file holds no list: {other:?}"), + }, Err(e) if e.kind() == std::io::ErrorKind::NotFound => vec![], Err(e) => panic!("the grants file could not be read: {e}"), }; @@ -2988,11 +3093,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { let other_wasm = asking(other, r#"["doc.read"]"#, &empty); let grants = folder.0.join("grants.json"); let ids = || -> Vec { - serde_json::from_slice::>(&std::fs::read(&grants).unwrap()) - .unwrap() - .iter() - .map(|e| e["id"].as_str().unwrap().to_string()) - .collect() + crate::store::grant_entries(&std::fs::read(&grants).unwrap()).iter().map(|e| e["id"].as_str().unwrap().to_string()).collect() }; let mut s = session(); s.attach_plugin_store(folder.0.clone()); @@ -3012,7 +3113,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { // A grant the store already holds for an id whose stored module lists no permissions. let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); let other_entry = json!({"id": other, "hash": sha256_hex(&other_wasm), "permissions": ["doc.read"]}); - std::fs::write(&grants, serde_json::to_vec(&json!([entry, other_entry])).unwrap()).unwrap(); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([entry, other_entry]).to_string())).unwrap(); vectorcraft_plugins::registry::remove(id); let mut third = session(); third.attach_plugin_store(folder.0.clone()); @@ -3022,7 +3123,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { // So does an entry this version can't read, and a grant held only by the process. let future = json!({"id": id, "hash": "00", "permissions": ["doc.read", "ui.panel"]}); - std::fs::write(&grants, serde_json::to_vec(&json!([future, other_entry])).unwrap()).unwrap(); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([future, other_entry]).to_string())).unwrap(); vectorcraft_plugins::registry::remove(id); vectorcraft_plugins::registry::grant(GrantToken::after_engine_approval(Grant { id: id.into(), @@ -3082,8 +3183,8 @@ fn a_grant_that_cannot_be_removed_keeps_the_stored_module() { let file = s.stored_plugin_file(id).unwrap(); // An entry this version can't use is written back as it was read: `1e9` as `1000000000.0`, which // makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); run(&mut s, "plugin.install", replace.clone()); @@ -3130,8 +3231,8 @@ fn a_grant_left_behind_when_its_module_cannot_go_back_stops_counting() { run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); let file = s.stored_plugin_file(id).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); crate::store::PUT_BACK_FAILS.set(true); @@ -3163,7 +3264,7 @@ fn an_unusable_entry_that_cannot_be_removed_stops_plugin_remove() { let file = s.stored_plugin_file(id).unwrap(); let entry = json!({"id": id, "hash": "0".repeat(64), "permissions": ["no.such.permission"]}); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); @@ -3196,8 +3297,8 @@ fn a_grant_that_cannot_be_removed_and_has_no_stored_module_stops_counting() { s.attach_plugin_store(folder.0.clone()); run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); let file = s.stored_plugin_file(id).unwrap(); - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); std::fs::remove_file(&file).unwrap(); @@ -3226,13 +3327,14 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() { let needs_approval = json!({"dataBase64": approved_data}); let grants = folder.0.join("grants.json"); let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); - let recorded = serde_json::to_vec(&json!([entry])).unwrap(); + let list = json!([entry]).to_string(); + let recorded = |dir: &std::path::Path| crate::store::signed_grants_file(dir, &list); let mut s = session(); s.attach_plugin_store(folder.0.clone()); run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)})); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); vectorcraft_plugins::registry::remove(id); let mut next = session(); @@ -3242,12 +3344,12 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() { let refused = next.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string(); assert!(refused.contains("doc.read"), "{refused}"); - std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap(); + std::fs::write(elsewhere.0.join("grants.json"), recorded(&elsewhere.0)).unwrap(); next.attach_plugin_store(elsewhere.0.clone()); assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts"); // A load that can rewrite the file forgets the grant, and the store has nothing ignored again. - std::fs::write(&grants, &recorded).unwrap(); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); next.attach_plugin_store(folder.0.clone()); assert!(!grants.exists(), "the load removes the grant"); @@ -3257,7 +3359,7 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() { let mut third = session(); third.attach_plugin_store(folder.0.clone()); std::fs::remove_dir(&grants).unwrap(); - std::fs::write(&grants, &recorded).unwrap(); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); assert_eq!(run(&mut third, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the file reads again, and the grant doesn't count"); // Attaching the same store again, with no stored module to try the removal for, keeps it out. @@ -3294,8 +3396,9 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() { let needs_approval = json!({"dataBase64": approved_data}); let grants = folder.0.join("grants.json"); let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); - let recorded = serde_json::to_vec(&json!([entry])).unwrap(); - std::fs::write(&grants, &recorded).unwrap(); + let list = json!([entry]).to_string(); + let recorded = |dir: &std::path::Path| crate::store::signed_grants_file(dir, &list); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); let mut first = session(); first.attach_plugin_store(folder.0.clone()); let inside = folder.0.join("inside"); @@ -3305,7 +3408,7 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() { assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts"); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); run(&mut first, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)})); let file = first.stored_plugin_file(id).unwrap(); @@ -3325,13 +3428,13 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() { later.attach_plugin_store(folder.0.clone()); assert_eq!(run(&mut later, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "a session attached later doesn't count it"); - std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap(); + std::fs::write(elsewhere.0.join("grants.json"), recorded(&elsewhere.0)).unwrap(); other.attach_plugin_store(elsewhere.0.clone()); assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts"); other.attach_plugin_store(folder.0.clone()); assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "back on the folder, it doesn't"); - std::fs::write(&grants, &recorded).unwrap(); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); assert!(later.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written"); for s in [&mut first, &mut other, &mut later] { assert_eq!(run(s, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again"); @@ -3389,7 +3492,7 @@ fn sessions_attached_before_the_folder_exists_share_its_ignored_grants() { let mut other = session(); other.attach_plugin_store(alias); std::fs::create_dir(&dir).unwrap(); - std::fs::write(dir.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap(); + std::fs::write(dir.join("grants.json"), crate::store::signed_grants_file(&dir, &json!([entry]).to_string())).unwrap(); assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts"); first.ignore_stored_grant(id, first.grant_writes()); @@ -3430,11 +3533,10 @@ fn a_linked_plugin_folder_uses_the_ignored_grants_of_where_the_link_leads() { let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)}); let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); - let recorded = serde_json::to_vec(&json!([entry])).unwrap(); let (old, new, link) = (folder.0.join("old"), folder.0.join("new"), folder.0.join("Plug-ins")); for dir in [&old, &new] { std::fs::create_dir(dir).unwrap(); - std::fs::write(dir.join("grants.json"), &recorded).unwrap(); + std::fs::write(dir.join("grants.json"), crate::store::signed_grants_file(dir, &json!([entry]).to_string())).unwrap(); } std::os::unix::fs::symlink(&old, &link).unwrap(); let mut linked = session(); @@ -3501,8 +3603,8 @@ fn a_grant_that_cannot_be_removed_stops_plugin_remove() { let file = s.stored_plugin_file(id).unwrap(); let recorded = std::fs::read(&grants).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&recorded).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&recorded).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); let data = crate::store::plugin_data_dir(&folder.0, id); std::fs::create_dir_all(&data).unwrap(); @@ -3560,8 +3662,8 @@ fn settings_that_cannot_be_moved_back_are_reported_and_moved_back_later() { run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]})); let recorded = std::fs::read(&grants).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&recorded).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&recorded).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); let data = crate::store::plugin_data_dir(&folder.0, id); let settings = br#"{"zoom":"aGVsbG8="}"#; @@ -3692,8 +3794,9 @@ fn a_grants_file_that_cannot_be_deleted_keeps_the_stored_module() { } /// When the last grant can't be removed because `grants.json` can't be deleted, a replacing module -/// that asks for no permissions doesn't stay in the store: the store gets back the module the grant -/// still covers, and the grant is left as it was. +/// that asks for no permissions doesn't stay in the store: the store gets back the earlier module, +/// and the file is left as it was. The generation was raised before the removal and stays raised, so +/// the file left in place grants nothing and the module asks again. #[test] fn a_grants_file_whose_deletion_fails_keeps_the_stored_module() { let folder = crate::tests_links::Folder::new("plugin-store-undeletable-grants"); @@ -3713,8 +3816,8 @@ fn a_grants_file_whose_deletion_fails_keeps_the_stored_module() { run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain), "replace": true})); crate::store::GRANTS_DELETE_FAILS.set(false); assert_eq!(std::fs::read(&file).unwrap(), approved, "the store gets the module the grant covers back"); - assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grant stays as it was"); - assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], false, "the grant still covers the module"); + assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the file stays as it was"); + assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": approved_data}))["needsApproval"], true, "the file left in place grants nothing"); run(&mut s, "plugin.remove", json!({"id": id})); assert!(!grants.exists(), "a removal that can delete the file forgets the grant"); @@ -3802,7 +3905,11 @@ fn a_stored_grant_covers_only_the_stored_module_it_recorded() { // A malformed hash is no wildcard, even for the module on disk. let upper = sha256_hex(&first).to_uppercase(); for hash in ["", "00", upper.as_str()] { - std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}])).unwrap()).unwrap(); + std::fs::write( + &grants, + crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}]).to_string()), + ) + .unwrap(); assert!(!starts(), "hash {hash:?}"); } @@ -3862,11 +3969,11 @@ fn a_failed_store_write_keeps_the_stored_module_with_its_grant() { // The grants file is full: the new grant, which is longer, doesn't fit. let cap = 1 << 20; - let mut entries: Vec = serde_json::from_slice(&recorded).unwrap(); + let mut entries: Vec = crate::store::grant_entries(&recorded); entries.push(json!({"id": "", "pad": ""})); - let room = cap - serde_json::to_vec(&entries).unwrap().len(); + let room = cap - crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&entries).unwrap()).len(); *entries.last_mut().unwrap() = json!({"id": "", "pad": "x".repeat(room)}); - let full = serde_json::to_vec(&entries).unwrap(); + let full = crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&entries).unwrap()); assert_eq!(full.len(), cap); std::fs::write(&grants, &full).unwrap(); run(&mut s, "plugin.install", update.clone()); @@ -4106,7 +4213,7 @@ fn tell_when_waiting(waiting: std::sync::mpsc::Sender<&'static str>) { /// The ids `grants.json` in `dir` holds grants for, and the hash of each. fn stored_grant_hashes(dir: &std::path::Path) -> std::collections::BTreeMap { - let entries: Vec = serde_json::from_slice(&std::fs::read(dir.join("grants.json")).unwrap()).unwrap(); + let entries = crate::store::grant_entries(&std::fs::read(dir.join("grants.json")).unwrap()); entries.iter().map(|e| (e["id"].as_str().unwrap().to_string(), e["hash"].as_str().unwrap().to_string())).collect() } @@ -4408,8 +4515,8 @@ fn a_plain_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off( assert!(!disabled.is_empty()); let file = s.stored_plugin_file(id).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(true); @@ -4629,6 +4736,118 @@ fn read_only_kind_field_and_omission_refuse_without_undo() { assert!(e.contains("`inputs` needs `api` 2"), "{e}"); } +/// A filter at `api` 3 that lists type, images and symbol instances in `writes` changes a type +/// object's characters, an image's transform and opacity and the symbol an instance shows, as one +/// undo step that undo takes back and redo gives again, and the changes are kept when the document +/// is saved and opened. An echo records no undo step; a refused write, and a write by a filter that +/// lists the kinds in `inputs` alone, leave the document and the history as they were. +#[test] +fn a_filter_that_writes_type_images_and_instances_is_one_undo_step() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Node, NodeKind, Symbol}; + use vectorcraft_geom::Affine; + let mut s = session(); + let r = rect(&mut s, 10.0, "#ff0000"); + let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 80, "text": "Hi"}))["id"].as_u64().unwrap()); + let (mut image, mut inst) = (NodeId(0), NodeId(0)); + s.edit("Set up", |d, _| { + for name in ["Sun", "Moon"] { + let art = Arc::new(Node::path(d.alloc_id(), triangle(), Appearance::default())); + d.symbols.push(Symbol { name: name.into(), art, dynamic: false }); + } + let layer = d.layers[0].id; + let im = vectorcraft_doc::ImageObject { + key: "none".into(), + width: 4, + height: 2, + xf: Affine::translate((100.0, 20.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + let n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + image = d.insert(Some(layer), usize::MAX, n).unwrap(); + let n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Sun".into(), xf: Affine::translate((200.0, 20.0)) }); + inst = d.insert(Some(layer), usize::MAX, n).unwrap(); + Ok(()) + }) + .unwrap(); + let manifest = |id: &str, writes: &str| { + format!( + r#"{{"id":"{id}","name":"Revise","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type","image","symbolInstance"]{writes}}}"# + ) + }; + let all = r#","writes":["type","image","symbolInstance"]"#; + let put = |s: &mut Session, src: &str| { + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true})) + }; + let p = |id: &str| json!({"id": id, "ids": [r.0, t.0, image.0, inst.0]}); + let style = match &node(&s, t).kind { + NodeKind::Text(x) => serde_json::to_value(&x.runs[0].style).unwrap(), + _ => panic!("type"), + }; + let edits = json!({"objects": [ + {"id": r.0}, + {"id": t.0, "text": {"runs": [{"text": "Bye now", "style": style}]}}, + {"id": image.0, "transform": [2, 0, 0, 2, 50, 60], "opacity": 0.25}, + {"id": inst.0, "symbolId": "Moon"}, + ]}); + let writer = "test.engine.writes.revise"; + let listed = put(&mut s, &tpl::returning(&manifest(writer, all), &edits.to_string())); + assert_eq!((&listed["api"], &listed["writes"]), (&json!(3), &json!(["type", "image", "symbolInstance"]))); + let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + assert_eq!(run(&mut s, "plugin.run", p(writer))["ids"], json!([r.0, t.0, image.0, inst.0])); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + let check = |d: &vectorcraft_doc::Document| { + let NodeKind::Text(x) = &d.node(t).unwrap().kind else { panic!("type") }; + assert_eq!(x.plain_text(), "Bye now"); + let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("image") }; + assert_eq!((im.xf, d.node(image).unwrap().opacity), (Affine::new([2.0, 0.0, 0.0, 2.0, 50.0, 60.0]), 0.25)); + assert!( + matches!(&d.node(inst).unwrap().kind, NodeKind::SymbolInstance { symbol, xf } if symbol == "Moon" && *xf == Affine::translate((200.0, 20.0))) + ); + }; + let after = s.doc().unwrap().doc.clone(); + check(&after); + assert!(matches!(&after.node(t).unwrap().kind, NodeKind::Text(x) if x.cached_bounds.is_some()), "the type is laid out again"); + assert_eq!(s.doc().unwrap().selection.objects, [r, t, image, inst]); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.doc().unwrap().doc.layers, after.layers); + check(&vectorcraft_format::load(&vectorcraft_format::save(&after, false)).unwrap()); + // An echo changes nothing and records no undo step. + let echo = "test.engine.writes.echo"; + put(&mut s, &tpl::module(&manifest(echo, all), tpl::ECHO, "", 1)); + let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + run(&mut s, "plugin.run", p(echo)); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&doc, undo), "an echo records no undo step"); + // Refused writes leave the document and the history as they were, also when a valid change + // comes before the refused one. + let bad = "test.engine.writes.bad"; + let retyped = json!({"id": t.0, "text": {"runs": [{"text": "Hello again", "style": style}]}}); + for (writes, output, says) in [ + ( + all, + json!({"objects": [{"id": r.0}, retyped, {"id": image.0}, {"id": inst.0, "symbolId": "Nowhere"}]}), + format!("objects[3] (id {}).symbolId: 'Nowhere' is not a symbol in this document", inst.0), + ), + ( + all, + json!({"objects": [{"id": r.0}, {"id": t.0}, {"id": image.0, "opacity": 1.5}, {"id": inst.0}]}), + format!("objects[2] (id {}).opacity: must be a number from 0 to 1", image.0), + ), + ("", edits.clone(), format!("objects[1] (id {}): read-only field 'text.kind' changed", t.0)), + ] { + put(&mut s, &tpl::returning(&manifest(bad, writes), &output.to_string())); + let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute("plugin.run", &p(bad)).unwrap_err().to_string(); + assert!(e.contains(&says), "{says}: {e}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&doc, undo), "{output}"); + } +} + /// The manifest of a filter at `api` 3 with id `id` that asks for the document information /// `context` (a JSON list), with `doc.read` and `doc.write`, and `rest` (keys after a comma, or /// nothing). @@ -4791,6 +5010,73 @@ fn the_document_context_is_capped_and_its_rows_cost_instructions() { refused(&mut s); } +/// A filter that writes type, run while typing is in progress: the plug-in is given the typed +/// text, so an echo keeps it, with Real-time Drawing on and off. An output that is refused leaves +/// the document and the history as they were; with Real-time Drawing on the typing stays in +/// progress, and off it is kept as its own step before the plug-in is given its input. +#[test] +fn a_filter_that_writes_type_is_given_the_typing_in_progress() { + use vectorcraft_doc::NodeKind; + use vectorcraft_tools::{PointerEvent, PointerKind}; + let manifest = |id: &str| { + format!( + r#"{{"id":"{id}","name":"Retype","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type"],"writes":["type"]}}"# + ) + }; + let put = |s: &mut Session, src: &str| { + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + run(s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read", "doc.write"], "replace": true})) + }; + let plain = |s: &Session, t: NodeId| match &node(s, t).kind { + NodeKind::Text(x) => x.plain_text(), + _ => panic!("type"), + }; + let labels = |s: &Session| s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect::>(); + let typing = |real_time: bool| { + let mut s = session(); + s.prefs.real_time_drawing = real_time; + let v = ViewInfo::default(); + let t = NodeId(run(&mut s, "text.create", json!({"x": 100, "y": 100, "text": "A", "size": 20}))["id"].as_u64().unwrap()); + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[t], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + s.tool_text("B", v).unwrap(); + assert_eq!(plain(&s, t), if real_time { "AB" } else { "A" }, "real time {real_time}"); + (s, t) + }; + let bang = "test.engine.writes.typing.bang"; + let bad = "test.engine.writes.typing.bad"; + for real_time in [false, true] { + // The plug-in adds "!" to the text it is given: "AB" or, given only "A", "A". + let (mut s, t) = typing(real_time); + let style = match &node(&s, t).kind { + NodeKind::Text(x) => serde_json::to_value(&x.runs[0].style).unwrap(), + _ => panic!("type"), + }; + let retyped = |text: &str| json!({"objects": [{"id": t.0, "text": {"runs": [{"text": text, "style": style}]}}]}).to_string(); + put(&mut s, &tpl::when_given_else(&manifest(bang), tpl::Given::Input, r#""AB""#, &retyped("AB!"), &retyped("A!"))); + run(&mut s, "plugin.run", json!({"id": bang, "ids": [t.0]})); + assert_eq!(plain(&s, t), "AB!", "real time {real_time}: the plug-in is given the typed text"); + let steps = labels(&s); + assert_eq!(steps[steps.len() - 2..], ["Typing", "Retype"], "real time {real_time}"); + + let (mut s, t) = typing(real_time); + put(&mut s, &tpl::returning(&manifest(bad), &json!({"objects": [{"id": t.0, "transform": [0, 0, 0, 0, 0, 0]}]}).to_string())); + let undo = labels(&s); + let e = s.execute("plugin.run", &json!({"id": bad, "ids": [t.0]})).unwrap_err().to_string(); + assert!(e.contains("transform: flattens the object to a line or a point"), "{e}"); + assert_eq!(plain(&s, t), "AB", "real time {real_time}"); + if real_time { + assert_eq!(labels(&s), undo, "the refused output leaves the history as it was"); + assert!(s.in_interaction(), "and the typing in progress"); + } else { + assert_eq!(labels(&s)[undo.len()..], ["Typing"], "only the typing is kept"); + } + } +} + /// A run past its memory budget fails before the plug-in starts, with the document and undo /// history as they were: a read-only object whose other fields don't fit, a path and a compound /// path that don't fit, and parameters past the input's half of the cap, with objects selected or @@ -5032,7 +5318,7 @@ fn a_grant_covers_only_the_module_it_was_given_to() { // A kept grant that records no hash, or an empty one, covers no module: the stored module isn't // installed at the next start and `plugin.inspect` asks for approval. for entry in [json!({"id": id, "permissions": ["settings", "cache"]}), json!({"id": id, "hash": "", "permissions": ["settings", "cache"]})] { - std::fs::write(folder.0.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap(); + std::fs::write(folder.0.join("grants.json"), crate::store::signed_grants_file(&folder.0, &json!([entry]).to_string())).unwrap(); vectorcraft_plugins::registry::remove(id); vectorcraft_plugins::registry::revoke(id); let mut again = session(); @@ -5063,9 +5349,9 @@ fn grants_this_version_cant_read_are_kept() { let invalid = json!({"id": "bad id/", "hash": "00", "permissions": ["doc.read"]}); let grant = json!({"id": kept, "hash": vectorcraft_plugins::permissions::sha256_hex(&kept_wasm), "permissions": ["doc.read"]}); let grants = folder.0.join("grants.json"); - std::fs::write(&grants, serde_json::to_vec(&json!([future, grant, invalid])).unwrap()).unwrap(); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([future, grant, invalid]).to_string())).unwrap(); std::fs::write(folder.0.join("kept.wasm"), &kept_wasm).unwrap(); - let entries = || serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap(); + let entries = || crate::store::grant_entries(&std::fs::read(&grants).unwrap()); let mut s = session(); s.attach_plugin_store(folder.0.clone()); assert!(vectorcraft_plugins::registry::get(kept).is_some(), "the entries this version can't read don't drop the grant next to them"); @@ -5099,7 +5385,7 @@ fn grants_this_version_cant_read_are_kept() { // and left as it is when even compact would. let cap = 1 << 20; let many: Vec = (0..14_000).map(|i| json!({"id": format!("x.{i}"), "hash": "00", "permissions": ["ui.panel"]})).collect(); - let compact = serde_json::to_vec(&many).unwrap(); + let compact = crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&many).unwrap()); assert!(compact.len() < cap && serde_json::to_vec_pretty(&many).unwrap().len() > cap); std::fs::write(&grants, &compact).unwrap(); run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm), "grant": ["doc.read"]})); @@ -5109,13 +5395,1082 @@ fn grants_this_version_cant_read_are_kept() { let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm)})); assert_eq!(inspected["needsApproval"], json!(false), "the compact file is read back"); run(&mut s, "plugin.remove", json!({"id": added})); - let full = serde_json::to_vec(&json!([{"id": "x.full", "hash": "0".repeat(cap - 100), "permissions": ["ui.panel"]}])).unwrap(); + let full = crate::store::signed_grants_file( + &folder.0, + &json!([{"id": "x.full", "hash": "0".repeat(cap - 250), "permissions": ["ui.panel"]}]).to_string(), + ); + assert!(full.len() < cap); std::fs::write(&grants, &full).unwrap(); run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm), "grant": ["doc.read"]})); assert_eq!(std::fs::read(&grants).unwrap(), full, "not written past the cap"); run(&mut s, "plugin.remove", json!({"id": added})); } +/// Tests: the key store `store` on this thread until the guard is dropped. +struct ThreadKeys; + +impl ThreadKeys { + fn using(store: impl crate::store::grant_keys::GrantKeyStore + 'static) -> Self { + crate::store::grant_keys::THREAD_STORE.set(Some(std::sync::Arc::new(store))); + ThreadKeys + } +} + +impl Drop for ThreadKeys { + fn drop(&mut self) { + crate::store::grant_keys::THREAD_STORE.set(None); + } +} + +/// A key store that is locked or can't be reached. +struct UnreachableKeys; + +impl crate::store::grant_keys::GrantKeyStore for UnreachableKeys { + fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } + + fn set_key(&self, _: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } + + fn generation(&self, _: &std::path::Path) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } + + fn set_generation(&self, _: &std::path::Path, _: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } +} + +/// A memory key store the test keeps a handle on. While `file_generations_fail` is set, it fails to +/// keep the generation that the grants file in the folder is at, and keeps every other one. +struct SharedKeys { + keys: std::sync::Arc, + file_generations_fail: std::sync::Arc, +} + +impl SharedKeys { + fn new(keys: &std::sync::Arc) -> Self { + SharedKeys { keys: keys.clone(), file_generations_fail: std::sync::Arc::default() } + } +} + +impl crate::store::grant_keys::GrantKeyStore for SharedKeys { + fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + crate::store::grant_keys::GrantKeyStore::key(self.keys.as_ref()) + } + + fn set_key(&self, key: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + crate::store::grant_keys::GrantKeyStore::set_key(self.keys.as_ref(), key) + } + + fn generation(&self, folder: &std::path::Path) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + crate::store::grant_keys::GrantKeyStore::generation(self.keys.as_ref(), folder) + } + + fn set_generation(&self, folder: &std::path::Path, generation: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + if self.file_generations_fail.load(std::sync::atomic::Ordering::SeqCst) + && std::fs::read(folder.join("grants.json")).ok().and_then(|bytes| generation_of(&bytes)) == Some(generation) + { + return Err(crate::store::grant_keys::KeyStoreError("the key store can't keep it".into())); + } + crate::store::grant_keys::GrantKeyStore::set_generation(self.keys.as_ref(), folder, generation) + } +} + +/// The generation the grants file `bytes` is at. +fn generation_of(bytes: &[u8]) -> Option { + serde_json::from_slice::(bytes).ok()?["generation"].as_u64() +} + +/// The generation `keys` keeps for the plug-in store `dir`. +fn kept_generation(keys: &crate::store::grant_keys::MemoryGrantKeys, dir: &std::path::Path) -> Option { + crate::store::grant_keys::GrantKeyStore::generation(keys, &crate::store::plugin_store_key(dir)).unwrap() +} + +/// Whether the stored plug-in `id` loads from the plug-in store `dir` at a new start, and whether +/// `plugin.inspect` of `data` (its module) then asks for approval. +fn starts_from(dir: &std::path::Path, id: &str, data: &str) -> (bool, bool) { + vectorcraft_plugins::registry::remove(id); + vectorcraft_plugins::registry::revoke(id); + let mut next = session(); + next.attach_plugin_store(dir.to_path_buf()); + let asks = run(&mut next, "plugin.inspect", json!({"dataBase64": data}))["needsApproval"] == json!(true); + (vectorcraft_plugins::registry::get(id).is_some(), asks) +} + +/// The grants file as VectorCraft wrote it keeps its grants; once it is changed outside VectorCraft +/// it grants nothing, and its plug-ins ask again: a grant given more permissions, a grant added, the +/// MAC taken out or cut short, a MAC made with another key, the file cut short, and the file copied +/// into another plug-in folder. +#[test] +fn a_grants_file_changed_outside_vectorcraft_grants_nothing() { + use crate::store::grant_keys::{GrantKey, MemoryGrantKeys}; + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-signed"); + let copy = crate::tests_links::Folder::new("plugin-store-signed-copy"); + let id = "test.engine.permissions.signed"; + let added = "test.engine.permissions.signedadded"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let added_wasm = asking(added, r#"["doc.read"]"#, &json!({"objects": []})); + let (data, added_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&added_wasm)); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let added_file = folder.0.join(format!("{}.wasm", crate::store::file_stem(added))); + std::fs::write(&added_file, &added_wasm).unwrap(); + let written = std::fs::read(&grants).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file as written keeps its grant"); + + let file: Value = serde_json::from_slice(&written).unwrap(); + let with = |change: &dyn Fn(&mut Value)| { + let mut file = file.clone(); + change(&mut file); + serde_json::to_vec(&file).unwrap() + }; + // At the generation kept for the folder, so that only the MAC tells the file apart. + let generation = file["generation"].as_u64().unwrap(); + let other_key = { + let keys = MemoryGrantKeys::with_key(GrantKey::from_bytes([7; 32])); + crate::store::grant_keys::GrantKeyStore::set_generation(&keys, &crate::store::plugin_store_key(&folder.0), generation).unwrap(); + let _other = ThreadKeys::using(keys); + crate::store::signed_grants_file(&folder.0, &file["grants"].to_string()) + }; + let tag = file["mac"].as_str().unwrap().to_string(); + let changed: [(&str, Vec); 6] = [ + ("a permission added", with(&|f| f["grants"][0]["permissions"] = json!(["doc.read", "doc.write"]))), + ( + "a grant added", + with(&|f| f["grants"].as_array_mut().unwrap().push(json!({"id": added, "hash": sha256_hex(&added_wasm), "permissions": ["doc.read"]}))), + ), + ("the MAC taken out", with(&|f| _ = f.as_object_mut().unwrap().remove("mac"))), + ("the MAC cut short", with(&|f| f["mac"] = json!(tag[..32]))), + ("a MAC made with another key", other_key), + ("the file cut short", written[..written.len() - 2].to_vec()), + ]; + for (what, bytes) in changed { + std::fs::write(&grants, &bytes).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "{what}"); + assert_eq!(starts_from(&folder.0, added, &added_data), (false, true), "{what}"); + assert_eq!(std::fs::read(&grants).unwrap(), bytes, "{what}: the file is left as it is"); + } + + std::fs::write(&grants, &written).unwrap(); + std::fs::write(copy.0.join("copied.wasm"), &wasm).unwrap(); + std::fs::write(copy.0.join("grants.json"), &written).unwrap(); + crate::store::grant_keys::set_current_generation(&crate::store::plugin_store_key(©.0), generation).unwrap(); + assert_eq!(starts_from(©.0, id, &data), (false, true), "copied into another folder"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file left as written keeps its grant"); + std::fs::remove_file(&added_file).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A grants file in the form an older version wrote, a plain list, grants nothing. Approving a +/// plug-in again replaces it with a signed file that holds that grant alone; removing a plug-in takes +/// its entry out and leaves the rest unsigned. +#[test] +fn an_unsigned_grants_file_is_replaced_by_the_next_approval() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-unsigned"); + let id = "test.engine.permissions.unsigned"; + let other = "test.engine.permissions.unsignedother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let entry = |id: &str, wasm: &[u8]| json!({"id": id, "hash": sha256_hex(wasm), "permissions": ["doc.read"]}); + let unsigned = serde_json::to_vec(&json!([entry(id, &wasm), entry(other, &other_wasm)])).unwrap(); + std::fs::write(&grants, &unsigned).unwrap(); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "an unsigned list grants nothing"); + assert_eq!(std::fs::read(&grants).unwrap(), unsigned, "and is left as it is"); + + // `other` isn't installed, so the removal reports it as not found after removing its entry. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.execute("plugin.remove", &json!({"id": other})).is_err()); + assert_eq!(crate::store::grant_entries(&std::fs::read(&grants).unwrap()), vec![entry(id, &wasm)], "the removal takes its entry out"); + assert!(std::fs::read(&grants).unwrap().starts_with(b"["), "and leaves the rest unsigned"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true)); + + std::fs::write(&grants, &unsigned).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true})); + assert_eq!(crate::store::grant_entries(&std::fs::read(&grants).unwrap()), vec![entry(id, &wasm)], "only the new grant is kept"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the approval counts at the next start"); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); +} + +/// With no key in the key store, a signed grants file grants nothing; the next approval makes a key +/// and signs a file that holds that grant alone. +#[test] +fn a_grants_file_without_its_key_is_replaced_by_the_next_approval() { + use crate::store::grant_keys::{GrantKey, GrantKeyStore, MemoryGrantKeys}; + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-no-key"); + let id = "test.engine.permissions.nokey"; + let other = "test.engine.permissions.nokeyother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let list = json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}, {"id": other, "hash": "0".repeat(64), "permissions": ["doc.read"]}]); + let signed = { + let _old = ThreadKeys::using(MemoryGrantKeys::with_key(GrantKey::from_bytes([3; 32]))); + crate::store::signed_grants_file(&folder.0, &list.to_string()) + }; + std::fs::write(&grants, &signed).unwrap(); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + let keys = std::sync::Arc::new(MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "no key, no grant"); + assert!(keys.key().unwrap().is_none(), "reading makes no key"); + assert_eq!(std::fs::read(&grants).unwrap(), signed, "the file is left as it is"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true})); + assert!(keys.key().unwrap().is_some(), "the approval makes a key"); + let ids: Vec = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).iter().map(|e| e["id"].clone()).collect(); + assert_eq!(ids, vec![json!(id)], "only the new grant is kept"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// When the key store can't be reached, no grants file grants anything and none is written: an +/// approval holds for the session only, the stored module isn't replaced, and a grant the file may +/// hold can't be removed. +#[test] +fn an_unreachable_key_store_keeps_approvals_in_the_session() { + let folder = crate::tests_links::Folder::new("plugin-store-unreachable-keys"); + let id = "test.engine.permissions.unreachable"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let written = std::fs::read(&grants).unwrap(); + let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap()); + + let locked = ThreadKeys::using(UnreachableKeys); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the stored grant can't be checked"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let changed = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "error": null})); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read"], "replace": true})); + assert_eq!( + vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()), + Some(vectorcraft_plugins::permissions::sha256_hex(&changed)), + "it runs in this session" + ); + assert_eq!(std::fs::read(&grants).unwrap(), written, "the grants file is left as it is"); + assert_eq!(std::fs::read(&module).unwrap(), wasm, "the store keeps the module its grant covers"); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "{refused}"); + assert_eq!(std::fs::read(&grants).unwrap(), written); + + drop(locked); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the grant counts once the key store can be reached"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); +} + +/// While the key store can't be reached, removing a plug-in fails and leaves it installed when no +/// earlier signed copy of the grants file can be kept from granting it again: with the grants file +/// gone, and with a grants file that doesn't name the plug-in. Once the key store can be reached, the +/// removal raises the generation, and the copy put back grants nothing. +#[test] +fn a_removal_the_key_store_cannot_make_last_fails() { + let folder = crate::tests_links::Folder::new("plugin-store-unreachable-remove"); + let id = "test.engine.permissions.unreachableremove"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap()); + let written = std::fs::read(&grants).unwrap(); + std::fs::remove_file(&grants).unwrap(); + + let locked = ThreadKeys::using(UnreachableKeys); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "with the grants file gone: {refused}"); + assert!(vectorcraft_plugins::registry::get(id).is_some() && module.exists(), "the plug-in stays installed"); + drop(locked); + run(&mut s, "plugin.remove", json!({"id": id})); + std::fs::write(&grants, &written).unwrap(); + std::fs::write(&module, &wasm).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the copy put back grants nothing"); + std::fs::remove_file(&grants).unwrap(); + std::fs::remove_file(&module).unwrap(); + + let other = "test.engine.permissions.unreachableremoveother"; + let plain = vectorcraft_format::base64_encode(&asking(id, "[]", &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + run(&mut s, "plugin.install", json!({"dataBase64": plain})); + let names: Vec = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).iter().map(|e| e["id"].clone()).collect(); + assert_eq!(names, vec![json!(other)], "the grants file doesn't name the plug-in"); + let locked = ThreadKeys::using(UnreachableKeys); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "with a grants file that can't be checked: {refused}"); + assert!(vectorcraft_plugins::registry::get(id).is_some() && module.exists(), "the plug-in stays installed"); + drop(locked); + run(&mut s, "plugin.remove", json!({"id": id})); + run(&mut s, "plugin.remove", json!({"id": other})); +} + +/// A stored plug-in that didn't load, because the grants file of an older version doesn't count, and +/// that keeps no settings or cache, is removed with its module and its entry, and the removal +/// reports it removed. A removal whose stored module can't be deleted fails and keeps its settings. +/// Removing an invalid id leaves the kept generation as it is. +#[test] +fn removing_a_stored_plugin_that_did_not_load_reports_it_removed() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-unloaded-remove"); + let id = "test.engine.permissions.unloadedremove"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let module = folder.0.join(format!("{}.wasm", crate::store::file_stem(id))); + std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}])).unwrap()).unwrap(); + std::fs::write(&module, &wasm).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the unsigned list grants nothing"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert_eq!(s.execute("plugin.remove", &json!({"id": id})).ok(), Some(json!({"removed": id}))); + assert!(!module.exists(), "the module is removed"); + assert!(!grants.exists(), "and its entry"); + assert!(s.execute("plugin.remove", &json!({"id": id})).is_err(), "a second removal finds nothing"); + + // A stored module that can't be deleted (here a folder in its place), of a plug-in that keeps + // settings, fails the removal, and the settings stay for the next try. + std::fs::create_dir_all(module.join("held")).unwrap(); + let data_dir = crate::store::plugin_data_dir(&folder.0, id); + std::fs::create_dir_all(&data_dir).unwrap(); + let setting = data_dir.join("settings.json"); + std::fs::write(&setting, b"{}").unwrap(); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains("can't delete"), "{refused}"); + assert!(module.exists()); + assert_eq!(std::fs::read(&setting).ok().as_deref(), Some(&b"{}"[..]), "the settings are moved back"); + std::fs::remove_dir_all(&module).unwrap(); + assert_eq!(s.execute("plugin.remove", &json!({"id": id})).ok(), Some(json!({"removed": id})), "a second removal deletes them"); + assert!(!data_dir.exists()); + + // An invalid id names no grant: its removal doesn't raise the generation. + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([3; 32]))); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + for invalid in ["", "not an id"] { + assert!(s.execute("plugin.remove", &json!({"id": invalid})).is_err(), "{invalid:?} isn't found"); + assert_eq!(kept_generation(&keys, &folder.0), None, "{invalid:?}: the generation is left as it is"); + } + assert!(s.execute("plugin.remove", &json!({"id": id})).is_err()); + assert_eq!(kept_generation(&keys, &folder.0), Some(2), "a valid id's removal still retires signed copies"); +} + +/// Removing an installed plug-in whose stored module can't be deleted fails, and the plug-in stays +/// installed with its settings and its stored grant; a second removal, once the module can be +/// deleted, removes it. +#[test] +fn removing_an_installed_plugin_whose_module_cant_be_deleted_keeps_it_installed() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([5; 32]))); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-installed-remove-held"); + let id = "test.engine.permissions.installedremoveheld"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let module = folder.0.join(format!("{}.wasm", crate::store::file_stem(id))); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert!(module.is_file(), "the module is stored"); + assert!(s.holds_plugin_grant(id), "and its grant"); + let stored_grant = s.stored_plugin_grant(id); + assert!(stored_grant.is_some(), "in the signed grants file"); + let data_dir = crate::store::plugin_data_dir(&folder.0, id); + std::fs::create_dir_all(&data_dir).unwrap(); + let setting = data_dir.join("settings.json"); + std::fs::write(&setting, b"{}").unwrap(); + + // A folder in the module's place can't be deleted as a file. + std::fs::remove_file(&module).unwrap(); + std::fs::create_dir_all(module.join("held")).unwrap(); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains("can't delete"), "{refused}"); + assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed"); + assert!(module.exists()); + assert!(s.stored_plugin_grant(id) == stored_grant, "the stored grant is kept for the next launch"); + assert_eq!(std::fs::read(&setting).ok().as_deref(), Some(&b"{}"[..]), "the settings are moved back"); + + std::fs::remove_dir_all(&module).unwrap(); + assert_eq!(s.execute("plugin.remove", &json!({"id": id})).ok(), Some(json!({"removed": id})), "a second removal removes it"); + assert!(vectorcraft_plugins::registry::get(id).is_none() && !module.exists() && !data_dir.exists()); + assert!(!s.holds_plugin_grant(id), "and its grant"); +} + +/// A MAC is made over the generation, the grants and the folder, and only the whole MAC of the same +/// key, generation, grants and folder verifies. A key's bytes are never printed. +#[test] +fn a_grants_mac_verifies_only_for_its_key_grants_and_folder() { + use crate::store::grant_keys::{GrantKey, sign, verify}; + let (key, other) = (GrantKey::from_bytes([1; 32]), GrantKey::from_bytes([2; 32])); + let folder = std::path::Path::new("/plug-ins"); + let tag = sign(&key, folder, 4, b"[]").unwrap(); + assert_eq!(tag.len(), 64); + assert!(verify(&key, folder, 4, b"[]", &tag)); + assert!(!verify(&other, folder, 4, b"[]", &tag), "another key"); + assert!(!verify(&key, std::path::Path::new("/other"), 4, b"[]", &tag), "another folder"); + assert!(!verify(&key, folder, 3, b"[]", &tag), "another generation"); + assert!(!verify(&key, folder, 4, b"[ ]", &tag), "other grants"); + assert!(!verify(&key, folder, 4, b"[]", &tag[..62]), "a MAC cut short"); + assert!(!verify(&key, folder, 4, b"[]", &tag.to_uppercase()), "upper case"); + assert!(!verify(&key, folder, 4, b"[]", "")); + assert_eq!(format!("{key:?}"), "GrantKey(..)"); +} + +/// A key store where another process keeps its key between this one's read and its write, and +/// that write does not replace it. +struct KeptFirstElsewhere { + reads: std::sync::Mutex, +} + +impl crate::store::grant_keys::GrantKeyStore for KeptFirstElsewhere { + fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + let mut reads = self.reads.lock().unwrap(); + *reads += 1; + // signing_key and create_key each read once before the write. + Ok((*reads > 2).then(|| crate::store::grant_keys::GrantKey::from_bytes([7; 32]))) + } + + fn set_key(&self, _: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Ok(()) + } + + fn generation(&self, _: &std::path::Path) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + Ok(None) + } + + fn set_generation(&self, _: &std::path::Path, _: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Ok(()) + } +} + +#[test] +fn a_new_grants_key_is_the_one_the_key_store_kept() { + use crate::store::grant_keys::{GrantKey, sign, verify}; + let _keys = ThreadKeys::using(KeptFirstElsewhere { reads: std::sync::Mutex::new(0) }); + let key = crate::store::grant_keys::signing_key().unwrap(); + assert_eq!(key, GrantKey::from_bytes([7; 32]), "the key kept first signs"); + let folder = std::path::Path::new("/plug-ins"); + assert!(verify(&GrantKey::from_bytes([7; 32]), folder, 1, b"[]", &sign(&key, folder, 1, b"[]").unwrap())); +} + +/// An earlier copy of the grants file put back over the current one grants nothing: after one +/// plug-in's grant is revoked while another's stays, and after the last grant is revoked and the +/// file removed. +#[test] +fn an_earlier_grants_file_put_back_grants_nothing() { + let folder = crate::tests_links::Folder::new("plugin-store-earlier-copy"); + let id = "test.engine.permissions.earlier"; + let other = "test.engine.permissions.earlierother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []})); + let (data, other_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&other_wasm)); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + let both = std::fs::read(&grants).unwrap(); + run(&mut s, "plugin.remove", json!({"id": other})); + let one = std::fs::read(&grants).unwrap(); + + std::fs::write(&grants, &both).unwrap(); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true), "the revoked grant doesn't come back"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the earlier copy grants nothing"); + std::fs::write(&grants, &one).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the current file keeps its grant"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); + std::fs::write(&grants, &one).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the last revoked grant doesn't come back"); + + // A grant revoked from a file edited outside VectorCraft doesn't come back with a signed copy + // made before the edit either. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + let mut edited: Value = serde_json::from_slice(&signed).unwrap(); + edited["mac"] = json!("0".repeat(64)); + std::fs::write(&grants, serde_json::to_vec(&edited).unwrap()).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked from the edited file doesn't come back"); +} + +/// A grant revoked while the grants file is gone, or while another file that grants nothing (one +/// without a MAC, or one that doesn't hold a list) is in its place, doesn't come back with the last +/// signed file put back: the revoke raises the generation. A revoke that a signed file without an +/// entry for the plug-in already covers, or one while the key store holds no key, leaves the +/// generation as it is. +#[test] +fn a_grant_revoked_without_a_signed_file_doesnt_come_back_with_one() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-revoke-without-file"); + let id = "test.engine.permissions.revokedgone"; + let other = "test.engine.permissions.revokedgoneother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(other, None), "nothing to revoke in an empty folder"); + assert_eq!(kept(&folder.0), None, "without a key nothing is signed, so no generation is kept"); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + assert_eq!(kept(&folder.0), Some(3)); + assert!(s.store_grant(other, None)); + assert_eq!(kept(&folder.0), Some(3), "the signed file names no grant for it, so nothing is raised"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + + // The file is gone when the grant is revoked. + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(id, None)); + assert_eq!(kept(&folder.0), Some(5)); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked while the file was gone doesn't come back"); + + // A file without a MAC that names no grant for it is in place. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + std::fs::write(&grants, b"[]").unwrap(); + assert!(s.store_grant(id, None)); + assert_eq!(std::fs::read(&grants).unwrap(), b"[]", "the unsigned file is left as it is"); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked over an unsigned file doesn't come back"); + + // A file that doesn't hold a list is in place: it is left as it is, and the revoke holds once it + // raises the generation. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + std::fs::write(&grants, br#""not a list""#).unwrap(); + assert!(s.store_grant(id, None)); + assert_eq!(std::fs::read(&grants).unwrap(), br#""not a list""#, "the file is left as it is"); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked over a file without a list doesn't come back"); +} + +/// Every signed write of the grants file raises the generation by two and is at the generation after +/// that, which the key store then keeps, and the file stays signed; removing the last grant raises +/// the generation too. +#[test] +fn a_signed_grants_write_raises_the_generation_and_stays_signed() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-generation"); + let id = "test.engine.permissions.generation"; + let other = "test.engine.permissions.generationother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(3), Some(3))); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(6), Some(6))); + run(&mut s, "plugin.remove", json!({"id": other})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(9), Some(9))); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file stays signed"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); + assert_eq!(kept(&folder.0), Some(11), "removing the file raises the generation"); +} + +/// Each plug-in folder has a generation of its own. +#[test] +fn two_plugin_folders_keep_their_own_generations() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let first = crate::tests_links::Folder::new("plugin-store-generation-a"); + let second = crate::tests_links::Folder::new("plugin-store-generation-b"); + let ids = ["test.engine.permissions.foldera", "test.engine.permissions.folderaother", "test.engine.permissions.folderb"]; + let data: Vec = ids.iter().map(|id| vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})))).collect(); + let mut a = session(); + a.attach_plugin_store(first.0.clone()); + run(&mut a, "plugin.install", json!({"dataBase64": data[0], "grant": ["doc.read"]})); + run(&mut a, "plugin.install", json!({"dataBase64": data[1], "grant": ["doc.read"]})); + let mut b = session(); + b.attach_plugin_store(second.0.clone()); + run(&mut b, "plugin.install", json!({"dataBase64": data[2], "grant": ["doc.read"]})); + assert_eq!((kept(&first.0), kept(&second.0)), (Some(6), Some(3))); + assert_eq!(starts_from(&first.0, ids[0], &data[0]), (true, false)); + assert_eq!(starts_from(&second.0, ids[2], &data[2]), (true, false)); + let (mut a, mut b) = (session(), session()); + a.attach_plugin_store(first.0.clone()); + b.attach_plugin_store(second.0.clone()); + run(&mut a, "plugin.remove", json!({"id": ids[0]})); + run(&mut a, "plugin.remove", json!({"id": ids[1]})); + run(&mut b, "plugin.remove", json!({"id": ids[2]})); +} + +/// A key store that holds a key and no generation for the folder, as one does the first time this +/// version runs, reads generation 0: a file signed at 0 keeps its grants, and the next write is at 3. +#[test] +fn a_key_without_a_generation_reads_generation_zero() { + use vectorcraft_plugins::permissions::sha256_hex; + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([5; 32]))); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-generation-zero"); + let id = "test.engine.permissions.generationzero"; + let other = "test.engine.permissions.generationzeroother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + assert_eq!(crate::store::grant_keys::current_generation(&crate::store::plugin_store_key(&folder.0)), Ok(0)); + let file = crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]).to_string()); + assert_eq!(generation_of(&file), Some(0)); + std::fs::write(&grants, &file).unwrap(); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file at generation 0 keeps its grant"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + assert_eq!(generation_of(&std::fs::read(&grants).unwrap()), Some(3)); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": other})); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A grant revoked while the file signed at generation 0 is gone doesn't come back with that file +/// put back: with a key kept, the revoke raises the generation from 0. +#[test] +fn a_grant_revoked_while_a_generation_zero_file_is_gone_doesnt_come_back() { + use vectorcraft_plugins::permissions::sha256_hex; + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([6; 32]))); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-generation-zero-revoke"); + let id = "test.engine.permissions.generationzerorevoke"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let file = crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]).to_string()); + assert_eq!(generation_of(&file), Some(0)); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(id, None)); + assert_eq!(kept_generation(&keys, &folder.0), Some(2)); + std::fs::write(&grants, &file).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file at generation 0 grants nothing"); +} + +/// When the key store can't keep the generation of a write, the file written is one generation ahead +/// of the kept one and grants nothing, so its plug-ins ask again; so does the earlier file, since +/// the generation was raised past it before the write, and a file behind the kept generation. +#[test] +fn a_grants_file_whose_generation_was_not_kept_grants_nothing() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let shared = SharedKeys::new(&keys); + let fail = shared.file_generations_fail.clone(); + let _keys = ThreadKeys::using(shared); + let folder = crate::tests_links::Folder::new("plugin-store-generation-unkept"); + let store = crate::store::plugin_store_key(&folder.0); + let id = "test.engine.permissions.generationunkept"; + let other = "test.engine.permissions.generationunkeptother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let written = std::fs::read(&grants).unwrap(); + + fail.store(true, std::sync::atomic::Ordering::SeqCst); + _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]})); + fail.store(false, std::sync::atomic::Ordering::SeqCst); + let ahead = std::fs::read(&grants).unwrap(); + let kept = crate::store::grant_keys::GrantKeyStore::generation(keys.as_ref(), &store).unwrap(); + assert_eq!((generation_of(&ahead), kept), (Some(6), Some(5)), "the file is one generation ahead"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "and grants nothing"); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true)); + + std::fs::write(&grants, &written).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the earlier file grants nothing"); + crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, 3).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file at the kept generation keeps its grant"); + crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, 4).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "a file one generation behind grants nothing"); +} + +/// A revoke over a signed file whose generation wasn't kept raises the generation past the file's, +/// so the file left in place still grants nothing. +#[test] +fn a_revoke_over_a_file_ahead_of_its_generation_leaves_it_granting_nothing() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let shared = SharedKeys::new(&keys); + let fail = shared.file_generations_fail.clone(); + let _keys = ThreadKeys::using(shared); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-revoke-ahead"); + let id = "test.engine.permissions.revokeahead"; + let other = "test.engine.permissions.revokeaheadother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + fail.store(true, std::sync::atomic::Ordering::SeqCst); + _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]})); + fail.store(false, std::sync::atomic::Ordering::SeqCst); + let ahead = std::fs::read(&grants).unwrap(); + assert_eq!((generation_of(&ahead), kept(&folder.0)), (Some(6), Some(5))); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant("test.engine.permissions.revokeaheadnone", None)); + assert_eq!(std::fs::read(&grants).unwrap(), ahead, "the file is left as it is"); + assert_eq!(kept(&folder.0), Some(7), "the generation is past the file's"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file still grants nothing"); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true)); +} + +/// A signed write raises the generation before it writes the file, so a signed write whose generation +/// wasn't kept also leaves the earlier file granting nothing; a revoke over that earlier file put back +/// is then not at the generation of the unkept write, and a copy of that write put back after the +/// revoke grants nothing. +#[test] +fn a_revoke_after_a_write_whose_generation_wasnt_kept_keeps_that_write_granting_nothing() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let shared = SharedKeys::new(&keys); + let fail = shared.file_generations_fail.clone(); + let _keys = ThreadKeys::using(shared); + let folder = crate::tests_links::Folder::new("plugin-store-revoke-after-unkept"); + let ids = ["test.engine.permissions.afterunkept", "test.engine.permissions.afterunkeptother", "test.engine.permissions.afterunkeptthird"]; + let data: Vec = ids.iter().map(|id| vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})))).collect(); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data[0], "grant": ["doc.read"]})); + run(&mut s, "plugin.install", json!({"dataBase64": data[1], "grant": ["doc.read"]})); + let earlier = std::fs::read(&grants).unwrap(); + fail.store(true, std::sync::atomic::Ordering::SeqCst); + _ = s.execute("plugin.install", &json!({"dataBase64": data[2], "grant": ["doc.read"]})); + fail.store(false, std::sync::atomic::Ordering::SeqCst); + let unkept = std::fs::read(&grants).unwrap(); + + std::fs::write(&grants, &earlier).unwrap(); + assert_eq!(starts_from(&folder.0, ids[0], &data[0]), (false, true), "the earlier file grants nothing"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(ids[1], None)); + std::fs::write(&grants, &unkept).unwrap(); + assert_eq!(starts_from(&folder.0, ids[1], &data[1]), (false, true), "the revoked grant doesn't come back"); + assert_eq!(starts_from(&folder.0, ids[2], &data[2]), (false, true), "the unkept write grants nothing"); + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + for id in ids { + _ = s.execute("plugin.remove", &json!({"id": id})); + } +} + +/// A grant whose signed file fits the 1 MiB limit at the generation it is written at is kept, also +/// when the file would not fit with a longer generation number. +#[test] +fn a_grants_file_that_fits_at_its_generation_is_written() { + use vectorcraft_plugins::permissions::sha256_hex; + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-grants-fit"); + let id = "test.engine.permissions.grantsfit"; + let grant = doc_read_grant(id, &sha256_hex(b"module")); + let grants = folder.0.join("grants.json"); + // The file as it is written: compact, since pretty-printed it is larger than the limit. + let size = |pad: &str| serde_json::to_vec(&json!({"version": 1, "generation": 3, "grants": [grant, pad], "mac": "0".repeat(64)})).unwrap().len(); + let pad = "a".repeat((1 << 20) - size("")); + assert_eq!(size(&pad), 1 << 20); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([pad]).to_string())).unwrap(); + assert!(s.store_grant(id, Some(grant)), "the grant is kept"); + let written = std::fs::read(&grants).unwrap(); + assert_eq!((written.len(), generation_of(&written)), (1 << 20, Some(3))); + assert_eq!(kept_generation(&keys, &folder.0), Some(3)); +} + +/// A grants file edited to carry the largest generations doesn't stop a revoke and doesn't move the +/// generation the key store keeps near the limit, so later grants are still kept: the generation +/// comes from the key store alone. +#[test] +fn a_grants_file_at_the_largest_generations_doesnt_stop_a_revoke() { + use vectorcraft_plugins::permissions::sha256_hex; + for carried in [u64::MAX, u64::MAX - 1] { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new(&format!("plugin-store-largest-generation-{}", u64::MAX - carried)); + let id = "test.engine.permissions.largestgeneration"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let edited = |entries: Value| json!({"version": 1, "generation": carried, "grants": entries, "mac": "0".repeat(64)}).to_string(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert_eq!(kept(&folder.0), Some(3)); + + // The edited file names the grant, which the revoke takes out. + std::fs::write(&grants, edited(json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]))).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists(), "generation {carried}: the entry is taken out"); + assert_eq!(kept(&folder.0), Some(5), "generation {carried}: the kept generation is raised from its own value"); + + // The edited file names no grant for it. + std::fs::write(&grants, edited(json!([]))).unwrap(); + assert!(s.store_grant(id, None), "generation {carried}: the revoke is recorded"); + assert_eq!(kept(&folder.0), Some(7), "generation {carried}: the kept generation is raised from its own value"); + + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(10), Some(10)), "generation {carried}"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "generation {carried}: a later grant is kept"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + } +} + +/// A signed write whose generation wasn't kept leaves a file one generation past the kept one. A +/// revoke raises the generation past that file too, so a copy of it put back grants nothing: a revoke +/// from a file without a MAC, one while the file is gone, one over a file that doesn't hold a list, +/// and one that removes the last grant of a signed file. +#[test] +fn a_write_whose_generation_wasnt_kept_grants_nothing_after_a_revoke() { + use vectorcraft_plugins::permissions::sha256_hex; + for path in ["unsigned", "gone", "not-a-list", "signed"] { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let shared = SharedKeys::new(&keys); + let fail = shared.file_generations_fail.clone(); + let _keys = ThreadKeys::using(shared); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new(&format!("plugin-store-unkept-copy-{path}")); + let id = "test.engine.permissions.unkeptcopy"; + let other = "test.engine.permissions.unkeptcopyother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []})); + let (data, other_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&other_wasm)); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + fail.store(true, std::sync::atomic::Ordering::SeqCst); + _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]})); + fail.store(false, std::sync::atomic::Ordering::SeqCst); + let unkept = std::fs::read(&grants).unwrap(); + let before = kept(&folder.0).unwrap(); + assert_eq!(generation_of(&unkept), Some(before + 1), "{path}: the file is one generation past the kept one"); + + let other_grant = json!([{"id": other, "hash": sha256_hex(&other_wasm), "permissions": ["doc.read"]}]).to_string(); + match path { + "unsigned" => std::fs::write(&grants, &other_grant).unwrap(), + "gone" => std::fs::remove_file(&grants).unwrap(), + "not-a-list" => std::fs::write(&grants, br#""not a list""#).unwrap(), + _ => std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &other_grant)).unwrap(), + } + assert!(s.store_grant(other, None), "{path}"); + std::fs::write(&grants, &unkept).unwrap(); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true), "{path}: the revoked grant doesn't come back"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "{path}: the copy grants nothing"); + assert_eq!(kept(&folder.0), Some(before + 2), "{path}: the generation is past the file whose generation wasn't kept"); + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + _ = s.execute("plugin.remove", &json!({"id": id})); + _ = s.execute("plugin.remove", &json!({"id": other})); + } +} + +/// A signed write that fails after raising the generation leaves the generation raised: the file +/// left in place, signed at the generation before the raise, grants nothing and its plug-ins ask +/// again, and so does a copy of it put back after a later write. +#[test] +fn a_grants_write_that_fails_leaves_the_generation_raised() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-write-fails"); + let id = "test.engine.permissions.writefails"; + let other = "test.engine.permissions.writefailsother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let earlier = std::fs::read(&grants).unwrap(); + assert_eq!((generation_of(&earlier), kept(&folder.0)), (Some(3), Some(3))); + + crate::store::GRANTS_WRITE_FAILS.set(true); + let grant = vectorcraft_plugins::permissions::Grant { + id: other.into(), + hash: vectorcraft_plugins::permissions::sha256_hex(b"module"), + permissions: vec![vectorcraft_plugins::permissions::Permission::DocRead], + }; + let written = s.store_grant(other, Some(grant)); + crate::store::GRANTS_WRITE_FAILS.set(false); + assert!(!written, "the write reports a failure"); + assert_eq!(std::fs::read(&grants).unwrap(), earlier, "the file is left as it was"); + assert_eq!(kept(&folder.0), Some(5), "the generation stays raised"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file left in place grants nothing"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(8), Some(8)), "the next write is past the raise"); + assert_eq!(starts_from(&folder.0, other, &other_data), (true, false), "the next write keeps its grant"); + std::fs::write(&grants, &earlier).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the copy from before the raise grants nothing"); + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + _ = s.execute("plugin.remove", &json!({"id": id})); + _ = s.execute("plugin.remove", &json!({"id": other})); +} + +/// A revoke whose signed grants file can't be removed leaves the generation raised: the grant left in +/// the file doesn't come back, and a later removal takes the file away. +#[test] +fn a_revoke_whose_grants_file_cant_be_removed_doesnt_bring_the_grant_back() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-remove-fails"); + let id = "test.engine.permissions.removefails"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let recorded = std::fs::read(&grants).unwrap(); + + crate::store::GRANTS_DELETE_FAILS.set(true); + let revoked = s.store_grant(id, None); + crate::store::GRANTS_DELETE_FAILS.set(false); + assert!(!revoked, "the removal reports a failure"); + assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the file is left as it was"); + assert_eq!(kept(&folder.0), Some(5), "the generation stays raised"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the revoked grant doesn't come back"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(id, None), "a later removal is recorded"); + assert!(!grants.exists(), "and takes the file away"); + std::fs::write(&grants, &recorded).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the copy put back grants nothing"); + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + _ = s.execute("plugin.remove", &json!({"id": id})); +} + +/// The key store's generation for a folder only goes up: a lower one is refused and the kept one +/// stays, while the same one and a higher one are kept. +#[test] +fn the_kept_grants_generation_is_never_lowered() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-generation-lowered"); + let store = crate::store::plugin_store_key(&folder.0); + assert!(crate::store::grant_keys::set_current_generation(&store, 5).is_ok()); + assert!(crate::store::grant_keys::set_current_generation(&store, 3).is_err(), "a lower generation is refused"); + assert_eq!(crate::store::grant_keys::current_generation(&store), Ok(5), "the kept one stays"); + assert!(crate::store::grant_keys::set_current_generation(&store, 5).is_ok(), "the same one is kept"); + assert!(crate::store::grant_keys::set_current_generation(&store, 6).is_ok()); + assert_eq!(crate::store::grant_keys::current_generation(&store), Ok(6)); +} + +/// A kept generation within two of the largest 64-bit value isn't raised: a signed write leaves the +/// file and the generation as they are, and the file keeps its grant. Three below it, the write goes +/// to the largest value. +#[test] +fn a_kept_generation_near_the_largest_value_isnt_raised() { + use vectorcraft_plugins::permissions::{Grant, Permission, sha256_hex}; + for (kept_before, written) in [(u64::MAX - 2, None), (u64::MAX - 3, Some(u64::MAX))] { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new(&format!("plugin-store-generation-near-max-{}", u64::MAX - kept_before)); + let store = crate::store::plugin_store_key(&folder.0); + let id = "test.engine.permissions.nearmax"; + let other = "test.engine.permissions.nearmaxother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, kept_before).unwrap(); + let file = + crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]).to_string()); + std::fs::write(&grants, &file).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "{kept_before}: the file grants"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let grant = Grant { id: other.into(), hash: sha256_hex(b"module"), permissions: vec![Permission::DocRead] }; + assert_eq!(s.store_grant(other, Some(grant)), written.is_some(), "{kept_before}"); + match written { + None => { + assert_eq!(std::fs::read(&grants).unwrap(), file, "{kept_before}: the file is left as it is"); + assert_eq!(kept_generation(&keys, &folder.0), Some(kept_before), "{kept_before}: the generation too"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "{kept_before}: the file keeps its grant"); + } + Some(generation) => { + assert_eq!( + (generation_of(&std::fs::read(&grants).unwrap()), kept_generation(&keys, &folder.0)), + (Some(generation), Some(generation)) + ); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "{kept_before}: the new file keeps the grant"); + } + } + std::fs::remove_file(&grants).unwrap(); + vectorcraft_plugins::registry::remove(id); + vectorcraft_plugins::registry::revoke(id); + } +} + /// The user agreed once: a heavy filter kept in the plug-in store is installed again at the next /// start without asking, with its budget. #[test] @@ -6308,12 +7663,14 @@ fn deferred_move(s: &mut Session) -> NodeId { r } -/// The rectangle a run that hands back what it is given left during [`deferred_move`]: moved, with -/// the interaction ended and the move the last undo step, since the run changed nothing. +/// The rectangle an echoing run during [`deferred_move`] left: moved, with the interaction ended and +/// the move the last undo step, since the run handed the rectangle back as it was and so records +/// none. fn assert_moved_once(s: &Session, r: NodeId) { assert!(!s.in_interaction()); assert_eq!(node(s, r).geometric_bounds().unwrap().x0, 17.0, "the filter was given the moved rectangle"); - assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Move")); + let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect(); + assert_eq!(labels, ["Move", "Rectangle"]); } /// With Real-time Drawing off, `plugin.run` of a filter that calls commands during a drag applies diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 0f3e3ef459..7a339b6cbd 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -216,6 +216,24 @@ fn reset_category_and_all() { assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err()); } +/// `prefs.reset` records each category it reset once, `None` for every category, and a failed +/// reset records nothing. +#[test] +fn prefs_reset_records_the_categories_it_reset() { + let mut s = Session::new(); + assert!(s.take_prefs_resets().is_empty()); + s.execute("prefs.reset", &json!({"category": "general"})).unwrap(); + s.execute("prefs.reset", &json!({"category": "General"})).unwrap(); + assert_eq!(s.take_prefs_resets(), vec![Some("General")]); + assert!(s.take_prefs_resets().is_empty(), "taking clears the list"); + assert!(s.execute("prefs.reset", &json!({"category": "Bogus"})).is_err()); + assert!(s.execute("prefs.reset", &json!({"category": 5})).is_err()); + assert!(s.take_prefs_resets().is_empty(), "a failed reset records nothing"); + s.execute("prefs.reset", &json!({})).unwrap(); + s.execute("prefs.reset", &json!({"category": "Type"})).unwrap(); + assert_eq!(s.take_prefs_resets(), vec![None, Some("Type")]); +} + /// A rectangle made into a guide path; nothing is selected after. fn guide_path(s: &mut Session, x: f64) -> NodeId { let id = square(s, x, 0.0); diff --git a/crates/engine/src/tests/prefs_file.rs b/crates/engine/src/tests/prefs_file.rs index bfe98b901b..98a756b1f7 100644 --- a/crates/engine/src/tests/prefs_file.rs +++ b/crates/engine/src/tests/prefs_file.rs @@ -197,3 +197,14 @@ fn hold_shortcut_preferences() { assert_eq!(restored.key_hold_delay(), 1.0); assert!(!restored.hold_shortcuts); } + +/// Display Print Size at 100% Zoom is on by default, also for saved preferences that predate the +/// key; a saved choice to turn it off stays off. +#[test] +fn display_print_size_is_on_unless_turned_off() { + assert!(Session::new().prefs.display_print_size); + let older: Prefs = serde_json::from_value(json!({"showToolTips": true})).unwrap(); + assert!(older.display_print_size); + let off: Prefs = serde_json::from_value(json!({"displayPrintSize": false})).unwrap(); + assert!(!off.display_print_size); +} diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index d9945fa723..e118dfc272 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -775,6 +775,8 @@ fn an_arc_drag_shows_the_protractor() { let protractors = |s: &mut Session| s.overlays(view()).iter().filter(|o| matches!(o, Overlay::Path { .. })).count(); for (action, shown) in [("line", 0), ("continuousArc", 1), ("sharpArc", 1)] { key(&mut s, ToolKey::Escape); + // With the last path selected, a press on its anchors would edit it instead of drawing. + s.execute("select.set", &json!({"ids": []})).unwrap(); s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap(); click(&mut s, 100.0, 100.0); click(&mut s, 200.0, 100.0); @@ -1372,3 +1374,335 @@ fn path_quick_pen_replaces_the_points_after_keep() { let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); assert_eq!(ends, [pt(0.0, 0.0), pt(100.0, 0.0), pt(200.0, 0.0)]); } + +/// A selected path drawn with `path.quickPen` from `start` through `pieces`, with the Quick Pen +/// chosen and no path being drawn. +fn selected_quick_pen_path(s: &mut Session, start: (f64, f64), pieces: Value) -> NodeId { + let r = s.execute("path.quickPen", &json!({"start": [start.0, start.1], "pieces": pieces})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + quick_pen(s); + id +} + +fn points(s: &Session) -> Vec { + only_path(s).anchors.iter().map(|a| a.p).collect() +} + +fn shift_click(s: &mut Session, x: f64, y: f64) { + let v = view(); + let mods = Mods { shift: true, ..Mods::default() }; + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent { mods, ..PointerEvent::new(kind, x, y) }, v).unwrap(); + } +} + +/// Is segment `i` of `sp` a circular arc: do its points a quarter and three quarters along lie on +/// the circle through its ends and its middle? +fn segment_is_circular(sp: &SubPath, i: usize) -> bool { + use vectorcraft_geom::ParamCurve; + let seg = sp.segment(i); + let (a, b, c) = (seg.eval(0.0), seg.eval(0.5), seg.eval(1.0)); + let d = 2.0 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)); + let sq = |p: Point| p.x * p.x + p.y * p.y; + let center = pt( + (sq(a) * (b.y - c.y) + sq(b) * (c.y - a.y) + sq(c) * (a.y - b.y)) / d, + (sq(a) * (c.x - b.x) + sq(b) * (a.x - c.x) + sq(c) * (b.x - a.x)) / d, + ); + let r = center.distance(a); + [0.25, 0.75].iter().all(|&t| (seg.eval(t).distance(center) - r).abs() < r * 1e-3) +} + +/// With no path being drawn, a drag on an anchor of the selected path moves that anchor alone, in +/// one undo step: at the corner between a line and an arc, the line stays a line and the arc a +/// circular arc. +#[test] +fn a_drag_on_an_anchor_moves_it_and_the_arc_stays_an_arc() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100, "action": "sharpArc", "turn": 90}])); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)]); + let undo = undo_steps(&s); + press(&mut s, &[(200.0, 100.0), (200.0, 80.0), (200.0, 50.0)]); + assert_eq!(undo_steps(&s), undo + 1); + let sp = only_path(&s); + assert_eq!(sp.anchors.iter().map(|a| a.p).collect::>(), [pt(100.0, 100.0), pt(200.0, 50.0), pt(300.0, 100.0)]); + assert!(sp.segment_is_line(0), "{:?}", sp.anchors); + assert!(!sp.segment_is_line(1) && segment_is_circular(&sp, 1), "{:?}", sp.anchors); + assert_eq!(paths(&s).len(), 1, "no new path"); +} + +/// A drag on a segment of the selected path moves that segment's two ends. +#[test] +fn a_drag_on_a_segment_moves_its_ends() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}, {"x": 300, "y": 400}])); + press(&mut s, &[(200.0, 300.0), (200.0, 280.0), (200.0, 250.0)]); + assert_eq!(points(&s), [pt(100.0, 250.0), pt(300.0, 250.0), pt(300.0, 400.0)]); + assert_eq!(paths(&s).len(), 1); +} + +/// A drag that starts on an end of the selected open path moves that end; a click there still +/// goes on drawing from it. +#[test] +fn a_drag_on_an_open_end_moves_it() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}])); + press(&mut s, &[(300.0, 300.0), (320.0, 320.0), (350.0, 350.0)]); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 350.0)]); + assert!(s.doc().unwrap().selection.partial(id).is_some(), "the dragged end is selected"); + click(&mut s, 350.0, 350.0); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "drawing goes on with the path selected whole"); + click(&mut s, 350.0, 450.0); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 350.0), pt(350.0, 450.0)]); +} + +/// A press let go past the drag distance moves what it holds even when no drag event went that +/// far: an inner anchor moves, and an open end moves instead of going on drawing. +#[test] +fn a_release_past_the_drag_distance_moves_the_anchor() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 102.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 100.0)]); + assert_eq!(undo_steps(&s), undo + 1); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 200.0), v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 200.0)]); + assert_eq!(undo_steps(&s), undo + 2); + assert_eq!(paths(&s).len(), 1, "no new path"); +} + +/// A drag on an anchor or a segment that comes back to where it started moves nothing and records +/// no undo step. +#[test] +fn a_drag_back_to_its_start_records_no_undo_step() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + for at in [(200.0, 100.0), (250.0, 100.0)] { + press(&mut s, &[at, (at.0, at.1 + 50.0), at]); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], "press at {at:?}"); + assert_eq!(undo_steps(&s), undo, "press at {at:?}"); + } + // Choosing another tool during such a drag records none either. + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 100.0), v).unwrap(); + s.select_tool("selection", v).unwrap(); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)]); + assert_eq!(undo_steps(&s), undo); +} + +/// When another command changes the selection while the press is down, neither a click nor a drag +/// selects or moves the anchor the press found. +#[test] +fn a_selection_change_during_an_edit_press_stops_it() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for drag in [false, true] { + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let undo = undo_steps(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let y = if drag { 150.0 } else { 100.0 }; + if drag { + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, y), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, y), v).unwrap(); + assert!(s.doc().unwrap().selection.objects.is_empty(), "drag: {drag}"); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 100.0), pt(300.0, 100.0)], "drag: {drag}"); + assert_eq!(undo_steps(&s), undo, "drag: {drag}"); + } +} + +/// When another command edits the path while the press is down, neither a drag nor a release past +/// the drag distance moves the anchor the press found. +#[test] +fn an_edit_during_an_edit_press_stops_the_move() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for (drag, x) in [(true, 90.0), (false, 80.0)] { + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": x, "y": 90})).unwrap(); + let undo = undo_steps(&s); + if drag { + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), [pt(x, 90.0), pt(200.0, 100.0), pt(300.0, 100.0)], "drag: {drag}"); + assert_eq!(undo_steps(&s), undo, "drag: {drag}"); + } +} + +/// An edit made by another command during an anchor drag stays: the rest of the drag and the +/// release move nothing more, and one undo step holds the move as last shown with the edit. +#[test] +fn an_edit_during_an_anchor_drag_stays() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 210.0), v).unwrap(); + assert_eq!(points(&s), [pt(90.0, 90.0), pt(200.0, 150.0), pt(300.0, 100.0)], "the edit and the move as last shown"); + assert_eq!(undo_steps(&s), undo + 1); + assert!(!s.in_interaction(), "the step is committed"); + // Escape after such an edit keeps it too. + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 150.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 80, "y": 80})).unwrap(); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 200.0), v).unwrap(); + assert_eq!(points(&s), [pt(80.0, 80.0), pt(200.0, 150.0), pt(300.0, 150.0)]); + assert!(!s.in_interaction(), "the step is committed"); +} + +/// When another command edits the path while a click is down, the click neither selects the +/// anchor nor goes on drawing from the open end it found. +#[test] +fn an_edit_during_an_edit_click_does_nothing() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let v = view(); + for (x, moved_y) in [(200.0, 90.0), (300.0, 80.0)] { + s.pointer(&PointerEvent::new(PointerKind::Down, x, 100.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 100, "y": moved_y})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, 100.0), v).unwrap(); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "no anchor selected after a click at x = {x}"); + } + // The open end was not taken up, so the next click starts a new path. + click(&mut s, 400.0, 200.0); + assert_eq!(paths(&s).len(), 2); +} + +/// A click on an anchor selects it alone, Shift-click adds another, and Delete (`edit.clear`, the +/// context menu's Delete) then removes both. +#[test] +fn clicks_select_anchors_for_delete() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}])); + let undo = undo_steps(&s); + click(&mut s, 200.0, 100.0); + let picked = |s: &Session| s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked(&s), [(0, 1)]); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(picked(&s), [(0, 1), (0, 2)]); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(picked(&s), [(0, 1)], "Shift-click takes it out again"); + shift_click(&mut s, 300.0, 100.0); + assert_eq!(undo_steps(&s), undo, "selecting is no edit"); + s.execute("edit.clear", &json!({})).unwrap(); + let left: Vec = paths(&s).iter().flat_map(|(_, pd)| pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect(); + assert!(!left.contains(&pt(200.0, 100.0)) && !left.contains(&pt(300.0, 100.0)), "{left:?}"); +} + +/// The first Shift-click on an anchor of a path selected whole selects that anchor alone. +#[test] +fn a_first_shift_click_selects_the_anchor_alone() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + assert!(s.doc().unwrap().selection.partial(id).is_none(), "the path is selected whole"); + shift_click(&mut s, 200.0, 100.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1)]); +} + +/// A drag on a segment moves its two ends alone, also when they are selected with another anchor. +#[test] +fn a_segment_drag_moves_only_its_ends() { + let mut s = session(); + let pieces = json!([{"x": 300, "y": 300}, {"x": 300, "y": 400}, {"x": 100, "y": 400}, {"x": 100, "y": 500}]); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), pieces); + click(&mut s, 300.0, 300.0); + shift_click(&mut s, 300.0, 400.0); + shift_click(&mut s, 100.0, 400.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1), (0, 2), (0, 3)]); + press(&mut s, &[(300.0, 350.0), (320.0, 350.0), (350.0, 350.0)]); + assert_eq!(points(&s), [pt(100.0, 300.0), pt(350.0, 300.0), pt(350.0, 400.0), pt(100.0, 400.0), pt(100.0, 500.0)]); + assert_eq!(paths(&s).len(), 1); +} + +/// A drag on a segment whose two ends are already selected as anchors selects the segment, so +/// Delete then cuts that connection and keeps both anchors. +#[test] +fn a_segment_drag_from_its_selected_ends_selects_the_segment() { + let mut s = session(); + let pieces = json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}, {"x": 400, "y": 100}]); + let id = selected_quick_pen_path(&mut s, (100.0, 100.0), pieces); + click(&mut s, 200.0, 100.0); + shift_click(&mut s, 300.0, 100.0); + let picked = s.doc().unwrap().selection.partial(id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(picked, [(0, 1), (0, 2)]); + press(&mut s, &[(250.0, 100.0), (250.0, 120.0), (250.0, 150.0)]); + assert_eq!(points(&s), [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 150.0), pt(400.0, 100.0)]); + let segments = s.doc().unwrap().selection.segments.get(&id).cloned().unwrap_or_default().into_iter().collect::>(); + assert_eq!(segments, [(0, 1)], "the segment is selected"); + s.execute("edit.clear", &json!({})).unwrap(); + let left: Vec = paths(&s).iter().flat_map(|(_, pd)| pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect(); + for p in [pt(100.0, 100.0), pt(200.0, 150.0), pt(300.0, 150.0), pt(400.0, 100.0)] { + assert!(left.contains(&p), "{p:?} stays: {left:?}"); + } +} + +/// A click on an open end of another path, in front of the selected path, that lies on a segment +/// of the selected path goes on drawing from that end. +#[test] +fn an_open_end_on_a_selected_segment_continues_its_path() { + let mut s = session(); + let id = selected_quick_pen_path(&mut s, (100.0, 300.0), json!([{"x": 300, "y": 300}])); + let r = s.execute("shape.line", &json!({"x1": 200, "y1": 200, "x2": 200, "y2": 300})).unwrap(); + let other = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + click(&mut s, 200.0, 300.0); + click(&mut s, 250.0, 250.0); + let all = paths(&s); + assert_eq!(all.len(), 2, "no new path"); + let ends: Vec = all.iter().find(|(id, _)| *id == other).unwrap().1.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(200.0, 200.0), pt(200.0, 300.0), pt(250.0, 250.0)]); +} + +/// Escape during a drag puts the anchor back, and the release then changes nothing. +#[test] +fn escape_takes_back_an_anchor_drag() { + let mut s = session(); + selected_quick_pen_path(&mut s, (100.0, 100.0), json!([{"x": 200, "y": 100}, {"x": 300, "y": 100}])); + let (before, undo) = (points(&s), undo_steps(&s)); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 150.0), v).unwrap(); + assert_ne!(points(&s), before, "the drag previews"); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 150.0), v).unwrap(); + assert_eq!(points(&s), before); + assert_eq!(undo_steps(&s), undo); + assert_eq!(paths(&s).len(), 1); +} + +/// While a path is being drawn, a press on one of its points adds a piece as before; the editing +/// starts only after Escape ends the path. +#[test] +fn a_press_while_drawing_adds_a_piece() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + click(&mut s, 200.0, 200.0); + press(&mut s, &[(200.0, 100.0), (220.0, 90.0), (250.0, 80.0)]); + assert_eq!(points(&s).len(), 4, "a piece added"); + key(&mut s, ToolKey::Escape); + press(&mut s, &[(200.0, 100.0), (200.0, 70.0), (200.0, 50.0)]); + let got = points(&s); + assert_eq!(got.len(), 4); + assert!(got[1].distance(pt(200.0, 50.0)) < 1e-9, "{got:?}"); +} diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs new file mode 100644 index 0000000000..c1aa77e6a6 --- /dev/null +++ b/crates/engine/src/tests/script_dom.rs @@ -0,0 +1,1906 @@ +//! The script object model: `app`, its documents, their selection and page items. + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +/// A 400 × 300 pt document with two rectangles. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +#[test] +fn app_documents_track_active_tab_and_new_document() { + let mut s = Session::new(); + assert_eq!(log(&mut s, "vc.log(app.documents.length); vc.log(app.typename);"), vec![json!(0), json!("Application")]); + assert!(failure(&mut s, "app.activeDocument;").contains("No active document")); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let out = log( + &mut s, + "var d = app.documents; vc.log(d.length); vc.log(app.activeDocument.width);\ + app.activeDocument = d[0]; vc.log(app.activeDocument.width); vc.log(d[0].parent.typename);\ + vc.log(d[5] === undefined); vc.log(app.activeDocument instanceof Document);\ + var n = d.add(DocumentColorSpace.CMYK, 50, 60, 2);\ + vc.log(d.length); vc.log(app.activeDocument.name === n.name); vc.log(n.documentColorSpace); vc.log(n.height);\ + vc.log(d.getByName(n.name).width);", + ); + let expected = [json!(2), json!(200), json!(400), json!("Application"), json!(true), json!(true), json!(3), json!(true)]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!("DocumentColorSpace.CMYK"), json!(60), json!(50)]); + assert_eq!(s.documents().len(), 3); + assert_eq!(s.active_index(), Some(2)); + assert_eq!(s.documents()[2].doc.artboards.len(), 2); + // A bad argument changes nothing. + assert!(failure(&mut s, "app.documents.add(DocumentColorSpace.RGB, -5);").contains("width")); + assert!(failure(&mut s, "app.documents.add('RGB');").contains("colorSpace")); + assert!(failure(&mut s, "app.documents.add(undefined, 10, 10, 101);").contains("numArtBoards")); + // The spacing is refused at file.new's limit, with the script's own name for it. + let spacing = "app.documents.add(undefined, 10, 10, 2, DocumentArtboardLayout.Row, 100001);"; + assert!(failure(&mut s, spacing).contains("artboardSpacing must be from 0 to 100000 points")); + assert!(failure(&mut s, "app.documents.index('none');").contains("Not found")); + assert_eq!(s.documents().len(), 3); +} + +#[test] +fn page_items_are_live_and_typed_for_all_node_kinds() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + rect(&mut s, 200.0, 200.0, 10.0, 10.0); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, t = [];\ + for (var i = 0; i < p.length; i++) t.push(p[i].typename);\ + vc.log(t.join(','));\ + vc.log(p[3].parent.typename); vc.log(p[0].parent.typename); vc.log(p.parent.typename);\ + p[1].remove(); vc.log(p.length); vc.log(p[-1] === undefined && p[1.5] === undefined && p[99] === undefined);\ + vc.log(p[2] instanceof PathItem && p[2] instanceof PageItem);", + ); + // Topmost first, each group before the objects in it. + assert_eq!( + out, + vec![ + json!("TextFrame,PathItem,GroupItem,PathItem,PathItem"), + json!("GroupItem"), + json!("Layer"), + json!("Document"), + json!(4), + json!(true), + json!(true) + ] + ); +} + +#[test] +fn page_items_list_the_art_inside_a_blend() { + let (mut s, a, b) = doc(); + log(&mut s, "app.activeDocument.pageItems[0].name = 'first';"); + s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 2})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, t = [];\ + for (var i = 0; i < p.length; i++) t.push(p[i].typename);\ + vc.log(t.join(','));\ + vc.log(p.getByName('first').parent.typename); vc.log(p.index('first').typename);", + ); + assert_eq!(out, vec![json!("BlendItem,PathItem,PathItem"), json!("BlendItem"), json!("PathItem")]); +} + +#[test] +fn page_item_geometry_uses_document_coordinates_with_y_up() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[1];\ + vc.log(i.geometricBounds); vc.log(i.position); vc.log([i.left, i.top, i.width, i.height]);\ + app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; vc.log(i.position);\ + app.coordinateSystem = CoordinateSystem.DOCUMENTCOORDINATESYSTEM;\ + i.position = [20, 250]; i.width = 60; vc.log(i.geometricBounds);", + ); + assert_eq!(out[0], json!([10, 280, 40, 240])); + assert_eq!(out[1], json!([10, 280])); + assert_eq!(out[2], json!([10, 280, 30, 40])); + assert_eq!(out[3], json!([10, 20])); + assert_eq!(out[4], json!([20, 250, 80, 210])); +} + +#[test] +fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let other = format!("{:?}", s.active().unwrap().doc.node(b)); + let out = log( + &mut s, + "var i = app.activeDocument.selection[0], h = i.height;\ + i.width = 80; vc.log([i.width, i.height - h]);\ + i.height = 90; vc.log([i.width, i.height]);\ + var g = i.geometricBounds; vc.log([g[2] - g[0], g[1] - g[3]]);", + ); + let pairs: Vec<[f64; 2]> = out.iter().map(|v| [v[0].as_f64().unwrap(), v[1].as_f64().unwrap()]).collect(); + for (got, want) in pairs.iter().zip([[80.0, 0.0], [80.0, 90.0], [80.0, 90.0]]) { + assert!((got[0] - want[0]).abs() < 1e-6 && (got[1] - want[1]).abs() < 1e-6, "{out:?}"); + } + assert_eq!(pairs.len(), 3, "{out:?}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was"); +} + +#[test] +fn convert_coordinate_pair_is_inverse_and_y_up() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, D = CoordinateSystem.DOCUMENTCOORDINATESYSTEM, A = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;\ + var p = d.convertCoordinate([10, 100], A, D); vc.log(p); vc.log(d.convertCoordinate(p, D, A));\ + vc.log(d.convertCoordinate([3, 4], D, D));", + ); + assert_eq!(out, vec![json!([10, 200]), json!([10, 100]), json!([3, 4])]); + assert!( + failure( + &mut s, + "app.activeDocument.convertCoordinate([1, NaN], CoordinateSystem.DOCUMENTCOORDINATESYSTEM, CoordinateSystem.DOCUMENTCOORDINATESYSTEM);" + ) + .contains("finite") + ); + assert!( + failure(&mut s, "app.activeDocument.convertCoordinate([1, 2], 'x', CoordinateSystem.DOCUMENTCOORDINATESYSTEM);").contains("CoordinateSystem") + ); +} + +#[test] +fn ruler_origin_round_trips_without_moving_art() { + let (mut s, a, _) = doc(); + let art = format!("{:?}", s.active().unwrap().doc.layers); + let out = log(&mut s, "var d = app.activeDocument; vc.log(d.rulerOrigin); d.rulerOrigin = [50, 60]; vc.log(d.rulerOrigin);"); + assert_eq!(out, vec![json!([0, 300]), json!([50, 60])]); + assert_eq!(s.active().unwrap().doc.ruler_origin_for(0), vectorcraft_geom::Point::new(50.0, 240.0)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), art); + assert!(s.active().unwrap().doc.node(a).is_some()); + let steps = undo_steps(&s); + log(&mut s, "var d = app.activeDocument; d.rulerOrigin = d.rulerOrigin;"); + assert_eq!(undo_steps(&s), steps, "setting the same origin adds no step"); + assert!(failure(&mut s, "app.activeDocument.rulerOrigin = [1e12, 0];").contains("outside the canvas")); +} + +#[test] +fn page_item_properties_join_one_undo_step() { + let (mut s, a, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[1];\ + i.name = 'box'; i.opacity = 40; i.locked = true; i.locked = false; i.hidden = true; i.hidden = false;\ + vc.log([i.name, i.opacity, i.locked, i.hidden, i.editable, i.zOrderPosition]);\ + vc.log(app.activeDocument.pageItems.getByName('box').name);", + ); + assert_eq!(out, vec![json!(["box", 40, false, false, true, 1]), json!("box")]); + let st = s.active().unwrap(); + let n = st.doc.node(a).unwrap(); + assert_eq!((n.name.as_deref(), (n.opacity * 100.0).round()), (Some("box"), 40.0)); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + let steps = undo_steps(&s); + log(&mut s, "var i = app.activeDocument.pageItems[1]; i.name = 'box'; i.opacity = 40; i.hidden = false;"); + assert_eq!(undo_steps(&s), steps, "values that change nothing add no step"); + for (source, part) in [ + ("app.activeDocument.pageItems[0].opacity = 101;", "opacity"), + ("app.activeDocument.pageItems[0].hidden = 'yes';", "hidden"), + ("app.activeDocument.pageItems[0].width = 0;", "width"), + ("app.activeDocument.pageItems[0].position = [1];", "position"), + ] { + assert!(failure(&mut s, source).contains(part), "{source}"); + } +} + +/// An opacity a graph mark already has still replaces the opacity another mark of its series left on +/// the graph, as `object.setProps` does. +#[test] +fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let r = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let kept = + |s: &Session| s.active().unwrap().doc.node(id).unwrap().extras().graph.as_deref().unwrap().series_paints.first().and_then(|p| p.opacity); + let series = |s: &Session| { + let n = s.active().unwrap().doc.node(id).unwrap().clone(); + let group = n.children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone(); + group.children().unwrap().iter().map(|m| m.id).collect::>() + }; + let marks = series(&s); + s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 50})).unwrap(); + assert_eq!(kept(&s), Some(0.5)); + s.execute("object.setProps", &json!({"id": series(&s)[1].0, "name": "mark"})).unwrap(); + // In a hidden or locked layer the same assignment would still change the graph, so it is refused. + let layer = s.active().unwrap().doc.layers[0].id; + for (on, off) in [ + (json!({"ids": [layer.0], "visible": false}), json!({"ids": [layer.0], "visible": true})), + (json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})), + ] { + s.execute("object.setProps", &on).unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "var m = app.activeDocument.pageItems.getByName('mark'); m.opacity = m.opacity;"); + assert!(e.contains("Cannot edit"), "{on}: {e}"); + assert_eq!(kept(&s), Some(0.5), "{on}"); + assert_eq!(undo_steps(&s), steps, "{on}"); + s.execute("object.setProps", &off).unwrap(); + } + log(&mut s, "app.activeDocument.pageItems.getByName('mark').opacity = 100;"); + assert_eq!(kept(&s), None); +} + +/// Assigning an item the opacity it reports, rounded to four decimals, changes nothing. +#[test] +fn assigning_the_reported_opacity_changes_nothing() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"id": a.0, "opacity": 100.0 / 3.0})).unwrap(); + let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s)); + let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.opacity); i.opacity = i.opacity;"); + assert_eq!(out, vec![json!(33.3333)]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before); + assert_eq!(undo_steps(&s), steps); + // A value close to the reported one but not equal to it is still applied. + s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap(); + let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s)); + log(&mut s, "app.activeDocument.pageItems[1].opacity = 50.00005;"); + assert!(s.active().unwrap().doc.node(a).unwrap().opacity > before, "the assigned opacity was applied"); + assert_eq!(undo_steps(&s), steps + 1); +} + +#[test] +fn selection_assignment_is_atomic_across_invalid_items() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];"); + assert!(e.contains("Cannot select PathItem"), "{e}"); + assert!(s.active().unwrap().selection.objects.is_empty()); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems; vc.log(d.selection instanceof Array && d.selection.length === 0);\ + d.selection = [p[1], p[0], p[1]]; vc.log(d.selection.length); vc.log(app.selection[0].selected);\ + p[0].selected = false; vc.log(d.selection.length);\ + d.selection = p[1]; vc.log(d.selection.length);", + ); + assert_eq!(out, vec![json!(true), json!(2), json!(true), json!(1), json!(1)]); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); + // An item of another document cannot be selected here. + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let e = failure(&mut s, "app.activeDocument.selection = app.documents[0].pageItems[0];"); + assert!(e.contains("Cannot select"), "{e}"); +} + +#[test] +fn a_guide_path_is_not_selected_while_guides_are_locked() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + // The assignment and `selected` refuse the guide path, and the selection stays as it was. + for source in ["app.activeDocument.selection = app.activeDocument.pageItems[1];", "app.activeDocument.pageItems[1].selected = true;"] { + let e = failure(&mut s, source); + assert!(e.contains(&format!("Cannot select PathItem {}", a.0)), "{source}: {e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![b], "{source}"); + } + // With the guides unlocked, the guide path is selected. + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[1];"); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); +} + +#[test] +fn an_inactive_document_changes_without_switching_tabs() { + let (mut s, a, _) = doc(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + log(&mut s, "var d = app.documents[0]; d.pageItems[1].name = 'far'; d.selection = d.pageItems[0];"); + assert_eq!(s.active_index(), Some(1)); + let first = &s.documents()[0]; + assert_eq!(first.doc.node(a).unwrap().name.as_deref(), Some("far")); + assert_eq!(first.selection.objects.len(), 1); +} + +#[test] +fn move_duplicate_and_zorder_obey_parent_order() { + let (mut s, a, b) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, first = p[1];\ + first.zOrder(ZOrderMethod.BRINGTOFRONT); vc.log(first.zOrderPosition);\ + var c = first.duplicate(); vc.log(c.zOrderPosition); vc.log(p.length); vc.log(app.activeDocument.selection.length);\ + c.zOrder(ZOrderMethod.SENDTOBACK); vc.log(c.zOrderPosition);", + ); + assert_eq!(out, vec![json!(2), json!(3), json!(3), json!(1), json!(1)]); + assert_eq!(s.active().unwrap().selection.objects, vec![b], "the selection stays as it was"); + let layer = &s.active().unwrap().doc.layers[0]; + let order: Vec = layer.children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(order[1..], [b, a]); + assert!(failure(&mut s, "app.activeDocument.pageItems[0].zOrder('front');").contains("ZOrderMethod")); +} + +/// The ids of the children of the first layer, bottom first. +fn layer_order(s: &Session) -> Vec { + s.active().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn move_and_duplicate_place_by_element_placement() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + // Before puts it directly above the relative object, after directly below. + let r = + log(&mut s, "var p = app.activeDocument.pageItems; var a = p[2], c = p[0]; vc.log(a.move(c, ElementPlacement.PLACEBEFORE) === undefined);"); + assert_eq!(r, vec![json!(false)]); + assert_eq!(layer_order(&s), [b, c, a]); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[2], ElementPlacement.PLACEAFTER);"); + assert_eq!(layer_order(&s), [a, b, c]); + // At the end of a container is under its contents, at the beginning on top. + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[0].parent, ElementPlacement.PLACEATEND);"); + assert_eq!(layer_order(&s), [c, a, b]); + log(&mut s, "var p = app.activeDocument.pageItems; p[2].move(p[2].parent, ElementPlacement.PLACEATBEGINNING);"); + assert_eq!(layer_order(&s), [a, b, c]); + assert_eq!(undo_steps(&s), steps + 4, "one step for each run that changed the order"); + // Moving to where it is runs nothing. + let steps = undo_steps(&s); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.PLACEBEFORE);"); + assert_eq!(undo_steps(&s), steps); + // Into a group, and a copy beside an object. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.INSIDE);"); + let inside: Vec = s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(inside, [a, b, c]); + let out = log( + &mut s, + "var g = app.activeDocument.pageItems[0], a = app.activeDocument.pageItems[3];\ + var copy = a.duplicate(g, ElementPlacement.PLACEATEND); vc.log(copy.parent.typename); vc.log(copy.zOrderPosition);", + ); + assert_eq!(out, vec![json!("GroupItem"), json!(1)]); + assert_eq!(s.active().unwrap().doc.node(g).unwrap().children().unwrap().len(), 4); + // Refused moves change nothing. + let before = format!("{:?}", s.active().unwrap().doc.layers); + for (source, part) in [ + ("var g = app.activeDocument.pageItems[0]; g.move(app.activeDocument.pageItems[1], ElementPlacement.INSIDE);", "into itself"), + ("var p = app.activeDocument.pageItems; p[1].move(p[2], ElementPlacement.INSIDE);", "cannot hold objects"), + ("var p = app.activeDocument.pageItems; p[1].move(p[2], 'inside');", "ElementPlacement"), + ("var p = app.activeDocument.pageItems; p[1].move();", "relative object"), + ("var p = app.activeDocument.pageItems; p[1].move(app.activeDocument);", "not available yet"), + ("var p = app.activeDocument.pageItems; p[1].duplicate(undefined, ElementPlacement.INSIDE);", "relative object"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + // A locked group takes nothing. + s.execute("object.setProps", &json!({"ids": [g.0], "locked": true})).unwrap(); + rect(&mut s, 0.0, 0.0, 5.0, 5.0); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.INSIDE);"); + assert!(e.contains("hidden or locked"), "{e}"); +} + +#[test] +fn a_copy_goes_beside_its_source() { + let (mut s, a, b) = doc(); + let out = log( + &mut s, + "var a = app.activeDocument.pageItems[1], c = a.duplicate(a, ElementPlacement.PLACEAFTER);\ + vc.log([c.zOrderPosition, a.zOrderPosition]);", + ); + assert_eq!(out, vec![json!([1, 2])]); + let order = layer_order(&s); + assert_eq!(order[1..], [a, b]); + // An object moved directly above or below itself stays where it is with no undo step, and it + // cannot go into itself; a copy cannot go into its source. + let (order, steps) = (layer_order(&s), undo_steps(&s)); + log(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1], ElementPlacement.PLACEAFTER); p[0].move(p[0], ElementPlacement.PLACEBEFORE);"); + assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps)); + assert!(failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1], ElementPlacement.PLACEATBEGINNING);").contains("into itself")); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let e = failure(&mut s, "var p = app.activeDocument.pageItems, g = p[0]; g.duplicate(g, ElementPlacement.INSIDE);"); + assert!(e.contains("into itself"), "{e}"); +} + +#[test] +fn a_copy_that_cannot_be_placed_is_deleted() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 10.0, 50.0, 50.0); + let b = rect(&mut s, 30.0, 30.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("livePaint.make", &json!({})).unwrap(); + s.execute("text.create", &json!({"x": 200, "y": 200, "text": "Hi"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let (steps, step) = (undo_steps(&s), s.active().unwrap().history.step()); + // A Live Paint group takes no type, so the copy is refused after it was made. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, n = p.length, g = p[1], t = p[0], m = '';\ + try { t.duplicate(g, ElementPlacement.INSIDE); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.length === n);", + ); + assert!(out[0].as_str().is_some_and(|m| m.contains("Live Paint takes paths")), "{out:?}"); + assert_eq!(out[1], json!(true)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + // The refused copy leaves no undo step and does not change the document's step. + assert_eq!((undo_steps(&s), s.active().unwrap().history.step()), (steps, step)); +} + +#[test] +fn a_path_inside_a_compound_path_is_not_duplicated() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; vc.log(p[0].typename); p[1].duplicate();"); + assert!(e.contains("Duplicating a path inside a compound path is not available yet"), "{e}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); + // The compound path itself is copied whole. + let out = log(&mut s, "var p = app.activeDocument.pageItems, c = p[0].duplicate(); vc.log([c.typename, p.length]);"); + assert_eq!(out, vec![json!(["CompoundPathItem", 6])]); +} + +#[test] +fn a_path_inside_a_compound_path_is_not_reordered() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + rect(&mut s, 200.0, 200.0, 20.0, 20.0); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, m = [], out = [];\ + for (var i = 0; i < p.length; i++) if (p[i].parent.typename == 'CompoundPathItem') m.push(p[i]);\ + var ways = [ZOrderMethod.BRINGTOFRONT, ZOrderMethod.BRINGFORWARD, ZOrderMethod.SENDBACKWARD, ZOrderMethod.SENDTOBACK];\ + for (var j = 0; j < m.length; j++) for (var k = 0; k < ways.length; k++) {\ + try { m[j].zOrder(ways[k]); out.push('ran'); } catch (e) { out.push(e.message); }\ + }\ + vc.log(m.length); vc.log(out);", + ); + assert_eq!(out[0], json!(2)); + let messages = out[1].as_array().cloned().unwrap_or_default(); + assert_eq!(messages.len(), 8, "{out:?}"); + for m in &messages { + assert!(m.as_str().is_some_and(|m| m.contains("Reordering a path inside a compound path is not available yet")), "{out:?}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); + // The compound path itself still moves. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, c;\ + for (var i = 0; i < p.length; i++) if (p[i].typename == 'CompoundPathItem') c = p[i];\ + var at = c.zOrderPosition; c.zOrder(ZOrderMethod.BRINGTOFRONT); vc.log([at, c.zOrderPosition]);", + ); + assert_eq!(out, vec![json!([1, 2])]); +} + +#[test] +fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + let layer = s.active().unwrap().doc.layers[0].id; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.pageItems[0], m = [d.pageItems[2], d.pageItems[1]];\ + m[0].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\ + m[1].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\ + vc.log([c.typename, c === d.pageItems[2]]);\ + var bad = []; for (var k in c) { try { c[k]; } catch (e) { bad.push(k + ': ' + e.message); } } vc.log(bad);\ + vc.log([c.geometricBounds, c.visibleBounds, c.position, c.width, c.height]);\ + c.left = 5; c.top = 5; c.position = [1, 2]; c.width = 10; c.height = 10; vc.log(c.geometricBounds);", + ); + let zeros = json!([0, 0, 0, 0]); + assert_eq!(out[..3], [json!(3), json!(3), json!(["CompoundPathItem", true])]); + // Every property `for`-`in` lists reads, and the emptied compound path has zero bounds that + // moving or resizing leaves as they are. + assert_eq!(out[3..], [json!([]), json!([zeros, zeros, [0, 0], 0, 0]), zeros]); + let doc = &s.active().unwrap().doc; + assert!(doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); + // Each path went directly above the compound path, the second above the first. + assert_eq!(layer_order(&s), [compound, b, a]); + assert!([a, b].iter().all(|id| doc.parent_of(*id) == Some(layer))); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); +} + +/// `remove()` on the last path of a compound path keeps the compound path, empty, as `move` does, +/// and a document holding it saves, reopens, exports and releases it. +#[test] +fn removing_the_last_path_of_a_compound_path_keeps_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.pageItems[0]; d.pageItems[2].remove(); d.pageItems[1].remove();\ + vc.log([c.typename, d.pageItems.length, c === d.pageItems[0]]);", + ); + assert_eq!(out, vec![json!(["CompoundPathItem", 1, true])]); + let doc = s.active().unwrap().doc.clone(); + assert!(doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); + assert!(s.execute("edit.clear", &json!({"ids": [compound.0], "keepEmpty": 1})).is_err(), "keepEmpty must be a boolean"); + // The native format keeps it, and the other writers and Release Compound Path accept it. + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + assert!(back.node(compound).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.children().is_some_and(|c| c.is_empty()))); + for format in ["svg", "pdf", "vectorcraft"] { + s.execute("document.export", &json!({"format": format})).unwrap_or_else(|e| panic!("{format}: {e}")); + } + s.execute("select.set", &json!({"ids": [compound.0]})).unwrap(); + s.execute("object.compoundPath.release", &json!({})).unwrap(); +} + +/// Clear with `keepEmpty` keeps the emptied compound path also when it deletes direct-selected +/// anchors, and without it deletes the compound path as before. +#[test] +fn clearing_anchors_with_keep_empty_keeps_the_compound_path() { + for keep in [true, false] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + for (id, mode) in [(a, "set"), (b, "add")] { + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": mode})).unwrap(); + } + s.execute("edit.clear", &json!({"keepEmpty": keep})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(b).is_none(), "keepEmpty {keep}: both paths are deleted"); + assert_eq!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), keep, "keepEmpty {keep}"); + } +} + +#[test] +fn a_copy_of_an_object_with_a_large_id_is_the_copy() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The copy's id, 2^53 + 1, is not exact as a number. + let big = 1u64 << 53; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + assert_eq!(a.0, big); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0], c = i.duplicate(); c.name = 'copy'; vc.log(c === i); vc.log(i.name);"); + assert_eq!(out, vec![json!(false), json!("")]); + let d = &s.active().unwrap().doc; + assert_eq!(d.node(NodeId(big + 1)).and_then(|n| n.name.clone()).as_deref(), Some("copy")); + assert_eq!(d.node(a).unwrap().name, None); +} + +#[test] +fn a_grid_by_column_takes_the_number_of_rows() { + let mut s = Session::new(); + // With five artboards in four rows, the columns hold four and one. + for (layout, count, given, rows, cols) in + [("GridByCol", 6, 2, 2, 3), ("RLGridByCol", 6, 2, 2, 3), ("GridByRow", 6, 2, 3, 2), ("GridByCol", 5, 4, 4, 2), ("RLGridByCol", 5, 4, 4, 2)] + { + run(&mut s, &format!("app.documents.add(DocumentColorSpace.RGB, 100, 100, {count}, DocumentArtboardLayout.{layout}, 10, {given});")).unwrap(); + let boards = &s.active().unwrap().doc.artboards; + let distinct = |mut v: Vec| { + v.sort_unstable(); + v.dedup(); + v.len() + }; + let tops = distinct(boards.iter().map(|b| b.rect.y0.round() as i64).collect()); + let lefts = distinct(boards.iter().map(|b| b.rect.x0.round() as i64).collect()); + assert_eq!((tops, lefts), (rows, cols), "{layout} {count}"); + } +} + +#[test] +fn file_new_takes_the_rows_of_a_grid_by_column() { + let mut s = Session::new(); + let first_column = |s: &mut Session, layout: Value| { + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": layout})).unwrap(); + let boards = &s.active().unwrap().doc.artboards; + boards.iter().filter(|b| b.rect.x0.round() as i64 == boards[0].rect.x0.round() as i64).count() + }; + assert_eq!(first_column(&mut s, json!({"layout": "gridByColumn", "rows": 4})), 4); + // Rows take the place of columns given beside them. + assert_eq!(first_column(&mut s, json!({"layout": "gridByColumn", "rows": 4, "columns": 1})), 4); + // A preset keeps and lists the rows, with the columns they give. + use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; + let settings = DocSettings { artboards: 5, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() }; + let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap(); + let listed = settings.to_json(); + assert_eq!((&listed["artboardLayout"]["columns"], &listed["artboardLayout"]["rows"]), (&json!(2), &json!(4)), "{listed}"); + let stored: DocSettings = serde_json::from_value(serde_json::to_value(&settings).unwrap()).unwrap(); + assert_eq!(stored.rows, 4); + // More artboards keep the rows; columns alone, or another layout, replace them. + let more = stored.clone().with_params(&json!({"artboards": 9, "artboardLayout": listed["artboardLayout"]}), "file.new").unwrap(); + assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4); + let by_columns = stored.clone().with_params(&json!({"artboardLayout": {"columns": 1}}), "file.new").unwrap(); + assert_eq!((by_columns.rows, by_columns.boards().iter().filter(|b| b.x0 == by_columns.boards()[0].x0).count()), (0, 5)); + for layout in [json!({"layout": "gridByRow"}), json!("gridByRow")] { + let by_row = stored.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap(); + assert_eq!((by_row.rows, by_row.to_json()["artboardLayout"].get("rows")), (0, None), "{layout}"); + } + let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string(); + assert!(e.contains("rows must be 1 or more"), "{e}"); + for layout in ["gridByRow", "row", "column"] { + let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string(); + assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}"); + } +} + +#[test] +fn a_listed_preset_keeps_more_rows_than_artboards() { + use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; + let settings = DocSettings { artboards: 2, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() }; + let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap(); + let listed = settings.to_json(); + assert_eq!((&listed["artboardLayout"]["columns"], &listed["artboardLayout"]["rows"]), (&json!(1), &json!(4)), "{listed}"); + // Five artboards from the listing fill four rows, not two. + let more = settings.with_params(&json!({"artboards": 5, "artboardLayout": listed["artboardLayout"]}), "file.new").unwrap(); + assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4); +} + +#[test] +fn stale_documents_throw_on_every_member() { + let (mut s, _, _) = doc(); + run(&mut s, "#targetengine keep\nvar d = app.activeDocument, p = d.pageItems, l = p[0].parent;").unwrap(); + for (member, message) in [ + ("d.typename", "Stale document"), + ("d.parent", "Stale document"), + ("p.typename", "Stale document"), + ("p.toString()", "Stale document"), + ("l.typename", "Stale"), + ] { + let e = failure(&mut s, &format!("#targetengine keep\n{member};")); + assert!(e.contains(message), "{member}: {e}"); + } +} + +#[test] +fn hiding_or_locking_a_selected_item_deselects_it() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].hidden = true;"); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + log(&mut s, "app.activeDocument.pageItems[0].locked = true;"); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + +#[test] +fn an_edit_keeps_direct_selected_anchors() { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + let before = s.active().unwrap().selection.clone(); + assert!(!before.anchors.is_empty()); + log(&mut s, "var p = app.activeDocument.pageItems; p[1].duplicate(); p[1].zOrder(ZOrderMethod.SENDTOBACK);"); + assert_eq!(s.active().unwrap().selection.anchors, before.anchors); + assert_eq!(s.active().unwrap().selection.objects, before.objects); + assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); +} + +#[test] +fn an_edit_keeps_the_order_of_a_mixed_selection() { + let (mut s, a, b) = doc(); + rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + let before = s.active().unwrap().selection.clone(); + assert_eq!(before.objects, vec![a, b]); + log(&mut s, "app.activeDocument.pageItems[2].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.anchors.clone()), (before.objects, before.anchors)); +} + +#[test] +fn assigning_the_selection_clears_a_layers_panel_target() { + let (mut s, a, _) = doc(); + s.execute("layer.target", &json!({"id": a.0})).unwrap(); + assert_eq!(s.active().unwrap().selection.target, Some(a)); + log(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[1];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.target), (vec![a], None)); +} + +#[test] +fn an_edit_keeps_a_layers_panel_target() { + let (mut s, a, b) = doc(); + s.execute("layer.target", &json!({"id": a.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.target), (vec![a], Some(a))); + // A targeted layer stays targeted, with its art selected. + let layer = s.active().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.target, sel.objects.len(), sel.objects.contains(&b)), (Some(layer), 4, true)); +} + +#[test] +fn an_edit_keeps_the_current_layer() { + let (mut s, a, b) = doc(); + let first = s.active().unwrap().doc.layers[0].id; + let back = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let layer = |s: &Session| (s.active().unwrap().active_layer, s.active().unwrap().highlighted_rows()); + assert_eq!(layer(&s), (Some(back), vec![back])); + // Moving an object of the first layer selects it for the command; the new layer stays current. + log(&mut s, "app.activeDocument.pageItems[0].left = 50;"); + assert_eq!(layer(&s), (Some(back), vec![back])); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + // With nothing selected and no row highlighted, the layer stays current and no row is highlighted. + s.execute("select.none", &json!({})).unwrap(); + s.execute("layer.setCurrent", &json!({"id": back.0})).unwrap(); + s.execute("layer.highlight", &json!({"ids": [], "mode": "set"})).unwrap(); + assert_eq!(layer(&s), (Some(back), vec![])); + log(&mut s, "app.activeDocument.pageItems[1].left = 120;"); + assert_eq!(layer(&s), (Some(back), vec![])); + assert!(s.active().unwrap().selection.objects.is_empty()); + // Targeting a layer makes it current and leaves another layer's row highlighted; both stay. + s.execute("layer.highlight", &json!({"ids": [first.0], "mode": "set"})).unwrap(); + s.execute("layer.target", &json!({"id": back.0})).unwrap(); + assert_eq!(layer(&s), (Some(back), vec![first])); + log(&mut s, "app.activeDocument.pageItems[0].left = 70;"); + assert_eq!(layer(&s), (Some(back), vec![first])); + // Assigning the selection makes the layer of the selected object current, as a click does. + log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[1];"); + assert_eq!(s.active().unwrap().active_layer, Some(first)); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); +} + +/// A document with a rectangle at the bottom of the stack, then a dynamic symbol instance of two +/// rectangles and an Objects on Path group of one rectangle: (session, instance, group, the +/// group's rectangle). +fn chosen_parts() -> (Session, NodeId, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + rect(&mut s, 300.0, 200.0, 20.0, 20.0); + let (x, y) = (rect(&mut s, 10.0, 10.0, 20.0, 20.0), rect(&mut s, 50.0, 10.0, 20.0, 20.0)); + let id = |v: Value| NodeId(v["id"].as_u64().unwrap()); + let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [x.0, y.0], "type": "dynamic"})).unwrap()); + let member = rect(&mut s, 10.0, 100.0, 20.0, 20.0); + let line = id(s.execute("shape.line", &json!({"x1": 50, "y1": 250, "x2": 350, "y2": 250})).unwrap()); + s.execute("select.set", &json!({"ids": [member.0]})).unwrap(); + let group = id(s.execute("object.objectsOnPath.attach", &json!({"path": line.0})).unwrap()); + (s, inst, group, member) +} + +#[test] +fn an_edit_keeps_an_object_chosen_inside_a_symbol_or_on_a_path() { + let (mut s, inst, group, member) = chosen_parts(); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + let before = s.active().unwrap().selection.clone(); + log(&mut s, "app.activeDocument.pageItems[0].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.symbol_part.clone()), (before.objects, before.symbol_part)); + s.execute("object.objectsOnPath.selectMember", &json!({"member": member.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.on_path_member), (vec![group], Some(member))); +} + +#[test] +fn assigning_the_selection_selects_a_symbol_or_on_path_group_as_a_whole() { + let (mut s, inst, group, member) = chosen_parts(); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + log(&mut s, "var d = app.activeDocument; d.selection = d.selection[0];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.symbol_part.clone()), (vec![inst], None)); + s.execute("object.objectsOnPath.selectMember", &json!({"member": member.0})).unwrap(); + log(&mut s, "var d = app.activeDocument; d.selection = d.selection[0];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.on_path_member), (vec![group], None)); +} + +#[test] +fn a_held_image_stays_the_same_object_when_it_is_embedded() { + let dir = super::links::Folder::new("dom-embed"); + let photo = dir.file("photo.png"); + super::links::write(&photo, &super::links::png(20, 10, [255, 0, 0])); + let mut s = super::links::session(); + let id = super::links::place(&mut s, &photo); + let out = log( + &mut s, + &format!( + "var i = app.activeDocument.pageItems[0]; vc.log(i.typename); vc.run('links.embed', {{ids: [{}]}});\ + var j = app.activeDocument.pageItems[0]; vc.log([i === j, i.typename, i instanceof RasterItem, i instanceof PlacedItem]);", + id.0 + ), + ); + assert_eq!(out, vec![json!("PlacedItem"), json!([true, "RasterItem", true, false])]); +} + +#[test] +fn an_edit_keeps_the_key_object() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.key), (vec![a, b], Some(b))); +} + +#[test] +fn an_edit_keeps_selected_slices() { + let (mut s, a, _) = doc(); + s.execute("object.slice.make", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.slice.select", &json!({"slices": [a.0]})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.slices.clone(), sel.objects.len()), (vec![a], 0)); +} + +#[test] +fn a_startup_preset_alone_gives_its_first_size() { + let mut s = Session::new(); + for profile in ["Web", "Print", "Mobile"] { + let first = crate::cmd::newdoc::category(&s, profile).unwrap().remove(0); + let out = log(&mut s, &format!("var d = app.documents.addDocument('{profile}'); vc.log([d.width, d.height]);")); + let got = (out[0][0].as_f64(), out[0][1].as_f64()); + assert_eq!(got, (Some(first.width), Some(first.height)), "{profile}"); + } +} + +#[test] +fn page_item_members_not_built_yet_throw_on_read_and_assignment() { + let (mut s, _, _) = doc(); + for source in + ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] + { + assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); + } + assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); + // A deleted item or an earlier run's document is stale first. + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.blendingMode;"); + assert!(e.contains("Stale page item"), "{e}"); + run(&mut s, "#targetengine keep\nvar d = app.activeDocument;").unwrap(); + let e = failure(&mut s, "#targetengine keep\nd.layers;"); + assert!(e.contains("Stale document"), "{e}"); +} + +#[test] +fn assigning_the_same_objects_clears_the_key_and_guides() { + let (mut s, a, b) = doc(); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert!(!s.active().unwrap().selection.guides.is_empty()); + log(&mut s, "var d = app.activeDocument; d.selection = [d.pageItems[1], d.pageItems[0]];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.key, sel.guides.len()), (vec![a, b], None, 0)); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + log(&mut s, "app.activeDocument.selection = null;"); + assert!(s.active().unwrap().selection.guides.is_empty()); +} + +/// Assigning `undefined` or a value that is not a page item to the selection throws and keeps it. +#[test] +fn assigning_undefined_to_the_selection_throws_and_keeps_it() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + for source in ["var u; app.activeDocument.selection = u;", "app.activeDocument.selection = undefined;", "app.activeDocument.selection = 1;"] { + let e = failure(&mut s, source); + assert!(e.contains("TypeError"), "{source}: {e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![a, b], "{source}"); + } +} + +#[test] +fn a_page_item_with_a_large_id_keeps_its_id() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + assert_eq!(a.0, big); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.name = 'big'; vc.log(i.name); i.remove();"); + assert_eq!(out, vec![json!("big")]); + assert!(s.active().unwrap().doc.node(a).is_none()); +} + +#[test] +fn only_class_constructors_construct() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var m = [];\ + try { new app.documents.add(); } catch (e) { m.push(e.name); }\ + try { new app.activeDocument.pageItems[0].remove(); } catch (e) { m.push(e.name); }\ + vc.log(m); vc.log(app.documents.length); vc.log(app.activeDocument.pageItems.length);", + ); + assert_eq!(out, vec![json!(["TypeError", "TypeError"]), json!(1), json!(2)]); +} + +#[test] +fn a_document_preset_is_an_instance_of_its_class() { + let mut s = Session::new(); + let out = log(&mut s, "var p = new DocumentPreset(); vc.log(p instanceof DocumentPreset); vc.log(p.typename); vc.log(p.width);"); + assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]); +} + +#[test] +fn the_same_document_or_item_is_the_same_object() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + vc.log([d === app.documents[0], p[1] === p[1], p[1] === d.selection[0], p[0] !== p[1], p === d.pageItems]);", + ); + assert_eq!(out, vec![json!([true, true, true, true, true])]); +} + +#[test] +fn collection_entries_are_found_by_in_and_array_methods() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, d = app.documents;\ + vc.log([0 in p, '1' in p, 2 in p, 0 in d, 1 in d]);\ + vc.log(Array.prototype.map.call(p, function (i) { return i.typename; }).join(','));", + ); + assert_eq!(out, vec![json!([true, true, false, true, false]), json!("PathItem,PathItem")]); +} + +#[test] +fn placement_in_another_document_is_refused() { + let (mut s, _, _) = doc(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + rect(&mut s, 0.0, 0.0, 5.0, 5.0); + let before: Vec = s.documents().iter().map(|d| format!("{:?}", d.doc.layers)).collect(); + for source in [ + "app.documents[0].pageItems[0].move(app.documents[1].pageItems[0], ElementPlacement.PLACEBEFORE);", + "app.documents[0].pageItems[0].duplicate(app.documents[1].pageItems[0].parent, ElementPlacement.INSIDE);", + ] { + let e = failure(&mut s, source); + assert!(e.contains("Cross-document placement is not available"), "{source}: {e}"); + } + let after: Vec = s.documents().iter().map(|d| format!("{:?}", d.doc.layers)).collect(); + assert_eq!(after, before); +} + +#[test] +fn note_is_the_attributes_note() { + let (mut s, a, _) = doc(); + let steps = undo_steps(&s); + let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.note); i.note = 'check bleed'; vc.log(i.note);"); + assert_eq!(out, vec![json!(""), json!("check bleed")]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().extras().attrs.as_ref().unwrap().note, "check bleed"); + assert_eq!(undo_steps(&s), steps + 1); + log(&mut s, "app.activeDocument.pageItems[1].note = 'check bleed';"); + assert_eq!(undo_steps(&s), steps + 1, "the same note adds no step"); + // A number or a Boolean becomes its text, as it does for `name`. + let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; i.note = 5; vc.log([typeof i.note, i.note]); i.note = true; vc.log(i.note);"); + assert_eq!(out, vec![json!(["string", "5"]), json!("true")]); + for value in ["null", "undefined", "{}"] { + assert!(failure(&mut s, &format!("app.activeDocument.pageItems[0].note = {value};")).contains("note must be a string"), "{value}"); + } + assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long")); +} + +#[test] +fn document_preset_applies_only_its_given_fields() { + let mut s = Session::new(); + let out = log( + &mut s, + "var p = new DocumentPreset(); vc.log([p.typename, p.width, p.height, p.numArtboards, p.artboardSpacing, p.artboardLayout]);\ + vc.log(p.colorMode === undefined && p.units === undefined);\ + p.width = 300; p.height = 200; p.numArtboards = 2; p.colorMode = DocumentColorSpace.CMYK; p.title = 'Flyer';\ + p.units = RulerUnits.Millimeters; p.rasterResolution = DocumentRasterResolution.HighResolution;\ + var d = app.documents.addDocument('Print', p); vc.log([d.name, d.width, d.height, d.documentColorSpace, d.rulerUnits]);\ + var e = app.documents.addDocument(DocumentPresetType.BasicRGB); vc.log(e.documentColorSpace);", + ); + assert_eq!(out[0], json!(["DocumentPreset", 612, 792, 1, 20, "DocumentArtboardLayout.GridByRow"])); + assert_eq!(out[1], json!(true)); + assert_eq!(out[2], json!(["Flyer", 300, 200, "DocumentColorSpace.CMYK", "RulerUnits.Millimeters"])); + assert_eq!(out[3], json!("DocumentColorSpace.RGB")); + assert_eq!(s.documents().len(), 2); + assert_eq!(s.documents()[0].doc.artboards.len(), 2); + assert!((s.documents()[0].doc.raster_effects_ppi - 300.0).abs() < 1e-9); + for (source, part) in [ + ("app.documents.addDocument('Nope');", "no startup preset"), + ("var p = new DocumentPreset(); p.numArtboards = 101; app.documents.addDocument('Print', p);", "numArtBoards"), + ("var p = new DocumentPreset(); p.units = RulerUnits.Qs; app.documents.addDocument('Print', p);", "units"), + ( + "var p = new DocumentPreset(); p.transparencyGrid = DocumentTransparencyGrid.TransparencyGridRed; app.documents.addDocument('Print', p);", + "not available yet", + ), + ("app.documents.addDocument('Print', 5);", "DocumentPreset"), + ("app.documents.addDocument(7);", "startup preset"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(s.documents().len(), 2, "a refused preset makes no document"); +} + +#[test] +fn headless_add_document_dialog_fails_without_creating() { + let mut s = Session::new(); + let e = failure(&mut s, "app.documents.addDocument('Print', new DocumentPreset(), true);"); + assert!(e.contains("Dialog unavailable"), "{e}"); + assert!(s.documents().is_empty()); + let out = log(&mut s, "vc.log(app.documents.addDocument('Web', undefined, false).typename);"); + assert_eq!(out, vec![json!("Document")]); + assert_eq!(s.documents().len(), 1); +} + +#[test] +fn setting_selected_keeps_how_the_other_objects_are_selected() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + let anchors = s.active().unwrap().selection.anchors.get(&a).cloned(); + assert!(anchors.is_some()); + log( + &mut s, + "var p = app.activeDocument.pageItems;\ + for (var i = 0; i < p.length; i++) { if (p[i].left == 200) p[i].selected = true; if (p[i].left == 100) p[i].selected = false; }", + ); + let sel = &s.active().unwrap().selection; + assert_eq!(sel.objects, vec![a, c]); + assert_eq!(sel.anchors.get(&a).cloned(), anchors, "the direct-selected anchors stay"); +} + +#[test] +fn add_document_takes_only_a_document_preset() { + let mut s = Session::new(); + for source in [ + "app.documents.addDocument('Print', {width: 500});", + "app.documents.addDocument('Print', {});", + "app.documents.addDocument('Print', {typename: 'DocumentPreset', width: 500});", + "var p = new DocumentPreset(); var q = {}; for (var k in p) q[k] = p[k]; app.documents.addDocument('Print', q);", + "app.documents.addDocument('Print', [612, 792]);", + "app.documents.addDocument('Print', 'DocumentPreset');", + ] { + let e = failure(&mut s, source); + assert!(e.contains("TypeError") && e.contains("presetSettings must be a DocumentPreset"), "{source}: {e}"); + } + assert!(s.documents().is_empty(), "a refused preset makes no document"); + let out = log(&mut s, "var p = new DocumentPreset(); p.width = 500; vc.log(app.documents.addDocument('Print', p).width);"); + assert_eq!(out, vec![json!(500)]); +} + +#[test] +fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { + let dir = std::env::temp_dir().join(format!("vc-script-add-document-profile-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + // A profile with no file gives the defaults. + let out = log(&mut s, "vc.log(app.documents.addDocument('Web').typename);"); + assert_eq!(out, vec![json!("Document")]); + assert_eq!(s.doc().unwrap().links_from, None); + // A script reads the profile's file in the app's own folder. + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + let file = dir.join("Print.vectorcraft").to_string_lossy().to_string(); + log(&mut s, "app.documents.addDocument('Print');"); + assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str())); + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } + std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); + // file.new itself makes the document with the defaults and reports the profile it could not read. + let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert_eq!(r["profileError"]["profile"], "Print", "{r}"); + s.execute("file.close", &json!({})).unwrap(); + let recent = s.execute("file.newPresets", &json!({"category": "Recent"})).unwrap(); + let e = failure(&mut s, "app.documents.addDocument('Print');"); + assert!(e.contains("Error: the New Document profile Print could not be read"), "{e}"); + assert!(s.documents().is_empty(), "the document made with the defaults is put back"); + // A script that catches the error finds nothing changed. + let out = log( + &mut s, + "var p = new DocumentPreset(); p.width = 333;\ + try { app.documents.addDocument('Print', p); } catch (e) { vc.log(e.name); } vc.log(app.documents.length);", + ); + assert_eq!(out, vec![json!("Error"), json!(0)]); + assert_eq!(s.execute("file.newPresets", &json!({"category": "Recent"})).unwrap(), recent, "the Recent sizes are as they were"); + // A startup preset with no profile reads no file. + let out = log(&mut s, "vc.log(app.documents.addDocument('Basic RGB').documentColorSpace);"); + assert_eq!(out, vec![json!("DocumentColorSpace.RGB")]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn add_document_names_a_color_profile_of_the_profile_file_that_cannot_be_used() { + let dir = std::env::temp_dir().join(format!("vc-script-add-document-warning-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } + let file = dir.join("Print.vectorcraft"); + let mut v: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + let broken = format!("Script profile broken {}", std::process::id()); + v["profiles"] = json!({ &broken: {"mime": "application/vnd.iccprofile", "data": "AAAA"} }); + std::fs::write(&file, serde_json::to_vec(&v).unwrap()).unwrap(); + let r = run(&mut s, "vc.log(app.documents.addDocument('Print').typename);").unwrap(); + assert_eq!(r["log"], json!(["Document"])); + let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default(); + let named = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("addDocument: ") && l.contains(&broken)); + assert!(named, "{lines:?}"); + assert_eq!(s.documents().len(), 1); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn add_document_refuses_pixel_preview() { + let mut s = Session::new(); + let e = failure(&mut s, "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.PixelPreview; app.documents.addDocument('Web', p);"); + assert!(e.contains("DocumentPreviewMode.PixelPreview is not available yet"), "{e}"); + assert!(s.documents().is_empty()); + let out = log( + &mut s, + "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.DefaultPreview; vc.log(app.documents.addDocument('Web', p).typename);", + ); + assert_eq!(out, vec![json!("Document")]); +} + +#[test] +fn document_preset_values_count_toward_the_data_a_run_passes() { + // A 64 KiB title, set once, then read or handed to addDocument 32 times: 2 MiB, over a 1 MiB limit. + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20))); + let mut s = Session::new(); + let set = "var p = new DocumentPreset(); p.title = new Array(65537).join('t');"; + let read = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) p.title;")); + let added = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) try {{ app.documents.addDocument('Print', p, 5); }} catch (e) {{}}")); + let within = run(&mut s, &format!("{set} for (var i = 0; i < 8; i++) p.title;")); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + for e in [read, added] { + assert!(e.contains("passed more data"), "{e}"); + } + within.unwrap(); + assert!(s.documents().is_empty()); +} + +#[test] +fn wrappers_go_stale_after_delete_and_undo() { + let (mut s, _, _) = doc(); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.name;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var c = app.activeDocument.pageItems[0].duplicate(); vc.run('edit.undo'); c.position;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p.removeAll(); vc.log(p.length); p[0].name;"); + assert!(e.contains("undefined"), "{e}"); + // A named engine keeps its globals, but an object from an earlier run is stale. + run(&mut s, "#targetengine keep\nvar held = app.activeDocument.pageItems[0];").unwrap(); + let e = failure(&mut s, "#targetengine keep\nheld.name;"); + assert!(e.contains("Stale page item"), "{e}"); +} + +#[test] +fn remove_all_refuses_locked_art_before_deleting_anything() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(e.contains(&b.0.to_string()), "{e}"); + assert_eq!(s.active().unwrap().doc.layers[0].children().unwrap().len(), 2); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + // A locked object inside an unlocked group stops it too. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(e.contains(&g.to_string()), "{e}"); + assert!(s.active().unwrap().doc.node(b).is_some()); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + let out = log(&mut s, "var p = app.activeDocument.pageItems; p.removeAll(); vc.log(p.length);"); + assert_eq!(out, vec![json!(0)]); +} + +#[test] +fn remove_refuses_hidden_or_locked_art_as_remove_all_does() { + let (mut s, a, b) = doc(); + for (on, off) in [ + (json!({"ids": [b.0], "locked": true}), json!({"ids": [b.0], "locked": false})), + (json!({"ids": [b.0], "visible": false}), json!({"ids": [b.0], "visible": true})), + ] { + s.execute("object.setProps", &on).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems[0].remove();"); + assert!(e.contains(&format!("cannot delete hidden or locked objects: {}", b.0)), "{on}: {e}"); + assert!(s.active().unwrap().doc.node(b).is_some(), "{on}"); + s.execute("object.setProps", &off).unwrap(); + } + // A group that holds a locked object is refused too. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems[0].remove();"); + assert!(e.contains(&g.to_string()), "{e}"); + assert!(s.active().unwrap().doc.node(b).is_some()); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].remove();"); + assert!(s.active().unwrap().doc.node(b).is_none()); +} + +/// Art on a locked artboard stays: `remove()` and `removeAll()` throw and delete nothing. +#[test] +fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + // An object on a second, unlocked artboard is not deleted either. + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 300})).unwrap(); + let c = rect(&mut s, 1100.0, 100.0, 50.0, 50.0); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pageItems[1].remove();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", b.0)), "{e}"); + let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()), "{e}"); + let out = + log(&mut s, "try { app.activeDocument.pageItems.removeAll(); } catch (e) { vc.log(e.name); } vc.log(app.activeDocument.pageItems.length);"); + assert_eq!(out, vec![json!("Error"), json!(3)]); + let doc = &s.active().unwrap().doc; + assert!(doc.node(a).is_some() && doc.node(b).is_some() && doc.node(c).is_some()); + assert_eq!(undo_steps(&s), steps); + // `editable` is false for art on the locked artboard and true for art on the unlocked one. + let editable = "var p = app.activeDocument.pageItems; vc.log([p[0].editable, p[1].editable, p[2].editable]);"; + assert_eq!(log(&mut s, editable), vec![json!([true, false, false])]); + lock(&mut s, false); + assert_eq!(log(&mut s, editable), vec![json!([true, true, true])]); + let out = log(&mut s, "var p = app.activeDocument.pageItems; p[1].remove(); p.removeAll(); vc.log(p.length);"); + assert_eq!(out, vec![json!(0)]); +} + +#[test] +fn move_and_duplicate_refuse_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let (order, steps) = (layer_order(&s), undo_steps(&s)); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[0], ElementPlacement.PLACEBEFORE);"); + assert!(e.contains(&format!("Cannot move PathItem {}", a.0)), "{e}"); + assert_eq!((layer_order(&s), undo_steps(&s)), (order.clone(), steps)); + // `duplicate` refuses it too, with or without a relative object. + for source in ["app.activeDocument.pageItems[1].duplicate();", "var p = app.activeDocument.pageItems; p[1].duplicate(p[0]);"] { + let e = failure(&mut s, source); + assert!(e.contains(&format!("Cannot duplicate PathItem {}", a.0)), "{source}: {e}"); + } + assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps)); + lock(&mut s, false); + log(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[0], ElementPlacement.PLACEBEFORE);"); + assert_eq!(layer_order(&s), [b, a]); +} + +#[test] +fn duplicate_refuses_hidden_or_locked_art() { + let (mut s, a, b) = doc(); + for (on, off) in [ + (json!({"ids": [b.0], "locked": true}), json!({"ids": [b.0], "locked": false})), + (json!({"ids": [b.0], "visible": false}), json!({"ids": [b.0], "visible": true})), + ] { + s.execute("object.setProps", &on).unwrap(); + let (order, steps) = (layer_order(&s), undo_steps(&s)); + // With no argument and with a relative object. + for source in ["app.activeDocument.pageItems[0].duplicate();", "var p = app.activeDocument.pageItems; p[0].duplicate(p[1]);"] { + let e = failure(&mut s, source); + assert!(e.contains(&format!("Cannot duplicate PathItem {}", b.0)), "{on} {source}: {e}"); + } + assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps), "{on}"); + s.execute("object.setProps", &off).unwrap(); + } + log(&mut s, "app.activeDocument.pageItems[0].duplicate();"); + let order = layer_order(&s); + assert_eq!(order.len(), 3); + assert!(order.contains(&a) && order.contains(&b)); +} + +#[test] +fn setters_refuse_art_on_a_locked_artboard() { + let (mut s, _, _) = doc(); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems[0], refused = [];\ + var setters = [function(){p.position=[5,5]},function(){p.left=5},function(){p.top=5},\ + function(){p.width=10},function(){p.height=10},function(){p.opacity=50},\ + function(){p.hidden=true},function(){p.locked=true},function(){p.zOrder(ZOrderMethod.SENDTOBACK)}];\ + for(var i=0;i {after:?}"); + // An artboard that is locked, or has no art on it, leaves the menu item dimmed: it does nothing. + let (mut s, _, _) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let steps = undo_steps(&s); + assert_eq!(log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds'); vc.log(1);"), vec![json!(1)]); + assert_eq!(s.active().unwrap().doc.artboards[0].rect, before); + assert_eq!(undo_steps(&s), steps, "locked"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let empty = s.active().unwrap().doc.artboards[0].rect; + assert_eq!(log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds'); vc.log(1);"), vec![json!(1)]); + assert_eq!(s.active().unwrap().doc.artboards[0].rect, empty); + assert_eq!(undo_steps(&s), 0, "no art"); +} + +#[test] +fn an_unknown_menu_command_throws_and_names_it() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');"); + assert!(e.contains("acmeNoSuchMenu"), "{e}"); + assert!(failure(&mut s, "app.executeMenuCommand('Ungroup');").contains("Ungroup"), "names are matched exactly"); + assert!(failure(&mut s, "app.executeMenuCommand(5);").contains("string")); + assert!(failure(&mut s, "app.executeMenuCommand();").contains("string")); + assert!(failure(&mut s, "app.executeMenuCommand(new Array(5000).join('a'));").contains("too long")); + assert_eq!(undo_steps(&s), steps, "nothing changed"); + // With no document open a known menu item does nothing, and an unknown one still throws. + let mut s = Session::new(); + assert_eq!(log(&mut s, "app.executeMenuCommand('selectall'); vc.log(app.documents.length);"), vec![json!(0)]); + assert!(failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');").contains("acmeNoSuchMenu")); +} + +#[test] +fn hostile_dom_values_do_not_reenter_or_exceed_limits() { + let (mut s, _, _) = doc(); + let before = s.active().unwrap().selection.objects.clone(); + // A plain object shaped like an object of the model is not one. + let e = failure(&mut s, "var f = {}; f['\\u0000hostRef'] = ['PathItem', 0, 1, 1]; app.activeDocument.selection = f;"); + assert!(e.contains("not plain data"), "{e}"); + // A getter in a value is refused before it runs. + let out = log( + &mut s, + "var hit = 0, v = {}; Object.defineProperty(v, 0, {get: function () { hit++; return 1; }, enumerable: true});\ + try { app.activeDocument.rulerOrigin = v; } catch (e) { vc.log(e.message); } vc.log(hit);", + ); + assert!(out[0].as_str().is_some_and(|m| m.contains("rulerOrigin")), "{out:?}"); + assert_eq!(out[1], json!(0)); + let e = failure(&mut s, "var a = []; for (var i = 0; i < 10001; i++) a.push(app.activeDocument.pageItems[0]); app.activeDocument.selection = a;"); + assert!(e.contains("at most 10000"), "{e}"); + assert_eq!(s.active().unwrap().selection.objects, before); +} + +#[test] +fn prototype_changes_cannot_forge_a_page_item() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var f = Object.create(PathItem.prototype); var m = '';\ + try { f.name = 'x'; } catch (e) { m = e.message; } vc.log(m);\ + try { PathItem.prototype.name = 'y'; } catch (e) { m = e.message; } vc.log(m); PageItem = null; Document.prototype.pageItems = null;\ + vc.log(Object.isFrozen(PathItem.prototype) || !Object.isExtensible(PathItem.prototype));\ + vc.log(app.activeDocument.pageItems.length);\ + try { new PathItem(); } catch (e) { m = e.name; } vc.log(m);", + ); + assert_eq!(out, vec![json!("this is not a page item"), json!("this is not a page item"), json!(true), json!(2), json!("TypeError")]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().name, None); +} + +#[test] +fn unsupported_members_say_so() { + let (mut s, _, _) = doc(); + assert!(failure(&mut s, "app.activeDocument.layers;").contains("Document.layers is not available yet")); +} + +/// A script that names each visible selected object after its place in `app.selection`, testing +/// the members it uses with `hasOwnProperty` and `propertyIsEnumerable` first. A member that is not +/// available yet, such as `blendingMode`, is read only when `hasOwnProperty` reports it, so it is +/// never read. +const NAME_PICKED: &str = "\ + var picked = app.selection, k = picked.length, named = 0;\ + if (!k) alert('Select something first.');\ + while (k--) {\ + var obj = picked[k];\ + var usable = obj.propertyIsEnumerable('name') && obj.hasOwnProperty('hidden') && !obj.hidden;\ + if (obj.hasOwnProperty('blendingMode') && obj.blendingMode) usable = false;\ + if (usable) { obj.name = 'picked ' + k; named += 1; }\ + }\ + if (picked.length && named < picked.length) alert('Some objects were skipped.');"; + +#[test] +fn a_script_that_checks_has_own_property_changes_every_kind_of_selected_object() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + let path = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let (g1, g2) = (rect(&mut s, 50.0, 10.0, 20.0, 20.0), rect(&mut s, 80.0, 10.0, 20.0, 20.0)); + s.execute("select.set", &json!({"ids": [g1.0, g2.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let text = NodeId(s.execute("text.create", &json!({"x": 10, "y": 100, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + let (c1, c2) = (rect(&mut s, 150.0, 10.0, 20.0, 20.0), rect(&mut s, 155.0, 15.0, 20.0, 20.0)); + s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.active().unwrap().selection.objects[0]; + let objects = [path, group, text, compound]; + s.execute("select.set", &json!({"ids": objects.iter().map(|n| n.0).collect::>()})).unwrap(); + let names = |s: &Session| -> Vec> { + let d = &s.active().unwrap().doc; + objects.iter().map(|n| d.node(*n).unwrap().name.clone()).collect() + }; + let before = names(&s); + let steps = undo_steps(&s); + // The run shows no alert: without an answer for one, it would stop there. + let r = run(&mut s, NAME_PICKED).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["dialogs"], json!([]), "{r}"); + let after = names(&s); + assert!(after.iter().all(|n| n.as_deref().is_some_and(|n| n.starts_with("picked "))), "every kind was named: {after:?}"); + assert_eq!(after.iter().collect::>().len(), objects.len(), "each got its own name: {after:?}"); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(names(&s), before); + // Opacity reads and writes on every kind too: each object goes to its own value, read back from the script. + s.execute("select.set", &json!({"ids": objects.iter().map(|n| n.0).collect::>()})).unwrap(); + let opacities = |s: &Session| -> Vec { + let d = &s.active().unwrap().doc; + objects.iter().map(|n| d.node(*n).unwrap().opacity).collect() + }; + let before = opacities(&s); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var sel = app.activeDocument.selection, read = [];\ + for (var i = 0; i < sel.length; i++) { sel[i].opacity = 20 + 10 * i; read.push(sel[i].opacity); }\ + vc.log(read);", + ); + assert_eq!(out, vec![json!([20, 30, 40, 50])]); + let after = opacities(&s); + assert!(after.iter().zip(&before).all(|(a, b)| a < b), "every kind got a lower opacity: {before:?} -> {after:?}"); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(opacities(&s), before); +} + +#[test] +fn the_selection_is_an_empty_list_when_nothing_is_selected() { + let (mut s, _, _) = doc(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + let out = log(&mut s, "var d = app.activeDocument; vc.log([d.selection instanceof Array, d.selection.length, app.selection.length]);"); + assert_eq!(out, vec![json!([true, 0, 0])]); + let steps = undo_steps(&s); + let r = s.execute("script.run", &json!({"source": NAME_PICKED, "name": "t.js", "answers": [{"kind": "alert", "value": "ok"}]})).unwrap(); + assert_eq!(r["dialogs"][0]["message"], json!("Select something first."), "{r}"); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn page_items_report_their_available_members_as_their_own() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems[0], d = app.activeDocument, keys = [];\ + for (var k in p) keys.push(k);\ + vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\ + Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\ + app.hasOwnProperty('activeDocument')]);\ + vc.log([p.hasOwnProperty('blendingMode'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\ + p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\ + vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('blendingMode')]);", + ); + assert_eq!(out[0], json!([true, true, true, true, true, true, true])); + // Members that are not available yet, unknown names and inherited ones are not the object's own. + assert_eq!(out[1], json!([false, false, false, false, false, false])); + // `for`-`in` lists the properties, not the methods or the members that are not available yet. + assert_eq!(out[2], json!([true, true, -1, -1])); +} + +/// A name a page item class's prototype has, such as `constructor`, is not an object's own, and a +/// script cannot put a name on the prototype. +#[test] +fn a_property_added_to_a_class_prototype_is_not_an_objects_own() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems[0]; PathItem.prototype.foo = 1; PageItem.prototype.bar = 2;\ + vc.log([PathItem.prototype.foo === undefined, PageItem.prototype.bar === undefined, 'foo' in p]);\ + vc.log([p.hasOwnProperty('foo'), p.hasOwnProperty('bar'), p.propertyIsEnumerable('foo'), p.hasOwnProperty('constructor')]);", + ); + assert_eq!(out, vec![json!([true, true, false]), json!([false, false, false, false])]); +} + +/// Reading every property `for`-`in` lists calls each getter, and each call counts against the run: +/// a loop of such reads ends at `maxFuel` and at `script.stop`. +#[test] +fn reading_every_listed_property_is_charged_and_can_be_stopped() { + let (mut s, _, _) = doc(); + let mut calls = |body: &str| { + let source = format!("var p = app.activeDocument.pageItems[0], n = 0; for (var k in p) {{ {body} n++; }} vc.log(n);"); + let r = run(&mut s, &source).unwrap_or_else(|e| panic!("{e}")); + (r["hostCalls"].as_u64().unwrap(), r["log"][0].as_u64().unwrap()) + }; + let (listed, n) = calls(""); + let (read, m) = calls("p[k];"); + assert_eq!(n, m); + assert!(n > 10, "{n} properties"); + assert!(read >= listed + n, "{listed} host calls to list, {read} to read {n} properties"); + let spin = "var p = app.activeDocument.pageItems[0]; while (true) for (var k in p) p[k];"; + let e = s.execute("script.run", &json!({"source": spin, "name": "t.js", "maxFuel": 200_000})).unwrap_err(); + assert!(e.to_string().ends_with("(limit)"), "{e}"); + s.script_frames = true; + assert_eq!(run(&mut s, spin).unwrap()["running"], true); + assert!(s.script_pump().is_none()); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert!(s.script_pump().unwrap().is_err()); + assert!(!s.script_running()); +} + +/// `pageItems` lists art topmost first, and the selection lists the selected objects in that +/// order whatever order they were selected or made in. +#[test] +fn page_items_and_the_selection_list_the_topmost_object_first() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "bottom"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "top"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + assert_eq!(s.active().unwrap().selection.objects, vec![a, b], "picked bottom first"); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log([d.pageItems[0].name, d.pageItems[1].name, d.selection[0].name, d.selection[1].name]);\ + d.selection = [d.pageItems[1], d.pageItems[0]]; vc.log(d.selection[0].name);", + ); + assert_eq!(out, vec![json!(["top", "bottom", "top", "bottom"]), json!("top")]); + // An object made last and sent to the back comes after the others it is selected with. + let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "last"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.pageItems.getByName('last'); c.zOrder(ZOrderMethod.SENDTOBACK);\ + d.selection = null; c.selected = true; d.pageItems.getByName('top').selected = true;\ + vc.log([d.selection[0].name, d.selection[1].name, d.pageItems[2].name]);", + ); + assert_eq!(out, vec![json!(["top", "last", "last"])]); +} + +/// The selection lists a group before the objects in it, in `pageItems`' order, and reading it +/// costs as much in a large document as in a small one. +#[test] +fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a.0, c.0, group]})).unwrap(); + let source = "var d = app.activeDocument, want = [], got = [];\ + for (var i = 0; i < d.pageItems.length; i++) if (d.pageItems[i].selected) want.push(d.pageItems[i].typename + i);\ + for (var i = 0; i < d.pageItems.length; i++) for (var j = 0; j < d.selection.length; j++)\ + if (d.selection[j] === d.pageItems[i]) got[j] = d.pageItems[i].typename + i;\ + vc.log([want, got]);"; + let out = log(&mut s, source); + assert_eq!(out[0][0], out[0][1], "the selection is in pageItems' order"); + assert_eq!(out[0][0].as_array().map(Vec::len), Some(3)); + // Each pass edits the document, so nothing kept from the last read can be reused. + let edits = "var d = app.activeDocument; for (var i = 0; i < 50; i++) d.selection[0].opacity = 50 + i % 2;"; + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + let small = run(&mut s, edits).unwrap()["fuelUsed"].as_u64().unwrap(); + // 3 objects doubled 11 times: 6,144. + s.execute("select.all", &json!({})).unwrap(); + for _ in 0..11 { + s.execute("edit.duplicate", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + } + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let large = run(&mut s, edits); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let large = large.unwrap_or_else(|e| panic!("the reads in a large document went over: {e}"))["fuelUsed"].as_u64().unwrap(); + assert_eq!(small, large); +} + +/// A collection read with a name gives what `getByName` gives, and throws as it does for no match. +#[test] +fn a_collection_read_with_a_name_gives_the_named_object() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "n"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems, m = [];\ + vc.log([p['n'] === p.getByName('n'), p['n'].name, 'n' in p, 'nosuch' in p, p['length'] === p.length]);\ + vc.log([app.documents[d.name] === d, d.name in app.documents, 'nosuch' in app.documents]);\ + try { p['nosuch']; } catch (e) { m.push(e.message); }\ + try { app.documents.nosuch; } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]); +} + +/// `opacity`, `hidden`, `locked` and the position and size setters on an object in a hidden or +/// locked layer throw and the run changes nothing, while its name and note still change; an object +/// that is hidden or locked itself takes them. +#[test] +fn setters_refuse_art_in_a_hidden_or_locked_layer() { + let (mut s, a, b) = doc(); + let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0); + rect(&mut s, 300.0, 200.0, 20.0, 20.0); + for (id, name) in [(a, "locked"), (b, "free"), (c, "closed")] { + s.execute("object.setProps", &json!({"ids": [id.0], "name": name})).unwrap(); + } + for (on, off) in [ + (json!({"ids": [layer.0], "visible": false}), json!({"ids": [layer.0], "visible": true})), + (json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})), + ] { + s.execute("object.setProps", &on).unwrap(); + // `hidden` and `locked` are refused even when the value is the one the object has. + for set in [ + "opacity = 50", + "hidden = true", + "hidden = false", + "locked = true", + "locked = false", + "left = 5", + "top = 5", + "position = [5, 5]", + "width = 10", + "height = 10", + "zOrder(ZOrderMethod.BRINGTOFRONT)", + ] { + let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); + // The change made before the refusal is put back with the rest of the run. + let e = failure(&mut s, &format!("var p = app.activeDocument.pageItems; p.getByName('free').opacity = 20; p.getByName('closed').{set};")); + assert!(e.contains(&format!("Cannot edit PathItem {}", c.0)), "{on} {set}: {e}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{on} {set}"); + assert_eq!(undo_steps(&s), steps, "{on} {set}"); + } + let out = log( + &mut s, + "var c = app.activeDocument.pageItems.getByName('closed'); c.note = 'n'; c.name = 'renamed'; c.opacity = c.opacity;\ + vc.log([c.name, c.note, c.opacity]); c.name = 'closed'; c.note = '';", + ); + assert_eq!(out, vec![json!(["renamed", "n", 100])], "{on}"); + s.execute("object.setProps", &off).unwrap(); + } + s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "visible": false})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems; p.getByName('locked').opacity = 50; p.getByName('free').opacity = 40;\ + vc.log([p.getByName('locked').opacity, p.getByName('free').opacity]);", + ); + assert_eq!(out, vec![json!([50, 40])]); +} + +/// `name` takes a number or a Boolean as the text `String` gives it, and nothing else. +#[test] +fn a_name_given_as_a_number_or_a_boolean_becomes_its_text() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[1]; i.name = 5; vc.log([typeof i.name, i.name]); i.name = 2.5e-7; vc.log(i.name);\ + i.name = true; vc.log(i.name);", + ); + assert_eq!(out, vec![json!(["string", "5"]), json!("2.5e-7"), json!("true")]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().name.as_deref(), Some("true")); + for value in ["null", "undefined", "{}"] { + assert!(failure(&mut s, &format!("app.activeDocument.pageItems[1].name = {value};")).contains("name must be a string"), "{value}"); + } +} + +/// `String` of an object of the object model names its class, and its name when it has one. +#[test] +fn objects_of_the_object_model_print_their_class_and_name() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "Logo"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + vc.log([String(p[0]), String(p[1]), '' + p[1], p[1].toString(), String(p[1].parent) === '[Layer ' + p[1].parent.name + ']']);\ + vc.log([String(d) === '[Document ' + d.name + ']', String(app), String(p), String(app.documents)]);", + ); + assert_eq!(out[0], json!(["[PathItem ]", "[PathItem Logo]", "[PathItem Logo]", "[PathItem Logo]", true])); + assert_eq!(out[1], json!([true, "[Application]", "[PageItems]", "[Documents]"])); +} + +/// `activeDocument`, `documents` and `selection` without `app.` read the application's members, and +/// assigning one assigns the member: `selection` selects, `documents` keeps its value. +#[test] +fn the_application_members_can_be_named_without_app() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log( + &mut s, + "vc.log([activeDocument === app.activeDocument, documents === app.documents, documents.length,\ + selection.length, selection[0] === app.activeDocument.pageItems[1], typeof activeDocument]);", + ); + assert_eq!(out, vec![json!([true, true, 1, 1, true, "object"])]); + let out = log( + &mut s, + "var d = app.activeDocument; selection = null; vc.log(d.selection.length);\ + selection = [d.pageItems[0], d.pageItems[1]]; vc.log(d.selection.length);\ + app.selection = d.pageItems[0]; vc.log([d.selection.length, selection[0] === d.pageItems[0]]);\ + var selection = d.selection; documents = 5; activeDocument = d; vc.log([selection.length, typeof documents]);", + ); + assert_eq!(out, vec![json!(0), json!(2), json!([1, true]), json!([1, "object"])]); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + // A top-level `var selection = []` clears the selection; a push goes to a list nobody keeps. + let out = log(&mut s, "var selection = []; selection.push(app.activeDocument.pageItems[0]); vc.log(selection.length);"); + assert_eq!(out, vec![json!(0)]); + assert!(s.active().unwrap().selection.objects.is_empty()); + assert!(failure(&mut s, "activeDocument = 5;").contains("not a Document")); + let e = failure(&mut s, "'use strict'; documents = 5;"); + assert!(e.contains("TypeError") && e.contains("cannot assign to property 'documents': it has only a getter"), "{e}"); + // With no document open, reading `activeDocument` throws as `app.activeDocument` does. + let mut s = Session::new(); + assert!(failure(&mut s, "activeDocument;").contains("No active document")); +} + +/// Assigning to a name a collection does not have throws as reading it does, and assigning an +/// index does not replace the object there. +#[test] +fn assigning_a_name_a_collection_lacks_throws() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + for source in ["app.activeDocument.pageItems.qux = 4;", "app.documents.qux = 4;"] { + assert!(failure(&mut s, source).contains("Not found"), "{source}"); + } + let out = log(&mut s, "var p = app.activeDocument.pageItems; p[0] = 3; vc.log(typeof p[0]);"); + assert_eq!(out, vec![json!("object")]); + // On a page item the value is not kept; strict-mode code throws instead. + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.qux = 4; vc.log(typeof i.qux);"); + assert_eq!(out, vec![json!("undefined")]); + let e = failure(&mut s, "'use strict'; app.activeDocument.pageItems[0].qux = 4;"); + assert!(e.contains("TypeError") && e.contains("qux"), "{e}"); + assert_eq!(undo_steps(&s), steps); +} + +/// `JSON.stringify` writes a collection, or data that holds one, without reading a `toJSON` the +/// collection lacks, while a script that reads `toJSON` itself gets `Not found`. +#[test] +fn json_stringify_writes_a_collection() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, m = ''; vc.log([JSON.stringify(p), JSON.stringify({list: [p, app.documents]})]);\ + try { p.toJSON; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, vec![json!(["{}", "{\"list\":[{},{}]}"]), json!("Not found")]); +} diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 8ea0482826..01d84ac99f 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -389,3 +389,16 @@ fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() { }); let _ = std::fs::remove_dir_all(dir); } + +#[test] +fn a_startup_listing_over_the_script_limit_keeps_the_first_names_in_order() { + let dir = vectorcraft_testkit::TempDir::new("startup-limit"); + for name in ["d.jsx", "b.jsx", "e.jsx", "a.jsx", "c.jsx"] { + touch(&dir, name); + } + let limits = Limits { scripts: 3, ..Limits::default() }; + let listing = crate::script::startup::list_with(&dir, &limits, &mut || Duration::ZERO); + let names: Vec<_> = listing.scripts.iter().map(|p| p.file_name().unwrap().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["a.jsx", "b.jsx", "c.jsx"]); + assert!(listing.truncated); +} diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index 78b0065b46..1b41d992fd 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -692,3 +692,59 @@ fn script_error_that_passes_through_a_finally_block_is_at_its_throw() { } let _ = std::fs::remove_dir_all(base); } + +#[test] +fn a_js_script_has_promise_and_a_jsx_script_does_not() { + let base = folder("promise-realm"); + let main = base.join("main/main.js"); + write(&main, "vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); }); vc.log(1);"); + let r = Session::new().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!(["function", 1, 2])); + assert!(r.get("unhandledRejections").is_none(), "{r}"); + let r = run(&base, "vc.log(typeof Promise);").unwrap(); + assert_eq!(r["log"], json!(["undefined"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it() { + let base = folder("promise-engine"); + let jsx = base.join("main/a.jsx"); + let js = base.join("main/b.js"); + let mut s = Session::new(); + let mut go = |path: &Path, text: &str| { + write(path, text); + s.execute("script.run", &json!({"path": path.to_string_lossy()})).unwrap()["log"].clone() + }; + assert_eq!(go(&jsx, "#targetengine kept\nvar n = 1; vc.log(typeof Promise);"), json!(["undefined"])); + assert_eq!( + go(&js, "#targetengine kept\nvc.log(n); vc.log(typeof Promise); Promise.resolve(2).then(function (v) { vc.log(v); });"), + json!([1, "function", 2]) + ); + assert_eq!(go(&jsx, "#targetengine kept\nvc.log(typeof Promise);"), json!(["function"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line() { + let base = folder("promise-rejections"); + write(&base.join("main/lib.jsxinc"), "var x = 1;\nPromise.reject(new RangeError('in lib'));\n"); + let main = base.join("main/main.js"); + write(&main, "var a = 1;\nPromise.reject(new Error('lost'));\n#include \"lib.jsxinc\"\nPromise.reject(3).catch(function () {});\n"); + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + let got: Vec<(String, u64, Option)> = r["unhandledRejections"] + .as_array() + .unwrap() + .iter() + .map(|j| (j["message"].as_str().unwrap().to_string(), j["line"].as_u64().unwrap(), j["file"].as_str().map(|f| f.ends_with("lib.jsxinc")))) + .collect(); + assert_eq!(got, vec![("Error: lost".to_string(), 2, None), ("RangeError: in lib".to_string(), 2, Some(true))], "{r}"); + assert_eq!(r["unhandledRejectionCount"], 2); + let c = s.execute("script.console", &json!({})).unwrap(); + let errors: Vec<&str> = c["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "error").filter_map(|l| l["text"].as_str()).collect(); + assert_eq!(errors.len(), 2, "{errors:?}"); + assert!(errors[0].starts_with("main.js:2:") && errors[0].ends_with(": unhandled promise rejection: Error: lost"), "{errors:?}"); + assert!(errors[1].contains("lib.jsxinc:2:"), "{errors:?}"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index e5d854850d..0f05c839c4 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -652,6 +652,63 @@ fn a_grants_change_without_its_lock_changes_nothing() { let _ = std::fs::remove_dir_all(base); } +/// `script.grants.revoke` removes a grant by the path `script.grants` lists for it, also when a +/// link has since taken that path's place and leads elsewhere. +#[cfg(unix)] +#[test] +fn a_grant_whose_path_is_now_a_link_is_revoked_by_its_listed_path() { + let base = folder("grants-relinked"); + let real = std::fs::canonicalize(&base).unwrap(); + let (kept, other) = (real.join("kept.txt"), real.join("other.txt")); + write(&other, b"other"); + let kept_path = kept.to_string_lossy().into_owned(); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": kept_path, "write": false, "folder": false}); + write(&base.join("settings/Script Grants.json"), json!({"version": 1, "grants": [grant]}).to_string().as_bytes()); + std::os::unix::fs::symlink(&other, &kept).unwrap(); + let mut s = with_data(&base); + let listed = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(listed["grants"][0]["path"], json!(kept_path)); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([])); + let _ = std::fs::remove_dir_all(base); +} + +/// A grant kept for a path that is now a link to another granted path is revoked alone: the grant of +/// the link's target stays. +#[cfg(unix)] +#[test] +fn revoking_a_grant_whose_path_now_links_to_another_grant_keeps_the_other() { + let base = folder("grants-relinked-both"); + let real = std::fs::canonicalize(&base).unwrap(); + let (kept, other) = (real.join("kept.txt"), real.join("other.txt")); + write(&other, b"other"); + let (kept_path, other_path) = (kept.to_string_lossy().into_owned(), other.to_string_lossy().into_owned()); + let grant = |path: &str| json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": path, "write": false, "folder": false}); + let stored = json!({"version": 1, "grants": [grant(&kept_path), grant(&other_path)]}); + write(&base.join("settings/Script Grants.json"), stored.to_string().as_bytes()); + std::os::unix::fs::symlink(&other, &kept).unwrap(); + let mut s = with_data(&base); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + let left = s.execute("script.grants", &json!({})).unwrap(); + let paths: Vec = left["grants"].as_array().into_iter().flatten().map(|g| g["path"].clone()).collect(); + assert_eq!(paths, [json!(other_path)], "{left}"); + // Another script's grant of the path as given does not keep this script's grant of the link's + // target from being removed. + let stored = json!({"version": 1, "grants": [ + {"script": "/t.jsx", "sha256": "0", "code": [], "path": kept_path, "write": false, "folder": false}, + grant(&other_path) + ]}); + write(&base.join("settings/Script Grants.json"), stored.to_string().as_bytes()); + let r = s.execute("script.grants.revoke", &json!({"script": "/s.jsx", "path": kept_path})).unwrap(); + assert_eq!(r["removed"], 1, "{r}"); + let left = s.execute("script.grants", &json!({})).unwrap(); + let scripts: Vec = left["grants"].as_array().into_iter().flatten().map(|g| g["script"].clone()).collect(); + assert_eq!(scripts, [json!("/t.jsx")], "{left}"); + let _ = std::fs::remove_dir_all(base); +} + /// Reading and changing the grants file wait for a lock another handle holds only for a bounded /// number of tries: then a listing and a change fail, with the file unchanged. A lock /// released while it waits is taken. diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 56bc5854a1..9489921682 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -165,7 +165,9 @@ fn an_error_names_the_script_its_place_and_kind() { assert_eq!(e, "t.js: line 2, column 3: TypeError: no (thrown)"); let e = run(&mut s, "var = 1;").unwrap_err().to_string(); assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); - assert!(run(&mut s, "app.activeDocument;").unwrap_err().to_string().contains("`vc`")); + assert!(run(&mut s, "new Window('dialog');").unwrap_err().to_string().contains("`vc`")); + // The application's members need no `app.`, so naming one alone is not an error. + assert_eq!(run(&mut s, "activeDocument;").unwrap()["ok"], true); assert!(run(&mut s, "#targetengine 9x\n1").unwrap_err().to_string().contains("#targetengine needs a name of letters, digits and _")); assert_eq!(s.script_report().unwrap()["line"], 1); } @@ -180,7 +182,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), - ("throw 'ReferenceError: app is not defined';", "thrown", "ReferenceError: app is not defined", "script"), + ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), @@ -204,7 +206,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}"); } // The app's own reference error names the `vc` object; the same text a script threw does not. - run(&mut s, "app.activeDocument;").unwrap_err(); + run(&mut s, "new Window('dialog');").unwrap_err(); assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`")); assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in"); // An error in code `eval` compiled keeps where its message came from. @@ -391,6 +393,33 @@ fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_runs_generators_and_a_jsx_script_does_not_read_them() { + let dir = fresh_folder("generators"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let source = "function* ids(n) { for (let i = 0; i < n; i++) yield `id${i}`; }\n\ + function* all() { yield* ids(2); yield* [vc.document ? 'doc' : 'none']; return 'end'; }\n\ + const it = all(); let s;\nwhile (!(s = it.next()).done) vc.log(s.value);\nvc.log(s.value);\n"; + let r = s.execute("script.run", &path(&write("gen.js", source))).unwrap(); + assert_eq!(r["log"], json!(["id0", "id1", "doc", "end"]), "{r}"); + let e = s.execute("script.run", &path(&write("gen.jsx", "function* g() {}"))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{e}"); + // `yield` stays a name in a `.jsx` script. + let r = s.execute("script.run", &path(&write("name.jsx", "var yield = 4; vc.log(yield);"))).unwrap(); + assert_eq!(r["log"], json!([4]), "{r}"); + // An engine a `.jsx` run made has no generator built-ins for a later `.js` run. + s.execute("script.run", &path(&write("keep.jsx", "#targetengine genkept\nvar a = 1;"))).unwrap(); + let e = s.execute("script.run", &path(&write("keep.js", "#targetengine genkept\nfunction* g() {}\ng();"))).unwrap_err().to_string(); + assert!(e.contains("TypeError"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn every_script_reads_e4x_and_has_the_xml_objects() { let dir = fresh_folder("e4x"); diff --git a/crates/engine/src/tests/script_tags.rs b/crates/engine/src/tests/script_tags.rs new file mode 100644 index 0000000000..cc477f27fa --- /dev/null +++ b/crates/engine/src/tests/script_tags.rs @@ -0,0 +1,286 @@ +//! Tags on page items: `PageItem.tags`, `Document.tags`, `Tag`, and the `object.tag.*` commands +//! they run. + +use serde_json::{Value, json}; +use vectorcraft_doc::{MAX_TAG_TEXT, MAX_TAGS, ObjectTag}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()) +} + +/// A document with two rectangles. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0); + let b = rect(&mut s, 100.0, 100.0); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +fn tags(s: &Session, id: NodeId) -> Vec<(String, String)> { + let d = &s.active().unwrap().doc; + crate::cmd::tags::tags_of(d.node(id).unwrap()).iter().map(|t| (t.name.clone(), t.value.clone())).collect() +} + +fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> { + list.iter().map(|(n, v)| (n.to_string(), v.to_string())).collect() +} + +#[test] +fn tags_are_added_named_read_and_removed_in_one_undo_step() { + let (mut s, a, _) = doc(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var item = app.activeDocument.pageItems[1], tags = item.tags;\ + vc.log(tags.typename); vc.log(tags.length);\ + var t = tags.add(); vc.log(t.typename); vc.log(t.name === '' && t.value === '');\ + t.name = 'size'; t.value = 'XL';\ + var u = tags.add(); u.name = 'size'; u.value = 'S';\ + var w = tags.add(); w.name = '../a\\\\b'; w.value = 'kept';\ + vc.log(tags.length); vc.log(tags.getByName('size').value); vc.log(tags[1].value); vc.log(tags.index(2).name);\ + vc.log(tags.index('../a\\\\b').value); vc.log(tags[3] === undefined); vc.log(t.parent.typename); vc.log(tags.parent.typename);\ + u.remove(); vc.log(tags.length); vc.log(tags[1].name);", + ); + let expected = [json!("Tags"), json!(0), json!("Tag"), json!(true), json!(3), json!("XL"), json!("S"), json!("../a\\b")]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!("kept"), json!(true), json!("PathItem"), json!("PathItem"), json!(2), json!("../a\\b")]); + assert_eq!(tags(&s, a), pairs(&[("size", "XL"), ("../a\\b", "kept")])); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(tags(&s, a).is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(tags(&s, a).len(), 2); + log(&mut s, "app.activeDocument.pageItems[1].tags.removeAll();"); + assert!(tags(&s, a).is_empty()); +} + +#[test] +fn document_tags_list_every_items_tags_and_add_none() { + let (mut s, a, b) = doc(); + s.execute("object.tag.add", &json!({"id": b.0, "name": "b1", "value": "2"})).unwrap(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "a1", "value": "1"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log(d.tags.length); vc.log(d.tags[0].name); vc.log(d.tags[1].name);\ + vc.log(d.tags.parent.typename); vc.log(d.tags.getByName('b1').parent.typename);", + ); + // `pageItems` lists the topmost item first, and so does `Document.tags`. + assert_eq!(out, [json!(2), json!("b1"), json!("a1"), json!("Document"), json!("PathItem")]); + // A copy keeps its source's tags. + let copy = s.execute("edit.duplicate", &json!({"ids": [a.0]})).unwrap()["ids"][0].as_u64().map(NodeId).unwrap(); + assert_eq!(tags(&s, copy), pairs(&[("a1", "1")])); + s.execute("edit.undo", &json!({})).unwrap(); + let before = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.tags.add();").contains("added to a page item's tags")); + assert_eq!(undo_steps(&s), before); + log(&mut s, "app.activeDocument.tags.removeAll();"); + assert!(tags(&s, a).is_empty() && tags(&s, b).is_empty()); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn bad_tag_values_throw_and_change_nothing() { + let (mut s, a, _) = doc(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "n", "value": "v"})).unwrap(); + let before = undo_steps(&s); + let tag = "app.activeDocument.pageItems[1].tags[0]"; + assert!(failure(&mut s, &format!("{tag}.name = 5;")).contains("TypeError: name must be a string")); + assert!(failure(&mut s, &format!("{tag}.value = null;")).contains("TypeError: value must be a string")); + let long = format!("{tag}.value = new Array({}).join('x');", MAX_TAG_TEXT + 2); + assert!(failure(&mut s, &long).contains("RangeError: a tag's value is longer than 65,536 bytes")); + assert!(failure(&mut s, "app.activeDocument.pageItems[1].tags.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.pageItems[1].tags.index(true);").contains("TypeError")); + // A run that fails after changing a tag puts it back. + assert!(failure(&mut s, &format!("{tag}.value = 'w'; throw new Error('stop');")).contains("stop")); + assert_eq!(tags(&s, a), pairs(&[("n", "v")])); + // Setting what a tag already has runs no command. + log(&mut s, &format!("{tag}.name = 'n'; {tag}.value = 'v';")); + assert_eq!(undo_steps(&s), before); +} + +#[test] +fn tags_work_on_an_item_and_with_tag_ids_above_2_to_the_53() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let a = rect(&mut s, 10.0, 20.0); + assert_eq!(a.0, big); + let out = log( + &mut s, + "var all = app.activeDocument.pageItems[0].tags, t = all.add(); t.name = 'n'; t.value = 'v';\ + var u = all.add(); u.name = 'm'; vc.log(all.length); vc.log(t.name); vc.log(all[1].name); vc.log(t.parent.typename);\ + t.remove(); vc.log(all.length); vc.log(all[0].name);", + ); + assert_eq!(out, [json!(2), json!("n"), json!("m"), json!("PathItem"), json!(1), json!("m")]); + assert_eq!(tags(&s, a), pairs(&[("m", "")])); +} + +#[test] +fn an_object_takes_at_most_64_tags() { + let (mut s, a, _) = doc(); + let out = log(&mut s, "var t = app.activeDocument.pageItems[1].tags; for (var i = 0; i < 64; i++) t.add(); vc.log(t.length);"); + assert_eq!(out, [json!(MAX_TAGS)]); + let e = failure(&mut s, "app.activeDocument.pageItems[1].tags.add();"); + assert!(e.contains("64 tags"), "{e}"); + assert_eq!(tags(&s, a).len(), MAX_TAGS); +} + +#[test] +fn a_tag_goes_stale_when_it_or_its_item_is_deleted() { + let (mut s, a, b) = doc(); + s.execute("object.tag.add", &json!({"id": a.0, "name": "x"})).unwrap(); + s.execute("object.tag.add", &json!({"id": b.0, "name": "y"})).unwrap(); + let e = failure(&mut s, "var t = app.activeDocument.pageItems[0].tags[0]; t.remove(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); + // `typename` throws too, on a deleted tag and on the tags of a deleted item (each failed run + // put the document back). + let e = failure(&mut s, "var t = app.activeDocument.pageItems[0].tags[0]; t.remove(); t.typename;"); + assert!(e.contains("Stale tag"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], all = i.tags; i.remove(); all.typename;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], t = i.tags[0], all = i.tags; i.remove(); all.length;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[1], t = i.tags[0]; i.remove(); t.value;"); + assert!(e.contains("Stale page item"), "{e}"); + // A tag added after another was deleted does not take the deleted one's place. + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all[0]; t.remove(); all.add(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); + // Nor after the run undoes the add: the undone document's next id does not give the tag's id + // out again. + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all.add(); vc.run('edit.undo'); all.add().name = 'u'; t.name;"); + assert!(e.contains("Stale tag"), "{e}"); + // Nor when the deleted tag's id was ahead of the document's next id (a tag pasted from + // another document). + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let ahead = d.peek_next_id() + 2; + d.node_mut(a).unwrap().edit_attrs(|at| at.tags = vec![ObjectTag { id: ahead, name: "p".into(), value: String::new() }]); + let e = failure(&mut s, "var all = app.activeDocument.pageItems[0].tags, t = all[0]; t.remove(); all.add(); all.add(); all.add(); t.name;"); + assert!(e.contains("Stale tag"), "{e}"); +} + +#[test] +fn tag_commands_check_their_params_and_skip_unchanged_edits() { + let (mut s, a, _) = doc(); + let tag = s.execute("object.tag.add", &json!({"id": a.0, "name": "k"})).unwrap()["tag"].as_u64().unwrap(); + let before = undo_steps(&s); + assert_eq!(s.execute("object.tag.set", &json!({"id": a.0, "tag": tag, "name": "k"})).unwrap()["changed"], false); + assert_eq!(s.execute("object.tag.removeAll", &json!({"ids": []})).unwrap()["changed"], 0); + assert_eq!(undo_steps(&s), before); + let too_long = "x".repeat(MAX_TAG_TEXT + 1); + for (id, p) in [ + ("object.tag.add", json!({"id": a.0, "name": too_long})), + ("object.tag.add", json!({"id": a.0, "value": 3})), + ("object.tag.add", json!({"id": a.0, "name": null})), + ("object.tag.set", json!({"id": a.0, "tag": tag, "name": null, "value": "updated"})), + ("object.tag.set", json!({"id": a.0, "tag": tag, "value": null})), + ("object.tag.add", json!({"id": 999_999})), + ("object.tag.add", json!({"id": "1"})), + ("object.tag.set", json!({"id": a.0, "tag": tag})), + ("object.tag.set", json!({"id": a.0, "tag": tag + 1, "name": "n"})), + ("object.tag.remove", json!({"id": a.0, "tag": -1})), + ("object.tag.removeAll", json!({"ids": [999_999]})), + ("object.tags", json!({})), + ] { + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + } + let layer = s.active().unwrap().doc.layers[0].id; + assert!(s.execute("object.tag.add", &json!({"id": layer.0})).is_err()); + assert_eq!(undo_steps(&s), before); + assert_eq!(s.execute("object.tags", &json!({"id": a.0})).unwrap(), json!({"tags": [{"tag": tag, "name": "k", "value": ""}]})); +} + +#[test] +fn tags_survive_native_save_and_open_and_hostile_ones_are_trimmed() { + let (mut s, a, b) = doc(); + let tag = s.execute("object.tag.add", &json!({"id": a.0, "name": "size", "value": "XL"})).unwrap()["tag"].as_u64().unwrap(); + let mut doc = (*s.active().unwrap().doc).clone(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(a).unwrap()); + assert_eq!(t.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect::>(), [("size", "XL")]); + // The tag keeps its id, so `object.tag.set` and `object.tag.remove` still find it. + assert_eq!(t[0].id, tag); + assert!(tag < back.peek_next_id()); + // A file with too many tags, repeated ids and over-long text opens with them within the limits. + doc.node_mut(b).unwrap().edit_attrs(|at| { + at.tags = (0..MAX_TAGS + 10).map(|i| ObjectTag { id: 7, name: format!("t{i}"), value: String::new() }).collect(); + at.tags.insert(0, ObjectTag { id: 1, name: "x".repeat(MAX_TAG_TEXT + 1), value: String::new() }); + }); + // The repeated ids get new ids from the next node id on. + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(b).unwrap()); + assert_eq!(t[0].id, 7); + assert!(t[1..].iter().all(|t| t.id > tag && t.id < back.peek_next_id())); + // An id at the top of the node id range, and one past it: the new ids are the smallest the + // object's other tags do not have. + let top = (1u64 << 62) - 1; + doc.node_mut(a).unwrap().edit_attrs(|at| { + at.tags[0].id = u64::MAX; + at.tags.insert(0, ObjectTag { id: top, name: "top".into(), value: String::new() }); + }); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + // Opening gives both new ids below the next node id, which stays within the node id range. + let fixed: Vec = crate::cmd::tags::tags_of(back.node(a).unwrap()).iter().map(|t| t.id).collect(); + assert_eq!(fixed.len(), 2); + assert!(fixed.iter().all(|id| *id < back.peek_next_id()) && fixed[0] != fixed[1], "{fixed:?}"); + assert_eq!(fixed, [top, 1]); + assert!(back.peek_next_id() <= 1 << 62, "{}", back.peek_next_id()); + // No tag id is left for a new tag: one past the range would not be kept on opening, and one + // below it could be a deleted tag's. + assert_eq!(back.clone().alloc_tag_id(a), None); + let t = crate::cmd::tags::tags_of(back.node(b).unwrap()); + assert_eq!(t.len(), MAX_TAGS); + assert_eq!(t[0].name, "t0"); + // The first tag with the repeated id keeps it; the others get new ones. + assert_eq!(t[0].id, 7); + let mut ids: Vec = t.iter().map(|t| t.id).collect(); + assert!(ids.iter().all(|id| *id < back.peek_next_id())); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), MAX_TAGS); +} + +#[test] +fn a_file_with_a_tag_id_that_is_not_a_whole_number_opens_and_the_tag_gets_a_new_id() { + let (s, a, _) = doc(); + let mut doc = (*s.active().unwrap().doc).clone(); + doc.node_mut(a).unwrap().edit_attrs(|at| { + at.tags = + ["k0", "k1", "k2"].iter().enumerate().map(|(i, n)| ObjectTag { id: 424_240 + i as u64, name: (*n).into(), value: "v".into() }).collect(); + }); + let mut hostile = String::from_utf8(vectorcraft_format::save(&doc, false)).unwrap(); + for (from, to) in [("\"id\":424240", "\"id\":-1"), ("\"id\":424241", "\"id\":1.5"), ("\"id\":424242", "\"id\":\"x\"")] { + assert!(hostile.contains(from), "{from}"); + hostile = hostile.replace(from, to); + } + let back = vectorcraft_format::load(hostile.as_bytes()).unwrap(); + let t = crate::cmd::tags::tags_of(back.node(a).unwrap()); + assert_eq!(t.iter().map(|t| (t.name.as_str(), t.value.as_str())).collect::>(), [("k0", "v"), ("k1", "v"), ("k2", "v")]); + let mut ids: Vec = t.iter().map(|t| t.id).collect(); + assert!(ids.iter().all(|id| *id >= 1 && *id < back.peek_next_id()), "{ids:?}"); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 3); +} diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index d49b18b031..96403dcaa0 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -3250,6 +3250,24 @@ fn ending_deferred_typing_for_another_edit_keeps_the_typing() { }); } +/// An effect applied while typing waits for its session to end keeps the typing as its own step +/// first, and the effect's own step still keeps the effect it applied. +#[test] +fn an_effect_applied_while_typing_waits_keeps_its_effect_on_its_step() { + let mut s = session(); + s.prefs.real_time_drawing = false; + let v = ViewInfo::default(); + let id = text(&mut s, "Hello"); + s.select_tool("type", v).unwrap(); + let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + click(&mut s, b.x1 - 1.0, b.center().y); + s.tool_text(" world", v).unwrap(); + s.execute("effect.apply", &json!({"effect": "stylize.feather", "ids": [id.0]})).unwrap(); + assert_eq!(undo_labels(&s).iter().rev().take(2).collect::>(), ["Feather", "Typing"]); + let h = s.doc().unwrap().history.undo.last().unwrap(); + assert_eq!(h.effect(), Some("stylize.feather")); +} + /// #1950: a colour previewed while typing (the Color Picker, a Color panel slider) colours the /// typed text: its interaction used to join the typing session and preview from the document /// before the typing, so the new type came back as its placeholder text. diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 69d382f2dc..7a28a84ec7 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -30,6 +30,55 @@ fn blob_tip_options_report_and_persist() { assert_eq!((next.tool_options()["angle"].as_f64(), next.tool_options()["roundness"].as_f64()), (Some(45.0), Some(0.0))); } +/// The Circle tool's From Center survives a tool switch and is saved with the preferences. +#[test] +fn circle_from_center_persists() { + let mut s = session(); + select(&mut s, "circle"); + let mut want = s.tool_options(); + assert_eq!(want["fromCenter"], json!(false)); + want["fromCenter"] = json!(true); + s.set_tool_option("fromCenter", &json!(true)); + select(&mut s, "selection"); + select(&mut s, "circle"); + assert_eq!(s.tool_options(), want); + select(&mut s, "selection"); + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut next = session(); + next.apply_prefs(serde_json::from_str(&saved).unwrap()); + select(&mut next, "circle"); + assert_eq!(next.tool_options(), want); +} + +/// An option set during a press (`tool.setOption`, or a Control bar change) is kept when the press +/// is dropped: the drop gives back only what the press itself changed. +#[test] +fn the_circle_from_center_set_during_a_dropped_press_is_kept() { + let v = ViewInfo::default(); + let mut s = session(); + select(&mut s, "circle"); + let mut want = s.tool_options(); + s.set_tool_option("fromCenter", &json!(true)); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.set_tool_option_cmd(&json!({"key": "fromCenter", "value": false})).unwrap(); + s.drop_tool_press(v).unwrap(); + want["fromCenter"] = json!(false); + assert_eq!(s.tool_options(), want); + assert_eq!(s.prefs.tool_settings["circle"]["fromCenter"], json!(false)); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.set_tool_option("fromCenter", &json!(true)); + s.drop_tool_press(v).unwrap(); + want["fromCenter"] = json!(true); + assert_eq!(s.tool_options(), want); + assert_eq!(s.prefs.tool_settings["circle"]["fromCenter"], json!(true)); + // Setting a Parametric Shape's kind also puts its numbers back to that kind's: those are kept too. + select(&mut s, "parametricShape"); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + let set = s.set_tool_option_cmd(&json!({"key": "kind", "value": "star"})).unwrap(); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_options(), set); +} + #[test] fn options_survive_a_tool_switch() { let mut s = session(); @@ -218,6 +267,25 @@ fn an_option_set_on_a_lending_tool_during_a_dropped_press_is_kept() { assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it"); } +/// A shared Liquify brush size set through another Liquify tool during a held press survives the +/// dropped press, also when the set value equals the size the press's drag has made current. +#[test] +fn a_shared_option_set_through_another_tool_during_a_dropped_press_is_kept() { + let mut s = session(); + select(&mut s, "warp"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap(); + let before = s.tool_options()["width"].as_f64().unwrap(); + // The press's own change to the shared size, not stored. + s.tool.set_option("width", &json!(before + 40.0)); + let current = s.tool_options()["width"].clone(); + s.set_tool_option_cmd(&json!({"tool": "pucker", "key": "width", "value": before + 40.0})).unwrap(); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_options()["width"], current, "the tool keeps the size set through the other tool"); + assert_eq!(s.prefs.tool_settings["liquify"]["width"], current, "and stores it"); +} + /// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with /// the next click. #[test] @@ -473,6 +541,54 @@ fn alt_smoothing_takes_the_smooth_tools_fidelity() { } } +/// The Smoothness an Alt smoothing drag sends with `path.smoothRegion` on a selected path. +fn alt_smoothness(s: &mut Session) -> Option { + use vectorcraft_tools::Action; + let mods = Mods { alt: true, ..Default::default() }; + let mut last = vec![]; + for (kind, x, y) in [(PointerKind::Down, 50.0, 150.0), (PointerKind::Drag, 150.0, 150.0), (PointerKind::Up, 250.0, 160.0)] { + let ev = PointerEvent { mods, ..PointerEvent::new(kind, x, y) }; + last = s.with_tool_cx(ViewInfo::default(), |t, cx| t.pointer(cx, &ev)); + } + last.iter().find_map(|a| match a { + Action::Exec(c, v) if c == "path.smoothRegion" => v["smoothness"].as_f64(), + _ => None, + }) +} + +/// Smooth Tool Options' Smoothness is kept with the preferences (50% until it is set), and Alt +/// smoothing with the Pencil, Paintbrush and Blob Brush uses it. A Smoothness outside 0 to 100 is +/// an error that sets nothing. +#[test] +fn the_smooth_tools_smoothness_is_kept_and_alt_smoothing_takes_it() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + select(&mut s, "smooth"); + assert_eq!(s.tool_options()["smoothness"], json!(50.0)); + for bad in [json!(-1), json!(100.5), json!("30"), json!(null)] { + let e = s.set_tool_option_cmd(&json!({"key": "smoothness", "value": bad})).unwrap_err(); + assert_eq!(e, "tool `smooth`: `smoothness` must be a number from 0 to 100", "{bad}"); + } + assert_eq!(s.tool_options()["smoothness"], json!(50.0)); + s.set_tool_option("smoothness", &json!(80)); + assert_eq!(s.prefs.tool_settings["smooth"]["smoothness"], json!(80.0)); + for id in ["pencil", "paintbrush", "blobBrush"] { + select(&mut s, id); + if id == "pencil" { + s.set_tool_option("altSmooth", &json!(true)); + } + assert_eq!(alt_smoothness(&mut s), Some(80.0), "{id}"); + assert!(s.tool_options().get("smoothness").is_none(), "{id} has no Smoothness of its own"); + } + s.set_tool_option_cmd(&json!({"tool": "smooth", "key": "smoothness", "value": 10})).unwrap(); + assert_eq!(alt_smoothness(&mut s), Some(10.0), "the Blob Brush takes the new Smoothness"); + let saved = serde_json::to_string(&s.prefs).unwrap(); + let mut next = session(); + next.apply_prefs(serde_json::from_str(&saved).unwrap()); + select(&mut next, "smooth"); + assert_eq!(next.tool_options()["smoothness"], json!(10.0)); +} + /// `tool.setOption` with a value of the wrong type, a number out of range, an unknown value or an /// option the tool doesn't have is an error naming the tool and the option. Nothing is set, also /// when another option given with it is good, and nothing is saved or recorded for undo. @@ -489,7 +605,10 @@ fn bad_option_values_are_errors_that_set_nothing() { (json!({"key": "bogus", "value": 1}), "tool `smooth`: unknown option `bogus`"), (json!({"tool": "pencil", "values": {"closeWithin": 5, "fidelity": "x"}}), "tool `pencil`: `fidelity` must be a number from 0.01 to 100"), (json!({"tool": "pencil", "key": "fill", "value": "yes"}), "tool `pencil`: `fill` must be true or false"), - (json!({"tool": "blobBrush", "key": "sizeMode", "value": "huge"}), "tool `blobBrush`: `sizeMode` must be one of `fixed`, `pressure`"), + ( + json!({"tool": "blobBrush", "key": "sizeMode", "value": "huge"}), + "tool `blobBrush`: `sizeMode` must be one of `fixed`, `pressure`, `stylusWheel`", + ), (json!({"tool": "eraser", "key": "fidelity", "value": 4}), "tool `eraser`: unknown option `fidelity`"), (json!({"tool": "polygon", "key": "sides", "value": 2}), "tool `polygon`: `sides` must be a whole number from 3 to 1000"), ( diff --git a/crates/engine/src/tests/turn_direction.rs b/crates/engine/src/tests/turn_direction.rs index a8961f3c46..f45fd3b7e4 100644 --- a/crates/engine/src/tests/turn_direction.rs +++ b/crates/engine/src/tests/turn_direction.rs @@ -6,6 +6,7 @@ use crate::command_specs; /// Params that are angles but not a turn, with why. const NOT_A_TURN: &[(&str, &str, &str)] = &[ + ("addon.packaging.setFoldAngle", "angle", "a fold out of the page: the description says which side the panel folds to"), ("addon.pathtools.cornerSet", "maxAngle", "the angle a corner's sides meet at"), ("addon.pathtools.cornerSet", "minAngle", "the angle a corner's sides meet at"), ("addon.shapes.box3d", "angleX", "a tilt out of the page: the description says which side turns away"), diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 39c95da3f6..0d1d6b50a8 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -163,6 +163,92 @@ fn gif_transparency_index_and_map_to_transparent() { assert_eq!(pixels(&gif).get_pixel(25, 15)[3], 0, "index {i}"); } +/// 40×30: red at 25% opacity on the left half, blue at 75% on the right, nothing behind them. +fn see_through() -> Session { + let mut s = session(40.0, 30.0); + rect(&mut s, [0.0, 0.0, 20.0, 30.0], "#ff0000"); + run(&mut s, "transparency.set", json!({"opacity": 25})); + rect(&mut s, [20.0, 0.0, 20.0, 30.0], "#0000ff"); + run(&mut s, "transparency.set", json!({"opacity": 75})); + s +} + +/// The shares of the left and right halves' pixels that are opaque. +fn opaque_halves(img: &image::RgbaImage) -> [f64; 2] { + [0, 20].map(|x0| (x0..x0 + 20).flat_map(|x| (0..30).map(move |y| (x, y))).filter(|&(x, y)| img.get_pixel(x, y)[3] == 255).count() as f64 / 600.0) +} + +#[test] +fn transparency_dither_keeps_a_share_of_partly_transparent_pixels() { + let mut s = see_through(); + for format in ["gif", "png8"] { + let file = |s: &mut Session, extra: Value| { + let mut p = json!({"format": format, "antiAlias": "none"}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + one(s, p) + }; + // By default the pixels under half opacity are transparent and the others opaque. + let none = file(&mut s, json!({})); + assert_eq!(opaque_halves(&pixels(&none)), [0.0, 1.0], "{format}"); + assert_eq!(file(&mut s, json!({"transparencyDither": "none"})), none, "{format}"); + assert_eq!(file(&mut s, json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 0})), none, "{format}"); + for method in ["diffusion", "pattern", "noise"] { + let p = json!({"transparencyDither": method}); + let dithered = file(&mut s, p.clone()); + let [left, right] = opaque_halves(&pixels(&dithered)); + assert!((left - 0.25).abs() < 0.1 && (right - 0.75).abs() < 0.1, "{format} {method}: {left} {right}"); + if format == "gif" { + assert_eq!(gif_transparent_index(&dithered), Some(0), "{method}"); + } + assert_eq!(file(&mut s, p.clone()), dithered, "{format} {method}: the same art gives the same file"); + // The preview shows what Save writes. + let mut pv = json!({"format": format, "antiAlias": "none", "image": true}); + pv["transparencyDither"] = json!(method); + let shown = run(&mut s, "document.exportForWeb.preview", pv); + assert_eq!(vectorcraft_format::base64_decode(shown["dataBase64"].as_str().unwrap()).unwrap(), dithered, "{format} {method}"); + // Without transparency the dither does nothing. + let opaque = file(&mut s, json!({"transparencyDither": method, "transparency": false})); + assert_eq!(opaque, file(&mut s, json!({"transparency": false})), "{format} {method}"); + } + // A fixed palette keeps the transparent entry for the dithered pixels. + let fixed = file(&mut s, json!({"transparencyDither": "pattern", "colorTable": {"customPalette": ["#ffbfbf", "#4040ff"]}})); + let [left, right] = opaque_halves(&pixels(&fixed)); + assert!(left > 0.0 && left < 1.0 && right > 0.0 && right < 1.0, "{format}: {left} {right}"); + } +} + +#[test] +fn transparency_dither_settings_are_checked_and_remembered() { + let mut s = see_through(); + for bad in [ + json!({"transparencyDither": "spray"}), + json!({"transparencyDither": 3}), + json!({"transparencyDitherAmount": 101}), + json!({"transparencyDitherAmount": -1}), + ] { + assert!(s.execute("document.exportForWeb", &bad).is_err(), "{bad}"); + assert!(s.execute("webExport.settings", &bad).is_err(), "{bad}"); + } + let e = s.execute("document.exportForWeb", &json!({"transparencyDitherAmount": 101})).unwrap_err().to_string(); + assert!(e.contains("`transparencyDitherAmount` must be from 0 to 100"), "{e}"); + assert_eq!(defaults()["transparencyDither"], "none"); + assert_eq!(defaults()["transparencyDitherAmount"], 100); + // The remembered settings and a saved preset keep both. + let set = run(&mut s, "webExport.settings", json!({"transparencyDither": "diffusion", "transparencyDitherAmount": 40})); + assert_eq!((&set["settings"]["transparencyDither"], &set["settings"]["transparencyDitherAmount"]), (&json!("diffusion"), &json!(40))); + let read = run(&mut s, "webExport.settings", json!({})); + assert_eq!(read["settings"], set["settings"]); + run(&mut s, "webExport.presets.save", json!({"name": "Soft edges", "transparencyDither": "noise", "transparencyDitherAmount": 60})); + let list = run(&mut s, "webExport.presets.list", json!({})); + let saved = list["presets"].as_array().unwrap().iter().find(|p| p["name"] == "Soft edges").unwrap(); + assert_eq!((&saved["settings"]["transparencyDither"], &saved["settings"]["transparencyDitherAmount"]), (&json!("noise"), &json!(60))); + let by_preset = one(&mut s, json!({"preset": "Soft edges", "format": "gif", "antiAlias": "none"})); + assert_eq!(by_preset, one(&mut s, json!({"format": "gif", "antiAlias": "none", "transparencyDither": "noise", "transparencyDitherAmount": 60}))); + // Settings saved before the keys existed take the defaults. + let old: cmd::webexport::WebSettings = serde_json::from_value(json!({"format": "png8", "dither": "pattern"})).unwrap(); + assert_eq!((old.transparency_dither.id(), old.transparency_dither_amount), ("none", 100)); +} + #[test] fn jpeg_size_grows_with_quality() { let mut s = many_colours(); @@ -1056,3 +1142,219 @@ fn optimize_to_file_size_finds_a_fit_when_a_lower_setting_gives_a_larger_file() assert!(highest_within(&mut size, &start, (1, 90), set_quality, 100, &mut smallest).unwrap().is_none()); assert_eq!(smallest.map(|(s, n)| (s.quality, n)), Some((36, 415))); } + +/// The bytes of a `document.exportForWeb.saveColorTable` reply without a path. +fn color_table_file(s: &mut Session, p: Value) -> (Value, Vec) { + let v = run(s, "document.exportForWeb.saveColorTable", p); + let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + (v, bytes) +} + +/// The color table file of `colors` (`#rrggbb`) and transparent entry `transparent`, as the +/// published layout gives it: 256 RGB triples (zero past the colors used), then the number of +/// colors and the transparent index (0xFFFF for none), two bytes each, most significant first. +fn act_layout(colors: &[&str], transparent: Option) -> Vec { + let mut out = vec![]; + for c in colors { + let rgb = u32::from_str_radix(c.trim_start_matches('#'), 16).unwrap(); + out.extend_from_slice(&[(rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8]); + } + out.resize(768, 0); + out.extend_from_slice(&(colors.len() as u16).to_be_bytes()); + out.extend_from_slice(&transparent.unwrap_or(0xFFFF).to_be_bytes()); + out +} + +/// Save Color Table writes the table the preview shows as a 772-byte color table file: the colors +/// as written, in file order, zero bytes after them, the count and the transparent entry. +#[test] +fn save_color_table_writes_the_act_layout() { + let mut s = two_colours(); + for format in ["gif", "png8"] { + let p = json!({"format": format, "dither": "none", "transparency": false}); + let pv = run(&mut s, "document.exportForWeb.preview", p.clone()); + let colors: Vec<&str> = pv["colors"].as_array().unwrap().iter().map(|c| c["color"].as_str().unwrap()).collect(); + assert_eq!(colors.len(), 2, "{pv}"); + let (v, bytes) = color_table_file(&mut s, p); + assert_eq!(bytes, act_layout(&colors, None), "{format}"); + assert_eq!((v["colors"].as_u64(), v["transparentIndex"].is_null(), v["bytes"].as_u64()), (Some(2), true, Some(772)), "{v}"); + } + // Transparent pixels: the trailer names the transparent entry. + let mut s = session(40.0, 30.0); + rect(&mut s, [10.0, 5.0, 10.0, 20.0], "#ff0000"); + let p = json!({"format": "gif", "antiAlias": "none", "dither": "none"}); + let pv = run(&mut s, "document.exportForWeb.preview", p.clone()); + let table = pv["colors"].as_array().unwrap(); + let at = table.iter().position(|c| c["transparent"] == true).expect("a transparent entry") as u16; + let colors: Vec<&str> = table.iter().map(|c| c["color"].as_str().unwrap()).collect(); + let (v, bytes) = color_table_file(&mut s, p); + assert_eq!(bytes, act_layout(&colors, Some(at))); + assert_eq!(v["transparentIndex"].as_u64(), Some(u64::from(at))); +} + +/// A color shifted by hand goes into the file as the color it is written as. +#[test] +fn save_color_table_writes_shifted_colors_as_written() { + let mut s = two_colours(); + let p = json!({"format": "gif", "dither": "none", "transparency": false, "colorTable": {"shifted": {"#ff0000": "#123456"}}}); + let (_, bytes) = color_table_file(&mut s, p); + let colors: Vec<[u8; 3]> = bytes[..6].chunks(3).map(|c| [c[0], c[1], c[2]]).collect(); + assert!(colors.contains(&[0x12, 0x34, 0x56]) && !colors.contains(&[255, 0, 0]), "{colors:?}"); +} + +/// Save Color Table writes the file at `path`, adding `.act` to a name without an extension and +/// keeping another extension, and refuses formats without a color table and bad params. +#[test] +fn save_color_table_writes_the_path_and_refuses_bad_params() { + let dir = std::env::temp_dir().join(format!("vc-color-table-save-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = two_colours(); + let p = json!({"format": "gif", "dither": "none"}); + let (_, bytes) = color_table_file(&mut s, p.clone()); + let bare = dir.join("table").to_string_lossy().into_owned(); + let v = run(&mut s, "document.exportForWeb.saveColorTable", merge(&p, json!({"path": bare}))); + let written = format!("{bare}.act"); + assert_eq!(v["path"].as_str(), Some(written.as_str())); + assert_eq!(std::fs::read(&written).unwrap(), bytes); + let other = dir.join("table.tbl").to_string_lossy().into_owned(); + run(&mut s, "document.exportForWeb.saveColorTable", merge(&p, json!({"path": other}))); + assert_eq!(std::fs::read(&other).unwrap(), bytes); + for (bad, says) in [ + (json!({"format": "jpg"}), "`jpg` has no color table"), + (json!({"format": "png24"}), "`png24` has no color table"), + (json!({"path": 5}), "`path` must be a string"), + (json!({"path": ""}), "`path` is empty"), + (json!({"path": " "}), "`path` is empty"), + (json!({"slice": "1"}), "`slice` is a slice number"), + (json!({"slice": 0}), "`slice` is a slice number"), + ] { + let e = s.execute("document.exportForWeb.saveColorTable", &bad).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + let _ = std::fs::remove_dir_all(dir); +} + +/// With Save for Web set to the selected slices and none selected, Save Color Table still writes +/// the whole image's table, the one the dialog's preview shows. A `slice` is still looked up among +/// the selected slices. +#[test] +fn save_color_table_of_the_whole_image_needs_no_selected_slice() { + let mut s = two_colours(); + let slice = run(&mut s, "object.slice.create", json!({"x": 0, "y": 0, "width": 20, "height": 30}))["id"].as_u64().unwrap(); + run(&mut s, "object.slice.select", json!({})); + let p = json!({"format": "gif", "dither": "none", "transparency": false}); + let (_, whole) = color_table_file(&mut s, merge(&p, json!({"slices": "none"}))); + let (v, bytes) = color_table_file(&mut s, merge(&p, json!({"slices": "selected"}))); + assert_eq!(bytes, whole, "{v}"); + let number = run(&mut s, "slice.list", json!({}))["slices"] + .as_array() + .unwrap() + .iter() + .find(|l| l["id"].as_u64() == Some(slice)) + .map(|l| l["number"].clone()) + .unwrap(); + let e = s.execute("document.exportForWeb.saveColorTable", &merge(&p, json!({"slices": "selected", "slice": number}))).unwrap_err().to_string(); + assert!(e.contains("no selected slice"), "{e}"); +} + +/// The preview refuses a `slice` that is not a slice number instead of previewing the whole image. +#[test] +fn preview_refuses_a_slice_that_is_not_a_number() { + let mut s = two_colours(); + for slice in [json!("1"), json!(0), json!(-1), json!(1.5)] { + let e = s.execute("document.exportForWeb.preview", &json!({"slice": slice})).unwrap_err().to_string(); + assert!(e.contains("`slice` is a slice number"), "{slice}: {e}"); + } + assert!(s.execute("document.exportForWeb.preview", &json!({"slice": null})).is_ok()); +} + +/// Color table files are read as the published layout gives them: 768 bytes are 256 colors without +/// a transparent entry; 772 bytes add the count and the transparent index. +#[test] +fn color_table_files_are_read_by_the_published_layout() { + use cmd::webexport::read_act; + let long: Vec = (0..768).map(|i| (i % 251) as u8).collect(); + let t = read_act(&long).unwrap(); + assert_eq!((t.colors.len(), t.colors[0], t.colors[255], t.transparent), (256, [0, 1, 2], [12, 13, 14], None)); + let t = read_act(&act_layout(&["#ff0000", "#00ff00", "#0000ff"], Some(1))).unwrap(); + assert_eq!((t.colors, t.transparent), (vec![[255, 0, 0], [0, 255, 0], [0, 0, 255]], Some(1))); + assert_eq!(read_act(&act_layout(&["#ff0000", "#00ff00"], None)).unwrap().transparent, None); + // An index past the colors used names no entry. + assert_eq!(read_act(&act_layout(&["#ff0000", "#00ff00"], Some(2))).unwrap().transparent, None); + let mut zero = act_layout(&["#ff0000"], None); + zero[768..770].copy_from_slice(&0u16.to_be_bytes()); + let mut over = act_layout(&["#ff0000"], None); + over[768..770].copy_from_slice(&257u16.to_be_bytes()); + for bad in [vec![], vec![0; 767], vec![0; 769], vec![0; 771], vec![0; 773], zero, over] { + assert!(read_act(&bad).unwrap_err().contains("not a color table"), "{} bytes", bad.len()); + } +} + +/// Load Color Table makes the file's colors the fixed palette, other than its transparent entry, +/// with the file's color count; the preview of the loaded settings writes those colors. +#[test] +fn load_color_table_makes_the_file_the_fixed_palette() { + let mut s = two_colours(); + let file = act_layout(&["#00ff00", "#ffffff", "#ff0000"], Some(1)); + let table = json!({ + "deleted": ["#0000ff"], "shifted": {"#ff0000": "#111111"}, "webShift": ["#ff0000"], "locked": ["#ff0000"], + "transparent": ["#00ff00"], "sort": "hue", + }); + let p = json!({"format": "gif", "dither": "none", "transparency": false, "webSnap": 100, "colorTable": table}); + let v = run(&mut s, "webExport.loadColorTable", merge(&p, json!({"dataBase64": vectorcraft_format::base64_encode(&file)}))); + assert_eq!((&v["colors"], &v["transparentIndex"]), (&json!(["#00ff00", "#ffffff", "#ff0000"]), &json!(1))); + let settings = &v["settings"]; + assert_eq!((&settings["colors"], &settings["webSnap"]), (&json!(3), &json!(0))); + let table = &settings["colorTable"]; + assert_eq!( + (&table["customPalette"], &table["deleted"], &table["shifted"], &table["webShift"]), + (&json!(["#00ff00", "#ff0000"]), &json!([]), &json!({}), &json!([])) + ); + assert_eq!((&table["locked"], &table["transparent"], &table["sort"]), (&json!([]), &json!([]), &json!("none"))); + // The loaded palette is what the image is written with: blue takes the nearest loaded color. + let pv = run(&mut s, "document.exportForWeb.preview", settings.clone()); + let written: Vec<&str> = pv["colors"].as_array().unwrap().iter().map(|c| c["color"].as_str().unwrap()).collect(); + assert!(!written.is_empty() && written.iter().all(|c| ["#00ff00", "#ff0000"].contains(c)), "{pv}"); + // A table saved and loaded again keeps its colors. + let opaque = json!({"format": "png8", "dither": "none", "transparency": false}); + let saved = color_table_file(&mut s, opaque.clone()).1; + let again = run(&mut s, "webExport.loadColorTable", json!({"format": "png8", "dataBase64": vectorcraft_format::base64_encode(&saved)})); + let shown = run(&mut s, "document.exportForWeb.preview", opaque); + let before: Vec<&Value> = shown["colors"].as_array().unwrap().iter().map(|c| &c["color"]).collect(); + assert_eq!(again["colors"].as_array().unwrap().iter().collect::>(), before); + // A table whose only color is its transparent entry loads that color. + let only = act_layout(&["#336699"], Some(0)); + let v = run(&mut s, "webExport.loadColorTable", json!({"dataBase64": vectorcraft_format::base64_encode(&only)})); + assert_eq!((&v["settings"]["colorTable"]["customPalette"], &v["settings"]["colors"]), (&json!(["#336699"]), &json!(2))); +} + +/// Load Color Table reads a path, reads no more of a file than a color table takes, and refuses +/// bad params without changing the remembered settings. +#[test] +fn load_color_table_reads_a_path_and_refuses_bad_params() { + let dir = std::env::temp_dir().join(format!("vc-color-table-load-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = two_colours(); + let path = dir.join("t.act").to_string_lossy().into_owned(); + std::fs::write(&path, act_layout(&["#010203", "#040506"], None)).unwrap(); + let v = run(&mut s, "webExport.loadColorTable", json!({"path": path})); + assert_eq!(v["settings"]["colorTable"]["customPalette"], json!(["#010203", "#040506"])); + let large = dir.join("large.act").to_string_lossy().into_owned(); + std::fs::write(&large, vec![0u8; 1 << 20]).unwrap(); + let b64 = vectorcraft_format::base64_encode(&act_layout(&["#010203"], None)); + for (bad, says) in [ + (json!({"path": large}), "not a color table"), + (json!({"dataBase64": vectorcraft_format::base64_encode(&[0u8; 100])}), "not a color table"), + // A whole table with more data after it is too long. + (json!({"dataBase64": format!("{b64}AAAA")}), "not a color table"), + (json!({}), "give exactly one of `path` and `dataBase64`"), + (json!({"path": path, "dataBase64": b64}), "give exactly one of `path` and `dataBase64`"), + (json!({"dataBase64": "%%%"}), "bad dataBase64"), + (json!({"dataBase64": b64, "format": "jpg"}), "`jpg` has no color table"), + ] { + let e = s.execute("webExport.loadColorTable", &bad).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + assert!(s.last_web_settings().color_table.custom_palette.is_empty(), "nothing is remembered"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 446d441fc4..be4615bb43 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -222,6 +222,8 @@ impl Session { self.deactivate_tool(view)?; self.keep_tool_settings(); self.tool = self.make_tool(id); + // A pick is armed for a stop after its tool is chosen (`note_stop_pick`). + self.stop_pick = None; if let Some(selection) = text_selection { self.tool.set_option("textSelection", &selection); } @@ -460,7 +462,7 @@ impl Session { /// Pen goes on drawing its path), less the work the gesture ended as a command would: a /// Cmd+click that takes the type being edited out of the selection ends its edit (#3779). pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> { - let lent_by_bucket = self.lent_by_bucket(); + let lent_by_painter = self.lent_by_painter(); let Some(lender) = self.lender.take() else { return Ok(()) }; // The points the lent tool left picked go back to the tool it was lent to when that tool // picks mesh points, none when it unpicked them all (#8090). Group Selection and the @@ -470,12 +472,12 @@ impl Session { .then(|| self.tool.options().get("meshPoints").cloned()) .flatten() .filter(|p| lender.options().get("meshPoints") != Some(p)); - // The lent tool's last actions (a drag it cancels or keeps) still count as the Live Paint - // Bucket's when the bucket lent it ([`Session::bucket_paints`]). - let outer_bucket = self.back_to_bucket; - self.back_to_bucket |= lent_by_bucket; + // The lent tool's last actions (a drag it cancels or keeps) still count as those of the tool + // that lent it when that tool paints with the chosen colors ([`Session::tool_paints`]). + let outer_painter = self.back_to_painter; + self.back_to_painter = self.back_to_painter.or(lent_by_painter); let r = self.deactivate_tool(view); - self.back_to_bucket = outer_bucket; + self.back_to_painter = outer_painter; self.keep_tool_settings(); self.tool = lender; // Back with the Selection or Group Selection tool, a symbol part the lent Direct @@ -524,12 +526,17 @@ impl Session { } } } - // Alt switches the Pencil, Paintbrush or Blob Brush to Smooth, using Smooth Tool Options' Fidelity. + // Alt switches the Pencil, Paintbrush or Blob Brush to Smooth, using Smooth Tool Options' Fidelity + // and Smoothness. if matches!(t.id(), "pencil" | "paintbrush" | "blobBrush") && wanted("smooth") - && let Some(v) = prefs.tool_settings.get("smooth").and_then(|s| s.get("fidelity")) + && let Some(saved) = prefs.tool_settings.get("smooth") { - t.set_option("smoothFidelity", v); + for (key, alt) in [("fidelity", "smoothFidelity"), ("smoothness", "smoothSmoothness")] { + if let Some(v) = saved.get(key) { + t.set_option(alt, v); + } + } } } @@ -567,6 +574,7 @@ impl Session { let Some(st) = self.active.and_then(|i| self.docs.get(i)) else { return R::default() }; let (unit, stroke_unit) = (self.general_unit(), self.stroke_unit()); let smart_guides = view.smart_guides && !view.pixel_preview; + let (pick_stop, armed_for_tool) = self.pick_stop(); let cx = ToolContext { doc: &st.doc, ruler_origin: st.doc.ruler_origin_for(view.artboard), @@ -592,7 +600,8 @@ impl Session { corner_widgets: view.corner_widgets, shape_widgets: view.shape_widgets, fill_active: self.fill_active, - gradient_stop: self.selected_stop(), + gradient_stop: pick_stop, + tool_paints: self.tool_paints(!self.fill_active) || armed_for_tool, appearance_item: self.appearance_item(), constrain_angle: self.prefs.constrain_angle, keyboard_increment: self.prefs.keyboard_increment, @@ -1060,6 +1069,12 @@ impl Session { self.tool.wants_samples() } + /// Does a stroke the active tool draws now vary with an airbrush pen's finger wheel + /// ([`vectorcraft_tools::Tool::reads_wheel`])? False with no document open. + pub fn tool_reads_wheel(&mut self, view: ViewInfo) -> bool { + self.with_tool_cx(view, |t, cx| t.reads_wheel(cx)) + } + /// Is the active tool waiting for work it runs on another thread ([`Tool::waiting`]), is input /// held until an edit it computes is applied, or are requests for the UI left from making it? pub fn tool_waiting(&self) -> bool { @@ -1486,6 +1501,7 @@ impl Session { let before_press = self.options_before_press_set(); let sets_pressed = self.press_taken_by(self.tool.id()); self.tool.set_option(key, v); + self.note_stop_pick(key, self.tool.id() == "eyedropper"); self.tool_set_since_reset = true; self.keep_tool_settings(); self.keep_press_set(before_press, |k| sets_pressed && k == key, sets_pressed); @@ -1572,10 +1588,44 @@ impl Session { let set = other.id(); Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store)); } - self.keep_press_set(before_press, |k| sets_pressed && values.contains_key(k), sets_pressed); + // Another tool's set also names the keys of the stores it shares with the pressed tool. + let shared: Vec<&str> = match (self.pressed_tool().map(|t| t.id()), id) { + (Some(pressed), Some(set)) if pressed != set => settings::stores(pressed) + .filter(|(store, _)| settings::stores(set).any(|(s, _)| s == *store)) + .flat_map(|(_, keys)| keys.iter().copied()) + .collect(), + _ => Vec::new(), + }; + self.keep_press_set(before_press, |k| values.contains_key(k) && (sets_pressed || shared.contains(&k)), sets_pressed); + // The Eyedropper waiting for a Cmd-drag it lent a selection tool to is armed as the active one. + if (active || lender) && values.contains_key("stop") { + let eyedropper = id.unwrap_or(self.tool.id()) == "eyedropper"; + self.note_stop_pick("stop", eyedropper); + } out } + /// After option `key` of the active tool, or of the tool waiting for a Cmd-drag it lent, is set + /// (`eyedropper`: that tool is the Eyedropper): an Eyedropper armed to sample into a stop of the + /// gradient a tool paints with (`stop`) keeps whose gradient that is ([`Session::stop_pick`]). + fn note_stop_pick(&mut self, key: &str, eyedropper: bool) { + if key == "stop" && eyedropper { + let selected = self.selected_stop().is_some(); + self.stop_pick = self.gradient_stop.map(|(_, owner)| owner).filter(|owner| selected && owner.painter().is_some()); + } + } + + /// The stop an armed Eyedropper pick samples into ([`ToolContext::gradient_stop`]): the + /// selected one, and for a pick armed for a stop of the gradient a tool paints with + /// ([`Session::stop_pick`]) only a stop still selected on that gradient. + fn pick_stop(&self) -> (Option, bool) { + let armed = self.stop_pick.filter(|owner| self.tool.returns_to().is_some_and(|id| owner.painter() == Some(id))); + match armed { + Some(owner) => (self.selected_stop().filter(|_| self.gradient_stop.is_some_and(|(_, o)| o == owner)), true), + None => (self.selected_stop(), false), + } + } + /// The tool that took the press under way: the active tool, or the tool that lent a selection /// tool for it (a Cmd-drag), which the dropped press gives its options back to. fn pressed_tool(&self) -> Option<&dyn Tool> { @@ -1743,10 +1793,16 @@ impl Session { self.put_back_interaction(); } let outer = std::mem::replace(&mut self.in_tool_actions, true); - let outer_bucket = self.back_to_bucket; - // The Eyedropper's sample into a stop of the Live Paint Bucket's gradient, which switches back to the bucket. - self.back_to_bucket |= - self.tool.id() == "eyedropper" && acts.iter().any(|a| matches!(a, Action::SwitchTool(t) if t == crate::cmd::LIVE_PAINT_BUCKET)); + let outer_painter = self.back_to_painter; + // The Eyedropper's sample into a stop of the gradient of a tool that paints with the chosen + // colors (the Live Paint Bucket, the Shape Builder), which switches back to that tool. + if self.tool.id() == "eyedropper" { + let back = acts.iter().find_map(|a| match a { + Action::SwitchTool(t) => crate::cmd::painting_tool_of(t, false).or_else(|| crate::cmd::painting_tool_of(t, true)), + _ => None, + }); + self.back_to_painter = self.back_to_painter.or(back); + } // A preview that settling applied (typing kept as its own step before a drag begins) shows // its warning in the status bar, as the tool's own commit shows its preview's. let r = if !outer && self.depth == 0 { @@ -1756,7 +1812,7 @@ impl Session { self.apply_tool_actions(acts) }; self.in_tool_actions = outer; - self.back_to_bucket = outer_bucket; + self.back_to_painter = outer_painter; if !outer && self.depth == 0 { self.trim_histories(); } diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index c07d741265..51f6f2a41d 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -939,6 +939,32 @@ fn saved_color_settings_that_cannot_be_used_leave_the_defaults() { } } +/// With a working RGB space other than sRGB, `color.contrast` writes the background in working RGB, +/// the form `against` takes: a given brown comes back as it was given, and the background read +/// behind the selection, given back, answers the same ratio. +#[test] +fn contrast_writes_the_background_as_against_takes_it_with_another_working_space() { + let _g = settings(); + let before = cms::active_settings(); + let mut s = session(); + exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB})); + let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#806040"})); + exec(&mut s, "file.new", json!({"width": 200, "height": 200})); + exec(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 80.3, "height": 160})); + exec(&mut s, "paint.setFill", json!({"color": "#2050a0"})); + exec(&mut s, "object.lock", json!({})); + exec(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})); + exec(&mut s, "paint.setFill", json!({"color": "#808080"})); + let below = s.execute("color.contrast", &json!({})); + let again = below.as_ref().ok().and_then(|b| s.execute("color.contrast", &json!({"against": b["against"].clone()})).ok()); + cms::set_active(&before).unwrap(); + let given = given.unwrap(); + assert_eq!(given["against"], "#806040", "{given}"); + let (below, again) = (below.unwrap(), again.unwrap()); + assert_eq!(below["against"], again["against"], "{below} {again}"); + assert!((below["ratio"].as_f64().unwrap() - again["ratio"].as_f64().unwrap()).abs() < 1e-9, "{below} {again}"); +} + /// View › Proof Setup › Customize's Preserve CMYK Numbers proofs each color from its own inks: /// with Device CMYK as the working space, C50 M50 Y50 and K50 show as the same gray, and on /// VectorCraft Generic CMYK they print, and so proof, as different grays; a pattern's tile art @@ -1767,6 +1793,37 @@ fn paste_on_all_artboards_leaves_artboard_backgrounds_out() { assert!(r.get("profileMismatch").is_none(), "{r}"); } +/// The swatch conflicts Paste on All Artboards raises leave copied artboard backgrounds out, as the +/// paste does: pasting back into the document the objects came from, where only the RGB background +/// of the copied artboard now has another profile, converts nothing for it, so its edited CMYK +/// swatch raises no conflict. A plain paste, which brings the background and converts it, compares +/// the swatches and lists the edited one. +#[test] +fn swatch_conflicts_on_all_artboards_leave_artboard_backgrounds_out() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + exec(&mut s, "swatch.new", json!({"name": "Brand", "color": {"c": 20, "m": 40, "y": 60, "k": 10}, "global": true})); + let ink = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [ink.0], "swatch": "Brand"})); + exec(&mut s, "paint.setStroke", json!({"ids": [ink.0], "none": true})); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "edit.assignProfile", json!({"rgb": null})); + exec(&mut s, "swatch.edit", json!({"name": "Brand", "color": {"c": 60, "m": 40, "y": 20, "k": 0}})); + let conflicts = |s: &mut Session, p: serde_json::Value| exec(s, "clipboard.conflicts", p)["swatches"].as_array().unwrap().len(); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert"})), 1, "a plain paste converts the RGB background"); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": true})), 0); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": false})), 1); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert", "allArtboards": null})), 1, "null is the default"); + for bad in [json!("yes"), json!(1)] { + assert!(s.execute("clipboard.conflicts", &json!({ "allArtboards": bad })).is_err(), "{bad}"); + } + let r = exec(&mut s, "edit.pasteOnAllArtboards", json!({"profileMismatch": "convert"})); + assert!(r.get("profileMismatch").is_none(), "{r}"); +} + /// A converting paste back into the document the objects came from (its profile changed since the /// copy) still takes its image blobs as the document's own: an image whose blob under its key /// changed since keeps that key, and so shows the document's blob. diff --git a/crates/engine/tests/it/param_keys.rs b/crates/engine/tests/it/param_keys.rs index cb364167a2..fb30bf3c5c 100644 --- a/crates/engine/tests/it/param_keys.rs +++ b/crates/engine/tests/it/param_keys.rs @@ -263,6 +263,56 @@ fn a_tone_curve_channel_it_does_not_have_is_refused() { assert_eq!(back.layers[0].children().unwrap()[0].appearance.effects[0].params["channel"], json!("alpha")); } +/// A Drop Shadow's or glow's `mode` that names no blend mode (which it drew as Normal) is refused +/// in new calls to `effect.apply`, `appearance.addEffect` and `effect.setParams`, with the modes it +/// takes, and the document and its undo history stay as they were. Blend-mode names in any +/// spelling pass, an omitted `mode` keeps the default, and an older saved step still plays. +#[test] +fn a_shadow_or_glow_mode_that_is_no_blend_mode_is_refused() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"opacity": 50}})).unwrap(); + let state = |s: &Session| { + let st = s.active().unwrap(); + (st.doc.clone(), st.history.undo.len()) + }; + let before = state(&s); + let why = "`mode` must be one of normal, darken, multiply, colorBurn"; + for bad in [json!("multipy"), json!(""), json!("passThrough"), json!(null), json!(["multiply"]), json!(1), json!(false)] { + for (cmd, params) in [ + ("effect.setParams", json!({"index": 0, "params": {"mode": bad}})), + ("effect.apply", json!({"effect": "stylize.innerGlow", "params": {"mode": bad}})), + ("effect.apply", json!({"effect": null, "id": "stylize.dropShadow", "ids": [id], "params": {"mode": bad}})), + ("appearance.addEffect", json!({"effect": "stylize.outerGlow", "params": {"mode": bad}})), + ] { + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(e.contains(why), "{cmd} {params}: {e}"); + let checked = s.check_params(cmd, ¶ms).unwrap_err().to_string(); + assert!(checked.contains(why), "{cmd} {params}: {checked}"); + assert!(state(&s) == before, "{cmd} {params} changed the document or its undo history"); + } + } + let effect = |s: &Session| s.active().unwrap().doc.layers[0].children().unwrap()[0].appearance.effects[0].clone(); + let shadow = effect(&s); + let drawn = vectorcraft_render::effects::merged_params(&shadow.id, &shadow.params); + assert_eq!(drawn["mode"], json!("multiply"), "an omitted mode keeps the default"); + for good in ["screen", "Color Burn", "color-burn", "COlor!!Burn#", "softLight", "LUMINOSITY"] { + let params = json!({"index": 0, "params": {"mode": good}}); + s.check_params("effect.setParams", ¶ms).unwrap_or_else(|e| panic!("{good}: {e}")); + s.execute("effect.setParams", ¶ms).unwrap_or_else(|e| panic!("{good}: {e}")); + assert_eq!(effect(&s).params["mode"], json!(good)); + } + s.replay("effect.setParams", &json!({"index": 0, "params": {"mode": "multipy"}})).unwrap(); + assert_eq!(effect(&s).params["mode"], json!("multipy")); + assert_eq!(vectorcraft_render::effects::blend_mode("multipy"), vectorcraft_color::BlendMode::Normal); + for mode in vectorcraft_color::BlendMode::ALL { + let id = vectorcraft_render::effects::blend_mode_id(mode); + assert_eq!(vectorcraft_render::effects::parse_blend_mode(&id), Some(mode)); + assert_eq!(vectorcraft_render::effects::blend_mode(&id), mode); + } +} + /// What a command adds to its own journal entry passes the check, so a recorded journal can be /// sent back through the control channel or MCP. #[test] diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 2ec927bd48..1c44685198 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -41,7 +41,8 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// The names the host adds that stay inside the document and the run, by the object that has them. /// Reading a file or a folder, a file dialog and a message to the person do not change anything -/// outside it. +/// outside it. The document model (`app`, its classes and the enumerations) acts on the open +/// documents; `Document.saveAs` and `close` throw "not available yet". const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder UnitValue alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), @@ -72,8 +73,74 @@ const INSIDE: &[(&str, &str)] = &[ "absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \ getRelativeURI localizedName modified name parent path relativeURI resolve selectDlg toString", ), + ( + "", + "activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ + DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ + Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= Tag Tags ZOrderMethod", + ), + ("Application.", "prototype"), + ( + "Application.prototype.", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \ + getIsFileOpen selection selection= toString typename", + ), + ("DocumentPreset.", "prototype"), + ( + "DocumentPreset.prototype.", + "artboardLayout artboardLayout= artboardRowsOrCols artboardRowsOrCols= artboardSpacing artboardSpacing= colorMode \ + colorMode= constructor documentBleedLink documentBleedLink= documentBleedOffsetRect documentBleedOffsetRect= height \ + height= numArtboards numArtboards= previewMode previewMode= rasterResolution rasterResolution= title title= \ + toString transparencyGrid transparencyGrid= typename units units= width width=", + ), + ("Documents.", "prototype"), + ("Documents.prototype.", "add addDocument constructor getByName index length parent toString typename"), + ("Document.", "prototype"), + ( + "Document.prototype.", + "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ + groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ + rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames textFrames= toString \ + typename views views= width", + ), + ("Layer.", "prototype"), + ("Layer.prototype.", "constructor name toString typename"), + ("PageItems.", "prototype"), + ("PageItems.prototype.", "constructor getByName index length parent removeAll toString typename"), + ("PageItem.", "prototype"), + ( + "PageItem.prototype.", + "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ + controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ + left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ + position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags toString top top= transform \ + transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ + width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", + ), + ("Tags.", "prototype"), + ("Tags.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Tag.", "prototype"), + ("Tag.prototype.", "constructor name name= parent remove typename value value="), + ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), + ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), + ("DocumentColorSpace.", "CMYK RGB"), + ("DocumentPresetType.", "BasicCMYK BasicRGB Mobile Print Video Web"), + ("DocumentPreviewMode.", "DefaultPreview OverprintPreview PixelPreview"), + ("DocumentRasterResolution.", "HighResolution MediumResolution ScreenResolution"), + ( + "DocumentTransparencyGrid.", + "TransparencyGridBlue TransparencyGridDark TransparencyGridGreen TransparencyGridLight TransparencyGridMedium \ + TransparencyGridNone TransparencyGridOrange TransparencyGridPurple TransparencyGridRed", + ), + ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), + ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), + ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; +/// The classes the host adds with nothing but a prototype and its constructor: the page item types. +const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ + PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; + /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. const NOT_CHECKED: &str = "vc"; @@ -93,6 +160,9 @@ const LIST: &str = r#"(function () { var globals = Object.getOwnPropertyNames(g); add(g, ""); for (var i = 0; i < globals.length; i++) { + // A global with a getter, such as `activeDocument`, is not read: it throws with no document open. + var gd = Object.getOwnPropertyDescriptor(g, globals[i]); + if (gd && gd.get) continue; var v = g[globals[i]]; if (v !== null && (typeof v == "object" || typeof v == "function")) { add(v, globals[i] + "."); @@ -120,7 +190,8 @@ fn language_names() -> BTreeSet { fn table_names() -> BTreeSet { let inside = INSIDE.iter().flat_map(|(prefix, names)| names.split_whitespace().map(move |n| format!("{prefix}{n}"))); - OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain([NOT_CHECKED.to_string()]).collect() + let bare = BARE_CLASSES.split_whitespace().flat_map(|c| [c.to_string(), format!("{c}.prototype"), format!("{c}.prototype.constructor")]); + OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain(bare).chain([NOT_CHECKED.to_string()]).collect() } #[test] diff --git a/crates/engine/tests/plugin_clear_cache.rs b/crates/engine/tests/plugin_clear_cache.rs index 7a323390c9..488c094c63 100644 --- a/crates/engine/tests/plugin_clear_cache.rs +++ b/crates/engine/tests/plugin_clear_cache.rs @@ -39,6 +39,7 @@ fn clearing_every_cache_empties_each_plugins_cache_and_keeps_its_settings() { let _ = std::fs::remove_dir_all(&folder); std::fs::create_dir_all(&folder).unwrap(); let ids = ["test.clearcache.a", "test.clearcache.b"]; + vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory(); let mut s = Session::new(); s.allow_plugin_grants_from_requests(); s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 33bc8bc299..911b39de34 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -1011,6 +1011,7 @@ proptest! { let store = Store(std::env::temp_dir().join(format!("vectorcraft-plugin-fuzz-storage-{}", std::process::id()))); let _ = std::fs::remove_dir_all(&store.0); let folder = store.0.clone(); + vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory(); let mut s = Session::new(); s.allow_plugin_grants_from_requests(); s.attach_plugin_store(folder.clone()); diff --git a/crates/engine/tests/plugin_js.rs b/crates/engine/tests/plugin_js.rs new file mode 100644 index 0000000000..0b5558da11 --- /dev/null +++ b/crates/engine/tests/plugin_js.rs @@ -0,0 +1,127 @@ +//! JavaScript filter plug-ins through the engine: a `.vcplugin` manifest and the `.js` file it +//! names install with `plugin.install {path}`, run with `plugin.run` as one undo step, and a run +//! that fails or exhausts its budget leaves the document as it was. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_engine::Session; +use vectorcraft_testkit::fixtures::{exec, rect, select, session}; + +/// Paints every input object's first fill blue. +const BLUE: &str = "function run(input, params) {\n\ + return {objects: input.objects.map(function (o) {\n\ + return {id: o.id, fills: [{type: 'solid', color: {model: 'rgb', r: 0, g: 0, b: 1}}]};\n\ + })};\n\ +}\n"; + +/// An empty folder for one test, with anything an earlier run left there removed. +fn folder(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("vc-plugin-js-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// Writes the manifest of filter `id`, whose code is `tint.js`, with `extra` keys, and `script` as +/// that file → the manifest's path. +fn package(dir: &Path, id: &str, extra: Value, script: Option<&str>) -> String { + let mut m = json!({"id": id, "name": "Tint", "kind": "filter", "runtime": "js", "script": "tint.js"}); + if let (Some(m), Value::Object(extra)) = (m.as_object_mut(), extra) { + m.extend(extra); + } + let path = dir.join(format!("{id}.vcplugin")); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + if let Some(script) = script { + std::fs::write(dir.join("tint.js"), script).unwrap(); + } + path.display().to_string() +} + +/// The active document's layers and its undo steps. +fn state(s: &mut Session) -> (Value, usize) { + let layers = exec(s, "document.inspect", json!({}))["layers"].take(); + (layers, s.doc().unwrap().history.undo.len()) +} + +fn fill(s: &Session, id: vectorcraft_doc::NodeId) -> Option { + s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color() +} + +#[test] +fn a_javascript_filter_changes_a_fill_as_one_undo_step() { + let dir = folder("blue"); + let mut s = session(); + let path = package(&dir, "test.js.engine.blue", json!({}), Some(BLUE)); + let info = exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + assert_eq!((info["runtime"].as_str(), info["script"].as_str(), info["kind"].as_str()), (Some("js"), Some("tint.js"), Some("filter"))); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + exec(&mut s, "paint.setFill", json!({"ids": [id.0], "color": "#ff0000"})); + select(&mut s, &[id]); + let before = state(&mut s); + let r = exec(&mut s, "plugin.run", json!({"id": "test.js.engine.blue"})); + assert_eq!(r["ids"], json!([id.0])); + assert_eq!(fill(&s, id).map(|c| c.to_rgb_uncalibrated()), Some([0.0, 0.0, 1.0])); + assert_eq!(state(&mut s).1, before.1 + 1, "one undo step"); + exec(&mut s, "edit.undo", json!({})); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.blue"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// An endless loop ends with the plug-in's instruction budget, the error names the plug-in, and the +/// document and its history stay as they were. +#[test] +fn an_endless_loop_stops_on_its_budget_and_changes_nothing() { + let dir = folder("loop"); + let mut s = session(); + let path = package(&dir, "test.js.engine.loop", json!({}), Some("function run(input) {\n while (true) {}\n}\n")); + exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + select(&mut s, &[id]); + let before = state(&mut s); + let e = s.execute("plugin.run", &json!({"id": "test.js.engine.loop"})).unwrap_err().to_string(); + assert!(e.contains("instruction budget") && e.contains("test.js.engine.loop, tint.js line 2"), "{e}"); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.loop"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A filter that reads `File` throws a `ReferenceError`: the realm has none of the script runner's +/// file access. Nothing changes. +#[test] +fn a_javascript_filter_has_no_file_access() { + let dir = folder("file"); + let mut s = session(); + let path = package(&dir, "test.js.engine.file", json!({}), Some("function run(input) {\n return new File('/etc/passwd').read();\n}\n")); + exec(&mut s, "plugin.install", json!({"path": path, "replace": true})); + let id = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + select(&mut s, &[id]); + let before = state(&mut s); + let e = s.execute("plugin.run", &json!({"id": "test.js.engine.file"})).unwrap_err().to_string(); + assert!(e.contains("ReferenceError") && e.contains("File") && e.contains("test.js.engine.file"), "{e}"); + assert_eq!(state(&mut s), before); + exec(&mut s, "plugin.remove", json!({"id": "test.js.engine.file"})); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A manifest with `"runtime": "js"` and no `script` is refused at install, the error names the +/// key, and nothing is installed. +#[test] +fn a_manifest_without_its_script_is_refused_at_install() { + let dir = folder("noscript"); + let mut s = session(); + let path = package(&dir, "test.js.engine.noscript", json!({"script": null}), None); + let mut m: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + m.as_object_mut().unwrap().remove("script"); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + for cmd in ["plugin.inspect", "plugin.install"] { + let e = s.execute(cmd, &json!({"path": path})).unwrap_err().to_string(); + assert!(e.contains("`runtime` \"js\" needs `script`"), "{cmd}: {e}"); + } + assert!(vectorcraft_plugins::registry::get("test.js.engine.noscript").is_none()); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/engine/tests/plugin_place.rs b/crates/engine/tests/plugin_place.rs new file mode 100644 index 0000000000..e5996c7a36 --- /dev/null +++ b/crates/engine/tests/plugin_place.rs @@ -0,0 +1,323 @@ +//! Importer plug-ins whose manifests set `place` (docs/plugins.md › Importers) through `file.place`: +//! which files they are given, the group their objects become in the open document, and what happens +//! when they fail, decline or are canceled. +//! +//! A test binary of its own: installed plug-ins are process-wide, and the unit tests that check the +//! exact list of formats would see these ones. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_engine::cmd::fileio; +use vectorcraft_engine::{EngineError, Session}; +use vectorcraft_plugins::wat::{self as tpl, Given}; + +/// An importer's output: a red rectangle "A" from (10, 20) to (110, 70) under a line "B" from +/// (10, 20) to (60, 20), and a warning. +const ART: &str = r#"{"objects":[{"type":"path","name":"A","path":{"subpaths":[{"closed":true,"anchors":[{"p":[10,20]},{"p":[110,20]},{"p":[110,70]},{"p":[10,70]}]}]},"fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]},{"type":"path","name":"B","path":{"subpaths":[{"closed":false,"anchors":[{"p":[10,20]},{"p":[60,20]}]}]}}],"warnings":["1 layer merged"]}"#; + +/// An importer's output: the rectangle "A" of [`ART`] and a guide "G" from (500, 500) to (900, 500). +const GUIDED: &str = r#"{"objects":[{"type":"path","name":"A","path":{"subpaths":[{"closed":true,"anchors":[{"p":[10,20]},{"p":[110,20]},{"p":[110,70]},{"p":[10,70]}]}]},"fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]},{"type":"path","name":"G","guide":true,"path":{"subpaths":[{"closed":false,"anchors":[{"p":[500,500]},{"p":[900,500]}]}]}}]}"#; + +/// The `vc_run` body of an importer that never returns. +const SPINS: &str = "(loop $l (br $l)) (i64.const 0)"; + +/// The manifest of an importer `id` reading `extensions` (a JSON list) that places its files. +fn placing(id: &str, extensions: &str) -> String { + format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"importer","extensions":{extensions},"place":true}}"#) +} + +/// Installs the plug-in written in WAT `src` → its `plugin.list` entry. +fn install(s: &mut Session, src: &str) -> Value { + let wasm = wat::parse_str(src).unwrap_or_else(|e| panic!("bad test WAT: {e}")); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap() +} + +/// `file.place` of a file `name` holding `bytes`, with more params `extra`. +fn place(s: &mut Session, name: &str, bytes: &[u8], extra: Value) -> Result { + let mut p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + s.execute("file.place", &p) +} + +/// A session with a new document holding one rectangle, selected. +fn with_document() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 400.0, "y": 400.0, "width": 20.0, "height": 10.0})).unwrap(); + s +} + +/// The active document's undo and redo steps, layers and content. +fn state(s: &mut Session) -> (usize, usize, usize, Value) { + let content = s.execute("document.inspect", &json!({})).unwrap(); + let d = s.doc().unwrap(); + (d.history.undo.len(), d.history.redo.len(), d.doc.layers.len(), content) +} + +/// A placed group: its name, the names of its children, and its bounds as `(x0, y0, x1, y1)`. +type Placed = (Option, Vec>, (f64, f64, f64, f64)); + +/// The group `id` of the active document. +fn object(s: &Session, id: u64) -> Placed { + let d = &s.doc().unwrap().doc; + let n = d.node(NodeId(id)).expect("placed"); + let kids = match &n.kind { + NodeKind::Group { children, clip: false } => children.iter().map(|c| c.name.clone()).collect(), + other => panic!("not a group: {other:?}"), + }; + let b = n.geometric_bounds_with(&d.symbol_boxes()).unwrap(); + (n.name.clone(), kids, (b.x0, b.y0, b.x1, b.y1)) +} + +/// A file only a placing importer reads is placed as one group named after the file, its objects in +/// the order the importer returned them and centered on `at`, embedded (also with `link: true`), as +/// one undo step that undo takes back whole. +#[test] +fn a_placing_importer_places_one_group_as_one_undo_step() { + let mut s = with_document(); + let entry = install(&mut s, &tpl::returning(&placing("test.place.one", r#"["tpo"]"#), ART)); + assert_eq!((&entry["place"], &entry["permissions"]), (&json!(true), &json!(["import.read"]))); + let formats = s.execute("document.formats", &json!({})).unwrap(); + let listed = formats["formats"].as_array().unwrap().iter().find(|f| f["id"] == "plugin.test.place.one").expect("listed"); + assert_eq!(listed["place"], json!(true)); + + let before = state(&mut s); + let r = place(&mut s, "Shapes.tpo", b"?", json!({"at": [300, 400], "link": true})).unwrap(); + assert_eq!( + (&r["format"], &r["linked"], &r["warnings"], &r["name"]), + (&json!("plugin.test.place.one"), &json!(false), &json!(["1 layer merged"]), &json!("Shapes.tpo")) + ); + let ids = r["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 1); + let id = ids[0].as_u64().unwrap(); + let (name, kids, bounds) = object(&s, id); + assert_eq!((name.as_deref(), kids), (Some("Shapes.tpo"), vec![Some("A".to_string()), Some("B".to_string())])); + assert_eq!(bounds, (250.0, 375.0, 350.0, 425.0)); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(id)]); + let after = state(&mut s); + assert_eq!(after.0, before.0 + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + let undone = state(&mut s); + assert_eq!((undone.0, undone.1, undone.2), (before.0, 1, before.2)); + assert_eq!((&undone.3["layers"], &undone.3["history"]), (&before.3["layers"], &before.3["history"])); +} + +/// `rect` fits the group in with its aspect, Template puts it on a new template layer, Replace swaps +/// the selected object at its center and stacking place, and `file.place.info` and the place cursor +/// read the file the same way. +#[test] +fn placing_follows_rect_template_and_replace() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.ways", r#"["tpw"]"#), ART)); + let r = place(&mut s, "a.tpw", b"?", json!({"rect": [0, 0, 50, 50]})).unwrap(); + assert_eq!(object(&s, r["ids"][0].as_u64().unwrap()).2, (0.0, 12.5, 50.0, 37.5)); + + let layers = s.doc().unwrap().doc.layers.len(); + let r = place(&mut s, "b.tpw", b"?", json!({"template": true})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.len(), layers + 1); + let layer = d.layer_of(NodeId(r["ids"][0].as_u64().unwrap())).and_then(|l| d.node(l)).unwrap(); + assert!(matches!(layer.kind, NodeKind::Layer { template: true, .. }) && layer.locked); + + let rect = s.execute("shape.rectangle", &json!({"x": 400.0, "y": 100.0, "width": 20.0, "height": 10.0})).unwrap(); + let old = NodeId(rect["id"].as_u64().unwrap()); + let (parent, index, _) = s.doc().unwrap().doc.position(old).unwrap(); + let r = place(&mut s, "c.tpw", b"?", json!({"replace": true})).unwrap(); + let id = NodeId(r["ids"][0].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + assert!(d.node(old).is_none()); + assert_eq!(d.position(id).map(|(p, i, _)| (p, i)), Some((parent, index))); + assert_eq!(object(&s, id.0).2, (360.0, 80.0, 460.0, 130.0)); + + let info = s.execute("file.place.info", &json!({"name": "d.tpw", "dataBase64": vectorcraft_format::base64_encode(b"?")})).unwrap(); + assert_eq!((&info["format"], &info["width"], &info["height"]), (&json!("plugin.test.place.ways"), &json!(100.0), &json!(50.0))); + let q = s.execute("file.place.queue", &json!({"files": [{"name": "e.tpw", "dataBase64": vectorcraft_format::base64_encode(b"?")}]})).unwrap(); + assert_eq!((&q["count"], &q["files"][0]["format"], &q["skipped"]), (&json!(1), &json!("plugin.test.place.ways"), &json!([]))); +} + +/// Guides the importer returns are left out of the placed group, and its box is that of the art +/// left, so a guide beside the art doesn't move it; output of guides alone places nothing. +#[test] +fn guides_are_left_out_of_what_is_placed() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.guided", r#"["tpg"]"#), GUIDED)); + let r = place(&mut s, "a.tpg", b"?", json!({"at": [300, 400]})).unwrap(); + let (_, kids, bounds) = object(&s, r["ids"][0].as_u64().unwrap()); + assert_eq!((kids, bounds), (vec![Some("A".to_string())], (250.0, 375.0, 350.0, 425.0))); + let info = s.execute("file.place.info", &json!({"name": "b.tpg", "dataBase64": vectorcraft_format::base64_encode(b"?")})).unwrap(); + assert_eq!((&info["width"], &info["height"]), (&json!(100.0), &json!(50.0))); + + let guides = r#"{"objects":[{"type":"path","guide":true,"path":{"subpaths":[{"closed":false,"anchors":[{"p":[0,0]},{"p":[100,0]}]}]}}]}"#; + install(&mut s, &tpl::returning(&placing("test.place.guides", r#"["tpq"]"#), guides)); + let before = state(&mut s); + let e = place(&mut s, "c.tpq", b"?", json!({})).unwrap_err().to_string(); + assert!(e.contains("`c.tpq` has no art to place"), "{e}"); + assert_eq!(state(&mut s), before); +} + +/// The importer is told it places the file (`_context.mode`), with the file's extension and name, +/// and is given its parameters. +#[test] +fn the_importer_is_told_it_places() { + let mut s = with_document(); + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#; + let manifest = placing("test.place.mode", r#"["tpm"]"#).replace(r#""place":true"#, &format!(r#""place":true,"params":{params}"#)); + for (i, needle) in [r#""mode":"place""#, r#""extension":"tpm""#, r#""name":"Shapes""#, r#""density":10.0"#].into_iter().enumerate() { + // ART when the parameters hold the needle; the file, which isn't JSON, otherwise. + let wasm = wat::parse_str(tpl::when_given(&manifest, Given::Params, needle, ART)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "replace": i > 0})).unwrap(); + let r = place(&mut s, "Shapes.tpm", b"not json", json!({"params": {"density": 12}})); + assert_eq!(r.map(|r| r["format"].clone()).map_err(|e| e.to_string()), Ok(json!("plugin.test.place.mode")), "{needle}"); + } + let before = state(&mut s); + let e = place(&mut s, "Shapes.tpm", b"", json!({"params": {"density": "lots"}})).unwrap_err(); + assert!(matches!(e, EngineError::BadParams { .. }), "{e}"); + assert_eq!(state(&mut s), before); +} + +/// Built-in formats keep their files: an importer that lists `svg` places an `.svg` only when +/// `importer` names it. An importer whose manifest doesn't set `place` opens its files and places +/// none: File › Place doesn't read them, and naming it is an error, as is naming it for a file of an +/// extension it doesn't list. +#[test] +fn built_in_formats_and_open_only_importers_keep_their_files() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.svg", r#"["tps","svg"]"#), ART)); + install(&mut s, &tpl::returning(&tpl::importer("test.place.openonly", r#"["tpx"]"#, "{}"), ART)); + let svg = br#""#; + assert_eq!(place(&mut s, "a.svg", svg, json!({})).unwrap()["format"], "svg"); + assert_eq!(place(&mut s, "b.svg", svg, json!({"importer": "plugin.test.place.svg"})).unwrap()["format"], "plugin.test.place.svg"); + assert_eq!(place(&mut s, "c.tps", svg, json!({})).unwrap()["format"], "svg", "an SVG named as the importer's file"); + + let before = state(&mut s); + let e = place(&mut s, "d.tpx", b"?", json!({})).unwrap_err().to_string(); + assert!(e.contains("not a format VectorCraft reads"), "{e}"); + let e = place(&mut s, "d.tpx", b"?", json!({"importer": "plugin.test.place.openonly"})).unwrap_err().to_string(); + assert!(e.contains("doesn't place them") && e.contains("Test test.place.openonly"), "{e}"); + let e = place(&mut s, "d.tpx", b"?", json!({"importer": "plugin.test.place.svg"})).unwrap_err().to_string(); + assert!(e.contains(".tps, .svg") && e.contains("d.tpx"), "{e}"); + let e = place(&mut s, "d.tps", b"?", json!({"importer": 3})).unwrap_err().to_string(); + assert!(e.contains("`importer` must be"), "{e}"); + assert_eq!(state(&mut s), before); + // The open-only importer still opens its files. + let r = s.execute("document.open", &json!({"name": "d.tpx", "dataBase64": vectorcraft_format::base64_encode(b"?")})).unwrap(); + assert_eq!(r["format"], "plugin.test.place.openonly"); +} + +/// File › Place's dialog lists a placing importer's extensions, under its name and in "All placeable +/// files", and not an open-only importer's; relinking an image keeps the built-in filters. A file only +/// a placing importer reads is dropped onto the canvas to be placed rather than opened. +#[test] +fn the_place_dialog_lists_placing_importers() { + let mut s = Session::new(); + install(&mut s, &tpl::returning(&placing("test.place.list", r#"["tpl","svg"]"#), ART)); + install(&mut s, &tpl::returning(&tpl::importer("test.place.listopen", r#"["tpy"]"#, "{}"), ART)); + let filters: Vec<_> = fileio::place_dialog_filters().collect(); + assert!(filters.contains(&("Test test.place.list", &["tpl"][..])), "{filters:?}"); + let all = filters.first().unwrap(); + assert_eq!(all.0, "All placeable files"); + assert!(all.1.contains(&"tpl") && !all.1.contains(&"tpy"), "{all:?}"); + assert_eq!(all.1.iter().filter(|e| **e == "svg").count(), 1); + assert!(!filters.iter().any(|(_, exts)| exts.contains(&"tpy"))); + assert!(!fileio::place_filters().any(|(_, exts)| exts.contains(&"tpl"))); + assert!(fileio::places_with_importer("x.TPL") && !fileio::opens_with_importer("x.tpl")); + assert!(!fileio::places_with_importer("x.tpy") && fileio::opens_with_importer("x.tpy")); + assert!(!fileio::places_with_importer("x.svg")); +} + +/// Nothing is placed, and the document keeps its content and undo steps, when the importer declines, +/// returns output that doesn't pass the checks, traps or is canceled, or when the file is larger +/// than an importer reads: that file is refused from its size, before it is read. +#[test] +fn failures_place_nothing() { + let mut s = with_document(); + let far = r#"{"objects":[{"type":"path","path":{"subpaths":[{"closed":false,"anchors":[{"p":[0,0]},{"p":[9000000,0]}]}]}}]}"#; + let cases = [ + ("test.place.fail.declines", r#"{"error":"Not a drawing."}"#, "Not a drawing."), + ("test.place.fail.notjson", "not json", "JSON"), + ("test.place.fail.empty", r#"{"objects":[]}"#, "the importer returned no objects"), + ("test.place.fail.key", r#"{"objects":[],"layers":[]}"#, "not `layers`"), + ("test.place.fail.far", far, "4000000"), + ( + "test.place.fail.point", + r#"{"objects":[{"type":"path","path":{"subpaths":[{"closed":false,"anchors":[{"p":[5,5]}]}]}}]}"#, + "no art to place", + ), + ]; + for (id, output, _) in cases { + install(&mut s, &tpl::returning(&placing(id, r#"["tpf"]"#), output)); + } + install(&mut s, &tpl::module(&placing("test.place.fail.traps", r#"["tpf"]"#), "(unreachable)", "", 1)); + install(&mut s, &tpl::module(&placing("test.place.fail.spins", r#"["tpf"]"#), SPINS, "", 1)); + let before = state(&mut s); + for (id, _, why) in cases { + let e = place(&mut s, "x.tpf", b"?", json!({"importer": format!("plugin.{id}")})).unwrap_err().to_string(); + assert!(e.contains(why) && e.contains("x.tpf"), "{id}: {e}"); + assert_eq!(state(&mut s), before, "{id}"); + } + assert!(place(&mut s, "x.tpf", b"?", json!({"importer": "plugin.test.place.fail.traps"})).is_err()); + assert_eq!(state(&mut s), before, "trapped"); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || place(&mut s, "x.tpf", b"?", json!({"importer": "plugin.test.place.fail.spins"}))); + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + assert_eq!(state(&mut s), before, "canceled"); + + // A file one byte past the limit, without data in it: the size alone refuses it. + let dir = std::env::temp_dir().join(format!("vc-plugin-place-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let big = dir.join("big.tpf"); + std::fs::File::create(&big).unwrap().set_len(vectorcraft_plugins::import::MAX_INPUT_BYTES as u64 + 1).unwrap(); + let e = s.execute("file.place", &json!({"path": big.to_string_lossy(), "importer": "plugin.test.place.fail.declines"})).unwrap_err().to_string(); + assert!(e.contains("can't place `big.tpf`") && e.contains("larger than"), "{e}"); + let e = s.execute("file.place", &json!({"path": big.to_string_lossy()})).unwrap_err().to_string(); + assert!(e.contains("larger than"), "by its extension: {e}"); + assert_eq!(state(&mut s), before, "too large"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A file past the limit, placed with `importer` named, is refused from its size before any of it +/// is read: here the file can't be read at all, and the error is still the size. +#[test] +fn a_named_importer_refuses_a_large_file_before_reading_it() { + let mut s = with_document(); + install(&mut s, &tpl::returning(&placing("test.place.unread", r#"["tpu"]"#), ART)); + let dir = std::env::temp_dir().join(format!("vc-plugin-place-unread-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let big = dir.join("big.tpu"); + std::fs::File::create(&big).unwrap().set_len(vectorcraft_plugins::import::MAX_INPUT_BYTES as u64 + 1).unwrap(); + // Unix: no read permission. Windows: another handle that shares nothing. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&big, std::fs::Permissions::from_mode(0o000)).unwrap(); + } + #[cfg(windows)] + let _held = { + use std::os::windows::fs::OpenOptionsExt; + std::fs::OpenOptions::new().read(true).share_mode(0).open(&big).unwrap() + }; + // A user that reads the file anyway (root) can't show the order of the checks. + if std::fs::File::open(&big).is_ok() { + let _ = std::fs::remove_dir_all(&dir); + return; + } + let before = state(&mut s); + let e = s.execute("file.place", &json!({"path": big.to_string_lossy(), "importer": "plugin.test.place.unread"})).unwrap_err().to_string(); + assert!(e.contains("can't place `big.tpu`") && e.contains("larger than"), "{e}"); + assert_eq!(state(&mut s), before); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&big, std::fs::Permissions::from_mode(0o644)); + } + #[cfg(windows)] + drop(_held); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 9e23624a31..03bef1ea28 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -59,11 +59,13 @@ fn installed(id: &str) -> bool { vectorcraft_plugins::registry::get(id).is_some() } -/// A new launch: nothing installed, the plug-in folder `dir` attached. +/// A new launch: nothing installed, the plug-in folder `dir` attached, its grants' key kept in +/// memory. fn launch(dir: &std::path::Path) -> Session { for p in vectorcraft_plugins::registry::list() { vectorcraft_plugins::registry::remove(p.id()); } + vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory(); let mut s = Session::new(); s.attach_plugin_store(dir.to_path_buf()); s diff --git a/crates/engine/tests/script_corpus.rs b/crates/engine/tests/script_corpus.rs index 870bfbabc2..c2ca9a38f6 100644 --- a/crates/engine/tests/script_corpus.rs +++ b/crates/engine/tests/script_corpus.rs @@ -89,9 +89,9 @@ fn a_script_that_ends_well_passes() { fn a_failure_gives_its_kind_and_place() { let r = result(&mut session(), &source("var a = 1;\nvar = ;")); assert_eq!((r["ok"].clone(), r["kind"].clone(), r["line"].clone()), (json!(false), json!("syntax"), json!(2))); - let r = result(&mut session(), &source("var d = app.activeDocument;")); + let r = result(&mut session(), &source("var d = undefinedHost.activeDocument;")); assert_eq!(r["kind"], "thrown"); - assert!(r["message"].as_str().unwrap().starts_with("ReferenceError: app"), "{r}"); + assert!(r["message"].as_str().unwrap().starts_with("ReferenceError: undefinedHost"), "{r}"); let r = result(&mut session(), &source("while (true) {}")); assert_eq!(r["kind"], "limit"); assert!(r["fuelUsed"].as_u64().unwrap() <= FUEL); diff --git a/crates/engine/tests/script_startup.rs b/crates/engine/tests/script_startup.rs new file mode 100644 index 0000000000..527374c9f6 --- /dev/null +++ b/crates/engine/tests/script_startup.rs @@ -0,0 +1,568 @@ +//! Startup scripts (`script.startup.run`): off by default, the folder's `.jsx` files in order at +//! launch and before a chosen script, Safe Mode and disabled scripts, failures and limits, and the +//! launch marker naming the startup script that runs. +//! +//! A test binary of its own: Safe Mode, the disabled list and the launch marker are process-wide, +//! so these tests run one at a time and no other test sees them. +// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_plugins::safe_mode; +use vectorcraft_testkit::TempDir; + +static LOCK: Mutex<()> = Mutex::new(()); + +/// Safe Mode off, nothing disabled, no launch marker. +fn reset() { + safe_mode::end_launch(); + safe_mode::set_active(None); + safe_mode::forget_previous(); + safe_mode::set_disabled(vec![]); +} + +/// Holds the lock for one test and resets the process-wide state when the test starts and when it +/// ends, so a test that fails leaves the next one as it would find a new process. +struct Fresh { + _guard: std::sync::MutexGuard<'static, ()>, +} + +fn fresh() -> Fresh { + let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + reset(); + Fresh { _guard: guard } +} + +impl Drop for Fresh { + fn drop(&mut self) { + reset(); + } +} + +/// A new, empty folder for test `tag`, removed with everything in it when the test ends. +fn tmp_dir(tag: &str) -> TempDir { + TempDir::new(&format!("script-startup-{tag}")) +} + +/// Writes `text` to `name` under `dir`, folders included. +fn write(dir: &Path, name: &str, text: &str) -> PathBuf { + let path = dir.join(name); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, text).unwrap(); + path +} + +/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on. +fn session(dir: &Path) -> Session { + let mut s = Session::new(); + s.attach_startup_scripts_dir(dir.to_path_buf()); + s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap(); + s +} + +/// The names of the runs the Script Console started, in order. +fn started(s: &Session) -> Vec { + let lines = s.script_console().to_json(); + lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == "start").map(|l| l["name"].as_str().unwrap().to_string()).collect() +} + +/// The texts of the Script Console's lines of `kind`. +fn console(s: &Session, kind: &str) -> Vec { + let lines = s.script_console().to_json(); + lines["lines"].as_array().unwrap().iter().filter(|l| l["kind"] == kind).map(|l| l["text"].as_str().unwrap().to_string()).collect() +} + +fn names(v: &Value) -> Vec<&str> { + v.as_array().unwrap().iter().map(|n| n.as_str().unwrap()).collect() +} + +#[test] +fn startup_scripts_are_off_by_default_and_run_nothing() { + let _f = fresh(); + let dir = tmp_dir("off"); + write(&dir, "a.jsx", "vc.log('ran');"); + let mut s = Session::new(); + assert!(!s.prefs.run_startup_scripts, "off by default"); + s.attach_startup_scripts_dir(dir.to_path_buf()); + assert_eq!(s.startup_skip(), Some("off")); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r, json!({"reason": "launch", "skipped": true, "why": "off"})); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(1);", "name": "chosen"}})).unwrap(); + assert_eq!(r["skipped"], true); + assert_eq!(r["then"]["ok"], true, "the chosen script still runs"); + assert_eq!(started(&s), ["chosen"], "no startup script ran"); +} + +#[test] +fn the_folders_jsx_files_run_in_name_order_at_launch_and_before_a_chosen_script() { + let _f = fresh(); + let dir = tmp_dir("order"); + for name in ["b.jsx", "C.JSX", "a.jsx", ".hidden.jsx", "x.js", "lib.jsxinc", "sub/d.jsx", "notes.txt"] { + write(&dir, name, "vc.log(1);"); + } + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["skipped"], false); + assert_eq!(names(&r["ran"]), ["a.jsx", "b.jsx", "C.JSX"], "by name without regard to case"); + assert!(r["failed"].as_array().unwrap().is_empty()); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX"]); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert_eq!(r["then"]["ok"], true); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX", "a.jsx", "b.jsx", "C.JSX", "chosen"], "the startup scripts run first"); +} + +#[test] +fn a_missing_folder_runs_nothing_and_a_session_without_one_skips() { + let _f = fresh(); + let dir = tmp_dir("missing"); + let mut s = session(&dir.join("Startup Scripts")); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["skipped"], false); + assert!(r["ran"].as_array().unwrap().is_empty() && r["failed"].as_array().unwrap().is_empty()); + assert_eq!(r["unreadable"], false); + let mut s = Session::new(); + s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap(); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["why"], "noFolder"); +} + +#[test] +fn safe_mode_skips_the_startup_scripts_and_still_runs_the_chosen_one() { + let _f = fresh(); + let dir = tmp_dir("safe"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + assert_eq!(s.startup_skip(), Some("safeMode")); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert_eq!(r["why"], "safeMode"); + assert_eq!(started(&s), ["chosen"]); +} + +#[test] +fn a_startup_script_the_safe_mode_choice_disabled_does_not_run() { + let _f = fresh(); + let dir = tmp_dir("disabled"); + let a = write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "vc.log(1);"); + let mut s = session(&dir); + safe_mode::disable(safe_mode::Item::file(a.to_string_lossy())); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(names(&r["disabled"]), ["a.jsx"]); + assert_eq!(names(&r["ran"]), ["b.jsx"]); +} + +#[test] +fn a_failing_or_endless_startup_script_is_reported_and_the_next_and_the_chosen_script_run() { + let _f = fresh(); + let dir = tmp_dir("failing"); + write(&dir, "1 throws.jsx", "throw new Error('broken');"); + write(&dir, "2 endless.jsx", "for (;;) {}"); + write(&dir, "3 syntax.jsx", "var = ;"); + write(&dir, "4 fine.jsx", "vc.log(1);"); + let mut s = session(&dir); + let then = json!({"source": "vc.log('chosen');", "name": "chosen"}); + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": then, "maxFuel": 100000})).unwrap(); + let failed = r["failed"].as_array().unwrap(); + let failed_names: Vec<&str> = failed.iter().map(|f| f["name"].as_str().unwrap()).collect(); + assert_eq!(failed_names, ["1 throws.jsx", "2 endless.jsx", "3 syntax.jsx"]); + assert!(failed[0]["error"].as_str().unwrap().contains("broken"), "{failed:?}"); + assert_eq!(names(&r["ran"]), ["4 fine.jsx"]); + assert_eq!(r["then"]["ok"], true, "the chosen script runs after them"); + assert!(console(&s, "end").contains(&"ended: fuel".to_string()), "the endless one ran out of instructions"); +} + +#[test] +fn a_startup_script_larger_than_a_script_may_be_is_refused_unread() { + let _f = fresh(); + let dir = tmp_dir("large"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "big.jsx", &big); + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}])); + assert!(console(&s, "error").iter().any(|l| l.contains(vectorcraft_engine::cmd::scripts::TOO_LARGE)), "the console names it"); +} + +#[test] +fn a_startup_script_cannot_start_another_startup_run() { + let _f = fresh(); + let dir = tmp_dir("nested"); + let text = + "try { vc.run('script.startup.run', {reason: 'menu', then: {source: 'vc.log(1);'}}); vc.log('nested'); } catch (e) { vc.log('refused'); }"; + write(&dir, "a.jsx", text); + let mut s = session(&dir); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(names(&r["ran"]), ["a.jsx"]); + assert_eq!(console(&s, "log"), ["refused"]); + assert_eq!(started(&s), ["a.jsx"]); +} + +#[test] +fn bad_parameters_are_refused() { + let _f = fresh(); + let dir = tmp_dir("params"); + let mut s = session(&dir); + for p in [ + json!({}), + json!({"reason": "boot"}), + json!({"reason": "menu", "then": "x.jsx"}), + json!({"reason": "launch", "maxFuel": 0}), + json!({"reason": "launch", "maxFuel": 1.5}), + ] { + assert!(s.execute("script.startup.run", &p).is_err(), "{p}"); + } + // `then` is checked as `script.run` checks its parameters, before any startup script runs. + write(&dir, "a.jsx", "vc.log(1);"); + let then = json!({"source": "vc.log(2);", "bogus": true}); + let alone = s.execute("script.run", &then).unwrap_err().to_string(); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap_err().to_string(); + assert_eq!(e, alone); + assert!(started(&s).is_empty(), "no startup script ran"); +} + +#[test] +fn in_the_app_the_runs_are_queued_and_the_launch_marker_names_the_running_startup_script() { + let _f = fresh(); + let dir = tmp_dir("app"); + let launch = tmp_dir("app-launch"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "throw new Error('broken');"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "bb.jsx", &big); + write(&dir, "c.jsx", "vc.log(3);"); + assert!(safe_mode::begin_launch(&launch).is_empty()); + let mut s = session(&dir); + s.script_frames = true; + let r = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(4);", "name": "chosen"}})).unwrap(); + assert_eq!((r["running"].clone(), r["queued"].clone(), r["failed"].clone()), (json!(true), json!(5), json!([]))); + let marker = || { + let file = std::fs::read_dir(&launch) + .unwrap() + .filter_map(Result::ok) + .map(|e| e.path()) + .find(|p| p.extension().is_some_and(|e| e == "json")) + .unwrap(); + safe_mode::parse_marker(&std::fs::read(file).unwrap()) + }; + let names = |items: Vec| items.into_iter().map(|i| i.name).collect::>(); + assert_eq!(names(marker()), [Some("a.jsx".to_string())], "the marker names the running startup script"); + let mut results = vec![]; + for _ in 0..10_000 { + if !s.script_running() { + break; + } + if let Some(r) = s.script_pump() { + results.push(r.is_ok()); + } + } + assert!(!s.script_running()); + assert_eq!(results, [true, false, true, true], "each run reports as it ends"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "bb.jsx", "c.jsx", "chosen"]); + let too_large = vectorcraft_engine::cmd::scripts::TOO_LARGE.to_string(); + assert_eq!(s.take_startup_failures(), [("bb.jsx".to_string(), too_large)], "the one that could not start is kept for the app"); + assert!(s.take_startup_failures().is_empty()); + assert!(marker().is_empty(), "the marker names nothing once they have run"); +} + +#[test] +fn a_chosen_script_that_cannot_start_is_refused_before_any_startup_script_runs() { + let _f = fresh(); + let dir = tmp_dir("app-then"); + write(&dir, "a.jsx", "vc.log(1);"); + let missing = dir.join("gone").join("missing.jsx"); + let then = json!({"path": missing.to_string_lossy()}); + for frames in [false, true] { + let mut s = session(&dir); + s.script_frames = frames; + let alone = s.execute("script.run", &then).unwrap_err().to_string(); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap_err(); + assert_eq!(e.to_string(), alone, "the error script.run gives, frames {frames}"); + assert!(!s.script_running()); + assert!(started(&s).is_empty(), "no startup script ran, frames {frames}"); + assert!(s.take_startup_failures().is_empty()); + let e = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"name": "neither"}})).unwrap_err(); + assert!(e.to_string().contains("exactly one of"), "{e}"); + assert!(started(&s).is_empty()); + } +} + +#[test] +fn a_stop_between_runs_survives_an_entry_that_cannot_start() { + let _f = fresh(); + let dir = tmp_dir("stop-before-failed-entry"); + write(&dir, "a.jsx", "vc.log('first');"); + write(&dir, "b.jsx", "var = ;"); + write(&dir, "c.jsx", "vc.log('must not run');"); + for by_interrupt in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert!((0..10_000).find_map(|_| s.script_pump()).unwrap().is_ok()); + if by_interrupt { + s.script_interrupt().set(); + } else { + assert!(s.script_request_stop()); + } + let stopped = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(stopped.is_err(), "by_interrupt={by_interrupt}"); + assert_eq!(s.script_report().unwrap()["name"], "c.jsx"); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert_eq!(console(&s, "log"), ["first"]); + assert_eq!(s.take_startup_failures().iter().map(|(name, _)| name.as_str()).collect::>(), ["b.jsx"]); + } +} + +#[test] +fn the_chosen_run_reads_includes_after_the_startup_runs() { + let _f = fresh(); + let dir = tmp_dir("chosen-includes"); + let startup = dir.join("startup"); + let chosen = dir.join("chosen"); + write(&startup, "a.jsx", "vc.log('startup');"); + let include = write(&chosen, "value.jsxinc", "vc.log('before');"); + let main = write(&chosen, "main.jsx", "#include \"value.jsxinc\"\nvc.log('main');"); + let mut s = session(&startup); + s.script_frames = true; + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": main.to_string_lossy()}})).unwrap(); + std::fs::write(&include, "vc.log('after');").unwrap(); + for _ in 0..1000 { + if !s.script_running() { + break; + } + s.script_pump(); + } + assert!(!s.script_running()); + assert_eq!(console(&s, "log"), ["startup", "after", "main"]); +} + +#[test] +fn failed_startup_entries_resume_in_fifo_order_on_later_pumps() { + let _f = fresh(); + let dir = tmp_dir("failed-startup-pumps"); + for name in ["a.jsx", "b.jsx", "c.jsx"] { + write(&dir, name, "var = ;"); + } + let mut s = session(&dir); + s.script_frames = true; + let first = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log('chosen');", "name": "chosen"}})).unwrap(); + let failures = first["failed"].as_array().unwrap(); + assert!(!failures.is_empty() && failures.len() < 3, "{first}"); + assert!(!started(&s).iter().any(|name| name == "chosen"), "the chosen run follows the remaining startup entries"); + let mut failed: Vec = failures.iter().map(|entry| entry["name"].as_str().unwrap().to_string()).collect(); + for _ in 0..100 { + if !s.script_running() { + break; + } + s.script_pump(); + failed.extend(s.take_startup_failures().into_iter().map(|(name, _)| name)); + } + assert!(!s.script_running()); + assert_eq!(failed, ["a.jsx", "b.jsx", "c.jsx"]); + assert_eq!(console(&s, "log"), ["chosen"]); +} + +#[test] +fn a_failed_chosen_preflight_clears_the_previous_report() { + let _f = fresh(); + let dir = tmp_dir("preflight-report"); + write(&dir, "a.jsx", "vc.log('startup');"); + for frames in [false, true] { + let mut s = session(&dir); + s.execute("script.run", &json!({"source": "vc.log('previous');"})).unwrap(); + assert!(s.script_report().is_some()); + let before = started(&s); + s.script_frames = frames; + assert!(s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "var = ;"}})).is_err()); + assert!(s.script_report().is_none(), "frames={frames}"); + assert_eq!(started(&s), before); + assert!(!s.script_running()); + } +} + +#[test] +fn a_chosen_script_with_invalid_syntax_is_refused_before_startup_scripts_run() { + let _f = fresh(); + let dir = tmp_dir("invalid-chosen-syntax"); + write(&dir, "a.jsx", "vc.log('startup ran');"); + for frames in [false, true] { + let mut s = session(&dir); + s.script_frames = frames; + let result = s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "var = ;"}})); + assert!(result.is_err(), "frames={frames}: {result:?}"); + assert!(!s.script_running()); + assert!(started(&s).is_empty(), "no startup script ran, frames={frames}"); + assert!(s.take_startup_failures().is_empty()); + } +} + +#[test] +fn an_installed_chosen_script_runs_the_text_read_before_startup_scripts() { + let _f = fresh(); + for frames in [false, true] { + let dir = tmp_dir(if frames { "chosen-snapshot-sliced" } else { "chosen-snapshot-sync" }); + let data = dir.join("data"); + let startup = dir.join("startup"); + let entry = write(&startup, "a.jsx", ""); + let real = std::fs::canonicalize(&entry).unwrap(); + let key = vectorcraft_plugins::permissions::sha256_hex(real.to_string_lossy().as_bytes()); + let installed = data.join(&key[..16]); + let chosen = write(&installed, "chosen.jsx", "vc.log('chosen');"); + let quoted = serde_json::to_string(&chosen.to_string_lossy()).unwrap(); + write(&startup, "a.jsx", &format!("Folder.userData; if (!new File({quoted}).remove()) throw 'remove failed';")); + let mut s = session(&startup); + s.attach_script_data(data); + s.attach_scripts_dir(installed); + s.script_frames = frames; + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"path": chosen, "installed": true}})).unwrap(); + for _ in 0..10_000 { + if !s.script_running() { + break; + } + if let Some(result) = s.script_pump() { + result.unwrap(); + } + } + assert!(!s.script_running()); + assert!(s.take_startup_failures().is_empty()); + assert_eq!(started(&s), ["a.jsx", "chosen.jsx"]); + assert!(!chosen.exists()); + } +} + +#[test] +fn in_the_app_a_stopped_startup_script_keeps_its_report_until_the_next_pump_starts_the_queued_run() { + let _f = fresh(); + let dir = tmp_dir("app-stop"); + write(&dir, "a.jsx", "for (;;) {}"); + let mut s = session(&dir); + s.script_frames = true; + s.execute("script.startup.run", &json!({"reason": "menu", "then": {"source": "vc.log(2);", "name": "chosen"}})).unwrap(); + assert!(s.script_pump().is_none(), "the endless one runs"); + assert!(s.script_request_stop()); + let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(ended.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped", "the ended run's report is still there"); + assert!(s.script_running(), "the chosen script waits for the next pump"); + // Nothing else starts ahead of the queued run. + let e = s.execute("script.run", &json!({"source": "vc.log(9);", "name": "direct"})).unwrap_err(); + assert!(matches!(e, vectorcraft_engine::EngineError::Busy), "{e}"); + assert_eq!(started(&s), ["a.jsx"]); + let r = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert_eq!(r.unwrap()["ok"], true); + assert_eq!(started(&s), ["a.jsx", "chosen"]); + assert!(!s.script_running()); +} + +#[test] +fn in_the_app_a_stop_between_two_runs_stops_the_run_that_starts_next() { + let _f = fresh(); + let dir = tmp_dir("app-stop-between"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "for (;;) {}"); + for by_interrupt in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + let then = json!({"source": "vc.log(3);", "name": "chosen"}); + s.execute("script.startup.run", &json!({"reason": "menu", "then": then, "maxFuel": 1_000_000})).unwrap(); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "a.jsx ends"); + assert!(s.script_running(), "b.jsx waits for the next pump"); + if by_interrupt { + // The status bar's Stop button. + s.script_interrupt().set(); + } else { + assert!(s.script_request_stop(), "script.stop has a run to stop"); + } + let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap(); + assert!(ended.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert_eq!(s.script_report().unwrap()["name"], "b.jsx"); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "the chosen script still runs"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "chosen"]); + } +} + +#[test] +fn a_startup_script_refused_before_it_begins_is_in_the_script_console() { + let _f = fresh(); + let dir = tmp_dir("refused"); + write(&dir, "a.jsx", "vc.log(1);"); + let mut s = session(&dir); + s.execute("file.new", &json!({})).unwrap(); + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + let error = r["failed"][0]["error"].as_str().unwrap().to_string(); + assert!(error.contains("undo group"), "{r}"); + assert_eq!(started(&s), ["a.jsx"]); + assert_eq!(console(&s, "error"), [format!("a.jsx: {error}")]); +} + +#[test] +fn in_the_app_abandoning_between_two_runs_drops_the_queued_runs() { + let _f = fresh(); + let dir = tmp_dir("app-abandon-between"); + write(&dir, "a.jsx", "vc.log(1);"); + write(&dir, "b.jsx", "vc.log(2);"); + let mut s = session(&dir); + s.script_frames = true; + let then = json!({"source": "vc.log(3);", "name": "chosen"}); + s.execute("script.startup.run", &json!({"reason": "menu", "then": then})).unwrap(); + assert_eq!((0..10_000).find_map(|_| s.script_pump()).unwrap().unwrap()["ok"], true, "a.jsx ends"); + assert!(s.script_running() && s.script_name().is_none(), "b.jsx waits for the next pump"); + assert!(s.script_abandon(), "the queued runs are stopped"); + assert!(!s.script_running()); + assert!(s.script_pump().is_none()); + assert_eq!(started(&s), ["a.jsx"]); +} + +#[test] +fn in_the_app_startup_scripts_that_cannot_start_are_in_the_reply() { + let _f = fresh(); + let dir = tmp_dir("app-unread"); + let mut big = "//".to_string(); + big.push_str(&"x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES)); + write(&dir, "big.jsx", &big); + let mut s = session(&dir); + s.script_frames = true; + let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap(); + assert_eq!(r["running"], json!(false)); + assert_eq!(r["failed"], json!([{"name": "big.jsx", "error": vectorcraft_engine::cmd::scripts::TOO_LARGE}])); + assert!(s.take_startup_failures().is_empty(), "the reply names them, so the status bar does not again"); +} + +#[test] +fn in_the_app_every_queued_run_keeps_the_automation_roots_of_the_request_that_queued_it() { + let _f = fresh(); + let dir = tmp_dir("app-roots"); + // Writes a file in the run's temporary folder, which is outside the write roots below. + let source = "var ok; try { var t = new File(Folder.temp.fsName + '/t.txt'); ok = t.open('w'); t.close(); } catch (e) { ok = false; }\n\ + vc.log(ok ? 'wrote' : 'refused');"; + write(&dir, "a.jsx", source); + write(&dir, "b.jsx", source); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[dir.as_path()], &[]).unwrap().unwrap(); + for confined in [false, true] { + let mut s = session(&dir); + s.script_frames = true; + let params = json!({"reason": "menu", "then": {"source": source, "name": "chosen"}}); + let mut request = || s.execute("script.startup.run", ¶ms).unwrap(); + let r = if confined { vectorcraft_engine::file_access::confine(Some(&roots), request) } else { request() }; + assert_eq!(r["queued"], json!(3)); + // The frames that start the later runs are outside the request. + for _ in 0..1000 { + if !s.script_running() { + break; + } + s.script_pump(); + } + assert!(!s.script_running(), "the startup queue did not finish, confined {confined}"); + assert_eq!(started(&s), ["a.jsx", "b.jsx", "chosen"]); + let want = if confined { "refused" } else { "wrote" }; + assert_eq!(console(&s, "log"), [want, want, want], "confined {confined}"); + } +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 8065b8cbb5..d95b1279c2 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -69,7 +69,7 @@ pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths tha pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps"; pub(super) const LIVE: &str = "repeats, placed documents, intertwines and distorted images are written as their art in the editing data for other apps"; -pub(super) const DEEP_DISTORTED: &str = "images changed by Perspective Distort or Free Distort more than 8 deep in opacity masks, symbols, live objects and pattern tiles are written as the nearest parallelogram in the editing data for other apps"; +pub(super) const DEEP_DISTORTED: &str = "images changed by Perspective Distort or Free Distort nested 8 deep in opacity masks, symbols, live objects and pattern tiles are written as the nearest parallelogram in the editing data for other apps"; pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps"; pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; pub(super) const ITEM_TRANSPARENCY: &str = diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index d1ae8ef9ab..8fbfcf3e83 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -130,7 +130,7 @@ const STROKES: &str = const IMAGE_ALPHA: &str = "transparent image pixels are written over white"; const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents, intertwines and distorted images are written as their art"; const DEEP_DISTORTED: &str = - "images changed by Perspective Distort or Free Distort more than 8 deep in symbols and live objects are written as the nearest parallelogram"; + "images changed by Perspective Distort or Free Distort nested 8 deep in symbols and live objects are written as the nearest parallelogram"; const GRAPHS: &str = "graphs are written as their art, without their data or settings"; /// The warning for an image left out because it can't be decoded: the note raster exports give /// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index e8f3c42b8e..44a9f01369 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -1,5 +1,7 @@ -//! Safe saving: a file is written to a temporary file beside it, then renamed over it, so a failed -//! or interrupted write never leaves a damaged file behind (the old one stays as it was). +//! [`write_atomic_with`] writes and flushes a temporary file, then renames it over its destination. +//! A failure while writing or flushing the temporary file leaves the original file unchanged. +//! On Unix, saves also flush the destination directory after the complete file is written. +//! An error at that step reports that the file was written. //! [`write_new_with`] creates a file the same way without ever replacing one. //! //! Where a folder refuses the temporary file or the rename (some network shares, a file another @@ -22,11 +24,29 @@ use std::io::{self, Write as _}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; -/// Whether the returned write error refuses this location. Recovery errors must still be shown: -/// their message names copies the user may need, even when their kind is PermissionDenied. +/// Reports whether a write error identifies a read-only location. +/// It returns false for recovery errors and for errors flushing a directory after a completed write, including PermissionDenied. pub fn read_only_location(error: &io::Error) -> bool { matches!(error.kind(), io::ErrorKind::ReadOnlyFilesystem | io::ErrorKind::PermissionDenied) - && !error.get_ref().is_some_and(|e| e.is::()) + && !error.get_ref().is_some_and(|e| e.is::() || e.is::()) +} + +#[derive(Debug)] +struct WrittenError { + path: PathBuf, + error: io::Error, +} + +impl std::fmt::Display for WrittenError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "The file was written to {}. Its folder could not be flushed: {}", self.path.display(), self.error) + } +} + +impl std::error::Error for WrittenError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&self.error) + } } /// Marks the existing recovery message without changing its text or the returned error kind. @@ -46,11 +66,10 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { write_atomic_with(path, |f| f.write_all(bytes)) } -/// Write `path` atomically with `fill`, which writes the content into the temporary file. When -/// `fill` or flushing fails, or the work was canceled meanwhile ([`vectorcraft_doc::cancel`]), the -/// temporary file is removed and `path` is left untouched. When the -/// folder refuses the temporary file or the rename, the content is copied into `path` instead (see -/// the module docs). +/// This function writes `path` atomically with `fill`, which writes content into a temporary file. +/// A failure from `fill`, flushing that file, or cancellation ([`vectorcraft_doc::cancel`]) leaves `path` unchanged. +/// Cleanup attempts to remove the temporary file and ignores removal errors. +/// When the folder refuses the temporary file or the rename, the content is copied into `path` instead (see the module docs). pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { // Replacing a file: its staging copy starts owner-only, so a private document is never readable // beside the target before `keep_permissions` has run (#1712). A new file keeps the default mode. @@ -97,7 +116,7 @@ fn write_atomic_stepping( // Best effort: a volume without Unix permissions (SMB, FAT) refuses them, and has none // to keep. let _ = keep_permissions(&target, &tmp); - let Err(e) = rename(&tmp, &target) else { return Ok(()) }; + let Err(e) = rename(&tmp, &target) else { return sync_written_parent(&target) }; e } }; @@ -137,7 +156,7 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { if let Some(old) = old { let _ = std::fs::remove_file(old); } - Ok(()) + sync_written_parent(target) } (Err(e), Some(old)) => Err(io::Error::new( e.kind(), @@ -168,7 +187,7 @@ fn create_private(path: &Path) -> io::Result { /// (`std::fs::hard_link`, which fails with `AlreadyExists` when the name is taken, also when it was /// taken meanwhile). The file appears whole or not at all. Where hard links fail for another /// reason, `path` is created with `create_new` and the content copied in; a failed copy removes -/// it. The temporary file is always removed. +/// it. Cleanup attempts to remove the temporary file and ignores removal errors. pub fn write_new_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { write_new_linking(path, fill, |tmp, path| std::fs::hard_link(tmp, path)) } @@ -189,7 +208,31 @@ fn write_new_linking( }); // Best effort: the temporary file is all there is to clean up. let _ = std::fs::remove_file(&tmp); - placed + placed.and_then(|()| sync_written_parent(path)) +} + +fn sync_written_parent(path: &Path) -> io::Result<()> { + #[cfg(unix)] + { + sync_parent(path).map_err(|error| io::Error::new(error.kind(), WrittenError { path: path.to_path_buf(), error })) + } + #[cfg(not(unix))] + { + let _ = path; + Ok(()) + } +} + +/// This function flushes the directory containing `path` with `fsync`. +/// It returns errors from opening or flushing the directory. +#[cfg(unix)] +pub fn sync_parent(path: &Path) -> io::Result<()> { + #[cfg(test)] + if DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "directory flush failed")); + } + let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); + rustix::fs::fsync(&File::open(parent)?).map_err(io::Error::from) } /// `Err` wrapping [`vectorcraft_doc::cancel::Cancelled`] when the work running on this thread has @@ -272,6 +315,8 @@ const ENOTTY: i32 = 25; #[cfg(test)] thread_local! { + #[cfg(unix)] + static DIRECTORY_SYNC_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: every full flush on this thread fails as on an SMB share mounted by macOS. static REFUSE_FULL_SYNC: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Tests: the plain `fsync` fallback fails too, with this OS error. @@ -472,6 +517,68 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_reports_the_completed_replacement() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-replace"); + let path = directory.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let result = write_atomic(&path, b"new"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(result.is_err(), "a failed directory flush was reported as success"); + let error = result.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("The file was written to"), "{error}"); + assert!(!read_only_location(&error), "the file was already replaced: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + assert!(leftovers(&directory, "doc.vectorcraft").is_empty()); + write_atomic(&path, b"retried").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"retried"); + } + + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_preserves_the_completed_new_file() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-create"); + let path = directory.join("doc.vectorcraft"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let result = write_new_with(&path, |file| file.write_all(b"created")); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + assert!(result.is_err(), "a failed directory flush was reported as success"); + let error = result.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.to_string().contains("The file was written to"), "{error}"); + assert!(!read_only_location(&error), "the file was already created: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"created"); + assert!(leftovers(&directory, "doc.vectorcraft").is_empty()); + let result = write_new_with(&path, |file| file.write_all(b"replacement")); + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(&path).unwrap(), b"created"); + } + + #[cfg(unix)] + #[test] + fn a_directory_sync_failure_is_reported_after_copy_fallbacks() { + let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-copy"); + let path = directory.join("doc.vectorcraft"); + std::fs::write(&path, b"old").unwrap(); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let replaced = write_atomic_stepping(&path, |file| file.write_all(b"new"), create_new, |_, _| denied()); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + let error = replaced.unwrap_err(); + assert!(!read_only_location(&error), "the file was already replaced: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + let new_path = directory.join("new.vectorcraft"); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true)); + let created = write_new_linking(&new_path, |file| file.write_all(b"created"), |_, _| denied()); + DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false)); + let error = created.unwrap_err(); + assert!(!read_only_location(&error), "the file was already created: {error}"); + assert_eq!(std::fs::read(&new_path).unwrap(), b"created"); + assert_eq!(std::fs::read_dir(&*directory).unwrap().count(), 2); + } + /// A save to an SMB share (#1620): macOS refuses the full flush there with `ENOTSUP`, so the /// file is flushed with a plain `fsync` and saved. When that fails too the save fails as before, /// the old file stays and no temporary file is left. Elsewhere `sync_all` is already a plain diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 66040d265c..1de16f938d 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -55,6 +55,8 @@ use serde::{Deserializer, Serialize}; use vectorcraft_brush::stored_art::StoredArt; use vectorcraft_doc::{Document, ImageBlob}; +#[cfg(all(unix, not(target_arch = "wasm32")))] +pub use atomic::sync_parent; #[cfg(not(target_arch = "wasm32"))] pub use atomic::{read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; use craft_gzip::Gz; @@ -644,6 +646,9 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize doc.dimensions = dimensions; // Untrusted: ruby ranges over the type's text, clamped to it (after the depth limit too). doc.fix_ruby(); + // Untrusted: at most 64 tags an object, each name and value at most 64 KiB, with distinct ids + // (after the depth limit too). + doc.tidy_tags(); // Untrusted: the raster effects resolution, within 1 to 2400 ppi (72 when it isn't finite). doc.raster_effects_ppi = Some(doc.raster_effects_ppi).filter(|v| v.is_finite()).unwrap_or(72.0).clamp(1.0, 2400.0); // Untrusted: the superscript, subscript and small caps proportions of the type, the graph diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index 304f20557e..aea7afde1d 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -51,12 +51,18 @@ const SMOOTH_TURN: f64 = 0.5 * std::f64::consts::PI / 180.0; /// side it touches `c` at `t`, its center one radius out from there. A `t` outside 0 to /// 1 and a segment whose points are not finite give [`NoCircle::Cusp`]. pub fn curvature_circle(c: CubicBez, t: f64, convex: bool) -> Result { + curvature_circle_with(c, t, convex, true) +} + +/// [`curvature_circle`], with `arcs` off giving the cubic's own curvature at `t` on the cubic of a +/// circular arc too. +pub fn curvature_circle_with(c: CubicBez, t: f64, convex: bool, arcs: bool) -> Result { let finite = [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()); if !finite || !(0.0..=1.0).contains(&t) { return Err(NoCircle::Cusp); } let at = c.eval(t); - let (center, radius, nominal) = match circular_arc(c) { + let (center, radius, nominal) = match circular_arc(c).filter(|_| arcs) { Some((center, radius)) => { let out = at - center; let len = out.hypot(); @@ -89,6 +95,11 @@ pub fn curvature_circle(c: CubicBez, t: f64, convex: bool) -> Result Result { + curvature_circle_on_with(sp, seg, t, convex, true) +} + +/// [`curvature_circle_on`] with [`curvature_circle_with`]'s `arcs`. +pub fn curvature_circle_on_with(sp: &SubPath, seg: usize, t: f64, convex: bool, arcs: bool) -> Result { let n = sp.segment_count(); if seg >= n { return Err(NoCircle::Cusp); @@ -106,7 +117,7 @@ pub fn curvature_circle_on(sp: &SubPath, seg: usize, t: f64, convex: bool) -> Re if corner { return Err(NoCircle::Corner); } - curvature_circle(c, t, convex) + curvature_circle_with(c, t, convex, arcs) } /// The nearest segment with length before (or with `forward`, after) segment `seg`, and whether @@ -260,6 +271,19 @@ mod tests { } } + /// With `arcs` off, a quarter circle's segment gives the cubic's own curvature, which is smaller + /// than the circle's at its ends: the circle is not nominal and is larger than the arc's. + #[test] + fn without_arcs_a_circle_segment_gives_its_own_curvature() { + let pd = shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)); + let sp = &pd.subpaths[0]; + let arc = curvature_circle_on_with(sp, 0, 0.0, false, true).unwrap(); + let own = curvature_circle_on_with(sp, 0, 0.0, false, false).unwrap(); + assert!(arc.nominal && !own.nominal, "{arc:?} {own:?}"); + assert!(own.radius > arc.radius && own.center != arc.center, "{arc:?} {own:?}"); + assert_eq!(own.at, sp.segment(0).eval(0.0)); + } + /// On the parabola y = x² / 200, the curvature at its vertex is 1/100: drawn as a cubic from /// (-100, 50) to (100, 50), the circle at the middle has radius 100 and center (0, 100), above /// the curve on the side it bends toward; Shift's other side puts the center at (0, -100). diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index e255258f34..8efa1458eb 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -244,6 +244,12 @@ pub enum Expr { OptionalChain(ExprId), /// The object or function before `?.` in an [`Expr::OptionalChain`]. Optional(ExprId), + /// `yield`, `yield expression` or (`delegate`) `yield* expression` in a generator function's + /// body (ECMA-262 2015 section 14.4). + Yield { + arg: Option, + delegate: bool, + }, } /// A piece of a template literal's text between its substitutions. @@ -440,6 +446,8 @@ pub struct Function { /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. pub strict: bool, + /// A generator function (`function*`, or `*name() {…}` in an object literal). + pub generator: bool, pub span: Span, } diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 49eeebf9f4..3baad7b7bd 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -1,10 +1,11 @@ //! The built-in objects (ECMA-262 5.1 section 15): `Object` with `Object.prototype` and the //! ES5 statics, `Function` with `Function.prototype.call`, `apply`, `bind` and `toString`, //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex -//! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with -//! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in -//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`) and -//! the iterators of arrays, strings and `arguments` objects (in `iterator`). +//! B's `escape` and `unescape`, `Boolean` with `Boolean.prototype`'s `toString` and `valueOf`, and +//! the prototypes primitive values look properties up on. `String`, `Number`, `RegExp` and `Date` are in +//! their own modules. A realm with [`crate::Options::es2015`] also has `Symbol` (in `symbol`), +//! the iterators of arrays, strings and `arguments` objects (in `iterator`), and the generator +//! objects' prototypes with `GeneratorFunction` (in `generator`). //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object //! or property it makes is checked against the heap limit before it is made, so no built-in can @@ -12,11 +13,13 @@ mod array; pub(crate) mod extensions; +mod generator; mod global; pub(crate) mod iterator; mod json; mod math; mod object; +pub(crate) mod promise; mod symbol; use std::rc::Rc; @@ -242,6 +245,8 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { method(interp, function_proto, "bind", function_bind, 1)?; method(interp, function_proto, "toString", function_to_string, 0)?; + let boolean = native(interp, "Boolean", boolean_ctor, 1, NativeKind::Plain, true)?; + constructor(interp, "Boolean", boolean, boolean_proto)?; method(interp, boolean_proto, "toString", boolean_to_string, 0)?; method(interp, boolean_proto, "valueOf", boolean_value_of, 0)?; @@ -258,10 +263,14 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { if interp.options.es2015 { symbol::install(interp, object)?; iterator::install(interp)?; + generator::install(interp, function)?; } if interp.options.e4x { crate::xml_builtins::install(interp)?; } + if interp.options.es2015 { + promise::install(interp)?; + } Ok(()) } @@ -293,7 +302,7 @@ fn get_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult { } fn has_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult { - interp.has_property(o, &key_of(k)) + interp.has_property_indexed(o, &key_of(k)) } /// The estimated bytes a new element adds. @@ -465,7 +474,7 @@ pub(crate) fn arg(args: &[Value], i: usize) -> Value { } fn unreachable_native(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { - Err(Abrupt::Internal("call or apply reached its native body".into())) + Err(Abrupt::Internal("a built-in the interpreter runs itself reached its native body".into())) } fn throw_type_error(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { @@ -516,6 +525,16 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J Ok(Value::str(&format!("[object {class}]"))) } +/// `Boolean(value)` and `new Boolean(value)` (sections 15.6.1 and 15.6.2). +fn boolean_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult { + let b = args.first().is_some_and(Value::truthy); + if !construct { + return Ok(Value::Bool(b)); + } + let proto = interp.intrinsics.boolean_proto; + Ok(Value::Object(interp.heap.alloc_object(Object::new(Class::Boolean(b), Some(proto))))) +} + /// The Boolean a `Boolean.prototype` method was called on (sections 15.6.4.2 and 15.6.4.3): a /// primitive, or the primitive value of a Boolean object. fn this_boolean(interp: &mut Interp, this: &Value, name: &str) -> JsResult { @@ -559,7 +578,15 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some())) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || is_host_member_pk(interp, o, &k)?)) +} + +/// [`Interp::is_host_member`] for either kind of key: a Symbol never names a host member. +fn is_host_member_pk(interp: &Interp, o: ObjId, k: &crate::symbol::PropKey) -> JsResult { + match k { + crate::symbol::PropKey::Str(name) => interp.is_host_member(o, name), + crate::symbol::PropKey::Sym(_) => Ok(false), + } } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -578,7 +605,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()))) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || is_host_member_pk(interp, o, &k)?)) } // ---- Function ---- @@ -586,7 +613,13 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b /// `Function(p1, …, body)` and `new Function(…)` (section 15.3.2.1): the source is read as /// `(function anonymous(p1,…\n) {\nbody\n})` and must be exactly that one function. fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { - const HEAD: &str = "(function anonymous("; + create_dynamic_function(interp, args, false) +} + +/// CreateDynamicFunction (ECMA-262 11th edition, section 19.2.1.1.1) for `Function` and, with +/// `generator`, for `GeneratorFunction`, whose source is read as `(function* anonymous(…`. +pub(crate) fn create_dynamic_function(interp: &mut Interp, args: &[Value], generator: bool) -> JsResult { + let head: &str = if generator { "(function* anonymous(" } else { "(function anonymous(" }; const MID: &str = "\n) {\n"; const TAIL: &str = "\n})"; let mut parts = Vec::with_capacity(args.len()); @@ -598,12 +631,12 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe let total = parts .iter() .map(Str::len) - .chain([parts.len().saturating_sub(1), HEAD.len() + MID.len() + TAIL.len(), body.len()]) + .chain([parts.len().saturating_sub(1), head.len() + MID.len() + TAIL.len(), body.len()]) .fold(0usize, usize::saturating_add); interp.check_source_units(total).map_err(|e| interp.compile_error_to_abrupt(e))?; interp.prepare_source(total)?; let mut units = Vec::with_capacity(total); - units.extend(HEAD.encode_utf16()); + units.extend(head.encode_utf16()); for (i, p) in parts.iter().enumerate() { if i > 0 { units.push(u16::from(b',')); @@ -623,8 +656,8 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe }; let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag, strict_writes: interp.writes_mode() }); let code = match compile_constructed_function(&program, &source) { - Ok(Some(code)) => code, - Ok(None) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), + Ok(Some(code)) if code.generator == generator => code, + Ok(_) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")), Err(CompileFail::Syntax(e)) => return Err(interp.throw(ErrorType::Syntax, &e.message)), Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)), }; @@ -663,6 +696,10 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J let Some(target) = this.as_object() else { return Err(interp.type_error("the value bind was called on is not a function")) }; let bound_this = arg(args, 0); let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into(); + // With ECMAScript 2015 the bound function inherits from the target's prototype, read before + // `length` and `name` (ECMA-262 2020 section 9.4.1.3 step 2), so a bound generator function + // inherits from %GeneratorFunction.prototype%. + let target_proto = interp.heap.object(target).and_then(|o| o.proto); // A host function's `length` is an ordinary property a script can set, so it is converted // to an integer first, as later editions specify. With ECMAScript 2015 only an own `length` is // read (ECMA-262 2020 section 19.2.3.2 step 4), so an inherited getter does not run. @@ -676,7 +713,7 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J // Adding 0 turns a negative zero into 0. let length = (target_length - bound_args.len() as f64).max(0.0) + 0.0; if interp.options.es2015 { - return bind_es2015(interp, target, bound_this, bound_args, length); + return bind_es2015(interp, target, target_proto, bound_this, bound_args, length); } interp.reserve_heap(OBJECT_BYTES + prop_bytes(&["length", "caller", "arguments"]) + BOUND_ARG_BYTES * bound_args.len())?; let proto = interp.intrinsics.function_proto; @@ -698,9 +735,10 @@ fn prop_bytes(names: &[&str]) -> usize { /// The rest of `Function.prototype.bind` with [`crate::Options::es2015`] (ECMA-262 2020 section /// 19.2.3.2): the bound function's `length` is configurable, its `name` is `bound ` and the -/// target's `name` when that is a string (read after `length`, so a getter for it runs). It keeps -/// the `caller` and `arguments` that throw, as without the option. -fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { +/// target's `name` when that is a string (read after `length`, so a getter for it runs), and its +/// prototype is `proto`, the target's. It keeps the `caller` and `arguments` that throw, as +/// without the option. +fn bind_es2015(interp: &mut Interp, target: ObjId, proto: Option, bound_this: Value, bound_args: Rc<[Value]>, length: f64) -> JsResult { let target_name = match interp.get_from(target, &key("name"), &Value::Object(target))? { Value::String(s) => s, _ => Str::from(""), @@ -716,9 +754,8 @@ fn bind_es2015(interp: &mut Interp, target: ObjId, bound_this: Value, bound_args crate::string_builtins::charge_units(interp, name_len)?; let mut units: Vec = "bound ".encode_utf16().collect(); units.extend_from_slice(&target_units); - let proto = interp.intrinsics.function_proto; let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() }); - let f = interp.heap.alloc_object(Object::new(class, Some(proto))); + let f = interp.heap.alloc_object(Object::new(class, proto)); interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES * bound_args.len() + string_bytes(name_len)); interp.define(f, key("length"), Prop::Data { value: Value::Number(length), flags: CONFIGURABLE })?; interp.define(f, key("name"), Prop::Data { value: Value::String(Str::from_units(units)), flags: CONFIGURABLE })?; diff --git a/crates/js/src/builtins/generator.rs b/crates/js/src/builtins/generator.rs new file mode 100644 index 0000000000..c8e46e09d6 --- /dev/null +++ b/crates/js/src/builtins/generator.rs @@ -0,0 +1,51 @@ +//! The generator built-ins (ECMA-262 11th edition, ): +//! `%GeneratorFunction%` with its `prototype` (sections 25.2.1 and 25.2.3) and +//! `%GeneratorPrototype%` with `next`, `return` and `throw` (section 25.4.1), which inherits +//! from `%IteratorPrototype%`. Installed in a realm with [`crate::Options::es2015`] only, after the +//! iterators. `GeneratorFunction` is not a global; a script reaches it through a generator +//! function's `constructor`. + +use super::{data, native, unreachable_native}; +use crate::generator::ResumeMode; +use crate::heap::{CONFIGURABLE, Class, HIDDEN, NativeKind, ObjId, Object, Prop}; +use crate::interp::{Interp, JsResult}; +use crate::value::Value; + +pub(super) fn install(interp: &mut Interp, function: ObjId) -> JsResult<()> { + let Some(to_string_tag) = interp.well_known(|w| &w.to_string_tag) else { return Ok(()) }; + let Some(mut objects) = interp.symbols.objects else { return Ok(()) }; + let object_proto = interp.intrinsics.object_proto; + let iterator_proto = interp.heap.object(objects.array_iterator_proto).and_then(|o| o.proto).unwrap_or(object_proto); + + let generator_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(iterator_proto))); + for (name, mode) in [("next", ResumeMode::Next), ("return", ResumeMode::Return), ("throw", ResumeMode::Throw)] { + let m = native(interp, name, unreachable_native, 1, NativeKind::Resume(mode), false)?; + data(interp, generator_proto, name, Value::Object(m), HIDDEN)?; + } + interp.define_sym(generator_proto, to_string_tag.clone(), Prop::Data { value: Value::str("Generator"), flags: CONFIGURABLE })?; + + let function_proto = interp.intrinsics.function_proto; + // %GeneratorFunction.prototype% is an ordinary object, not a function, that inherits from + // Function.prototype (section 25.2.3). + let generator_function_proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(function_proto))); + data(interp, generator_function_proto, "prototype", Value::Object(generator_proto), CONFIGURABLE)?; + data(interp, generator_proto, "constructor", Value::Object(generator_function_proto), CONFIGURABLE)?; + interp.define_sym(generator_function_proto, to_string_tag, Prop::Data { value: Value::str("GeneratorFunction"), flags: CONFIGURABLE })?; + + let generator_function = native(interp, "GeneratorFunction", generator_function_ctor, 1, NativeKind::Plain, true)?; + if let Some(o) = interp.heap.object_mut(generator_function) { + o.proto = Some(function); + } + data(interp, generator_function, "prototype", Value::Object(generator_function_proto), 0)?; + data(interp, generator_function_proto, "constructor", Value::Object(generator_function), CONFIGURABLE)?; + + objects.generator_proto = generator_proto; + objects.generator_function_proto = generator_function_proto; + interp.symbols.objects = Some(objects); + Ok(()) +} + +/// `GeneratorFunction(p1, …, body)` and `new GeneratorFunction(…)` (section 25.2.1.1). +fn generator_function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + super::create_dynamic_function(interp, args, true) +} diff --git a/crates/js/src/builtins/iterator.rs b/crates/js/src/builtins/iterator.rs index b40f979fc0..d7d5a8192a 100644 --- a/crates/js/src/builtins/iterator.rs +++ b/crates/js/src/builtins/iterator.rs @@ -84,7 +84,7 @@ fn iter_result_bytes() -> usize { } /// CreateIterResultObject (section 7.4.7): `{ value, done }`. -fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { +pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(iter_result_bytes()))?; let proto = interp.intrinsics.object_proto; let o = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index e01a47b085..2b022bc858 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -538,7 +538,7 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K keep(interp, &v); let name = Value::String(Str::from_rc(k.clone())); if let Value::Object(o) = v { - let to_json = interp.get_from(o, &key("toJSON"), &v)?; + let to_json = interp.get_property_only(o, &key("toJSON"), &v)?; if interp.is_callable(&to_json) { v = interp.call(&to_json, &v, std::slice::from_ref(&name))?; keep(interp, &v); diff --git a/crates/js/src/builtins/promise.rs b/crates/js/src/builtins/promise.rs new file mode 100644 index 0000000000..9122362928 --- /dev/null +++ b/crates/js/src/builtins/promise.rs @@ -0,0 +1,1185 @@ +//! `Promise` (ECMA-262 11th edition, section 25.6, ) +//! and the run's queue of promise jobs (section 8.4), in realms with [`crate::Options::es2015`]: +//! the constructor, `then`, `catch` and `finally`, and `Promise.resolve`, `reject`, `all`, +//! `allSettled` and `race`. `Promise.any` (ES2021) is not provided. +//! +//! A job is queued when a promise settles with reactions waiting, when `then` is called on a +//! settled promise, and when a promise is resolved with a thenable. Jobs run one at a time, in the +//! order they were queued, once the script's own code has ended and no other code runs: at the end +//! of [`crate::Realm::run`], and in the slices [`crate::Realm::advance`] runs after the script's +//! code, before it reports the run done. A job that a job queues joins the end of the queue. A job +//! takes a unit of fuel, its callback runs on the run's fuel, heap and frame limits, and a callback +//! written in JavaScript runs as the script's own code, so a slice can pause inside it. Each queued +//! job counts [`JOB_BYTES`] toward the heap limit, and more than [`MAX_JOBS`] queued jobs end the +//! run with [`LimitKind::Jobs`]. A run that ends with an error or a limit, or is ended, drops the +//! jobs still queued. A promise that is still pending when the queue is empty stays pending. +//! +//! A promise rejected while it has no handler is noted (HostPromiseRejectionTracker, section +//! 25.6.1.9); one that still has none when the run ends successfully is reported by +//! [`crate::Realm::unhandled_rejections`], with the place it was rejected at when known. +//! +//! `all`, `allSettled` and `race` read their input through `Symbol.iterator` and close the iterator +//! when processing a yielded value throws. Noniterable values reject the promise they return +//! with a `TypeError`. The statics need a constructor as `this`, and the +//! promises they and `then` make are always built-in promises: subclasses and `Symbol.species` +//! are not read. + +use std::collections::VecDeque; +use std::rc::Rc; + +use super::{arg, constructor, create_at, method, native, new_array}; +use crate::LimitKind; +use crate::bytecode::Code; +use crate::heap::{ + BOUND_ARG_BYTES, CONFIGURABLE, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key, +}; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::Value; + +/// Where a promise was rejected: the code and the instruction. +pub(crate) type Site = (Rc, usize); + +/// The estimated bytes of a promise's state, without its reactions. +pub(crate) const PROMISE_BYTES: usize = 64; +/// The estimated bytes of a reaction a pending promise holds. +pub(crate) const REACTION_BYTES: usize = 48; +/// The estimated bytes of the state a promise operation's functions share. +pub(crate) const RECORD_BYTES: usize = 48; +/// The estimated bytes of a queued job. +pub(crate) const JOB_BYTES: usize = 64; +/// The most jobs the queue may hold at once. +pub(crate) const MAX_JOBS: usize = 1 << 20; +/// The most unhandled rejections a run reports one by one. +pub(crate) const MAX_REPORTED: usize = 20; +/// The most characters of a rejection's reason a report gives. +const MAX_REASON_CHARS: usize = 500; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum State { + Pending, + Fulfilled, + Rejected, +} + +/// A `then` waiting for a pending promise: the handlers (`undefined` when not callable) and the +/// promise `then` returned. +#[derive(Clone)] +pub(crate) struct Reaction { + on_fulfilled: Value, + on_rejected: Value, + derived: ObjId, +} + +/// A promise's internal slots (section 25.6.6), with where it was rejected. +#[derive(Clone)] +pub(crate) struct PromiseData { + pub(crate) state: State, + pub(crate) result: Value, + reactions: Vec, + pub(crate) handled: bool, + pub(crate) site: Option, +} + +impl PromiseData { + fn new() -> Self { + Self { state: State::Pending, result: Value::Undefined, reactions: Vec::new(), handled: false, site: None } + } + + /// The values the promise holds, for the collector. + pub(crate) fn values(&self) -> Vec { + let mut out = vec![self.result.clone()]; + for r in &self.reactions { + out.extend([r.on_fulfilled.clone(), r.on_rejected.clone(), Value::Object(r.derived)]); + } + out + } + + /// The estimated bytes of the state, beyond the object. + pub(crate) fn bytes(&self) -> usize { + PROMISE_BYTES + REACTION_BYTES * self.reactions.len() + } +} + +/// The state the functions a promise operation makes share. +#[derive(Clone)] +pub(crate) enum Record { + /// A promise's resolve and reject functions (section 25.6.1.3): the first call wins. + Resolving { promise: ObjId, done: bool }, + /// `Promise.all` and `allSettled`: the result's resolving record, the values so far and the + /// inputs not yet settled. + Combinator { resolving: ObjId, values: ObjId, remaining: u64 }, + /// The functions for one input of `Promise.all` or `allSettled`. + Element { combinator: ObjId, index: u32, called: bool }, + /// `finally`'s callback. + Finally { on_finally: Value }, + /// A value `finally` passes on or throws again. + Thunk { value: Value }, +} + +impl Record { + /// The values the record holds, for the collector. + pub(crate) fn values(&self) -> Vec { + match self { + Record::Resolving { promise, .. } => vec![Value::Object(*promise)], + Record::Combinator { resolving, values, .. } => vec![Value::Object(*resolving), Value::Object(*values)], + Record::Element { combinator, .. } => vec![Value::Object(*combinator)], + Record::Finally { on_finally: v } | Record::Thunk { value: v } => vec![v.clone()], + } + } +} + +/// A queued job. +enum Job { + /// PromiseReactionJob (section 25.6.2.1): calls `handler` with `argument` and settles + /// `derived` with the result, or passes `argument` on when `handler` is not callable. + Reaction { handler: Value, argument: Value, reject: bool, derived: ObjId, site: Option }, + /// PromiseResolveThenableJob (section 25.6.2.2): calls `then` on `thenable` with new + /// resolving functions for `promise`. + Thenable { promise: ObjId, thenable: Value, then: Value }, +} + +/// What happens when the running job's call ends. +enum Then { + /// The result resolves this promise, and an exception rejects it. + Settle(ObjId, Option), + /// An exception rejects through this resolving record. + Reject(ObjId), + /// The call was a `finally` callback that a reaction job runs in place of the Then Finally or + /// Catch Finally function: `derived` is settled as that function's result settles it. + Finally { derived: ObjId, value: Value, throws: bool }, +} + +/// The built-in functions a promise operation's functions call, with their record. +#[derive(Clone, Copy)] +enum Kind { + Resolve, + Reject, + AllElement, + SettledFulfilled, + SettledRejected, + ThenFinally, + CatchFinally, + ValueThunk, + Thrower, +} + +const KINDS: [(Kind, NativeFn); 9] = [ + (Kind::Resolve, resolve_function), + (Kind::Reject, reject_function), + (Kind::AllElement, all_element), + (Kind::SettledFulfilled, settled_fulfilled), + (Kind::SettledRejected, settled_rejected), + (Kind::ThenFinally, then_finally), + (Kind::CatchFinally, catch_finally), + (Kind::ValueThunk, value_thunk), + (Kind::Thrower, thrower), +]; + +/// `Promise`'s objects and the run's job queue. +pub(crate) struct Promises { + proto: Option, + ctor: Option, + /// The built-ins for each [`Kind`], in [`KINDS`] order. + natives: Vec, + queue: VecDeque, + running: Option, + /// The script's completion value while the jobs after it run. + completion: Option, + /// The script's own code has ended and the queue's jobs are running. + pub(crate) draining: bool, + /// Promises rejected in this run while they had no handler. + rejected: Vec, + /// The most jobs the queue may hold ([`MAX_JOBS`]; tests set it lower). + pub(crate) max_jobs: usize, +} + +impl Default for Promises { + fn default() -> Self { + Self { + proto: None, + ctor: None, + natives: Vec::new(), + queue: VecDeque::new(), + running: None, + completion: None, + draining: false, + rejected: Vec::new(), + max_jobs: MAX_JOBS, + } + } +} + +impl Promises { + /// Adds what the queue and the promise objects hold to the collector's roots. + pub(crate) fn add_roots<'a>(&'a self, roots: &mut Roots<'a>) { + roots.objects.extend(self.proto.iter().chain(&self.ctor).chain(&self.natives).chain(&self.rejected)); + roots.values.extend(self.completion.iter()); + match &self.running { + Some(Then::Settle(o, site)) => { + roots.objects.push(*o); + roots.codes.extend(site.iter().map(|(code, _)| &**code)); + } + Some(Then::Reject(o)) => roots.objects.push(*o), + Some(Then::Finally { derived, value, .. }) => { + roots.objects.push(*derived); + roots.values.push(value); + } + None => {} + } + for job in &self.queue { + match job { + Job::Reaction { handler, argument, derived, site, .. } => { + roots.values.extend([handler, argument]); + roots.objects.push(*derived); + roots.codes.extend(site.iter().map(|(code, _)| &**code)); + } + Job::Thenable { promise, thenable, then } => { + roots.values.extend([thenable, then]); + roots.objects.push(*promise); + } + } + } + } + + /// The estimated bytes the queued jobs hold. + pub(crate) fn queue_bytes(&self) -> usize { + JOB_BYTES.saturating_mul(self.queue.len()) + } + + /// How many jobs are queued, and how many the queue's buffer has room for. + #[cfg(test)] + pub(crate) fn queue_size(&self) -> (usize, usize) { + (self.queue.len(), self.queue.capacity()) + } + + /// Drops the noted rejections whose promise has a handler now. + pub(crate) fn forget_handled(&mut self, heap: &crate::heap::Heap) { + self.rejected.retain(|p| matches!(heap.object(*p).map(|o| &o.class), Some(Class::Promise(d)) if !d.handled)); + } +} + +/// Creates `Promise`, its prototype methods and its statics. +pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + interp.promises.proto = Some(proto); + if let Some(tag) = interp.well_known(|w| &w.to_string_tag) { + interp.define_sym(proto, tag, Prop::Data { value: Value::str("Promise"), flags: CONFIGURABLE })?; + } + let ctor = native(interp, "Promise", promise_ctor, 1, NativeKind::Plain, true)?; + interp.promises.ctor = Some(ctor); + constructor(interp, "Promise", ctor, proto)?; + method(interp, proto, "then", promise_then, 2)?; + method(interp, proto, "catch", promise_catch, 1)?; + method(interp, proto, "finally", promise_finally, 1)?; + method(interp, ctor, "resolve", promise_resolve_static, 1)?; + method(interp, ctor, "reject", promise_reject_static, 1)?; + method(interp, ctor, "all", promise_all, 1)?; + method(interp, ctor, "allSettled", promise_all_settled, 1)?; + method(interp, ctor, "race", promise_race, 1)?; + for (_, f) in KINDS { + let n = native(interp, "", f, 1, NativeKind::Plain, false)?; + interp.promises.natives.push(n); + } + Ok(()) +} + +/// Creates `Promise` in a realm made without [`crate::Options::es2015`], replacing a global +/// `Promise` an earlier script defined, and leaves the language the realm's runs read as it is. A +/// realm that has the built-in `Promise` already keeps it. When `Promise` cannot be created, every +/// later run of the realm ends with an internal error, as for a realm whose built-ins could not be +/// installed. +pub(crate) fn add_to(interp: &mut Interp) { + if interp.promises.ctor.is_some() || interp.install_error.is_some() { + return; + } + if let Err(e) = install(interp) { + let reason = match e { + Abrupt::Throw(v) => interp.describe(&v), + Abrupt::Limit(kind) => format!("limit reached: {kind:?}"), + Abrupt::Internal(message) => message, + }; + interp.install_error = Some(format!("the built-ins could not be installed: {reason}")); + } +} + +// ---- helpers ---- + +/// Runs `f`, then drops the temporary roots it added. +fn scoped(interp: &mut Interp, f: impl FnOnce(&mut Interp) -> JsResult) -> JsResult { + let mark = interp.temp_roots.len(); + let r = f(interp); + interp.temp_roots.truncate(mark); + r +} + +fn root(interp: &mut Interp, v: &Value) { + interp.temp_roots.push(v.clone()); +} + +/// An exception that a promise operation turns into a rejection: it is no longer propagating, and +/// the place it was thrown at, when known, is the rejection's. +fn caught(interp: &mut Interp) -> Option { + interp.passing = Value::Undefined; + interp.thrown_mark = None; + interp.throw_site.take() +} + +/// The instruction the innermost script frame is running. +fn here(interp: &Interp) -> Option { + interp.frames.last().map(|f| (f.code.clone(), f.pc.saturating_sub(1))) +} + +/// The value an error of type `t` with `message` is. +fn error_value(interp: &mut Interp, t: ErrorType, message: &str) -> Value { + match interp.throw(t, message) { + Abrupt::Throw(v) => v, + _ => Value::Undefined, + } +} + +fn promise_data(interp: &mut Interp, p: ObjId) -> JsResult<&mut PromiseData> { + match interp.heap.object_mut(p).map(|o| &mut o.class) { + Some(Class::Promise(d)) => Ok(d), + _ => Err(Abrupt::Internal("a promise operation lost its promise".into())), + } +} + +fn record<'a>(interp: &'a mut Interp, r: &Value) -> JsResult<&'a mut Record> { + match r.as_object().and_then(|o| interp.heap.object_mut(o)).map(|o| &mut o.class) { + Some(Class::PromiseRecord(rec)) => Ok(rec), + _ => Err(Abrupt::Internal("a promise function lost its record".into())), + } +} + +fn is_promise(interp: &Interp, v: &Value) -> bool { + v.as_object().and_then(|o| interp.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Promise(_))) +} + +/// `this` for a `Promise.prototype` method that needs a promise. +fn this_promise(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + match this.as_object() { + Some(o) if is_promise(interp, this) => Ok(o), + _ => Err(interp.type_error(&format!("Promise.prototype.{name} was called on a value that is not a promise"))), + } +} + +/// Invoke (section 7.3.18): calls `v[name]` with `v` as `this`. +fn invoke(interp: &mut Interp, v: &Value, name: &str, args: &[Value]) -> JsResult { + let f = interp.get_value(v, &key(name))?; + if !interp.is_callable(&f) { + return Err(interp.type_error(&format!("{name} is not a function"))); + } + interp.call(&f, v, args) +} + +/// A new pending promise. +fn new_promise(interp: &mut Interp) -> JsResult { + interp.reserve_heap(OBJECT_BYTES + PROMISE_BYTES)?; + let proto = interp.promises.proto; + let o = interp.heap.alloc_object(Object::new(Class::Promise(Box::new(PromiseData::new())), proto)); + interp.heap.bytes = interp.heap.bytes.saturating_add(PROMISE_BYTES); + Ok(o) +} + +/// A new record. The values it holds must be rooted. +fn new_record(interp: &mut Interp, rec: Record) -> JsResult { + interp.reserve_heap(OBJECT_BYTES + RECORD_BYTES)?; + let o = interp.heap.alloc_object(Object::new(Class::PromiseRecord(Box::new(rec)), None)); + interp.heap.bytes = interp.heap.bytes.saturating_add(RECORD_BYTES); + Ok(o) +} + +/// A function that calls the built-in for `kind` with `rec` before its own arguments. `rec` must +/// be rooted. +fn record_function(interp: &mut Interp, kind: Kind, rec: ObjId, length: u32) -> JsResult { + let Some(&target) = interp.promises.natives.get(kind as usize) else { return Err(Abrupt::Internal("Promise is not installed".into())) }; + interp.reserve_heap(OBJECT_BYTES + PROP_BYTES + BOUND_ARG_BYTES + 16)?; + let proto = interp.intrinsics.function_proto; + let args: Rc<[Value]> = Rc::from([Value::Object(rec)]); + let f = interp.heap.alloc_object(Object::new(Class::Function(Func::Bound { target, this: Value::Undefined, args }), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(BOUND_ARG_BYTES); + interp.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + Ok(Value::Object(f)) +} + +/// CreateResolvingFunctions (section 25.6.1.3): the shared record, the resolve function and the +/// reject function. `promise` must be rooted. +fn resolving_functions(interp: &mut Interp, promise: ObjId) -> JsResult<(ObjId, Value, Value)> { + scoped(interp, |interp| { + let rec = new_record(interp, Record::Resolving { promise, done: false })?; + root(interp, &Value::Object(rec)); + let resolve = record_function(interp, Kind::Resolve, rec, 1)?; + root(interp, &resolve); + let reject = record_function(interp, Kind::Reject, rec, 1)?; + Ok((rec, resolve, reject)) + }) +} + +/// Checks that `n` more jobs fit in the queue and in the heap. Everything the caller still needs +/// must be reachable from the roots. +fn reserve_jobs(interp: &mut Interp, n: usize) -> JsResult<()> { + if interp.promises.queue.len().saturating_add(n) > interp.promises.max_jobs { + return Err(Abrupt::Limit(LimitKind::Jobs)); + } + interp.reserve_heap(JOB_BYTES.saturating_mul(n)) +} + +/// Queues a job [`reserve_jobs`] made room for. +fn push_job(interp: &mut Interp, job: Job) { + interp.heap.bytes = interp.heap.bytes.saturating_add(JOB_BYTES); + interp.promises.queue.push_back(job); +} + +/// Settles pending promise `p` (FulfillPromise and RejectPromise, sections 25.6.1.4 and 25.6.1.7) +/// and queues a job for each reaction. `p` and `value` must be rooted. +fn settle(interp: &mut Interp, p: ObjId, fulfilled: bool, value: Value, site: Option) -> JsResult<()> { + let waiting = promise_data(interp, p)?.reactions.len(); + reserve_jobs(interp, waiting)?; + let data = promise_data(interp, p)?; + if data.state != State::Pending { + return Ok(()); + } + data.state = if fulfilled { State::Fulfilled } else { State::Rejected }; + data.result = value.clone(); + if !fulfilled { + data.site.clone_from(&site); + } + let reactions = std::mem::take(&mut data.reactions); + let handled = data.handled; + interp.heap.bytes = interp.heap.bytes.saturating_sub(REACTION_BYTES.saturating_mul(reactions.len())); + for r in reactions { + let handler = if fulfilled { r.on_fulfilled } else { r.on_rejected }; + push_job(interp, Job::Reaction { handler, argument: value.clone(), reject: !fulfilled, derived: r.derived, site: site.clone() }); + } + if !fulfilled && !handled { + interp.promises.rejected.push(p); + } + Ok(()) +} + +fn reject_promise(interp: &mut Interp, p: ObjId, reason: Value, site: Option) -> JsResult<()> { + scoped(interp, |interp| { + root(interp, &Value::Object(p)); + root(interp, &reason); + settle(interp, p, false, reason, site) + }) +} + +/// A resolve function's steps after its first-call check (section 25.6.1.3.2): `resolution` +/// fulfills `p`, unless it is `p` itself (a `TypeError` rejects it) or an object whose `then` is +/// callable (a job adopts its state), and an exception reading `then` rejects it. +fn resolve_promise(interp: &mut Interp, p: ObjId, resolution: Value) -> JsResult<()> { + scoped(interp, |interp| { + root(interp, &Value::Object(p)); + root(interp, &resolution); + let Value::Object(o) = resolution else { return settle(interp, p, true, resolution, None) }; + if o == p { + let e = error_value(interp, ErrorType::Type, "a promise cannot be resolved with itself"); + let site = here(interp); + return reject_promise(interp, p, e, site); + } + let then = match interp.get_from(o, &key("then"), &resolution) { + Ok(t) => t, + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + return settle(interp, p, false, e, site); + } + Err(e) => return Err(e), + }; + if !interp.is_callable(&then) { + return settle(interp, p, true, resolution, None); + } + root(interp, &then); + reserve_jobs(interp, 1)?; + push_job(interp, Job::Thenable { promise: p, thenable: resolution, then }); + Ok(()) + }) +} + +/// The resolve function of the resolving record `rec`. +fn resolve_through(interp: &mut Interp, rec: ObjId, value: Value) -> JsResult<()> { + let Record::Resolving { promise, done } = record(interp, &Value::Object(rec))? else { + return Err(Abrupt::Internal("not a resolving record".into())); + }; + if *done { + return Ok(()); + } + *done = true; + let p = *promise; + resolve_promise(interp, p, value) +} + +/// The reject function of the resolving record `rec`. +fn reject_through(interp: &mut Interp, rec: ObjId, reason: Value, site: Option) -> JsResult<()> { + let Record::Resolving { promise, done } = record(interp, &Value::Object(rec))? else { + return Err(Abrupt::Internal("not a resolving record".into())); + }; + if *done { + return Ok(()); + } + *done = true; + let p = *promise; + reject_promise(interp, p, reason, site) +} + +/// PerformPromiseThen (section 25.6.5.4.1) with `derived` as the result capability's promise. +/// Every value must be rooted. +fn perform_then(interp: &mut Interp, p: ObjId, on_fulfilled: Value, on_rejected: Value, derived: ObjId) -> JsResult<()> { + let on_fulfilled = if interp.is_callable(&on_fulfilled) { on_fulfilled } else { Value::Undefined }; + let on_rejected = if interp.is_callable(&on_rejected) { on_rejected } else { Value::Undefined }; + let state = promise_data(interp, p)?.state; + if state == State::Pending { + interp.reserve_heap(REACTION_BYTES)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(REACTION_BYTES); + } else { + reserve_jobs(interp, 1)?; + } + let data = promise_data(interp, p)?; + data.handled = true; + match data.state { + State::Pending => { + data.reactions.push(Reaction { on_fulfilled, on_rejected, derived }); + } + State::Fulfilled => { + let argument = data.result.clone(); + push_job(interp, Job::Reaction { handler: on_fulfilled, argument, reject: false, derived, site: None }); + } + State::Rejected => { + let (argument, site) = (data.result.clone(), data.site.clone()); + push_job(interp, Job::Reaction { handler: on_rejected, argument, reject: true, derived, site }); + } + } + Ok(()) +} + +/// PromiseResolve (section 25.6.4.5.1) with `c` as the constructor: `x` when it is a promise whose +/// `constructor` is `c`, otherwise a new promise resolved with `x`. +fn promise_resolve(interp: &mut Interp, c: &Value, x: Value) -> JsResult { + scoped(interp, |interp| { + root(interp, &x); + if let Value::Object(o) = x + && is_promise(interp, &x) + { + let ctor = interp.get_from(o, &key("constructor"), &x)?; + if crate::interp::same_value(&ctor, c) { + return Ok(x); + } + } + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + resolve_promise(interp, p, x)?; + Ok(Value::Object(p)) + }) +} + +// ---- the job queue ---- + +impl Interp { + /// A run begun with [`crate::Realm::start`] is going: its script's code or the jobs after it. + pub(crate) fn running(&self) -> bool { + !self.frames.is_empty() || self.promises.draining + } + + /// Runs the queued jobs, and the jobs they queue, until the queue is empty, after the script's + /// code ended with `completion`, which this gives back. + pub(crate) fn drain_jobs(&mut self, completion: Value) -> JsResult { + self.promises.completion = Some(completion); + loop { + if !self.frames.is_empty() { + let r = self.execute(); + self.job_returned(r)?; + continue; + } + let Some(job) = self.promises.queue.pop_front() else { break }; + self.start_job(job)?; + } + Ok(self.promises.completion.take().unwrap_or(Value::Undefined)) + } + + /// [`Interp::execute_slice`] for a run begun with [`crate::Realm::start`]: runs the script's + /// code and then the queued jobs, and gives `Some` with the script's completion value once the + /// code has ended and the queue is empty. + pub(crate) fn execute_run_slice(&mut self, pause_at: u64) -> JsResult> { + loop { + if self.frames.is_empty() { + let Some(job) = self.promises.queue.pop_front() else { + self.promises.draining = false; + // A pause asked for in the run's last step ends with the run. + self.pause.set(false); + return Ok(Some(self.promises.completion.take().unwrap_or(Value::Undefined))); + }; + self.start_job(job)?; + if self.can_pause_between_jobs(pause_at) { + return Ok(None); + } + continue; + } + match self.execute_slice(pause_at) { + Ok(None) => return Ok(None), + Ok(Some(v)) if self.promises.running.is_none() => { + // The script's own code ended. + if self.promises.queue.is_empty() { + self.pause.set(false); + return Ok(Some(v)); + } + self.promises.completion = Some(v); + self.promises.draining = true; + } + Ok(Some(v)) => self.finish_job(Ok(v))?, + Err(Abrupt::Throw(v)) if self.promises.running.is_some() => self.finish_job(Err(v))?, + Err(e) => return Err(e), + } + if self.can_pause_between_jobs(pause_at) { + return Ok(None); + } + } + } + + /// No code is running and jobs are still queued, and the slice has used its fuel or the host + /// asked for a pause. With the queue empty the run is done instead, and the next turn of the + /// loop ends it. + fn can_pause_between_jobs(&self, pause_at: u64) -> bool { + self.frames.is_empty() && !self.promises.queue.is_empty() && (self.fuel <= pause_at || self.pause.replace(false)) + } + + fn job_returned(&mut self, r: JsResult) -> JsResult<()> { + match r { + Ok(v) => self.finish_job(Ok(v)), + Err(Abrupt::Throw(v)) => self.finish_job(Err(v)), + Err(e) => Err(e), + } + } + + /// Starts a job: a native callback runs to its end here, and a callback written in JavaScript + /// gets a frame the caller runs. + fn start_job(&mut self, job: Job) -> JsResult<()> { + self.heap.bytes = self.heap.bytes.saturating_sub(JOB_BYTES); + self.use_fuel()?; + scoped(self, |interp| { + let (f, this, args, then) = match job { + Job::Reaction { handler, argument, reject, derived, site } => { + if !interp.is_callable(&handler) { + return if reject { reject_promise(interp, derived, argument, site) } else { resolve_promise(interp, derived, argument) }; + } + root(interp, &Value::Object(derived)); + match finally_callback(interp, &handler) { + // The callback runs as the job's own call, so a slice can pause inside it. + Some((on_finally, throws)) => { + interp.temp_roots.extend([handler, argument.clone()]); + (on_finally, Value::Undefined, Vec::new(), Then::Finally { derived, value: argument, throws }) + } + None => (handler, Value::Undefined, vec![argument], Then::Settle(derived, site)), + } + } + Job::Thenable { promise, thenable, then } => { + interp.temp_roots.extend([Value::Object(promise), thenable.clone(), then.clone()]); + let (rec, resolve, reject) = resolving_functions(interp, promise)?; + (then, thenable, vec![resolve, reject], Then::Reject(rec)) + } + }; + interp.temp_roots.push(f.clone()); + interp.temp_roots.push(this.clone()); + interp.temp_roots.extend(args.iter().cloned()); + interp.promises.running = Some(then); + match interp.start_call(f, this, args) { + Ok(Some(v)) => interp.finish_job(Ok(v)), + Ok(None) => Ok(()), + Err(Abrupt::Throw(e)) => interp.finish_job(Err(e)), + Err(e) => Err(e), + } + }) + } + + /// Ends the running job with its call's result or exception. + fn finish_job(&mut self, r: Result) -> JsResult<()> { + let site = if r.is_err() { caught(self) } else { None }; + let Some(then) = self.promises.running.take() else { return Err(Abrupt::Internal("no promise job is running".into())) }; + match (then, r) { + (Then::Settle(d, _), Ok(v)) => resolve_promise(self, d, v), + (Then::Settle(d, _), Err(e)) => reject_promise(self, d, e, site), + (Then::Reject(_), Ok(_)) => Ok(()), + (Then::Reject(rec), Err(e)) => scoped(self, |interp| { + root(interp, &Value::Object(rec)); + reject_through(interp, rec, e, site) + }), + (Then::Finally { derived, value, throws }, Ok(result)) => scoped(self, |interp| { + interp.temp_roots.extend([Value::Object(derived), value.clone(), result.clone()]); + match after_finally(interp, result, value, throws) { + Ok(v) => resolve_promise(interp, derived, v), + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + reject_promise(interp, derived, e, site) + } + Err(e) => Err(e), + } + }), + (Then::Finally { derived, .. }, Err(e)) => reject_promise(self, derived, e, site), + } + } + + /// Drops the run's queued jobs and its state; with `keep_rejections` false, the rejections it + /// noted too. + pub(crate) fn end_jobs(&mut self, keep_rejections: bool) { + let queued = self.promises.queue_bytes(); + self.heap.bytes = self.heap.bytes.saturating_sub(queued); + // A new queue frees the old one's buffer, which the heap estimate does not count. + self.promises.queue = VecDeque::new(); + self.promises.running = None; + self.promises.completion = None; + self.promises.draining = false; + if !keep_rejections { + self.promises.rejected.clear(); + } + } + + /// The promises the run rejected that still have no handler, the first [`MAX_REPORTED`] of + /// them described, and how many there are; the run's notes are cleared. + pub(crate) fn take_unhandled(&mut self) -> (Vec, usize) { + let rejected = std::mem::take(&mut self.promises.rejected); + let mut out = Vec::new(); + let mut attribution = Vec::new(); + let mut count = 0; + for p in rejected { + let (reason, site) = match self.heap.object(p).map(|o| &o.class) { + Some(Class::Promise(d)) if !d.handled && d.state == State::Rejected => (d.result.clone(), d.site.clone()), + _ => continue, + }; + count += 1; + if out.len() >= MAX_REPORTED { + continue; + } + // Two code units per character keeps MAX_REASON_CHARS characters and one more, so the + // cut below still marks a longer reason. + let mut message = self.describe_prefix(&reason, 2 * MAX_REASON_CHARS + 2); + if let Some((cut, _)) = message.char_indices().nth(MAX_REASON_CHARS) { + message.truncate(cut); + message.push('…'); + } + let authored = if let Some(object) = reason.as_object() { + if let Some((_, authored)) = attribution.iter().find(|(seen, _)| *seen == object) { + *authored + } else { + let authored = self.thrown_by_script(&reason); + attribution.push((object, authored)); + authored + } + } else { + self.thrown_by_script(&reason) + }; + let (tag, (line, column)) = site.map_or((crate::UNKNOWN_SOURCE, (0, 0)), |(code, pc)| (code.source.tag, code.line_column(pc))); + out.push(crate::Rejection { message, line, column, tag, authored }); + } + (out, count) + } +} + +// ---- Promise ---- + +/// `new Promise(executor)` (section 25.6.3.1). Calling `Promise` without `new` is a `TypeError`. +fn promise_ctor(interp: &mut Interp, _: Value, args: &[Value], constructed: bool) -> JsResult { + if !constructed { + return Err(interp.type_error("Promise must be called with new")); + } + let executor = arg(args, 0); + if !interp.is_callable(&executor) { + return Err(interp.type_error("the Promise executor is not a function")); + } + scoped(interp, |interp| { + root(interp, &executor); + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let (rec, resolve, reject) = resolving_functions(interp, p)?; + interp.temp_roots.extend([Value::Object(rec), resolve.clone(), reject.clone()]); + match interp.call(&executor, &Value::Undefined, &[resolve, reject]) { + Ok(_) => {} + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + reject_through(interp, rec, e, site)?; + } + Err(e) => return Err(e), + } + Ok(Value::Object(p)) + }) +} + +/// A promise's resolve function (section 25.6.1.3.2). +fn resolve_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a resolve function lost its record".into()))?; + resolve_through(interp, rec, arg(args, 1))?; + Ok(Value::Undefined) +} + +/// A promise's reject function (section 25.6.1.3.1). +fn reject_function(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let rec = arg(args, 0).as_object().ok_or_else(|| Abrupt::Internal("a reject function lost its record".into()))?; + let site = here(interp).or_else(|| match &interp.promises.running { + Some(Then::Settle(_, site)) => site.clone(), + _ => None, + }); + reject_through(interp, rec, arg(args, 1), site)?; + Ok(Value::Undefined) +} + +/// `Promise.prototype.then` (section 25.6.5.4). +fn promise_then(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let p = this_promise(interp, &this, "then")?; + scoped(interp, |interp| { + let derived = new_promise(interp)?; + root(interp, &Value::Object(derived)); + perform_then(interp, p, arg(args, 0), arg(args, 1), derived)?; + Ok(Value::Object(derived)) + }) +} + +/// `Promise.prototype.catch` (section 25.6.5.1). +fn promise_catch(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + invoke(interp, &this, "then", &[Value::Undefined, arg(args, 0)]) +} + +/// `Promise.prototype.finally` (section 25.6.5.3). +fn promise_finally(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + if !matches!(this, Value::Object(_)) { + return Err(interp.type_error("Promise.prototype.finally was called on a value that is not an object")); + } + let on_finally = arg(args, 0); + if !interp.is_callable(&on_finally) { + return invoke(interp, &this, "then", &[on_finally.clone(), on_finally]); + } + scoped(interp, |interp| { + let rec = new_record(interp, Record::Finally { on_finally })?; + root(interp, &Value::Object(rec)); + let then_finally = record_function(interp, Kind::ThenFinally, rec, 1)?; + root(interp, &then_finally); + let catch_finally = record_function(interp, Kind::CatchFinally, rec, 1)?; + root(interp, &catch_finally); + invoke(interp, &this, "then", &[then_finally, catch_finally]) + }) +} + +/// Then Finally and Catch Finally (sections 25.6.5.3.1 and 25.6.5.3.2): calls the callback, then +/// passes `value` on, or throws it again when `throws`, once the callback's result settles. +fn finally_step(interp: &mut Interp, args: &[Value], throws: bool) -> JsResult { + let rec_value = arg(args, 0); + let value = arg(args, 1); + let Record::Finally { on_finally } = record(interp, &rec_value)? else { return Err(Abrupt::Internal("not a finally record".into())) }; + let on_finally = on_finally.clone(); + let result = interp.call(&on_finally, &Value::Undefined, &[])?; + after_finally(interp, result, value, throws) +} + +/// The steps of Then Finally and Catch Finally after the callback returned `result`: a promise +/// that passes `value` on, or throws it again when `throws`, once `result` settles. +fn after_finally(interp: &mut Interp, result: Value, value: Value, throws: bool) -> JsResult { + scoped(interp, |interp| { + root(interp, &value); + root(interp, &result); + let ctor = interp.promises.ctor.map_or(Value::Undefined, Value::Object); + let promise = promise_resolve(interp, &ctor, result)?; + root(interp, &promise); + let rec = new_record(interp, Record::Thunk { value })?; + root(interp, &Value::Object(rec)); + let thunk = record_function(interp, if throws { Kind::Thrower } else { Kind::ValueThunk }, rec, 0)?; + root(interp, &thunk); + invoke(interp, &promise, "then", &[thunk]) + }) +} + +/// When `handler` is the Then Finally or Catch Finally function of a `finally` call, its callback, +/// and whether the function throws the value it gets again. +fn finally_callback(interp: &Interp, handler: &Value) -> Option<(Value, bool)> { + let Some(Class::Function(Func::Bound { target, args, .. })) = handler.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) else { + return None; + }; + let natives = &interp.promises.natives; + let throws = if natives.get(Kind::ThenFinally as usize) == Some(target) { + false + } else if natives.get(Kind::CatchFinally as usize) == Some(target) { + true + } else { + return None; + }; + match args.first().and_then(Value::as_object).and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + Some(Class::PromiseRecord(rec)) => match &**rec { + Record::Finally { on_finally } => Some((on_finally.clone(), throws)), + _ => None, + }, + _ => None, + } +} + +fn then_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + finally_step(interp, args, false) +} + +fn catch_finally(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + finally_step(interp, args, true) +} + +fn thunk_value(interp: &mut Interp, args: &[Value]) -> JsResult { + match record(interp, &arg(args, 0))? { + Record::Thunk { value } => Ok(value.clone()), + _ => Err(Abrupt::Internal("not a thunk record".into())), + } +} + +fn value_thunk(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + thunk_value(interp, args) +} + +fn thrower(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + Err(Abrupt::Throw(thunk_value(interp, args)?)) +} + +/// `v` is a constructor: a function written in JavaScript other than an arrow function, generator +/// function or method, a built-in constructor, or a bound function whose target is one. +fn is_constructor(interp: &mut Interp, v: &Value) -> JsResult { + let mut v = v.clone(); + loop { + let func = match v.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + Some(Class::Function(f)) => f.clone(), + _ => return Ok(false), + }; + match func { + Func::Closure { code, .. } => return Ok(!code.arrow && !code.method && !code.generator), + Func::Native { constructor, .. } => return Ok(constructor), + Func::Bound { target, .. } => { + interp.use_fuel()?; + v = Value::Object(target); + } + _ => return Ok(false), + } + } +} + +/// The `this` value of a static method, which must be a constructor. +fn this_constructor(interp: &mut Interp, this: &Value, name: &str) -> JsResult<()> { + if is_constructor(interp, this)? { + return Ok(()); + } + Err(interp.type_error(&format!("Promise.{name} was called on a value that is not a constructor"))) +} + +/// `Promise.resolve` (section 25.6.4.6). +fn promise_resolve_static(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_constructor(interp, &this, "resolve")?; + promise_resolve(interp, &this, arg(args, 0)) +} + +/// `Promise.reject` (section 25.6.4.5). +fn promise_reject_static(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_constructor(interp, &this, "reject")?; + scoped(interp, |interp| { + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let site = here(interp); + reject_promise(interp, p, arg(args, 0), site)?; + Ok(Value::Object(p)) + }) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Combine { + All, + AllSettled, + Race, +} + +impl Combine { + fn name(self) -> &'static str { + match self { + Combine::All => "all", + Combine::AllSettled => "allSettled", + Combine::Race => "race", + } + } +} + +fn promise_all(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::All) +} + +fn promise_all_settled(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::AllSettled) +} + +fn promise_race(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + combine(interp, this, arg(args, 0), Combine::Race) +} + +/// `Promise.all`, `allSettled` and `race` (sections 25.6.4.1, 25.6.4.2 and 25.6.4.4): an exception +/// on the way rejects the promise they return (IfAbruptRejectPromise). +fn combine(interp: &mut Interp, this: Value, input: Value, how: Combine) -> JsResult { + this_constructor(interp, &this, how.name())?; + scoped(interp, |interp| { + root(interp, &input); + let p = new_promise(interp)?; + root(interp, &Value::Object(p)); + let (rec, resolve, reject) = resolving_functions(interp, p)?; + interp.temp_roots.extend([Value::Object(rec), resolve.clone(), reject.clone()]); + match combine_inputs(interp, &this, &input, how, rec, &resolve, &reject) { + Ok(()) => {} + Err(Abrupt::Throw(e)) => { + let site = caught(interp); + root(interp, &e); + reject_through(interp, rec, e, site)?; + } + Err(e) => return Err(e), + } + Ok(Value::Object(p)) + }) +} + +fn combine_inputs(interp: &mut Interp, this: &Value, input: &Value, how: Combine, rec: ObjId, resolve: &Value, reject: &Value) -> JsResult<()> { + let resolve_fn = interp.get_value(this, &key("resolve"))?; + if !interp.is_callable(&resolve_fn) { + return Err(interp.type_error(&format!("Promise.{}: the constructor's resolve is not a function", how.name()))); + } + root(interp, &resolve_fn); + let iterator = interp.get_iterator(input)?; + root(interp, &Value::Object(iterator)); + let result = combine_iterator(interp, this, iterator, how, rec, &resolve_fn, (resolve, reject)); + if let Err(Abrupt::Throw(reason)) = &result { + root(interp, reason); + let site = interp.throw_site.clone(); + let mark = interp.thrown_mark; + match interp.iter_close(iterator) { + Ok(()) | Err(Abrupt::Throw(_)) => { + interp.throw_site = site; + interp.thrown_mark = mark; + interp.passing = reason.clone(); + } + Err(other) => return Err(other), + } + } + result +} + +fn combine_iterator( + interp: &mut Interp, + this: &Value, + iterator: ObjId, + how: Combine, + rec: ObjId, + resolve_fn: &Value, + handlers: (&Value, &Value), +) -> JsResult<()> { + let (resolve, reject) = handlers; + let combinator = if how == Combine::Race { + None + } else { + let values = new_array(interp, 0)?; + root(interp, &Value::Object(values)); + let c = new_record(interp, Record::Combinator { resolving: rec, values, remaining: 1 })?; + root(interp, &Value::Object(c)); + Some((c, values)) + }; + let mut index: u32 = 0; + loop { + let mark = interp.temp_roots.len(); + let Some(next) = interp.iter_next(iterator)? else { break }; + root(interp, &next); + let next_promise = interp.call(resolve_fn, this, &[next])?; + root(interp, &next_promise); + match combinator { + None => { + invoke(interp, &next_promise, "then", &[resolve.clone(), reject.clone()])?; + } + Some((c, values)) => { + create_at(interp, values, f64::from(index), Value::Undefined)?; + let el = new_record(interp, Record::Element { combinator: c, index, called: false })?; + root(interp, &Value::Object(el)); + let (on_fulfilled, on_rejected) = if how == Combine::All { + (record_function(interp, Kind::AllElement, el, 1)?, reject.clone()) + } else { + let f = record_function(interp, Kind::SettledFulfilled, el, 1)?; + root(interp, &f); + (f, record_function(interp, Kind::SettledRejected, el, 1)?) + }; + interp.temp_roots.extend([on_fulfilled.clone(), on_rejected.clone()]); + if let Record::Combinator { remaining, .. } = record(interp, &Value::Object(c))? { + *remaining += 1; + } + invoke(interp, &next_promise, "then", &[on_fulfilled, on_rejected])?; + } + } + interp.temp_roots.truncate(mark); + index = index.checked_add(1).filter(|&i| i < u32::MAX).ok_or_else(|| interp.throw(ErrorType::Range, "too many promises to combine"))?; + } + if let Some((c, _)) = combinator { + element_done(interp, c)?; + } + Ok(()) +} + +/// Counts one more settled input of a `Promise.all` or `allSettled`; after the last one, resolves +/// the result with the values. +fn element_done(interp: &mut Interp, c: ObjId) -> JsResult<()> { + let Record::Combinator { resolving, values, remaining } = record(interp, &Value::Object(c))? else { + return Err(Abrupt::Internal("not a combinator record".into())); + }; + *remaining = remaining.saturating_sub(1); + if *remaining > 0 { + return Ok(()); + } + let (resolving, values) = (*resolving, *values); + scoped(interp, |interp| { + root(interp, &Value::Object(c)); + resolve_through(interp, resolving, Value::Object(values)) + }) +} + +/// Stores `value` as one input's result (the first call only) and counts the input settled. +fn element_settled(interp: &mut Interp, args: &[Value], make: impl FnOnce(&mut Interp, Value) -> JsResult) -> JsResult { + let rec_value = arg(args, 0); + let Record::Element { combinator, index, called } = record(interp, &rec_value)? else { + return Err(Abrupt::Internal("not an element record".into())); + }; + if *called { + return Ok(Value::Undefined); + } + *called = true; + let (c, index) = (*combinator, *index); + let Record::Combinator { values, .. } = record(interp, &Value::Object(c))? else { + return Err(Abrupt::Internal("not a combinator record".into())); + }; + let values = *values; + let v = make(interp, arg(args, 1))?; + scoped(interp, |interp| { + root(interp, &v); + super::put_at(interp, values, f64::from(index), v.clone())?; + element_done(interp, c) + })?; + Ok(Value::Undefined) +} + +/// `Promise.all` Resolve Element Functions (section 25.6.4.1.2). +fn all_element(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |_, v| Ok(v)) +} + +/// An `allSettled` result object: `{ status, value }` or `{ status, reason }`. +fn settled_object(interp: &mut Interp, fulfilled: bool, v: Value) -> JsResult { + scoped(interp, |interp| { + root(interp, &v); + interp.reserve_heap(OBJECT_BYTES + 2 * PROP_BYTES + 64)?; + let o = interp.new_object(); + root(interp, &Value::Object(o)); + let (status, name) = if fulfilled { ("fulfilled", "value") } else { ("rejected", "reason") }; + interp.define(o, key("status"), Prop::Data { value: Value::str(status), flags: OPEN })?; + interp.define(o, key(name), Prop::Data { value: v, flags: OPEN })?; + Ok(Value::Object(o)) + }) +} + +/// `Promise.allSettled` Resolve Element Functions (section 25.6.4.2.2). +fn settled_fulfilled(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |interp, v| settled_object(interp, true, v)) +} + +/// `Promise.allSettled` Reject Element Functions (section 25.6.4.2.3). +fn settled_rejected(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + element_settled(interp, args, |interp, v| settled_object(interp, false, v)) +} diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index b671f51e42..109493a03d 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -44,13 +44,16 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?; let function_proto = interp.intrinsics.function_proto; let has_instance = sym_method(interp, function_proto, has_instance, "[Symbol.hasInstance]", function_has_instance, 1, 0)?; - // The iterator prototypes and `%ArrayProto_values%` are set when the iterators are installed. + // The iterator and generator prototypes and `%ArrayProto_values%` are set when the iterators + // and generators are installed. interp.symbols.objects = Some(Es2015Objects { symbol_proto: proto, array_iterator_proto: proto, string_iterator_proto: proto, array_values: has_instance, has_instance, + generator_proto: proto, + generator_function_proto: function_proto, }); Ok(()) } diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index c009dddc9a..6a6867b270 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -407,6 +407,21 @@ fn boolean_prototype_converts_booleans() { throws("Object.getPrototypeOf(true).valueOf.call({})", "TypeError"); } +#[test] +fn the_boolean_constructor_converts_and_wraps() { + // Called as a function it gives ToBoolean of its argument (section 15.6.1). + truth("Boolean() === false && Boolean(0) === false && Boolean('') === false && Boolean(NaN) === false && Boolean(null) === false"); + truth("Boolean(1) === true && Boolean('false') === true && Boolean({}) === true && Boolean(new Boolean(false)) === true"); + truth("['', 'a', 0, 2].filter(Boolean).length === 2"); + // With new it makes a Boolean object (section 15.6.2), which is truthy whatever it holds. + truth("var b = new Boolean(0); typeof b === 'object' && b.valueOf() === false && !!b && b instanceof Boolean"); + assert_eq!(string("Object.prototype.toString.call(new Boolean(1)) + new Boolean('')"), "[object Boolean]false"); + // The constructor and Boolean.prototype are linked, and true and false look methods up there. + truth("Boolean.prototype === Object.getPrototypeOf(true) && Boolean.prototype.constructor === Boolean && true.constructor === Boolean"); + truth("Boolean.length === 1 && Object(false) instanceof Boolean"); + truth("!Object.getOwnPropertyDescriptor(this, 'Boolean').enumerable && !Object.getOwnPropertyDescriptor(Boolean, 'prototype').writable"); +} + #[test] fn array_methods_overwriting_elements_need_no_heap_for_new_ones() { // With the heap exactly at its limit, an array method's write over an existing element diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 2671959b17..5a44e6385a 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -246,6 +246,30 @@ pub(crate) enum Op { InitIndex, /// `object key function` → `object`: a getter (`true`) or a setter with a computed name. InitAccessorIndex(bool), + /// Ends a generator function's call once its parameters are initialized: the frame becomes a + /// new generator object, which the call returns. The first `next` goes on after it. + GeneratorStart, + /// `value` → `received mode`: suspends the generator, giving its caller `{ value, done: false }` + /// (or, when true, the value itself, an iterator result from `yield*`'s delegate). It goes on + /// when the generator is resumed, with the value it was resumed with and how (0 `next`, 1 + /// `throw`, 2 `return`). + Yield(bool), + /// `received mode` → `received`: goes on for `next`, throws the value for `throw`, and jumps + /// with it for `return`. + Resume(u32), + /// `value` → `iterator next`: GetIterator (ECMA-262 11th edition, section 7.4.1) for `yield*`, + /// which calls the iterator's methods itself. + DelegateIterator, + /// `iterator next received mode` → `iterator next mode method iterator received`, ready for + /// `Call(1)`: the delegate's `next`, `throw` or `return`. With `return` and no `return` method + /// it jumps with `iterator next received`; with `throw` and no `throw` method it closes the + /// iterator and throws a `TypeError` (section 14.4.14). + DelegateCall(u32), + /// `mode result` → `result` when the iterator result is not done; when it is, jumps with + /// `mode value`. A result that is not an object is a `TypeError`. + DelegateResult(u32), + /// `mode value` → `value`; for `return`, jumps with it. + DelegateDone(u32), } /// The names a block declares, entered with [`Op::PushBlock`]. @@ -354,6 +378,9 @@ pub(crate) struct Code { /// The code is a method's, a getter's or a setter's, read with [`crate::Options::es2015`]: /// its functions have no `prototype` and cannot be constructed (section 14.3.8). pub(crate) method: bool, + /// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]), + /// and it is not a constructor. + pub(crate) generator: bool, } /// What [`Op::SetFunctionNameKey`] puts before a computed name: `get ` and `set ` for accessors. @@ -476,6 +503,12 @@ fn effect(op: Op, finally_tables: &[Vec]) -> Result { Op::IterClose => e(1, 0), Op::IterCloseThrow => end(2), Op::InitIndex | Op::InitAccessorIndex(_) => e(3, 1), + Op::GeneratorStart => e(0, 0), + Op::Yield(_) => e(1, 2), + Op::Resume(t) | Op::DelegateDone(t) => Effect { pops: 2, next: Some(1), jumps: vec![(t, 1)] }, + Op::DelegateIterator => e(1, 2), + Op::DelegateCall(t) => Effect { pops: 2, next: Some(4), jumps: vec![(t, 1)] }, + Op::DelegateResult(t) => Effect { pops: 2, next: Some(1), jumps: vec![(t, 2)] }, }) } @@ -511,6 +544,7 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> { Op::PushBlock(i) => check(i, code.scopes.len(), "scope"), Op::TemplateObject(i) => check(i, code.templates.len(), "template"), Op::RegExp(i) => check(i, code.regexps.len(), "regular expression"), + Op::GeneratorStart | Op::Yield(_) if !code.generator => Err("a generator instruction outside a generator function".into()), _ => Ok(()), } } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 26cd0a71cd..f4314f2e5e 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -109,6 +109,8 @@ struct FnCompiler<'a> { /// The optional chains being compiled, innermost last: where a step that finds `undefined` /// or `null` jumps, and the stack depth the chain started at. optional: Vec<(Label, u32)>, + /// The code is a generator function's. + generator: bool, } /// The `var` names and function declarations a body hoists. @@ -157,6 +159,7 @@ impl<'a> FnCompiler<'a> { block_funcs: HashSet::new(), annex: HashSet::new(), optional: Vec::new(), + generator: false, } } @@ -281,12 +284,13 @@ impl<'a> FnCompiler<'a> { Stmt::Var(decls) => decls.iter().flat_map(|d| self.ast.bound_names(&d.target)).for_each(|n| add_var(&mut out, key_of(&n.name))), Stmt::Lexical(..) => {} Stmt::FunctionDecl(fid) => { - let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else { + let Some((name, generator)) = self.ast.function(*fid).and_then(|f| Some((f.name.as_ref()?, f.generator))) else { return internal("function declaration without a name"); }; let k = key_of(&name.name); if self.es2015 && nested { - if !self.strict { + // Annex B.3.3 gives plain function declarations only a var binding too. + if !self.strict && !generator { annex.push((k, scope, id)); } } else { @@ -1351,10 +1355,73 @@ impl<'a> FnCompiler<'a> { self.at(self.ast.expr_span(id).end); self.nullish_check()?; } + Expr::Yield { arg, delegate: false } => { + match arg { + Some(e) => self.expr(*e)?, + None => self.emit(Op::Undefined), + } + self.at(self.ast.expr_span(id).start); + self.emit(Op::Yield(false)); + self.resume_after_yield()?; + } + Expr::Yield { arg: Some(e), delegate: true } => self.yield_delegate(id, *e)?, + Expr::Yield { arg: None, delegate: true } => return internal("yield* without an operand"), } Ok(()) } + /// After a `Yield` that left `received mode`: goes on with the received value for `next`, + /// throws it for `throw`, and for `return` returns it through the `finally` blocks around. + fn resume_after_yield(&mut self) -> CResult<()> { + if !self.generator { + return internal("yield outside a generator function"); + } + let ret = self.new_label(); + let after = self.new_label(); + self.jump(Op::Resume, ret); + self.jump(Op::Jump, after); + self.bind(ret); + self.emit_exit(Exit::Return)?; + self.bind(after); + Ok(()) + } + + /// `yield* operand` (ECMA-262 11th edition, section 14.4.14): each `next`, `throw` and `return` + /// the generator is resumed with goes to the operand's iterator, each result it gives that is + /// not done is yielded as it is, and a done one gives the expression its value, or for a + /// `return` returns that value. + fn yield_delegate(&mut self, id: ExprId, operand: ExprId) -> CResult<()> { + if !self.generator { + return internal("yield outside a generator function"); + } + let d = self.depth; + self.expr(operand)?; + self.at(self.ast.expr_span(id).start); + self.emit(Op::DelegateIterator); + // The first step calls `next` with one argument, `undefined`: the spec starts with + // `received` as NormalCompletion(undefined) and calls `next` with « received.[[Value]] ». + self.emit(Op::Undefined); + self.push_number(0.0); + let (step, ret, done, end) = (self.new_label(), self.new_label(), self.new_label(), self.new_label()); + self.bind(step); + self.jump(Op::DelegateCall, ret); + self.emit(Op::Call(1)); + self.jump(Op::DelegateResult, done); + self.emit(Op::Yield(true)); + self.jump(Op::Jump, step); + self.bind(done); + self.depth = d + 4; + self.jump(Op::DelegateDone, ret); + self.emit(Op::PopUnder(2)); + self.jump(Op::Jump, end); + self.bind(ret); + self.depth = d + 3; + self.emit_exit(Exit::Return)?; + self.bind(end); + self.depth = d + 1; + Ok(()) + } + /// Pushes the nearest XML value in scope that holds the E4X name `name` of the expression /// `id`, then the name, as an assignment, update or `delete` uses them. fn xml_scope_ref(&mut self, id: ExprId, name: ExprId) -> CResult<()> { @@ -2075,7 +2142,11 @@ impl<'a> FnCompiler<'a> { | Op::JumpIfNullish { target: t, .. } | Op::ForInNext(t) | Op::IterStep(t) - | Op::XmlFilterNext(t), + | Op::XmlFilterNext(t) + | Op::Resume(t) + | Op::DelegateCall(t) + | Op::DelegateResult(t) + | Op::DelegateDone(t), ) => *t = target, _ => return internal("patching an instruction that is not a jump"), } @@ -2123,6 +2194,7 @@ impl<'a> FnCompiler<'a> { es2015: self.es2015, own_name: meta.own_name, method: meta.method, + generator: self.generator, }; code.max_stack = verify(&code).map_err(CompileFail::Internal)?; Ok(Rc::new(code)) @@ -2156,6 +2228,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, let Some(f) = ast.function(fid) else { return internal("function out of range") }; let mut c = FnCompiler::new(ast, source, CodeKind::Function, f.strict, recursion); c.es2015 = es2015; + c.generator = f.generator; c.at(f.span.start); c.enter()?; // A destructured parameter has a binding of its own under a name no script can write, which @@ -2207,6 +2280,12 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, } c.emit(Op::BodyEnv); } + if f.generator { + // The call has bound the arguments and run the default values; the body waits for + // the first `next` (ECMA-262 2015 section 14.4.11). + c.at(f.span.start); + c.emit(Op::GeneratorStart); + } c.stmts(&f.body)?; c.at(f.span.end.saturating_sub(1)); c.emit(Op::Undefined); diff --git a/crates/js/src/generator.rs b/crates/js/src/generator.rs new file mode 100644 index 0000000000..ccf3aee006 --- /dev/null +++ b/crates/js/src/generator.rs @@ -0,0 +1,414 @@ +//! Generator objects (ECMA-262 11th edition, , +//! sections 14.4 and 25.4), in a realm with [`crate::Options::es2015`]. +//! +//! A call to a generator function runs its parameters' initialization and stops at +//! [`Op::GeneratorStart`]: its frame, with the operands above the frame's base and the `finally` +//! blocks it is inside, moves into a new generator object, which the call returns. `next`, +//! `return` and `throw` push the frame back on the interpreter's frame stack and go on in the same +//! loop, so a generator driven from JavaScript uses no Rust stack, and each resumption takes a unit +//! of fuel and counts against the frame limit. `yield` moves the frame back into the object. A +//! suspended generator's frame is reachable only through its object, so the collector keeps it +//! while the object is reachable and frees it with the object. +//! +//! [`Op::GeneratorStart`]: crate::bytecode::Op::GeneratorStart + +use std::rc::Rc; + +use crate::LimitKind; +use crate::builtins::iterator::iter_result; +use crate::bytecode::Code; +use crate::heap::{Class, EnvId, OBJECT_BYTES, ObjId, Object, key}; +use crate::interp::{Abrupt, Frame, Interp, JsResult, Prepared, ThrowSite, internal}; +use crate::value::Value; + +/// How a generator is resumed: by `next`, `throw` or `return` (sections 25.4.1.3 and 25.4.1.4). +/// The code after a `yield` reads it as the number [`ResumeMode::number`] gives. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ResumeMode { + Next, + Throw, + Return, +} + +impl ResumeMode { + fn number(self) -> f64 { + match self { + ResumeMode::Next => 0.0, + ResumeMode::Throw => 1.0, + ResumeMode::Return => 2.0, + } + } + + fn of(v: &Value) -> JsResult { + match v { + Value::Number(n) if *n == 0.0 => Ok(ResumeMode::Next), + Value::Number(n) if *n == 1.0 => Ok(ResumeMode::Throw), + Value::Number(n) if *n == 2.0 => Ok(ResumeMode::Return), + _ => internal("a resumption mode that is not one"), + } + } +} + +/// The estimated bytes of a suspended generator's frame besides its operands. +const GENERATOR_BYTES: usize = 128; + +/// The estimated bytes of each operand and `finally` entry a suspended frame holds. +const SLOT_BYTES: usize = 16; + +/// A generator's frame while it is suspended: what [`Frame`] holds, with the operands above its +/// base and its `finally` entries, their stack slots counted from its base. +#[derive(Clone)] +pub(crate) struct SavedFrame { + pub(crate) code: Rc, + pc: usize, + pub(crate) env: EnvId, + pub(crate) var_env: EnvId, + env_depth: u32, + pub(crate) this: Value, + pub(crate) callee: Option, + pub(crate) completion: Value, + pub(crate) stack: Vec, + /// [`Interp::finally_sites`] entries. + pub(crate) sites: Vec<(ThrowSite, usize)>, + /// [`Interp::finally_marks`] entries. + pub(crate) marks: Vec<(ObjId, u32, usize)>, +} + +/// A generator's [[GeneratorState]] (section 25.4.3), with its frame while it is suspended. +#[derive(Clone)] +pub(crate) enum GenState { + SuspendedStart(SavedFrame), + SuspendedYield(SavedFrame), + Executing, + Completed, +} + +impl GenState { + /// The suspended frame, if the generator is suspended. + pub(crate) fn saved(&self) -> Option<&SavedFrame> { + match self { + GenState::SuspendedStart(s) | GenState::SuspendedYield(s) => Some(s), + GenState::Executing | GenState::Completed => None, + } + } +} + +/// The bytes a suspended frame adds to its generator object, which a collection counts. +pub(crate) fn saved_bytes(s: &SavedFrame) -> usize { + GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(s.stack.len().saturating_add(s.sites.len()).saturating_add(s.marks.len()))) +} + +/// A generator resumed by `next`, `return` or `throw`, ready to be pushed: the value it was +/// resumed with and how, unless it had not started. +pub(crate) struct Resumed { + generator: ObjId, + saved: SavedFrame, + received: Option<(Value, ResumeMode)>, +} + +impl Interp { + fn generator_state_mut(&mut self, g: ObjId) -> Option<&mut GenState> { + match self.heap.object_mut(g).map(|o| &mut o.class) { + Some(Class::Generator(s)) => Some(s), + _ => None, + } + } + + /// Marks the generator `g`, whose frame was popped without being saved, completed. + pub(crate) fn end_generator(&mut self, g: Option) { + if let Some(state) = g.and_then(|g| self.generator_state_mut(g)) + && let GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved) = std::mem::replace(state, GenState::Completed) + { + self.release_saved(&saved); + } + } + + /// Takes a saved frame that left its generator object off the heap's total. + fn release_saved(&mut self, saved: &SavedFrame) { + self.heap.bytes = self.heap.bytes.saturating_sub(saved_bytes(saved)); + } + + /// Gives a frame's caller `v`: the Rust call that pushed a boundary frame, or the frame below. + fn deliver(&mut self, boundary: bool, v: Value) -> JsResult> { + if boundary { + return Ok(Some(v)); + } + self.push(v)?; + Ok(None) + } + + /// Moves `frame`, just popped, with its operands and `finally` entries, into a [`SavedFrame`]. + fn save_frame(&mut self, frame: Frame) -> SavedFrame { + let base = frame.base; + let stack = self.stack.split_off(base.min(self.stack.len())); + let i = self.finally_sites.partition_point(|&(_, slot)| slot < base); + let sites = self.finally_sites.split_off(i).into_iter().map(|(site, slot)| (site, slot - base)).collect(); + let mut marks = Vec::new(); + self.finally_marks.retain(|&(id, mark, slot)| { + let below = slot < base; + if !below { + marks.push((id, mark, slot - base)); + } + below + }); + SavedFrame { + code: frame.code, + pc: frame.pc, + env: frame.env, + var_env: frame.var_env, + env_depth: frame.env_depth, + this: frame.this, + callee: frame.callee, + completion: frame.completion, + stack, + sites, + marks, + } + } + + /// [`Op::GeneratorStart`](crate::bytecode::Op::GeneratorStart): OrdinaryCreateFromConstructor + /// of the function's `prototype` (section 14.4.11), or %GeneratorPrototype% when that is not an + /// object, holding the frame, which the call returns. + pub(crate) fn op_generator_start(&mut self) -> JsResult> { + let Some(callee) = self.frame()?.callee else { return internal("a generator's body without its function") }; + // A realm made without `Options::es2015` that reads the syntax later has no generator + // built-ins. + let Some(fallback) = self.symbols.objects.map(|o| o.generator_proto) else { + return Err(self.type_error("generators need the ECMAScript 2015 built-ins, and this realm was made without them")); + }; + let proto = match self.get_from(callee, &key("prototype"), &Value::Object(callee))? { + Value::Object(p) => p, + _ => fallback, + }; + self.rooted(&[Value::Object(proto)], |i| i.reserve_heap(OBJECT_BYTES + GENERATOR_BYTES))?; + let Some(frame) = self.frames.pop() else { return internal("no frame") }; + let boundary = frame.boundary; + let saved = self.save_frame(frame); + let bytes = saved_bytes(&saved); + let g = self.heap.alloc_object(Object::new(Class::Generator(Box::new(GenState::SuspendedStart(saved))), Some(proto))); + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + self.deliver(boundary, Value::Object(g)) + } + + /// [`Op::Yield`](crate::bytecode::Op::Yield): GeneratorYield (section 25.4.3.7). The frame, + /// already past the instruction, goes into the generator object, and its caller gets the + /// iterator result. + pub(crate) fn op_yield(&mut self, raw: bool) -> JsResult> { + let Some(g) = self.frame()?.generator else { return internal("yield outside a generator's body") }; + if !raw { + let v = self.peek(0)?; + let result = iter_result(self, v, false)?; + self.replace(1, result)?; + } + // What `save_frame` keeps: the frame's operands without the result, popped below, and its + // own `finally` entries, not those of the frames under it. + let base = self.frame()?.base; + let sites = self.finally_sites.len().saturating_sub(self.finally_sites.partition_point(|&(_, slot)| slot < base)); + let marks = self.finally_marks.iter().filter(|&&(_, _, slot)| slot >= base).count(); + let held = self.stack.len().saturating_sub(base.saturating_add(1)).saturating_add(sites).saturating_add(marks); + let bytes = GENERATOR_BYTES.saturating_add(SLOT_BYTES.saturating_mul(held)); + self.reserve_heap(bytes)?; + let result = self.pop()?; + let Some(frame) = self.frames.pop() else { return internal("no frame") }; + let boundary = frame.boundary; + let saved = self.save_frame(frame); + self.heap.bytes = self.heap.bytes.saturating_add(saved_bytes(&saved)); + let Some(state) = self.generator_state_mut(g) else { return internal("a generator's frame without its object") }; + *state = GenState::SuspendedYield(saved); + self.deliver(boundary, result) + } + + /// GeneratorResume and GeneratorResumeAbrupt (sections 25.4.3.3 and 25.4.3.4) for `next`, + /// `return` and `throw` called on `this` with `sent`: the result when the generator does not + /// run, or its frame to push. + pub(crate) fn prepare_resume(&mut self, this: Value, mode: ResumeMode, sent: Value) -> JsResult { + // Whether it has started, or `None` when it is running or completed. + let (g, started) = match this { + Value::Object(g) => match self.heap.object(g).map(|o| &o.class) { + Some(Class::Generator(s)) => match **s { + GenState::SuspendedStart(_) => (g, Some(false)), + GenState::SuspendedYield(_) => (g, Some(true)), + GenState::Executing => return Err(self.type_error("the generator is already running")), + GenState::Completed => (g, None), + }, + _ => return Err(self.type_error("the value is not a generator object")), + }, + _ => return Err(self.type_error("the value is not a generator object")), + }; + let Some(started) = started else { + return match mode { + ResumeMode::Next => Ok(Prepared::Done(iter_result(self, Value::Undefined, true)?)), + ResumeMode::Return => Ok(Prepared::Done(iter_result(self, sent, true)?)), + ResumeMode::Throw => Err(Abrupt::Throw(sent)), + }; + }; + if !started && mode != ResumeMode::Next { + self.end_generator(Some(g)); + return match mode { + ResumeMode::Throw => Err(Abrupt::Throw(sent)), + _ => Ok(Prepared::Done(iter_result(self, sent, true)?)), + }; + } + if self.frames.len() >= self.limits.frames { + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let Some(state) = self.generator_state_mut(g) else { return internal("a generator object without its state") }; + let (GenState::SuspendedStart(saved) | GenState::SuspendedYield(saved)) = std::mem::replace(state, GenState::Executing) else { + return internal("a suspended generator without its frame"); + }; + self.release_saved(&saved); + let received = started.then_some((sent, mode)); + Ok(Prepared::Resume(Box::new(Resumed { generator: g, saved, received }))) + } + + /// Pushes a resumed generator's frame, with the value it was resumed with and how on top of + /// its operands when it had yielded. + pub(crate) fn enter_resumed(&mut self, r: Resumed, boundary: bool) -> JsResult<()> { + let Resumed { generator, saved, received } = r; + if self.frames.len() >= self.limits.frames { + let bytes = saved_bytes(&saved); + if let Some(state) = self.generator_state_mut(generator) { + *state = if received.is_some() { GenState::SuspendedYield(saved) } else { GenState::SuspendedStart(saved) }; + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + } + return Err(Abrupt::Limit(LimitKind::Frames)); + } + let base = self.stack.len(); + self.drop_left_finally_sites(base); + let SavedFrame { code, pc, env, var_env, env_depth, this, callee, completion, stack, sites, marks } = saved; + self.stack.extend(stack); + if let Some((value, mode)) = received { + self.stack.push(value); + self.stack.push(Value::Number(mode.number())); + } + self.finally_sites.extend(sites.into_iter().map(|(site, slot)| (site, slot + base))); + self.finally_marks.extend(marks.into_iter().map(|(id, mark, slot)| (id, mark, slot + base))); + self.frames.push(Frame { + code, + pc, + base, + env, + var_env, + env_depth, + this, + callee, + construct: None, + completion, + boundary, + generator: Some(generator), + }); + Ok(()) + } + + /// [`Op::Resume`](crate::bytecode::Op::Resume): `received mode` → `received`. + pub(crate) fn op_resume(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(0)?)?; + let received = self.peek(1)?; + self.pop()?; + self.pop()?; + match mode { + ResumeMode::Next => self.push(received), + ResumeMode::Throw => { + self.thrown_mark = None; + Err(Abrupt::Throw(received)) + } + ResumeMode::Return => { + self.push(received)?; + self.jump_to(target) + } + } + } + + /// GetMethod (section 7.3.10): the property `name` of `v`, `None` when it is `undefined` or + /// `null`. + fn get_method(&mut self, v: &Value, name: &str) -> JsResult> { + let f = self.get_value(v, &key(name))?; + if f.is_nullish() { + return Ok(None); + } + if !self.is_callable(&f) { + return Err(self.type_error(&format!("the iterator's {name} is not a function"))); + } + Ok(Some(f)) + } + + /// [`Op::DelegateIterator`](crate::bytecode::Op::DelegateIterator): `value` → `iterator next`. + pub(crate) fn op_delegate_iterator(&mut self) -> JsResult<()> { + let v = self.peek(0)?; + let Some(sym) = self.well_known(|w| &w.iterator) else { return internal("no Symbol.iterator in this realm") }; + let method = self.get_value_sym(&v, &sym)?; + if !self.is_callable(&method) { + return Err(self.type_error("the value is not iterable")); + } + let iterator = self.call(&method, &v, &[])?; + if !matches!(iterator, Value::Object(_)) { + return Err(self.type_error("the iterator is not an object")); + } + self.replace(1, iterator.clone())?; + let next = self.get_value(&iterator, &key("next"))?; + self.push(next) + } + + /// [`Op::DelegateCall`](crate::bytecode::Op::DelegateCall): the method of `yield*`'s iterator + /// that the generator's resumption calls (section 14.4.14, step 7). + pub(crate) fn op_delegate_call(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(0)?)?; + let iterator = self.peek(3)?; + let method = match mode { + ResumeMode::Next => Some(self.peek(2)?), + ResumeMode::Throw => self.get_method(&iterator, "throw")?, + ResumeMode::Return => self.get_method(&iterator, "return")?, + }; + let received = self.peek(1)?; + match (method, mode) { + (Some(m), _) => { + self.replace(2, Value::Number(mode.number()))?; + self.push(m)?; + self.push(iterator)?; + self.push(received) + } + (None, ResumeMode::Return) => { + self.replace(2, received)?; + self.jump_to(target) + } + (None, _) => { + // The iterator has no `throw`: it is closed, and the protocol violation is a + // `TypeError` (step 7.b.iii). + if let Some(close) = self.get_method(&iterator, "return")? { + let result = self.call(&close, &iterator, &[])?; + if !matches!(result, Value::Object(_)) { + return Err(self.type_error("the iterator result is not an object")); + } + } + Err(self.type_error("the iterator has no throw method")) + } + } + } + + /// [`Op::DelegateResult`](crate::bytecode::Op::DelegateResult): `mode result` → `result`, or + /// when it is done, a jump with `mode value`. + pub(crate) fn op_delegate_result(&mut self, target: u32) -> JsResult<()> { + let result = self.peek(0)?; + if !matches!(result, Value::Object(_)) { + return Err(self.type_error("the iterator result is not an object")); + } + if self.get_value(&result, &key("done"))?.truthy() { + let value = self.get_value(&result, &key("value"))?; + self.replace(1, value)?; + return self.jump_to(target); + } + self.replace(2, result) + } + + /// [`Op::DelegateDone`](crate::bytecode::Op::DelegateDone): `mode value` → `value`, a jump for + /// `return`. + pub(crate) fn op_delegate_done(&mut self, target: u32) -> JsResult<()> { + let mode = ResumeMode::of(&self.peek(1)?)?; + let value = self.peek(0)?; + self.replace(2, value)?; + if mode == ResumeMode::Return { + return self.jump_to(target); + } + Ok(()) + } +} diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs new file mode 100644 index 0000000000..551fb4e5e6 --- /dev/null +++ b/crates/js/src/generator_tests.rs @@ -0,0 +1,382 @@ +//! Generator functions, `yield`, `yield*` and the generator objects, in a realm with +//! [`Options::es2015`]. + +use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; + +fn es2015(limits: Limits) -> Realm { + Realm::with_options(Options { es2015: true, ..Options::default() }, limits) +} + +fn run(src: &str) -> JsValue { + match es2015(Limits::default()).run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn truth(src: &str) { + assert_eq!(run(src), JsValue::Bool(true), "{src}"); +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// The run throws an error whose message starts with `name`. +fn throws(src: &str, name: &str) { + match es2015(Limits::default()).run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } +} + +/// The script does not parse in a realm with `options`. +fn syntax_with(src: &str, options: Options) { + match Realm::with_options(options, Limits::default()).run(src) { + Err(RunError { kind: RunErrorKind::Syntax, .. }) => {} + other => panic!("{src}: {other:?}"), + } +} + +fn syntax(src: &str) { + syntax_with(src, Options { es2015: true, ..Options::default() }); +} + +#[test] +fn promise_jobs_resume_generator_callbacks() { + let mut realm = es2015(Limits::default()); + realm + .run( + "var log = []; var it = (function* () { log.push('start'); var value = yield 7; \ + log.push('resume:' + value); return 9; })(); \ + Promise.resolve().then(it.next.bind(it)).then(function (result) { \ + log.push(result.value + ':' + result.done); return it.next(5); \ + }).then(function (result) { log.push(result.value + ':' + result.done); });", + ) + .unwrap(); + assert_eq!(realm.run("log.join(',')").unwrap(), JsValue::String("start,7:false,resume:5,9:true".into())); +} + +#[test] +fn promise_static_methods_reject_generator_constructors() { + truth( + "var g = function* () {}, count = 0; [g, g.bind(null)].forEach(function (C) { \ + try { Promise.resolve.call(C, 1); } catch (error) { if (error instanceof TypeError) count++; } \ + try { Promise.reject.call(C, 1).catch(function () {}); } \ + catch (error) { if (error instanceof TypeError) count++; } }); count === 4", + ); +} + +#[test] +fn a_generator_runs_its_body_one_yield_at_a_time() { + assert_eq!( + string( + "var log = []; function* g(a, b) { log.push('start'); var x = yield a; log.push(x); yield b + x; return 'end'; } \ + var it = g(1, 2); log.push('made'); var r = [it.next('ignored'), it.next(10), it.next(20), it.next()]; \ + log.join() + ' ' + r.map(function (o) { return o.value + ':' + o.done; }).join()" + ), + "made,start,10 1:false,12:false,end:true,undefined:true" + ); + // The parameters' default values run at the call, the body at the first `next`. + assert_eq!(string("var log = []; function* g(a = log.push('d')) { log.push('b'); } var it = g(); log.push('c'); it.next(); log.join()"), "d,c,b"); + truth("function* g() { yield this; } var o = { g: g }; o.g().next().value === o"); + truth("function* g() { return arguments.length; } g(1, 2, 3).next().value === 3"); + truth("var it = (function* () {})(); var r = it.next(); r.value === undefined && r.done === true"); + truth("function* g() { yield 1; } var a = g(), b = g(); a.next(); a.next().done && !b.next().done"); +} + +#[test] +fn yield_takes_an_operand_only_on_the_same_line() { + assert_eq!(string("function* g() { yield\n1; } var it = g(); String(it.next().value) + ',' + it.next().done"), "undefined,true"); + truth("function* g() { var x = yield; return x; } var it = g(); it.next(); it.next(7).value === 7"); + truth("function* g() { yield /a/g; } g().next().value instanceof RegExp"); + truth("function* g() { yield yield 1; } var it = g(); it.next().value === 1 && it.next(2).value === 2"); + truth("function* g() { var a = [yield 1, yield 2]; return a.join(); } var it = g(); it.next(); it.next('x'); it.next('y').value === 'x,y'"); +} + +#[test] +fn return_runs_the_finally_blocks_around_the_yield() { + truth( + "var log = []; function* g() { try { yield 1; yield 2; } finally { log.push('f'); } } \ + var it = g(); it.next(); var r = it.return(9); r.value === 9 && r.done === true && log.join() === 'f' && it.next().done", + ); + // A `finally` block that yields suspends the return, which ends at the next resumption. + assert_eq!( + string( + "function* g() { try { yield 1; } finally { yield 'cleanup'; } } var it = g(); it.next(); \ + var a = it.return(5), b = it.next(), c = it.next(); [a.value, a.done, b.value, b.done, c.done].join()" + ), + "cleanup,false,5,true,true" + ); + truth("function* g() { try { yield 1; } finally { return 'override'; } } var it = g(); it.next(); it.return(5).value === 'override'"); + // Before the body starts, and after it ends, `return` only completes the generator. + truth("var ran = false; function* g() { ran = true; } var it = g(); var r = it.return(3); r.value === 3 && r.done && !ran && it.next().done"); + truth("function* g() {} var it = g(); it.next(); var r = it.return(4); r.value === 4 && r.done"); +} + +#[test] +fn throw_goes_into_a_suspended_generator() { + truth("function* g() { try { yield 1; } catch (e) { yield 'caught ' + e; } } var it = g(); it.next(); it.throw('x').value === 'caught x'"); + truth( + "function* g() { yield 1; yield 2; } var it = g(); it.next(); var e; try { it.throw(new RangeError('r')); } catch (x) { e = x; } \ + e instanceof RangeError && it.next().done", + ); + // A generator that has not started is completed by `throw`, which its body never sees. + truth( + "var ran = false; function* g() { ran = true; } var it = g(); var e; try { it.throw(1); } catch (x) { e = x; } e === 1 && !ran && it.next().done", + ); + throws("function* g() {} var it = g(); it.next(); it.throw(new TypeError('after the end'));", "TypeError: after the end"); +} + +#[test] +fn resuming_a_running_generator_is_a_type_error() { + truth( + "var it; function* g() { try { it.next(); } catch (e) { yield e instanceof TypeError; } } it = g(); \ + it.next().value === true", + ); + truth("var it; function* g() { it.next(); } it = g(); var e; try { it.next(); } catch (x) { e = x; } e instanceof TypeError && it.next().done"); + throws("var g = function* () {}; g.prototype.next.call({});", "TypeError"); + throws("(function* () {}).prototype.next.call(1);", "TypeError"); +} + +#[test] +fn yield_star_delegates_next_throw_and_return() { + truth( + "function* g() { yield* [1, 2]; yield* 'ab'; } var r = []; var it = g(), s; while (!(s = it.next()).done) r.push(s.value); r.join() === '1,2,a,b'", + ); + truth( + "function* inner() { yield 1; return 'r'; } function* outer() { var v = yield* inner(); yield v; } var it = outer(); it.next().value === 1 && it.next().value === 'r'", + ); + // The values `next` sends go to the delegate. + truth( + "function* inner() { var x = yield 1; yield x * 2; } function* outer() { yield* inner(); } var it = outer(); it.next(); it.next(21).value === 42", + ); + truth( + "var log = []; function* inner() { try { yield 1; } finally { log.push('inner'); } } function* outer() { try { yield* inner(); } finally { log.push('outer'); } } \ + var it = outer(); it.next(); var r = it.return(7); r.value === 7 && r.done && log.join() === 'inner,outer'", + ); + truth( + "function* inner() { try { yield 1; } catch (e) { yield 'in ' + e; } } function* outer() { yield* inner(); } var it = outer(); it.next(); it.throw('t').value === 'in t'", + ); + // The delegate's own results are passed on as they are. + truth( + "var r = { done: false, value: 1, extra: 2 }; var o = {}; o[Symbol.iterator] = function () { return { next: function () { return r; } }; }; function* g() { yield* o; } g().next() === r", + ); + // A delegate without `throw` is closed, and the generator gets a TypeError. + truth( + "var closed = false; var o = {}; o[Symbol.iterator] = function () { return { next: function () { return { done: false }; }, return: function () { closed = true; return {}; } }; }; \ + function* g() { yield* o; } var it = g(); it.next(); var e; try { it.throw(1); } catch (x) { e = x; } e instanceof TypeError && closed", + ); + throws("function* g() { yield* 5; } g().next();", "TypeError"); + throws( + "var o = {}; o[Symbol.iterator] = function () { return { next: function () { return 1; } }; }; function* g() { yield* o; } g().next();", + "TypeError", + ); +} + +#[test] +fn generator_methods_and_the_generator_objects() { + truth("var o = { *g(a) { yield this === o && a; } }; o.g(5).next().value === 5"); + truth("var o = { *'s'() { yield 1; }, *2() { yield 2; } }; o.s().next().value + o[2]().next().value === 3"); + throws("function* g() {} new g();", "TypeError"); + throws("var o = { *m() {} }; new o.m();", "TypeError"); + // A generator method has a `prototype` that its generator objects inherit from, unlike other + // methods, and takes a computed name and the method's `name`. + truth("var o = { *m() {} }; var it = o.m(); Object.getPrototypeOf(it) === o.m.prototype && !o.m.prototype.hasOwnProperty('constructor')"); + truth("var k = 'c'; var o = { *[k + 'd']() { yield 4; } }; o.cd().next().value === 4 && o.cd.name === 'cd'"); + truth("function* g() {} var GP = Object.getPrototypeOf(g); GP === Object.getPrototypeOf(function* () {}) && GP !== Function.prototype"); + truth("function* g() {} Object.getPrototypeOf(g.prototype) === Object.getPrototypeOf(g).prototype && !g.prototype.hasOwnProperty('constructor')"); + truth("function* g() {} var it = g(); it[Symbol.iterator]() === it && Object.prototype.toString.call(it) === '[object Generator]'"); + truth("function* g() {} Object.prototype.toString.call(g) === '[object GeneratorFunction]' && g instanceof Function && typeof g === 'function'"); + // %GeneratorFunction.prototype% is an ordinary object, not a function (section 25.2.3). + truth("var GP = Object.getPrototypeOf(function* () {}); typeof GP === 'object' && Object.getPrototypeOf(GP) === Function.prototype"); + throws("Object.getPrototypeOf(function* () {})();", "TypeError"); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; var f = GF('a', 'yield a; yield a * 2;'); var it = f(3); it.next().value + it.next().value === 9", + ); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; Object.getPrototypeOf(GF) === Function && GF.prototype === Object.getPrototypeOf(function* () {})", + ); + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor; typeof this.GeneratorFunction === 'undefined' && new GF('yield 1')().next().value === 1", + ); + truth("function* g() { yield 1 } String(g) === 'function* g() { yield 1 }'"); + // A generator function's own `prototype` is used when it is an object. + truth("function* g() {} var p = { mark: 1 }; g.prototype = p; Object.getPrototypeOf(g()) === p"); + truth("function* g() {} g.prototype = 1; Object.getPrototypeOf(g()) === Object.getPrototypeOf(function* () {}).prototype"); +} + +#[test] +fn a_bound_generator_function_inherits_from_the_targets_prototype() { + truth("function* g() {} var b = g.bind(null); Object.getPrototypeOf(b) === Object.getPrototypeOf(g) && b.constructor !== Function"); + truth("function* g(a) { yield a; } g.bind(null, 3)().next().value === 3"); + truth("function f() {} Object.getPrototypeOf(f.bind(null)) === Function.prototype"); +} + +#[test] +fn yield_is_an_identifier_outside_generators_in_sloppy_code() { + truth("var yield = 1; yield + 1 === 2"); + truth("function f(yield) { return yield; } f(3) === 3"); + truth("function* g() { function f() { var yield = 4; return yield; } yield f(); } g().next().value === 4"); + truth("function* g() { var o = { yield: 5 }; yield o.yield; } g().next().value === 5"); + truth("function* yield() { yield 6; } yield().next().value === 6"); + syntax("'use strict'; var yield = 1;"); +} + +#[test] +fn bad_generators_are_syntax_errors() { + for src in [ + "function* g() { var yield; }", + "function* g(yield) {}", + "function* g(a = yield) {}", + "function* g() { function* h(a = yield 1) {} }", + "var f = function* yield() {};", + "function* g() { (yield) => 1; }", + "function* g() { yield = 1; }", + "function* g() { yi\\u0065ld 1; }", + "function* g() { yield\n* 1; }", + "function* g() { yield: 1; }", + "if (true) function* g() {}", + "L: function* g() {}", + "{ function* g() {} function* g() {} }", + "function* g() { yield* ; }", + "var o = { *m(a, a) {} };", + "function* g() { (a = yield) => 1; }", + ] { + syntax(src); + } + // A `yield` in the body of a function in a generator's parameters belongs to that function. + truth("function* g(a = function* () { yield 1; }) { yield* a(); } g().next().value === 1"); + truth("function* g(a = function* () { yield 2; }, b = (c = function* () { yield 3; }) => c) { yield* b()(); } g().next().value === 3"); +} + +#[test] +fn realms_without_es2015_have_no_generators() { + let es5 = Options::default(); + let extendscript = Options { e4x: true, preprocessor_lines: true, ..Options::default() }; + for options in [es5, extendscript] { + for src in ["function* g() {}", "var g = function* () {};", "var o = { *m() {} };"] { + syntax_with(src, options.clone()); + } + let mut realm = Realm::with_options(options, Limits::default()); + assert_eq!(realm.run("function f() { var yield = 2; return yield; } f()"), Ok(JsValue::Number(2.0))); + // Reading the syntax later does not add the built-ins, so a call is a TypeError. + realm.set_es2015(true); + match realm.run("function* g() { yield 1; } g();") { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{message}"), + other => panic!("{other:?}"), + } + } +} + +#[test] +fn a_suspended_generator_keeps_its_frame_across_a_collection() { + let mut realm = es2015(Limits::default()); + let setup = "function* g() { var local = { v: 'left' }; var r = [{ w: 'held' }, yield 1]; yield local.v + r[0].w + r[1]; } \ + var it = g(); it.next(); it.next('!').value"; + assert_eq!(realm.run(setup), Ok(JsValue::String("leftheld!".into()))); + // The operands on the stack at the `yield` (the array being built) survive a collection. + assert_eq!(realm.run("var it3 = g(); it3.next(); 'ok'"), Ok(JsValue::String("ok".into()))); + realm.collect_garbage(); + assert_eq!(realm.run("it3.next('#').value"), Ok(JsValue::String("leftheld#".into()))); +} + +#[test] +fn a_frame_taken_out_of_its_generator_leaves_the_heap_total() { + let mut realm = es2015(Limits::default()); + // At the `yield`, the 500 arguments before it are operands in the saved frame. + let args = vec!["0"; 500].join(", "); + let setup = format!("function f() {{}} function* g() {{ while (true) f({args}, yield 1); }} var it = g(); it.next(); 0"); + assert_eq!(realm.run(&setup), Ok(JsValue::Number(0.0))); + let mut gaps = Vec::new(); + for resumes in [10, 210] { + realm.collect_garbage(); + assert_eq!(realm.run(&format!("for (var i = 0; i < {resumes}; i++) it.next(); 0")), Ok(JsValue::Number(0.0))); + let counted = realm.interp().heap.bytes; + gaps.push(counted.saturating_sub(realm.collect_garbage())); + } + // 200 more resumptions leave far less than one saved frame's worth each. + assert!(gaps[1] < gaps[0] + 200 * 1024, "{gaps:?}"); +} + +#[test] +fn an_unreachable_suspended_generator_is_freed() { + let mut realm = es2015(Limits::default()); + let setup = "function* g() { var big = []; for (var i = 0; i < 20000; i++) big.push({ i: i }); yield big.length; } var it = g(); it.next().value"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(20000.0))); + let held = realm.collect_garbage(); + assert_eq!(realm.run("it = null; 0"), Ok(JsValue::Number(0.0))); + let freed = realm.collect_garbage(); + assert!(freed + 1_000_000 < held, "held {held}, after {freed}"); +} + +/// The smallest heap limit, to within 256 bytes, under which `script` runs after `setup`. +fn smallest_heap_limit(setup: &str, script: &str) -> usize { + let fits = |limit: usize| { + let mut realm = es2015(Limits::default()); + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + realm.collect_garbage(); + realm.set_limits(Limits { heap_bytes: limit, ..Limits::default() }); + realm.run(script).is_ok() + }; + let (mut low, mut high) = (0, 64 << 20); + assert!(fits(high), "{script}"); + while high - low > 256 { + let mid = low + (high - low) / 2; + if fits(mid) { + high = mid; + } else { + low = mid; + } + } + high +} + +#[test] +fn a_yield_reserves_only_what_its_frame_keeps() { + // At the `yield` in `inside`, the 1,001 frames under the generator's are in `finally` blocks + // that a throw entered. Their entries stay with those frames, so the yield needs no more room + // than the one in `before`, which comes before those frames are pushed. + let setup = "function* g() { yield 1; } var it = g(); 0"; + let inside = "function f(n) { try { throw 0; } finally { if (n) f(n - 1); else it.next(); } } try { f(1000); } catch (e) {} 0"; + let before = "it.next(); function f(n) { try { throw 0; } finally { if (n) f(n - 1); } } try { f(1000); } catch (e) {} 0"; + let (inside, before) = (smallest_heap_limit(setup, inside), smallest_heap_limit(setup, before)); + assert!(inside < before + 4096, "inside {inside}, before {before}"); +} + +#[test] +fn generators_stay_within_the_limits() { + let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); + match realm.run("function* g() { while (true) yield 1; } var it = g(); while (true) it.next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + // Each resumption takes fuel even when the generator has completed: 1,000 calls of its `next` + // take at least 1,000 more than the same calls of a native method that takes none. + let mut realm = es2015(Limits::default()); + let setup = "var it = (function* () {})(); it.next(); var control = { next: Object.prototype.valueOf }; 0"; + assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0))); + let mut used = Vec::new(); + for callee in ["control", "it"] { + assert_eq!(realm.run(&format!("for (var i = 0; i < 1000; i++) {callee}.next(); 0")), Ok(JsValue::Number(0.0))); + used.push(Limits::default().fuel - realm.fuel_left()); + } + assert!(used[1] >= used[0] + 1000, "{used:?}"); + // A deep `yield*` chain stops at the frame limit, and the realm can run again. + let mut realm = es2015(Limits { frames: 200, ..Limits::default() }); + match realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(1000).next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Frames), .. }) => {} + other => panic!("{other:?}"), + } + assert_eq!(realm.run("function* d(n) { if (n) yield* d(n - 1); else yield 1; } d(20).next().value"), Ok(JsValue::Number(1.0))); + // A generator whose body was running when a limit ended the run cannot be resumed. + let mut realm = es2015(Limits { fuel: 20_000, ..Limits::default() }); + match realm.run("var it = (function* () { while (true) {} })(); it.next();") { + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {} + other => panic!("{other:?}"), + } + assert_eq!(realm.run("var r = it.next(); r.done && r.value === undefined"), Ok(JsValue::Bool(true))); +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index af98f259df..1a58fa1d28 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -181,6 +181,8 @@ pub(crate) enum NativeKind { Apply, /// The global `eval`: a call to it by that name is a direct eval. Eval, + /// `%GeneratorPrototype%`'s `next`, `return` or `throw`. + Resume(crate::generator::ResumeMode), } /// What a function object runs. `Bound` is a function made by `Function.prototype.bind` (section @@ -245,6 +247,8 @@ pub(crate) enum Class { /// The Iterator Record of a `for-of` loop, an array pattern or a spread in progress, on the /// operand stack only. IterRecord(Box), + /// A generator object and its state (ECMA-262 11th edition, section 25.4). + Generator(Box), ForIn(Box), /// The `Math` object (section 15.8). Math, @@ -264,8 +268,14 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// An object of a class a host defined ([`crate::host_classes`]). + Host(crate::host_classes::HostObj), /// A `UnitValue` object and its measurement ([`crate::unit_value`]). UnitValue(Box), + /// A promise (ECMA-262 11th edition, section 25.6) and its state. + Promise(Box), + /// The state that the functions a promise operation makes share; scripts never see it. + PromiseRecord(Box), } /// What an XML value is. @@ -329,10 +339,17 @@ impl Class { Class::XmlList(_) => "XMLList", Class::Namespace(_) => "Namespace", Class::QName { .. } => "QName", - Class::XmlFilter(_) => "Object", + Class::XmlFilter(_) | Class::PromiseRecord(_) => "Object", + Class::Promise(_) => "Promise", Class::Math => "Math", Class::Json => "JSON", - Class::Ordinary | Class::ForIn(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object", + Class::Ordinary + | Class::ForIn(_) + | Class::Host(_) + | Class::Symbol(_) + | Class::Iterator(_) + | Class::IterRecord(_) + | Class::Generator(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", @@ -752,6 +769,24 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u crate::builtins::iterator::IterState::Array { target, .. } => work.extend(target.iter().map(|o| o.0)), crate::builtins::iterator::IterState::String { text, .. } => text.iter().for_each(|s| strings.add(s)), }, + Class::Generator(state) => { + if let Some(saved) = state.saved() { + work.push(saved.env.0); + work.push(saved.var_env.0); + work.extend(saved.callee.iter().map(|o| o.0)); + work.extend(saved.marks.iter().map(|&(id, _, _)| id.0)); + mark_value(&saved.this, work, strings); + mark_value(&saved.completion, work, strings); + for v in &saved.stack { + mark_value(v, work, strings); + } + mark_code(&saved.code, strings); + for ((code, _), _) in &saved.sites { + mark_code(code, strings); + } + extra = crate::generator::saved_bytes(saved); + } + } Class::Xml(node) => { work.extend(node.parent.iter().chain(&node.attrs).chain(&node.children).map(|o| o.0)); strings.add(&node.value); @@ -777,6 +812,21 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } Class::UnitValue(_) => extra = UNIT_VALUE_BYTES, + Class::Promise(p) => { + for v in p.values() { + mark_value(&v, work, strings); + } + if let Some((code, _)) = &p.site { + mark_code(code, strings); + } + extra = p.bytes(); + } + Class::PromiseRecord(r) => { + for v in r.values() { + mark_value(&v, work, strings); + } + extra = crate::builtins::promise::RECORD_BYTES; + } _ => {} } OBJECT_BYTES + PROP_BYTES * (o.props.len() + syms) + extra diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 1f0bcdd0c0..276895e782 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -30,6 +30,7 @@ pub enum Data { } /// How much one crossing may carry. +/// Host receivers, their handles and explicit arguments share these limits. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct DataLimits { /// How deeply arrays and objects may nest. @@ -113,6 +114,10 @@ pub(crate) enum ArgRead { Each(Rc<[Arg]>), /// None: the function is given the [`CallSite`] of the code that calls it, as three numbers. Site, + /// A member of a host class ([`crate::host_classes`]): `this` first, then each argument as + /// [`Data`], objects of host classes in them as [`crate::host_ref`] gives them; the objects of + /// host classes in the result are made from theirs. + Hosted, } /// A member of an object the host adds to the global environment. @@ -188,6 +193,9 @@ struct Reading { ancestors: Vec, path: Vec, function: Rc, + /// Objects of host classes are read as [`crate::host_ref`] gives them, and a plain object + /// that has [`crate::HOST_REF_KEY`] is refused. + hosted: bool, } impl Reading { @@ -258,6 +266,8 @@ impl Interp { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } let shape = match &self.object(id)?.class { + Class::Host(_) if r.hosted => return self.read_host_ref(id, r), + Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), Class::Array { length, .. } => Shape::Array(*length), Class::Ordinary => { let o = self.object(id)?; @@ -288,6 +298,14 @@ impl Interp { out } + fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult { + let Some((name, len)) = self.host_ref_size(id)? else { return Err(Abrupt::Internal("host object without a class".into())) }; + self.charge_entries(r, len.saturating_add(2))?; + let key = crate::HOST_REF_KEY.len().saturating_mul(3).saturating_add(8); + self.charge_reading(r, key.saturating_add(name.saturating_mul(3)).saturating_add(2))?; + self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())) + } + fn read_array(&mut self, id: ObjId, length: u32, r: &mut Reading) -> JsResult { self.charge_entries(r, length as usize)?; let mut items = Vec::with_capacity(length as usize); @@ -313,6 +331,9 @@ impl Interp { self.use_fuel()?; self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; let name = String::from_utf16_lossy(&k); + if r.hosted && name == crate::HOST_REF_KEY { + return Err(self.data_error(r, ErrorType::Type, "is not plain data")); + } r.path.push(Step::Name(k)); let item = match prop { // A property holding `undefined` reads as one left out. @@ -348,6 +369,9 @@ impl Interp { Data::Array(items) => { self.write_container(items.into_iter().enumerate().map(|(i, d)| (Slot::Index(i), d)).collect(), true, depth, frozen)? } + Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, _)] if k == crate::HOST_REF_KEY) => { + self.write_host_ref(&Data::Object(items))? + } Data::Object(items) => self.write_container(items.into_iter().map(|(k, d)| (Slot::Name(k), d)).collect(), false, depth, frozen)?, }) } @@ -387,20 +411,24 @@ impl Interp { /// Calls host function `f`: reads its arguments as `how` says, runs it, and gives its result to /// the script. - pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult { + pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, this: &Value, args: &[Value], how: &ArgRead) -> JsResult { let data = match how { ArgRead::Site => site_data(self.call_site()), - _ => self.read_args(name, args, how)?, + ArgRead::Hosted => self.read_args(name, Some(this), args, how)?, + _ => self.read_args(name, None, args, how)?, }; - // Only the script's own code, in a run that can pause, can wait for a result. - let can_wait = self.in_slice && self.reentry == 0; + // Only the script's own code, in a run that can pause, can wait for a result, and a host + // class's constructor called with `new` cannot. + let can_wait = self.in_slice && self.reentry == 0 && !self.constructing; self.can_wait.set(can_wait); let result = f(data); self.can_wait.set(false); match result { + Ok(d) if matches!(how, ArgRead::Hosted) => self.write_hosted(d), Ok(d) => self.write_data(d, 0, matches!(how, ArgRead::Frozen)), Err(HostError::Wait) if can_wait => { self.waiting = true; + self.waiting_hosted = matches!(how, ArgRead::Hosted); self.pause.set(true); Ok(Value::Undefined) } @@ -434,7 +462,7 @@ impl Interp { name: &Rc, args: &[Value], ) -> JsResult { - let data = self.read_args(name, args, &ArgRead::Data)?; + let data = self.read_args(name, None, args, &ArgRead::Data)?; let source = match f(data) { Ok(Data::String(source)) => source, Ok(d) => return self.write_data(d, 0, false), @@ -476,24 +504,39 @@ impl Interp { r } - /// The arguments of host function `name` as [`Data`], read as `how` says. - fn read_args(&mut self, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult> { - let mut reading = Reading { limits: self.data_limits, bytes: 0, entries: 0, ancestors: Vec::new(), path: Vec::new(), function: name.clone() }; + /// The arguments of host function `name` as [`Data`], read as `how` says, with an optional host receiver first. + fn read_args(&mut self, name: &Rc, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult> { + let mut reading = Reading { + limits: self.data_limits, + bytes: 0, + entries: 0, + ancestors: Vec::new(), + path: Vec::new(), + function: name.clone(), + hosted: matches!(how, ArgRead::Hosted), + }; let args = match how { ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args), _ => args, }; - let mut data = Vec::with_capacity(args.len()); + let mut data = Vec::with_capacity(args.len() + 1); + if let Some(this) = this { + let this = match this { + Value::Object(o) if self.host_ref_size(*o)?.is_some() => self.read_host_ref(*o, &mut reading)?, + _ => Data::Undefined, + }; + data.push(this); + } // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); - if !matches!(how, ArgRead::Data | ArgRead::Frozen) { + if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) { self.temp_roots.extend(args.iter().cloned()); } let mut read = Ok(()); for (i, a) in args.iter().enumerate() { reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); let d = match how { - ArgRead::Data | ArgRead::Frozen | ArgRead::Site => self.read_data(a, &mut reading), + ArgRead::Data | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading), ArgRead::Text => self.read_text(a, &mut reading), ArgRead::Each(list) => match list.get(i) { Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined), @@ -515,10 +558,33 @@ impl Interp { Ok(data) } + pub(crate) fn read_index_args(&mut self, id: ObjId, key: Data, probe: bool) -> JsResult> { + let mut reading = Reading { + limits: self.data_limits, + bytes: 0, + entries: 0, + ancestors: Vec::new(), + path: Vec::new(), + function: Rc::from("host indexer"), + hosted: true, + }; + let receiver = self.read_host_ref(id, &mut reading)?; + match &key { + Data::String(s) => self.charge_reading(&mut reading, s.encode_utf16().count().saturating_mul(3).saturating_add(2))?, + Data::Number(_) => {} + _ => return Err(Abrupt::Internal("a host indexer key is not a number or string".into())), + } + let mut args = vec![receiver, key]; + if probe { + args.push(Data::Bool(true)); + } + Ok(args) + } + /// What host error `e` throws, or the limit it ends the run with. A function that waits /// ([`HostError::Wait`]) where its caller does not handle the wait ends the run with an internal /// error. - fn host_error(&mut self, e: HostError) -> JsResult { + pub(crate) fn host_error(&mut self, e: HostError) -> JsResult { match e { HostError::Wait => Ok(Abrupt::Internal("a host function waited for its result where the run cannot pause".into())), HostError::Abort(message) => { diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs new file mode 100644 index 0000000000..9d14718dee --- /dev/null +++ b/crates/js/src/host_classes.rs @@ -0,0 +1,373 @@ +//! Classes a host defines ([`crate::Realm::define_host_classes`]): objects that stand for something +//! the host keeps, such as an open document or an object in one, with members the host's functions +//! answer. +//! +//! Each object holds the name of its class and a handle, a list of numbers the host chose, in an +//! internal slot that a script cannot read, write or copy onto another object. A host function sees +//! such an object as the [`Data`] that [`host_ref`] makes, and gives one back the same way; a plain +//! object a script made that carries [`HOST_REF_KEY`] is refused, so a script cannot make an object +//! of a host class from its own data. A class's prototype and constructor are frozen. While a +//! script holds the object for a class and handle, each read of that class and handle gives the +//! same object. Classes that descend from the same class without a parent share their objects: a +//! read of another of them with the same handle gives the object the script holds, now of the +//! class that read names. +//! +//! Every member function gets the object it is called on (`this`) as its first argument, or +//! `undefined` when `this` is not an object of a host class, followed by the call's arguments; a +//! setter gets `this` and the value assigned. A class with an indexer answers `object[i]` for each +//! array index `i` with it, called with `this` and the index as a number. Other names are looked up +//! as usual, and a name that the object and its prototypes lack goes to the indexer as a string (as +//! a number when it is the text of one, such as `-1`), so the indexer may throw for a name nothing +//! has. Names the engine looks up itself, such as `toJSON` in `JSON.stringify`, do not go to the +//! indexer. Assigning to such a name reads it with the indexer first, so the assignment throws what +//! the read throws; otherwise the value is not kept. `k in object` calls the indexer with `true` as +//! a third argument, and is true when it gives a value other than `undefined`. +//! +//! `hasOwnProperty` and `propertyIsEnumerable` are true on an object of a host class for each +//! member of its class and of the classes it descends from, apart from the members that are not +//! available yet ([`HostMember::Unavailable`]). `for`-`in` lists the properties among those members, +//! and not the methods. `Object.keys`, `Object.getOwnPropertyNames` and +//! `Object.getOwnPropertyDescriptor` do not report the members. + +use std::collections::HashSet; +use std::rc::Rc; + +use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, ObjId, Object, Prop, key}; +use crate::host::ArgRead; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::Value; +use crate::{Data, HostError, HostFunction}; + +/// The one key of the [`Data`] object that stands for an object of a host class ([`host_ref`]). +pub const HOST_REF_KEY: &str = "\u{0}hostRef"; + +/// A member of a host class's prototype. +#[derive(Clone)] +pub enum HostMember { + /// A read-only property: the function gives its value each time it is read. + Get(HostFunction), + /// A property the function `get` reads and `set` assigns. + Property { get: HostFunction, set: HostFunction }, + /// A method. + Method(HostFunction), + /// A property the class lists that is not available yet: the function answers both a read and + /// an assignment, with an error. It is not reported as the object's own, and `for`-`in` skips it. + Unavailable(HostFunction), +} + +/// A class [`crate::Realm::define_host_classes`] adds. +#[derive(Clone)] +pub struct HostClass { + pub name: String, + /// A class defined before this one, or in the same call before it, whose prototype this + /// class's prototype inherits from. + pub parent: Option, + pub members: Vec<(String, HostMember)>, + /// What `object[i]` gives for an array index `i`. + pub index: Option, + /// What `new Name(...)` and `Name(...)` give; without it both throw a `TypeError`. + pub construct: Option, +} + +/// The internal slot of an object of a host class: its class, as an index into the realm's +/// classes, and its handle. +#[derive(Clone, Debug)] +pub(crate) struct HostObj { + pub(crate) class: u32, + pub(crate) handle: Rc<[f64]>, +} + +/// A class the realm has. +#[derive(Clone)] +pub(crate) struct Entry { + name: Rc, + proto: ObjId, + ctor: ObjId, + index: Option, + /// The class without a parent this class descends from (itself for such a class), as an index + /// into the realm's classes. + family: u32, + /// The class this class's prototype inherits from, as an index into the realm's classes. + parent: Option, + /// The names of the members `hasOwnProperty` reports: every member but the unavailable ones. + own: Rc>, + /// The names of the members this class declares as unavailable. + unavailable: Rc>, +} + +impl Entry { + pub(crate) fn objects(&self) -> [ObjId; 2] { + [self.proto, self.ctor] + } +} + +/// A family of classes ([`Entry::family`]) and the bits of a handle. +type MadeKey = (u32, Box<[u64]>); + +/// The object made for each family of classes and handle ([`Interp::host_objects`]). +pub(crate) type Made = std::collections::HashMap; + +/// Whether `id` is still the object made for `key`, and not a freed cell or another object that +/// was given its cell. +fn is_made(heap: &crate::heap::Heap, classes: &[Entry], id: ObjId, key: &MadeKey) -> bool { + heap.object(id).is_some_and(|o| match &o.class { + Class::Host(h) => { + classes.get(h.class as usize).is_some_and(|e| e.family == key.0) && h.handle.iter().map(|n| n.to_bits()).eq(key.1.iter().copied()) + } + _ => false, + }) +} + +/// Drops the entries of `made` whose objects the last collection freed. +pub(crate) fn forget_collected(made: &mut Made, heap: &crate::heap::Heap, classes: &[Entry]) { + made.retain(|key, id| is_made(heap, classes, *id, key)); +} + +/// The [`Data`] that stands for the object of host class `class` with `handle`. +pub fn host_ref(class: &str, handle: &[f64]) -> Data { + let mut list = Vec::with_capacity(handle.len() + 1); + list.push(Data::String(class.to_string())); + list.extend(handle.iter().map(|n| Data::Number(*n))); + Data::Object(vec![(HOST_REF_KEY.to_string(), Data::Array(list))]) +} + +/// The class and handle of the object `d` stands for, when it is one [`host_ref`] made. +pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { + let Data::Object(items) = d else { return None }; + let [(k, Data::Array(list))] = items.as_slice() else { return None }; + if k != HOST_REF_KEY { + return None; + } + let (Data::String(class), rest) = list.split_first()? else { return None }; + let handle = rest.iter().map(|d| if let Data::Number(n) = d { Some(*n) } else { None }).collect::>>()?; + Some((class.as_str(), handle)) +} + +impl Interp { + /// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host + /// class, and `k` names an available member of that class or of a class it descends from. The + /// nearest class that declares `k` decides, so a member a class declares unavailable is not + /// reported even when a class it descends from has it. + pub(crate) fn is_host_member(&self, id: ObjId, k: &[u16]) -> JsResult { + let Class::Host(h) = &self.object(id)?.class else { return Ok(false) }; + let mut class = Some(h.class); + while let Some(c) = class { + let Some(e) = self.host_classes.get(c as usize) else { return Err(Abrupt::Internal("host class out of range".into())) }; + if e.own.contains(k) { + return Ok(true); + } + if e.unavailable.contains(k) { + return Ok(false); + } + class = e.parent; + } + Ok(false) + } + + /// The [`Data`] for the object of a host class `id`, or `None` when it is not one. + pub(crate) fn host_ref_of(&self, id: ObjId) -> JsResult> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + let name = + self.host_classes.get(h.class as usize).map(|e| e.name.clone()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?; + Ok(Some(host_ref(&name, &h.handle))) + } + + pub(crate) fn host_ref_size(&self, id: ObjId) -> JsResult> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + let name = self.host_classes.get(h.class as usize).map(|e| e.name.len()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?; + Ok(Some((name, h.handle.len()))) + } + + /// The object of a host class that `d`, which a host function gave, stands for. + pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult { + let Some((name, handle)) = host_ref_parts(d) else { + return Err(self.throw(ErrorType::Type, "a host value names an object of a host class wrongly")); + }; + let Some((class, entry)) = self.host_classes.iter().enumerate().find(|(_, e)| &*e.name == name) else { + return Err(self.throw(ErrorType::Type, &format!("a host value names the unknown class {name}"))); + }; + let (proto, family) = (entry.proto, entry.family); + let class = u32::try_from(class).unwrap_or(u32::MAX); + let made = (family, handle.iter().map(|n| n.to_bits()).collect::>()); + if let Some(&id) = self.host_objects.get(&made) + && is_made(&self.heap, &self.host_classes, id, &made) + { + // An object of another class of the family becomes one of `class`. + let o = self.object_mut(id)?; + if let Class::Host(h) = &mut o.class + && h.class != class + { + h.class = class; + o.proto = Some(proto); + } + return Ok(Value::Object(id)); + } + self.reserve_heap(crate::heap::OBJECT_BYTES)?; + let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); + o.extensible = false; + let id = self.heap.alloc_object(o); + self.host_objects.insert(made, id); + Ok(Value::Object(id)) + } + + /// Whether `id` is the constructor of a host class (its other functions are not constructors). + pub(crate) fn is_host_constructor(&self, id: ObjId) -> bool { + self.host_classes.iter().any(|e| e.ctor == id) + } + + /// The indexer of the host class of `id`, when it is an object of a host class that has one. + pub(crate) fn host_indexer(&self, id: ObjId) -> JsResult> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + Ok(self.host_classes.get(h.class as usize).and_then(|e| e.index.clone())) + } + + /// `object[k]` of an object of a host class, which its class's indexer `f` answers: `k` is an + /// array index as a number, or a name as a string. With `probe`, for `k in object`, the indexer + /// gets `true` as a third argument. + pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult { + self.use_fuel()?; + if self.host_ref_size(id)?.is_none() { + return Ok(Value::Undefined); + } + let args = self.read_index_args(id, k, probe)?; + match f(args) { + Ok(d) => self.write_hosted(d), + Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())), + Err(e) => Err(self.host_error(e)?), + } + } + + /// The key an indexer gets for `k`: a number for an array index and for any other key that is + /// the text of a number (`-1`, `1.5`, `NaN`), otherwise the name. + pub(crate) fn indexer_key(k: &[u16]) -> Data { + if let Some(i) = crate::value::array_index(k) { + return Data::Number(f64::from(i)); + } + let name = String::from_utf16_lossy(k); + match name.parse::() { + Ok(n) if crate::number_to_string(n) == name => Data::Number(n), + _ => Data::String(name), + } + } + + /// [[HasProperty]] of `k` on `id`: for an object of a host class with an indexer, an array index, + /// or a name that the object and its prototypes lack, is there when the indexer gives a value other + /// than `undefined` for it. + pub(crate) fn has_property_indexed(&mut self, id: ObjId, k: &[u16]) -> JsResult { + let index = crate::value::array_index(k).is_some(); + if (index || !self.has_property(id, k)?) + && let Some(f) = self.host_indexer(id)? + { + return Ok(!matches!(self.host_index(&f, id, Self::indexer_key(k), true)?, Value::Undefined)); + } + self.has_property(id, k) + } + + /// `d` as a JavaScript value, the objects of host classes in it made from their [`host_ref`]. + pub(crate) fn write_hosted(&mut self, d: Data) -> JsResult { + let was = std::mem::replace(&mut self.write_hosted, true); + let r = self.write_data(d, 0, false); + self.write_hosted = was; + r + } +} + +/// Adds `classes` and the global objects `instances`, each made from the [`host_ref`] given. +pub(crate) fn install(i: &mut Interp, classes: Vec, instances: Vec<(String, Data)>) -> JsResult<()> { + for class in classes { + install_class(i, class)?; + } + for (name, d) in instances { + let v = i.write_hosted(d)?; + let global = i.global; + i.define(global, key(&name), Prop::Data { value: v, flags: 0 })?; + } + Ok(()) +} + +/// Adds the global properties `globals`, each read with its getter and assigned with its setter as +/// a member of a host class is. Assigning one without a setter keeps its value, and throws in strict +/// mode code. +pub(crate) fn install_globals(i: &mut Interp, globals: Vec<(String, HostFunction, Option)>) -> JsResult<()> { + let global = i.global; + for (name, get, set) in globals { + let mark = i.temp_roots.len(); + let get = hosted_function(i, get, &name); + i.temp_roots.push(Value::Object(get)); + let set = set.map(|f| hosted_function(i, f, &name)); + i.temp_roots.truncate(mark); + i.define(global, key(&name), Prop::Accessor { get: Some(get), set, flags: CONFIGURABLE })?; + } + Ok(()) +} + +fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { + if i.host_classes.iter().any(|e| *e.name == *class.name) { + return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); + } + let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX); + let (parent, family, parent_class) = match &class.parent { + None => (i.intrinsics.object_proto, own, None), + Some(p) => match i.host_classes.iter().enumerate().find(|(_, e)| *e.name == **p) { + Some((n, e)) => (e.proto, e.family, u32::try_from(n).ok()), + None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))), + }, + }; + let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(parent))); + let mark = i.temp_roots.len(); + i.temp_roots.push(Value::Object(proto)); + let r = fill_class(i, proto, &class); + i.temp_roots.truncate(mark); + let ctor = r?; + let (unavailable, members): (Vec<_>, Vec<_>) = class.members.iter().partition(|(_, m)| matches!(m, HostMember::Unavailable(_))); + let names = |list: Vec<&(String, HostMember)>| list.into_iter().map(|(name, _)| key(name)).collect::>(); + i.host_classes.push(Entry { + name: class.name.as_str().into(), + proto, + ctor, + index: class.index, + family, + parent: parent_class, + own: Rc::new(names(members)), + unavailable: Rc::new(names(unavailable)), + }); + let global = i.global; + i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) +} + +/// Puts the members of `class` on `proto` and makes its constructor. → the constructor. +fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult { + let path = &class.name; + for (name, member) in &class.members { + let full = format!("{path}.{name}"); + let prop = match member { + HostMember::Get(f) => Prop::Accessor { get: Some(hosted_function(i, f.clone(), &full)), set: None, flags: ENUMERABLE }, + HostMember::Property { get, set } => { + let get = hosted_function(i, get.clone(), &full); + i.temp_roots.push(Value::Object(get)); + Prop::Accessor { get: Some(get), set: Some(hosted_function(i, set.clone(), &full)), flags: ENUMERABLE } + } + HostMember::Method(f) => Prop::Data { value: Value::Object(hosted_function(i, f.clone(), &full)), flags: 0 }, + HostMember::Unavailable(f) => { + let f = hosted_function(i, f.clone(), &full); + Prop::Accessor { get: Some(f), set: Some(f), flags: 0 } + } + }; + i.define(proto, key(name), prop)?; + } + let construct = class.construct.clone().unwrap_or_else(|| { + let message = format!("{path} cannot be constructed by a script"); + Rc::new(move |_| Err(HostError::Type(message.clone()))) + }); + let ctor = hosted_function(i, construct, path); + i.define(ctor, key("prototype"), Prop::Data { value: Value::Object(proto), flags: 0 })?; + i.define(proto, key("constructor"), Prop::Data { value: Value::Object(ctor), flags: 0 })?; + i.object_mut(proto)?.extensible = false; + i.object_mut(ctor)?.extensible = false; + Ok(ctor) +} + +fn hosted_function(i: &mut Interp, f: HostFunction, name: &str) -> ObjId { + let proto = i.intrinsics.function_proto; + i.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), read: ArgRead::Hosted }), Some(proto))) +} diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 0a682811ec..8c4b036898 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -11,6 +11,57 @@ fn realm(fuel: u64) -> Realm { r } +#[test] +fn non_finite_indexer_keys_reach_the_host_unchanged() { + let mut r = realm(1_000_000); + let index: HostFunction = Rc::new(|args| { + assert!(matches!(args.get(1), Some(Data::Number(n)) if !n.is_finite()), "{args:?}"); + Ok(Data::Bool(true)) + }); + let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(index), construct: None }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap(); + let source = "[it[NaN], it[Infinity], it[-Infinity], NaN in it, Infinity in it, -Infinity in it].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("true|true|true|true|true|true".into())); +} + +#[test] +fn host_receivers_obey_limits_lowered_after_the_object_was_created() { + for limits in [DataLimits { depth: 64, bytes: 1_000, entries: 2 }, DataLimits { depth: 64, bytes: 1, entries: 100 }] { + for expression in ["it[0]", "0 in it", "it.method()", "it.take(it)"] { + let mut r = realm(1_000_000); + let calls = Rc::new(Cell::new(0)); + let called = calls.clone(); + let function: HostFunction = Rc::new(move |_| { + called.set(called.get() + 1); + Ok(Data::Undefined) + }); + let class = HostClass { + name: "Indexed".into(), + parent: None, + members: vec![("method".into(), HostMember::Method(function.clone())), ("take".into(), HostMember::Method(function.clone()))], + index: Some(function), + construct: None, + }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0, 2.0, 3.0]))]).unwrap(); + r.set_data_limits(limits); + let source = format!("var result = 'called'; try {{ {expression}; }} catch (e) {{ result = e.name; }} result"); + assert_eq!(r.run(&source).unwrap(), JsValue::String("RangeError".into()), "{expression}: {limits:?}"); + assert_eq!(calls.get(), 0, "{expression}"); + } + } +} + +#[test] +fn index_keys_share_the_receivers_data_budget() { + let mut r = realm(1_000_000); + let class = HostClass { name: "Indexed".into(), parent: None, members: vec![], index: Some(Rc::new(|_| Ok(Data::Bool(true)))), construct: None }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Indexed", &[1.0]))]).unwrap(); + r.set_data_limits(DataLimits { depth: 64, bytes: 256, entries: 100 }); + assert_eq!(r.run("it['short']").unwrap(), JsValue::Bool(true)); + let source = "var result = 'called'; try { it[new Array(71).join('x')]; } catch (e) { result = e.name; } result"; + assert_eq!(r.run(source).unwrap(), JsValue::String("RangeError".into())); +} + /// A realm with `host.take(value)`, which records what it was given and returns it. fn with_take(r: &mut Realm) -> Rc>> { let seen: Rc>> = Rc::default(); @@ -75,6 +126,96 @@ fn an_ended_run_leaves_the_realm_ready_for_the_next() { r.end(); } +fn paused_for_replacement(promise: bool) -> Realm { + let mut r = Realm::with_options(Options { es2015: promise, ..Options::default() }, Limits::default()); + let pause = r.pause_flag(); + r.define_function("pauseNow", move |_| { + pause.set(true); + Ok(JsValue::Undefined) + }); + let source = if promise { + "var kept = 'yes', after = false, queued = false;\n\ + Promise.resolve().then(function () { pauseNow(); after = true; });\n\ + Promise.resolve().then(function () { queued = true; }); 'old'" + } else { + "var kept = 'yes', after = false, queued = false; pauseNow(); after = true; 'old'" + }; + r.start(source).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Paused); + assert!(r.is_running()); + if promise { + assert!(r.interp().promises.draining); + } + r +} + +fn replacement(r: &mut Realm, sliced: bool, source: &str) -> Result { + if sliced { + r.start(source)?; + finish(r, 1_000).0 + } else { + r.run(source) + } +} + +#[test] +fn replacing_a_paused_promise_run_discards_its_reaction_and_queued_jobs() { + for sliced in [false, true] { + let mut r = paused_for_replacement(true); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } +} + +#[test] +fn replacing_a_paused_script_discards_its_remaining_code() { + for sliced in [false, true] { + let mut r = paused_for_replacement(false); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } +} + +#[test] +fn replacing_a_waiting_run_discards_its_host_call() { + for sliced in [false, true] { + let mut r = realm(1_000_000); + let calls = with_ask(&mut r); + r.start("var after = false; ask('old'); after = true").unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + assert_eq!(replacement(&mut r, sliced, "'new'").unwrap(), JsValue::String("new".into())); + assert!(!r.waits()); + assert_eq!(r.run("after").unwrap(), JsValue::Bool(false)); + assert_eq!(calls.get(), 1); + assert!(r.answer(Data::Null).is_err()); + } +} + +#[test] +fn replacing_a_paused_run_with_invalid_source_still_ends_it() { + for promise in [false, true] { + for sliced in [false, true] { + let mut r = paused_for_replacement(promise); + assert_eq!(replacement(&mut r, sliced, "(").unwrap_err().kind, RunErrorKind::Syntax); + assert!(!r.is_running()); + assert_eq!(r.run("[kept, after, queued].join('|')").unwrap(), JsValue::String("yes|false|false".into())); + } + } +} + +#[test] +fn replacing_a_paused_run_applies_its_pending_language_setting() { + for sliced in [false, true] { + let mut r = paused_for_replacement(false); + r.set_es2015(true); + assert_eq!(replacement(&mut r, sliced, "let fresh = 7; fresh").unwrap(), JsValue::Number(7.0)); + assert_eq!(r.run("after").unwrap(), JsValue::Bool(false)); + } +} + /// Setting `Folder.current` back for the next run drops what only the last run's uncaught /// exception held, so a full heap from that exception does not stop the next run. #[test] @@ -675,6 +816,134 @@ fn a_host_function_that_waits_where_it_cannot_ends_the_run() { assert_eq!(e.kind, RunErrorKind::Internal); } +/// The host class `Thing` with the method `fetch`, which waits for its answer where it can, the +/// getter `id`, the first number of the object's handle, and the constructor `make`; and the +/// global `thing`, the `Thing` with the handle `[1]`. +fn with_thing(r: &mut Realm, make: Option) { + let can_wait = r.wait_flag(); + let fetch: HostFunction = Rc::new(move |_| if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) }); + let id: HostFunction = Rc::new(|a| Ok(a.first().and_then(host_ref_parts).and_then(|(_, h)| h.first().copied()).map_or(Data::Null, Data::Number))); + let members = vec![("fetch".to_string(), HostMember::Method(fetch)), ("id".to_string(), HostMember::Get(id))]; + let class = HostClass { name: "Thing".into(), parent: None, members, index: None, construct: make }; + r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap(); +} + +#[test] +fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { + let mut r = realm(1_000_000); + with_thing(&mut r, None); + r.start("var t = thing.fetch(), u = thing.fetch(); [t instanceof Thing, t.id, t === u, t === thing].join()").unwrap(); + for _ in 0..2 { + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + r.answer(host_ref("Thing", &[2.0])).unwrap(); + } + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into())); +} + +#[test] +fn a_host_class_constructor_called_with_new_cannot_wait() { + let mut r = realm(1_000_000); + let could: Rc>> = Rc::default(); + let (seen, can_wait) = (could.clone(), r.wait_flag()); + let make: HostFunction = Rc::new(move |_| { + seen.set(Some(can_wait.get())); + if can_wait.get() { Err(HostError::Wait) } else { Ok(Data::Object(Vec::new())) } + }); + with_thing(&mut r, Some(make)); + r.start("var c = new Thing(); c instanceof Thing").unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::Bool(true)); + assert_eq!(could.get(), Some(false)); +} + +#[test] +fn objects_of_a_host_class_report_its_available_members_as_their_own() { + let mut r = realm(1_000_000); + let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0))); + let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into()))); + let base = HostClass { + name: "Base".into(), + parent: None, + members: vec![ + ("size".to_string(), HostMember::Get(value.clone())), + ("shape".to_string(), HostMember::Property { get: value.clone(), set: value.clone() }), + ("grow".to_string(), HostMember::Method(value.clone())), + ("later".to_string(), HostMember::Unavailable(missing)), + ], + index: None, + construct: None, + }; + let leaf = HostClass { + name: "Leaf".into(), + parent: Some("Base".into()), + members: vec![("leaf".to_string(), HostMember::Get(value))], + index: None, + construct: None, + }; + r.define_host_classes(vec![base, leaf], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap(); + r.start( + "var own = Object.prototype.hasOwnProperty, keys = [];\ + for (var k in it) keys.push(k);\ + [it.hasOwnProperty('size'), it.hasOwnProperty('shape'), it.hasOwnProperty('grow'), it.hasOwnProperty('leaf'),\ + own.call(it, 'size'), it.propertyIsEnumerable('grow'),\ + it.hasOwnProperty('later'), it.propertyIsEnumerable('later'), it.hasOwnProperty('nope'),\ + it.hasOwnProperty('hasOwnProperty'), it.hasOwnProperty('constructor'), 'later' in it,\ + keys.sort().join(' '), Leaf.prototype.hasOwnProperty('size'), ({}).hasOwnProperty('size')].join()", + ) + .unwrap(); + assert_eq!( + finish(&mut r, 1_000_000).0.unwrap(), + JsValue::String("true,true,true,true,true,true,false,false,false,false,false,true,leaf shape size,false,false".into()) + ); +} + +#[test] +fn a_member_a_class_declares_unavailable_is_not_its_own_when_its_parent_has_it() { + let mut r = realm(1_000_000); + let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0))); + let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into()))); + let base = HostClass { + name: "Base".into(), + parent: None, + members: vec![("size".to_string(), HostMember::Get(value.clone())), ("grow".to_string(), HostMember::Method(value))], + index: None, + construct: None, + }; + let leaf = HostClass { + name: "Leaf".into(), + parent: Some("Base".into()), + members: vec![("size".to_string(), HostMember::Unavailable(missing))], + index: None, + construct: None, + }; + r.define_host_classes(vec![base, leaf], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap(); + r.start("[it.hasOwnProperty('size'), it.propertyIsEnumerable('size'), it.hasOwnProperty('grow')].join()").unwrap(); + assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,true".into())); +} + +#[test] +fn assigning_a_name_a_prototype_has_does_not_call_the_indexer() { + let mut r = realm(1_000_000); + let calls: Rc> = Rc::default(); + let seen = calls.clone(); + let index: HostFunction = Rc::new(move |a| { + seen.set(seen.get() + 1); + match a.get(1) { + Some(Data::Number(_)) => Ok(Data::Undefined), + _ => Err(HostError::Error("no such member".into())), + } + }); + let class = HostClass { name: "List".into(), parent: None, members: Vec::new(), index: Some(index), construct: None }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("List", &[1.0]))]).unwrap(); + r.start("Object.prototype.extra = 1; it.extra = 2; it.extra").unwrap(); + assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::Number(1.0)); + assert_eq!(calls.get(), 0); + // A name nothing has still goes to the indexer, which throws. + r.start("it.nope = 2").unwrap(); + assert!(finish(&mut r, 1_000_000).0.is_err()); + assert_eq!(calls.get(), 1); +} + #[test] fn a_converted_function_reads_each_argument_as_its_list_says() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index a64763947f..f8e80a6e87 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -4,7 +4,9 @@ //! JavaScript recursion uses the heap, not the Rust stack. The loop runs again inside a Rust call //! only where the language needs a function's result in the middle of an operation (a getter or //! setter, `valueOf` and `toString` during a conversion, indirect `eval`); those nested runs are -//! counted against [`crate::Limits::reentry`]. +//! counted against [`crate::Limits::reentry`]. A generator's body runs in a frame of its own, +//! which `yield` moves into the generator object, operands included, and a call to its `next`, +//! `return` or `throw` pushes again ([`crate::generator`]). //! //! Before each instruction the interpreter takes one unit of fuel, checks the interrupt flag and, //! when the heap has grown past its threshold, collects garbage. Running out of fuel, the heap @@ -55,12 +57,37 @@ pub(crate) fn internal(message: &str) -> JsResult { /// The hash an error the interpreter throws keeps of its description ([`Interp::throw`]). fn description_hash(text: &str) -> u64 { - use std::hash::{Hash, Hasher}; - let mut h = std::hash::DefaultHasher::new(); - text.hash(&mut h); + let mut h = DescriptionHash::default(); + h.text(text); h.finish() } +/// A [`description_hash`] fed the description's code units a run at a time, so a long string is +/// hashed without being copied. +#[derive(Default)] +struct DescriptionHash(std::hash::DefaultHasher); + +impl DescriptionHash { + fn units(&mut self, units: &[u16]) { + use std::hash::Hasher; + for &u in units { + self.0.write_u16(u); + } + } + + fn text(&mut self, text: &str) { + use std::hash::Hasher; + for u in text.encode_utf16() { + self.0.write_u16(u); + } + } + + fn finish(&self) -> u64 { + use std::hash::Hasher; + self.0.finish() + } +} + /// The kinds of error object the engine throws. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum ErrorType { @@ -173,22 +200,24 @@ pub(crate) struct Frame { pub(crate) code: Rc, pub(crate) pc: usize, /// Where this frame's operands start on the operand stack. - base: usize, + pub(crate) base: usize, pub(crate) env: EnvId, pub(crate) var_env: EnvId, /// `with` and catch environments entered and not yet left. - env_depth: u32, - this: Value, - callee: Option, + pub(crate) env_depth: u32, + pub(crate) this: Value, + pub(crate) callee: Option, /// The object `new` made, returned unless the function returns an object. - construct: Option, - completion: Value, + pub(crate) construct: Option, + pub(crate) completion: Value, /// Returning from this frame returns from the Rust call that pushed it. - boundary: bool, + pub(crate) boundary: bool, + /// The generator object whose body this frame runs, once [`Op::GeneratorStart`] has made it. + pub(crate) generator: Option, } /// Where the exception being thrown was raised: the code and the instruction. -type ThrowSite = (Rc, usize); +pub(crate) type ThrowSite = (Rc, usize); /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; @@ -279,6 +308,14 @@ pub(crate) struct Interp { pub(crate) install_error: Option, /// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]). pub(crate) files: Option, + /// The classes a host added ([`crate::Realm::define_host_classes`]), in the order it added them. + pub(crate) host_classes: Vec, + /// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`]. + pub(crate) write_hosted: bool, + /// The object made for each family of classes and handle ([`crate::host_classes`]), so that two reads of + /// the same one give the same object. It is not a root: an entry whose object was collected is + /// dropped after each collection. + pub(crate) host_objects: crate::host_classes::Made, /// `UnitValue`, once a host has added it ([`crate::Realm::add_unit_values`]). Until then the /// operators take no object as a measurement. pub(crate) unit_values: Option, @@ -302,6 +339,11 @@ pub(crate) struct Interp { pub(crate) can_wait: Rc>, /// A host function's call waits for its result: the value on top of the stack stands in for it. pub(crate) waiting: bool, + /// The call that waits is a member of a host class ([`crate::host::ArgRead::Hosted`]): its + /// answer is read as such a member's result is ([`Interp::write_hosted`]). + pub(crate) waiting_hosted: bool, + /// A host class's constructor runs with `new`: it may not wait for its result. + pub(crate) constructing: bool, /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before /// the next instruction runs. pub(crate) resuming: Option, @@ -341,6 +383,8 @@ pub(crate) struct Interp { pub(crate) error_mark: Option, /// [`crate::bytecode::Source::strict_writes`] for the scripts the realm runs. pub(crate) strict_writes: bool, + /// `Promise` and the run's promise job queue ([`crate::builtins::promise`]). + pub(crate) promises: crate::builtins::promise::Promises, /// The well-known Symbols, `Symbol.for`'s registry and the objects that go with them, in a /// realm with [`crate::Options::es2015`]. pub(crate) symbols: crate::symbol::Symbols, @@ -490,7 +534,7 @@ fn arguments_bytes(args: usize) -> usize { } /// A call to a function written in JavaScript, ready to enter. -struct Entry { +pub(crate) struct Entry { callee: ObjId, code: Rc, env: EnvId, @@ -499,9 +543,11 @@ struct Entry { } /// What a call resolved to. -enum Prepared { +pub(crate) enum Prepared { Closure(Entry), Done(Value), + /// A generator's `next`, `return` or `throw` that goes on with its body. + Resume(Box), } /// A variable found in the environment chain. @@ -583,6 +629,9 @@ impl Interp { held_bytes: 0, install_error: None, files: None, + host_classes: Vec::new(), + write_hosted: false, + host_objects: crate::host_classes::Made::default(), unit_values: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), @@ -593,6 +642,8 @@ impl Interp { in_slice: false, can_wait: Rc::default(), waiting: false, + waiting_hosted: false, + constructing: false, resuming: None, host_abort: None, data_limits: crate::DataLimits::default(), @@ -607,6 +658,7 @@ impl Interp { finally_sites: Vec::new(), error_mark: None, strict_writes: false, + promises: crate::builtins::promise::Promises::default(), symbols: crate::symbol::Symbols::default(), }; // With `Options::es2015`, the first run names the built-in functions, under the limits @@ -658,7 +710,7 @@ impl Interp { let Value::Object(o) = v else { return true }; let Some(Class::Error(Some(hash))) = self.heap.object(*o).map(|o| &o.class) else { return true }; let hash = *hash; - description_hash(&self.describe(v)) != hash + self.describe_hash(*o) != hash } pub(crate) fn type_error(&mut self, message: &str) -> Abrupt { @@ -822,7 +874,7 @@ impl Interp { /// Removes the [`Self::finally_sites`] entries whose stack slot is at or above `len`: those of /// `finally` blocks that were left. The slots rise along the list, so only its end is looked at. - fn drop_left_finally_sites(&mut self, len: usize) { + pub(crate) fn drop_left_finally_sites(&mut self, len: usize) { while let Some(&(_, slot)) = self.finally_sites.last() { #[cfg(test)] SITE_CHECKS.with(|c| c.set(c.get() + 1)); @@ -836,6 +888,7 @@ impl Interp { pub(crate) fn collect_garbage(&mut self) { self.drop_left_finally_marks(); self.drop_left_finally_sites(self.stack.len()); + self.promises.forget_handled(&self.heap); let mut roots = Roots::default(); roots.values.extend(self.stack.iter()); roots.values.extend(self.temp_roots.iter()); @@ -849,7 +902,7 @@ impl Interp { for f in &self.frames { roots.values.push(&f.this); roots.values.push(&f.completion); - roots.objects.extend(f.callee.iter().chain(f.construct.iter())); + roots.objects.extend(f.callee.iter().chain(f.construct.iter()).chain(f.generator.iter())); roots.envs.push(f.env); roots.envs.push(f.var_env); roots.codes.push(&f.code); @@ -857,6 +910,7 @@ impl Interp { roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); + roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects)); roots.values.extend(self.symbols.root_values()); roots.objects.extend(self.symbols.root_objects()); roots.objects.extend(self.unit_values.iter().map(crate::unit_value::Classes::object)); @@ -871,12 +925,20 @@ impl Interp { } self.template_objects.retain(|(site, _), (code, _)| Rc::strong_count(code) > sites.get(site).copied().unwrap_or(0)); roots.objects.extend(self.template_objects.values().map(|&(_, id)| id)); + self.promises.add_roots(&mut roots); self.heap.collect(&roots); + crate::host_classes::forget_collected(&mut self.host_objects, &self.heap, &self.host_classes); // The collection counts the live total again, so bytes already released are not in it. self.held.released.set(0); self.flattened.set(0); - self.heap.bytes = - self.heap.bytes.saturating_add(self.held_bytes).saturating_add(self.held.now.get()).saturating_add(self.symbols.registry_bytes()); + let queued = self.promises.queue_bytes(); + self.heap.bytes = self + .heap + .bytes + .saturating_add(self.held_bytes) + .saturating_add(self.held.now.get()) + .saturating_add(self.symbols.registry_bytes()) + .saturating_add(queued); } /// Runs frames until the boundary frame on top returns, and returns its value. @@ -939,6 +1001,8 @@ impl Interp { let v = self.frame()?.completion.clone(); self.return_value(v) } + Op::GeneratorStart => self.op_generator_start(), + Op::Yield(raw) => self.op_yield(raw), _ => self.exec(op).map(|()| None), } } @@ -993,6 +1057,7 @@ impl Interp { } let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) }; self.stack.truncate(frame.base); + self.end_generator(frame.generator); if frame.boundary { self.passing = v.clone(); return Err(Abrupt::Throw(v)); @@ -1009,6 +1074,7 @@ impl Interp { fn abort_to_boundary(&mut self) { while let Some(frame) = self.frames.pop() { self.stack.truncate(frame.base); + self.end_generator(frame.generator); if frame.boundary { break; } @@ -1016,8 +1082,15 @@ impl Interp { } fn return_value(&mut self, v: Value) -> JsResult> { + // A generator's body that returns ends it, and its caller gets `{ value, done: true }`, + // made while the frame is still there to fail in. + let v = match self.frames.last().and_then(|f| f.generator) { + Some(_) => crate::builtins::iterator::iter_result(self, v, true)?, + None => v, + }; let Some(frame) = self.frames.pop() else { return internal("return without a frame") }; self.stack.truncate(frame.base); + self.end_generator(frame.generator); // A `return` in a finally block leaves the block, and the value takes its exception's slot. self.drop_left_finally_sites(frame.base); let v = match frame.construct { @@ -1198,7 +1271,12 @@ impl Interp { Op::PatternGet(n) => self.op_pattern_get(n), Op::InitIndex => self.op_init_index(), Op::InitAccessorIndex(getter) => self.op_init_accessor_index(getter), - Op::Return | Op::ReturnCompletion => internal("return reached the dispatcher"), + Op::Resume(t) => self.op_resume(t), + Op::DelegateIterator => self.op_delegate_iterator(), + Op::DelegateCall(t) => self.op_delegate_call(t), + Op::DelegateResult(t) => self.op_delegate_result(t), + Op::DelegateDone(t) => self.op_delegate_done(t), + Op::Return | Op::ReturnCompletion | Op::GeneratorStart | Op::Yield(_) => internal("a frame-ending instruction reached the dispatcher"), } } @@ -1573,6 +1651,28 @@ impl Interp { /// [[Get]] starting at `start`, with `receiver` as `this` for a getter. pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + // An array index of an object of a host class with an indexer is the indexer's answer. + if let Some(i) = array_index(k) + && let Some(f) = self.host_indexer(start)? + { + return self.host_index(&f, start, crate::Data::Number(f64::from(i)), false); + } + match self.find_property(start, k)? { + // A name the object and its prototypes lack is the indexer's answer too. + None => match self.host_indexer(start)? { + Some(f) => self.host_index(&f, start, Self::indexer_key(k), false), + None => Ok(Value::Undefined), + }, + Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), + Some(Prop::Data { value, .. }) => Ok(value), + Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), + } + } + + /// [[Get]] of a name that is not an array index, without the indexer of an object of a host + /// class: a name the object and its prototypes lack is `undefined`. For names the engine looks + /// up itself, such as `toJSON`, which a collection's indexer would answer with an error. + pub(crate) fn get_property_only(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { match self.find_property(start, k)? { None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Some(Prop::Data { value, .. }) => Ok(value), @@ -1862,16 +1962,25 @@ impl Interp { None => {} } let proto = self.object(id)?.proto; - match proto.map(|p| self.find_property(p, &k)).transpose()?.flatten() { + let inherited = proto.map(|p| self.find_property(p, &k)).transpose()?.flatten(); + match inherited { Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"), Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"), _ => {} } - let o = self.object(id)?; - if !o.extensible { + if !self.object(id)?.extensible { + // A name that an object of a host class with an indexer lacks, and its prototypes lack + // too, is read with the indexer first, so assigning it throws what reading it throws. + if inherited.is_none() + && array_index(&k).is_none() + && let Some(f) = self.host_indexer(id)? + { + self.host_index(&f, id, Self::indexer_key(&k), false)?; + } return self.reject(throw, &k, "the object is not extensible"); } + let o = self.object(id)?; if let Class::Array { length, length_writable: false } = o.class && array_index(&k).is_some_and(|i| i >= length) { @@ -2320,7 +2429,8 @@ impl Interp { Some(_) => self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(env) }), None => env, }; - let proto = self.intrinsics.function_proto; + let generator = code.generator.then(|| self.symbols.objects.map(|o| (o.generator_function_proto, o.generator_proto))).flatten(); + let proto = generator.map_or(self.intrinsics.function_proto, |(function_proto, _)| function_proto); let length = code.length; let strict = code.strict; let arrow = code.arrow; @@ -2334,6 +2444,18 @@ impl Interp { if let Some(name) = own_name { self.define(f, key("name"), Prop::Data { value: Value::String(Str::from_rc(name)), flags: CONFIGURABLE })?; } + // A generator function's `prototype`, a generator method's included, inherits from + // %GeneratorPrototype% and has no `constructor` (ECMA-262 11th edition, section 14.4.13). + // A generator function has no own `caller` or `arguments`, strict or not + // (section 16.2). + if let (false, Some((_, generator_proto))) = (arrow, generator) { + let p = self.heap.alloc_object(Object::new(Class::Ordinary, Some(generator_proto))); + self.define(f, key("prototype"), Prop::Data { value: Value::Object(p), flags: WRITABLE })?; + if let Some(name) = self_name { + self.env_insert(env, name, Binding::new(Value::Object(f), false, false))?; + } + return Ok(f); + } // An arrow function, a method and an accessor of ECMAScript 2015 code have no // `prototype` and cannot be constructed (sections 14.2.16 and 14.3.8). if arrow || method { @@ -2732,6 +2854,11 @@ impl Interp { let callee = f.as_object().ok_or_else(|| Abrupt::Internal("callee is not an object".into()))?; return Ok(Prepared::Closure(Entry { callee, code, env, this, args })); } + Func::Native { kind: NativeKind::Resume(mode), .. } => { + self.use_fuel()?; + let sent = args.into_iter().next().unwrap_or(Value::Undefined); + return self.prepare_resume(this, mode, sent); + } Func::Native { kind: NativeKind::Call, .. } => { self.use_fuel()?; f = this; @@ -2743,9 +2870,12 @@ impl Interp { return Err(self.type_error("apply was called on a value that is not a function")); } let list = args.get(1).cloned().unwrap_or(Value::Undefined); + let mut roots = vec![f.clone(), this.clone()]; + roots.extend(args.iter().cloned()); + let expanded = self.rooted(&roots, |i| i.list_from_array_like(&list))?; f = this; this = args.first().cloned().unwrap_or(Value::Undefined); - args = self.list_from_array_like(&list)?; + args = expanded; } Func::Bound { target, this: bound_this, args: bound_args } => { self.use_fuel()?; @@ -2782,7 +2912,7 @@ impl Interp { Func::Data { f, name, read } => { // The arguments are read before the function runs, and a result being built // keeps itself reachable. - return Ok(Prepared::Done(self.call_data(&f, &name, &args, &read)?)); + return Ok(Prepared::Done(self.call_data(&f, &name, &this, &args, &read)?)); } Func::Eval { f, end, strict_writes, name } => { return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args)?)); @@ -2854,6 +2984,10 @@ impl Interp { self.stack.truncate(start); self.enter_function(entry, None, false) } + Prepared::Resume(r) => { + self.stack.truncate(start); + self.enter_resumed(*r, false) + } } } @@ -2874,6 +3008,7 @@ impl Interp { } match self.func_of(&f) { Some(Func::Closure { code, .. }) if code.arrow => Err(self.type_error("an arrow function is not a constructor")), + Some(Func::Closure { code, .. }) if code.generator => Err(self.type_error("a generator function is not a constructor")), Some(Func::Closure { code, .. }) if code.method => Err(self.type_error("a method is not a constructor")), Some(Func::Closure { code, env }) => { let Some(callee) = f.as_object() else { return internal("callee is not an object") }; @@ -2893,6 +3028,25 @@ impl Interp { self.stack.truncate(start); self.push(v) } + // A host class's constructor ([`crate::host_classes`]) gives the object it makes. A plain + // object it gives inherits from the class's prototype. The class's other functions are + // not constructors. A constructor called with `new` cannot wait for its result. + Some(Func::Data { f: host, name, read: read @ crate::host::ArgRead::Hosted }) + if f.as_object().is_some_and(|o| self.is_host_constructor(o)) => + { + let was = std::mem::replace(&mut self.constructing, true); + let v = self.call_data(&host, &name, &Value::Undefined, &args, &read); + self.constructing = was; + let v = v?; + if let (Some(callee), Value::Object(o)) = (f.as_object(), &v) + && matches!(self.object(*o)?.class, Class::Ordinary) + && let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))? + { + self.object_mut(*o)?.proto = Some(proto); + } + self.stack.truncate(start); + self.push(v) + } _ => Err(self.type_error("the value is not a constructor")), } } @@ -2957,6 +3111,7 @@ impl Interp { construct, completion: Value::Undefined, boundary, + generator: None, }); Ok(()) } @@ -3139,7 +3294,7 @@ impl Interp { self.temp_roots.extend(keep.iter().cloned()); let was_waiting = self.waiting; let answer = match self.func_of(&host) { - Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), + Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read), _ => self.call(&host, &Value::Undefined, &args), }; self.temp_roots.truncate(mark); @@ -3179,6 +3334,22 @@ impl Interp { r } + /// Starts a call to `f` with no frame running, for a promise job: a native or host function + /// runs now and gives `Some` with its result, and a function written in JavaScript gets a + /// boundary frame that the caller runs, and gives `None`. A host function called here cannot + /// wait for its result, since no script code is running; a function written in JavaScript + /// runs as the script's own code does. + pub(crate) fn start_call(&mut self, f: Value, this: Value, args: Vec) -> JsResult> { + self.reentry += 1; + let prepared = self.prepare_call(f, this, args); + self.reentry -= 1; + match prepared? { + Prepared::Done(v) => Ok(Some(v)), + Prepared::Closure(entry) => self.enter_function(entry, None, true).map(|()| None), + Prepared::Resume(resumed) => self.enter_resumed(*resumed, true).map(|()| None), + } + } + fn call_rooted(&mut self, f: Value, this: Value, args: Vec, saved: usize) -> JsResult { match self.prepare_call(f, this, args)? { Prepared::Done(v) => Ok(v), @@ -3187,6 +3358,11 @@ impl Interp { self.enter_function(entry, None, true)?; self.execute() } + Prepared::Resume(r) => { + self.stack.truncate(saved); + self.enter_resumed(*r, true)?; + self.execute() + } } } @@ -3436,6 +3612,7 @@ impl Interp { construct: None, completion: Value::Undefined, boundary, + generator: None, }); Ok(()) } @@ -3836,7 +4013,11 @@ impl Interp { } let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) }; let k = self.to_prop_key(a)?; - self.has_pk(*o, &k).map(Value::Bool) + match &k { + PropKey::Str(name) => self.has_property_indexed(*o, name), + PropKey::Sym(_) => self.has_pk(*o, &k), + } + .map(Value::Bool) } } } @@ -4010,9 +4191,15 @@ impl Interp { /// A description of a thrown value that runs no JavaScript: `Name: message` for an error, /// the text of a primitive. pub(crate) fn describe(&mut self, v: &Value) -> String { - let Value::Object(o) = v else { return self.primitive_to_str(v).to_rust_string() }; + self.describe_prefix(v, usize::MAX) + } + + /// [`Interp::describe`] with each string it reads cut to its first `max_units` code units + /// before it is copied. + pub(crate) fn describe_prefix(&mut self, v: &Value, max_units: usize) -> String { + let Value::Object(o) = v else { return self.primitive_to_str(v).prefix_to_rust_string(max_units) }; let data = |interp: &Self, k: &str| match interp.find_property(*o, &key(k)) { - Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s.to_rust_string()), + Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s.prefix_to_rust_string(max_units)), _ => None, }; match (data(self, "name"), data(self, "message")) { @@ -4022,6 +4209,26 @@ impl Interp { (None, None) => format!("[object {}]", self.heap.object(*o).map_or("Object", |o| o.class.name())), } } + + /// The [`description_hash`] of the text [`Interp::describe`] gives for the object `o`, read + /// along its strings without copying them. + fn describe_hash(&self, o: ObjId) -> u64 { + let data = |k: &str| match self.find_property(o, &key(k)) { + Ok(Some(Prop::Data { value: Value::String(s), .. })) => Some(s), + _ => None, + }; + let mut h = DescriptionHash::default(); + match (data("name"), data("message")) { + (Some(n), Some(m)) if m.len() != 0 => { + n.for_each_chunk(|c| h.units(c)); + h.text(": "); + m.for_each_chunk(|c| h.units(c)); + } + (Some(s), _) | (None, Some(s)) => s.for_each_chunk(|c| h.units(c)), + (None, None) => h.text(&format!("[object {}]", self.heap.object(o).map_or("Object", |o| o.class.name()))), + } + h.finish() + } } /// A compile failure, before it becomes an exception or a run error. diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 586ae77e24..97f33ea054 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -613,6 +613,26 @@ fn apply_keeps_its_arguments_alive_while_a_native_function_runs() { assert_eq!(realm.run(src), Ok(JsValue::Number(42.0))); } +#[test] +fn successive_apply_expansions_keep_getter_receivers_alive() { + for queued in [false, true] { + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 1 << 20, ..Limits::default() }); + let src = "var result; function callback(a) { result = this.kept + a; } \ + var inner = {length: 1, get 0() { for (var i = 0; i < 20000; i++) ({i: i}); return 2; }}; \ + var outer = {length: 2, get 0() { return {kept: 40}; }, get 1() { return inner; }};"; + realm.run(src).unwrap(); + let collections = realm.interp().heap.collections; + let call = if queued { + "Promise.resolve(outer).then(Function.prototype.apply.bind(Function.prototype.apply, callback));" + } else { + "Function.prototype.apply.apply(callback, outer);" + }; + realm.run(call).unwrap(); + assert!(realm.interp().heap.collections > collections); + assert_eq!(realm.run("result"), Ok(JsValue::Number(42.0)), "queued: {queued}"); + } +} + #[test] fn to_number_skips_the_white_space_the_lexer_skips() { let mut realm = small(Limits::default()); @@ -995,6 +1015,7 @@ fn code(ops: Vec) -> Code { es2015: false, own_name: None, method: false, + generator: false, } } diff --git a/crates/js/src/iteration.rs b/crates/js/src/iteration.rs index 49a503f506..eac1d4abe6 100644 --- a/crates/js/src/iteration.rs +++ b/crates/js/src/iteration.rs @@ -162,7 +162,7 @@ impl Interp { /// IteratorClose (section 7.4.6) with a normal completion: calls the iterator's `return` /// method, unless it is done, and checks that it gives an object. - fn iter_close(&mut self, rec: ObjId) -> JsResult<()> { + pub(crate) fn iter_close(&mut self, rec: ObjId) -> JsResult<()> { let r = self.record(rec)?; if r.done { return Ok(()); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 0086d8ede6..a93dcd5483 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -26,7 +26,7 @@ //! with loops. The realm provides the language (sections 10 to 14 of ECMA-262 5.1) and these //! built-ins: the global functions and constants (15.1, with Annex B's `escape` and `unescape`), //! `Object` (15.2), `Function` with `call`, `apply` and `bind` (15.3), `Array` (15.4), `String` -//! (15.5), `Boolean.prototype`'s `toString` and `valueOf` (15.6.4), `Number` (15.7), `Math` (15.8), +//! (15.5), `Boolean` (15.6), `Number` (15.7), `Math` (15.8), //! `Date` (15.9), `RegExp` (15.10), the error types (15.11) and `JSON` (15.12). The array methods //! visit only the indices an array or array-like object has, so a sparse array of length 2^32-1 //! costs as much as its elements, and `JSON.parse`, `JSON.stringify` and the reviver walk use no @@ -63,7 +63,16 @@ //! closes its iterator. In a realm made without the option and later given it with //! [`Realm::set_es2015`], which has no `Symbol.iterator`, they walk arrays and `arguments` objects //! by index and strings by code point, and throw a `TypeError` for other values. -//! Object rest properties (`{ a, ...rest }`), classes, generators and modules stay syntax errors. +//! Object rest properties (`{ a, ...rest }`), classes and modules stay syntax errors. +//! +//! With [`Options::es2015`], the parser and the realm also have generators (ECMA-262 11th edition, +//! sections 14.4 and 25.4): `function*` declarations and expressions, `*name() {…}` methods in +//! object literals, `yield` and `yield*`, which passes `next`, `throw` and `return` on to the +//! iterator it delegates to, and generator objects with `next`, `return` and `throw` from +//! `%GeneratorPrototype%`, reached through `%GeneratorFunction%`. Outside a generator function's +//! body and parameters, `yield` stays an identifier in sloppy code. A generator's suspended frame +//! lives in the heap, each resumption takes fuel and counts against the frame limit, and resuming a +//! generator while its body runs is a `TypeError`. //! //! With [`Options::es2015`], the realm also has `Symbol` (ECMA-262 11th edition, section 19.4, //! ): `Symbol.for` and `Symbol.keyFor` over a registry @@ -78,6 +87,14 @@ //! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator //! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry //! entry counts against the heap limit. +//! +//! With [`Options::es2015`], the realm also provides `Promise` (ECMA-262 11th edition, section +//! 25.6, ): the constructor, `then`, +//! `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`. The promise +//! jobs a script queues run in order once its code has ended, before its run ends, on the run's +//! limits; a promise still rejected with no handler at the end is reported by +//! [`Realm::unhandled_rejections`]. [`Realm::add_es2015`] gives a realm made without the option +//! `Promise` for its next runs. #![forbid(unsafe_code)] pub mod ast; @@ -88,8 +105,10 @@ mod compiler; mod date_builtins; mod error; mod file_classes; +mod generator; mod heap; mod host; +mod host_classes; mod interp; mod iteration; mod lexer; @@ -117,9 +136,12 @@ pub use ast::{ pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; +pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; -pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; +pub use realm::{ + Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, Rejection, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE, +}; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; /// How a script is read. @@ -143,11 +165,12 @@ pub struct Options { /// `f?.()`) and `??`. Off, they are syntax errors and the language is ES5.1's. Code a /// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts. /// A realm made with it on also has the later editions' built-ins this engine has: `Symbol` - /// with Symbol-keyed properties and the iterators of arrays, strings and `arguments` objects. - /// A realm made with it off has the ES5.1 built-ins only, as the app's scripts expect. Those - /// built-ins are chosen when the realm is made: turning the option on or off later with - /// [`Realm::set_es2015`] changes the language later runs read, and does not add or remove - /// them. Runs with it on also convert `0b` and `0o` strings to numbers. + /// with Symbol-keyed properties, the iterators of arrays, strings and `arguments` objects, and + /// `Promise` with its job queue. A realm made with it off has the ES5.1 built-ins only, as the + /// app's scripts expect. Those built-ins are chosen when the realm is made: turning the option + /// on or off later with [`Realm::set_es2015`] changes the language later runs read, and does + /// not add or remove them; [`Realm::add_es2015`] adds `Promise` to a realm made without it. + /// Runs with it on also convert `0b` and `0o` strings to numbers. pub es2015: bool, } @@ -260,10 +283,14 @@ mod es2020_tests; #[cfg(test)] mod extension_tests; #[cfg(test)] +mod generator_tests; +#[cfg(test)] mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod promise_tests; +#[cfg(test)] mod symbol_tests; #[cfg(test)] mod tests; diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 0e25c141fe..b0b6870b67 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -37,6 +37,9 @@ struct Context { breakables: u32, /// The current function body's directive prologue has a `"use strict"` directive. use_strict: bool, + /// The code is a generator function's body or parameters: `yield` starts a yield expression + /// there and is not an identifier (ECMA-262 2015 sections 12.1.1 and 14.4). + generator: bool, } /// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations @@ -115,6 +118,9 @@ pub(crate) struct Parser<'s> { /// section B.3.1). Each is also in `cover_inits`, so it is a `SyntaxError` unless the literal /// is read as a destructuring pattern. proto_twice: HashSet, + /// Where each yield expression read so far starts, in the order read, so the parameters of a + /// generator function and an arrow function's head can be checked for one. + yields: Vec, } impl<'s> Parser<'s> { @@ -143,6 +149,7 @@ impl<'s> Parser<'s> { cover_ok: false, rest_commas: HashSet::new(), proto_twice: HashSet::new(), + yields: Vec::new(), }; parser.tok = parser.next_significant()?; Ok(parser) @@ -284,9 +291,18 @@ impl<'s> Parser<'s> { if self.ctx.strict && strict_reserved(name) { return Err(self.error_at_token(token, format!("'{name}' is a reserved word in strict mode"))); } + if self.ctx.generator && name == "yield" { + return Err(self.error_at_token(token, "'yield' cannot be an identifier in a generator function")); + } Ok(()) } + /// A yield expression starts at `offset` or later, before `end`. + fn yield_between(&self, offset: u32, end: u32) -> bool { + let i = self.yields.partition_point(|&y| y < offset); + self.yields.get(i).is_some_and(|&y| y < end) + } + /// Reads an identifier that a declaration binds: checked as [`Self::check_identifier`] does, /// and in strict code neither `eval` nor `arguments`. fn binding_identifier(&mut self) -> Result { @@ -359,7 +375,7 @@ impl<'s> Parser<'s> { /// Declares a function declaration that stands in a statement list: var-scoped in a function /// body or the script, lexical in a block. fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> { - let Some(name) = self.ast.function(id).and_then(|f| f.name.clone()) else { return Ok(()) }; + let Some((name, generator)) = self.ast.function(id).and_then(|f| Some((f.name.clone()?, f.generator))) else { return Ok(()) }; match self.scopes.last_mut() { Some(scope) if scope.function => { if scope.lexical.contains_key(&name.name) { @@ -368,7 +384,8 @@ impl<'s> Parser<'s> { scope.vars.insert(name.name); Ok(()) } - Some(_) => self.declare_lexical(&name, true), + // Only plain function declarations may repeat in a block (Annex B.3.3.4). + Some(_) => self.declare_lexical(&name, !generator), None => Ok(()), } } @@ -532,6 +549,9 @@ impl<'s> Parser<'s> { }; return Err(self.error_at_token(&self.tok, message)); } + if self.es2015 && self.peek().is_some_and(|t| t.is_punct(Punct::Star)) { + return Err(self.error_at_token(&self.tok, "a generator declaration cannot stand here; put it in a block")); + } self.parse_function_declaration() } TokenKind::Ident(_) if self.peek().is_some_and(|t| t.is_punct(Punct::Colon)) => self.parse_labeled(in_list), @@ -1039,8 +1059,9 @@ impl<'s> Parser<'s> { fn parse_function_declaration(&mut self) -> Result { let start = self.expect_keyword(Keyword::Function)?.span; + let generator = self.es2015 && self.eat(Punct::Star)?; let name = self.function_name()?; - let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start)?; + let id = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator)?; Ok(self.ast.push_stmt(Stmt::FunctionDecl(id), self.span_from(start))) } @@ -1056,15 +1077,28 @@ impl<'s> Parser<'s> { Ok((Name { name, span: token.span }, token)) } - /// The parameters and body of a function, from `(`. - fn parse_function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + /// The parameters and body of a function, from `(`; with `generator`, a generator function's. + fn parse_function_rest( + &mut self, + kind: FunctionKind, + name: Option<(Name, Token)>, + start: Span, + generator: bool, + ) -> Result { self.enter()?; - let result = self.function_rest(kind, name, start); + // The parameters are read with the function's own `yield` rule, not the enclosing code's. + let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); + let yields = self.yields.len(); + let result = self.function_rest(kind, name, start, generator); + // The `yield` expressions of this function are not in the code around it. + self.yields.truncate(yields); + self.ctx.generator = outer_generator; self.leave(); result } - fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result { + fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span, generator: bool) -> Result { + let params_start = self.tok.span.start; self.expect(Punct::LParen)?; let mut params: Vec = Vec::new(); let mut defaults: Vec> = Vec::new(); @@ -1097,6 +1131,10 @@ impl<'s> Parser<'s> { } } let close = self.expect(Punct::RParen)?; + if generator && self.yield_between(params_start, close.span.start) { + let at = self.yields.get(self.yields.partition_point(|&y| y < params_start)).copied().unwrap_or(params_start); + return Err(self.error_at_offset(at, "a yield expression cannot stand in a generator function's parameters")); + } match kind { FunctionKind::Getter if !params.is_empty() || rest.is_some() => { return Err(self.error_at_token(&close, "a getter must not have parameters")); @@ -1112,7 +1150,7 @@ impl<'s> Parser<'s> { self.expect(Punct::LBrace)?; let names: Vec = params.iter().chain(&rest).flat_map(|p| self.ast.bound_names(p)).map(|n| n.name).collect(); let outer_strict = self.ctx.strict; - let inner = Context { strict: outer_strict, in_function: true, ..Context::default() }; + let inner = Context { strict: outer_strict, in_function: true, generator, ..Context::default() }; let outer = std::mem::replace(&mut self.ctx, inner); self.push_scope(true, names); let body = self.parse_body(true); @@ -1121,7 +1159,7 @@ impl<'s> Parser<'s> { self.ctx = outer; let body = body?; self.expect(Punct::RBrace)?; - let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, generator, span: self.span_from(start) }; self.check_params(&function, use_strict)?; Ok(self.ast.push_function(function)) } @@ -1153,7 +1191,8 @@ impl<'s> Parser<'s> { self.expect(Punct::RBrace)?; } let defaults = if defaults.iter().all(Option::is_none) { Vec::new() } else { defaults }; - let function = Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, span: self.span_from(start) }; + let function = + Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, generator: false, span: self.span_from(start) }; self.check_params(&function, use_strict)?; let id = self.ast.push_function(function); Ok(self.ast.push_expr(Expr::Arrow(id), self.span_from(start))) @@ -1271,10 +1310,15 @@ impl<'s> Parser<'s> { fn assignment(&mut self, no_in: bool) -> Result { let mut targets: Vec<(ExprId, AssignOp)> = Vec::new(); loop { - let mut expr = self.parse_conditional(no_in)?; - if self.es2015 && self.at(Punct::Arrow) { - expr = self.arrow_from(expr, no_in)?; - } + let expr = if self.ctx.generator && self.tok.ident() == Some("yield") && !self.tok.escaped { + self.parse_yield(no_in)? + } else { + let mut expr = self.parse_conditional(no_in)?; + if self.es2015 && self.at(Punct::Arrow) { + expr = self.arrow_from(expr, no_in)?; + } + expr + }; let Some(op) = assign_op(&self.tok) else { let mut value = expr; while let Some((target, op)) = targets.pop() { @@ -1293,10 +1337,28 @@ impl<'s> Parser<'s> { } } + /// A yield expression, from `yield` (ECMA-262 2015 section 14.4): its operand is left out when + /// a line break follows `yield` or the next token cannot start an expression, and `yield*` + /// must have one. + fn parse_yield(&mut self, no_in: bool) -> Result { + let start = self.bump()?.span; + self.yields.push(start.start); + let delegate = !self.tok.newline_before && self.at(Punct::Star); + if delegate { + self.bump()?; + } + let arg = + if delegate || (!self.tok.newline_before && starts_expression(&self.tok, self.e4x)) { Some(self.parse_assignment(no_in)?) } else { None }; + Ok(self.ast.push_expr(Expr::Yield { arg, delegate }, self.span_from(start))) + } + /// The arrow function whose head is `expr`, read before the current `=>`: a name standing /// alone, or parameters in parentheses. fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result { let start = self.ast.expr_span(expr); + if self.yield_between(start.start, start.end) { + return Err(self.error_at_offset(start.start, "a yield expression cannot stand in an arrow function's parameters")); + } let params = match self.ast.expr(expr) { Some(Expr::Ident(name)) => (vec![Binding::Name(Name { name: name.clone(), span: start })], vec![None], None), Some(Expr::Paren(_)) => self.arrow_params(expr)?, @@ -1706,8 +1768,13 @@ impl<'s> Parser<'s> { fn parse_function_expression(&mut self) -> Result { let start = self.expect_keyword(Keyword::Function)?.span; - let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { Some(self.function_name()?) } else { None }; - let id = self.parse_function_rest(FunctionKind::Expression, name, start)?; + let generator = self.es2015 && self.eat(Punct::Star)?; + // A generator expression's name is read with its own `yield` rule. + let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); + let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name().map(Some) } else { Ok(None) }; + self.ctx.generator = outer_generator; + let name = name?; + let id = self.parse_function_rest(FunctionKind::Expression, name, start, generator)?; Ok(self.ast.push_expr(Expr::Function(id), self.span_from(start))) } @@ -1790,7 +1857,7 @@ impl<'s> Parser<'s> { let word = self.bump()?; if property_key(&self.tok).is_some() { let (key, _) = self.parse_property_key()?; - let function = self.parse_function_rest(kind, None, start)?; + let function = self.parse_function_rest(kind, None, start, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } @@ -1829,6 +1896,42 @@ fn property_key(token: &Token) -> Option { } } +/// The token can start an expression, so a `yield` before it on the same line takes an operand. +fn starts_expression(token: &Token, e4x: bool) -> bool { + match &token.kind { + TokenKind::Ident(_) | TokenKind::Number(_) | TokenKind::String(_) | TokenKind::Template { .. } | TokenKind::RegExp { .. } => true, + TokenKind::Keyword(k) => matches!( + k, + Keyword::This + | Keyword::Null + | Keyword::True + | Keyword::False + | Keyword::Function + | Keyword::New + | Keyword::Delete + | Keyword::Void + | Keyword::Typeof + ), + TokenKind::Punct(p) => { + matches!( + p, + Punct::LParen + | Punct::LBracket + | Punct::LBrace + | Punct::Plus + | Punct::Minus + | Punct::Bang + | Punct::Tilde + | Punct::PlusPlus + | Punct::MinusMinus + | Punct::Slash + | Punct::SlashEq + ) || (e4x && matches!(p, Punct::Lt | Punct::At)) + } + _ => false, + } +} + fn is_eval_or_arguments(name: &str) -> bool { name == "eval" || name == "arguments" } diff --git a/crates/js/src/parser/pattern.rs b/crates/js/src/parser/pattern.rs index 27d684ced2..a616adc805 100644 --- a/crates/js/src/parser/pattern.rs +++ b/crates/js/src/parser/pattern.rs @@ -146,6 +146,12 @@ impl Parser<'_> { /// initializer (`a = 1`), which only a pattern may hold. pub(super) fn parse_property_es2015(&mut self) -> Result { let start = self.tok.span; + // `*name(…) {…}`: a generator method (ECMA-262 2015 section 14.4). + if self.eat(Punct::Star)? { + let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 }; + let function = self.parse_function_rest(FunctionKind::Method, None, start, true)?; + return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) }); + } // `get` and `set` start an accessor only when written without escapes and followed by a // property name. let accessor = match self.tok.ident().filter(|_| !self.tok.escaped) { @@ -158,7 +164,7 @@ impl Parser<'_> { { self.bump()?; let key = if self.at(Punct::LBracket) { self.computed_key()? } else { self.parse_property_key()?.0 }; - let function = self.parse_function_rest(kind, None, start)?; + let function = self.parse_function_rest(kind, None, start, false)?; let value = if kind == FunctionKind::Getter { PropertyValue::Get(function) } else { PropertyValue::Set(function) }; return Ok(Property { key, value, span: self.span_from(start) }); } @@ -192,7 +198,7 @@ impl Parser<'_> { /// the value may still turn out to be a pattern. fn cover_property_value(&mut self, key: PropertyKey, start: Span) -> Result { if self.at(Punct::LParen) { - let function = self.parse_function_rest(FunctionKind::Method, None, start)?; + let function = self.parse_function_rest(FunctionKind::Method, None, start, false)?; return Ok(Property { key, value: PropertyValue::Method(function), span: self.span_from(start) }); } self.expect(Punct::Colon)?; diff --git a/crates/js/src/promise_tests.rs b/crates/js/src/promise_tests.rs new file mode 100644 index 0000000000..01abc2c92e --- /dev/null +++ b/crates/js/src/promise_tests.rs @@ -0,0 +1,529 @@ +//! `Promise` and the promise job queue in realms with [`Options::es2015`]. + +use super::*; + +fn realm() -> Realm { + Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default()) +} + +fn run(src: &str) -> JsValue { + match realm().run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// Runs `src`, which writes to the global `log`, and gives `log` after the jobs ran. +fn log(src: &str) -> String { + let mut r = realm(); + if let Err(e) = r.run(&format!("var log = [];\n{src}")) { + panic!("{src}\n{e:?}"); + } + match r.run("log.join(' ')") { + Ok(JsValue::String(s)) => s, + other => panic!("{src}: {other:?}"), + } +} + +#[test] +fn an_extendscript_realm_has_no_promise() { + assert_eq!(Realm::new().run("typeof Promise").unwrap(), JsValue::String("undefined".into())); + assert_eq!(string("typeof Promise"), "function"); +} + +#[test] +fn adding_promise_leaves_the_language_and_the_other_built_ins_as_they_were() { + let mut r = Realm::new(); + r.add_es2015(); + assert_eq!(r.run("typeof Promise").unwrap(), JsValue::String("function".into())); + assert_eq!(r.run("typeof Symbol").unwrap(), JsValue::String("undefined".into())); + assert!(matches!(r.run("let a = 1;"), Err(RunError { kind: RunErrorKind::Syntax, .. }))); + r.set_es2015(true); + assert_eq!(r.run("let b = 2; b").unwrap(), JsValue::Number(2.0)); +} + +#[test] +fn promise_prototype_cannot_be_replaced() { + let src = "var before = Promise.prototype; Promise.prototype = {}; \ + var p = new Promise(function () {}); \ + [Promise.prototype === before, Object.getPrototypeOf(p) === before, p instanceof Promise].join()"; + assert_eq!(string(src), "true,true,true"); +} + +#[test] +fn promise_prototype_has_a_configurable_string_tag() { + assert_eq!( + string( + "var d = Object.getOwnPropertyDescriptor(Promise.prototype, Symbol.toStringTag); \ + [Object.prototype.toString.call(Promise.prototype), \ + Object.prototype.toString.call(Promise.resolve()), \ + d.value, d.writable, d.enumerable, d.configurable].join()" + ), + "[object Promise],[object Promise],Promise,false,false,true" + ); + let mut r = Realm::new(); + r.add_es2015(); + assert_eq!(r.run("Object.prototype.toString.call(Promise.resolve())").unwrap(), JsValue::String("[object Promise]".into())); +} + +#[test] +fn then_callbacks_run_after_the_scripts_code_in_order() { + let src = "Promise.resolve(1).then(function (v) { log.push('a' + v); });\n\ + new Promise(function (res) { log.push('executor'); res(2); }).then(function (v) { log.push('b' + v); });\n\ + log.push('sync');"; + assert_eq!(log(src), "executor sync a1 b2"); +} + +#[test] +fn jobs_run_first_in_first_out_and_a_jobs_jobs_join_the_end() { + let src = "var p = Promise.resolve();\n\ + p.then(function () { log.push(1); Promise.resolve().then(function () { log.push(4); }); });\n\ + p.then(function () { log.push(2); });\n\ + p.then(function () { log.push(3); });"; + assert_eq!(log(src), "1 2 3 4"); +} + +#[test] +fn a_thenable_is_adopted_in_a_later_job() { + let src = "var thenable = { then: function (res) { log.push('then'); res(7); } };\n\ + Promise.resolve(thenable).then(function (v) { log.push('got' + v); });\n\ + log.push('sync');"; + assert_eq!(log(src), "sync then got7"); + let rejecting = "var t = { then: function (res, rej) { rej('no'); res(1); } };\n\ + new Promise(function (res) { res(t); }).then(null, function (r) { log.push('rejected ' + r); });"; + assert_eq!(log(rejecting), "rejected no"); + let throwing = "var t = { then: function (res) { res(1); throw new Error('late'); } };\n\ + Promise.resolve(t).then(function (v) { log.push('kept ' + v); });"; + assert_eq!(log(throwing), "kept 1"); +} + +#[test] +fn a_promise_resolved_with_itself_rejects_with_a_type_error() { + let src = "var res; var p = new Promise(function (r) { res = r; }); res(p);\n\ + p.then(null, function (e) { log.push(e instanceof TypeError); });"; + assert_eq!(log(src), "true"); +} + +#[test] +fn collections_while_a_promise_is_resolved_with_itself_keep_its_type_error() { + let src = "var bad = 0; function check(e) { if (!(e instanceof TypeError)) bad++; }\n\ + for (var i = 0; i < 200; i++) { var res; var p = new Promise(function (r) { res = r; }); p.then(null, check); res(p); }"; + let mut finished = 0; + for spare in (40_000..240_000).step_by(641) { + let mut r = realm(); + let live = r.collect_garbage(); + r.set_limits(Limits { heap_bytes: live + spare, ..Limits::default() }); + match r.run(src) { + Ok(_) => finished += 1, + Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => continue, + Err(e) => panic!("{spare}: {e:?}"), + } + r.set_limits(Limits::default()); + assert_eq!(r.run("bad"), Ok(JsValue::Number(0.0)), "{spare}"); + } + assert!(finished > 0); +} + +#[test] +fn catch_finally_and_the_combinators_settle_as_the_specification_says() { + let src = "Promise.reject(new Error('x')).catch(function (e) { log.push('caught ' + e.message); });\n\ + Promise.resolve(5).finally(function () { log.push('finally'); return 9; }).then(function (v) { log.push('kept ' + v); });\n\ + Promise.all([1, Promise.resolve(2), { then: function (r) { r(3); } }]).then(function (v) { log.push('all ' + v.join(',')); });\n\ + Promise.allSettled([Promise.reject('r'), 4]).then(function (v) { log.push(v[0].status + ':' + v[0].reason + ' ' + v[1].status + ':' + v[1].value); });\n\ + Promise.race([new Promise(function () {}), Promise.resolve('fast')]).then(function (v) { log.push('race ' + v); });\n\ + Promise.all('ab').then(function (v) { log.push('chars ' + v.length); });\n\ + Promise.all(5).then(null, function (e) { log.push('not a list ' + (e instanceof TypeError)); });\n\ + Promise.race(new Error('e')).then(null, function (e) { log.push('no length ' + (e instanceof TypeError)); });\n\ + Promise.all({ length: 1.5 }).then(null, function (e) { log.push('bad length ' + (e instanceof TypeError)); });"; + let out = log(src); + for part in [ + "caught x", + "finally", + "kept 5", + "all 1,2,3", + "rejected:r fulfilled:4", + "race fast", + "chars 2", + "not a list true", + "no length true", + "bad length true", + ] { + assert!(out.contains(part), "{part} in {out}"); + } +} + +#[test] +fn promise_combinator_iterators_use_custom_values_and_boxed_string_code_points() { + let src = "var input = {}; input[Symbol.iterator] = function () {\n\ + var n = 0; return { next: function () { return n < 2 ? { value: ++n, done: false } : { done: true }; } };\n\ + };\n\ + Promise.all(input).then(function (v) { log.push('all ' + v.join(',')); });\n\ + Promise.allSettled(input).then(function (v) { log.push('settled ' + v[0].value + ',' + v[1].value); });\n\ + Promise.race(input).then(function (v) { log.push('race ' + v); });\n\ + var a = [99]; a[Symbol.iterator] = input[Symbol.iterator];\n\ + Promise.all(a).then(function (v) { log.push('array ' + v.join(',')); });\n\ + Promise.all(new String('\u{1d306}x')).then(function (v) { log.push('string ' + v.length + ',' + v[0].length); });"; + let out = log(src); + for expected in ["all 1,2", "settled 1,2", "race 1", "array 1,2", "string 2,2"] { + assert!(out.contains(expected), "{expected} in {out}"); + } +} + +#[test] +fn promise_combinator_iterators_close_after_resolve_or_then_throws() { + let src = "function check(name, failure) {\n\ + var closed = 0, input = {};\n\ + input[Symbol.iterator] = function () { return {\n\ + next: function () { return { value: 1, done: false }; },\n\ + return: function () { closed++; throw 'close'; }\n\ + }; };\n\ + Promise.resolve = failure === 'resolve' ? function () { throw 'resolve'; } :\n\ + function () { return { get then() { throw 'then'; } }; };\n\ + Promise[name](input).then(null, function (e) { log.push(name + ':' + failure + ':' + e + ':' + closed); });\n\ + }\n\ + var original = Promise.resolve;\n\ + for (var i = 0; i < 3; i++) { var name = ['all', 'allSettled', 'race'][i]; check(name, 'resolve'); check(name, 'then'); }\n\ + Promise.resolve = original;"; + let out = log(src); + for name in ["all", "allSettled", "race"] { + for failure in ["resolve", "then"] { + let expected = format!("{name}:{failure}:{failure}:1"); + assert!(out.contains(&expected), "{expected} in {out}"); + } + } +} + +#[test] +fn promise_combinator_iterators_do_not_close_when_the_step_throws_or_finishes() { + let src = "var closed = 0;\n\ + function input(failure) { var o = {}; o[Symbol.iterator] = function () { return {\n\ + next: function () { if (failure === 'next') throw failure;\n\ + return { get done() { if (failure === 'done') throw failure; return false; },\n\ + get value() { throw failure; } }; },\n\ + return: function () { closed++; return {}; }\n\ + }; }; return o; }\n\ + for (var i = 0; i < 3; i++) {\n\ + Promise.all(input(['next', 'done', 'value'][i])).then(null, function (e) { log.push(e); });\n\ + }\n\ + var empty = {}; empty[Symbol.iterator] = function () { return {\n\ + next: function () { return { done: true }; }, return: function () { closed++; return {}; }\n\ + }; };\n\ + Promise.all(empty).then(function (v) { log.push('empty ' + v.length); });\n\ + Promise.race(empty).then(function () { log.push('race settled'); });\n\ + log.push('closed ' + closed);"; + let out = log(src); + for expected in ["next", "done", "value", "empty 0", "closed 0"] { + assert!(out.contains(expected), "{expected} in {out}"); + } + assert!(!out.contains("race settled"), "{out}"); +} + +#[test] +fn the_combinators_read_an_array_to_its_changing_length_and_reject_noniterable_array_likes() { + // `Promise.resolve` runs once for each input and appends to the input while it is read. + let src = "var resolve = Promise.resolve; var input;\n\ + Promise.resolve = function (x) {\n\ + if (input.length < 3) { input[input.length] = x + 1; if (!(input instanceof Array)) input.length++; }\n\ + return resolve.call(this, x);\n\ + };\n\ + input = [1]; Promise.all(input).then(function (v) { log.push('array ' + v.join(',')); });\n\ + input = { length: 1, 0: 1 }; Promise.all(input).then(null, function (e) { log.push('object ' + (e instanceof TypeError)); });"; + let out = log(src); + assert!(out.contains("array 1,2,3"), "{out}"); + assert!(out.contains("object true"), "{out}"); +} + +#[test] +fn a_string_a_combinator_reads_is_charged_to_the_heap_before_it_is_flattened() { + // A rope of 4 Mi code units is a few nodes until it is flattened to 8 MiB, more than the heap + // has room for. The combinator would stop at its first input. + let mut r = realm(); + r.run("var s = 'ab'; for (var i = 0; i < 21; i++) s = s + s; var calls = 0; Promise.resolve = function () { calls++; throw 'stop'; };").unwrap(); + let live = r.collect_garbage(); + r.set_limits(Limits { heap_bytes: live + (1 << 20), ..Limits::default() }); + let e = r.run("Promise.race(s)").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}"); + r.set_limits(Limits::default()); + assert_eq!(r.run("calls").unwrap(), JsValue::Number(0.0)); +} + +#[test] +fn calling_promise_without_new_or_without_an_executor_is_a_type_error() { + let mut r = realm(); + for src in [ + "Promise(function () {})", + "new Promise(1)", + "Promise.prototype.then.call({}, null)", + "Promise.resolve.call(1, 2)", + "Promise.all.call(Math.max, [])", + "Promise.resolve.call(() => {}, 1)", + "Promise.reject.call({ m() {} }.m, 1)", + "Promise.race.call((() => {}).bind(null), [])", + ] { + match r.run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with("TypeError"), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } + } +} + +#[test] +fn an_unhandled_rejection_is_reported_with_its_line() { + let mut r = realm(); + r.run("var a = 1;\nPromise.reject(new Error('lost'));\nnew Promise(function () {\n throw new TypeError('also');\n});\nPromise.reject(2).catch(function () {});") + .unwrap(); + let got: Vec<(String, u32)> = r.unhandled_rejections().iter().map(|j| (j.message.clone(), j.line)).collect(); + assert_eq!(got, vec![("Error: lost".to_string(), 2), ("TypeError: also".to_string(), 4)]); + assert_eq!(r.unhandled_rejection_count(), 2); + assert!(r.unhandled_rejections().iter().all(|j| j.authored)); +} + +#[test] +fn a_long_rejection_reason_is_reported_cut_to_its_first_500_characters() { + let mut r = realm(); + r.run( + "function rep(t, n) { var s = ''; for (var i = 0; i < n; i++) s = s + t; return s; }\n\ + var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\ + Promise.reject(ab);\n\ + Promise.reject(new RangeError(ab));\n\ + Promise.reject(rep('\\ud83d\\ude00', 600));\n\ + Promise.reject(rep('x', 500));", + ) + .unwrap(); + let got: Vec = r.unhandled_rejections().iter().map(|j| j.message.clone()).collect(); + let want = vec![ + format!("{}…", "ab".repeat(250)), + format!("RangeError: {}…", "ab".repeat(244)), + format!("{}…", "\u{1F600}".repeat(500)), + "x".repeat(500), + ]; + assert_eq!(got, want); +} + +#[test] +fn combinator_rejection_relays_keep_the_input_location() { + for method in ["all", "race"] { + let mut r = realm(); + r.run(&format!("var input =\n Promise.reject('lost');\nPromise.{method}([input]);")).unwrap(); + let reported = r.unhandled_rejections(); + assert_eq!(reported.len(), 1, "{method}: {reported:?}"); + assert_eq!(reported[0].line, 2, "{method}: {:?}", reported[0]); + assert!(reported[0].column > 0); + assert_eq!(reported[0].tag, r.script_tag()); + } + let mut r = realm(); + r.run("var reject; new Promise(function (_, no) { reject = no; });\nPromise.reject('handled').catch(function () {\n reject('lost');\n});") + .unwrap(); + assert_eq!(r.unhandled_rejections().len(), 1); + assert_eq!(r.unhandled_rejections()[0].line, 3); + assert!(r.unhandled_rejections()[0].column > 0); + let mut r = realm(); + r.run("eval(\"Promise.reject('eval')\"); Function(\"Promise.reject('function')\")();").unwrap(); + let reported = r.unhandled_rejections(); + assert_eq!(reported.len(), 2); + assert!(reported.iter().all(|r| r.tag == UNKNOWN_SOURCE), "{reported:?}"); +} + +#[test] +fn an_interpreter_error_given_a_long_message_is_reported_as_the_scripts_text_without_copying_it() { + let mut r = realm(); + r.run( + "var ab = 'ab'; for (var i = 0; i < 16; i++) ab = ab + ab;\n\ + var e; try { null.x; } catch (x) { e = x; }\n\ + e.message = ab;\n\ + Promise.reject(e);\n\ + try { null.x; } catch (x) { Promise.reject(x); }", + ) + .unwrap(); + let got: Vec<(String, bool)> = r.unhandled_rejections().iter().map(|j| (j.message.clone(), j.authored)).collect(); + assert_eq!(got.len(), 2); + assert_eq!(got[0], (format!("TypeError: {}a…", "ab".repeat(244)), true)); + assert!(!got[1].1, "an error the interpreter threw, unchanged: {:?}", got[1]); + let interp = r.interp(); + match interp.find_property(interp.global, &crate::heap::key("ab")) { + Ok(Some(crate::heap::Prop::Data { value: crate::value::Value::String(s), .. })) => assert!(s.is_rope(), "the message was flattened"), + other => panic!("{other:?}"), + } +} + +#[test] +fn a_rejection_handled_in_a_later_job_is_not_reported() { + let mut r = realm(); + r.run("var p = Promise.reject(1); Promise.resolve().then(function () { p.catch(function () {}); });").unwrap(); + assert!(r.unhandled_rejections().is_empty()); + assert_eq!(r.unhandled_rejection_count(), 0); +} + +#[test] +fn a_run_that_fails_reports_no_rejections_and_drops_its_jobs() { + let mut r = realm(); + let e = r.run("var ran = false; Promise.reject(1); Promise.resolve().then(function () { ran = true; }); throw 'stop';").unwrap_err(); + assert_eq!((e.kind, e.message.as_str()), (RunErrorKind::Thrown, "stop")); + assert!(r.unhandled_rejections().is_empty()); + assert_eq!(r.run("ran").unwrap(), JsValue::Bool(false)); +} + +#[test] +fn an_endless_then_chain_is_stopped_by_fuel() { + let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 200_000, ..Limits::default() }); + let e = r.run("function again() { return Promise.resolve().then(again); } again();").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); + let e = r.run("var res; var p = new Promise(function (r) { res = r; }); function loop() { p.then(loop); } p.then(loop); res(1);").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel)); + assert!(!r.is_running()); +} + +#[test] +fn each_job_takes_fuel() { + // `then` on a settled promise queues a job, and on a pending one it does not; the difference in + // fuel between 50 calls and none is the jobs' fuel. + let used = |start: &str, calls: usize| { + let mut r = realm(); + r.set_limits(Limits { fuel: 1_000_000, ..Limits::default() }); + r.run(&format!("var p = {start};{}", "p.then();".repeat(calls))).unwrap(); + 1_000_000 - r.fuel_left() + }; + let settled = used("Promise.resolve()", 50) - used("Promise.resolve()", 0); + let pending = used("new Promise(function () {})", 50) - used("new Promise(function () {})", 0); + assert_eq!(settled - pending, 50); +} + +#[test] +fn more_jobs_than_the_queue_holds_end_the_run_with_a_clear_error() { + let mut r = realm(); + r.interp().promises.max_jobs = 100; + let e = r.run("var p = Promise.resolve(); for (var i = 0; i < 200; i++) p.then(function () {});").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Jobs)); + assert!(e.message.contains("more than 100 promise jobs"), "{}", e.message); + assert!(r.run("var q = Promise.resolve(); for (var i = 0; i < 50; i++) q.then(function () {}); 1").is_ok()); +} + +#[test] +fn a_sliced_run_pauses_inside_the_jobs_and_ends_once_the_queue_is_empty() { + let mut r = realm(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + r.start("var t = 0; Promise.resolve().then(function () { for (var i = 0; i < 5000; i++) t += i; }); 'done'").unwrap(); + let mut paused_in_jobs = 0; + let v = loop { + match r.advance(500).unwrap() { + Progress::Paused => { + if r.interp().promises.draining { + paused_in_jobs += 1; + } + } + Progress::Done(v) => break v, + } + }; + assert_eq!(v, JsValue::String("done".into())); + assert!(paused_in_jobs > 1, "{paused_in_jobs}"); + assert!(!r.is_running()); + assert_eq!(r.run("t").unwrap(), JsValue::Number(12_497_500.0)); +} + +#[test] +fn a_sliced_run_whose_last_job_ends_a_slice_is_done_in_that_slice() { + let mut r = realm(); + r.start("Promise.resolve().then(); Promise.reject(1).then(null, function () {}); 'done'").unwrap(); + let v = loop { + match r.advance(1).unwrap() { + Progress::Paused => { + let interp = r.interp(); + assert!(!interp.frames.is_empty() || interp.promises.queue_size().0 > 0, "paused with nothing left to run"); + } + Progress::Done(v) => break v, + } + }; + assert_eq!(v, JsValue::String("done".into())); + assert!(!r.is_running()); +} + +#[test] +fn a_pause_the_last_job_asks_for_does_not_pause_the_next_run() { + let mut r = realm(); + let flag = r.pause_flag(); + r.define_function("pauseNow", move |_| { + flag.set(true); + Ok(JsValue::Undefined) + }); + r.start("Promise.resolve().then(pauseNow); 'first'").unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::String("first".into()))); + r.start("var a = 1; var b = 2; a + b").unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::Number(3.0))); +} + +#[test] +fn a_sliced_run_pauses_inside_a_finally_callback() { + let mut r = realm(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + r.set_unbroken_fuel(5_000); + r.start( + "var t = 0, kept, caught; function work() { for (var i = 0; i < 5000; i++) t += i; return Promise.resolve('ignored'); }\n\ + Promise.resolve(1).finally(work).then(function (v) { kept = v; });\n\ + Promise.reject(2).finally(work).then(null, function (e) { caught = e; });\n\ + 'done'", + ) + .unwrap(); + let mut paused_in_jobs = 0; + let v = loop { + match r.advance(500).unwrap() { + Progress::Paused => { + if r.interp().promises.draining { + paused_in_jobs += 1; + } + } + Progress::Done(v) => break v, + } + }; + assert_eq!(v, JsValue::String("done".into())); + assert!(paused_in_jobs > 10, "{paused_in_jobs}"); + assert_eq!(r.run("t + ' ' + kept + ' ' + caught").unwrap(), JsValue::String("24995000 1 2".into())); +} + +#[test] +fn a_finally_callback_that_returns_a_pending_promise_holds_the_result_until_a_later_run_settles_it() { + let mut r = realm(); + r.run( + "var log = [], settle = {};\n\ + function wait(name) { return function () { return new Promise(function (res, rej) { settle[name] = { res: res, rej: rej }; }); }; }\n\ + function report(name) { return [function (v) { log.push(name + ' kept ' + v); }, function (e) { log.push(name + ' rejected ' + e); }]; }\n\ + var a = report('a'), b = report('b'), c = report('c'), d = report('d');\n\ + Promise.resolve(1).finally(wait('a')).then(a[0], a[1]);\n\ + Promise.reject(2).finally(wait('b')).then(b[0], b[1]);\n\ + Promise.resolve(3).finally(wait('c')).then(c[0], c[1]);\n\ + Promise.reject(4).finally(wait('d')).then(d[0], d[1]);", + ) + .unwrap(); + assert_eq!(r.run("Object.keys(settle).sort().join(' ') + '|' + log.join(' ')").unwrap(), JsValue::String("a b c d|".into())); + r.collect_garbage(); + r.run("settle.a.res('ignored'); settle.b.res('ignored'); settle.c.rej('new c'); settle.d.rej('new d');").unwrap(); + assert_eq!(r.run("log.join(', ')").unwrap(), JsValue::String("a kept 1, b rejected 2, c rejected new c, d rejected new d".into())); +} + +#[test] +fn an_ended_sliced_run_drops_its_jobs() { + let mut r = realm(); + r.start( + "var ran = 0, after = false; Promise.resolve().then(function () { for (;;) ran++; }); Promise.resolve().then(function () { after = true; });", + ) + .unwrap(); + let mut slices = 0; + while r.advance(500).unwrap() == Progress::Paused && !r.interp().promises.draining { + slices += 1; + assert!(slices < 1000); + } + assert!(r.is_running()); + assert_eq!(r.interp().promises.queue_size().0, 1); + r.end(); + assert!(!r.is_running()); + assert_eq!(r.interp().promises.queue_bytes(), 0); + assert_eq!(r.interp().promises.queue_size(), (0, 0)); + assert_eq!(r.run("typeof ran").unwrap(), JsValue::String("number".into())); + assert_eq!(r.run("after").unwrap(), JsValue::Bool(false)); +} diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 9daf4b9e9d..bd191b0463 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -57,6 +57,23 @@ pub enum LimitKind { Unbroken, /// A host function ended the run ([`crate::HostError::Abort`]). Host, + /// More promise jobs were waiting to run than a run may queue. + Jobs, +} + +/// A promise the last run rejected that still had no rejection handler when the run ended +/// ([`Realm::unhandled_rejections`]). `line` and `column` are where it was rejected: the `throw`, +/// or the call to its reject function or `Promise.reject`; they are 0 when that is not known. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Rejection { + /// The reason, described as an uncaught exception's message is. + pub message: String, + pub line: u32, + pub column: u32, + /// The source tag of the code `line` and `column` are in ([`Realm::error_tag`]). + pub tag: u32, + /// `message` is text the script supplied ([`RunError::authored`]). + pub authored: bool, } /// The tag [`Realm::error_source`] gives for a source that is neither the realm's script nor an @@ -172,6 +189,8 @@ pub struct Realm { /// before the first script, for a script the realm did not compile, and once the tags are used /// up. script_tag: u32, + /// The unhandled rejections of the last run that ended successfully, and how many there were. + rejections: (Vec, usize), } impl Default for Realm { @@ -189,7 +208,7 @@ impl Realm { /// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it /// counted together. pub fn with_options(options: Options, limits: Limits) -> Self { - Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE } + Self { interp: Interp::new(options, limits), unbroken_fuel: MAX_UNBROKEN_FUEL, script_tag: UNKNOWN_SOURCE, rejections: (Vec::new(), 0) } } /// Sets the fuel [`Realm::advance`] lets a nested run spend past its slice (by default @@ -218,6 +237,14 @@ impl Realm { self.interp.reset_gc_threshold(); } + /// Gives a realm made without [`Options::es2015`] the `Promise` that option adds, for its next + /// runs; a realm that has it already is left as it is. It does not take it away again, and it + /// does not add the option's other built-ins (`Symbol` and the iterators). Call it between + /// runs. + pub fn add_es2015(&mut self) { + crate::builtins::promise::add_to(&mut self.interp); + } + /// Sets [`Options::es2015`] for the next runs, and for the code they evaluate. The `let` and /// `const` names earlier runs declared stay visible when it is turned off. A run begun with /// [`Realm::start`] that is still going keeps the language it started with for the code it @@ -247,19 +274,23 @@ impl Realm { let _ = interp.define(global, key(name), Prop::Data { value: Value::Object(o), flags: HIDDEN }); } - /// Runs `source` as a script in the global environment and returns its completion value (the - /// value of the last expression statement that ran). A realm whose built-ins could not be - /// installed runs nothing and gives an internal error. + /// Runs `source` as a script in the global environment, then the promise jobs it queued, and + /// returns its completion value (the value of the last expression statement that ran). A realm + /// whose built-ins could not be installed runs nothing and gives an internal error. + /// A paused or waiting run ends first; its globals remain available. pub fn run(&mut self, source: &str) -> Result { let code = self.compile(source)?; - let result = self.interp.run_global(code, false); + let result = self.interp.run_global(code, false).and_then(|v| self.interp.drain_jobs(v)); self.outcome(result) } /// Compiles `source` and readies the realm for a run. fn compile(&mut self, source: &str) -> Result, RunError> { + self.end(); self.script_tag = UNKNOWN_SOURCE; + self.rejections = (Vec::new(), 0); let interp = &mut self.interp; + interp.end_jobs(false); if let Some(message) = &interp.install_error { return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0, authored: false }); } @@ -271,6 +302,8 @@ impl Realm { interp.last_error = Value::Null; interp.host_abort = None; interp.waiting = false; + interp.waiting_hosted = false; + interp.constructing = false; interp.resuming = None; interp.error_tag = UNKNOWN_SOURCE; interp.thrown_mark = None; @@ -320,17 +353,26 @@ impl Realm { interp.finally_marks.clear(); interp.finally_sites.clear(); interp.stack.clear(); + // A generator whose body was running when the run ended cannot go on. + let running: Vec<_> = interp.frames.iter().filter_map(|f| f.generator).collect(); + running.into_iter().for_each(|g| interp.end_generator(Some(g))); interp.frames.clear(); interp.temp_roots.clear(); interp.join_stack.clear(); interp.waiting = false; + interp.waiting_hosted = false; + interp.constructing = false; interp.resuming = None; interp.passing = Value::Undefined; + interp.end_jobs(result.is_ok()); if let Some(es2015) = interp.next_es2015.take() { interp.set_es2015(es2015); } match result { - Ok(v) => Ok(interp.to_js_value(&v)), + Ok(v) => { + self.rejections = interp.take_unhandled(); + Ok(interp.to_js_value(&v)) + } Err(Abrupt::Throw(v)) => { let message = interp.describe(&v); let authored = interp.thrown_by_script(&v); @@ -341,6 +383,11 @@ impl Realm { let message = interp.host_abort.take().unwrap_or_else(|| format!("limit reached: {:?}", LimitKind::Host)); Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column, authored: false }) } + Err(Abrupt::Limit(LimitKind::Jobs)) => { + let max = interp.promises.max_jobs; + let message = format!("limit reached: Jobs (more than {max} promise jobs were waiting to run)"); + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Jobs), message, line, column, authored: false }) + } Err(Abrupt::Limit(kind)) => { Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column, authored: false }) } @@ -349,6 +396,7 @@ impl Realm { } /// Begins a run that [`Realm::advance`] carries on: compiles `source` and enters it. + /// A paused or waiting run ends first; its globals remain available. pub fn start(&mut self, source: &str) -> Result<(), RunError> { let code = self.compile(source)?; match self.interp.enter_global(code, false) { @@ -360,12 +408,14 @@ impl Realm { /// Runs the script begun with [`Realm::start`] for about `slice` units of fuel (at least one /// instruction), and pauses where it can resume: between two instructions of the script's own /// code. A getter, a built-in's callback or another nested run has native frames under it, so - /// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. Once this has returned + /// it runs on to its end, for at most [`Realm::set_unbroken_fuel`] more. After the script's code + /// ends, the slices run the promise jobs it queued, pausing between jobs and inside a callback + /// written in JavaScript, and the run is done once the queue is empty. Once this has returned /// [`Progress::Done`] or an error, the run is over. While a host function's call waits for its /// result ([`Realm::waits`]), the run does not advance: this gives an internal error. pub fn advance(&mut self, slice: u64) -> Result { let interp = &mut self.interp; - if interp.frames.is_empty() { + if !interp.running() { return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0, authored: false }); } if interp.waiting { @@ -381,7 +431,7 @@ impl Realm { let cap = slice.saturating_add(self.unbroken_fuel).min(total); interp.fuel = cap; interp.in_slice = true; - let r = interp.execute_slice(cap - slice.min(cap)); + let r = interp.execute_run_slice(cap - slice.min(cap)); interp.in_slice = false; let used = cap - interp.fuel; interp.fuel = total - used; @@ -396,7 +446,28 @@ impl Realm { /// Is a run begun with [`Realm::start`] still going? pub fn is_running(&self) -> bool { - !self.interp.frames.is_empty() + self.interp.running() + } + + /// The promises the last run rejected that still had no rejection handler when it ended + /// successfully, in the order they were rejected: the first 20 of them. Empty after a run that + /// ended with an error, and until a run ends. + pub fn unhandled_rejections(&self) -> &[Rejection] { + &self.rejections.0 + } + + /// How many unhandled rejections the last run that ended successfully had, the ones + /// [`Realm::unhandled_rejections`] leaves out included. + pub fn unhandled_rejection_count(&self) -> usize { + self.rejections.1 + } + + /// Which source the code with tag `tag` is, as [`Realm::error_source`] gives it for an error. + pub fn source_of(&self, tag: u32) -> u32 { + match tag { + UNKNOWN_SOURCE => UNKNOWN_SOURCE, + tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE), + } } /// Ends a run begun with [`Realm::start`] where it is, paused or waiting for a host function's @@ -442,8 +513,11 @@ impl Realm { }); } interp.waiting = false; + // A member of a host class gets its answer as it gets an immediate result. + let hosted = std::mem::take(&mut interp.waiting_hosted); // The value on top of the stack stood in for the result. - let r = interp.write_data(d, 0, false).and_then(|v| { + let written = if hosted { interp.write_hosted(d) } else { interp.write_data(d, 0, false) }; + let r = written.and_then(|v| { interp.stack.pop(); interp.push(v) }); @@ -476,10 +550,7 @@ impl Realm { /// [`crate::HostItem::Evaluator`] gave since then, and [`UNKNOWN_SOURCE`] otherwise, which /// includes code from an earlier script and from the sources given during its run. pub fn error_source(&self) -> u32 { - match self.interp.error_tag { - UNKNOWN_SOURCE => UNKNOWN_SOURCE, - tag => tag.checked_sub(self.script_tag).unwrap_or(UNKNOWN_SOURCE), - } + self.source_of(self.interp.error_tag) } /// The source tag of the code the last error's `line` and `column` are in, which stays the same @@ -546,6 +617,27 @@ impl Realm { } } + /// Adds the host classes `classes` ([`crate::HostClass`]), each a global constructor whose + /// prototype holds its members, and the global objects `instances`, each made from the + /// [`crate::host_ref`] given. Prototypes and constructors are frozen; the instances cannot be + /// replaced. A heap too small for them ends with the error the realm's next run would give. + pub fn define_host_classes(&mut self, classes: Vec, instances: Vec<(String, crate::Data)>) -> Result<(), RunError> { + match crate::host_classes::install(&mut self.interp, classes, instances) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + + /// Adds the global properties `globals`: a name, the function that answers a read, and the + /// function that answers an assignment, each called with `undefined` as `this` (and the value + /// assigned). Assigning one without a setter keeps its value, and throws in strict mode code. + pub fn define_host_globals(&mut self, globals: Vec<(String, crate::HostFunction, Option)>) -> Result<(), RunError> { + match crate::host_classes::install_globals(&mut self.interp, globals) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Sets `Folder.current` back to the host's `current`, for the next run of a realm that has /// `File` and `Folder` ([`Realm::define_file_classes`]); a realm without them keeps its /// `Folder.current`. The files an earlier run opened are no longer open. The last run's uncaught diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 7f19ba162e..4bb98b1e55 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -185,6 +185,10 @@ pub(crate) struct Es2015Objects { pub(crate) array_values: ObjId, /// `Function.prototype[@@hasInstance]`. pub(crate) has_instance: ObjId, + /// `%GeneratorPrototype%`, which each generator function's `prototype` inherits from. + pub(crate) generator_proto: ObjId, + /// `%GeneratorFunction.prototype%`, the `[[Prototype]]` of every generator function. + pub(crate) generator_function_proto: ObjId, } /// The estimated bytes of a registry entry without its Symbol. @@ -208,7 +212,17 @@ impl Symbols { /// The objects the collector starts from. pub(crate) fn root_objects(&self) -> Vec { - self.objects.map_or_else(Vec::new, |o| vec![o.symbol_proto, o.array_iterator_proto, o.string_iterator_proto, o.array_values, o.has_instance]) + self.objects.map_or_else(Vec::new, |o| { + vec![ + o.symbol_proto, + o.array_iterator_proto, + o.string_iterator_proto, + o.array_values, + o.has_instance, + o.generator_proto, + o.generator_function_proto, + ] + }) } /// The bytes the registry's entries hold besides their Symbols, which a collection adds. diff --git a/crates/js/src/value.rs b/crates/js/src/value.rs index 4911c6e36b..1df3a9a6f0 100644 --- a/crates/js/src/value.rs +++ b/crates/js/src/value.rs @@ -221,6 +221,46 @@ impl Str { pub(crate) fn to_rust_string(&self) -> String { String::from_utf16_lossy(&self.flat()) } + + /// The first `max_units` code units as a Rust string, read along the rope without flattening + /// it, so a long string is not copied whole. + pub(crate) fn prefix_to_rust_string(&self, max_units: usize) -> String { + if self.len() <= max_units { + return self.to_rust_string(); + } + let mut units = Vec::with_capacity(max_units); + let mut stack = vec![self.clone()]; + while let Some(s) = stack.pop() { + let room = max_units - units.len(); + if room == 0 { + break; + } + match &*s.0.borrow() { + Node::Flat(f) => units.extend_from_slice(&f[..f.len().min(room)]), + Node::Concat { left, right, .. } => { + stack.push(right.clone()); + stack.push(left.clone()); + } + Node::Taken => {} + } + } + String::from_utf16_lossy(&units) + } + + /// Calls `f` with each run of code units in order, read along the rope without flattening it. + pub(crate) fn for_each_chunk(&self, mut f: impl FnMut(&[u16])) { + let mut stack = vec![self.clone()]; + while let Some(s) = stack.pop() { + match &*s.0.borrow() { + Node::Flat(units) => f(units), + Node::Concat { left, right, .. } => { + stack.push(right.clone()); + stack.push(left.clone()); + } + Node::Taken => {} + } + } + } } impl PartialEq for Str { diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 61417a2879..8d012a81e1 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -40,16 +40,26 @@ //! `annexb-language-failures.txt` and `annexb-builtins-failures.txt`). A suite without //! `test/annexB/` skips them; a folder there with no test to parse or run fails them. //! +//! Another test runs the tests under `test/built-ins/Promise` in realms with `Options::es2015`: +//! those whose feature tags name only `Promise`, `Promise.allSettled` and +//! `Promise.prototype.finally`, whose code parses and uses only the built-ins present. `async` tests +//! run with the suite's `doneprintHandle.js` and pass when they print the completion line. Its +//! failures go to `promise-failures.txt`. +//! //! Another test runs the tests of `Symbol`, `Object.getOwnPropertySymbols` and the iterators of //! arrays and strings (the folders [`SYMBOL_BUILT_INS`] names) in a realm with //! [`Options::es2015`]: tests of any edition whose feature tags are all in [`SYMBOL_FEATURES`] and //! that parse with that option. Its failures go to `symbol-failures.txt`. //! -//! The last test reads the tests of `for-of` and destructuring (the folders +//! Another test reads the tests of `for-of` and destructuring (the folders //! [`FOR_OF_AND_PATTERN_FOLDERS`] names) with [`Options::es2015`]: tests of any edition whose //! feature tags are all in [`FOR_OF_AND_PATTERN_FEATURES`]. Negative parse tests must give a //! `SyntaxError`; the others run as the Symbol tests run. Its failures go to `for-of-failures.txt`. //! +//! The last test reads and runs the tests of generator functions, `yield` and the generator objects +//! (the folders [`GENERATOR_FOLDERS`] names) the same way, with the `generators` tag and the tags of +//! the two tests before it. Its failures go to `generators-failures.txt`. +//! //! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses //! an `includes:` name that leaves the `harness/` folder, and refuses a file over //! [`MAX_FILE_BYTES`] before reading it. A folder or file it cannot read fails the test. @@ -58,7 +68,6 @@ use std::collections::HashSet; use std::path::{Path, PathBuf}; use vectorcraft_js::{JsValue, Limits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize}; - /// A test file's metadata, from its `/*--- … ---*/` block. #[derive(Default)] struct Meta { @@ -364,7 +373,7 @@ fn parse_check(source: &str, meta: &Meta, strict: bool) -> Result<(), String> { /// Globals and method names the interpreter does not provide yet: a test that names one, in its /// own source or in a harness file it includes, is skipped. -const MISSING_BUILTINS: &str = "String Number Boolean Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \ +const MISSING_BUILTINS: &str = "String Number Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \ WeakSet ArrayBuffer DataView Int8Array Uint8Array Float64Array charAt charCodeAt fromCharCode substring substr split replace \ match search exec test toUpperCase toLowerCase trim toFixed toPrecision toExponential now"; @@ -899,6 +908,145 @@ fn run_annex_b(dir: &Path) { assert_eq!(panicked, 0, "the interpreter panicked; see the Annex B failure files in {}", dir.display()); } +/// The feature tags a `test/built-ins/Promise` test may carry and still run: `Promise`, +/// `Promise.allSettled` and `Promise.prototype.finally`. +const PROMISE_FEATURES: &[&str] = &["Promise", "Promise.allSettled", "Promise.prototype.finally"]; + +#[test] +fn promise_builtins_run() { + let Some(dir) = suite_dir() else { + println!("test262 Promise: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_promise(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs one `test/built-ins/Promise` test in a new realm with [`Options::es2015`] and a global +/// `print` that collects its output; an `async` test passes when it prints +/// `Test262:AsyncTestComplete`. +fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool) -> Result<(), String> { + let options = Options { es2015: true, ..Options::default() }; + let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); + let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new())); + let out = printed.clone(); + realm.define_function("print", move |args| { + let line = match args.first() { + Some(JsValue::String(s)) => s.clone(), + Some(other) => format!("{other:?}"), + None => String::new(), + }; + out.borrow_mut().push_str(&line); + out.borrow_mut().push('\n'); + Ok(JsValue::Undefined) + }); + let result = realm.run(script); + if asynchronous && result.is_ok() && negative_type.is_none() { + let printed = printed.borrow(); + return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") { + Ok(()) + } else { + Err(format!("printed {:?}", printed.trim())) + }; + } + match (result, negative_type) { + (Ok(_), None) => Ok(()), + (Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")), + (Err(e), Some(t)) if e.kind == RunErrorKind::Thrown => { + realm.bind_last_thrown("__thrown"); + match realm.run(&format!("typeof __thrown === 'object' && __thrown !== null && __thrown.constructor === {t}")) { + Ok(JsValue::Bool(true)) => Ok(()), + _ => Err(format!("threw {} (line {}); a {t} was expected", e.message, e.line)), + } + } + (Err(e), _) => Err(format!("{:?}: {} (line {}, column {})", e.kind, e.message, e.line, e.column)), + } +} + +/// Runs the tests under `test/built-ins/Promise` whose feature tags are all in +/// [`PROMISE_FEATURES`], whose code parses as ES5 and uses only the built-ins present, as sloppy +/// and strict code as [`run_tests`] does, `async` tests included. Prints the counts and writes the +/// failures to `promise-failures.txt` beside the suite. +fn run_promise(dir: &Path) { + let root = or_fail(inside(dir, "test/built-ins/Promise")); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + // A harness file is named by the test's `includes:`, so it is read only inside `harness/`. + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let done = harness("doneprintHandle.js"); + let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Promise $DONE print"]); + let mut groups: std::collections::BTreeMap = std::collections::BTreeMap::new(); + let (mut files, mut other_features) = (0usize, 0usize); + for path in or_fail(test_files(&root)) { + files += 1; + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if meta.features.iter().any(|f| !PROMISE_FEATURES.contains(&f.as_str())) { + other_features += 1; + continue; + } + let asynchronous = meta.flags.iter().any(|f| f == "async"); + let tags = if meta.features.is_empty() { "no feature tag".to_string() } else { meta.features.join(", ") }; + let counts = groups.entry(format!("{tags}, {}", if asynchronous { "async" } else { "sync" })).or_default(); + let negative_parse = matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")); + if negative_parse || meta.flags.iter().any(|f| f == "module") { + counts.skipped += 1; + continue; + } + let mut includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + if asynchronous { + includes.push_str(&done); + includes.push('\n'); + } + if parse(&source, &Options::default()).is_err() || needs_missing_builtin(&[&source, &includes], &missing) { + counts.skipped += 1; + continue; + } + counts.tests += 1; + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; + let script = if strict { format!("\"use strict\";\n{body}") } else { body }; + let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); + match std::panic::catch_unwind(|| run_promise_one(&script, negative_type.as_deref(), asynchronous)) { + Ok(Ok(())) => counts.passed += 1, + Ok(Err(why)) => { + counts.failed += 1; + counts.failures.push_str(&format!("{rel} ({mode}): {why}\n")); + } + Err(_) => { + counts.failed += 1; + counts.panicked += 1; + counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n")); + } + } + } + } + let mut all = RunCounts::default(); + for (group, counts) in &groups { + println!("test262 built-ins/Promise, {group}: {}.", counts.summary()); + all.tests += counts.tests; + all.skipped += counts.skipped; + all.passed += counts.passed; + all.failed += counts.failed; + all.panicked += counts.panicked; + all.failures.push_str(&counts.failures); + } + let report = dir.join("promise-failures.txt"); + if let Err(e) = std::fs::write(&report, &all.failures) { + println!("could not write {}: {e}", report.display()); + } + println!( + "test262 built-ins/Promise through the interpreter: {files} files, {other_features} with other feature tags left out; {}. Failures: {}", + all.summary(), + report.display() + ); + assert!(all.tests > 0, "no Promise tests ran under {}", root.display()); + assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", report.display()); +} + /// The folders of the tests of `Symbol`, Symbol-keyed properties and the iterators of arrays and /// strings, which run in a realm with [`Options::es2015`]. const SYMBOL_BUILT_INS: &[&str] = &[ @@ -1032,6 +1180,58 @@ fn run_for_of_and_patterns(dir: &Path) { assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display()); } +/// The folders of the tests of generator functions, `yield` and the generator objects, which run +/// in a realm with [`Options::es2015`]. +const GENERATOR_FOLDERS: &[&str] = &[ + "language/statements/generators", + "language/expressions/generators", + "language/expressions/yield", + "built-ins/GeneratorPrototype", + "built-ins/GeneratorFunction", +]; + +#[test] +fn es2015_generators_run() { + let Some(dir) = suite_dir() else { + println!("test262 generators: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_generators(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Reads the tests under each folder [`GENERATOR_FOLDERS`] names whose feature tags are all +/// `generators` or in [`FOR_OF_AND_PATTERN_FEATURES`] or [`SYMBOL_FEATURES`] with +/// [`Options::es2015`], as [`run_for_of_and_patterns`] reads its tests. Prints the counts of each +/// folder and writes the failures to `generators-failures.txt` beside the suite. +fn run_generators(dir: &Path) { + let options = Options { es2015: true, ..Options::default() }; + let missing: HashSet<&str> = missing_builtins(&[TEXT_BUILTINS, "Symbol"]); + let mut features: Vec<&str> = vec!["generators"]; + features.extend(FOR_OF_AND_PATTERN_FEATURES); + features.extend(SYMBOL_FEATURES); + let mut all = RunCounts::default(); + let mut report = String::new(); + for folder in GENERATOR_FOLDERS { + let Some(root) = or_fail(present(dir, &format!("test/{folder}"))) else { + println!("test262 {folder}: SKIPPED (not in this suite)"); + continue; + }; + let mut counts = run_parse_negatives(dir, &root, &options, &features); + counts.add(run_tagged_tests(dir, &root, &missing, &options, &features)); + println!("test262 {folder} with Options::es2015: {}.", counts.summary()); + report.push_str(&format!("# {folder}\n{}\n", counts.failures)); + all.add(counts); + } + assert!(all.tests > 0, "no generator tests ran under {}", dir.display()); + let path = dir.join("generators-failures.txt"); + if let Err(e) = std::fs::write(&path, &report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 generators with Options::es2015: {}. Failures: {}", all.summary(), path.display()); + assert_eq!(all.panicked, 0, "the interpreter panicked; see {}", path.display()); +} + /// Parses the negative parse tests under `root` whose feature tags are all in `features`, in /// each mode the test names, with `options`; each must give a `SyntaxError`. fn run_parse_negatives(dir: &Path, root: &Path, options: &Options, features: &[&str]) -> RunCounts { diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 7c3d717d5a..c1a661c4e3 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -776,6 +776,15 @@ fn set_paint_reports_how_many_objects_it_painted() { assert_eq!(v["objects"], 2, "{v}"); let v = paint(&mut s, 16, json!({"strokeWidth": 2})); assert_eq!(v["objects"], 2, "{v}"); + + // While the Shape Builder is the active tool, the fill goes to new art only and the stroke to + // the selection: the reply names the command that painted nothing. + let r = call(&mut s, 17, "select_tool", json!({"tool": "shapeBuilder"})); + assert_eq!(r["isError"], false, "{r}"); + let v = paint(&mut s, 18, json!({"fill": "#ff00ff", "stroke": "#00ffff"})); + assert_eq!(v["objects"], 2, "{v}"); + assert_eq!(v["unpainted"], json!(["paint.setFill"]), "{v}"); + assert!(v["note"].as_str().is_some_and(|n| n.contains("Shape Builder")), "{v}"); } /// #1003: type made on or in a path takes add_text's `color` too, over the current fill. @@ -1662,6 +1671,18 @@ fn headless_backend_methods() { assert_eq!(with_enclosing[0][1]["label"], "Enclosing Lasso Tool"); assert!(with_enclosing[0][1]["shortcut"].is_null()); assert_eq!(h.call("ui.tool.select", json!({"tool": enclosing})).unwrap()["tool"], enclosing); + // The Smart Pen Tool is listed once, at the end of the Pen tool's group. + let smart_pen = vectorcraft_tools::addons::smart_pen::ID; + let with_smart_pen: Vec<_> = + groups.iter().map(|group| group.as_array().unwrap()).filter(|group| group.iter().any(|entry| entry["id"] == smart_pen)).collect(); + assert_eq!(with_smart_pen.len(), 1, "{smart_pen} is in one group"); + let ids: Vec<_> = with_smart_pen[0].iter().map(|entry| entry["id"].clone()).collect(); + assert_eq!(ids.first(), Some(&json!("pen"))); + assert_eq!(ids[ids.len().saturating_sub(2)..], [json!("quickPen"), json!(smart_pen)]); + let entry = with_smart_pen[0].iter().find(|entry| entry["id"] == smart_pen).unwrap(); + assert_eq!(entry["label"], "Smart Pen Tool"); + assert!(entry["shortcut"].is_null()); + assert_eq!(h.call("ui.tool.select", json!({"tool": smart_pen})).unwrap()["tool"], smart_pen); let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso"); assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool"))); assert!(h.call("ui.resize", json!({})).is_err()); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 931e910315..d8d215b86e 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -282,7 +282,7 @@ pub fn tool_definitions() -> Vec { tool( "set_paint", "Set paint", - "Set fill, stroke and/or stroke weight on the selection (or `ids`) and as the default for new art. Returns {applied, objects}: `objects` counts the objects painted, as paint.setFill, paint.setStroke and stroke.set report them (the largest of their counts); when it is 0, a `note` says that only the default for new art changed.", + "Set fill, stroke and/or stroke weight on the selection (or `ids`) and as the default for new art. Returns {applied, objects}: `objects` counts the objects painted, as paint.setFill, paint.setStroke and stroke.set report them (the largest of their counts); when it is 0, a `note` says that only the default for new art changed, and when only some of those commands painted no object, `unpainted` lists them with a `note`.", obj( json!({ "fill": paint_schema("Fill"), diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 12c3b24f37..752f72b928 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -183,11 +183,16 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result Result<(Vec>, Map), Str } /// Sets the paint `a` gives on `ids` (default: the selection) and as the default for new art. -/// Returns the paint applied and the most objects one of its edits painted (the `objects` of the -/// `paint.setFill`, `paint.setStroke` and `stroke.set` replies). -pub(super) fn apply_paint(b: &mut dyn Backend, a: &Args, ids: Option) -> Result<(Value, u64), String> { +/// Returns the paint applied, the most objects one of its edits painted (the `objects` of the +/// `paint.setFill`, `paint.setStroke` and `stroke.set` replies) and the commands among them that +/// painted no object. +pub(super) fn apply_paint(b: &mut dyn Backend, a: &Args, ids: Option) -> Result<(Value, u64, Vec<&'static str>), String> { let (steps, applied) = paint_steps(a)?; - let mut objects = 0; + let (mut objects, mut unpainted) = (0, vec![]); for (cmd, mut p) in steps { if let Some(ids) = &ids { p["ids"] = ids.clone(); } let r = exec(b, cmd, p)?; - objects = objects.max(r.get("objects").and_then(Value::as_u64).unwrap_or(0)); + let n = r.get("objects").and_then(Value::as_u64).unwrap_or(0); + if n == 0 { + unpainted.push(cmd); + } + objects = objects.max(n); } - Ok((Value::Object(applied), objects)) + Ok((Value::Object(applied), objects, unpainted)) } /// Checks `draw_path` / `draw_shape`'s `dash`, `cap`, `join`, `opacity`, `name` and `effects` diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 18d0ebc247..a519986ed0 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -484,7 +484,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "view.actualSize", "Actual Size", "Cmd+1", - "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills 96 screen points (an inch at the system's reference density, whatever the display scaling); the same at every UI Scaling", + "{} 100%: with Display Print Size at 100% Zoom off, one document point per screen point; on, one document inch fills an inch of the display that shows the window, measured from the physical size the system reports for it, or 96 screen points where it reports none or a size no display has; the same at every UI Scaling", ), ("view.setZoom", "Set Zoom", "", "{zoom: percent, center?: [x,y]}"), ( @@ -658,19 +658,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.toolbar.dock", "Dock Toolbar", "", - "{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` in the lane along the window's left or right edge (omitted: the edge it docked at last, the left at first), as Dock to Left and Dock to Right in its title bar's context menu and dropping its title bar on that edge do; `order` is its place in that edge's stack, 0 at the top (omitted: the end, or where it is when it is docked at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}", + "{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` as a column of the dock along the window's left or right edge (omitted: the edge it docks at, else the edge it docked at last, the left at first), as dragging its title bar to that edge does; a hidden toolbar shows; `order` is its column's place in that edge's dock, 0 at the window's edge (omitted: the innermost, or where it is when it docks at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}, `pos` its top-left corner while it floats (else null)", ), ( "window.toolbar.float", "Float Toolbar", "", - "{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in screen points (both or neither; omitted: where it floated last), as Float Toolbar in its title bar's context menu and dragging its title bar out of its lane do; returns {toolbar, floating, side, order, pos}", + "{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in window points (both or neither, each from -1000000 to 1000000; omitted: where the dock floats a panel, and a floating toolbar stays where it is), as dragging its title bar out of the dock does; a hidden toolbar shows; returns {toolbar, floating, side, order, pos}", ), ( "window.toolbar.list", "List Toolbars", "", - "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", + "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its column's place in that edge's dock, 0 at the window's edge, while docked (else null)", ), ("window.taskBar", "Contextual Task Bar", "", "{}"), ( @@ -771,7 +771,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.panel.float", "Float Panel", "", - "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window; omitted components keep their current values. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", + "{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window when the float takes the whole window (a panel alone in it, `column`, or `group` on a tab group that fills it); omitted components keep their current values. A panel that shares its native window floats into a new window instead, and the shared window keeps its other panels. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}", ), ( "window.panel.dock", @@ -867,7 +867,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "retype.find", "Find Matching Fonts", "", - "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", + "{more?: bool, installed?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first, then, unless installed is false, the installed fonts not loaded yet, which the app reads in the background, with retype.cancelSearch to stop it, when the panel's button, a menu or the command palette runs it): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more or installed other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", ), ( "retype.list", @@ -994,7 +994,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.recolorDialog", "Recolor Artwork…", "", - "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", + "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any), preset?: bool (Recolor with Preset: first open the `recolorPreset` dialog, whose Limit to Library field `limitTo` starts on `library`; its OK opens Recolor Artwork with `colors` and that library; an error with `group`)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", ), ( "ui.recolorUndo", @@ -1174,7 +1174,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1513,7 +1513,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", ), ( "ui.widthPointEdit", @@ -1525,7 +1525,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.corners", "Corners…", "", - "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget with Direct Selection opens it too): OK runs object.setLiveShape", + "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radii (relative|absolute), radius (pt, or with relative radii a percentage of each corner's own maximum); double-clicking a corner widget with Direct Selection opens it too): OK runs object.setLiveShape, as one command.batch undo step when relative radii give the corners different lengths", ), ( "ui.simplifyAuto", @@ -1597,7 +1597,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, vision, documentColors}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the active document's RGB space (its assigned profile, else the working RGB space) is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, contrast, contrastFor, contrastBackground, vision, documentColors}", ), ( "ui.savePdfDialog", @@ -1986,7 +1986,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "plugin.dialog", "Plug-in…", "", - "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns)", + "{id: an object filter plug-in (plugin.list), params?: {…}} Object › Plug-ins: run the filter at once when it takes no parameters or params are given (plugin.run), else open its dialog (dialog `plugin`: a field per parameter at the value the filter last ran with in this session, else its default, `__plugin` the id, live preview; OK runs plugin.run as one undo step). A heavy filter, and a filter that lists `progress` and no commandAllowlist, run in the background when they run at once or OK runs them without a kept preview → {background: true, status} (see plugin.cancelRuns)", + ), + ( + "plugin.applyLastFilter", + "Apply Last Filter", + "", + "{} Object › Plug-ins › Apply : run the object filter that last ran in this session (a plugin.run that succeeded: its menu item, its dialog's OK, a request, a command.batch step or an action.batch step; not a plug-in's own commands) again on the selection with the same parameters, without its dialog, as one undo step; it runs in the background where its menu item would → plugin.run's result | {background: true, status}. An error with no document open, when no filter ran yet, when that filter was removed or installed again (the same module too) since, or when its manifest no longer takes those parameters as they are", + ), + ( + "plugin.lastFilter", + "Last Filter…", + "", + "{} Object › Plug-ins › …: open the dialog of the object filter that last ran in this session (see plugin.applyLastFilter) with the parameters it ran with (dialog `plugin`); OK runs it as one undo step and Cancel changes nothing. A filter without parameters runs at once. The same errors as plugin.applyLastFilter", ), ( "ui.installPlugin", @@ -2018,17 +2030,23 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} close the progress window of the Image Traces running in the background; they go on, shown in the status bar → {hidden: n}", ), + ( + "retype.cancelSearch", + "Cancel Font Search", + "", + "{} stop the search of the installed fonts that Type › Retype or the Retype panel's Find Matching Fonts runs in the background (its progress window's Cancel): it stops before its next file, and Retype changes nothing and the list stays as it was → {cancelled: n}", + ), ( "ui.runScript", "Other Script…", "Cmd+F12", - "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( "ui.runInstalledScript", "Run Script", "", - "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again; with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar", ), ( "ui.checkScript", diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index af7bf90231..102d7e7138 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -226,7 +226,7 @@ pub fn pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Ve ); subpaths.into_iter().zip(shapes).filter(|(sp, _)| !sp.is_empty()).flat_map(|(sp, s)| one(PathData::new(sp), s.key)).collect() } - PathfinderOp::Outline => outline_edges(&arr, shapes), + PathfinderOp::Outline => outline_edges(&arr, shapes, precision), PathfinderOp::HardMix | PathfinderOp::SoftMix => regions_of(&arr) .into_iter() .filter_map(|r| { @@ -971,13 +971,60 @@ fn along(a: &[PathSeg], b: &[PathSeg], tol: f64) -> bool { covers(a, b) && covers(b, a) } -/// Pathfinder Outline: split every shape's boundary at junctions of the arrangement. -fn outline_edges(arr: &Arrangement, shapes: &[Shape]) -> Vec { +/// [`along`] with each piece checked at points no farther apart along its control polygon than +/// `tol`, at most 64 to a piece, so curves that meet at the middles and ends of their pieces but +/// part between them are not one. `a` and `b` run opposite ways. Each piece's samples include its +/// middle. Chains whose pieces pair up with control points within `tol` of each other are one +/// without sampling: each point of such a piece is within `tol` of the point of its pair at the same +/// parameter. +fn along_closely(a: &[PathSeg], b: &[PathSeg], tol: f64) -> bool { + let within = |p: Point, q: Point| p.distance(q) <= tol; + let paired = a.len() == b.len() + && a.iter().zip(b.iter().rev()).all(|(p, q)| match (p, q.reverse()) { + (PathSeg::Line(x), PathSeg::Line(y)) => within(x.p0, y.p0) && within(x.p1, y.p1), + (PathSeg::Quad(x), PathSeg::Quad(y)) => within(x.p0, y.p0) && within(x.p1, y.p1) && within(x.p2, y.p2), + (PathSeg::Cubic(x), PathSeg::Cubic(y)) => within(x.p0, y.p0) && within(x.p1, y.p1) && within(x.p2, y.p2) && within(x.p3, y.p3), + _ => false, + }); + if paired { + return true; + } + let samples = |s: &PathSeg| { + let len = match s { + PathSeg::Line(l) => l.p0.distance(l.p1), + PathSeg::Quad(q) => q.p0.distance(q.p1) + q.p1.distance(q.p2), + PathSeg::Cubic(c) => c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3), + }; + // An even count puts a sample at the middle of the piece. + let n = if tol > 0.0 { ((len / tol / 2.0).ceil().clamp(1.0, 32.0) as usize) * 2 } else { 64 }; + let s = *s; + (1..=n).map(move |k| s.eval(k as f64 / n as f64)) + }; + let covers = |from: &[PathSeg], to: &[PathSeg]| { + // Each point's search goes back along `to` from the piece the point before it was near. + let mut at = to.len(); + from.iter().flat_map(samples).all(|p| { + let mut order = to.iter().enumerate().take(at).rev().chain(to.iter().enumerate().skip(at).rev()); + let Some((i, _)) = order.find(|(_, t)| t.nearest(p, 1e-12).distance_sq.sqrt() <= tol) else { return false }; + at = i + 1; + true + }) + }; + covers(a, b) && covers(b, a) +} + +/// Pathfinder Outline: split every shape's boundary at junctions of the arrangement. Junctions +/// closer together than `reach` are one, and coincident edges within ten times it are one edge. +/// `reach` is the larger of the arrangement's tolerance for the art's size and `precision` / 10,000, +/// with `precision` kept within 0.001 to 10 pt (Pathfinder Options › Precision's range), so the +/// default precision gives 0.000001 pt as before. Scaling the art and the precision together scales +/// `reach` by the same amount. +fn outline_edges(arr: &Arrangement, shapes: &[Shape], precision: f64) -> Vec { // Sorted by x (then y), so a segment needs only the junctions inside its control box. let junctions = arr.junctions(); let scale = shapes.iter().filter_map(|s| s.path.control_bounds()).map(|r| r.width().max(r.height())).fold(1.0, f64::max); let tol = scale * 1e-7; - let reach = tol.max(1e-6); + let reach = tol.max(1e-6 * (precision / DEFAULT_PRECISION).clamp(0.1, 1000.0)); // (chain, key, source index) let mut chains: Vec<(Vec, u64)> = Vec::new(); for s in shapes { @@ -1054,8 +1101,15 @@ fn outline_edges(arr: &Arrangement, shapes: &[Shape]) -> Vec { // De-duplicate coincident chains, keeping the front-most key (later shapes overwrite). A // match has its midpoint within `near` of this one's, so only the chains in the grid cells // around it are candidates; the first of them in `out` order is the one a scan would find. + // Ends and midpoint only pick the candidates: two chains are one edge when each lies within `d` + // of the other along its whole length. let mut out: Vec<(Vec, u64)> = Vec::new(); let mut sigs: Vec<(Point, Point, Point)> = Vec::new(); + let mut paths: Vec> = Vec::new(); + let as_path = |c: &[Seg]| -> Vec { + c.iter().map(|s| if s.line { PathSeg::Line(Line::new(s.c.p0, s.c.p3)) } else { PathSeg::Cubic(s.c) }).collect() + }; + let reversed = |c: &[PathSeg]| -> Vec { c.iter().rev().map(|s| s.reverse()).collect() }; let sig = |c: &[Seg]| -> (Point, Point, Point) { let a = c[0].c.p0; let b = c[c.len() - 1].c.p3; @@ -1068,6 +1122,7 @@ fn outline_edges(arr: &Arrangement, shapes: &[Shape]) -> Vec { let mut grid: HashMap<(i64, i64), Vec> = HashMap::new(); for (chain, key) in chains { let (a, b, m) = sig(&chain); + let path = as_path(&chain); let (cx, cy) = cell(m); let found = (cx - 1..=cx + 1) .flat_map(|x| (cy - 1..=cy + 1).map(move |y| (x, y))) @@ -1076,7 +1131,21 @@ fn outline_edges(arr: &Arrangement, shapes: &[Shape]) -> Vec { .copied() .filter(|&i| { let (a2, b2, m2) = sigs[i]; - near(m, m2) && ((near(a, a2) && near(b, b2)) || (near(a, b2) && near(b, a2))) + let other = &paths[i]; + let same = near(a, a2) && near(b, b2); + let opposite = near(a, b2) && near(b, a2); + if !near(m, m2) || !(same || opposite) { + return false; + } + // A chain whose ends meet matches both ways round; the end of its first piece shows + // which way the other runs. `along_closely` takes chains that run opposite ways. + let runs_same = same + && (!opposite + || match (path.first(), other.first(), other.last()) { + (Some(p), Some(f), Some(l)) => p.end().distance(f.end()) <= p.end().distance(l.start()), + _ => true, + }); + if runs_same { along_closely(&path, &reversed(other), d) } else { along_closely(&path, other, d) } }) .min(); match found { @@ -1084,6 +1153,7 @@ fn outline_edges(arr: &Arrangement, shapes: &[Shape]) -> Vec { None => { grid.entry((cx, cy)).or_default().push(out.len()); sigs.push((a, b, m)); + paths.push(path); out.push((chain, key)); } } @@ -1711,4 +1781,41 @@ mod tests { assert_eq!(merged.len(), 40); assert!(merged.iter().enumerate().all(|(k, s)| s.key == k as u64)); } + + /// A curve with the ends of a line that passes within 0.25 pt of the line's middle, and whose + /// own middle is within 0.25 pt of the line, but which runs about 23 pt past the line's start: + /// the middles and ends of the two pieces match, and the two are still not one edge. + #[test] + fn along_closely_checks_curves_between_the_middles_of_their_pieces() { + let line = [PathSeg::Line(Line::new((100.0, 0.0), (0.0, 0.0)))]; + let curve = [PathSeg::Cubic(kurbo::CubicBez::new((0.0, 0.0), (-54.56, 0.4537), (198.85, 0.0963), (100.0, 0.0)))]; + assert!(along(&line, &curve, 0.25), "the middles and ends match"); + assert!(!along_closely(&line, &curve, 0.25)); + assert!(!along_closely(&curve, &line, 0.25)); + let same = [PathSeg::Line(Line::new((0.0, 0.0), (100.0, 0.0)))]; + assert!(along_closely(&line, &same, 0.25)); + } + + /// A curve 1.05 pt from a line at its middle and under 1 pt from it at its thirds: with a + /// control polygon under three times the tolerance long, the samples still take in the middle. + #[test] + fn along_closely_samples_the_middle_of_a_short_piece() { + let line = [PathSeg::Line(Line::new((0.15, 0.0), (0.0, 0.0)))]; + let curve = [PathSeg::Cubic(kurbo::CubicBez::new((0.0, 0.0), (0.05, 1.4), (0.1, 1.4), (0.15, 0.0)))]; + assert!(!along_closely(&curve, &line, 1.0)); + } + + /// Pieces whose control points pair up within the tolerance are one edge, copies included. + #[test] + fn along_closely_takes_pieces_whose_control_points_pair_up() { + let a = [ + PathSeg::Cubic(kurbo::CubicBez::new((0.0, 0.0), (10.0, 20.0), (30.0, 20.0), (40.0, 0.0))), + PathSeg::Line(Line::new((40.0, 0.0), (80.0, 0.0))), + ]; + let reversed: Vec = a.iter().rev().map(|s| s.reverse()).collect(); + assert!(along_closely(&a, &reversed, 0.01)); + let shifted: Vec = reversed.iter().map(|s| kurbo::Affine::translate((0.0, 0.2)) * *s).collect(); + assert!(along_closely(&a, &shifted, 0.25)); + assert!(!along_closely(&a, &shifted, 0.1)); + } } diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index 60410a0d5d..e26d0e69e9 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -237,6 +237,68 @@ fn pf_outline_dedups_shared_edges() { assert!(close(len, 70.0, 1e-9), "len {len}"); } +/// Outline follows Precision: two bars whose left edges cross a square's top edge 0.00005 pt apart +/// leave a piece of that length between the crossings at the default precision, and none at 10 pt, +/// where the two crossings are one junction. +#[test] +fn pf_outline_joins_junctions_closer_than_the_precision() { + let s = vec![shape(rect(0.0, 0.0, 100.0, 100.0), 1), shape(rect(50.0, 90.0, 10.0, 20.0), 2), shape(rect(50.00005, 95.0, 4.99995, 10.0), 3)]; + let shortest = |r: &[Shape]| r.iter().map(|s| s.path.length()).fold(f64::INFINITY, f64::min); + let length = |r: &[Shape]| r.iter().map(|s| s.path.length()).sum::(); + let at_default = pathfinder_with(PathfinderOp::Outline, &s, DEFAULT_PRECISION); + assert_eq!(at_default, pathfinder(PathfinderOp::Outline, &s)); + assert!(shortest(&at_default) < 1e-4, "{at_default:?}"); + let coarse = pathfinder_with(PathfinderOp::Outline, &s, 10.0); + assert!(shortest(&coarse) > 1e-3, "{coarse:?}"); + assert!(coarse.len() < at_default.len(), "{} pieces at 10 pt, {} at the default", coarse.len(), at_default.len()); + assert!(close(length(&coarse), length(&at_default), 1e-6), "{} against {}", length(&coarse), length(&at_default)); +} + +/// Outline at a tenth of the size and a tenth of the precision gives the same pieces at a tenth of +/// the length: crossings 0.05 pt apart on a 1,000 pt square at 10 pt, and 0.005 pt apart on a 100 pt +/// square at 1 pt, stay two junctions in both. +#[test] +fn pf_outline_scales_with_the_art_and_the_precision_together() { + let art = |k: f64| { + vec![ + shape(rect(0.0, 0.0, 1000.0 * k, 1000.0 * k), 1), + shape(rect(500.0 * k, 900.0 * k, 100.0 * k, 200.0 * k), 2), + shape(rect(500.05 * k, 950.0 * k, 49.95 * k, 100.0 * k), 3), + ] + }; + let length = |r: &[Shape]| r.iter().map(|s| s.path.length()).sum::(); + let large = pathfinder_with(PathfinderOp::Outline, &art(1.0), 10.0); + let small = pathfinder_with(PathfinderOp::Outline, &art(0.1), 1.0); + assert_eq!(large.len(), small.len(), "{large:?}\n{small:?}"); + assert!(close(length(&large) / 10.0, length(&small), 1e-6), "{} against {}", length(&large), length(&small)); + let pieces = |r: &[Shape], k: f64| { + let mut l: Vec = r.iter().map(|s| s.path.length() / k).collect(); + l.sort_by(f64::total_cmp); + l + }; + let (a, b) = (pieces(&large, 1.0), pieces(&small, 0.1)); + assert!(a.iter().zip(&b).all(|(x, y)| close(*x, *y, 1e-6)), "{a:?} against {b:?}"); +} + +/// Two boundaries that are close only at their start, end and middle stay two edges at 10 pt: an +/// ellipse 0.005 pt inside a circle at its rightmost and leftmost points, and 30 pt inside it at +/// the top and bottom. Two copies of one boundary are still one edge at that precision. +#[test] +fn pf_outline_keeps_boundaries_that_differ_between_their_ends_at_coarse_precision() { + let ellipse = |rx: f64, ry: f64| PathData::from_bezpath(&kurbo::Ellipse::new((100.0, 100.0), (rx, ry), 0.0).to_path(1e-4)); + let s = vec![shape(ellipse(50.0, 50.0), 1), shape(ellipse(49.995, 20.0), 2)]; + let length = |r: &[Shape]| r.iter().map(|s| s.path.length()).sum::(); + let expected = s[0].path.length() + s[1].path.length(); + for precision in [DEFAULT_PRECISION, 10.0] { + let r = pathfinder_with(PathfinderOp::Outline, &s, precision); + assert_eq!(r.len(), 2, "{precision} pt: {r:?}"); + assert!(close(length(&r), expected, 1e-6), "{precision} pt: {} against {expected}", length(&r)); + } + let copies = vec![shape(ellipse(50.0, 50.0), 1), shape(ellipse(50.0, 50.0), 2)]; + let r = pathfinder_with(PathfinderOp::Outline, &copies, 10.0); + assert!(close(length(&r), copies[0].path.length(), 1e-6), "{r:?}"); +} + #[test] fn regions_and_region_at() { let s = stack(); diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index 69269cb7eb..15d6746ce1 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -615,6 +615,10 @@ impl Dest { /// The catalog entries `set` asks for (none in PDF/A files, which carry their own); a PDF/X file's /// output intent profile is `cmyk_profile` (the CMYK profile in effect) unless `set` names one. +/// When the settings leave the condition identifier blank, a profile computed for a registered +/// printing condition ([`cms::characterization`]) gives the condition's name as the identifier, +/// and its registry when the settings leave the registry blank too. An identifier set in the +/// settings is written as given, with the settings' registry. fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option { let o = &set.output; if set.standard == Standard::PdfA2b { @@ -631,13 +635,13 @@ fn catalog(set: &PdfSettings, cmyk_profile: &str) -> Option { ProfileKind::Gray => None, }); let text = |s: &str| s.trim().chars().take(MAX_TEXT).collect::(); - OutputIntent { - id: text(if id.is_empty() { name } else { id }), - condition: text(&o.output_condition), - registry: text(&o.registry), - info: text(name), - profile, - } + // Without a condition identifier, a profile computed for a registered printing condition + // names that condition and, unless the settings name one, the registry it belongs to. + let (id, registry) = match cms::characterization(name) { + Some((reference, registry)) if id.is_empty() => (reference, if o.registry.trim().is_empty() { registry } else { o.registry.as_str() }), + _ => (if id.is_empty() { name } else { id }, o.registry.as_str()), + }; + OutputIntent { id: text(id), condition: text(&o.output_condition), registry: text(registry), info: text(name), profile } }); let trapped = (o.trapped || intent.is_some()).then_some(o.trapped); (intent.is_some() || trapped.is_some()).then_some(Catalog { intent, trapped }) diff --git a/crates/pdf/src/tests/pdfx.rs b/crates/pdf/src/tests/pdfx.rs index f7cf8ff56a..6af2e0e0a5 100644 --- a/crates/pdf/src/tests/pdfx.rs +++ b/crates/pdf/src/tests/pdfx.rs @@ -151,6 +151,75 @@ fn each_standard_writes_its_header_output_intent_boxes_and_identification() { assert!(matches!(e, Err(PdfError::BadSetting(m)) if m.contains("embeds"))); } +/// The ICC tag signatures of `icc`'s tag table. +fn icc_tags(icc: &[u8]) -> Vec { + let count = u32::from_be_bytes(icc[128..132].try_into().unwrap()) as usize; + (0..count).map(|i| String::from_utf8_lossy(&icc[132 + 12 * i..136 + 12 * i]).into_owned()).collect() +} + +#[test] +fn a_registered_condition_profile_names_its_condition_and_embeds_itself() { + use std::io::Read; + let d = doc(&[Color::cmyk(0.0, 1.0, 1.0, 0.0), Color::cmyk(0.6, 0.0, 0.2, 0.1)]); + for (profile, reference) in [(cms::FOGRA51_CMYK, "FOGRA51"), (cms::FOGRA52_CMYK, "FOGRA52")] { + let r = export_with_report(&d, &opts(Standard::PdfX4, |s| s.output.output_intent = profile.into())).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let t = text(&r.bytes); + let info = profile.replace('(', r"\(").replace(')', r"\)"); + for want in [ + "/S/GTS_PDFX".to_string(), + format!("/OutputConditionIdentifier({reference})"), + "/RegistryName(http://www.color.org)".into(), + format!("/Info({info})"), + ] { + assert!(t.contains(&want), "{profile}: {want}"); + } + // The embedded profile is the working space's: a CMYK output profile with Lab tables both + // ways, read from the file's bytes. + let oi: u32 = t.split("/DestOutputProfile ").nth(1).unwrap().split(' ').next().unwrap().parse().unwrap(); + let (start, end) = crate::patch::Xref::read(&r.bytes).unwrap().dict(&r.bytes, oi).unwrap(); + let obj = &r.bytes[start..end]; + let at = crate::lab_spot::find(obj, b"/Length", 0).unwrap(); + let (length, _) = crate::patch::number(obj, at + b"/Length".len()).unwrap(); + let mut data = crate::lab_spot::find(obj, b"stream", at).unwrap() + b"stream".len(); + data += obj[data..].iter().take(2).take_while(|b| matches!(b, b'\r' | b'\n')).count(); + let raw = &obj[data..data + length]; + let mut icc = vec![]; + if crate::lab_spot::find(&obj[..data], b"/FlateDecode", 0).is_some() { + flate2::read::ZlibDecoder::new(raw).read_to_end(&mut icc).unwrap(); + } else { + icc = raw.to_vec(); + } + assert_eq!(icc.as_slice(), &*cms::icc_bytes(profile).unwrap()); + assert_eq!((&icc[12..16], &icc[16..20], &icc[20..24], &icc[36..40]), (&b"prtr"[..], &b"CMYK"[..], &b"Lab "[..], &b"acsp"[..])); + assert!(matches!(icc[8], 2 | 4), "ICC version {}", icc[8]); + let tags = icc_tags(&icc); + for tag in ["A2B0", "B2A0", "A2B1", "B2A1", "gamt", "wtpt", "desc", "cprt"] { + assert!(tags.iter().any(|t| t == tag), "{profile}: {tag} in {tags:?}"); + } + let back = cms::IccProfile::from_bytes(None, &icc).unwrap(); + assert_eq!((back.name.as_str(), back.kind), (profile, cms::ProfileKind::Cmyk)); + assert!(import(&r.bytes).is_ok()); + } + // A condition identifier or registry the settings give stays. + let o = opts(Standard::PdfX4, |s| { + s.output.output_intent = cms::FOGRA51_CMYK.into(); + s.output.output_condition_id = "Press 2".into(); + }); + let t = text(&export(&d, &o).unwrap()); + assert!(t.contains("/OutputConditionIdentifier(Press 2)") && !t.contains("/RegistryName"), "{t}"); + let o = opts(Standard::PdfX4, |s| { + s.output.output_intent = cms::FOGRA51_CMYK.into(); + s.output.registry = "https://example.com/registry".into(); + }); + let t = text(&export(&d, &o).unwrap()); + assert!(t.contains("/OutputConditionIdentifier(FOGRA51)") && t.contains("/RegistryName(https://example.com/registry)")); + // Other profiles keep their name as the identifier, with no registry. + let t = text(&export(&d, &opts(Standard::PdfX4, |s| s.output.output_intent = GENERIC_CMYK.into())).unwrap()); + let id = GENERIC_CMYK.replace('(', r"\(").replace(')', r"\)"); + assert!(t.contains(&format!("/OutputConditionIdentifier({id})")) && !t.contains("/RegistryName"), "{t}"); +} + #[test] fn pdfx_1a_files_have_no_rgb() { let mut d = doc(&[Color::rgb(0.9, 0.1, 0.1), Color::Lab { l: 50.0, a: 40.0, b: -20.0 }, Color::gray(0.5), Color::cmyk(0.1, 0.2, 0.3, 0.4)]); diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index 0a964167a2..c5d80823d6 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "vectorcraft-plugins" -description = "Sandboxed WebAssembly plug-ins for VectorCraft: a resource-limited wasmi host for object filters and live effects" +description = "Sandboxed plug-ins for VectorCraft: a resource-limited wasmi host for object filters and live effects, and JavaScript object filters" version.workspace = true edition.workspace = true license.workspace = true @@ -21,6 +21,8 @@ craft-vectorcraft-format = { workspace = true } # The SHA-256 of a module, which the install prompt shows and a grant records. sha2 = { version = "0.10", default-features = false } thiserror = { workspace = true } +# The interpreter of JavaScript plug-ins (`js.rs`). +vectorcraft-js = { workspace = true } wasmi = { workspace = true } wasmparser = { workspace = true } # The monotonic clock of run deadlines and the first-view budget: `std::time::Instant` on the diff --git a/crates/plugins/src/dialog.rs b/crates/plugins/src/dialog.rs index 3777dab2e0..f154065fae 100644 --- a/crates/plugins/src/dialog.rs +++ b/crates/plugins/src/dialog.rs @@ -1,5 +1,6 @@ //! How the host's generated dialogs show a plug-in's parameters: the optional `label`, `unit`, -//! `group`, `help`, `helpUrl` and `visibleWhen` keys of each one (docs/plugins.md › Parameters). +//! `group`, `help`, `helpUrl`, `visibleWhen` and `widget` keys of each one +//! (docs/plugins.md › Parameters). //! //! These keys are presentation only. A host from before them ignores them, so a plug-in that //! declares them still installs there, and a plug-in is given every parameter whether its dialog @@ -58,6 +59,48 @@ pub struct ParamUi { /// Shown only while each parameter named here has one of the values listed for it. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub visible_when: BTreeMap>, + /// The control that shows a number: [`Widget::Slider`] adds a slider beside its field. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub widget: Option, +} + +/// The control a `number` or `int` parameter's row shows besides its number field (`widget`). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Widget { + /// A slider over `min..max`, beside the number field. + Slider, +} + +/// The largest whole number an `f64` holds exactly, which bounds an `int` slider's range. +const EXACT_INT: i64 = 1 << 53; + +impl ParamUi { + /// The range a slider shows `spec`'s value over, when the parameter asks for one + /// ([`Widget::Slider`]) and `spec` is a `number` or `int` the manifest checks allow it on. + pub fn slider_range(&self, spec: &ParamSpec) -> Option> { + if self.widget != Some(Widget::Slider) { + return None; + } + match spec { + ParamSpec::Number { min, max, .. } if min < max => Some(*min..=*max), + ParamSpec::Int { min, max, .. } if min < max && -EXACT_INT <= *min && *max <= EXACT_INT => Some(*min as f64..=*max as f64), + _ => None, + } + } + + /// Checks `widget` against parameter `spec`; `bad` builds the error. + fn validate_slider(&self, spec: &ParamSpec, bad: impl Fn(&str) -> Result<()>) -> Result<()> { + if self.widget.is_none() || self.slider_range(spec).is_some() { + return Ok(()); + } + match spec { + ParamSpec::Number { .. } | ParamSpec::Int { .. } => { + bad(&format!("a slider needs `min` below `max`, and an `int` slider a range within ±{EXACT_INT}")) + } + _ => bad("a slider is only for `number` and `int` parameters"), + } + } } /// Is `s` 1 to `max` characters, not all spaces, without control characters (`\n` too, unless @@ -86,6 +129,9 @@ impl ParamUi { return bad(&format!("`helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes")); } } + if let Some((_, p)) = m.params.get(index) { + self.validate_slider(&p.spec, bad)?; + } if self.visible_when.len() > MAX_CONDITIONS { return bad(&format!("`visibleWhen` names at most {MAX_CONDITIONS} parameters")); } @@ -304,4 +350,46 @@ mod tests { let fine = with("help", r#""Two\nlines.""#); assert!(Manifest::parse(fine.as_bytes()).is_ok()); } + + /// A `number` or `int` parameter with a range may ask for a slider; the key reads back as + /// written, and a parameter without it asks for none. + #[test] + fn slider_key_parses_and_round_trips() { + let m = Manifest::parse( + br#"{"id":"a","name":"x","kind":"filter","params":{ + "area":{"type":"number","min":0,"max":100,"default":10,"widget":"slider"}, + "count":{"type":"int","min":1,"max":20,"default":4,"widget":"slider"}, + "plain":{"type":"number","min":0,"max":100,"default":10}}}"#, + ) + .unwrap(); + let (area, count, plain) = (m.param("area").unwrap(), m.param("count").unwrap(), m.param("plain").unwrap()); + assert_eq!(area.ui.slider_range(&area.spec), Some(0.0..=100.0)); + assert_eq!(count.ui.slider_range(&count.spec), Some(1.0..=20.0)); + assert_eq!(plain.ui.slider_range(&plain.spec), None); + assert_eq!(Manifest::parse(&serde_json::to_vec(&m).unwrap()).unwrap(), m); + assert_eq!(serde_json::to_value(&m).unwrap()["params"]["count"]["widget"], json!("slider")); + } + + #[test] + fn slider_keys_that_cannot_apply_are_refused() { + let param = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{"p":{p}}}}}"#); + for bad in [ + // Only numbers have a slider, over a range that has room to move. + r#"{"type":"bool","widget":"slider"}"#, + r#"{"type":"choice","options":["a","b"],"widget":"slider"}"#, + r#"{"type":"numberList","min":0,"max":1,"widget":"slider"}"#, + r#"{"type":"number","min":5,"max":5,"default":5,"widget":"slider"}"#, + r#"{"type":"int","min":0,"max":9007199254740993,"widget":"slider"}"#, + // A control the host doesn't have. + r#"{"type":"number","min":0,"max":1,"default":0,"widget":"knob"}"#, + ] { + assert!(Manifest::parse(param(bad).as_bytes()).is_err(), "{bad}"); + } + // A command's parameters are checked the same way. + let command = |p: &str| format!(r#"{{"id":"a","name":"x","kind":"filter","commands":[{{"id":"go","label":"Go","params":{{"p":{p}}}}}]}}"#); + assert!(Manifest::parse(command(r#"{"type":"number","min":0,"max":1,"default":0,"widget":"slider"}"#).as_bytes()).is_ok()); + assert!(Manifest::parse(command(r#"{"type":"bool","widget":"slider"}"#).as_bytes()).is_err()); + let fine = param(r#"{"type":"int","min":0,"max":10,"widget":"slider"}"#); + assert!(Manifest::parse(fine.as_bytes()).is_ok()); + } } diff --git a/crates/plugins/src/host.rs b/crates/plugins/src/host.rs index 354610e4c0..fb12557f37 100644 --- a/crates/plugins/src/host.rs +++ b/crates/plugins/src/host.rs @@ -688,7 +688,7 @@ impl Run { } } - fn progress(&mut self, done: i64, total: i64) { + pub(crate) fn progress(&mut self, done: i64, total: i64) { let total = u64::try_from(total).unwrap_or(0); let done = u64::try_from(done).unwrap_or(0); let done = if total > 0 { done.min(total) } else { done }; @@ -710,12 +710,12 @@ impl Run { vectorcraft_doc::cancel::progress(done, total, PROGRESS_STEP); } - fn cancelled(&self) -> i32 { + pub(crate) fn cancelled(&self) -> i32 { i32::from(vectorcraft_doc::cancel::is_cancelled() || self.deadline.passed()) } /// Writes the `len` bytes at `ptr` in `memory` as a line of `level` → what `vc_log` returns. - fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 { + pub(crate) fn log(&mut self, level: i32, memory: &[u8], ptr: usize, len: usize) -> i32 { let Some(level) = LogLevel::from_code(level) else { return LOG_BAD_LEVEL }; let Some(bytes) = ptr.checked_add(len).and_then(|end| memory.get(ptr..end)) else { return LOG_OUTSIDE_MEMORY }; if self.report.truncated { diff --git a/crates/plugins/src/import.rs b/crates/plugins/src/import.rs index 599470e0aa..453ed75f41 100644 --- a/crates/plugins/src/import.rs +++ b/crates/plugins/src/import.rs @@ -7,6 +7,10 @@ //! sorts first opens it ([`for_extension`]). File › Open With and `document.open {importer}` pick an //! importer by its format id (`plugin.`), also for an extension a built-in format reads. //! +//! An importer whose manifest sets `place` also reads its files for File › Place (`file.place`), +//! by the same rules among the importers that set it ([`placing`]): its objects become one group in +//! the open document, and it is told so in `_context.mode` ([`Mode::Place`]). +//! //! The host hands the importer the file's bytes as they are, at most [`MAX_INPUT_BYTES`] of them, //! and reads back the objects of the new document in the same form filters return them //! ([`crate::objects`]): `{"objects": [...], "warnings"?: ["…"]}`, or `{"error": "…"}` to decline. @@ -61,6 +65,38 @@ pub fn for_extension(ext: &str) -> Vec> { installed().into_iter().filter(|p| p.manifest().extensions.contains(&ext)).collect() } +/// The installed importers whose manifests set `place` and that list extension `ext` (any case, +/// leading dot allowed), by plug-in id: the first is the one File › Place uses. +pub fn placing(ext: &str) -> Vec> { + for_extension(ext).into_iter().filter(|p| p.manifest().place).collect() +} + +/// The error of importer `m`, whose manifest doesn't set `place`, asked to place a file. +pub fn not_placing(m: &crate::Manifest) -> Error { + let shown = crate::permissions::display_text(&m.name, crate::permissions::MAX_SHOWN_NAME); + Error::Params(format!("“{shown}” opens files but doesn't place them: its manifest doesn't set `place`")) +} + +/// What an import is for, which the importer is told as `_context.mode`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// File › Open: the objects become a new document (`"import"`). + Import, + /// File › Place: the objects become one group in the open document (`"place"`). Only an + /// importer whose manifest sets `place` runs for it. + Place, +} + +impl Mode { + /// Its name in `_context.mode`. + pub fn name(self) -> &'static str { + match self { + Mode::Import => "import", + Mode::Place => "place", + } + } +} + /// What an importer returned. #[derive(Clone, Debug, PartialEq)] pub struct Imported { @@ -93,15 +129,24 @@ pub fn limits(plugin: &Plugin) -> Limits { /// Runs importer `plugin` on `file`, the bytes of the file being opened, with `params` (checked /// against its manifest: missing ones take their defaults) for the file `source`. pub fn run(plugin: &Plugin, file: &[u8], params: &Value, source: Source) -> Result { + run_as(plugin, file, params, source, Mode::Import) +} + +/// [`run`] for `mode`. [`Mode::Place`] is refused for an importer whose manifest doesn't set `place` +/// ([`not_placing`]), before it runs. +pub fn run_as(plugin: &Plugin, file: &[u8], params: &Value, source: Source, mode: Mode) -> Result { let m = plugin.manifest(); if m.kind != Kind::Importer { return Err(not_importer(m)); } + if mode == Mode::Place && !m.place { + return Err(not_placing(m)); + } if file.len() > MAX_INPUT_BYTES { return Err(too_large()); } let mut params = Value::Object(m.resolve_params(params)?); - params["_context"] = json!({"mode": "import", "extension": source.extension, "name": source.name}); + params["_context"] = json!({"mode": mode.name(), "extension": source.extension, "name": source.name}); let params = serde_json::to_vec(¶ms).map_err(|e| Error::Params(e.to_string()))?; decode(&plugin.run_limited(file, ¶ms, &limits(plugin))?) } diff --git a/crates/plugins/src/js.rs b/crates/plugins/src/js.rs new file mode 100644 index 0000000000..a8fa158c41 --- /dev/null +++ b/crates/plugins/src/js.rs @@ -0,0 +1,517 @@ +//! JavaScript plug-ins: an object filter whose manifest gives `"runtime": "js"`, with its code in a +//! JavaScript file instead of a WebAssembly module, run on `vectorcraft-js`. +//! +//! On disk the plug-in is a manifest file (`.vcplugin`, JSON) with `"runtime": "js"` and `script`, +//! the name of its `.js` file in the same folder ([`crate::registry::read_js_package`]). The host +//! loads it as one JSON object, the manifest with the script's text in `source` +//! ([`read_bundle`]): that object is what `plugin.install {dataBase64}` takes, what the plug-in +//! store keeps, and what the SHA-256 a grant records covers, so a change to the manifest or to the +//! script needs a new approval. Loading parses the script and runs none of it. +//! +//! Each run gets a fresh realm with the language's built-ins and a `vc` object: `vc.input` +//! and `vc.params` hold the input and parameter JSON a WebAssembly filter's `vc_run` is given, and +//! with the `progress` permission `vc.progress(done, total)`, `vc.cancelled()` and +//! `vc.log(level, text)` do what `vc_progress`, `vc_cancelled` and `vc_log` do ([`crate::host`]). +//! The realm has no `$`, `File`, `Folder`, `app` or other global of the script runner, no clock +//! (`Date.now()` is `NaN`) and no host function besides these. The script's top level runs, then +//! `run(input, params)` is called with the parsed JSON, and the value it returns, written as JSON, +//! is the run's output, which the host checks as it checks a WebAssembly filter's. +//! +//! A run is held to the filter's instruction budget (one budget for the top level and the call, +//! checked in slices between which the deadline and Cancel are checked), a heap of at most the +//! plug-in's memory cap, and the interpreter's frame and re-entry limits. A thrown error, a limit +//! or a malformed result fails the run with an [`Error`] that names the plug-in, its script and, +//! when known, the line and column. + +use std::cell::RefCell; +use std::rc::Rc; + +use serde_json::{Map, Value}; +use vectorcraft_js::{Data, HostError, HostItem, JsValue, LimitKind, Progress, Realm, RunError, RunErrorKind}; + +use crate::host::{Deadline, LOG_BAD_LEVEL, LOG_DROPPED, LOG_WRITTEN, Report, Run}; +use crate::manifest::{MAX_MANIFEST_BYTES, Manifest, Runtime}; +use crate::permissions::{self, Permission}; +use crate::runtime::SELECTION_TOO_LARGE; +use crate::{Error, Limits, Result}; + +/// The extension of a JavaScript plug-in's manifest file. +pub const PACKAGE_EXT: &str = "vcplugin"; + +/// Largest script, in bytes. +pub const MAX_SCRIPT_BYTES: usize = 8 << 20; + +/// Longest script file name, in bytes. +pub const MAX_SCRIPT_NAME: usize = 128; + +/// The script's name when the plug-in's JSON gives none. +pub const DEFAULT_SCRIPT: &str = "plugin.js"; + +/// Instructions a run executes between two checks of its deadline and Cancel. +pub const FUEL_SLICE: u64 = 1_000_000; + +/// Longest error message a run reports, in characters. +const MAX_ERROR_TEXT: usize = 512; + +/// What `script` may hold. +const SCRIPT_NAME_RULE: &str = + "`script` must be the name of a .js file in the manifest's folder: 1-128 bytes, no folder, no `:`, not starting with `.`"; + +/// Where the script's text may be given. +pub const SOURCE_RULE: &str = + "`source` is the script's text, given only in the JSON that plugin.install's dataBase64 takes: a .vcplugin file names its script in `script`"; + +/// The error of a plug-in's JSON without `"runtime": "js"`. +pub(crate) const NOT_JS: &str = "a JavaScript plug-in's manifest gives `runtime` \"js\""; + +/// What the arguments of `vc.progress` and `vc.log` may be. +const PROGRESS_ARGS: &str = "vc.progress(done, total) takes two numbers"; +const LOG_ARGS: &str = "vc.log(level, text) takes a level, 0 (error), 1 (warning), 2 (information) or 3 (debug), and a string"; + +/// What runs the plug-in: its script's top level is done, `run` is called with the input and the +/// parameters, and what it returns is written as JSON. +const ENTRY: &str = "(function () {\n\ + if (typeof run !== 'function') throw new TypeError('the script defines no function run(input, params)');\n\ + return JSON.stringify(run(JSON.parse(vc.input), JSON.parse(vc.params)));\n\ +})()"; + +/// A JavaScript plug-in's code. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Script { + /// Its file name, which errors give. + pub(crate) name: String, + pub(crate) source: String, +} + +/// Is `name` a script file name `script` may give: a `.js` file directly in the manifest's folder? +pub fn valid_script_name(name: &str) -> bool { + (1..=MAX_SCRIPT_NAME).contains(&name.len()) + && !name.starts_with('.') + && !name.chars().any(|c| matches!(c, '/' | '\\' | ':') || c.is_control()) + && name.len() > 3 + && name.get(name.len() - 3..).is_some_and(|ext| ext.eq_ignore_ascii_case(".js")) +} + +/// The `script` a manifest's JSON gives, checked. +pub(crate) fn script_name(v: &Value) -> Result { + match v.as_str() { + Some(name) if valid_script_name(name) => Ok(name.to_string()), + _ => Err(Error::Manifest(SCRIPT_NAME_RULE.into())), + } +} + +/// The error of a manifest with `"runtime": "js"` and no `script`. +pub(crate) fn no_script() -> Error { + Error::Manifest("`runtime` \"js\" needs `script`: the name of the plug-in's .js file, next to the manifest".into()) +} + +/// Does `map`, a plug-in's JSON, give `"runtime": "js"`? +pub(crate) fn is_js(map: &Map) -> bool { + map.get("runtime").and_then(Value::as_str) == Some(Runtime::Js.name()) +} + +/// How the script is read. +fn options() -> vectorcraft_js::Options { + vectorcraft_js::Options { max_source_units: MAX_SCRIPT_BYTES, ..vectorcraft_js::Options::default() } +} + +/// Reads a JavaScript plug-in given as one JSON object: its manifest, with the script's text in +/// `source` and its file name in `script` (left out: [`DEFAULT_SCRIPT`]). The manifest is checked as +/// a module's is, and the script is parsed, not run. +pub(crate) fn read_bundle(bytes: &[u8]) -> Result<(Manifest, Script)> { + let mut map: Map = serde_json::from_slice(bytes).map_err(|e| Error::Manifest(e.to_string()))?; + if !is_js(&map) { + return Err(Error::Manifest(NOT_JS.into())); + } + let named = map.remove("script"); + let source = match map.remove("source") { + Some(Value::String(s)) => s, + Some(_) => return Err(Error::Manifest(SOURCE_RULE.into())), + None if named.is_some() => return Err(Error::Manifest(SOURCE_RULE.into())), + None => return Err(no_script()), + }; + let name = named.as_ref().map_or_else(|| Ok(DEFAULT_SCRIPT.to_string()), script_name)?; + if source.len() > MAX_SCRIPT_BYTES { + return Err(Error::Module(format!("{} is {} bytes (limit {})", name, source.len(), MAX_SCRIPT_BYTES))); + } + // The manifest is read from `bytes`, so `params` keep their order; its size is counted + // without `script` and `source`. + let size = serde_json::to_vec(&map).map_err(|e| Error::Manifest(e.to_string()))?.len(); + if size > MAX_MANIFEST_BYTES { + return Err(Error::Manifest(format!("manifest is {size} bytes (limit {MAX_MANIFEST_BYTES})"))); + } + let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?; + let manifest = Manifest::parse_text(text)?; + if let Err(e) = vectorcraft_js::parse(&source, &options()) { + let named = Named { id: &manifest.id, script: &name }; + return Err(Error::Module(located(&permissions::display_text(&e.message, MAX_ERROR_TEXT), &named, Some((e.line, e.column))))); + } + Ok((manifest, Script { name, source })) +} + +/// `reason` followed by where it happened: the plug-in's id, its script's name and, when `at` gives +/// them, the line and column. +fn located(reason: &str, named: &Named<'_>, at: Option<(u32, u32)>) -> String { + let (id, script) = (named.id, named.script); + match at { + Some((line, column)) if line > 0 => format!("{reason} ({id}, {script} line {line}, column {column})"), + _ => format!("{reason} ({id}, {script})"), + } +} + +/// One run's input and budgets. +pub(crate) struct Call<'a> { + pub(crate) input: &'a [u8], + pub(crate) params: &'a [u8], + pub(crate) limits: &'a Limits, + /// The plug-in's memory cap, which the run's heap stays within. + pub(crate) max_memory: usize, + pub(crate) deadline: Deadline, +} + +/// The heap a run may use with memory cap `max_memory`. +fn heap_bytes(max_memory: usize) -> usize { + vectorcraft_js::Limits::default().heap_bytes.min(max_memory) +} + +/// Runs `script`, the code of the plug-in `m` describes, on `call`'s input in a fresh realm → the +/// output JSON. What it reported with `vc.progress` and `vc.log` goes to `report`. +pub(crate) fn run(script: &Script, m: &Manifest, call: &Call<'_>, state: Run, report: &mut Report) -> Result> { + let heap = heap_bytes(call.max_memory); + // Each UTF-8 byte may become a UTF-16 code unit of two bytes, and the parsed JSON takes more. + if call.input.len().saturating_add(call.params.len()) > heap / 8 { + return Err(Error::Limit(SELECTION_TOO_LARGE.into())); + } + // The host writes the input and the parameters with serde_json, so they are UTF-8. + let (input, params) = (String::from_utf8_lossy(call.input), String::from_utf8_lossy(call.params)); + let state = Rc::new(RefCell::new(state)); + let out = run_realm(script, m, (&*input, &*params), call, heap, &state); + *report = std::mem::take(&mut state.borrow_mut().report); + out +} + +/// What errors name: the plug-in's id and its script's file name. +struct Named<'a> { + id: &'a str, + script: &'a str, +} + +fn run_realm( + script: &Script, + m: &Manifest, + (input, params): (&str, &str), + call: &Call<'_>, + heap: usize, + state: &Rc>, +) -> Result> { + let defaults = vectorcraft_js::Limits::default(); + let fuel = call.limits.fuel_base.saturating_add((call.input.len() as u64).saturating_mul(call.limits.fuel_per_byte)); + let limits = vectorcraft_js::Limits { fuel, heap_bytes: heap, ..defaults }; + let mut realm = Realm::with_options(options(), limits); + realm.set_clock(|| f64::NAN); + let named = Named { id: &m.id, script: &script.name }; + realm.define_host_object("vc", vc_items(input, params, m, state)).map_err(|e| match e.kind { + RunErrorKind::Limit(LimitKind::Heap) => Error::Limit(SELECTION_TOO_LARGE.into()), + _ => js_error(&realm, e, vectorcraft_js::UNKNOWN_SOURCE, &named), + })?; + let (_, tag) = drive(&mut realm, &script.source, &call.deadline, &named, None)?; + // The call takes what the top level left of the budget. + let left = realm.fuel_left(); + realm.set_limits(vectorcraft_js::Limits { fuel: left, ..realm.limits().clone() }); + let (value, _) = drive(&mut realm, ENTRY, &call.deadline, &named, Some(tag))?; + vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; + call.deadline.check()?; + match value { + JsValue::String(s) if s.len() > call.limits.max_output_bytes => { + let (what, len, max) = ("the output", s.len(), call.limits.max_output_bytes); + Err(Error::Limit(format!("output size ({what} is {len} bytes, limit {max})"))) + } + JsValue::String(s) => Ok(s.into_bytes()), + _ => Err(Error::Output(located(NO_OUTPUT, &named, None))), + } +} + +/// The error of a `run` that returned nothing JSON can write. +const NO_OUTPUT: &str = "run(input, params) returned no output object"; + +/// The limit a run that nested its calls too deeply exceeded. +const CALL_DEPTH: &str = "call depth"; + +/// Runs `source` in `realm` to its end, in slices of [`FUEL_SLICE`] with the deadline and Cancel +/// checked between them → its completion value, and the source tag of the plug-in's script: +/// `script_tag`, or with `None` the tag of `source`, which is then the script. +fn drive(realm: &mut Realm, source: &str, deadline: &Deadline, named: &Named<'_>, script_tag: Option) -> Result<(JsValue, u32)> { + let started = realm.start(source); + let tag = script_tag.unwrap_or_else(|| realm.script_tag()); + started.map_err(|e| js_error(realm, e, tag, named))?; + loop { + match realm.advance(FUEL_SLICE) { + Ok(Progress::Done(v)) => return Ok((v, tag)), + Ok(Progress::Paused) => {} + Err(e) => return Err(js_error(realm, e, tag, named)), + } + if vectorcraft_doc::cancel::check().is_err() { + realm.end(); + return Err(Error::Cancelled); + } + if let Err(e) = deadline.check() { + realm.end(); + return Err(e); + } + } +} + +/// The plug-in error for `e`, which a run of `realm` ended with: it names the plug-in and the script, +/// and the line and column when the error is in the script (source tag `tag`). +fn js_error(realm: &Realm, e: RunError, tag: u32, named: &Named<'_>) -> Error { + let at = (realm.error_tag() == tag).then_some((e.line, e.column)); + let message = permissions::display_text(&e.message, MAX_ERROR_TEXT); + match e.kind { + RunErrorKind::Syntax => Error::Module(located(&message, named, at)), + RunErrorKind::Thrown | RunErrorKind::Limit(LimitKind::Host) => Error::Failed(located(&message, named, at)), + RunErrorKind::Limit(LimitKind::Jobs) => Error::Limit(located(&message, named, at)), + RunErrorKind::Limit(LimitKind::Fuel | LimitKind::Unbroken) => Error::Limit(located("instruction budget", named, at)), + RunErrorKind::Limit(LimitKind::Heap) => Error::Limit(located("memory budget", named, at)), + RunErrorKind::Limit(LimitKind::Frames | LimitKind::Reentry) => Error::Limit(located(CALL_DEPTH, named, at)), + RunErrorKind::Limit(LimitKind::Interrupted) => Error::Cancelled, + RunErrorKind::Internal => Error::Trap(located(&message, named, at)), + } +} + +/// The members of the realm's `vc` object. +fn vc_items(input: &str, params: &str, m: &Manifest, state: &Rc>) -> Vec<(String, HostItem)> { + let mut items = vec![ + ("input".to_string(), HostItem::Value(Data::String(input.into()))), + ("params".to_string(), HostItem::Value(Data::String(params.into()))), + ]; + if !m.permissions().contains(&Permission::Progress) { + return items; + } + let number = |args: &[Data], i: usize, rule: &str| match args.get(i) { + Some(Data::Number(n)) => Ok(*n), + _ => Err(HostError::Type(rule.into())), + }; + let run = state.clone(); + items.push(( + "progress".into(), + HostItem::Function(Rc::new(move |args| { + let (done, total) = (number(&args, 0, PROGRESS_ARGS)?, number(&args, 1, PROGRESS_ARGS)?); + // `as` turns NaN into 0 and clamps the rest, as `vc_progress` clamps negative values. + run.borrow_mut().progress(done as i64, total as i64); + Ok(Data::Undefined) + })), + )); + let run = state.clone(); + items.push(("cancelled".into(), HostItem::Function(Rc::new(move |_| Ok(Data::Bool(run.borrow().cancelled() == 1)))))); + let run = state.clone(); + items.push(( + "log".into(), + HostItem::Function(Rc::new(move |args| { + let level = number(&args, 0, LOG_ARGS)?; + let Some(Data::String(text)) = args.get(1) else { return Err(HostError::Type(LOG_ARGS.into())) }; + let level = if level.fract() == 0.0 && (0.0..=3.0).contains(&level) { level as i32 } else { LOG_BAD_LEVEL }; + match run.borrow_mut().log(level, text.as_bytes(), 0, text.len()) { + LOG_WRITTEN => Ok(Data::Bool(true)), + LOG_DROPPED => Ok(Data::Bool(false)), + _ => Err(HostError::Range(LOG_ARGS.into())), + } + })), + )); + items +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + + use crate::{Error, Limits, Plugin}; + + /// A JavaScript filter `id` with `source` as its code, and `extra` manifest keys. + fn bundle(id: &str, source: &str, extra: Value) -> Vec { + let mut m = json!({"id": id, "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js", "source": source}); + if let (Some(m), Value::Object(extra)) = (m.as_object_mut(), extra) { + m.extend(extra); + } + serde_json::to_vec(&m).unwrap() + } + + fn load(bytes: &[u8]) -> crate::Result { + load_with(bytes, Limits::default()) + } + + fn load_with(bytes: &[u8], limits: Limits) -> crate::Result { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + Plugin::load(bytes, limits) + } + + const PATH: &str = r#"{"objects":[{"id":7,"type":"path","fills":[{"type":"solid","color":{"model":"rgb","r":1,"g":0,"b":0}}]}]}"#; + + /// The output of `run(input, params)` is the run's output JSON. + #[test] + fn a_filter_returns_its_objects_as_json() { + let src = "function run(input, params) { return {objects: input.objects.map(function (o) { \ + return {id: o.id, fills: [{type: 'solid', color: {model: 'rgb', r: 0, g: 0, b: params.blue}}]}; })}; }"; + let p = load(&bundle("test.js.blue", src, json!({}))).unwrap(); + assert_eq!((p.runtime(), p.script()), (crate::Runtime::Js, Some("test.js"))); + let out: Value = serde_json::from_slice(&p.run(PATH.as_bytes(), br#"{"blue":1}"#).unwrap()).unwrap(); + assert_eq!(out, json!({"objects": [{"id": 7, "fills": [{"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}]}]})); + } + + /// The realm has none of the script runner's globals, so code that reads them throws a + /// `ReferenceError` naming the global, the plug-in and where in its script. + #[test] + fn file_folder_and_app_are_not_defined() { + for name in ["File", "Folder", "$", "app", "BridgeTalk"] { + let src = format!("function run(input) {{\n return {name}.x;\n}}"); + let e = load(&bundle("test.js.globals", &src, json!({}))).unwrap().run(PATH.as_bytes(), b"{}").unwrap_err(); + let Error::Failed(why) = &e else { panic!("{name}: {e:?}") }; + assert!(why.starts_with("ReferenceError") && why.contains(name), "{name}: {why}"); + assert!(why.ends_with("(test.js.globals, test.js line 2, column 10)"), "{name}: {why}"); + } + let p = load(&bundle("test.js.clock", "function run() { return {objects: [], n: String(Date.now())}; }", json!({}))).unwrap(); + let out: Value = serde_json::from_slice(&p.run(b"{\"objects\":[]}", b"{}").unwrap()).unwrap(); + assert_eq!(out["n"], "NaN", "no clock"); + } + + /// Each run has a realm of its own: what one run changes in the built-ins, the next run doesn't + /// see. + #[test] + fn a_polluted_prototype_does_not_reach_the_next_run() { + let src = "function run() { var seen = Object.prototype.polluted; Object.prototype.polluted = 1; \ + Array.prototype.map = null; return {objects: [], seen: String(seen)}; }"; + let p = load(&bundle("test.js.pollute", src, json!({}))).unwrap(); + for _ in 0..2 { + let out: Value = serde_json::from_slice(&p.run(b"{\"objects\":[]}", b"{}").unwrap()).unwrap(); + assert_eq!(out["seen"], "undefined"); + } + } + + /// An endless loop ends with the instruction budget, naming the plug-in and the line. + #[test] + fn an_endless_loop_ends_with_the_instruction_budget() { + let p = load(&bundle("test.js.loop", "function run() {\n for (;;) {}\n}", json!({}))).unwrap(); + let limits = Limits { fuel_base: 3 * super::FUEL_SLICE, fuel_per_byte: 0, ..Limits::default() }; + let e = p.run_limited(b"{\"objects\":[]}", b"{}", &limits).unwrap_err(); + assert!(matches!(&e, Error::Limit(why) if why.starts_with("instruction budget (test.js.loop, test.js line 2")), "{e:?}"); + } + + /// A plug-in that fills its heap ends with its memory budget, and a realm another caller holds + /// meanwhile, such as a script's, runs on as before. + #[test] + fn heap_exhaustion_leaves_a_held_realm_usable() { + let mut held = vectorcraft_js::Realm::new(); + held.run("var kept = 41;").unwrap(); + let src = "function run() { var a = []; for (;;) { a.push(new Array(1000).join('x') + a.length); } }"; + let small = load_with(&bundle("test.js.heap", src, json!({})), Limits { max_memory_bytes: 8 << 20, ..Limits::default() }).unwrap(); + let e = small.run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Limit(why) if why.starts_with("memory budget (test.js.heap")), "{e:?}"); + assert_eq!(held.run("kept + 1").unwrap(), vectorcraft_js::JsValue::Number(42.0)); + } + + /// An input too large for the heap is refused before it is copied in. + #[test] + fn a_selection_too_large_for_the_heap_is_refused() { + let small = + load_with(&bundle("test.js.big", "function run(i) { return i; }", json!({})), Limits { max_memory_bytes: 1 << 20, ..Limits::default() }) + .unwrap(); + let input = format!(r#"{{"objects":[],"pad":"{}"}}"#, "x".repeat(200_000)); + assert_eq!(small.run(input.as_bytes(), b"{}"), Err(Error::Limit(crate::runtime::SELECTION_TOO_LARGE.into()))); + } + + /// A result that isn't an output object, and a script without `run`, fail the run. + #[test] + fn a_missing_entry_or_result_fails_the_run() { + let e = load(&bundle("test.js.none", "var x = 1;", json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.contains("defines no function run")), "{e:?}"); + let e = load(&bundle("test.js.undef", "function run() {}", json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Output(why) if why.contains("test.js.undef")), "{e:?}"); + let e = load(&bundle("test.js.cycle", "function run() { var o = {}; o.o = o; return o; }", json!({}))) + .unwrap() + .run(b"{\"objects\":[]}", b"{}") + .unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.starts_with("TypeError")), "{e:?}"); + } + + /// With `progress`, `vc.progress` and `vc.log` report as their imports do; without it, `vc` + /// has neither. + #[test] + fn progress_and_log_need_the_progress_permission() { + let src = "function run() { vc.progress(3, 4); vc.log(2, 'half'); return {objects: [], cancelled: vc.cancelled()}; }"; + let p = load(&bundle("test.js.progress", src, json!({"api": 2, "permissions": ["progress"]}))).unwrap(); + let (out, report) = p.run_reporting(b"{\"objects\":[]}", b"{}", p.limits()); + let out: Value = serde_json::from_slice(&out.unwrap()).unwrap(); + assert_eq!(out["cancelled"], false); + assert_eq!(report.progress, Some((3, 4))); + assert_eq!(report.lines, vec![crate::LogLine { level: crate::LogLevel::Info, text: "half".into() }]); + let e = load(&bundle("test.js.quiet", src, json!({}))).unwrap().run(b"{\"objects\":[]}", b"{}").unwrap_err(); + assert!(matches!(&e, Error::Failed(why) if why.starts_with("TypeError")), "{e:?}"); + } + + /// Loading checks the manifest and the script, and runs none of it. + #[test] + fn loading_refuses_a_bad_manifest_or_script() { + let ok = "function run() { return {objects: []}; }"; + let refused = |bytes: Vec| load(&bytes).unwrap_err(); + let e = refused(bundle("test.js.syntax", "function run( {", json!({}))); + assert!(matches!(&e, Error::Module(why) if why.contains("(test.js.syntax, test.js line 1, column")), "{e:?}"); + let big = "x".repeat(super::MAX_SCRIPT_BYTES + 1); + assert!(matches!(refused(bundle("test.js.big", &big, json!({}))), Error::Module(why) if why.starts_with("test.js is"))); + let e = refused(bundle("test.js.effect", ok, json!({"kind": "effect"}))); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`runtime` \"js\" is for an object filter")), "{e:?}"); + let e = refused(bundle("test.js.settings", ok, json!({"api": 2, "permissions": ["settings"]}))); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`settings`")), "{e:?}"); + let e = refused(bundle("test.js.name", ok, json!({"script": "../x.js"}))); + assert!(matches!(&e, Error::Manifest(why) if why.starts_with("`script`")), "{e:?}"); + let e = refused(bundle("test.js.py", ok, json!({"runtime": "py"}))); + assert!(matches!(&e, Error::Manifest(why) if why == super::NOT_JS), "{e:?}"); + let mut no_source: Value = serde_json::from_slice(&bundle("test.js.nosource", ok, json!({}))).unwrap(); + no_source.as_object_mut().unwrap().remove("source"); + let e = refused(serde_json::to_vec(&no_source).unwrap()); + assert!(matches!(&e, Error::Manifest(why) if why.contains("`source`")), "{e:?}"); + // Top-level code that would throw does not run at load. + assert!(load(&bundle("test.js.lazy", "throw new Error('ran');", json!({}))).is_ok()); + } + + /// A WebAssembly module's manifest can't give `"runtime": "js"`. + #[test] + fn a_module_manifest_cannot_be_javascript() { + let manifest = r#"{"id":"test.js.wasm","name":"T","kind":"filter","runtime":"js"}"#; + let bytes = wat::parse_str(crate::wat::returning(manifest, r#"{"objects":[]}"#)).unwrap(); + assert!(matches!(load(&bytes), Err(Error::Manifest(why)) if why.contains("`runtime`"))); + } + + /// The SHA-256 a grant records is the bundle's, so another script is another module. + #[test] + fn the_hash_covers_the_script() { + let a = load(&bundle("test.js.hash", "function run() { return {objects: []}; }", json!({}))).unwrap(); + let b = load(&bundle("test.js.hash", "function run() { return {objects: [] }; }", json!({}))).unwrap(); + assert_ne!(a.hash(), b.hash()); + } + + /// The parameters, and a command's, keep the order the plug-in's JSON declares them in. + #[test] + fn params_keep_their_declaration_order() { + let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#; + let text = format!( + r#"{{"id": "test.js.order", "name": "JS test", "kind": "filter", "runtime": "js", "script": "test.js", + "params": {{"z": {num}, "a": {num}, "m": {num}}}, + "commands": [{{"id": "go", "label": "Go", "params": {{"y": {num}, "b": {num}}}}}], + "source": "function run(i) {{ return i; }}"}}"# + ); + let (manifest, _) = super::read_bundle(text.as_bytes()).unwrap(); + let names = |p: &[(String, crate::manifest::Param)]| p.iter().map(|(k, _)| k.clone()).collect::>(); + assert_eq!(names(&manifest.params), ["z", "a", "m"]); + assert_eq!(names(&manifest.commands[0].params), ["y", "b"]); + } + + #[test] + fn script_names_stay_in_the_manifest_s_folder() { + for ok in ["tint.js", "Tint Tool.JS", "a.b.js"] { + assert!(super::valid_script_name(ok), "{ok}"); + } + for bad in ["", ".js", ".hidden.js", "../x.js", "sub/x.js", "sub\\x.js", "c:x.js", "x.jsx", "x.js\n", "x.wasm"] { + assert!(!super::valid_script_name(bad), "{bad:?}"); + } + assert!(!super::valid_script_name(&format!("{}.js", "a".repeat(126)))); + } +} diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index df4c9a0a23..c4597fcec4 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -32,6 +32,10 @@ //! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A //! filter or a live effect may also add menu commands of its own ([`Command`]), which the host //! runs through `vc_run` with the command's id in `_context`. +//! +//! An object filter may also be written in JavaScript ([`js`]): its manifest gives +//! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each +//! run, with the same input, output, permissions and budgets. #![forbid(unsafe_code)] pub mod deferred; @@ -40,6 +44,7 @@ pub mod effect; pub mod export; pub mod host; pub mod import; +pub mod js; pub mod loader; pub mod manifest; pub mod objects; @@ -53,7 +58,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; -pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec}; +pub use manifest::{Budget, Command, ContextSection, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec, Runtime}; pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index f20756e149..56b8357cf1 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; use crate::dialog::ParamUi; -use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission}; +use crate::permissions::{self, API_LEVEL, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission, WRITES_API}; use crate::{Error, Result}; /// Longest manifest the host reads. @@ -224,6 +224,32 @@ impl Budget { } } +/// What runs a plug-in's code. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Runtime { + /// A WebAssembly module ([`crate::Plugin::load`]); the manifest is the module's `vc_manifest`. + #[default] + Wasm, + /// A JavaScript file run on `vectorcraft-js` ([`crate::js`]): an object filter whose manifest + /// gives `"runtime": "js"`. + Js, +} + +impl Runtime { + pub fn name(self) -> &'static str { + match self { + Runtime::Wasm => "wasm", + Runtime::Js => "js", + } + } + + /// WebAssembly, which a manifest written back leaves out (`skip_serializing_if`). + fn is_wasm(&self) -> bool { + *self == Runtime::Wasm + } +} + /// One declared parameter. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] @@ -456,6 +482,11 @@ pub struct Manifest { /// lists them. Left out or empty, it is given paths and compound paths alone. #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "input_names")] pub inputs: Vec, + /// The kinds among `inputs` the filter may change, by [`InputKind::name`]: only a filter at + /// `api` 3 or later whose `permissions` list `doc.read` and `doc.write` lists them. Left out or + /// empty, every kind it reads stays read-only. + #[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "write_names")] + pub writes: Vec, /// The parts of the document a run is given in `_context.document`, by /// [`ContextSection::name`]: only a filter, or a live effect with `commands` (for its command /// runs), at `api` 3 or later whose `permissions` list `doc.read` lists them. Left out or empty, @@ -469,6 +500,11 @@ pub struct Manifest { /// the one an exporter's files get. Only exporters and importers declare them. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub extensions: Vec, + /// An importer whose files File › Place also reads (`file.place`), into the open document as one + /// group ([`crate::import::Mode::Place`]): `true` when the manifest has `"place": true`. Only an + /// importer sets it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub place: bool, /// How much a run may compute: only a filter may be [`Budget::Heavy`]. #[serde(default, skip_serializing_if = "Budget::is_light")] pub budget: Budget, @@ -484,6 +520,9 @@ pub struct Manifest { /// lists any ([`Manifest::validate`]). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub command_allowlist: Vec, + /// What runs its code: WebAssembly when left out, or `"js"` for a JavaScript filter. + #[serde(default, skip_serializing_if = "Runtime::is_wasm")] + pub runtime: Runtime, } impl Manifest { @@ -493,6 +532,13 @@ impl Manifest { return Err(Error::Manifest(format!("manifest is {} bytes (limit {MAX_MANIFEST_BYTES})", bytes.len()))); } let text = std::str::from_utf8(bytes).map_err(|_| Error::Manifest("manifest is not UTF-8".into()))?; + Manifest::parse_text(text) + } + + /// [`Manifest::parse`] without its size limit, for JSON that holds other keys besides the + /// manifest's (a JavaScript plug-in's `source`), whose caller checks the manifest's size. Keys + /// the manifest doesn't declare are ignored, and `params` keep the order the text gives them. + pub(crate) fn parse_text(text: &str) -> Result { if serde_json::from_str::(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) { return Err(Error::Manifest("`paintOutput` may only be true".into())); } @@ -514,13 +560,16 @@ impl Manifest { api: 1, permissions: None, inputs: Vec::new(), + writes: Vec::new(), context: Vec::new(), params: Vec::new(), extensions: Vec::new(), + place: false, budget: Budget::Light, paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + runtime: Runtime::Wasm, } } @@ -585,11 +634,15 @@ impl Manifest { return Err(Error::Manifest(format!("permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API}"))); } self.validate_inputs()?; + self.validate_writes()?; self.validate_context()?; if self.paint_output && (self.kind != Kind::Effect || self.api < 2) { return Err(Error::Manifest("`paintOutput` is only for a live effect (`kind` \"effect\") at `api` 2".into())); } self.validate_extensions()?; + if self.place && self.kind != Kind::Importer { + return Err(Error::Manifest("`place` is only for an importer (`kind` \"importer\")".into())); + } match (self.budget, self.kind) { (Budget::Light, _) | (Budget::Heavy, Kind::Filter) => {} (Budget::Heavy, Kind::Effect) => { @@ -604,7 +657,30 @@ impl Manifest { } self.validate_params()?; self.validate_commands()?; - self.validate_allowlist() + self.validate_allowlist()?; + self.validate_runtime() + } + + /// A JavaScript plug-in (`"runtime": "js"`) is an object filter, and of the host's permissions + /// it lists only `progress`: its realm has no settings, cache or command calls. + fn validate_runtime(&self) -> Result<()> { + if self.runtime == Runtime::Wasm { + return Ok(()); + } + if self.kind != Kind::Filter { + let kind = self.kind.name(); + return Err(Error::Manifest(format!("`runtime` \"js\" is for an object filter (`kind` \"filter\"), not `kind` \"{kind}\""))); + } + let listed = self.permissions.as_deref().unwrap_or_default(); + for p in [Permission::Settings, Permission::Cache, Permission::Commands] { + if listed.iter().any(|n| n == p.name()) { + let name = p.name(); + return Err(Error::Manifest(format!( + "a JavaScript plug-in can't list the permission `{name}`: of the host's permissions it may list `progress`" + ))); + } + } + Ok(()) } /// `commandAllowlist` lists at most [`MAX_ALLOWED_COMMANDS`] distinct command ids @@ -682,6 +758,37 @@ impl Manifest { Ok(()) } + /// `writes` names each [`InputKind`] at most once, each one `inputs` lists, and only a filter at + /// `api` 3 or later lists any, with a `permissions` list that holds `doc.read` and `doc.write`. + fn validate_writes(&self) -> Result<()> { + if self.writes.is_empty() { + return Ok(()); + } + if self.kind != Kind::Filter { + return Err(Error::Manifest("only a filter declares `writes`".into())); + } + for (i, name) in self.writes.iter().enumerate() { + let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD); + if InputKind::parse(name).is_none() { + return Err(Error::Manifest(format!("`writes` names an unknown object kind `{shown}`: use type, image or symbolInstance"))); + } + if self.writes.get(..i).is_some_and(|before| before.contains(name)) { + return Err(Error::Manifest(format!("`writes` lists `{shown}` twice"))); + } + if !self.inputs.contains(name) { + return Err(Error::Manifest(format!("`writes` lists `{shown}`, which `inputs` doesn't list"))); + } + } + if self.api < WRITES_API { + return Err(Error::Manifest(format!("`writes` needs `api` {WRITES_API} or later"))); + } + let listed = |p: Permission| self.permissions.as_ref().is_some_and(|names| names.iter().any(|n| n == p.name())); + if !listed(Permission::DocWrite) { + return Err(Error::Manifest("`writes` needs the permission `doc.write`".into())); + } + Ok(()) + } + /// `context` names each [`ContextSection`] at most once, and only a filter, or a live effect /// with commands, at `api` 3 or later lists any, with a `permissions` list that holds /// `doc.read`: installing it then asks the user to grant it ([`Manifest::asks_permissions`]). @@ -755,6 +862,11 @@ impl Manifest { self.inputs.iter().filter_map(|n| InputKind::parse(n)).collect() } + /// The kinds among those it reads that it may change (`writes`). + pub fn write_kinds(&self) -> Vec { + self.writes.iter().filter_map(|n| InputKind::parse(n)).collect() + } + /// An exporter or an importer lists 1 to [`MAX_EXTENSIONS`] distinct extensions of 1 to 16 /// lower-case letters and digits; other kinds list none. fn validate_extensions(&self) -> Result<()> { @@ -924,6 +1036,16 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result, D::Error> { + let wrong = || serde::de::Error::custom("`writes` must be a list of object kinds: type, image or symbolInstance"); + match Value::deserialize(d)? { + Value::Null => Ok(Vec::new()), + Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(), + _ => Err(wrong()), + } +} + /// Reads `context`: a list of names (`null`: none). Anything else is the error /// [`Manifest::validate_context`] gives a wrong entry. fn context_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { @@ -1258,6 +1380,33 @@ mod tests { } } + /// Only an importer sets `place`, to a boolean, and it asks for no permission beyond + /// `import.read`; false, the default, isn't written back. + #[test] + fn only_an_importer_places_its_files() { + let m = Manifest::parse(br#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":true}"#).unwrap(); + assert!(m.place); + assert_eq!(m.permissions(), [Permission::ImportRead]); + assert_eq!(serde_json::to_value(&m).unwrap()["place"], json!(true)); + for open_only in [ + r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"]}"#, + r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":false}"#, + ] { + let m = Manifest::parse(open_only.as_bytes()).unwrap(); + assert!(!m.place && serde_json::to_value(&m).unwrap().get("place").is_none(), "{open_only}"); + } + for (bad, says) in [ + (r#"{"id":"a","name":"x","kind":"filter","place":true}"#, "`place` is only for an importer"), + (r#"{"id":"a","name":"x","kind":"exporter","extensions":["plt"],"place":true}"#, "`place` is only for an importer"), + (r#"{"id":"a","name":"x","kind":"effect","place":true}"#, "`place` is only for an importer"), + (r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":"yes"}"#, "invalid type"), + (r#"{"id":"a","name":"x","kind":"importer","extensions":["plt"],"place":1}"#, "invalid type"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + /// A filter may ask for a heavy budget; a live effect runs while the document is drawn and an /// exporter has an export's budget, so they can't. Light, the default, isn't written back. #[test] @@ -1383,6 +1532,64 @@ mod tests { assert!(Manifest::parse(long.as_bytes()).unwrap_err().to_string().contains("twice")); } + /// A filter at `api` 3 may change the kinds it reads that it lists in `writes`, each once, with + /// `doc.read` and `doc.write`. Left out or empty, everything it reads stays read-only and the key + /// isn't written back. Anything else is refused naming `writes`. + #[test] + fn a_filter_at_api_3_lists_the_kinds_it_writes() { + let m = Manifest::parse( + br#"{"id":"org.example.revise","name":"Revise","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["type","image","symbolInstance"],"writes":["type","image","symbolInstance"]}"#, + ) + .unwrap(); + assert_eq!(m.write_kinds(), InputKind::ALL); + assert_eq!(serde_json::to_value(&m).unwrap()["writes"], json!(["type", "image", "symbolInstance"])); + let some = Manifest::parse( + br#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read","doc.write"],"inputs":["image","type"],"writes":["image"]}"#, + ) + .unwrap(); + assert_eq!((some.input_kinds(), some.write_kinds()), (vec![InputKind::Image, InputKind::Type], vec![InputKind::Image])); + for none in [ + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["doc.read"],"inputs":["type"]}"#, + r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"inputs":["type"],"writes":[]}"#, + r#"{"id":"a","name":"x","kind":"filter","writes":null}"#, + ] { + let m = Manifest::parse(none.as_bytes()).unwrap(); + assert!(m.write_kinds().is_empty(), "{none}"); + assert!(serde_json::to_value(&m).unwrap().get("writes").is_none(), "{none}"); + } + let rw = r#""permissions":["doc.read","doc.write"]"#; + for (bad, says) in [ + ( + format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["text"]}}"#), + "`writes` names an unknown object kind `text`", + ), + ( + format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["type","type"]}}"#), + "`writes` lists `type` twice", + ), + ( + format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":["image"]}}"#), + "`writes` lists `image`, which `inputs` doesn't list", + ), + (format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"writes":["image"]}}"#), "which `inputs` doesn't list"), + (format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":"type"}}"#), "`writes` must be a list"), + (format!(r#"{{"id":"a","name":"x","kind":"filter","api":3,{rw},"inputs":["type"],"writes":[1]}}"#), "`writes` must be a list"), + (format!(r#"{{"id":"a","name":"x","kind":"filter","api":2,{rw},"inputs":["type"],"writes":["type"]}}"#), "`writes` needs `api` 3"), + ( + r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.read"],"inputs":["type"],"writes":["type"]}"#.into(), + "`writes` needs the permission `doc.write`", + ), + ( + r#"{"id":"a","name":"x","kind":"filter","api":3,"permissions":["doc.write"],"inputs":["type"],"writes":["type"]}"#.into(), + "`inputs` needs the permission `doc.read`", + ), + (r#"{"id":"a","name":"x","kind":"effect","api":3,"writes":["type"]}"#.into(), "only a filter declares `writes`"), + ] { + let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + /// A filter, or a live effect with commands, at `api` 3 may ask for parts of the document /// (`context`), each once, with a `permissions` list holding `doc.read`, so installing it asks /// for approval. Left out or empty, it asks for none and isn't written back. Anything else is diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index ad69c25720..4b0a528703 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -38,6 +38,8 @@ pub const MITER_LIMIT: std::ops::RangeInclusive = 1.0..=500.0; pub const MAX_EFFECT_ID: usize = 128; /// Largest data a plug-in may keep with a document (`documentData`), in bytes of JSON. pub const MAX_DOCUMENT_DATA: usize = 1 << 20; +/// Most characters of a filter's `notice` as the host shows it, its escapes counted. +pub const MAX_NOTICE_CHARS: usize = 200; /// Most text a filter is given of one type object, in bytes of UTF-8 over all its runs: longer /// type comes with `truncated` and no runs or paragraphs. pub const MAX_INPUT_TEXT: usize = 256 * 1024; @@ -80,6 +82,10 @@ pub struct OutObject { /// A read-only input object (type, an image or a symbol instance) returned as it was given: /// it stays as it is, and new objects listed after it go above it. pub kept: bool, + /// A type object, an image or a symbol instance of a kind the filter may change (`writes`) + /// returned with changes: the fields it changes, by their names in the input, checked when + /// they are applied ([`apply_output`]). + pub edit: Option>, } /// One stroke of an [`OutObject`]. `None` fields keep the stroke's value (a new stroke's @@ -293,7 +299,7 @@ fn affine_json(xf: Affine) -> Value { /// paragraphs: [style]}` with the native character and paragraph attributes, one paragraph style /// for each paragraph, and `truncated`: true, with no runs or paragraphs, past [`MAX_INPUT_TEXT`] /// or [`MAX_INPUT_RUNS`]; -/// - an image (`"image"`): `pixelSize: [w, h]`, `colorMode: "rgb"|"cmyk"|"gray"|"unknown"`, +/// - an image (`"image"`): `opacity` (0 to 1), `pixelSize: [w, h]`, `colorMode: "rgb"|"cmyk"|"gray"|"unknown"`, /// `linked`, `pixelsOmitted`, and for an embedded image of at most [`MAX_INPUT_PIXELS`] /// `pixelsBase64`: straight RGBA, 8 bits a channel, row by row from the top (a CMYK image's inks /// through the working CMYK profile, as sRGB). A linked image's file and path are never read or @@ -330,6 +336,7 @@ fn encode_read_only_within(doc: &Document, n: &Node, symbols: &SymbolBoxes, left if let Some(q) = n.image_quad() { o["corners"] = json!(q.map(|p| [p.x, p.y])); } + o["opacity"] = json!(n.opacity); o["pixelSize"] = json!([im.width, im.height]); o["colorMode"] = json!(doc.image_blob(im).map_or("unknown", color_mode)); o["linked"] = json!(im.link.is_some()); @@ -670,6 +677,15 @@ fn decode_paint(v: &Value, at: &str) -> Result { Ok(p) } +/// An object's name from plug-in output (`null`: no name), without control characters and at most +/// 256 of them. +fn decode_name(n: &Value, at: &str) -> Result { + Ok(match n { + Value::Null => String::new(), + n => n.as_str().ok_or_else(|| out_err(at, "`name` must be a string"))?.chars().filter(|c| !c.is_control()).take(256).collect(), + }) +} + fn opt<'a>(o: &'a serde_json::Map, key: &str) -> Option<&'a Value> { o.get(key).filter(|v| !v.is_null()) } @@ -691,11 +707,7 @@ fn decode_object(v: &Value, at: &str, anchors: &mut usize) -> Result }); } if let Some(n) = o.get("name") { - let name = match n { - Value::Null => String::new(), - n => n.as_str().ok_or_else(|| out_err(at, "`name` must be a string"))?.chars().filter(|c| !c.is_control()).take(256).collect(), - }; - out.name = Some(name); + out.name = Some(decode_name(n, at)?); } if let Some(p) = opt(o, "path") { out.path = Some(decode_path(p, &format!("{at}.path"), anchors)?); @@ -794,10 +806,12 @@ pub struct Output { /// (what the plug-in keeps stays as it is), `Some(None)` for `null` (it forgets it), else what /// it keeps from now on, at most [`MAX_DOCUMENT_DATA`] bytes of JSON. pub document_data: Option>, + /// `notice`, the run's report for the status bar, as [`decode_notice`] reads it. + pub notice: Option, } -/// Parses a filter's output: `{"objects": [...], "documentData"?: …}`, or `{"error": "message"}` -/// when the plug-in declined (the message reaches the user). +/// Parses a filter's output: `{"objects": [...], "documentData"?: …, "notice"?: "…"}`, or +/// `{"error": "message"}` when the plug-in declined (the message reaches the user). pub fn decode_output(bytes: &[u8]) -> Result { decode_output_with(bytes, &[], &HashMap::new()) } @@ -809,8 +823,18 @@ pub fn decode_output(bytes: &[u8]) -> Result { /// differs, before anything changes. Each object is parsed from `input` only to compare it, one at /// a time, and an object that can't be read from there is an error. pub fn decode_output_with(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans) -> Result { + decode_output_writing(bytes, input, read_only, &[]) +} + +/// [`decode_output_with`] for a filter that may change the objects of kinds `writes` among them +/// (its manifest's `writes`): such an object is still listed exactly once, and an entry for it may +/// leave fields out, which keep their values, and give its name, its transform, and type's +/// `text.runs` and `text.paragraphs`, an image's `opacity` or an instance's `symbolId` changed. +/// Such an entry is [`OutObject::edit`] with the fields it changes; one that changes nothing is +/// [`OutObject::kept`]. Any other field must be as given, and the error names the first that isn't. +pub fn decode_output_writing(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans, writes: &[InputKind]) -> Result { let mut v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?; - let objects = decode_objects(&v, input, read_only)?; + let objects = decode_objects(&v, input, read_only, writes)?; let document_data = match v.get_mut("documentData").map(Value::take) { None => None, Some(Value::Null) => Some(None), @@ -822,19 +846,82 @@ pub fn decode_output_with(bytes: &[u8], input: &[u8], read_only: &ReadOnlySpans) Some(Some(data)) } }; - Ok(Output { objects, document_data }) + let notice = decode_notice(&v)?; + Ok(Output { objects, document_data, notice }) +} + +/// The `notice` of output `v`: `None` when it has none (or `null`), else its text without the +/// white space around it, as [`crate::permissions::display_text`] shows plug-in text (control, +/// bidirectional formatting and separator characters escaped) and at most [`MAX_NOTICE_CHARS`] +/// characters. A `notice` that is not a string, or whose shown part has no character besides white +/// space, control characters and the default-ignorable characters the host does not escape, is an +/// error. +pub fn decode_notice(v: &Value) -> Result> { + match v.get("notice") { + None | Some(Value::Null) => Ok(None), + Some(Value::String(s)) if shown_part_is_visible(s.trim()) => Ok(Some(crate::permissions::display_text(s.trim(), MAX_NOTICE_CHARS))), + Some(_) => Err(Error::Output("`notice` must be a string with visible text".into())), + } +} + +/// Does the part of notice `s` that [`crate::permissions::display_text`] keeps within +/// [`MAX_NOTICE_CHARS`], escapes counted and room left for the `…` when it cuts, hold a character +/// that draws something? +fn shown_part_is_visible(s: &str) -> bool { + let shows = |c: char| !c.is_whitespace() && !c.is_control() && !draws_nothing(c); + let width = |c: char| crate::permissions::display_text(c.encode_utf8(&mut [0; 4]), usize::MAX).chars().count(); + // Characters written through the end of `c`, and through the first visible character. + let mut used = 0; + let mut visible_by = None; + for c in s.chars() { + used += width(c); + if visible_by.is_none() && shows(c) { + visible_by = Some(used); + } + if used > MAX_NOTICE_CHARS { + break; + } + } + visible_by.is_some_and(|end| used <= MAX_NOTICE_CHARS || end < MAX_NOTICE_CHARS) +} + +/// Is `c` one of Unicode's default-ignorable characters (soft hyphen, zero-width and invisible +/// characters, fillers, variation selectors, tags) that [`crate::permissions::display_text`] keeps +/// as it is, so it draws nothing? The bidirectional ones it escapes are not among them. +fn draws_nothing(c: char) -> bool { + matches!( + c, + '\u{00AD}' + | '\u{034F}' + | '\u{115F}' + | '\u{1160}' + | '\u{17B4}' + | '\u{17B5}' + | '\u{180B}'..='\u{180F}' + | '\u{200B}'..='\u{200D}' + | '\u{2060}'..='\u{2065}' + | '\u{206A}'..='\u{206F}' + | '\u{3164}' + | '\u{FE00}'..='\u{FE0F}' + | '\u{FEFF}' + | '\u{FFA0}' + | '\u{FFF0}'..='\u{FFF8}' + | '\u{1BCA0}'..='\u{1BCA3}' + | '\u{1D173}'..='\u{1D17A}' + | '\u{E0000}'..='\u{E0FFF}' + ) } /// Parses a plug-in's objects: `{"objects": [...]}`, or `{"error": "message"}` when the plug-in /// declined (the message reaches the user). A live effect's other keys don't matter. pub fn decode(bytes: &[u8]) -> Result> { let v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?; - decode_objects(&v, &[], &HashMap::new()) + decode_objects(&v, &[], &HashMap::new(), &[]) } /// The objects of output `v`, or its decline; entries for `read_only` objects as -/// [`decode_output_with`] reads them. -fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result> { +/// [`decode_output_writing`] reads them, those of kinds `writes` changeable. +fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans, writes: &[InputKind]) -> Result> { if let Some(e) = declined(v) { return Err(e); } @@ -843,6 +930,8 @@ fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result< return Err(Error::Output(format!("{} objects (limit {MAX_OBJECTS})", objects.len()))); } let mut anchors = 0; + // Bytes of type text the output writes, over all its objects. + let mut text = 0; let mut returned: HashSet = HashSet::new(); let out = objects .iter() @@ -853,12 +942,19 @@ fn decode_objects(v: &Value, input: &[u8], read_only: &ReadOnlySpans) -> Result< if !returned.insert(id) { return Err(out_err(&at, "is listed twice")); } + let kept = OutObject { id: Some(id), kept: true, ..OutObject::default() }; // `{"id": …}` alone keeps the object, so there is nothing to compare it with. - if o.as_object().is_none_or(|m| m.len() != 1) { - let given = serde_json::from_slice(input.get(span.clone()).unwrap_or_default()).map_err(|e| Error::Io(e.to_string()))?; + let Some(entry) = o.as_object().filter(|m| m.len() != 1) else { return Ok(kept) }; + let given: Value = serde_json::from_slice(input.get(span.clone()).unwrap_or_default()).map_err(|e| Error::Io(e.to_string()))?; + let kind = given.get("type").and_then(Value::as_str).and_then(InputKind::parse).filter(|k| writes.contains(k)); + let Some(kind) = kind else { check_unchanged(o, &given, &at)?; - } - Ok(OutObject { id: Some(id), kept: true, ..OutObject::default() }) + return Ok(kept); + }; + Ok(match writes::changes(entry, &given, kind, &at, &mut text)? { + Some(edit) => OutObject { id: Some(id), edit: Some(edit), ..OutObject::default() }, + None => kept, + }) } None => decode_object(o, &format!("objects[{i}]"), &mut anchors), }) @@ -884,28 +980,40 @@ fn output_id(o: &Value) -> Option { /// numbers compared by value. Otherwise the error names the first field that differs /// (`text.runs[0].text`): a field the entry gives before one it leaves out, shown as /// [`crate::permissions::display_text`] shows a manifest string, since the entry's keys are the -/// plug-in's. +/// plug-in's. An image's `opacity`, which filters are given from plug-in API level 3, may be left +/// out, so an entry that a filter built for level 2 writes as it was given there still matches. fn check_unchanged(o: &Value, given: &Value, at: &str) -> Result<()> { let changed = match (o, given) { (Value::Object(x), Value::Object(y)) => { let mut keys: Vec<&String> = x.keys().collect(); keys.sort(); - keys.into_iter().find_map(|k| match y.get(k) { - Some(q) => first_difference(&x[k], q, k), - None => Some(k.clone()), - }) + keys.into_iter() + .find_map(|k| match y.get(k) { + Some(q) => first_difference(&x[k], q, k), + None => Some(k.clone()), + }) + .or_else(|| { + let image = y.get("type").and_then(Value::as_str) == Some(InputKind::Image.name()); + let mut missing: Vec<&String> = y.keys().filter(|k| !x.contains_key(*k) && !(image && *k == "opacity")).collect(); + missing.sort(); + missing.first().map(|k| (*k).clone()) + }) } - _ => None, + _ => first_difference(o, given, ""), }; - match changed.or_else(|| first_difference(o, given, "")) { + match changed { None => Ok(()), - Some(field) => { - let field = crate::permissions::display_text(&field, crate::permissions::MAX_SHOWN_FIELD); - Err(out_err(at, format!("read-only field '{field}' changed"))) - } + Some(field) => Err(read_only_changed(at, &field)), } } +/// The error for an entry at `at` that changes read-only `field`, which is shown as +/// [`crate::permissions::display_text`] shows a manifest string. +fn read_only_changed(at: &str, field: &str) -> Error { + let field = crate::permissions::display_text(field, crate::permissions::MAX_SHOWN_FIELD); + out_err(at, format!("read-only field '{field}' changed")) +} + /// The path of the first place `a` and `b` differ (`""`: they differ as a whole), `None` when they /// are the same JSON with numbers compared by value. fn first_difference(a: &Value, b: &Value, at: &str) -> Option { @@ -1261,7 +1369,9 @@ impl Plan { /// input object, just below the first one listed after them (at the first input object's place /// when the output keeps none; on top of `parent` when there were no inputs). Input objects missing /// from the output are deleted. An object's effect records replace its own once `admit` lets them -/// in. Returns the resulting objects in output order (to select). +/// in. Type, images and symbol instances stay as they are, or take the changes of their +/// [`OutObject::edit`] once each value is checked. Returns the resulting objects in output order +/// (to select). pub fn apply_output(doc: &mut Document, inputs: &[NodeId], out: Vec, parent: Option, admit: AdmitEffects) -> Result> { let wanted: HashSet = inputs.iter().copied().collect(); let mut originals: HashMap = HashMap::new(); @@ -1286,12 +1396,15 @@ pub fn apply_output(doc: &mut Document, inputs: &[NodeId], out: Vec, out_err(&at, format!("{} is not the id of an input object", id.0)) } })?; - // Type, images and symbol instances are only read: writing one would make it a path. - if input_kind(&n).is_some() && !o.kept { - return Err(out_err(&at, format!("{} is read-only", id.0))); - } + // Type, images and symbol instances change only through the fields a filter that + // may write them returns: writing one as a path would make it a path. let kept = o.kept; - if !kept { + if input_kind(&n).is_some() && !kept { + let Some(edit) = &o.edit else { return Err(out_err(&at, format!("{} is read-only", id.0))) }; + writes::apply(doc, &mut n, edit, &format!("{at} (id {})", id.0))?; + } else if o.edit.is_some() { + return Err(out_err(&at, format!("{} is not type, an image or a symbol instance", id.0))); + } else if !kept { write(doc, &mut n, o, &at, admit)?; } if !run.is_empty() { @@ -1348,5 +1461,7 @@ pub fn output_geometry(objects: Vec) -> PathData { PathData::new(objects.into_iter().filter_map(|o| o.path).flat_map(|p| p.subpaths).collect()) } +mod writes; + #[cfg(test)] mod tests; diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index 58159c3370..5bfa28215d 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -1066,7 +1066,8 @@ fn a_changed_field_is_named_escaped_and_short() { } /// A filter given read-only objects returns each one as `{"id": …}` or exactly as given (numbers by -/// value), and they stay as they are, new objects listed after one going just above it. Any change, +/// value; an image may leave out its `opacity`), and they stay as they are, new objects listed +/// after one going just above it. Any change, /// an object left out or listed twice, and a new object of such a kind are refused before anything /// changes. #[test] @@ -1087,6 +1088,14 @@ fn read_only_kind_field_and_omission_refuse() { let mut echo = input.clone(); echo["objects"][3]["transform"] = json!([1, 0, 0, 1, 5, 50]); assert!(decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).is_ok()); + // An image without `opacity`, as plug-in API level 2 gave it, is the image as given. + let mut echo = input.clone(); + for i in [4, 5] { + assert_eq!(echo["objects"][i]["type"], json!("image")); + echo["objects"][i].as_object_mut().unwrap().remove("opacity"); + } + let out = decode_output_with(echo.to_string().as_bytes(), &bytes, &read_only).unwrap(); + assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 5); // So is an id written as a float; a fractional one names no object. let id = input["objects"][3]["id"].as_u64().unwrap(); let mut echo = input.clone(); @@ -1151,6 +1160,486 @@ fn read_only_kind_field_and_omission_refuse() { assert_eq!(d, before); } +/// [`mixed`] with a second symbol, "Moon", and its targets and input for a filter that reads and may +/// change every kind. +fn writable() -> (Document, Vec, Vec, ReadOnlySpans, [NodeId; 5]) { + let (mut d, _, layer, extra) = mixed(); + let art = Arc::new(Node::path(d.alloc_id(), square(5.0), Appearance::default())); + d.symbols.push(vectorcraft_doc::Symbol { name: "Moon".into(), art, dynamic: false }); + let targets = filter_targets_with(&d, &[layer], &InputKind::ALL); + let (bytes, read_only) = encode_input_with(&d, &targets, &InputKind::ALL, usize::MAX).unwrap(); + (d, targets, bytes, read_only, extra) +} + +/// Decodes `out` for [`writable`]'s input with `writes` and applies it to `d`. +fn write_out( + d: &mut Document, + targets: &[NodeId], + bytes: &[u8], + read_only: &ReadOnlySpans, + writes: &[InputKind], + out: &Value, +) -> Result> { + let out = decode_output_writing(out.to_string().as_bytes(), bytes, read_only, writes)?; + apply_output(d, targets, out.objects, None, &keep) +} + +/// A filter that may write type, images and symbol instances changes type's runs and character +/// attributes, an image's transform and opacity, and the symbol and transform of an instance, +/// with entries that give only the fields they change. What it writes reads back the same. An +/// exact echo, `{"id": …}` alone and fields given as they were (numbers by value) change nothing. +#[test] +fn writable_kinds_take_type_runs_image_placement_and_instance_symbols() { + use vectorcraft_doc::{CharStyle, ParaStyle}; + let (mut d, targets, bytes, read_only, [text, embedded, linked, star, ghost]) = writable(); + let before = d.clone(); + let all = &InputKind::ALL; + let echo = decode_output_writing(&bytes, &bytes, &read_only, all).unwrap(); + assert!(echo.objects.iter().all(|o| o.edit.is_none())); + apply_output(&mut d, &targets, echo.objects, None, &keep).unwrap(); + assert_eq!(d, before, "an exact echo changes nothing"); + let ro = |id: NodeId| json!({"id": id.0}); + let paths: Vec = targets.iter().filter(|id| !read_only.contains_key(id)).map(|id| ro(*id)).collect(); + let with = |entries: Vec| { + let objects = [paths.clone(), entries].concat(); + json!({ "objects": objects }) + }; + let same = with(vec![ + json!({"id": text.0, "transform": [1, 0, 0, 1, 5, 50], "name": "T"}), + json!({"id": embedded.0, "opacity": 1}), + ro(linked), + json!({"id": star.0, "symbolId": "Star"}), + ro(ghost), + ]); + let out = decode_output_writing(same.to_string().as_bytes(), &bytes, &read_only, all).unwrap(); + assert!(out.objects.iter().all(|o| o.edit.is_none())); + assert_eq!(out.objects.iter().filter(|o| o.kept).count(), 5, "fields given as they were change nothing"); + // The changes, each entry giving only what it changes. + let big = CharStyle { size: 24.0, ..CharStyle::default() }; + let runs = json!([{"text": "Bye\n", "style": CharStyle::default()}, {"text": "now", "style": big}]); + let out = with(vec![ + json!({"id": text.0, "name": "Renamed", "text": {"runs": runs}}), + json!({"id": embedded.0, "transform": [1, 0, 0, 1, 10, 20], "opacity": 0.5}), + ro(linked), + json!({"id": star.0, "symbolId": "Moon", "transform": [1, 0, 0, 1, 50, 0]}), + ro(ghost), + ]); + let made = write_out(&mut d, &targets, &bytes, &read_only, all, &out).unwrap(); + assert_eq!(made.len(), targets.len()); + let node = |id: NodeId| d.node(id).unwrap().clone(); + let NodeKind::Text(t) = &node(text).kind else { panic!("type") }; + assert_eq!((t.plain_text().as_str(), t.runs[1].style.size), ("Bye\nnow", 24.0)); + assert_eq!(t.para_at(1).space_before, 6.0, "paragraphs keep their styles"); + assert_eq!(t.para_at(0), &ParaStyle::default()); + assert_eq!(node(text).name.as_deref(), Some("Renamed")); + let NodeKind::Image(im) = &node(embedded).kind else { panic!("image") }; + assert_eq!((im.xf, node(embedded).opacity), (Affine::new([1.0, 0.0, 0.0, 1.0, 10.0, 20.0]), 0.5)); + assert_eq!(node(star).kind, NodeKind::SymbolInstance { symbol: "Moon".into(), xf: Affine::translate((50.0, 0.0)) }); + for id in [linked, ghost] { + assert_eq!(d.node(id), before.node(id), "objects returned by id stay as they were"); + } + // Read again, the changed objects give what was written. + let read = |id: NodeId| encode_read_only(&d, d.node(id).unwrap()).unwrap(); + assert_eq!(read(text)["text"]["runs"], runs); + assert_eq!((&read(embedded)["transform"], &read(embedded)["opacity"]), (&json!([1.0, 0.0, 0.0, 1.0, 10.0, 20.0]), &json!(0.5))); + assert_eq!((&read(star)["symbolId"], &read(star)["transform"]), (&json!("Moon"), &json!([1.0, 0.0, 0.0, 1.0, 50.0, 0.0]))); + assert!(read(star).get("missing").is_none()); + // An instance of a symbol the document lacks can point to one it has. + let mut d = before.clone(); + let out = with(vec![ro(text), ro(embedded), ro(linked), ro(star), json!({"id": ghost.0, "symbolId": "Star"})]); + write_out(&mut d, &targets, &bytes, &read_only, all, &out).unwrap(); + assert!(matches!(&d.node(ghost).unwrap().kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Star")); +} + +/// An entry that changes a field its kind can't change, a kind the manifest doesn't list in +/// `writes`, or gives a value out of range is refused naming the object and the field, before +/// anything changes. +#[test] +fn bad_writes_are_refused_naming_the_object_and_the_field() { + use vectorcraft_doc::CharStyle; + let (d, targets, bytes, read_only, [text, embedded, linked, star, ghost]) = writable(); + let input: Value = serde_json::from_slice(&bytes).unwrap(); + let at = |id: NodeId| input["objects"].as_array().unwrap().iter().position(|o| o["id"] == json!(id.0)).unwrap(); + let style = serde_json::to_value(CharStyle::default()).unwrap(); + let styled = |f: &dyn Fn(&mut Value)| { + let mut s = style.clone(); + f(&mut s); + json!([{"text": "Hi\nthere", "style": s}]) + }; + let (t, e, l, s) = (text.0, embedded.0, linked.0, star.0); + let (ti, ei, si) = (at(text), at(embedded), at(star)); + let cases: Vec<(NodeId, Value, &[InputKind], String)> = vec![ + (text, json!({"text": {"kind": "area"}}), &InputKind::ALL, format!("objects[{ti}] (id {t}): read-only field 'text.kind' changed")), + (text, json!({"text": {"x": 1}}), &InputKind::ALL, format!("(id {t}): read-only field 'text.x' changed")), + (text, json!({"bounds": [0, 0, 1, 1]}), &InputKind::ALL, format!("(id {t}): read-only field 'bounds[0]' changed")), + (text, json!({"opacity": 0.5}), &InputKind::ALL, format!("(id {t}): read-only field 'opacity' changed")), + (text, json!({"text": {"runs": []}}), &InputKind::ALL, "text.runs: type needs at least one run".into()), + ( + text, + json!({"text": {"runs": styled(&|s| s["fontSzie"] = json!(9))}}), + &InputKind::ALL, + "text.runs[0].style: unknown key 'fontSzie'".into(), + ), + ( + text, + json!({"text": {"runs": styled(&|s| s["size"] = json!(5000))}}), + &InputKind::ALL, + "text.runs[0].style.size: `size` must be from 0.1 to 1296".into(), + ), + (text, json!({"text": {"runs": styled(&|s| s["size"] = json!("big"))}}), &InputKind::ALL, "text.runs[0].style:".into()), + ( + text, + json!({"text": {"runs": styled(&|s| s["font_family"] = json!(" "))}}), + &InputKind::ALL, + "font_family: must be 1-256 printable characters".into(), + ), + ( + text, + json!({"text": {"runs": styled(&|s| s["font_family"] = json!(format!(" {}", "a".repeat(256))))}}), + &InputKind::ALL, + "font_family: must be 1-256 printable characters".into(), + ), + ( + text, + json!({"text": {"runs": styled(&|s| s["fill"] = json!({"type": "solid", "color": s["fill"]["color"], "tintt": 0.5}))}}), + &InputKind::ALL, + "text.runs[0].style.fill: unknown key 'tintt'".into(), + ), + ( + text, + json!({"text": {"runs": styled(&|s| s["stroke"] = json!({"type": "none", "pattern": "Dots"}))}}), + &InputKind::ALL, + "text.runs[0].style.stroke: unknown key 'pattern'".into(), + ), + ( + text, + json!({"text": {"runs": [{"text": "A\nB\nC", "style": style}], "paragraphs": input["objects"][at(text)]["text"]["paragraphs"]}}), + &InputKind::ALL, + "text.paragraphs: expected 3 paragraph styles, one per paragraph".into(), + ), + (text, json!({"text": {"runs": [{"text": "Hi", "style": style, "color": 1}]}}), &InputKind::ALL, "text.runs[0]: unknown key 'color'".into()), + (text, json!({"text": 5}), &InputKind::ALL, format!("objects[{ti}] (id {t}): `text` must be an object")), + (text, json!({"text": {"runs": [{"text": 5, "style": style}]}}), &InputKind::ALL, "text.runs[0]: `text` must be a string".into()), + (text, json!({"text": {"runs": [{"text": "Hi", "style": 5}]}}), &InputKind::ALL, "text.runs[0]: `style` must be an object".into()), + (text, json!({"text": {"paragraphs": [5, {}]}}), &InputKind::ALL, "text: `paragraphs[0]` must be an object".into()), + (text, json!({"text": {"paragraphs": [{"spaceBefor": 1}, {}]}}), &InputKind::ALL, "text.paragraphs[0]: unknown key 'spaceBefor'".into()), + ( + text, + json!({"text": {"paragraphs": [{"hyphenation": {"wordLongerThen": 3}}, {}]}}), + &InputKind::ALL, + "text.paragraphs[0].hyphenation: unknown key 'wordLongerThen'".into(), + ), + ( + text, + json!({"text": {"paragraphs": [{"justification": {"wordSpacng": [80, 100, 133]}}, {}]}}), + &InputKind::ALL, + "text.paragraphs[0].justification: unknown key 'wordSpacng'".into(), + ), + ( + text, + json!({"text": {"paragraphs": [{}, {"tabs": [{"position": 36}, {"position": 72, "aling": "center"}]}]}}), + &InputKind::ALL, + "text.paragraphs[1].tabs[1]: unknown key 'aling'".into(), + ), + (text, json!({"text": {"paragraphs": [{"list": {"levl": 2}}, {}]}}), &InputKind::ALL, "text.paragraphs[0].list: unknown key 'levl'".into()), + ( + text, + json!({"text": {"runs": styled(&|s| s["stroke_dash"] = json!({"pattern": [2, 2], "ofset": 1}))}}), + &InputKind::ALL, + "text.runs[0].style.stroke_dash: unknown key 'ofset'".into(), + ), + ( + text, + json!({"text": {"runs": [{"text": "Hi\u{FFFC}", "style": style}]}}), + &InputKind::ALL, + "holds the character of an inline graphic".into(), + ), + (text, json!({"text": {"paragraphs": [{}]}}), &InputKind::ALL, "text.paragraphs: expected 2 paragraph styles, one per paragraph".into()), + (text, json!({"transform": [1, 0, 0, 0, 0, 0]}), &InputKind::ALL, format!("objects[{ti}] (id {t}).transform: flattens the object")), + (text, json!({"transform": [1, 0, 0, 1, 1e9, 0]}), &InputKind::ALL, "transform: a number is out of range".into()), + (text, json!({"transform": [1, 0, null, 0, 1, 10, 20]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()), + (text, json!({"transform": [1, 0, 0, 1, 10]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()), + (text, json!({"transform": [1, 0, 0, 1]}), &InputKind::ALL, "transform: must be a list of 6 numbers".into()), + (embedded, json!({"pixelSize": [3, 1]}), &InputKind::ALL, format!("(id {e}): read-only field 'pixelSize[0]' changed")), + (embedded, json!({"opacity": 2}), &InputKind::ALL, format!("objects[{ei}] (id {e}).opacity: must be a number from 0 to 1")), + (embedded, json!({"opacity": "half"}), &InputKind::ALL, "opacity: must be a number from 0 to 1".into()), + (linked, json!({"linked": false}), &InputKind::ALL, format!("(id {l}): read-only field 'linked' changed")), + (embedded, json!({"opacity": 0.5}), &[InputKind::Type, InputKind::SymbolInstance], format!("(id {e}): read-only field 'opacity' changed")), + ( + star, + json!({"symbolId": "Nowhere"}), + &InputKind::ALL, + format!("objects[{si}] (id {s}).symbolId: 'Nowhere' is not a symbol in this document"), + ), + (star, json!({"symbolId": 7}), &InputKind::ALL, "symbolId: must be the name of a symbol".into()), + (star, json!({"overrides": {"a": 1}}), &InputKind::ALL, format!("(id {s}): read-only field 'overrides.a' changed")), + (ghost, json!({"missing": false}), &InputKind::ALL, "read-only field 'missing' changed".into()), + (star, json!({"symbolId": "Moon"}), &[InputKind::Type], format!("(id {s}): read-only field 'symbolId' changed")), + ]; + for (id, entry, writes, says) in cases { + let mut out = input.clone(); + let mut e = entry.clone(); + e["id"] = json!(id.0); + out["objects"][at(id)] = e; + let mut doc = d.clone(); + let err = write_out(&mut doc, &targets, &bytes, &read_only, writes, &out).unwrap_err().to_string(); + assert!(err.contains(&says), "{entry}: {says}: {err}"); + assert_eq!(doc, d, "{entry}: nothing changed"); + } + // Leaving a writable object out is still refused: it isn't deleted. + let mut out = input.clone(); + out["objects"].as_array_mut().unwrap().remove(at(star)); + let e = write_out(&mut d.clone(), &targets, &bytes, &read_only, &InputKind::ALL, &out).unwrap_err().to_string(); + assert!(e.contains(&format!("objects (id {s}): a read-only object was left out")), "{e}"); +} + +/// The text a filter writes to one type object is held to [`MAX_INPUT_TEXT`] bytes and +/// [`MAX_INPUT_RUNS`] runs and paragraphs, as the text it is given; type given as `truncated` +/// keeps its text, though it can still move. +#[test] +fn written_text_is_held_to_the_input_limits_and_truncated_type_keeps_its_text() { + use vectorcraft_doc::{CharStyle, TextObject}; + let (mut d, _, layer, [text, ..]) = mixed(); + let long = Node::new( + d.alloc_id(), + NodeKind::Text(Box::new(TextObject::point(Point::new(0.0, 0.0), &"x".repeat(MAX_INPUT_TEXT + 1), CharStyle::default()))), + ); + let long = d.insert(Some(layer), usize::MAX, long).unwrap(); + let targets = filter_targets_with(&d, &[layer], &[InputKind::Type]); + let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap(); + let input: Value = serde_json::from_slice(&bytes).unwrap(); + let at = |id: NodeId| input["objects"].as_array().unwrap().iter().position(|o| o["id"] == json!(id.0)).unwrap(); + assert_eq!(input["objects"][at(long)]["truncated"], json!(true)); + let style = serde_json::to_value(CharStyle::default()).unwrap(); + let run = |s: String| json!({"text": s, "style": style}); + let writes = &[InputKind::Type]; + for (id, text_v, says) in [ + (text, json!({"runs": [run("x".repeat(MAX_INPUT_TEXT + 1))]}), format!("bytes of text (limit {MAX_INPUT_TEXT})")), + (text, json!({"runs": vec![run("x".into()); MAX_INPUT_RUNS + 1]}), format!("must be a list of at most {MAX_INPUT_RUNS} entries")), + (text, json!({"runs": [run("\n".repeat(MAX_INPUT_RUNS))]}), format!("{} paragraphs (limit {MAX_INPUT_RUNS})", MAX_INPUT_RUNS + 1)), + (text, json!({"paragraphs": vec![json!({}); MAX_INPUT_RUNS + 1]}), format!("must be a list of at most {MAX_INPUT_RUNS} entries")), + (long, json!({"runs": [run("short".into())]}), "the text of type given as `truncated` can't be changed".to_string()), + ] { + let mut out = input.clone(); + out["objects"][at(id)] = json!({"id": id.0, "text": text_v}); + let mut doc = d.clone(); + let e = write_out(&mut doc, &targets, &bytes, &read_only, writes, &out).unwrap_err().to_string(); + assert!(e.contains(&says), "{says}: {e}"); + assert_eq!(doc, d); + } + // At the limit the text is written; truncated type still moves. + let mut out = input.clone(); + out["objects"][at(text)] = json!({"id": text.0, "text": {"runs": [run("x".repeat(MAX_INPUT_TEXT))]}}); + out["objects"][at(long)] = json!({"id": long.0, "transform": [1, 0, 0, 1, 3, 4]}); + write_out(&mut d, &targets, &bytes, &read_only, writes, &out).unwrap(); + assert!(matches!(&d.node(text).unwrap().kind, NodeKind::Text(t) if t.plain_text().len() == MAX_INPUT_TEXT)); + assert!( + matches!(&d.node(long).unwrap().kind, NodeKind::Text(t) if t.xf == Affine::translate((3.0, 4.0)) && t.plain_text().len() == MAX_INPUT_TEXT + 1) + ); +} + +/// An inline graphic in type stays as it was, in its place among the inline graphics: the runs +/// around it can change, and adding, removing or changing one is refused. +#[test] +fn inline_graphics_in_written_type_stay_as_they_were() { + use vectorcraft_doc::{CharStyle, InlineArt, TextObject, TextRun}; + let (mut d, _, layer, _) = mixed(); + let mut t = TextObject::point(Point::new(0.0, 0.0), "A", CharStyle::default()); + t.runs = vec![ + TextRun::new("A", CharStyle::default()), + TextRun::inline(InlineArt::new("Star"), CharStyle::default()), + TextRun::new("B", CharStyle::default()), + ]; + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let id = d.insert(Some(layer), usize::MAX, n).unwrap(); + let targets = vec![id]; + let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap(); + let input: Value = serde_json::from_slice(&bytes).unwrap(); + let runs = input["objects"][0]["text"]["runs"].clone(); + let writes = &[InputKind::Type]; + let with = |runs: Value| json!({"objects": [{"id": id.0, "text": {"runs": runs}}]}); + let mut changed = runs.clone(); + changed[0]["text"] = json!("Before "); + changed[2]["text"] = json!(" after"); + let mut doc = d.clone(); + write_out(&mut doc, &targets, &bytes, &read_only, writes, &with(changed)).unwrap(); + let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") }; + assert_eq!(t.plain_text(), "Before \u{FFFC} after"); + assert_eq!(t.runs[1].inline.as_ref().map(|a| a.symbol.as_str()), Some("Star")); + let mut moved = runs.clone(); + moved[1]["inline"]["symbol"] = json!("Moon"); + let without = json!([runs[0], runs[2]]); + let doubled = json!([runs[0], runs[1], runs[1], runs[2]]); + for bad in [moved, without, doubled] { + let mut doc = d.clone(); + let e = write_out(&mut doc, &targets, &bytes, &read_only, writes, &with(bad.clone())).unwrap_err().to_string(); + assert!(e.contains("inline graphics can't be added, removed, reordered or changed"), "{bad}: {e}"); + assert_eq!(doc, d); + } +} + +/// Runs written without `paragraphs` keep each paragraph's style when the number of paragraphs +/// stays the same, and otherwise the styles follow the paragraphs' text: a paragraph whose text +/// stays keeps its style, also when changes are made at two places, a paragraph added at the start +/// takes the style of the next one and one added later the style of the one before it, and joining +/// two paragraphs keeps the first one's style. +#[test] +fn written_runs_without_paragraphs_keep_each_paragraph_s_style() { + use vectorcraft_doc::{CharStyle, Justify, ParaStyle, TextObject}; + let (mut d, _, layer, _) = mixed(); + let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB\nC", CharStyle::default()); + let styled = |justify| ParaStyle { justify, ..ParaStyle::default() }; + t.set_paragraph_styles(vec![styled(Justify::Left), styled(Justify::Center), styled(Justify::Right)]); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let id = d.insert(Some(layer), usize::MAX, n).unwrap(); + let targets = vec![id]; + let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap(); + let justified = |text: &str| { + let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": text, "style": CharStyle::default()}]}}]}); + let mut doc = d.clone(); + write_out(&mut doc, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap(); + let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") }; + assert_eq!(t.plain_text(), text); + (0..t.paragraph_count()).map(|i| t.para_at(i).justify).collect::>() + }; + assert_eq!(justified("X\nA\nB\nC"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right]); + assert_eq!(justified("A\nBé\nC"), [Justify::Left, Justify::Center, Justify::Right]); + assert_eq!(justified("One\nTwo\nThree"), [Justify::Left, Justify::Center, Justify::Right]); + assert_eq!(justified("AB\nC"), [Justify::Left, Justify::Right]); + assert_eq!(justified("A\nB\nC\nD"), [Justify::Left, Justify::Center, Justify::Right, Justify::Right]); + // Two separate changes: B and C keep their styles. + assert_eq!(justified("X\nA\nB\nC\nY"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right, Justify::Right]); + assert_eq!(justified("A\nX\nB\nC\nY"), [Justify::Left, Justify::Left, Justify::Center, Justify::Right, Justify::Right]); + // A changed paragraph takes the style of the one it replaces; the one added after it, that style. + assert_eq!(justified("A\nB2\nB3\nC"), [Justify::Left, Justify::Center, Justify::Center, Justify::Right]); + assert_eq!(justified("A2\nC"), [Justify::Left, Justify::Right]); +} + +/// A paragraph that a change adds next to a numbered one takes its style without the number, and +/// the numbered paragraph keeps it. +#[test] +fn written_runs_give_an_added_paragraph_no_list_number() { + use vectorcraft_doc::text::ParaList; + use vectorcraft_doc::{CharStyle, ParaStyle, TextObject}; + let (mut d, _, layer, _) = mixed(); + let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default()); + let numbered = ParaStyle { list: Some(ParaList { start: Some(5), ..ParaList::default() }), ..ParaStyle::default() }; + t.set_paragraph_styles(vec![ParaStyle::default(), numbered]); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let id = d.insert(Some(layer), usize::MAX, n).unwrap(); + let targets = vec![id]; + let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap(); + let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": "X\nA\nB\nY", "style": CharStyle::default()}]}}]}); + write_out(&mut d, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap(); + let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("type") }; + let starts: Vec<_> = (0..t.paragraph_count()).map(|i| t.para_at(i).list.map(|l| l.start)).collect(); + assert_eq!(starts, [None, None, Some(Some(5)), Some(None)]); +} + +/// Past 262,144 pairs of old and new paragraphs to compare, the paragraphs are paired in order. +#[test] +fn written_runs_pair_paragraphs_in_order_past_the_compare_limit() { + use vectorcraft_doc::{CharStyle, Justify, ParaStyle, TextObject}; + let (mut d, _, layer, _) = mixed(); + let paras: Vec = (0..600).map(|i| format!("p{i}")).collect(); + let mut t = TextObject::point(Point::new(0.0, 0.0), ¶s.join("\n"), CharStyle::default()); + let styled = |i: usize| ParaStyle { justify: if i.is_multiple_of(2) { Justify::Left } else { Justify::Right }, ..ParaStyle::default() }; + t.set_paragraph_styles((0..600).map(styled).collect()); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let id = d.insert(Some(layer), usize::MAX, n).unwrap(); + let targets = vec![id]; + let (bytes, read_only) = encode_input_with(&d, &targets, &[InputKind::Type], usize::MAX).unwrap(); + // 600 old paragraphs times 602 new ones: none starts or ends both texts. + let text = format!("X\n{}\nY", paras.join("\n")); + let out = json!({"objects": [{"id": id.0, "text": {"runs": [{"text": text, "style": CharStyle::default()}]}}]}); + write_out(&mut d, &targets, &bytes, &read_only, &[InputKind::Type], &out).unwrap(); + let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("type") }; + assert_eq!(t.paragraph_count(), 602); + let got: Vec<_> = (0..602).map(|i| t.para_at(i).justify).collect(); + let want: Vec<_> = (0..602).map(|i| styled(i.min(599)).justify).collect(); + assert_eq!(got, want); +} + +/// Every number in the character and paragraph styles a filter writes is checked against the range +/// the style commands keep it to, in a style of the filter's own and in one the type already has, +/// and a custom Kinsoku set must be one of the document's. Each bad value is refused naming the +/// object and the field, and the document stays as it was. A set of the document's, given by +/// name, takes the document's characters. +#[test] +fn written_style_numbers_are_checked_even_in_a_style_the_type_has() { + use vectorcraft_doc::{CharStyle, KinsokuSet, ParaStyle, TabAlign, TabStop, TextObject}; + let (mut d, _, layer, _) = mixed(); + d.kinsoku_sets.push(KinsokuSet { name: "Mine".into(), cannot_start: vec!['、'], ..KinsokuSet::default() }); + let stop = TabStop { position: 10.0, align: TabAlign::Left, leader: String::new(), align_on: '.' }; + let outside = KinsokuSet { name: "Elsewhere".into(), ..KinsokuSet::default() }; + let bad_chars: [(&str, CharStyle, &str); 5] = [ + ("leading 1e9", CharStyle { leading: Some(1e9), ..CharStyle::default() }, "style.leading: `leading` must be from 0.1 to 5000"), + ("scale 0", CharStyle { h_scale: 0.0, ..CharStyle::default() }, "style.h_scale: `h_scale` must be from 1 to 10000"), + ("baseline shift", CharStyle { baseline_shift: 1e9, ..CharStyle::default() }, "style.baseline_shift: `baseline_shift` must be from"), + ("tracking", CharStyle { tracking: -5000.0, ..CharStyle::default() }, "style.tracking: `tracking` must be from -1000 to 10000"), + ("aki", CharStyle { aki_left: 2000.0, ..CharStyle::default() }, "style.akiLeft: `akiLeft` must be from 0 to 1000"), + ]; + let hard = |set: KinsokuSet| ParaStyle { kinsoku: vectorcraft_doc::Kinsoku::Hard, kinsoku_set: Some(Arc::new(set)), ..ParaStyle::default() }; + let bad_paras: [(&str, ParaStyle, &str); 4] = [ + ("100000 tabs", ParaStyle { tabs: vec![stop.clone(); 100_000], ..ParaStyle::default() }, "paragraphs[0].tabs: at most 256 tab stops"), + ("indent", ParaStyle { left_indent: 1e9, ..ParaStyle::default() }, "paragraphs[0].left_indent: `left_indent` must be from -1296 to 1296"), + ( + "hyphenation", + ParaStyle { hyphenation: vectorcraft_doc::HyphenationOptions { after_first: 0, ..Default::default() }, ..ParaStyle::default() }, + "paragraphs[0].hyphenation.after_first", + ), + ("unknown kinsoku set", hard(outside.clone()), "paragraphs[0].kinsoku_set: the document has no Kinsoku set named 'Elsewhere'"), + ]; + // `own`: the type already has the bad style, and the filter changes only its other run or + // paragraph; otherwise the bad style is the filter's own. + let run = |id: NodeId, own: bool, bad: &CharStyle| { + let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default()); + if own { + t.runs = vec![vectorcraft_doc::TextRun::new("A\n", bad.clone()), vectorcraft_doc::TextRun::new("B", CharStyle::default())]; + } + let mut doc = d.clone(); + let n = Node::new(id, NodeKind::Text(Box::new(t))); + let id = doc.insert(Some(layer), usize::MAX, n).unwrap(); + (doc, id) + }; + let check = |doc: &Document, id: NodeId, entry: Value, says: &str, what: &str| { + let (bytes, read_only) = encode_input_with(doc, &[id], &[InputKind::Type], usize::MAX).unwrap(); + let mut entry = entry; + entry["id"] = json!(id.0); + let mut changed = doc.clone(); + let e = write_out(&mut changed, &[id], &bytes, &read_only, &[InputKind::Type], &json!({"objects": [entry]})).unwrap_err().to_string(); + assert!(e.contains(&format!("(id {}).text.", id.0)) && e.contains(says), "{what}: {says}: {e}"); + assert_eq!(&changed, doc, "{what}: nothing changed"); + }; + let fresh = d.clone().alloc_id(); + for (what, bad, says) in &bad_chars { + let (doc, id) = run(fresh, false, bad); + let runs = json!([{"text": "A\n", "style": bad}, {"text": "B", "style": CharStyle::default()}]); + check(&doc, id, json!({"text": {"runs": runs}}), says, what); + let (doc, id) = run(fresh, true, bad); + let runs = json!([{"text": "A\n", "style": bad}, {"text": "Be", "style": CharStyle::default()}]); + check(&doc, id, json!({"text": {"runs": runs}}), says, &format!("{what}, a style the type has")); + } + let centered = ParaStyle { justify: vectorcraft_doc::Justify::Center, ..ParaStyle::default() }; + for (what, bad, says) in &bad_paras { + let (doc, id) = run(fresh, false, &CharStyle::default()); + check(&doc, id, json!({"text": {"paragraphs": [bad, ParaStyle::default()]}}), says, what); + let mut doc = doc; + if let Some(Node { kind: NodeKind::Text(t), .. }) = doc.node_mut(id) { + t.set_paragraph_styles(vec![bad.clone(), ParaStyle::default()]); + } + check(&doc, id, json!({"text": {"paragraphs": [bad, centered]}}), says, &format!("{what}, a style the type has")); + } + // A set the document has, by name, takes the document's characters. + let (mut doc, id) = run(fresh, false, &CharStyle::default()); + let (bytes, read_only) = encode_input_with(&doc, &[id], &[InputKind::Type], usize::MAX).unwrap(); + let named = hard(KinsokuSet { name: "Mine".into(), cannot_start: vec!['x'; 3], ..KinsokuSet::default() }); + let out = json!({"objects": [{"id": id.0, "text": {"paragraphs": [named, ParaStyle::default()]}}]}); + write_out(&mut doc, &[id], &bytes, &read_only, &[InputKind::Type], &out).unwrap(); + let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") }; + assert_eq!(t.para_at(0).kinsoku_set.as_deref().map(|s| s.cannot_start.clone()), Some(vec!['、'])); +} + /// A filter's `documentData`: absent keeps what the plug-in keeps, `null` forgets it, any other JSON /// of at most [`MAX_DOCUMENT_DATA`] bytes is kept, and more refuses the whole output. #[test] @@ -1172,3 +1661,52 @@ fn document_data_is_kept_forgotten_or_refused() { // A decline is still a decline. assert!(matches!(decode_output(br#"{"error": "No pens.", "documentData": 1}"#), Err(Error::Failed(_)))); } + +/// A filter's `notice`: absent or `null` is none; a string is trimmed, its control, bidirectional +/// and separator characters escaped, and cut at [`MAX_NOTICE_CHARS`] with an ellipsis; anything +/// else, and text with nothing visible, refuses the whole output. +#[test] +fn notice_is_escaped_capped_and_checked() { + let out = |notice: Option| { + let mut v = json!({"objects": []}); + if let Some(n) = notice { + v["notice"] = n; + } + decode_output(v.to_string().as_bytes()).map(|o| o.notice) + }; + assert_eq!(out(None).unwrap(), None); + assert_eq!(out(Some(Value::Null)).unwrap(), None); + assert_eq!(out(Some(json!(" Selected 12 objects \n"))).unwrap().as_deref(), Some("Selected 12 objects")); + let shown = out(Some(json!("Saved\u{202E}txt.exe\nError: disk full\u{7}"))).unwrap().unwrap_or_default(); + assert_eq!(shown, "Saved\\u{202E}txt.exe\\u{000A}Error: disk full\\u{0007}"); + let long = out(Some(json!("y".repeat(10_000)))).unwrap().unwrap_or_default(); + assert_eq!(long.chars().count(), MAX_NOTICE_CHARS); + assert!(long.ends_with('…')); + // Escapes count toward the limit, so a notice of right-to-left overrides stays within it too. + let escaped = out(Some(json!("\u{202E}".repeat(10_000)))).unwrap().unwrap_or_default(); + assert!(escaped.chars().count() <= MAX_NOTICE_CHARS && !escaped.contains('\u{202E}'), "{escaped}"); + for bad in [ + json!(""), + json!(" \t\n "), + json!("\u{200B}\u{FEFF}"), + json!("\u{034F}"), + json!("\u{3164}\u{FE0F}\u{E0041}"), + // The visible text comes after the cut, so the status bar would show only the `…`. + json!(format!("{}AB", "\u{200B}".repeat(MAX_NOTICE_CHARS - 1))), + json!(format!("{}A", "\u{7}".repeat(MAX_NOTICE_CHARS / 8))), + json!(12), + json!(["a"]), + json!({"text": "a"}), + json!(true), + ] { + assert!(matches!(out(Some(bad.clone())), Err(Error::Output(ref e)) if e.contains("`notice`")), "{bad}"); + } + // Text with a visible character keeps the invisible ones, and its bidirectional ones escaped. + assert_eq!(out(Some(json!("\u{2067}Done\u{034F}"))).unwrap().as_deref(), Some("\\u{2067}Done\u{034F}")); + // A visible character in the last place the limit shows, whole or before the `…`, is enough. + let pad = "\u{200B}".repeat(MAX_NOTICE_CHARS - 2); + assert_eq!(out(Some(json!(format!("{pad}\u{200B}A")))).unwrap(), Some(format!("{pad}\u{200B}A"))); + assert_eq!(out(Some(json!(format!("{pad}ABC")))).unwrap(), Some(format!("{pad}A…"))); + // A decline is still a decline. + assert!(matches!(decode_output(br#"{"error": "No pens.", "notice": "Done"}"#), Err(Error::Failed(_)))); +} diff --git a/crates/plugins/src/objects/writes.rs b/crates/plugins/src/objects/writes.rs new file mode 100644 index 0000000000..574ebb6216 --- /dev/null +++ b/crates/plugins/src/objects/writes.rs @@ -0,0 +1,526 @@ +//! What a filter whose manifest lists `writes` may change about the type, images and symbol +//! instances it was given: each one's name and transform; type's runs, with their character +//! attributes, and its paragraph styles; an image's opacity; and the symbol an instance shows. +//! Every other field stays read-only, and every value is checked before anything changes. + +use std::collections::HashSet; + +use serde::de::DeserializeOwned; +use serde_json::{Map, Value}; +use vectorcraft_doc::text::{AttrRangeError, INLINE_CHAR}; +use vectorcraft_doc::{CharStyle, Document, JustificationOptions, KinsokuSet, Node, NodeKind, ParaStyle, TextObject, TextRun}; +use vectorcraft_geom::Affine; + +use super::{ + MAX_COORD, MAX_INPUT_RUNS, MAX_INPUT_TEXT, MAX_INPUT_TEXT_TOTAL, admit_paint, decode_name, decode_paint, first_difference, out_err, + read_only_changed, +}; +use crate::{Error, InputKind, Result}; + +/// The longest font family name a filter may set, in characters. +const MAX_FAMILY: usize = 256; +/// The smallest determinant a transform a filter sets may have: a smaller one flattens the object. +const MIN_DETERMINANT: f64 = 1e-12; +/// The most pairs of an old and a new paragraph, past those both texts start and end with, that a +/// change of the paragraph count compares by their text ([`moved_para_styles`]). +const MAX_MATCHED_PAIRS: usize = 1 << 18; + +/// The fields of an object of `kind` a filter that lists the kind in `writes` may change. +fn writable(kind: InputKind) -> &'static [&'static str] { + match kind { + InputKind::Type => &["name", "transform", "text"], + InputKind::Image => &["name", "transform", "opacity"], + InputKind::SymbolInstance => &["name", "transform", "symbolId"], + } +} + +/// The changes entry `o` of a filter's output makes to object `given` of `kind` (as the input gave +/// it), `None` when it changes nothing. Fields it leaves out keep their values; a field it gives +/// that isn't [`writable`] must be as given. Changed type text counts toward `text`, the bytes of +/// text written over the whole output. The changes are keyed `name`, `transform`, `opacity`, +/// `symbolId`, `runs` and `paragraphs`; their values are checked when they are applied ([`apply`]). +pub(super) fn changes(o: &Map, given: &Value, kind: InputKind, at: &str, text: &mut usize) -> Result>> { + let mut keys: Vec<&String> = o.keys().filter(|k| *k != "id").collect(); + keys.sort(); + let mut out = Map::new(); + for k in keys { + let v = &o[k]; + let was = given.get(k); + if !writable(kind).contains(&k.as_str()) { + if let Some(field) = was.map_or_else(|| Some(k.clone()), |w| first_difference(v, w, k)) { + return Err(read_only_changed(at, &field)); + } + continue; + } + match (k.as_str(), was) { + ("text", Some(was)) => text_changes(k, v, was, given.get("truncated") == Some(&Value::Bool(true)), at, text, &mut out)?, + ("name", None) if v.is_null() => {} + (_, Some(was)) if first_difference(v, was, "").is_none() => {} + _ => { + out.insert(k.clone(), v.clone()); + } + } + } + Ok((!out.is_empty()).then_some(out)) +} + +/// The `runs` and `paragraphs` of type text `v`, the output's field `key`, that differ from `was` +/// (the text the input gave), into `out`; its other fields must be as given, and type given as +/// `truncated` keeps its text. A changed list is held to [`MAX_INPUT_RUNS`] entries, and changed +/// runs to [`MAX_INPUT_TEXT`] bytes of text, which count toward `total`, held to +/// [`MAX_INPUT_TEXT_TOTAL`], and to [`MAX_INPUT_RUNS`] paragraphs. With changed runs, `paragraphs` +/// given as they were go into `out` too, to be checked against the new paragraphs. +fn text_changes(key: &str, v: &Value, was: &Value, truncated: bool, at: &str, total: &mut usize, out: &mut Map) -> Result<()> { + let t = v.as_object().ok_or_else(|| out_err(at, format!("`{key}` must be an object")))?; + let mut keys: Vec<&String> = t.keys().collect(); + keys.sort(); + for k in keys { + let field = format!("{key}.{k}"); + let given = was.get(k); + let differs = given.is_none_or(|g| first_difference(&t[k], g, "").is_some()); + if !matches!(k.as_str(), "runs" | "paragraphs") { + if differs { + let shown = given.and_then(|g| first_difference(&t[k], g, &field)).unwrap_or_else(|| field.clone()); + return Err(read_only_changed(at, &shown)); + } + continue; + } + if !differs { + continue; + } + if truncated { + return Err(out_err(&format!("{at}.{field}"), "the text of type given as `truncated` can't be changed")); + } + let list = t[k].as_array().filter(|l| l.len() <= MAX_INPUT_RUNS); + let list = list.ok_or_else(|| out_err(&format!("{at}.{field}"), format!("must be a list of at most {MAX_INPUT_RUNS} entries")))?; + if k == "runs" { + if list.is_empty() { + return Err(out_err(&format!("{at}.{field}"), "type needs at least one run")); + } + let bytes = list.iter().fold(0usize, |n, r| n.saturating_add(r.get("text").and_then(Value::as_str).map_or(0, str::len))); + if bytes > MAX_INPUT_TEXT { + return Err(out_err(&format!("{at}.{field}"), format!("{bytes} bytes of text (limit {MAX_INPUT_TEXT})"))); + } + // Each paragraph gets a paragraph style; the text holds at most as many paragraphs as runs. + let breaks = |r: &Value| r.get("text").and_then(Value::as_str).map_or(0, |s| s.bytes().filter(|&b| b == b'\n').count()); + let paragraphs = list.iter().fold(1usize, |n, r| n.saturating_add(breaks(r))); + if paragraphs > MAX_INPUT_RUNS { + return Err(out_err(&format!("{at}.{field}"), format!("{paragraphs} paragraphs (limit {MAX_INPUT_RUNS})"))); + } + *total = total.saturating_add(bytes); + if *total > MAX_INPUT_TEXT_TOTAL { + return Err(out_err(&format!("{at}.{field}"), format!("more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output"))); + } + } + out.insert(k.clone(), t[k].clone()); + } + // Paragraph styles given as they were still need one per paragraph of the new runs. + if out.contains_key("runs") + && !out.contains_key("paragraphs") + && let Some(p) = t.get("paragraphs") + { + out.insert("paragraphs".into(), p.clone()); + } + Ok(()) +} + +/// Every attribute name `T` reads, including those its JSON leaves out at their defaults: the field +/// names serde's derive hands `deserialize_struct`. +fn attr_names() -> &'static [&'static str] { + use serde::de::{Error as _, Visitor, value::Error}; + + struct Names<'a>(&'a mut &'static [&'static str]); + impl<'de> serde::Deserializer<'de> for Names<'_> { + type Error = Error; + fn deserialize_any>(self, _: V) -> std::result::Result { + Err(Error::custom("not a struct")) + } + fn deserialize_struct>(self, _: &'static str, fields: &'static [&'static str], _: V) -> std::result::Result { + *self.0 = fields; + Err(Error::custom("field names only")) + } + serde::forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf option unit + unit_struct newtype_struct seq tuple tuple_struct map enum identifier ignored_any + } + } + + let mut fields: &'static [&'static str] = &[]; + // Always an error: the probe only records the names. + let _ = T::deserialize(Names(&mut fields)); + fields +} + +/// `v`, the field `key` of the entry at `parent`, as a `T` whose attributes are all ones `T` reads: +/// a value that isn't an object is an error at `parent`, and an unknown key, as an ill-typed value, +/// an error at `parent.key`. +fn strict(v: &Value, parent: &str, key: &str) -> Result { + let o = v.as_object().ok_or_else(|| out_err(parent, format!("`{key}` must be an object")))?; + let at = format!("{parent}.{key}"); + let names = attr_names::(); + if let Some(k) = o.keys().find(|k| !names.contains(&k.as_str())) { + let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); + return Err(out_err(&at, format!("unknown key '{k}'"))); + } + serde_json::from_value(v.clone()).map_err(|e| out_err(&at, e)) +} + +/// The field `key` of `v`, the style at `at`, holds only attributes `T` reads: an object, or each +/// object of a list. An unknown key is an error at `at.key` (or `at.key[i]`); other values are left +/// to the style's own checks. +fn known_keys(v: &Value, at: &str, key: &str) -> Result<()> { + let names = attr_names::(); + let check = |o: &Map, at: &str| match o.keys().find(|k| !names.contains(&k.as_str())) { + Some(k) => { + let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); + Err(out_err(at, format!("unknown key '{k}'"))) + } + None => Ok(()), + }; + match v.get(key) { + Some(Value::Object(o)) => check(o, &format!("{at}.{key}")), + Some(Value::Array(list)) => list.iter().enumerate().try_for_each(|(i, e)| match e { + Value::Object(o) => check(o, &format!("{at}.{key}[{i}]")), + _ => Ok(()), + }), + _ => Ok(()), + } +} + +/// A transform from a filter's output: six finite numbers, each within ±[`MAX_COORD`], that don't +/// flatten the object. +fn decode_transform(v: &Value, at: &str) -> Result { + let c: Option> = v.as_array().and_then(|a| a.iter().map(Value::as_f64).collect()); + let c: [f64; 6] = c.and_then(|c| c.try_into().ok()).ok_or_else(|| out_err(at, "must be a list of 6 numbers"))?; + if !c.iter().all(|x| x.is_finite() && x.abs() <= MAX_COORD) { + return Err(out_err(at, format!("a number is out of range (limit ±{MAX_COORD})"))); + } + let xf = Affine::new(c); + if xf.determinant().abs() < MIN_DETERMINANT { + return Err(out_err(at, "flattens the object to a line or a point")); + } + Ok(xf) +} + +/// The transform object `n` is given with: type's and an instance's own, an image's (for a +/// distorted image, the placement nearest its corners at its middle). +fn given_transform(n: &Node) -> Option { + match &n.kind { + NodeKind::Text(t) => Some(t.xf), + NodeKind::Image(im) => Some(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf)), + NodeKind::SymbolInstance { xf, .. } => Some(*xf), + _ => None, + } +} + +/// Applies `changes` ([`changes`]) to `n`, an input object of `doc`; `at` names it in errors. Each +/// value is checked first, and an error leaves `n` to be dropped. +pub(super) fn apply(doc: &Document, n: &mut Node, changes: &Map, at: &str) -> Result<()> { + if let Some(v) = changes.get("transform") { + let at = format!("{at}.transform"); + let new = decode_transform(v, &at)?; + let old = given_transform(n).filter(|xf| xf.determinant().abs() >= MIN_DETERMINANT); + let old = old.ok_or_else(|| out_err(&at, "an object flattened to a line or a point can't be placed again"))?; + // Everything the object carries moves with it: a distorted image's corners, its gradients. + n.transform(new * old.inverse(), false); + let distorted = n.is_distorted_image(); + match &mut n.kind { + NodeKind::Text(t) => t.xf = new, + NodeKind::SymbolInstance { xf, .. } => *xf = new, + NodeKind::Image(im) if !distorted => im.xf = new, + _ => {} + } + } + if let Some(v) = changes.get("opacity") { + let op = v.as_f64().filter(|o| (0.0..=1.0).contains(o)); + n.opacity = op.ok_or_else(|| out_err(&format!("{at}.opacity"), "must be a number from 0 to 1"))? as f32; + } + if let Some(v) = changes.get("symbolId") { + let at = format!("{at}.symbolId"); + let name = v.as_str().ok_or_else(|| out_err(&at, "must be the name of a symbol"))?; + if !doc.symbols.iter().any(|s| s.name == name) { + let shown = crate::permissions::display_text(name, crate::permissions::MAX_SHOWN_FIELD); + return Err(out_err(&at, format!("'{shown}' is not a symbol in this document"))); + } + let other = matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol != name); + if let NodeKind::SymbolInstance { symbol, .. } = &mut n.kind { + *symbol = name.to_string(); + } + // An edited part's path names an object of the old symbol's art, as Replace Symbol finds. + if other && !n.extras().symbol_overrides.is_empty() { + n.extras_mut().symbol_overrides.clear(); + } + } + if changes.contains_key("runs") || changes.contains_key("paragraphs") { + let story = doc.story_of(n.id).len(); + let NodeKind::Text(t) = &mut n.kind else { return Err(read_only_changed(at, "text")) }; + set_text(doc, t, story > 1, changes.get("runs"), changes.get("paragraphs"), at)?; + } + if let Some(v) = changes.get("name") { + n.name = Some(decode_name(v, at)?).filter(|s| !s.trim().is_empty()); + } + Ok(()) +} + +/// Gives type `t` the runs `runs` and paragraph styles `paragraphs` a filter returned (`threaded`: +/// it is a frame of a story that flows through others). Each run has `text`, `style` and, for an +/// inline graphic, `inline`; each attribute is one the type reads. Inline graphics stay as they +/// were, in the same order, and the characters of threaded type or type with ruby stay as they +/// were. Every number of every run's style is in the range the character style commands keep it +/// to ([`CharStyle::check_ranges`]), and a run whose style isn't one of the type's own has a font +/// family, and its paints are checked as an object's are. Paragraph styles are one per paragraph +/// ([`para_style`]). With runs alone, each paragraph keeps its style when the number of paragraphs stays +/// the same, and otherwise the styles follow the paragraphs' text ([`moved_para_styles`]). +fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Value>, paragraphs: Option<&Value>, at: &str) -> Result<()> { + if let Some(runs) = runs { + let at = format!("{at}.text.runs"); + let list = runs.as_array().map(Vec::as_slice).unwrap_or_default(); + // The type's own styles, as JSON text, to look each run's style up once. + let own: HashSet = t.runs.iter().filter_map(|r| serde_json::to_string(&r.style).ok()).collect(); + let mut new = Vec::with_capacity(list.len()); + for (i, v) in list.iter().enumerate() { + let at = format!("{at}[{i}]"); + let o = v.as_object().ok_or_else(|| out_err(&at, "a run must be {\"text\", \"style\", \"inline\"?}"))?; + if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "text" | "style" | "inline")) { + let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); + return Err(out_err(&at, format!("unknown key '{k}'"))); + } + let key = "text"; + let text = o.get(key).and_then(Value::as_str).ok_or_else(|| out_err(&at, format!("`{key}` must be a string")))?; + let style_v = o.get("style").unwrap_or(&Value::Null); + let mut style: CharStyle = strict(style_v, &at, "style")?; + known_keys::(style_v, &format!("{at}.style"), "stroke_dash")?; + let inline = match o.get("inline") { + None | Some(Value::Null) => None, + Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| out_err(&format!("{at}.inline"), e))?), + }; + if inline.is_none() { + if text.contains(INLINE_CHAR) { + return Err(out_err(&at, "`text` holds the character of an inline graphic")); + } + // Every number goes to the layout, so it is checked even in a style the type has. + style.check_ranges(|_| true).map_err(|e| range_err(&format!("{at}.style"), &e))?; + for key in ["fill", "stroke"] { + if let Some(p) = style_v.get(key) { + check_paint_keys(p, &format!("{at}.style.{key}"))?; + } + } + if !serde_json::to_string(&style).is_ok_and(|s| own.contains(&s)) { + check_style(doc, &mut style, t.runs.get(i).map(|r| &r.style), &format!("{at}.style"))?; + } + } + new.push(TextRun { text: text.to_string(), style, inline }); + } + // Inline graphics are compared as saved (their measured bounds aren't), and keep those. + let saved = |r: &&TextRun| serde_json::to_value(r).ok(); + let old_inline: Vec<&TextRun> = t.runs.iter().filter(|r| r.inline.is_some()).collect(); + let new_inline: Vec<&TextRun> = new.iter().filter(|r| r.inline.is_some()).collect(); + if old_inline.len() != new_inline.len() || old_inline.iter().zip(&new_inline).any(|(a, b)| saved(a) != saved(b)) { + return Err(out_err(&at, "inline graphics can't be added, removed, reordered or changed")); + } + let mut kept = old_inline.into_iter().cloned().collect::>().into_iter(); + for r in new.iter_mut().filter(|r| r.inline.is_some()) { + if let Some(old) = kept.next() { + *r = old; + } + } + let plain: String = new.iter().map(|r| r.text.as_str()).collect(); + let old = t.plain_text(); + let mut moved = None; + if plain != old { + if threaded { + return Err(out_err(&at, "the characters of threaded type can't be changed")); + } + if !t.ruby.is_empty() { + return Err(out_err(&at, "the characters of type with ruby can't be changed")); + } + let breaks = |s: &str| s.bytes().filter(|&b| b == b'\n').count(); + if paragraphs.is_none() && breaks(&plain) != breaks(&old) { + // Paragraphs added or joined: the styles follow the paragraphs' text. With as many + // paragraphs as before, each keeps its style. + moved = Some(moved_para_styles(&t.paragraph_styles(), &old, &plain)); + } + } + t.runs = new; + if let Some(styles) = moved { + t.set_paragraph_styles(styles); + } + } + match paragraphs { + Some(v) => { + let text = format!("{at}.text"); + let list = v.as_array().map(Vec::as_slice).unwrap_or_default(); + let count = t.paragraph_count(); + if list.len() != count { + return Err(out_err(&format!("{text}.paragraphs"), format!("expected {count} paragraph styles, one per paragraph"))); + } + let styles = list.iter().enumerate().map(|(i, p)| para_style(doc, p, &text, &format!("paragraphs[{i}]"))).collect::>()?; + t.set_paragraph_styles(styles); + } + None => t.normalize_paras(), + } + // The layout is measured again before the type is drawn. + t.cached_bounds = None; + t.cached_baselines.clear(); + t.cached_ink = None; + Ok(()) +} + +/// The paragraph styles of text `new` that replaced `old`, whose paragraphs had `styles` (one per +/// paragraph). The paragraphs, split at `\n`, are matched as a longest common subsequence of their +/// texts after the paragraphs both start and end with are set aside; when the paragraphs left in +/// the old text times those left in the new pass [`MAX_MATCHED_PAIRS`], they are paired in order +/// instead. A +/// matched paragraph keeps its style. Between two matched paragraphs, the changed ones take the +/// styles of the old paragraphs there in order, and the last of those past their count; paragraphs +/// added where there were none take the style of the paragraph before them, or of the next one at +/// the start. A style copied to a paragraph that was not there loses its list number +/// ([`vectorcraft_doc::text::ParaList::start`]). +fn moved_para_styles(styles: &[ParaStyle], old: &str, new: &str) -> Vec { + let a: Vec<&str> = old.split('\n').collect(); + let b: Vec<&str> = new.split('\n').collect(); + let pre = a.iter().zip(&b).take_while(|(x, y)| x == y).count(); + let (a_rest, b_rest) = (a.get(pre..).unwrap_or_default(), b.get(pre..).unwrap_or_default()); + let suf = a_rest.iter().rev().zip(b_rest.iter().rev()).take_while(|(x, y)| x == y).count(); + // `matched[j]`: the old paragraph that new paragraph `j` is, if any. + let mut matched: Vec> = vec![None; b.len()]; + for (j, m) in matched.iter_mut().enumerate().take(pre) { + *m = Some(j); + } + for k in 0..suf { + if let Some(m) = matched.get_mut(b.len() - 1 - k) { + *m = Some(a.len() - 1 - k); + } + } + let (am, bm) = (a_rest.get(..a_rest.len() - suf).unwrap_or_default(), b_rest.get(..b_rest.len() - suf).unwrap_or_default()); + if !am.is_empty() && !bm.is_empty() && am.len().saturating_mul(bm.len()) <= MAX_MATCHED_PAIRS { + let mut ids = std::collections::HashMap::new(); + let mut id = |s: &str| { + let next = ids.len(); + *ids.entry(s.to_string()).or_insert(next) + }; + let ai: Vec = am.iter().map(|s| id(s)).collect(); + let bi: Vec = bm.iter().map(|s| id(s)).collect(); + // `len[i * w + j]`: the length of the longest common subsequence of `ai[i..]` and `bi[j..]`. + let w = bi.len() + 1; + let mut len = vec![0u32; (ai.len() + 1) * w]; + for i in (0..ai.len()).rev() { + for j in (0..bi.len()).rev() { + let at = |i: usize, j: usize| len.get(i * w + j).copied().unwrap_or(0); + let v = if ai.get(i) == bi.get(j) { at(i + 1, j + 1) + 1 } else { at(i + 1, j).max(at(i, j + 1)) }; + if let Some(c) = len.get_mut(i * w + j) { + *c = v; + } + } + } + let at = |i: usize, j: usize| len.get(i * w + j).copied().unwrap_or(0); + let (mut i, mut j) = (0, 0); + while i < ai.len() && j < bi.len() { + if ai.get(i) == bi.get(j) { + if let Some(m) = matched.get_mut(pre + j) { + *m = Some(pre + i); + } + (i, j) = (i + 1, j + 1); + } else if at(i + 1, j) >= at(i, j + 1) { + i += 1; + } else { + j += 1; + } + } + } + let style = |i: usize, numbered: bool| { + let mut s = styles.get(i).or(styles.last()).cloned().unwrap_or_default(); + if !numbered && let Some(l) = s.list.as_mut() { + l.start = None; + } + s + }; + let mut out = Vec::with_capacity(b.len()); + let (mut next_old, mut j) = (0, 0); + while j < b.len() { + if let Some(&Some(i)) = matched.get(j) { + out.push(style(i, true)); + (next_old, j) = (i + 1, j + 1); + continue; + } + // New paragraphs `j..end` stand where old paragraphs `next_old..old_end` were. + let end = (j..b.len()).find(|&k| matched.get(k).is_some_and(Option::is_some)).unwrap_or(b.len()); + let old_end = matched.get(end).copied().flatten().unwrap_or(a.len()); + for g in 0..end - j { + out.push(if next_old < old_end { + style((next_old + g).min(old_end - 1), next_old + g < old_end) + } else { + style(next_old.checked_sub(1).unwrap_or(old_end), false) + }); + } + j = end; + } + out +} + +/// An attribute of the style at `at` out of its range, naming the attribute. +fn range_err(at: &str, e: &AttrRangeError) -> Error { + out_err(&format!("{at}.{}", e.key), &e.message) +} + +/// Paragraph style `v` from a filter's output, the entry `key` of the text at `parent`: each +/// attribute one a paragraph reads, each number in the range the paragraph style commands keep it +/// to ([`ParaStyle::check_ranges`], the Justification options as given), and a custom Kinsoku set +/// one of `doc`'s, by name, whose characters it takes. +fn para_style(doc: &Document, v: &Value, parent: &str, key: &str) -> Result { + let mut st: ParaStyle = strict(v, parent, key)?; + let at = format!("{parent}.{key}"); + known_keys::(v, &at, "hyphenation")?; + known_keys::(v, &at, "justification")?; + known_keys::(v, &at, "tabs")?; + known_keys::(v, &at, "list")?; + let justification = match v.get("justification") { + None | Some(Value::Null) => None, + Some(j) => Some(serde_json::from_value::(j.clone()).map_err(|e| out_err(&format!("{at}.justification"), e))?), + }; + st.check_ranges(justification.as_ref(), &[], |_, _| true).map_err(|e| range_err(&at, &e))?; + if let Some(set) = &st.kinsoku_set { + let found = KinsokuSet::named(&doc.kinsoku_sets, &set.name).ok_or_else(|| { + let shown = crate::permissions::display_text(&set.name, crate::permissions::MAX_SHOWN_FIELD); + out_err(&format!("{at}.kinsoku_set"), format!("the document has no Kinsoku set named '{shown}'")) + })?; + st.kinsoku_set = Some(std::sync::Arc::new(found.clone())); + } + Ok(st) +} + +/// Checks character style `s`, a filter's own (`was`: the style of the run in its place before): +/// its font family is 1 to [`MAX_FAMILY`] printable characters, counted as given, and its fill and +/// stroke are admitted as an object's paints are. Its numbers and its paints' keys are checked for +/// every run ([`set_text`]). +fn check_style(doc: &Document, s: &mut CharStyle, was: Option<&CharStyle>, at: &str) -> Result<()> { + let family = s.font_family.trim(); + if family.is_empty() || s.font_family.chars().count() > MAX_FAMILY || s.font_family.chars().any(char::is_control) { + return Err(out_err(&format!("{at}.font_family"), format!("must be 1-{MAX_FAMILY} printable characters"))); + } + let paint = |p: &vectorcraft_color::Paint, was: Option<&vectorcraft_color::Paint>, key: &str| { + let at = format!("{at}.{key}"); + let v = serde_json::to_value(p).map_err(|e| out_err(&at, e))?; + admit_paint(doc, decode_paint(&v, &at)?, was, &at) + }; + s.fill = paint(&s.fill, was.map(|w| &w.fill), "fill")?; + s.stroke = paint(&s.stroke, was.map(|w| &w.stroke), "stroke")?; + Ok(()) +} + +/// Checks that paint `v` of a style, at `at`, has no key besides `type` and those its `type` +/// reads; a key of another paint, or an unknown one, is an error naming it. +fn check_paint_keys(v: &Value, at: &str) -> Result<()> { + let Some(o) = v.as_object() else { return Ok(()) }; + let known: &[&str] = match o.get("type").and_then(Value::as_str) { + Some("solid") => &["color", "swatch", "tint"], + Some("gradient") => attr_names::(), + Some("pattern") => &["pattern", "xf"], + _ => &[], + }; + if let Some(k) = o.keys().find(|k| *k != "type" && !known.contains(&k.as_str())) { + let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD); + return Err(out_err(at, format!("unknown key '{k}'"))); + } + Ok(()) +} diff --git a/crates/plugins/src/painted.rs b/crates/plugins/src/painted.rs index 484e761677..e7ed51e225 100644 --- a/crates/plugins/src/painted.rs +++ b/crates/plugins/src/painted.rs @@ -47,8 +47,8 @@ pub enum Scope { } /// Parses and checks a painted result: `{"objects": [...]}`, or `{"error": "message"}` when the -/// plug-in declined. `rule` is the fill rule a piece without `fillRule` takes. Any other top-level -/// key, an unknown key in a piece, stroke or paint, a list or count past its limit, a number out of +/// plug-in declined. `rule` is the fill rule a piece without `fillRule` takes. A top-level `notice` +/// is ignored. Any other top-level key, an unknown key in a piece, stroke or paint, a list or count past its limit, a number out of /// range or a paint of the wrong form refuses the whole result, naming the field. pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result> { let v: Value = serde_json::from_slice(bytes).map_err(|e| out_err("output", format!("not JSON: {e}")))?; @@ -56,8 +56,8 @@ pub fn decode(bytes: &[u8], scope: Scope, rule: FillRule) -> Result> return Err(e); } let top = v.as_object().ok_or_else(|| out_err("output", "expected {\"objects\": [...]}"))?; - if let Some(k) = top.keys().find(|k| !matches!(k.as_str(), "objects" | "error")) { - return Err(out_err(k, "a painted live effect returns only `objects`")); + if let Some(k) = top.keys().find(|k| !matches!(k.as_str(), "objects" | "error" | "notice")) { + return Err(out_err(k, "a painted live effect returns only `objects` and `notice`")); } let objects = top.get("objects").and_then(Value::as_array).ok_or_else(|| out_err("objects", "expected {\"objects\": [...]}"))?; if objects.len() > MAX_OBJECTS { diff --git a/crates/plugins/src/painted/tests.rs b/crates/plugins/src/painted/tests.rs index 59acf18521..471c12ea48 100644 --- a/crates/plugins/src/painted/tests.rs +++ b/crates/plugins/src/painted/tests.rs @@ -154,6 +154,21 @@ fn faults_refuse_the_whole_result_by_field() { assert_eq!(declined, Error::Failed("nothing to do".into())); } +/// A top-level `notice` is ignored, as a filter-only key a live effect may hand back; other +/// unknown top-level keys still refuse the result. +#[test] +fn a_notice_is_ignored_and_other_top_level_keys_refused() { + let ok = json!({"path": square(), "fills": [red()]}); + let decode_top = |top: Value| decode(&serde_json::to_vec(&top).unwrap(), Scope::Object, FillRule::NonZero); + let pieces = decode_top(json!({"objects": [ok], "notice": "Done"})).unwrap(); + assert_eq!(pieces.len(), 1); + assert_eq!(decode_top(json!({"objects": [ok], "notice": 12})).unwrap().len(), 1); + for key in ["note", "notices", "message"] { + let e = decode_top(json!({"objects": [ok], key: "Done"})).unwrap_err().to_string(); + assert!(e.contains(&format!("{key}:")) && e.contains("returns only `objects` and `notice`"), "{key}: {e}"); + } +} + /// A key a paint does not have, at any level of it, refuses the result and is named; it is not /// dropped. #[test] diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index 82f8db8641..5fda6fb896 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -15,7 +15,8 @@ use crate::{Error, Kind, Result}; /// The plug-in API level this host implements. A manifest's `api` (1 when left out) may be at most /// this. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput` -/// ([`crate::painted`]); level 3 adds a manifest's `context` ([`CONTEXT_API`]). +/// ([`crate::painted`]); level 3 adds a filter's `writes` ([`WRITES_API`]) and a manifest's +/// `context` ([`CONTEXT_API`]). pub const API_LEVEL: u32 = 3; /// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`, @@ -25,6 +26,9 @@ pub const PROGRESS_API: u32 = 2; /// The API level that adds a filter's `inputs` ([`crate::InputKind`]). pub const INPUTS_API: u32 = 2; +/// The API level that adds a filter's `writes`: the kinds among its `inputs` it may change. +pub const WRITES_API: u32 = 3; + /// The API level that reads a command's `menu` ([`crate::manifest::MenuPlace`]); below it the key /// is ignored. pub const MENU_API: u32 = 2; diff --git a/crates/plugins/src/registry.rs b/crates/plugins/src/registry.rs index 9432b151b8..d1f7265cff 100644 --- a/crates/plugins/src/registry.rs +++ b/crates/plugins/src/registry.rs @@ -279,14 +279,73 @@ pub fn intern(s: &str) -> &'static str { v } -/// Reads a `.wasm` file (refusing anything that isn't a regular file or exceeds the module limit) +/// Reads a `.wasm` file (refusing anything that isn't a regular file or exceeds the module limit), +/// or a JavaScript plug-in's `.vcplugin` manifest and the script it names ([`read_js_package`]), /// and loads it. #[cfg(not(target_arch = "wasm32"))] pub fn load_file(path: &std::path::Path, limits: Limits) -> Result { - let bytes = read_module(path, &limits, || {})?; + load_file_where(path, limits, &|_| Ok(())) +} + +/// [`load_file`], reading a JavaScript plug-in's script only when `allow` accepts its path. +#[cfg(not(target_arch = "wasm32"))] +fn load_file_where(path: &std::path::Path, limits: Limits, allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>) -> Result { + let bytes = if is_js_package(path) { read_js_package(path, allow)? } else { read_module(path, &limits, || {})? }; Ok(Plugin::load(&bytes, limits)?.with_source(path.display().to_string())) } +/// Does `path` name a JavaScript plug-in's manifest file: is its extension `.vcplugin`? +pub fn is_js_package(path: &std::path::Path) -> bool { + path.extension().is_some_and(|x| x.eq_ignore_ascii_case(crate::js::PACKAGE_EXT)) +} + +/// The JavaScript plug-in whose manifest file is `path`, as the one JSON object [`Plugin::load`] +/// reads: the manifest, with the text of the script its `script` names in `source`. The manifest +/// file must give `"runtime": "js"` and `script`, a `.js` file in the same folder, and no `source`. +/// Each file is refused before it is read when it isn't a regular file or is larger than its limit +/// ([`crate::manifest::MAX_MANIFEST_BYTES`], [`crate::js::MAX_SCRIPT_BYTES`]); the script is read +/// only when `allow` accepts its path, and must be UTF-8. +#[cfg(not(target_arch = "wasm32"))] +pub fn read_js_package(path: &std::path::Path, allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>) -> Result> { + read_js_package_with(path, allow, || {}) +} + +/// [`read_js_package`], with `opening` run between the script's size check and its open. +#[cfg(not(target_arch = "wasm32"))] +fn read_js_package_with( + path: &std::path::Path, + allow: &dyn Fn(&std::path::Path) -> std::result::Result<(), String>, + opening: impl FnOnce(), +) -> Result> { + use serde_json::Value; + let manifest_limits = Limits { max_module_bytes: crate::manifest::MAX_MANIFEST_BYTES, ..Limits::default() }; + let bytes = read_module(path, &manifest_limits, || {})?; + let map: serde_json::Map = serde_json::from_slice(&bytes).map_err(|e| Error::Manifest(format!("{}: {e}", path.display())))?; + if !crate::js::is_js(&map) { + return Err(Error::Manifest(crate::js::NOT_JS.into())); + } + if map.contains_key("source") { + return Err(Error::Manifest(crate::js::SOURCE_RULE.into())); + } + let name = crate::js::script_name(map.get("script").ok_or_else(crate::js::no_script)?)?; + let file = path.parent().unwrap_or(std::path::Path::new("")).join(&name); + allow(&file).map_err(Error::Io)?; + let script_limits = Limits { max_module_bytes: crate::js::MAX_SCRIPT_BYTES, ..Limits::default() }; + let source = read_module(&file, &script_limits, opening)?; + let source = String::from_utf8(source).map_err(|_| Error::Module("the script is not UTF-8 text".into()))?; + // `source` is added to the manifest's own text, so its keys keep their order. The text parsed as + // an object that has `runtime`, so its last character other than white space is its closing `}`. + let end = bytes.iter().rposition(|b| !b.is_ascii_whitespace()).filter(|&i| bytes[i] == b'}'); + let end = end.ok_or_else(|| Error::Manifest(format!("{}: not a JSON object", path.display())))?; + let source = serde_json::to_vec(&Value::String(source)).map_err(|e| Error::Manifest(e.to_string()))?; + let mut out = Vec::with_capacity(bytes.len() + source.len() + 12); + out.extend_from_slice(&bytes[..end]); + out.extend_from_slice(b",\"source\":"); + out.extend_from_slice(&source); + out.push(b'}'); + Ok(out) +} + /// The bytes of the module file at `path`. A path that doesn't name a regular file is refused /// before it is opened, and so is one over the module limit. On Unix the file is opened without /// waiting, so a named pipe put in its place after that check doesn't hold the load until something @@ -329,7 +388,7 @@ fn open_module(path: &std::path::Path) -> std::io::Result { #[cfg(not(target_arch = "wasm32"))] const MAX_FOLDER_FILES: usize = 1000; -/// The first [`MAX_FOLDER_FILES`] `*.wasm` paths directly in `dir` by file name, sorted, and how +/// The first [`MAX_FOLDER_FILES`] `*.wasm` and `*.vcplugin` paths directly in `dir` by file name, sorted, and how /// many more there are. Only that many paths are held while the folder is listed. An error while /// the folder is listed is returned, as one opening it is. #[cfg(not(target_arch = "wasm32"))] @@ -340,7 +399,7 @@ fn folder_files(dir: &std::path::Path) -> Result<(Vec, usize let mut more = 0; for entry in rd { let p = entry.map_err(io)?.path(); - if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) { + if !p.extension().is_some_and(|x| x.eq_ignore_ascii_case("wasm")) && !is_js_package(&p) { continue; } kept.push(p); @@ -373,7 +432,7 @@ pub struct FolderReport { pub no_thread: bool, } -/// Installs every `*.wasm` directly in `dir` (not recursive), in file-name order, up to the first +/// Installs every `*.wasm` and `*.vcplugin` ([`read_js_package`]) directly in `dir` (not recursive), in file-name order, up to the first /// 1,000 by file name; the report counts the files left out ([`FolderReport::left_out`]). Anything /// that isn't a regular file, such as a named pipe, is reported and skipped without waiting on it /// ([`load_file`]). The modules load on worker threads ([`FolderLoad`]) and install in file-name @@ -386,7 +445,7 @@ pub fn load_folder(dir: &std::path::Path) -> Result { load_folder_where(dir, |_| Ok(()), approved) } -/// [`load_folder`], loading only the files `allow` accepts, and of the plug-ins that list +/// [`load_folder`], loading only the files `allow` accepts (a JavaScript plug-in's script too), and of the plug-ins that list /// permissions only those `approve` accepts and a recorded grant covers ([`install`]); the others /// are reported as failed with the reason. A plug-in the user disabled ([`crate::safe_mode::skipped`]) is reported and /// skipped, by its file before it loads or by its id after (its file is then disabled too, so the @@ -500,7 +559,7 @@ impl FolderLoad { hook(&path); } } - load_file(&path, Limits::default()) + load_file_where(&path, Limits::default(), &*allow) })); } files.push((f, refused)); @@ -885,6 +944,104 @@ mod tests { assert!(matches!(&read, Err(Error::Module(e)) if e.contains("limit 16")), "{read:?}"); } + /// A JavaScript plug-in's manifest file and its script, in `dir`. + #[cfg(not(target_arch = "wasm32"))] + fn write_js(dir: &std::path::Path, id: &str, manifest: serde_json::Value, script: Option<&str>) -> std::path::PathBuf { + let mut m = serde_json::json!({"id": id, "name": "JS", "kind": "filter", "runtime": "js", "script": "f.js"}); + if let (Some(m), serde_json::Value::Object(extra)) = (m.as_object_mut(), manifest) { + m.extend(extra); + } + let path = dir.join(format!("{id}.vcplugin")); + std::fs::write(&path, serde_json::to_vec(&m).unwrap()).unwrap(); + if let Some(script) = script { + std::fs::write(dir.join("f.js"), script).unwrap(); + } + path + } + + /// A `.vcplugin` in a folder installs with its script, and its SHA-256 is the one an install of + /// the same package by bytes gets. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_folder_installs_a_javascript_plugin() { + let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + crate::safe_mode::set_active(None); + let dir = test_dir("js"); + let id = "test.registry.js"; + write_js(&dir, id, serde_json::json!({}), Some("function run(i) { return i; }")); + let r = load_folder_where(&dir, |_| Ok(()), |_| false).unwrap(); + let bytes = read_js_package(&dir.join(format!("{id}.vcplugin")), &|_| Ok(())).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(r.loaded, vec![id.to_string()], "{r:?}"); + let p = get(id).unwrap(); + assert_eq!((p.script(), p.hash()), (Some("f.js"), crate::permissions::sha256_hex(&bytes).as_str())); + assert!(remove(id)); + } + + /// A manifest with `"runtime": "js"` and no `script` is refused, and the error names the key; + /// so is one that names a script `allow` refuses or that isn't there. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_javascript_manifest_needs_its_script() { + let dir = test_dir("js-script"); + let no_key = write_js(&dir, "a", serde_json::json!({"script": null}), None); + let mut m: serde_json::Value = serde_json::from_slice(&std::fs::read(&no_key).unwrap()).unwrap(); + m.as_object_mut().unwrap().remove("script"); + std::fs::write(&no_key, serde_json::to_vec(&m).unwrap()).unwrap(); + let missing = write_js(&dir, "b", serde_json::json!({}), None); + let inline = write_js(&dir, "c", serde_json::json!({"source": "function run(i) { return i; }"}), None); + let not_js = write_js(&dir, "d", serde_json::json!({"runtime": "wasm"}), None); + let refused = read_js_package(&missing, &|p| Err(format!("{} is outside", p.display()))); + let results = [ + read_js_package(&no_key, &|_| Ok(())), + read_js_package(&missing, &|_| Ok(())), + read_js_package(&inline, &|_| Ok(())), + read_js_package(¬_js, &|_| Ok(())), + ]; + std::fs::remove_dir_all(&dir).unwrap(); + assert!(matches!(&results[0], Err(Error::Manifest(e)) if e.starts_with("`runtime` \"js\" needs `script`")), "{:?}", results[0]); + assert!(matches!(&results[1], Err(Error::Io(e)) if e.contains("f.js")), "{:?}", results[1]); + assert!(matches!(&results[2], Err(Error::Manifest(e)) if e.contains("`source`")), "{:?}", results[2]); + assert!(matches!(&results[3], Err(Error::Manifest(e)) if e == crate::js::NOT_JS), "{:?}", results[3]); + assert!(matches!(&refused, Err(Error::Io(e)) if e.ends_with("is outside")), "{refused:?}"); + } + + /// A script larger than the limit is refused by its size before it is opened. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_oversized_script_is_refused_before_it_is_read() { + let dir = test_dir("js-big"); + let path = write_js(&dir, "big", serde_json::json!({}), Some("")); + std::fs::File::options().write(true).open(dir.join("f.js")).unwrap().set_len(crate::js::MAX_SCRIPT_BYTES as u64 + 1).unwrap(); + let opened = std::cell::Cell::new(false); + let read = read_js_package_with(&path, &|_| Ok(()), || opened.set(true)); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(matches!(&read, Err(Error::Module(e)) if e.contains(&format!("limit {}", crate::js::MAX_SCRIPT_BYTES))), "{read:?}"); + assert!(!opened.get(), "the script was opened"); + } + + /// A manifest file's parameters keep their declaration order through the package it is read + /// into, which is its own text with `source` added. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_javascript_package_keeps_the_manifest_s_order() { + let dir = test_dir("js-order"); + let num = r#"{"type": "number", "min": 0, "max": 10, "default": 1}"#; + let text = format!( + "{{\"id\": \"order\", \"name\": \"JS\", \"kind\": \"filter\", \"runtime\": \"js\", \"script\": \"f.js\", \"params\": {{\"z\": {num}, \"a\": {num}}}}}\n" + ); + let path = dir.join("order.vcplugin"); + std::fs::write(&path, &text).unwrap(); + std::fs::write(dir.join("f.js"), "function run(i) { return i; }").unwrap(); + let bytes = read_js_package(&path, &|_| Ok(())); + std::fs::remove_dir_all(&dir).unwrap(); + let bytes = bytes.unwrap(); + let expected = format!("{},\"source\":\"function run(i) {{ return i; }}\"}}", text.trim_end().strip_suffix('}').unwrap()); + assert_eq!(String::from_utf8_lossy(&bytes), expected); + let (manifest, _) = crate::js::read_bundle(&bytes).unwrap(); + assert_eq!(manifest.params.iter().map(|(k, _)| k.as_str()).collect::>(), ["z", "a"]); + } + /// A folder load reports a subfolder, a named pipe and a link to a named pipe with `.wasm` /// names as not files, and goes on. #[cfg(unix)] diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index b7950f0056..1ad3a194fa 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -7,7 +7,7 @@ use wasmi::{ use wasmparser::{CompositeInnerType, Parser, Payload, Validator, WasmFeatures}; use crate::host::{self, Bridge, Deadline, Host, Report, Run}; -use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest}; +use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest, Runtime}; use crate::permissions::Permission; use crate::{Error, Kind, Result}; @@ -169,12 +169,17 @@ impl Default for Limits { } } +/// A plug-in's code: a WebAssembly module, or a JavaScript file ([`crate::js`]). +enum Code { + Wasm { engine: Engine, module: Module }, + Js(crate::js::Script), +} + /// A loaded, validated plug-in. Cheap to share (`Arc`) and safe to run from several threads: -/// every run gets its own store and instance. +/// every run gets its own store and instance, or for a JavaScript plug-in its own realm. pub struct Plugin { manifest: Manifest, - engine: Engine, - module: Module, + code: Code, limits: Limits, size: usize, hash: String, @@ -341,13 +346,21 @@ impl Plugin { /// is one the host offers ([`crate::host::IMPORTS`]) and its manifest allows, and checks the /// exports. A module that carries its manifest in a [`MANIFEST_SECTION`] custom section is /// checked without being instantiated, so none of its code runs; one without that section is - /// instantiated to call `vc_abi_version` and `vc_manifest`. In Safe Mode nothing is loaded - /// ([`Error::SafeMode`]). + /// instantiated to call `vc_abi_version` and `vc_manifest`. Bytes that hold a JSON object with + /// `"runtime": "js"` are a JavaScript plug-in ([`crate::js`]): its manifest is checked and its + /// script parsed, and none of it runs. In Safe Mode nothing is loaded ([`Error::SafeMode`]). pub fn load(bytes: &[u8], limits: Limits) -> Result { crate::safe_mode::check()?; if bytes.len() > limits.max_module_bytes { return Err(Error::Module(format!("module is {} bytes (limit {})", bytes.len(), limits.max_module_bytes))); } + if bytes.trim_ascii_start().starts_with(b"{") { + let (manifest, script) = crate::js::read_bundle(bytes)?; + let hash = crate::permissions::sha256_hex(bytes); + let mut p = Plugin { manifest, code: Code::Js(script), limits, size: bytes.len(), hash, source: None, serial: 0 }; + p.heavy_limits(); + return Ok(p); + } if !bytes.starts_with(b"\0asm") { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())); } @@ -362,8 +375,17 @@ impl Plugin { let module = Module::new(&engine, bytes).map_err(|e| Error::Module(e.to_string()))?; let imports = host::check_imports(&module)?; let hash = crate::permissions::sha256_hex(bytes); - let mut p = Plugin { manifest: Manifest::placeholder(), engine, module, limits, size: bytes.len(), hash, source: None, serial: 0 }; - let live = match section_manifest(&p.module)? { + let section = section_manifest(&module)?; + let mut p = Plugin { + manifest: Manifest::placeholder(), + code: Code::Wasm { engine, module: module.clone() }, + limits, + size: bytes.len(), + hash, + source: None, + serial: 0, + }; + let live = match section { Some(manifest) => { p.manifest = manifest; None @@ -388,13 +410,11 @@ impl Plugin { Some(live) } }; - host::check_granted(&p.manifest, &imports)?; - // A heavy filter's runs get the larger budget the host allows for one, which the host - // lets the user allow or refuse before installing it. - if p.manifest.budget == crate::Budget::Heavy { - p.limits.fuel_base = p.limits.fuel_base.max(p.limits.heavy_fuel); - p.limits.wall_time_ms = p.limits.wall_time_ms.max(p.limits.heavy_wall_time_ms); + if p.manifest.runtime != Runtime::Wasm { + return Err(Error::Manifest("a WebAssembly module's manifest leaves `runtime` out: \"js\" is for a JavaScript plug-in".into())); } + host::check_granted(&p.manifest, &imports)?; + p.heavy_limits(); // The other exports must exist with the right types. match live { Some(live) => { @@ -402,13 +422,35 @@ impl Plugin { live.func::("vc_run")?; } None => { - check_exports(&p.module, p.limits.max_memory_bytes)?; + check_exports(&module, p.limits.max_memory_bytes)?; check_tables(bytes)?; } } Ok(p) } + /// A heavy filter's runs get the larger budget the host allows for one, which the host lets the + /// user allow or refuse before installing it. + fn heavy_limits(&mut self) { + if self.manifest.budget == crate::Budget::Heavy { + self.limits.fuel_base = self.limits.fuel_base.max(self.limits.heavy_fuel); + self.limits.wall_time_ms = self.limits.wall_time_ms.max(self.limits.heavy_wall_time_ms); + } + } + + /// What runs its code ([`Manifest::runtime`]). + pub fn runtime(&self) -> Runtime { + self.manifest.runtime + } + + /// A JavaScript plug-in's script file name; `None` for a WebAssembly module. + pub fn script(&self) -> Option<&str> { + match &self.code { + Code::Js(script) => Some(&script.name), + Code::Wasm { .. } => None, + } + } + pub fn manifest(&self) -> &Manifest { &self.manifest } @@ -452,6 +494,7 @@ impl Plugin { /// A new instance for `run`, with the host imports of the permissions `granted` linked. When the /// module's start function fails, what it reported through the host imports goes to `report`. fn instantiate(&self, run: Run, granted: &[Permission], report: &mut Report) -> Result { + let Code::Wasm { engine, module } = &self.code else { return Err(Error::Module("not a WebAssembly binary (missing \\0asm header)".into())) }; let limits = StoreLimitsBuilder::new() .memory_size(self.limits.max_memory_bytes) .memories(1) @@ -459,13 +502,13 @@ impl Plugin { .table_elements(MAX_TABLE_ELEMENTS as usize) .instances(1) .build(); - let mut store = Store::new(&self.engine, Host { limits, run }); + let mut store = Store::new(engine, Host { limits, run }); store.limiter(|h| &mut h.limits); // The start function (if any) runs on one slice of fuel: it runs before `call` can check // the deadline or a cancel between slices, so a heavy budget would let it run for minutes. store.set_fuel(self.limits.fuel_base.min(FUEL_SLICE)).map_err(wasm_err)?; - let linker = host::linker(&self.engine, granted); - let instance = match linker.instantiate_and_start(&mut store, &self.module) { + let linker = host::linker(engine, granted); + let instance = match linker.instantiate_and_start(&mut store, module) { Ok(instance) => instance, Err(e) => { *report = std::mem::take(&mut store.data_mut().run.report); @@ -595,6 +638,14 @@ impl Plugin { let deadline = Deadline::new(limits.wall_time_ms); let m = &self.manifest; let run = Run::new(&m.id, m.kind != Kind::Effect, true, deadline).with_storage(crate::registry::storage(&m.id)); + if let Code::Js(script) = &self.code { + // Its manifest lists no `commands`, so nothing calls it with a bridge. + if bridge.is_some() { + return Err(Error::Abi("a JavaScript plug-in makes no command calls".into())); + } + let call = crate::js::Call { input, params, limits, max_memory: self.limits.max_memory_bytes, deadline }; + return crate::js::run(script, m, &call, run, report); + } let mut live = self.instantiate(run, &m.permissions(), report)?; // Calls can be made from `vc_run` on, not from the start function. if bridge.is_some() { diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index cad3127abd..ae2a5c2fdc 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -1,8 +1,9 @@ //! Colour reduction for palette formats (PNG-8, GIF): a palette of at most 256 colours chosen by //! median cut over a 15-bit histogram (refined by a few k-means passes) or a fixed palette, then //! each pixel mapped to its nearest entry with optional dithering (Floyd–Steinberg diffusion, an -//! 8×8 ordered pattern, or noise). Pixels under half opacity can become one transparent entry; -//! the others are blended over the matte colour. +//! 8×8 ordered pattern, or noise). Pixels under half opacity can become one transparent entry, or +//! with a transparency dither a share of the partly transparent pixels that follows their +//! opacity; the others are blended over the matte color. use std::collections::HashMap; @@ -111,11 +112,18 @@ pub struct PaletteOptions { pub dither: Dither, /// Dither strength 0–100. pub dither_amount: u8, - /// Pixels under half opacity become a transparent entry; otherwise every pixel is opaque. + /// Pixels under half opacity become a transparent entry (see `transparency_dither`); + /// otherwise every pixel is opaque. pub transparency: bool, /// The colour partly transparent pixels are blended over. `None`: with transparency, they /// keep their own colour (hard edges); without, white. pub matte: Option<[u8; 3]>, + /// With `transparency`, how partly transparent pixels are split between the transparent entry + /// and their color ([`clear_mask`]); `Dither::None` cuts them at half opacity. + pub transparency_dither: Dither, + /// The strength of the diffusion transparency dither, 0–100 (0 cuts at half opacity); the + /// pattern and noise methods do not use it. + pub transparency_dither_amount: u8, } impl Default for PaletteOptions { @@ -127,6 +135,8 @@ impl Default for PaletteOptions { dither_amount: 100, transparency: true, matte: Some([255; 3]), + transparency_dither: Dither::None, + transparency_dither_amount: 100, } } } @@ -153,12 +163,12 @@ pub fn quantize(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions) -> Ind /// them all anyway; locked colours no pixel ends up using are left out. pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, locked: &[[u8; 3]]) -> Indexed { let px = rgba.as_chunks::<4>().0; - let clear = |p: &[u8; 4]| o.transparency && p[3] < 128; + let clear = clear_mask(rgba, width, o); let matte = o.matte.unwrap_or([255; 3]); let colors = opaque_colors(px, o, matches!(o.reduction, Reduction::Gray | Reduction::BlackWhite)); - let has_clear = px.iter().any(clear); + let has_clear = clear.contains(&true); let k = (o.colors.clamp(2, 256) as usize - usize::from(has_clear)).max(1); - let opaque = || colors.iter().zip(px).filter(|(_, p)| !clear(p)).map(|(c, _)| *c); + let opaque = || colors.iter().zip(&clear).filter(|(_, c)| !**c).map(|(c, _)| *c); // Locked colours take their slots first (at least one is left for the reduction). let mut lock: Vec<[u8; 3]> = Vec::with_capacity(locked.len().min(k)); for c in locked { @@ -168,6 +178,22 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, } let free = k - lock.len(); let (mut palette, exact) = match o.reduction { + // With one entry left (two colors and a transparent entry, or the others locked): black or + // white, whichever leaves the opaque pixels nearer the palette, the locked colors included. + Reduction::BlackWhite if free < 2 => { + let mut hist = [0u64; 256]; + for c in opaque() { + hist[c[0] as usize] += 1; + } + let w = o.reduction.weights(); + let cost = |end: [u8; 3]| -> f32 { + let entries: Vec<[f32; 3]> = lock.iter().chain([&end]).map(|c| c.map(f32::from)).collect(); + let near = |g: f32| entries.iter().map(|&e| dist([g; 3], e, w)).fold(f32::INFINITY, f32::min); + hist.iter().enumerate().filter(|(_, n)| **n > 0).map(|(g, &n)| n as f32 * near(g as f32)).sum() + }; + let ends = [[0; 3], [255; 3]].into_iter().filter(|c| !lock.contains(c)); + (ends.min_by(|a, b| cost(*a).total_cmp(&cost(*b))).into_iter().collect(), false) + } Reduction::BlackWhite => (vec![[0; 3], [255; 3]], false), Reduction::Gray => ((0..free).map(|i| [(i * 255 / (free - 1).max(1)) as u8; 3]).collect(), false), Reduction::Web => (web(opaque(), free), false), @@ -185,7 +211,7 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, if palette.is_empty() { palette.push(matte); } - finish(px, &colors, width, height, &palette, o, if exact { Dither::None } else { o.dither }) + finish(&clear, &colors, width, height, &palette, o, if exact { Dither::None } else { o.dither }) } /// [`quantize`] to the fixed `palette`: each pixel takes its nearest entry, with `o`'s dither, @@ -195,26 +221,92 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, palette: &[[u8; 3]]) -> Indexed { let px = rgba.as_chunks::<4>().0; let colors = opaque_colors(px, o, false); - let has_clear = o.transparency && px.iter().any(|p| p[3] < 128); + let clear = clear_mask(rgba, width, o); + let has_clear = clear.contains(&true); let mut palette: Vec<[u8; 3]> = palette.iter().take(256 - usize::from(has_clear)).copied().collect(); if palette.is_empty() { palette.push(o.matte.unwrap_or([255; 3])); } - finish(px, &colors, width, height, &palette, o, o.dither) + finish(&clear, &colors, width, height, &palette, o, o.dither) } -/// For each pixel of `rgba`, the entry of `palette` nearest its color, as [`quantize_to`] measures -/// it (the matte, transparency and `o.reduction`'s distance weights) without dither; `None` for a -/// pixel that becomes transparent, and for every pixel when `palette` is empty. `f` gets each -/// pixel's entry in pixel order, worked out one pixel at a time. -pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]], mut f: impl FnMut(Option)) { +/// For each pixel of `rgba` (`width` pixels a row), the entry of `palette` nearest its color, as +/// [`quantize_to`] measures it (the matte, transparency and `o.reduction`'s distance weights) +/// without dither; `None` for a pixel that becomes transparent ([`clear_mask`]), and for every +/// pixel when `palette` is empty. `f` gets each pixel's entry in pixel order, worked out one pixel +/// at a time. +pub fn nearest_entries(rgba: &[u8], width: u32, o: &PaletteOptions, palette: &[[u8; 3]], mut f: impl FnMut(Option)) { + let clear = clear_mask(rgba, width, o); let pal: Vec<[f32; 3]> = palette.iter().map(|c| c.map(f32::from)).collect(); let index = PaletteIndex::new(&pal, o.reduction.weights()); - for p in rgba.as_chunks::<4>().0 { - f(if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(opaque_color(p, o, false).map(f32::from))) }); + for (p, &clear) in rgba.as_chunks::<4>().0.iter().zip(&clear) { + f(if pal.is_empty() || clear { None } else { Some(index.nearest(opaque_color(p, o, false).map(f32::from))) }); } } +/// Which pixels of `rgba` (`width` pixels a row) become the transparent entry. Without +/// `o.transparency`, none. Otherwise fully transparent pixels always do and opaque ones never; a +/// partly transparent pixel does under half opacity with no transparency dither, and else by +/// `o.transparency_dither`. With pattern, noise, or diffusion at amount 100, about as many of an +/// area's pixels stay opaque as its opacity says; a lower diffusion amount moves the result toward +/// the cut at half opacity. Diffusion spreads each partly transparent pixel's opacity error to the +/// pixels right of it and below it (Floyd–Steinberg, scaled by `o.transparency_dither_amount`), and +/// fully transparent and opaque pixels pass on the error they receive; pattern compares the +/// opacity with the 8×8 ordered pattern and noise with a noise threshold. The result depends only +/// on the pixels and the options, so exports are reproducible. +pub fn clear_mask(rgba: &[u8], width: u32, o: &PaletteOptions) -> Vec { + let px = rgba.as_chunks::<4>().0; + if !o.transparency { + return vec![false; px.len()]; + } + let width = (width as usize).min(px.len()).max(1); + let amount = f32::from(o.transparency_dither_amount.min(100)) / 100.0; + let dither = match o.transparency_dither { + Dither::Diffusion if amount == 0.0 => Dither::None, + d => d, + }; + // Two rows of opacity error for diffusion (the current one and the next), one pixel of margin + // on each side. + let mut err = vec![0f32; if dither == Dither::Diffusion { 2 * (width + 2) } else { 0 }]; + let half = err.len() / 2; + let mut out = Vec::with_capacity(px.len()); + for (y, row) in px.chunks(width).enumerate() { + let (cur, next) = err.split_at_mut(half); + next.fill(0.0); + for (x, p) in row.iter().enumerate() { + let a = f32::from(p[3]); + let clear = match (p[3], dither) { + (0, _) => true, + (255, _) => false, + (_, Dither::None) => p[3] < 128, + (_, Dither::Pattern) => a < 255.0 * bayer(x % 8, y % 8), + // Another noise than the color dither's, so the two do not line up. + (_, Dither::Noise) => a < 255.0 * noise(x ^ 0x5a5a, y ^ 0xa5a5), + (_, Dither::Diffusion) => a + cur[x + 1] < 127.5, + }; + if dither == Dither::Diffusion { + // A partly transparent pixel spreads its own opacity error. A fully transparent or + // opaque pixel keeps its state and passes on the error it received unchanged, so + // the partly transparent pixels around it keep their share of opacity + // (VectorCraft's own rule). + let got = cur[x + 1]; + let e = match p[3] { + 0 | 255 => got, + _ => (a + got - if clear { 0.0 } else { 255.0 }) * amount, + }; + // 7/16 right, 3/16 below left, 5/16 below, 1/16 below right. + cur[x + 2] += e * 7.0 / 16.0; + next[x] += e * 3.0 / 16.0; + next[x + 1] += e * 5.0 / 16.0; + next[x + 2] += e / 16.0; + } + out.push(clear); + } + cur.copy_from_slice(next); + } + out +} + /// The color of each pixel when opaque: blended over the matte, and gray when `gray`. fn opaque_colors(px: &[[u8; 4]], o: &PaletteOptions, gray: bool) -> Vec<[u8; 3]> { px.iter().map(|p| opaque_color(p, o, gray)).collect() @@ -229,20 +321,20 @@ fn opaque_color(p: &[u8; 4], o: &PaletteOptions, gray: bool) -> [u8; 3] { if gray { [luma(c); 3] } else { c } } -/// Map the pixels `px` (their opaque `colors`) to `palette` with `dither`, then drop the entries -/// no pixel uses and put the transparent entry first when a pixel is transparent. -fn finish(px: &[[u8; 4]], colors: &[[u8; 3]], width: u32, height: u32, palette: &[[u8; 3]], o: &PaletteOptions, dither: Dither) -> Indexed { - let clear = |p: &[u8; 4]| o.transparency && p[3] < 128; +/// Map the pixels (their opaque `colors`, transparent where `clear` says) to `palette` with +/// `dither`, then drop the entries no pixel uses and put the transparent entry first when a pixel +/// is transparent. +fn finish(clear: &[bool], colors: &[[u8; 3]], width: u32, height: u32, palette: &[[u8; 3]], o: &PaletteOptions, dither: Dither) -> Indexed { + let clear = |i: usize| clear.get(i).copied().unwrap_or(false); let matte = o.matte.unwrap_or([255; 3]); - let has_clear = px.iter().any(clear); + let has_clear = (0..colors.len()).any(clear); let weights = o.reduction.weights(); // (A width past the pixels there are would size the error rows from a number nothing checked.) - let mut indices = - map(colors, (width as usize).min(colors.len()), palette, weights, dither, f32::from(o.dither_amount.min(100)) / 100.0, |i| clear(&px[i])); + let mut indices = map(colors, (width as usize).min(colors.len()), palette, weights, dither, f32::from(o.dither_amount.min(100)) / 100.0, clear); // Drop the entries no pixel uses (fixed palettes), keeping the order. let mut used = [false; 256]; for (i, &ix) in indices.iter().enumerate() { - if !clear(&px[i]) { + if !clear(i) { used[ix as usize] = true; } } @@ -258,7 +350,7 @@ fn finish(px: &[[u8; 4]], colors: &[[u8; 3]], width: u32, height: u32, palette: } } for (i, ix) in indices.iter_mut().enumerate() { - *ix = if clear(&px[i]) { 0 } else { remap[*ix as usize] }; + *ix = if clear(i) { 0 } else { remap[*ix as usize] }; } Indexed { width, height, palette: kept, transparent: has_clear.then_some(0), indices } } diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index d9a8a2fc0f..837c62f359 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -3,7 +3,7 @@ use vectorcraft_doc::{Appearance, Node}; use vectorcraft_geom::shapes; use super::png::{PngOptions, encode_indexed}; -use super::quantize::{Dither, Indexed, PaletteOptions, Reduction, quantize, quantize_to}; +use super::quantize::{Dither, Indexed, PaletteOptions, Reduction, clear_mask, nearest_entries, quantize, quantize_to}; use super::*; /// A `w`×`h` opaque image of `f(x, y)` colours. @@ -71,7 +71,7 @@ fn colours_cap_the_palette() { let px = ramps(64, 48); for colors in [2, 16, 64, 256] { for dither in Dither::ALL { - for reduction in [Reduction::Perceptual, Reduction::Selective, Reduction::Adaptive, Reduction::Web, Reduction::Gray] { + for reduction in Reduction::ALL { let ix = quantize(&px, 64, 48, &PaletteOptions { colors, dither, reduction, ..Default::default() }); assert!(ix.palette.len() <= colors as usize, "{colors} {dither:?} {reduction:?}: {}", ix.palette.len()); assert!(ix.indices.iter().all(|&i| (i as usize) < ix.palette.len())); @@ -252,3 +252,104 @@ fn ids_round_trip() { assert_eq!(Dither::from_id(d.id()), Some(d)); } } + +/// A `w`×`h` red image whose pixels have the opacity `alpha(x, y)`. +fn see_through(w: u32, h: u32, alpha: impl Fn(u32, u32) -> u8) -> Vec { + (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| [255, 0, 0, alpha(x, y)]).collect() +} + +/// The share of the pixels of `ix` that are not transparent. +fn opaque_share(ix: &Indexed) -> f64 { + ix.indices.iter().filter(|&&i| ix.transparent != Some(i)).count() as f64 / ix.indices.len() as f64 +} + +fn alpha_dither(d: Dither, amount: u8) -> PaletteOptions { + PaletteOptions { transparency_dither: d, transparency_dither_amount: amount, ..Default::default() } +} + +#[test] +fn transparency_dither_keeps_about_as_many_pixels_as_their_opacity() { + let (w, h) = (32, 32); + for alpha in [64u8, 128, 191] { + let px = see_through(w, h, |_, _| alpha); + // No transparency dither cuts at half opacity, and so does Diffusion at 0. + let none = quantize(&px, w, h, &alpha_dither(Dither::None, 100)); + assert_eq!(opaque_share(&none), if alpha < 128 { 0.0 } else { 1.0 }, "none at {alpha}"); + assert_eq!(quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 0)), none, "diffusion at 0, {alpha}"); + for d in [Dither::Diffusion, Dither::Pattern, Dither::Noise] { + let ix = quantize(&px, w, h, &alpha_dither(d, 100)); + let share = opaque_share(&ix); + assert!((share - f64::from(alpha) / 255.0).abs() < 0.08, "{d:?} at {alpha}: {share}"); + assert_eq!(ix.transparent, Some(0), "{d:?} at {alpha}"); + // The same pixels and options give the same image. + assert_eq!(quantize(&px, w, h, &alpha_dither(d, 100)), ix, "{d:?} at {alpha}"); + // A fixed palette and the nearest entries make the same pixels transparent. + let fixed = quantize_to(&px, w, h, &alpha_dither(d, 100), &[[255, 0, 0], [0, 0, 255]]); + assert_eq!(opaque_share(&fixed), share, "{d:?} at {alpha}, fixed palette"); + let mut near = Vec::new(); + nearest_entries(&px, w, &alpha_dither(d, 100), &[[255, 0, 0]], |n| near.push(n)); + let mask = clear_mask(&px, w, &alpha_dither(d, 100)); + assert_eq!(near.iter().map(Option::is_none).collect::>(), mask, "{d:?} at {alpha}"); + } + // Diffusion at half strength keeps fewer pixels of a light area opaque than at full. + if alpha < 128 { + let half = opaque_share(&quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 50))); + let full = opaque_share(&quantize(&px, w, h, &alpha_dither(Dither::Diffusion, 100))); + assert!(0.0 < half && half < full, "{alpha}: {half} {full}"); + } + } + // The methods arrange the pixels differently. + let px = see_through(w, h, |_, _| 96); + let masks: Vec> = [Dither::Diffusion, Dither::Pattern, Dither::Noise].map(|d| clear_mask(&px, w, &alpha_dither(d, 100))).into(); + assert!(masks[0] != masks[1] && masks[1] != masks[2] && masks[0] != masks[2]); +} + +#[test] +fn transparency_dither_leaves_clear_and_opaque_pixels_and_needs_transparency() { + let (w, h) = (16, 8); + // Fully transparent on the left, opaque on the right: every method keeps them as they are. + let hard = see_through(w, h, |x, _| if x < 8 { 0 } else { 255 }); + let none = clear_mask(&hard, w, &alpha_dither(Dither::None, 100)); + assert_eq!(none.iter().filter(|c| **c).count(), 64); + for d in Dither::ALL { + assert_eq!(clear_mask(&hard, w, &alpha_dither(d, 100)), none, "{d:?}"); + } + // Without transparency nothing is transparent, whatever the transparency dither. + let soft = see_through(w, h, |x, _| (x * 16) as u8); + for d in Dither::ALL { + let o = PaletteOptions { transparency: false, ..alpha_dither(d, 100) }; + assert!(!clear_mask(&soft, w, &o).contains(&true), "{d:?}"); + assert_eq!(quantize(&soft, w, h, &o).transparent, None, "{d:?}"); + } + // A palette of two entries keeps one for the transparent pixels and one for the others. + let o = PaletteOptions { colors: 2, ..alpha_dither(Dither::Pattern, 100) }; + let ix = quantize(&see_through(w, h, |_, _| 128), w, h, &o); + assert_eq!((ix.palette.len(), ix.transparent), (2, Some(0))); + // So does Black & White, with black and white pixels both left opaque. + let bw = PaletteOptions { reduction: Reduction::BlackWhite, matte: None, ..o }; + let px: Vec = (0..64u32).flat_map(|i| if i % 8 < 4 { [0, 0, 0, 128] } else { [255, 255, 255, 128] }).collect(); + let ix = quantize(&px, 8, 8, &bw); + assert_eq!(ix.transparent, Some(0)); + assert!(ix.palette.len() <= 2, "{:?}", ix.palette); + // No pixels, and a width past the pixels there are. + assert!(clear_mask(&[], 0, &alpha_dither(Dither::Diffusion, 100)).is_empty()); + assert_eq!(clear_mask(&see_through(3, 1, |_, _| 200), 1000, &alpha_dither(Dither::Diffusion, 100)).len(), 3); +} + +#[test] +fn transparency_diffusion_passes_error_through_clear_and_opaque_pixels() { + // Half-opaque pixels between fully transparent or fully opaque ones, in one row and in a + // checkerboard: about half of them stay opaque, and the others keep their state. + for other in [0u8, 255] { + for (w, h, half) in [(64, 1, (|x, _| x % 2 == 0) as fn(u32, u32) -> bool), (32, 32, |x, y| (x + y) % 2 == 0)] { + let px = see_through(w, h, |x, y| if half(x, y) { 128 } else { other }); + let mask = clear_mask(&px, w, &alpha_dither(Dither::Diffusion, 100)); + let at = |x: u32, y: u32| mask[(y * w + x) as usize]; + let cells: Vec<(u32, u32)> = (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).collect(); + assert!(cells.iter().filter(|&&(x, y)| !half(x, y)).all(|&(x, y)| at(x, y) == (other == 0)), "{other} {w}x{h}"); + let halves: Vec<_> = cells.iter().filter(|&&(x, y)| half(x, y)).collect(); + let share = halves.iter().filter(|&&&(x, y)| !at(x, y)).count() as f64 / halves.len() as f64; + assert!((share - 128.0 / 255.0).abs() < 0.1, "{other} {w}x{h}: {share}"); + } + } +} diff --git a/crates/render/src/encode/tests_web.rs b/crates/render/src/encode/tests_web.rs index 79e36b3f5f..3eb10c364b 100644 --- a/crates/render/src/encode/tests_web.rs +++ b/crates/render/src/encode/tests_web.rs @@ -22,6 +22,15 @@ fn locked_colours_survive_a_reduction() { let ix = quantize_locked(&px, 64, 16, &o, &[rare]); assert!(ix.palette.contains(&rare) && ix.palette.len() <= 4, "{:?}", ix.palette); assert_eq!(colours(&ix)[0], rare); + // Black & White with black locked and one entry left: white takes it, though most pixels are black. + let px = image(8, 8, |x, _| if x == 7 { [255; 3] } else { [0; 3] }); + let o = PaletteOptions { colors: 2, dither: Dither::None, reduction: Reduction::BlackWhite, ..Default::default() }; + let ix = quantize_locked(&px, 8, 8, &o, &[[0; 3]]); + assert_eq!(ix.palette, [[0; 3], [255; 3]]); + // With a light gray locked, black takes the entry left, though most pixels are white. + let px = image(10, 1, |x, _| if x < 4 { [0; 3] } else { [255; 3] }); + let ix = quantize_locked(&px, 10, 1, &o, &[[200; 3]]); + assert_eq!(ix.palette, [[200; 3], [0; 3]]); } #[test] diff --git a/crates/render/src/node_checks.rs b/crates/render/src/node_checks.rs index a4d9fda7af..ecba138052 100644 --- a/crates/render/src/node_checks.rs +++ b/crates/render/src/node_checks.rs @@ -112,9 +112,7 @@ pub(crate) fn holds_instance(n: &Node) -> bool { /// guide the view hides, a ruler guide (the canvas draws those), drawn hidden, or the instance its /// symbol is being edited from? pub(crate) fn left_out(opts: &crate::RenderOptions, doc: &vectorcraft_doc::Document, a: &Node) -> bool { - let view_item = a.is_ruler_guide() - || (opts.skip_templates || opts.hide_templates) && matches!(a.kind, NodeKind::Layer { template: true, .. }) - || (opts.skip_templates || opts.hide_guides) && matches!(a.kind, NodeKind::Path { guide: true, .. }); + let view_item = a.is_ruler_guide() || a.hidden_by_view(opts.skip_templates || opts.hide_templates, opts.skip_templates || opts.hide_guides); !a.visible || view_item || opts.hidden.contains(&a.id) || edited_instance(opts, doc, a.id) } diff --git a/crates/render/src/proof.rs b/crates/render/src/proof.rs index ed38102f61..d8e3aae26d 100644 --- a/crates/render/src/proof.rs +++ b/crates/render/src/proof.rs @@ -669,6 +669,5 @@ pub fn active_proof() -> Option { /// Whether [`RenderOptions::overprint_preview`] should be on (Separations Preview implies it). pub fn overprint_preview_on() -> bool { - let v = view(); - v.overprint || v.separations.is_some() + VIEW.read().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|v| v.overprint || v.separations.is_some()) } diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 01dc0dfbb2..0e331057d7 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -338,18 +338,19 @@ impl Operand { /// object: `[new] File|Folder(…)`, `new File|Folder`, `File.openDialog(…)`, `File.saveDialog(…)`, /// `Folder.selectDialog(…)`, `Folder.` ([`catalog::FOLDER_PLACES`]) or a variable holding /// one. `file`: `t` is the platform's `File` or `Folder`; `alias`: `t` names a variable holding a - /// File or Folder object. + /// File or Folder object, `Some(true)` when it counts as a Folder object whatever the path names. /// - /// Only `new Folder(…)`, `new Folder` and `Folder.` are Folder objects whatever the path - /// names. `Folder(…)` gives a File object when the path names a file, `Folder.selectDialog(…)` - /// gives a File or Folder object for what the user picks, `Folder.current` is the one place a - /// script can assign, and a variable another variable was assigned to may hold a File object. - fn file_step(self, t: &Sig, file: bool, alias: bool) -> Operand { + /// Only `new Folder(…)`, `new Folder`, `Folder.` and such a variable are Folder objects + /// whatever the path names. `Folder(…)` gives a File object when the path names a file, + /// `Folder.selectDialog(…)` gives a File or Folder object for what the user picks, and + /// `Folder.current` is the one place a script can assign. A variable another variable is assigned + /// may hold a File object, so a grouped value passes `Some(false)` for any variable. + fn file_step(self, t: &Sig, file: bool, alias: Option) -> Operand { match self { Operand::Start if t.word("new") => Operand::New, Operand::Start if file => Operand::FileName { new: false, folder: t.text == catalog::FOLDER }, Operand::New if file => Operand::FileName { new: true, folder: t.text == catalog::FOLDER }, - Operand::Start if alias => Operand::Done(Held::File { folder: false }), + Operand::Start if alias.is_some() => Operand::Done(Held::File { folder: alias == Some(true) }), Operand::FileName { new, folder } if t.is("(") => Operand::FileCall { folder: new && folder }, Operand::FileDialog if t.is("(") => Operand::FileCall { folder: false }, Operand::FileName { new: false, folder } if t.is(".") => Operand::FileMember { folder }, @@ -1378,7 +1379,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn group_step(&mut self, t: &Sig<'s>, started: bool, before: usize) { let after = self.depth(); let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text); - let alias = self.alias(t); + let alias = self.alias(t).then_some(false); let Some(g) = self.groups.last_mut().filter(|g| !g.closed) else { return }; if after < g.level { // The `)` of the innermost pair: the operand, when complete, is the pair's value and the @@ -1436,7 +1437,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn paren_step(&mut self, t: &Sig<'s>, before: usize) { let after = self.depth(); let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text); - let alias = self.alias(t); + // A variable in grouping parentheses is the object it holds now, as it is outside them + // ([`Analyzer::held_file`]). + let alias = self.alias(t).then(|| self.folder(t.text)); if let Some(p) = self.parens.last_mut() { if before == p.level { p.operand = match std::mem::replace(&mut p.operand, Operand::Other) { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 45f5d02d02..dd11c3dd0a 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -619,6 +619,25 @@ fn file_only_calls_on_a_folder_do_nothing() { assert_eq!(lines("file.dialog"), [8]); } +/// A variable holding a Folder object is the same object in grouping parentheses, so `(d).write(s)` +/// and `(d).length = 0` do nothing, as `d.write(s)` and `d.length = 0` do. A variable that may hold +/// a File object still counts in them. +#[test] +fn a_folder_in_parentheses_is_still_a_folder() { + let r = report(concat!( + "var d = new Folder(p);\n", + "(d).write(s); ((d)).copy(q); (d).open('r'); (d).length = 0;\n", + "var f = new File(p);\n", + "(f).write(s);\n", + "var g = Folder(p); (g).open('r');\n", + )); + let lines = |id: &str| feature(&r, id).map(|f| f.lines.clone()).unwrap_or_default(); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[4][..])]); + assert_eq!(lines("file.write"), [4]); + assert_eq!(lines("file.read"), [5]); +} + /// A File object assigned to a function's own variable, its parameter or a `catch` block's /// parameter ends with them; one assigned to an outer variable stays. Such a variable or parameter /// starts without what the outer variable of the same name was assigned. diff --git a/crates/text/src/colr.rs b/crates/text/src/colr.rs index 637dd9c243..37c4cefbae 100644 --- a/crates/text/src/colr.rs +++ b/crates/text/src/colr.rs @@ -73,6 +73,10 @@ pub(crate) fn colour_glyph( return (None, false); } let used = tree.foreground_used; + // Over the budget nothing is drawn, not even the raster fallback: it would replay the graph. + if tree.too_large { + return (None, used); + } if tree.unsupported.is_some() { // What it paints, y up, for a glyph without a clip box. let painted = tree.painted.map(|b| FLIP.transform_rect_bbox(b)); @@ -114,7 +118,7 @@ fn outline(font: &skrifa::FontRef<'_>, location: LocationRef<'_>, gid: GlyphId) if let Some(g) = font.outline_glyphs().get(gid) { let _ = g.draw(DrawSettings::unhinted(Size::unscaled(), location), &mut pen); } - let mut path = pen.0; + let mut path = pen.finish(); path.apply_affine(FLIP); path } @@ -507,6 +511,9 @@ impl ColorPainter for Tree<'_> { self.unsupported.get_or_insert("a fill outside any glyph"); return; }; + if self.too_large { + return; + } let Some(clip) = self.groups.get(at).and_then(|g| g.clip.clone()) else { return }; let innermost = at + 1 == self.groups.len(); let before = self.groups.last().map_or(0, |g| g.children.len()); @@ -523,6 +530,9 @@ impl ColorPainter for Tree<'_> { /// The glyph's outline filled, the brush moved by `brush_transform` (the glyph stays). fn fill_glyph(&mut self, glyph_id: GlyphId, brush_transform: Option, brush: Brush<'_>) { + if self.too_large { + return; + } let path = self.layer_outline(glyph_id); let brush_xf = self.transform() * brush_transform.as_ref().map_or(Affine::IDENTITY, affine); self.transforms.push(brush_xf); diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 67818e8d9f..6964c3af19 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -27,6 +27,7 @@ mod dirs; mod face; mod glyph_pen; mod gsub; +mod installed; mod lookup; mod names; mod scan; @@ -58,6 +59,7 @@ pub(crate) use face::PathAlignHeights; pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins, OutlineFormat}; pub(crate) use glyph_pen::FlipPen; pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; +pub use installed::{InstalledFace, UnloadedFile}; #[cfg(not(target_arch = "wasm32"))] use names::SysFallback; #[cfg(test)] diff --git a/crates/text/src/fontdb/glyph_pen.rs b/crates/text/src/fontdb/glyph_pen.rs index a7f5c869bf..f01b0d9639 100644 --- a/crates/text/src/fontdb/glyph_pen.rs +++ b/crates/text/src/fontdb/glyph_pen.rs @@ -7,14 +7,20 @@ pub(super) fn svg_drawn(face: &FontFace, font: &skrifa::FontRef<'_>, gid: u32) - face.svg_glyphs && !crate::colr::has_colour_glyph(font, gid) } -/// The most path elements one glyph outline keeps. Real outlines have hundreds; a variable -/// composite glyph can repeat a big base outline into millions. Elements past it are dropped. +/// Most path elements one glyph outline may have: a glyph that needs more (a variable font's +/// composite glyph repeating a large component many times) is drawn as nothing, not kept. pub(crate) const MAX_OUTLINE_ELEMENTS: usize = 1 << 20; -/// A pen drawing outlines y down, as text space has them. +/// A pen drawing outlines y down, as text space has them. It stops taking segments once the path +/// holds [`MAX_OUTLINE_ELEMENTS`], and [`Self::finish`] then gives an empty path. pub(crate) struct FlipPen(pub(crate) BezPath); impl FlipPen { + /// The outline drawn, or an empty path when it passed [`MAX_OUTLINE_ELEMENTS`]. + pub(crate) fn finish(self) -> BezPath { + if self.0.elements().len() >= MAX_OUTLINE_ELEMENTS { BezPath::new() } else { self.0 } + } + fn full(&self) -> bool { self.0.elements().len() >= MAX_OUTLINE_ELEMENTS } @@ -77,12 +83,17 @@ mod tests { use super::*; #[test] - fn a_pen_keeps_at_most_the_element_cap() { + fn a_pen_past_the_cap_gives_nothing() { let mut pen = FlipPen(BezPath::new()); pen.move_to(0.0, 0.0); for i in 0..MAX_OUTLINE_ELEMENTS + 10 { - pen.line_to(i as f32, 0.0); + pen.line_to(i as f32, 1.0); } - assert_eq!(pen.0.elements().len(), MAX_OUTLINE_ELEMENTS); + assert_eq!(pen.0.elements().len(), MAX_OUTLINE_ELEMENTS, "it stops taking segments"); + assert!(pen.finish().elements().is_empty()); + let mut small = FlipPen(BezPath::new()); + small.move_to(0.0, 0.0); + small.line_to(1.0, 1.0); + assert_eq!(small.finish().elements().len(), 2); } } diff --git a/crates/text/src/fontdb/installed.rs b/crates/text/src/fontdb/installed.rs new file mode 100644 index 0000000000..05ec64bccb --- /dev/null +++ b/crates/text/src/fontdb/installed.rs @@ -0,0 +1,201 @@ +//! Installed faces that nothing has loaded yet, read for one search without adding them to the +//! database (Retype's matching, `vectorcraft_text::retype`). + +#[cfg(not(target_arch = "wasm32"))] +use super::build::make_face; +#[cfg(not(target_arch = "wasm32"))] +use super::face::FontBytes; +#[cfg(not(target_arch = "wasm32"))] +use super::scan::enumerate_faces; +use super::{Arc, FontDb, FontFace, Path, PathBuf}; + +/// One style of an installed family that is not loaded: no loaded face has its family and style. +#[derive(Clone, Debug, PartialEq)] +pub struct InstalledFace { + pub family: String, + pub style: String, + /// The font file holding it (a suitcase font's file, whose fonts are in its resource fork). + pub path: PathBuf, + /// The file's length in bytes (a suitcase font's resource fork's), when the scan read it. + pub len: u64, +} + +impl FontDb { + /// The installed faces no loaded face has the family and style of, by family name and then + /// style, as the font scan cataloged them. Reading the list reads no font file. Empty on wasm, + /// where no fonts are installed. + pub fn unloaded_installed_faces(&self) -> Vec { + #[cfg(not(target_arch = "wasm32"))] + { + // The catalog first: the first scan takes the faces' lock, which a guard held here would block. + // The bundled faces have no file to read. The catalog lists a bundled face ahead of an + // installed file of the same face, so each face's file is its first installed version. + let cataloged: Vec<(String, String, PathBuf)> = self + .catalog + .faces() + .iter() + .filter_map(|f| { + let path = + self.catalog.versions(f).into_iter().filter(|v| v.source != craft::font_catalog::Source::Bundled).find_map(|v| v.path)?; + Some((f.family.clone(), f.style.clone(), path)) + }) + .collect(); + let unloaded: Vec<(String, String, PathBuf)> = { + let loaded = self.read_faces(); + let is_loaded = + |family: &str, style: &str| loaded.iter().any(|f| f.family.eq_ignore_ascii_case(family) && f.style.eq_ignore_ascii_case(style)); + cataloged.into_iter().filter(|(family, style, _)| !is_loaded(family, style)).collect() + }; + let mut out: Vec = + unloaded.into_iter().map(|(family, style, path)| InstalledFace { family, style, len: file_len(&path), path }).collect(); + out.sort_by(|a, b| { + a.family + .to_lowercase() + .cmp(&b.family.to_lowercase()) + .then_with(|| a.style.to_lowercase().cmp(&b.style.to_lowercase())) + .then(a.path.cmp(&b.path)) + }); + out + } + #[cfg(target_arch = "wasm32")] + { + vec![] + } + } + + /// The faces in the font file at `path` (a suitcase font's in its resource fork), read for one + /// search and not added to the database, with the bytes read: no faces when the file, or the + /// fork, is longer than `max_len` bytes ([`UnloadedFile::too_long`]) or holds no font. Each face + /// read has an id of its own, which no loaded face has, and its path is `path`. Empty on wasm. + pub fn read_unloaded_file(&self, path: &Path, max_len: u64) -> UnloadedFile { + #[cfg(not(target_arch = "wasm32"))] + { + let (files, bytes) = if crate::suitcase::is_suitcase(path) { + match crate::suitcase::read_fonts_within(path, max_len) { + (_, n, true) => return UnloadedFile { bytes: n, too_long: true, ..Default::default() }, + (fonts, n, false) => (fonts, n), + } + } else { + match read_within(path, max_len) { + Some((data, n)) if n <= max_len => (vec![data], n), + Some((_, n)) => return UnloadedFile { bytes: n, too_long: true, ..Default::default() }, + None => return UnloadedFile::default(), + } + }; + let mut faces = vec![]; + for data in files { + let data = Arc::new(data); + for (i, spec) in enumerate_faces(&data) { + if let Some(f) = make_face(FontBytes::Owned(data.clone()), i, spec, Some(path.to_path_buf())) { + faces.push(Arc::new(f)); + } + } + } + UnloadedFile { faces, bytes, too_long: false } + } + #[cfg(target_arch = "wasm32")] + { + let _ = (path, max_len); + UnloadedFile::default() + } + } +} + +/// What [`FontDb::read_unloaded_file`] read from one font file. +#[derive(Default)] +pub struct UnloadedFile { + /// The faces read, not loaded. + pub faces: Vec>, + /// The bytes read from the file, those of a file longer than the limit included (at most one + /// past it). + pub bytes: u64, + /// The file, or the fork, is longer than the limit: no face was read. + pub too_long: bool, +} + +impl FontDb { + /// Load `face`, a face [`Self::read_unloaded_file`] read, without reading its file again or + /// the family's other files: it joins the loaded faces, unless a face of its family, style and + /// version is loaded already, which is returned instead. + pub fn load_read_face(&self, face: Arc) -> Arc { + let same = + |f: &FontFace| f.family.eq_ignore_ascii_case(&face.family) && f.style.eq_ignore_ascii_case(&face.style) && f.version == face.version; + let mut faces = self.faces.write().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(f) = faces.iter().find(|f| same(f)) { + return f.clone(); + } + faces.push(face.clone()); + drop(faces); + self.changed(); + face + } +} + +/// The length of the font file at `path`, or of its resource fork for a suitcase font; 0 when it +/// cannot be read. +#[cfg(not(target_arch = "wasm32"))] +fn file_len(path: &Path) -> u64 { + match std::fs::metadata(path) { + Ok(m) if m.len() == 0 => crate::suitcase::fork_len(path), + Ok(m) => m.len(), + Err(_) => 0, + } +} + +/// The file at `path`, read no further than one byte past `max_len`, with the bytes read: more than +/// `max_len` when the file is longer. None when it cannot be read. +#[cfg(not(target_arch = "wasm32"))] +fn read_within(path: &Path, max_len: u64) -> Option<(Vec, u64)> { + use std::io::Read; + let mut data = Vec::new(); + std::fs::File::open(path).ok()?.take(max_len.saturating_add(1)).read_to_end(&mut data).ok()?; + let n = data.len() as u64; + Some((data, n)) +} + +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +mod tests { + use super::*; + + /// A database whose catalog holds the bundled font files, with Inter's faces dropped from the + /// loaded ones: Inter is installed and not loaded. + fn inter_unloaded() -> FontDb { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts"); + let db = FontDb::with_font_dirs(vec![dir]); + db.faces.write().unwrap().retain(|f| f.family != "Inter"); + db + } + + #[test] + fn installed_faces_not_loaded_are_listed_and_read_without_loading_them() { + let db = inter_unloaded(); + let list = db.unloaded_installed_faces(); + let inter: Vec<&InstalledFace> = list.iter().filter(|f| f.family == "Inter").collect(); + assert!(inter.iter().any(|f| f.style == "Regular"), "{list:?}"); + // The loaded families are not listed. + assert!(!list.iter().any(|f| f.family == "Source Sans 3"), "{list:?}"); + let regular = inter.iter().find(|f| f.style == "Regular").unwrap(); + assert_eq!(regular.len, std::fs::metadata(®ular.path).unwrap().len()); + let before = db.loaded_faces().len(); + let file = db.read_unloaded_file(®ular.path, regular.len); + assert_eq!((file.bytes, file.too_long), (regular.len, false)); + let read = file.faces; + assert!(read.iter().any(|f| f.family == "Inter" && f.style == "Regular"), "the file's face is read"); + assert!(read.iter().all(|f| f.path() == Some(regular.path.as_path()))); + // Read for the search only: the database does not hold it, and no loaded face has its id. + assert_eq!(db.loaded_faces().len(), before); + assert!(read.iter().all(|f| db.face_by_id(f.id()).is_none())); + assert!(db.unloaded_installed_faces().iter().any(|f| f.family == "Inter"), "still not loaded"); + // A file longer than the limit is not read past one byte over it, and says so. + let long = db.read_unloaded_file(®ular.path, regular.len - 1); + assert!(long.faces.is_empty()); + assert_eq!((long.bytes, long.too_long), (regular.len, true)); + let missing = db.read_unloaded_file(®ular.path.with_extension("missing"), u64::MAX); + assert!(missing.faces.is_empty()); + assert_eq!((missing.bytes, missing.too_long), (0, false)); + // Once loaded, the family is no longer listed. + assert!(db.face("Inter", "Regular").is_some_and(|f| f.family == "Inter")); + assert!(!db.unloaded_installed_faces().iter().any(|f| f.family == "Inter" && f.style == "Regular")); + } +} diff --git a/crates/text/src/fontdb/lookup.rs b/crates/text/src/fontdb/lookup.rs index 67ec31a560..f1a024d020 100644 --- a/crates/text/src/fontdb/lookup.rs +++ b/crates/text/src/fontdb/lookup.rs @@ -725,7 +725,8 @@ impl FontDb { // As before, keep the prefix emitted before a malformed glyph reports an error. let _ = font.draw_to(gid, &mut pen); } - pen.0 + // An outline past MAX_OUTLINE_ELEMENTS comes back empty. + pen.finish() } /// Glyph `gid`'s colour bitmap (`sbix`, `CBDT`) in `face`, cached per (face, glyph). diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 07357a87f3..25e44392d6 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -46,10 +46,10 @@ pub use features::{ pub use file_font::{FILE_FONT_UPEM, FileFontInfo, FileGlyph, MAX_FILE_GLYPHS, build_file_font}; pub use fontdb::{ CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, GlyphAlternate, - GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, MAX_FILE_FACES, OutlineFormat, PlatformFontFiles, - RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file, - is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight, - system_font_dirs, user_font_dirs, + GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, InstalledFace, JoiningPosition, LentCompositeFonts, MAX_FILE_FACES, OutlineFormat, + PlatformFontFiles, RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, UnloadedFile, WantedFont, WantedFonts, + app_font_dir, is_font_file, is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, + set_user_font_dirs_confined, style_weight, system_font_dirs, user_font_dirs, }; pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions}; pub use layout::{envelope_ink, layout_inputs, register_envelope_ink}; diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index d7cf48e025..191e1dad87 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -217,12 +217,7 @@ impl RetypeIndex { near: &[NearKey], near_glyphs: usize, ) -> Self { - let near: Vec = near - .iter() - .copied() - .filter(|k| k.contours <= MAX_NEAR_CONTOURS && k.compact.is_finite() && k.compact > 0.0) - .take(MAX_NEAR_KEYS) - .collect(); + let near = Self::near_keys(near); let mut kept: Vec> = vec![]; for f in faces { if kept.len() >= MAX_FACES { @@ -232,6 +227,35 @@ impl RetypeIndex { kept.push(f); } } + Self::indexed_faces(db, kept, keys, &near, near_glyphs, false) + } + + /// Index the outline glyphs of `face`, a face read for one search and not loaded + /// ([`FontDb::read_unloaded_file`]), as [`Self::build_near`] indexes a loaded face's: those + /// whose [`shape_key`] is in `keys`, and for near matching those that could near match a shape + /// with one of the [`near_key`]s in `near`. The face's keys are not kept for a later search, so + /// the keys of loaded faces stay kept. Each of its encoded glyphs ([`encoded_glyphs`]) is drawn + /// once, for its key and its sampling both. + pub fn build_unloaded_near(db: &FontDb, face: Arc, keys: &BTreeSet, near: &[NearKey]) -> Self { + let near = Self::near_keys(near); + Self::indexed_faces(db, vec![face], keys, &near, MAX_NEAR_GLYPHS, true) + } + + /// [`Self::build_unloaded_near`] for exact matching only. + pub fn build_unloaded(db: &FontDb, face: Arc, keys: &BTreeSet) -> Self { + Self::build_unloaded_near(db, face, keys, &[]) + } + + /// The near keys an index looks glyphs up by: the first [`MAX_NEAR_KEYS`] of `near` that a + /// glyph can have. + fn near_keys(near: &[NearKey]) -> Vec { + near.iter().copied().filter(|k| k.contours <= MAX_NEAR_CONTOURS && k.compact.is_finite() && k.compact > 0.0).take(MAX_NEAR_KEYS).collect() + } + + /// The index of the glyphs of `kept` that [`Self::build_near_within`] takes, with `near` read + /// by [`Self::near_keys`]. With `unloaded`, the faces' keys are read for this index only and + /// not kept ([`face_keys`]), each glyph drawn once. + fn indexed_faces(db: &FontDb, kept: Vec>, keys: &BTreeSet, near: &[NearKey], near_glyphs: usize, unloaded: bool) -> Self { // Each face gets an equal share of the near checks and entries, so a face with many glyphs // (a CJK face) does not use them up before the faces after it. let share = |cap: usize| cap / kept.len().max(1); @@ -246,13 +270,20 @@ impl RetypeIndex { close.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); close.truncate(keep); }; - for &(gid, ch, key, count) in face_keys(db, face).iter() { + // A loaded face's keys are kept, and a glyph is drawn when it is sampled; an unloaded + // face's glyphs are each drawn once, for the key and the sampling both. + let kept_keys = if unloaded { None } else { Some(face_keys(db, face)) }; + let glyphs: Box + '_> = match &kept_keys { + Some(k) => Box::new(k.iter().map(|&(gid, ch, key, count)| (gid, ch, key, count, None))), + None => Box::new(drawn_keys(db, face).map(|(gid, ch, key, count, outline)| (gid, ch, key, count, Some(outline)))), + }; + for (gid, ch, key, count, drawn) in glyphs { // The budget holds inside a face too: no glyph is sampled past it. if entries.len() >= MAX_GLYPHS { break 'faces; } if keys.contains(&key) { - let outline = db.outline_uncached(face, gid); + let outline = drawn.unwrap_or_else(|| db.outline_uncached(face, gid)); if let Some(sig) = signatures(&outline, false).into_iter().next() { entries.push(Entry { face: fi, gid, ch, sig, outline, exact: true }); } @@ -263,7 +294,7 @@ impl RetypeIndex { continue; } face_checks += 1; - let outline = db.outline_uncached(face, gid); + let outline = drawn.unwrap_or_else(|| db.outline_uncached(face, gid)); let Some(g) = near_key(&outline) else { continue }; let Some(d) = near.iter().filter(|k| k.close_to(&g)).map(|k| k.apart(&g)).min_by(f64::total_cmp) else { continue }; close.push((d, gid, ch, outline)); @@ -281,6 +312,11 @@ impl RetypeIndex { } } } + Self::indexed(kept, entries) + } + + /// The index of `entries`, glyphs of `kept`. + fn indexed(kept: Vec>, entries: Vec) -> Self { let mut buckets: HashMap> = HashMap::new(); for (i, e) in entries.iter().enumerate() { buckets.entry(e.sig.contours).or_default().push(i); @@ -1037,23 +1073,7 @@ fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { return keys.clone(); } } - let mut by_gid: HashMap = HashMap::new(); - for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { - if c.is_whitespace() || c.is_control() || is_shape_symbol(c) { - continue; - } - by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); - } - let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); - gids.sort_unstable(); - let keys: FaceKeys = Arc::new( - gids.into_iter() - .filter_map(|(gid, ch)| { - let (key, count) = key_and_count(&db.outline_uncached(face, gid))?; - Some((gid, ch, key, u16::try_from(count).ok()?)) - }) - .collect(), - ); + let keys: FaceKeys = Arc::new(drawn_keys(db, face).map(|(gid, ch, key, count, _)| (gid, ch, key, count)).collect()); let mut k = kept.lock().unwrap_or_else(|e| e.into_inner()); if k.generation != generation { return keys; @@ -1069,6 +1089,42 @@ fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { keys } +/// The glyphs of `face` that are matched, under the lowest character that maps to each: its +/// encoded characters (the first [`MAX_GLYPHS_PER_FACE`]) less spaces, controls and +/// [`is_shape_symbol`]s. +fn matched_glyphs(face: &FontFace) -> Vec<(u32, char)> { + let mut by_gid: HashMap = HashMap::new(); + for &(c, gid) in face.mapped_chars().iter().take(MAX_GLYPHS_PER_FACE) { + if c.is_whitespace() || c.is_control() || is_shape_symbol(c) { + continue; + } + by_gid.entry(gid).and_modify(|e| *e = (*e).min(c)).or_insert(c); + } + let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); + gids.sort_unstable(); + gids +} + +/// How many glyphs of `face` an index draws to read their keys: the glyphs it matches, each once, +/// at most [`MAX_GLYPHS_PER_FACE`]. Reads the face's cmap only. +pub fn encoded_glyphs(face: &FontFace) -> usize { + matched_glyphs(face).len() +} + +/// A glyph with its key as [`FaceKeys`] holds it (glyph id, character, key and contour count) and +/// its outline when it was drawn already. +type KeyedGlyph = (u32, char, u64, u16, Option); + +/// The keys of `face`'s matched glyphs ([`matched_glyphs`]) as [`FaceKeys`] holds them, each glyph +/// drawn once, past the outline cache, and given with its outline. +fn drawn_keys<'a>(db: &'a FontDb, face: &'a FontFace) -> impl Iterator + 'a { + matched_glyphs(face).into_iter().filter_map(move |(gid, ch)| { + let outline = db.outline_uncached(face, gid); + let (key, count) = key_and_count(&outline)?; + Some((gid, ch, key, u16::try_from(count).ok()?, outline)) + }) +} + /// Characters whose glyphs are plain shapes (box drawing, blocks, geometric shapes, legacy /// computing symbols) or a font's own icons (private use): a drawn rectangle or circle is the same /// shape as one of them, so matching them would turn art into text. They are not matched. @@ -1534,6 +1590,20 @@ fn key_and_count(path: &BezPath) -> Option<(u64, usize)> { Some((h, cs.len())) } +/// Is `path` a plain shape: one contour of at most [`PLAIN_EDGES`] straight edges, as +/// [`contours`] reads it (a rectangle, a triangle, a bar)? Many fonts have a glyph of such a shape +/// (a hyphen, a bar, a mark), so it does not tell which font outlined text is in. `false` for an +/// empty shape or one past the size caps. +pub fn is_plain(path: &BezPath) -> bool { + match contours(path).as_deref() { + Some([c]) => c.len() <= PLAIN_EDGES && c.iter().all(|s| matches!(s, PathSeg::Line(_))), + _ => false, + } +} + +/// The most straight edges of a plain shape ([`is_plain`]). +const PLAIN_EDGES: usize = 4; + /// `path` read for matching: one reading per choice of starting corners (the corner of each contour /// farthest from the centre of all the shape's corners; every tied corner when `all_ties`, else the /// first), at most [`MAX_VARIANTS`] tried. Empty for a shape with nothing to match. @@ -2472,4 +2542,53 @@ mod tests { index.matches(&shape).iter().map(|m| m.face.id()).collect::>() ); } + + #[test] + fn plain_shapes_are_one_contour_of_up_to_four_straight_edges() { + let rect = kurbo::Rect::new(0.0, 0.0, 80.0, 40.0).to_path(0.1); + assert!(is_plain(&rect)); + let mut triangle = BezPath::new(); + triangle.move_to((0.0, 0.0)); + triangle.line_to((50.0, 0.0)); + // A straight edge split in two reads as one. + triangle.line_to((50.0, 20.0)); + triangle.line_to((50.0, 40.0)); + triangle.close_path(); + assert!(is_plain(&triangle)); + let mut pentagon = BezPath::new(); + pentagon.move_to((0.0, 0.0)); + for p in [(40.0, 0.0), (50.0, 30.0), (20.0, 50.0), (-10.0, 30.0)] { + pentagon.line_to(p); + } + pentagon.close_path(); + assert!(!is_plain(&pentagon)); + assert!(!is_plain(&kurbo::Circle::new((0.0, 0.0), 10.0).to_path(0.1)), "curves"); + assert!(!is_plain(&letter()), "two contours"); + assert!(!is_plain(&BezPath::new())); + } + + /// A face read from an installed file and not loaded is indexed as a loaded one is, and the + /// count of glyphs its index draws comes from its cmap: the glyphs it matches, each once. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_unloaded_face_is_indexed_as_a_loaded_one() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts"); + let db = FontDb::with_font_dirs(vec![]); + let loaded = db.face("Source Sans 3", "Regular").unwrap(); + let read = db.read_unloaded_file(&dir.join("SourceSans3-Regular.ttf"), u64::MAX).faces; + let face = read.into_iter().find(|f| f.family == "Source Sans 3").unwrap(); + assert_ne!(face.id(), loaded.id()); + assert_eq!(encoded_glyphs(&face), matched_glyphs(&face).len()); + // Spaces, controls and shape symbols are not drawn, nor one glyph twice for two characters. + assert!(encoded_glyphs(&face) < face.mapped_chars().len().min(MAX_GLYPHS_PER_FACE)); + let shape = Affine::translate((40.0, 90.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('g')); + let keys: BTreeSet = std::iter::once(shape_key(&shape).unwrap()).collect(); + let unloaded = RetypeIndex::build_unloaded(&db, face.clone(), &keys); + let built = RetypeIndex::build(&db, [loaded.clone()], &keys); + assert_eq!(unloaded.len(), built.len()); + let (a, b) = (unloaded.matches(&shape), built.matches(&shape)); + assert_eq!(a.first().map(|m| (m.face.id(), m.ch)), Some((face.id(), 'g'))); + assert_eq!(b.first().map(|m| m.ch), Some('g')); + assert!(a.first().unwrap().origin.distance(b.first().unwrap().origin) < 1e-9); + } } diff --git a/crates/text/src/suitcase.rs b/crates/text/src/suitcase.rs index ff06a66672..102492b252 100644 --- a/crates/text/src/suitcase.rs +++ b/crates/text/src/suitcase.rs @@ -65,6 +65,19 @@ pub(crate) fn read_fonts(path: &Path) -> Vec> { sfnt_resources(&fork).into_iter().map(<[u8]>::to_vec).collect() } +/// [`read_fonts`] reading the fork no further than one byte past `max_len` (at most the longest +/// fork read), with the bytes read: no fonts, and true, when the fork is longer. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_fonts_within(path: &Path, max_len: u64) -> (Vec>, u64, bool) { + let max_len = max_len.min(MAX_FORK); + let Some(fork) = read_fork_within(path, max_len.saturating_add(1)) else { return (vec![], 0, false) }; + let n = fork.len() as u64; + if n > max_len { + return (vec![], n, true); + } + (sfnt_resources(&fork).into_iter().map(<[u8]>::to_vec).collect(), n, false) +} + /// Whether the file at `path` is a suitcase font: nothing in its data fork and something in its /// resource fork. pub(crate) fn is_suitcase(path: &Path) -> bool { @@ -84,9 +97,15 @@ pub(crate) fn fork_len(path: &Path) -> u64 { #[cfg(target_os = "macos")] fn read_fork(path: &Path) -> Option> { + read_fork_within(path, MAX_FORK) +} + +/// The first `max` bytes of the resource fork of the file at `path`. +#[cfg(target_os = "macos")] +fn read_fork_within(path: &Path, max: u64) -> Option> { use std::io::Read; let mut fork = Vec::new(); - std::fs::File::open(fork_path(path)).ok()?.take(MAX_FORK).read_to_end(&mut fork).ok()?; + std::fs::File::open(fork_path(path)).ok()?.take(max).read_to_end(&mut fork).ok()?; Some(fork) } @@ -101,6 +120,11 @@ fn read_fork(_: &Path) -> Option> { None } +#[cfg(all(not(target_os = "macos"), not(target_arch = "wasm32")))] +fn read_fork_within(_: &Path, _: u64) -> Option> { + None +} + /// A resource fork holding `fonts` as `sfnt` resources and one other resource (a `vers`), as /// a font utility writes them. #[cfg(test)] diff --git a/crates/text/src/tests/colr.rs b/crates/text/src/tests/colr.rs index e59fb390c9..cd71fbae1c 100644 --- a/crates/text/src/tests/colr.rs +++ b/crates/text/src/tests/colr.rs @@ -714,3 +714,25 @@ fn a_colour_glyph_on_a_path_turns_with_it() { assert!((b.width() - upright.height()).abs() < 1.0 && (b.height() - upright.width()).abs() < 1.0, "on its side: {b:?}"); assert!(b.y0 >= -1.0 && b.y1 <= 400.0, "along the path: {b:?}"); } + +/// A layer list that reuses one run of layers many times grows the tree past its node cap: the +/// glyph is then no colour glyph (it draws its outline), and the layers after the cap are not drawn. +#[test] +fn layers_repeating_a_run_of_layers_pass_the_cap() { + use write_fonts::tables::colr::{BaseGlyphList, BaseGlyphPaint, Colr, LayerList}; + use write_fonts::types::GlyphId16; + let bytes = colr_font(false).unwrap(); + let o = skrifa::FontRef::new(&bytes).unwrap().charmap().map(COLOUR_CHAR).unwrap().to_u32(); + let o = GlyphId16::new(u16::try_from(o).unwrap()); + let font = |runs: u8| { + // 255 glyph layers, then `runs` layers that each repeat all of them. + let mut layers: Vec = (0..255).map(|_| ColrPaint::glyph(solid(0), o)).collect(); + layers.extend((0..runs).map(|_| ColrPaint::colr_layers(255, 0))); + let mut colr = Colr::new(0, None, None, 0); + colr.base_glyph_list = Some(BaseGlyphList::new(1, vec![BaseGlyphPaint::new(o, ColrPaint::colr_layers(runs, 255))])).into(); + colr.layer_list = Some(LayerList::new(layers.len() as u32, layers)).into(); + crate::test_fonts::colr_font_with(&format!("Colrtest Runs {runs}"), &colr).unwrap() + }; + assert!(matches!(content(&font(2), COLOUR_CHAR), Some(ColourContent::Art(_))), "510 layers fit"); + assert!(content(&font(100), COLOUR_CHAR).is_none(), "25,500 layers do not"); +} diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index c469b48ead..44da64b495 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -997,6 +997,26 @@ fn a_search_reads_a_suitcase_font_only_within_its_share() { let _ = std::fs::remove_dir_all(&dir); } +/// A suitcase font read for one search (Retype) is read no further than one byte past the limit, +/// and the bytes read are counted. +#[cfg(target_os = "macos")] +#[test] +fn a_suitcase_font_read_for_a_search_counts_the_bytes_of_its_fork() { + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-unloaded-suitcase", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let suitcase = dir.join("Sysfont Sans3"); + std::fs::write(&suitcase, b"").unwrap(); + let fork = crate::suitcase::fork_of(&[renamed("SourceSans3-Regular.ttf")]); + let len = fork.len() as u64; + std::fs::write(suitcase.join("..namedfork/rsrc"), &fork).unwrap(); + let db = FontDb::with_font_dirs(vec![]); + let file = db.read_unloaded_file(&suitcase, len); + assert_eq!((file.faces.len(), file.bytes, file.too_long), (1, len, false)); + let long = db.read_unloaded_file(&suitcase, len - 1); + assert_eq!((long.faces.len(), long.bytes, long.too_long), (0, len, true)); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn font_files_are_told_by_their_extension() { for name in ["a/B.TTF", "c.otf", "d.Ttc", "e.otc"] { diff --git a/crates/three-d/src/fold.rs b/crates/three-d/src/fold.rs index 1bfb46f93b..14bc32fa6d 100644 --- a/crates/three-d/src/fold.rs +++ b/crates/three-d/src/fold.rs @@ -46,12 +46,31 @@ impl LineKind { } } -/// A fold line: the path (document coordinates), its kind, and a key the issues name it by. +/// A fold line: the path (document coordinates), its kind, a key the issues name it by, and its +/// own fold angle (degrees), which a line that folds takes instead of its kind's. #[derive(Clone, Debug)] pub struct FoldLine { pub path: PathData, pub kind: LineKind, pub key: u64, + pub angle: Option, +} + +/// `angle` (degrees) to the whole millionth of a degree, the finest fold angle a line keeps. A fold +/// that close to flat is flat: the preview tells panels in one plane from panels a millionth of a +/// degree apart, but not from panels closer than that. +pub fn kept_angle(angle: f64) -> f64 { + (angle * 1e6).round() / 1e6 + 0.0 +} + +impl FoldLine { + /// The angle (degrees) the line folds at: its own angle when it has one from -180 to 180, to the + /// millionth of a degree ([`kept_angle`]), else its kind's ([`LineKind::fold_angle`]); none for + /// a Cut, whatever its own angle. + pub fn fold_angle(&self) -> Option { + let own = self.angle.filter(|a| (-180.0..=180.0).contains(a)).map(kept_angle); + self.kind.fold_angle().map(|default| own.unwrap_or(default)) + } } /// One blank: its panels, the hinges between them, and its holes. @@ -79,14 +98,17 @@ impl Panel { /// The hinge between panels `a` and `b` (indices into the blank's panels, `a` < `b`): the straight /// line from `from` to `to`, made of the lines `keys`. `straight` is false when its pieces are not on /// one straight line within the tolerance; `from` and `to` are then on the line through its longest -/// piece. `angle` (degrees) is the fold angle of the kind of line its longest piece is -/// ([`LineKind::fold_angle`]). +/// piece. `angle` (degrees) is the fold angle ([`FoldLine::fold_angle`]) of the line with the most +/// length in the hinge, the one with the lowest key among lines of equal length. `on` is the middle +/// of its longest piece, a point where the two panels meet, which a hinge with gaps between its +/// pieces may not have at the middle of `from` to `to`. #[derive(Clone, Debug)] pub struct Hinge { pub a: usize, pub b: usize, pub from: Point, pub to: Point, + pub on: Point, pub keys: Vec, pub straight: bool, pub angle: f64, @@ -1297,9 +1319,34 @@ impl Context<'_> { let sp = p.path.subpaths.first()?; Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) }; - let ((p0, p1), longest) = + let ((p0, p1), _) = group.iter().filter_map(|p| Some((chord(p)?, p))).max_by(|(x, _), (y, _)| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; - let angle = longest.lines.iter().filter_map(|&l| self.lines.get(l)?.kind.fold_angle()).next().unwrap_or(90.0); + let lengths: Vec = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::()).collect(); + // The angle of the line with the most length in the hinge, the one with the lowest key on a + // tie: a line the planar map split into several pieces counts whole. + let mut by_line: HashMap = HashMap::new(); + for (p, len) in group.iter().zip(&lengths) { + // Subpaths of one line on top of each other count once. + let mut lines = p.lines.clone(); + lines.sort_unstable(); + lines.dedup(); + for l in lines { + *by_line.entry(l).or_default() += len; + } + } + let folding: Vec<(f64, f64, u64)> = by_line + .iter() + .filter_map(|(&l, &len)| { + let line = self.lines.get(l)?; + Some((line.fold_angle()?, len, line.key)) + }) + .collect(); + // Lengths summed from pieces in another order differ in their last bits: a few epsilons per + // piece, and no more, so a line measurably longer still wins. + let most = folding.iter().map(|f| f.1).fold(0.0, f64::max); + let pieces = f64::from(u32::try_from(group.len()).unwrap_or(u32::MAX)); + let rounding = 8.0 * f64::EPSILON * (pieces + 1.0) * most; + let angle = folding.iter().filter(|f| f.1 >= most - rounding).min_by_key(|f| f.2).map_or(90.0, |f| f.0); let len = p0.distance(p1); // The longest piece only sets the direction; the length check is on the whole hinge below. if len.is_nan() || len <= 1e-9 { @@ -1321,7 +1368,7 @@ impl Context<'_> { } // The pieces' own length, not the span from the first to the last, which takes in the gaps // between pieces that lie apart. - let length: f64 = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::()).sum(); + let length: f64 = lengths.iter().sum(); if !(lo.is_finite() && hi.is_finite()) || hi - lo < self.tolerance || length.is_nan() || length < self.tolerance { return None; } @@ -1331,7 +1378,7 @@ impl Context<'_> { let mut keys = self.keys(lines); keys.sort_unstable(); keys.dedup(); - Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight, angle }) + Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, on: p0.midpoint(p1), keys, straight, angle }) } /// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a @@ -1465,7 +1512,7 @@ pub fn base_panel(panels: &[Panel]) -> Option { mod pose; pub mod raster; -pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, fold, panel_at, pick, polygon}; +pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, Stack, fold, panel_at, pick, polygon}; #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/pose.rs b/crates/three-d/src/fold/pose.rs index 650ab54291..91a6cdfb12 100644 --- a/crates/three-d/src/fold/pose.rs +++ b/crates/three-d/src/fold/pose.rs @@ -19,6 +19,11 @@ use super::{Blank, base_panel, point_in}; /// test and the preview. pub const MAX_POLYGON_POINTS: usize = 1 << 16; +/// How far apart two placements of a panel may turn a unit direction and still be one placement: +/// above the rounding of up to [`super::MAX_PANELS`] turns, below the turn of a hinge a millionth +/// of a degree from another ([`super::kept_angle`], 1.7e-8). +const TURNED: f64 = 1e-10; + type V3 = [f64; 3]; fn sub(a: V3, b: V3) -> V3 { @@ -105,14 +110,24 @@ impl Pose { let r_at = [dot(r[0], at), dot(r[1], at), dot(r[2], at)]; Pose { m, t: add(self.turn(sub(at, r_at)), self.t) } } + + /// This pose, taken about `origin` (a point less `origin` to its place less `origin`), in the + /// flat blank's own terms. + fn about(&self, origin: V3) -> Pose { + Pose { m: self.m, t: add(sub(self.t, self.turn(origin)), origin) } + } } -/// A folded panel: where it is, its parent in the fold tree (`None` for the base and for a panel no -/// chain of hinges joins to it, which stays flat where it is) and how many hinges lie between it -/// and the base. +/// A folded panel: where it is, the same about [`Folded::origin`] (`local`), its parent in the fold +/// tree (`None` for the base and for a panel no chain of hinges joins to it, which stays flat where +/// it is) and how many hinges lie between it and the base. #[derive(Clone, Debug)] pub struct FoldedPanel { pub pose: Pose, + /// Where the panel is with the flat blank moved so `origin` is at 0: it takes a flat point less + /// `origin` to its place less `origin`. Worked out in these terms, it keeps the rounding of a + /// blank far from the document's origin to the size of the blank. + pub local: Pose, pub parent: Option, pub depth: usize, } @@ -141,6 +156,28 @@ pub struct Folded { pub hinges: Vec, /// Pairs of panels (`a` < `b`) that pass through each other. pub collisions: Vec<(usize, usize)>, + /// The fold tree that panels folded flat onto each other stack by. + pub stack: Stack, + /// The middle of the blank's bounds (flat, see [`flat`]), which [`FoldedPanel::local`] is about. + pub origin: [f64; 3], +} + +/// The fold tree that panels in one plane stack by: the tree from the blank's largest panel (its +/// `root`), whichever panel is the base, so choosing another base moves the folded blank without +/// changing which panel shows where they lie flat on each other. The base's own tree when the two +/// join different panels. +#[derive(Clone, Debug, Default)] +pub struct Stack { + pub root: usize, + /// Each panel's parent in this tree. + pub parent: Vec>, + /// The panels in breadth-first order from `root`, the panels not joined to it last. + pub order: Vec, + /// For each panel, the way from the hinge it is folded on into its parent, as folded: a vector + /// in the parent's plane, across the hinge to the side the fold took the parent to be on, as + /// long as the corners of the parent's bounds reach that way. `None` for `root` and the + /// panels not joined to it. + pub toward_parent: Vec>, } /// The panel of `blank` that `p` (document coordinates) lies in. @@ -204,10 +241,25 @@ pub fn fold(blank: &Blank, base: Option, amount: f64, tolerance: f64) -> }); } let centers: Vec> = blank.panels.iter().map(|p| point_in(&p.outline).map(flat)).collect(); - let (panels, tree, order) = place(blank, &by_panel, ¢ers, base, amount); + // The corners of each panel's bounds (flat). + let corners: Vec> = blank + .panels + .iter() + .map(|p| p.outline.bounds().map(|b| [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1)].map(|(x, y)| flat(Point::new(x, y))))) + .collect(); + let origin = corners + .iter() + .flatten() + .flatten() + .fold(None, |b: Option<(V3, V3)>, c| { + Some(b.map_or((*c, *c), |(lo, hi)| ([lo[0].min(c[0]), lo[1].min(c[1]), 0.0], [hi[0].max(c[0]), hi[1].max(c[1]), 0.0]))) + }) + .map_or([0.0; 3], |(lo, hi)| scale(add(lo, hi), 0.5)); + let placing = Placing { blank, by_panel: &by_panel, centers: ¢ers, corners: &corners, origin }; + let (panels, tree, order, toward_parent) = place(&placing, base, amount); // Closing hinges are measured with every hinge at its full angle, so a blank that closes when // folded is not reported open part of the way there. - let full = if amount == 1.0 { None } else { Some(place(blank, &by_panel, ¢ers, base, 1.0).0) }; + let full = if amount == 1.0 { None } else { Some(place(&placing, base, 1.0).0) }; let measured = full.as_deref().unwrap_or(&panels); let hinges = blank .hinges @@ -224,15 +276,64 @@ pub fn fold(blank: &Blank, base: Option, amount: f64, tolerance: f64) -> }) .collect(); let collisions = collisions(blank, &panels, tolerance); - Some(Folded { base, panels, order, hinges, collisions }) + let own = Stack { root: base, parent: panels.iter().map(|p| p.parent).collect(), order: order.clone(), toward_parent }; + let stack = match base_panel(&blank.panels) { + Some(root) if root != base => { + let (placed, root_tree, root_order, toward) = place(&placing, root, amount); + // Whether the root's tree puts every panel where the base's does, moved with the root + // (which lies at the identity in its own): the same hinges do, and around a loop of + // panels another tree can leave out a fold that placed them. Each panel's turn is + // compared to within `TURNED` whatever its size or place, and its inside point by the + // poses about `origin` (`local`), to rounding at that distance from it. + let agrees = |r: &FoldedPanel| { + let near = |a: V3, b: V3| length(sub(a, b)) <= 1e-9 * (1.0 + length(a).max(length(b))); + placed.iter().zip(&panels).enumerate().all(|(i, (p, q))| { + let joined = (i == root || p.parent.is_some(), i == base || q.parent.is_some()); + let at = centers.get(i).copied().flatten().map_or([0.0; 3], |c| sub(c, origin)); + let turned = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] + .into_iter() + .all(|e| length(sub(r.local.turn(p.local.turn(e)), q.local.turn(e))) <= TURNED); + joined.0 == joined.1 && (!joined.0 || (turned && near(r.local.apply(p.local.apply(at)), q.local.apply(at)))) + }) + }; + match panels.get(root) { + // The root's tree in the base's terms. + Some(r) if root_tree == tree || agrees(r) => Stack { + root, + parent: placed.iter().map(|p| p.parent).collect(), + order: root_order, + toward_parent: toward.into_iter().map(|v| v.map(|v| r.pose.turn(v))).collect(), + }, + _ => own, + } + } + _ => own, + }; + Some(Folded { base, panels, order, hinges, collisions, stack, origin }) } -/// The panels of `blank` placed by the fold tree from `base` with each hinge at `amount` of its -/// angle, which hinges are in the tree, and the panels in breadth-first order (the panels not -/// joined to the base last). -fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: usize, amount: f64) -> (Vec, Vec, Vec) { +/// What [`place`] gives: the placed panels, which hinges are in the tree, the panels' order and +/// [`Stack::toward_parent`]. +type Tree = (Vec, Vec, Vec, Vec>); + +/// What [`place`] places: the blank, each panel's hinges in order, each panel's inside point and +/// bounds corners (flat), and the point the panels' local poses are about. +struct Placing<'a> { + blank: &'a Blank, + by_panel: &'a [Vec], + centers: &'a [Option], + corners: &'a [Option<[V3; 4]>], + origin: V3, +} + +/// The panels of the blank placed by the fold tree from `base` with each hinge at `amount` of its +/// angle, which hinges are in the tree, the panels in breadth-first order (the panels not joined +/// to the base last), and [`Stack::toward_parent`]. +fn place(placing: &Placing, base: usize, amount: f64) -> Tree { + let Placing { blank, by_panel, centers, corners, origin } = *placing; let n = blank.panels.len(); - let mut panels: Vec = vec![FoldedPanel { pose: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut panels: Vec = vec![FoldedPanel { pose: Pose::IDENTITY, local: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut toward_parent: Vec> = vec![None; n]; let mut reached = vec![false; n]; let mut tree = vec![false; blank.hinges.len()]; let mut order = Vec::with_capacity(n); @@ -257,7 +358,7 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u // The parent on the left of the hinge's direction, the child on its right. The side is // read next to the hinge, so a parent with a notch or an arm past the hinge's line still // turns the child the right way; the panel's inside point is the fallback. - let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len)) { + let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len, flat(h.on))) { Some(left) => left, None => centers.get(p).copied().flatten().is_none_or(|c| cross(sub(to, from), sub(c, from))[2] >= 0.0), }; @@ -270,7 +371,15 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u continue; } if let Some(slot) = panels.get_mut(child) { - *slot = FoldedPanel { pose: parent.pose.turned_about(from, axis, theta), parent: Some(p), depth: parent.depth + 1 }; + let local = parent.local.turned_about(sub(from, origin), axis, theta); + *slot = FoldedPanel { pose: local.about(origin), local, parent: Some(p), depth: parent.depth + 1 }; + } + // Across the hinge, to its left: into the parent, as far as the corners of its bounds + // reach that way. + let into = [-axis[1], axis[0], 0.0]; + let reach = corners.get(p).copied().flatten().map_or(0.0, |c| c.into_iter().map(|c| dot(sub(c, from), into)).fold(0.0, f64::max)); + if let Some(slot) = toward_parent.get_mut(child) { + *slot = Some(parent.pose.turn(scale(into, reach))); } if let Some(r) = reached.get_mut(child) { *r = true; @@ -282,23 +391,27 @@ fn place(blank: &Blank, by_panel: &[Vec], centers: &[Option], base: u } } order.extend((0..n).filter(|&i| reached.get(i) == Some(&false))); - (panels, tree, order) + (panels, tree, order, toward_parent) } /// Whether `outline` lies on the left of the line from `from` to `to` (flat coordinates, `len` apart) -/// next to its middle: `Some(true)` when a point just off the middle on the left is inside it and -/// the matching point on the right is not, `Some(false)` the other way round, `None` when no offset -/// tells them apart. The nearest offset is tried first. -fn side_of(outline: &PathData, from: V3, to: V3, len: f64) -> Option { +/// next to it: `true` when a point just off the line on the left is inside it and the matching +/// point on the right is not, `false` the other way round. `on` (a point of the line where the +/// panels meet: [`super::Hinge::on`]) is tried first, then the middle and points a quarter and an +/// eighth of the way along, each with the nearest offset first; `None` when no point tells the +/// sides apart. +fn side_of(outline: &PathData, from: V3, to: V3, len: f64, on: V3) -> Option { let bp = outline.to_bezpath(); - let mid = scale(add(from, to), 0.5); let left = [-(to[1] - from[1]) / len, (to[0] - from[0]) / len, 0.0]; let doc = |v: V3| Point::new(v[0], -v[1]); let mut offsets = [1e-3, 0.25, len * 0.01]; offsets.sort_by(f64::total_cmp); - offsets.into_iter().find_map(|off| { - let (l, r) = (bp.winding(doc(add(mid, scale(left, off)))) != 0, bp.winding(doc(sub(mid, scale(left, off)))) != 0); - (l != r).then_some(l) + let along = [0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875].map(|t| add(from, scale(sub(to, from), t))); + std::iter::once(on).chain(along).find_map(|at| { + offsets.into_iter().find_map(|off| { + let (l, r) = (bp.winding(doc(add(at, scale(left, off)))) != 0, bp.winding(doc(sub(at, scale(left, off)))) != 0); + (l != r).then_some(l) + }) }) } diff --git a/crates/three-d/src/fold/raster.rs b/crates/three-d/src/fold/raster.rs index 9cccbaf6d9..4db9cd728f 100644 --- a/crates/three-d/src/fold/raster.rs +++ b/crates/three-d/src/fold/raster.rs @@ -16,8 +16,18 @@ pub const MAX_SIDE: u32 = 4096; pub const MAX_PIXELS: u32 = 1 << 21; /// The share of the eye's distance a panel is cut at in front of the eye. const NEAREST: f64 = 1e-3; -/// How far apart (points of view depth) two panels may be and still tie. +/// How far apart (points of view depth) two panels in one plane may be and still tie. const TIE: f64 = 1e-4; +/// How far apart (the sine of the angle) two panels' normals may be for the panels to lie in one +/// plane. +const PARALLEL: f64 = 1e-9; +/// How far apart two parallel panels' planes may be for the panels to lie in one plane: rounding, +/// as this many times the precision of a number at their distance from the origin for each hinge +/// that placed them. +const COPLANAR: f64 = 16.0 * f64::EPSILON; +/// How far across a panel's plane (the cosine to its normal) a fold's step may go and still count +/// as along it. +const ALONG: f64 = 1e-6; /// The light's direction: above, to the left of and toward the viewer. const LIGHT: [f64; 3] = [-0.37, 0.56, 0.74]; @@ -278,11 +288,11 @@ fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> { inv.iter().flatten().all(|v| v.is_finite()).then_some(inv) } -fn map_panel(camera: &Camera, f: &super::FoldedPanel) -> Option { +fn map_panel(camera: &Camera, pose: &super::Pose) -> Option { let r = camera.rotation(); - let turn = |v: V3| mul(&r, f.pose.turn(v)); + let turn = |v: V3| mul(&r, pose.turn(v)); let (a, b) = (turn([1.0, 0.0, 0.0]), turn([0.0, 1.0, 0.0])); - let o = camera.to_view(f.pose.t); + let o = camera.to_view(pose.t); let (cx, cy) = (f64::from(camera.width) / 2.0 + camera.pan[0], f64::from(camera.height) / 2.0 + camera.pan[1]); let normal = turn([0.0, 0.0, 1.0]); let (w, k, printed) = match camera.eye() { @@ -326,18 +336,23 @@ struct Target { panel: Vec, } -/// One panel's fill: its map, rank (for ties), panel number and colors. +/// One panel's fill: its map, rank and plane (for ties: the plane of every panel by its index, as +/// [`planes`] gives them), panel number and colors. struct Fill<'a> { mapped: &'a Mapped, rank: u16, + planes: &'a [u16], panel: u16, print: Option<&'a Print>, + /// The flat point the map is about ([`Folded::origin`]): a flat point less it is what + /// `mapped` maps. + origin: [f64; 2], inside: [f32; 4], outside: [f32; 4], } impl Fill<'_> { - /// The document point under pixel center `(x, y)`, or `None` behind the eye. + /// The flat point (less [`Fill::origin`]) under pixel center `(x, y)`, or `None` behind the eye. fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> { let [u, v, w] = mul(&self.mapped.inverse, [x, y, 1.0]); (w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite()) @@ -346,7 +361,7 @@ impl Fill<'_> { /// The color of the panel at flat point `(u, v)`, `footprint` points across a pixel. fn color(&self, u: f64, v: f64, footprint: f64) -> [f32; 4] { let base = if self.mapped.printed { - let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u, -v), footprint)); + let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u + self.origin[0], -(v + self.origin[1])), footprint)); let under = 1.0 - p[3] / 255.0; [p[0] + self.outside[0] * under, p[1] + self.outside[1] * under, p[2] + self.outside[2] * under, 255.0] } else { @@ -370,8 +385,12 @@ impl Fill<'_> { let [a, b, c] = self.mapped.depth; let z = u * a + v * b + c; let i = row * target.width + col; - let (Some(&zb), Some(&rb)) = (target.depth.get(i), target.rank.get(i)) else { continue }; - let wins = z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb); + let (Some(&zb), Some(&rb), Some(&pb)) = (target.depth.get(i), target.rank.get(i), target.panel.get(i)) else { continue }; + // Panels in one plane tie within `TIE` and stack by rank; panels in different planes + // that pass this close go by depth alone. Panel numbers count from 1. + let plane = |p: u16| usize::from(p).checked_sub(1).and_then(|p| self.planes.get(p)); + let one_plane = plane(self.panel).is_some_and(|a| plane(pb) == Some(a)); + let wins = if one_plane { z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb) } else { z > zb }; if !wins { continue; } @@ -442,6 +461,161 @@ fn flat_rings(panel: &Panel, scale: f64) -> Option>> { Some(polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| [p.x, -p.y]).collect()).collect()) } +/// The rank (from 1) each panel of `folded.order` takes in a depth tie, the higher one drawn. Each +/// fold puts a panel in a layer next to its parent in [`Folded::stack`]: behind the parent's printed +/// side for a positive angle, in front of it for a negative one, level with it for 0°. Layers are +/// compared fold by fold from the stack's root (the largest panel, whichever panel is the base), so +/// a panel folded back over its parent's parent lands between the two at any depth. A tie, between +/// panels in one plane, goes to the panel whose layer is nearer the viewer across that plane (the +/// side of the plane `camera` sees). Two folds into one layer stack by the stack's order, the later +/// one nearer seen from one side of their plane and the earlier one seen +/// from the other, and the panels folded on from each stay with it. Two panels folded flat onto each other +/// (±180°) tie in depth everywhere they overlap. A panel that comes back onto the plane of a panel +/// it branched from, after leaving it, takes the side of that plane it came back from for every +/// step up to the one it left by: the side the nearest panel out of the plane lies on from the +/// hinge it joins the plane at ([`super::Stack::toward_parent`]). `planes` gives each panel's plane, as +/// [`planes`] does. +fn tie_ranks(folded: &Folded, camera: &Camera, planes: &[u16]) -> Vec { + let n = folded.panels.len(); + // Each panel's layer holds a step per fold up to the base: past the panels a blank can have, + // the order alone decides. So it does when every panel lies where it lies flat (a fold amount + // of 0), as panels there do not overlap. + if n > super::MAX_PANELS || folded.order.len() > super::MAX_PANELS || folded.panels.iter().all(|f| f.pose == super::Pose::IDENTITY) { + return (1..=folded.order.len()).map(|r| u16::try_from(r).unwrap_or(u16::MAX)).collect(); + } + // The step each panel takes off its parent: the parent's printed side, negated for a positive + // angle; none for a 0° hinge or a panel without a parent. + // The parents are those of [`Folded::stack`], so the panels stack the same about any base. + let stack = &folded.stack; + let parent_of = |c: usize| stack.parent.get(c).copied().flatten(); + let mut step: Vec> = vec![None; n]; + for c in 0..n { + let Some(p) = parent_of(c) else { continue }; + let Some(h) = folded.hinges.iter().find(|h| (h.a, h.b) == (p, c) || (h.a, h.b) == (c, p)) else { continue }; + let (Some(parent), Some(slot)) = (folded.panels.get(p), step.get_mut(c)) else { continue }; + let [x, y, z] = parent.pose.normal(); + *slot = match h.angle { + a if a > 0.0 => Some([-x, -y, -z]), + a if a < 0.0 => Some([x, y, z]), + _ => None, + }; + } + // Each panel's layer, from the base out: +1 for a step toward the viewer across the panel's + // plane, -1 for one away from it, 0 for one along it. Comparing these in order puts a panel next + // to its parent, before any later step, however many folds deep. + // Each panel's place in the stack's order. + let mut place = vec![0usize; n]; + for (i, &pi) in stack.order.iter().enumerate() { + if let Some(slot) = place.get_mut(pi) { + *slot = i; + } + } + // Each step also carries the place in `folded.order` of the panel that took it, so panels whose + // steps match up to a fold that branches stack by that branch: the later panel nearer seen from + // one side of their plane, the earlier one seen from the other, so the two sides show opposite + // panels. The rest of a branch stays with it. + // Whether the view sees each panel's printed side. + let sees_print: Vec = folded.panels.iter().map(|f| map_panel(camera, &f.pose).is_none_or(|m| m.printed)).collect(); + // The nearest panel out of `pi`'s plane on its way to the base, and the side of that plane it + // lies on from the hinge it joins the panels in the plane at: 1 the side `n_view` points to, -1 + // the other; `None` when every panel on the way lies in the plane. The plane is the one + // [`planes`] gives, the same that decides which panels tie, so a ramp however shallow leaves it + // and a stack folded a hair short of flat goes by depth instead. + let approach = |pi: usize, n_view: V3| -> Option<(usize, i8)> { + let (mut child, mut up) = (pi, parent_of(pi)); + for _ in 0..n { + let c = up?; + if planes.get(c) != planes.get(pi) + && let Some(Some(way)) = stack.toward_parent.get(child) + { + let d = dot(*way, n_view); + if d != 0.0 { + return Some((c, if d > 0.0 { 1 } else { -1 })); + } + } + (child, up) = (c, parent_of(c)); + } + None + }; + let layer = |pi: usize| -> Vec<(i8, i64)> { + let Some(f) = folded.panels.get(pi) else { return vec![] }; + let printed = sees_print.get(pi).copied().unwrap_or(true); + let n_view = { + let [x, y, z] = f.pose.normal(); + if printed { [x, y, z] } else { [-x, -y, -z] } + }; + let mut out = vec![]; + let mut at = Some(pi); + // From the nearest panel out of the plane on the way to the base, every step counts as on + // the side of the plane that panel lies on: a panel that comes round onto the plane of a + // panel it branched from lies on the side it came back from, whatever its folds before. + let (back_at, back_side) = approach(pi, n_view).map_or((None, 0), |(c, s)| (Some(c), s)); + let mut returned = false; + // A panel's chain to the base is at most the panel count long. + for _ in 0..n { + let Some(c) = at else { break }; + returned |= Some(c) == back_at; + if let Some(Some(s)) = step.get(c) { + let d = if returned { f64::from(back_side) } else { dot(*s, n_view) }; + // Branches off one panel stack one way seen from that panel's printed side and the + // other way from its back, so the panels of one plane that compare a step off one + // parent agree, however the parent is turned. + let branch = place.get(c).map_or(i64::MAX, |&p| i64::try_from(p).unwrap_or(i64::MAX)); + // A parent seen edge on gives no side: the panel that took the step gives it, and + // when that is edge on too, the largest part of the view's normal does. Each choice + // gives two panels of one plane the same sign however an edge-on dot rounds, and + // each turns over with the side of the plane the view is on. + let faces = |f: &super::FoldedPanel| { + let d = dot(f.pose.normal(), n_view); + (d.abs() > ALONG).then_some(d >= 0.0) + }; + // The view's normal in the root's flat terms, so this too is the same about any base. + let largest = || { + let m = folded.panels.get(stack.root).map_or(super::Pose::IDENTITY.m, |r| r.pose.m); + let local = [0, 1, 2].map(|j| (0..3).map(|i| m[i][j] * n_view[i]).sum::()); + local.into_iter().max_by(|a, b| a.abs().total_cmp(&b.abs())).is_none_or(|v| v >= 0.0) + }; + let parent = parent_of(c).and_then(|p| folded.panels.get(p)); + let parent_faces = parent.map_or(Some(true), faces).or_else(|| folded.panels.get(c).and_then(faces)).unwrap_or_else(largest); + let branch = if parent_faces { branch } else { -branch }; + // Any step that is not along the plane counts whole, so a step seen from two panels + // of one plane counts the same for both. + out.push((i8::from(d > ALONG) - i8::from(d < -ALONG), branch)); + } + at = parent_of(c); + } + out.reverse(); + out + }; + // Layers compared step by step, a missing step as none. + let compare = |a: &[(i8, i64)], b: &[(i8, i64)]| { + (0..a.len().max(b.len())) + .map(|k| a.get(k).copied().unwrap_or((0, 0)).cmp(&b.get(k).copied().unwrap_or((0, 0)))) + .find(|o| o.is_ne()) + .unwrap_or(std::cmp::Ordering::Equal) + }; + // A panel alone in its plane ties with no other, so its layer is not worked out. + let mut in_plane = vec![0usize; planes.iter().map(|&p| usize::from(p) + 1).max().unwrap_or(0)]; + for &p in planes { + if let Some(c) = in_plane.get_mut(usize::from(p)) { + *c += 1; + } + } + let alone = |pi: usize| planes.get(pi).and_then(|&p| in_plane.get(usize::from(p))).is_some_and(|&c| c <= 1); + let mut keys: Vec<(Vec<(i8, i64)>, usize)> = + folded.order.iter().enumerate().map(|(i, &pi)| (if alone(pi) { vec![] } else { layer(pi) }, i)).collect(); + // Then by the stack's order, for panels that stack as one. + let placed = |i: usize| folded.order.get(i).and_then(|&pi| place.get(pi)).copied().unwrap_or(usize::MAX); + keys.sort_by(|a, b| compare(&a.0, &b.0).then(placed(a.1).cmp(&placed(b.1))).then(a.1.cmp(&b.1))); + let mut ranks = vec![0u16; folded.order.len()]; + for (r, &(_, i)) in keys.iter().enumerate() { + if let Some(slot) = ranks.get_mut(i) { + *slot = u16::try_from(r + 1).unwrap_or(u16::MAX); + } + } + ranks +} + /// `scene` drawn; `None` when the view is not usable (a size of 0, a side over [`MAX_SIDE`], more /// than [`MAX_PIXELS`] pixels, or a value that is not finite). Panels whose map is not finite, or whose outline has more than /// [`super::MAX_POLYGON_POINTS`] points, are left out. @@ -456,10 +630,17 @@ pub fn render(scene: &Scene) -> Option { Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] }; let (inside, outside) = (opaque(scene.inside), opaque(scene.outside)); let near = camera.eye().map(|(eye, _)| eye * NEAREST); - for (rank, &pi) in scene.folded.order.iter().enumerate() { + let planes = planes(scene.folded, scene.blank); + let ranks = tie_ranks(scene.folded, &camera, &planes); + // Panels are drawn by their poses about the blank's middle (`FoldedPanel::local`), with the flat + // points and the view's center moved to match. + let o = scene.folded.origin; + let local = Camera { center: [camera.center[0] - o[0], camera.center[1] - o[1], camera.center[2] - o[2]], ..camera }; + for (&pi, &rank) in scene.folded.order.iter().zip(&ranks) { let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue }; - let Some(mapped) = map_panel(&camera, f) else { continue }; + let Some(mapped) = map_panel(&local, &f.local) else { continue }; let Some(rings) = flat_rings(panel, camera.scale) else { continue }; + let rings: Vec> = rings.into_iter().map(|r| r.into_iter().map(|[u, v]| [u - o[0], v - o[1]]).collect()).collect(); let projected: Vec> = rings .iter() .map(|r| match near { @@ -480,9 +661,11 @@ pub fn render(scene: &Scene) -> Option { .collect(); let fill = Fill { mapped: &mapped, - rank: u16::try_from(rank + 1).unwrap_or(u16::MAX), + rank, + planes: &planes, panel: u16::try_from(pi + 1).unwrap_or(u16::MAX), print: scene.print, + origin: [o[0], o[1]], inside, outside, }; @@ -491,5 +674,46 @@ pub fn render(scene: &Scene) -> Option { Some(Image { width: camera.width, height: camera.height, pixels: target.color, panels: target.panel }) } +/// The plane each panel of `folded` lies in, as a number shared by the panels in one plane: their +/// normals parallel to within [`PARALLEL`] and their planes as far apart as rounding leaves them +/// ([`COPLANAR`] at their distance from [`Folded::origin`] for each hinge between them and the +/// base), so a parallel panel any measurable way behind another goes by depth. Each panel is +/// measured at the middle of its bounds in `blank`, by its pose about [`Folded::origin`] +/// ([`super::FoldedPanel::local`]), so where the blank lies in the document does not change the +/// planes. Past [`super::MAX_PANELS`] panels, one plane for all. +fn planes(folded: &Folded, blank: &Blank) -> Vec { + let n = folded.panels.len(); + if n > super::MAX_PANELS { + return vec![0; n]; + } + let length = |v: V3| dot(v, v).sqrt(); + // Each plane's normal, a point of it, the size of the coordinates that point came from and the + // hinges that placed it. + let mut kinds: Vec<(V3, V3, f64, usize)> = vec![]; + folded + .panels + .iter() + .enumerate() + .map(|(i, f)| { + let o = folded.origin; + let middle = blank.panels.get(i).and_then(|p| p.outline.bounds()).map_or([0.0; 3], |b| [b.center().x - o[0], -b.center().y - o[1], 0.0]); + let (normal, at) = (f.local.normal(), f.local.apply(middle)); + let size = length(at).max(length(middle)); + let same = |(m, p, s, d): &(V3, V3, f64, usize)| { + let c = [normal[1] * m[2] - normal[2] * m[1], normal[2] * m[0] - normal[0] * m[2], normal[0] * m[1] - normal[1] * m[0]]; + let apart = dot(*m, [at[0] - p[0], at[1] - p[1], at[2] - p[2]]).abs(); + // Saturating: a `Folded` built by a caller may carry any depth. + let hinges = f64::from(u32::try_from(f.depth.saturating_add(*d).saturating_add(1)).unwrap_or(u32::MAX)); + length(c) <= PARALLEL && apart <= COPLANAR * hinges * (1.0 + size.max(*s)) + }; + let k = kinds.iter().position(same).unwrap_or_else(|| { + kinds.push((normal, at, size, f.depth)); + kinds.len() - 1 + }); + u16::try_from(k).unwrap_or(u16::MAX) + }) + .collect() +} + #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs index 8639615a53..014cf010d7 100644 --- a/crates/three-d/src/fold/raster/tests.rs +++ b/crates/three-d/src/fold/raster/tests.rs @@ -1,6 +1,8 @@ +use std::collections::HashSet; + use vectorcraft_geom::{PathData, Point, Rect, SubPath}; -use super::super::{Blank, Folded, FoldedPanel, Panel, Pose}; +use super::super::{Blank, Folded, FoldedPanel, Panel, Pose, Stack}; use super::*; fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { @@ -16,10 +18,12 @@ fn scene_of(panels: Vec, poses: Vec) -> (Blank, Folded) { let n = panels.len(); let folded = Folded { base: 0, - panels: poses.into_iter().map(|pose| FoldedPanel { pose, parent: None, depth: 0 }).collect(), + panels: poses.into_iter().map(|pose| FoldedPanel { pose, local: pose, parent: None, depth: 0 }).collect(), order: (0..n).collect(), hinges: vec![], collisions: vec![], + stack: Stack { root: 0, parent: vec![None; n], order: (0..n).collect(), toward_parent: vec![None; n] }, + origin: [0.0; 3], }; (Blank { panels, hinges: vec![], holes: vec![] }, folded) } @@ -135,6 +139,1032 @@ fn the_nearer_of_two_panels_shows_and_a_tie_goes_to_the_later_one() { assert_eq!(img.panel_at(80, 50), Some(1), "and in front on the right"); } +#[test] +fn of_two_parallel_panels_the_nearer_shows_however_close() { + // 2 and 2.0001 points deep: a hair more than `TIE` apart once subtracted, though 2 + `TIE` + // equals 2.0001. The panels lie in different planes, so the nearer shows whichever is drawn + // first. + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + for (near, poses) in [(1, vec![moved(2.0), moved(2.0001)]), (0, vec![moved(2.0001), moved(2.0)])] { + let (b, f) = scene_of(vec![whole(), whole()], poses); + assert_eq!(planes(&f, &b).iter().collect::>().len(), 2, "two planes"); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(50, 50), Some(near)); + } +} + +#[test] +fn a_scene_whose_panels_claim_any_depth_still_draws() { + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let (b, mut f) = scene_of(vec![whole(), whole()], vec![moved(5.0), moved(5.0)]); + for p in &mut f.panels { + p.depth = usize::MAX; + } + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert!(img.panel_at(50, 50).is_some()); +} + +#[test] +fn a_flap_folded_flat_lies_behind_the_print_at_180_and_in_front_at_minus_180() { + // A 100 × 60 blank with a crease at x = 60: the flap (x 60 to 100) folds over onto the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + // Folds a hair short of flat lie on the same side, everywhere within a tie of the base. + for (angle, flap_in_front) in [(180.0, false), (-180.0, true), (179.9999, false), (-179.9999, true)] { + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + super::super::FoldLine { + path: poly(&[(60.0, 0.0), (60.0, 60.0)], false), + kind: super::super::LineKind::Crease, + key: 2, + angle: Some(angle), + }, + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = 1 - f.base; + let views = [ + (front(), true), + (Camera { rotate_y: 180.0, ..front() }, false), + (Camera { perspective: 60.0, ..front() }, true), + (Camera { rotate_y: 180.0, perspective: 60.0, ..front() }, false), + ]; + for (camera, seen_from_print) in views { + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // The point x 40, y 30 of the blank, where the flap lies over the base. + let x = if seen_from_print { 40 } else { 60 }; + let want = if flap_in_front == seen_from_print { flap } else { f.base }; + assert_eq!(img.panel_at(x, 30), Some(want), "{angle}°, seen from the print: {seen_from_print}, {camera:?}"); + } + } +} + +#[test] +fn a_hinge_left_at_0_degrees_keeps_its_panel_level_with_its_parent() { + // A 100 × 60 blank: the base (x 0 to 60), a strip (60 to 65) left flat at 0°, and a flap (65 to + // 100) folded back at 180°, which lies behind the base from x 30 to 60. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2, 0.0), + crease(65.0, 3, 180.0), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(45, 30), Some(f.base), "the base is in front of the flap behind it"); +} + +#[test] +fn a_flap_folded_back_over_a_folded_panel_lies_between_it_and_the_base() { + // A 110 × 60 strip: the base (x 0 to 60), a panel (60 to 100) folded back under the base at + // 180°, and a flap (100 to 110) folded back at 180° from that panel, between it and the base, at + // x 20 to 30. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let middle = f.panels.iter().position(|p| p.parent == Some(f.base)).expect("the panel folded from the base"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(25, 30), Some(f.base), "the base, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..front() }).panel_at(75, 30), Some(middle), "the folded panel, from the back"); + // Folded about the flap instead, the blank only moves: the flap (x 100 to 110 now) still lies + // between the other two, the 60 pt panel over it on the printed side. + let tip = super::super::panel_at(b, Point::new(105.0, 30.0)).expect("the flap"); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let at_tip = Camera { center: [105.0, -30.0, 0.0], ..front() }; + let wide = super::super::panel_at(b, Point::new(30.0, 30.0)).expect("the 60 pt panel"); + assert_eq!(draw(at_tip).panel_at(50, 50), Some(wide), "the 60 pt panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(middle), "the folded panel, from the back"); +} + +#[test] +fn a_strip_far_from_the_origin_stacks_the_same_about_any_base() { + // The strip of the test above turned 45° and moved to about (3,000,000, 3,000,000) pt, folded + // about its 10 pt flap: the 60 pt panel still lies over the flap on the printed side. + let s = std::f64::consts::FRAC_1_SQRT_2; + let at = |x: f64, y: f64| Point::new(3_000_000.0 + (x - y) * s, 3_000_000.0 + (x + y) * s); + let poly = + |pts: &[(f64, f64)], closed: bool| PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| at(x, y)).collect::>(), closed)); + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let panel = |x: f64, y: f64| super::super::panel_at(b, at(x, y)).expect("a panel"); + let (wide, middle, tip) = (panel(30.0, 30.0), panel(80.0, 30.0), panel(105.0, 30.0)); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let c = at(105.0, 30.0); + let at_tip = Camera { center: [c.x, -c.y, 0.0], ..front() }; + assert_eq!(draw(at_tip).panel_at(50, 50), Some(wide), "the 60 pt panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(middle), "the folded panel, from the back"); +} + +#[test] +fn a_flat_stack_far_from_the_origin_stays_in_one_plane() { + // A strip from x = 3,000,000 pt: the base (60 pt wide), a 40 pt panel folded back under it at + // 180° and a 35 pt flap folded back at 180° between the two. + let x0 = 3_000_000.0; + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x0 + x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(180.0), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (135.0, 0.0), (135.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(60.0, 2), + crease(100.0, 3), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let middle = super::super::panel_at(b, Point::new(x0 + 80.0, 30.0)).expect("the middle panel"); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + assert_eq!(planes(&f, b).iter().collect::>().len(), 1, "one plane"); + let draw = |rotate_y| { + let camera = Camera { rotate_y, center: [x0 + 40.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 50) + }; + assert_eq!((draw(0.0), draw(180.0)), (Some(f.base), Some(middle))); +} + +#[test] +fn a_panel_parallel_to_the_base_a_hair_behind_it_goes_by_depth() { + // A strip 30 pt tall: the base (x 0 to 100), a 20 pt panel folded back at 179.9999° and a 30 pt + // flap at 0.0001° off it, parallel to the base and about 0.000035 pt behind it; then the same + // strip 100,000 pt to the right; then at 179.999999° and 0.000001°, about 0.00000035 pt behind, + // 3,000,000 pt to the right; then with a 1 pt middle panel, about 0.0000000175 pt behind, at the + // origin and 3,000,000 pt to the right. + for (dx, back, w) in + [(0.0, 0.0001, 20.0), (100_000.0, 0.0001, 20.0), (3_000_000.0, 0.000001, 20.0), (0.0, 0.000001, 1.0), (3_000_000.0, 0.000001, 1.0)] + { + parallel_a_hair_behind(dx, back, w); + } +} + +fn parallel_a_hair_behind(dx: f64, back: f64, w: f64) { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x + dx, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (130.0 + w, 0.0), (130.0 + w, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease(100.0, 2, 180.0 - back), + crease(100.0 + w, 3, back), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let at = Point::new(115.0 + w + dx, 15.0); + let flap = super::super::panel_at(b, at).expect("the flap"); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let m = f.panels[flap].pose.place(at); + assert!(m[2] < 0.0 && m[2] > -1e-4, "the flap lies a hair behind the base: {m:?}"); + let draw = |rotate_y| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + assert_eq!((draw(0.0), draw(180.0)), (Some(f.base), Some(flap)), "at x + {dx}, a {w} pt middle panel"); +} + +#[test] +fn a_small_blank_folded_near_flat_draws_the_same_far_from_the_origin() { + // A 4 pt strip, its second half folded back at 179.999999° so it lies a hair behind the first, + // seen at a three-quarter turn with and without perspective: every pixel shows the same panel + // at the origin and 3,000,000 pt right and down. + let draw = |at: f64, perspective: f64| { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x + at, y + at)).collect::>(), closed)) + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (4.0, 0.0), (4.0, 1.0), (0.0, 1.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + super::super::FoldLine { + path: poly(&[(2.0, 0.0), (2.0, 1.0)], false), + kind: super::super::LineKind::Crease, + key: 2, + angle: Some(179.999999), + }, + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let base = super::super::panel_at(b, Point::new(0.5 + at, 0.5 + at)).expect("the base"); + let f = super::super::fold(b, Some(base), 1.0, 0.0001).expect("folds"); + let camera = Camera { rotate_x: 35.0, rotate_y: 40.0, scale: 40.0, perspective, center: [1.0 + at, -0.5 - at, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let shown: Vec> = + (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).map(|(x, y)| img.panel_at(x, y).map(|p| p == base)).collect(); + assert!(shown.contains(&Some(true)), "the base shows"); + shown + }; + for perspective in [0.0, 40.0] { + assert!(draw(0.0, perspective) == draw(3_000_000.0, perspective), "perspective {perspective}"); + } +} + +#[test] +fn a_blank_lying_flat_takes_its_ranks_from_the_order_alone() { + // A strip of 64 panels, each crease at 180°, not yet folded: no panel overlaps another, so no + // layer is worked out. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (640.0, 0.0), (640.0, 10.0), (0.0, 10.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for i in 1..64u32 { + let x = f64::from(i) * 10.0; + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 10.0)], false), + kind: super::super::LineKind::Crease, + key: u64::from(i) + 1, + angle: Some(180.0), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let f = super::super::fold(&blanks[0], None, 0.0, 0.1).expect("folds"); + let ranks = tie_ranks(&f, &front(), &planes(&f, &blanks[0])); + assert_eq!(ranks, (1..=64).collect::>()); +} + +#[test] +fn round_a_loop_of_panels_the_stack_follows_the_hinges_that_placed_them() { + // A 100 × 100 blank cut into four 50 pt squares by four creases, one per side of the middle + // point. The crease that closes the loop when folded about the largest panel folds at 180° and + // the rest at 0°; folded about a panel on that crease, the crease is in the tree and its flap + // lies flat behind the panel. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let lines = |flat_key: Option| { + let crease = |from: (f64, f64), to: (f64, f64), key: u64| super::super::FoldLine { + path: poly(&[from, to], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(if Some(key) == flat_key { 180.0 } else { 0.0 }), + }; + vec![ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease((50.0, 0.0), (50.0, 50.0), 2), + crease((50.0, 50.0), (50.0, 100.0), 3), + crease((0.0, 50.0), (50.0, 50.0), 4), + crease((50.0, 50.0), (100.0, 50.0), 5), + ] + }; + let (blanks, issues) = super::super::blanks(&lines(None), 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let level = super::super::fold(&blanks[0], None, 1.0, 0.1).expect("folds"); + let closing = level.hinges.iter().position(|h| !h.tree).expect("a hinge closes the loop"); + let key = *blanks[0].hinges[closing].keys.first().expect("a line"); + let (blanks, issues) = super::super::blanks(&lines(Some(key)), 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let h = &b.hinges[closing]; + assert_eq!(h.keys, [key]); + let f = super::super::fold(b, Some(h.a), 1.0, 0.1).expect("folds"); + assert!(f.hinges[closing].tree); + // The panel's middle, in pixels: the blank's top left square is pixels 0 to 50. + let middle = |p: usize| { + let c = b.panels[p].outline.bounds().expect("bounds").center(); + (c.x as u32, c.y as u32) + }; + let (x, y) = middle(h.a); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(x, y), Some(h.a), "the panel, from its printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..front() }).panel_at(100 - x, y), Some(h.b), "the flap, from the back"); +} + +#[test] +fn round_a_flat_loop_the_stack_is_the_same_whichever_tree_reaches_the_flaps() { + // A 2 × 2 grid of panels joined by 0° creases (the largest at the bottom left), and two flaps + // folded back at 180° off the top right panel: the first (x 100 to 130) under that panel, the + // tip (130 to 140) between the two. Folded about the tip, the tree reaches the grid another way, + // and the stack stays as it is about the largest panel. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |from: (f64, f64), to: (f64, f64), key: u64, angle: f64| super::super::FoldLine { + path: poly(&[from, to], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let lines = [ + super::super::FoldLine { + path: poly(&[(0.0, 0.0), (140.0, 0.0), (140.0, 40.0), (100.0, 40.0), (100.0, 100.0), (0.0, 100.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }, + crease((60.0, 0.0), (60.0, 40.0), 2, 0.0), + crease((60.0, 40.0), (60.0, 100.0), 3, 0.0), + crease((0.0, 40.0), (60.0, 40.0), 4, 0.0), + crease((60.0, 40.0), (100.0, 40.0), 5, 0.0), + crease((100.0, 0.0), (100.0, 40.0), 6, 180.0), + crease((130.0, 0.0), (130.0, 40.0), 7, 180.0), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let at = |x: f64, y: f64| super::super::panel_at(b, Point::new(x, y)).expect("a panel"); + let (corner, under, tip) = (at(80.0, 20.0), at(115.0, 20.0), at(135.0, 20.0)); + let f = super::super::fold(b, Some(tip), 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let at_tip = Camera { center: [135.0, -20.0, 0.0], ..front() }; + assert_eq!(draw(at_tip).panel_at(50, 50), Some(corner), "the top right panel, from the printed side"); + assert_eq!(draw(Camera { rotate_y: 180.0, ..at_tip }).panel_at(50, 50), Some(under), "the first flap, from the back"); +} + +#[test] +fn two_flaps_folded_flat_behind_the_base_show_opposite_ones_from_each_side() { + // The base (x 30 to 80) with a window (52 to 58), a flap on each side folded back at 180°: the + // left one to x 30 to 60, the right one to 50 to 80, so both lie behind the window. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (110.0, 0.0), (110.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(52.0, 20.0), (58.0, 20.0), (58.0, 40.0), (52.0, 40.0)], true, Cut, 2, None), + line(&[(30.0, 0.0), (30.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(80.0, 0.0), (80.0, 60.0)], false, Crease, 4, Some(180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let through_window = draw(front()).panel_at(55, 30); + let from_back = draw(Camera { rotate_y: 180.0, ..front() }).panel_at(45, 30); + let flaps: Vec = (0..b.panels.len()).filter(|&i| i != f.base).collect(); + assert!(through_window.is_some_and(|p| flaps.contains(&p)), "{through_window:?}"); + assert!(from_back.is_some_and(|p| flaps.contains(&p)), "{from_back:?}"); + assert_ne!(through_window, from_back); +} + +#[test] +fn a_flap_split_by_a_0_degree_crease_stacks_as_one_against_another_flap() { + // The base (x 30 to 90), a right flap (90 to 140) folded back to 40 to 90, and a left flap (0 to + // 30) folded back to 30 to 60 in two parts joined at 0° (x 15), both parts over the right flap. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (140.0, 0.0), (140.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(30.0, 0.0), (30.0, 60.0)], false, Crease, 2, Some(180.0)), + line(&[(90.0, 0.0), (90.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(15.0, 0.0), (15.0, 60.0)], false, Crease, 4, Some(0.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let camera = Camera { width: 140, center: [70.0, -50.0, 0.0], rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // From the back the image is mirrored: x on the blank is 140 - x in the image. + let starting_at = |x0: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x0).abs() < 1e-6)); + let right_flap = starting_at(90.0).expect("the right flap"); + // Folded back about x 30, the left flap's part from 15 to 30 lies at 30 to 45 and its part from + // 0 to 15 at 45 to 60. + let (inner, outer) = (starting_at(15.0).expect("the left flap's inner part"), starting_at(0.0).expect("its outer part")); + let (near, far) = (img.panel_at(140 - 42, 30), img.panel_at(140 - 52, 30)); + // Either flap may be in front, but the same one at both samples. + let right = (near, far) == (Some(right_flap), Some(right_flap)); + let left = (near, far) == (Some(inner), Some(outer)); + assert!(right || left, "{near:?} {far:?}: right flap {right_flap}, left flap {inner} and {outer}"); +} + +#[test] +fn a_tip_folded_on_a_flap_stays_on_that_flap_s_side_of_another_flap() { + // Left to right: a tip (x 0 to 20), a left flap (20 to 70), the base (70 to 140) and a right flap + // (140 to 205). Both flaps fold back at 180° behind the base (to 70 to 120 and 75 to 140), and + // the tip folds at -180° on the left flap (to 100 to 120), so the three overlap from 100 to 120. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (205.0, 0.0), (205.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(20.0, 0.0), (20.0, 60.0)], false, Crease, 2, Some(-180.0)), + line(&[(70.0, 0.0), (70.0, 60.0)], false, Crease, 3, Some(180.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 4, Some(180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (tip, left, right) = (starts_at(0.0), starts_at(20.0), starts_at(140.0)); + let camera = Camera { width: 210, center: [105.0, -50.0, 0.0], rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + // From the back the image is mirrored: x on the blank is 210 - x in the image. + let (flaps_only, with_tip) = (img.panel_at(210 - 90, 30), img.panel_at(210 - 110, 30)); + if flaps_only == Some(right) { + assert_eq!(with_tip, Some(right), "the right flap covers the left flap and the tip on it"); + } else { + assert_eq!((flaps_only, with_tip), (Some(left), Some(tip)), "the left flap, and the tip on it, cover the right flap"); + } +} + +#[test] +fn a_tip_folded_back_toward_a_folded_panel_s_print_covers_it_from_the_back() { + // The base (x 0 to 60), a panel (60 to 100) folded back at 180° to 20 to 60, and a tip (100 to + // 110) folded at -180° onto that panel's printed side, to 20 to 30, behind it from the front. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + // The same with the tip a hair short of flat, and with an 80 pt panel under a 100 pt base. + for (middle, tip_angle) in [(40.0, -180.0), (40.0, -179.9999), (40.0, -179.999), (80.0, -179.9999), (1000.0, -179.999)] { + let base = middle + 20.0; + let end = base + middle + 10.0; + let lines = [ + line(&[(0.0, 0.0), (end, 0.0), (end, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(base, 0.0), (base, 60.0)], false, Crease, 2, Some(180.0)), + line(&[(base + middle, 0.0), (base + middle, 60.0)], false, Crease, 3, Some(tip_angle)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let tip = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - (base + middle)).abs() < 1e-6)).expect("the tip"); + let back = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: back }).expect("drawn"); + assert_eq!(img.panel_at(100 - 25, 30), Some(tip), "{middle} pt, {tip_angle}°"); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(25, 30), Some(f.base), "{middle} pt, {tip_angle}°"); + } +} + +#[test] +fn overlapping_lid_flaps_keep_their_order_as_the_view_turns_on_one_side_of_the_lid() { + // A box strip: a left flap (x 0 to 60), a wall (60 to 100), the base (100 to 200), a wall (200 to + // 240) and a right flap (240 to 300). The walls fold 90° down and the flaps 90° in, so the flaps + // meet in one plane 40 pt below the base and overlap from x 140 to 160. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let crease = |x: f64, key| line(&[(x, 0.0), (x, 60.0)], false, Crease, key, Some(90.0)); + let lines = [ + line(&[(0.0, 0.0), (300.0, 0.0), (300.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + crease(60.0, 2), + crease(100.0, 3), + crease(200.0, 4), + crease(240.0, 5), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + // Looking up at the lid from below, a little to one side and then the other, at its middle. + let shown = |rotate_y: f64| { + let camera = Camera { width: 200, rotate_y, center: [150.0, -30.0, -40.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(100, 50) + }; + let (left, right) = (shown(175.0), shown(185.0)); + assert!(left.is_some_and(|p| p != f.base), "{left:?}"); + assert_eq!(left, right); +} + +#[test] +fn flaps_folded_onto_a_panel_keep_their_order_as_the_panel_tilts_either_way() { + // The base (x 0 to 100, y -50 to 110) and a panel (100 to 200, 0 to 60) on a crease at x = 100, + // with a flap above (y -40 to 0) and one below (60 to 100), each cut free of the base and folded + // at -180° onto the panel's printed side, where they overlap from y 20 to 40. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let shown = |tilt: f64| { + let outline = [(0.0, -50.0), (100.0, -50.0), (100.0, -40.0), (200.0, -40.0), (200.0, 100.0), (100.0, 100.0), (100.0, 110.0), (0.0, 110.0)]; + let lines = [ + line(&outline, true, Cut, 1, None), + line(&[(100.0, -40.0), (100.0, 0.0)], false, Cut, 2, None), + line(&[(100.0, 60.0), (100.0, 100.0)], false, Cut, 3, None), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 4, Some(tilt)), + line(&[(100.0, 0.0), (200.0, 0.0)], false, Crease, 5, Some(-180.0)), + line(&[(100.0, 60.0), (200.0, 60.0)], false, Crease, 6, Some(-180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let camera = Camera { width: 200, center: [150.0, -30.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let flap = |y: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.y0 - y).abs() < 1e-6 && r.x0 > 99.0)); + let shown = img.panel_at(100, 50); + if shown == flap(-40.0) { + "above" + } else if shown == flap(60.0) { + "below" + } else { + "neither" + } + }; + let (up, down) = (shown(1.0), shown(-1.0)); + assert_ne!(up, "neither"); + assert_eq!(up, down); +} + +#[test] +fn a_flap_folded_onto_a_wall_standing_at_90_degrees_covers_its_print() { + // The base (x 0 to 60), a wall (60 to 100) folded 90° and a flap (100 to 130) folded at -180° + // onto the wall's printed side, where it covers the wall from 10 to 40 pt out from the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (130.0, 0.0), (130.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(60.0, 0.0), (60.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 3, Some(-180.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (wall, flap) = (starts_at(60.0), starts_at(100.0)); + let mut sides = vec![]; + for rotate_y in [90.0, -90.0] { + // Facing the wall from one side and then the other, the middle row of the view. + let camera = Camera { width: 200, height: 100, rotate_y, center: [60.0, -30.0, 0.0], ..front() }; + let printed = map_panel(&camera, &f.panels[wall].pose).is_some_and(|m| m.printed); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let count = |p: usize| (0..img.width).filter(|&x| img.panel_at(x, 50) == Some(p)).count(); + let (walls, flaps) = (count(wall), count(flap)); + if printed { + assert!(flaps > 25 && walls < 15, "from the wall's printed side the flap covers it: wall {walls} px, flap {flaps} px"); + } else { + assert!(flaps == 0 && walls > 35, "from the back the wall covers the flap: wall {walls} px, flap {flaps} px"); + } + sides.push(printed); + } + assert_ne!(sides[0], sides[1], "both sides of the wall are looked at"); +} + +#[test] +fn end_flaps_seen_straight_through_an_open_carton_show_opposite_ones_from_each_side() { + // The base (x 40 to 140, y 0 to 60) and a side wall on each side (0 to 40 and 140 to 180), each + // with an end flap (y 60 to 160) that folds in across the carton's end, so both flaps cover + // the same 100 pt. Looking straight through that end, the base and walls are edge on. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let outline = [(0.0, 0.0), (180.0, 0.0), (180.0, 160.0), (140.0, 160.0), (140.0, 60.0), (40.0, 60.0), (40.0, 160.0), (0.0, 160.0)]; + let lines = [ + line(&outline, true, Cut, 1, None), + line(&[(40.0, 0.0), (40.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 3, Some(90.0)), + line(&[(0.0, 60.0), (40.0, 60.0)], false, Crease, 4, Some(90.0)), + line(&[(140.0, 60.0), (180.0, 60.0)], false, Crease, 5, Some(90.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6 && r.y0 > 59.0)).expect("a flap"); + let (left, right) = (flap(0.0), flap(140.0)); + let shown = |rotate_x: f64| { + let camera = Camera { width: 300, height: 300, rotate_x, center: [90.0, -60.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let count = + |p: usize| (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter(|&(x, y)| img.panel_at(x, y) == Some(p)).count(); + (count(left), count(right)) + }; + let (one, other) = (shown(90.0), shown(-90.0)); + // Each view shows one flap over (nearly) the whole of the other. + let winner = |(l, r): (usize, usize)| { + if l > 10 * r.max(1) { + Some(left) + } else if r > 10 * l.max(1) { + Some(right) + } else { + None + } + }; + assert!(winner(one).is_some() && winner(other).is_some(), "the flaps cover the same end: {one:?} {other:?}"); + assert_ne!(winner(one), winner(other), "{one:?} {other:?}"); +} + +#[test] +fn a_flap_looped_round_onto_the_base_shows_from_the_side_it_came_from() { + // A strip: the base (x 0 to 100) and panels 40, 60, 40 and 80 pt wide, folded 90°, -90°, -90° + // and -90°, so the last one comes round and lies on the base's plane over part of it. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let lines = [ + line(&[(0.0, 0.0), (320.0, 0.0), (320.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(100.0, 0.0), (100.0, 60.0)], false, Crease, 2, Some(90.0)), + line(&[(140.0, 0.0), (140.0, 60.0)], false, Crease, 3, Some(-90.0)), + line(&[(200.0, 0.0), (200.0, 60.0)], false, Crease, 4, Some(-90.0)), + line(&[(240.0, 0.0), (240.0, 60.0)], false, Crease, 5, Some(-90.0)), + ]; + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let flap = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - 240.0).abs() < 1e-6)).expect("the flap"); + // The panels between the base and the flap all lie behind the base's printed side. + for (i, (panel, folded)) in b.panels.iter().zip(&f.panels).enumerate() { + let r = panel.outline.bounds().expect("bounds"); + let z = folded.pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0))[2]; + if i != f.base && i != flap { + assert!(z < -1.0, "panel {i} at z {z}"); + } + } + // At x 90 the flap lies on the base: from the front the base covers it, from the back it + // covers the base. + let at = |rotate_y: f64, x: u32| { + let camera = Camera { width: 400, height: 100, rotate_y, center: [100.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(x, 50) + }; + assert_eq!(at(0.0, 200 - 10), Some(f.base)); + assert_eq!(at(180.0, 200 + 10), Some(flap)); +} + +#[test] +fn a_strip_wrapped_round_a_wall_lands_its_flap_on_the_print_side_it_came_from() { + // A strip 60 pt tall: the base (x 0 to 100) and panels 20, 20, 40, 40 and 20 pt wide, then a + // flap (240 to 270, y 0 to 30), folded 90°, -90°, -90°, -90°, -90° and 90°. The 20 pt wall the + // flap folds from stands on the printed side of the base, and the flap lands on the base at x + // 50 to 80. With `tab`, the wall also runs on past the flap's hinge (to x 340, y 30 to 60), + // through the base's plane, which moves its middle to the other side of that plane. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + // With `cutout` of 5, a 10 pt hole on the middle of each crease breaks every hinge in two; with + // a larger one, the hole runs to within 2 pt of each end, as wide as `cutout` either side. + let shown = |tab: bool, cutout: f64| { + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let mut lines = if tab { + vec![ + line(&[(0.0, 0.0), (270.0, 0.0), (270.0, 30.0), (340.0, 30.0), (340.0, 60.0), (0.0, 60.0)], true, Cut, 1, None), + line(&[(240.0, 30.0), (270.0, 30.0)], false, Cut, 2, None), + ] + } else { + vec![line(&[(0.0, 0.0), (270.0, 0.0), (270.0, 30.0), (240.0, 30.0), (240.0, 60.0), (0.0, 60.0)], true, Cut, 1, None)] + }; + let creases = + [(100.0, 60.0, 90.0), (120.0, 60.0, -90.0), (140.0, 60.0, -90.0), (180.0, 60.0, -90.0), (220.0, 60.0, -90.0), (240.0, 30.0, 90.0)]; + for (i, (x, high, a)) in creases.into_iter().enumerate() { + let key = 10 * (i as u64 + 1); + if cutout > 0.0 { + let (lo, hi) = if cutout > 5.0 { (2.0, high - 2.0) } else { (high / 2.0 - 5.0, high / 2.0 + 5.0) }; + let w = cutout.min(5.0); + lines.push(line(&[(x - w, lo), (x + w, lo), (x + w, hi), (x - w, hi)], true, Cut, key, None)); + lines.push(line(&[(x, 0.0), (x, lo)], false, Crease, key + 1, Some(a))); + lines.push(line(&[(x, hi), (x, high)], false, Crease, key + 2, Some(a))); + } else { + lines.push(line(&[(x, 0.0), (x, high)], false, Crease, key, Some(a))); + } + } + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (wall, flap) = (starts_at(220.0), starts_at(240.0)); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let middle = |i: usize| { + let r = b.panels[i].outline.bounds().expect("bounds"); + f.panels[i].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)) + }; + let m = middle(flap); + assert!(m[2].abs() < 1e-6 && (m[0] - 65.0).abs() < 1e-6, "the flap lies on the base: {m:?}"); + assert_eq!(middle(wall)[2] > 0.0, !tab, "the wall's middle is on the printed side without the tab only"); + // The flap's row at y 5, at x 65, from the front and from the back (mirrored). + let at = |rotate_y: f64, px: u32| { + let camera = Camera { width: 400, height: 100, rotate_y, center: [100.0, -30.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(px, 25) + }; + let named = |p: Option| match p { + Some(p) if p == f.base => "base", + Some(p) if p == flap => "flap", + _ => "other", + }; + (named(at(0.0, 200 - 35)), named(at(180.0, 200 + 35))) + }; + assert_eq!(shown(false, 0.0), ("flap", "base")); + assert_eq!(shown(true, 0.0), ("flap", "base"), "the side next to the hinge decides, not the wall's middle"); + assert_eq!(shown(false, 5.0), ("flap", "base"), "a hinge broken by a cutout"); + assert_eq!(shown(true, 5.0), ("flap", "base"), "both"); + assert_eq!(shown(true, 6.0), ("flap", "base"), "hinges joined only near their ends"); +} + +#[test] +fn a_flap_that_comes_down_onto_the_base_at_a_shallow_angle_lands_on_the_side_it_came_from() { + // A strip 30 pt tall: the base (x 0 to `base`), a panel 10 pt wide folded down behind it, one + // 20 pt wide back level, one up through the base's plane to `drop` in front of it, a ramp + // `ramp` wide that comes back down to the base's plane over its width, and a flap (30 pt) that + // lies on the base from where the ramp ends. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let shown = |base: f64, ramp: f64, drop: f64| { + // To the millionth of a degree a line keeps, and the drop that ramp comes down by. + let tilt = super::super::kept_angle((drop / ramp).asin().to_degrees()); + let drop = ramp * tilt.to_radians().sin(); + let up = base + 30.0; + let creases = [(base, 90.0), (base + 10.0, -90.0), (up, -90.0), (up + 10.0 + drop, -90.0 - tilt), (up + 10.0 + drop + ramp, tilt)]; + let end = up + 10.0 + drop + ramp + 30.0; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (end, 0.0), (end, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for (i, (x, a)) in creases.into_iter().enumerate() { + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key: 2 + i as u64, + angle: Some(a), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let flap = b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - (end - 30.0)).abs() < 1e-6)).expect("the flap"); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let r = b.panels[flap].outline.bounds().expect("bounds"); + let m = f.panels[flap].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)); + let x = base + 20.0 - ramp - 15.0; + assert!(m[2].abs() < 1e-6 && (m[0] - x).abs() < 1e-2 && x > 0.0, "the flap lies on the base at {x}: {m:?}"); + // The flap's middle, from the front and from the back. + let at = |rotate_y: f64| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + (at(0.0) == Some(flap), at(180.0) == Some(f.base)) + }; + assert_eq!(shown(100.0, 40.0, 0.01), (true, true), "a 40 pt ramp 0.01 pt high"); + assert_eq!(shown(600.0, 500.0, 0.01), (true, true), "a 500 pt ramp 0.01 pt high"); + assert_eq!(shown(2100.0, 2000.0, 0.01), (true, true), "a 2,000 pt ramp 0.01 pt high"); + assert_eq!(shown(600.0, 500.0, 0.001), (true, true), "a 500 pt ramp 0.001 pt high"); +} + +#[test] +fn a_flap_brought_back_by_folds_all_near_flat_lands_on_the_side_its_ramp_came_from() { + // A strip 30 pt tall: the base (x 0 to 1,000) and panels 100, 300, 200 and 50 pt wide, folded + // `tilt`, 180°, -2 `tilt` and `tilt`: at 0.04° the 200 pt panel comes back down onto the base's + // plane from about 0.14 pt off it, at 0.00001° from 0.00004 pt, and the last panel lies on the + // base. + for tilt in [0.04, 0.00001] { + flap_brought_back_by_folds_all_near_flat(tilt); + } +} + +fn flap_brought_back_by_folds_all_near_flat(tilt: f64) { + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let creases = [(1000.0, tilt), (1100.0, 180.0), (1400.0, -2.0 * tilt), (1600.0, tilt)]; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (1650.0, 0.0), (1650.0, 30.0), (0.0, 30.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + for (i, (x, a)) in creases.into_iter().enumerate() { + lines.push(super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 30.0)], false), + kind: super::super::LineKind::Crease, + key: 2 + i as u64, + angle: Some(a), + }); + } + let (blanks, issues) = super::super::blanks(&lines, 0.0001); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (ramp, flap) = (starts_at(1400.0), starts_at(1600.0)); + let f = super::super::fold(b, None, 1.0, 0.0001).expect("folds"); + let middle = |i: usize| { + let r = b.panels[i].outline.bounds().expect("bounds"); + f.panels[i].pose.place(Point::new((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0)) + }; + let (m, above) = (middle(flap), middle(ramp)[2]); + assert!(m[2].abs() < 1e-3 && (0.0..1000.0).contains(&m[0]) && above.abs() > tilt * 0.25, "the flap lies on the base: {m:?}, the ramp at {above}"); + let at = |rotate_y: f64| { + let camera = Camera { width: 100, height: 60, rotate_y, center: [m[0], -15.0, 0.0], ..front() }; + render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn").panel_at(50, 30) + }; + let (from_front, from_back) = (at(0.0), at(180.0)); + if above > 0.0 { + assert_eq!((from_front, from_back), (Some(flap), Some(f.base)), "{tilt}°"); + } else { + assert_eq!((from_front, from_back), (Some(f.base), Some(flap)), "{tilt}°"); + } +} + +#[test] +fn a_strip_wrapped_round_onto_a_panel_that_is_not_the_base_lands_on_the_side_it_came_from() { + // The strip of the test above, with a larger base (x -150 to 0) on the left that the strip's + // first panel (0 to 100) stands up from at -90°. The flap lands on that panel's printed side. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let line = |pts: &[(f64, f64)], closed: bool, kind, key, angle| super::super::FoldLine { path: poly(pts, closed), kind, key, angle }; + use super::super::LineKind::{Crease, Cut}; + let mut lines = vec![line(&[(-150.0, 0.0), (270.0, 0.0), (270.0, 30.0), (240.0, 30.0), (240.0, 60.0), (-150.0, 60.0)], true, Cut, 1, None)]; + lines.push(line(&[(0.0, 0.0), (0.0, 60.0)], false, Crease, 2, Some(-90.0))); + for (i, (x, a)) in [(100.0, 90.0), (120.0, -90.0), (140.0, -90.0), (180.0, -90.0), (220.0, -90.0)].into_iter().enumerate() { + lines.push(line(&[(x, 0.0), (x, 60.0)], false, Crease, 3 + i as u64, Some(a))); + } + lines.push(line(&[(240.0, 0.0), (240.0, 30.0)], false, Crease, 9, Some(90.0))); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (panel, flap) = (starts_at(0.0), starts_at(240.0)); + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + assert_eq!(f.base, starts_at(-150.0)); + let mut seen = vec![]; + for rotate_y in [90.0, -90.0] { + // Facing the panel from one side and then the other: how many pixels show the flap. + let camera = Camera { width: 400, height: 200, rotate_y, center: [0.0, -30.0, 0.0], ..front() }; + let printed = map_panel(&camera, &f.panels[panel].pose).is_some_and(|m| m.printed); + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let flaps = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter(|&(x, y)| img.panel_at(x, y) == Some(flap)).count(); + seen.push((printed, flaps)); + } + let (from_print, from_back) = if seen[0].0 { (seen[0].1, seen[1].1) } else { (seen[1].1, seen[0].1) }; + assert_ne!(seen[0].0, seen[1].0, "both sides of the panel are looked at"); + assert!(from_print > 600 && from_back == 0, "the flap shows on the panel's printed side only: {seen:?}"); +} + +#[test] +fn a_strip_rolled_up_45_times_keeps_the_base_in_front() { + // A strip: the base (x 0 to 60) and 45 panels 50 pt wide, every crease folded back at 180°, so + // each panel rolls under the one before it and all of them lie behind the base. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let end = 60.0 + 45.0 * 50.0; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (end, 0.0), (end, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + lines.extend((0u32..45).map(|i| { + let x = 60.0 + 50.0 * f64::from(i); + super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key: 10 + u64::from(i), + angle: Some(180.0), + } + })); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let draw = |camera| render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + assert_eq!(draw(front()).panel_at(40, 30), Some(f.base)); +} + +#[test] +fn hinges_left_at_0_degrees_before_two_folds_back_do_not_use_up_layers() { + // A 155 × 60 strip: the base (x 0 to 60), 45 strips 1 pt wide left flat at 0°, a panel (105 to + // 145) folded back at 180° and a flap (145 to 155) folded back at 180° from it, which lies + // behind the flat strips at x 65 to 75. + let poly = |pts: &[(f64, f64)], closed: bool| { + PathData::single(SubPath::polyline(&pts.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), closed)) + }; + let crease = |x: f64, key: u64, angle: f64| super::super::FoldLine { + path: poly(&[(x, 0.0), (x, 60.0)], false), + kind: super::super::LineKind::Crease, + key, + angle: Some(angle), + }; + let mut lines = vec![super::super::FoldLine { + path: poly(&[(0.0, 0.0), (155.0, 0.0), (155.0, 60.0), (0.0, 60.0)], true), + kind: super::super::LineKind::Cut, + key: 1, + angle: None, + }]; + lines.extend((0u32..45).map(|i| crease(60.0 + f64::from(i), 10 + u64::from(i), 0.0))); + lines.push(crease(105.0, 2, 180.0)); + lines.push(crease(145.0, 3, 180.0)); + let (blanks, issues) = super::super::blanks(&lines, 0.1); + assert!(issues.is_empty(), "{issues:?}"); + let b = &blanks[0]; + let f = super::super::fold(b, None, 1.0, 0.1).expect("folds"); + let starts_at = |x: f64| b.panels.iter().position(|p| p.outline.bounds().is_some_and(|r| (r.x0 - x).abs() < 1e-6)).expect("a panel"); + let (strip, middle, flap) = (starts_at(70.0), starts_at(105.0), starts_at(145.0)); + let camera = Camera { width: 160, center: [80.0, -50.0, 0.0], ..front() }; + let img = render(&Scene { blank: b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let shown = img.panel_at(70, 30); + assert_eq!(shown, Some(strip), "a flat strip, not the flap ({flap}) or the folded panel ({middle})"); +} + #[test] fn a_hole_in_a_panel_is_left_empty() { let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0), square(30.0, 30.0, 70.0, 70.0)])], vec![Pose::IDENTITY]); diff --git a/crates/three-d/src/fold/tests.rs b/crates/three-d/src/fold/tests.rs index 8031a0b2a1..6781a2c64d 100644 --- a/crates/three-d/src/fold/tests.rs +++ b/crates/three-d/src/fold/tests.rs @@ -13,7 +13,7 @@ fn poly(points: &[(f64, f64)], closed: bool) -> PathData { } fn line(kind: LineKind, points: &[(f64, f64)], closed: bool, key: u64) -> FoldLine { - FoldLine { path: poly(points, closed), kind, key } + FoldLine { path: poly(points, closed), kind, key, angle: None } } fn cut(points: &[(f64, f64)], key: u64) -> FoldLine { @@ -188,7 +188,7 @@ fn a_round_tuck_flap_folds_like_any_panel() { bp.curve_to(p(100.0, 10.0), p(80.0, 0.0), p(50.0, 0.0)); bp.curve_to(p(20.0, 0.0), p(0.0, 10.0), p(0.0, 40.0)); bp.close_path(); - let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1 }, crease((0.0, 40.0), (100.0, 40.0), 2)]; + let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1, angle: None }, crease((0.0, 40.0), (100.0, 40.0), 2)]; let (b, issues) = check(&lines); assert!(issues.is_empty(), "{issues:?}"); assert_eq!(b[0].panels.len(), 2); @@ -353,7 +353,7 @@ fn an_outline_drawn_twice_keeps_its_material() { // The same two squares as the subpaths of one compound path. let mut twice = poly(&square, true); twice.subpaths.extend(poly(&square, true).subpaths); - let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1 }]); + let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1, angle: None }]); assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); assert_eq!(issues[0].keys, vec![1]); assert_eq!(areas(&b[0]), vec![10_000_000]); @@ -549,7 +549,7 @@ fn a_curved_crease_is_measured_at_its_farthest_point_from_its_line() { bp.curve_to(p(10000.0 / 3.0 - off, 10000.0 / 3.0 + off), p(20000.0 / 3.0 + off, 20000.0 / 3.0 - off), p(10000.0, 10000.0)); let lines = vec![ cut(&[(0.0, 0.0), (10000.0, 0.0), (10000.0, 10000.0), (0.0, 10000.0)], 1), - FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2 }, + FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2, angle: None }, ]; let (b, issues) = blanks(&lines, 10.0); assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}"); @@ -1233,3 +1233,202 @@ fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() { assert_eq!(b[0].hinges.len(), 1); assert_eq!(b[0].hinges[0].angle, 90.0); } + +#[test] +fn a_line_s_own_angle_takes_the_place_of_its_kind_s() { + let own = |kind, angle| FoldLine { path: poly(&[(0.0, 0.0), (1.0, 0.0)], false), kind, key: 1, angle }; + assert_eq!(own(LineKind::Crease, Some(45.0)).fold_angle(), Some(45.0)); + assert_eq!(own(LineKind::PartialCut, Some(30.0)).fold_angle(), Some(30.0)); + assert_eq!(own(LineKind::Perforation, Some(-120.0)).fold_angle(), Some(-120.0)); + assert_eq!(own(LineKind::PartialCut, None).fold_angle(), Some(-90.0)); + // An angle that is not a number folds at the kind's; a cut never folds. + assert_eq!(own(LineKind::Crease, Some(f64::NAN)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::Crease, Some(f64::INFINITY)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::Crease, Some(f64::MAX)).fold_angle(), Some(90.0)); + // Past -180 to 180, before rounding, as for an angle the engine stores. + assert_eq!(own(LineKind::Crease, Some(360.0)).fold_angle(), Some(90.0)); + assert_eq!(own(LineKind::PartialCut, Some(-180.0000001)).fold_angle(), Some(-90.0)); + assert_eq!(own(LineKind::Crease, Some(-180.0)).fold_angle(), Some(-180.0)); + assert_eq!(own(LineKind::Cut, Some(45.0)).fold_angle(), None); + // To the millionth of a degree: closer to flat than that is flat. + assert_eq!(own(LineKind::Crease, Some(-179.99999998)).fold_angle(), Some(-180.0)); + assert_eq!(own(LineKind::Crease, Some(179.9999994)).fold_angle(), Some(179.999999)); + assert_eq!(own(LineKind::Crease, Some(-0.0000001)).fold_angle().map(f64::to_bits), Some(0.0f64.to_bits())); +} + +#[test] +fn a_tray_wall_with_its_own_angle_stands_at_that_angle() { + let mut lines = tray(); + // The wall below the base (y 90 to 120) folds at 45°, the others at 90°. + for l in lines.iter_mut().filter(|l| l.key == 12) { + l.angle = Some(45.0); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + for (i, panel) in b.panels.iter().enumerate().filter(|(i, _)| *i != f.base) { + let n = f.panels[i].pose.normal(); + // The cosine of the angle between the wall's print and the base's. + let lower = panel.outline.bounds().is_some_and(|r| r.y0 > 89.0); + let want = if lower { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 }; + assert!((n[2] - want).abs() < 1e-9, "panel {i} ({lower}): {n:?}"); + } + let h = b.hinges.iter().find(|h| h.keys == [12]).expect("the lower wall's hinge"); + assert_eq!(h.angle, 45.0); +} + +#[test] +fn a_hinge_takes_the_angle_of_its_longest_line_however_the_map_splits_it() { + // One hinge along y = 60: a 60 pt crease at 30° and a 40 pt crease at 120°. A crease that + // stops inside the panel above meets the first at x = 30, splitting it into two 30 pt pieces. + let mut lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1), + crease((0.0, 60.0), (60.0, 60.0), 2), + crease((60.0, 60.0), (100.0, 60.0), 3), + crease((30.0, 60.0), (30.0, 90.0), 4), + ]; + lines[1].angle = Some(30.0); + lines[2].angle = Some(120.0); + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}"); + let hinges: Vec<_> = b[0].hinges.iter().filter(|h| h.keys.contains(&2)).collect(); + assert_eq!(hinges.len(), 1, "{:?}", b[0].hinges); + assert_eq!((hinges[0].keys.clone(), hinges[0].angle), (vec![2, 3], 30.0)); +} + +#[test] +fn a_line_s_subpaths_on_top_of_each_other_count_once_toward_the_hinge_angle() { + // One hinge along y = 60: a 40 pt crease at 30° drawn as two subpaths on top of each other, + // and a 60 pt crease at 120°. + let mut twice = poly(&[(0.0, 60.0), (40.0, 60.0)], false); + twice.subpaths.extend(poly(&[(0.0, 60.0), (40.0, 60.0)], false).subpaths); + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1), + FoldLine { path: twice, kind: LineKind::Crease, key: 2, angle: Some(30.0) }, + FoldLine { path: poly(&[(40.0, 60.0), (100.0, 60.0)], false), kind: LineKind::Crease, key: 3, angle: Some(120.0) }, + ]; + let (b, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}"); + assert_eq!(b[0].hinges.len(), 1, "{:?}", b[0].hinges); + assert_eq!(b[0].hinges[0].angle, 120.0); +} + +#[test] +fn lines_of_equal_length_on_one_hinge_give_the_lowest_key_s_angle_in_any_order() { + let mut a = crease((0.0, 60.0), (50.0, 60.0), 5); + a.angle = Some(30.0); + let mut b = crease((50.0, 60.0), (100.0, 60.0), 3); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1); + for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline.clone(), b.clone(), a.clone()]] { + let (blanks, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } + // The same along a diagonal, with the line of the higher key split in two by a crease that + // stops inside a panel: its pieces' lengths (2√2 and 10√2) add up to a little more than the + // other line's (12√2) in floating point. + let mut a = crease((0.0, 0.0), (12.0, 12.0), 5); + a.angle = Some(30.0); + let mut b = crease((12.0, 12.0), (24.0, 24.0), 3); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (24.0, 0.0), (24.0, 24.0), (0.0, 24.0)], 1); + let dangling = crease((2.0, 2.0), (6.0, 3.0), 4); + for lines in [vec![outline.clone(), a.clone(), b.clone(), dangling.clone()], vec![outline, dangling, b, a]] { + let (blanks, issues) = check(&lines); + assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } + // A line 0.0005 pt longer than the other at 1,000,000 pt is longer, not a tie: its angle wins + // over the lower key's. + let mut a = crease((0.0, 60.0), (1_000_000.0, 60.0), 3); + a.angle = Some(30.0); + let end = 2_000_000.000_5; + let mut b = crease((1_000_000.0, 60.0), (end, 60.0), 5); + b.angle = Some(120.0); + let outline = cut(&[(0.0, 0.0), (end, 0.0), (end, 160.0), (0.0, 160.0)], 1); + for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline, b, a]] { + let (blanks, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges); + assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::>()); + } +} + +#[test] +fn a_loop_folded_about_another_panel_stacks_by_the_same_tree_wherever_it_lies() { + // A 100 × 100 blank cut into four 50 pt squares, its creases at 0° but for the one that closes + // the loop about the largest panel, at 0.001°: folded about a panel on that crease, the largest + // panel's tree places the panels up to 0.0009 pt from where the fold's own does. The same at the + // origin and 3,000,000 pt to the right. + let own_tree = |dx: f64| { + let lines = |closing: Option| { + let crease = |a: (f64, f64), b: (f64, f64), key: u64| { + let mut l = crease((a.0 + dx, a.1), (b.0 + dx, b.1), key); + l.angle = Some(if Some(key) == closing { 0.001 } else { 0.0 }); + l + }; + vec![ + cut(&[(dx, 0.0), (100.0 + dx, 0.0), (100.0 + dx, 100.0), (dx, 100.0)], 1), + crease((50.0, 0.0), (50.0, 50.0), 2), + crease((50.0, 50.0), (50.0, 100.0), 3), + crease((0.0, 50.0), (50.0, 50.0), 4), + crease((50.0, 50.0), (100.0, 50.0), 5), + ] + }; + let (b, issues) = check(&lines(None)); + assert!(issues.is_empty(), "{issues:?}"); + let level = fold(&b[0], None, 1.0, TOL).expect("folds"); + let closing = level.hinges.iter().position(|h| !h.tree).expect("a hinge closes the loop"); + let key = b[0].hinges[closing].keys[0]; + let (b, issues) = check(&lines(Some(key))); + assert!(issues.is_empty(), "{issues:?}"); + let f = fold(&b[0], Some(b[0].hinges[closing].a), 1.0, TOL).expect("folds"); + f.stack.root == f.base + }; + assert!(own_tree(0.0), "the trees do not agree, so the fold's own tree"); + assert!(own_tree(3_000_000.0), "far from the origin too"); +} + +#[test] +fn small_panels_far_from_the_middle_of_the_blank_stack_by_the_fold_s_own_tree() { + // A 2 × 2 grid of 5 pt squares at the end of a 1,000 pt strip, the largest panel, joined to the + // grid's right squares. Every crease is at 0° but the one between the two left squares, at a + // millionth of a degree: folded about a panel on it, the strip's tree leaves that crease out + // and places the other square at most 0.0000001 pt from where the fold's own tree does. + let mut lines = vec![ + cut(&[(0.0, 0.0), (1010.0, 0.0), (1010.0, 10.0), (0.0, 10.0)], 1), + crease((5.0, 0.0), (5.0, 5.0), 2), + crease((5.0, 5.0), (5.0, 10.0), 3), + crease((0.0, 5.0), (5.0, 5.0), 4), + crease((5.0, 5.0), (10.0, 5.0), 5), + crease((10.0, 0.0), (10.0, 10.0), 6), + ]; + for l in &mut lines { + l.angle = Some(if l.key == 4 { 0.000001 } else { 0.0 }); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let h = b[0].hinges.iter().find(|h| h.keys == [4]).expect("the left squares' hinge"); + let f = fold(&b[0], Some(h.a), 1.0, TOL).expect("folds"); + assert!(f.hinges.iter().zip(&b[0].hinges).any(|(fh, h)| fh.tree && h.keys == [4])); + assert_eq!(f.stack.root, f.base, "the trees place a panel at different turns"); +} + +#[test] +fn a_negative_angle_folds_a_crease_toward_the_print() { + let mut lines = two_panels(LineKind::Crease, 0, false, false); + for l in lines.iter_mut().filter(|l| l.key == 2) { + l.angle = Some(-90.0); + } + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + let child = 1 - f.base; + let placed = f.panels[child].pose.apply(flat_center(b, child)); + assert!(placed[2] > 0.0, "in front of the print: {placed:?}"); +} diff --git a/crates/tools/Cargo.toml b/crates/tools/Cargo.toml index 96b6a36291..e8b705a54a 100644 --- a/crates/tools/Cargo.toml +++ b/crates/tools/Cargo.toml @@ -8,6 +8,9 @@ description = "VectorCraft tool state machines: pointer events in, commands and [lints] workspace = true +[features] +testing = [] + [dependencies] vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } @@ -21,6 +24,7 @@ serde = { workspace = true } serde_json = { workspace = true } [dev-dependencies] +vectorcraft-tools = { workspace = true, features = ["testing"] } craft-image-codecs = { workspace = true } # The tests lay type out in the bundled fonts (the workspace leaves turning them on to the engine). vectorcraft-text = { workspace = true, features = ["test-fonts", "bundled-fonts"] } diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index db983759b9..d62bc0bd62 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -1,9 +1,9 @@ //! The tools of VectorCraft's built-in add-ons. They aren't in the toolbars as they ship: the All //! Tools drawer lists them (under their add-on's heading) so they can be added, and each add-on's -//! submenu selects them. Tool gestures emit engine commands. Two tools are the exceptions: the Trim -//! at Crossings Tool is in the Scissors tool's group and the Enclosing Lasso Tool is in the Lasso -//! tool's group ([`crate::TOOL_GROUPS`]), where the toolbars and the All Tools drawer show them, as -//! well as in their add-ons' submenus. +//! submenu selects them. Tool gestures emit engine commands. Three tools are the exceptions: the +//! Trim at Crossings Tool is in the Scissors tool's group, the Enclosing Lasso Tool is in the Lasso +//! tool's group and the Smart Pen Tool is in the Pen tool's group ([`crate::TOOL_GROUPS`]), where +//! the toolbars and the All Tools drawer show them, as well as in their add-ons' submenus. pub mod anchor_eraser; pub mod box3d; @@ -35,9 +35,6 @@ pub const PATH_TOOLS: &[ToolInfo] = &[ ToolInfo { id: tangent_circle::ID, label: "Tangent Circle Tool", shortcut: None, icon: "dc-tangent-circle" }, ]; -/// Smart Pen's tool, a flyout group of its own. -pub const SMART_PEN: &[ToolInfo] = &[ToolInfo { id: smart_pen::ID, label: "Smart Pen Tool", shortcut: None, icon: "spline-pointer" }]; - pub const CONTOUR: &[ToolInfo] = &[ToolInfo { id: contour::ID, label: "Contour Tool", shortcut: None, icon: "tool-contour" }]; pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "dc-cube" }]; @@ -48,10 +45,10 @@ pub const POLYGONAL_LASSO: &[ToolInfo] = /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the /// heading the All Tools drawer lists it under (its add-on's name). const HEADED: &[(&[ToolInfo], &str)] = - &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (CONTOUR, "Contour"), (BOX_3D, "3D Box"), (POLYGONAL_LASSO, "Polygonal Lasso")]; + &[(PATH_TOOLS, "Path Precision Tools"), (CONTOUR, "Contour"), (BOX_3D, "3D Box"), (POLYGONAL_LASSO, "Polygonal Lasso")]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]). -pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, CONTOUR, BOX_3D, POLYGONAL_LASSO]; +pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, CONTOUR, BOX_3D, POLYGONAL_LASSO]; /// The heading the All Tools drawer lists tool `id` under: its add-on's name. pub fn heading(id: &str) -> Option<&'static str> { @@ -93,7 +90,6 @@ mod tests { assert!(!crate::TOOL_GROUPS.iter().any(|g| g.iter().any(|x| x.id == t.id)), "{} is not in the toolbar's groups", t.id); } assert!(PATH_TOOLS.iter().all(|t| heading(t.id) == Some("Path Precision Tools"))); - assert_eq!(heading(smart_pen::ID), Some("Smart Pen")); assert_eq!(heading(contour::ID), Some("Contour")); assert_eq!(heading(box3d::ID), Some("3D Box")); assert_eq!(heading(polygonal_lasso::ID), Some("Polygonal Lasso")); @@ -135,4 +131,22 @@ mod tests { assert!(heading(id).is_none(), "not listed again under the add-on"); assert_eq!(crate::catalog::all_tools().filter(|t| t.id == id).count(), 1); } + + /// The Smart Pen Tool is in the Pen tool's group, after the Pen family's own tools, with no + /// default shortcut, listed once, and still made by its add-on. + #[test] + fn smart_pen_is_in_the_pen_group_once() { + let id = smart_pen::ID; + let groups: Vec<_> = crate::TOOL_GROUPS.iter().filter(|g| g.iter().any(|t| t.id == id)).collect(); + assert_eq!(groups.len(), 1); + let ids: Vec<_> = groups[0].iter().map(|t| t.id).collect(); + assert_eq!(ids.first(), Some(&"pen"), "the Pen stays the group's default"); + assert_eq!(ids[ids.len().saturating_sub(2)..], [crate::quickpen::ID, id], "right after the Quick Pen, last"); + let info = crate::tool_info(id).expect("catalogued"); + assert_eq!((info.label, info.shortcut), ("Smart Pen Tool", None)); + assert_eq!(crate::tool_info("pen").and_then(|t| t.shortcut), Some("P"), "the Pen keeps its shortcut"); + assert_eq!(create(id).map(|tool| tool.id()), Some(id)); + assert!(heading(id).is_none(), "not listed again under the add-on"); + assert_eq!(crate::catalog::all_tools().filter(|t| t.id == id).count(), 1); + } } diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index b40cffd8e7..845379311d 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -15,9 +15,23 @@ //! press on the second segment is dropped. Escape, an edit or Undo outside the tool, another //! document, or a change to the first segment that leaves no undo step (a live preview, or one that //! was canceled) forgets the first segment. The circles are looked for again whenever either -//! segment's shape differs from the one they were found on. +//! segment's shape differs from the one they were found on. With the `addPoints` option on (Alt at +//! the release turns it the other way, and a dot beside the pointer shows when it is in effect), the +//! segments the circle touches get an anchor point at each touch, which splits them without changing +//! their shape, in the same undo step as the circle; a touch at an existing anchor adds none. +//! +//! The tool's options (its options dialog, `tool.setOption`; kept with the preferences): `radius`; +//! `addPoints`; `center` and `radii` show or hide the circle's center cross and the lines from its center to the +//! two points it touches; `color` is the color of the circle, the cross, those lines and the note +//! (one of [`COLORS`]); `snapTolerance` is how near (screen pixels) the pointer picks a segment +//! with Smart Guides on, where Smart Guides' Snapping Tolerance counts instead when it is larger, +//! or with Smart Guides off while `snapWithoutGuides` is on. Without snapping a segment is picked +//! within the selection tolerance, as a click on a path picks it, and that is also the least reach +//! snapping has. Of the segments within reach the nearest is picked ([`pick_at`]). By default +//! `addPoints` is off, the cross and the lines show, the color is red, the tolerance is 3 px and +//! `snapWithoutGuides` is on. -use kurbo::{CubicBez, Shape}; +use kurbo::{CubicBez, ParamCurveNearest, Shape}; use serde_json::{Value, json}; use vectorcraft_doc::NodeId; use vectorcraft_geom::{BezPath, ParamCurve, Point}; @@ -42,6 +56,28 @@ pub const NO_CIRCLE: &str = "No tangent circle here"; const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff]; const RED: [u8; 3] = [0xe0, 0x3c, 0x3c]; const GREY: [u8; 3] = [0x80, 0x80, 0x80]; +/// The label of the `addPoints` option in the tool's options. +pub const ADD_POINTS: &str = "Add Points to Existing Paths"; +/// How far (screen pixels) right of and below the pointer the dot shows while `addPoints` is in +/// effect, and its size. +const DOT_PX: f64 = 10.0; +const DOT_SIZE: f32 = 4.0; +/// The colors the `color` option takes, by option value, with the color the circle, its center +/// cross, its radii and the note are drawn in. Red is the first. +pub const COLORS: &[(&str, [u8; 3])] = &[ + ("red", RED), + ("blue", crate::draw2::FEEDBACK), + ("magenta", [0xd6, 0x2c, 0xd6]), + ("green", [0x1f, 0xb4, 0x4b]), + ("black", [0x00, 0x00, 0x00]), + ("gray", GREY), +]; +/// The snapping tolerance the tool starts with (screen pixels). +pub const SNAP_PX: f64 = 3.0; +/// The snapping tolerance the `snapTolerance` option takes (screen pixels). +pub const SNAP_RANGE: (f64, f64) = (0.0, 25.0); +/// The option keys that are true or false. +const SWITCHES: &[&str] = &["addPoints", "center", "radii", "snapWithoutGuides"]; /// A segment under the pointer: where on it, and the segment itself. #[derive(Clone, Debug, PartialEq)] @@ -64,6 +100,9 @@ struct Press { at: Point, /// Whether Shift was held when the click's circle was last looked for. shift: bool, + /// The tool's `radius` when the button went down: Shift uses it for the whole press, whatever + /// `tool.setOption` writes meanwhile. + shift_radius: f64, /// How far the pointer was from the press last time, and the radius the drag set (none until /// the pointer moves far enough). reach: f64, @@ -72,6 +111,19 @@ struct Press { pub struct TangentCircleTool { radius: f64, + /// Whether drawing a circle adds anchor points where it touches the segments. + add_points: bool, + /// The keys held at the last pointer event, and whether the pointer is over the canvas. + mods: Mods, + over: bool, + /// Whether the preview shows the center cross and the radii. + center: bool, + radii: bool, + /// An entry of [`COLORS`]. + color: usize, + /// The snapping tolerance (screen pixels), and whether the tool snaps with Smart Guides off. + snap_px: f64, + snap_without_guides: bool, first: Option, hover: Option, press: Option, @@ -91,13 +143,48 @@ type CacheKey = (NodeId, usize, usize, Option, CubicBez, Vec); impl Default for TangentCircleTool { fn default() -> Self { - Self { radius: RADIUS, first: None, hover: None, press: None, picking: false, found: None, looked: false, pointer: Point::ZERO, cache: None } + Self { + radius: RADIUS, + add_points: false, + mods: Mods::default(), + over: false, + center: true, + radii: true, + color: 0, + snap_px: SNAP_PX, + snap_without_guides: true, + first: None, + hover: None, + press: None, + picking: false, + found: None, + looked: false, + pointer: Point::ZERO, + cache: None, + } } } -/// The path segment under `p`, of any editable path. -fn pick_at(cx: &ToolContext, p: Point) -> Option { - let (id, subpath, segment, t) = crate::draw2::hit_segment(cx, p, cx.pick_tol())?; +/// The nearest path segment within `reach` of `p`, of any editable path; of segments at the same +/// distance, one of a selected path, then the one on top. +fn pick_at(cx: &ToolContext, p: Point, reach: f64) -> Option { + let mut best: Option<((NodeId, usize, usize, f64), f64)> = None; + for id in crate::draw2::candidate_paths(cx) { + let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue }; + // A path whose control points' box, with its edges, lies out of reach holds no point within + // reach. + let near = |b: vectorcraft_geom::Rect| p.x >= b.x0 - reach && p.x <= b.x1 + reach && p.y >= b.y0 - reach && p.y <= b.y1 + reach; + if pd.control_bounds().is_none_or(|b| !near(b)) { + continue; + } + if let Some((subpath, segment, t, _, d)) = pd.nearest(p) + && d <= reach + && best.is_none_or(|(_, b)| d < b) + { + best = Some(((id, subpath, segment, t), d)); + } + } + let ((id, subpath, segment, t), _) = best?; let sp = cx.doc.node(id)?.path_data()?.subpaths.get(subpath)?; if segment >= sp.segment_count() { return None; @@ -120,6 +207,11 @@ fn unchanged(cx: &ToolContext, pick: &Pick) -> bool { /// The segments a circle may touch when `second` is picked: it and the segments on either side of /// it, without `first`. None when `second` is the first segment again. fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { + second_segments(cx, first, second).into_iter().map(|(_, c)| c).collect() +} + +/// [`second_set`] with each segment's index on the second pick's subpath. +fn second_segments(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<(usize, CubicBez)> { if (first.id, first.subpath, first.segment) == (second.id, second.subpath, second.segment) { return vec![]; } @@ -136,7 +228,36 @@ fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { indices.sort_unstable(); indices.dedup(); let is_first = |k: usize| first.id == second.id && first.subpath == second.subpath && first.segment == k; - indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| sp.segment(k)).collect() + indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| (k, sp.segment(k))).collect() +} + +/// Where on `curve` the point `p` lies: its parameter, or none when `p` is within `tol` of either +/// end, where the segment already has an anchor point. +fn split_at(curve: &CubicBez, p: Point, tol: f64) -> Option { + if p.distance(curve.p0) <= tol || p.distance(curve.p3) <= tol { + return None; + } + let t = curve.nearest(p, 1e-12).t; + (t > 0.0 && t < 1.0).then_some(t) +} + +/// The `path.insertAnchor` steps that add an anchor point where circle `c` touches the first segment +/// and the segment of `second` (the segments a circle may touch, with their indices, on the subpath +/// of `pick`) nearest its second touch. On one subpath the later segment comes first, so that the +/// anchor added before it does not move it along. +fn anchor_steps(first: &Pick, pick: &Pick, second: &[(usize, CubicBez)], c: &SegmentCircle, tol: f64) -> Vec { + let mut at: Vec<(NodeId, usize, usize, f64)> = vec![]; + if let Some(t) = split_at(&first.curve, c.first, tol) { + at.push((first.id, first.subpath, first.segment, t)); + } + let nearest = second.iter().min_by(|(_, a), (_, b)| a.nearest(c.second, 1e-12).distance_sq.total_cmp(&b.nearest(c.second, 1e-12).distance_sq)); + if let Some((k, curve)) = nearest + && let Some(t) = split_at(curve, c.second, tol) + { + at.push((pick.id, pick.subpath, *k, t)); + } + at.sort_by_key(|a| std::cmp::Reverse((a.0, a.1, a.2))); + at.into_iter().map(|(id, subpath, segment, t)| json!({ "command": "path.insertAnchor", "params": { "id": id.0, "subpath": subpath, "segment": segment, "t": t } })).collect() } /// Of `circles`, the one touching the second segments nearest `at`, leaving out those [`draw`] cannot @@ -173,6 +294,14 @@ fn round_step(least: f64) -> f64 { /// distance from the origin, or too large, in floating point), or when the circle would reach past /// the canvas ([`crate::circle::circle_of`]), which the command refuses. fn draw(c: &SegmentCircle, tol: f64) -> Option { + circle_params(c, tol).map(|p| Action::Exec(CIRCLE.into(), p)) +} + +/// The command [`draw`] runs. +const CIRCLE: &str = "shape.circleThroughPoints"; + +/// The params of the [`CIRCLE`] command that [`draw`] runs. +fn circle_params(c: &SegmentCircle, tol: f64) -> Option { let (at, r) = (c.circle.center, c.circle.radius); let points: Vec = [90.0f64, 210.0, 330.0] .iter() @@ -186,7 +315,7 @@ fn draw(c: &SegmentCircle, tol: f64) -> Option { return None; } let points: Vec<[f64; 2]> = points.iter().map(|p| [p.x, p.y]).collect(); - Some(Action::Exec("shape.circleThroughPoints".into(), json!({ "points": points }))) + Some(json!({ "points": points })) } fn segment_path(c: &CubicBez) -> BezPath { @@ -197,6 +326,26 @@ fn segment_path(c: &CubicBez) -> BezPath { } impl TangentCircleTool { + /// How near (document units) the pointer picks a segment: with Smart Guides on, the snapping + /// tolerance or Smart Guides' Snapping Tolerance, whichever is larger; with them off, the + /// snapping tolerance while `snapWithoutGuides` is on, and otherwise none. Never less than the + /// selection tolerance. + fn reach(&self, cx: &ToolContext) -> f64 { + let pick = cx.pick_tol(); + if cx.smart_guides { + pick.max(cx.tol(self.snap_px)).max(cx.snap_tol()) + } else if self.snap_without_guides { + pick.max(cx.tol(self.snap_px)) + } else { + pick + } + } + + /// The color the preview is drawn in. + fn preview_color(&self) -> [u8; 3] { + COLORS.get(self.color).map_or(RED, |(_, rgb)| *rgb) + } + /// The radius a drag gives, with Shift in round steps. fn shown_radius(cx: &ToolContext, r: f64, shift: bool) -> f64 { if !shift { @@ -252,8 +401,8 @@ impl TangentCircleTool { // A change without an undo step since the press: a changed first segment is forgotten (the // press then draws nothing), and the circle follows the segments it may touch as they are now. self.forget_if_changed(cx); - let radius = self.radius; let (Some(first), Some(press)) = (&self.first, &mut self.press) else { return }; + let radius = press.shift_radius; // A pressed segment that is gone leaves nothing to touch. let second = if segment_now(cx, &press.pick).is_some() { second_set(cx, first, &press.pick) } else { vec![] }; let moved = second != press.second; @@ -302,14 +451,16 @@ impl Tool for TangentCircleTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.pointer = ev.pos; + self.mods = ev.mods; + self.over = true; match ev.kind { PointerKind::Move => { - self.hover = pick_at(cx, ev.pos); + self.hover = pick_at(cx, ev.pos, self.reach(cx)); self.look(cx, ev.pos, ev.mods); vec![] } PointerKind::Down => { - let Some(pick) = pick_at(cx, ev.pos) else { return vec![] }; + let Some(pick) = pick_at(cx, ev.pos, self.reach(cx)) else { return vec![] }; self.forget_if_changed(cx); let Some(first) = self.first.clone() else { self.first = Some(pick); @@ -324,7 +475,7 @@ impl Tool for TangentCircleTool { self.found = nearest_to(found, ev.pos, cx.tol(DRAW_PX)); self.looked = true; self.hover = None; - self.press = Some(Press { pick, second, at: ev.pos, shift: ev.mods.shift, reach: 0.0, radius: None }); + self.press = Some(Press { pick, second, at: ev.pos, shift: ev.mods.shift, shift_radius: self.radius, reach: 0.0, radius: None }); vec![] } PointerKind::Drag => { @@ -335,15 +486,34 @@ impl Tool for TangentCircleTool { // The release's own position and keys set the radius of a drag. self.drag_to(cx, ev); self.picking = false; - if self.press.take().is_none() { - return vec![]; - } + let Some(press) = self.press.take() else { return vec![] }; // No circle, or one the three points cannot draw: the first segment stays picked, // for another try. It also stays when the command fails: only a drawn circle tells // the tool (`notify`) to forget it. - let Some(action) = self.found.take().and_then(|c| draw(&c, cx.tol(DRAW_PX))) else { return vec![] }; + let Some(c) = self.found.take() else { return vec![] }; + let Some(params) = circle_params(&c, cx.tol(DRAW_PX)) else { return vec![] }; self.looked = false; - vec![action, Action::Notify(DRAWN.into())] + // Alt at the release turns `addPoints` the other way. + let steps = match &self.first { + Some(first) if self.add_points != ev.mods.alt => { + let second = if segment_now(cx, &press.pick).is_some() { second_segments(cx, first, &press.pick) } else { vec![] }; + anchor_steps(first, &press.pick, &second, &c, cx.tol(DRAW_PX)) + } + _ => vec![], + }; + if steps.is_empty() { + return vec![Action::Exec(CIRCLE.into(), params), Action::Notify(DRAWN.into())]; + } + let mut commands = steps; + // A path that was not selected becomes the selection when it gets an anchor; the + // selection is put back before the circle, which Draw Behind places behind it. + if commands.iter().any(|s| s["params"]["id"].as_u64().is_some_and(|id| !cx.selection.contains(NodeId(id)))) { + let ids: Vec = cx.selection.objects.iter().map(|id| id.0).collect(); + commands.push(json!({ "command": "select.set", "params": { "ids": ids } })); + } + commands.push(json!({ "command": CIRCLE, "params": params })); + // One undo step for the anchors and the circle, and none of them when a step fails. + vec![Action::Exec("command.batch".into(), json!({ "label": "Ellipse", "commands": commands })), Action::Notify(DRAWN.into())] } // The canvas sends a double-click after the second click's `Up`, which drew the circle. PointerKind::DoubleClick | PointerKind::TripleClick => vec![], @@ -394,6 +564,7 @@ impl Tool for TangentCircleTool { fn hover_ended(&mut self, _cx: &ToolContext) { self.hover = None; + self.over = false; if self.press.is_none() { self.found = None; self.looked = false; @@ -415,21 +586,31 @@ impl Tool for TangentCircleTool { { out.push(Overlay::Line { a: press.at, b: self.pointer, color: GREY, dashed: false }); } + let color = self.preview_color(); if let Some(c) = &self.found { let (at, r) = (c.circle.center, c.circle.radius); // A tolerance of at least a ten-thousandth of the radius keeps a huge circle to a few // dozen segments. let tol = cx.tol(0.1).max(r * 1e-4); - out.push(Overlay::Path { path: kurbo::Circle::new(at, r).to_path(tol), color: RED, width: 1.0, dashed: false }); - let arm = cx.tol(4.0); - out.push(Overlay::Line { a: at - kurbo::Vec2::new(arm, 0.0), b: at + kurbo::Vec2::new(arm, 0.0), color: RED, dashed: false }); - out.push(Overlay::Line { a: at - kurbo::Vec2::new(0.0, arm), b: at + kurbo::Vec2::new(0.0, arm), color: RED, dashed: false }); - out.push(Overlay::Line { a: at, b: c.first, color: RED, dashed: true }); - out.push(Overlay::Line { a: at, b: c.second, color: RED, dashed: true }); + out.push(Overlay::Path { path: kurbo::Circle::new(at, r).to_path(tol), color, width: 1.0, dashed: false }); + if self.center { + let arm = cx.tol(4.0); + out.push(Overlay::Line { a: at - kurbo::Vec2::new(arm, 0.0), b: at + kurbo::Vec2::new(arm, 0.0), color, dashed: false }); + out.push(Overlay::Line { a: at - kurbo::Vec2::new(0.0, arm), b: at + kurbo::Vec2::new(0.0, arm), color, dashed: false }); + } + if self.radii { + out.push(Overlay::Line { a: at, b: c.first, color, dashed: true }); + out.push(Overlay::Line { a: at, b: c.second, color, dashed: true }); + } out.push(Overlay::Measure { p: self.pointer, text: format!("R: {}", cx.len(r)) }); } else if self.looked { // A label, which the canvas shows in the interface language. - out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color: RED }); + out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color }); + } + // `addPoints` in effect, with Alt as it is now. + if (self.over || self.press.is_some()) && self.add_points != self.mods.alt { + let off = cx.tol(DOT_PX); + out.push(Overlay::CurvePoint { p: self.pointer + kurbo::Vec2::new(off, off), color: BLUE, filled: true, size: DOT_SIZE }); } out } @@ -439,14 +620,31 @@ impl Tool for TangentCircleTool { } fn options(&self) -> Value { - json!({ "radius": self.radius }) + json!({ + "radius": self.radius, + "addPoints": self.add_points, + "center": self.center, + "radii": self.radii, + "color": COLORS.get(self.color).map_or("red", |(name, _)| *name), + "snapTolerance": self.snap_px, + "snapWithoutGuides": self.snap_without_guides, + }) } + /// Sets one option; a value the option does not take leaves it as it was. fn set_option(&mut self, key: &str, v: &Value) { - if key == "radius" - && let Some(r) = v.as_f64().filter(|r| (RADIUS_RANGE.0..=RADIUS_RANGE.1).contains(r)) - { - self.radius = r; + if self.check_option(key, v).is_err() { + return; + } + match key { + "radius" => self.radius = v.as_f64().unwrap_or(self.radius), + "addPoints" => self.add_points = v.as_bool().unwrap_or(self.add_points), + "center" => self.center = v.as_bool().unwrap_or(self.center), + "radii" => self.radii = v.as_bool().unwrap_or(self.radii), + "color" => self.color = v.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)).unwrap_or(self.color), + "snapTolerance" => self.snap_px = v.as_f64().unwrap_or(self.snap_px), + "snapWithoutGuides" => self.snap_without_guides = v.as_bool().unwrap_or(self.snap_without_guides), + _ => {} } } @@ -454,6 +652,9 @@ impl Tool for TangentCircleTool { use crate::option_check as c; match key { "radius" => c::number(key, v, RADIUS_RANGE.0, RADIUS_RANGE.1), + "snapTolerance" => c::number(key, v, SNAP_RANGE.0, SNAP_RANGE.1), + "color" => c::one_of(key, v, &COLORS.iter().map(|(name, _)| *name).collect::>()), + k if SWITCHES.contains(&k) => c::boolean(key, v), _ => Err(c::unknown(key)), } } @@ -598,6 +799,141 @@ mod tests { assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}"); } + #[test] + fn a_press_keeps_the_radius_it_started_with() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.set_option("radius", &json!(20)); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &shifted(PointerKind::Down, 200.0, 139.0)); + // A radius written during the press does not reach the circle, however Shift changes. + t.set_option("radius", &json!(5)); + t.pointer(&cx, &ev(PointerKind::Drag, 200.0, 139.0)); + t.pointer(&cx, &shifted(PointerKind::Drag, 200.0, 139.0)); + let released = up(&mut t, &cx, &shifted(PointerKind::Up, 200.0, 139.0)); + assert!(close(drawn(&released), (180.0, 100.0, 40.0, 40.0)), "{released:?}"); + } + + #[test] + fn the_preview_options_set_its_cross_radii_and_color() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let green = COLORS.iter().find(|(name, _)| *name == "green").map(|(_, rgb)| *rgb); + let lines = + |ov: &[Overlay], dashed_lines: bool| ov.iter().filter(|o| matches!(o, Overlay::Line { dashed, .. } if *dashed == dashed_lines)).count(); + let mut t = TangentCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Move, 200.0, 139.0)); + // By default: the red circle, its center cross (two lines) and its two radii. + let ov = t.overlays(&cx); + assert_eq!((lines(&ov, false), lines(&ov, true)), (2, 2), "{ov:?}"); + assert!(ov.iter().any(|o| matches!(o, Overlay::Path { color, width, .. } if *color == RED && *width == 1.0)), "{ov:?}"); + t.set_option("center", &json!(false)); + let ov = t.overlays(&cx); + assert_eq!((lines(&ov, false), lines(&ov, true)), (0, 2), "no cross: {ov:?}"); + t.set_option("radii", &json!(false)); + t.set_option("color", &json!("green")); + let ov = t.overlays(&cx); + assert_eq!((lines(&ov, false), lines(&ov, true)), (0, 0), "no radii: {ov:?}"); + assert!(ov.iter().any(|o| matches!(o, Overlay::Path { color, .. } if Some(*color) == green)), "{ov:?}"); + assert!(ov.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("R: 20.00"))), "the radius still shows: {ov:?}"); + // The note takes the color too. + t.set_option("radius", &json!(5)); + t.pointer(&cx, &shifted(PointerKind::Move, 200.0, 140.0)); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Label { text, color, .. } if text == NO_CIRCLE && Some(*color) == green))); + } + + #[test] + fn the_preview_and_snap_options_take_only_their_values() { + let mut t = TangentCircleTool::default(); + let o = t.options(); + assert_eq!( + (&o["center"], &o["radii"], &o["color"], &o["snapTolerance"], &o["snapWithoutGuides"]), + (&json!(true), &json!(true), &json!("red"), &json!(3.0), &json!(true)) + ); + for (key, good) in [ + ("center", json!(false)), + ("radii", json!(false)), + ("snapWithoutGuides", json!(false)), + ("color", json!("gray")), + ("snapTolerance", json!(0)), + ("snapTolerance", json!(25)), + ("snapTolerance", json!(7.5)), + ] { + assert_eq!(t.check_option(key, &good), Ok(()), "{key} {good}"); + t.set_option(key, &good); + let now = t.options()[key].clone(); + assert!(now == good || (good.is_number() && now.as_f64() == good.as_f64()), "{key}: {now} for {good}"); + } + let colors = "`color` must be one of `red`, `blue`, `magenta`, `green`, `black`, `gray`"; + for (key, bad, error) in [ + ("center", json!(1), "`center` must be true or false"), + ("radii", json!("no"), "`radii` must be true or false"), + ("snapWithoutGuides", Value::Null, "`snapWithoutGuides` must be true or false"), + ("color", json!("orange"), colors), + ("color", json!("Red"), colors), + ("color", json!(0), colors), + ("snapTolerance", json!(-1), "`snapTolerance` must be a number from 0 to 25"), + ("snapTolerance", json!(26), "`snapTolerance` must be a number from 0 to 25"), + ("snapTolerance", json!("3"), "`snapTolerance` must be a number from 0 to 25"), + ] { + assert_eq!(t.check_option(key, &bad), Err(error.into()), "{key} {bad}"); + let before = t.options(); + t.set_option(key, &bad); + assert_eq!(t.options(), before, "{key} {bad}"); + } + } + + #[test] + fn the_snap_options_set_how_near_a_segment_is_picked() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + // At 100%, Selection Tolerance 3 px; the first line is at y = 100. + let picks = |t: &mut TangentCircleTool, cx: &ToolContext, y: f64| { + t.forget(); + t.pointer(cx, &ev(PointerKind::Down, 150.0, y)); + t.pointer(cx, &ev(PointerKind::Up, 150.0, y)); + t.first.is_some() + }; + let guides = |tolerance: f64| ToolContext { smart_guides: true, snapping_tolerance: tolerance, ..cx(&d, &sel, &p) }; + let no_guides = ToolContext { smart_guides: false, ..cx(&d, &sel, &p) }; + let mut t = TangentCircleTool::default(); + // Smart Guides on: their Snapping Tolerance when it is larger than the tool's. + assert!(picks(&mut t, &guides(10.0), 109.0)); + assert!(!picks(&mut t, &guides(10.0), 111.0)); + t.set_option("snapTolerance", &json!(12)); + assert!(picks(&mut t, &guides(4.0), 111.0), "the tool's when it is larger"); + assert!(!picks(&mut t, &guides(4.0), 113.0)); + // Smart Guides off: the tool's tolerance while it snaps without them. + t.set_option("snapTolerance", &json!(8)); + assert!(picks(&mut t, &no_guides, 107.0)); + assert!(!picks(&mut t, &no_guides, 109.0)); + // Without snapping, only the Selection Tolerance; a tolerance below it does not shrink it. + t.set_option("snapWithoutGuides", &json!(false)); + assert!(!picks(&mut t, &no_guides, 105.0)); + assert!(picks(&mut t, &no_guides, 102.5)); + t.set_option("snapWithoutGuides", &json!(true)); + t.set_option("snapTolerance", &json!(0)); + assert!(picks(&mut t, &no_guides, 102.5)); + // Over the gap between the two lines, the nearer one is picked, though both are in reach. + t.set_option("snapTolerance", &json!(25)); + t.forget(); + t.pointer(&no_guides, &ev(PointerKind::Move, 150.0, 122.0)); + assert!(t.hover.as_ref().is_some_and(|h| (h.p.y - 140.0).abs() < 1e-9), "{:?}", t.hover); + t.pointer(&no_guides, &ev(PointerKind::Move, 150.0, 118.0)); + assert!(t.hover.as_ref().is_some_and(|h| (h.p.y - 100.0).abs() < 1e-9), "{:?}", t.hover); + // A segment exactly at the reach is in reach, on either side of it. + t.pointer(&no_guides, &ev(PointerKind::Move, 150.0, 75.0)); + assert!(t.hover.as_ref().is_some_and(|h| (h.p.y - 100.0).abs() < 1e-9), "{:?}", t.hover); + t.pointer(&no_guides, &ev(PointerKind::Move, 150.0, 165.0)); + assert!(t.hover.as_ref().is_some_and(|h| (h.p.y - 140.0).abs() < 1e-9), "{:?}", t.hover); + } + #[test] fn a_drag_sets_the_radius_with_shift_steps_and_a_slow_drag() { let d = doc(); @@ -812,6 +1148,144 @@ mod tests { assert!(matches!(segments[..], [n] if n < 100), "{segments:?}"); } + /// The steps of the `command.batch` an action list runs: (command, params) each. + fn batch_steps(actions: &[Action]) -> Vec<(String, Value)> { + let [Action::Exec(cmd, p), Action::Notify(what)] = actions else { panic!("{actions:?}") }; + assert_eq!((cmd.as_str(), what.as_str()), ("command.batch", DRAWN)); + p["commands"].as_array().unwrap().iter().map(|s| (s["command"].as_str().unwrap().to_string(), s["params"].clone())).collect() + } + + /// An inserted anchor's place: (path, subpath, segment) and the point at its `t` on that segment. + fn inserted(cx: &ToolContext, params: &Value) -> (u64, u64, u64, Point) { + let (id, sub, seg) = (params["id"].as_u64().unwrap(), params["subpath"].as_u64().unwrap(), params["segment"].as_u64().unwrap()); + let sp = &cx.doc.node(NodeId(id)).unwrap().path_data().unwrap().subpaths[sub as usize]; + (id, sub, seg, sp.segment(seg as usize).eval(params["t"].as_f64().unwrap())) + } + + fn alt(mut e: PointerEvent) -> PointerEvent { + e.mods.alt = true; + e + } + + #[test] + fn add_points_adds_an_anchor_where_the_circle_touches_each_segment() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let line_at = |y: f64| pick_at(&cx, Point::new(150.0, y), cx.pick_tol()).map(|p| p.id.0).unwrap(); + let (top, below) = (line_at(100.0), line_at(140.0)); + let mut t = TangentCircleTool::default(); + t.set_option("addPoints", &json!(true)); + assert_eq!(t.options()["addPoints"], json!(true)); + // The circle through (150, 100) touching the line below at (150, 140): an anchor a quarter + // along each line, then the circle, in one batch. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + let steps = batch_steps(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0))); + assert_eq!(steps.len(), 4, "{steps:?}"); + assert!(steps[..2].iter().all(|(c, _)| c == "path.insertAnchor"), "{steps:?}"); + let mut anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect(); + anchors.sort_by_key(|a| a.0); + let mut want = [(top, 0, 0, Point::new(150.0, 100.0)), (below, 0, 0, Point::new(150.0, 140.0))]; + want.sort_by_key(|a| a.0); + assert!(top != below && anchors.iter().zip(want).all(|(a, b)| (a.0, a.1, a.2) == (b.0, b.1, b.2) && a.3.distance(b.3) < 1e-6), "{anchors:?}"); + // The lines were not selected, so the selection (none) is put back before the circle. + assert_eq!(steps[2], ("select.set".to_string(), json!({ "ids": [] })), "{steps:?}"); + let (cmd, params) = &steps[3]; + let circle = drawn(&[Action::Exec(cmd.clone(), params.clone()), Action::Notify(DRAWN.into())]); + assert!(close(circle, (130.0, 100.0, 40.0, 40.0)), "{steps:?}"); + assert!(t.first.is_none(), "ready for the next circle"); + // With both lines selected, the anchors leave the selection as it is: no step puts it back. + let mut both = Selection::default(); + both.add(NodeId(top)); + both.add(NodeId(below)); + let selected = self::cx(&d, &both, &p); + t.pointer(&selected, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&selected, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&selected, &ev(PointerKind::Down, 200.0, 139.0)); + let steps = batch_steps(&up(&mut t, &selected, &ev(PointerKind::Up, 200.0, 139.0))); + assert!(steps.len() == 3 && steps[2].0 == CIRCLE, "{steps:?}"); + // Alt at the release turns it off for that circle, and with the option off turns it on. + for (on, alt_up, adds) in [(true, true, false), (false, true, true), (false, false, false)] { + t.set_option("addPoints", &json!(on)); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + t.pointer(&cx, &alt(ev(PointerKind::Drag, 200.0, 139.0))); + let release = if alt_up { alt(ev(PointerKind::Up, 200.0, 139.0)) } else { ev(PointerKind::Up, 200.0, 139.0) }; + let released = up(&mut t, &cx, &release); + if adds { + assert_eq!(batch_steps(&released).len(), 4, "on {on}, Alt {alt_up}: {released:?}"); + } else { + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "on {on}, Alt {alt_up}: {released:?}"); + } + } + } + + #[test] + fn add_points_on_one_path_adds_the_later_anchor_first_and_none_at_an_anchor() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.set_option("addPoints", &json!(true)); + t.set_option("radius", &json!(10)); + // The L's corner circle of radius 10 touches (290, 300) on its first segment and (300, 310) + // on its second: the second segment's anchor comes first, so the first one's index holds. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &shifted(PointerKind::Down, 300.0, 350.0)); + let steps = batch_steps(&up(&mut t, &cx, &shifted(PointerKind::Up, 300.0, 350.0))); + assert_eq!(steps.len(), 4, "{steps:?}"); + let l = pick_at(&cx, Point::new(300.0, 350.0), cx.pick_tol()).map(|p| p.id.0); + let anchors: Vec<(u64, u64, u64, Point)> = steps[..2].iter().map(|(_, p)| inserted(&cx, p)).collect(); + let want = [(1, Point::new(300.0, 310.0)), (0, Point::new(290.0, 300.0))]; + assert!(anchors.iter().zip(want).all(|(a, (seg, at))| Some(a.0) == l && a.1 == 0 && a.2 == seg && a.3.distance(at) < 1e-6), "{anchors:?}"); + assert_eq!((steps[2].0.as_str(), steps[3].0.as_str()), ("select.set", CIRCLE)); + // A circle touching both lines at their right ends: no anchor is added on top of an anchor, + // so only the circle is drawn, as without the option. + t.set_option("radius", &json!(36)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 300.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 299.0, 139.0)); + let released = up(&mut t, &cx, &ev(PointerKind::Up, 299.0, 139.0)); + assert!(close(drawn(&released), (280.0, 100.0, 40.0, 40.0)), "{released:?}"); + } + + #[test] + fn add_points_shows_a_dot_and_is_an_option_that_refuses_other_values() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + assert_eq!(t.options()["addPoints"], json!(false), "off to start"); + let dot = + |t: &TangentCircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::CurvePoint { filled: true, color, .. } if *color == BLUE)); + t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0)); + assert!(!dot(&t)); + // Alt turns it on while held, and back off with the option on. + t.pointer(&cx, &alt(ev(PointerKind::Move, 50.0, 50.0))); + assert!(dot(&t)); + t.set_option("addPoints", &json!(true)); + assert!(!dot(&t)); + t.pointer(&cx, &ev(PointerKind::Move, 50.0, 50.0)); + assert!(dot(&t)); + let Some(Overlay::CurvePoint { p, .. }) = t.overlays(&cx).into_iter().find(|o| matches!(o, Overlay::CurvePoint { .. })) else { + panic!("no dot") + }; + assert!(p.x > 50.0 && p.y > 50.0, "beside the pointer: {p:?}"); + // The pointer off the canvas: no dot left behind. + t.hover_ended(&cx); + assert!(!dot(&t)); + for bad in [json!(1), json!("true"), Value::Null] { + assert_eq!(t.check_option("addPoints", &bad), Err("`addPoints` must be true or false".into()), "{bad}"); + t.set_option("addPoints", &bad); + assert_eq!(t.options()["addPoints"], json!(true), "{bad}"); + } + assert_eq!(t.check_option("addPoints", &json!(false)), Ok(())); + } + #[test] fn a_circle_that_would_reach_past_the_canvas_is_not_offered() { // Two lines 40 pt apart ending at the canvas edge, x = 4,000,000: a click at x the first gives diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index cec57b2887..cdc7f6f7dc 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -33,6 +33,9 @@ mod live_paint; mod lookup; mod map; +#[cfg(all(feature = "testing", not(target_arch = "wasm32")))] +pub mod testing; + use cache::{BACKGROUND_SEGMENTS, CacheKey, RegionCache}; pub use fill_area::{AreaFinder, EnclosedArea, FillAreaTool, every_layer, fill_area_roots}; #[cfg(test)] @@ -260,7 +263,13 @@ struct PendingMerge { #[cfg(not(target_arch = "wasm32"))] fn spawn_merge(map: Arc, touched: Touched, gap: f64, inputs: Vec) -> Option> { let (tx, done) = std::sync::mpsc::channel(); + #[cfg(feature = "testing")] + let gate = testing::take(); let spawned = std::thread::Builder::new().name("vectorcraft-shape-builder-merge".into()).spawn(move || { + #[cfg(feature = "testing")] + if let Some(gate) = gate { + gate.wait(); + } // The tool may have dropped the receiver meanwhile (another tool, another document). let _ = tx.send(merge_geometry(&map, &touched, gap, &inputs)); }); diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index f535bd0aa3..adb16b8f79 100644 --- a/crates/tools/src/builder/fill_area.rs +++ b/crates/tools/src/builder/fill_area.rs @@ -2,6 +2,7 @@ //! closed path of that area with the current fill and stroke (`shapeBuilder.copyRegion`). The //! paths around the area stay as they are, and nothing needs to be selected. +use vectorcraft_geom::kurbo::ParamCurveDeriv; use vectorcraft_geom::path::segment_bounds; use vectorcraft_geom::{ParamCurve, PathSeg}; @@ -74,7 +75,8 @@ struct Reach<'a> { face: &'a PathData, bez: &'a vectorcraft_geom::kurbo::BezPath, zone: Rect, - /// How close (pt) to the outline a path may come and still change the area: the gap and 1 pt. + /// How close (pt) to the outline a path may come and still change the area: the gap and + /// [`CONTACT`]. reach: f64, } @@ -146,6 +148,100 @@ fn within(inner: &Rect, outer: &Rect) -> bool { inner.x0 >= outer.x0 && inner.x1 <= outer.x1 && inner.y0 >= outer.y0 && inner.y1 <= outer.y1 } +/// The outlines of the clipping masks [`unmasked`] has read, by the clipping group or clipped +/// layer: None for one whose mask clips to nothing, which hides all it clips. +type Masks = std::collections::HashMap>; + +/// `shape`, the outline of `leaf`, cut to where every clipping mask around `leaf` shows it +/// ([`clip_to`]). A path in a mask is not cut by that mask. None when the masks hide all of it. +fn unmasked(doc: &Document, leaf: &Node, mut shape: po::Shape, masks: &mut Masks) -> Option { + let Some(line) = doc.ancestry(leaf.id) else { return Some(shape) }; + let filled = leaf.appearance.has_drawn_fill(); + for a in line.iter().filter(|a| **a != leaf.id) { + let Some(n) = doc.node(*a).filter(|n| n.clips()) else { continue }; + let Some(mask) = n.children().and_then(|c| c.first()) else { continue }; + if line.contains(&mask.id) { + continue; + } + let outline = masks.entry(*a).or_insert_with(|| { + vectorcraft_effects::clip_outline(mask).map(|(bp, rule)| (PathData::from_bezpath(&bp), rule)).filter(|(p, _)| !p.is_empty()) + }); + let (m, rule) = outline.as_ref()?; + shape = clip_to(shape, filled, m, *rule)?; + } + Some(shape) +} + +/// How far (pt) the middle of a piece of an outline may lie from a mask's outline and still count +/// as on the mask's edge, which [`clip_to`] keeps. It covers rounding only, so a piece just outside +/// the mask is still left out. +const ON_MASK: f64 = 1e-6; + +/// How far (pt) to each side of a piece [`shows_through`] looks for the mask's filled area: past +/// [`ON_MASK`], and within a filled strip of the mask as narrow as this. +const MASK_SIDE: f64 = 1e-4; + +/// Does the piece of an outline whose middle is `p`, running in direction `dir` there, show +/// through `mask` filled with `rule`? A piece off the mask's outline shows when the filled area +/// holds `p`. A piece on the outline ([`ON_MASK`]) shows when the filled area lies on one side of +/// it ([`MASK_SIDE`]), so every side of a square clipped by the same square shows, and an outline +/// of the mask that bounds no filled area (two copies of one outline under even-odd) hides it. +fn shows_through(mask: &PathData, rule: FillRule, p: Point, dir: vectorcraft_geom::Vec2) -> bool { + if !mask.nearest(p).is_some_and(|(.., d)| d <= ON_MASK) { + return path_contains(mask, rule, p); + } + let len = dir.hypot(); + if !(len > 0.0 && len.is_finite()) { + return false; + } + let side = dir.turn_90() * (MASK_SIDE / len); + path_contains(mask, rule, p + side) || path_contains(mask, rule, p - side) +} + +/// `shape` cut to `mask` (filled with `rule`). With `filled` (the path's fill draws), its closed +/// subpaths are cut to their overlap with the mask, whose edge then bounds the fill. Its other +/// subpaths, and every subpath of a path without a fill, are cut to their pieces inside the mask or +/// on its edge ([`shows_through`]), so a hidden part of an outline does not close an area. A +/// subpath with more segments or crossings than [`po::addons::pathtools::crossings_on`] takes is +/// left out. None when nothing of it is inside. +pub(super) fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> Option { + let (b, mb) = (shape.path.bounds()?, mask.bounds()?); + if !meet(&b, &mb) { + return None; + } + let (closed, lines): (Vec, Vec) = shape.path.subpaths.into_iter().partition(|sp| filled && sp.closed); + let had_closed = !closed.is_empty(); + let mut subs = if had_closed { po::boolean(&PathData::new(closed), shape.rule, mask, rule, po::BoolOp::Intersect).subpaths } else { vec![] }; + for sp in lines { + let one = PathData::new(vec![sp]); + // A subpath whose crossings with the mask are past what can be found is left out, so no + // part of it the mask hides bounds an area. + let Some(crossed) = po::addons::pathtools::crossings_on(&one, &[mask]) else { continue }; + let places: Vec<(usize, f64)> = crossed.into_iter().map(|(_, s, t)| (s, t)).collect(); + let Some(sp) = one.subpaths.first() else { continue }; + let (cut, at) = po::addons::pathtools::insert_at(sp, &places); + subs.extend(cut.cut_at(&at).into_iter().filter(|piece| { + let n = piece.segment_count(); + n > 0 && { + let seg = piece.segment(n / 2); + // Where the tangent vanishes (a cusp at the middle), the curve runs along its second + // derivative there, and a straight segment with that degenerate form along its chord. + let d1 = seg.deriv(); + let dir = [d1.eval(0.5).to_vec2(), d1.deriv().eval(0.5).to_vec2(), seg.p3 - seg.p0] + .into_iter() + .find(|v| v.hypot2() > 0.0) + .unwrap_or_default(); + shows_through(mask, rule, seg.eval(0.5), dir) + } + })); + } + if subs.is_empty() { + return None; + } + let rule = if had_closed { FillRule::NonZero } else { shape.rule }; + Some(po::Shape::new(PathData::new(subs), rule, shape.key)) +} + /// The object directly in `scope` (the isolated object in isolation mode), or else directly in a /// layer (or sublayer), that holds `id`: `id` itself when `scope` or a layer holds it, or when `id` /// is `scope`. @@ -217,7 +313,8 @@ pub fn fill_area_roots(doc: &Document, isolation: Option, named: Option< impl AreaFinder { /// The finder over the paths of `roots` (layers or objects) that the Shape Builder takes: /// visible, unlocked paths, compound paths and Live Paint faces and edges that draw, not on a - /// locked artboard. Gaps up to `gap` close, and with `open_filled_as_closed` a filled open path + /// locked artboard. A path a clipping mask clips counts only where the mask shows it + /// ([`unmasked`]). Gaps up to `gap` close, and with `open_filled_as_closed` a filled open path /// bounds an area as if an invisible edge closed it. With `scope` (the isolated object in /// isolation mode), an area's new path goes directly above the object in `scope` that holds the /// front-most path along it, so it stays inside the isolated object. @@ -225,11 +322,13 @@ impl AreaFinder { let roots = sorted_roots(doc, roots); let (shapes, leaves) = shape_builder_shapes(doc, &roots, open_filled_as_closed); let editable = doc.editable(); + let mut masks = Masks::new(); let inputs: Vec<(po::Shape, Rect, NodeId)> = shapes .into_iter() .zip(leaves) .filter(|(_, l)| editable(l.id)) .filter_map(|(s, l)| { + let s = unmasked(doc, l, s, &mut masks)?; let b = s.path.bounds()?; Some((s, b, outermost(doc, l.id, scope))) }) @@ -298,13 +397,15 @@ impl AreaFinder { let before = window; match bounds { // A path left out that crosses the area or comes within its reach could cut it, and - // only the map of every path holds both. + // only the map of every path holds both. A bridge reaches at most `gap`, so a path + // farther than that from the outline, give or take [`CONTACT`], does not change it. Some(rb) if within(&rb, &window) => { - let reached = rb.inflate(reach, reach); + let contact = self.gap + CONTACT; + let reached = rb.inflate(contact, contact); let mut budget = CUT_BUDGET; let cut = any_left_out && face.is_none_or(|(region, bez, _)| { - let area = Reach { face: ®ion.path, bez, zone: reached, reach }; + let area = Reach { face: ®ion.path, bez, zone: reached, reach: contact }; self.inputs.iter().zip(&left_out).any(|((s, b, _), out)| *out && meet(b, &reached) && cuts(&s.path, &area, &mut budget)) }); if !cut { diff --git a/crates/tools/src/builder/testing.rs b/crates/tools/src/builder/testing.rs new file mode 100644 index 0000000000..a378014e32 --- /dev/null +++ b/crates/tools/src/builder/testing.rs @@ -0,0 +1,75 @@ +//! Channel control for the next Shape Builder merge started on the calling thread. + +use std::cell::RefCell; +use std::marker::PhantomData; +use std::rc::Rc; +use std::sync::Arc; +use std::sync::mpsc::{Receiver, RecvError, Sender, channel}; + +thread_local! { + static NEXT: RefCell> = const { RefCell::new(None) }; +} + +/// Holds a merge worker until released. Dropping the gate also releases the worker. +pub struct MergeGate { + id: Arc<()>, + started: Receiver<()>, + release: Option>, + _thread: PhantomData>, +} + +impl MergeGate { + /// Waits until the worker reaches the gate. + pub fn wait_started(&self) -> Result<(), RecvError> { + self.started.recv() + } + + /// Allows the worker to compute the merge. + pub fn release(&mut self) { + if let Some(release) = self.release.take() { + let _ = release.send(()); + } + } +} + +impl Drop for MergeGate { + fn drop(&mut self) { + NEXT.with_borrow_mut(|next| { + if next.as_ref().is_some_and(|gate| Arc::ptr_eq(&gate.id, &self.id)) { + *next = None; + } + }); + self.release(); + } +} + +pub(super) struct WorkerGate { + id: Arc<()>, + started: Sender<()>, + release: Receiver<()>, +} + +impl WorkerGate { + pub(super) fn wait(self) { + let _ = self.started.send(()); + let _ = self.release.recv(); + } +} + +pub(super) fn take() -> Option { + NEXT.with_borrow_mut(Option::take) +} + +/// Pauses the next merge started on this thread. Returns an error if a gate is already waiting. +pub fn pause_next_merge() -> Result { + NEXT.with_borrow_mut(|next| { + if next.is_some() { + return Err("a Shape Builder merge gate is already waiting on this thread"); + } + let id = Arc::new(()); + let (started_tx, started) = channel(); + let (release, release_rx) = channel(); + *next = Some(WorkerGate { id: id.clone(), started: started_tx, release: release_rx }); + Ok(MergeGate { id, started, release: Some(release), _thread: PhantomData }) + }) +} diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 0cdaad3434..a0d210f566 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -3796,6 +3796,32 @@ fn fill_area_press_does_not_search_a_hover_position_it_passed() { assert_eq!(super::fill_area::hover_searches_started() - started, 1, "only the search that was running"); } +/// An outline without a fill, cut to a clipping mask, keeps the pieces on the mask's edge: a square +/// clipped by the same square keeps all four sides. A square just outside the mask, and a square on +/// an outline of the mask that bounds no filled area (two copies of the square under even-odd), +/// keep nothing. +#[test] +fn fill_area_clip_keeps_outline_pieces_on_the_mask_edge() { + let unit = Rect::new(0.0, 0.0, 100.0, 100.0); + let clip = + |shape: PathData, mask: &PathData, rule: FillRule| super::fill_area::clip_to(po::Shape::new(shape, FillRule::NonZero, 1), false, mask, rule); + let kept = clip(shapes::rectangle(unit), &shapes::rectangle(unit), FillRule::NonZero).expect("the sides on the mask's edge"); + assert_eq!(kept.path.subpaths.iter().map(|sp| sp.segment_count()).sum::(), 4, "{:?}", kept.path); + let outside = shapes::rectangle(Rect::new(-0.005, -0.005, 100.005, 100.005)); + assert!(clip(outside, &shapes::rectangle(unit), FillRule::NonZero).is_none()); + let mut twice = shapes::rectangle(unit); + let mut back = shapes::rectangle(unit).subpaths; + back[0].anchors.reverse(); + twice.subpaths.extend(back); + assert!(clip(shapes::rectangle(unit), &twice, FillRule::EvenOdd).is_none()); + // A top side drawn as a cubic whose tangent vanishes at its middle shows as well. + let a = |p: Point, h_in: Point, h_out: Point| vectorcraft_geom::Anchor { p, h_in, h_out, kind: vectorcraft_geom::AnchorKind::Corner }; + let (o, x, xy, y) = (Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)); + let cusp = SubPath::new(vec![a(o, o, x), a(x, o, x), a(xy, xy, xy), a(y, y, y)], true); + let kept = clip(PathData::single(cusp), &shapes::rectangle(unit), FillRule::NonZero).expect("the sides on the mask's edge"); + assert_eq!(kept.path.subpaths.iter().map(|sp| sp.segment_count()).sum::(), 4, "{:?}", kept.path); +} + #[test] fn create_builds_the_three_tools() { for id in ["shapeBuilder", "livePaintBucket", "livePaintSelection"] { diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 54b50f0aa6..eb18001b19 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -35,6 +35,8 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ t("deleteAnchor", "Delete Anchor Point Tool", Some("-"), "tool-pen-delete"), t("anchorPoint", "Anchor Point Tool", Some("Shift+C"), "tool-anchor"), t(crate::quickpen::ID, "Quick Pen Tool", Some("Alt+P"), "tool-quick-pen"), + // Smart Pen's tool, kept out of `addons::GROUPS` so that `all_tools` lists it once. + t(crate::addons::smart_pen::ID, "Smart Pen Tool", None, "spline-pointer"), ], &[t("curvature", "Curvature Tool", Some("Shift+~"), "tool-curvature")], &[ diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index e50e595e26..52c3de1664 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -17,6 +17,16 @@ //! reach past the canvas, the tool shows none and the release draws nothing; for three different //! points on one line, or a circle past the canvas, the pointer shows "Circle too large". //! +//! With the option From Center (`fromCenter`, in the Control bar) on, the first point is the +//! circle's center and the outline passes through the second: a drag from the center, or a click +//! on the center and then on a point of the outline, draws the circle whose radius is the distance +//! between them (`shape.circleThroughPoints` with `center`). The second point snaps to anchors and +//! Smart Guides as the others do, so the outline can pass exactly through another object's anchor. +//! Shift keeps the second point at 45° steps from the center, and Alt rounds the diameter to the +//! rulers' ticks. The option in force when the first point is placed applies to that circle, and +//! `dragThird` does not apply to it, since it has only two points. With `standardAnchors` off, its +//! one anchor on the outline is the second point. +//! //! The tool's options (Circle Tool Options, `tool.setOption`; kept with the preferences): //! `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the //! diameter label; `color` is the color of the cross and the lines (one of [`COLORS`]); @@ -24,7 +34,7 @@ //! at 0°, 90°, 180° and 270° (`anchors: "points"`); `dragThird` off places the second point with //! a click and draws the circle through three points with a third click, and a click on the second //! point again (as a double-click there does) draws the circle on the two points. Every option is -//! on by default, and `color` is blue. +//! on by default except `fromCenter`, which is off, and `color` is blue. use serde_json::{Map, Value, json}; use vectorcraft_doc::MAX_COORD; @@ -56,7 +66,7 @@ pub const COLORS: &[(&str, [u8; 3])] = &[ ]; /// The option keys that are true or false. -const SWITCHES: &[&str] = &["center", "radii", "diameter", "standardAnchors", "dragThird"]; +const SWITCHES: &[&str] = &["center", "radii", "diameter", "standardAnchors", "dragThird", "fromCenter"]; /// The tool's options (see the module comment). #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -68,11 +78,13 @@ struct Options { color: usize, standard_anchors: bool, drag_third: bool, + /// The option From Center: the first point is the center. + from_center: bool, } impl Default for Options { fn default() -> Self { - Options { center: true, radii: true, diameter: true, color: 1, standard_anchors: true, drag_third: true } + Options { center: true, radii: true, diameter: true, color: 1, standard_anchors: true, drag_third: true, from_center: false } } } @@ -84,6 +96,7 @@ impl Options { "diameter" => &mut self.diameter, "standardAnchors" => &mut self.standard_anchors, "dragThird" => &mut self.drag_third, + "fromCenter" => &mut self.from_center, _ => return None, }) } @@ -143,48 +156,85 @@ pub struct CircleTool { press: Option, /// Where the pointer is, snapped: the point the next press or release places. pointer: Option, + /// Is the circle being drawn drawn from its center (From Center when its first point was + /// placed)? + centered: bool, } -/// The command the tool runs for `points`; with `standard_anchors` off, the circle's anchors are -/// at the points. -fn command(points: &[Point], standard_anchors: bool) -> (String, Value) { - let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); - let params = if standard_anchors { json!({ "points": pairs }) } else { json!({ "points": pairs, "anchors": "points" }) }; +/// The command the tool runs for `points`: with `centered`, the first point is the center and +/// the second is on the outline. With `standard_anchors` off, the circle's anchors are at the +/// points (from a center, the one point on the outline). +fn command(points: &[Point], centered: bool, standard_anchors: bool) -> (String, Value) { + let pair = |p: &Point| json!([p.x, p.y]); + let mut params = match points { + [c, p] if centered => json!({ "center": pair(c), "points": [pair(p)] }), + _ => json!({ "points": points.iter().map(pair).collect::>() }), + }; + if !standard_anchors { + params["anchors"] = json!("points"); + } ("shape.circleThroughPoints".into(), params) } +/// Is the circle at `c` with radius `r` inside the canvas, with its opposite edges on different +/// numbers (as `shape.circleThroughPoints` requires)? +fn on_canvas(c: Point, r: f64) -> bool { + [c.x - r, c.y - r, c.x + r, c.y + r].iter().all(|v| v.abs() <= MAX_COORD) && c.x - r < c.x + r && c.y - r < c.y + r +} + /// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints` /// draws it: none where no circle passes through them or it would reach past the canvas. pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> { - let on_canvas = |(c, r): &(Point, f64)| [c.x - r, c.y - r, c.x + r, c.y + r].iter().all(|v| v.abs() <= MAX_COORD); - shapes::circle_through_points(points).filter(on_canvas) + shapes::circle_through_points(points).filter(|(c, r)| on_canvas(*c, *r)) } -/// [`circle_of`], as the tool draws it: with `standard_anchors` off, also none where the path with -/// an anchor at each point ([`shapes::circle_with_anchors_at`]) reaches past the canvas, since its -/// curves can reach slightly outside the circle. -fn drawn_circle(points: &[Point], standard_anchors: bool) -> Option<(Point, f64)> { +/// The circle `points` give: with `centered`, the circle at the first point whose outline passes +/// through the second, as `shape.circleThroughPoints` with `center` draws it (none for a second +/// point on the center or a circle past the canvas); otherwise [`circle_of`]. +fn circle_for(points: &[Point], centered: bool) -> Option<(Point, f64)> { + match *points { + [c, p] if centered => { + let r = c.distance(p); + (c.is_finite() && r.is_finite() && r > 0.0 && on_canvas(c, r)).then_some((c, r)) + } + _ if centered => None, + _ => circle_of(points), + } +} + +/// [`circle_for`], as the tool draws it: with `standard_anchors` off, also none where the path with +/// an anchor at each point ([`shapes::circle_with_anchors_at`]; from a center, the one point on the +/// outline) reaches past the canvas, since its curves can reach slightly outside the circle. +fn drawn_circle(points: &[Point], centered: bool, standard_anchors: bool) -> Option<(Point, f64)> { + let anchors = if centered { points.get(1..).unwrap_or(&[]) } else { points }; let fits = |(c, r): &(Point, f64)| { - let b = vectorcraft_geom::Shape::bounding_box(&shapes::circle_with_anchors_at(*c, *r, points).to_bezpath()); + let b = vectorcraft_geom::Shape::bounding_box(&shapes::circle_with_anchors_at(*c, *r, anchors).to_bezpath()); [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD) }; - circle_of(points).filter(|c| standard_anchors || fits(c)) + circle_for(points, centered).filter(|c| standard_anchors || fits(c)) } -/// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on -/// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and -/// when that rounding leaves no distance. -fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point { - let d = first.distance(p); +/// With Alt, `p` moved along the line from `first` so that the diameter (their distance, or twice +/// it from a center) is on the nearest ruler tick at the current zoom, in the General unit; `p` +/// itself without Alt, and when that rounding leaves no distance. +fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods, centered: bool) -> Point { + let per = if centered { 2.0 } else { 1.0 }; + let d = first.distance(p) * per; let rounded = cx.unit.snap_to_ruler_tick(d, cx.zoom); if mods.alt && d > 0.0 && rounded > 0.0 && rounded.is_finite() { first + (p - first) * (rounded / d) } else { p } } +/// Whether a circle preview of radius `r` is drawn dashed. The canvas draws a dashed outline dash by +/// dash along its whole length, so a circle longer than [`DASHED_PX`] on screen is drawn solid. +pub(crate) fn preview_dashed(cx: &ToolContext, r: f64) -> bool { + std::f64::consts::TAU * r <= cx.tol(DASHED_PX) +} + /// Are the points two or more different points through which no circle is drawn: three on one /// line, or a circle that would reach past the canvas? -fn too_large(points: &[Point], standard_anchors: bool) -> bool { +fn too_large(points: &[Point], centered: bool, standard_anchors: bool) -> bool { let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p)); - points.len() >= 2 && distinct && drawn_circle(points, standard_anchors).is_none() + points.len() >= 2 && distinct && drawn_circle(points, centered, standard_anchors).is_none() } impl CircleTool { @@ -193,9 +243,21 @@ impl CircleTool { self.second = None; self.press = None; self.pointer = None; + self.centered = false; self.snap.clear(); } + /// [`round_diameter`] for the circle being drawn. + fn round(&self, cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point { + round_diameter(cx, first, p, mods, self.centered) + } + + /// Does a drag place the third point? A circle drawn from its center has no third point, so + /// `dragThird` does not apply to it. + fn drag_third(&self) -> bool { + self.options.drag_third || self.centered + } + /// How the second point keeps to the first: Shift's 45° steps and the construction guides. A /// third point keeps to neither. fn leave(&self, cx: &ToolContext, mods: Mods) -> Option { @@ -222,9 +284,12 @@ impl CircleTool { Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())), // A press on the first point adds no point: a drag from it drags out a diameter. Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)), + // From a center, the second point follows the pointer once the press has been dragged; + // until then it is the pressed point, which a release within DRAG_PX draws through. + Some(Press::Second { dragged: true, .. }) if self.centered => out.extend(self.pointer), Some(Press::Second { at, dragged: false, .. }) => out.push(at), // With `dragThird` off, a drag moves the second point. - Some(Press::Second { at, .. }) if !self.options.drag_third => out.push(at), + Some(Press::Second { at, .. }) if !self.drag_third() => out.push(at), Some(Press::Second { snapped, dragged: true, .. }) => { out.push(snapped); out.extend(self.pointer); @@ -234,13 +299,17 @@ impl CircleTool { out } - /// The second point as the tool shows it: none for a press on the first point. + /// The second point as the tool shows it: none for a press on the first point, nor for a + /// circle drawn from its center, whose second point follows the pointer. fn second(&self) -> Option { + if self.centered { + return None; + } if let Some((b, _)) = self.second { return Some(b); } match self.press { - Some(Press::Second { on_first: false, at, .. }) if !self.options.drag_third => Some(at), + Some(Press::Second { on_first: false, at, .. }) if !self.drag_third() => Some(at), Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at), Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped), _ => None, @@ -250,11 +319,12 @@ impl CircleTool { /// Runs the circle through `points` and starts afresh; where no circle is drawn through them /// (the tool showed none), it only starts afresh. fn draw(&mut self, points: &[Point]) -> Vec { + let centered = self.centered; self.clear(); - if drawn_circle(points, self.options.standard_anchors).is_none() { + if drawn_circle(points, centered, self.options.standard_anchors).is_none() { return vec![]; } - let (c, v) = command(points, self.options.standard_anchors); + let (c, v) = command(points, centered, self.options.standard_anchors); vec![Action::Exec(c, v)] } @@ -267,7 +337,7 @@ impl CircleTool { if on_second && !dragged { return self.draw(&[a, b]); } - if (on_first && !dragged) || drawn_circle(&[a, b, at], self.options.standard_anchors).is_none() { + if (on_first && !dragged) || drawn_circle(&[a, b, at], false, self.options.standard_anchors).is_none() { self.snap.clear(); return vec![]; } @@ -329,7 +399,7 @@ impl Tool for CircleTool { let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref()); // Alt's rounding of the diameter is for the second point only. let rounds = self.first.filter(|_| self.second.is_none()); - self.pointer = Some(rounds.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + self.pointer = Some(rounds.map_or(p, |a| self.round(cx, a, p, ev.mods))); vec![] } PointerKind::Down => { @@ -352,13 +422,14 @@ impl Tool for CircleTool { None => { let at = self.snap.press(cx, ev.pos, &[], None); self.first = Some(at); + self.centered = self.options.from_center; self.press = Some(Press::First { at, from: ev.pos, dragged: false }); self.pointer = Some(at); } Some(a) => { let leave = self.leave(cx, ev.mods); let snapped = self.snap.press(cx, ev.pos, &[], leave.as_ref()); - let at = round_diameter(cx, a, snapped, ev.mods); + let at = self.round(cx, a, snapped, ev.mods); let on_first = snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX); self.press = Some(Press::Second { at, snapped, from: ev.pos, on_first, dragged: false }); self.pointer = Some(at); @@ -367,7 +438,8 @@ impl Tool for CircleTool { vec![] } PointerKind::Drag => { - let drag_third = self.options.drag_third; + let centered = self.centered; + let drag_third = self.drag_third(); let first = self.first; match &mut self.press { // With `dragThird` off, the second point follows the pointer as it does before @@ -378,7 +450,7 @@ impl Tool for CircleTool { if *dragged { let leave = first.map(|a| Leave::segment(cx, a, ev.mods.shift)); *snapped = self.snap.drag(cx, ev.pos, leave.as_ref()); - *at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods)); + *at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods, false)); self.pointer = Some(*at); } } @@ -392,15 +464,16 @@ impl Tool for CircleTool { Some(Press::First { at, from, dragged }) => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); let leave = Leave::segment(cx, *at, ev.mods.shift); - self.pointer = Some(round_diameter(cx, *at, self.snap.drag(cx, ev.pos, Some(&leave)), ev.mods)); + self.pointer = Some(round_diameter(cx, *at, self.snap.drag(cx, ev.pos, Some(&leave)), ev.mods, centered)); } // Dragged from the first point, the pointer is the other end of a diameter, as - // for a drag from a first press. - Some(Press::Second { from, on_first: true, dragged, .. }) => { + // for a drag from a first press; from a center, the second point is always the + // pointer. + Some(Press::Second { from, dragged, on_first, .. }) if *on_first || centered => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); let leave = self.first.map(|a| Leave::segment(cx, a, ev.mods.shift)); let p = self.snap.drag(cx, ev.pos, leave.as_ref()); - self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods, centered))); } Some(Press::Second { from, dragged, .. }) => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); @@ -414,15 +487,22 @@ impl Tool for CircleTool { (Some(Press::Third { at, on_first, on_second, dragged, .. }), ..) => self.third_up(at, on_first, on_second, dragged), // With `dragThird` off, the release places the second point; let go on the first // point, as a press there is, it places nothing. - (Some(Press::Second { at, snapped, on_first: false, .. }), Some(a), _) if !self.options.drag_third => { + (Some(Press::Second { at, snapped, on_first: false, .. }), Some(a), _) if !self.drag_third() => { if !(at == a || snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX)) { self.second = Some((at, ev.pos)); } self.snap.clear(); vec![] } - (Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]), - // A click places the first point; the guides of the press go. + // A release DRAG_PX or more from the press draws the circle the tool shows; where it + // shows none, the release draws nothing and starts afresh. + (Some(Press::First { at, dragged: true, .. }), _, Some(b)) + if b.distance(at) >= cx.tol(DRAG_PX) || circle_for(&[at, b], self.centered).is_some() => + { + self.draw(&[at, b]) + } + // A click, or a drag back onto the press, places the first point; the guides of the + // press go. (Some(Press::First { .. }), ..) => { self.snap.clear(); vec![] @@ -431,6 +511,9 @@ impl Tool for CircleTool { // a drag from there draws the circle on the diameter it drags out. (Some(Press::Second { on_first: true, dragged: false, .. }), ..) => vec![], (Some(Press::Second { on_first: true, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, c]), + // From a center: the outline passes through the point the tool shows it on, where + // the drag ends or, within DRAG_PX of the press, the pressed point. + (Some(Press::Second { .. }), Some(a), Some(c)) if self.centered => self.draw(&[a, c]), (Some(Press::Second { at, dragged: false, .. }), Some(a), _) => self.draw(&[a, at]), // Three points: Alt's rounding of the diameter does not apply. (Some(Press::Second { snapped, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, snapped, c]), @@ -487,21 +570,21 @@ impl Tool for CircleTool { let mut o = self.snap.guides().to_vec(); let points = self.points(); let color = crate::draw2::FEEDBACK; - if let Some((c, r)) = drawn_circle(&points, self.options.standard_anchors) { - // The path the release draws: with `standardAnchors` off, the one with an anchor at each point. + if let Some((c, r)) = drawn_circle(&points, self.centered, self.options.standard_anchors) { + // The path the release draws: with `standardAnchors` off, the one with an anchor at each + // point (from a center, at the one point on the outline). let path = if self.options.standard_anchors { shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath() } else { - shapes::circle_with_anchors_at(c, r, &points).to_bezpath() + let on_outline = if self.centered { points.get(1..).unwrap_or(&[]) } else { &points[..] }; + shapes::circle_with_anchors_at(c, r, on_outline).to_bezpath() }; - // The canvas draws a dashed outline dash by dash along its whole length: a circle longer - // than DASHED_PX on screen is drawn solid instead. - let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); - o.push(Overlay::Path { path, color, width: 1.0, dashed }); + o.push(Overlay::Path { path, color, width: 1.0, dashed: preview_dashed(cx, r) }); let opts = self.options; let lines = COLORS.get(opts.color).map_or(color, |(_, rgb)| *rgb); if opts.radii { - for p in &points { + // A circle drawn from its center has one radius, to the point on its outline. + for p in points.iter().filter(|p| **p != c) { o.push(Overlay::Line { a: c, b: *p, color: lines, dashed: false }); } } @@ -513,7 +596,7 @@ impl Tool for CircleTool { if let Some(p) = self.pointer.filter(|_| cx.measurement_labels && opts.diameter) { o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) }); } - } else if let Some(p) = self.pointer.filter(|_| too_large(&points, self.options.standard_anchors)) { + } else if let Some(p) = self.pointer.filter(|_| too_large(&points, self.centered, self.options.standard_anchors)) { o.push(Overlay::Label { p, text: "Circle too large".into(), color }); } for p in self.first.into_iter().chain(self.second()) { @@ -536,6 +619,7 @@ impl Tool for CircleTool { "color": color, "standardAnchors": o.standard_anchors, "dragThird": o.drag_third, + "fromCenter": o.from_center, }) } @@ -545,7 +629,8 @@ impl Tool for CircleTool { } /// Sets one option; a value the option does not take leaves it as it was. Switching - /// `dragThird` drops the points placed so far. + /// `dragThird` drops the points placed so far; a circle being drawn keeps the `fromCenter` mode + /// it started with. fn set_option(&mut self, key: &str, value: &Value) { if key == "color" { if let Some(i) = value.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)) { @@ -558,7 +643,8 @@ impl Tool for CircleTool { if let Some(switch) = self.options.switch(key) { *switch = on; } - if self.options.drag_third != was { + // A circle drawn from its center has no third point, so its center stays placed. + if self.options.drag_third != was && !self.centered { self.clear(); } } diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index 4e700b6c3b..3264a771e8 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -140,7 +140,10 @@ fn the_options_show_or_hide_the_center_radii_and_diameter_in_their_color() { let o = t.overlays(&cx); assert_eq!(annotations(&o, c), (vec![red; 2], vec![red; 2])); assert!(o.iter().any(|o| matches!(o, Overlay::Path { color, .. } if *color == blue)), "{o:?}"); - assert_eq!(t.options(), json!({"center": true, "radii": true, "diameter": false, "color": "red", "standardAnchors": true, "dragThird": true})); + assert_eq!( + t.options(), + json!({"center": true, "radii": true, "diameter": false, "color": "red", "standardAnchors": true, "dragThird": true, "fromCenter": false}) + ); // A value an option does not take leaves it as it was. for (key, value) in [("color", json!("orange")), ("center", json!("no")), ("radii", json!(0))] { t.set_option(key, &value); @@ -192,8 +195,8 @@ fn anchors_at_the_points_keep_the_path_on_the_canvas() { let at = |deg: f64| (r * deg.to_radians().cos(), r * deg.to_radians().sin()); let points = [at(0.0), at(70.0), at(180.0)]; let geom: Vec = points.iter().map(|(x, y)| Point::new(*x, *y)).collect(); - assert!(drawn_circle(&geom, true).is_some()); - assert_eq!(drawn_circle(&geom, false), None); + assert!(drawn_circle(&geom, false, true).is_some()); + assert_eq!(drawn_circle(&geom, false, false), None); let mut t = CircleTool::default(); t.set_option("standardAnchors", &json!(false)); click(&mut t, &cx, points[0]); @@ -584,8 +587,8 @@ fn points_on_one_line_say_the_circle_is_too_large() { assert_eq!(label(&t), None, "a circle is shown"); t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default())); assert_eq!(label(&t), None, "the third point is on the second"); - assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true)); - assert!(!too_large(&[Point::new(0.0, 0.0)], true) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)], true)); + assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], false, true)); + assert!(!too_large(&[Point::new(0.0, 0.0)], false, true) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)], false, true)); } /// Escape drops the first point; so do a dropped press and an edit made outside the tool. A @@ -698,6 +701,193 @@ fn a_huge_circle_is_previewed_solid() { assert!(preview(&t.overlays(&cx)).is_some()); } +/// The command the tool runs for a circle at `c` whose outline passes through `p`. +fn centered(c: (f64, f64), p: (f64, f64)) -> Vec { + vec![Action::Exec("shape.circleThroughPoints".into(), json!({ "center": [c.0, c.1], "points": [[p.0, p.1]] }))] +} + +fn from_center() -> CircleTool { + let mut t = CircleTool::default(); + t.set_option("fromCenter", &json!(true)); + t +} + +/// With From Center, a drag from the corner anchor of the rectangle at (200, 200) to next to the +/// opposite corner at (100, 100) snaps both ends to the anchors: the circle is centered on one +/// corner, its outline passes through the other, and its radius is the diagonal. Until the release +/// the outline passes through the pointer, with one radius drawn to it. +#[test] +fn from_center_the_outline_passes_through_the_opposite_corner() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = from_center(); + assert_eq!(t.options()["fromCenter"], json!(true)); + t.pointer(&cx, &ev(PointerKind::Move, (201.0, 199.5), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Down, (201.0, 199.5), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (150.0, 150.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (101.0, 101.5), Mods::default())); + let r = 100.0 * std::f64::consts::SQRT_2; + let o = t.overlays(&cx); + let shown = o + .iter() + .find_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + _ => None, + }) + .expect("the circle is shown"); + assert!(near(shown, Rect::new(200.0 - r, 200.0 - r, 200.0 + r, 200.0 + r)), "{o:?}"); + let center = Point::new(200.0, 200.0); + let radii: Vec = o + .iter() + .filter_map(|o| match o { + Overlay::Line { a, b, .. } if *a == center => Some(*b), + _ => None, + }) + .collect(); + assert_eq!(radii, vec![Point::new(100.0, 100.0)], "one radius, to the pointer: {o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("D: 282.84"))), "{o:?}"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.0, 101.5), Mods::default())), centered((200.0, 200.0), (100.0, 100.0))); + assert_eq!(circle_for(&[center, Point::new(100.0, 100.0)], true), Some((center, r))); +} + +/// With From Center, a click places the center and a second click the point the outline passes +/// through; a second click on the center places nothing, and the center stays. +#[test] +fn from_center_two_clicks_draw_the_circle_through_the_second() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]); + assert_eq!(click(&mut t, &cx, (300.5, 300.0)), vec![], "a double-click places the center alone"); + assert!(t.ends_on_escape(&cx)); + t.pointer(&cx, &ev(PointerKind::Move, (330.0, 340.0), Mods::default())); + // Center (300, 300), radius 50. + assert!(near(preview(&t.overlays(&cx)).expect("the circle is shown"), Rect::new(250.0, 250.0, 350.0, 350.0)), "{:?}", t.overlays(&cx)); + assert_eq!(click(&mut t, &cx, (330.0, 340.0)), centered((300.0, 300.0), (330.0, 340.0))); + // A second press dragged from elsewhere moves the point the outline passes through. + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(drag(&mut t, &cx, (330.0, 340.0), &[(360.0, 300.0)], Mods::default()), centered((300.0, 300.0), (360.0, 300.0))); +} + +/// With From Center, the release draws the circle the tool shows: a drag from the center ends +/// where it is let go, and a second press moved less than 2 screen points shows and draws the +/// outline through the point of the press. +#[test] +fn from_center_the_release_draws_the_circle_shown() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (380.0, 300.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (400.0, 300.0), Mods::default())), centered((300.0, 300.0), (400.0, 300.0))); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (330.0, 340.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (331.0, 340.0), Mods::default())); + let shown = preview(&t.overlays(&cx)).expect("the circle is shown"); + let r = Point::new(300.0, 300.0).distance(Point::new(330.0, 340.0)); + assert!(near(shown, Rect::new(300.0 - r, 300.0 - r, 300.0 + r, 300.0 + r)), "{:?}", t.overlays(&cx)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (331.0, 340.0), Mods::default())), centered((300.0, 300.0), (330.0, 340.0))); +} + +/// A first press let go within 2 screen points of where it was pressed is a click also after a +/// drag that came back to it, from a center and on a diameter: it places the first point. +#[test] +fn a_first_press_dragged_back_near_its_press_places_the_first_point() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(320.0, 300.0), (301.0, 300.0)], Mods::default()), vec![]); + assert!(t.ends_on_escape(&cx), "the center is placed"); + assert_eq!(click(&mut t, &cx, (380.0, 300.0)), centered((300.0, 300.0), (380.0, 300.0))); + let mut t = CircleTool::default(); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(320.0, 300.0), (301.0, 300.0)], Mods::default()), vec![]); + assert!(t.ends_on_escape(&cx), "the first point is placed"); + t.key(&cx, ToolKey::Escape, Mods::default()); + // A drag to a circle past the canvas draws nothing and leaves no point behind. + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(4.1e6, 300.0)], Mods::default()), vec![]); + assert!(!t.ends_on_escape(&cx), "nothing is left pending"); +} + +/// With From Center, Shift keeps the point at 45° steps from the center, and Alt rounds the +/// diameter, twice the radius, to the rulers' ticks (every 5 pt at 100% in points). +#[test] +fn from_center_shift_and_alt_keep_to_the_center() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + let shift = Mods { shift: true, ..Mods::default() }; + let acts = drag(&mut t, &cx, (300.0, 300.0), &[(400.0, 310.0)], shift); + let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") }; + assert!((v["points"][0][1].as_f64().unwrap() - 300.0).abs() < 1e-9, "level with the center: {v}"); + // Near the diagonal, the point keeps to the 45° line through the center. + let acts = drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 372.0)], shift); + let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") }; + let (x, y) = (v["points"][0][0].as_f64().unwrap(), v["points"][0][1].as_f64().unwrap()); + assert!(((x - 300.0) - (y - 300.0)).abs() < 1e-9 && x > 300.0, "on the 45° line from the center: {v}"); + let alt = Mods { alt: true, ..Mods::default() }; + // A radius of 26 is a diameter of 52, which Alt makes 50. + assert_eq!(drag(&mut t, &cx, (0.0, 0.0), &[(0.0, 26.0)], alt), centered((0.0, 0.0), (0.0, 25.0))); +} + +/// The option in force when the first point is placed applies to that circle: turning From Center +/// off part way keeps the circle being drawn centered, and the next circle is drawn on a diameter. +/// A point on the center draws nothing. +#[test] +fn from_center_holds_for_the_circle_being_drawn() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + click(&mut t, &cx, (100.0, 100.0)); + t.set_option("fromCenter", &json!(false)); + assert_eq!(click(&mut t, &cx, (100.0, 150.0)), centered((100.0, 100.0), (100.0, 150.0))); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)])); + assert_eq!(circle_for(&[Point::new(1.0, 1.0), Point::new(1.0, 1.0)], true), None); + assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true, true)); + // Edges that round to one number at document precision, as `shape.circleThroughPoints` refuses. + let x = 1_048_576.0; + assert_eq!(circle_for(&[Point::new(x, 0.0), Point::new(x, 1e-11)], true), None); + assert_eq!(circle_of(&[Point::new(x, 0.0), Point::new(x, 2e-11)]), None); + t.set_option("fromCenter", &json!("yes")); + assert_eq!(t.options()["fromCenter"], json!(false), "a value that is not true or false is ignored"); +} + +/// Switching `dragThird` while a center is placed keeps the center: the circle from it is still +/// drawn. Without From Center, the switch drops the point placed. +#[test] +fn switching_third_point_by_dragging_keeps_a_placed_center() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = from_center(); + click(&mut t, &cx, (100.0, 100.0)); + t.set_option("dragThird", &json!(false)); + assert!(t.ends_on_escape(&cx), "the center is still placed"); + assert_eq!(click(&mut t, &cx, (100.0, 150.0)), centered((100.0, 100.0), (100.0, 150.0))); + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.set_option("dragThird", &json!(false)); + assert!(!t.ends_on_escape(&cx), "the first point is dropped"); +} + +/// `tool.setOption` takes `fromCenter` as true or false, and no other key. +#[test] +fn the_options_are_checked() { + let map = |v: Value| v.as_object().cloned().unwrap(); + assert_eq!(check_options(&map(json!({ "fromCenter": true }))), Ok(())); + assert_eq!(check_options(&map(json!({ "fromCenter": 1 }))), Err("`fromCenter` must be true or false".into())); + assert_eq!(check_options(&map(json!({ "radius": 5 }))), Err("unknown Circle tool option `radius`".into())); + let t = CircleTool::default(); + assert_eq!(t.check_option("fromCenter", &json!(false)), Ok(())); + assert_eq!(t.check_option("fromCenter", &json!(1)), Err("`fromCenter` must be true or false".into())); + assert_eq!(t.check_option("radius", &json!(5)), Err("unknown Circle tool option `radius`".into())); +} + /// The tool is in the Ellipse tool's group, after the Ellipse tool. #[test] fn the_circle_tool_follows_the_ellipse_tool() { diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index bc0f822c06..67658b4ea9 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -228,8 +228,16 @@ pub struct ToolContext<'a> { pub shape_widgets: bool, /// Which paint proxy is in front (true = Fill): the one the Gradient tool edits. pub fill_active: bool, - /// The selected gradient stop (`gradient.selectStop`), marked on the gradient annotator. + /// The selected gradient stop (`gradient.selectStop`), marked on the gradient annotator. For + /// an Eyedropper pick armed for a stop of the gradient a tool paints with, only a stop still + /// selected on that gradient. pub gradient_stop: Option, + /// Is [`Self::paint`]'s paint behind the proxy in front ([`Self::fill_active`]) the color the + /// active tool, or the tool an armed one-shot pick returns to, paints with (the Live Paint + /// Bucket's fill and stroke, the Shape Builder's fill), or was the pick armed for a stop of + /// that tool's paint? A pick armed for such a stop then ends once [`Self::gradient_stop`] no + /// longer names it, also after the stop was cleared or the other proxy came to the front. + pub tool_paints: bool, /// The Appearance panel's active fill/stroke (paint-order index into the first selected /// object's stack); paint tools show and edit that item. pub appearance_item: Option, diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 0d0106eddb..0b19e3e4c0 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -47,14 +47,20 @@ look = "The same pointer as Arrow, hollow: white with a dark outline." [[cursor]] id = "DirectAnchor" group = "Selection" -shown_when = ["Direct Selection over an anchor of a path that isn't selected."] +shown_when = [ + "Direct Selection over an anchor of a path that isn't selected.", + "The Quick Pen, with no path being drawn, over an anchor of a selected path that is not itself selected (a click selects it, a drag moves it).", +] hotspot = "The arrow's tip." look = "ArrowHollow with a small hollow square badge (an unselected anchor)." [[cursor]] id = "DirectAnchorSelected" group = "Selection" -shown_when = ["Direct Selection over an anchor of a selected path."] +shown_when = [ + "Direct Selection over an anchor of a selected path.", + "The Quick Pen, with no path being drawn, over a selected anchor.", +] hotspot = "The arrow's tip." look = "ArrowHollow with a small filled square badge (a selected anchor)." @@ -137,6 +143,7 @@ shown_when = [ "The Gradient tool over the annotator's handles and during most gradient drags.", "The Perspective Grid and Perspective Selection over plane widgets and handles.", "Selection and Objects on Path over an Objects on Path group's Move All widget, and while dragging it.", + "The Quick Pen, with no path being drawn, over a segment of a selected path, and while a drag moves an anchor or a segment.", ] hotspot = "The centre." look = "A four-way move cursor." @@ -242,6 +249,7 @@ group = "Pen" shown_when = [ "The Pen (not drawing) over an end of an open path (a click continues it).", "The Curvature tool over an open end.", + "The Quick Pen (not drawing) over an end of an open path (a click continues it, a drag on a selected path's end moves it).", ] hotspot = "The nib's tip." look = "The Pen nib with a slash badge." diff --git a/crates/tools/src/curvature_circle.rs b/crates/tools/src/curvature_circle.rs index 7124f55cda..05aaef2feb 100644 --- a/crates/tools/src/curvature_circle.rs +++ b/crates/tools/src/curvature_circle.rs @@ -14,21 +14,35 @@ //! nothing. The pointer passes over the circles the tool drew until the selection holds none of //! them, another tool is chosen, another document becomes active, or an edit, Undo or Redo is //! made outside the tool. +//! +//! The tool's options (Curvature Circle Tool Options, `tool.setOption`; kept with the +//! preferences): `snapTolerance` is the 5 screen points above (VectorCraft's own range of 1 to 40); +//! `snapWithoutGuides` off makes the pointer reach no further than Selection & Anchor Display › +//! Tolerance while Smart Guides are off (when that tolerance is as large as the reach, the reach +//! stays the same); `annotateRadius` off hides the radius label; +//! `standardAnchors` off draws the circle with an anchor where it touches the path and one every +//! 90° from there (`anchors: "touch"`) instead of at 0°, 90°, 180° and 270°; `constantRadius` off +//! gives the cubic's own curvature on the cubic of a circular arc too, with no asterisk. Every +//! switch is on by default. use std::collections::HashSet; -use serde_json::json; +use serde_json::{Value, json}; use vectorcraft_doc::{MAX_COORD, NodeId}; -use vectorcraft_geom::curvature::{CurvatureCircle, NoCircle, curvature_circle_on}; -use vectorcraft_geom::{Point, Rect, Vec2, shapes}; +use vectorcraft_geom::curvature::{CurvatureCircle, NoCircle, curvature_circle_on_with}; +use vectorcraft_geom::{PathData, Point, Rect, Vec2, shapes}; +use crate::option_check; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; pub const ID: &str = "curvatureCircle"; -/// How near (screen points) a path pulls the pointer, unless the Smart Guides' snapping tolerance -/// is larger. -const SNAP_PX: f64 = 5.0; +/// The range of `snapTolerance` (screen points). +pub const SNAP_RANGE: (f64, f64) = (1.0, 40.0); +/// `snapTolerance` by default (screen points). +pub const DEFAULT_SNAP: f64 = 5.0; +/// The option keys that are true or false. +const SWITCHES: &[&str] = &["snapWithoutGuides", "annotateRadius", "standardAnchors", "constantRadius"]; /// How far (screen points) the pointer travels from a press before the press counts as a drag. const DRAG_PX: f64 = 2.0; /// Half the length (screen points) of each arm of the cross at the circle's center. @@ -52,8 +66,37 @@ enum Found { Refused(&'static str, Point), } +/// The tool's options (see the module comment). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Options { + snap_tolerance: f64, + snap_without_guides: bool, + annotate_radius: bool, + standard_anchors: bool, + constant_radius: bool, +} + +impl Default for Options { + fn default() -> Self { + Options { snap_tolerance: DEFAULT_SNAP, snap_without_guides: true, annotate_radius: true, standard_anchors: true, constant_radius: true } + } +} + +impl Options { + fn switch(&mut self, key: &str) -> Option<&mut bool> { + Some(match key { + "snapWithoutGuides" => &mut self.snap_without_guides, + "annotateRadius" => &mut self.annotate_radius, + "standardAnchors" => &mut self.standard_anchors, + "constantRadius" => &mut self.constant_radius, + _ => return None, + }) + } +} + #[derive(Default)] pub struct CurvatureCircleTool { + options: Options, /// The point under the pointer, and whether Shift was held. hover: Option<(Hit, bool)>, /// The press in progress, where the pointer was pressed: what a release draws. @@ -64,6 +107,17 @@ pub struct CurvatureCircleTool { drawn: HashSet, } +/// How near (document units) a path pulls the pointer: `snapTolerance`, or Smart Guides › +/// Snapping Tolerance when that is larger; with Smart Guides off and `snapWithoutGuides` off, no +/// further than Selection & Anchor Display › Tolerance. +fn reach(cx: &ToolContext, o: &Options) -> f64 { + let snap = cx.tol(o.snap_tolerance).max(cx.snap_tol()); + if !cx.smart_guides && !o.snap_without_guides { + return snap.min(cx.pick_tol()); + } + snap +} + impl CurvatureCircleTool { /// After Deselect or a selection made outside the tool, the selection holds none of the /// circles the tool drew, and the pointer reaches them again. @@ -77,10 +131,9 @@ impl CurvatureCircleTool { } } -/// The nearest point within reach of `p` on the paths a click can pick, guides and the paths in +/// The nearest point within `tol` of `p` on the paths a click can pick, guides and the paths in /// `skip` left out; of paths at the same distance, a selected one, then the one on top. -fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet) -> Option { - let tol = cx.tol(SNAP_PX).max(cx.snap_tol()); +fn hit_at(cx: &ToolContext, p: Point, tol: f64, skip: &HashSet) -> Option { let mut best: Option<(Hit, f64)> = None; for id in crate::draw2::candidate_paths(cx) { if skip.contains(&id) { @@ -103,14 +156,14 @@ fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet) -> Option { /// The circle at `hit` as `shape.curvatureCircle` draws it, or why it draws none; `None` when the /// path or segment is gone. -fn found(cx: &ToolContext, hit: Hit, convex: bool) -> Option { +fn found(cx: &ToolContext, hit: Hit, convex: bool, o: &Options) -> Option { let sp = cx.doc.node(hit.id)?.path_data()?.subpaths.get(hit.subpath)?; if hit.segment >= sp.segment_count() { return None; } let at = vectorcraft_geom::ParamCurve::eval(&sp.segment(hit.segment), hit.t); - Some(match curvature_circle_on(sp, hit.segment, hit.t, convex) { - Ok(c) if on_canvas(&c) => Found::Circle(c), + Some(match curvature_circle_on_with(sp, hit.segment, hit.t, convex, o.constant_radius) { + Ok(c) if on_canvas(&c, o) => Found::Circle(c), Ok(_) => Found::Refused("Circle too large", at), Err(NoCircle::Straight) => Found::Refused("Straight segment", at), Err(NoCircle::Cusp) => Found::Refused("Cusp", at), @@ -118,10 +171,19 @@ fn found(cx: &ToolContext, hit: Hit, convex: bool) -> Option { }) } -/// Does the circle stay on the canvas? -fn on_canvas(c: &CurvatureCircle) -> bool { +/// The path `shape.curvatureCircle` draws for `c`: with `standardAnchors`, the circle with anchors +/// at 0°, 90°, 180° and 270°; without, the circle with an anchor where it touches the path. +fn drawn_path(c: &CurvatureCircle, o: &Options) -> PathData { let (p, r) = (c.center, c.radius); - [p.x - r, p.y - r, p.x + r, p.y + r].iter().all(|v| v.abs() <= MAX_COORD) + if !o.standard_anchors { + return shapes::circle_with_anchors_at(p, r, &[c.at]); + } + shapes::ellipse(Rect::new(p.x - r, p.y - r, p.x + r, p.y + r)) +} + +/// Does the circle stay on the canvas, as `shape.curvatureCircle` checks it? +fn on_canvas(c: &CurvatureCircle, o: &Options) -> bool { + drawn_path(c, o).bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= MAX_COORD)) } impl Tool for CurvatureCircleTool { @@ -134,13 +196,14 @@ impl Tool for CurvatureCircleTool { return vec![]; } self.forget_unselected(cx); + let (o, tol) = (self.options, reach(cx, &self.options)); match ev.kind { PointerKind::Move => { - self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.hover = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); vec![] } PointerKind::Down => { - self.press = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.press = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); self.hover = self.press; self.from = ev.pos; vec![] @@ -155,12 +218,21 @@ impl Tool for CurvatureCircleTool { } PointerKind::Up => { let press = self.press.take(); - self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.hover = hit_at(cx, ev.pos, tol, &self.drawn).map(|h| (h, ev.mods.shift)); let Some((hit, convex)) = press else { return vec![] }; - if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) || !matches!(found(cx, hit, convex), Some(Found::Circle(_))) { + if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) || !matches!(found(cx, hit, convex, &o), Some(Found::Circle(_))) { return vec![]; } - let p = json!({"id": hit.id.0, "subpath": hit.subpath, "segment": hit.segment, "t": hit.t, "convex": convex}); + let anchors = if o.standard_anchors { "standard" } else { "touch" }; + let p = json!({ + "id": hit.id.0, + "subpath": hit.subpath, + "segment": hit.segment, + "t": hit.t, + "convex": convex, + "constantRadius": o.constant_radius, + "anchors": anchors, + }); vec![Action::Exec("shape.curvatureCircle".into(), p), Action::Notify("created".into())] } PointerKind::DoubleClick | PointerKind::TripleClick => vec![], @@ -236,10 +308,10 @@ impl Tool for CurvatureCircleTool { let Some((hit, convex)) = self.hover else { return vec![] }; let color = crate::draw2::FEEDBACK; let mut o = vec![]; - match found(cx, hit, convex) { + match found(cx, hit, convex, &self.options) { Some(Found::Circle(c)) => { let r = c.radius; - let path = shapes::ellipse(Rect::new(c.center.x - r, c.center.y - r, c.center.x + r, c.center.y + r)).to_bezpath(); + let path = drawn_path(&c, &self.options).to_bezpath(); // The outline is drawn solid when it is longer than DASHED_PX on screen. let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); o.push(Overlay::Path { path, color, width: 1.0, dashed }); @@ -248,7 +320,7 @@ impl Tool for CurvatureCircleTool { o.push(Overlay::Line { a: c.center - Vec2::new(arm, 0.0), b: c.center + Vec2::new(arm, 0.0), color, dashed: false }); o.push(Overlay::Line { a: c.center - Vec2::new(0.0, arm), b: c.center + Vec2::new(0.0, arm), color, dashed: false }); o.push(Overlay::Anchor { p: c.at, color, filled: true, size: 6.0 }); - if cx.measurement_labels { + if cx.measurement_labels && self.options.annotate_radius { let star = if c.nominal { "*" } else { "" }; o.push(Overlay::Measure { p: c.at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("R: {}{star}", cx.len(r)) }); } @@ -262,6 +334,39 @@ impl Tool for CurvatureCircleTool { fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { Cursor::Crosshair } + + fn options(&self) -> Value { + let o = self.options; + json!({ + "snapTolerance": o.snap_tolerance, + "snapWithoutGuides": o.snap_without_guides, + "annotateRadius": o.annotate_radius, + "standardAnchors": o.standard_anchors, + "constantRadius": o.constant_radius, + }) + } + + /// `snapTolerance` takes a number in [`SNAP_RANGE`], and the switches true or false. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key == "snapTolerance" { + option_check::number(key, value, SNAP_RANGE.0, SNAP_RANGE.1) + } else if SWITCHES.contains(&key) { + option_check::boolean(key, value) + } else { + Err(option_check::unknown(key)) + } + } + + /// Sets one option; a value the option does not take leaves it as it was. + fn set_option(&mut self, key: &str, value: &Value) { + if key == "snapTolerance" { + if let Some(v) = value.as_f64().filter(|v| (SNAP_RANGE.0..=SNAP_RANGE.1).contains(v)) { + self.options.snap_tolerance = v; + } + } else if let (Some(switch), Some(on)) = (self.options.switch(key), value.as_bool()) { + *switch = on; + } + } } #[cfg(test)] diff --git a/crates/tools/src/curvature_circle/tests.rs b/crates/tools/src/curvature_circle/tests.rs index 1dccebecc6..76df830591 100644 --- a/crates/tools/src/curvature_circle/tests.rs +++ b/crates/tools/src/curvature_circle/tests.rs @@ -305,3 +305,98 @@ fn the_curvature_circle_tool_follows_the_circle_tool() { let circle = ids.iter().position(|id| *id == crate::circle::ID).unwrap(); assert_eq!(ids.get(circle + 1), Some(&ID)); } + +/// `snapTolerance` sets how far the pointer reaches, and with `snapWithoutGuides` off and Smart +/// Guides off the pointer reaches no further than the selection tolerance, and never further than +/// with the switch on; with Smart Guides on it reaches as far as before. +#[test] +fn the_snap_options_set_how_far_the_pointer_reaches() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, snapping_tolerance: 0.0, selection_tolerance: 2.0, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + assert_eq!(click(&mut t, &cx, (308.0, 200.0), Mods::default()), vec![]); + t.set_option("snapTolerance", &json!(10)); + assert_eq!(click(&mut t, &cx, (308.0, 200.0), Mods::default()).len(), 2); + t.set_option("snapTolerance", &json!(5)); + t.set_option("snapWithoutGuides", &json!(false)); + assert_eq!(click(&mut t, &cx, (304.0, 200.0), Mods::default()), vec![]); + assert_eq!(click(&mut t, &cx, (301.0, 200.0), Mods::default()).len(), 2); + let guides = ToolContext { smart_guides: true, ..cx }; + assert_eq!(click(&mut t, &guides, (304.0, 200.0), Mods::default()).len(), 2); + let wide = ToolContext { selection_tolerance: 8.0, ..cx }; + assert_eq!(click(&mut t, &wide, (304.0, 200.0), Mods::default()).len(), 2); + assert_eq!(click(&mut t, &wide, (307.0, 200.0), Mods::default()), vec![]); +} + +/// `annotateRadius` off hides the radius label; `constantRadius` off shows the cubic's own radius +/// without the asterisk and sends `constantRadius: false`; `standardAnchors` off sends +/// `anchors: "touch"`. +#[test] +fn the_label_and_circle_options_change_what_is_shown_and_drawn() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let measure = |t: &CurvatureCircleTool| { + t.overlays(&cx).iter().find_map(|o| match o { + Overlay::Measure { text, .. } => Some(text.clone()), + _ => None, + }) + }; + let mut t = CurvatureCircleTool::default(); + let v = params(&click(&mut t, &cx, (300.0, 200.0), Mods::default())); + assert_eq!((&v["constantRadius"], &v["anchors"]), (&json!(true), &json!("standard"))); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 200.0), Mods::default())); + assert!(measure(&t).is_some_and(|m| m.ends_with('*'))); + t.set_option("annotateRadius", &json!(false)); + assert_eq!(measure(&t), None); + t.set_option("annotateRadius", &json!(true)); + let arc = preview(&t.overlays(&cx)).unwrap(); + t.set_option("constantRadius", &json!(false)); + assert!(measure(&t).is_some_and(|m| !m.ends_with('*')), "{:?}", measure(&t)); + assert!(preview(&t.overlays(&cx)).unwrap().width() > arc.width()); + t.set_option("standardAnchors", &json!(false)); + let v = params(&click(&mut t, &cx, (300.0, 200.0), Mods::default())); + assert_eq!((&v["constantRadius"], &v["anchors"]), (&json!(false), &json!("touch"))); +} + +/// The preview's outline is the path the click draws: starting at 0° whatever the Constrain Angle, +/// or with `standardAnchors` off starting where the circle touches the path. +#[test] +fn the_preview_follows_the_anchor_options() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let start = |t: &CurvatureCircleTool, cx: &ToolContext| { + t.overlays(cx).iter().find_map(|o| match o { + Overlay::Path { path, .. } => path.elements().first().and_then(|e| e.end_point()), + _ => None, + }) + }; + let mut t = CurvatureCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (200.0, 98.0), Mods::default())); + let upright = start(&t, &cx).unwrap(); + let turned = ToolContext { constrain_angle: 30.0, ..cx }; + assert_eq!(start(&t, &turned), Some(upright)); + assert!(upright.distance(Point::new(200.0, 100.0)) > 1.0, "{upright:?}"); + t.set_option("standardAnchors", &json!(false)); + let at = start(&t, &cx).unwrap(); + assert!(at.distance(Point::new(200.0, 100.0)) < 1e-6, "{at:?}"); +} + +/// An option the tool lacks, a tolerance out of range and a switch that is not true or false are +/// errors, and `set_option` leaves the option as it was for them. +#[test] +fn invalid_options_are_refused() { + let mut t = CurvatureCircleTool::default(); + assert!(t.check_option("snapTolerance", &json!(0)).is_err()); + assert!(t.check_option("snapTolerance", &json!(41)).is_err()); + assert!(t.check_option("snapTolerance", &json!("5")).is_err()); + assert!(t.check_option("annotateRadius", &json!(1)).is_err()); + assert!(t.check_option("size", &json!(1)).is_err()); + assert!(t.check_option("snapTolerance", &json!(12.5)).is_ok()); + let before = t.options(); + t.set_option("snapTolerance", &json!(0)); + t.set_option("annotateRadius", &json!("no")); + assert_eq!(t.options(), before); +} diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 0c032e0684..7e334ce31f 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -92,6 +92,11 @@ pub fn pressure_size(size: f64, variation: f64, pressure: f64) -> f64 { /// The narrowest a Blob Brush or Eraser stroke gets, in points (their Size field's minimum). pub const MIN_BRUSH_SIZE: f64 = 0.1; +/// The modes the Blob Brush's Size takes (`sizeMode`). The Eraser's Size takes every +/// [`vectorcraft_brush::Variation`]. +pub const BLOB_SIZE_MODES: [vectorcraft_brush::Variation; 3] = + [vectorcraft_brush::Variation::Fixed, vectorcraft_brush::Variation::Pressure, vectorcraft_brush::Variation::StylusWheel]; + /// A pen's tilt as a lean on the page (each tilt's tangent) and its angle from upright in degrees, /// as Pointer Events' tiltX and tiltY convert to an altitude and an azimuth. fn pen_lean(tilt: [f32; 2]) -> ([f64; 2], f64) { diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 4f2fb7b463..ede52c46c7 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -85,6 +85,9 @@ const BAND_WORK_PER_CALL: usize = 20_000; const PREVIEW_FIDELITY_PX: f64 = 0.5; /// The Smooth tool's Fidelity (screen pixels) until Smooth Tool Options sets another. const SMOOTH_FIDELITY: f64 = 2.5; +/// The Smooth tool's Smoothness (percent) until Smooth Tool Options sets another: the strength +/// `path.smoothRegion` smooths with when a drag leaves it out. VectorCraft's own value. +const SMOOTH_SMOOTHNESS: f64 = 50.0; /// How far the pointer goes from the press point, in screen pixels, before a Shift-drag of the /// Eraser takes the 45° step it lies nearest to. const ERASER_SHIFT_PX: f64 = 3.0; @@ -146,9 +149,10 @@ pub struct GestureTool { pub fidelity: f64, /// Brush / eraser diameter in points (the Eraser's across its tip's long axis). pub size: f64, - /// Blob Brush and Eraser Tool Options' Size mode: Fixed or Pressure for the Blob Brush (with - /// Pressure the tip is `size` − `size_variation` wide at the lightest pen pressure and `size` + - /// `size_variation` at the heaviest), and any [`Variation`] for the Eraser. + /// Blob Brush and Eraser Tool Options' Size mode: Fixed, Pressure or Stylus Wheel for the Blob + /// Brush (with Pressure the tip is `size` − `size_variation` wide at the lightest pen pressure + /// and `size` + `size_variation` at the heaviest, and with Stylus Wheel from one end of an + /// airbrush pen's finger wheel travel to the other), and any [`Variation`] for the Eraser. pub size_mode: Variation, /// Blob Brush and Eraser Tool Options' Size Variation, in points. pub size_variation: f64, @@ -182,6 +186,11 @@ pub struct GestureTool { /// The Smooth tool's Fidelity (screen pixels), used when Alt switches the Pencil, Paintbrush or /// Blob Brush to Smooth. The engine sets it from Smooth Tool Options (`smoothFidelity`). smooth_fidelity: f64, + /// Smooth Tool Options' Smoothness (percent, 0 to 100): how strongly a Smooth drag smooths the + /// path before it is refitted. The Smooth tool's own (`smoothness`), and for the Pencil, + /// Paintbrush and Blob Brush the one an Alt smoothing drag uses, which the engine sets from + /// Smooth Tool Options (`smoothSmoothness`). + smoothness: f64, /// Active drag is smoothing with the Pencil, Paintbrush or Blob Brush (Alt held). smoothing: bool, /// The pointer has moved from the press point, by any distance (a move too short to add a @@ -907,6 +916,7 @@ impl GestureTool { live_preview: true, live_fit: true, smooth_fidelity: SMOOTH_FIDELITY, + smoothness: SMOOTH_SMOOTHNESS, smoothing: false, moved: false, marquee: false, @@ -1001,12 +1011,13 @@ impl GestureTool { } } - /// Give the Eraser's last stroke sample the pen's tilt and rotation of the event `ev`, a drag - /// within a pixel of that sample that adds none: a pen turned or tilted in place turns its tip - /// there, in the outline and in what the release erases. The sample keeps its pressure, which - /// the area outline of the drag was built with, and its pose when `ev` reads none. + /// Give the Eraser's or the Blob Brush's last stroke sample the pen's tilt, rotation and wheel + /// of the event `ev`, a drag within a pixel of that sample that adds none: a pen turned or + /// tilted in place, or its wheel turned there, changes its tip there, in the outline and in + /// what the release erases or paints. The sample keeps its pressure, which the area outline of + /// the drag was built with, and its pose when `ev` reads none. fn refresh_last_pose(&mut self, ev: &PointerEvent) { - if self.id != "eraser" || self.poses.len() != self.points.len() || ev.pen.is_none() { + if !matches!(self.id, "eraser" | "blobBrush") || self.poses.len() != self.points.len() || ev.pen.is_none() { return; } let pose = ev.pen.map(PenPose::sanitized); @@ -1126,8 +1137,8 @@ impl GestureTool { } /// The Blob Brush's or the Eraser's tip at the pointer, before and while painting: its outline - /// `size` across at its angle and roundness (the Eraser's as the pen varies them while it - /// erases, [`Self::tip_now`]), at the zoom, black on a white halo so it reads on + /// `size` across at its angle and roundness (as the pen varies them while it erases or + /// paints, [`Self::tip_now`]), at the zoom, black on a white halo so it reads on /// any art. Precise cursors show only the crosshair, and smoothing shows no tip. fn tip_outline(&self, cx: &ToolContext) -> Vec { let Some(at) = self.tip_at.filter(|_| !self.smoothing && !cx.precise_cursors) else { return vec![] }; @@ -1275,7 +1286,7 @@ impl GestureTool { outline.filter(|o| !o.elements().is_empty()) } - /// Does the tool's Size take Fixed or Pressure (the Blob Brush and the Eraser)? + /// Does the tool's Size take a variation mode (the Blob Brush and the Eraser)? fn varies_size(&self) -> bool { matches!(self.id, "blobBrush" | "eraser") } @@ -1365,14 +1376,23 @@ impl GestureTool { /// value on a mode that follows the pen goes from the value less its Variation to the value /// plus it as the pen reads now (the pressure once the pen has pressed less than fully, the /// tilt, rotation and wheel of the last point, and the bearing of the last point the pen leaned 1° or - /// more at), as `path.eraseRegion` reads the stroke; before a press, and for Random, Fixed and a - /// pen that gives no reading, the values themselves. The Blob Brush's are its own values. + /// more at), as `path.eraseRegion` reads the stroke; before a press, and for Random, Fixed, a + /// pen that gives no reading and a reading the release does not send (a mode set during the + /// drag), the values themselves. The Blob Brush's size follows the pen the + /// same way while it paints, as `path.blob` reads the stroke, and its angle and roundness are + /// its own values (a roundness of 0 included). fn tip_now(&self) -> [f64; 3] { - if self.id != "eraser" || !self.active { + if !matches!(self.id, "eraser" | "blobBrush") || !self.active { return [self.angle, self.roundness, self.size]; } - let pressure = if self.light { self.pressures.last().map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; - self.tip_for(pressure, self.poses.last().copied().flatten(), self.bearing) + // What the release does not read ([`Self::reads_pressures`], [`Self::reads_poses`]) reads ½. + let pressure = if self.reads_pressures() { self.pressures.last().map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; + let (pose, bearing) = if self.reads_poses() { (self.poses.last().copied().flatten(), self.bearing) } else { (None, None) }; + let tip = self.tip_for(pressure, pose, bearing); + if self.id == "blobBrush" { + return [self.angle, self.roundness, tip[2]]; + } + tip } /// The tip's angle, roundness and size for a pen at `pressure` held as `pose`, leaning toward @@ -1563,8 +1583,9 @@ impl GestureTool { /// The preview of a stroke being drawn: [`Self::freehand_params`], except that a stroke that /// redraws a selected path is shown as it is drawn, joined at its start to the point of the - /// path nearest to it, with no fill, and leaves the path and the selection as they are: where - /// the stroke ends is only known at the release, which redraws the path (`finish`). + /// path nearest to it, with no fill, on top in any drawing mode, and leaves the path and the + /// selection as they are: where the stroke ends is only known at the release, which redraws + /// the path (`finish`). fn drawing_params(&self, cx: &ToolContext) -> Value { let mut v = self.freehand_params(cx, false); let Some((id, _)) = self.redraw else { return v }; @@ -1573,7 +1594,7 @@ impl GestureTool { } v["fill"] = json!(false); v["keepSelected"] = json!(false); - v["leaveSelection"] = json!(true); + v["preview"] = json!(true); let on = self.points.first().and_then(|&p| cx.doc.node(id)?.path_data()?.nearest(p)).map(|n| n.3); if let (Some(on), Some(pts)) = (on, v["points"].as_array_mut()) { pts.insert(0, json!([on.x, on.y])); @@ -1590,7 +1611,7 @@ impl GestureTool { if pts.len() >= 2 && has_selected_smooth_path(cx) { return vec![Action::Exec( "path.smoothRegion".into(), - json!({"points": points_json(pts), "radius": radius, "fidelity": smooth_tolerance(cx, self.smooth_fidelity)}), + json!({"points": points_json(pts), "radius": radius, "fidelity": smooth_tolerance(cx, self.smooth_fidelity), "smoothness": self.smoothness}), )]; } return vec![]; @@ -1655,7 +1676,7 @@ impl GestureTool { "smooth" if pts.len() >= 2 && has_selected_smooth_path(cx) => { vec![Action::Exec( "path.smoothRegion".into(), - json!({"points": points_json(pts), "radius": radius, "fidelity": smooth_tolerance(cx, self.fidelity)}), + json!({"points": points_json(pts), "radius": radius, "fidelity": smooth_tolerance(cx, self.fidelity), "smoothness": self.smoothness}), )] } "pathEraser" if has_sel => vec![Action::Exec("path.eraseSegments".into(), json!({"points": points_json(pts), "width": reach(cx, 8.0)}))], @@ -1861,6 +1882,11 @@ impl Tool for GestureTool { fn wants_samples(&self) -> bool { matches!(self.id, "pencil" | "paintbrush" | "blobBrush" | "eraser" | "knife" | "smooth" | "pathEraser") } + /// The Blob Brush's and the Eraser's tip varies with the wheel when a value is on Stylus Wheel + /// with a Variation above 0. + fn reads_wheel(&self, _cx: &ToolContext) -> bool { + self.tip_modes().contains(&Variation::StylusWheel) + } /// The outline of a long Blob Brush or Eraser drag, and a smoothing drag's band outlined again /// after a zoom change, reach the whole drag over several frames. fn overlays_pending(&self) -> bool { @@ -2089,7 +2115,7 @@ impl Tool for GestureTool { "closeWithin": self.close_within }) } - "smooth" => json!({"fidelity": self.fidelity}), + "smooth" => json!({"fidelity": self.fidelity, "smoothness": self.smoothness}), "blobBrush" => { json!({ "fidelity": self.fidelity, @@ -2120,10 +2146,10 @@ impl Tool for GestureTool { match key { "fidelity" => self.fidelity = v.as_f64().unwrap_or(self.fidelity).clamp(super::min_fidelity(self.id), 100.0), "size" => self.size = v.as_f64().unwrap_or(self.size).clamp(0.1, 1000.0), - // The Blob Brush's Size is Fixed or Pressure; the Eraser's Angle, Roundness and Size - // take any mode. + // The Blob Brush's Size is Fixed, Pressure or Stylus Wheel; the Eraser's Angle, + // Roundness and Size take any mode. "sizeMode" if self.varies_size() => match v.as_str().and_then(Variation::parse) { - Some(m) if self.id == "eraser" || matches!(m, Variation::Fixed | Variation::Pressure) => self.size_mode = m, + Some(m) if self.id == "eraser" || super::BLOB_SIZE_MODES.contains(&m) => self.size_mode = m, _ => {} }, "angleMode" if self.id == "eraser" => self.angle_mode = v.as_str().and_then(Variation::parse).unwrap_or(self.angle_mode), @@ -2142,6 +2168,11 @@ impl Tool for GestureTool { "smoothFidelity" if matches!(self.id, "pencil" | "paintbrush" | "blobBrush") => { self.smooth_fidelity = v.as_f64().unwrap_or(self.smooth_fidelity).clamp(super::min_fidelity("smooth"), 100.0) } + // A value that is not a number from 0 to 100 leaves the Smoothness as it is. + "smoothness" if self.id == "smooth" => self.smoothness = v.as_f64().filter(|n| (0.0..=100.0).contains(n)).unwrap_or(self.smoothness), + "smoothSmoothness" if matches!(self.id, "pencil" | "paintbrush" | "blobBrush") => { + self.smoothness = v.as_f64().filter(|n| (0.0..=100.0).contains(n)).unwrap_or(self.smoothness) + } "keepSelected" => self.keep_selected = v.as_bool().unwrap_or(self.keep_selected), "mergeOnlySelection" => self.merge_only_selection = v.as_bool().unwrap_or(self.merge_only_selection), "editWithin" => self.edit_within = v.as_f64().unwrap_or(self.edit_within).clamp(0.0, 100.0), @@ -2149,17 +2180,19 @@ impl Tool for GestureTool { _ => {} } } - /// The options the tool shows ([`Self::options`]), and the Smooth tool's Fidelity that the - /// Pencil, Paintbrush and Blob Brush smooth with while Alt is held (`smoothFidelity`). + /// The options the tool shows ([`Self::options`]), and the Smooth tool's Fidelity and Smoothness + /// that the Pencil, Paintbrush and Blob Brush smooth with while Alt is held (`smoothFidelity`, + /// `smoothSmoothness`). fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { use crate::option_check as c; - let smooth_store = key == "smoothFidelity" && matches!(self.id, "pencil" | "paintbrush" | "blobBrush"); + let smooth_store = matches!(key, "smoothFidelity" | "smoothSmoothness") && matches!(self.id, "pencil" | "paintbrush" | "blobBrush"); if !smooth_store && self.options().get(key).is_none() { return Err(c::unknown(key)); } match key { "fidelity" => c::number(key, v, super::min_fidelity(self.id), 100.0), "smoothFidelity" => c::number(key, v, super::min_fidelity("smooth"), 100.0), + "smoothness" | "smoothSmoothness" => c::number(key, v, 0.0, 100.0), "size" => c::number(key, v, 0.1, 1000.0), "sizeVariation" => c::number(key, v, 0.0, 1000.0), "angle" => c::number(key, v, -180.0, 180.0), @@ -2167,9 +2200,9 @@ impl Tool for GestureTool { "editWithin" | "closeWithin" => c::number(key, v, 0.0, 100.0), "angleVariation" => c::number(key, v, 0.0, 180.0), "roundnessVariation" => c::number(key, v, 0.0, 100.0), - // The Blob Brush's Size is Fixed or Pressure; the Eraser's Angle, Roundness and Size - // take any mode (`set_option`). - "sizeMode" if self.id != "eraser" => c::one_of(key, v, &[Variation::Fixed.id(), Variation::Pressure.id()]), + // The Blob Brush's Size is Fixed, Pressure or Stylus Wheel; the Eraser's Angle, + // Roundness and Size take any mode (`set_option`). + "sizeMode" if self.id != "eraser" => c::one_of(key, v, &super::BLOB_SIZE_MODES.map(Variation::id)), "sizeMode" | "angleMode" | "roundnessMode" => c::one_of(key, v, &Variation::ALL.map(Variation::id)), "fill" | "altSmooth" | "livePreview" | "liveFit" | "keepSelected" | "mergeOnlySelection" => c::boolean(key, v), _ => Err(c::unknown(key)), diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 24a0e1e5e6..c8aa002add 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -690,7 +690,10 @@ fn blob_brush_alt_switches_to_the_smooth_tool() { let acts = drag_held(&mut t, &cx, &stroke, alt); assert!(acts[..acts.len() - 1].iter().all(|a| a.is_empty()), "{acts:?}"); let v = smoothed(&acts).unwrap_or_else(|| panic!("{acts:?}")); - assert_eq!(v, json!({"points": [[50.0, 150.0], [150.0, 150.0], [250.0, 160.0]], "radius": cx.tol(12.0), "fidelity": cx.tol(SMOOTH_FIDELITY)})); + assert_eq!( + v, + json!({"points": [[50.0, 150.0], [150.0, 150.0], [250.0, 160.0]], "radius": cx.tol(12.0), "fidelity": cx.tol(SMOOTH_FIDELITY), "smoothness": SMOOTH_SMOOTHNESS}) + ); // Mid-drag the cursor stays the Smooth tool's when Alt is let go, and the line is thin with // no length label. t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0).with_mods(alt)); @@ -882,7 +885,7 @@ fn pencil_previews_a_redraw_as_the_stroke_drawn_and_redraws_at_the_release() { let previews: Vec<&Value> = drawing.iter().flatten().filter_map(|a| if let Action::Preview(_, v) = a { Some(v) } else { None }).collect(); assert!(!previews.is_empty(), "{acts:?}"); for v in previews { - assert!(v.get("redraw").is_none() && v["fill"] == false && v["keepSelected"] == false && v["leaveSelection"] == true, "{v}"); + assert!(v.get("redraw").is_none() && v["fill"] == false && v["keepSelected"] == false && v["preview"] == true, "{v}"); assert_eq!(v["points"][0], json!([350.0, 300.0]), "joined to the path where it starts: {v}"); assert_eq!(v["points"][1], json!([350.0, 304.0]), "{v}"); } @@ -1783,6 +1786,50 @@ fn alt_smoothing_uses_the_smooth_tools_fidelity() { } } +/// The Smooth tool sends Smooth Tool Options' Smoothness (50% until it is set) with each drag, and +/// an Alt smoothing drag with the Pencil, Paintbrush or Blob Brush sends the one the engine gives it +/// (`smoothSmoothness`). A value that is not a number from 0 to 100 is refused and sets nothing. +#[test] +fn smooth_drags_send_the_smoothness() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let pts = [(50.0, 150.0), (150.0, 150.0), (250.0, 160.0)]; + let smoothness = |acts: &[Vec]| match acts.last().and_then(|a| a.first()) { + Some(Action::Exec(c, v)) if c == "path.smoothRegion" => v["smoothness"].as_f64(), + a => panic!("expected path.smoothRegion, got: {a:?}"), + }; + let mut t = GestureTool::new("smooth"); + assert_eq!(t.options()["smoothness"], json!(50.0)); + assert_eq!(smoothness(&drag(&mut t, &cx, &pts, Mods::default())), Some(50.0)); + for bad in [json!(-1), json!(100.5), json!("30"), json!(true)] { + assert_eq!(t.check_option("smoothness", &bad), Err("`smoothness` must be a number from 0 to 100".into()), "{bad}"); + t.set_option("smoothness", &bad); + assert_eq!(t.options()["smoothness"], json!(50.0), "{bad}"); + } + for ok in [0.0, 75.0, 100.0] { + assert_eq!(t.check_option("smoothness", &json!(ok)), Ok(())); + t.set_option("smoothness", &json!(ok)); + assert_eq!(smoothness(&drag(&mut t, &cx, &pts, Mods::default())), Some(ok)); + } + let alt = Mods { alt: true, ..Default::default() }; + for (id, alt_smooth) in [("pencil", true), ("blobBrush", false), ("paintbrush", false)] { + let mut t = GestureTool::new(id); + t.set_option("altSmooth", &json!(alt_smooth)); + assert_eq!(smoothness(&drag_held(&mut t, &cx, &pts, alt)), Some(50.0), "{id}"); + assert_eq!(t.check_option("smoothSmoothness", &json!(101)), Err("`smoothSmoothness` must be a number from 0 to 100".into()), "{id}"); + t.set_option("smoothSmoothness", &json!(101)); + t.set_option("smoothness", &json!(20.0)); + assert_eq!(smoothness(&drag_held(&mut t, &cx, &pts, alt)), Some(50.0), "{id}: only smoothSmoothness sets it"); + t.set_option("smoothSmoothness", &json!(20.0)); + assert_eq!(smoothness(&drag_held(&mut t, &cx, &pts, alt)), Some(20.0), "{id}"); + assert!(t.options().get("smoothness").is_none() && t.options().get("smoothSmoothness").is_none(), "{id}"); + } +} + /// The Smooth tool's Fidelity is in screen pixels: the Smooth tool and an Alt smoothing drag with /// the Pencil, Paintbrush or Blob Brush send it in points at Fidelity / zoom, so a drag smooths as /// much on screen at any zoom. @@ -3314,7 +3361,10 @@ fn the_eraser_tip_follows_its_variation_modes() { assert_eq!(t.check_option("angleMode", &json!("wheel")), Err(format!("`angleMode` {modes}"))); assert_eq!(t.check_option("angleVariation", &json!(181)), Err("`angleVariation` must be a number from 0 to 180".into())); assert_eq!(t.check_option("roundnessVariation", &json!(500)), Err("`roundnessVariation` must be a number from 0 to 100".into())); - assert_eq!(GestureTool::new("blobBrush").check_option("sizeMode", &json!("tilt")), Err("`sizeMode` must be one of `fixed`, `pressure`".into())); + assert_eq!( + GestureTool::new("blobBrush").check_option("sizeMode", &json!("tilt")), + Err("`sizeMode` must be one of `fixed`, `pressure`, `stylusWheel`".into()) + ); // A mode it does not have leaves the mode as it was; a Variation is kept within its range. t.set_option("angleMode", &json!("wheel")); t.set_option("roundnessVariation", &json!(500)); @@ -3352,7 +3402,7 @@ fn the_eraser_tip_follows_its_variation_modes() { t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); near(tip(&t), (190.0, 47.5, 210.0, 52.5)); t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) }); - // The Blob Brush's Size is Fixed or Pressure, and its Angle and Roundness have no menus. + // The Blob Brush's Size is Fixed, Pressure or Stylus Wheel, and its Angle and Roundness have no menus. let mut b = GestureTool::new("blobBrush"); b.set_option("sizeMode", &json!("tilt")); b.set_option("angleMode", &json!("rotation")); @@ -3362,6 +3412,77 @@ fn the_eraser_tip_follows_its_variation_modes() { assert_eq!(b.options()["sizeMode"], json!("pressure")); } +/// The Blob Brush's Size on Stylus Wheel follows the wheel the pen recorded, in the tip outline +/// while it paints (its roundness kept as set, 0% included) and in the points the release sends; +/// a pen that gives no wheel keeps the Size. +#[test] +fn the_blob_brush_size_follows_the_stylus_wheel() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let tip = |t: &GestureTool| match &t.overlays(&cx)[..] { + [.., Overlay::Path { path, color: [0, 0, 0], width: 1.0, .. }] => vectorcraft_geom::Shape::bounding_box(path), + o => panic!("{o:?}"), + }; + let near = |b: vectorcraft_geom::Rect, want: (f64, f64, f64, f64)| { + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); + }; + let mut t = GestureTool::new("blobBrush"); + assert_eq!(t.check_option("sizeMode", &json!("stylusWheel")), Ok(())); + for (k, v) in [("size", json!(20)), ("roundness", json!(50)), ("sizeMode", json!("stylusWheel")), ("sizeVariation", json!(8))] { + t.set_option(k, &v); + } + assert_eq!((t.options()["sizeMode"].clone(), t.options()["sizeVariation"].clone()), (json!("stylusWheel"), json!(8.0))); + // Before a press the outline is the set tip, 20 by 10 pt. + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 100.0, 50.0)); + near(tip(&t), (90.0, 45.0, 110.0, 55.0)); + // The wheel at the far end of its travel gives 28 by 14 pt, and half way 20 by 10. + let wheel = |w: Option| Some(PenPose { tilt: None, rotation: None, wheel: w }); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); + near(tip(&t), (186.0, 43.0, 214.0, 57.0)); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(0.5)), ..PointerEvent::new(PointerKind::Drag, 300.0, 50.0) }); + near(tip(&t), (290.0, 45.0, 310.0, 55.0)); + // The wheel turned with the pen held in place: the tip there and the release follow it. + t.pointer(&cx, &PointerEvent { pen: wheel(Some(0.0)), ..PointerEvent::new(PointerKind::Drag, 300.0, 50.0) }); + near(tip(&t), (294.0, 47.0, 306.0, 53.0)); + let acts = t.pointer(&cx, &PointerEvent { pen: wheel(Some(0.0)), ..PointerEvent::new(PointerKind::Up, 300.0, 50.0) }); + let Some(Action::Exec(c, v)) = acts.first() else { panic!("{acts:?}") }; + assert_eq!((c.as_str(), &v["sizeMode"], &v["sizeVariation"]), ("path.blob", &json!("stylusWheel"), &json!(8.0))); + assert_eq!( + v["points"], + json!([[100.0, 50.0, null, null, null, null, 1.0], [200.0, 50.0, null, null, null, null, 1.0], [300.0, 50.0, null, null, null, null, 0.0]]) + ); + // A pen without a wheel keeps the set tip. + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); + near(tip(&t), (190.0, 45.0, 210.0, 55.0)); + t.pointer(&cx, &PointerEvent { pen: wheel(None), ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) }); + // A 0% round tip stays as flat as set while the wheel widens it. + t.set_option("roundness", &json!(0)); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) }); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) }); + let flat = tip(&t); + assert!((flat.width() - 28.0).abs() < 0.01 && flat.height() < 0.1, "{flat:?}"); + t.pointer(&cx, &PointerEvent { pen: wheel(Some(1.0)), ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) }); + // Size set from Fixed to Stylus Wheel or Pressure during a drag: the release reads no wheel or + // pressure for the points before it, so the tip keeps the Size, as the release paints. + t.set_option("roundness", &json!(50)); + for (mode, pressure) in [("stylusWheel", 1.0), ("pressure", 0.25)] { + t.set_option("sizeMode", &json!("fixed")); + let ev = |kind, x| PointerEvent { pen: wheel(Some(1.0)), pressure, ..PointerEvent::new(kind, x, 50.0) }; + t.pointer(&cx, &ev(PointerKind::Down, 100.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 200.0)); + t.set_option("sizeMode", &json!(mode)); + t.pointer(&cx, &ev(PointerKind::Drag, 300.0)); + near(tip(&t), (290.0, 45.0, 310.0, 55.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 300.0)); + let Some(Action::Exec(_, v)) = acts.first() else { panic!("{acts:?}") }; + assert_eq!(v["points"], json!([[100.0, 50.0], [200.0, 50.0], [300.0, 50.0]]), "{mode}"); + } +} + /// An Eraser value on Stylus Wheel follows the wheel the pen recorded, in the tip outline while it /// erases and in the points the release sends; a pen that gives no wheel reads half way, the value /// itself. @@ -4008,3 +4129,26 @@ fn pencil_alt_toggles_to_smooth_when_enabled_and_closes_when_disabled() { assert!(matches!(&last[0], Action::Preview(_, v) if v["closed"] == true && v["style"] == "pencil")); assert_eq!(last[1], Action::Commit); } + +#[test] +fn a_tip_reads_the_wheel_only_with_a_value_on_stylus_wheel() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + for id in ["pencil", "paintbrush", "blobBrush", "eraser"] { + assert!(!GestureTool::new(id).reads_wheel(&cx), "{id} at its defaults"); + } + for value in ["angle", "roundness", "size"] { + let mut t = GestureTool::new("eraser"); + t.set_option(&format!("{value}Mode"), &json!("stylusWheel")); + assert!(!t.reads_wheel(&cx), "{value} on Stylus Wheel with no Variation"); + t.set_option(&format!("{value}Variation"), &json!(4)); + assert!(t.reads_wheel(&cx), "{value} on Stylus Wheel"); + t.set_option(&format!("{value}Mode"), &json!("pressure")); + assert!(!t.reads_wheel(&cx), "{value} on Pressure"); + } + let mut t = GestureTool::new("blobBrush"); + t.set_option("sizeMode", &json!("stylusWheel")); + t.set_option("sizeVariation", &json!(4)); + assert!(t.reads_wheel(&cx), "the Blob Brush's size on Stylus Wheel"); +} diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 486de86876..ec2b83f1a6 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -319,6 +319,12 @@ pub trait Tool: Send { fn wants_samples(&self) -> bool { false } + /// Does a stroke the tool draws now vary with an airbrush pen's finger wheel (a brush or tip + /// with Stylus Wheel variation)? A host that has to open a tablet interface of its own to read + /// the wheel opens it only while this is so. + fn reads_wheel(&self, _cx: &ToolContext) -> bool { + false + } /// Is the tool waiting for work it runs on another thread (the planar map of a large selection /// for the Shape Builder and the Live Paint Bucket, a Shape Builder merge of one)? It /// highlights nothing under the pointer until a map is done. While this holds, the desktop app @@ -639,6 +645,7 @@ pub(crate) mod testutil { shape_widgets: true, fill_active: true, gradient_stop: None, + tool_paints: false, appearance_item: None, constrain_angle: 0.0, keyboard_increment: 1.0, diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index abae4bc5ea..92377ac2d7 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -12,6 +12,7 @@ //! point closes the path, a click on an end of an open path goes on drawing from it, and Escape //! or Enter ends the path. The path's points show as circles, without handles, and a preview //! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step. +//! While no path is being drawn, the tool edits the selected paths ([`edit`]). //! //! A handle stands beyond each end of the path being drawn, or, while none is, of the selected //! path, where that end is a straight line or a circular arc. Dragging it makes the line or arc @@ -33,6 +34,8 @@ //! the document or the selection changes, the canvas hovers the still pointer again. Shift does //! not constrain Quick Pen points, so it does not change the snapping. +mod edit; + use std::f64::consts::{FRAC_PI_2, PI}; use std::sync::Arc; @@ -44,6 +47,7 @@ use crate::draw2::FEEDBACK; use crate::guides::{DrawSnap, Leave, SnapSettings}; use crate::pen::{continue_from, open_end_at}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use edit::{Edit, Grab}; use length::EndPiece; /// The tool's id. @@ -449,6 +453,8 @@ pub struct QuickPenTool { turn: f64, drawing: Option, press: Option, + /// A press on an anchor or a segment of a selected path while no path is being drawn. + edit: Option, length: Option, hover: Option, snap: DrawSnap, @@ -466,6 +472,7 @@ impl Default for QuickPenTool { turn: DEFAULT_TURN, drawing: None, press: None, + edit: None, length: None, hover: None, snap: DrawSnap::default(), @@ -657,8 +664,9 @@ impl QuickPenTool { } /// What a press draws: a piece on the path being drawn, its closing piece, or a new path (from - /// an end of an open path, the path goes on). - fn press_down(&mut self, cx: &ToolContext, p: Point) -> Vec { + /// an end of an open path, the path goes on). With no path being drawn, a press on an anchor + /// or a segment of a selected path waits to see whether it drags ([`edit`]). + fn press_down(&mut self, cx: &ToolContext, p: Point, shift: bool) -> Vec { if self.drawing.is_some() && self.active(cx).is_none() { self.drawing = None; } @@ -689,11 +697,11 @@ impl QuickPenTool { self.length = Some(drag); return vec![]; } - self.click(cx, p) + self.click(cx, p, shift) } /// What a press away from a length handle, or a click on one, draws. - fn click(&mut self, cx: &ToolContext, p: Point) -> Vec { + fn click(&mut self, cx: &ToolContext, p: Point, shift: bool) -> Vec { let tol = point_tol(cx); if let Some((id, sp)) = self.active(cx) { let (first, last) = match (sp.anchors.first(), sp.anchors.last()) { @@ -724,28 +732,90 @@ impl QuickPenTool { self.press = Some(Press { at: p, dragged: false, begun: true, end: Some((p, snapped)) }); return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } + // An anchor of a selected path comes first, then an open end, then a selected path's + // segment. + let grab = edit::grab_at(cx, p, tol); + if let Some(grab @ Grab::Anchor { .. }) = grab { + self.edit = Some(Edit::new(cx, grab, p, shift)); + return vec![]; + } if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None) && cx.doc.is_editable(id) { - // From its start, `continue_from` reverses the path first; the tool then sees it. - self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() }); - let mut out = continue_from(cx, id, si, at_first); - out.push(drawn()); - return out; + return self.continue_path(cx, id, si, at_first); } + if let Some(grab) = grab { + self.edit = Some(Edit::new(cx, grab, p, shift)); + return vec![]; + } + self.start_path(cx, p) + } + + /// Goes on drawing from an end of subpath `si` of path `id`. + fn continue_path(&mut self, cx: &ToolContext, id: NodeId, si: usize, at_first: bool) -> Vec { + // From its start, `continue_from` reverses the path first; the tool then sees it. + self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() }); + let mut out = vec![]; + // Anchors selected by an earlier click or drag: the path is selected whole again. + if !cx.selection.anchors.is_empty() || !cx.selection.segments.is_empty() { + let top = cx.doc.parent_of(id).filter(|p| cx.doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id); + out.push(Action::Exec("select.set".into(), json!({"ids": [top.0]}))); + } + out.extend(continue_from(cx, id, si, at_first)); + out.push(drawn()); + out + } + + /// Starts a new path at `p`. + fn start_path(&mut self, cx: &ToolContext, p: Point) -> Vec { let q = self.snap.press(cx, p, &[], None); self.drawing = Some(Drawing { start: Some(q), ..Drawing::default() }); vec![Action::Exec(COMMAND.into(), self.params(false)), Action::Notify("created".into())] } - /// Ends the path being drawn; a press that added a piece is taken back. - fn end(&mut self) -> Vec { + /// Ends the path being drawn; a press that added a piece, or moved part of a path, is taken + /// back. A move that another command's edit interrupted is kept with that edit. + fn end(&mut self, cx: &ToolContext) -> Vec { self.drawing = None; self.pointer = None; self.snap.clear(); + let moved = self.edit.take().filter(|e| e.began).map(|mut e| if e.open(cx) { Action::Cancel } else { Action::Commit }); match self.press.take() { Some(pr) if pr.begun => vec![Action::Cancel], - _ => vec![], + _ => moved.into_iter().collect(), + } + } + + /// The release of a press on an anchor or a segment of a selected path: a drag, also one let + /// go past the drag distance after shorter drag events, moves what it holds to `p` and ends + /// its undo step. A click on an end of an open path goes on drawing from it, a click on another + /// anchor selects it alone (with Shift, adds it to the selected anchors or takes it out), and a + /// click on a segment starts a new path there. A click whose path or selection another command + /// changed while the press was down does nothing. + fn release_edit(&mut self, cx: &ToolContext, mut e: Edit, p: Point) -> Vec { + if e.began || p.distance(e.start) >= cx.tol(DRAG_PX) { + let mut out = e.drag(cx, p); + // A drag that could not begin (its path or the selection changed under the press) has + // no step to end. + out.extend(e.finish(cx)); + return out; + } + if !e.unchanged(cx) { + return vec![]; + } + match e.grab { + Grab::Anchor { id, si, ai, .. } if e.shift => { + // `select.anchors` toggles from every anchor of a path selected whole on its own, + // so the first Shift-click there selects the anchor alone. + let whole = cx.selection.anchors.is_empty() && cx.selection.objects.len() <= 1; + let mode = if whole { "set" } else { "toggle" }; + vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": mode}))] + } + Grab::Anchor { id, si, ai, end: true, .. } => self.continue_path(cx, id, si, ai == 0), + Grab::Anchor { id, si, ai, .. } => { + vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"}))] + } + Grab::Segment { .. } => self.start_path(cx, e.start), } } @@ -929,7 +999,12 @@ impl QuickPenTool { return if drag.begun { vec![Action::Commit] } else { vec![] }; } if !drag.dragged { - let mut out = self.click(cx, drag.press); + let mut out = self.click(cx, drag.press, false); + // A handle over a segment of the selected path: the press has ended, so the click + // there is released at once. + if let Some(e) = self.edit.take() { + out.extend(self.release_edit(cx, e, drag.press)); + } if self.press.take().is_some_and(|pr| pr.begun) { out.extend([Action::Commit, Action::Notify(PLACED.into())]); } @@ -978,7 +1053,7 @@ impl Tool for QuickPenTool { } fn busy(&self) -> bool { - self.press.is_some() || self.length.is_some() + self.press.is_some() || self.edit.is_some() || self.length.is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { @@ -992,7 +1067,7 @@ impl Tool for QuickPenTool { vec![] } PointerKind::Down => { - if self.press.is_some() || self.length.is_some() { + if self.press.is_some() || self.edit.is_some() || self.length.is_some() { return vec![]; } // The hover shows again when the pointer moves after the press: the point the press @@ -1003,10 +1078,16 @@ impl Tool for QuickPenTool { } self.hover = None; self.pointer = None; - self.press_down(cx, p) + self.press_down(cx, p, ev.mods.shift) } PointerKind::Drag if self.length.is_some() => self.length_drag_to(cx, p), PointerKind::Drag => { + if let Some(e) = self.edit.as_mut() { + if !e.began && p.distance(e.start) < cx.tol(DRAG_PX) { + return vec![]; + } + return e.drag(cx, p); + } let Some(mut pr) = self.press else { return vec![] }; if !pr.dragged && p.distance(pr.at) < cx.tol(DRAG_PX) { return vec![]; @@ -1019,6 +1100,9 @@ impl Tool for QuickPenTool { self.drag_to(cx, p) } PointerKind::Up => { + if let Some(e) = self.edit.take() { + return self.release_edit(cx, e, p); + } if self.length.is_some() { self.snap.clear(); // The end goes where the press is let go, also past the last drag. @@ -1054,6 +1138,12 @@ impl Tool for QuickPenTool { } fn notify(&mut self, cx: &ToolContext, what: &str) { + if what == edit::MOVED { + if let Some(e) = self.edit.as_mut() { + e.revision = Some(cx.revision); + } + return; + } if what == DRAWN && let Some(drag) = self.length.as_mut() { @@ -1106,6 +1196,8 @@ impl Tool for QuickPenTool { /// The drawing goes on only when the path is back as it was before the press. fn drop_press(&mut self, cx: &ToolContext) -> Vec { self.snap.clear(); + // The session takes back what an edit moved; the release that follows does nothing. + self.edit = None; if let Some(drag) = self.length.take() { self.restore_last_piece(&drag); if let Some(dr) = self.drawing.as_mut() { @@ -1158,7 +1250,7 @@ impl Tool for QuickPenTool { ToolKey::Enter if self.length.is_some() => vec![], // C and [ ] change the last piece once the drag has ended. ToolKey::Letter('c') | ToolKey::BracketLeft | ToolKey::BracketRight if self.length.is_some() => vec![], - ToolKey::Escape | ToolKey::Enter => self.end(), + ToolKey::Escape | ToolKey::Enter => self.end(cx), ToolKey::Letter('c') => { if self.last_sharp_arc(cx).is_none() { return vec![]; @@ -1206,15 +1298,16 @@ impl Tool for QuickPenTool { } } - fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + fn deactivate(&mut self, cx: &ToolContext) -> Vec { self.drawing = None; self.snap.clear(); + let moved = self.edit.take().and_then(|mut e| e.finish(cx)); if self.length.take().is_some_and(|drag| drag.begun) { return vec![Action::Commit]; } match self.press.take() { Some(pr) if pr.begun => vec![Action::Commit], - _ => vec![], + _ => moved.into_iter().collect(), } } @@ -1238,6 +1331,9 @@ impl Tool for QuickPenTool { fn overlays(&self, cx: &ToolContext) -> Vec { // A stale hover's Smart Guides go with its preview. let mut o = if self.hover_stale(cx) { vec![] } else { self.snap.guides().to_vec() }; + if let Some(e) = &self.edit { + o.extend(e.guides.iter().cloned()); + } // The length handles: a line from each end to a handle circle beyond it; during a drag, the // one being dragged, where the changed end is. let handles: Vec<(Point, Point)> = match &self.length { @@ -1247,7 +1343,7 @@ impl Tool for QuickPenTool { let piece = sp.and_then(|sp| length::end_piece(sp, h.at_start)); piece.map(|pc| (pc.end, pc.end + pc.out * cx.tol(LENGTH_HANDLE_PX))).into_iter().collect() } - None if self.press.is_none() => self.length_handles(cx).iter().map(|h| (h.piece.end, h.at)).collect(), + None if self.press.is_none() && self.edit.is_none() => self.length_handles(cx).iter().map(|h| (h.piece.end, h.at)).collect(), None => vec![], }; for &(a, b) in &handles { @@ -1306,7 +1402,17 @@ impl Tool for QuickPenTool { let close = sp.anchors.len() >= 2 && sp.anchors.first().is_some_and(|f| f.p.distance(p) <= tol); return if close { Cursor::PenClose } else { Cursor::PenDrawing }; } - if open_end_at(cx, p, tol, None).is_some() { Cursor::PenContinue } else { Cursor::Pen } + if let Some(e) = &self.edit { + return if e.began { Cursor::Move } else { edit::cursor(cx, e.grab) }; + } + let grab = edit::grab_at(cx, p, tol); + if let Some(grab @ Grab::Anchor { .. }) = grab { + return edit::cursor(cx, grab); + } + if open_end_at(cx, p, tol, None).is_some() { + return Cursor::PenContinue; + } + grab.map_or(Cursor::Pen, |grab| edit::cursor(cx, grab)) } fn options(&self) -> Value { diff --git a/crates/tools/src/quickpen/edit.rs b/crates/tools/src/quickpen/edit.rs new file mode 100644 index 0000000000..e06680d282 --- /dev/null +++ b/crates/tools/src/quickpen/edit.rs @@ -0,0 +1,211 @@ +//! Editing with the Quick Pen while no path is being drawn: a drag on an anchor of a selected path +//! moves it, and a drag on one of its segments moves that segment (`path.moveAnchors` with +//! `interpolate`: a segment with one moved end is turned and scaled to its new ends, so a line +//! stays a line and an arc stays an arc of the same angle; at a smooth point, where two arcs join, +//! the handles stay in line and the arcs bend to meet). The moved anchor snaps as a Direct +//! Selection drag's does. A click on an anchor selects it, Shift-click adds it to the selected anchors or takes it +//! out, and the canvas context menu's Delete then removes them (`edit.clear`). A click on an end +//! of an open path goes on drawing from it, as before. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_doc::{AnchorRef, Node, NodeId, Selection}; +use vectorcraft_geom::Point; + +use super::{same_node, shared_node}; +use crate::draw2::{anchor_in, segment_in, shown_paths}; +use crate::guides::{PointSnap, Targets}; +use crate::{Action, Cursor, Overlay, ToolContext}; + +/// The notice the tool asks for after each preview of a drag, to see the document's revision then. +pub(super) const MOVED: &str = "moved"; + +/// What a press holds. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Grab { + /// Anchor `ai` of subpath `si` of path `id`, at `at`; `end` when it is an end of an open subpath. + Anchor { id: NodeId, si: usize, ai: usize, at: Point, end: bool }, + /// The segment from anchor `seg` of subpath `si` of path `id` to the next one. + Segment { id: NodeId, si: usize, seg: usize }, +} + +impl Grab { + /// The path the grab is on. + pub(super) fn id(self) -> NodeId { + match self { + Grab::Anchor { id, .. } | Grab::Segment { id, .. } => id, + } + } + + /// The anchors the drag moves when they are not already selected: the anchor, or the + /// segment's two ends. + fn anchors(self, cx: &ToolContext) -> Option> { + match self { + Grab::Anchor { si, ai, .. } => Some(vec![(si, ai)]), + Grab::Segment { id, si, seg } => { + let n = cx.doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.len(); + Some(vec![(si, seg), (si, (seg + 1).checked_rem(n)?)]) + } + } + } +} + +/// An anchor or a segment of a selected path under `p`, within the tool's point tolerance `tol`. +/// Anchors come before segments. +pub(super) fn grab_at(cx: &ToolContext, p: Point, tol: f64) -> Option { + let shown = shown_paths(cx); + if let Some((id, si, ai)) = anchor_in(cx, shown.iter().copied(), p, tol) { + let sp = cx.doc.node(id)?.path_data()?.subpaths.get(si)?; + let at = sp.anchors.get(ai)?.p; + let end = !sp.closed && (ai == 0 || ai + 1 == sp.anchors.len()); + return Some(Grab::Anchor { id, si, ai, at, end }); + } + segment_in(cx, shown, p, tol).map(|(id, si, seg, _)| Grab::Segment { id, si, seg }) +} + +/// The cursor over `grab`: an open end shows that a click goes on drawing from it, another anchor +/// that it can be selected and moved, and a segment that it moves. +pub(super) fn cursor(cx: &ToolContext, grab: Grab) -> Cursor { + match grab { + Grab::Anchor { end: true, .. } => Cursor::PenContinue, + Grab::Anchor { id, si, ai, .. } if cx.selection.partial(id).is_some_and(|s| s.contains(&(si, ai))) => Cursor::DirectAnchorSelected, + Grab::Anchor { .. } => Cursor::DirectAnchor, + Grab::Segment { .. } => Cursor::Move, + } +} + +/// A press on an anchor or a segment of a selected path, while no path is being drawn. +pub(super) struct Edit { + pub(super) grab: Grab, + /// Where the press went down. + pub(super) start: Point, + pub(super) shift: bool, + /// Whether the press has dragged far enough to move what it holds (an undo step began). + pub(super) began: bool, + /// Whether the last drag left what the press holds away from where it started. + pub(super) moved: bool, + /// The document's revision ([`ToolContext::revision`]) after the drag's last preview. + pub(super) revision: Option<(u64, u64)>, + /// Whether another command changed the document or the selection during the drag: the drag + /// then previews no more, and its undo step keeps that edit with the move as last shown. + pub(super) interrupted: bool, + /// The grabbed path as the document had it when the press went down. + pressed: Option>, + /// The selection when the press went down. + pressed_selection: Selection, + snap: Option, + pub(super) guides: Vec, +} + +impl Edit { + pub(super) fn new(cx: &ToolContext, grab: Grab, start: Point, shift: bool) -> Self { + let pressed = shared_node(cx.doc, grab.id()).cloned(); + let pressed_selection = cx.selection.clone(); + Self { + grab, + start, + shift, + began: false, + moved: false, + revision: None, + interrupted: false, + pressed, + pressed_selection, + snap: None, + guides: vec![], + } + } + + /// Whether the drag began and still previews: no other command changed the document or the + /// selection since its last preview. + pub(super) fn open(&mut self, cx: &ToolContext) -> bool { + if self.began && self.revision.is_some_and(|r| r != cx.revision) { + self.interrupted = true; + } + self.began && !self.interrupted + } + + /// What ends a drag that began when the press is let go: a commit, or a cancel when the drag + /// came back to where it started and no other command's edit is in its undo step. + pub(super) fn finish(&mut self, cx: &ToolContext) -> Option { + if !self.began { + return None; + } + Some(if self.open(cx) && !self.moved { Action::Cancel } else { Action::Commit }) + } + + /// Whether the grabbed path and the selection are as they were when the press went down. + pub(super) fn unchanged(&self, cx: &ToolContext) -> bool { + let path = match (cx.doc.node(self.grab.id()), self.pressed.as_ref()) { + (Some(now), Some(then)) => same_node(now, then), + _ => false, + }; + path && *cx.selection == self.pressed_selection + } + + /// Moves what the press holds by the drag to `p`. The first move selects the anchor, or the + /// segment, unless it is already selected, and begins the undo step; a drag that starts on + /// one of several selected anchors moves them all. When the grabbed path or the selection + /// changed after the press went down, the drag does not begin, and after another command's edit during the + /// drag it moves nothing more. + pub(super) fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + let mut out = vec![]; + if self.began && !self.open(cx) { + return out; + } + if !self.began { + let id = self.grab.id(); + if !self.unchanged(cx) { + return out; + } + let Some(picked) = self.grab.anchors(cx) else { return out }; + // A drag on one of several selected anchors moves them all; a drag on a segment moves + // its two ends alone and leaves that segment selected, not its ends as anchors. + let already = match self.grab { + Grab::Anchor { .. } => cx.selection.partial(id).is_some_and(|s| picked.iter().all(|a| s.contains(a))), + Grab::Segment { si, seg, .. } => { + cx.selection.objects == [id] + && cx.selection.anchors.len() == 1 + && cx.selection.partial(id).is_some_and(|s| s.len() == picked.len() && picked.iter().all(|a| s.contains(a))) + && cx.selection.segments.len() == 1 + && cx.selection.segments.get(&id).is_some_and(|s| s.len() == 1 && s.contains(&(si, seg))) + } + }; + let moving = if already { + cx.selection.clone() + } else { + out.push(match self.grab { + Grab::Anchor { si, ai, .. } => Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"})), + Grab::Segment { si, seg, .. } => { + Action::Exec("select.segments".into(), json!({"id": id.0, "segments": [[si, seg]], "mode": "set"})) + } + }); + let mut sel = Selection { objects: vec![id], ..Selection::default() }; + sel.anchors.insert(id, picked.into_iter().collect::>()); + sel + }; + out.push(Action::Begin("Move".into())); + // A held anchor snaps; the anchors and segments that stay put are targets too. + if matches!(self.grab, Grab::Anchor { .. }) { + self.snap = Some(PointSnap::moving(cx, || Targets::for_anchor_drag(cx.doc, &moving))); + } + self.began = true; + } + let d = match (self.grab, &self.snap) { + (Grab::Anchor { at, .. }, Some(snap)) => { + let (q, guides) = snap.snap_from(cx, at + (p - self.start), None); + self.guides = guides; + q - at + } + _ => p - self.start, + }; + if d.x.is_finite() && d.y.is_finite() { + self.moved = d.x != 0.0 || d.y != 0.0; + out.push(Action::Preview("path.moveAnchors".into(), json!({"dx": d.x, "dy": d.y, "interpolate": true}))); + } + out.push(Action::Notify(MOVED.into())); + out + } +} diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index ce6fd5ec4b..34311e9d96 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -196,6 +196,34 @@ fn the_first_click_starts_a_path() { assert_eq!(t.cursor(&cx, pt(400.0, 400.0), Mods::default()), Cursor::Pen); } +/// With no path being drawn, the cursor over a selected path shows what a press there does: an +/// anchor is selected and moved, a selected anchor shows as one, and a segment moves. A press there +/// waits for a drag or a release instead of starting a path. +#[test] +fn a_selected_paths_anchors_and_segments_show_the_edit_cursors() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = QuickPenTool::default(); + assert_eq!(t.cursor(&cx, pt(100.0, 100.0), Mods::default()), Cursor::DirectAnchor); + assert_eq!(t.cursor(&cx, pt(150.0, 100.0), Mods::default()), Cursor::Move); + assert_eq!(t.cursor(&cx, pt(400.0, 400.0), Mods::default()), Cursor::Pen); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 100.0)).is_empty()); + assert!(t.busy()); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 130.0)); + assert!(matches!(&a[0], Action::Exec(c, v) if c == "select.segments" && v["mode"] == "set"), "{a:?}"); + assert!(matches!(&a[2], Action::Preview(c, v) if c == "path.moveAnchors" && v["dy"] == 30.0 && v["interpolate"] == true), "{a:?}"); + assert_eq!(t.cursor(&cx, pt(150.0, 130.0), Mods::default()), Cursor::Move); + let up = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 130.0)); + assert_eq!(up.last(), Some(&Action::Commit)); + assert!(!t.busy()); + s.anchors.insert(id, (0..4).map(|ai| (0, ai)).collect()); + let cx = crate::testutil::cx(&d, &s, &p); + assert_eq!(t.cursor(&cx, pt(100.0, 100.0), Mods::default()), Cursor::DirectAnchorSelected); +} + /// The circle `arc_circle` gives is the one `append` draws the arc on, for sharp-corner arcs of /// less and more than a half circle, flipped, and continuous arcs; a line has none. #[test] diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 1d9d8c4a54..7c9bd3ce81 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -63,7 +63,7 @@ const ROWS: &[Row] = &[ // Pencil Tool Options' Alt key toggles to Smooth Tool, Live preview and Live curve fitting (the // Paintbrush has none of them). (&["pencil"], None, &["altSmooth", "livePreview", "liveFit"]), - (&["smooth"], None, &["fidelity"]), + (&["smooth"], None, &["fidelity", "smoothness"]), (&["blobBrush", "eraser"], None, &["size", "sizeMode", "sizeVariation"]), (&["blobBrush"], None, &["fidelity", "keepSelected", "mergeOnlySelection"]), // Eraser Tool Options' tip shape. @@ -78,8 +78,10 @@ const ROWS: &[Row] = &[ (&["star"], None, &["points"]), // The Ellipse dialog's Anchors. (&["ellipse"], None, &["anchors"]), - // Circle Tool Options (`circle::CircleTool`). - (&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird"]), + // Circle Tool Options (`circle::CircleTool`) and the Control bar's From Center. + (&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird", "fromCenter"]), + // Curvature Circle Tool Options (`curvature_circle::CurvatureCircleTool`). + (&[crate::curvature_circle::ID], None, &["snapTolerance", "snapWithoutGuides", "annotateRadius", "standardAnchors", "constantRadius"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( @@ -108,7 +110,7 @@ const ROWS: &[Row] = &[ (&[crate::addons::extend_path::ID], None, &["mode"]), (&[crate::addons::corner_tool::ID], None, &["radius", "kind"]), (&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]), - (&[crate::addons::tangent_circle::ID], None, &["radius"]), + (&[crate::addons::tangent_circle::ID], None, &["radius", "addPoints", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]), (&[crate::addons::smart_pen::ID], None, &["next"]), // The kind first: a new kind resets the values after it. (&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]), diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index b93c94dddc..cb288e5938 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -999,7 +999,7 @@ impl Tool for ShapeTool { let mut o = if tangent.is_some() { self.tangent_line.guides(cx) } else { self.snap.guides().to_vec() }; o.extend(self.guides.iter().cloned()); // The points Shift-clicks placed, and after two of them the circle through them and the - // pointer, dashed. + // pointer, dashed (solid when it is too long on screen, as the Circle tool draws it). for p in &self.through { o.push(Overlay::Anchor { p: *p, color: crate::draw2::FEEDBACK, filled: true, size: 6.0 }); } @@ -1007,7 +1007,7 @@ impl Tool for ShapeTool { && let Some((c, r)) = vectorcraft_geom::shapes::circle_through(*a, *b, h) { let path = vectorcraft_geom::shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); - o.push(Overlay::Path { path, color: crate::draw2::FEEDBACK, width: 1.0, dashed: true }); + o.push(Overlay::Path { path, color: crate::draw2::FEEDBACK, width: 1.0, dashed: crate::circle::preview_dashed(cx, r) }); } if let Some((p, text)) = &self.measure { o.push(Overlay::Measure { p: *p, text: text.clone() }); diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index fa089bf4e7..993fc9c104 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -667,6 +667,37 @@ fn the_circle_preview_passes_through_the_snapped_pointer() { assert!(matches!(&a[..], [Action::Exec(_, v)] if v["points"][2] == json!([100.0, 100.0])), "{a:?}"); } +/// A circle through the Shift-clicked points more than 50,000 screen points around is previewed +/// solid, as the Circle tool previews it: points nearly on one line give a radius of about +/// 1,250,000 pt. +#[test] +fn a_huge_circle_through_shift_clicked_points_is_previewed_solid() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let shift = Mods { shift: true, ..Default::default() }; + let mut t = ShapeTool::new("ellipse"); + for (x, y) in [(0.0, 0.0), (1000.0, 0.0)] { + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(shift)); + } + let paths = |t: &ShapeTool| { + t.overlays(&cx) + .into_iter() + .filter_map(|o| match o { + Overlay::Path { dashed, .. } => Some(dashed), + _ => None, + }) + .collect::>() + }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 500.0, 0.1)); + assert_eq!(paths(&t), vec![false]); + // At 100% a circle 100 pt across is dashed. + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 500.0, 300.0)); + assert_eq!(paths(&t), vec![true]); +} + /// Escape, a plain click and a drag drop the points Shift-clicks placed, so the next Shift-click /// starts a new circle. #[test] diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 165ced795e..9d6fe2e887 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -438,6 +438,20 @@ impl Tool for BrushPaintTool { fn wants_samples(&self) -> bool { self.inner.wants_samples() } + /// The brush it paints with varies with the wheel: a Calligraphic brush with a value on Stylus + /// Wheel and a variation other than 0, a Scatter brush with a value on it whose two values + /// differ, or an Art brush whose width is on it with two different widths. + fn reads_wheel(&self, cx: &ToolContext) -> bool { + use vectorcraft_brush::{BrushKind, Variation}; + let wheel = |mode: Variation| mode == Variation::StylusWheel; + let Some(brush) = self.brush_name(cx).and_then(|n| vectorcraft_brush::find(cx.doc, &n)) else { return false }; + match brush.kind { + BrushKind::Calligraphic(c) => c.modes().into_iter().zip(c.variation).any(|(m, v)| wheel(m) && v != 0.0), + BrushKind::Scatter(s) => s.modes().into_iter().zip(s.values()).any(|(m, (a, b))| wheel(m) && a != b), + BrushKind::Art(a) => a.width_mode.is_some_and(wheel) && a.width_range().0 != a.width_range().1, + BrushKind::Pattern(_) | BrushKind::Bristle(_) => false, + } + } fn busy(&self) -> bool { self.inner.busy() } @@ -758,4 +772,52 @@ mod tests { let a = drag(&d, &mut BrushPaintTool::default()); assert!(matches!(&a, Action::Preview(c, v) if c == "path.freehand" && v.get("brush").is_none()), "no brush: {a:?}"); } + + #[test] + fn the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush() { + use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, Scatter, Variation}; + let wheel = Variation::StylusWheel; + let calligraphic = + |modes, size| BrushKind::Calligraphic(Calligraphic { variation: [0.0, 0.0, size], modes: Some(modes), ..Calligraphic::default() }); + let scatter = |size| { + BrushKind::Scatter(Scatter { size, modes: Some([wheel, Variation::Fixed, Variation::Fixed, Variation::Fixed]), ..Scatter::default() }) + }; + let art = |width_mode, width_max| BrushKind::Art(ArtBrush { width_mode, width_max: Some(width_max), ..ArtBrush::default() }); + let library = [ + Brush { name: "Plain".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, Variation::Pressure], 2.0) }, + Brush { name: "Nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 2.0) }, + Brush { name: "Still nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 0.0) }, + Brush { name: "Dots".into(), kind: scatter((50.0, 150.0)) }, + Brush { name: "Even dots".into(), kind: scatter((100.0, 100.0)) }, + Brush { name: "Taper".into(), kind: art(Some(wheel), 200.0) }, + Brush { name: "Even taper".into(), kind: art(Some(wheel), 100.0) }, + Brush { name: "Flat".into(), kind: art(None, 200.0) }, + ]; + let (mut d, _) = doc_with_rect(); + d.unknown.insert(vectorcraft_brush::DOC_KEY.into(), serde_json::to_value(library).unwrap()); + let (s, p) = (Selection::default(), paint()); + let reads = |d: &vectorcraft_doc::Document, t: &BrushPaintTool| t.reads_wheel(&cx(d, &s, &p)); + let mut t = BrushPaintTool::default(); + assert!(!reads(&d, &t), "no brush"); + let brushes = [ + ("Plain", false), + ("Nib", true), + ("Still nib", false), + ("Dots", true), + ("Even dots", false), + ("Taper", true), + ("Even taper", false), + ("Flat", false), + ("Deleted", false), + ]; + for (name, varies) in brushes { + d.unknown.insert(vectorcraft_brush::CURRENT_KEY.into(), json!(name)); + assert_eq!(reads(&d, &t), varies, "the current brush {name}"); + } + t.set_option("brush", &json!("Plain")); + assert!(!reads(&d, &t), "the tool's own brush comes first"); + t.set_option("brush", &json!("Nib")); + d.unknown.remove(vectorcraft_brush::CURRENT_KEY); + assert!(reads(&d, &t), "and reads the wheel"); + } } diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 0c63f2f21c..134b9b6069 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -16,8 +16,9 @@ //! //! The Gradient panel's eyedropper sets the `stop` option (the tool to return to): the next click //! samples the colour under the cursor into the selected gradient stop (`paint.sampleColor -//! {stop}`) and switches back to that tool. Armed for the Live Paint Bucket, a click once its stop -//! is no longer selected ends the pick without sampling and switches back to the bucket. +//! {stop}`) and switches back to that tool. Armed for a stop of the gradient a tool paints with +//! (the Live Paint Bucket's, the Shape Builder's fill), a click once its stop is no longer +//! selected ends the pick without sampling and switches back to that tool. //! //! Gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso before switching //! to the Eyedropper stay picked (its `meshPoints` option), and go back to one of those tools @@ -559,9 +560,9 @@ impl Tool for EyedropperTool { self.brush_key_color = false; vec![Action::Dialog("brushKeyColor".into(), json!({ "color": color_json(&c) })), Action::SwitchTool(back)] } - Click::BackToBucket => { + Click::Back(back) => { self.stop = None; - vec![Action::SwitchTool("livePaintBucket".into())] + vec![Action::SwitchTool(back)] } Click::MeshPoints(id, points, color) => { let params = json!({ "id": id.0, "points": points, "color": color_json(&color), "keepModel": true }); @@ -691,8 +692,9 @@ enum Click { ImageTrace(Value), /// Brush Options › Key Color: this color, sampled from this object. BrushKeyColor(Color, NodeId), - /// A pick for a Live Paint Bucket stop that is no longer selected switches back unsampled. - BackToBucket, + /// A pick for a stop of the gradient a tool paints with (the Live Paint Bucket's, the Shape + /// Builder's fill) that is no longer selected switches back to that tool unsampled. + Back(String), /// The fill color goes to these points of this selected gradient mesh. MeshPoints(NodeId, Vec, Color), /// `appearance.copyFrom` this source, with `reverse` or `append` or neither. @@ -707,7 +709,7 @@ impl Click { /// The object of the document the click reads from or writes to. fn object(&self) -> Option { match self { - Click::ImageTrace(_) | Click::BackToBucket => None, + Click::ImageTrace(_) | Click::Back(_) => None, Click::BrushKeyColor(_, id) | Click::MeshPoints(id, ..) | Click::CopyFrom(id, _) | Click::Sample { source: id, .. } => Some(*id), } } @@ -728,13 +730,17 @@ impl EyedropperTool { let (c, source) = sample_at(cx, p)?; return Some(Click::BrushKeyColor(c, source)); } - // A pick for a stop of the Live Paint Bucket's gradient (the default paint's) ends without + // A pick for a stop of the gradient of a tool that paints with the chosen colors (the + // default paint's: the Live Paint Bucket's, or the Shape Builder's fill) ends without // sampling once that stop is no longer selected (a Cmd-click selected another object) or no // longer there (another paint was chosen): the click switches back. - let bucket_paint = if cx.fill_active { &cx.paint.fill } else { &cx.paint.stroke }; - let bucket_stop = cx.gradient_stop.filter(|i| matches!(bucket_paint, Paint::Gradient(g) if *i < g.gradient.stops.len())); - if self.stop.as_deref() == Some("livePaintBucket") && bucket_stop.is_none() { - return Some(Click::BackToBucket); + let tool_paint = if cx.fill_active { &cx.paint.fill } else { &cx.paint.stroke }; + let tool_stop = cx.gradient_stop.filter(|i| matches!(tool_paint, Paint::Gradient(g) if *i < g.gradient.stops.len())); + if cx.tool_paints + && tool_stop.is_none() + && let Some(back) = &self.stop + { + return Some(Click::Back(back.clone())); } let stop = self.stop.clone().zip(cx.gradient_stop); // A plain click on a selected gradient mesh gives the fill color to the point there, else @@ -934,19 +940,23 @@ mod tests { ] ); assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}), "one sample only"); - // Armed for the Live Paint Bucket with its stop no longer selected, a click ends the pick. - cx.gradient_stop = None; - t.set_option("stop", &json!("livePaintBucket")); - let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); - assert_eq!(a, vec![Action::SwitchTool("livePaintBucket".into())]); - assert_eq!(t.returns_to(), None); - // So does a click once the default paint has no such stop (here, a solid fill). - cx.gradient_stop = Some(1); - assert!(!matches!(cx.paint.fill, Paint::Gradient(_))); - t.set_option("stop", &json!("livePaintBucket")); - assert_eq!(t.returns_to(), Some("livePaintBucket")); - let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); - assert_eq!(a, vec![Action::SwitchTool("livePaintBucket".into())]); + // Armed for a tool that paints with the chosen colors (the Live Paint Bucket, or the Shape + // Builder's fill) with its stop no longer selected, a click ends the pick. + cx.tool_paints = true; + for back in ["livePaintBucket", "shapeBuilder"] { + cx.gradient_stop = None; + t.set_option("stop", &json!(back)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); + assert_eq!(a, vec![Action::SwitchTool(back.into())]); + assert_eq!(t.returns_to(), None); + // So does a click once the default paint has no such stop (here, a solid fill). + cx.gradient_stop = Some(1); + assert!(!matches!(cx.paint.fill, Paint::Gradient(_))); + t.set_option("stop", &json!(back)); + assert_eq!(t.returns_to(), Some(back)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); + assert_eq!(a, vec![Action::SwitchTool(back.into())]); + } // Neither a Key Color pick nor an Image Trace ignored-color pick is a gradient stop's. t.set_option("brushKeyColor", &json!(true)); t.set_option("stop", &json!("livePaintBucket")); diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index d0ff487af8..3bd8df6cec 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -86,6 +86,9 @@ struct Drag { /// when the Alt state at the release changes what it transforms. pointer: Point, shift: bool, + /// The pointer's own movement since the press, before snapping: a snapped press can turn a + /// level drag diagonal, so Scale's Shift-drag uses this to pick an axis (#6324). + moved: Vec2, last: Affine, /// The document revision at the press: a press whose document or selection changes before it /// becomes a drag is dropped, so its reference point is never applied to other objects. @@ -100,6 +103,16 @@ impl Drag { } } +/// The pointer drag [`TransformTool::solve`] turns into a transform. +struct SolveDrag { + start: Point, + p: Point, + /// The pointer's own movement since the press, before snapping (#6324). + moved: Vec2, + shift: bool, + bounds: Rect, +} + /// The first point of a Reflect axis set by a click, waiting for the second point, with the /// selection and the document revision it was set for. #[derive(Clone, Debug)] @@ -128,6 +141,11 @@ pub struct TransformTool { snap: Option, } +/// The selected objects and ruler guides, which a reference point set by a click belongs to. +fn selected_ids(cx: &ToolContext) -> Vec { + cx.selection.objects.iter().chain(&cx.selection.guides).copied().collect() +} + fn about(o: Point, a: Affine) -> Affine { Affine::translate(o.to_vec2()) * a * Affine::translate(-o.to_vec2()) } @@ -170,10 +188,11 @@ impl TransformTool { } /// The effective reference point: the custom one if it belongs to the current selection, - /// otherwise the centre of its bounding box (rotated with rotated objects). + /// otherwise the centre of its bounding box (rotated with rotated objects). With ruler guides + /// selected, it is the center of the objects' box and the guides' lines together. pub fn reference_point(&self, cx: &ToolContext) -> Option { if let Some((p, ids)) = &self.origin - && *ids == cx.selection.objects + && *ids == selected_ids(cx) && !ids.is_empty() { return Some(*p); @@ -181,7 +200,29 @@ impl TransformTool { // Anchors selected with Direct Selection transform alone, about their own centre. vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure()) .map(|b| b.center()) - .or_else(|| selection_box(cx).map(|b| b.center())) + .or_else(|| if self.guide_lines(cx).is_empty() { selection_box(cx).map(|b| b.center()) } else { self.bounds(cx).map(|b| b.center()) }) + } + + /// The selected ruler guides the tool transforms, as the boxes of the lines they stand for + /// ([`vectorcraft_doc::Document::guide_line`]): those that can be edited, with objects + /// selected, and with the Rotate tool also without. + fn guide_lines(&self, cx: &ToolContext) -> Vec { + if cx.selection.is_empty() && self.kind != TransformKind::Rotate { + return vec![]; + } + let d = cx.doc; + let guides = cx.selection.guides.iter().filter_map(|id| d.ruler_guide(*id)).filter(|g| d.guide_editable(g)); + guides.filter_map(|g| d.guide_line(&g)).map(|(a, b)| Rect::from_points(a, b)).collect() + } + + /// The bounding box of the selected objects and the lines of the guides the tool transforms. + fn bounds(&self, cx: &ToolContext) -> Option { + self.guide_lines(cx).into_iter().fold(selection_bounds(cx), |acc, r| Some(acc.map_or(r, |acc| acc.union(r)))) + } + + /// Is there anything selected for the tool to transform? + fn has_target(&self, cx: &ToolContext) -> bool { + !cx.selection.is_empty() || !self.guide_lines(cx).is_empty() } /// Transform for dragging from `start` to `p` about `o`; returns the matrix and a readout. @@ -194,7 +235,7 @@ impl TransformTool { /// and Shift's 45° steps start from the box's axes. A Reflect axis drawn by the drag is the /// line the pointer draws on the page. pub fn matrix_in(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, String) { - let (m, a, b) = self.solve(angle, o, start, p, shift, bounds); + let (m, a, b) = self.solve(angle, o, SolveDrag { start, p, moved: p - start, shift, bounds }); (m, self.label(a, b)) } @@ -225,7 +266,8 @@ impl TransformTool { /// axis in degrees counter-clockwise (Reflect), the scale along the box's width and height /// (Scale), or the angle of the shear axis (0 horizontal, 90 vertical) and the shear angle as /// `object.shear` takes it (Shear). - fn solve(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, f64, f64) { + fn solve(&self, angle: f64, o: Point, d: SolveDrag) -> (Affine, f64, f64) { + let SolveDrag { start, p, moved, shift, bounds } = d; let frame = OrientedBox { angle, rect: Rect::ZERO }; let local = |v: Vec2| frame.to_doc().inverse() * v.to_point(); match self.kind { @@ -248,7 +290,18 @@ impl TransformTool { let d1 = local(p - o).to_vec2(); let ratio = |a: f64, b: f64| if a.abs() > 1e-6 { b / a } else { 1.0 }; let (mut sx, mut sy) = (ratio(d0.x, d1.x), ratio(d0.y, d1.y)); - if shift { + // Shift: a drag within 22.5° of an axis scales along that axis alone, a diagonal + // one uniformly (#6324). The pointer's own movement decides, in the box's axes; a + // snapped press can otherwise turn a level drag diagonal. A drag that starts level + // with the reference point on that axis has nothing to scale it by, so it stays uniform. + let moved_local = local(moved).to_vec2(); + let axis_angle = moved_local.y.abs().atan2(moved_local.x.abs()).to_degrees(); + let along = moved_local.hypot() > 1e-9; + if shift && along && axis_angle <= 22.5 && d0.x.abs() > 1e-6 { + sy = 1.0; + } else if shift && along && axis_angle >= 67.5 && d0.y.abs() > 1e-6 { + sx = 1.0; + } else if shift { let l2 = d0.hypot2(); let k = if l2 > 1e-12 { d1.dot(d0) / l2 } else { 1.0 }; sx = k; @@ -331,7 +384,7 @@ impl Tool for TransformTool { let p = ev.pos; match ev.kind { PointerKind::Down => { - let Some(bounds) = selection_bounds(cx) else { return vec![] }; + let Some(bounds) = self.bounds(cx) else { return vec![] }; self.hover.clear(); let (pick, _) = snap_pick(cx, p); // Alt: decided on release. A click sets the point and opens the dialog; a drag @@ -352,6 +405,7 @@ impl Tool for TransformTool { anchors, pointer: p, shift: false, + moved: Vec2::ZERO, last: Affine::IDENTITY, revision: cx.revision, }); @@ -378,10 +432,15 @@ impl Tool for TransformTool { Some(if self.kind == TransformKind::Scale { PointSnap::scaling(cx, targets) } else { PointSnap::moving(cx, targets) }); out.push(Action::Begin(self.kind.label().into())); } + let moved = p - d.start; let (p, guides) = self.snap.as_ref().map_or((p, vec![]), |s| s.snap(cx, p)); self.hover = guides; - let (m, a, b) = self.solve(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, p, ev.mods.shift, d.bounds); - (d.last, d.pointer, d.shift) = (m, p, ev.mods.shift); + let (m, a, b) = self.solve( + d.angle_for(ev.mods.alt, ev.backquote), + d.origin, + SolveDrag { start: d.pick, p, moved, shift: ev.mods.shift, bounds: d.bounds }, + ); + (d.last, d.pointer, d.shift, d.moved) = (m, p, ev.mods.shift, moved); self.drag = Some(d); self.measure = Some((p, self.label(a, b))); self.readout = Some(self.readout_of(m, a, b, d.bounds)); @@ -395,7 +454,12 @@ impl Tool for TransformTool { // or moves only pattern tiles, and with anchors selected, whether it acts // along the box or the page. let m = if d.anchors { - self.matrix_in(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, d.pointer, d.shift, d.bounds).0 + self.solve( + d.angle_for(ev.mods.alt, ev.backquote), + d.origin, + SolveDrag { start: d.pick, p: d.pointer, moved: d.moved, shift: d.shift, bounds: d.bounds }, + ) + .0 } else { d.last }; @@ -417,12 +481,16 @@ impl Tool for TransformTool { } self.drop_axis(); let copy = ev.mods.alt; - let (m, _, _) = self.solve(d.angle_for(copy, ev.backquote), first, first, d.pick, false, d.bounds); + let (m, _, _) = self.solve( + d.angle_for(copy, ev.backquote), + first, + SolveDrag { start: first, p: d.pick, moved: d.pick - first, shift: false, bounds: d.bounds }, + ); vec![Action::Begin(self.kind.label().into()), preview(m, copy, ev.backquote), Action::Commit] } else { // A click sets the reference point; with Alt, it opens the dialog too. With the // Reflect tool, a plain click also sets the first point of an axis. - self.origin = Some((d.pick, cx.selection.objects.clone())); + self.origin = Some((d.pick, selected_ids(cx))); self.drop_axis(); if d.alt { vec![self.dialog(d.pick)] @@ -450,7 +518,7 @@ impl Tool for TransformTool { PointerKind::TripleClick => vec![], PointerKind::Move => { if self.drag.is_none() { - let (pick, hover) = if cx.selection.is_empty() { (p, vec![]) } else { snap_pick(cx, p) }; + let (pick, hover) = if self.has_target(cx) { snap_pick(cx, p) } else { (p, vec![]) }; self.hover = hover; self.axis_to = self.axis_first(cx).map(|_| pick); } @@ -525,7 +593,7 @@ impl Tool for TransformTool { } fn cursor(&self, cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { - if cx.selection.is_empty() { + if !self.has_target(cx) { return Cursor::NotAllowed; } match self.kind { @@ -657,6 +725,35 @@ mod tests { assert_eq!(up.last(), Some(&Action::Commit)); } + /// With only a ruler guide selected, the Rotate tool drags about the middle of the guide's + /// line, and Alt-click opens its dialog; the Scale tool still needs objects. + #[test] + fn the_rotate_tool_turns_a_selected_ruler_guide_alone() { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let g = d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 100.0)); + let mut s = Selection::default(); + s.guides.push(g); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = TransformTool::new(TransformKind::Rotate); + assert_eq!(t.reference_point(&cx), Some(Point::new(100.0, 250.0))); + assert_ne!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::NotAllowed); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 200.0, 250.0)).is_empty()); + let a = t.pointer(&cx, &ev(PointerKind::Drag, 100.0, 350.0)); + assert_eq!(a[0], Action::Begin("Rotate".into())); + let m = matrix(&a[1]); + assert!((m * Point::new(100.0, 250.0)).distance(Point::new(100.0, 250.0)) < 1e-9); + assert!((m * Point::new(200.0, 250.0)).distance(Point::new(100.0, 350.0)) < 1e-9); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 100.0, 350.0)).last(), Some(&Action::Commit)); + t.pointer(&cx, &ev(PointerKind::Down, 50.0, 60.0).with_mods(alt())); + let up = t.pointer(&cx, &ev(PointerKind::Up, 50.0, 60.0).with_mods(alt())); + assert!(matches!(up.as_slice(), [Action::Dialog(id, _)] if id == "rotate"), "{up:?}"); + let mut scale = TransformTool::new(TransformKind::Scale); + assert_eq!(scale.reference_point(&cx), None); + assert!(scale.pointer(&cx, &ev(PointerKind::Down, 200.0, 250.0)).is_empty()); + assert!(scale.pointer(&cx, &ev(PointerKind::Drag, 100.0, 350.0)).is_empty()); + } + #[test] fn click_sets_reference_point_then_drag_uses_it() { let (d, id) = doc_with_rect(); @@ -684,6 +781,54 @@ mod tests { assert!((c[0] - c[3]).abs() < 1e-9 && c[0] > 1.0); } + /// A Shift-drag along one axis scales along that axis alone, and a diagonal one scales + /// uniformly (#6324): the drag's own direction decides, within 22.5° of an axis. + #[test] + fn scale_shift_follows_the_drag_direction() { + let t = TransformTool::new(TransformKind::Scale); + let o = Point::new(100.0, 100.0); + let scales = |p: Point| { + let c = t.matrix_for(o, Point::new(150.0, 140.0), p, true, Rect::ZERO).0.as_coeffs(); + (c[0], c[3]) + }; + // Sideways, a little off the level: width only. + let (sx, sy) = scales(Point::new(200.0, 145.0)); + assert!((sx - 2.0).abs() < 1e-9 && (sy - 1.0).abs() < 1e-9, "{sx} {sy}"); + // Up or down: height only. + let (sx, sy) = scales(Point::new(148.0, 180.0)); + assert!((sx - 1.0).abs() < 1e-9 && (sy - 2.0).abs() < 1e-9, "{sx} {sy}"); + // Diagonal: both, by the same factor. + let (sx, sy) = scales(Point::new(200.0, 180.0)); + assert!((sx - sy).abs() < 1e-9 && sx > 1.0, "{sx} {sy}"); + // A drag that starts straight above (beside) the reference point has no width (height) to + // scale, so a sideways (up or down) Shift-drag from there scales uniformly, as before. + let from = |start: Point, p: Point| { + let c = t.matrix_for(o, start, p, true, Rect::ZERO).0.as_coeffs(); + (c[0], c[3]) + }; + let (sx, sy) = from(Point::new(100.0, 150.0), Point::new(150.0, 160.0)); + assert!((sx - sy).abs() < 1e-9 && (sx - 1.2).abs() < 1e-9, "{sx} {sy}"); + let (sx, sy) = from(Point::new(150.0, 100.0), Point::new(160.0, 150.0)); + assert!((sx - sy).abs() < 1e-9 && (sx - 1.2).abs() < 1e-9, "{sx} {sy}"); + } + + /// The axis of a Shift-drag comes from the pointer's own movement: a press near a corner + /// snaps to it, and a level drag from there still scales the width alone. + #[test] + fn scale_shift_axis_follows_the_pointer_not_the_snapped_press() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Default::default() }; + let mut t = TransformTool::new(TransformKind::Scale); + t.pointer(&cx, &ev(PointerKind::Down, 198.0, 203.0).with_mods(shift)); + let drag = t.pointer(&cx, &ev(PointerKind::Drag, 205.0, 203.0).with_mods(shift)); + let c = matrix(drag.last().expect("a preview")).as_coeffs(); + assert!((c[0] - 1.1).abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9, "the width alone: {c:?}"); + } + #[test] fn alt_click_opens_dialog_and_alt_release_copies() { let (d, id) = doc_with_rect(); diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 154afe235d..95487e91c0 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -101,6 +101,7 @@ egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } egui_extras = { workspace = true } vectorcraft-apischema = { workspace = true } vectorcraft-testkit = { workspace = true } +vectorcraft-tools = { workspace = true, features = ["testing"] } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } wat = { workspace = true } diff --git a/crates/ui-egui/src/addons/color.rs b/crates/ui-egui/src/addons/color.rs index aca41a2620..6696e4b0d3 100644 --- a/crates/ui-egui/src/addons/color.rs +++ b/crates/ui-egui/src/addons/color.rs @@ -91,6 +91,12 @@ fn adjustment(i: usize) -> (&'static str, &'static str, &'static [AdjustValue]) ADJUSTMENTS.get(i).copied().unwrap_or(ADJUSTMENTS[0]) } +/// The adjustments' names in `lang`, in [`ADJUSTMENTS`] order: each effect's name as the Effect +/// menu, History and Edit › Undo show it ([`crate::i18n::effect_name`]). +fn adjustment_names(lang: crate::i18n::Lang) -> Vec { + ADJUSTMENTS.iter().map(|a| crate::i18n::effect_name(lang, a.0).unwrap_or_else(|| crate::i18n::tr(lang, a.1).to_string())).collect() +} + /// Object › Plug-ins › Color Effects. pub fn menu() -> Vec { let cmd = |(label, id, p): (&'static str, &'static str, Value)| cp(label, id, p); @@ -153,7 +159,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; } let mut st = std::mem::take(&mut app.addon_panels.color); - let entries: Vec> = ADJUSTMENTS.iter().enumerate().map(|(i, a)| Entry::new(i, tl!(a.1).to_string())).collect(); + let entries: Vec> = adjustment_names(crate::i18n::current()).into_iter().enumerate().map(|(i, name)| Entry::new(i, name)).collect(); FieldGroup::new(tl!("Adjustment").to_string()).show(ui, |ui, _| { Field::new(tl!("Adjustment").to_string()).show(ui, |ui, _| { Select::new(tl!("Adjustment").to_string(), Bind::bound(&mut st.index), &entries).show(ui); diff --git a/crates/ui-egui/src/addons/color/tests.rs b/crates/ui-egui/src/addons/color/tests.rs index b3ab29fdaa..506327e399 100644 --- a/crates/ui-egui/src/addons/color/tests.rs +++ b/crates/ui-egui/src/addons/color/tests.rs @@ -4,6 +4,7 @@ use vectorcraft_engine::Session; use super::{ADJUSTMENTS, Picked}; use crate::VectorcraftApp; +use crate::i18n::LangExt; /// An app in a window with a selected red rectangle. fn app() -> VectorcraftApp { @@ -62,6 +63,36 @@ fn every_adjustment_offered_is_a_colour_adjustment_with_its_defaults() { } } +/// Apply as Filter records a step that History and Edit › Undo name as the panel names the +/// adjustment, in every language (German's plain `Levels` row and its Effect menu row differ). +#[test] +fn history_names_a_filter_step_as_the_panel_names_its_adjustment() { + for (i, (id, _, fields)) in ADJUSTMENTS.iter().enumerate() { + let mut app = app(); + app.run("paint.setFill", json!({"color": "#806040"})).unwrap(); + let (_, mut params) = Picked { index: i, ..Picked::default() }.params(); + if let Some((key, _, (_, max), ..)) = fields.first() { + params[*key] = json!(max); + } + app.run("addon.color.filter", json!({ "effect": id, "params": params })).unwrap(); + let h = app.session.active().unwrap().history.undo.last().cloned().unwrap(); + assert_eq!(h.effect(), Some(*id), "the step Apply as Filter records for {params}"); + app.addon_panels.color = Picked { index: i, ..Picked::default() }; + let app = std::rc::Rc::new(std::cell::RefCell::new(app)); + let shown = std::rc::Rc::clone(&app); + let mut fixture = craft::ui::testing::Fixture::new(move |ui| super::show(&mut shown.borrow_mut(), ui)); + fixture.room(egui::vec2(320.0, 700.0)); + for lang in crate::i18n::Lang::all() { + crate::i18n::set_current(lang); + let step = crate::panels::history::shown(&h); + fixture.settle(); + let texts: Vec = fixture.texts().iter().map(|t| t.text.clone()).collect(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(texts.contains(&step), "{} {id}: {step:?} in {texts:?}", lang.code()); + } + } +} + #[test] fn the_halftone_effect_dialog_has_the_command_fields_and_edits_the_effect() { let mut app = app(); diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 55ad5dd64d..d29066a126 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -99,8 +99,8 @@ fn pump_commit(app: &mut VectorcraftApp) { let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), (spec.params)(d.fields())))); if let Some((previewing, params)) = &live { let mut preview = mem::take(&mut app.addon_dialogs.preview); - // PLAN: the undo step's label is the command id; `Spec` carries no heading (wg.A20 takes a label) - let answer = preview.run(app, *previewing, spec.command, spec.command, params); + let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); + let answer = preview.run(app, *previewing, label, spec.command, params); app.addon_dialogs.preview = preview; if let (Some(found), Some(answer)) = (spec.found, answer) { host.with(|h| { diff --git a/crates/ui-egui/src/addons/dialogs/tests.rs b/crates/ui-egui/src/addons/dialogs/tests.rs index 9a24a362eb..eb24e09c37 100644 --- a/crates/ui-egui/src/addons/dialogs/tests.rs +++ b/crates/ui-egui/src/addons/dialogs/tests.rs @@ -247,6 +247,25 @@ fn add_on_dialogs_preview_cancel_and_run_their_command() { } } +#[test] +fn keeping_an_add_on_preview_records_the_command_name() { + let mut app = two_rects(); + let undo = undo_len(&app); + open_item(&mut app, "Arrange Tools", "Arrange in Grid…"); + let id = dialog_id(&app); + set(&app, id, "layout", json!("row")); + set(&app, id, "preview", json!(true)); + frame(&mut app); + assert_eq!(x0(&app, 1), 30.0, "previewed"); + assert_eq!(undo_len(&app), undo, "the preview is still temporary"); + + assert!(confirm(&app, id)); + frame(&mut app); + let history = &app.session.doc().unwrap().history; + assert_eq!(history.undo.len(), undo + 1); + assert_eq!(history.undo.last().unwrap().label, "Arrange in Grid"); +} + #[test] fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview() { let mut app = two_rects(); diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 8656e0f7ad..9e4d188ddc 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -1,12 +1,14 @@ //! Packaging Tools' submenu (Object › Plug-ins › Packaging Tools) and its Fold Lines panel. The //! panel lists the fold line roles, each with its swatch's chip and how many of the selected objects //! have it (of the whole document while nothing is selected); clicking a role gives the selected -//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that -//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu -//! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it -//! (clicking one selects its objects); each document's list is kept until that document changes. Its -//! Fold Preview button, like the Fold Preview menu item, shows the blank folded in 3D ([`preview`], -//! `ui.foldPreview`). +//! paths that role (`addon.packaging.setRole`). While the selection holds lines that fold, its Fold +//! Angle field shows the angle they fold at and sets it (`addon.packaging.setFoldAngle`, as Set Fold +//! Angle… in the submenu does), and Reset takes their own angles away. Its menu's Role Swatches… +//! picks the swatch that carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the +//! Check Fold Lines menu item, checks the fold lines (`addon.packaging.check`) and lists the issues +//! found under it (clicking one selects its objects); each document's list is kept until that +//! document changes. Its Fold Preview button, like the Fold Preview menu item, shows the blank folded +//! in 3D ([`preview`], `ui.foldPreview`). use std::collections::HashMap; use std::sync::{Arc, Weak}; @@ -14,11 +16,17 @@ use std::sync::{Arc, Weak}; use craft::keymap::CommandRef; use craft::menu::Node; use craft::ui::buttons::Button; -use craft::ui::contract::{ActivateOn, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, WordSetCx as _}; +use craft::ui::contract::{ + ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, WordSetCx as _, clicked, +}; use craft::ui::display::{Divider, Text}; +use craft::ui::form::Field; +use craft::ui::layout_components::Row as Line; use craft::ui::list::{Finding, Findings, FindingsList, FindingsWords, List, ListRow, Severity, ThumbSize}; use craft::ui::menu::PanelRow; use craft::ui::runtime::commands::{CommandState, CommandStates}; +use craft::ui::runtime::env::UnitKind; +use craft::ui::text::NumberField; use egui::Ui; use serde_json::{Value, json}; use vectorcraft_engine::doc::Document; @@ -36,6 +44,18 @@ pub const SET_ROLE: &str = "addon.packaging.setRole"; pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; /// The command that checks the fold lines. pub const CHECK: &str = "addon.packaging.check"; +/// The command that sets or resets the fold angle of fold lines. +pub const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle"; + +/// The fold angles `addon.packaging.setFoldAngle` takes, in degrees. +pub const FOLD_ANGLES: std::ops::RangeInclusive = -180.0..=180.0; +/// The places a fold angle field shows `angle` to: all it has, so an angle such as 179.9999999° is +/// not shown as 180°, which typing 180 into the field would then leave unchanged; at least one, the +/// place the field's fine steps (a tenth of a degree) round to. +pub fn angle_places(angle: Option) -> usize { + // f64's Display is the shortest text that reads back as the same number, without an exponent. + angle.map_or(0, |a| format!("{a}").split_once('.').map_or(0, |(_, places)| places.len())).max(1) +} /// The command that shows the Fold Preview window. pub const PREVIEW: &str = "ui.foldPreview"; /// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them. @@ -54,6 +74,7 @@ pub fn menu() -> Vec { make("Make Perforation Line", "perforation"), Sep, c("Check Fold Lines", CHECK), + c("Set Fold Angle…", SET_FOLD_ANGLE), Sep, cp("Fold Preview", PREVIEW, json!({})), ] @@ -215,14 +236,22 @@ struct Rows { /// What they were read for: the document, its revision and its selection. key: Option<(u64, u64, Vec)>, rows: Vec, + /// Whether the rows count the selection (not the whole document). + selection: bool, + /// How many lines that fold (Crease, Partial Cut, Perforation) Set Fold Angle can change. + fold_lines: u64, + /// The angle they all fold at (`None`: they differ, or there are none). + angle: Option, + /// How many of them hold a stored angle, readable or not: what Reset takes away. + stored_angles: u64, } /// The rows for the active document as it is now, read again only when it changed. -fn rows(app: &mut VectorcraftApp) -> Vec { - let Some(st) = app.session.active() else { return vec![] }; +fn read_rows(app: &mut VectorcraftApp) -> Rows { + let Some(st) = app.session.active() else { return Rows::default() }; let key = (st.uid, st.revision, st.selection.objects.iter().map(|id| id.0).collect::>()); if app.addon_panels.fold.rows.key.as_ref() == Some(&key) { - return app.addon_panels.fold.rows.rows.clone(); + return app.addon_panels.fold.rows.clone(); } let answer = app.session.execute("addon.packaging.roles", &json!({})).unwrap_or(Value::Null); let d = app.session.active().map(|st| st.doc.clone()); @@ -231,9 +260,74 @@ fn rows(app: &mut VectorcraftApp) -> Vec { let paint = d.as_ref().and_then(|d| d.swatch(&swatch)).map(|s| s.paint.clone()); Some((r["role"].as_str()?.to_string(), swatch, paint, r["count"].as_u64()?)) }; - let rows: Vec = answer["roles"].as_array().into_iter().flatten().filter_map(row).collect(); - app.addon_panels.fold.rows = Rows { key: Some(key), rows: rows.clone() }; - rows + let kept = Rows { + key: Some(key), + rows: answer["roles"].as_array().into_iter().flatten().filter_map(row).collect(), + selection: answer["scope"] == "selection", + fold_lines: answer["foldLines"].as_u64().unwrap_or(0), + angle: answer["foldAngle"].as_f64(), + stored_angles: answer["storedAngles"].as_u64().unwrap_or(0), + }; + app.addon_panels.fold.rows = kept.clone(); + kept +} + +/// The role rows for the active document as it is now. +#[cfg(test)] +fn rows(app: &mut VectorcraftApp) -> Vec { + read_rows(app).rows +} + +/// The fields Set Fold Angle… opens with: `addon.packaging.setFoldAngle`'s options on the angle +/// the selected lines that it can change all fold at, else 90°, and those lines as the `ids` OK +/// sends, so OK changes the lines the dialog opened on even when the selection changes while it is +/// open, with the uid of their document as `__doc`, so OK changes nothing once another document is +/// the active one. The command's reason while it can't change any. +pub(crate) fn dialog_fields(app: &VectorcraftApp) -> Result, String> { + let command = vectorcraft_engine::find_command(SET_FOLD_ANGLE).ok_or_else(|| format!("unknown command {SET_FOLD_ANGLE}"))?; + (command.enabled)(&app.session)?; + let angle = vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle.unwrap_or(90.0); + let ids: Vec = vectorcraft_engine::cmd::selection_fold_lines(&app.session).iter().map(|id| id.0).collect(); + let doc = app.session.active().map(|st| st.uid); + match json!({ "angle": angle, "__params": { "ids": ids }, "__doc": doc }) { + Value::Object(fields) => Ok(fields), + _ => Err("no fields".into()), + } +} + +/// Set Fold Angle…: opens the parameter dialog on [`dialog_fields`]. +pub(crate) fn open_dialog(app: &mut VectorcraftApp) -> Result { + let fields = dialog_fields(app)?; + crate::dialogs::command::open(app, SET_FOLD_ANGLE, "Set Fold Angle", fields) +} + +/// The Fold Angle row, while the selection holds lines that fold and can be changed: the angle +/// they all fold at (empty when they differ), which sets theirs when changed, and Reset, which +/// takes away the angles of their own. +fn show_angle(app: &mut VectorcraftApp, ui: &mut Ui, kept: &Rows) { + if !kept.selection || kept.fold_lines == 0 { + return; + } + let mut call = None; + let _ = Line::new().fill_width().show(ui, |ui, _| { + Field::new(tl!("Fold Angle")).show(ui, |ui, _| { + let field = NumberField::new(tl!("Fold Angle"), Bind::given(kept.angle)) + .unit_kind(UnitKind::Degrees) + .range(FOLD_ANGLES) + .max_decimals(angle_places(kept.angle)); + if let Some(a) = field.id_salt("fold-angle").show(ui).value().copied().flatten() { + call = Some(json!({ "angle": a })); + } + }); + if clicked(&Button::new(tl!("Reset")).enabled(kept.stored_angles > 0).show(ui)) { + call = Some(json!({ "reset": true })); + } + }); + if let Some(p) = call + && let Err(e) = app.run(SET_FOLD_ANGLE, p) + { + app.status(e); + } } /// The label of role `role` (its id when it is none of [`ROLES`]). @@ -249,8 +343,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if !selected { Text::new(tl!("No objects are selected.").to_string()).show(ui); } - let rows = rows(app); - let source = Positional { rows: &rows, label: |row| role_label(&row.0) }; + let kept = read_rows(app); + let rows = &kept.rows; + let source = Positional { rows, label: |row| role_label(&row.0) }; let out = List::::new(tl!("Fold line roles").to_string()) .select(SelectMode::None) .activate(ActivateOn::Click) @@ -277,6 +372,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } + show_angle(app, ui, &kept); show_check(app, ui); } diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs index fcaf37a7b5..4eca13035a 100644 --- a/crates/ui-egui/src/addons/packaging/preview/tests.rs +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -519,6 +519,8 @@ fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() { order: vec![], hinges: vec![hinge(true, true, 0.0), hinge(false, false, 12.34), hinge(false, false, 3.0), hinge(false, true, 0.05)], collisions: vec![(0, 1)], + stack: Default::default(), + origin: [0.0; 3], }; // The summary, the fold line errors, the other blanks, the open joint, the crossing panels. assert_eq!(status(3, Some((&Blank::default(), &f)), true).len(), 5); diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index 80f59d2e34..8222b179d5 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -3,8 +3,9 @@ use std::sync::Arc; use serde_json::json; use vectorcraft_engine::Session; -use super::{CHECK, ID, SET_ROLE, follow_role, last_check, rows, run_check, select_issue}; +use super::{CHECK, ID, SET_FOLD_ANGLE, SET_ROLE, follow_role, last_check, read_rows, rows, run_check, select_issue, show}; use crate::i18n::LangExt as _; +use crate::tests::panel_harness::Panel; use crate::{VectorcraftApp, menus}; /// An app with two rectangles, nothing selected → (app, their ids). @@ -142,8 +143,67 @@ fn every_issue_message_translates_in_every_complete_message_catalog() { "ca", "nl", "da", ] { let lang = crate::i18n::Lang::from_code(code).unwrap(); - for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0"]) { + let no_fold_line = "select a crease, partial cut or perforation line that is neither locked nor hidden"; + for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0", no_fold_line]) { assert_ne!(crate::i18n::message(lang, m), m, "{code}: {m}"); } } } + +#[test] +fn set_fold_angle_is_listed_after_check_fold_lines() { + let (app, _, _) = app(); + let entries = menus::menu_entries(&app); + let items: Vec<&str> = entries.iter().filter(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"]).map(|e| e.label.as_str()).collect(); + let at = |label: &str| items.iter().position(|l| *l == label).unwrap_or_else(|| panic!("{label}: {items:?}")); + assert_eq!(at("Set Fold Angle…"), at("Check Fold Lines") + 1); + let item = entries.iter().find(|e| e.label == "Set Fold Angle…").expect("listed"); + assert_eq!(item.command.as_deref(), Some(SET_FOLD_ANGLE)); +} + +#[test] +fn a_fold_angle_field_shows_every_place_the_angle_has() { + use super::angle_places; + assert_eq!([None, Some(90.0), Some(-135.5), Some(179.9999999), Some(1e-12)].map(angle_places), [1, 1, 1, 7, 12]); +} + +#[test] +fn the_panel_shows_the_selected_lines_fold_angle_and_what_reset_takes_away() { + let (mut app, a, b) = app(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run(SET_ROLE, json!({"role": "cut", "ids": [b]})).unwrap(); + app.run("select.set", json!({"ids": [b]})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(!text.contains("Fold Angle"), "a cut line has no fold angle: {text}"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let kept = read_rows(&mut app); + assert_eq!((kept.selection, kept.fold_lines, kept.angle, kept.stored_angles), (true, 1, Some(90.0), 0), "Reset is dimmed"); + app.run(SET_FOLD_ANGLE, json!({"angle": 135})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Fold Angle") && text.contains("Reset"), "{text}"); + let panel = Panel::new(app, show); + let values = panel.values(); + let mut app = panel.app(); + assert!(values.iter().any(|v| v.strip_prefix("135").is_some_and(|unit| unit.is_empty() || unit.starts_with([' ', '°']))), "{values:?}"); + let kept = read_rows(&mut app); + assert_eq!((kept.angle, kept.stored_angles), (Some(135.0), 1)); + // Stored text that is not an angle: the field shows the role's angle, and Reset can still remove the text. + app.session + .edit("Test", |d, _| { + if let Some(n) = d.node_mut(vectorcraft_doc::NodeId(a)) { + n.edit_attrs(|at| { + at.data.retain(|(k, _)| k != "vc-fold-angle"); + at.data.push(("vc-fold-angle".into(), "wide".into())); + }); + } + Ok(()) + }) + .unwrap(); + let kept = read_rows(&mut app); + assert_eq!((kept.angle, kept.stored_angles), (Some(90.0), 1)); + // Nothing selected: the rows count the document and no Fold Angle row shows. + app.run("select.none", json!({})).unwrap(); + assert!(!read_rows(&mut app).selection); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(!text.contains("Fold Angle"), "{text}"); +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 307d4a3e29..8ad60b5fb4 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -17,10 +17,10 @@ pub mod tangent_circle; use craft::behavior::ColumnWidth; use craft::menu::Node; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, Sizing, clicked}; +use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _, Sizing, clicked}; use craft::ui::display::{Divider, Text}; use craft::ui::form::Field; -use craft::ui::layout_components::{Grid, Row}; +use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; use craft::ui::text::NumberField; @@ -192,6 +192,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { empty_state(ui, "dc-anchor-smooth", tl!("No document"), tl!("Open a document to edit its anchor points.")); return; } + Stack::new().label(tl!("Anchor Inspector")).fill().scroll(Scroll::vertical()).show(ui, |ui, _| show_inspector(app, ui)); +} + +fn show_inspector(app: &mut VectorcraftApp, ui: &mut Ui) { let readout = readout(app); let anchor = readout.anchor.as_ref(); let selected = app.session.active().is_some_and(|st| !st.selection.is_empty()); @@ -301,7 +305,19 @@ fn options_params(tool: &str, lengths: LengthUnits) -> Vec { if tool == tangent_circle_tool::ID { let (lo, hi) = tangent_circle_tool::RADIUS_RANGE; let kind = ParamKind::number(Some(lo), Some(hi), tangent_circle_tool::RADIUS, 1.0, 2); - return vec![Param::new("radius", tl!("Radius"), kind).length(lengths)]; + let colors = + tangent_circle_tool::COLORS.iter().zip(TANGENT_CIRCLE_COLORS).map(|((name, _), label)| ((*name).to_owned(), tl!(label).into())).collect(); + let (snap_lo, snap_hi) = tangent_circle_tool::SNAP_RANGE; + let snap = ParamKind::number(Some(snap_lo), Some(snap_hi), tangent_circle_tool::SNAP_PX, 1.0, 2); + return vec![ + Param::new("radius", tl!("Radius"), kind).length(lengths), + Param::new("addPoints", tl!(tangent_circle_tool::ADD_POINTS), ParamKind::bool(false)), + Param::new("center", tl!("Circle Center"), ParamKind::bool(true)), + Param::new("radii", tl!("Circle Radii Lines"), ParamKind::bool(true)), + Param::new("color", tl!("Color"), ParamKind::choice(colors, Some("red".into()))), + Param::new("snapTolerance", tl!("Snap Tolerance"), snap).unit(UnitKind::Pixels), + Param::new("snapWithoutGuides", tl!("Snap When Smart Guides Are Off"), ParamKind::bool(true)), + ]; } let (size, tolerance) = (anchor_eraser::SIZE_RANGE, anchor_eraser::TOLERANCE_RANGE); vec![ @@ -311,6 +327,9 @@ fn options_params(tool: &str, lengths: LengthUnits) -> Vec { ] } +/// The labels of the Tangent Circle tool's colors ([`tangent_circle_tool::COLORS`]), in its order. +const TANGENT_CIRCLE_COLORS: [&str; 6] = ["Red", "Blue", "Magenta", "Green", "Black", "Gray"]; + /// Open the options of add-on tool `tool` with its current values. OK sets them; when the tool refuses one, the dialog /// stays open with the reason. pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result { diff --git a/crates/ui-egui/src/addons/pathtools/shape.rs b/crates/ui-egui/src/addons/pathtools/shape.rs index e32ece3450..7a666e695e 100644 --- a/crates/ui-egui/src/addons/pathtools/shape.rs +++ b/crates/ui-egui/src/addons/pathtools/shape.rs @@ -70,6 +70,13 @@ pub(super) fn target(app: &VectorcraftApp) -> (Option, ParametricShape) (None, apply(fallback, &app.session.tool_options_of(tool::ID)).unwrap_or(fallback)) } +/// Whether anchors are direct-selected, so that the selection's box is the box around them. +fn anchors_selected(app: &VectorcraftApp) -> bool { + app.session + .active() + .is_some_and(|st| vectorcraft_effects::preview::anchor_bounds_with(&st.selection, &st.doc, app.session.bounds_measure()).is_some()) +} + /// Whether something is selected and none of it is a parametric shape Convert could take. pub(super) fn plain_selected(app: &VectorcraftApp) -> bool { app.session.active().is_some_and(|st| !st.selection.is_empty()) && selected(app).is_none() @@ -143,6 +150,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { match (change, id) { (Some(mut p), Some(id)) => { p["id"] = json!(id.0); + // The Transform panel and the Control bar share one reference point locator. W and H + // keep the point of the shape's bounding box chosen there in place. With anchors + // direct-selected the locator shows their box, so the shape keeps its center instead. + if p.get("width").or_else(|| p.get("height")).is_some() && !anchors_selected(app) { + p["reference"] = json!(app.ui.transform_panel.reference_point); + } run(app, "addon.pathtools.shape.set", p); } (Some(values), None) => run(app, "tool.setOption", json!({ "tool": tool::ID, "values": values })), diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 464ce72f42..9a63194c34 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -44,6 +44,32 @@ fn the_inspector_shows_the_selected_anchor_and_its_buttons_edit() { assert!(a.lengths.iter().all(|l| *l > 0.0) && a.angles.iter().all(|d| d.is_some()), "{:?} {:?}", a.lengths, a.angles); } +#[test] +fn a_short_anchor_inspector_scrolls_to_the_selected_anchors_actions() { + let mut app = app(); + let path = app.run("path.create", json!({ "anchors": [{"x": 10, "y": 10}, {"x": 110, "y": 10}, {"x": 110, "y": 110}] })).unwrap(); + let id = vectorcraft_doc::NodeId(path["id"].as_u64().unwrap()); + app.session + .select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + let mut panel = Panel::new(app, super::show); + let room = egui::vec2(220.0, 215.0); + panel.room(room).frame(); + panel.frame(); + let action = "Remove Points, Keep Shape"; + assert!(panel.rect(action).bottom() > room.y, "the action starts clipped"); + panel.focus(action); + let rect = panel.rect(action); + assert!(panel.focused(action) && rect.top() >= 0.0 && rect.bottom() <= room.y, "focus reveals the action: {rect:?}"); + panel.focus("Make Smooth"); + panel.click("Make Smooth"); + let anchor = readout(&panel.app()).anchor.unwrap(); + assert!(anchor.lengths.iter().all(|length| *length > 0.0)); +} + /// Runs `f` on the held options dialog, `None` when none is open. fn held(app: &VectorcraftApp, f: impl FnOnce(Option<&mut HostedParamDialog>) -> R) -> R { app.dialogs().expect("the window's dialogs").with(|h| f(h.get_mut::())) @@ -84,15 +110,107 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() { assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("straight")); ok(&mut app, &[("mode", FieldValue::Text("arc".into()))]); assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("arc")); - // The Tangent Circle tool's radius for Shift. + // The Tangent Circle tool's radius for Shift, and Add Points to Existing Paths (off to start). app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); - assert_eq!(held(&app, |d| d.expect("the held dialog").fields().number("radius")), Some(36.0)); - ok(&mut app, &[("radius", FieldValue::Number(12.5))]); + let shown = held(&app, |d| { + let f = d.expect("the held dialog").fields(); + (f.number("radius"), f.bool("addPoints")) + }); + assert_eq!(shown, (Some(36.0), Some(false))); + let rows = super::options_params("tangentCircle", crate::canvas::rulers::general_lengths(&app)); + assert!(rows.iter().any(|p| p.key == "addPoints" && p.label.as_str() == "Add Points to Existing Paths"), "the option has a row"); + ok(&mut app, &[("radius", FieldValue::Number(12.5)), ("addPoints", FieldValue::Bool(true))]); assert_eq!(app.session.tool_options_of("tangentCircle")["radius"], json!(12.5)); + assert_eq!(app.session.tool_options_of("tangentCircle")["addPoints"], json!(true)); assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err()); assert_eq!(KIND, "pathToolOptions"); } +/// The Tangent Circle tool's options dialog shows the preview and snapping options, OK sets them, +/// and a value the tool refuses sets none of them and keeps the dialog open. +#[test] +fn the_tangent_circle_options_set_the_preview_and_snapping() { + let mut app = app_with_window(); + let ctx = host::ctx(&app); + let ok = |app: &mut VectorcraftApp, set: &[(&str, FieldValue)]| { + held(app, |d| { + let d = d.expect("the held dialog"); + for (key, value) in set { + d.set_field(*key, value.clone()); + } + }); + app.dialogs().expect("the window's dialogs").with(|h| h.confirm::(&ctx)); + crate::dialogs::host::pump(app, &ctx); + crate::tests_synthetic::key_frame(app, &ctx, vec![]); + }; + app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); + let shown = held(&app, |d| { + let f = d.expect("the held dialog").fields(); + (f.bool("center"), f.bool("radii"), f.text("color").map(str::to_owned), f.number("snapTolerance"), f.bool("snapWithoutGuides")) + }); + assert_eq!(shown, (Some(true), Some(true), Some("red".to_owned()), Some(3.0), Some(true))); + ok( + &mut app, + &[ + ("center", FieldValue::Bool(false)), + ("radii", FieldValue::Bool(false)), + ("color", FieldValue::Text("magenta".into())), + ("snapTolerance", FieldValue::Number(9.0)), + ("snapWithoutGuides", FieldValue::Bool(false)), + ], + ); + assert!(held(&app, |d| d.is_none()), "OK closes the dialog"); + let o = app.session.tool_options_of("tangentCircle"); + assert_eq!((&o["center"], &o["radii"], &o["color"], &o["snapWithoutGuides"]), (&json!(false), &json!(false), &json!("magenta"), &json!(false))); + assert_eq!(o["snapTolerance"].as_f64(), Some(9.0)); + // A negative tolerance is refused: nothing changes and the dialog stays open. + app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); + ok(&mut app, &[("center", FieldValue::Bool(true)), ("snapTolerance", FieldValue::Number(-2.0))]); + assert!(held(&app, |d| d.is_some()), "a refusal keeps the dialog open"); + let o = app.session.tool_options_of("tangentCircle"); + assert_eq!((&o["center"], o["snapTolerance"].as_f64()), (&json!(false), Some(9.0))); +} + +/// The Tangent Circle tool's options dialog has a row for each option, a fractional snapping +/// tolerance opens as it is, and every color has a label, in the tool's order. +#[test] +fn the_tangent_circle_options_have_their_rows_and_a_fractional_tolerance() { + use craft::ui::patterns::form_dialogs::ParamKind; + let mut app = app_with_window(); + let params = super::options_params("tangentCircle", crate::canvas::rulers::general_lengths(&app)); + let rows: Vec<(&str, &str)> = params.iter().map(|p| (p.key.as_str(), p.label.as_str())).collect(); + assert_eq!( + rows, + [ + ("radius", "Radius"), + ("addPoints", "Add Points to Existing Paths"), + ("center", "Circle Center"), + ("radii", "Circle Radii Lines"), + ("color", "Color"), + ("snapTolerance", "Snap Tolerance"), + ("snapWithoutGuides", "Snap When Smart Guides Are Off"), + ] + ); + let colors = params.iter().find_map(|p| match &p.kind { + ParamKind::Choice { options, .. } if p.key == "color" => { + Some(options.iter().map(|(id, label)| (id.clone(), label.as_str().to_owned())).collect::>()) + } + _ => None, + }); + let expected: Vec<(String, String)> = vectorcraft_tools::addons::tangent_circle::COLORS + .iter() + .zip(super::TANGENT_CIRCLE_COLORS) + .map(|((name, _), label)| ((*name).to_owned(), label.to_owned())) + .collect(); + assert_eq!(colors, Some(expected)); + for (name, _) in vectorcraft_tools::addons::tangent_circle::COLORS { + assert!(super::TANGENT_CIRCLE_COLORS.iter().any(|label| label.to_lowercase() == *name), "{name} has a label"); + } + app.run("tool.setOption", json!({"tool": "tangentCircle", "values": {"snapTolerance": 7.5}})).unwrap(); + app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); + assert_eq!(held(&app, |d| d.expect("the held dialog").fields().number("snapTolerance")), Some(7.5)); +} + #[test] fn the_parametric_shape_panel_edits_the_selected_shape_or_the_tools_next_one() { let mut app = app(); @@ -112,6 +230,44 @@ fn the_parametric_shape_panel_edits_the_selected_shape_or_the_tools_next_one() { assert!(id.is_none() && super::shape::plain_selected(&app)); } +/// The panel's W and H keep the point of the selection's box that the Transform panel and the +/// Control bar share in place, as their own W and H do, on upright and turned shapes. +#[test] +fn the_parametric_shape_panels_size_fields_keep_the_shared_reference_point() { + for (refi, rotation) in [(0usize, 0.0), (8, 0.0), (2, 30.0), (0, 180.0)] { + let mut app = app(); + let params = json!({"kind": "rectangle", "center": [150, 150], "width": 100, "height": 60, "rotation": rotation}); + let id = vectorcraft_doc::NodeId(app.run("addon.pathtools.shape.create", params).unwrap()["id"].as_u64().unwrap()); + let shape = + |app: &VectorcraftApp| vectorcraft_tools::addons::parametric_shape::read(app.session.active().unwrap().doc.node(id).unwrap()).unwrap(); + app.ui.transform_panel.reference_point = refi; + let (before, was) = (shape(&app), app.selection_box().unwrap().reference_point(refi)); + let mut panel = Panel::new(app, super::shape::show); + panel.type_into("W", "160"); + panel.type_into("H", "20"); + let mut app = panel.app(); + let after = shape(&app); + assert!(after.width > before.width && after.height < before.height, "reference {refi}: W and H took {after:?}"); + let moved = app.selection_box().unwrap().reference_point(refi).distance(was); + assert!(moved < 1e-6, "reference {refi}, rotation {rotation}: the reference point moved {moved} pt"); + } + // With an anchor direct-selected the locator shows the anchors' box, so W keeps the shape's center. + let mut app = app(); + let params = json!({"kind": "rectangle", "center": [150, 150], "width": 100, "height": 60}); + let id = vectorcraft_doc::NodeId(app.run("addon.pathtools.shape.create", params).unwrap()["id"].as_u64().unwrap()); + app.session + .select(|_, sel| { + sel.anchors.insert(id, [(0, 1)].into_iter().collect()); + }) + .unwrap(); + app.ui.transform_panel.reference_point = 0; + let mut panel = Panel::new(app, super::shape::show); + panel.type_into("W", "160"); + let app = panel.app(); + let after = vectorcraft_tools::addons::parametric_shape::read(app.session.active().unwrap().doc.node(id).unwrap()).unwrap(); + assert!((after.width - 160.0).abs() < 1e-6 && after.center.distance(vectorcraft_geom::Point::new(150.0, 150.0)) < 1e-6, "{after:?}"); +} + /// The Corner Tool and Shared Edge Merge Tool items leave a floating Anchor Inspector showing /// instead of closing it, and in Presentation Mode they choose the tool without failing. #[test] diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 2f25c3ea4d..b7502126e1 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -31,7 +31,7 @@ use super::state::SYSTEM_CLIPBOARD_POLL; use super::{ Arc, AutomationRoots, ControlRequest, Receiver, Session, UiState, VectorcraftApp, View, ViewInfo, background, canvas, chrome, credits, dialogs, edits, export_progress, file_access, file_asks, fileio, font_menu, i18n, io, menus, opening, palette, panel_docking, panels, place, placing, - plugin_runs, prefs_dialog, recovery, screen_color, shortcuts, theme, trace_runs, unsaved, updates_ui, + plugin_runs, prefs_dialog, recovery, retype_runs, screen_color, shortcuts, theme, trace_runs, unsaved, updates_ui, }; mod commands; @@ -120,6 +120,7 @@ impl VectorcraftApp { last_ms: 0.0, moved: false, from_worker: false, + worker_parts: false, reused: None, waits_for_still: cfg!(target_arch = "wasm32"), still: None, @@ -150,6 +151,7 @@ impl VectorcraftApp { carry_target: None, last_drag: None, escaped_press: false, + host_caps_lock: None, committed_preview: false, panes: Default::default(), windows: crate::doc_windows::Windows::new(known), @@ -185,6 +187,7 @@ impl VectorcraftApp { titlebar_inset: 0.0, last_effect: None, last_pathfinder: None, + last_filters: Default::default(), character_focus: None, run_count: 0, channel: None, @@ -221,6 +224,7 @@ impl VectorcraftApp { plugin_runs: Default::default(), placing: Default::default(), trace_runs: Default::default(), + retype_runs: Default::default(), recovery: Default::default(), closing: None, prefs: None, @@ -229,7 +233,9 @@ impl VectorcraftApp { shortcuts_dialog: None, shortcut_overrides: Default::default(), told: Default::default(), + missing_font_edit_token: None, held: Default::default(), + document_setup_source: None, edit_scopes: Default::default(), command_dialog: Default::default(), effect_dialogs: Default::default(), @@ -342,6 +348,7 @@ impl VectorcraftApp { plugin_runs::poll(self); trace_runs::poll(self); placing::poll(self); + retype_runs::poll(self); } /// The language the UI is drawn in: the Preferences window's choice while it is open (so a @@ -382,7 +389,8 @@ impl VectorcraftApp { self.host = Arc::new(self.host.with_lang(lang)); } let native_ppp = self.ui_ctx.as_ref().map_or(1.0, |ctx| ctx.pixels_per_point() / ctx.zoom_factor()); - let root = root_env(&self.session.prefs, native_ppp); + // The canvas steps through the zoom stops of the current window's display. + let root = root_env(&self.session.prefs, native_ppp, self.print_ppi()); FrameInput::new(root).commands(menus::model::command_input(self)).host(self.host.clone()) } @@ -441,6 +449,14 @@ impl VectorcraftApp { let now = self.now(); self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0); self.sync_views(); + // With no document open too, so closing the last one stops the host reading the wheel. A + // held press, whose previews change the document each frame, keeps what it was told. + if self.canvas.grab.is_none() { + crate::stylus::sync_wheel_use(self); + } + // A document that moved between the main window and a floating OS window, or opened, takes + // the density of the display that shows it. + self.settle_screen_ppi_if_changed(); self.refresh_replace_font_warning(false); updates_ui::tick(self, ctx); // Read the system clipboard only when that alone decides whether Paste is enabled. A @@ -499,6 +515,7 @@ impl VectorcraftApp { || !self.plugin_runs.running.is_empty() || !self.placing.pending.is_empty() || !self.trace_runs.running.is_empty() + || self.retype_runs.running.is_some() { // Keep the status bar's progress moving and pick the result up when it arrives. ctx.request_repaint_after(std::time::Duration::from_millis(100)); @@ -537,6 +554,9 @@ impl VectorcraftApp { if let Some(wait) = crate::panels::actions::tick_playback(self, now) { ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); } + // A `prefs.reset` run in this frame outside `Self::run` (a script's, say): the pass that follows draws the + // reset rows. + prefs_dialog::apply_prefs_resets(self); } /// The canvas panel's body: the document tabs, then the canvas (a pane for each document while @@ -691,16 +711,21 @@ impl VectorcraftApp { } } +/// Use the same supported scale for the interface and the canvas. Invalid saved values fall back to 100%. +fn applied_ui_scaling(saved: f64) -> f32 { + if saved.is_finite() && saved > 0.0 { saved.clamp(0.75, 2.0) as f32 } else { 1.0 } +} + /// The root values the preferences give every frame: the theme, the interface scale (UI Scaling -/// over the display's `native_ppp`), Show Tool Tips, the zoom stops and which drags scrub a value -/// (Scrub Numeric Fields: the side label only, or nothing). -pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32) -> RootEnv { +/// over the display's `native_ppp`), Show Tool Tips, the zoom stops (100% at `print` screen points +/// to an inch, [`crate::state::print_ppi`]) and which drags scrub a value (Scrub Numeric Fields: the +/// side label only, or nothing). +pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print: Option) -> RootEnv { let (theme, mode, accent) = theme::root_theme(prefs); - // A hand-edited preferences file must not scale the interface to nothing. - let scaling = if prefs.ui_scaling.is_finite() && prefs.ui_scaling > 0.0 { prefs.ui_scaling as f32 } else { 1.0 }; + let scaling = applied_ui_scaling(prefs.ui_scaling); let mut root = RootEnv::new().theme(theme).mode(mode).accent(accent).scale(Scale::new(scaling)).tooltips(prefs.show_tool_tips); root.sizes = theme::app_sizes(); - root.values.set(view::zoom_scheme(prefs, native_ppp)); + root.values.set(view::zoom_scheme(print, native_ppp)); root.values.set(if prefs.scrub_numeric_fields { ScrubDrags::LabelOnly } else { ScrubDrags::Off }); // Number fields as production drew them: the value and its unit one run at the start ("720 pt"), percentages // whole and lengths to a thousandth of a point (357.114 pt). diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index c912a62fa7..9f21fee18d 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -77,10 +77,16 @@ impl VectorcraftApp { pub fn run(&mut self, id: &str, params: Value) -> Result { self.beacon.command(id); let touch_workspace = self.session.prefs.touch_workspace; + // A `prefs.reset` that ran straight on the session applies before this command can switch workspaces. + crate::prefs_dialog::apply_prefs_resets(self); let result = self.run_now(id, params); + crate::prefs_dialog::apply_prefs_resets(self); if id == "prefs.import" && result.is_ok() { crate::prefs_dialog::imported(self, touch_workspace); } + if let Ok(r) = &result { + crate::plugin_runs::show_notice(self, id, r); + } placing::settle_swatch_paste(self); result } @@ -234,6 +240,7 @@ impl VectorcraftApp { return Err(e); } let spot_base = panels::color_guide::before_command(self); + let plugins_before = dialogs::plugin::before_command(); let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); let r = panels::actions::after_recorded_command(self, r); if r.is_ok() @@ -241,6 +248,8 @@ impl VectorcraftApp { { self.last_pathfinder = Some(op.to_string()); } + // A filter plug-in run becomes Object › Plug-ins › Apply Last Filter. + dialogs::plugin::after_command(self, id, ¶ms, &r, plugins_before); let copied = r.is_ok() && self.publish_copy(id); self.sync_views(); self.refresh_replace_font_warning(false); diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 4d27ffa98d..fcd71714d3 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -19,10 +19,21 @@ pub(crate) fn navigation(p: &Prefs) -> NavigationOptions { options } -/// The zoom rungs and range of the app, with 100 % at the device zoom Display Print Size at 100 % -/// Zoom gives on a display of `native_ppp` pixels per point. -pub(crate) fn zoom_scheme(p: &Prefs, native_ppp: f32) -> ZoomScheme { - ZoomScheme::ILLUSTRATOR.with_hundred(crate::state::zoom_baseline(p.display_print_size) * f64::from(native_ppp)) +/// The zoom rungs and range of the app, with 100 % at the device zoom that shows a document inch in +/// `print` screen points ([`crate::state::print_ppi`]; one document point per screen point when +/// `None`) on a display of `native_ppp` pixels per point. +pub(crate) fn zoom_scheme(print: Option, native_ppp: f32) -> ZoomScheme { + ZoomScheme::ILLUSTRATOR.with_hundred(crate::state::zoom_baseline(print) * f64::from(native_ppp)) +} + +/// Whether view command `command` fits the view to the window (`Some(true)`), sets a zoom +/// percentage (`Some(false)`), or leaves the zoom alone (`None`). +pub(crate) fn fits_window(command: ViewCommands) -> Option { + match command { + ViewCommands::FitOnScreen | ViewCommands::FillScreen | ViewCommands::FitArtboard | ViewCommands::FitLayers => Some(true), + ViewCommands::RotateClockwise | ViewCommands::RotateCounterclockwise | ViewCommands::ResetRotation => None, + _ => Some(false), + } } impl VectorcraftApp { @@ -47,8 +58,11 @@ impl VectorcraftApp { } self.views.truncate(docs.len()); self.views.extend(docs.iter().skip(self.views.len()).map(View::of)); + // A new view counts its zoom from the main window's display, where it is first shown. + let main = self.main_ppi(); for (view, doc) in self.views.iter_mut().zip(docs) { view.artboard = view.artboard.min(doc.doc.artboards.len().saturating_sub(1)); + view.shown_ppi.get_or_insert(main); } let uids: Vec = docs.iter().map(|d| d.uid).collect(); if let Some(ctx) = &self.ui_ctx { @@ -135,6 +149,169 @@ impl VectorcraftApp { self.session.active().map_or(vectorcraft_geom::Point::ZERO, |d| d.doc.ruler_origin_for(artboard)) } + /// The screen points an inch takes at 100% zoom with Display Print Size at 100% Zoom on, for + /// the current window's display; `None` with it off ([`crate::state::print_ppi`]). + pub(crate) fn print_ppi(&self) -> Option { + self.print_ppi_of(crate::doc_windows::current(self)) + } + + /// [`Self::print_ppi`] for window `w`: the density its view's zoom counts from, which is the + /// density of the display that shows it once [`Self::settle_screen_ppi`] has run. + pub(crate) fn print_ppi_of(&self, w: Option) -> Option { + let counted = w.and_then(|w| crate::doc_windows::view(self, w)?.shown_ppi); + let ppi = counted.unwrap_or_else(|| w.map_or(self.main_ppi(), |w| self.window_ppi(w))); + crate::state::print_ppi(self.session.prefs.display_print_size, ppi.ppi()) + } + + /// The density of the display that shows window `w`: its own OS window's when it floats in one + /// that the host found on a display, else the main window's ([`Self::main_ppi`]). + fn window_ppi(&self, w: crate::doc_windows::Win) -> crate::ScreenPpi { + crate::doc_windows::screen_ppi(self, w).unwrap_or(self.main_ppi()) + } + + /// The density the main window's views count from: the host's reading, or while the main + /// window's display has not answered, the last reading, so every view there counts from the + /// same density. + fn main_ppi(&self) -> crate::ScreenPpi { + match self.services.screen_ppi { + crate::ScreenPpi::Unread => self.canvas.windows.main_read.unwrap_or(crate::ScreenPpi::Unread), + read => read, + } + } + + /// Takes `ppi` as the density the host read for the main window's display, `None` for a + /// display that reports no size ([`crate::Services::screen_ppi`]), and settles the views + /// ([`Self::settle_screen_ppi`]). Returns whether the density changed. + pub fn set_screen_ppi(&mut self, ppi: Option) -> bool { + self.set_screen_reading(crate::ScreenPpi::Read(ppi)) + } + + /// [`Self::set_screen_ppi`] with the host's reading, [`crate::ScreenPpi::Unread`] while the + /// main window's display is unknown or has not answered. + pub fn set_screen_reading(&mut self, ppi: crate::ScreenPpi) -> bool { + if self.services.screen_ppi == ppi { + return false; + } + // A switch of the preference made since the last frame applies before the reading does. + self.follow_print_size_switch(); + self.services.screen_ppi = ppi; + if ppi != crate::ScreenPpi::Unread && self.session.prefs.display_print_size { + self.canvas.windows.main_read = Some(ppi); + } + self.settle_screen_ppi(); + true + } + + /// Gives each window's view the density of the display that shows it. With Display Print Size + /// at 100% Zoom on, a view moved between two displays the host has read keeps its zoom + /// percentage (a display that reports no size counts 96 points to an inch), so the art keeps + /// its physical size on the new display; the views of other displays keep their zoom. At the + /// first reading of a view's display, a view that still has the zoom a fit or the document's + /// saved view gave it keeps that zoom, and any other view keeps its percentage, counted from + /// 96 points to an inch until then. + pub(crate) fn settle_screen_ppi(&mut self) { + for w in crate::doc_windows::windows(self) { + self.settle_window_ppi(w, true); + } + } + + /// [`Self::settle_screen_ppi`] for window `w` alone. With `keep` false (a fit made for the + /// window), the view counts from the display's reading, without a change of zoom; while the + /// display is being read, it counts from the last reading, and the reading still to come + /// leaves its zoom alone. + pub(crate) fn settle_window_ppi(&mut self, w: crate::doc_windows::Win, keep: bool) { + let on = self.session.prefs.display_print_size; + let now = self.window_ppi(w); + let reading = crate::doc_windows::screen_ppi(self, w).unwrap_or(self.services.screen_ppi); + let Some(v) = crate::doc_windows::view_mut(self, w) else { return }; + // Off, a view counts from no reading, so the first one after the preference is turned on + // keeps the zoom chosen meanwhile. + if !on { + v.shown_ppi = Some(crate::ScreenPpi::Unread); + v.fit_unread = false; + return; + } + if !keep { + // While the display is being read, the fit counts from the last reading, as the other + // views there do, and the reading keeps its zoom. A floating window whose display has + // not answered keeps counting from the density it was last shown at. + match now { + crate::ScreenPpi::Unread => { + v.shown_ppi.get_or_insert(now); + } + read => v.shown_ppi = Some(read), + } + v.fit_unread = reading == crate::ScreenPpi::Unread; + return; + } + // A fit made while its display is being read waits for that reading. + if v.fit_unread && reading == crate::ScreenPpi::Unread { + return; + } + // A display that has not answered yet leaves the view counting from the last one read, so + // the answer, when it comes, keeps the zoom percentage. + let crate::ScreenPpi::Read(after) = now else { + v.shown_ppi.get_or_insert(now); + return; + }; + let fitted = v.fit_zoom == Some(v.zoom); + let before = match v.shown_ppi { + _ if fitted && v.fit_unread => None, + Some(crate::ScreenPpi::Read(before)) => Some(before), + _ if fitted => None, + _ => Some(None), + }; + v.fit_unread = false; + if let Some(before) = before + && before != after + && let (Some(b), Some(a)) = (crate::state::print_ppi(on, before), crate::state::print_ppi(on, after)) + { + v.zoom = (v.zoom * a / b).clamp(0.0313, 640.0); + } + v.shown_ppi = Some(now); + } + + /// [`Self::settle_screen_ppi`] when the main window's density or a floating window's changed + /// since it last ran from here, or a window started or stopped floating, or Presentation Mode + /// started or ended. With Display Print Size at 100% Zoom off, the desktop host does not read + /// the displays: every density read before is forgotten, so the readings after the preference + /// is turned on again count as first readings. + pub(crate) fn settle_screen_ppi_if_changed(&mut self) { + self.follow_print_size_switch(); + let key = (self.services.screen_ppi, crate::doc_windows::floating_ppi(self)); + if self.canvas.windows.settled.as_ref() != Some(&key) { + self.settle_screen_ppi(); + self.canvas.windows.settled = Some(key); + } + } + + /// Takes in a change of Display Print Size at 100% Zoom since this last ran: turned off, every + /// density read before is forgotten; turned on, every view's zoom counts as the one its first + /// reading keeps. + fn follow_print_size_switch(&mut self) { + let off = !self.session.prefs.display_print_size; + let was_off = std::mem::replace(&mut self.canvas.windows.print_size_off, off); + if off && !was_off { + crate::doc_windows::forget_ppi(self); + self.services.screen_ppi = crate::ScreenPpi::Unread; + self.canvas.windows.main_read = None; + self.services.screens.clear(); + for w in crate::doc_windows::windows(self) { + if let Some(v) = crate::doc_windows::view_mut(self, w) { + v.shown_ppi = Some(crate::ScreenPpi::Unread); + } + } + } + if was_off && !off { + // The zoom chosen while it was off stays when the displays are read. + for w in crate::doc_windows::windows(self) { + if let Some(v) = crate::doc_windows::view_mut(self, w) { + v.fit_zoom = Some(v.zoom); + } + } + } + } + pub fn view_mut(&mut self) -> Option<&mut View> { self.sync_views(); let i = self.session.active_index()?; @@ -150,7 +327,7 @@ impl VectorcraftApp { /// Preferences › User Interface › UI Scaling, as the interface applies it. pub(crate) fn ui_scaling(&self) -> f32 { - self.session.prefs.ui_scaling.clamp(0.75, 2.0) as f32 + super::applied_ui_scaling(self.session.prefs.ui_scaling) } /// Ask the active view's canvas to run `request` in its next pass; `bounds` are the layers' bounds @@ -178,17 +355,38 @@ impl VectorcraftApp { }; let target = crate::canvas::view_target(self, win); let (scaling, ppp) = (self.ui_scaling(), ctx.pixels_per_point()); - let scheme = zoom_scheme(&self.session.prefs, ppp / ctx.zoom_factor()); + self.before_view_command(win, command); + let scheme = zoom_scheme(self.print_ppi_of(Some(win)), ppp / ctx.zoom_factor()); let Some(v) = self.view_mut() else { return }; let before = *v; let mut cv = v.canvas(scaling, v.rect); let layers = move || bounds; if command.apply(&mut cv, &target, Some(&layers), ppp, &scheme) { v.set_canvas(&cv, scaling); + self.after_view_command(win, command); self.ease_view(before); } } + /// Before view command `command` runs on window `w`'s view: a fit to the window is made for the + /// display the window is on now, and a zoom percentage (Actual Size) counts from the density the + /// view counts from, which a reading still to come rescales (Display Print Size at 100% Zoom). + pub(crate) fn before_view_command(&mut self, w: crate::doc_windows::Win, command: ViewCommands) { + if let Some(fit) = fits_window(command) { + self.settle_window_ppi(w, !fit); + } + } + + /// After view command `command` ran on window `w`'s view: a fit to the window is kept at the + /// first reading of its display; a zoom percentage keeps its percentage then. + pub(crate) fn after_view_command(&mut self, w: crate::doc_windows::Win, command: ViewCommands) { + if let Some(fit) = fits_window(command) + && let Some(v) = crate::doc_windows::view_mut(self, w) + { + v.fit_zoom = fit.then_some(v.zoom); + } + } + pub fn view_info(&self) -> ViewInfo { ViewInfo { // The tools measure their tolerances and widgets in the interface's points. @@ -208,7 +406,33 @@ impl VectorcraftApp { shape_widgets: self.ui.view.shape_widgets, screen: self.screen_frame(), artboard: self.view().map_or(0, |v| v.artboard), - ..ViewInfo::default() + precise: self.precise_cursors(), + } + } + + /// Whether the drawing tools show precise cursors: General › Use Precise Cursors is on, or Caps Lock is + /// (`Session::caps_lock`, which the canvas keeps at the host's state and `view.capsLock` sets). The canvas's pointer + /// and the tools' brush tips both follow it. + pub(crate) fn precise_cursors(&self) -> bool { + self.session.prefs.use_precise_cursors || self.session.caps_lock + } + + /// Takes the host's Caps Lock state `on` when it changes: the session follows it until the next change, and a + /// `view.capsLock` call between changes stays in place. + pub(crate) fn follow_caps_lock(&mut self, on: bool) { + if self.canvas.host_caps_lock == Some(on) { + return; + } + let first_reading = self.canvas.host_caps_lock.is_none(); + self.canvas.host_caps_lock = Some(on); + // A `view.capsLock` call that ran before the first reading stays in place; that reading is only the baseline. + if first_reading && self.session.caps_lock { + return; + } + if self.session.caps_lock != on + && let Err(err) = self.run("view.capsLock", serde_json::json!({ "on": on })) + { + log::error!("Could not update the Caps Lock state: {err}"); } } } diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 90875851d4..08b15cddc5 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -25,6 +25,10 @@ pub struct CanvasCache { /// The frame shown was rendered on the worker: an interaction's frames stay there /// ([`canvas::show`]). pub from_worker: bool, + /// The worker's frame shown drew art in a way that depends on its size, or a part of it drawn + /// again on this thread would not have matched the frame around it: until the worker's next + /// frame is shown, edits of the frame shown render on the worker ([`canvas::show`]). + pub worker_parts: bool, /// The frame shown holds pixels the worker copied from its last frame, and when it was shown /// (seconds, egui's input time): it renders whole once it has been shown for /// [`canvas::STILL_SECS`] with the view unmoved. @@ -107,6 +111,9 @@ pub struct CanvasCache { /// Escape cancelled the tool's press while the button is still down: its release still sends the tool its Up, /// which gives back a selection tool Cmd lent. pub escaped_press: bool, + /// The host's Caps Lock state at the last canvas pass, which `VectorcraftApp::follow_caps_lock` compares with the + /// next reading; `None` before the first pass. + pub host_caps_lock: Option, /// A press on the canvas committed a panel field's running preview before the tool took the press, as the field's /// commit came first in production: the field's own commit later in the pass has nothing left to run. pub committed_preview: bool, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 596cb119f0..d13d79e4b9 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5,9 +5,11 @@ use craft::behavior::{CanvasView, PressPhase}; use craft::keymap::Mods; use craft::ui::canvas::{ - Canvas, CanvasScrollbars, CanvasSpace, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, canvas_space, tool_pass, + Canvas, CanvasScrollbars, CanvasSpace, ContextSource, RotateView, ToolHostResponse, ToolPass, ViewCommands, ViewRequest, ViewTarget, + canvas_space, tool_pass, }; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::primitives::PaintSlot; use craft::ui::runtime::env::Env; use craft::ui::runtime::focus::NudgeMods; use craft::ui::style::StyleCx; @@ -108,6 +110,10 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if app.ui.home.is_some_and(|k| k != crate::menus::home_key(app)) { app.ui.home = None; } + // The Home screen and the empty window show no marks: a closed document's text nodes are not kept. + if app.session.active().is_none() { + marks::release_text_marks(app); + } let full = ui.available_rect_before_wrap(); if crate::menus::home_showing(app) { // No type editor shows to lose the keys: the marked text stays as typed. @@ -133,6 +139,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut Ui) { struct Body { reply: Option, context_at: Option, + /// The pasteboard's `context_at` answers the Menu key or Shift+F10, not a secondary click. + context_key: bool, /// A view a compass or scroll bar edit made this pass. edited: Option, } @@ -147,9 +155,19 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin // A measuring run applies no view request: the view, its request and its fit wait for the pass // that shows the canvas. let measuring = craft::ui::runtime::measure::active(ui.ctx()); - let Some(view) = doc_windows::view_mut(app, win) else { return false }; // Presentation Mode shows the active artboard on the whole screen: it fits again when the screen changes. - let refit = !view.fitted || (presenting && view.rect != area); + let refits = |v: &crate::state::View| !v.fitted || (presenting && v.rect != area); + // The view command this pass runs, made for the display the window is on (Display Print Size at 100% Zoom). + let command = doc_windows::view(app, win) + .filter(|_| !measuring) + .and_then(|v| v.request.map(|(r, _)| r.command()).or_else(|| refits(v).then_some(ViewCommands::FitArtboard))); + if let Some(command) = command { + app.before_view_command(win, command); + } + let ppp = ui.ctx().pixels_per_point(); + let scheme = crate::app::view::zoom_scheme(app.print_ppi_of(Some(win)), ppp / ui.ctx().zoom_factor()); + let Some(view) = doc_windows::view_mut(app, win) else { return false }; + let refit = refits(view); let (request, moved) = if measuring { (view.request, view.moved) } else { @@ -165,6 +183,16 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin } let mut cv = view.canvas(scaling, area); let given = cv; + // A zoom percentage (Actual Size) counts from the density of the display that shows this + // window: it runs here with that display's zoom stops, which the canvas's own may not be. + let mut moved = moved; + if let Some(request) = queued.first().copied().filter(|r| crate::app::view::fits_window(r.command()) == Some(false)) { + let layers = move || bounds; + if request.command().apply(&mut cv, &target, Some(&layers), ppp, &scheme) && matches!(request, ViewRequest::Command(_)) { + moved = Some(ViewMove::Ease(given)); + } + queued.clear(); + } let (x, y, zero) = rulers::texts(app, win); let strips = if app.ui.view.rulers && !presenting { Some(rulers::strips(zero, kind)) @@ -174,6 +202,11 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin }; let pasteboard = app.session.documents().get(win.0).map(|st| artboards::pasteboard_color(app, st, app.outline_view())); let layers = move || bounds; + let host_caps_lock = craft::ui::runtime::lock_keys::caps_lock(ui.ctx()); + app.follow_caps_lock(host_caps_lock); + // The canvas reverses the state it is given while the host's Caps Lock is on: given this, it shows the precise + // cursors the tools are told about. + let precise = app.precise_cursors() != host_caps_lock; let prefs = &app.session.prefs; let mut canvas = Canvas::new("Document") .id(canvas_id(win)) @@ -185,7 +218,7 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin .body_nudges(ARROWS) .rulers(x, y) .with_rulers(strips) - .precise_cursors(prefs.use_precise_cursors); + .precise_cursors(precise); if let Some(pasteboard) = pasteboard { canvas = canvas.pasteboard(pasteboard); } @@ -210,8 +243,12 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin rulers::apply(app, ui, out); } let pressed = matches!(output.press.phase, PressPhase::Down { .. }); - let Body { reply, context_at, edited } = body; - let request = reply.as_ref().and_then(|r| r.context.as_ref()).map(|c| c.at).or(context_at); + let Body { reply, context_at, context_key, edited } = body; + let request = reply + .as_ref() + .and_then(|r| r.context.as_ref()) + .map(|c| context_menu::Request { at: c.at, key: c.source == ContextSource::Key }) + .or(context_at.map(|at| context_menu::Request { at, key: context_key })); let jumped = edited.is_some(); // Presentation Mode keeps its view through a drag of the middle button, which the canvas pans on its own. let view_now = @@ -223,6 +260,9 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin // An edit of the compass or a scroll bar reaches the next pass, which stops a running ease. view.moved = jumped.then_some(ViewMove::Jump); } + if let Some(command) = command { + app.after_view_command(win, command); + } if kind == BodyKind::Pane || presenting { return pressed; } @@ -238,11 +278,17 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin pressed } -/// The body of the canvas in order: controls that take presses first, the tool host, the picture last. +/// The body of the canvas in order: controls that take presses first, the tool host, the selection's marks, the +/// picture last. fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: Option<&ToolPass>, win: Win, kind: BodyKind) -> Body { let live = kind == BodyKind::Live; let presenting = app.ui.screen_mode == 3; - let mut out = Body { context_at: artboards::show(app, ui, space, win, kind).map(|p| space.view.to_screen(p)), ..Body::default() }; + let background = space.background(); + let mut out = Body { + context_at: artboards::show(app, ui, space, win, kind).map(|p| space.view.to_screen(p)), + context_key: background.context.is_none() && background.context_key, + ..Body::default() + }; grids(app, ui, space, win); if live { find_shown_tool(app, ui.ctx(), space); @@ -253,7 +299,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::dialogs::simplify_slider::show(app, ui, &space.view); } guides::show(app, ui, space, win, kind); - selection::show(app, ui, space, win, kind); + // The selection's marks paint here, under the widgets and bars, and are drawn after the tool host has taken this + // frame's pointer event, from the document as the event leaves it. + let marks = PaintSlot::reserve(ui.painter()); widgets::show(app, ui, space, win, kind); if !presenting && !revolve_editing(app) { crate::panels::three_d::handles::show(app, ui, space); @@ -290,6 +338,9 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::type_editing::show(app, ui); } } + let after = PaintSlot::reserve(ui.painter()); + selection::show(app, ui, space, win, kind); + marks.extend(ui.ctx(), after.take_after(ui.ctx())); drops::show(app, ui, win, kind); raster::picture(app, ui, space, win, kind); out @@ -333,7 +384,7 @@ fn grids(app: &VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, win: Win) { if let Some((grid, in_back)) = app.session.documents().get(win.0).and_then(|st| grid::document_grid(app, st)) { let _ = if in_back { grid.picture() } else { grid }.show_at(ui, space.view.rect); } - if let Some(grid) = grid::pixel_grid(app) { + if let Some(grid) = grid::pixel_grid(app, app.print_ppi_of(Some(win))) { let _ = grid.show_at(ui, space.view.rect); } } diff --git a/crates/ui-egui/src/canvas/artboards.rs b/crates/ui-egui/src/canvas/artboards.rs index e493bbc561..605e7108d2 100644 --- a/crates/ui-egui/src/canvas/artboards.rs +++ b/crates/ui-egui/src/canvas/artboards.rs @@ -61,18 +61,28 @@ pub(super) fn frames(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, vi .collect() } -/// A line round each artboard in Outline, the drop shadow in Preview. +/// A line round each artboard in Outline, the drop shadow in Preview, and no border in Overprint Preview (and +/// Separations Preview, which turns it on). pub(super) fn border(outline: bool) -> PageBorder { - if outline { PageBorder::Line } else { PageBorder::DropShadow } + if outline { + PageBorder::Line + } else if vectorcraft_render::proof::overprint_preview_on() { + PageBorder::None + } else { + PageBorder::DropShadow + } } -/// The pasteboard's color: white in Outline, the paper under Hide Artboards, else User Interface › Canvas Color, or the -/// interface's when that matches the interface brightness. +/// The pasteboard's color: white in Outline, the paper under Hide Artboards, white in Overprint Preview (and Separations +/// Preview, which turns it on), else User Interface › Canvas Color, or the interface's when that matches the interface +/// brightness. pub(super) fn pasteboard_color(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, outline: bool) -> PasteboardColor { if outline { PasteboardColor::Custom(DataColor::new(Color32::WHITE)) } else if !shows_artboards(app) { PasteboardColor::Custom(DataColor::new(paper_color(&st.doc.setup))) + } else if vectorcraft_render::proof::overprint_preview_on() { + PasteboardColor::Custom(DataColor::new(Color32::WHITE)) } else { crate::prefs_dialog::canvas_color(&app.session.prefs.canvas_color) .map_or(PasteboardColor::Default, |c| PasteboardColor::Custom(DataColor::new(c))) diff --git a/crates/ui-egui/src/canvas/artboards/tests.rs b/crates/ui-egui/src/canvas/artboards/tests.rs index 54cc9aedec..742e798e63 100644 --- a/crates/ui-egui/src/canvas/artboards/tests.rs +++ b/crates/ui-egui/src/canvas/artboards/tests.rs @@ -48,6 +48,7 @@ fn shift_clicking_a_name_toggles_selection_and_a_plain_click_activates() { #[test] fn outline_has_a_white_canvas_line_edges_and_no_paper() { + let _view = crate::testing::DefaultProofView::new(); let app = app_with(2); let st = app.session.active().unwrap(); assert_eq!(pasteboard_color(&app, st, true), PasteboardColor::Custom(DataColor::new(Color32::WHITE))); @@ -58,9 +59,43 @@ fn outline_has_a_white_canvas_line_edges_and_no_paper() { assert!(frames_of(&app, false).iter().all(|f| f.fill.is_some())); } +/// Overprint Preview, and Separations Preview, which turns it on, draw a white canvas around the artboards and no +/// shadows, in every Canvas Color; the artboards keep their paper. Outline keeps its line edges, and Hide Artboards its +/// paper canvas. Turning the preview off brings back the pasteboard color and the shadows. +#[test] +fn overprint_preview_draws_a_white_canvas_without_shadows() { + let _view = crate::testing::DefaultProofView::new(); + let mut app = app_with(2); + let white = PasteboardColor::Custom(DataColor::new(Color32::WHITE)); + let (overprint, separations) = ("view.overprintPreview", "view.separationsPreview"); + for canvas_color in ["matchUi", "darkGray", "lightGray"] { + app.run("prefs.set", json!({"key": "canvasColor", "value": canvas_color})).unwrap(); + let before = pasteboard_color(&app, app.session.active().unwrap(), false); + for (id, on) in [(overprint, true), (overprint, false), (separations, true), (separations, false)] { + app.run(id, json!({"on": on})).unwrap(); + let st = app.session.active().unwrap(); + let at = format!("{id} {on}, canvas color {canvas_color}"); + if on { + assert_eq!(pasteboard_color(&app, st, false), white, "{at}"); + assert_eq!(border(false), PageBorder::None, "{at}"); + } else { + assert_eq!(pasteboard_color(&app, st, false), before, "{at}"); + assert_eq!(border(false), PageBorder::DropShadow, "{at}"); + } + assert_eq!(border(true), PageBorder::Line, "{at}"); + assert!(frames_of(&app, false).iter().all(|f| f.fill.is_some()), "{at}"); + } + } + app.run("view.overprintPreview", json!({"on": true})).unwrap(); + app.ui.view.artboards = false; + let st = app.session.active().unwrap(); + assert_eq!(pasteboard_color(&app, st, false), PasteboardColor::Custom(DataColor::new(paper_color(&st.doc.setup)))); +} + /// User Interface › Canvas Color paints the pasteboard in Preview; Outline keeps its white one. #[test] fn the_canvas_color_preference_paints_the_pasteboard() { + let _view = crate::testing::DefaultProofView::new(); let mut app = app_with(1); app.run("prefs.set", json!({"key": "canvasColor", "value": "darkGray"})).unwrap(); let st = app.session.active().unwrap(); diff --git a/crates/ui-egui/src/canvas/context_menu.rs b/crates/ui-egui/src/canvas/context_menu.rs index 146e91d039..853ec2e038 100644 --- a/crates/ui-egui/src/canvas/context_menu.rs +++ b/crates/ui-egui/src/canvas/context_menu.rs @@ -4,25 +4,39 @@ use craft::ui::contract::{Bind, ShowContainer as _, Trigger}; use craft::ui::menu::Menu; use egui::Pos2; use serde_json::json; +use vectorcraft_geom::Point; use super::marks; use super::outline::{hit_with, selection_hit_at}; use crate::VectorcraftApp; -/// The canvas context menu (right-click, Menu key, Shift+F10). A `request` (screen points: the pointer, or -/// the view centre for a key) selects the object under it unless it already is, then the menu lists what -/// applies to the selection ([`crate::menus::context_items`]) at that point until it closes. The locked -/// objects under the pointer ([`vectorcraft_doc::hit::locked_objects_at`]) are kept in `ui.context_locked` -/// for its Unlock submenu. With the Intertwine tool, a right-click where three or more objects of the group -/// overlap keeps the selection and puts what it arranges in `ui.context_intertwine` -/// ([`vectorcraft_tools::intertwine::menu_target`]). With the Artboard tool, an artboard takes the place of -/// the object ([`crate::panels::artboards::right_click`]). +/// A request for the canvas menu at `at` (screen points): a secondary click at the pointer, or the Menu key or +/// Shift+F10 (`key`), which the canvas reports at the view centre. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Request { + pub(crate) at: Pos2, + pub(crate) key: bool, +} + +/// The canvas context menu (right-click, Menu key, Shift+F10). A right-click selects the object under the +/// pointer unless it already is, then the menu lists what applies to the selection +/// ([`crate::menus::context_items`]) at that point until it closes. The locked objects under the pointer +/// ([`vectorcraft_doc::hit::locked_objects_at`]) are kept in `ui.context_locked` for its Unlock submenu. With +/// the Intertwine tool, a right-click where three or more objects of the group overlap keeps the selection and +/// puts what it arranges in `ui.context_intertwine` ([`vectorcraft_tools::intertwine::menu_target`]). With the +/// Artboard tool, an artboard takes the place of the object ([`crate::panels::artboards::right_click`]). A key +/// request keeps the selection and opens the menu at it ([`prepare_key`]). /// /// Called on every pass after the canvas shows, with its response as `opener`: the menu is shown from the /// point stored in `ui.context_menu_at`, so a later pass without a request keeps it open. -pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, opener: &egui::Response, request: Option) { - if let Some(at) = request { - prepare(app, space, at); +pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, opener: &egui::Response, request: Option) { + if let Some(request) = request { + let at = if request.key { + prepare_key(app, space) + } else { + prepare(app, space, request.at); + request.at + }; app.ui.context_menu_at = Some(at); } let Some(at) = app.ui.context_menu_at else { return }; @@ -69,3 +83,33 @@ fn prepare(app: &mut VectorcraftApp, space: &CanvasSpace, at: Pos2) { let _ = app.run("select.set", json!({ "ids": [top.0] })); } } + +/// The one-shot work of a key request: the menu is for the selection as it is (the selected artboards with the +/// Artboard tool), at the centre of the part of it in view, or at the view centre when none of it is in view. +/// Nothing under a point is looked up: no locked objects, word or Intertwine target. Returns the menu's point. +fn prepare_key(app: &mut VectorcraftApp, space: &CanvasSpace) -> Pos2 { + app.ui.context_locked = None; + app.ui.context_intertwine = None; + app.ui.context_spelling = None; + let on_artboards = app.session.tool_id() == "artboard"; + let bounds = if on_artboards { + app.session.active().and_then(|st| { + let picked = crate::panels::artboards::picked(app, st.doc.artboards.len()); + picked.iter().filter_map(|&i| st.doc.artboards.get(i).map(|a| a.rect)).reduce(|a, b| a.union(b)) + }) + } else { + app.selection_bounds() + }; + let view = &space.view; + let at = bounds + .map(|b| { + egui::Rect::from_points(&[b.origin(), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)].map(|p| view.to_screen(p))) + }) + .map(|r| r.intersect(view.rect)) + .filter(|r| !r.is_negative()) + .map_or(view.rect.center(), |r| r.center()); + if on_artboards { + crate::panels::artboards::measure_menu(app, view.to_doc(at)); + } + at +} diff --git a/crates/ui-egui/src/canvas/drops.rs b/crates/ui-egui/src/canvas/drops.rs index 274b1fde7f..f3f96171c0 100644 --- a/crates/ui-egui/src/canvas/drops.rs +++ b/crates/ui-egui/src/canvas/drops.rs @@ -23,7 +23,7 @@ use crate::doc_windows::Win; use crate::panel_drag::PanelDrag; use crate::panels::brushes::BrushKey; use crate::panels::brushes::BrushLibraries; -use crate::panels::graphic_styles::StyleKey; +use crate::panels::graphic_styles::StyleDrag; use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _}; use crate::panels::symbols::{SymbolKey, SymbolLibraries}; use crate::place::{CanvasDrop, CanvasFiles}; @@ -50,7 +50,7 @@ pub(crate) struct CarriedArt { #[derive(Clone, Debug)] enum Payload { Panel(PanelDrag), - Style(StyleKey), + Style(StyleDrag), Symbol(SymbolKey), Brush(BrushKey), Library(LibraryKey), @@ -171,12 +171,12 @@ impl Component for CanvasDrops<'_> { if self.kind == BodyKind::Live { // The art of this canvas's own document is not accepted as a panel payload: its move resumes. let panel = Target::new(rect, view, covered, |p: &PanelDrag| (!matches!(p, PanelDrag::Art { .. })).then(|| Payload::Panel(p.clone()))); - let style = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Style(d.grabbed.clone()))); + let style = Target::new(rect, view, covered, |d: &StyleDrag| (d.document == self.document).then(|| Payload::Style(d.clone()))); let symbol = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Symbol(d.grabbed.clone()))); let brush = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Brush(d.grabbed.clone()))); let library = Target::new(rect, view, covered, |d: &ListDrag| Some(Payload::Library(d.grabbed.clone()))); let panel = cx.drop_target::(&panel); - let style = cx.drop_target::, _>(&style); + let style = cx.drop_target::(&style); let symbol = cx.drop_target::, _>(&symbol); let brush = cx.drop_target::, _>(&brush); let library = cx.drop_target::, _>(&library); @@ -344,11 +344,12 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), run(app, "brush.apply", json!({"name": key.name, "ids": [owner]})) } }, - Payload::Style(key) => { + Payload::Style(style) if app.session.active().is_some_and(|st| st.uid == style.document) => { let Some(hit) = hit() else { return Ok(()) }; let top = top_object(app, &hit)?; - run(app, "graphicStyle.apply", json!({"name": key, "ids": [top], "add": drop.op == DropOperation::Copy})) + run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy})) } + Payload::Style(_) => Ok(()), Payload::Panel(PanelDrag::Paint { params, paint, .. }) if !params.is_null() => { if let Some(color) = paint.color() && crate::panels::proxy_cmd(app, false) == "paint.setFill" @@ -362,6 +363,12 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(), params["ids"] = json!([owner(app, &hit)?]); params["focus"] = json!(false); let cmd = crate::panels::proxy_cmd(app, false); + if let Some(gradient) = params.get_mut("gradient").and_then(Value::as_object_mut) { + if cmd == "paint.setStroke" { + gradient.remove("dither"); + } + params["keepModel"] = json!(true); + } run(app, cmd, params) } Payload::Panel(PanelDrag::Appearance(source)) => { diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index a9a8833daa..358c01f385 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -12,6 +12,7 @@ use vectorcraft_geom::Point; use super::{CarriedArt, Dropped, Payload, apply_drop}; use crate::panel_drag::PanelDrag; use crate::panels::brushes::{BrushKey, BrushLibraries}; +use crate::panels::graphic_styles::StyleDrag; use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _}; use crate::panels::symbols::{SymbolKey, SymbolLibraries}; use crate::{VectorcraftApp, canvas}; @@ -45,6 +46,71 @@ fn undo_len(app: &VectorcraftApp) -> usize { app.session.active().unwrap().history.undo.len() } +#[test] +fn a_foreign_graphic_style_drop_does_not_apply_a_style_with_the_same_name() { + let (mut app, ctx) = app_with_canvas(); + let add = |app: &mut VectorcraftApp, x| { + NodeId(app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()) + }; + add(&mut app, 20); + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Shared name"})).unwrap(); + let document = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + add(&mut app, 20); + app.run("paint.setFill", json!({"color": "#ed1c24"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Shared name"})).unwrap(); + let target = add(&mut app, 200); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + frame(&mut app, &ctx, vec![]); + + let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(); + let before = fill(&app); + let history = undo_len(&app); + let at = Point::new(250.0, 70.0); + let payload = Payload::Style(StyleDrag { document, name: "Shared name".into() }); + for operation in [DropOperation::Move, DropOperation::Copy] { + drop_at(&mut app, payload.clone(), at, operation).unwrap(); + assert_eq!(fill(&app), before); + assert_eq!(undo_len(&app), history, "neither kind of foreign drop makes an edit"); + } +} + +fn drop_dithered_rgb_gradient(app: &mut VectorcraftApp, fill: bool) -> NodeId { + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + let result = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 100})).unwrap(); + let id = NodeId(result["id"].as_u64().unwrap()); + app.session.fill_active = fill; + let mut gradient = GradientPaint::new(Default::default()); + gradient.gradient.stops[0].color = Color::rgb8(255, 0, 0); + gradient.gradient.dither = true; + let start = undo_len(app); + let drag = PanelDrag::paint(Paint::Gradient(Box::new(gradient))); + drop_at(app, Payload::Panel(drag), Point::new(50.0, 50.0), DropOperation::Move).unwrap(); + assert_eq!(undo_len(app), start + 1); + id +} + +#[test] +fn a_gradient_drop_preserves_rgb_stops_and_fill_dither() { + let (mut app, _ctx) = app_with_canvas(); + let id = drop_dithered_rgb_gradient(&mut app, true); + let doc = &app.session.active().unwrap().doc; + let Paint::Gradient(fill) = doc.node(id).unwrap().appearance.fill_paint() else { panic!("expected a gradient fill") }; + assert_eq!(fill.gradient.stops[0].color, Color::rgb8(255, 0, 0)); + assert!(fill.gradient.dither); +} + +#[test] +fn a_dithered_gradient_drop_applies_to_a_stroke_without_dither() { + let (mut app, _ctx) = app_with_canvas(); + let id = drop_dithered_rgb_gradient(&mut app, false); + let doc = &app.session.active().unwrap().doc; + let Paint::Gradient(stroke) = &doc.node(id).unwrap().appearance.stroke().unwrap().paint else { panic!("expected a gradient stroke") }; + assert_eq!(stroke.gradient.stops[0].color, Color::rgb8(255, 0, 0)); + assert!(!stroke.gradient.dither); +} + /// Each payload's effect, on art and off it: a style applies to the object hit (Alt adds on top), a paint fills it /// and leaves the selection (a gradient fits it), an appearance copies unless dropped on its source, a brush strokes /// the path hit and off art places its art if it has any, a library brush is added and applied in one step, a symbol @@ -67,12 +133,14 @@ fn a_drop_runs_the_effect_of_its_payload() { drop_at(&mut app, Payload::Panel(swatch), on_b, Move).unwrap(); assert_eq!(app.session.active().unwrap().doc.node(b).unwrap().appearance.fill_paint(), red); assert_eq!(app.session.active().unwrap().selection.objects, [a], "the selection stays"); - let name = app.session.active().unwrap().doc.graphic_styles[2].name.clone(); - drop_at(&mut app, Payload::Style(name.clone()), on_b, Move).unwrap(); + let st = app.session.active().unwrap(); + let name = st.doc.graphic_styles[2].name.clone(); + let style = Payload::Style(StyleDrag { document: st.uid, name: name.clone() }); + drop_at(&mut app, style.clone(), on_b, Move).unwrap(); let st = app.session.active().unwrap(); assert_eq!(st.doc.node(b).unwrap().extras().graphic_style, st.doc.graphic_style(&name).map(|g| g.id)); let items = st.doc.node(b).unwrap().appearance.items.len(); - drop_at(&mut app, Payload::Style(name.clone()), on_b, Copy).unwrap(); + drop_at(&mut app, style, on_b, Copy).unwrap(); let added = app.session.active().unwrap().doc.node(b).unwrap(); assert!(added.appearance.items.len() > items && added.extras().graphic_style.is_none(), "with Alt the style goes on top, unlinked"); let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(b).unwrap().appearance.fill_paint(); diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 71641858c1..6ee138bd34 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -44,13 +44,15 @@ pub(super) fn grid_look(prefs: &vectorcraft_engine::Prefs) -> (GridLine, Color32 } /// The pixel grid (Guides & Grid › Show Pixel Grid (Above 600% Zoom)): a line at every document -/// pixel in Pixel Preview, which the control draws from [`PIXEL_GRID_ZOOM`] on (its `min_zoom` is -/// the device zoom, as the view's). -pub(super) fn pixel_grid(app: &VectorcraftApp) -> Option { +/// pixel in Pixel Preview, which the control draws from [`PIXEL_GRID_ZOOM`] on as the zoom field +/// counts it, with `print` screen points to an inch at 100% ([`crate::state::print_ppi`]; its +/// `min_zoom` is the device zoom, as the view's). +pub(super) fn pixel_grid(app: &VectorcraftApp, print: Option) -> Option { if app.ui.screen_mode >= 3 || !app.ui.view.pixel_preview || !app.session.prefs.show_pixel_grid { return None; } - Some(CanvasGrid::new("Pixel grid").spacing((1.0, 1.0).into()).subdivisions(1).color(DataColor::new(PIXEL_GRID)).min_zoom(PIXEL_GRID_ZOOM)) + let min_zoom = PIXEL_GRID_ZOOM * crate::state::zoom_baseline(print); + Some(CanvasGrid::new("Pixel grid").spacing((1.0, 1.0).into()).subdivisions(1).color(DataColor::new(PIXEL_GRID)).min_zoom(min_zoom)) } /// A `#rrggbb` colour preference, `fallback` when it doesn't parse. diff --git a/crates/ui-egui/src/canvas/guides/tests.rs b/crates/ui-egui/src/canvas/guides/tests.rs index a989261d4d..dd0adb2963 100644 --- a/crates/ui-egui/src/canvas/guides/tests.rs +++ b/crates/ui-egui/src/canvas/guides/tests.rs @@ -105,9 +105,9 @@ fn trim_view_hides_the_guides_and_the_grid() { #[test] fn pixel_grid_shows_in_pixel_preview_from_600_percent() { let mut app = app(); - assert!(pixel_grid(&app).is_none(), "not in Pixel Preview"); + assert!(pixel_grid(&app, None).is_none(), "not in Pixel Preview"); app.ui.view.pixel_preview = true; - assert!(pixel_grid(&app).is_some()); + assert!(pixel_grid(&app, None).is_some()); app.session.execute("prefs.set", &json!({"key": "showPixelGrid", "value": false})).unwrap(); - assert!(pixel_grid(&app).is_none(), "the preference is off"); + assert!(pixel_grid(&app, None).is_none(), "the preference is off"); } diff --git a/crates/ui-egui/src/canvas/marks.rs b/crates/ui-egui/src/canvas/marks.rs index ca21ef7119..abe7c5a6db 100644 --- a/crates/ui-egui/src/canvas/marks.rs +++ b/crates/ui-egui/src/canvas/marks.rs @@ -160,6 +160,13 @@ pub(crate) struct Marks { artboard_marks: Vec, } +/// Drops the hidden-character and spelling memos and the text nodes they hold. +pub(crate) fn release_text_marks(app: &mut VectorcraftApp) { + app.canvas.hidden_chars.marks.clear(); + app.canvas.spelling = SpellingMarks::default(); + app.canvas.text_nodes = TextNodes::default(); +} + /// The marks of one canvas pass over `view`. The memos of [`crate::CanvasCache`] are kept while their /// gate is on and dropped, with the text nodes they hold, when it is off. pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks { @@ -183,9 +190,7 @@ pub(crate) fn marks_of(app: &mut VectorcraftApp, view: &CanvasView) -> Marks { let fades = artboards::fades_outside_artboards(app); let shows_artboards = artboards::shows_artboards(app); let Some(st) = app.session.active() else { - app.canvas.hidden_chars.marks.clear(); - app.canvas.spelling = SpellingMarks::default(); - app.canvas.text_nodes = TextNodes::default(); + release_text_marks(app); return m; }; let key = (st.uid, st.revision); diff --git a/crates/ui-egui/src/canvas/marks/tests.rs b/crates/ui-egui/src/canvas/marks/tests.rs index 2bb6ecda50..29336a8ad8 100644 --- a/crates/ui-egui/src/canvas/marks/tests.rs +++ b/crates/ui-egui/src/canvas/marks/tests.rs @@ -122,6 +122,32 @@ fn hidden_characters_off_and_a_closed_document_release_the_text_nodes() { assert!(app.canvas.text_nodes.list.is_none(), "no list of the closed document's text objects is kept"); } +/// Closing the last document drops the memos' text nodes on the canvas's next frame, whether it +/// shows the Home screen or, with Show The Home Screen When No Documents Are Open off, an empty window. +#[test] +fn a_canvas_frame_without_a_document_releases_the_text_nodes() { + let ctx = crate::testing::ui_context(); + let frame = |app: &mut VectorcraftApp| { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0))), ..Default::default() }; + crate::testing::part_frame(app, &ctx, raw, crate::canvas::show); + }; + for home in [true, false] { + let mut app = app(); + app.session.execute("prefs.set", &json!({"key": "showHomeScreen", "value": home})).unwrap(); + text(&mut app, 20, 60, "one\ttwo qzxv\nthree"); + app.ui.view.hidden_chars = true; + app.ui.view.auto_spell_check = true; + frame(&mut app); + assert!(app.canvas.text_nodes.list.is_some() && !app.canvas.hidden_chars.marks.is_empty(), "home {home}: the canvas keeps the memos"); + app.session.execute("file.close", &json!({})).unwrap(); + assert_eq!(crate::menus::home_showing(&app), home); + frame(&mut app); + assert!(app.canvas.text_nodes.list.is_none(), "home {home}: no list of the closed document's text objects is kept"); + assert!(app.canvas.hidden_chars.marks.is_empty(), "home {home}: no hidden-character marks of the closed document are kept"); + assert!(app.canvas.spelling.lines.is_empty(), "home {home}: no spelling marks of the closed document are kept"); + } +} + /// `paths` small rectangles and three point type objects with hidden characters and words no /// dictionary knows: the first on the first layer, the second in a group on that layer and the /// third on a second layer. Show Hidden Characters and Auto Spell Check are on. Returns the type diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 7a80d814d6..03b8e4da67 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -8,12 +8,36 @@ pub(super) fn c32(rgb: [u8; 3]) -> Color32 { Color32::from_rgb(rgb[0], rgb[1], rgb[2]) } -/// Outline of a node for highlighting (paths, compound children, area type frames, other -/// text/image bounds, symbol instances' bounds measured by their art from `symbols`; a clip -/// group's clipping path only, as [`walk_drawn`] visits it). -pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { +/// What the view hides among a selected object's members, which the selection marks leave out as +/// the canvas does ([`Node::hidden_by_view`]): template layers while View › Hide Template is on, +/// and paths made into guides while the guides are hidden. The default hides nothing. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct ViewHides { + pub(super) templates: bool, + pub(super) guides: bool, +} + +impl ViewHides { + /// What `app`'s view hides. + pub(super) fn of(app: &VectorcraftApp) -> Self { + Self { templates: !app.ui.view.templates, guides: !app.ui.view.guides_shown() } + } + + /// [`Node::drawn_children`] of `n` without the members the view leaves out. Every path of a + /// compound path stays, since the compound path draws all of them, guides or not. + fn children(self, n: &Node) -> impl Iterator> { + let hide_guides = self.guides && !matches!(n.kind, NodeKind::Compound { .. }); + n.drawn_children().filter(move |c| !c.hidden_by_view(self.templates, hide_guides)) + } +} + +/// Outline of a node for highlighting (paths, compound children, area type frames, image bounds, +/// the box as drawn of type in perspective and of symbol instances, whose art `symbols` measures +/// ([`Node::drawn_corners`]); a clip group's clipping path only, as [`walk_drawn`] visits it, +/// without the members `hides` leaves out). +pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes, hides: ViewHides) -> BezPath { let mut bp = BezPath::new(); - walk_drawn(n, &mut |c| match &c.kind { + walk_drawn(n, hides, &mut |c| match &c.kind { NodeKind::Path { path, .. } => bp.extend(path.to_bezpath()), // Area type shows its frame: the type area Direct Selection reshapes; type on a path its // path, which the selection tools' brackets sit on; point type shows its baseline(s). @@ -27,13 +51,20 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp.line_to(t.xf * b); } } - } else if let Some(b) = c.geometric_bounds_with(symbols) { - bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); + } else if let Some(q) = c.drawn_corners(symbols) { + corners(&mut bp, q); } } - NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => { - if let Some(b) = c.geometric_bounds_with(symbols) { - bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); + // An image shows its frame, turned or distorted with it. + NodeKind::Image(_) => { + if let Some(frame) = c.image_frame() { + bp.extend(frame); + } + } + // A symbol instance shows its art's box, turned, skewed or in perspective with it. + NodeKind::SymbolInstance { .. } => { + if let Some(q) = c.drawn_corners(symbols) { + corners(&mut bp, q); } } // A placed document shows its box, turned with it. @@ -56,6 +87,46 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { bp } +/// Whether `n` is a linked image or a placed document, which the selection marks cross. +fn is_linked(n: &Node) -> bool { + match &n.kind { + NodeKind::Image(im) => im.link.is_some(), + NodeKind::PlacedDocument(_) => true, + _ => false, + } +} + +/// The lines that cross each linked image and placed document of `n` that [`walk_drawn`] visits, +/// from corner to corner of its frame or box (#9080), without the members `hides` leaves out. The +/// selection marks draw them; the hover highlight does not. +pub(super) fn linked_crosses(n: &Node, hides: ViewHides) -> BezPath { + let mut bp = BezPath::new(); + walk_drawn(n, hides, &mut |c| match &c.kind { + NodeKind::Image(_) if is_linked(c) => { + if let Some(cross) = c.image_cross() { + bp.extend(cross); + } + } + NodeKind::PlacedDocument(p) => { + let [tl, tr, br, bl] = p.corners(); + bp.move_to(tl); + bp.line_to(br); + bp.move_to(tr); + bp.line_to(bl); + } + _ => {} + }); + bp +} + +/// Adds the closed outline through the four corners `q` to `bp`. +fn corners(bp: &mut BezPath, q: [Point; 4]) { + let [a, b, c, d] = q; + bp.move_to(a); + [b, c, d].into_iter().for_each(|p| bp.line_to(p)); + bp.close_path(); +} + /// The most points ([`overlay_points`]) the selection's outlines and anchors, and the hover /// highlight, are drawn for: an Image Trace of a photo selects hundreds of thousands of paths at /// once, and selecting all of an opened PDF can select as many type objects, images and gradient @@ -63,22 +134,36 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { /// #2460). pub(super) const OVERLAY_MAX_ANCHORS: usize = 100_000; -/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`]; -/// counting stops there). -pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator) -> bool { - fn over(n: &Node, left: &mut usize) -> bool { - match left.checked_sub(overlay_points(n)) { +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline ([`overlay_points`], +/// without the members `hides` leaves out; counting stops there). +pub(super) fn too_many_anchors<'a>(nodes: impl IntoIterator, hides: ViewHides) -> bool { + over_limit(nodes, false, hides) +} + +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points to outline and to cross where they +/// are linked images or placed documents ([`linked_crosses`]), as the selection marks draw them +/// without the members `hides` leaves out. +pub(super) fn too_many_marks<'a>(nodes: impl IntoIterator, hides: ViewHides) -> bool { + over_limit(nodes, true, hides) +} + +/// Whether `nodes` have more than [`OVERLAY_MAX_ANCHORS`] points ([`overlay_points`], with the +/// ends of the crossing lines when `crosses`) in what [`walk_drawn`] visits; counting stops there. +fn over_limit<'a>(nodes: impl IntoIterator, crosses: bool, hides: ViewHides) -> bool { + fn over(n: &Node, left: &mut usize, crosses: bool, hides: ViewHides) -> bool { + let ends = if crosses && is_linked(n) { 4 } else { 0 }; + match left.checked_sub(overlay_points(n) + ends) { Some(l) => *left = l, None => return true, } // A clip group counts only its clipping path, the one child `walk_drawn` visits. if n.clips() { - return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left)); + return n.children().and_then(|children| children.first()).is_some_and(|clip| over(clip, left, crosses, hides)); } - !matches!(n.kind, NodeKind::Envelope { .. }) && n.editing_children().iter().any(|c| over(c, left)) + !matches!(n.kind, NodeKind::Envelope { .. }) && hides.children(n).any(|c| over(c, left, crosses, hides)) } let mut left = OVERLAY_MAX_ANCHORS; - nodes.into_iter().any(|n| over(n, &mut left)) + nodes.into_iter().any(|n| over(n, &mut left, crosses, hides)) } /// The points counted for `n` itself, without its children, toward [`OVERLAY_MAX_ANCHORS`]: a @@ -106,21 +191,22 @@ fn overlay_points(n: &Node) -> usize { } /// [`Node::walk`] over what a selection highlight shows: an envelope's content is left out (the -/// envelope shows its mesh instead), and a clip group or clipping layer shows only its clipping -/// path, its first child, not the art the path clips (#2422). -pub(super) fn walk_drawn<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { +/// envelope shows its mesh instead), a clip group or clipping layer shows only its clipping path, +/// its first child, not the art the path clips (#2422), and hidden members +/// ([`Node::drawn_children`]) and the members `hides` leaves out are left out. +pub(super) fn walk_drawn<'a>(n: &'a Node, hides: ViewHides, f: &mut impl FnMut(&'a Node)) { f(n); if matches!(n.kind, NodeKind::Envelope { .. }) { return; } if n.clips() { if let Some(clip) = n.children().and_then(|children| children.first()) { - walk_drawn(clip, f); + walk_drawn(clip, hides, f); } return; } - for c in n.editing_children().iter() { - walk_drawn(c, f); + for c in hides.children(n) { + walk_drawn(c, hides, f); } } diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 7be8250984..8f9bd6f663 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -9,7 +9,7 @@ use craft::draw::ui::{HandleStyle, PathOptionsSettings}; use craft::ui::canvas::{CanvasSpace, canvas_space, hud}; use craft::ui::canvas_controls::{Marquee, MarqueeLook, Measure, SelectionOutline, SmartGuides, path_runs}; use craft::ui::contract::{Common, Component, Cx, Input, MeasureCx, PaintUi, PartsCx, Role, Show as _}; -use craft::ui::primitives::{DataWidth, Draw, PaintShape, StrokeWidth, TextRun}; +use craft::ui::primitives::{Dashes, DataWidth, Draw, PaintShape, StrokeWidth, TextRun}; use craft::ui::runtime::env::Label; use craft::ui::style::{ComponentStyle, DataColor, Metrics, StyleColor, StyleCx, TypeRole, UiTokens}; use egui::{Color32, CornerRadius, Pos2, Rect as ScreenRect, Response, Vec2}; @@ -191,8 +191,15 @@ fn paint(draw: &Draw<'_>, view: &CanvasView, overlays: &[Overlay], options: &Pat stroke_run(draw, points, closed, *dashed, DataWidth::points(*width), data(*color)); } } - Overlay::Line { a, b, color, dashed } => { - stroke_run(draw, vec![view.to_screen(*a), view.to_screen(*b)], false, *dashed, StrokeWidth::Thin, data(*color)); + Overlay::Line { a, b, color, dashed: true } => { + let pattern = draw.dashes(); + let margin = pattern.dash + pattern.gap + draw.width(StrokeWidth::Thin); + if let Some((run, from)) = visible_run(view, *a, *b, view.rect.expand(margin)) { + draw.dashed(&run, dashes_from(pattern, from), StrokeWidth::Thin, data(*color)); + } + } + Overlay::Line { a, b, color, dashed: false } => { + stroke_run(draw, vec![view.to_screen(*a), view.to_screen(*b)], false, false, StrokeWidth::Thin, data(*color)); } Overlay::GridLine { a, b, color } => { stroke_run(draw, vec![view.to_screen(*a), view.to_screen(*b)], false, false, StrokeWidth::Thin, data_rgba(*color)); @@ -262,6 +269,69 @@ fn stroke_run( } } +/// The part inside `clip` of the screen line that `view` draws from document point `a` to `b`, with how far along the +/// whole line that part starts, in points. The line is clipped in `f64`, so a line millions of points long keeps its +/// part on the canvas. None when no part of it is inside `clip`, or when an end does not map to a finite point. +fn visible_run(view: &CanvasView, a: vectorcraft_geom::Point, b: vectorcraft_geom::Point, clip: ScreenRect) -> Option<([Pos2; 2], f64)> { + let affine = view.affine(); + let (a, b) = (affine * a, affine * b); + if !(a.is_finite() && b.is_finite()) { + return None; + } + let screen = |p: vectorcraft_geom::Point| Pos2::new(p.x as f32, p.y as f32); + // Halved, so ends near the largest `f64` do not overflow. + let half = b.to_vec2() * 0.5 - a.to_vec2() * 0.5; + let length = half.hypot(); + if length == 0.0 { + let c = screen(a); + return clip.contains(c).then_some(([c, c], 0.0)); + } + let u = half / length; + // The run is measured from the point of the line nearest the middle of `clip`, so the clipped ends keep their + // precision when the line's ends are far off. + // That point is found from the line's distance to the middle, taken from the cross product of its ends, so a line + // whose ends are far off and not on one diagonal keeps its place on the canvas. + let c = vectorcraft_geom::Point::new(f64::from(clip.center().x), f64::from(clip.center().y)); + let offset = (half.cross(c.to_vec2()) + 2.0 * exact_cross(a.to_vec2() * 0.5, b.to_vec2() * 0.5)) / length; + let origin = if offset.is_finite() { c - vectorcraft_geom::Vec2::new(-u.y, u.x) * offset } else { a + u * (c - a).dot(u) }; + let (mut s0, mut s1) = ((a - origin).dot(u), (b - origin).dot(u)); + let start = s0; + let axes = [(origin.x, u.x, f64::from(clip.left()), f64::from(clip.right())), (origin.y, u.y, f64::from(clip.top()), f64::from(clip.bottom()))]; + for (at, step, lo, hi) in axes { + if step == 0.0 { + if at < lo || at > hi { + return None; + } + } else { + let (enter, leave) = ((lo - at) / step, (hi - at) / step); + s0 = s0.max(enter.min(leave)); + s1 = s1.min(enter.max(leave)); + } + } + if s0 > s1 { + return None; + } + Some(([screen(origin + u * s0), screen(origin + u * s1)], s0 - start)) +} + +/// `p.x * q.y - p.y * q.x`, with the rounding error of the second product added back (Kahan's method), so two far-off +/// points whose products nearly cancel keep the small difference between them. +fn exact_cross(p: vectorcraft_geom::Vec2, q: vectorcraft_geom::Vec2) -> f64 { + let w = p.y * q.x; + let error = (-p.y).mul_add(q.x, w); + p.x.mul_add(q.y, -w) + error +} + +/// `pattern` for a run that starts `from` points along its line, so its dashes fall where the whole line has them. +fn dashes_from(pattern: Dashes, from: f64) -> Dashes { + let period = f64::from(pattern.dash) + f64::from(pattern.gap); + if !(period.is_finite() && period > 0.0 && from.is_finite()) { + return pattern; + } + let phase = (f64::from(pattern.phase) - from).rem_euclid(period); + pattern.phase(phase as f32) +} + /// An anchor or curve point: filled in `color` when selected, else a white body with a `color` edge. fn marker(draw: &Draw<'_>, shape: &PaintShape, color: DataColor, filled: bool) { draw.data_fill(shape, if filled { color } else { DataColor::new(Color32::WHITE) }); diff --git a/crates/ui-egui/src/canvas/overlays/tests.rs b/crates/ui-egui/src/canvas/overlays/tests.rs index c154dc8f77..6c7d8e21d1 100644 --- a/crates/ui-egui/src/canvas/overlays/tests.rs +++ b/crates/ui-egui/src/canvas/overlays/tests.rs @@ -61,3 +61,127 @@ fn a_tip_disc_is_scaled_by_the_zoom_and_never_empty() { fn empty_tip() -> Overlay { Overlay::HoverText { center: Point::new(f64::NAN, 0.0), radius: 5.0, text: "Tip" } } + +/// The dashes of `points` in `pattern`, as `Draw::dashed` lays them out. +fn dashes_along(points: &[Pos2], pattern: Dashes) -> Vec { + let s = egui::Stroke::new(1.0, Color32::WHITE); + egui::Shape::dashed_line_with_offset(points, s, &[pattern.dash], &[pattern.gap], pattern.phase) +} + +/// The stretches of x that horizontal dashes cover inside `lo..hi`, in order. +fn spans(shapes: &[egui::Shape], lo: f32, hi: f32) -> Vec<(f32, f32)> { + let mut out: Vec<(f32, f32)> = shapes + .iter() + .map(|s| match s { + egui::Shape::LineSegment { points: [a, b], .. } => (a.x.min(b.x).max(lo), a.x.max(b.x).min(hi)), + other => panic!("{other:?}"), + }) + .filter(|(a, b)| b > a) + .collect(); + out.sort_by(|a, b| a.0.total_cmp(&b.0)); + out +} + +/// A dashed line much longer than the canvas is dashed only where it shows, with the dashes on the canvas where the +/// whole line dashed in one go has them, for any phase of the pattern. +#[test] +fn a_long_dashed_line_is_dashed_only_on_the_canvas() { + let view = view(); + let clip = view.rect.expand(8.0); + let (lo, hi) = (view.rect.left(), view.rect.right()); + // From 1,000 points left of the canvas to 1,740 points right of it. + let (a, b) = (Point::new(-1000.0, 100.0), Point::new(1900.0, 100.0)); + for phase in [0.0, 2.5, 6.9] { + let pattern = Dashes::new(4.0, 3.0).phase(phase); + let whole = dashes_along(&[view.to_screen(a), view.to_screen(b)], pattern); + let (run, from) = visible_run(&view, a, b, clip).unwrap(); + let drawn = dashes_along(&run, dashes_from(pattern, from)); + let (want, got) = (spans(&whole, lo, hi), spans(&drawn, lo, hi)); + assert_eq!(want.len(), got.len(), "{phase}: {want:?} {got:?}"); + assert!(want.iter().zip(&got).all(|(w, g)| (w.0 - g.0).abs() < 1e-2 && (w.1 - g.1).abs() < 1e-2), "{phase}: {want:?} {got:?}"); + assert!(drawn.len() <= 30, "only the dashes on the canvas: {}", drawn.len()); + } +} + +/// Ends 10,000,000,000 points away on both sides still keep the part on the canvas, dashed in whole dashes. +#[test] +fn a_dashed_line_with_far_ends_keeps_its_part_on_the_canvas() { + let view = view(); + let pattern = Dashes::new(4.0, 3.0); + let (run, from) = visible_run(&view, Point::new(-1e10, 100.0), Point::new(1e10, 100.0), view.rect.expand(8.0)).unwrap(); + assert!(from > 1e9, "{from}"); + let drawn = spans(&dashes_along(&run, dashes_from(pattern, from)), view.rect.left(), view.rect.right()); + assert!((20..=26).contains(&drawn.len()), "{drawn:?}"); + assert!(drawn.iter().all(|(a, b)| b - a <= 4.0 + 1e-3), "{drawn:?}"); + // Ends so far off that the clipped ends round to one point along the line still keep the canvas's width. + let clip = view.rect.expand(8.0); + let (run, _) = visible_run(&view, Point::new(-1e20, 100.0), Point::new(1e20, 100.0), clip).unwrap(); + assert_eq!(run, [Pos2::new(clip.left(), 100.0), Pos2::new(clip.right(), 100.0)]); + // A slanted line keeps its slant there too. + let (run, _) = visible_run(&view, Point::new(-1e20, -1e20), Point::new(1e20, 1e20), clip).unwrap(); + assert!(run.iter().all(|p| (p.x - p.y).abs() < 1e-3 && clip.expand(1e-2).contains(*p)), "{run:?}"); + assert!(run[0].distance(run[1]) > 200.0, "{run:?}"); + // Far-off ends off one diagonal keep the line's offset: these ends, as `f64` holds them, give a line that + // crosses x = 0 at y = 72.35. + let (run, _) = visible_run(&view, Point::new(-1e18, -1e18 + 100.0), Point::new(1.3e18, 1.3e18 + 100.0), clip).unwrap(); + assert!(run.iter().all(|p| (p.y - p.x - 72.35).abs() < 1e-2 && clip.expand(1e-2).contains(*p)), "{run:?}"); +} + +/// The line segments in `shapes`, with nested shape lists opened. +fn segments(shapes: &[egui::Shape]) -> Vec<[Pos2; 2]> { + let mut out = Vec::new(); + for s in shapes { + match s { + egui::Shape::LineSegment { points, .. } => out.push(*points), + egui::Shape::Vec(inner) => out.extend(segments(inner)), + other => panic!("{other:?}"), + } + } + out +} + +/// A long dashed line overlay painted through `paint` gives only the dashes near the canvas, each on the line. +#[test] +fn a_long_dashed_line_overlay_paints_only_its_dashes_on_the_canvas() { + use craft::i18n::Direction; + use craft::theme::{Contrast, Mode}; + use craft::ui::style::Ink; + use craft::ui::testing::Frames; + use craft::ui::testing::style::{paint_frame, tokens}; + + let view = view(); + let tokens = tokens(Mode::Light, Contrast::Standard); + let style = ToolMarksStyle { + metrics: Metrics::new(), + dark: StyleColor(Color32::BLACK), + ink: StyleColor(Color32::WHITE), + accent: StyleColor(Color32::BLUE), + pad: Vec2::ZERO, + radius: CornerRadius::ZERO, + handle: 3.0, + }; + let line = Overlay::Line { a: Point::new(-1000.0, 100.0), b: Point::new(1900.0, 100.0), color: [255, 0, 255], dashed: true }; + let mut frames = Frames::new(); + let (shapes, _) = paint_frame(&mut frames, &tokens, Direction::Ltr, Ink::OnPanel, |draw| { + paint(draw, &view, std::slice::from_ref(&line), &PathOptionsSettings::default(), &style); + }); + let drawn = segments(&shapes); + assert!(!drawn.is_empty(), "the part on the canvas is drawn"); + assert!(drawn.len() <= 40, "only the dashes near the canvas: {}", drawn.len()); + let near = view.rect.expand(32.0); + assert!(drawn.iter().flatten().all(|p| near.contains(*p) && (p.y - 100.0).abs() < 1e-3), "{drawn:?}"); +} + +/// A turned view clips the line to the canvas too, and a line off the canvas or with an end that is not finite draws +/// nothing. +#[test] +fn a_dashed_line_off_the_canvas_draws_nothing() { + let mut view = view(); + view.rotation = 0.3; + let clip = view.rect.expand(8.0); + let (run, _) = visible_run(&view, Point::new(-1e6, 100.0), Point::new(1e6, 100.0), clip).unwrap(); + assert!(run.iter().all(|p| clip.expand(1e-2).contains(*p)), "{run:?}"); + assert!(visible_run(&view, Point::new(-1e6, 5000.0), Point::new(1e6, 5000.0), clip).is_none()); + assert!(visible_run(&view, Point::new(0.0, 100.0), Point::new(f64::INFINITY, 100.0), clip).is_none()); + assert!(visible_run(&view, Point::new(f64::NAN, 100.0), Point::new(10.0, 100.0), clip).is_none()); +} diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index a7e971a747..9cf1965cfc 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -415,6 +415,36 @@ fn art_area(app: &VectorcraftApp, w: Win, cell: egui::Rect) -> egui::Rect { crate::doc_windows::view(app, w).map(|v| v.rect).filter(|r| r.is_positive()).unwrap_or(cell) } +/// Whether window `w`'s view is still where a pane fit left it, in a pane of `size`. +pub(crate) fn follows_fit(app: &VectorcraftApp, w: Win, size: Option) -> bool { + let fit = slot(app, w).and_then(|s| app.canvas.panes.fits.get(&s).copied()); + crate::doc_windows::view(app, w).is_some_and(|v| v.fitted && fit.is_some_and(|(s, z, c)| Some(s) == size && z == v.zoom && c == v.center)) +} + +/// Records window `w`'s view as fitted to a pane of `size` at its zoom and center now, as +/// [`note_fits`] does after a fit. +#[cfg(test)] +pub(crate) fn note_fit(app: &mut VectorcraftApp, w: Win, size: egui::Vec2) { + if let (Some(s), Some(v)) = (slot(app, w), crate::doc_windows::view(app, w).copied()) { + app.canvas.panes.fits.insert(s, (size, v.zoom, v.center)); + } +} + +/// The pane fit recorded for window `w` ([`note_fits`]). +#[cfg(test)] +pub(crate) fn fit_of(app: &VectorcraftApp, w: Win) -> Option<(egui::Vec2, f64, Point)> { + slot(app, w).and_then(|s| app.canvas.panes.fits.get(&s).copied()) +} + +/// Window `w`'s view, rescaled while it still fitted its pane ([`follows_fit`]), keeps fitting the +/// pane at its new zoom and center. +pub(crate) fn refollow_fit(app: &mut VectorcraftApp, w: Win) { + let (Some(s), Some(v)) = (slot(app, w), crate::doc_windows::view(app, w).copied()) else { return }; + if let Some(fit) = app.canvas.panes.fits.get_mut(&s) { + *fit = (fit.0, v.zoom, v.center); + } +} + /// Unfit each window whose view is still where a pane fit left it when its view's area (`areas`, /// by window) has changed size, as when the window or a panel is resized: it fits its pane again. /// A view zoomed or scrolled since keeps its place. → which of `areas`' views are unfitted now. @@ -454,16 +484,24 @@ fn fit_pane(v: &mut View, doc: &vectorcraft_doc::Document, area: egui::Rect, (ui craft::behavior::canvas::zoom::fit_rect(&mut view, target, target.size(), pixels_per_point, Vec2::new(FIT_MARGIN, FIT_MARGIN), scheme); v.set_canvas(&view, ui_zoom); v.fitted = true; + v.fit_zoom = Some(v.zoom); } } -/// Fit window `w`'s view to its pane when it is unfitted, with the zoom stops of `ui`'s scope. +/// Fit window `w`'s view to its pane when it is unfitted, with the zoom stops of the display that +/// shows the pane (Display Print Size at 100% Zoom). fn fit_window(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) { + if !crate::doc_windows::view(app, w).is_some_and(|v| !v.fitted) { + return; + } let area = art_area(app, w, cell); let Some(doc) = app.session.documents().get(w.0).map(|st| st.doc.clone()) else { return }; - let scheme = Env::of(ui).get::(); - let scaling = (app.ui_scaling(), ui.ctx().pixels_per_point()); - if let Some(v) = crate::doc_windows::view_mut(app, w).filter(|v| !v.fitted) { + // The fit is made for the display the pane is on. + app.settle_window_ppi(w, false); + let ctx = ui.ctx(); + let scheme = crate::app::view::zoom_scheme(app.print_ppi_of(Some(w)), ctx.pixels_per_point() / ctx.zoom_factor()); + let scaling = (app.ui_scaling(), ctx.pixels_per_point()); + if let Some(v) = crate::doc_windows::view_mut(app, w) { fit_pane(v, &doc, area, scaling, &scheme); } } diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 0ed7de10cd..4ea015bac6 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -798,6 +798,69 @@ fn other_panes_draw_their_guides_and_selected_objects() { assert!(!crate::canvas::selection::outlines(&app, st).is_empty(), "the selected rectangle is outlined in its pane"); } +/// Another pane crosses a selected linked image from corner to corner, as the current pane does, and outlines a +/// selected embedded image alone (#9080). +#[test] +fn other_panes_cross_a_selected_linked_image() { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + let png = vectorcraft_testkit::temp_dir("panes-linked-image").join("red.png"); + let image = Image::from_raw(40, 40, ChannelLayout::Rgba, SampleType::U8, [200u8, 40, 40, 255].repeat(40 * 40)).unwrap(); + std::fs::write(&png, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + let mut app = app_with(2); + app.run("document.activate", json!({"index": 0})).unwrap(); + let mut place = |link: bool, at: [f64; 2]| { + app.session.execute("file.place", &json!({"path": png, "link": link, "at": at})).unwrap()["ids"][0].as_u64().unwrap() + }; + let (linked, embedded) = (place(true, [100.0, 100.0]), place(false, [250.0, 100.0])); + app.run("window.arrange.tile", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + // How many paths the first document's pane outlines with `id` selected there. + let mut paths = |id: u64| { + app.run("document.activate", json!({"index": 0})).unwrap(); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let st = &app.session.documents()[0]; + crate::canvas::selection::outlines(&app, st).iter().map(|o| o.paths.len()).sum::() + }; + let (linked, embedded) = (paths(linked), paths(embedded)); + assert_eq!((linked, embedded), (2, 1), "the outline of a linked image and its crossing lines; an embedded image's outline alone"); +} + +/// Another pane outlines a selected group's visible members only: hiding a member draws the same outlines as deleting +/// it. +#[test] +fn other_panes_leave_out_a_selected_groups_hidden_members() { + let mut app = app_with(2); + app.run("document.activate", json!({"index": 0})).unwrap(); + let id = |made: serde_json::Value| made["id"].as_u64().unwrap(); + let shown = id(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 80})).unwrap()); + let hidden = id(app.run("shape.ellipse", json!({"x": 200, "y": 100, "width": 90, "height": 60})).unwrap()); + app.run("select.set", json!({"ids": [shown, hidden]})).unwrap(); + let group = id(app.run("object.group", json!({})).unwrap()); + app.run("window.arrange.tile", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + // The paths the first document's pane outlines with the group selected there, after the commands `edit` there. + let outlines = |app: &mut VectorcraftApp, edit: &[(&str, serde_json::Value)]| { + app.run("document.activate", json!({"index": 0})).unwrap(); + for (command, params) in edit { + app.run(command, params.clone()).unwrap(); + } + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(app, &ctx, vec![]); + frame(app, &ctx, vec![]); + let st = &app.session.documents()[0]; + crate::canvas::selection::outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect::>() + }; + let both = outlines(&mut app, &[]); + let without = outlines(&mut app, &[("select.set", json!({"ids": [hidden]})), ("edit.clear", json!({}))]); + let with_hidden = outlines(&mut app, &[("edit.undo", json!({})), ("select.set", json!({"ids": [hidden]})), ("object.hide", json!({}))]); + assert_ne!(both, without, "the outlines show both members"); + assert_eq!(with_hidden, without, "a hidden member is not outlined"); +} + #[test] fn opening_a_document_while_tiled_fits_each_document_to_its_new_pane() { let mut app = app_with(2); diff --git a/crates/ui-egui/src/canvas/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 711fe29187..780dd5f7a8 100644 --- a/crates/ui-egui/src/canvas/raster.rs +++ b/crates/ui-egui/src/canvas/raster.rs @@ -48,13 +48,19 @@ pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::Colo /// The pixels of the `w`×`h` frame through `view` to render again for `doc`, when only the document /// changed, or placed documents' bitmaps were made, since the frame shown (its key `key` but for -/// the revision and [`CacheKey::placed`], and its render options `opts`), which this thread -/// rendered, and no frame is on its way from the worker: those it changed in, and those the -/// objects showing those bitmaps' files cover (`Some(None)`: none), grown to whole eighths of the -/// frame, as long as they are at most half of it. None: render the whole frame. Frames the worker -/// renders stay whole: its renderer keeps the rasters of the art's effects, this thread's doesn't. -/// What changed is measured by this thread's renderer, which drew the frame shown: it keeps what -/// it measures (a 3D effect's art) to draw the part again. +/// the revision and [`CacheKey::placed`], and its render options `opts`), and no frame of another +/// document, or of this revision or a later one, is on its way from the worker: those it changed +/// in, and those the objects showing those bitmaps' files cover (`Some(None)`: none), grown to +/// whole eighths of the frame, as long as they are at most half of it. None: render the whole +/// frame. A frame the worker rendered is drawn again here too, so an edit (a Pen drag's curve) +/// shows in the frame it is made in, when the part's share of the frame's last whole render time +/// is at most 8 ms, and except when that frame drew raster effects from rasters made before their +/// objects moved ([`crate::CanvasCache::moved`]), holds pixels copied from the worker's last frame +/// ([`crate::CanvasCache::reused`]), drew art in a way that depends on its size, or a part drawn +/// again here since it arrived would have differed from it ([`crate::CanvasCache::worker_parts`]): +/// the worker's renderer keeps the rasters of the art's effects, and this thread's doesn't. What +/// changed is measured by this thread's renderer: it keeps what it measures (a 3D effect's art) to +/// draw the part again. pub(super) fn changed_pixels( app: &mut VectorcraftApp, key: &CacheKey, @@ -71,19 +77,25 @@ pub(super) fn changed_pixels( } let shown_key = app.canvas.key.as_ref()?; let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, ..key.clone() }; - if !same_view || app.canvas.texture.is_none() || app.canvas.from_worker || app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()) { + let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.worker_parts || app.canvas.reused.is_some()); + // A frame on its way of an older revision is not shown when it arrives ([`show_worker_frame`]). + let on_its_way = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|p| p.doc != key.doc || p.revision >= key.revision); + if !same_view || app.canvas.texture.is_none() || worker_kept || on_its_way { return None; } // The placed documents' files whose bitmaps were made since the frame shown. let entry = app.session.documents().iter().find(|d| d.uid as usize == key.doc).and_then(|d| app.canvas.placed_keys.get(&d.uid)); let placed = placed_changes(entry, shown_key.placed, key.placed, doc, vectorcraft_render::placed_document::made_between)?; + // Over a frame the worker rendered, the part's share of the whole frame's time is at most 8 ms. + let budget = if app.canvas.from_worker { 8.0 / app.canvas.last_ms } else { 0.5 }; match app.canvas.renderer.changed(shown, doc, opts).and(placed) { vectorcraft_render::Changed::Nothing => Some(None), vectorcraft_render::Changed::Area(area) => match vectorcraft_render::view_pixels(area, view, w, h) { None => Some(None), Some([x0, y0, x1, y1]) => { let ((x0, x1), (y0, y1)) = (in_steps(x0, x1, w), in_steps(y0, y1, h)); - (u64::from(x1 - x0) * u64::from(y1 - y0) * 2 <= u64::from(w) * u64::from(h)).then_some(Some([x0, y0, x1, y1])) + let share = (f64::from(x1 - x0) * f64::from(y1 - y0)) / (f64::from(w) * f64::from(h)); + (share <= budget.min(0.5)).then_some(Some([x0, y0, x1, y1])) } }, vectorcraft_render::Changed::Everything => None, @@ -122,6 +134,9 @@ pub(crate) struct WorkerFrame { pub(crate) moved: usize, /// The frame holds pixels copied from the last frame. pub(crate) reused: bool, + /// The frame drew art in a way that depends on its size + /// ([`vectorcraft_render::FrameStats::view_sized`]). + pub(crate) view_sized: bool, } /// Nothing but the position of the view differs between the frame `kept` and the job `job`, in @@ -239,6 +254,8 @@ pub(crate) fn render_job(r: &mut vectorcraft_render::Renderer, kept: &mut Option let moved = r.stats.moved; (img, moved) }); + // A copied frame's parts draw nothing that depends on the frame's size ([`composed_frame`]). + let view_sized = !reused && r.stats.view_sized > 0; let keeps = job.may_keep && moved == 0 && r.stats.view_sized == 0 && img.pixels.len() <= MAX_KEPT_BYTES && (img.width, img.height) == (job.w, job.h); *kept = @@ -246,7 +263,7 @@ pub(crate) fn render_job(r: &mut vectorcraft_render::Renderer, kept: &mut Option // The kept frame stays sRGB, so the next frame's copied pixels are converted only once. let width = img.width; crate::display_profile::convert_over(job.display.as_deref(), &mut img.pixels, width, job.view, job.key.over()); - WorkerFrame { img, moved, reused } + WorkerFrame { img, moved, reused, view_sized } } /// Upload the art's raster directly into the canvas texture without reallocating or copying pixels; @@ -580,6 +597,7 @@ fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate: app.canvas.reused = done.reused.then(|| frame::clock(ctx)); app.canvas.moved = done.moved > 0; app.canvas.from_worker = true; + app.canvas.worker_parts = done.view_sized; } /// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas. @@ -667,7 +685,13 @@ pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::f /// Draw `region` of `frame` again, into the texture of the frame shown, which then shows `frame`'s /// key: only the document changed since the frame shown, in that part of it /// ([`changed_pixels`]). `None`: nothing in view changed. `last_ms` stays the whole frame's. -fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) { +/// +/// Over a frame the worker rendered, a part that drew raster effects from rasters made before +/// their objects moved or at a drag's lower resolution ([`vectorcraft_render::FrameStats::moved`]), +/// or art in a way that depends on the frame's size ([`vectorcraft_render::FrameStats::view_sized`]), +/// would not match the frame around it: it is not drawn, false is returned, and the edits after it +/// render on the worker until the worker's next frame is shown ([`crate::CanvasCache::worker_parts`]). +fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) -> bool { let Frame { key, doc, effects, view, opts, pixel, .. } = frame; let t0 = monotonic_ms(); if region.is_none() { @@ -679,6 +703,10 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] let renderer = &mut app.canvas.renderer; let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * *view; let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, opts)); + if app.canvas.from_worker && (renderer.stats.moved > 0 || renderer.stats.view_sized > 0) { + app.canvas.worker_parts = true; + return false; + } let width = part.width; crate::display_profile::convert_over(display.as_deref(), &mut part.pixels, width, part_view, key.over()); let color = color_image(&part); @@ -689,6 +717,7 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4] app.canvas.key = Some((*key).clone()); app.canvas.shown = Some(((*doc).clone(), opts.clone())); app.perf.render_ms = monotonic_ms() - t0; + true } /// With `waits_for_still` set (the web build) and the last render slow, an edit while the view @@ -736,7 +765,8 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { // Frames that would be slow on this thread (the last one took over 8 ms) go // to the worker. An interaction's frames stay on the worker once it drew the frame shown: // its renderer keeps the rasters of the art's effects that make those frames fast, and this - // thread's renderer has none, so a frame fast on the worker would be slow here. + // thread's renderer has none, so a frame fast on the worker would be slow here. An edit in a + // part of the frame shown is drawn again here, unless that part would differ ([`draw_changed`]). let same_doc = app.canvas.key.as_ref().is_some_and(|k| k.doc == key.doc); let settling = app.canvas.moved && !key.interacting; let staying = key.interacting && app.canvas.from_worker; @@ -751,11 +781,14 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { let may_copy = app.canvas.key.as_ref() != Some(key); let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); let mut landed = None; - match (&mut app.canvas.worker, heavy, changed) { - // Only the document changed since the frame shown, in a part of it: that part is - // rendered again, here, into the texture. `last_ms` stays the whole frame's. - (_, _, Some(region)) => draw_changed(app, &Frame { key, doc, effects, size: (w, h), view, opts, pixel }, region), - (Some(worker), true, None) => { + // Only the document changed since the frame shown, in a part of it: that part is rendered + // again, here, into the texture. `last_ms` stays the whole frame's. + let part = Frame { key, doc, effects, size: (w, h), view, opts, pixel }; + let drawn = changed.is_some_and(|region| draw_changed(app, &part, region)); + let Frame { opts, .. } = part; + match (&mut app.canvas.worker, heavy, drawn) { + (_, _, true) => {} + (Some(worker), true, false) => { // The worker draws the frame: what this thread's renderer made to measure the edit // isn't drawn here. app.canvas.renderer.let_go_of_measured(); @@ -816,7 +849,8 @@ pub(super) fn backdrop( let paper = paper_color(setup); let b = if shows_artboards(app) { crate::display_profile::Backdrop { - everywhere: None, + // In Overprint Preview the canvas around the artboards is white paper. + everywhere: vectorcraft_render::proof::overprint_preview_on().then_some([255; 3]), artboards: st.doc.artboards.iter().map(|ab| (ab.rect, rgb(artboard_paper(ab, paper)))).collect(), grid: shows_transparency_grid(st).then(|| (setup.grid_colors.map(|c| rgb(crate::panels::c32(&c))), setup.grid_size.cell())), } diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index 96be3fcc89..c8e0dd5212 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -24,7 +24,7 @@ use vectorcraft_geom::{AnchorKind, BezPath, PathData, PathEl, Point}; use vectorcraft_tools::Mods; use super::cursor::ViewKey; -use super::outline::{c32, node_outline, selection_hit_at, too_many_anchors, walk_drawn}; +use super::outline::{ViewHides, c32, linked_crosses, node_outline, selection_hit_at, too_many_anchors, too_many_marks, walk_drawn}; // PLAN: `BodyKind`, `Win` and `ViewKey::from(CanvasView)` are canvas-w10's (cv.S1, S2, S5); their paths here follow the contract. use super::{BodyKind, VectorcraftApp, Win}; // PLAN: `anchors` takes `tool_points` because the Curvature tool's own points come from `session.overlays`, which only `show` may call (`&mut app`). @@ -147,9 +147,9 @@ fn hidden(app: &VectorcraftApp) -> bool { crate::dialogs::halftone::previewing(app) } -/// Whether the selection has too many points to outline: its bounds stand for it. -fn too_big(st: &DocState) -> bool { - too_many_anchors(st.selection.objects.iter().filter_map(|id| st.doc.node(*id))) +/// Whether the selection has too many points to outline and cross in `app`'s view: its bounds stand for it. +fn too_big(app: &VectorcraftApp, st: &DocState) -> bool { + too_many_marks(st.selection.objects.iter().filter_map(|id| st.doc.node(*id)), ViewHides::of(app)) } /// The rectangle of `bounds` as a path. @@ -166,17 +166,17 @@ fn group(out: &mut Vec, color: Color32) -> &mut Outlined { &mut out[at] } -/// The outlines of the selection, one [`Outlined`] per layer colour: each selected object's outline (the bounds of -/// all of them when they have too many points), the spine of each selected blend, and the key object's outline (its +/// The outlines of the selection, one [`Outlined`] per layer colour: each selected object's outline and the lines +/// across its linked images and placed documents (the bounds of all of them when they have too many points), the spine of each selected blend, and the key object's outline (its /// bounds when it has too many points). Nothing during Halftone Preview. pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { let mut out: Vec = vec![]; if hidden(app) { return out; } - let (sel, symbols) = (&st.selection, st.doc.symbol_boxes()); + let (sel, symbols, hides) = (&st.selection, st.doc.symbol_boxes(), ViewHides::of(app)); let color_of = |id: NodeId| c32(st.doc.layer_color(id)); - if too_big(st) { + if too_big(app, st) { // The cache is warmed by `show`; a test or a miss measures again. let bounds = match app.canvas.selection_bounds { Some((key, bounds)) if key == (st.uid, st.revision) => bounds, @@ -188,9 +188,11 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { } else { for id in &sel.objects { let Some(node) = st.doc.node(*id) else { continue }; - let path = node_outline(node, &symbols); - if !path.elements().is_empty() { - group(&mut out, color_of(*id)).paths.push(path); + // Linked images and placed documents are also crossed from corner to corner. + for path in [node_outline(node, &symbols, hides), linked_crosses(node, hides)] { + if !path.elements().is_empty() { + group(&mut out, color_of(*id)).paths.push(path); + } } } for (blend, spine) in blend_spines(st) { @@ -198,7 +200,11 @@ pub(super) fn outlines(app: &VectorcraftApp, st: &DocState) -> Vec { } } if let Some((key, node)) = sel.key.and_then(|key| Some((key, st.doc.node(key)?))) { - let path = if too_many_anchors([node]) { node.geometric_bounds_with(&symbols).map(bounds_path) } else { Some(node_outline(node, &symbols)) }; + let path = if too_many_anchors([node], hides) { + node.geometric_bounds_with(&symbols).map(bounds_path) + } else { + Some(node_outline(node, &symbols, hides)) + }; if let Some(path) = path { group(&mut out, color_of(key)).key = Some(path); } @@ -266,10 +272,10 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin segment_mark: SegmentMark::Line, options: path_options(prefs), }; - if hidden(app) || too_big(st) || (curvature && tool_points) { + if hidden(app) || too_big(app, st) || (curvature && tool_points) { return out; } - let sel = &st.selection; + let (sel, hides) = (&st.selection, ViewHides::of(app)); // The selected anchors by path, and the selected segment with its path. let mut chosen: Vec<(u64, Vec)> = vec![]; let mut segment: Option<(u64, KnotRef)> = None; @@ -277,7 +283,7 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin let Some(node) = st.doc.node(*id) else { continue }; let partial = sel.partial(*id); let color = c32(st.doc.layer_color(*id)); - walk_drawn(node, &mut |c| { + walk_drawn(node, hides, &mut |c| { let envelope = vectorcraft_doc::live::envelope_overlay(c).and_then(|(_, grid)| grid); let grid = match &c.kind { NodeKind::Mesh(m) => Some(m), @@ -369,13 +375,14 @@ pub(super) fn hover(app: &VectorcraftApp, st: &DocState, tool: &str, at: Point, if kept { return None; } - outline_of(st, id) + outline_of(st, id, ViewHides::of(app)) } -/// The hover outline of `id` in its layer colour, unless it has too many points. -fn outline_of(st: &DocState, id: NodeId) -> Option { - let node = st.doc.node(id).filter(|n| !too_many_anchors([*n]))?; - Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes()), color: c32(st.doc.layer_color(id)) }) +/// The hover outline of `id` in its layer colour, without the members `hides` leaves out, unless it has too many +/// points. +fn outline_of(st: &DocState, id: NodeId, hides: ViewHides) -> Option { + let node = st.doc.node(id).filter(|n| !too_many_anchors([*n], hides))?; + Some(Hovered { path: node_outline(node, &st.doc.symbol_boxes(), hides), color: c32(st.doc.layer_color(id)) }) } /// The hover outline the canvas shows at document point `at` with the keys `held`: none while Space lends the view @@ -405,7 +412,7 @@ pub(super) fn eyedropper_hover(app: &mut VectorcraftApp, at: Point, mods: Mods, } let info = app.view_info(); let id = eyedropper_hover_object(app, at, mods, info)?; - outline_of(app.session.active()?, id) + outline_of(app.session.active()?, id, ViewHides::of(app)) } /// What the Eyedropper's hover object depends on: the point, the keys held, the document as it is, the selection and @@ -495,7 +502,7 @@ fn eyedropper_hover_object(app: &mut VectorcraftApp, at: Point, mods: Mods, view /// The dots of the selection: point type's origin, the centre of each object that shows it, and the key anchor. pub(super) fn dots(app: &VectorcraftApp, st: &DocState) -> Dots { let mut out = Dots { grow: grow(&app.session.prefs), ..Dots::default() }; - if hidden(app) || too_big(st) { + if hidden(app) || too_big(app, st) { return out; } let symbols = st.doc.symbol_boxes(); diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index 4f5e469a63..a2c32f5d53 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -243,7 +243,7 @@ fn the_key_object_has_its_own_outline() { let ids = app.session.active().unwrap().selection.objects.clone(); app.run("select.key", json!({"id": curve.0})).unwrap(); let st = app.session.active().unwrap(); - let want = node_outline(st.doc.node(curve).unwrap(), &st.doc.symbol_boxes()); + let want = node_outline(st.doc.node(curve).unwrap(), &st.doc.symbol_boxes(), ViewHides::default()); let color = c32(st.doc.layer_color(curve)); let out = outlines(&app, st); let key = out.iter().find(|o| o.color == color).and_then(|o| o.key.as_ref()).unwrap(); @@ -252,6 +252,298 @@ fn the_key_object_has_its_own_outline() { assert_eq!(out.iter().map(|o| o.paths.len()).sum::(), ids.len(), "the selection's own outlines stay"); } +/// A file with a 40 × 40 px red PNG in a new temporary folder named `name`. +fn red_png(name: &str) -> std::path::PathBuf { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType}; + let png = vectorcraft_testkit::temp_dir(name).join("red.png"); + let image = Image::from_raw(40, 40, ChannelLayout::Rgba, SampleType::U8, [200u8, 40, 40, 255].repeat(40 * 40)).unwrap(); + std::fs::write(&png, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + png +} + +/// The two lines from corner to corner of `[tl, tr, br, bl]`. +fn cross_of([tl, tr, br, bl]: [Point; 4]) -> Vec { + vec![PathEl::MoveTo(tl), PathEl::LineTo(br), PathEl::MoveTo(tr), PathEl::LineTo(bl)] +} + +/// The outline of `[tl, tr, br, bl]`: its corners joined by straight lines. +fn frame_of([tl, tr, br, bl]: [Point; 4]) -> Vec { + vec![PathEl::MoveTo(tl), PathEl::LineTo(tr), PathEl::LineTo(br), PathEl::LineTo(bl), PathEl::ClosePath] +} + +/// A selected linked image and a selected placed document are crossed from corner to corner, on a turned or +/// distorted image along its frame; a selected embedded image shows its outline alone, along its frame when turned or +/// distorted. The key object's outline and the hover outline are not crossed (#9080). +#[test] +fn a_selected_linked_image_is_crossed_and_an_embedded_one_is_not() { + let png = red_png("selection-linked"); + let placed = png.with_file_name("art.vectorcraft"); + std::fs::write(&placed, vectorcraft_format::save_file(&vectorcraft_doc::Document::new(60.0, 40.0))).unwrap(); + let mut app = blank(); + let place = |app: &mut VectorcraftApp, path: &std::path::Path, link: bool, at: [f64; 2]| { + NodeId(app.run("file.place", json!({"path": path, "link": link, "at": at})).unwrap()["ids"][0].as_u64().unwrap()) + }; + let linked = place(&mut app, &png, true, [100.0, 120.0]); + let embedded = place(&mut app, &png, false, [300.0, 120.0]); + let document = place(&mut app, &placed, true, [200.0, 230.0]); + let corners = |app: &VectorcraftApp, id: NodeId| { + let n = app.session.active().unwrap().doc.node(id).unwrap(); + match &n.kind { + NodeKind::PlacedDocument(p) => p.corners(), + _ => n.image_corners().unwrap(), + } + }; + // Whether the selection's outlines hold a path made of `els`. + let drawn = |app: &VectorcraftApp, els: &[PathEl]| { + outlines(app, app.session.active().unwrap()).iter().any(|o| o.paths.iter().any(|p| p.elements() == els)) + }; + // Whether `id` is crossed, and whether it is outlined along its frame. + let marked = |app: &VectorcraftApp, id: NodeId| (drawn(app, &cross_of(corners(app, id))), drawn(app, &frame_of(corners(app, id)))); + app.run("select.all", json!({})).unwrap(); + assert_eq!(marked(&app, linked), (true, true), "a linked image"); + assert!(drawn(&app, &cross_of(corners(&app, document))), "a placed document"); + assert_eq!(marked(&app, embedded), (false, true), "an embedded image"); + assert_eq!(outlines(&app, app.session.active().unwrap()).iter().map(|o| o.paths.len()).sum::(), 5, "three outlines and two crosses"); + app.run("select.set", json!({"ids": [linked.0, embedded.0]})).unwrap(); + app.run("object.rotate", json!({"angle": 30})).unwrap(); + assert_eq!(marked(&app, linked), (true, true), "a turned linked image, along its frame"); + assert_eq!(marked(&app, embedded), (false, true), "a turned embedded image, outlined along its frame"); + // Move each image's bottom right corner up its right side, so its corners no longer make a parallelogram. + app.session + .edit("Distort", |doc, _| { + for id in [linked, embedded] { + if let Some(n) = doc.node_mut(id) + && let Some([tl, tr, br, bl]) = n.image_corners() + { + n.set_image_corners([tl, tr, br.lerp(tr, 0.4), bl]).map_err(|e| vectorcraft_engine::EngineError::Other(format!("{e:?}")))?; + } + } + Ok(()) + }) + .unwrap(); + let doc = &app.session.active().unwrap().doc; + assert!([linked, embedded].iter().all(|id| doc.node(*id).unwrap().is_distorted_image()), "both images are distorted"); + assert_eq!(marked(&app, linked), (true, true), "a distorted linked image, corner to corner"); + assert_eq!(marked(&app, embedded), (false, true), "a distorted embedded image, outlined along its frame"); + // The key object's outline is its frame alone, and so is the hover outline. + for id in [linked, embedded] { + app.run("select.key", json!({"id": id.0})).unwrap(); + let st = app.session.active().unwrap(); + let key = outlines(&app, st).into_iter().find_map(|o| o.key).unwrap(); + assert_eq!(key.elements(), frame_of(corners(&app, id)).as_slice(), "the key object's outline of {id:?}"); + assert_eq!( + outline_of(st, id, ViewHides::default()).unwrap().path.elements(), + frame_of(corners(&app, id)).as_slice(), + "the hover outline of {id:?}" + ); + } +} + +/// The selection's outlines count the ends of the lines that cross linked images toward the overlay's limit; the +/// hover outline and the key object's outline, which draw no such lines, do not (#9080). +#[test] +fn the_overlay_limit_counts_crossing_lines_only_where_they_are_drawn() { + use super::super::outline::{too_many_anchors, too_many_marks}; + let image = |link: Option| { + let im = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: vectorcraft_geom::Affine::IDENTITY, + link, + placement: Default::default(), + pixels: None, + }; + vectorcraft_doc::Node::new(NodeId(1), NodeKind::Image(Box::new(im))) + }; + // Four corners each fit; with the four ends of the crossing lines they do not. + let count = OVERLAY_MAX_ANCHORS / 6; + let linked = vec![image(Some(vectorcraft_doc::LinkInfo { path: "/a.png".into(), ..Default::default() })); count]; + let embedded = vec![image(None); count]; + let all = ViewHides::default(); + assert!(!too_many_anchors(&linked, all) && too_many_marks(&linked, all), "linked images"); + assert!(!too_many_anchors(&embedded, all) && !too_many_marks(&embedded, all), "embedded images"); +} + +/// A selected group outlines, marks and crosses only the members the canvas draws: a hidden member and a linked image +/// in a hidden group inside it leave no outline, anchors or crossing lines, in the selection's marks and in the hover +/// outline. Hiding them shows the same as deleting them. +#[test] +fn a_selected_group_leaves_its_hidden_members_unmarked() { + let png = red_png("selection-hidden"); + let mut app = blank(); + let left = id_of(&app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let right = id_of(&app.run("shape.rectangle", json!({"x": 330, "y": 230, "width": 20, "height": 20})).unwrap()); + let hidden = id_of(&app.run("shape.rectangle", json!({"x": 120, "y": 100, "width": 40, "height": 40})).unwrap()); + let linked = app.run("file.place", json!({"path": png, "link": true, "at": [240.0, 150.0]})).unwrap()["ids"][0].as_u64().unwrap(); + app.run("select.set", json!({"ids": [linked]})).unwrap(); + let inner = id_of(&app.run("object.group", json!({})).unwrap()); + app.run("select.set", json!({"ids": [left.0, right.0, hidden.0, inner.0]})).unwrap(); + let group = id_of(&app.run("object.group", json!({})).unwrap()); + // With the group selected after the commands `edit`: its outline paths, the paths that show anchors with their + // anchor count, and its hover outline. + let shown = |app: &mut VectorcraftApp, edit: &[(&str, serde_json::Value)]| { + for (command, params) in edit { + app.run(command, params.clone()).unwrap(); + } + app.run("select.set", json!({"ids": [group.0]})).unwrap(); + let st = app.session.active().unwrap(); + let outlined: Vec> = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect(); + let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); + let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.elements().to_vec()); + (outlined, anchored, hovered) + }; + let both = shown(&mut app, &[]); + let without = shown(&mut app, &[("select.set", json!({"ids": [hidden.0, inner.0]})), ("edit.clear", json!({}))]); + let with_hidden = shown(&mut app, &[("edit.undo", json!({})), ("select.set", json!({"ids": [hidden.0, inner.0]})), ("object.hide", json!({}))]); + assert_ne!(both, without, "the marks show every member"); + assert_eq!(without.1, vec![4, 4], "the anchors of the two visible members"); + assert_eq!(with_hidden, without, "hidden members are not marked"); +} + +/// A selected group leaves out a member made into a guide while the guides are hidden, as the canvas does: its +/// outlines, anchors and hover outline are the same as with that member deleted. With the guides shown, the guide is +/// marked too. +#[test] +fn a_selected_group_leaves_out_its_guides_while_guides_are_hidden() { + let mut app = blank(); + let path = id_of(&app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let guide = id_of(&app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 40, "height": 40})).unwrap()); + app.run("select.set", json!({"ids": [guide.0]})).unwrap(); + app.run("view.guides.make", json!({})).unwrap(); + app.run("select.set", json!({"ids": [path.0, guide.0]})).unwrap(); + let group = id_of(&app.run("object.group", json!({})).unwrap()); + assert!( + matches!(app.session.active().unwrap().doc.node(guide).map(|n| &n.kind), Some(NodeKind::Path { guide: true, .. })), + "the group holds a guide" + ); + // With the group selected: the boxes of its outline paths, the paths that show anchors, and its hover outline's box. + let shown = |app: &mut VectorcraftApp| { + app.run("select.set", json!({"ids": [group.0]})).unwrap(); + let st = app.session.active().unwrap(); + let outlined: Vec = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.bounding_box()).collect(); + let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); + let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.bounding_box()); + (outlined, anchored, hovered) + }; + let both = shown(&mut app); + app.run("view.guides", json!({})).unwrap(); + assert!(!app.ui.view.guides_shown(), "the guides are hidden"); + let guides_hidden = shown(&mut app); + app.run("view.guides", json!({})).unwrap(); + app.run("select.set", json!({"ids": [guide.0]})).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + let without = shown(&mut app); + assert_eq!(both.1.len(), 2, "with the guides shown, the guide shows its anchors too: {both:?}"); + assert_ne!(both, without, "with the guides shown, the guide is marked"); + assert_eq!(guides_hidden, without, "with the guides hidden, only the path is marked"); +} + +/// A selected layer leaves out the art of a template sublayer while View › Hide Template is on, and a group a guide +/// while the guides are hidden: their outlines and the overlay's point limit count only what the canvas draws. +#[test] +fn the_marks_leave_out_template_layers_and_guides_the_view_hides() { + use super::super::outline::{node_outline, too_many_anchors, too_many_marks}; + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, Node}; + use vectorcraft_geom::SubPath; + let rect = |id: u64, r: vectorcraft_geom::Rect| Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::default()); + let path = Arc::new(rect(2, vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0))); + let points: Vec = (0..=OVERLAY_MAX_ANCHORS).map(|i| Point::new(i as f64, 0.0)).collect(); + let mut many = Node::path(NodeId(3), PathData::single(SubPath::polyline(&points, false)), Appearance::default()); + let mut template = Node::layer(NodeId(4), "Template", LayerColor::Preset(1)); + if let NodeKind::Layer { template: on, children, .. } = &mut template.kind { + *on = true; + children.push(Arc::new(many.clone())); + } + let mut layer = Node::layer(NodeId(5), "Layer", LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + children.extend([Arc::new(template), path.clone()]); + } + if let NodeKind::Path { guide, .. } = &mut many.kind { + *guide = true; + } + let group = Node::group(NodeId(6), vec![Arc::new(many), path.clone()]); + let doc = vectorcraft_doc::Document::new(300.0, 300.0); + let symbols = doc.symbol_boxes(); + let alone = node_outline(&path, &symbols, ViewHides::default()).bounding_box(); + let mut wrong = vec![]; + for (n, what, hides) in [ + (&layer, "a layer with a template sublayer", ViewHides { templates: true, guides: false }), + (&group, "a group with a guide", ViewHides { templates: false, guides: true }), + ] { + for (hides, hidden) in [(ViewHides::default(), false), (hides, true)] { + let outline = node_outline(n, &symbols, hides).bounding_box(); + if (outline == alone) != hidden || too_many_anchors([n], hides) == hidden || too_many_marks([n], hides) == hidden { + wrong.push(format!("{what}, hidden by the view: {hidden}")); + } + } + } + assert!(wrong.is_empty(), "the marks count only what the view draws: {wrong:?}"); + // A compound path made into a guide draws every path, so each stays outlined while the guides are hidden. + let guide_rect = |id: u64, r: vectorcraft_geom::Rect| { + let mut n = rect(id, r); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + Arc::new(n) + }; + let compound = Node::new( + NodeId(7), + NodeKind::Compound { + children: vec![ + guide_rect(8, vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0)), + guide_rect(9, vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0)), + ], + rule: vectorcraft_geom::FillRule::EvenOdd, + }, + ); + let contours = |hides| node_outline(&compound, &symbols, hides).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); + assert_eq!(contours(ViewHides { templates: false, guides: true }), contours(ViewHides::default()), "a compound path keeps its guide paths"); +} + +/// The overlay's limit counts the points of the members the highlight outlines: a hidden member of a group, a blend, a +/// repeat or an intertwine, and the art of a hidden sublayer, do not count toward it. +#[test] +fn the_overlay_limit_leaves_out_hidden_members() { + use super::super::outline::{too_many_anchors, too_many_marks}; + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, Node}; + use vectorcraft_geom::SubPath; + let points: Vec = (0..=OVERLAY_MAX_ANCHORS).map(|i| Point::new(i as f64, 0.0)).collect(); + let many = Arc::new(Node::path(NodeId(2), PathData::single(SubPath::polyline(&points, false)), Appearance::default())); + let few = Arc::new(Node::path( + NodeId(3), + vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)), + Appearance::default(), + )); + let mut wrong = vec![]; + for visible in [true, false] { + let mut member = (*many).clone(); + member.visible = visible; + let members = || vec![Arc::new(member.clone()), few.clone()]; + let group = Node::group(NodeId(1), members()); + let blend = Node::new(NodeId(6), NodeKind::Blend { children: members(), spec: Default::default() }); + let repeat = Node::new(NodeId(7), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(members(), 0.0, 0.0))); + let intertwine = Node::new(NodeId(8), NodeKind::Intertwine { children: members() }); + let mut sublayer = Node::layer(NodeId(5), "Sublayer", LayerColor::Preset(1)); + sublayer.visible = visible; + if let Some(children) = sublayer.children_mut() { + children.push(many.clone()); + } + let mut layer = Node::layer(NodeId(4), "Layer", LayerColor::Preset(0)); + if let Some(children) = layer.children_mut() { + children.extend([Arc::new(sublayer), few.clone()]); + } + for (n, what) in [(&group, "a group"), (&blend, "a blend"), (&repeat, "a repeat"), (&intertwine, "an intertwine"), (&layer, "a layer")] { + if too_many_anchors([n], ViewHides::default()) != visible || too_many_marks([n], ViewHides::default()) != visible { + wrong.push(format!("{what}, member visible: {visible}")); + } + } + } + assert!(wrong.is_empty(), "the limit is crossed only by visible points: {wrong:?}"); +} + #[test] fn the_anchors_of_a_container_selected_whole_draw_selected() { let (mut app, _) = scene(); diff --git a/crates/ui-egui/src/canvas/selection_widgets.rs b/crates/ui-egui/src/canvas/selection_widgets.rs index 00abc89bc9..921a9e73e4 100644 --- a/crates/ui-egui/src/canvas/selection_widgets.rs +++ b/crates/ui-egui/src/canvas/selection_widgets.rs @@ -260,7 +260,7 @@ pub(super) struct SelectionWidgets { impl SelectionWidgets { fn new(layout: Layout) -> Self { - SelectionWidgets { common: Common::new(), layout, presses: vec![] }.label("Selection widgets") + SelectionWidgets { common: Common::new(), layout, presses: vec![] }.label(tl!("Selection widgets")) } } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 8722616ac2..d560fd2b6b 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -11,7 +11,7 @@ use super::artboards::names_an_artboard; use super::cursor::still_wait; use super::fill::{fill_view, polygon_area}; use super::marks::{HiddenMarks, thread_overlays}; -use super::outline::{node_outline, walk_drawn}; +use super::outline::{ViewHides, node_outline, walk_drawn}; use super::raster::{frame_view, pixel_region, placed_changes, placed_key_at, placed_since, poll_worker}; use super::*; use crate::CacheKey; @@ -31,9 +31,13 @@ fn shaper_selection_highlights_only_the_visible_result() { let g = st.doc.node(st.selection.objects[0]).unwrap(); assert!(g.extras().shaper.is_some()); let symbols = st.doc.symbol_boxes(); - let bounds = node_outline(g, &symbols).bounding_box(); + let bounds = node_outline(g, &symbols, ViewHides::default()).bounding_box(); assert!((bounds.x0 - 100.0).abs() < 0.01 && (bounds.x1 - 200.0).abs() < 0.01, "{bounds:?}"); - assert_eq!(node_outline(st.doc.node(line).unwrap(), &symbols).bounding_box().x0, 50.0, "an isolated original still shows its full outline"); + assert_eq!( + node_outline(st.doc.node(line).unwrap(), &symbols, ViewHides::default()).bounding_box().x0, + 50.0, + "an isolated original still shows its full outline" + ); } #[test] @@ -50,7 +54,95 @@ fn a_symbol_instance_is_outlined_around_its_art() { inst = Some(n); } }); - assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0)); + assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes(), ViewHides::default()).bounding_box(), Rect::new(20.0, 30.0, 40.0, 50.0)); +} + +/// The points of `bp`'s move and line elements, in order. +fn outline_points(bp: &vectorcraft_geom::BezPath) -> Vec { + use vectorcraft_geom::kurbo::PathEl; + bp.elements() + .iter() + .filter_map(|el| match el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => Some(*p), + _ => None, + }) + .collect() +} + +/// Whether `got` are the points `want`, each within 1e-9, a last point of `got` that repeats its +/// first left out. +fn same_points(got: &[Point], want: &[Point]) -> bool { + let near = |a: &Point, b: &Point| a.distance(*b) < 1e-9; + let got = match got { + [first, rest @ .., last] if !rest.is_empty() && near(first, last) => &got[..got.len() - 1], + _ => got, + }; + got.len() == want.len() && got.iter().zip(want).all(|(a, b)| near(a, b)) +} + +/// Puts `n` in perspective, drawn through `h`. +fn in_perspective(n: &mut Node, h: vectorcraft_geom::Homography) { + let at = vectorcraft_doc::PerspectiveAttachment { projection: Some(h.to_array()), ..vectorcraft_doc::PerspectiveAttachment::new("left", 0.0) }; + n.extras_mut().perspective = Some(Box::new(at)); +} + +#[test] +fn a_turned_or_skewed_symbol_instance_is_outlined_along_its_frame() { + // The 20 × 20 square symbol of the test above, its instance at (20, 30). + let svg = r##""##; + let mut s = Session::new(); + s.execute("document.open", &json!({"name": "star.svg", "dataBase64": vectorcraft_format::base64_encode(svg.as_bytes())})).unwrap(); + let st = s.active().unwrap(); + let mut inst = None; + st.doc.walk(|n| { + if matches!(n.kind, NodeKind::SymbolInstance { .. }) { + inst = Some(n.clone()); + } + }); + let inst = inst.unwrap(); + let symbols = st.doc.symbol_boxes(); + let square = [(0.0, 0.0), (20.0, 0.0), (20.0, 20.0), (0.0, 20.0)].map(|(x, y)| Point::new(x, y)); + let placed = |a: Affine| { + let mut n = inst.clone(); + let NodeKind::SymbolInstance { xf, .. } = &mut n.kind else { panic!("an instance") }; + *xf = a * *xf; + let xf = *xf; + (n, square.map(|p| xf * p)) + }; + for (case, a) in [ + ("unturned", Affine::IDENTITY), + ("turned 30 degrees", Affine::rotate_about(30f64.to_radians(), Point::new(30.0, 40.0))), + ("skewed", Affine::skew(0.5, 0.0)), + ] { + let (n, frame) = placed(a); + let got = outline_points(&node_outline(&n, &symbols, ViewHides::default())); + assert!(same_points(&got, &frame), "{case}: {got:?} is not the frame {frame:?}"); + } + // In perspective, the frame's corners go through the projection. + let h = vectorcraft_geom::Homography([[1.0, 0.0, 0.0], [0.1, 1.0, 0.0], [0.004, 0.0, 1.0]]); + let mut n = inst.clone(); + in_perspective(&mut n, h); + let (_, flat) = placed(Affine::IDENTITY); + let drawn = flat.map(|p| h.apply(p).unwrap()); + let got = outline_points(&node_outline(&n, &symbols, ViewHides::default())); + assert!(same_points(&got, &drawn), "in perspective: {got:?} is not the projected frame {drawn:?}"); +} + +#[test] +fn type_in_perspective_is_outlined_by_its_projected_box() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("text.create", &json!({"x": 100, "y": 150, "text": "Hello world", "size": 24})).unwrap(); + let id = vectorcraft_doc::NodeId(r["id"].as_u64().unwrap()); + let st = s.active().unwrap(); + let mut n = st.doc.node(id).unwrap().clone(); + let NodeKind::Text(t) = &n.kind else { panic!("type") }; + let b = t.bounds().unwrap(); + let h = vectorcraft_geom::Homography([[1.0, 0.0, 0.0], [0.1, 1.0, 0.0], [0.002, 0.0, 1.0]]); + in_perspective(&mut n, h); + let drawn = [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| h.apply(Point::new(x, y)).unwrap()); + let got = outline_points(&node_outline(&n, &st.doc.symbol_boxes(), ViewHides::default())); + assert!(same_points(&got, &drawn), "{got:?} is not the projected box {drawn:?}"); } /// One headless canvas frame on an 800 × 600 window. @@ -166,6 +258,99 @@ fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() { assert_eq!(cmd_frame(&mut app, Point::new(200.0, 380.0)), "directSelection", "away from it, in the same frame"); } +/// One headless canvas frame with `events` → the points it paints: the centres of circles and rectangles and the +/// points of lines and paths. +fn painted_points(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let mut points = vec![]; + for shape in flat_shapes(out.shapes) { + match shape { + Shape::Circle(c) => points.push(c.center), + Shape::Rect(r) => points.push(r.rect.center()), + Shape::LineSegment { points: ends, .. } => points.extend_from_slice(&ends), + Shape::Path(p) => points.extend_from_slice(&p.points), + _ => {} + } + } + points +} + +/// A document with smart guides and the task bar off, every frame drawn on this thread. +fn drag_app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.task_bar = false; + app.canvas.worker_started = true; + app +} + +fn press(at: Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } +} + +/// A drag with the Selection tool draws the moved object's marks in the frame the pointer moves: at the corner the +/// object has after that frame's event, and none at the corner it had before it. +#[test] +fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() { + let mut app = drag_app(); + let id = app.session.execute("shape.rectangle", &json!({"x": 150, "y": 100, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + let corner = |app: &VectorcraftApp| { + let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + xf.to_screen(Point::new(b.x0, b.y0)) + }; + let start = xf.to_screen(Point::new(180.0, 120.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, &ctx, vec![press(start, true)]); + let mut moved = 0; + for i in 1..=6 { + let before = corner(&app); + let points = painted_points(&mut app, &ctx, vec![egui::Event::PointerMoved(start + vec2(12.0, 7.0) * i as f32)]); + let after = corner(&app); + if after.distance(before) < 4.0 { + continue; + } + moved += 1; + let near = |q: Pos2| points.iter().any(|p| p.distance(q) < 1.0); + assert!(near(after), "move {i}: a mark at the corner after the move, {after:?}"); + assert!(!near(before), "move {i}: no mark at the corner before it, {before:?}"); + } + assert!(moved >= 4, "the drag moves the object: {moved} frames"); +} + +/// A Pen drag draws the handle it pulls out in the frame the pointer moves: its end at that frame's pointer, and +/// none at the pointer of the frame before. +#[test] +fn a_pen_drag_draws_its_handle_in_the_frame_the_pointer_moves() { + let mut app = drag_app(); + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("pen"); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let xf = app.canvas_view().unwrap(); + let start = xf.to_screen(Point::new(105.0, 155.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, &ctx, vec![press(start, true)]); + let mut before = start; + for i in 1..=6 { + let at = start + vec2(9.0, 5.0) * i as f32; + let points = painted_points(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + let near = |q: Pos2| points.iter().any(|p| p.distance(q) < 1.0); + assert!(near(at), "move {i}: the handle's end at this frame's pointer, {at:?}"); + if i > 1 { + assert!(!near(before), "move {i}: no handle end at the pointer of the frame before, {before:?}"); + } + before = at; + } +} + /// A click with the Selection tool inside an artboard makes it the active one, and Paste in /// Place then pastes onto it, where the objects were on their own artboard (#693). #[test] @@ -533,6 +718,121 @@ fn cmd_with_another_tool_drags_with_the_selection_tool_used_last() { assert_eq!(cmd_drag(&mut app, inside, inside), "selection"); } +/// One frame of the whole app on `ctx` with `events`, in a 1600 × 850 window, as the hosts run it. +fn app_step(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 850.0)); + crate::testing::app_frame(app, ctx, egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }); +} + +/// A Rectangle tool on a new 400 × 300 document in the whole app, after three frames, with Smart +/// Guides and Snap to Point off → (the app, its context, the canvas view). +fn rectangle_tool() -> (VectorcraftApp, egui::Context, craft::behavior::CanvasView) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + app.select_tool("rectangle"); + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + app_step(&mut app, &ctx, vec![]); + } + let xf = app.canvas_view().unwrap(); + (app, ctx, xf) +} + +/// The bounds of the paths in the active document. +fn drawn_paths(app: &VectorcraftApp) -> Vec { + let mut found = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if n.path_data().is_some() { + found.extend(n.geometric_bounds()); + } + }); + found +} + +/// A primary button event at `pos` with `modifiers` held. +fn primary(pos: Pos2, pressed: bool, modifiers: egui::Modifiers) -> egui::Event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } +} + +/// A press or release of Space. +fn space_key(pressed: bool) -> egui::Event { + egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE } +} + +/// A tool drag ends with the modifiers held when its button went up. Shift let go after the +/// release in the same frame still constrains the Rectangle tool's rectangle to a square, Shift +/// pressed after the release does not constrain it, and Alt held only at the release draws it +/// from its center. +#[test] +fn tool_drag_ends_with_the_modifiers_of_its_button_release() { + let draw = |held: egui::Modifiers, after: egui::Modifiers| { + let (mut app, ctx, xf) = rectangle_tool(); + let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); + let none = egui::Modifiers::NONE; + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + app_step(&mut app, &ctx, vec![primary(from, true, none)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + app_step( + &mut app, + &ctx, + vec![egui::Event::PointerMoved(to), egui::Event::ModifiersChanged(held), primary(to, false, held), egui::Event::ModifiersChanged(after)], + ); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(none)]); + let paths = drawn_paths(&app); + assert_eq!(paths.len(), 1, "the drag draws one rectangle"); + paths[0] + }; + let near = |a: f64, b: f64| (a - b).abs() < 1e-3; + let r = draw(egui::Modifiers::SHIFT, egui::Modifiers::NONE); + assert!(near(r.width(), r.height()), "Shift held at the release draws a square: {r:?}"); + let r = draw(egui::Modifiers::NONE, egui::Modifiers::SHIFT); + assert!(near(r.width(), 60.0) && near(r.height(), 30.0), "Shift pressed after the release does not constrain: {r:?}"); + let r = draw(egui::Modifiers::ALT, egui::Modifiers::NONE); + assert!(near(r.width(), 120.0) && near(r.x0, 40.0), "Alt held at the release draws from the center: {r:?}"); +} + +/// Shift pressed only in the frame of a tool drag's release, with the pointer held still since +/// the drag's last frame, still constrains the Rectangle tool's rectangle to a square. +#[test] +fn shift_pressed_at_a_still_release_constrains_the_tool_drag() { + let (mut app, ctx, xf) = rectangle_tool(); + let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from), primary(from, true, egui::Modifiers::NONE)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), primary(to, false, egui::Modifiers::SHIFT)]); + app_step(&mut app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + let paths = drawn_paths(&app); + assert_eq!(paths.len(), 1, "the drag draws one rectangle"); + assert!((paths[0].width() - paths[0].height()).abs() < 1e-3, "Shift pressed at a still release draws a square: {:?}", paths[0]); +} + +/// The move in the frame of a tool drag's release counts for the drag: the Rectangle tool's last +/// move sizes the rectangle, and with Space held through the release it moves the rectangle +/// instead, at the size the drag had before that move. +#[test] +fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() { + let draw = |space: bool| { + let (mut app, ctx, xf) = rectangle_tool(); + let (from, to) = (xf.to_screen(Point::new(100.0, 100.0)), xf.to_screen(Point::new(160.0, 130.0))); + let none = egui::Modifiers::NONE; + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from), primary(from, true, none)]); + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from.lerp(to, 0.5))]); + if space { + app_step(&mut app, &ctx, vec![space_key(true)]); + } + app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(to), primary(to, false, none)]); + app_step(&mut app, &ctx, if space { vec![space_key(false)] } else { vec![] }); + let paths = drawn_paths(&app); + assert_eq!(paths.len(), 1, "the drag draws one rectangle"); + paths[0] + }; + assert_eq!(draw(false), Rect::new(100.0, 100.0, 160.0, 130.0), "the last move sizes the rectangle"); + assert_eq!(draw(true), Rect::new(130.0, 115.0, 160.0, 130.0), "with Space held through the release the last move moves it"); +} + /// #6369: only the selection box remains over the temporary halftone, and the original /// selection's outlines come back when Preview is turned off or the dialog is cancelled. #[test] @@ -905,6 +1205,88 @@ fn the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on() assert_eq!(count(&mut app, red), Some(srgb)); } +/// With a display profile, in Overprint Preview translucent art around the artboards is blended +/// with the white canvas before the conversion, as art over the paper is. With the preview off it +/// converts alone, over the pasteboard. +#[test] +fn translucent_art_around_the_artboards_is_blended_with_overprint_previews_white_canvas() { + keeping_color_settings(translucent_art_around_the_artboards); +} + +fn translucent_art_around_the_artboards() { + use crate::display_profile::{Found, Reading}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.canvas.worker_started = true; // every frame on this thread + // Left of the artboard. + let outside = app.run("shape.rectangle", json!({"x": -60, "y": 100, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [outside], "color": "#00ff00"})).unwrap(); + app.run("transparency.set", json!({"ids": [outside], "opacity": 50})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + // The whole art raster one frame uploads: its width and its pixels. + let upload = |app: &mut VectorcraftApp| -> Option<(usize, Vec)> { + let (_, mut delta) = frame_output(app, &ctx); + let art = app.canvas.texture.as_ref()?.id(); + let up = delta.set.iter().find(|e| e.0.eq(&art)).and_then(|e| e.1.last()).filter(|d| d.pos.is_none()).map(|d| { + let egui::ImageData::Color(img) = &d.image; + (img.width(), img.pixels.clone()) + }); + delta.clear(); + up + }; + upload(&mut app).expect("the first frame"); + let v = app.view_mut().unwrap(); + (v.zoom, v.center) = (1.0, Point::new(120.0, 150.0)); + upload(&mut app).expect("the view at 100%"); + let p3 = crate::display_profile::tests::p3(); + let t = crate::display_profile::tests::transform(); + app.display_profile.report(Reading { display: Some("DP-1".into()), found: Found::Profile { icc: p3, from: "test".into() } }); + upload(&mut app).expect("drawn again, converted"); + let white = convert8(&t, [255; 3]); + // What the canvas shows of pixel `c` over the converted paper `under`, as egui blends it. + let over = |c: egui::Color32, under: [u8; 3]| { + let k = 255 - u32::from(c.a()); + [0, 1, 2].map(|i| u32::from(c.to_array()[i]) + (u32::from(under[i]) * k + 127) / 255) + }; + let plain = |s: egui::Color32| { + let mut px = s.to_array(); + t.apply_premultiplied_rgba8(&mut px); + egui::Color32::from_rgba_premultiplied(px[0], px[1], px[2], px[3]) + }; + // The pixel at the translucent rectangle's center, in sRGB (the display profile's preference + // off) and as the canvas shows it (on). + let pixel = |app: &mut VectorcraftApp| { + app.session.prefs.monitor_profile_display = false; + let (width, srgb) = upload(app).expect("drawn in sRGB"); + let key = app.canvas.key.clone().unwrap(); + let (_, _, view) = + frame_view(None, (key.w, key.h), &CanvasView::new(egui::Rect::NOTHING, Point::new(key.cx, key.cy), key.zoom).rotation(key.rot), key.ppp); + let at = view * Point::new(-40.0, 120.0); + let at = at.y as usize * width + at.x as usize; + app.session.prefs.monitor_profile_display = true; + let (_, shown) = upload(app).expect("drawn again, converted"); + (srgb[at], shown[at], app.canvas.key.clone().unwrap()) + }; + let (s, c, key) = pixel(&mut app); + assert!((50..=205).contains(&s.a()), "the 50% fill: {s:?}"); + assert!(key.backdrop.as_ref().is_some_and(|b| b.everywhere.is_none()), "Preview: the pasteboard is no paper"); + assert_eq!(c, plain(s), "over the pasteboard the art converts alone"); + app.run("view.overprintPreview", json!({"on": true})).unwrap(); + let (s, c, key) = pixel(&mut app); + assert!((50..=205).contains(&s.a()), "the 50% fill: {s:?}"); + assert_eq!(key.backdrop.as_ref().and_then(|b| b.everywhere), Some([255; 3]), "the white canvas is paper"); + let k = 255 - u32::from(s.a()); + let mix = [0, 1, 2].map(|j| (u32::from(s.to_array()[j]) + (255 * k + 127) / 255).min(255) as u8); + let (want, got) = (convert8(&t, mix), over(c, white)); + assert!((0..3).all(|j| got[j].abs_diff(u32::from(want[j])) <= 1), "{got:?} shown, {want:?} wanted"); + // The test tells the two apart: the fill converted alone shows another color over the white canvas. + let alone = over(plain(s), white); + assert!((0..3).any(|j| alone[j].abs_diff(got[j]) > 2), "{alone:?} and {got:?}"); +} + /// With a display profile, translucent art and the anti-aliased edges of art over the paper are /// blended with the paper in sRGB before the conversion: drawn over the converted paper, each such /// pixel shows the converted blend. Opaque art, and art over the pasteboard, convert as before. The @@ -1531,6 +1913,89 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { } } +/// A Pen drag over a frame the worker drew draws each move's curve into that frame, here, in the +/// frame of the move: once the press's frame arrives from the worker, every move shows the +/// document's revision and queues nothing on the worker. When the frame shown drew effect rasters +/// from before their objects moved, when a part drawn here would have differed from it, or when +/// the part's share of the whole frame's time is over 8 ms, the next move renders on the worker, +/// and the moves after the worker's frame are drawn here again. A frame of an older revision on +/// its way does not hold a move back. +#[test] +fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for i in 0..60 { + let (x, y) = (f64::from(i % 10) * 40.0, f64::from(i / 10) * 50.0); + app.session.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 30, "height": 30})).unwrap(); + } + app.session.execute("select.none", &json!({})).unwrap(); + app.ui.view.smart_guides = false; + app.canvas.worker_started = true; // the first frame renders on this thread + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let (worker, mut side) = WorkerSide::start(); + app.canvas.worker = Some(worker); + app.canvas.last_ms = 50.0; + app.select_tool("pen"); + let revision = |app: &VectorcraftApp| Some(app.session.active().unwrap().revision); + let shown = |app: &VectorcraftApp| app.canvas.key.as_ref().map(|k| k.revision); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let mut at = app.canvas_view().unwrap().to_screen(Point::new(105.0, 155.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(at, true)]); + assert!(shown(&app) < revision(&app), "the press's frame, the first of the drag, renders on the worker"); + assert!(side.render()); + let mut drag = |app: &mut VectorcraftApp| { + at += vec2(9.0, 5.0); + frame(app, &ctx, vec![egui::Event::PointerMoved(at)]); + }; + for step in 0..6 { + drag(&mut app); + assert_eq!(shown(&app), revision(&app), "move {step}: the curve is drawn in its own frame"); + assert!(side.jobs.try_recv().is_err(), "move {step}: nothing is queued on the worker"); + } + for case in ["moved", "differs", "slow"] { + match case { + "moved" => app.canvas.moved = true, + "differs" => app.canvas.worker_parts = true, + _ => app.canvas.last_ms = 10_000.0, + } + drag(&mut app); + assert!(shown(&app) < revision(&app), "{case}: the move is not drawn here"); + assert!(side.render(), "{case}: the move renders on the worker"); + drag(&mut app); + assert_eq!(shown(&app), revision(&app), "{case}: after the worker's frame, the next move is drawn here"); + assert!(!app.canvas.worker_parts, "{case}"); + } + // A worker's frame that drew art in a way that depends on its size: the move after it renders + // on the worker too. + app.canvas.worker_parts = true; + drag(&mut app); + let job = side.jobs.try_iter().last().expect("the move is on the worker"); + let done = crate::render_worker::render(&mut side.renderer, &mut side.kept, job); + side.done.send(crate::render_worker::Done { ms: 50.0, view_sized: true, ..done }).unwrap(); + drag(&mut app); + assert!(app.canvas.worker_parts, "the frame shown drew art that depends on its size"); + assert!(shown(&app) < revision(&app) && side.render(), "the move after it renders on the worker"); + drag(&mut app); + assert_eq!(shown(&app), revision(&app), "after the next worker frame, the move is drawn here"); + // A frame on its way of an older revision: the next move is drawn here, and that frame is not + // shown when it arrives. + app.canvas.worker_parts = true; + drag(&mut app); + assert!(app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()), "a frame is on its way"); + app.canvas.worker_parts = false; + for late in [false, true] { + if late { + assert!(side.render()); + } + drag(&mut app); + assert_eq!(shown(&app), revision(&app), "drawn here, the frame on its way arrived: {late}"); + } + frame(&mut app, &ctx, vec![button(at, false)]); + app.canvas.worker = None; +} + /// The frame after an interaction renders without `interacting` also when the interaction /// leaves the document as it was (#1257): here a drag back to where it started. #[test] @@ -1695,7 +2160,9 @@ fn cached_frames_keep_their_scale() { // Deliver the actual replacement and verify that it replaces the cached key. let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts); let expected = job.key.clone(); - completed.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 1.0, moved: 0, reused: false }).unwrap(); + completed + .send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 1.0, moved: 0, reused: false, view_sized: false }) + .unwrap(); frame(&mut app, size, new_ppp); assert_eq!(app.canvas.key.as_ref(), Some(&expected), "the worker's frame arrived"); } @@ -1835,7 +2302,9 @@ fn a_pan_fills_the_area() { // The fill arrives; the next frame draws it, and asks for no other fill. let img = app.canvas.renderer.render(&fill_job.doc, fill_job.w, fill_job.h, fill_job.view, &fill_job.opts); let (doc, opts) = (fill_job.doc, fill_job.opts); - fill_completed.send(crate::render_worker::Done { key: fill_job.key, doc, opts, img, ms: 5.0, moved: 0, reused: false }).unwrap(); + fill_completed + .send(crate::render_worker::Done { key: fill_job.key, doc, opts, img, ms: 5.0, moved: 0, reused: false, view_sized: false }) + .unwrap(); let (meshes, pixels) = frame(&mut app); assert!(fill_jobs.try_recv().is_err(), "the fill covers the canvas"); assert_eq!(app.canvas.key.as_ref(), Some(&old), "the last frame is still shown"); @@ -1880,11 +2349,15 @@ fn a_pan_fills_the_area() { app.view_mut().unwrap().center = Point::new(250.0, 150.0); // That fill finishes after the worker's frame: it is taken and not kept. let img = app.canvas.renderer.render(&next.doc, next.w, next.h, next.view, &next.opts); - fill_completed.send(crate::render_worker::Done { key: next.key, doc: next.doc, opts: next.opts, img, ms: 5.0, moved: 0, reused: false }).unwrap(); + fill_completed + .send(crate::render_worker::Done { key: next.key, doc: next.doc, opts: next.opts, img, ms: 5.0, moved: 0, reused: false, view_sized: false }) + .unwrap(); // The worker's frame arrives: it covers the canvas, and the fill is no longer drawn or kept. let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts); let expected = job.key.clone(); - completed.send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0, reused: false }).unwrap(); + completed + .send(crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img, ms: 50.0, moved: 0, reused: false, view_sized: false }) + .unwrap(); let (meshes, _) = frame(&mut app); assert_eq!(app.canvas.key.as_ref(), Some(&expected), "the worker's frame is shown"); assert!(app.canvas.fill.is_none() && meshes.iter().all(|m| m.texture_id != fill_tex), "the fill is dropped"); @@ -2864,12 +3337,14 @@ fn hidden_characters_mark_no_space_at_a_bullet() { assert_eq!((plain, dots(&t)), (2, 2)); } -/// General › Display Print Size at 100% Zoom (#394): Actual Size shows the document larger with it -/// on (an inch at 96 screen points) than off (a point at a point), and reads 100% either way. +/// General › Display Print Size at 100% Zoom (#394, #9051): Actual Size shows the document larger +/// with it on (an inch at 96 screen points where no display was measured) than off (a point at a +/// point), and reads 100% either way. #[test] fn view_actual_size_follows_display_print_size() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); let ctx = crate::testing::ui_context(); // Frames as the hosts run them: the zoom stops come from the preferences through the app's frame input. let frame = |app: &mut VectorcraftApp, ctx: &egui::Context, _: Vec| { @@ -2884,7 +3359,7 @@ fn view_actual_size_follows_display_print_size() { app.run("view.actualSize", json!({})).unwrap(); frame(app, &ctx, vec![]); let view = app.canvas_view().unwrap(); - let scheme = crate::app::view::zoom_scheme(&app.session.prefs, ctx.pixels_per_point() / ctx.zoom_factor()); + let scheme = crate::app::view::zoom_scheme(app.print_ppi(), ctx.pixels_per_point() / ctx.zoom_factor()); (view.zoom, scheme.percent(craft::behavior::canvas::zoom::device(&view, ctx.pixels_per_point()))) }; let (off, off_percent) = actual(&mut app); @@ -2894,6 +3369,42 @@ fn view_actual_size_follows_display_print_size() { assert!((off_percent - 100.0).abs() < 1e-9 && (on_percent - 100.0).abs() < 1e-9, "both read 100%: {off_percent}, {on_percent}"); } +/// #9051: with Display Print Size on, Actual Size shows a document inch in an inch of the display +/// the window is on, from the density the host measured for it. When the window moves to a display +/// of another density, the view keeps its zoom percentage, so the art keeps its physical size there. +#[test] +fn view_actual_size_fills_an_inch_of_the_measured_display() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + let ctx = crate::testing::ui_context(); + let frame = |app: &mut VectorcraftApp, ctx: &egui::Context| { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + crate::testing::part_frame(app, ctx, raw, show); + }; + let run = |app: &mut VectorcraftApp, id: &str| { + app.run(id, json!({})).unwrap(); + frame(app, &ctx); + }; + frame(&mut app, &ctx); + run(&mut app, "view.fitArtboard"); + let fitted = app.view().unwrap().zoom; + assert!(app.set_screen_ppi(Some(127.0))); + assert_eq!(app.view().unwrap().zoom, fitted, "the first measurement leaves a fitted view alone"); + run(&mut app, "view.actualSize"); + assert!((app.view().unwrap().zoom * 72.0 - 127.0).abs() < 1e-6, "72 pt take the display's 127 points to an inch"); + assert!(app.set_screen_ppi(Some(91.0)), "the window moved to a sparser display"); + assert!(!app.set_screen_ppi(Some(91.0)), "the same reading changes nothing"); + assert!((app.view().unwrap().zoom * 72.0 - 91.0).abs() < 1e-6, "100% still fills an inch"); + assert_eq!(crate::state::zoom_label(app.view().unwrap().zoom, app.print_ppi()), "100%"); + assert!(app.set_screen_ppi(None), "the window moved to a display that reports no size"); + assert!((app.view().unwrap().zoom * 72.0 - 96.0).abs() < 1e-6, "100% there is 96 points to an inch"); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + let zoom = app.view().unwrap().zoom; + assert!(app.set_screen_ppi(Some(110.0))); + assert_eq!(app.view().unwrap().zoom, zoom, "off, a move leaves the zoom alone"); +} + /// Fit Artboard in Window fits the active artboard as a turned view shows it: with the second of /// two artboards active, at 45° all of it is on the canvas, and the two together are not. #[test] @@ -2948,11 +3459,7 @@ fn space_types_a_space_while_editing_text_and_does_not_pan() { assert_ne!(shown(&mut app), editing, "Cmd+Space shows the magnifier"); typing_frame(&mut app, &ctx, vec![button(at, true, Modifiers::COMMAND)]); typing_frame(&mut app, &ctx, vec![button(at, false, Modifiers::COMMAND)]); - assert_eq!( - app.view().unwrap().zoom, - crate::state::next_zoom(before.zoom, true, app.session.prefs.display_print_size), - "Cmd+Space click zooms in" - ); + assert_eq!(app.view().unwrap().zoom, crate::state::next_zoom(before.zoom, true, app.print_ppi()), "Cmd+Space click zooms in"); typing_frame(&mut app, &ctx, vec![space(false, Modifiers::COMMAND), Event::ModifiersChanged(Modifiers::NONE)]); assert_eq!(plain(&app, id), "a ", "the text is as typed"); } @@ -3304,7 +3811,10 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { // Cancel: nothing is edited, and the document, its undo history and the selection stay. let (before, undo, selected) = (node(&app), app.session.doc().unwrap().history.undo.len(), app.session.active().unwrap().selection.objects.clone()); + let cancelled_token = app.missing_font_edit_token.expect("the question's edit token"); answer(&mut app, false); + // A delayed approval for the cancelled question can no longer start an edit. + app.session.set_tool_option("missingFontEdit", &json!({"token": cancelled_token, "ok": true})); timed(&mut app, 1.5, vec![]); assert_eq!(app.session.tool_options()["editing"], json!(null)); assert!(!app.session.tool_wants_text()); @@ -3314,6 +3824,16 @@ fn double_clicking_type_in_a_missing_font_asks_before_editing() { // A new double-click asks again; OK edits with the caret where the type was clicked. double_click(&mut app, 3.0); assert!(asking(&app), "asked again"); + let replaced_token = app.missing_font_edit_token; + // A Type press sent through automation can replace the prompt before the user answers. + let view = app.view_info(); + let point = Point::new(b.x0 + b.width() * 0.25, b.center().y); + for kind in [PointerKind::Down, PointerKind::Up] { + crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, point.x, point.y), view); + } + assert_ne!(app.missing_font_edit_token, replaced_token); + crate::dialogs::host::pump(&mut app, &ctx); + assert!(asking(&app), "the replacement question is open"); answer(&mut app, true); timed(&mut app, 3.5, vec![]); assert!(!asking(&app)); @@ -3624,6 +4144,23 @@ fn start_typing(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 { app.session.active().unwrap().selection.objects[0].0 } +#[test] +fn the_canvas_type_editor_uses_the_interface_language() { + use crate::i18n::LangExt as _; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = crate::testing::ui_context(); + ctx.enable_accesskit(); + let former = crate::i18n::current(); + start_typing(&mut app, &ctx); + crate::i18n::set_current(crate::i18n::Lang::from_code("fr").unwrap()); + let out = typing_frame(&mut app, &ctx, vec![egui::Event::Text("Bonjour".into())]); + crate::i18n::set_current(former); + + let nodes = out.platform_output.accesskit_update.unwrap().nodes; + assert!(nodes.iter().any(|(_, node)| node.role() == egui::accesskit::Role::MultilineTextInput && node.label() == Some("Texte"))); +} + /// Returns a key press and its release. fn tap(key: egui::Key) -> [egui::Event; 2] { [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() }) @@ -4537,17 +5074,83 @@ fn live_trace_selection_highlight_excludes_the_retained_source_rectangle() { for view in TraceView::ALL { group.extras_mut().trace = Some(Box::new(json!({"view":view.id()}))); let mut visited = vec![]; - walk_drawn(&group, &mut |n| visited.push(n.id)); + walk_drawn(&group, ViewHides::default(), &mut |n| visited.push(n.id)); assert_eq!(visited.contains(&NodeId(2)), view.shows_source()); let want = if view.shows_source() { vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0) } else { vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0) }; - assert_eq!(node_outline(&group, &symbols).bounding_box(), want); + assert_eq!(node_outline(&group, &symbols, ViewHides::default()).bounding_box(), want); } + // Without a trace the image is an ordinary hidden member, which the canvas does not draw. group.extras_mut().trace = None; - assert_eq!(node_outline(&group, &symbols).bounding_box(), vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)); + assert_eq!(node_outline(&group, &symbols, ViewHides::default()).bounding_box(), vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)); + // A hidden path sent to the back of a trace is not its source image, in any view. + let mut path = + Node::path(NodeId(4), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 200.0, 200.0)), Appearance::default()); + path.visible = false; + let art = Node::path(NodeId(3), vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0)), Appearance::default()); + let mut group = Node::group(NodeId(1), vec![Arc::new(path), Arc::new(art)]); + for view in TraceView::ALL { + group.extras_mut().trace = Some(Box::new(json!({"view":view.id()}))); + assert_eq!( + node_outline(&group, &symbols, ViewHides::default()).bounding_box(), + vectorcraft_geom::Rect::new(20.0, 30.0, 80.0, 90.0), + "{view:?}" + ); + } +} + +/// A compound path draws every path it holds, hidden ones included, so its highlight outlines them +/// all; a group, a blend, a repeat, an intertwine and a layer leave out a hidden member, and a +/// layer the art of a hidden sublayer. A clip group shows its clipping path whether or not it is +/// hidden, and a hidden object on its own keeps its outline. +#[test] +fn a_compound_path_outlines_its_hidden_paths_and_a_group_does_not() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, LayerColor, NodeId}; + use vectorcraft_geom::{FillRule, PathEl}; + let rect = |id: u64, r: vectorcraft_geom::Rect, visible: bool| { + let mut n = Node::path(NodeId(id), vectorcraft_geom::shapes::rectangle(r), Appearance::default()); + n.visible = visible; + Arc::new(n) + }; + let children = || { + vec![rect(2, vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0), true), rect(3, vectorcraft_geom::Rect::new(30.0, 30.0, 70.0, 70.0), false)] + }; + let doc = vectorcraft_doc::Document::new(300.0, 300.0); + let symbols = doc.symbol_boxes(); + let contours = |n: &Node| node_outline(n, &symbols, ViewHides::default()).elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Compound { children: children(), rule: FillRule::EvenOdd })), 2, "a compound path"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Blend { children: children(), spec: Default::default() })), 1, "a blend"); + assert_eq!(contours(&Node::group(NodeId(1), children())), 1, "a group"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Intertwine { children: children() })), 1, "an intertwine"); + assert_eq!(contours(&Node::new(NodeId(1), NodeKind::Repeat(vectorcraft_doc::RepeatSpec::grid(children(), 0.0, 0.0)))), 1, "a repeat"); + // A clip group shows its clipping path, hidden or not, and none of the art it clips. + let clip = |visible: bool| { + let mut members = children(); + members.insert(0, rect(6, vectorcraft_geom::Rect::new(10.0, 10.0, 90.0, 90.0), visible)); + let mut n = Node::group(NodeId(1), members); + if let NodeKind::Group { clip, .. } = &mut n.kind { + *clip = true; + } + contours(&n) + }; + assert_eq!((clip(true), clip(false)), (1, 1), "a clip group"); + // A hidden object that is itself selected keeps its outline. + assert_eq!(contours(&rect(7, vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0), false)), 1, "a hidden object"); + let mut layer = Node::layer(NodeId(1), "Layer", LayerColor::Preset(0)); + let mut sublayer = Node::layer(NodeId(4), "Sublayer", LayerColor::Preset(1)); + sublayer.visible = false; + if let Some(c) = sublayer.children_mut() { + c.push(rect(5, vectorcraft_geom::Rect::new(150.0, 150.0, 200.0, 200.0), true)); + } + if let Some(c) = layer.children_mut() { + c.extend(children()); + c.push(Arc::new(sublayer)); + } + assert_eq!(contours(&layer), 1, "a layer"); } /// #2572: Show Text Threads links a thread's frames from the out port of one to the in port of @@ -4927,6 +5530,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra ms: 2.5, moved: 0, reused: false, + view_sized: false, }) .unwrap(); @@ -4950,6 +5554,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra ms: 2.5, moved: 0, reused: false, + view_sized: false, }) .unwrap(); @@ -4972,6 +5577,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra ms: 2.5, moved: 0, reused: false, + view_sized: false, }) .unwrap(); @@ -4994,6 +5600,7 @@ fn poll_worker_accepts_frames_not_older_than_displayed_and_discards_obsolete_fra ms: 2.5, moved: 0, reused: false, + view_sized: false, }) .unwrap(); @@ -5054,7 +5661,16 @@ fn the_contour_bar_sets_corners_and_bakes() { /// A frame the render worker finished for `job`: white pixels of the job's size. fn finished(job: &crate::render_worker::Job) -> crate::render_worker::Done { let img = vectorcraft_render::Rendered { width: job.w, height: job.h, pixels: vec![255; job.w as usize * job.h as usize * 4] }; - crate::render_worker::Done { key: job.key.clone(), doc: job.doc.clone(), opts: job.opts.clone(), img, ms: 40.0, moved: 0, reused: false } + crate::render_worker::Done { + key: job.key.clone(), + doc: job.doc.clone(), + opts: job.opts.clone(), + img, + ms: 40.0, + moved: 0, + reused: false, + view_sized: false, + } } /// A job for the render worker to pan over a document of `doc`: a view at 100% moved by `(dx, dy)` @@ -5520,7 +6136,8 @@ fn a_pan_after_the_settling_frame() { let job = jobs.try_recv().unwrap_or_else(|_| panic!("{name}: the canvas asks for a frame")); let f = render_job(&mut r, &mut kept, &job); assert_eq!(f.reused, copies, "{name}"); - let done = crate::render_worker::Done { key: job.key, doc: job.doc, opts: job.opts, img: f.img, ms: 40.0, moved: f.moved, reused: f.reused }; + let (key, doc, opts, img) = (job.key, job.doc, job.opts, f.img); + let done = crate::render_worker::Done { key, doc, opts, img, ms: 40.0, moved: f.moved, reused: f.reused, view_sized: f.view_sized }; done_tx.send(done).unwrap(); }; frame(&mut app, 1.0); diff --git a/crates/ui-egui/src/canvas/tests_ui_scaling.rs b/crates/ui-egui/src/canvas/tests_ui_scaling.rs index 230bf917ff..64dca524b3 100644 --- a/crates/ui-egui/src/canvas/tests_ui_scaling.rs +++ b/crates/ui-egui/src/canvas/tests_ui_scaling.rs @@ -27,10 +27,12 @@ fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, (native, ui_zoom): (f32, } /// A 512 × 512 pt document shown at `native` device pixels a point and UI Scaling `ui_zoom`, with a -/// controlled render worker, and the receiver of the frames it is asked to render. +/// controlled render worker, and the receiver of the frames it is asked to render. Display Print +/// Size at 100% Zoom is off, so 100% is one document point per screen point. fn shown(native: f32, ui_zoom: f32) -> (VectorcraftApp, egui::Context, std::sync::mpsc::Receiver) { let ctx = crate::testing::ui_context(); let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); app.run("file.new", json!({"width": 512, "height": 512})).unwrap(); // The app's frames zoom the interface by the preference. app.session.prefs.ui_scaling = f64::from(ui_zoom); @@ -90,3 +92,20 @@ fn pixel_preview_compares_a_document_pixel_with_a_device_pixel() { } } } + +#[test] +fn out_of_range_saved_ui_scaling_keeps_actual_size_correct() { + let (a, b) = (Point::new(100.0, 100.0), Point::new(228.0, 100.0)); + for (saved, expected) in [(0.5, 0.75), (3.0, 2.0), (0.0, 1.0), (f64::NAN, 1.0)] { + let (mut app, ctx, jobs) = shown(1.0, 1.5); + app.run("view.actualSize", json!({})).unwrap(); + frame(&mut app, &ctx, (1.0, 1.5), vec![]); + let before = device_length(rendered(&jobs), a, b); + app.session.prefs.ui_scaling = saved; + let scale = crate::app::root_env(&app.session.prefs, 1.0, None).scale.0; + assert_eq!(scale, expected, "interface scale from saved value {saved}"); + frame(&mut app, &ctx, (1.0, scale), vec![]); + let length = device_length(rendered(&jobs), a, b); + assert!((length - before).abs() < 1e-4, "saved scale {saved} changes 128 pt from {before} to {length} pixels"); + } +} diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 3a8f20f69c..af12608aa5 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -150,6 +150,18 @@ impl<'a> SessionTool<'a> { Self { app: RefCell::new(app), view, carrying: Cell::new(false), ctx: ui.ctx().clone(), layer: ui.layer_id() } } + /// `ev` with Shift, Alt, Cmd and Ctrl as they were held when the gesture's button went up in this pass, latched ones + /// included (the pointer frame's `pick_mods`), instead of as they are at the end of the pass: a modifier pressed or + /// let go after the release does not count for it. Space and Backtick stay as the host holds them. Unchanged in a + /// pass where that button did not come up. + fn at_release(&self, pointer: &ToolPointer, mut ev: PointerEvent) -> PointerEvent { + let frame = craft::ui::runtime::pointer::frame(&self.ctx); + if frame.release == Some(pointer.button) { + ev.mods = tool_mods(frame.pick_mods, ev.mods.space); + } + ev + } + /// Whether another window covers the canvas at `pointer`, so art moved there leaves the canvas: a floating /// document's or a floating panel's OS window. fn covered(&self, pointer: &ToolPointer) -> bool { @@ -322,7 +334,8 @@ impl CanvasTool for SessionTool<'_> { let covered = self.covered(pointer); let carried = super::drops::carry_out(&mut self.app(), cx, pointer, covered); if !carried { - let ev = pointer_event(PointerKind::Drag, pointer, cx); + // The moves of the pass that releases the press came before its release, with the keys held then. + let ev = self.at_release(pointer, pointer_event(PointerKind::Drag, pointer, cx)); dispatch(&mut self.app(), &ev, self.view); self.app().canvas.last_drag = Some((pointer.pos, ev)); } @@ -340,21 +353,31 @@ impl CanvasTool for SessionTool<'_> { return; } drop(app); + // The press ends where it went up, with the keys held at its release. + let up = self.at_release(pointer, pointer_event(PointerKind::Up, pointer, cx)); let covered = self.covered(pointer); let carried = super::drops::carried(&self.app(), cx, pointer, covered); self.app().canvas.panes.released_from = carried.as_ref().map(|art| (art.document, art.revision)); - if cx.over_drop_target() || carried.is_some() { + let given_up = cx.over_drop_target() || carried.is_some(); + if given_up { // The art goes to the drop target, or nowhere off the canvas: the move is given up where it started. let _ = self.app().session.cancel_interaction(); } if let Some(art) = carried.filter(|_| !cx.over_drop_target()) { // Released over a pane in the frame the pointer reached it: no target could take it yet. - let op = if pointer.mods.alt { DropOperation::Copy } else { DropOperation::Move }; + let op = if up.mods.alt { DropOperation::Copy } else { DropOperation::Move }; let mut app = self.app(); app.canvas.panes.released = super::drops::released_on_pane(&app, art, pointer.pos, op); } self.app().canvas.grab = None; - self.send(PointerKind::Up, pointer, cx); + // When the pointer moved or the keys changed since the drag's last move, the tool gets a move where the press went + // up first, as it does while held: the last move of the release's pass still sizes the shape, and Shift pressed in + // that pass still draws a square. A move that was given up gets none. + let last = self.app().canvas.last_drag.map(|(_, ev)| ev); + if !given_up && last.is_some_and(|last| (last.pos, last.mods, last.backquote) != (up.pos, up.mods, up.backquote)) { + dispatch(&mut self.app(), &PointerEvent { kind: PointerKind::Drag, ..up }, self.view); + } + dispatch(&mut self.app(), &up, self.view); if self.app().canvas.last_drag.is_some() { // A press that dragged is no click, and the framework counts presses: the next press starts a new run. self.app().ui.trace_pick_clicks = pointer.clicks; @@ -367,7 +390,7 @@ impl CanvasTool for SessionTool<'_> { _ => return, }; let before = self.app().session.tool_id(); - self.send(follow, pointer, cx); + dispatch(&mut self.app(), &PointerEvent { kind: follow, ..up }, self.view); // A double click on type switched a selection tool to the Type tool: the caret goes where the type was // clicked, so typing edits it at once. let switched = follow == PointerKind::DoubleClick && before != "type" && self.app().session.tool_id() == "type"; @@ -577,8 +600,13 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too } // Once a frame, before its press, which then uses the new tool; a held press (its grab) waits for the frame after // the release, and a pointer over another window for the pointer to come in. - if ui.ctx().current_pass_index() == 0 && app.canvas.grab.is_none() && ui.input(|i| i.pointer.has_pointer()) { - crate::stylus::sync_eraser_tool(app); + if ui.ctx().current_pass_index() == 0 + && app.canvas.grab.is_none() + && ui.input(|i| i.pointer.has_pointer()) + && crate::stylus::sync_eraser_tool(app) + { + // Before the press, which holds what the host was told about the wheel until its release. + crate::stylus::sync_wheel_use(app); } // A press on the canvas that a view tool takes (a middle-button pan, a held Space's Hand) counts as a press // elsewhere for the clicks the tool's double-click or triple-click compares. diff --git a/crates/ui-egui/src/canvas/tool_adapter/tests.rs b/crates/ui-egui/src/canvas/tool_adapter/tests.rs index 88e1c533be..1ff48b983a 100644 --- a/crates/ui-egui/src/canvas/tool_adapter/tests.rs +++ b/crates/ui-egui/src/canvas/tool_adapter/tests.rs @@ -67,3 +67,88 @@ fn bucket_modifier_only_hover_updates_the_visible_cursor() { assert_ne!(alt, plain, "Alt shows the Eyedropper's cursor"); assert_eq!(shown(&mut app, egui::Modifiers::NONE), plain, "and letting go brings the bucket back"); } + +/// The Blob Brush's or the Eraser's tip outline at the pointer, as the canvas draws it this pass. +fn shows_tip(app: &mut VectorcraftApp) -> bool { + let view = app.view_info(); + app.session.overlays(view).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Path { .. })) +} + +/// Use Precise Cursors or Caps Lock, or both, gives the Blob Brush and the Eraser only the crosshair: the tool draws no +/// tip outline around it. With both off, each shows its own pointer and the tip outline. +#[test] +fn precise_cursors_hide_the_brush_tip_outline() { + use craft::ui::runtime::windows::WindowHost; + let crosshair = Some(crate::cursors::tool_cursor(vectorcraft_tools::Cursor::Crosshair)); + for tool in ["blobBrush", "eraser"] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool(tool); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let at = app.canvas_view().unwrap().to_screen(Point::new(200.0, 150.0)); + for (preference, caps_lock) in [(false, false), (true, false), (false, true), (true, true), (false, false)] { + app.run("prefs.set", serde_json::json!({"key": "usePreciseCursors", "value": preference})).unwrap(); + WindowHost::of(&ctx).set_caps_lock(Some(caps_lock)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]); + let precise = preference || caps_lock; + let case = format!("{tool}, Use Precise Cursors {preference}, Caps Lock {caps_lock}"); + assert_eq!(app.session.caps_lock, caps_lock, "{case}: the session takes the host's Caps Lock state"); + assert_eq!(app.view_info().precise, precise, "{case}"); + assert_eq!(shows_tip(&mut app), !precise, "{case}"); + assert_eq!(craft::ui::runtime::cursor::current(&ctx) == crosshair, precise, "{case}"); + } + } +} + +/// `view.capsLock` sets the Caps Lock state the tools and the canvas's pointer follow until the host's state changes. +#[test] +fn the_caps_lock_command_gives_the_brushes_the_crosshair() { + use craft::ui::runtime::windows::WindowHost; + let crosshair = Some(crate::cursors::tool_cursor(vectorcraft_tools::Cursor::Crosshair)); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("blobBrush"); + let ctx = crate::testing::ui_context(); + WindowHost::of(&ctx).set_caps_lock(Some(false)); + frame(&mut app, &ctx, vec![]); + let at = app.canvas_view().unwrap().to_screen(Point::new(200.0, 150.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(shows_tip(&mut app)); + app.run("view.capsLock", serde_json::json!({"on": true})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]); + assert!(app.session.caps_lock, "the host's unchanged state leaves the command's in place"); + assert!(!shows_tip(&mut app)); + assert_eq!(craft::ui::runtime::cursor::current(&ctx), crosshair); + app.run("view.capsLock", serde_json::json!({"on": false})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(shows_tip(&mut app)); + assert_ne!(craft::ui::runtime::cursor::current(&ctx), crosshair); + // With the host's Caps Lock on, the command turns it off for the tools and the canvas's pointer alike. + WindowHost::of(&ctx).set_caps_lock(Some(true)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]); + assert!(!shows_tip(&mut app)); + assert_eq!(craft::ui::runtime::cursor::current(&ctx), crosshair); + app.run("view.capsLock", serde_json::json!({"on": false})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(!app.session.caps_lock); + assert!(shows_tip(&mut app)); + assert_ne!(craft::ui::runtime::cursor::current(&ctx), crosshair); +} + +/// A `view.capsLock` call that runs before the first canvas pass stays in place when the host's Caps Lock is off. +#[test] +fn the_caps_lock_command_before_the_first_frame_stays_in_place() { + use craft::ui::runtime::windows::WindowHost; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("blobBrush"); + app.run("view.capsLock", serde_json::json!({"on": true})).unwrap(); + let ctx = crate::testing::ui_context(); + WindowHost::of(&ctx).set_caps_lock(Some(false)); + frame(&mut app, &ctx, vec![]); + assert!(app.session.caps_lock, "the first host reading is only the baseline"); + frame(&mut app, &ctx, vec![]); + assert!(app.session.caps_lock); +} diff --git a/crates/ui-egui/src/canvas/widgets.rs b/crates/ui-egui/src/canvas/widgets.rs index 204853bd98..2545d16761 100644 --- a/crates/ui-egui/src/canvas/widgets.rs +++ b/crates/ui-egui/src/canvas/widgets.rs @@ -275,7 +275,7 @@ impl ShapeWidgets { } fn new(marks: Vec) -> Self { - ShapeWidgets { common: Common::new(), marks }.label("Shape widgets") + ShapeWidgets { common: Common::new(), marks }.label(tl!("Shape widgets")) } } @@ -334,7 +334,7 @@ impl Component for ShapeWidgets { } fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { - access.description("Shape widgets"); + access.description(tl!("Shape widgets")); } fn finish(self, cx: Cx<'_, Self>) -> Response { diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index ab90d71dc2..5401e9800f 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -120,48 +120,21 @@ pub fn anchor_buttons(app: &mut VectorcraftApp, ui: &mut Ui, controls: AnchorCon } } -/// The selected paths' eligible corners, as document lengths, beside the anchor controls. -/// Explicit partial selections with no corners contribute no target (unlike `picked`'s fallback). +/// The Corners link and the radius of the selected paths' picked corners +/// ([`crate::panels::picked_corners`]), beside the anchor controls. The link opens the Corners +/// pop-up for those corners; a narrow bar leaves out the link and the field together. fn corner_radius(app: &mut VectorcraftApp, ui: &mut Ui) { - let Some(st) = app.session.active() else { return }; - let mut items = Vec::new(); - let mut radius: Option = None; - let mut mixed = false; - for &id in &st.selection.objects { - let Some(lc) = st.doc.node(id).and_then(vectorcraft_doc::LiveCorners::of) else { continue }; - let corners = st.selection.partial(id).map_or_else(|| lc.all(), |anchors| lc.corners_of(anchors)); - if corners.is_empty() { - continue; - } - for &k in &corners { - // Keep absolute requested radii, even when their drawing is fitted smaller. Relative - // storage is a fraction, but the field and setLiveShape both consume document lengths. - let value = if lc.radii_relative() { lc.radius(k) * lc.corner(k).map_or(0.0, |c| c.max_radius()) } else { lc.radius(k) }; - if let Some(first) = radius { - mixed |= (first - value).abs() >= 1e-9; - } else { - radius = Some(value); - } - } - items.push(json!({"id": id, "corners": corners})); - } - if items.is_empty() { - return; - } + let Some(picked) = crate::panels::picked_corners(app) else { return }; let label = tl!("Corner Radius:"); - let shown = if mixed { None } else { radius }; - // PLAN: assumed `crate::canvas::general_lengths(app) -> LengthUnits` (cv.B5b, canvas-w15). let lengths = crate::canvas::general_lengths(app); let mut typed = None; group(ui, rank::GROUP, |ui| { - Field::new(label).show(ui, |ui, _| { - let number = NumberField::length(label, Bind::given(shown), lengths).show(ui); - typed = number.edit.events.committed().copied().flatten().or(typed); - }); + crate::panels::corners_link(app, ui); + let number = NumberField::length(label, Bind::given(picked.radius), lengths).show(ui); + typed = number.edit.events.committed().copied().flatten().or(typed); }); if let Some(radius) = typed { - // App::run reports any command failure in the status bar, as the other inline fields do. - app.run("object.setLiveShape", json!({"items": items, "radius": radius.max(0.0)})).ok(); + crate::panels::set_picked_corners(app, &picked, json!({"radius": radius.max(0.0)})); } } @@ -609,9 +582,8 @@ fn members(app: &mut VectorcraftApp, ui: &mut Ui) { }); } if typed && paragraph { - ranked(ui, rank::TYPE, |ui| { - crate::panels::paragraph::control_bar(app, ui); - }); + // The Paragraph group ranks its link and its Align buttons as two members, so the buttons leave first. + crate::panels::paragraph::control_bar(app, ui); } let vertical = group_on(app, "verticalAlignment") && crate::panels::properties::vertical_align::shown(app).is_some(); if vertical { diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 0751e2802b..aef6749bbc 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -20,7 +20,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(secs) = next { ui.ctx().request_repaint_after(std::time::Duration::from_secs(secs)); } - let print = app.session.prefs.display_print_size; + let print = app.print_ppi(); let nab = app.session.active().map(|d| d.doc.artboards.len()).unwrap_or(0); let cur = crate::panels::artboards::selected(app, nab); // PLAN: assumed Artboard::rect has `width()` and `height()`. @@ -32,8 +32,12 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { .map(|d| d.doc.artboards.iter().enumerate().map(|(i, a)| Entry::new(i, format!("{} {}", i + 1, a.name))).collect()) .unwrap_or_default(); let angles: Vec> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect(); - let rotation = app.view().map_or(0.0, |v| v.rotation); + let view = app.view(); + let rotation = view.map_or(0.0, |v| v.rotation); let turned = ROTATE_VIEW_ANGLES.iter().position(|(_, a)| (rotation - a).abs() < 1e-9).unwrap_or(usize::MAX); + // An angle between the presets, from the Rotate View tool or `view.rotate`, shows in whole degrees; adding 0.0 + // turns the -0 of a small negative angle into 0. + let angle = format!("{}°", rotation.round() + 0.0); let shows: Vec> = StatusBarShow::ALL.into_iter().map(|s| Entry::new(s, s.label()).checked(app.ui.status_bar_show == s)).collect(); let unit = app.session.general_unit(); @@ -68,13 +72,19 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let zoom = Field::new(tl!("Zoom")) .side(SideLabel::new().kind(LabelKind::Hidden)) .show(ui, |ui, _| ZoomField::new(tl!("Zoom"), app.canvas_view(), document).scrub(true).show(ui)); - // PLAN: assumed CanvasView::zoom and crate::state::zoom_display_percent(zoom, print) through the scheme (cv.S4). + // The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom. if let Some(view) = zoom.inner.and_then(|z| z.view.committed().copied()) { - zoom_to = Some(crate::state::zoom_display_percent(view.zoom, print)); + zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(&view, app.ui_scaling()), print)); } Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { // Entries are keyed by index: an angle is not a hashable value. - rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles).look(SelectLook::Filled).show(ui).value().copied(); + rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles) + .placeholder(angle.clone()) + .look(SelectLook::Filled) + .enabled(view.is_some()) + .show(ui) + .value() + .copied(); }); Divider::vertical().show(ui); for (icon, to, tip, enabled) in @@ -310,15 +320,22 @@ fn date_time_now() -> (String, u64) { } /// The status message in the interface language. While it is the error of the last script run -/// and that error's message is text the script supplied, that text is shown as it is and only the -/// words around it are translated. +/// and that error's message is text the script supplied, or a plug-in run's notice +/// ([`crate::state::UiState::status_kept`]), that text is shown as it is and only the words around +/// it are translated. pub(crate) fn status_message(app: &VectorcraftApp) -> String { let status = app.ui.status.as_str(); + let is = |before: &str, kept: &str, after: &str| status.strip_prefix(before).and_then(|rest| rest.strip_suffix(after)) == Some(kept); if let Some((before, kept, after)) = app.session.script_authored_failure() - && status.strip_prefix(before.as_str()).and_then(|rest| rest.strip_suffix(after.as_str())) == Some(kept) + && is(&before, kept, &after) { return crate::i18n::msg_keeping(&before, kept, &after); } + if let Some((before, kept, after)) = &app.ui.status_kept + && is(before, kept, after) + { + return crate::i18n::msg_keeping(before, kept, after); + } crate::i18n::msg(status) } diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 59f0dda7ce..4ba5c01293 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -9,22 +9,22 @@ use craft::ui::tabs::{DocumentTab, DocumentTabs, DocumentTabsEvent}; /// [`view_tab_title`] for a document with one view. #[cfg(test)] -pub(super) fn tab_title(d: &vectorcraft_engine::DocState, zoom: f64, outline: bool, display_print_size: bool) -> String { - view_tab_title(d, None, true, zoom, outline, display_print_size) +pub(super) fn tab_title(d: &vectorcraft_engine::DocState, zoom: f64, outline: bool, print: Option) -> String { + view_tab_title(d, None, true, zoom, outline, print) } /// A document tab's title: "Name* @ 66.67 % (RGB/Preview)", or while an opacity mask is edited /// "Name* @ 66.67 % (/Opacity Mask)". For a view of a document with more than one /// view, the view's `number` follows the name: "Name:2* @ 66.67 % (RGB/Preview)". The `*` of unsaved changes shows /// when `marked`; a document tab shows its own modified mark instead. -fn view_tab_title(d: &vectorcraft_engine::DocState, number: Option, marked: bool, zoom: f64, outline: bool, display_print_size: bool) -> String { +fn view_tab_title(d: &vectorcraft_engine::DocState, number: Option, marked: bool, zoom: f64, outline: bool, print: Option) -> String { let mode = if d.doc.mask_edit.is_some() { format!("<{0}>/{0}", tl!("Opacity Mask")) } else { let color = if d.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { "CMYK" } else { "RGB" }; format!("{color}/{}", if outline { tl!("Outline") } else { tl!("Preview") }) }; - format!("{} @ {} ({mode})", view_tab_name(d, number, marked), zoom_label(zoom, display_print_size).replace('%', " %")) + format!("{} @ {} ({mode})", view_tab_name(d, number, marked), zoom_label(zoom, print).replace('%', " %")) } /// The start of [`view_tab_title`], which an inactive document tab shows alone (#8582): "Name*", @@ -39,7 +39,7 @@ fn view_tab_name(d: &vectorcraft_engine::DocState, number: Option, marked: fn window_tab_title(app: &VectorcraftApp, w: crate::doc_windows::Win, d: &vectorcraft_engine::DocState, marked: bool) -> String { let view = crate::doc_windows::view(app, w); let zoom = view.map_or(1.0, |v| v.zoom); - view_tab_title(d, crate::doc_windows::label(app, w), marked, zoom, view.is_some_and(|v| v.outline), app.session.prefs.display_print_size) + view_tab_title(d, crate::doc_windows::label(app, w), marked, zoom, view.is_some_and(|v| v.outline), app.print_ppi_of(Some(w))) } /// The title of window `w`'s tab and floating window ([`crate::doc_windows`]). @@ -224,11 +224,30 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { crumbs.push((None, false, pn.clone())); } // Up one level: the isolated object's parent group, or `object.exitIsolation`, which goes from an - // isolated sublayer to its parent layer and otherwise leaves isolation mode. - let up = match ancestry.iter().rev().nth(1).filter(|p| st.doc.node(**p).is_some_and(|n| !n.is_layer())) { + // isolated sublayer to its parent layer, from a group in a symbol's art to the symbol's layer, and + // otherwise leaves isolation mode. While a pattern is edited the back arrow is Done. Screen readers + // call it by what it does. + let parent_group = ancestry.iter().rev().nth(1).copied().filter(|p| st.doc.node(*p).is_some_and(|n| !n.is_layer())); + let up = match parent_group { Some(parent) => ("object.isolate", json!({ "id": parent.0 })), None => ("object.exitIsolation", json!({})), }; + let symbol_layer = st.doc.symbol_edit.as_ref().map(|e| e.layer); + let up_one = parent_group.is_some() + || symbol_layer.is_some_and(|l| l != iso && ancestry.contains(&l)) + || (st.doc.mask_edit.is_none() + && symbol_layer.is_none() + && st.doc.node(iso).is_some_and(|n| n.is_layer()) + && st.doc.parent_of(iso).is_some_and(|p| st.doc.is_editable(p))); + let back_name = if pattern_edit.is_some() { + tl!("Done") + } else if up_one { + tl!("Back One Level") + } else if symbol_layer == Some(iso) { + tl!("Exit Symbol Editing Mode") + } else { + tl!("Exit Isolation Mode") + }; let entries: Vec> = crumbs.iter().enumerate().map(|(i, (_, _, name))| Entry::new(i, name.clone())).collect(); let mut nav: Option<(&str, serde_json::Value)> = None; let mut pattern_cmd: Option<&str> = None; @@ -237,7 +256,7 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(area)); Bar::new(tl!("Isolation mode"), BarKind::Options).show(&mut bar_ui, |ui, _| { Row::new().fill().senses_surface().show(ui, |ui, cx| { - if IconButton::new(craft::behavior::IconId::new("chevron_left")).label(tl!("Back")).show(ui).clicked() { + if IconButton::new(craft::behavior::IconId::new("chevron_left")).label(back_name).show(ui).clicked() { if pattern_edit.is_some() { pattern_cmd = Some("object.pattern.done"); } else { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 532c6ffef0..63935c2863 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -500,6 +500,59 @@ fn german_script_status_preserves_authored_error_and_translates_native_error() { assert_eq!(app.session.script_authored_failure(), None); } +/// A plug-in run's notice shows in the status bar after the plug-in's name once its output is +/// applied: the words around it are translated and the notice itself never is, even when it reads +/// like one of the app's own messages. A run whose output is refused shows no notice, and the next +/// status message replaces the notice. +#[test] +fn plugin_notice_shows_after_the_plug_in_s_name_and_is_never_translated() { + use vectorcraft_plugins::wat as tpl; + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let install = |app: &mut crate::VectorcraftApp, id: &str, output: &str| { + let module = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), output)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module), "replace": true})).unwrap(); + }; + let id = "test.ui.notice"; + install(&mut app, id, r#"{"objects":[],"notice":"invalid array length"}"#); + let r = app.run("plugin.run", json!({"id": id})).unwrap(); + assert_eq!(r["notice"], json!("invalid array length")); + assert_eq!(app.ui.status, format!("Plug-in “Test {id}”: invalid array length")); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + assert_eq!(super::status_bar::status_message(&app), format!("Plug-in „Test {id}“: invalid array length")); + // The same words as an ordinary message are translated. + app.status("invalid array length"); + assert_eq!(super::status_bar::status_message(&app), "ungültige Array-Länge"); + crate::i18n::set_current(crate::i18n::Lang::EN); + // An output refused for its notice shows no notice. + let bad = "test.ui.notice.bad"; + install(&mut app, bad, r#"{"objects":[],"notice":"\u0007"}"#); + app.status(""); + assert!(app.run("plugin.run", json!({"id": bad})).is_err()); + assert!(!app.ui.status.starts_with("Plug-in “"), "{}", app.ui.status); + // A plug-in step of a batch, as an action plays it, shows its notice too. + app.status(""); + app.replay("command.batch", json!({"commands": [{"command": "plugin.run", "params": {"id": id}}, {"command": "select.none"}]})).unwrap(); + assert_eq!(app.ui.status, format!("Plug-in “Test {id}”: invalid array length")); + // A batch without a plug-in step leaves the status bar as it is. + app.status("kept"); + app.run("command.batch", json!({"commands": [{"command": "select.none"}]})).unwrap(); + assert_eq!(app.ui.status, "kept"); + // The notice keeps the plug-in's name when a later step of the batch removes the plug-in. + app.status(""); + let run_and_remove = json!({"commands": [{"command": "plugin.run", "params": {"id": id}}, {"command": "plugin.remove", "params": {"id": id}}]}); + app.run("command.batch", run_and_remove).unwrap(); + assert!(vectorcraft_plugins::registry::get(id).is_none()); + assert_eq!(app.ui.status, format!("Plug-in “Test {id}”: invalid array length")); + // A name's closing ellipsis is dropped, and a name that is only an ellipsis shows the plug-in's id. + for (name, shown) in [("Resize…", "Resize"), (" … ", id)] { + let r = json!({"plugin": id, "ids": [], "notice": "done", "pluginName": name}); + crate::plugin_runs::show_notice(&mut app, "plugin.run", &r); + assert_eq!(app.ui.status, format!("Plug-in “{shown}”: done")); + } + app.run("plugin.remove", json!({"id": bad})).unwrap(); +} + /// The message of an open that starts with a line about its linked files lists the open's notes on /// hover and for screen readers, in a wide and in a narrow window. A later message leaves the list /// out. @@ -663,6 +716,47 @@ fn the_status_bar_show_choice_is_checked_and_saved() { ); } +/// The status bar's Rotation box shows the view's angle: a preset angle shows its row's label, an angle between the +/// presets shows rounded to a whole degree, and a pick from the list still turns the view. +#[test] +fn the_status_bar_rotation_box_shows_the_view_angle() { + let mut bar = status_readout_app(); + let rotation = |bar: &mut Shown, angle: f64| { + bar.app().run("view.rotate", json!({ "angle": angle })).unwrap(); + let rotation = bar.settle().find("Rotation").unwrap_or_else(|| panic!("the status bar has the Rotation box")); + let value = bar.tree().value_of(rotation.node).map(str::to_owned); + (rotation, value) + }; + for (angle, shown) in [(17.0, "17°"), (37.4, "37°"), (-0.3, "0°"), (-122.6, "-123°")] { + let (_, value) = rotation(&mut bar, angle); + assert_eq!(value.as_deref(), Some(shown), "the box at {angle}°"); + assert!(bar.texts().iter().any(|t| t.text == shown), "the box draws {shown}"); + } + let (_, value) = rotation(&mut bar, 45.0); + assert_eq!(value.as_deref(), Some("45°")); + // From an angle between the presets, the list still turns the view to the row picked. + let (opener, _) = rotation(&mut bar, 17.0); + bar.click_on(&opener).settle(); + bar.click("-45°").settle(); + assert_eq!(bar.app().view().map(|v| v.rotation), Some(-45.0)); + let rotation = bar.find("Rotation").unwrap_or_else(|| panic!("the status bar has the Rotation box")); + assert_eq!(bar.tree().value_of(rotation.node), Some("-45°")); +} + +#[test] +fn the_status_bar_rotation_picker_requires_a_document_view() { + let mut bar = status_readout_app(); + bar.app().run("file.close", json!({})).unwrap(); + assert!(bar.app().view().is_none()); + bar.settle().click("Rotation").settle(); + assert!(bar.find("-45°").is_none(), "the picker stays closed without a view"); + + bar.app().run("file.new", json!({"width": 100, "height": 100})).unwrap(); + bar.settle().click("Rotation").settle(); + bar.click("-45°").settle(); + assert_eq!(bar.app().view().map(|v| v.rotation), Some(-45.0)); +} + /// While background work runs the status bar shows it where the message was, with the count of the jobs after the /// first, and the message of the work's result takes the same place when it ends. Screen readers find the progress. #[test] @@ -733,7 +827,8 @@ fn the_artboard_navigator_goes_to_artboards_and_fitting_shows_the_current_one() assert_eq!(at(&mut bar), (1, Point::new(320.0, 50.0))); bar.app().run("view.actualSize", json!({})).unwrap(); let center = at(&mut bar).1; - assert_eq!((center, bar.app().view().unwrap().zoom), (Point::new(320.0, 50.0), 1.0)); + let baseline = crate::state::zoom_baseline(bar.app().print_ppi()); + assert_eq!((center, bar.app().view().unwrap().zoom), (Point::new(320.0, 50.0), baseline)); bar.click("First Artboard"); assert_eq!(at(&mut bar), (0, Point::new(100.0, 50.0)), "first"); // The command also takes an index, clamped to the last artboard. @@ -752,6 +847,28 @@ fn set_zoom_100_matches_actual_size_with_display_print_size() { assert!((app.view().unwrap().zoom - 96.0 / 72.0).abs() < 1e-12); } +/// At UI Scaling 150% the zoom field shows the zoom `view.setZoom` set, and a zoom typed into it is the zoom the view +/// gets, as at 100%: 200% gives the view the zoom `view.setZoom` gives for 200%. +#[test] +fn the_zoom_field_sets_the_typed_zoom_at_any_ui_scaling() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.session.prefs.ui_scaling = 1.5; + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(460.0, 260.0)); + app.run("view.setZoom", json!({"zoom": 200})).unwrap(); + let wanted = app.view().unwrap().zoom; + app.run("view.setZoom", json!({"zoom": 100})).unwrap(); + let mut bar = crate::tests::panel_harness::Panel::new(app, super::status_bar); + assert!((bar.ctx().zoom_factor() - 1.5).abs() < 1e-6, "the interface is zoomed by UI Scaling"); + let shown = |bar: &crate::tests::panel_harness::Panel| bar.value("Zoom").unwrap_or_default(); + assert!(shown(&bar).starts_with("100"), "the field shows the zoom view.setZoom set: {}", shown(&bar)); + bar.type_into("Zoom", "200"); + let zoom = bar.app().view().unwrap().zoom; + assert!((zoom - wanted).abs() < 1e-9, "typing 200% gives the zoom of view.setZoom 200%: {zoom}, not {wanted}"); + assert!(shown(&bar).starts_with("200"), "the field shows the typed zoom: {}", shown(&bar)); +} + /// Read the painted coordinates while checking that drawing never changes the source /// position, document, selection or either branch of its edit history. fn assert_status_coordinates(bar: &mut Shown, expected: Option<&str>) { @@ -1085,7 +1202,7 @@ fn the_tab_title_names_the_opacity_mask_while_it_is_edited() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); - let title = |s: &Session| super::tab_title(s.active().unwrap(), 1.0, false, false); + let title = |s: &Session| super::tab_title(s.active().unwrap(), 1.0, false, None); assert!(title(&s).ends_with("(RGB/Preview)"), "{}", title(&s)); s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); assert!(title(&s).ends_with("(/Opacity Mask)"), "{}", title(&s)); @@ -1110,6 +1227,27 @@ fn control_shown(app: crate::VectorcraftApp) -> Shown { Shown::new(app, egui::vec2(1600.0, 300.0), super::control_bar) } +/// With the Circle tool, the Control bar shows From Center unchecked; a click on it turns the option on and checks +/// it, and a second click turns it off and unchecks it. +#[test] +fn the_circle_tool_s_from_center_checkbox_sets_the_option() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + app.select_tool("circle"); + let mut bar = control_shown(app); + let from_center = |bar: &Shown| bar.app().session.tool_options()["fromCenter"].clone(); + assert_eq!(from_center(&bar), json!(false)); + let target = bar.named("From Center"); + assert!(!bar.checked(&target), "From Center starts unchecked"); + for want in [true, false] { + bar.click("From Center").settle(); + assert_eq!(from_center(&bar), json!(want)); + let target = bar.named("From Center"); + assert_eq!(bar.checked(&target), want, "the checkbox shows the option"); + } +} + /// The Control bar's isolation button, if it shows: Isolate Selected Object, Exit Isolation Mode or Exit Symbol /// Editing Mode. fn isolation_button(bar: &mut Shown) -> Option { @@ -1153,9 +1291,28 @@ fn isolation_shown(app: crate::VectorcraftApp) -> Shown { /// A point on the isolation bar's own surface: right of its crumbs, at the end of the path, which fills the bar up /// to the pattern editing buttons at its right. fn isolation_bar_surface(bar: &mut Shown) -> egui::Pos2 { - let back = bar.named("Back"); let path = bar.named("Isolation path"); - egui::pos2(path.rect.right() - 8.0, back.center().y) + egui::pos2(path.rect.right() - 8.0, path.center().y) +} + +/// The names of the isolation bar's controls in the latest frame that screen readers read with `role`, sorted. +fn isolation_names(bar: &Shown, role: Role) -> Vec { + let tree = bar.tree(); + let mut names: Vec = + tree.keys().into_iter().filter(|key| tree.role_of(*key) == Some(role)).filter_map(|key| tree.name_of(key)).map(str::to_owned).collect(); + names.sort(); + names +} + +/// The isolation bar's back arrow: the leftmost button named `name`. +fn isolation_back(bar: &mut Shown, name: &str) -> Target { + bar.frame(Vec::new()); + let tree = bar.tree(); + let keys: Vec<_> = tree.keys().into_iter().filter(|key| tree.role_of(*key) == Some(Role::BUTTON) && tree.name_of(*key) == Some(name)).collect(); + keys.into_iter() + .filter_map(|key| bar.fixture.target(key)) + .min_by(|a, b| a.rect.left().total_cmp(&b.rect.left())) + .unwrap_or_else(|| panic!("no {name:?} button in {:?}", bar.names())) } /// #4468: In nested isolation, clicking the back button steps up one level in the hierarchy, @@ -1184,15 +1341,15 @@ fn isolation_bar_navigation_and_back_button_steps_up() { let isolation = |bar: &Shown| bar.app().session.active().unwrap().isolation; // Clicking back from `a` steps up to parent group `g1` - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(NodeId(g1))); // Clicking back from `g1` steps up to grandparent group `g2` - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(NodeId(g2))); // Clicking back from `g2` (parent is layer) exits isolation mode completely - bar.click("Back"); + bar.click("Exit Isolation Mode"); assert_eq!(isolation(&bar), None); // Deep isolate again to test clicking ancestor breadcrumb directly @@ -1231,11 +1388,11 @@ fn isolation_bar_back_button_steps_up_through_sublayers() { let steps = |bar: &Shown| bar.app().session.doc().unwrap().history.undo.len(); let before = steps(&bar); - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(mid), "back from the deepest sublayer"); - bar.click("Back"); + bar.click("Back One Level"); assert_eq!(isolation(&bar), Some(top), "back from the middle sublayer"); - bar.click("Back"); + bar.click("Exit Isolation Mode"); assert_eq!(isolation(&bar), None, "back from the top-level layer"); assert_eq!(steps(&bar), before, "no undo step"); @@ -1298,7 +1455,8 @@ fn isolation_bar_background_click_leaves_pattern_edit_open() { let st = app.session.active().unwrap(); assert!(st.doc.pattern_edit.is_some() && st.isolation.is_some(), "pattern editing stays open"); } - bar.click("Back"); + let back = isolation_back(&mut bar, "Done"); + bar.click_on(&back); let app = bar.app(); let st = app.session.active().unwrap(); assert!(st.doc.pattern_edit.is_none() && st.isolation.is_none(), "the back arrow ends pattern editing"); @@ -1382,6 +1540,72 @@ fn isolation_bar_click_on_the_current_name_exits() { assert_eq!(bar.app().session.active().unwrap().isolation, None); } +/// Screen readers call the isolation bar's back arrow by what it does: Back One Level, Exit Isolation Mode, Exit +/// Symbol Editing Mode, or Done while a pattern is edited, in the UI's language. Each crumb of the levels above is +/// a link with the name it shows, and the current object's name is not a control. +#[test] +fn the_isolation_bars_controls_have_screen_reader_names() { + use vectorcraft_doc::NodeId; + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let rect = |app: &mut crate::VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (rect(&mut app, 10.0), rect(&mut app, 50.0)); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + let name = |app: &crate::VectorcraftApp, id: NodeId| app.session.active().unwrap().doc.node(id).unwrap().display_name(); + let st = app.session.active().unwrap(); + let (layer, group) = (st.doc.layer_of(NodeId(a)).unwrap(), st.doc.parent_of(NodeId(a)).unwrap()); + let (layer_name, group_name) = (name(&app, layer), name(&app, group)); + let mut bar = isolation_shown(app); + let shown = |bar: &mut Shown, role: Role| { + bar.frame(Vec::new()); + isolation_names(bar, role) + }; + + // A path in a group: back goes to the group. + bar.app().run("object.isolate", json!({"id": a})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Back One Level"]); + let mut crumbs = vec![layer_name.clone(), group_name.clone()]; + crumbs.sort(); + assert_eq!(shown(&mut bar, Role::LINK), crumbs, "the current object's name is not a link"); + + // The group itself: back leaves isolation mode. + bar.app().run("object.isolate", json!({"id": group.0})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Isolation Mode"]); + assert_eq!(shown(&mut bar, Role::LINK), std::slice::from_ref(&layer_name)); + + // An isolated sublayer: back goes to its parent layer, and from the top-level layer it leaves. + let sub = bar.app().run("layer.newSublayer", json!({"parent": layer.0, "name": "Sublayer B"})).unwrap()["id"].as_u64().unwrap(); + bar.app().run("object.isolate", json!({"id": sub})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Back One Level"]); + bar.app().run("object.isolate", json!({"id": layer.0})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Isolation Mode"]); + bar.app().run("object.isolate", json!({"id": group.0})).unwrap(); + + // In German. + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let german = shown(&mut bar, Role::BUTTON); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(german, ["Isolationsmodus beenden"]); + bar.app().run("object.exitIsolation", json!({"all": true})).unwrap(); + + // Pattern editing: back is Done, beside Save a Copy, Done and Cancel. + let c = rect(&mut bar.app(), 200.0); + bar.app().run("select.set", json!({"ids": [c]})).unwrap(); + bar.app().run("object.pattern.make", json!({"name": "Dots", "width": 20, "height": 20})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Cancel", "Done", "Done", "Save a Copy"]); + bar.app().run("object.pattern.cancel", json!({})).unwrap(); + + // Symbol editing mode: back leaves it. + let d = rect(&mut bar.app(), 300.0); + bar.app().run("select.set", json!({"ids": [d]})).unwrap(); + bar.app().run("symbol.new", json!({"name": "Box"})).unwrap(); + bar.app().run("symbol.edit", json!({"name": "Box"})).unwrap(); + assert_eq!(shown(&mut bar, Role::BUTTON), ["Exit Symbol Editing Mode"]); +} + /// The Control bar's Isolate Selected Object isolates a path inside a group that Direct /// Selection selected, and Exit Isolation Mode leaves with the path selected. Type, symbol /// instances, blends, two objects and an envelope's contents get no isolate button, and pattern @@ -2476,6 +2700,26 @@ fn the_type_groups_leave_the_control_bar_before_opacity_and_style() { assert!(seen.iter().any(|s| s[2] && !s[0]), "some width shows Opacity without the Character group"); } +/// With type selected, the Paragraph group's Align left, Align center and Align right buttons leave the Control bar +/// before its Paragraph: link: some width shows the link without them, and no width shows them without the link. +#[test] +fn the_paragraph_link_stays_on_the_control_bar_after_its_align_buttons_leave() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let text = app.run("text.create", json!({"x": 10, "y": 100, "text": "Hi"})).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [text] })).unwrap(); + let mut bar = control_shown(app); + let names = ["Paragraph:", "Align left", "Align center", "Align right"]; + let seen = control_bar_widths(&mut bar, &names); + assert!(seen.iter().any(|s| s.iter().all(|shown| *shown)), "a wide bar shows {names:?}"); + for s in &seen { + assert!(s[1..].iter().all(|shown| *shown == s[1]), "the three Align buttons show or go together: {s:?}"); + assert!(!s[1] || s[0], "the Align buttons show only with the Paragraph: link: {s:?}"); + } + assert!(seen.iter().any(|s| s[0] && !s[1]), "some width shows the Paragraph: link without the Align buttons"); +} + /// With area type selected, its vertical alignment buttons leave the Control bar before Opacity and the Style group, /// and after the Align buttons that follow them, with the Character and Paragraph groups shown and with both off. #[test] @@ -2602,6 +2846,34 @@ fn the_anchor_points_group_holds_convert_and_anchors() { assert!(has(&bar, "Anchor Point") && has(&bar, "Stroke:"), "{bar:?}"); } +/// With three corners of a path Direct-Selected, the Control bar's Corners link opens the Corners +/// pop-up; a kind picked there sets those three corners and leaves the fourth, in one undo step. +#[test] +fn the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners() { + use vectorcraft_geom::shapes::CornerKind; + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("object.expandShape", json!({})).unwrap(); + app.select_tool("directSelection"); + app.run("select.anchors", json!({"id": id, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": "set"})).unwrap(); + let mut bar = crate::tests::panel_harness::Panel::new(app, crate::chrome::control_bar); + bar.room(egui::vec2(2400.0, 400.0)).frame(); + assert!(bar.shows("Corners") && !bar.shows("Chamfer"), "the pop-up starts closed"); + bar.click("Corners"); + for name in ["Round", "Inverted Round", "Chamfer", "Radius", "Relative", "Absolute"] { + assert!(bar.shows(name), "the pop-up has {name}"); + } + let depth = bar.app().session.doc().unwrap().history.undo.len(); + bar.click("Chamfer"); + assert_eq!(bar.app().session.doc().unwrap().history.undo.len(), depth + 1, "one undo step"); + let n = bar.app().session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone(); + let lc = vectorcraft_doc::LiveCorners::of(&n).unwrap(); + assert_eq!((0..4).map(|k| lc.kind(k)).collect::>(), [CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Chamfer, CornerKind::Round]); +} + /// With the Artboard tool in use, the Control bar shows the Align buttons after the artboard /// controls while it has room, and the Distribute buttons for two or more selected artboards with /// Align to Artboard and three or more with Align to Selection. A diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index b7914c350f..b550182214 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -171,6 +171,12 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { // The display profile the canvas is drawn through, or why none (Preferences › // Performance › Use Monitor Profile for Canvas). "displayProfile": app.display_profile.status(app.session.prefs.monitor_profile_display), + // With Preferences › General › Display Print Size at 100% Zoom on, the measured density of + // the main window's display in points per inch (null where none was measured), and the + // points an inch takes at 100% in the current window. Both are null with it off, when the + // desktop app does not measure the displays. + "screenPpi": app.session.prefs.display_print_size.then(|| app.services.screen_ppi.ppi()).flatten(), + "printPpi": app.print_ppi(), // Window › Arrange › Tile and its layout (not saved, so not in `ui`) and the panes the // last frame drew: each one's document index, view number (Window › New Window) and rect. // Canvas coordinates map to the current window's pane, inside its rulers and scroll bars @@ -1451,6 +1457,7 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val Some(Some("cancel")) => Some("ui.dialog.cancel"), Some(_) => return err("`action` must be confirm or cancel"), }; + let pdf = app.save_pdf.as_ref().map(|open| open.id).filter(|_| method == "ui.dialog.set"); let reply = dialogs.with(|host| { // The answer goes to the dialog the fields went to, even when setting them opens another over it. if answer.is_some() @@ -1459,9 +1466,18 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val { params["dialog"] = json!(top.id.value().to_string()); } + if method == "ui.dialog.set" + && let Ok(id) = craft::automation::dialogs::dialog_id(host, ¶ms) + { + crate::dialogs::effect::normalize_set_mode(app, id, &mut params); + } let sets = params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog")); let set = if answer.is_none() || sets { - craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms) + // A Save PDF settings object keeps the options it leaves out. + match pdf.and_then(|id| crate::dialogs::save_pdf::set_settings_objects(host, ctx, id, ¶ms)) { + Some(set) => Some(set.map(|()| Value::Null)), + None => craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms), + } } else { Some(Ok(Value::Null)) }; diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index fdda88b384..d267ab460e 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -4,7 +4,7 @@ use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; use craft::automation::{ControlRequest, Reply}; -use super::handle; +use super::{handle, inspect}; use crate::{Services, VectorcraftApp}; /// Whether a dialog is open on the app's window. @@ -785,7 +785,24 @@ fn the_method_table_routes_each_method_and_checks_its_params() { assert_eq!(after, before, "{id} {params}: nothing changes"); } app.run("view.setZoom", json!({"zoom": null, "center": null})).unwrap(); - assert_eq!(app.view().map(|v| v.zoom), Some(crate::state::zoom_from_display_percent(100.0, app.session.prefs.display_print_size))); + assert_eq!(app.view().map(|v| v.zoom), Some(crate::state::zoom_from_display_percent(100.0, app.print_ppi()))); +} + +/// `ui.inspect` gives the measured density of the main window's display and the points an inch +/// takes at 100% while Display Print Size at 100% Zoom is on, and neither with it off (#9051). +#[test] +fn inspect_reports_the_display_density() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let ctx = egui::Context::default(); + let got = inspect(&app, &ctx); + assert_eq!((got["screenPpi"].clone(), got["printPpi"].as_f64()), (Value::Null, Some(96.0)), "nothing measured: an inch is 96 points"); + app.set_screen_ppi(Some(127.0)); + let got = inspect(&app, &ctx); + assert_eq!((got["screenPpi"].as_f64(), got["printPpi"].as_f64()), (Some(127.0), Some(127.0))); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + let got = inspect(&app, &ctx); + assert_eq!((got["screenPpi"].clone(), got["printPpi"].clone()), (Value::Null, Value::Null)); } #[test] @@ -895,6 +912,7 @@ fn pointer_replies_name_the_key_object() { /// A Shape Builder click on a large selection merges on another thread: the frames go on, and /// the `ui.pointer` reply comes once the merge is applied, with the selection after it. +#[cfg(not(target_arch = "wasm32"))] #[test] fn pointer_reply_waits_for_a_merge_on_another_thread() { let (tx, rx) = std::sync::mpsc::channel(); @@ -916,8 +934,10 @@ fn pointer_reply_waits_for_a_merge_on_another_thread() { assert_eq!(hover.try_recv().unwrap()["ok"], true, "a hover is answered at once"); app.session.tool_poll(app.view_info(), true).unwrap(); let revision = app.session.active().unwrap().revision; + let mut merge = vectorcraft_tools::builder::testing::pause_next_merge().unwrap(); let click = send(&mut app, json!([{"kind": "down", "x": 15, "y": 10}, {"kind": "up", "x": 15, "y": 10}])); assert!(click.try_recv().is_err() && app.session.tool_editing(), "the click is not answered before the merge is applied"); + merge.wait_started().unwrap(); // A hover sent meanwhile is answered at once; a click is made after the merge, and its // reply waits until then. let hover = send(&mut app, json!([{"kind": "move", "x": 35, "y": 10}])); @@ -927,32 +947,20 @@ fn pointer_reply_waits_for_a_merge_on_another_thread() { assert!(press.try_recv().is_err(), "a Cmd-click during the merge waits for it"); let hover = send(&mut app, json!([{"kind": "move", "x": 45, "y": 10}])); assert_eq!(hover.try_recv().map(|r| r["ok"].clone()), Ok(json!(true)), "a hover after the held Cmd-click"); - let start = std::time::Instant::now(); - let reply = loop { - if let Ok(r) = click.try_recv() { - break r; - } - assert!(app.session.tool_editing(), "the merge is being computed until the reply goes"); - assert_eq!(app.session.active().unwrap().revision, revision); - assert!(start.elapsed() < std::time::Duration::from_secs(60), "no reply"); - std::thread::sleep(std::time::Duration::from_millis(2)); - // A frame: the canvas checks on the tool, then the replies are answered. - let r = app.session.tool_poll(app.view_info(), false); - crate::canvas::apply_requests(&mut app, r); - app.run_control(&ctx); - }; + assert!(app.session.tool_editing(), "the merge is being computed until the reply goes"); + assert_eq!(app.session.active().unwrap().revision, revision); + merge.release(); + let r = app.session.tool_poll(app.view_info(), true); + crate::canvas::apply_requests(&mut app, r); + app.run_control(&ctx); + let reply = click.try_recv().expect("the merge was applied before answering the click"); assert_eq!(reply["ok"], true, "{reply}"); assert_eq!(reply["result"]["selection"].as_array().map(Vec::len), Some(41), "{reply}: the selection after the merge"); assert_ne!(app.session.active().unwrap().revision, revision); - let press = loop { - if let Ok(r) = press.try_recv() { - break r; - } - assert!(start.elapsed() < std::time::Duration::from_secs(60), "no reply to the Cmd-click"); - let r = app.session.tool_poll(app.view_info(), false); - crate::canvas::apply_requests(&mut app, r); - app.run_control(&ctx); - }; + let r = app.session.tool_poll(app.view_info(), true); + crate::canvas::apply_requests(&mut app, r); + app.run_control(&ctx); + let press = press.try_recv().expect("the held Cmd-click was applied after the merge"); assert_eq!(press["result"]["selection"].as_array().map(Vec::len), Some(0), "{press}: the lent selection tool deselected after the merge"); assert_eq!(press["result"]["tool"], "shapeBuilder", "{press}"); } diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index 2b3f5c31d1..2f9c594ab7 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -39,10 +39,18 @@ pub static CURSOR_ICONS: AppIcons = AppIcons::new( /// Where the glyphs that start at the box's upper left have their tip, in the icon's 24-unit box. const TIP: Vec2 = Vec2::new(2.0, 2.0); -/// The tip of the glyphs that point down-left (a pipette, a brush, a bucket, a knife). -const LOWER_LEFT: Vec2 = Vec2::new(2.0, 22.0); +/// The pipette's sampling tip, at the box's lower left. +const PIPETTE_TIP: Vec2 = Vec2::new(2.0, 22.0); /// The middle of the Anchor Point caret's square. const CARET: Vec2 = Vec2::new(12.0, 6.0); +/// The blade's point of the knife, at the box's upper right. +const BLADE_POINT: Vec2 = Vec2::new(20.0, 4.0); +/// The bottom of the drop below the paint bucket. +const BUCKET_DROP: Vec2 = Vec2::new(20.0, 22.0); +/// The bottom of the drop beside the Live Paint diamond. +const DIAMOND_DROP: Vec2 = Vec2::new(20.0, 18.0); +/// The middle of the brush's bristle edge, at its lower left. +const BRISTLE_TIP: Vec2 = Vec2::new(6.0, 17.5); fn system(icon: CursorIcon) -> cb::Cursor { cb::Cursor::System(icon) @@ -111,7 +119,7 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor { Cursor::HandGrab => system(CursorIcon::Grabbing), Cursor::ZoomIn => PaintedCursor::zoom(false).into(), Cursor::ZoomOut => PaintedCursor::zoom(true).into(), - Cursor::Eyedropper => tool("pipette", LOWER_LEFT, None), + Cursor::Eyedropper => tool("pipette", PIPETTE_TIP, None), Cursor::NotAllowed => system(CursorIcon::NotAllowed), Cursor::Busy => system(CursorIcon::Progress), Cursor::AddStop => badged(CursorBadge::Add), @@ -136,10 +144,10 @@ pub fn tool_cursor(c: Cursor) -> cb::Cursor { Cursor::PencilContinue => marked(Crosshair, "cursor-mark-line-rising"), // Only the centre: the tool draws the tip's outline round it, at the zoom. Cursor::BlobBrush | Cursor::Eraser => PaintedCursor::circle(1.25).into(), - Cursor::Knife => tool("dc-knife", LOWER_LEFT, None), - Cursor::LivePaintBucket => tool("paint-bucket", LOWER_LEFT, None), - Cursor::LivePaintBucketFace => tool("dc-live-bucket", LOWER_LEFT, None), - Cursor::LivePaintBucketEdge => tool("paintbrush", LOWER_LEFT, None), + Cursor::Knife => tool("dc-knife", BLADE_POINT, None), + Cursor::LivePaintBucket => tool("paint-bucket", BUCKET_DROP, None), + Cursor::LivePaintBucketFace => tool("dc-live-bucket", DIAMOND_DROP, None), + Cursor::LivePaintBucketEdge => tool("paintbrush", BRISTLE_TIP, None), Cursor::LivePaintSelectFace => marked(Arrow, "cursor-mark-square"), Cursor::LivePaintSelectEdge => marked(Arrow, "cursor-mark-edge"), Cursor::LivePaintSelectOutside => marked(Arrow, "x"), diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index 68357f6b65..c3e9fc92e4 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -10,6 +10,41 @@ fn every_tool_cursors_hotspot_lies_inside_its_icon_box() { } } +/// A click lands where the glyph points: in every painted tool cursor's image, the icon's own +/// mark color (not only its halo) covers the hotspot pixel or one next to it. +#[test] +fn every_tool_cursors_hotspot_is_on_its_glyph() { + use craft::ui::primitives::{painted_image, register_app_icons}; + use craft::ui::runtime::env::Env; + use craft::ui::style::rgba_color; + register_app_icons(&crate::icons::APP_ICONS); + register_app_icons(&CURSOR_ICONS); + let mut missed = Vec::new(); + crate::testing::ui_context() + .run_ui(Default::default(), |ui| { + let env = Env::of(ui); + let ink = rgba_color(env.tokens.tokens().color.overlay.stroke); + let near_ink = |px: &[u8]| px[3] == 255 && [ink.r(), ink.g(), ink.b()].iter().zip(px).all(|(want, got)| want.abs_diff(*got) <= 8); + for c in GLYPHS { + let cb::Cursor::Painted(painted @ PaintedCursor::Tool { .. }) = tool_cursor(c) else { continue }; + let Some(image) = painted_image(&env, &painted, 2.0) else { + missed.push(format!("{c:?}: no image")); + continue; + }; + let ([w, h], [hx, hy]) = (image.size.map(usize::from), image.hotspot.map(usize::from)); + let on_glyph = (hy.saturating_sub(1)..=(hy + 1).min(h - 1)) + .flat_map(|y| (hx.saturating_sub(1)..=(hx + 1).min(w - 1)).map(move |x| (y * w + x) * 4)) + .any(|i| near_ink(&image.rgba[i..i + 4])); + if !on_glyph { + missed.push(format!("{c:?}")); + } + } + }) + .textures_delta + .clear(); + assert!(missed.is_empty(), "hotspots off their glyphs: {missed:?}"); +} + /// A `cursor-` icon name a cursor uses must be in the set the host registers. #[test] fn every_cursor_icon_the_app_names_is_in_its_set() { diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index 9a89308e38..b1d1c3b356 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -23,7 +23,7 @@ use std::collections::BTreeSet; use craft::behavior::IconId; -use craft::behavior::dock::{Action, DockEdge}; +use craft::behavior::dock::{Action, DockEdge, DockPlacement, Target}; use craft::ui::buttons::IconButton; use craft::ui::contract::{PopupKind, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::dialog::DialogResult; @@ -345,6 +345,133 @@ fn set_shown(app: &mut VectorcraftApp, name: &str, show: Option) -> Result Ok(show) } +// ---------- docking and floating ---------- + +/// The window edge and column index from that edge where `panel` docks; none while it floats or is hidden. +fn docked_at(ui: &UiState, panel: &str) -> Option<(DockEdge, usize)> { + panel_docking::column_of(panel_docking::layout_of(ui), panel).and_then(|(slot, _)| slot) +} + +/// The window edge toolbar panel `panel` docks at: while docked, its edge; while it floats or is +/// hidden, the edge of the docked panel the dock records it left; else the left edge. +fn last_edge(ui: &UiState, panel: &str) -> DockEdge { + let ws = &ui.dock_workspace; + let left = ws.floated().iter().chain(ws.hidden()).find(|(p, _)| p == panel).and_then(|(_, at)| at.anchor.as_deref()); + docked_at(ui, panel).or_else(|| left.and_then(|anchor| docked_at(ui, anchor))).map_or(DockEdge::Start, |(edge, _)| edge) +} + +/// The `side` param's name of `edge`. +fn side_name(edge: DockEdge) -> &'static str { + if edge == DockEdge::End { "right" } else { "left" } +} + +/// Where toolbar `bar` is: `{toolbar, floating, side, order, pos}`, as `window.toolbar.dock` and +/// `window.toolbar.float` return it. +fn placement(app: &VectorcraftApp, bar: &str) -> Result { + let b = find(&app.ui, bar).ok_or_else(|| format!("no toolbar named `{bar}`"))?; + let panel = panel_id(b.id); + let docked = docked_at(&app.ui, &panel); + let pos = panel_docking::floating_window(panel_docking::layout_of(&app.ui), &panel).map(|w| [w.rect.min.x, w.rect.min.y]); + Ok(json!({ + "toolbar": b.name, + "floating": docked.is_none(), + "side": side_name(last_edge(&app.ui, &panel)), + "order": docked.map(|(_, n)| n), + "pos": pos, + })) +} + +/// `window.toolbar.dock`: docks the toolbar named `name` as a column of the dock on the `side` edge +/// (omitted: [`last_edge`]), at column `order` from the window edge (omitted: the innermost, or where it +/// is when it docks at that edge already). Bad params are errors and change nothing. +fn dock(app: &mut VectorcraftApp, p: &Value) -> Result { + let name = p.get("name").and_then(Value::as_str).ok_or("name (a toolbar's name) is required")?; + let bar = find(&app.ui, name).ok_or_else(|| format!("no toolbar named `{name}`"))?; + let (id, panel, name) = (bar.id, panel_id(bar.id), bar.name.clone()); + let edge = match p.get("side") { + None | Some(Value::Null) => last_edge(&app.ui, &panel), + // `Start` and `End`, as panels take them, too. + Some(Value::String(s)) if s.eq_ignore_ascii_case("left") || s.eq_ignore_ascii_case("start") => DockEdge::Start, + Some(Value::String(s)) if s.eq_ignore_ascii_case("right") || s.eq_ignore_ascii_case("end") => DockEdge::End, + Some(Value::String(s)) => return Err(format!("side is left or right, not `{s}`")), + Some(v) => return Err(format!("side is left or right, not `{v}`")), + }; + // A panel of each other column of that edge's dock, from the window edge inwards. + let others: Vec = panel_docking::edge_columns(panel_docking::layout_of(&app.ui), edge) + .iter() + .filter(|c| !c.panels().any(|q| *q == panel)) + .filter_map(|c| c.panels().next().cloned()) + .collect(); + let order = match p.get("order") { + None | Some(Value::Null) => None, + Some(v) => match v.as_u64().and_then(|n| usize::try_from(n).ok()).filter(|&n| n <= others.len()) { + Some(n) => Some(n), + None => return Err(format!("order is a whole number from 0 to {}, not `{v}`", others.len())), + }, + }; + let here = docked_at(&app.ui, &panel).filter(|(e, _)| *e == edge).map(|(_, n)| n); + if here.is_none() { + // A new innermost column of that edge's dock; a hidden toolbar shows. + let hidden = !panel_docking::layout_of(&app.ui).contains(&panel); + app.run("window.panel.dock", json!({ "panel": panel, "side": if edge == DockEdge::End { "End" } else { "Start" } }))?; + shown_again(app, id, hidden); + } + let now = docked_at(&app.ui, &panel).map(|(_, n)| n); + if let Some(n) = order.filter(|n| Some(*n) != now) { + let to = match others.get(n) { + Some(anchor) => Target::at(anchor.clone(), DockPlacement::column(false)), + None => match others.last() { + Some(last) => Target::at(last.clone(), DockPlacement::column(true)), + None => return placement(app, &name), + }, + }; + let ctx = app.ui_ctx.clone(); + panel_docking::apply(app, ctx.as_ref(), vec![Action::move_panel(panel, to)])?; + } + // A toolbar where it was asked to go shows too, which ends a Tab hide. + panel_docking::show_panels(app); + placement(app, &name) +} + +/// `window.toolbar.float`: floats the toolbar named `name` with its top-left corner at `x`, `y` in +/// window points (both or neither; neither: where the dock floats a panel, and a floating toolbar +/// stays where it is). +fn float(app: &mut VectorcraftApp, p: &Value) -> Result { + let name = p.get("name").and_then(Value::as_str).ok_or("name (a toolbar's name) is required")?; + let bar = find(&app.ui, name).ok_or_else(|| format!("no toolbar named `{name}`"))?; + let (id, panel, name) = (bar.id, panel_id(bar.id), bar.name.clone()); + let coord = |k: &str| match p.get(k) { + None | Some(Value::Null) => Some(None), + Some(v) => v.as_f64().filter(|f| f.abs() <= 1e6).map(|f| Some(f as f32)), + }; + let at = match (coord("x"), coord("y")) { + (Some(Some(x)), Some(Some(y))) => Some(pos2(x, y)), + (Some(None), Some(None)) => None, + _ => return Err("x and y must both be numbers from -1000000 to 1000000".into()), + }; + let window = panel_docking::floating_window(panel_docking::layout_of(&app.ui), &panel).map(|w| w.rect); + let hidden = !panel_docking::layout_of(&app.ui).contains(&panel); + match (at, window) { + (Some(at), _) => panel_docking::place_floating(app, &panel, at, window.map_or(0.0, |r| r.width()))?, + (None, None) => { + app.run("window.panel.float", json!({ "panel": panel }))?; + } + (None, Some(_)) => {} + } + shown_again(app, id, hidden); + // A toolbar floating already shows too, which ends a Tab hide. + panel_docking::show_panels(app); + placement(app, &name) +} + +/// After a command showed toolbar `id`, which was `hidden`, the groups torn off it show again, as +/// Show Toolbar brings them back. +fn shown_again(app: &mut VectorcraftApp, id: u32, hidden: bool) { + if hidden && panel_docking::layout_of(&app.ui).contains(&panel_id(id)) { + crate::toolbar::strips_follow(app, &Owner::Toolbar(id), true); + } +} + /// Opens New Toolbar: a name box whose OK is held while the name is refused, the refusal shown under /// the row. fn open_new(app: &mut VectorcraftApp) -> Result<(), String> { @@ -464,6 +591,8 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option dock(app, p), + "window.toolbar.float" => float(app, p), "window.toolbar.list" => { let layout = panel_docking::layout_of(&app.ui); Ok(json!( @@ -474,7 +603,6 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option>().len(), MAX, "every toolbar has an id of its own"); } + + /// A hidden toolbar that `window.toolbar.dock` or `window.toolbar.float` shows brings back the + /// group torn off it, as Show Toolbar does. + #[test] + fn docking_or_floating_a_hidden_toolbar_brings_back_its_torn_off_group() { + let mut app = app(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Mine"})).unwrap(); + app.run("toolbar.addTool", json!({"tool": "curvature", "toolbar": "Mine", "slot": 0, "place": "group"})).unwrap(); + app.run("window.floatTools", json!({"tool": "pen", "toolbar": "Mine"})).unwrap(); + let id = find(&app.ui, "Mine").unwrap().id; + let strip = strip_id(&Owner::Toolbar(id), "pen"); + let on = |app: &VectorcraftApp| panel_docking::layout_of(&app.ui).contains(&strip); + assert!(on(&app)); + for (command, params) in [ + ("window.toolbar.dock", json!({"name": "Mine"})), + ("window.toolbar.float", json!({"name": "Mine"})), + ("window.toolbar.float", json!({"name": "Mine", "x": 40, "y": 50})), + ] { + app.run("window.toolbar.custom", json!({"name": "Mine", "show": false})).unwrap(); + assert!(!on(&app), "the strip hides with its toolbar"); + app.run(command, params.clone()).unwrap(); + assert!(panel_docking::layout_of(&app.ui).contains(&panel_id(id)), "{command} {params} shows the toolbar"); + assert!(on(&app), "{command} {params} brings the strip back"); + } + } + + /// The dock layout, to compare. + fn layout(app: &VectorcraftApp) -> Value { + serde_json::to_value(panel_docking::layout_of(&app.ui)).unwrap() + } + + /// Where the toolbar named `name` docks: its edge and column from that edge (none: floating). + fn dock_place(app: &VectorcraftApp, name: &str) -> Option<(DockEdge, usize)> { + docked_at(&app.ui, &panel_id(find(&app.ui, name).unwrap().id)) + } + + /// `window.toolbar.dock` docks a toolbar at an edge, innermost or at the column asked for, and + /// `window.toolbar.float` floats it, at x, y when given; bad params and a toolbar already where + /// it is asked to go change nothing, and `window.toolbar.list` reports the same places. + #[test] + fn toolbars_dock_and_float_by_their_commands() { + let mut app = app(); + for name in ["A", "B", "C"] { + app.run("window.toolbar.new", json!({ "name": name })).unwrap(); + } + assert_eq!(dock_place(&app, "A"), None, "New Toolbar floats"); + let undo = app.session.doc().map_or(0, |d| d.history.undo.len()); + let r = app.run("window.toolbar.dock", json!({"name": "a"})).unwrap(); + assert_eq!((&r["toolbar"], &r["floating"], &r["side"], &r["pos"]), (&json!("A"), &json!(false), &json!("left"), &Value::Null)); + let (edge, a) = dock_place(&app, "A").unwrap(); + assert_eq!(edge, DockEdge::Start); + assert_eq!(r["order"], json!(a)); + // Each one docked after it goes inside it; one asked to go at A's column goes outside it. + app.run("window.toolbar.dock", json!({"name": "B", "side": "left"})).unwrap(); + let b = dock_place(&app, "B").unwrap().1; + assert!(b > dock_place(&app, "A").unwrap().1, "B docks inside A"); + let at_a = dock_place(&app, "A").unwrap().1; + app.run("window.toolbar.dock", json!({"name": "C", "side": "start", "order": at_a})).unwrap(); + let [c, a, b] = ["C", "A", "B"].map(|n| dock_place(&app, n).unwrap().1); + assert!(c < a && a < b, "C goes outside A: {c} {a} {b}"); + // Docked again at the edge it docks at, with no column asked for, nothing changes. + let before = layout(&app); + app.run("window.toolbar.dock", json!({"name": "A"})).unwrap(); + app.run("window.toolbar.dock", json!({"name": "A", "side": "left", "order": a})).unwrap(); + assert_eq!(layout(&app), before); + // Bad params are errors and change nothing. + let columns = panel_docking::edge_columns(panel_docking::layout_of(&app.ui), DockEdge::Start).len(); + for p in [ + json!({"name": "A", "side": "top"}), + json!({"name": "A", "side": 1}), + json!({"name": "A", "order": columns}), + json!({"name": "A", "order": -1}), + json!({"name": "A", "order": 0.5}), + json!({"name": "A", "order": "1"}), + json!({"name": "Nope"}), + json!({}), + ] { + assert!(app.run("window.toolbar.dock", p.clone()).is_err(), "{p}"); + } + for p in [ + json!({"name": "A", "x": 10}), + json!({"name": "A", "x": 1e7, "y": 0}), + json!({"name": "A", "x": "1", "y": 2}), + json!({"name": "Nope"}), + json!({}), + ] { + assert!(app.run("window.toolbar.float", p.clone()).is_err(), "{p}"); + } + assert_eq!(layout(&app), before); + // The innermost column asked for: A moves inside B. + app.run("window.toolbar.dock", json!({"name": "A", "order": columns - 1})).unwrap(); + assert!(dock_place(&app, "A").unwrap().1 > dock_place(&app, "B").unwrap().1); + // At the right edge. + let r = app.run("window.toolbar.dock", json!({"name": "A", "side": "RIGHT"})).unwrap(); + assert_eq!(r["side"], json!("right")); + assert_eq!(dock_place(&app, "A").map(|(e, _)| e), Some(DockEdge::End)); + // Floated, it remembers the right edge, and docks there again. + let r = app.run("window.toolbar.float", json!({"name": "A"})).unwrap(); + assert_eq!((&r["floating"], &r["side"], &r["order"]), (&json!(true), &json!("right"), &Value::Null)); + assert!(r["pos"].is_array()); + let listed = app.run("window.toolbar.list", json!({})).unwrap(); + let a_row = listed.as_array().unwrap().iter().find(|t| t["name"] == "A").unwrap().clone(); + assert_eq!((&a_row["floating"], &a_row["side"]), (&json!(true), &json!("right"))); + // Floating already, with no x, y: it stays where it is. + let before = layout(&app); + app.run("window.toolbar.float", json!({"name": "A"})).unwrap(); + assert_eq!(layout(&app), before); + let r = app.run("window.toolbar.float", json!({"name": "A", "x": 300, "y": 200})).unwrap(); + assert_eq!(r["pos"], json!([300.0, 200.0])); + assert_eq!(app.run("window.toolbar.dock", json!({"name": "A"})).unwrap()["side"], json!("right")); + // A hidden toolbar shows where it is docked or floated to. + app.run("window.toolbar.custom", json!({"name": "B", "show": false})).unwrap(); + app.run("window.toolbar.float", json!({"name": "B", "x": 50, "y": 60})).unwrap(); + assert!(panel_docking::floating_window(panel_docking::layout_of(&app.ui), &panel_id(find(&app.ui, "B").unwrap().id)).is_some()); + // Neither command records an undo step. + assert_eq!(app.session.doc().map_or(0, |d| d.history.undo.len()), undo); + } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 7ce5c83baa..6fcff63221 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -28,6 +28,7 @@ pub(crate) mod command; pub mod composite_fonts; pub mod confirm; pub mod corners; +pub mod curvature_circle_options; pub mod custom_dictionary; pub mod dimension; mod document_setup; @@ -117,6 +118,7 @@ mod psd_options; pub mod raster_effects; pub mod rearrange_artboards; pub mod recolor; +pub mod recolor_preset; pub mod relink; pub mod rename_artboards; pub(crate) mod revolve; diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 705913d428..4b2b79a02d 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -8,6 +8,7 @@ //! empty, or Data Sets without a document, is an error and the dialog stays open. use std::hash::Hash; +use std::sync::Arc; use craft::automation::actions::Action; use craft::host::PickRequest; @@ -131,6 +132,8 @@ pub(crate) enum Folder { /// The Batch dialog on the dialog host. pub struct BatchDialog { id: DialogId, + /// Identifies this opening even when another Batch dialog reuses `id`. + folder_owner: Arc<()>, /// The index of the action's set. pub set: usize, /// The index of the action in its set. @@ -150,13 +153,13 @@ impl BatchDialog { &self.form.values } - /// The Browse presses since the last call. - pub(crate) fn take_asked(&mut self) -> Vec { - std::mem::take(&mut self.asked) + /// The Browse presses since the last call and the opening that made them. + pub(crate) fn take_asked(&mut self) -> (Arc<()>, Vec) { + (self.folder_owner.clone(), std::mem::take(&mut self.asked)) } /// Writes the folder the picker answered into its row. - pub(crate) fn set_folder(&mut self, which: Folder, path: String) { + fn set_folder(&mut self, which: Folder, path: String) { match which { Folder::Source => self.form.values.folder = path, Folder::Destination => self.form.values.destination_folder = path, @@ -176,6 +179,7 @@ pub fn open(app: &mut VectorcraftApp, set: usize, action: usize) -> Result, which: Folder) { let title = match which { Folder::Source => crate::i18n::t("Source Folder"), Folder::Destination => crate::i18n::t("Destination Folder"), @@ -218,10 +222,9 @@ pub(crate) fn ask_folder(app: &mut VectorcraftApp, which: Folder) { if let Some(path) = picked.paths().first() && let Some(dialogs) = app.dialogs() { - let path = path.to_string_lossy().into_owned(); dialogs.with(|host| { - if let Some(dialog) = host.get_mut::() { - dialog.set_folder(which, path); + if let Some(dialog) = host.get_mut::().filter(|d| Arc::ptr_eq(&d.folder_owner, &owner)) { + dialog.set_folder(which, path.to_string_lossy().into_owned()); } }); } @@ -437,6 +440,44 @@ mod tests { }); } + #[test] + fn batch_folder_answers_belong_to_the_dialog_that_asked() { + let step = ActionStep::new("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})); + let mut app = app_with(vec![step]); + let picker = crate::tests::picks::scripted(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let request_folders = |app: &mut VectorcraftApp| { + dialogs.with(|host| host.get_mut::().unwrap().asked.extend([Folder::Source, Folder::Destination])); + pump(app, &ctx); + }; + let folders = || { + dialogs.with(|host| { + let fields = host.get::().unwrap().fields(); + (fields.folder.clone(), fields.destination_folder.clone()) + }) + }; + let answer = |app: &mut VectorcraftApp, source: &str, destination: &str| { + picker.answer(&[destination]); + picker.answer(&[source]); + file_asks::poll(app); + }; + + open(&mut app, 0, 0).unwrap(); + request_folders(&mut app); + assert_eq!(picker.requests().len(), 2); + dialogs.with(|host| host.cancel::(&ctx)); + open(&mut app, 0, 0).unwrap(); + set_fields(&app, &[("folder", json!("new-source")), ("destinationFolder", json!("new-destination"))]); + answer(&mut app, "old-source", "old-destination"); + assert_eq!(folders(), ("new-source".into(), "new-destination".into())); + + request_folders(&mut app); + assert_eq!(picker.requests().len(), 4); + answer(&mut app, "picked-source", "picked-destination"); + assert_eq!(folders(), ("picked-source".into(), "picked-destination".into())); + } + /// Batch plays an action recorded with a key its command no longer reads, as Play does. #[test] fn an_action_with_a_key_no_longer_read_still_plays_in_a_batch() { diff --git a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs index acb6065d7a..9f8ae5af95 100644 --- a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs +++ b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs @@ -19,6 +19,7 @@ use craft::ui::display::{Shade, Text}; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::Row as Line; use craft::ui::list::{List, ListRow}; +use craft::ui::primitives::Revision; use craft::ui::runtime::env::Label; use craft::ui::text::TextField; use egui::{Context, Ui}; @@ -258,6 +259,7 @@ impl StackDialog for InsertMenuItemDialog { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let rows = &self.rows; + let rows_key = self.key; self.form.show(ui, label("Insert Menu Item"), None, |ui, fields| { FieldGroup::new(label("Insert Menu Item")).show(ui, |ui, _| { let before = fields.find.clone(); @@ -284,16 +286,18 @@ impl StackDialog for InsertMenuItemDialog { } let listed: Vec<&Row> = matches(rows, &fields.find).take(MAX_LISTED).collect(); let texts: Vec = listed.iter().map(|row| row.shown.clone()).collect(); - let lead = listed.iter().position(|row| picked(fields, row)); - let mut selection = lead.map_or_else(Selection::default, Selection::single); + let selected = listed.iter().position(|row| picked(fields, row)); + let mut selection = selected.map_or_else(Selection::default, Selection::single); List::::new(label("Menu Items")) .select(SelectMode::Single) + .rows_stamp(Revision::of(&(rows_key, &fields.find, selected)).get()) .selection(Bind::bound(&mut selection)) .sizing(Sizing::Content) .max_rows(8) .show_items(ui, &Listed(&texts), &mut |key, _| ListRow::new(texts.get(*key).cloned().unwrap_or_default())); - if selection.lead != lead - && let Some(row) = selection.lead.and_then(|at| listed.get(at)) + let chosen = selection.items.first().copied(); + if chosen != selected + && let Some(row) = chosen.and_then(|at| listed.get(at)) { pick(fields, row); } @@ -336,10 +340,13 @@ impl StackDialog for InsertMenuItemDialog { #[cfg(test)] mod tests { + use craft::automation::actions::Action; use craft::menu::Node; + use egui::{Key, Modifiers}; use super::*; use crate::dialogs::actions::pump; + use crate::tests::panel_harness::Panel; fn fields(find: &str, command: &str) -> InsertMenuItemFields { InsertMenuItemFields { find: find.into(), command: command.into(), ..InsertMenuItemFields::default() } @@ -359,6 +366,61 @@ mod tests { assert_eq!((f.note, f.command.as_str()), (FindNote::NoMatch, "object.ungroup"), "a failed Find keeps the pick"); } + #[test] + fn arrow_navigation_inserts_the_command_after_the_selected_filtered_result() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.ui.actions = Default::default(); + app.ui.actions.push(Action { set: Some("Test".into()), ..Action::new("View", Vec::new()) }).unwrap(); + let available = build(Lang::EN, true, &menus::Listed::default()); + let fit_params = available.iter().find(|row| row.command == "view.fitArtboard").unwrap().params.clone(); + let rows = [ + ("view.zoomIn", "First command", "first command"), + ("view.zoomOut", "Second command", "remaining commands"), + ("view.fitArtboard", "Third command", "remaining commands"), + ("view.outline", "Fourth command", "remaining commands"), + ] + .into_iter() + .map(|(command, shown, haystack)| Row { + command: command.into(), + params: available.iter().find(|row| row.command == command).unwrap().params.clone(), + shown: shown.into(), + haystack: haystack.into(), + }) + .collect(); + let mut panel = Panel::new(app, |app, ui| app.dialogs().unwrap().with(|host| host.run(ui))); + let dialog = InsertMenuItemDialog { + id: dialog_id(KEY), + target: Target::new(Some((0, 0)), None), + form: Form::new(InsertMenuItemFields::default(), check), + rows, + key: None, + }; + open_or_say(&mut panel.app(), dialog); + panel.frame(); + panel.frame(); + + let dialogs = panel.app().dialogs().unwrap(); + let command = || dialogs.with(|host| host.get::().unwrap().form.values.command.clone()); + panel.click("First command"); + assert_eq!(command(), "view.zoomIn"); + dialogs.with(|host| { + host.set_json_field(panel.ctx(), dialog_id(KEY), "find", json!("remaining")).unwrap(); + host.set_json_field(panel.ctx(), dialog_id(KEY), "command", json!("view.fitArtboard")).unwrap(); + host.set_json_field(panel.ctx(), dialog_id(KEY), "params", fit_params).unwrap(); + }); + panel.frame(); + assert!(!panel.shows("First command")); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(command(), "view.outline"); + panel.click(tl!("OK")); + let mut app = panel.app(); + pump(&mut app, panel.ctx()); + let steps = &app.ui.actions.action(0).unwrap().steps; + assert_eq!(steps.len(), 1); + assert_eq!(steps[0].command, "view.outline"); + } + /// The list holds the menu items that run an engine command, and the View menu items that the /// app runs itself, without asking for values first, outside the application, File, Window and /// Help menus, and leaves out Undo, Redo, the Pastes, Image Trace's Make and Make and Expand, diff --git a/crates/ui-egui/src/dialogs/actions.rs b/crates/ui-egui/src/dialogs/actions.rs index 7d52338be2..8a6de85fe4 100644 --- a/crates/ui-egui/src/dialogs/actions.rs +++ b/crates/ui-egui/src/dialogs/actions.rs @@ -363,13 +363,13 @@ fn push_app_data(app: &VectorcraftApp) { } } -/// The folder picks the open Batch dialog asked for: each goes to the app's folder request, whose -/// answer is written into the dialog. +/// Files the folder picks the Batch dialog asked for with the identity of that opening. fn ask_batch_folders(app: &mut VectorcraftApp) { let Some(dialogs) = app.dialogs() else { return }; - let asked = dialogs.with(|host| host.get_mut::().map(BatchDialog::take_asked).unwrap_or_default()); - for which in asked { - super::action_batch::ask_folder(app, which); + let asked = dialogs.with(|host| host.get_mut::().map(BatchDialog::take_asked)); + let Some((owner, folders)) = asked else { return }; + for which in folders { + super::action_batch::ask_folder(app, owner.clone(), which); } } diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index b49ab8d83f..cb1c6337e5 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -137,8 +137,7 @@ impl ArtboardOptionsValue { } } -/// What the dialog shows but does not edit; read from the app when it opens, since a modal dialog's -/// document, presets and preferences cannot change while it is open. +/// What the dialog shows but does not edit, read from the app when it opens. struct Setup { /// The lengths the fields keep and show. lengths: LengthUnits, @@ -152,9 +151,17 @@ struct Setup { fit_bounds: [Option; 2], } +#[derive(Clone, Copy)] +struct Target { + document: u64, + /// The current artboard's ID, or no ID while creating a new artboard. + artboard: Option, +} + /// Artboard Options on the dialog host: the artboard's value, the held OK and the color requests. pub struct ArtboardOptionsDialog { id: DialogId, + target: Target, value: ArtboardOptionsValue, setup: Setup, held: HeldAnswer, @@ -162,8 +169,8 @@ pub struct ArtboardOptionsDialog { } impl ArtboardOptionsDialog { - fn new(value: ArtboardOptionsValue, setup: Setup) -> Self { - ArtboardOptionsDialog { id: dialog_id(KIND), value, setup, held: HeldAnswer::new(), requests: HostRequests::new() } + fn new(target: Target, value: ArtboardOptionsValue, setup: Setup) -> Self { + ArtboardOptionsDialog { id: dialog_id(KIND), target, value, setup, held: HeldAnswer::new(), requests: HostRequests::new() } } } @@ -546,13 +553,15 @@ pub(crate) fn active_index(app: &VectorcraftApp) -> usize { /// Opens the dialog over `value`, with the preferences, the shared reference point and what the dialog /// shows read from the app. -fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue) -> Result { +fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue, artboard: Option) -> Result { let host = app.dialogs().ok_or("no window")?; + let st = app.session.active().ok_or("no document")?; + let target = Target { document: st.uid, artboard }; + let artwork = vectorcraft_render::encode::art_bounds(&st.doc); let [(_, fade), (_, update_while_dragging)] = global_fields(app); (value.fade, value.update_while_dragging, value.reference) = (fade, update_while_dragging, app.ui.transform_panel.reference_point); let fills = fill_colors(app); value.seed_customs(&fills); - let artwork = app.session.active().and_then(|st| vectorcraft_render::encode::art_bounds(&st.doc)); let setup = Setup { lengths: crate::canvas::rulers::general_lengths(app), origin: app.ruler_origin(), @@ -560,7 +569,7 @@ fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue) -> Result< fills, fit_bounds: [artwork, app.selection_bounds()], }; - host.with(|h| h.open(ArtboardOptionsDialog::new(value, setup))); + host.with(|h| h.open(ArtboardOptionsDialog::new(target, value, setup))); Ok(json!({ "dialog": KIND })) } @@ -569,6 +578,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let index = active_index(app); let st = app.session.active().ok_or("no document")?; let a = st.doc.artboards.get(index).ok_or("no artboard")?; + let artboard = a.id; let r = a.rect; let value = ArtboardOptionsValue { index, @@ -585,7 +595,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { pixel_aspect: a.video_ruler_pixel_aspect_ratio, ..Default::default() }; - present(app, value) + present(app, value, Some(artboard)) } /// `ui.newArtboard` (Alt-click on the Artboards panel's New Artboard): Artboard Options for a new @@ -605,7 +615,7 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result { pixel_aspect: 1.0, ..Default::default() }; - present(app, value) + present(app, value, None) } /// Runs once per frame after the shell pass: runs the artboard command of a filed OK and answers it @@ -613,12 +623,15 @@ pub fn open_new(app: &mut VectorcraftApp) -> Result { /// point picked in the dialog. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(host) = app.dialogs() else { return }; - let Some((held, reference)) = host.with(|h| h.get_mut::().map(|d| (d.held.take(), d.value.reference))) else { return }; + let Some((target, held, reference)) = host.with(|h| h.get_mut::().map(|d| (d.target, d.held.take(), d.value.reference))) + else { + return; + }; if app.ui.transform_panel.reference_point != reference { app.ui.transform_panel.reference_point = reference; } if let Some(value) = held { - let answer = confirm(app, &value).map(drop).map_err(Label::from); + let answer = confirm(app, target, &value).map(drop).map_err(Label::from); host.with(|h| { if let Some(d) = h.get_mut::() { d.held.answer(answer); @@ -633,21 +646,28 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { /// used (its column and row), all in one undo step. Fitting applies only to this artboard and never /// moves its artwork. The Global checkboxes' preferences are set only after the artboard command /// succeeds, so an error leaves them as they were. -fn confirm(app: &mut VectorcraftApp, v: &ArtboardOptionsValue) -> Result { +fn confirm(app: &mut VectorcraftApp, target: Target, v: &ArtboardOptionsValue) -> Result { + let st = app + .session + .active() + .filter(|st| st.uid == target.document) + .ok_or(tl!("Artboard Options can only change the document where it was opened."))?; let globals = global_changes(app, v); if v.new { let r = confirm_new(app, v)?; set_globals(app, globals)?; return Ok(r); } - let p = v.params(); - let was = app.session.active().and_then(|st| st.doc.artboards.get(v.index)).map(|a| a.rect); - let changed = |k: &str, old: Option| p[k].as_f64().filter(|n| old.is_some_and(|old| (n - old).abs() > 1e-6)); - let (w, h) = (changed("width", was.map(|r| r.width())), changed("height", was.map(|r| r.height()))); + let (index, board) = + st.doc.artboards.iter().enumerate().find(|(_, board)| Some(board.id) == target.artboard).ok_or(tl!("This artboard was removed."))?; + let mut p = v.params(); + p["index"] = json!(index); + let changed = |k: &str, old: f64| p[k].as_f64().filter(|n| (n - old).abs() > 1e-6); + let (w, h) = (changed("width", board.rect.width()), changed("height", board.rect.height())); let refi = v.ref_y.min(2) * 3 + v.ref_x.min(2); let mut entries = vec![]; if !v.fit && (v.size_choice.is_some() || w.is_some() || h.is_some()) { - for i in crate::panels::artboards::resized_with(app, v.index).into_iter().filter(|i| *i != v.index) { + for i in crate::panels::artboards::resized_with(app, index).into_iter().filter(|i| *i != index) { if let Some(r) = app.session.active().and_then(|st| st.doc.artboards.get(i)).map(|a| a.rect) { let (w, h) = if let Some(choice) = v.size_choice { let Some((w, h)) = choice.size_for(r.width(), r.height()) else { continue }; @@ -753,6 +773,69 @@ mod tests { app.session.doc().unwrap().history.undo.len() } + #[test] + fn confirmation_follows_the_original_artboard_after_reorder() { + let mut app = app(); + app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 50})).unwrap(); + crate::panels::artboards::select(&mut app, 0); + let original = app.session.active().unwrap().doc.artboards[0].id; + open(&mut app).unwrap(); + set(&app, &[("name", json!("Renamed"))]).unwrap(); + + app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.artboards[1].id, original); + let undo = undo_len(&app); + ok(&mut app).unwrap(); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!((artboards[0].name.as_str(), artboards[1].name.as_str()), ("Artboard 2", "Renamed")); + assert_eq!(undo_len(&app), undo + 1); + } + + #[test] + fn confirmation_refuses_to_edit_or_add_artboards_in_another_document() { + for create in [false, true] { + let mut app = app(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + if create { + open_new(&mut app).unwrap(); + } else { + open(&mut app).unwrap(); + } + set(&app, &[("name", json!("Source"))]).unwrap(); + + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = undo_len(&app); + let answer = ok(&mut app); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!((artboards.len(), artboards[0].name.as_str()), (1, "Artboard 1")); + assert_eq!(undo_len(&app), undo); + assert!(answer.is_err() && is_open(&app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + ok(&mut app).unwrap(); + let artboards = &app.session.active().unwrap().doc.artboards; + assert_eq!(artboards.len(), if create { 2 } else { 1 }); + assert_eq!(artboards.last().unwrap().name, "Source"); + } + } + + #[test] + fn confirmation_refuses_to_edit_a_deleted_artboards_replacement() { + let mut app = app(); + app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 50})).unwrap(); + crate::panels::artboards::select(&mut app, 0); + open(&mut app).unwrap(); + set(&app, &[("name", json!("Renamed"))]).unwrap(); + + app.run("artboard.delete", json!({"index": 0})).unwrap(); + let undo = undo_len(&app); + let answer = ok(&mut app); + assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Artboard 2"); + assert_eq!(undo_len(&app), undo); + assert!(answer.is_err() && is_open(&app)); + } + /// A new X moves the art only with Move Artwork with Artboard on, and Undo restores the document. #[test] fn position_moves_art_only_with_the_tool_option_on() { diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index 13261028e5..3bb0d3c8c8 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -528,13 +528,18 @@ fn art_rows(object: bool) -> Vec { rows } -/// The direction of the art along the stroke: a segment per direction in [`DIRECTIONS`] order. +/// The direction of the art along the stroke: an arrow segment per direction in [`DIRECTIONS`] order, +/// named by its tooltip. fn direction_row() -> Param { - // PLAN: the arrows are text until sh.S5's `APP_ICONS` names its arrow icons (with the tooltips Left to Right, Right to Left, Top to Bottom, Bottom to Top); a screen reader reads each segment as its glyph. - let arrows = ["→", "←", "↓", "↑"]; + let arrows = [ + ("dc-arrow-right", tl!("Left to Right")), + ("dc-arrow-left", tl!("Right to Left")), + ("dc-arrow-down", tl!("Top to Bottom")), + ("dc-arrow-up", tl!("Bottom to Top")), + ]; Param::custom("direction", tl!("Direction"), move |ui, f, _| { let current = DIRECTIONS.iter().position(|d| *d == parse_field::(f, "direction")).unwrap_or(0); - let entries: Vec> = arrows.iter().enumerate().map(|(i, arrow)| Entry::new(i, *arrow)).collect(); + let entries: Vec> = arrows.iter().enumerate().map(|(i, (icon, tip))| Entry::new(i, *tip).icon(IconId::new(icon))).collect(); let shown = Segmented::new(tl!("Direction"), Bind::given(current), &entries).show(ui); if let Some(dir) = shown.value().and_then(|i| DIRECTIONS.get(*i)) { f.set("direction", id_of(dir)); diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 0f2db21d46..34e11865cf 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -278,6 +278,26 @@ fn ok_redraws_the_strokes_painted_with_the_brush() { assert!((drawn_height(&app, id) - before).abs() < 1e-6); } +/// Art Brush Options draws each Direction segment as an arrow icon named by its tooltip, so the +/// accessibility tree reads the direction instead of an arrow glyph. +#[test] +fn art_brush_direction_segments_are_named_by_their_tooltips() { + let mut app = app(); + open(&mut app, "Arrow"); + crate::dialogs::tests::settle(&mut app); + let out = crate::dialogs::tests::frame(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + // Segmented gives each segment the radio button role. + let segments: Vec<&str> = + nodes.iter().filter(|(_, node)| node.role() == egui::accesskit::Role::RadioButton).filter_map(|(_, node)| node.label()).collect(); + for tip in ["Left to Right", "Right to Left", "Top to Bottom", "Bottom to Top"] { + assert!(segments.contains(&tip), "no segment is named {tip} in {segments:?}"); + } + for glyph in ["→", "←", "↓", "↑"] { + assert!(!segments.contains(&glyph), "a segment is named {glyph}"); + } +} + #[test] fn a_taken_name_keeps_the_dialog_open() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/color_group_options.rs b/crates/ui-egui/src/dialogs/color_group_options.rs index 859d7752f6..36fab4b2a1 100644 --- a/crates/ui-egui/src/dialogs/color_group_options.rs +++ b/crates/ui-egui/src/dialogs/color_group_options.rs @@ -32,7 +32,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let key = "group"; let group = match p.get(key) { Some(Value::String(g)) => g.clone(), - None | Some(Value::Null) => crate::panels::swatches::sole_selected_group(app).ok_or("missing `group`")?, + None | Some(Value::Null) => { + crate::panels::swatches::sole_selected_group(app).ok_or("select a color group in the Swatches panel, or pass group")? + } Some(_) => return Err(format!("`{key}` must be a string")), }; let st = app.session.active().ok_or("no document open")?; diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index af1b318728..e0ad66addf 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -6,7 +6,8 @@ //! `artboard.setProps {index, color}`. //! //! A command dialog's colour row raises a `ColorRequest`; [`pump`] opens a picker over that dialog -//! and answers the row with its OK. The OK for a Save for Web colour table cell shifts the cell's +//! and answers the row with its OK. Every picker has the Color Swatches view; one over Recolor +//! Artwork shows the library that Limit to Library limits to. The OK for a Save for Web colour table cell shifts the cell's //! colour in the table instead ([`super::save_for_web::take_palette_pick`]). //! //! Fields agents set with `ui.dialog.set`: the framework picker's (`color`, `mode`, `webColors`, @@ -104,7 +105,7 @@ pub(crate) fn open_picker(app: &VectorcraftApp) -> Option { /// The document's swatches and the swatch libraries as the picker's Color Swatches view: solid /// colours only, tints as their colour. -fn swatch_view(app: &VectorcraftApp) -> PickerSwatches { +pub(crate) fn swatch_view(app: &VectorcraftApp) -> PickerSwatches { let solid = |swatches: &[vectorcraft_color::Swatch]| -> Vec<(Label, Srgba)> { swatches.iter().filter_map(|s| Some((Label::from(s.name.clone()), srgba(&s.paint.color()?)))).collect() }; @@ -124,6 +125,15 @@ fn swatch_view(app: &VectorcraftApp) -> PickerSwatches { PickerSwatches::new(libraries, tl!("Open a document to see its swatches.")) } +/// The index in [`swatch_view`]'s libraries of the library a Limit to Library key names +/// (`"document"` or a library id); `None` when the view does not list it. +fn library_index(app: &VectorcraftApp, limit: &str) -> Option { + if limit == swatchlib::DOCUMENT_SWATCHES { + return Some(0); + } + colour_libraries(app).iter().position(|lib| lib.id == limit).map(|i| i + 1) +} + /// The working CMYK profile as the picker's CMYK converter, so its CMYK fields follow the document's /// inks; `None` (the picker's built-in coated CMYK) when the profile can't link to sRGB. fn working_cmyk() -> Option { @@ -204,8 +214,20 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { while let Some((parent, request)) = dialogs.with(|h| h.take_color_request()) { let start = request.color.unwrap_or(Srgba { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }); let key = request.key.clone(); - let child = ColorPickerDialog::from_request(request).eyedropper(true).add_to_swatches(false).gamut(gamut(app)).working_rgb(WorkingRgb); + let library = super::recolor::limit_to(&dialogs, parent).and_then(|limit| library_index(app, &limit)); + let child = ColorPickerDialog::from_request(request) + .eyedropper(true) + .add_to_swatches(false) + .gamut(gamut(app)) + .working_rgb(WorkingRgb) + .swatch_view(swatch_view(app)); let id = dialogs.with(|h| h.open_child(child, parent)); + // Over Recolor Artwork, the swatches view shows the library that Limit to Library limits to. + if let Some(i) = library + && let Err(e) = dialogs.with(|h| h.set_json_field(ctx, id, "library", json!(i))) + { + app.status(e); + } app.color_dialogs.pickers.push(Open { id, target: Target::Answer { parent, key }, start, keep: false, preview: LivePreview::default() }); } let busy = app.screen_pick.busy(); diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 97965e26dc..46d2a44802 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -44,6 +44,8 @@ struct Open { preview: LivePreview, /// Set Role Swatch: the role the Swatch row was last filled for. filled_for: Option, + /// The uid of the document whose objects the dialog opened on (`__doc`), for Set Fold Angle. + doc: Option, /// Names this dialog's own open among reopenings of the same command, for its OK and Cancel. token: Arc<()>, } @@ -66,7 +68,8 @@ impl Setting { } /// Opens the parameter dialog of `command`, headed `label`, on `params` (a menu item's own values, `__params` for the -/// fixed ones and `__rowGutterLinked` for Area Type Options' linked Row Gutter). +/// fixed ones, `__rowGutterLinked` for Area Type Options' linked Row Gutter and `__doc` for the uid of the document +/// whose objects the dialog edits). pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut params: Map) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; if let Some(old) = app.command_dialog.open.take() { @@ -77,6 +80,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par _ => Map::new(), }; let linked = params.remove("__rowGutterLinked").and_then(|v| v.as_f64()); + let doc = params.remove("__doc").and_then(|v| v.as_u64()); params.retain(|k, _| !k.starts_with("__")); let previews = previews(command, ¶ms); let setting = Setting::of(app); @@ -104,6 +108,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par previews, preview: LivePreview::default(), filled_for: None, + doc, token, }); Ok(Value::Null) @@ -162,9 +167,14 @@ fn step(app: &mut VectorcraftApp, open: &mut Open) { } /// OK: runs the command on the dialog's values (keeping a preview as the one undo step) and closes the dialog; an -/// error keeps it open with the reason under its rows. +/// error keeps it open with the reason under its rows. A dialog opened on one document's objects (`__doc`, its uid) +/// closes as Cancel does and runs nothing once another document is the active one. fn confirm(app: &mut VectorcraftApp, token: &Arc<()>, fields: &DialogFields) -> Result { let open = app.command_dialog.open.take_if(|o| Arc::ptr_eq(&o.token, token)).ok_or("the dialog is gone")?; + if open.doc.is_some() && open.doc != app.session.active().map(|st| st.uid) { + open.preview.cancel(app); + return Ok(Value::Null); + } let params = command_params(&open.command, &open.opening, Setting::of(app)); let value = call(&open.command, &open.fixed, open.linked, form::json_of(¶ms, fields)); let result = if open.previews { @@ -222,7 +232,17 @@ fn row(command: &str, key: &str, value: &Value, setting: Setting) -> Option Param::new(key, label, ParamKind::bool(*on)), Value::Number(n) => { let whole = n.is_i64() || n.is_u64(); - let mut param = Param::number(key, label, n.as_f64().unwrap_or(0.0), 1.0, if whole { 0 } else { 3 }); + let range = number_range(command, key); + // A ranged number (a fold angle) is shown to every place it keeps. + let decimals = match range { + Some(_) => u32::try_from(crate::addons::packaging::angle_places(n.as_f64())).unwrap_or(u32::MAX), + None if whole => 0, + None => 3, + }; + let mut param = Param::number(key, label, n.as_f64().unwrap_or(0.0), 1.0, decimals); + if let Some(range) = range { + param = param.bounds(Some(*range.start()), Some(*range.end())); + } if lengths(command).contains(&key) { param = param.length(setting.units); if let Some(range) = length_range(command, key) { @@ -358,6 +378,15 @@ pub(crate) fn length_range(command: &str, key: &str) -> Option Option> { + match (command, key) { + (crate::addons::packaging::SET_FOLD_ANGLE, "angle") => Some(crate::addons::packaging::FOLD_ANGLES), + _ => None, + } +} + /// The order the fields of the commands this dialog edits come in, where the order of their /// names isn't it (the rest follow, by name). fn order(command: &str) -> &'static [&'static str] { @@ -781,4 +810,134 @@ mod tests { } } } + + use crate::addons::packaging::{SET_FOLD_ANGLE, SET_ROLE}; + + /// A window app with two rectangles, `a` a crease and `b` a cut line, nothing selected → (app, a, b). + fn fold_lines() -> (VectorcraftApp, u64, u64) { + let mut app = windowed(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let rect = |app: &mut VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (rect(&mut app, 20.0), rect(&mut app, 100.0)); + app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap(); + app.run(SET_ROLE, json!({"role": "cut", "ids": [b]})).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app, a, b) + } + + /// The angle the open Set Fold Angle… dialog shows. + fn shown_angle(app: &VectorcraftApp) -> Option { + let id = id_of(app); + app.dialogs().unwrap().with(|h| h.get_by_id::(id).and_then(|d| d.fields().number("angle"))) + } + + /// Set Fold Angle… from its menu item → the angle its dialog opens on, the dialog then canceled; `None` when no + /// dialog opens. + fn opened_angle(app: &mut VectorcraftApp) -> Option { + crate::menus::invoke(app, SET_FOLD_ANGLE, json!({})); + app.command_dialog.open.as_ref()?; + pump(app); + let angle = shown_angle(app); + answer_cancel(app); + angle + } + + /// The angle the selection's fold lines fold at, after selecting `id`. + fn fold_angle(app: &mut VectorcraftApp, id: u64) -> Option { + app.run("select.set", json!({"ids": [id]})).unwrap(); + vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle + } + + #[test] + fn set_fold_angle_opens_its_dialog_on_the_selected_lines_angle() { + let (mut app, a, b) = fold_lines(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + assert_eq!(opened_angle(&mut app), Some(90.0), "a crease folds at 90° until it has an angle of its own"); + app.run(SET_FOLD_ANGLE, json!({"angle": 45})).unwrap(); + assert_eq!(opened_angle(&mut app), Some(45.0)); + // The cut line does not fold, so the crease's angle is still the one shown. + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + assert_eq!(opened_angle(&mut app), Some(45.0)); + // Lines that differ open on 90°. + let c = app.run("shape.rectangle", json!({"x": 180, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run(SET_ROLE, json!({"role": "partialCut", "ids": [c]})).unwrap(); + app.run("select.set", json!({"ids": [a, c]})).unwrap(); + assert_eq!(opened_angle(&mut app), Some(90.0)); + // With only a cut line selected there is nothing to set: no dialog opens, and ui.menuDialog gives the reason. + app.run("select.set", json!({"ids": [b]})).unwrap(); + assert_eq!(opened_angle(&mut app), None); + assert!(app.command_dialog.open.is_none()); + let e = app.run("ui.menuDialog", json!({"command": SET_FOLD_ANGLE})).unwrap_err(); + assert!(e.contains("select a crease, partial cut or perforation line"), "{e}"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("ui.menuDialog", json!({"command": SET_FOLD_ANGLE})).unwrap(); + pump(&mut app); + assert_eq!(shown_angle(&app), Some(45.0)); + answer_cancel(&mut app); + // The options dialog opened with an angle keeps it. + crate::menus::invoke(&mut app, "ui.paramDialog", json!({"command": SET_FOLD_ANGLE, "label": "Set Fold Angle", "params": {"angle": 30}})); + pump(&mut app); + assert_eq!(shown_angle(&app), Some(30.0)); + } + + /// Set Fold Angle…'s OK changes the lines the dialog opened on, even when the selection changes while it is open + /// (a remote command can change it): the other crease keeps its angle. + #[test] + fn set_fold_angle_s_ok_changes_the_lines_the_dialog_opened_on() { + let (mut app, a, b) = fold_lines(); + app.run(SET_ROLE, json!({"role": "crease", "ids": [b]})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + crate::menus::invoke(&mut app, SET_FOLD_ANGLE, json!({})); + pump(&mut app); + app.run("select.set", json!({"ids": [b]})).unwrap(); + set(&mut app, "angle", json!(30.0)); + answer_ok(&mut app); + assert!(app.command_dialog.open.is_none(), "OK closes the dialog"); + assert_eq!(fold_angle(&mut app, a), Some(30.0), "the line the dialog opened on"); + assert_eq!(fold_angle(&mut app, b), Some(90.0), "the line selected later keeps its role's angle"); + } + + /// Set Fold Angle…'s OK changes nothing once another document is the active one, even a line there with the same + /// id as the line the dialog opened on. + #[test] + fn set_fold_angle_s_ok_changes_nothing_in_another_document() { + let (mut app, a, _) = fold_lines(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + crate::menus::invoke(&mut app, SET_FOLD_ANGLE, json!({})); + pump(&mut app); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let other = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(other, a, "the same id in the other document"); + app.run(SET_ROLE, json!({"role": "crease", "ids": [other]})).unwrap(); + set(&mut app, "angle", json!(30.0)); + answer_ok(&mut app); + assert!(app.command_dialog.open.is_none(), "OK closes the dialog"); + assert_eq!(fold_angle(&mut app, other), Some(90.0), "the other document's line keeps its role's angle"); + assert!(app.session.set_active(0)); + assert_eq!(fold_angle(&mut app, a), Some(90.0), "the first document's line is left as it was"); + } + + /// Set Fold Angle…'s Angle row takes -180° to 180°, the range the command takes, and shows every place the angle + /// it opens on has. + #[test] + fn set_fold_angle_s_angle_row_keeps_the_commands_range() { + let (mut app, a, _) = fold_lines(); + app.run(SET_FOLD_ANGLE, json!({"angle": 179.999999, "ids": [a]})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let param = row(SET_FOLD_ANGLE, "angle", &json!(179.999999), Setting::of(&app)).expect("a row"); + match param.kind { + ParamKind::Number { min, max, decimals, .. } => assert_eq!((min, max, decimals), (Some(-180.0), Some(180.0), 6)), + _ => panic!("a number row"), + } + crate::menus::invoke(&mut app, SET_FOLD_ANGLE, json!({})); + pump(&mut app); + assert_eq!(shown_angle(&app), Some(179.999999)); + let (ctx, id) = (app.ui_ctx.clone().unwrap(), id_of(&app)); + assert!(app.dialogs().unwrap().with(|h| h.set_json_field(&ctx, id, "angle", json!(181))).is_err(), "past the range"); + set(&mut app, "angle", json!(-180)); + answer_ok(&mut app); + assert_eq!(fold_angle(&mut app, a), Some(-180.0)); + } } diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 9584166098..72fb9a40a6 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -7,6 +7,7 @@ use craft::ui::dialog::{Alert, DialogHost, DialogId, DialogResult, HostedAlert, PromptChoice, StackDialog, StandardPrompt, StartupStage}; use egui::Context; use serde_json::{Value, json}; +use vectorcraft_engine::file_access::ScopeHandle; use crate::VectorcraftApp; @@ -81,16 +82,25 @@ macro_rules! wrapped_dialog { } pub(crate) use wrapped_dialog; -/// A confirmation: its tag is the command OK runs and that command's params. +/// A confirmation: its tag is an [`Asked`]. pub(crate) struct Question(StandardPrompt); + +/// The tag of a confirmation ([`ask`]): the command OK runs, and the access it runs under. +struct Asked { + command: String, + params: Value, + /// The automation roots in force when asked: the command runs under them. + scope: ScopeHandle, + /// Automation asked ([`VectorcraftApp::automation_asked`]): the command runs as automation. + automated: bool, +} wrapped_dialog!(Question, StandardPrompt, KIND); /// A message with a Close button. pub(crate) struct Message(HostedAlert); wrapped_dialog!(Message, HostedAlert, MESSAGE); -/// The Type tool's question whether to edit type set in fonts that aren't available; its tag is the -/// tool's edit token. +/// The Type tool's question whether to edit type set in fonts that aren't available. pub(crate) struct MissingFontQuestion(StandardPrompt); wrapped_dialog!(MissingFontQuestion, StandardPrompt, MISSING_FONT_EDIT); @@ -110,6 +120,10 @@ pub(crate) struct ReplaceFiles { pub(crate) command: String, /// Its params. pub(crate) params: Value, + /// The automation roots in force when asked: the command runs again under them. + pub(crate) scope: ScopeHandle, + /// Automation asked ([`VectorcraftApp::automation_asked`]): the command runs again as automation. + pub(crate) automated: bool, } /// Ask `message` (with an optional `detail` line), both in the UI language; OK runs `command` @@ -123,7 +137,8 @@ pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, if !detail.is_empty() { prompt = prompt.paragraph(detail.to_string()); } - let prompt = prompt.button(PromptChoice::Proceed, tl!("OK")).button(PromptChoice::Cancel, tl!("Cancel")).tag((command.to_string(), params)); + let asked = Asked { command: command.to_string(), params, scope: ScopeHandle::capture(), automated: app.automation_asked() }; + let prompt = prompt.button(PromptChoice::Proceed, tl!("OK")).button(PromptChoice::Cancel, tl!("Cancel")).tag(asked); dialogs.with(|host| host.open(Question(prompt))); } @@ -184,6 +199,8 @@ pub(crate) fn ask_replace_files(app: &mut VectorcraftApp, doc: u64, files: &[Str allowed: allowed.to_vec(), command: command.to_string(), params, + scope: ScopeHandle::capture(), + automated: app.automation_asked(), }); // Asked when a Background Save or Export ends: a dialog open then stays, and this waits its turn // (however many messages wait: the save or export needs the answer). @@ -197,13 +214,15 @@ pub(crate) fn ask_replace_files(app: &mut VectorcraftApp, doc: u64, files: &[Str /// While another dialog is open (a press sent with `ui.pointer` reaches the tool then), that dialog /// stays and the Type tool forgets the edit, as Cancel would. pub(crate) fn ask_missing_font_edit(app: &mut VectorcraftApp, p: &Value) { - let token = p.get("token").cloned().unwrap_or(Value::Null); + let Some(token) = p.get("token").and_then(Value::as_u64) else { + return; + }; let Some(dialogs) = app.dialogs() else { - answer_missing_font_edit(app, &token, false); + answer_missing_font_edit(app, token, false); return; }; if app.any_dialog_open() && !dialogs.with(|host| host.is_open::()) { - answer_missing_font_edit(app, &token, false); + answer_missing_font_edit(app, token, false); return; } let names = |k: &str| p.get(k).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect::>(); @@ -216,14 +235,18 @@ pub(crate) fn ask_missing_font_edit(app: &mut VectorcraftApp, p: &Value) { let prompt = StandardPrompt::custom(tl!("Edit type set in fonts that aren't available?")) .paragraph(detail) .button(PromptChoice::Proceed, tl!("OK")) - .button(PromptChoice::Cancel, tl!("Cancel")) - .tag(token); - dialogs.with(|host| host.open(MissingFontQuestion(prompt))); + .button(PromptChoice::Cancel, tl!("Cancel")); + dialogs.with(|host| { + host.open(MissingFontQuestion(prompt)); + // Replacing a prompt leaves its Cancel in the host. The tool is already waiting on the new token. + let _ = host.take::(); + }); + app.missing_font_edit_token = Some(token); } /// Give the Type tool the answer to [`ask_missing_font_edit`]'s question about the edit `token` /// names: with `ok` the edit starts at once; without, the tool forgets it. -pub(crate) fn answer_missing_font_edit(app: &mut VectorcraftApp, token: &Value, ok: bool) { +fn answer_missing_font_edit(app: &mut VectorcraftApp, token: u64, ok: bool) { app.session.set_tool_option("missingFontEdit", &json!({"token": token, "ok": ok})); if ok { let r = app.session.tool_poll(app.view_info(), false); @@ -240,8 +263,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { }; if let Some(DialogResult::Ok(mut answer)) = dialogs.with(|host| host.take::()) && answer.choice == PromptChoice::Proceed - && let Some((command, params)) = answer.take_tag::<(String, Value)>() - && let Err(e) = app.run(&command, params) + && let Some(Asked { command, params, scope, automated }) = answer.take_tag::() + && let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params))) { app.status(e); } @@ -259,13 +282,12 @@ pub(crate) fn pump_missing_font(app: &mut VectorcraftApp, _ctx: &Context) { let Some(dialogs) = app.dialogs() else { return; }; - let (ok, token) = match dialogs.with(|host| host.take::()) { - None => return, - Some(DialogResult::Ok(mut answer)) => (answer.choice == PromptChoice::Proceed, answer.take_tag::()), - // PLAN: a question the host cancelled carries no tag, so the tool's token is unknown here. - Some(_) => (false, None), - }; - answer_missing_font_edit(app, &token.unwrap_or(Value::Null), ok); + if let Some(result) = dialogs.with(|host| host.take::()) + && let Some(token) = app.missing_font_edit_token.take() + { + let ok = matches!(result, DialogResult::Ok(answer) if answer.choice == PromptChoice::Proceed); + answer_missing_font_edit(app, token, ok); + } } /// The confirmation open now, if one is: its message and detail as shown, and the command OK runs. @@ -273,8 +295,8 @@ pub(crate) fn pump_missing_font(app: &mut VectorcraftApp, _ctx: &Context) { pub(crate) fn open_question(app: &VectorcraftApp) -> Option<(String, String, String)> { app.dialogs()?.with(|host| { let prompt = &host.get::()?.0; - let (command, _) = prompt.tag_as::<(String, Value)>()?; - Some((prompt.shown_message(&app.host), prompt.shown_paragraphs(&app.host).join("\n"), command.clone())) + let asked = prompt.tag_as::()?; + Some((prompt.shown_message(&app.host), prompt.shown_paragraphs(&app.host).join("\n"), asked.command.clone())) }) } @@ -290,3 +312,13 @@ pub(crate) fn open_message(app: &VectorcraftApp) -> Option<(String, String)> { pub(crate) fn open_replace_files(app: &VectorcraftApp) -> Option> { app.dialogs()?.with(|host| host.get::().and_then(|q| q.0.tag_as::().map(|tag| tag.files.clone()))) } + +/// Whether the open question about replacing files runs its command confined to automation roots, +/// and whether as automation, while it is open. +#[cfg(test)] +pub(crate) fn open_replace_files_access(app: &VectorcraftApp) -> Option<(bool, bool)> { + app.dialogs()?.with(|host| { + let tag = host.get::()?.0.tag_as::()?; + Some((tag.scope.clone().run(vectorcraft_engine::file_access::current).is_some(), tag.automated)) + }) +} diff --git a/crates/ui-egui/src/dialogs/corners.rs b/crates/ui-egui/src/dialogs/corners.rs index 9c2a03ad10..6eb3d2702c 100644 --- a/crates/ui-egui/src/dialogs/corners.rs +++ b/crates/ui-egui/src/dialogs/corners.rs @@ -115,21 +115,51 @@ fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { if let Some(k) = f.text("kind") { p["kind"] = json!(k); } - if let Some(mut r) = f.number("radius") { - if relative { - let id = NodeId(json_field(f, "id").as_u64().unwrap_or(0)); - let st = app.session.active().ok_or("no document")?; - if let Some(lc) = st.doc.node(id).and_then(LiveCorners::of) { - let corners: BTreeSet = serde_json::from_value(json_field(f, "corners")).unwrap_or_default(); - if let Some(k) = corners.iter().next() { - let max = lc.corner(*k).map(|c| c.max_radius()).unwrap_or(0.0); - r = (r / 100.0).clamp(0.0, 1.0) * max; - } + let Some(r) = f.number("radius") else { + return app.run("object.setLiveShape", p).map(|_| ()); + }; + if !relative { + p["radius"] = json!(r); + return app.run("object.setLiveShape", p).map(|_| ()); + } + // Relative: the percentage is of each corner's own maximum, so corners with different + // maximums (a star's points and its inner corners) get different lengths. Corners of the + // same length share one `object.setLiveShape`; several run as one undo step. + let id = NodeId(json_field(f, "id").as_u64().unwrap_or(0)); + let st = app.session.active().ok_or("no document")?; + let mut lengths: Vec<(f64, Vec)> = vec![]; + if let Some(lc) = st.doc.node(id).and_then(LiveCorners::of) { + let corners: BTreeSet = serde_json::from_value(json_field(f, "corners")).unwrap_or_default(); + for k in corners { + let len = (r / 100.0).clamp(0.0, 1.0) * lc.corner(k).map(|c| c.max_radius()).unwrap_or(0.0); + match lengths.iter_mut().find(|(l, _)| (*l - len).abs() < 1e-9) { + Some((_, ks)) => ks.push(k), + None => lengths.push((len, vec![k])), } } - p["radius"] = json!(r); } - app.run("object.setLiveShape", p).map(|_| ()) + match &lengths[..] { + [] => { + p["radius"] = json!(r); + app.run("object.setLiveShape", p).map(|_| ()) + } + [(len, _)] => { + p["radius"] = json!(len); + app.run("object.setLiveShape", p).map(|_| ()) + } + _ => { + let commands: Vec = lengths + .iter() + .map(|(len, ks)| { + let mut step = p.clone(); + step["corners"] = json!(ks); + step["radius"] = json!(len); + json!({"command": "object.setLiveShape", "params": step}) + }) + .collect(); + app.run("command.batch", json!({"label": "Live Shape", "commands": commands})).map(|_| ()) + } + } } #[cfg(test)] @@ -277,4 +307,38 @@ mod tests { assert!(matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Path { .. }))); assert_eq!(crate::panels::corner_radius(&app, &n), Some(5.0)); } + + /// Relative rounding gives each corner the percentage of its own maximum: a star's point and + /// the inner corner beside it differ, and OK rounds both as one undo step. + #[test] + fn relative_radius_is_a_percentage_of_each_corners_own_maximum() { + let (mut app, _) = app(); + let id = app.run("shape.star", json!({"cx": 200, "cy": 200, "radius1": 60, "radius2": 30})).unwrap()["id"].as_u64().unwrap(); + app.run("object.setLiveShape", json!({"id": id, "radius": 1})).unwrap(); + let lc = |app: &VectorcraftApp| { + let n = app.session.active().unwrap().doc.node(NodeId(id)).unwrap().clone(); + let c = LiveCorners::of(&n).unwrap(); + (c.radii_relative(), c.radius(0), c.radius(1), c.corner(0).unwrap().max_radius(), c.corner(1).unwrap().max_radius()) + }; + let (_, _, _, max0, max1) = lc(&app); + assert!((max0 - max1).abs() > 1.0, "the corners' maximums differ: {max0} and {max1}"); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let n = steps(&app); + app.run("ui.corners", json!({"id": id, "corners": [0, 1]})).unwrap(); + set(&app, "radii", json!("relative")); + set(&app, "radius", json!(50)); + confirm(&mut app); + assert!(!is_open(&app)); + let (relative, f0, f1, _, _) = lc(&app); + assert!(relative); + assert!((f0 - 0.5).abs() < 1e-9 && (f1 - 0.5).abs() < 1e-9, "stored fractions: {f0} and {f1}"); + assert_eq!(steps(&app), n + 1, "one undo step"); + // The same values again change nothing and record no step. + app.run("ui.corners", json!({"id": id, "corners": [0, 1]})).unwrap(); + set(&app, "radius", json!(50)); + confirm(&mut app); + assert_eq!(steps(&app), n + 1); + app.run("edit.undo", json!({})).unwrap(); + assert!(!lc(&app).0, "undo brings back absolute radii"); + } } diff --git a/crates/ui-egui/src/dialogs/curvature_circle_options.rs b/crates/ui-egui/src/dialogs/curvature_circle_options.rs new file mode 100644 index 0000000000..7b0aecf47d --- /dev/null +++ b/crates/ui-egui/src/dialogs/curvature_circle_options.rs @@ -0,0 +1,84 @@ +//! Curvature Circle Tool Options (double-click the Curvature Circle tool, or `tool.options`): Snap +//! Tolerance is how near, in screen points, a path pulls the pointer (Smart Guides' Snapping +//! Tolerance applies when it is larger); with Snap with Smart Guides Off unchecked, the pointer +//! reaches no further than the selection tolerance while Smart Guides are off; Annotate Radius +//! off hides the radius label; Anchors at Standard Positions off gives the circle an anchor where +//! it touches the path and one every 90° from there; Use the Radius of Circular Arcs off gives the +//! curve's own curvature on the curve of a circular arc too. OK sets them with +//! `tool.setOption {tool: "curvatureCircle", values}`; they last across tool switches and are saved +//! with the preferences. + +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; +use craft::ui::runtime::env::UnitKind; +use serde_json::{Value, json}; +use vectorcraft_tools::curvature_circle::{DEFAULT_SNAP, ID as TOOL, SNAP_RANGE}; + +use super::{form, host, tool_options}; +use crate::VectorcraftApp; + +/// The dialog kind of Curvature Circle Tool Options. +pub const KIND: &str = "curvatureCircleOptions"; + +/// The switches the dialog edits, in the order it shows them, with their labels. +const SWITCHES: [(&str, &str); 4] = [ + ("snapWithoutGuides", "Snap with Smart Guides Off"), + ("annotateRadius", "Annotate Radius"), + ("standardAnchors", "Anchors at Standard Positions"), + ("constantRadius", "Use the Radius of Circular Arcs"), +]; + +/// The rows: Snap Tolerance, then the switches. +fn params() -> Vec { + let (min, max) = SNAP_RANGE; + let snap = Param::number("snapTolerance", tl!("Snap Tolerance:"), DEFAULT_SNAP, 1.0, 1).unit(UnitKind::Pixels).bounds(Some(min), Some(max)); + std::iter::once(snap).chain(SWITCHES.iter().map(|(key, label)| Param::new(*key, tl!(*label), ParamKind::bool(true)))).collect() +} + +/// Open the tool's options with their current values; an error when there is no window to show them in. +pub fn open(app: &mut VectorcraftApp) -> Result { + let params = params(); + let options = app.session.tool_options_of(TOOL); + let fields = options.as_object().map(|m| form::fields_of(¶ms, m)).unwrap_or_default(); + let (title, shown) = (tool_options::title(TOOL), params.clone()); + let ok = move |app: &mut VectorcraftApp, result: &ParamResult| tool_options::set_options(app, TOOL, form::json_of(¶ms, &result.fields)); + let opened = app.ui_ctx.clone().and_then(|ctx| { + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |f| ParamDialog::new(KIND, title.clone(), shown.clone()).values(Bind::bound(f))); + host::open_held(app, dialog, ok) + }); + if opened.is_none() { + let message = tl!("No window to show the dialog in.").to_string(); + app.status(message.clone()); + return Err(message); + } + Ok(json!({ "dialog": KIND })) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + /// `tool.setOption` takes only the values the options take, and an invalid one changes none. + #[test] + fn invalid_values_are_errors_and_change_nothing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + for values in [ + json!({"annotateRadius": false, "constantRadius": "no"}), + json!({"annotateRadius": false, "snapTolerance": 0}), + json!({"annotateRadius": false, "size": 3}), + ] { + assert!(app.run("tool.setOption", json!({"tool": TOOL, "values": values})).is_err(), "{values}"); + assert_eq!(app.session.tool_options_of(TOOL)["annotateRadius"], json!(true)); + } + } + + /// Without a window the dialog cannot open, and `tool.options` says so instead of reporting it open. + #[test] + fn without_a_window_opening_the_options_is_an_error() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + assert!(app.run("tool.options", json!({"tool": TOOL})).is_err()); + } +} diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index 805a502223..b53bab2351 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -718,7 +718,8 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) { && let Some(dialogs) = app.dialogs() { let key = request.key.clone(); - let picker = dialogs.with(|host| host.open(ColorPickerDialog::from_request(request))); + let picker = ColorPickerDialog::from_request(request).swatch_view(super::color_picker::swatch_view(app)); + let picker = dialogs.with(|host| host.open(picker)); app.object_dialogs.dimension = Some(Pick { id: picker, key, target: NodeId(id) }); } Row::new().show(ui, |ui, _| { diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 0d28e683a2..c3aa0ef099 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -73,7 +73,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields["rgbProfile"] = json!(rgb.unwrap_or_else(|| WORKING_RGB.into())); fields["cmykProfile"] = json!(cmyk.unwrap_or_else(|| WORKING_CMYK.into())); fields["convertColors"] = json!(true); - let (mode, setup) = (st.doc.color_mode, st.doc.setup.clone()); + let (source, mode, setup) = (st.uid, st.doc.color_mode, st.doc.setup.clone()); let Value::Object(map) = fields else { return Err("document.setup reported no settings".into()) }; let presets: Vec = app.session.flattener_presets().into_iter().map(|p| p.name).collect(); let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); @@ -82,6 +82,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { PropertiesDialog::new(KIND, tl!("Document Setup"), tabs.clone(), values) }); super::host::open_held(app, dialog, |app, fields| confirm(app, fields).map(|_| ())).ok_or("no window to show the dialog in")?; + app.document_setup_source = Some(source); Ok(Value::Null) } @@ -185,6 +186,9 @@ fn color_commands(app: &VectorcraftApp, fields: &Map) -> Result Result { + if app.session.active().is_none_or(|st| Some(st.uid) != app.document_setup_source) { + return Err(tl!("Document Setup can only change the document where it was opened.").to_owned()); + } let map = json_map(fields); let params = nest(map.iter().filter(|(k, _)| !is_ui_only(k)).map(|(k, v)| (k.clone(), v.clone())).collect()); let color = color_commands(app, &map)?; @@ -220,9 +224,12 @@ fn short_of_bleed_note(app: &VectorcraftApp, before: [f64; 4]) -> Option pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; let id = dialog_id(KIND); - let edit = dialogs.with(|host| { - host.get_by_id::(id).filter(|d| d.fields().bool("editArtboards") == Some(true)).map(|d| d.fields().clone()) - }); + let Some(edit) = dialogs.with(|host| { + host.get_by_id::(id).map(|d| (d.fields().bool("editArtboards") == Some(true)).then(|| d.fields().clone())) + }) else { + app.document_setup_source = None; + return; + }; if let Some(fields) = edit { match confirm(app, &fields) { Ok(_) => { @@ -389,7 +396,14 @@ fn grid_colors_row(setup: DocSetup) -> Param { picked = Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).value().cloned(); Row::new().show(ui, |ui, _| { for (i, color) in resolved.iter().enumerate() { - let name = format!("{} {}", tl!("Grid Colors:"), i + 1); + let number = (i + 1).to_string(); + let template = tl!("Grid Colors: {number}"); + let name = if template == "Grid Colors: {number}" { + // Keep the translated prefix for catalogs that have yet to add the complete label. + format!("{} {number}", tl!("Grid Colors:")) + } else { + crate::i18n::fmt(template, &[("number", &number)]) + }; let [r, g, b, _] = color.to_rgba8(1.0); let srgb = box_color(color); wells[i] = Swatch::new(name.clone(), srgb).well().show(ui).clicked.then_some(srgb); @@ -638,6 +652,54 @@ mod tests { app.session.active().unwrap().history.undo.len() } + fn check_source_document(edit_artboards: bool) { + let (mut app, ctx) = new_app(); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + set(&app, &ctx, "bleed", json!([9, 9, 9, 9])); + set(&app, &ctx, "colorMode", json!("cmyk")); + + let apply = |app: &mut VectorcraftApp| { + if edit_artboards { + set(app, &ctx, "editArtboards", json!(true)); + super::pump(app, &ctx); + !is_open(app) + } else { + press_ok(app, &ctx) + } + }; + app.run("document.activate", json!({"index": 1})).unwrap(); + let undo = undo_steps(&app); + let accepted = apply(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, destination); + assert_eq!((st.doc.setup.bleed, st.doc.color_mode), ([0.0; 4], ColorMode::Rgb), "the other document keeps its settings"); + assert_eq!(undo_steps(&app), undo); + assert_eq!(app.session.tool_id(), "selection"); + assert!(!accepted && is_open(&app)); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(apply(&mut app)); + let st = app.session.active().unwrap(); + assert_eq!(st.uid, source); + assert_eq!((st.doc.setup.bleed, st.doc.color_mode, undo_steps(&app)), ([9.0; 4], ColorMode::Cmyk, 1)); + assert_eq!(app.session.tool_id(), if edit_artboards { "artboard" } else { "selection" }); + assert!(!is_open(&app)); + } + + #[test] + fn source_document_is_required_to_confirm_document_setup() { + check_source_document(false); + } + + #[test] + fn source_document_is_required_to_edit_artboards_from_document_setup() { + check_source_document(true); + } + #[test] fn edit_artboards_applies_settings_and_closes_the_dialog() { let (mut app, ctx) = setup_open(); @@ -1116,4 +1178,76 @@ mod tests { let preset = fields(json!({"gridColors": "blue"})); assert_eq!(super::preview_grid(&preset, &setup), (vectorcraft_doc::GridSize::Large, [hex("#ffffff"), hex("#c4dcff")])); } + + /// The grid preview the open dialog draws in `ctx`, in frames run as the hosts run them + /// ([`crate::testing::part_frame_uploads`]): its rect, the span of its texture + /// coordinates (two cells per unit) and the four pixels of the texture it draws. `tiles` holds + /// the pixels of each 2 × 2 texture uploaded so far in `ctx`, so every frame drawn in `ctx` + /// goes through this function. The preview is the largest rect drawn with such a texture. + fn drawn_preview( + app: &mut VectorcraftApp, + ctx: &egui::Context, + tiles: &mut std::collections::HashMap>, + ) -> (Rect, egui::Vec2, Vec) { + let mut preview = None; + for _ in 0..4 { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0))), ..Default::default() }; + let mut out = crate::testing::part_frame_uploads(app, ctx, raw, |app, ui| { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|h| h.run(ui)); + } + }); + for (id, deltas) in &out.textures_delta.set { + if let Some(d) = deltas.last() { + let egui::ImageData::Color(img) = &d.image; + if img.size == [2, 2] { + tiles.insert(*id, img.pixels.clone()); + } + } + } + out.textures_delta.clear(); + preview = out + .shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Rect(r) => { + r.brush.as_ref().filter(|b| tiles.contains_key(&b.fill_texture_id)).map(|b| (r.rect, b.uv, b.fill_texture_id)) + } + _ => None, + }) + .max_by(|a, b| a.0.area().total_cmp(&b.0.area())); + } + let (rect, uv, texture) = preview.unwrap_or_else(|| panic!("no grid preview")); + let pixels = tiles.get(&texture).cloned().unwrap_or_else(|| panic!("no tile for {texture:?}")); + (rect, uv.size(), pixels) + } + + /// The tile's pixels for the grid colors `a` and `b`: `a` in the top-left and bottom-right cells. + fn tile(a: &str, b: &str) -> Vec { + let c = |h| crate::panels::c32(&hex(h)); + vec![c(a), c(b), c(b), c(a)] + } + + /// In an open dialog, the preview follows each edit of Grid Colors and Grid Size: after a + /// color edit it draws a tile in the new colors, and after a size edit it draws the new cells. + #[test] + fn the_grid_preview_follows_edits_in_the_open_dialog() { + let (mut app, ctx) = setup_open(); + let mut tiles = std::collections::HashMap::new(); + set(&app, &ctx, "tab", json!("Transparency")); + let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); + assert_eq!((uv, pixels), (rect.size() / 16.0, tile(LIGHT[0], LIGHT[1])), "Medium, Light"); + set(&app, &ctx, "gridColors", json!(["#ff0000", "#0000ff"])); + let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); + assert_eq!((uv, pixels), (rect.size() / 16.0, tile("#ff0000", "#0000ff")), "color edit"); + set(&app, &ctx, "gridSize", json!("large")); + let (rect, uv, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); + assert_eq!((uv, pixels), (rect.size() / 32.0, tile("#ff0000", "#0000ff")), "size edit"); + set(&app, &ctx, "gridColors", json!("Dark")); + let (_, _, pixels) = drawn_preview(&mut app, &ctx, &mut tiles); + assert_eq!(pixels, tile("#666666", "#4d4d4d"), "preset edit"); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.setup.grid_size, st.doc.setup.grid_colors), (vectorcraft_doc::GridSize::Medium, LIGHT.map(hex))); + assert_eq!(undo_steps(&app), 0); + } } diff --git a/crates/ui-egui/src/dialogs/dxf_options.rs b/crates/ui-egui/src/dialogs/dxf_options.rs index d1a66945ff..a23a07e757 100644 --- a/crates/ui-egui/src/dialogs/dxf_options.rs +++ b/crates/ui-egui/src/dialogs/dxf_options.rs @@ -9,9 +9,11 @@ //! (asking where when there is no path); bad options keep the dialog open. use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _}; +use craft::ui::display::{Shade, Text}; use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::pickers::Select; +use craft::ui::style::TypeRole; use craft::ui::text::NumberField; use serde_json::{Map, Value, json}; use vectorcraft_cad::{ColorDepth, DxfPreset, DxfVersion, Preserve, RasterFormat}; @@ -145,11 +147,11 @@ pub(crate) fn scale_param(disabled_when: Option<(&str, FieldValue)>) -> Param { let (lo, hi) = (*vectorcraft_cad::SCALE_RANGE.start(), *vectorcraft_cad::SCALE_RANGE.end()); let shown = Row::new() .show(ui, |ui, _| { - ui.label("1"); + Text::new("1").show(ui); Select::new(tl!("Unit"), Bind::bound(&mut unit), &units).show(ui); - ui.label("="); + Text::new("=").show(ui); NumberField::new(tl!("Scale"), Bind::bound(&mut scale)).range(lo..=hi).show(ui); - ui.label(tl!("Units")); + Text::new(tl!("Units")).show(ui); }) .output; let scale = scale.unwrap_or(1.0); @@ -200,10 +202,13 @@ pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) { .values(Bind::bound(fields)) .ok_label(tl!("Export").into()) .below(|ui, fields| { - ui.weak(match fields.text("preserve").and_then(Preserve::from_id).unwrap_or_default() { + Text::new(match fields.text("preserve").and_then(Preserve::from_id).unwrap_or_default() { Preserve::Appearance => tl!("Type becomes outlines, and strokes a CAD line can't draw become filled shapes."), Preserve::Editability => tl!("Type stays text, and every stroke is a line with its lineweight and dashes."), - }); + }) + .role(TypeRole::Caption) + .shade(Shade::Muted) + .show(ui); }) }); export_host::open(app, Export::Dxf, selection, dialog); diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index bcfecb47e1..7849d98124 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -10,6 +10,7 @@ //! effect's defaults for the rest. use std::path::PathBuf; +use std::sync::Arc; use craft::host::{PickRequest, Picked}; use craft::ui::contract::Bind; @@ -48,6 +49,8 @@ pub(crate) struct EffectDialogs { pub(crate) struct Open { /// The dialog's id; while [`asking`](Open::asking), the question's. pub id: DialogId, + /// Identity of this opening, since effect dialogs reuse the same dialog ID. + opening: Arc<()>, /// The item the effect goes to, resolved. target: Value, /// The parameters that find the applied effect (`item`, `aligned`). @@ -69,6 +72,26 @@ pub(crate) struct Open { asking: bool, } +/// Match an automation request's blend-mode spelling to the mode shown in the targeted effect dialog. +pub(crate) fn normalize_set_mode(app: &VectorcraftApp, id: DialogId, params: &mut Value) { + let Some(open) = app.effect_dialogs.effect.as_ref() else { return }; + if id != open.id || open.asking || !vectorcraft_effects::takes_blend_mode(&open.cx.id, "mode") { + return; + } + let normalize = |field: &mut Value| { + if field["field"] == "mode" + && let Some(mode) = field["value"].as_str().and_then(vectorcraft_effects::parse_blend_mode) + { + field["value"] = json!(vectorcraft_effects::blend_mode_id(mode)); + } + }; + if let Some(fields) = params.get_mut("fields").and_then(Value::as_array_mut) { + fields.iter_mut().for_each(normalize); + } else { + normalize(params); + } +} + /// `effect.dialog {effect, index?, item?}`: edit applied effect `index` of `item` (null: the /// object's effects; omitted: the active item's, else the object's) prefilled with its values, /// or add `effect`, first asking when that list already has it. @@ -87,6 +110,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let target = edit_target.get("item").cloned().unwrap_or(target); let mut open = Open { id: DialogId::NULL, + opening: Arc::new(()), target: target.clone(), edit_target, index: None, @@ -124,6 +148,7 @@ pub(crate) fn open_last(app: &mut VectorcraftApp, effect: &str, params: Value) - vectorcraft_effects::effect_info(effect).ok_or_else(|| format!("unknown effect `{effect}`"))?; let open = Open { id: DialogId::NULL, + opening: Arc::new(()), target: Value::Null, edit_target: json!({}), index: None, @@ -445,7 +470,18 @@ fn drive(app: &mut VectorcraftApp, mut open: Open) { let _ = open.preview.run(app, previewing, &english, cmd, ¶ms); if let Some(request) = path { let (id, key) = (open.id, request.key); - pick_texture(app, Owner::Document, move |app, path, fields| { + let opening = Arc::clone(&open.opening); + let is_current = move |app: &VectorcraftApp| { + app.effect_dialogs.effect.as_ref().is_some_and(|current| current.id == id && Arc::ptr_eq(&opening, ¤t.opening)) + }; + let same_opening = is_current.clone(); + let is_live = move |app: &VectorcraftApp| { + same_opening(app) && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::(id).is_some())) + }; + pick_texture_while(app, Owner::Document, is_live, move |app, path, fields| { + if !is_current(app) { + return; + } let Some(dialogs) = app.dialogs() else { return }; dialogs.with(|h| { if let Some(d) = h.get_mut_by_id::(id) { @@ -466,11 +502,20 @@ pub(super) fn pick_texture( app: &mut VectorcraftApp, owner: Owner, then: impl FnOnce(&mut VectorcraftApp, PathBuf, [(&'static str, FieldValue); 2]) + 'static, +) { + pick_texture_while(app, owner, |_| true, then); +} + +fn pick_texture_while( + app: &mut VectorcraftApp, + owner: Owner, + current: impl FnOnce(&VectorcraftApp) -> bool + 'static, + then: impl FnOnce(&mut VectorcraftApp, PathBuf, [(&'static str, FieldValue); 2]) + 'static, ) { use vectorcraft_engine::cmd::fileio; let rasters = fileio::FORMATS.iter().filter(|f| f.read && f.raster); let request = rasters.fold(PickRequest::open("texture"), |r, f| r.filter(f.label, fileio::read_extensions(f))); - file_asks::ask(app, request, owner, move |app: &mut VectorcraftApp, picked: Picked| { + file_asks::ask_while(app, request, owner, current, move |app: &mut VectorcraftApp, picked: Picked| { let Some(path) = picked.first_path() else { return Ok(Value::Null) }; let bytes = match picked { Picked::Contents(mut files) if !files.is_empty() => files.swap_remove(0).1, @@ -561,6 +606,21 @@ mod tests { assert_eq!((pa["detail"].as_f64(), pb["detail"].as_f64()), (Some(3.0), Some(8.0)), "each keeps its untouched value"); } + /// Zig Zag's Ridges per segment and Roughen's Detail are counts: their rows show no percent sign, while Size + /// with Relative, a share of the object's size, shows one. + #[test] + fn zig_zag_ridges_and_roughen_detail_show_no_percent_sign() { + use craft::ui::runtime::env::UnitKind; + let app = app(); + for (effect, key) in [("distort.zigZag", "ridges"), ("distort.roughen", "detail")] { + let cx = EffectCx::new(&app, effect, false); + let rows = super::super::effect_rows::distort(&cx, &DialogFields::new()); + let unit = |k: &str| rows.iter().find(|p| p.key == k).map(|p| p.unit); + assert_eq!(unit(key), Some(None), "{effect} {key}"); + assert_eq!(unit("size"), Some(Some(UnitKind::Percent)), "{effect} size"); + } + } + /// The lists the dialogs draw hold the values the effect's parameter documentation lists, in /// its order; Rasterize's Color Model names the document's mode first. #[test] @@ -633,6 +693,77 @@ mod tests { } } + #[test] + fn a_delayed_texture_reply_only_reaches_the_effect_opening_that_requested_it() { + use std::cell::RefCell; + use std::rc::Rc; + + use craft::ui::testing::{Fixture, Room}; + use vectorcraft_effects::pixel::TEXTURE_IMAGE; + + let mut png = Vec::new(); + let img: image::DynamicImage = image::RgbaImage::from_pixel(6, 4, image::Rgba([40, 60, 90, 255])).into(); + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + for (reopen, switch_document) in [(true, false), (false, true), (false, false)] { + let mut app = app(); + rect(&mut app, 10); + app.run("select.all", json!({})).unwrap(); + let app = Rc::new(RefCell::new(app)); + let shown = Rc::clone(&app); + let mut fixture = Fixture::new(move |ui| crate::tests::picks::dialogs(&mut shown.borrow_mut(), ui)); + fixture.in_room(Room::Window); + let ctx = fixture.ctx().clone(); + app.borrow_mut().ui_ctx = Some(ctx.clone()); + let picker = crate::tests::picks::scripted(&mut app.borrow_mut()); + let open = || app.borrow_mut().run("effect.dialog", json!({"effect": ROUGH_PASTELS})).unwrap(); + open(); + fixture.settle(); + let browse = fixture.by_label("Browse…").expect("the Load Texture Browse button"); + fixture.click(&browse).settle(); + assert_eq!(picker.requests().len(), 1, "Browse requested a file"); + + if reopen || switch_document { + let dialog = id(&app.borrow()); + assert!(app.borrow().dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, dialog))); + } + if switch_document { + let mut app = app.borrow_mut(); + let original = app.session.active().unwrap().uid; + // The reply arrives before the host pump has cleared the closed effect's app record. + app.session.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let active = app.session.active().unwrap().uid; + assert_ne!(active, original, "a different document is active"); + let status = app.ui.status.clone(); + picker.answer_contents(&[("invalid.png", b"not an image")]); + crate::file_asks::poll(&mut app); + assert_eq!(app.session.active().unwrap().uid, active, "a stale reply cannot switch documents"); + assert_eq!(app.ui.status, status, "a stale reply cannot report a texture error"); + continue; + } + if reopen { + fixture.settle(); + open(); + fixture.settle(); + } + let current = || { + let app = app.borrow(); + fields(&app, id(&app)) + }; + let before = current(); + picker.answer_contents(&[("texture.png", &png)]); + crate::file_asks::poll(&mut app.borrow_mut()); + fixture.settle(); + let after = current(); + if reopen { + assert_eq!(after.text("texture"), before.text("texture"), "a reopened effect keeps its own texture choice"); + assert_eq!(after.text(TEXTURE_IMAGE), before.text(TEXTURE_IMAGE), "the previous effect's image is absent"); + } else { + assert_eq!(after.text("texture"), Some("loaded"), "the originating effect loads the picked texture"); + assert!(after.text(TEXTURE_IMAGE).and_then(vectorcraft_effects::pixel::texture).is_some()); + } + } + } + /// A Pathfinder effect opens with its own Pathfinder Options (or, saved without them, the /// values it evaluates with); OK with nothing changed records no step, a change one step. #[test] diff --git a/crates/ui-egui/src/dialogs/effect_gallery.rs b/crates/ui-egui/src/dialogs/effect_gallery.rs index 6fc5ad7813..a515addb0e 100644 --- a/crates/ui-egui/src/dialogs/effect_gallery.rs +++ b/crates/ui-egui/src/dialogs/effect_gallery.rs @@ -10,6 +10,7 @@ use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; +use std::sync::Arc; use craft::imaging::ui::filter_gallery::{ EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGallerySession, FilterIndex, FilterTree, @@ -117,7 +118,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { let shown = dialogs.with(|host| { host.get_mut_by_id::(id).map(|dialog| { let visible = dialog.entries(true); - (dialog.preview_on && !visible.is_empty(), stack_batch_params(&visible), dialog.asked.take()) + let asked = dialog.asked.take().map(|layer| (Arc::clone(&dialog.opening), layer)); + (dialog.preview_on && !visible.is_empty(), stack_batch_params(&visible), asked) }) }); let Some((on, batch, asked)) = shown else { @@ -127,18 +129,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) { // `run` reports a failed preview itself. let _ = open.preview.run(app, on, LABEL, COMMAND, &batch); app.effect_dialogs.gallery = Some(open); - if let Some(layer) = asked { - ask_texture(app, id, layer); + if let Some((opening, layer)) = asked { + ask_texture(app, id, opening, layer); } } -/// Asks for the image Load Texture reads into the layer `layer`. The answer finds the layer by its own id, wherever -/// it moved, and is dropped for a layer deleted since or a gallery that closed (a layer id is never used twice). -fn ask_texture(app: &mut VectorcraftApp, id: DialogId, layer: LayerId) { +/// Load Texture follows `layer` within its gallery opening and drops the reply when either is gone. +fn ask_texture(app: &mut VectorcraftApp, id: DialogId, opening: Arc<()>, layer: LayerId) { effect::pick_texture(app, Owner::Free, move |app, _, fields| { let Some(dialogs) = app.dialogs() else { return }; dialogs.with(|host| { - if let Some(dialog) = host.get_mut_by_id::(id) { + if let Some(dialog) = host.get_mut_by_id::(id).filter(|dialog| Arc::ptr_eq(&opening, &dialog.opening)) { dialog.answer_texture(layer, fields); } }); @@ -234,6 +235,8 @@ fn entries_of(layers: &[EffectLayer], index: &FilterIndex, visible_only: bool) - /// [`FilterGallerySession`], with a preview of the visible layers and OK held for [`commit`]. pub(crate) struct EffectGalleryDialog { id: DialogId, + /// Dialog IDs and layer IDs can both be reused when the gallery opens again. + opening: Arc<()>, open: bool, catalog: Catalog, index: FilterIndex, @@ -255,6 +258,7 @@ impl EffectGalleryDialog { let session = FilterGallerySession::new(&first, &catalog); EffectGalleryDialog { id: dialog_id(KEY), + opening: Arc::new(()), open: true, catalog, index, @@ -456,7 +460,7 @@ fn stack_batch_params(stack: &[StackEntry]) -> Value { } fn effect_label(id: &str) -> String { - vectorcraft_effects::effect_info(id).map(|e| tl!(e.label).trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string()) + crate::i18n::effect_name(crate::i18n::current(), id).unwrap_or_else(|| id.to_string()) } /// Where the preview rasters sit: one document point per pixel, origin at the top-left. @@ -652,8 +656,7 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); } - /// Load Texture… in the Settings, answered after the stack changed: the image goes into the layer that asked - /// wherever it moved, and an answer for a deleted layer is dropped. + /// A delayed Load Texture… reply follows its layer when it moves and is dropped when the layer or its gallery closes. #[test] fn settings_load_texture_answers_into_the_gallery() { use vectorcraft_effects::pixel::{TEXTURE_IMAGE, texture}; @@ -677,10 +680,13 @@ mod tests { }) .collect() }; - // Selects `row`, presses Browse of its Texture row, and lets `meanwhile` change the stack before the answer. - let ask = |app: &mut VectorcraftApp, row: usize, meanwhile: &dyn Fn(&VectorcraftApp)| { + let rough_pastels = || { let layer = json!({ "filter": "artistic.roughPastels", "visible": true, "params": {} }); - set(app, &ctx, "effects", json!([layer, layer])); + json!([layer, layer]) + }; + // Selects `row`, presses Browse of its Texture row, and lets `meanwhile` change the gallery before the answer. + let ask = |app: &mut VectorcraftApp, row: usize, meanwhile: &dyn Fn(&mut VectorcraftApp)| { + set(app, &ctx, "effects", rough_pastels()); set(app, &ctx, "select", json!(row)); // The Texture row's Browse press, as the dialog's pass records it. app.dialogs().unwrap().with(|host| { @@ -696,6 +702,18 @@ mod tests { assert_eq!(ask(&mut app, 1, &|_| {}), [false, true], "the selected layer asked"); assert_eq!(ask(&mut app, 0, &|app| set(app, &ctx, "move", json!({"from": 0, "to": 1}))), [false, true], "the layer that asked moved"); assert_eq!(ask(&mut app, 1, &|app| set(app, &ctx, "delete", json!(true))), [false], "the layer that asked was deleted"); + let reopen = |app: &mut VectorcraftApp| { + assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id()))); + frame(app, &ctx); + super::open(app, &json!({})).unwrap(); + }; + // Both openings start with identical stacks, which gives their corresponding layers the same session-local IDs. + reopen(&mut app); + let answers = ask(&mut app, 0, &|app| { + reopen(app); + set(app, &ctx, "effects", rough_pastels()); + }); + assert_eq!(answers, [false, false], "a reopened gallery keeps its own textures"); let _ = std::fs::remove_dir_all(&dir); } } diff --git a/crates/ui-egui/src/dialogs/effect_params.rs b/crates/ui-egui/src/dialogs/effect_params.rs index 06bf617898..5876d9265e 100644 --- a/crates/ui-egui/src/dialogs/effect_params.rs +++ b/crates/ui-egui/src/dialogs/effect_params.rs @@ -150,6 +150,11 @@ fn generic_row(cx: &EffectCx, key: &str, default: &Value, relative: bool) -> Opt Param::number(key, label, n, 1.0, 2) } } + // The blend mode the effect draws in: the mode it draws a name in, Normal for one it doesn't know. + Value::String(text) if vectorcraft_effects::takes_blend_mode(id, key) => { + let mode = vectorcraft_effects::blend_mode_id(vectorcraft_effects::blend_mode(text)); + Param::new(key, label, ParamKind::blend(crate::fields::effect_blend_modes(), Some(mode))) + } Value::String(text) => match options() { Some(list) => Param::new(key, label, ParamKind::choice(list, Some(text.clone()))), None if text.starts_with('#') => Param::new(key, label, ParamKind::color(None)), @@ -172,16 +177,14 @@ pub(crate) fn heading(cx: &EffectCx) -> String { } } -/// The effect's name in the UI language: the catalog may carry it with or without its trailing -/// ellipsis. A plug-in effect's name is shown as it is. +/// The effect's name in the UI language as the Effect menu shows it ([`crate::i18n::effect_name`]). +/// A plug-in effect's name is shown as it is. pub(crate) fn label(id: &str) -> String { let name = vectorcraft_effects::effect_info(id).map(|i| i.label.trim_end_matches('…').to_string()).unwrap_or_else(|| id.to_string()); if vectorcraft_plugins::effect::plugin_id(id).is_some() { return name; } - let dotted = format!("{name}…"); - let shown = tl!(&dotted); - if shown != dotted { shown.trim_end_matches('…').to_string() } else { tl!(&name).to_string() } + crate::i18n::effect_name(crate::i18n::current(), id).unwrap_or(name) } /// Film Grain's bounded, whole-number controls, in the same order as its parameter docs. diff --git a/crates/ui-egui/src/dialogs/effect_rows.rs b/crates/ui-egui/src/dialogs/effect_rows.rs index 580036d430..ef91055575 100644 --- a/crates/ui-egui/src/dialogs/effect_rows.rs +++ b/crates/ui-egui/src/dialogs/effect_rows.rs @@ -36,7 +36,12 @@ fn data_label(text: &str) -> Label { /// A whole-number slider row over `0..=100` percent. fn percent_range(key: &str, label: Label, default: f64) -> Param { - Param::new(key, label, ParamKind::range(0.0, 100.0, default, SliderScale::Linear)).decimals(0).unit(UnitKind::Percent) + count_range(key, label, default).unit(UnitKind::Percent) +} + +/// A whole-number slider row over `0..=100` with no unit after the number. +fn count_range(key: &str, label: Label, default: f64) -> Param { + Param::new(key, label, ParamKind::range(0.0, 100.0, default, SliderScale::Linear)).decimals(0) } /// The row of `key` for either unit of a Relative/Absolute pair: a share of the object's size, or a distance in the @@ -82,7 +87,7 @@ pub(super) fn transform(cx: &EffectCx, _fields: &DialogFields) -> Vec { pub(super) fn distort(cx: &EffectCx, fields: &DialogFields) -> Vec { let roughen = cx.id == "distort.roughen"; // PLAN: production suffixes Detail with "/in"; `Param::unit` takes a `UnitKind` and none stands for it - let second = if roughen { percent_range("detail", lbl!("Detail:"), 10.0) } else { percent_range("ridges", lbl!("Ridges per segment:"), 4.0) }; + let second = if roughen { count_range("detail", lbl!("Detail:"), 10.0) } else { count_range("ridges", lbl!("Ridges per segment:"), 4.0) }; let points: Vec<(String, Label)> = choices(&cx.id, "points") .unwrap_or_default() .iter() diff --git a/crates/ui-egui/src/dialogs/eps_options.rs b/crates/ui-egui/src/dialogs/eps_options.rs index 2a1ee5ec8b..eda7ff4724 100644 --- a/crates/ui-egui/src/dialogs/eps_options.rs +++ b/crates/ui-egui/src/dialogs/eps_options.rs @@ -17,8 +17,10 @@ use std::sync::Arc; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, Show as _, ShowContainer as _, TooltipSpec}; use craft::ui::dialog::DialogId; +use craft::ui::display::{Shade, Text}; use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; +use craft::ui::style::TypeRole; use serde_json::{Map, Value, json}; use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset, fileio}; use vectorcraft_eps::{Level, Overprint, Preview}; @@ -139,11 +141,14 @@ pub fn open_with(app: &mut VectorcraftApp, params: &Value, selection: bool) { builtin_label(fields); normalise_level(fields); ParamDialog::new(KIND, tl!("EPS Options"), rows(&presets)).values(Bind::bound(fields)).ok_label(tl!("Export").into()).below(|ui, fields| { - ui.weak(if fields.text("level").and_then(Level::from_id) == Some(Level::Two) || fields.bool("compatibleGradients") == Some(true) { + Text::new(if fields.text("level").and_then(Level::from_id) == Some(Level::Two) || fields.bool("compatibleGradients") == Some(true) { tl!("Transparency is flattened with the preset. Type is written as outlines; gradients as bands of colour.") } else { tl!("Transparency is flattened with the preset. Type is written as outlines; gradients stay smooth.") - }); + }) + .role(TypeRole::Caption) + .shade(Shade::Muted) + .show(ui); }) }); export_host::open(app, Export::Eps, selection, dialog); @@ -198,7 +203,10 @@ pub(super) fn custom_dialog(app: &VectorcraftApp, parent: DialogId, fields: &Dia ParamDialog::new(CUSTOM_KIND, tl!("Custom Transparency Flattener Options"), flatten::option_params(&FIXED, FIXED_REASON)) .values(Bind::bound(fields)) .below(|ui, _| { - ui.weak(tl!("EPS has no alpha transparency, and Overprints sets whether overprints are kept.")); + Text::new(tl!("EPS has no alpha transparency, and Overprints sets whether overprints are kept.")) + .role(TypeRole::Caption) + .shade(Shade::Muted) + .show(ui); }) }) } diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index 3c76dea90e..6e8f8bc1d2 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -11,9 +11,11 @@ use std::sync::LazyLock; -use craft::ui::contract::Bind; +use craft::ui::contract::{Bind, Show as _}; +use craft::ui::display::{Shade, Text}; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::Label; +use craft::ui::style::TypeRole; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format}; @@ -127,7 +129,7 @@ fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Res ParamDialog::new(KIND, tl!("Export As"), params()) .values(Bind::bound(fields)) .below(|ui, fields| { - ui.weak(summary(fields)); + Text::new(summary(fields)).role(TypeRole::Caption).shade(Shade::Muted).show(ui); }) .ok_label(Label::from("Export…")) }); diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 5e765e306c..0211830949 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -996,17 +996,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { let key = app.session.active().map(|st| (st.uid, st.revision)); let pdf_presets = pdf::presets(&app.session); let saved = &app.session.prefs.screen_export_presets; - let Some((stale, pending, rename, filed)) = dialogs.with(|host| { + let Some((shown, pending, rename, filed)) = dialogs.with(|host| { let d = host.get_mut_by_id::(id)?; screen_formats::preset_list(&mut d.presets, saved); if d.pdf_presets != pdf_presets { d.pdf_presets = pdf_presets; } - Some((d.doc.as_ref().map(|s| s.key) != key, d.pending.take(), d.rename.take(), d.held.take())) + Some((d.doc.as_ref().map(|s| s.key), d.pending.take(), d.rename.take(), d.held.take())) }) else { return; }; - if stale { + if shown != key { let (doc, thumbs) = document_view(app, ctx); dialogs.with(|host| { if let Some(d) = host.get_mut_by_id::(id) { @@ -1031,7 +1031,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) { rename_artboard(app, board, &name); } if let Some(fields) = filed { - let answer = params(app, &fields).and_then(|p| io::export_for_screens(app, p)).map(drop).map_err(Label::from); + // OK validated its selection against the document the dialog showed before refreshing. + let answer = if shown.map(|(uid, _)| uid) == app.session.active().map(|st| st.uid) { + params(app, &fields).and_then(|p| io::export_for_screens(app, p)).map(drop).map_err(Label::from) + } else { + Err(Label::from(tl!("The active document changed. Review the export selection and try again."))) + }; dialogs.with(|host| { if let Some(d) = host.get_mut_by_id::(id) { d.held.answer(answer); diff --git a/crates/ui-egui/src/dialogs/file_info.rs b/crates/ui-egui/src/dialogs/file_info.rs index e43435b5ae..fffa334f21 100644 --- a/crates/ui-egui/src/dialogs/file_info.rs +++ b/crates/ui-egui/src/dialogs/file_info.rs @@ -55,8 +55,14 @@ type Info = Map; pub fn open(app: &mut VectorcraftApp) -> Result { let fields = app.session.execute("file.info", &json!({})).map_err(|e| e.to_string())?; let fields = fields.as_object().cloned().ok_or("file.info gave no fields")?; - let ok = |app: &mut VectorcraftApp, fields: &Info| app.run("file.info", Value::Object(fields.clone())).map(|_| ()); - crate::dialogs::host::open_held(app, FileInfoDialog::new(fields), ok).ok_or("no window")?; + let document = app.session.active().ok_or("no document")?.uid; + let ok = |app: &mut VectorcraftApp, (document, fields): &(u64, Info)| { + if !app.session.active().is_some_and(|active| active.uid == *document) { + return Err(tl!("File Info can only change the document it was opened for.").to_owned()); + } + app.run("file.info", Value::Object(fields.clone())).map(|_| ()) + }; + crate::dialogs::host::open_held(app, FileInfoDialog::new(document, fields), ok).ok_or("no window")?; Ok(Value::Null) } @@ -215,6 +221,7 @@ impl Templates { /// The File Info dialog: a form over the fields `file.info` reports, whose OK is held for the app. pub(crate) struct FileInfoDialog { id: DialogId, + document: u64, open: bool, /// OK files its answer for the app instead of closing ([`HoldsOk::held_ok`]). hold: bool, @@ -230,9 +237,10 @@ pub(crate) struct FileInfoDialog { } impl FileInfoDialog { - fn new(value: Info) -> Self { + fn new(document: u64, value: Info) -> Self { FileInfoDialog { id: dialog_id(KEY), + document, open: true, hold: false, value, @@ -371,15 +379,15 @@ fn import_options(ui: &mut egui::Ui, mode: &mut &'static str) -> Option { } impl HoldsOk for FileInfoDialog { - type Answer = Info; + type Answer = (u64, Info); fn held_ok(mut self) -> Self { self.hold = true; self } - fn take_ok(&mut self) -> Option { - self.held.take() + fn take_ok(&mut self) -> Option { + self.held.take().map(|fields| (self.document, fields)) } fn answer_ok(&mut self, answer: Result<(), Label>) { @@ -674,6 +682,58 @@ mod tests { assert!(with_dialog(&app, |_| ()).is_some()); } + #[test] + fn a_file_info_confirmation_stays_with_its_document() { + let mut app = windowed(); + for (title, author) in [("Source", "Ada"), ("Destination", "Grace")] { + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.info", json!({"title": title, "author": author})).unwrap(); + } + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "title", json!("Revised Source")).unwrap(); + set(&app, PENDING, json!("print")).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog_id(KEY))), "the edit waits for the application"); + + activate(&mut app, 1); + let before = app.session.active().unwrap(); + let document = before.doc.clone(); + let b_undo = before.history.undo.len(); + crate::dialogs::host::pump(&mut app, &ctx); + let after = app.session.active().unwrap(); + assert_eq!(after.doc.info_title(), document.info_title(), "the destination's title stays untouched"); + assert_eq!(after.doc.metadata, document.metadata, "the destination's metadata stays untouched"); + assert_eq!(after.history.undo.len(), b_undo); + assert!(matches!(held_state(&app), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + assert!(press_ok(&mut app), "a fresh confirmation can apply the original draft"); + let source = app.session.active().unwrap(); + assert_eq!(source.doc.info_title(), "Revised Source"); + assert_eq!(source.doc.metadata.author, "Ada"); + assert_eq!(source.doc.metadata.keywords, ["print"]); + assert_eq!(source.history.undo.len(), a_undo + 1); + } + + #[test] + fn a_reopened_file_info_confirmation_uses_the_new_drafts_document() { + let mut app = windowed(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("ui.fileInfoDialog", json!({})).unwrap(); + set(&app, "title", json!("Revised Destination")).unwrap(); + assert!(press_ok(&mut app)); + assert_eq!(app.session.active().unwrap().doc.info_title(), "Revised Destination"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(app.session.active().unwrap().history.undo.is_empty()); + } + #[test] fn an_imported_template_fills_the_fields_and_ok_is_one_undo_step() { let dir = vectorcraft_testkit::TempDir::new("ui-file-info-template"); diff --git a/crates/ui-egui/src/dialogs/flattener_presets.rs b/crates/ui-egui/src/dialogs/flattener_presets.rs index b59f3b2a15..5346bf06f6 100644 --- a/crates/ui-egui/src/dialogs/flattener_presets.rs +++ b/crates/ui-egui/src/dialogs/flattener_presets.rs @@ -90,10 +90,7 @@ fn run(app: &mut VectorcraftApp, event: &ManagerEvent, current: &str) -> Result< Ok(app.session.flattener_presets().get(above).map(|p| p.name.clone())) } ManagerEvent::Action(ManagerAction::Import) => preset_manager::import(app, KEY, "flattener.presets.import", "Flattener presets", PRESET_EXTS), - ManagerEvent::Action(ManagerAction::Export) => { - crate::io::save_command_output(app, "flattener.presets.export", PRESET_FORMAT, json!({ "names": [current] }), |_, _| Ok(Value::Null))?; - Ok(None) - } + ManagerEvent::Action(ManagerAction::Export) => preset_manager::export(app, "flattener.presets.export", PRESET_FORMAT, current), // A new name that is taken or a built-in one is refused by the command. ManagerEvent::Rename(name) if name.trim() == current => Ok(None), ManagerEvent::Rename(name) => Ok(select(app.run("flattener.presets.save", json!({ "name": current, "newName": name }))?)), @@ -216,6 +213,8 @@ mod tests { let picker = crate::tests::picks::scripted(&mut app); open(&mut app, Some("Mine")); press(&mut app, ManagerAction::Export); + // The save panel suggests the preset's name. + assert_eq!(picker.requests().last().and_then(|r| r.file_name.clone()).as_deref(), Some("Mine.vcflattener")); // The answered save panel writes the file in the next frame. picker.answer_saved(&file, None); frame(&mut app); diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 6d81d18214..be7cf18a3b 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -171,6 +171,13 @@ fn field_value(row: Option<&Param>, value: &Value) -> Option { }, // A pair of radio buttons over a flag (Relative / Absolute): the ids are "true" and "false". Some(ParamKind::Radio { .. }) if value.is_boolean() => value.as_bool().map(|b| FieldValue::Text(b.to_string())), + // Use the renderer's mode for each spelling, including Normal for unknown names and the effect's default for + // a legacy value that is not text. + Some(ParamKind::Blend { default, .. }) => value + .as_str() + .map(|s| vectorcraft_effects::blend_mode_id(vectorcraft_effects::blend_mode(s))) + .or_else(|| default.clone()) + .map(FieldValue::Text), // A custom row's list, and one a key no row has carries through (an export's `artboards: [0, 1]`), stay JSON: a // list of whole numbers would read back as a grid, and one of two or three as a point or colour. Some(ParamKind::Custom(_)) | None if value.is_array() => Some(FieldValue::Json(value.clone())), @@ -298,7 +305,10 @@ fn plugin_row(key: &str, p: &PluginParam) -> Param { // there. Past it, the number typed is read as an integer. const EXACT: i64 = 1 << 53; let start = (*default).max(*min).min(*max); - if -EXACT <= *min && *max <= EXACT { + if let Some(range) = p.ui.slider_range(&p.spec) { + // A slider over the whole numbers of the range, as the framework's range row with no decimals. + Param::new(key, name, ParamKind::range(*range.start(), *range.end(), start as f64, SliderScale::Linear)).decimals(0) + } else if -EXACT <= *min && *max <= EXACT { Param::new(key, name, ParamKind::int(Some(*min), Some(*max), start)) } else { let (min, max) = (*min, *max); diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index d4b411dc90..d38a4eb35a 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -4,14 +4,14 @@ //! (Live curve fitting, on: its preview fits the stroke while it is drawn). //! //! Fields: `tool`; `fidelity` (screen pixels for the Pencil, Paintbrush and Smooth, points for the -//! Blob Brush), `fill` (Pencil and +//! Blob Brush), `smoothness` (percent, 0 to 100; Smooth), `fill` (Pencil and //! Paintbrush), `keepSelected` (Pencil, Paintbrush and Blob Brush), `mergeOnlySelection` (Blob //! Brush), `closeWithin` and `editWithin` (screen pixels, 0 turns it off; Pencil and Paintbrush), //! `angle` (degrees) and `roundness` (percent; Blob Brush and Eraser), `livePreview` (Pencil: the stroke shows //! with its fill and stroke while it is drawn, or as a thin line until the release), `size` //! (points; Blob Brush and Eraser), and `sizeMode` and `sizeVariation` (points; Blob Brush and //! Eraser: with Pressure the tip is Size − Variation wide at the lightest pen pressure and Size + -//! Variation at the heaviest). The Blob Brush's `sizeMode` is `fixed` or `pressure`. The Eraser's +//! Variation at the heaviest). The Blob Brush's `sizeMode` is `fixed`, `pressure` or `stylusWheel`. The Eraser's //! Angle, Roundness and Size each have a menu (`angleMode`, `roundnessMode`, `sizeMode`: `fixed`, //! `random`, `pressure`, `tilt`, `bearing` or `rotation`) before the field and a Variation field //! under it (`angleVariation` in degrees, `roundnessVariation` in percent, `sizeVariation`), @@ -45,8 +45,9 @@ pub const KIND: &str = "freehandOptions"; pub const TOOLS: [&str; 5] = ["pencil", "paintbrush", "smooth", "blobBrush", "eraser"]; /// The options the dialog edits, in the order it shows them (a tool has those it reports). -const KEYS: [&str; 18] = [ +const KEYS: [&str; 19] = [ "fidelity", + "smoothness", "angle", "angleMode", "angleVariation", @@ -227,6 +228,12 @@ fn params(tool: &str, present: &[&str]) -> Vec { .full_width(), ); } + if has("smoothness") { + // The Smooth tool's Smoothness: a slider from 0% to 100% with the field at its end, in whole percent. + rows.push( + Param::new("smoothness", tl!("Smoothness:"), ParamKind::range(0.0, 100.0, 50.0, SliderScale::Linear)).decimals(0).unit(UnitKind::Percent), + ); + } if eraser { rows.push(variation_param("angle", tl!("Angle:"), UnitKind::Degrees, 0, (-180.0, 180.0), (0.0, 180.0), &Variation::ALL)); rows.push(variation_param("roundness", tl!("Roundness:"), UnitKind::Percent, 0, (1.0, 100.0), (0.0, 100.0), &Variation::ALL)); @@ -244,7 +251,7 @@ fn params(tool: &str, present: &[&str]) -> Vec { rows.push(Param::custom("tip", "", |ui, fields, _| tip_row(ui, fields, 0.0)).full_width()); } if has("sizeMode") { - let offered = &[Variation::Fixed, Variation::Pressure]; + let offered = &vectorcraft_tools::draw2::BLOB_SIZE_MODES; rows.push(variation_param("size", tl!("Size:"), UnitKind::Points, 1, (0.1, 1000.0), (0.0, 1000.0), offered)); } else if has("size") { rows.push(Param::number("size", tl!("Size:"), 10.0, 1.0, 1).unit(UnitKind::Points).bounds(Some(0.1), Some(1000.0))); diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 38b911f0b5..a02e3d12cd 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -43,6 +43,32 @@ fn the_fidelity_keys_step_finely_at_the_low_end() { assert_eq!((fidelity_step(0.035, 1.0), fidelity_step(0.035, -1.0), fidelity_step(1.5, 1.0), fidelity_step(1.5, -1.0)), (0.04, 0.03, 2.0, 1.0)); } +/// Smooth Tool Options shows Smoothness under Fidelity, at 50% until it is set, and OK sets it from 0% to 100%; a +/// Smoothness past 100% is refused and sets nothing. The other freehand tools have no Smoothness. +#[test] +fn smooth_tool_options_set_the_smoothness() { + let mut app = app(); + let smooth = app.session.tool_options_of("smooth"); + assert_eq!(smooth["smoothness"], json!(50.0)); + let present: Vec<&str> = KEYS.iter().copied().filter(|key| smooth.get(*key).is_some()).collect(); + let keys: Vec = params("smooth", &present).iter().map(|p| p.key.to_string()).collect(); + let (fidelity, smoothness) = (keys.iter().position(|k| k == "fidelity"), keys.iter().position(|k| k == "smoothness")); + assert!(fidelity.is_some() && fidelity < smoothness, "{keys:?}"); + for value in [30.0, 0.0, 100.0] { + set_through_dialog(&mut app, "smooth", &[("smoothness", json!(value))]); + assert_eq!(app.session.tool_options_of("smooth")["smoothness"], json!(value)); + } + let key = app.run("tool.options", json!({"tool": "smooth"})).unwrap()["dialog"].as_str().unwrap().to_owned(); + let (ctx, id) = (app.ui_ctx.clone().expect("a window"), open_id(&app, &key)); + let host = app.dialogs().expect("a window"); + assert!(host.with(|host| host.set_json_field(&ctx, id, "smoothness", json!(120))).is_err(), "120% is refused"); + host.with(|host| host.cancel_by_id(&ctx, id)); + assert_eq!(app.session.tool_options_of("smooth")["smoothness"], json!(100.0)); + for tool in ["pencil", "paintbrush", "blobBrush", "eraser"] { + assert!(app.session.tool_options_of(tool).get("smoothness").is_none(), "{tool}"); + } +} + /// Each tool's dialog, opened as the user opens it, stores the values set in it as the tool's options: the field /// keys, the units (Liquify's percent is a fraction) and the companion keys of the variation rows. #[test] @@ -51,6 +77,7 @@ fn ok_sets_each_tools_options() { let layers = app.session.doc().unwrap().doc.layers.clone(); let circle = vectorcraft_tools::circle::ID; let arc = vectorcraft_tools::three_point_arc::ID; + let curvature = vectorcraft_tools::curvature_circle::ID; // The tool opened, the fields set, the tool whose options are read, and the options expected there. let rows: Vec<(&str, Value, &str, Value)> = vec![ ( @@ -60,7 +87,7 @@ fn ok_sets_each_tools_options() { json!({"fidelity": 6.5, "fill": true, "altSmooth": true, "closeWithin": 0.0, "editWithin": 20.0, "liveFit": false}), ), ("paintbrush", json!({"fidelity": 3, "keepSelected": false}), "paintbrush", json!({"fidelity": 3.0, "keepSelected": false})), - ("smooth", json!({"fidelity": 5}), "smooth", json!({"fidelity": 5.0})), + ("smooth", json!({"fidelity": 5, "smoothness": 75}), "smooth", json!({"fidelity": 5.0, "smoothness": 75.0})), ( "blobBrush", json!({"angle": 45, "roundness": 0, "sizeMode": "pressure", "sizeVariation": 6, "fidelity": 0.01, "keepSelected": true, "mergeOnlySelection": true}), @@ -81,6 +108,12 @@ fn ok_sets_each_tools_options() { circle, json!({"radii": false, "standardAnchors": false, "dragThird": false, "color": "magenta"}), ), + ( + curvature, + json!({"snapTolerance": 8, "annotateRadius": false, "standardAnchors": false}), + curvature, + json!({"snapTolerance": 8.0, "snapWithoutGuides": true, "annotateRadius": false, "standardAnchors": false, "constantRadius": true}), + ), (arc, json!({"direction": true}), arc, json!({"direction": true})), ("objectsOnPath", json!({"pivot": 7, "rotate": 30}), "objectsOnPath", json!({"pivot": 7, "rotate": 30.0})), ( @@ -306,3 +339,30 @@ fn the_blob_brush_and_eraser_size_can_follow_the_pen_pressure() { let o = app.session.tool_options_of("pencil"); assert!(o.get("sizeMode").is_none() && o.get("sizeVariation").is_none()); } + +/// The names and values the window's access tree shows. +fn shown_text(app: &mut VectorcraftApp) -> String { + crate::dialogs::tests::settle(app); + let out = crate::dialogs::tests::frame(app, vec![]); + let update = out.platform_output.accesskit_update.expect("an accessibility tree"); + update.nodes.iter().flat_map(|(_, node)| [node.label(), node.value()]).flatten().collect::>().join("\n") +} + +/// The Blob Brush's Size menu offers Stylus Wheel beside Fixed and Pressure, Fixed still the +/// default; the menu shows it once chosen, and OK sets it with the Variation. +#[test] +fn the_blob_brush_size_offers_the_stylus_wheel() { + let mut app = app(); + app.run("tool.options", json!({"tool": "blobBrush"})).unwrap(); + assert_eq!(crate::dialogs::tests::fields(&app)["sizeMode"], json!("fixed"), "Fixed by default"); + crate::dialogs::tests::set(&mut app, "sizeMode", json!("stylusWheel")); + crate::dialogs::tests::set(&mut app, "sizeVariation", json!(5)); + let text = shown_text(&mut app); + assert!(text.contains("Stylus Wheel"), "{text}"); + assert!(crate::dialogs::tests::confirm(&mut app), "OK closes the dialog"); + let o = app.session.tool_options_of("blobBrush"); + assert_eq!((o["sizeMode"].clone(), o["sizeVariation"].as_f64()), (json!("stylusWheel"), Some(5.0))); + app.run("tool.options", json!({"tool": "blobBrush"})).unwrap(); + let text = shown_text(&mut app); + assert!(text.contains("Stylus Wheel"), "it shows again on the next open: {text}"); +} diff --git a/crates/ui-egui/src/dialogs/gradient_stop.rs b/crates/ui-egui/src/dialogs/gradient_stop.rs index d38eae5bb0..3ba900ff01 100644 --- a/crates/ui-egui/src/dialogs/gradient_stop.rs +++ b/crates/ui-egui/src/dialogs/gradient_stop.rs @@ -30,12 +30,12 @@ use craft::ui::text::NumberField; use egui::{Pos2, Ui, vec2}; use serde_json::{Value, json}; use vectorcraft_color::gradient::move_stop; -use vectorcraft_color::{Color, FreeformPoint, GradientKind, GradientStop, Paint}; +use vectorcraft_color::{Color, FreeformPoint, GradientStop, Paint}; use vectorcraft_geom::{Point, Rect}; use vectorcraft_tools::params::color_json; use crate::VectorcraftApp; -use crate::panels::gradient::{edit_point, set_stops, set_stops_keeping_models, shown_points}; +use crate::panels::gradient::{edit_point, edits_points, set_stops, set_stops_keeping_models, shown_points}; use crate::panels::{Live, active_paint, c32}; /// The dialog kind of the gradient stop popover. @@ -82,7 +82,7 @@ impl Target { fn selected(app: &VectorcraftApp) -> Option { let Paint::Gradient(g) = active_paint(app) else { return None }; - if g.gradient.kind == GradientKind::Freeform { + if edits_points(app, &g) { let f = shown_points(&g); let i = app.session.selected_freeform_point().filter(|i| *i < f.points.len())?; return Some(Target::Point(f.points[i], i)); @@ -390,7 +390,7 @@ pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) { let Some(ctx) = app.ui_ctx.clone() else { return }; let Some(dialogs) = app.dialogs() else { return }; if let Paint::Gradient(g) = active_paint(app) - && g.gradient.kind != GradientKind::Freeform + && !edits_points(app, &g) && app.session.selected_stop() != Some(index) { // An index past the last stop selects nothing, and `selected` then finds nothing to edit. diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index 85bb9503c1..ffcc511501 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -18,6 +18,7 @@ //! empties it). use std::collections::BTreeMap; +use std::sync::Arc; use craft::behavior::{EditEvent, NumberCodec}; use craft::host::{PickRequest, Picked}; @@ -395,8 +396,12 @@ fn can_import(app: &VectorcraftApp) -> bool { file_asks::can(app, craft::host::PickKind::Open) && app.services.read.is_some() } -/// Import Data's answer: a tab-separated text file's rows into the sheet. -fn import(app: &mut VectorcraftApp, picked: Picked) -> Result { +/// Import Data's answer: a tab-separated text file's rows into the sheet that asked for it. +fn import(app: &mut VectorcraftApp, owner: &Arc<()>, picked: Picked) -> Result { + let Some(dialogs) = app.dialogs() else { return Ok(Value::Null) }; + if !dialogs.with(|host| host.get::().is_some_and(|d| Arc::ptr_eq(&d.import_owner, owner))) { + return Ok(Value::Null); + } let bytes = match picked { Picked::Paths(paths) => { let Some(path) = paths.first().map(|p| p.to_string_lossy().into_owned()) else { return Ok(Value::Null) }; @@ -420,15 +425,14 @@ fn import(app: &mut VectorcraftApp, picked: Picked) -> Result { return Err("the file is larger than 1 MB".into()); } let grid = grid_from_text(&decode(&bytes)); - if let Some(dialogs) = app.dialogs() { - dialogs.with(|host| host.get_mut::().map(|d| d.replace(grid))); - } + dialogs.with(|host| host.get_mut::().filter(|d| Arc::ptr_eq(&d.import_owner, owner)).map(|d| d.replace(grid))); Ok(Value::Null) } /// What the window asked of the app since the last [`pump`]. struct Asks { graph: Option, + import_owner: Arc<()>, apply: Option, actions: Vec, } @@ -444,7 +448,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { d.take_asks() }) }); - let Some(Asks { graph, apply: filed, actions }) = asked else { return }; + let Some(Asks { graph, import_owner, apply: filed, actions }) = asked else { return }; if let Some(sheet) = filed { if let Err(e) = apply(app, &sheet, graph) { app.status(e); @@ -455,7 +459,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { match action { Action::Import => { let request = PickRequest::open("document").filter("Text", &["txt", "tsv", "csv"]); - file_asks::ask(app, request, Owner::Document, import); + let owner = import_owner.clone(); + let current = import_owner.clone(); + file_asks::ask_while( + app, + request, + Owner::Document, + move |app| { + app.dialogs().is_some_and(|dialogs| { + dialogs.with(|host| host.get::().is_some_and(|d| Arc::ptr_eq(&d.import_owner, ¤t))) + }) + }, + move |app, picked| import(app, &owner, picked), + ); } Action::Revert => match graph_grid(app, graph) { Ok(grid) => { @@ -636,6 +652,8 @@ fn body(ui: &mut egui::Ui, values: &mut Sheet, pane: &mut Pane<'_>) -> bool { /// sheet for [`pump`], which sends it to the graph and keeps the window open. pub(crate) struct GraphDataDialog { id: DialogId, + /// Identifies this opening even when another Graph Data dialog reuses `id`. + import_owner: Arc<()>, sheet: Sheet, state: GridState, entry: Entry, @@ -658,6 +676,7 @@ impl GraphDataDialog { load(&sheet, &state, &mut entry); GraphDataDialog { id: dialog_id(KIND), + import_owner: Arc::new(()), sheet, state, entry, @@ -672,7 +691,7 @@ impl GraphDataDialog { /// Everything the window asked since the last call, once. fn take_asks(&mut self) -> Asks { - Asks { graph: self.graph, apply: self.held.take(), actions: std::mem::take(&mut self.actions) } + Asks { graph: self.graph, import_owner: self.import_owner.clone(), apply: self.held.take(), actions: std::mem::take(&mut self.actions) } } /// The pump sent Apply's sheet to the graph; the window stays open and Apply is ready again. @@ -712,7 +731,6 @@ impl StackDialog for GraphDataDialog { .ok_label(tl!("Apply")) .ok_enabled(!held.is_waiting()) .accept_stays_open(true) - .enter_confirms(false) // The sheet owns the scroll; the controls above it stay in view. .collection_body(true) .shaped(|dialog| dialog.initial_focus(Initial::Default)) @@ -960,6 +978,62 @@ mod tests { assert_eq!(at(&h, 0, 1), "c"); } + #[test] + fn graph_data_import_keeps_late_answers_out_of_a_reopened_sheet() { + let (mut app, _) = app_with(",first\nQ1,1", "column"); + let files = Arc::new(ScriptedFiles::held()); + app.services.read = Some(Box::new(|_| Err("this picker answers with bytes".into()))); + app.host.with_files(files.clone()).install(app.ui_ctx.as_ref().unwrap()); + app.host = Arc::new(app.host.with_files(files.clone())); + open(&mut app).unwrap(); + let mut h = harness(app); + h.run_steps(4); + h.get_by_label("Import Data…").click(); + h.run_steps(3); + assert_eq!(files.open(), 1); + + let app = h.state_mut(); + let ctx = app.ui_ctx.as_ref().unwrap().clone(); + app.dialogs().unwrap().with(|host| host.cancel::(&ctx)); + app.run("graph.create", json!({"type": "column", "x": 20, "y": 20, "width": 100, "height": 100, "csv": ",second\nQ2,2"})).unwrap(); + open(app).unwrap(); + let series = |h: &Harness| read(h.state(), |d| cell_of(&d.sheet.grid, 0, 1)); + assert!(files.answer(Picked::Contents(vec![("first.txt".into(), b"\tstale\nQ1\t7".to_vec())])).is_some()); + h.run_steps(4); + assert_eq!(series(&h), "second"); + + h.get_by_label("Import Data…").click(); + h.run_steps(3); + assert!(files.answer(Picked::Contents(vec![("second.txt".into(), b"\timported\nQ2\t8".to_vec())])).is_some()); + h.run_steps(4); + assert_eq!(series(&h), "imported"); + } + + #[test] + fn graph_data_import_does_not_reactivate_the_document_of_a_closed_sheet() { + let (mut app, _) = app_with(",first\nQ1,1", "column"); + let picker = crate::tests::picks::scripted(&mut app); + let ctx = app.ui_ctx.as_ref().unwrap().clone(); + let first = app.session.active().unwrap().uid; + open(&mut app).unwrap(); + edit(&app, |d| d.actions.push(Action::Import)); + pump(&mut app, &ctx); + assert_eq!(picker.requests().len(), 1); + + app.dialogs().unwrap().with(|host| host.cancel::(&ctx)); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("graph.create", json!({"type": "column", "x": 20, "y": 20, "width": 100, "height": 100, "csv": ",second\nQ2,2"})).unwrap(); + let second = app.session.active().unwrap().uid; + assert_ne!(first, second); + assert_eq!(app.session.documents().len(), 2); + open(&mut app).unwrap(); + + picker.answer_contents(&[("first.txt", b"\tstale\nQ1\t7")]); + file_asks::poll(&mut app); + assert_eq!(app.session.active().unwrap().uid, second); + assert_eq!(read(&app, |d| cell_of(&d.sheet.grid, 0, 1)), "second"); + } + #[test] fn transpose_and_switch_xy() { assert_eq!(transpose(&g(&[&["", "a", "b"], &["Q1", "1", "2"]])), g(&[&["", "Q1"], &["a", "1"], &["b", "2"]])); @@ -1015,6 +1089,41 @@ mod tests { assert!(app.dialogs().is_some_and(|d| d.with(|host| host.is_open::()))); } + /// Enter in the entry box and in the sheet moves the picked cell down and applies nothing. Enter in a field that + /// does not use it is Apply: the graph is redrawn and the window stays open. + #[test] + fn enter_moves_in_the_entry_box_and_the_sheet_and_applies_elsewhere() { + let (mut app, id) = app_with(",a,b\nQ1,1,2\nQ2,3,4\nQ3,5,6", "column"); + let before = data(&mut app, id); + open(&mut app).unwrap(); + set_field(&app, "sel", json!([1, 1])).unwrap(); + let mut h = harness(app); + h.run_steps(4); + // The entry box. + h.get_by_label("Cell Value").click(); + h.run_steps(2); + edit(h.state(), |d| d.entry.text = "9".into()); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(read(h.state(), |d| (active(&d.state), cell_of(&d.sheet.grid, 1, 1))), ((2, 1), "9".to_string()), "Enter moves down"); + assert_eq!(data(h.state_mut(), id), before, "Enter in the entry box applies nothing"); + // The sheet. + h.get_by_label("Q1").click(); + h.run_steps(2); + assert_eq!(read(h.state(), |d| active(&d.state)), (1, 0), "the click picks the cell"); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert_eq!(read(h.state(), |d| active(&d.state)), (2, 0), "Enter moves down in the sheet"); + assert_eq!(data(h.state_mut(), id), before, "Enter in the sheet applies nothing"); + // A field that does not use Enter. + h.get_by_label("Column Width").click(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(4); + assert_eq!(data(h.state_mut(), id)["rows"][0][0], json!(9.0), "Enter applies the sheet"); + assert!(h.state().dialogs().is_some_and(|d| d.with(|host| host.is_open::())), "the window stays open"); + } + #[test] fn the_entry_box_writes_its_text_and_moves_the_picked_cell() { let (mut app, id) = app_with(",a,b\nQ1,1,2", "column"); diff --git a/crates/ui-egui/src/dialogs/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index 2bfdf7b913..348287e7bd 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -519,13 +519,14 @@ impl GraphDesignDialog { } true }); - if let Some(options) = shown.accepted { - self.column = options; + if shown.closed.is_some() { + return Some(DialogResult::Cancel); + } + if shown.picked == Some(0) && !waiting { let answer = self.answer(); self.held.file(answer); - return None; } - shown.closed.map(|_| DialogResult::Cancel) + None } } @@ -836,6 +837,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { #[cfg(test)] mod tests { + use egui_kittest::kittest::Queryable; use serde_json::{Value, json}; use super::GraphDesignDialog; @@ -879,6 +881,48 @@ mod tests { assert!(!dialogs.with(|host| host.is_open::())); } + #[test] + fn graph_design_footer_ok_applies_column_and_marker_designs_unless_dismissed() { + for (graph_type, command, dismiss) in [("column", "graph.column", false), ("line", "graph.marker", false), ("column", "graph.column", true)] { + let (mut app, ctx) = app_with_design(); + select_graph(&mut app, graph_type); + crate::menus::invoke(&mut app, command, json!({})); + set(&app, &ctx, "selected", json!("New Design")).unwrap(); + + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::testing::install(ui.ctx()); + return; + } + app.dialogs().unwrap().with(|host| host.run(ui)); + super::pump(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + if dismiss { + h.get_by_label("OK").click_accesskit(); + h.input_mut().events.push(egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed: true, + repeat: false, + modifiers: Default::default(), + }); + } else { + h.get_by_label("OK").click(); + } + h.run_steps(4); + + let app = h.state_mut(); + assert!(!app.dialogs().unwrap().with(|host| host.is_open::())); + let expected = if dismiss { Value::Null } else { json!("New Design") }; + assert_eq!(app.session.execute(command, &json!({})).unwrap()["design"], expected); + } + } + #[test] fn marker_lists_the_designs_and_applies_the_one_picked() { let (mut app, ctx) = app_with_design(); diff --git a/crates/ui-egui/src/dialogs/hpgl_options.rs b/crates/ui-egui/src/dialogs/hpgl_options.rs index 50eab143f5..90d17d4f6f 100644 --- a/crates/ui-egui/src/dialogs/hpgl_options.rs +++ b/crates/ui-egui/src/dialogs/hpgl_options.rs @@ -12,15 +12,16 @@ //! nothing. use craft::behavior::IconId; +use craft::theme::variant::Tone; use craft::theme::{Rgba, Srgba}; use craft::ui::buttons::{Button, IconButton}; use craft::ui::choice::{Radio, RadioGroup, Swatch}; -use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Politeness, Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::dialog::DialogId; +use craft::ui::display::Text; use craft::ui::layout_components::{Row, Stack}; +use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog}; -use craft::ui::runtime::env::Env; -use craft::ui::style::rgba_color; use craft::ui::text::TextField; use serde_json::{Map, Value, json}; use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE}; @@ -209,8 +210,10 @@ fn pens_ui(ui: &mut egui::Ui, fields: &DialogFields) -> PensAsked { asked.table = Some(on); } if let Some(e) = fields.text(PEN_ERROR).filter(|_| asked.table != Some(false)) { - let error = rgba_color(Env::of(ui).tokens.tokens().color.status.bad.fg); - ui.colored_label(error, crate::i18n::message(crate::i18n::current(), e)); + Notice::new(Tone::Bad, crate::i18n::message(crate::i18n::current(), e).to_string()) + .layout(NoticeLayout::Inline) + .announce(Politeness::Assertive) + .show(ui); } // A table longer than a plot takes (set through `ui.dialog.set`) draws no rows: OK refuses it. let Some(mut pens) = list.filter(|a| asked.table.is_none() && a.len() <= MAX_PENS) else { return asked }; @@ -225,7 +228,7 @@ fn pens_ui(ui: &mut egui::Ui, fields: &DialogFields) -> PensAsked { (remove, asked.pick) = (None, None); for (i, pen) in pens.iter().enumerate() { Row::new().id_salt(("hpgl-pen-row", i)).show(ui, |ui, _| { - ui.label((i + 1).to_string()); + Text::new((i + 1).to_string()).show(ui); let mut color = pen.as_str().and_then(Rgba::from_hex).unwrap_or(Rgba::rgb(0, 0, 0)); if Swatch::new(tl!("Pen color"), Srgba::from(color)).show(ui).clicked { asked.pick = Some((i, Srgba::from(color))); diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index e28bdbb021..df899ee1c3 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -372,14 +372,13 @@ impl ImportPdfDialog { if self.held.refusal().is_some_and(|(_, refused)| *refused != self.s) { self.held.clear_refusal(); } - match (out.accepted, out.closed) { - (Some(_), _) => { - self.ok(); - None - } - (None, Some(_)) => Some(DialogResult::Cancel), - (None, None) => None, + if out.closed.is_some() { + return Some(DialogResult::Cancel); } + if out.picked == Some(0) && !waiting { + self.ok(); + } + None } } @@ -630,17 +629,17 @@ pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[ p } -/// The `file.place` params `p` of a PDF the user places embedded (Link off, from bytes or with a -/// password) get the `pdfTextAs` preference as their `textAs` when it is Outlines and they have no -/// `textAs`. A linked page shows the file's own text, and a `.ai` or `.ait` file is placed as it -/// says. An empty `password` is none, so a place from a path with Link on and an empty -/// `password` stays linked. +/// The `file.place` params `p` of a PDF placed embedded (Link off, from bytes or with a password), +/// by the user or as a command, get the `pdfTextAs` preference as their `textAs` when it is Outlines and they have no +/// `textAs`. Bytes are a PDF by their content ([`places_pdf`]). A linked page shows the file's own +/// text, and a `.ai` or `.ait` file is placed as it says. An empty `password` is none, so a place +/// from a path with Link on and an empty `password` stays linked. pub(crate) fn place_with_preferred_text_as(app: &VectorcraftApp, p: &mut Value) { let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); let path = p.get("path").and_then(Value::as_str); let name = path.or_else(|| p.get("name").and_then(Value::as_str)).unwrap_or_default(); let linked = path.is_some() && p.get("link").and_then(Value::as_bool) != Some(false) && !gives_password(p); - if given("textAs") || linked || preferred_text_as(app) == TextAs::Text || fileio::extension(name) != "pdf" { + if given("textAs") || linked || preferred_text_as(app) == TextAs::Text || !places_pdf(p, path, name) { return; } if let Some(o) = p.as_object_mut() { @@ -648,6 +647,21 @@ pub(crate) fn place_with_preferred_text_as(app: &VectorcraftApp, p: &mut Value) } } +/// Do the `file.place` params `p` place a PDF (not a `.ai` or `.ait` file, which is PDF inside): +/// a `path` by its extension, as [`place_source`] picks one, and `dataBase64` by its content, as +/// `file.place` reads it ([`fileio::detect`]: bytes that start with `%PDF`), so bytes without a +/// `name` or with another extension count too. Only the first bytes are decoded. +fn places_pdf(p: &Value, path: Option<&str>, name: &str) -> bool { + let ext = fileio::extension(name); + match (path, p.get("dataBase64").and_then(Value::as_str)) { + (None, Some(b64)) => { + let head: String = b64.chars().filter(|c| !c.is_ascii_whitespace()).take(8).collect(); + !matches!(ext.as_str(), "ai" | "ait") && vectorcraft_format::base64_decode(&head).is_some_and(|b| b.starts_with(b"%PDF")) + } + _ => ext == "pdf", + } +} + /// Keeps the Text choice OK confirmed in the `pdfTextAs` preference. fn keep_text_as(app: &mut VectorcraftApp, text_as: TextAs) { if preferred_text_as(app) != text_as { diff --git a/crates/ui-egui/src/dialogs/javascript_files.rs b/crates/ui-egui/src/dialogs/javascript_files.rs index 01e3012abe..d15f561816 100644 --- a/crates/ui-egui/src/dialogs/javascript_files.rs +++ b/crates/ui-egui/src/dialogs/javascript_files.rs @@ -16,12 +16,13 @@ use craft::behavior::{Selection, keyed}; use craft::host::PickRequest; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked}; +use craft::ui::contract::{Bind, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, clicked}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow}; use craft::ui::patterns::form_dialogs::PathRow; +use craft::ui::primitives::Revision; use craft::ui::sections::{DialogRole, FooterButton}; use egui::{Context, Ui}; use serde_json::{Value, json}; @@ -199,22 +200,22 @@ const LIST_ROWS: u16 = 6; fn body(ui: &mut Ui, files: &[(String, String)], form: &mut Form) { let source = keyed(files, |(linked, _): &(String, String)| linked.clone()); - let selection = - selected_row(files, &form.selected).and_then(|i| files.get(i)).map(|(linked, _)| Selection::single(linked.clone())).unwrap_or_default(); - let list = List::::options(tl!("Linked files")) + let selected = selected_row(files, &form.selected).map(|i| &files[i].0); + let mut selection = selected.map(|linked| Selection::single(linked.clone())).unwrap_or_default(); + List::new(tl!("Linked files")) + .select(SelectMode::Single) + .rows_stamp(Revision::of(&selected).get()) .min_rows(LIST_ROWS) .max_rows(LIST_ROWS) - .selection(Bind::given(selection)) + .selection(Bind::bound(&mut selection)) .sizing(Sizing::FillWidth) .empty(tl!("No JavaScript files linked")) .show_items(ui, &source, &mut |key, _| { // Paths and URLs are data: shown as they are. ListRow::new(files.iter().find(|(linked, _)| linked == key).map_or_else(String::new, |(_, shown)| shown.clone())) }); - for event in list.events { - if let CollectionEvent::Activate(key) = event { - form.selected = key; - } + if selection.items.first() != selected { + form.selected = selection.items.into_iter().next().unwrap_or_default(); } Field::new(caption("File or URL:")).show(ui, |ui, _| { let request = PickRequest::open("javascript").filter("JavaScript", &["js"]); @@ -243,6 +244,7 @@ mod tests { use craft::host::{AppInfo, Host, Picked, ScriptedFiles}; use craft::ui::testing::Fixture; + use egui::{Key, Modifiers}; use vectorcraft_engine::Session; use super::*; @@ -288,6 +290,31 @@ mod tests { assert_eq!(json_selected(&panel), json!("https://example.com/b.js")); } + #[test] + fn arrow_navigation_changes_which_javascript_file_remove_unlinks() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + for file in ["scripts/first.js", "scripts/second.js"] { + app.run("svgInteractivity.addFile", json!({"file": file})).unwrap(); + } + let mut panel = Panel::new(app, draw); + panel.app().run("ui.javascriptFilesDialog", json!({})).unwrap(); + panel.frame(); + panel.frame(); + + panel.click("scripts/first.js"); + assert_eq!(json_selected(&panel), "scripts/first.js"); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(json_selected(&panel), "scripts/second.js"); + // A selection changed outside the list gives the next arrow its new starting row. + set_field(&panel, "selected", "scripts/first.js"); + panel.frame(); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(json_selected(&panel), "scripts/second.js"); + panel.click(tl!("Remove")); + assert_eq!(panel.app().session.active().unwrap().doc.svg_scripts, ["scripts/first.js"]); + } + /// In a frame drawn with read roots in force, the list names a linked file outside them by its /// file name alone, and that name unlinks it; the person sees the whole path. #[test] diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets.rs b/crates/ui-egui/src/dialogs/kinsoku_sets.rs index c2c334f148..6eb690989d 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets.rs @@ -15,12 +15,14 @@ //! Behavior reference: the help page //! . +use craft::theme::variant::Tone; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, Entry, Politeness, Props as _, Show as _, ShowContainer as _}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft::ui::display::Text; use craft::ui::form::{Field, FieldGroup}; use craft::ui::layout_components::{Row, Stack}; +use craft::ui::notices::{Notice, NoticeLayout}; use craft::ui::patterns::presets::{ NameCheck, NamedPresetEvent, NamedPresetRow, PickerField, PresetError, PresetPicker, PresetRow, PresetSource, PresetState, }; @@ -359,10 +361,11 @@ impl KinsokuDialog { let rows: Vec> = list.iter().map(|s| PresetRow::item(name_of(s).to_owned(), name_of(s), 0)).collect(); let mut value = list.get(self.index(list.len())).map(|s| name_of(s).to_owned()); let suggestion = new_name(&list, &self.opened); - // PLAN: PresetPicker has no placeholder: an empty list shows an empty name field, not "None". let source = PresetSource::listed(&rows); let refuses = |typed: &str| name_problem(&list, typed); - let picker = PresetPicker::new(tl!("Kinsoku Set"), Bind::bound(&mut value), &source, Bind::bound(&mut self.picker)).field(PickerField::Name); + let picker = PresetPicker::new(tl!("Kinsoku Set"), Bind::bound(&mut value), &source, Bind::bound(&mut self.picker)) + .field(PickerField::Name) + .placeholder(tl!("None")); let out = NamedPresetRow::new(tl!("Kinsoku Set"), picker).suggest_name(suggestion).check_name(NameCheck::of_host(&refuses)).show(ui); self.apply(out.events); @@ -408,9 +411,8 @@ impl KinsokuDialog { } fn show_problem(&self, ui: &mut Ui) { - // PLAN: craft_ui does not re-export `Tone`, which `Notice` needs, so the reason shows as plain text. if let Some(problem) = &self.problem { - Text::new(problem.clone()).show(ui); + Notice::new(Tone::Bad, problem.clone()).layout(NoticeLayout::Inline).announce(Politeness::Assertive).show(ui); } } } diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs index f39cf6d596..887dbbc202 100644 --- a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs +++ b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs @@ -47,6 +47,21 @@ fn cancel(app: &VectorcraftApp) { app.dialogs().unwrap().with(|h| h.cancel::(&ctx)); } +#[test] +fn empty_kinsoku_list_shows_none_in_the_preset_picker() { + let mut fixture = craft::ui::testing::Fixture::new(|ui| crate::dialogs::host::window_dialogs(ui.ctx()).with(|host| host.run(ui))); + fixture.room(egui::vec2(800.0, 600.0)); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui_ctx = Some(fixture.ctx().clone()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + open(&mut app).unwrap(); + fixture.settle(); + + let picker = fixture.by_label("Kinsoku Set").expect("Kinsoku Set picker"); + assert_eq!(fixture.tree().value_of(picker.node), Some("None")); + assert!(picked(&app).is_empty(), "the caption does not select a set"); +} + /// Type › Kinsoku Shori Settings… opens on the document's sets; New adds one based on Hard, its /// categories edited in their fields and Add putting in a character by its code point; nothing /// changes until OK, which sets them as one undo step; Cancel leaves them. diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index 3ed57d9471..944051cf7d 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -249,8 +249,9 @@ fn fields_of(n: &Node, xml_id: bool) -> LayerOptionsValue { /// Opens the dialog on `value`. fn open_value(app: &mut VectorcraftApp, value: LayerOptionsValue) -> Result { + let document = app.session.active().ok_or("no document open")?.uid; let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(LayerOptionsDialog::new(value))); + dialogs.with(|host| host.open(LayerOptionsDialog::new(document, value))); Ok(Value::Null) } @@ -410,6 +411,7 @@ pub(crate) fn params(v: &LayerOptionsValue) -> (&'static str, Value) { /// the dialog open with the reason under its rows. pub(crate) struct LayerOptionsDialog { id: DialogId, + document: u64, open: bool, value: LayerOptionsValue, held: HeldAnswer, @@ -421,8 +423,8 @@ pub(crate) struct LayerOptionsDialog { impl LayerOptionsDialog { /// The dialog over `value`. - fn new(value: LayerOptionsValue) -> Self { - LayerOptionsDialog { id: dialog_id(KEY), open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None } + fn new(document: u64, value: LayerOptionsValue) -> Self { + LayerOptionsDialog { id: dialog_id(KEY), document, open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None } } /// The OK filed by the user, once. @@ -571,7 +573,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(dialogs) = app.dialogs() else { return }; // The closed dialog's answer was run when OK was filed. let _ = dialogs.with(|host| host.take::()); - let Some(value) = dialogs.with(|host| host.get_mut::().and_then(LayerOptionsDialog::take_filed)) else { return }; + let Some((document, value)) = dialogs.with(|host| { + let dialog = host.get_mut::()?; + Some((dialog.document, dialog.take_filed()?)) + }) else { + return; + }; let (cmd, p) = params(&value); let sublayer = match cmd { "layer.new" => Some(false), @@ -579,8 +586,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { _ => None, }; // Isolation mode can start while the dialog is open. - let answer = match sublayer { - Some(sublayer) if app.session.active().is_some_and(|st| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => { + let answer = match app.session.active().filter(|st| st.uid == document) { + None => Err(Label::from(tl!("Layer Options can only change the document it was opened for."))), + Some(st) if sublayer.is_some_and(|sublayer| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => { Err(Label::from("exit isolation mode first")) } _ => { @@ -681,6 +689,48 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); } + #[test] + fn layer_options_and_new_layers_follow_their_document() { + for (command, arguments) in [("ui.layerOptions", json!({})), ("ui.newLayer", json!({})), ("ui.newLayer", json!({"sublayer": true}))] { + let mut app = app(); + let source_id = app.session.active().unwrap().doc.layers[0].id; + app.run("file.new", json!({"width": 160, "height": 160})).unwrap(); + let destination_id = app.session.active().unwrap().doc.layers[0].id; + assert_eq!(destination_id, source_id, "the two documents reuse a layer ID"); + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + app.run(command, arguments).unwrap(); + set(&mut app, "name", json!("Source Draft")); + let ctx = app.ui_ctx.clone().unwrap(); + let dialog = open_id(&app); + app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog)); + + let layers = |app: &VectorcraftApp| { + let mut names = vec![]; + app.session.active().unwrap().doc.walk(|node| { + if node.is_layer() { + names.push(node.display_name()); + } + }); + names + }; + activate(&mut app, 1); + let before = layers(&app); + let b_undo = app.session.active().unwrap().history.undo.len(); + pump(&mut app, &ctx); + assert_eq!(layers(&app), before, "the destination's layers stay unchanged for {command}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), b_undo); + assert!(matches!(app.dialogs().unwrap().with(|host| host.held_state(dialog)), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + ok(&mut app); + assert!(!app.any_dialog_open()); + assert!(layers(&app).iter().any(|name| name == "Source Draft")); + assert_eq!(app.session.active().unwrap().history.undo.len(), a_undo + 1); + } + } + /// Two layers with different options, the first plain and the second green, locked, in /// outline view and dimmed to 30%. fn two_layers(app: &mut VectorcraftApp) -> (NodeId, NodeId) { diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index e60e9e0b3a..a76bdedd7a 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -35,7 +35,7 @@ use craft::ui::pickers::Select; use craft::ui::popover::Popover; use craft::ui::runtime::env::{Label, LengthUnits, UnitKind}; use craft::ui::sections::Section; -use craft::ui::text::{LinkMode, LinkedFields, NumberField}; +use craft::ui::text::{LinkMode, LinkedFields, LinkedLayout, NumberField}; use super::host::open_held; use crate::VectorcraftApp; @@ -329,6 +329,7 @@ impl DocumentSettings for VcNewDocument { let captions = [text(tl!("Top")), text(tl!("Bottom")), text(tl!("Left")), text(tl!("Right"))]; let out = LinkedFields::<4>::new(bleed.clone(), Bind::given(parts), Bind::bound(&mut linked)) .mode(LinkMode::Equal) + .layout(LinkedLayout::Columns) .captions(captions) .range(0.0..=vectorcraft_doc::setup::MAX_BLEED) .lengths(lengths) @@ -479,7 +480,7 @@ fn more_settings(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) { Field::new(layout.clone()).show(ui, |ui, _| { let entries: Vec> = ArtboardLayout::ALL.iter().map(|l| Entry::new(*l, text(tl!(l.label())))).collect(); if let Some(l) = Segmented::new(layout.clone(), Bind::given(s.layout), &entries).enabled(several).show(ui).value().copied() { - s.layout = l; + choose_layout(s, l); } }); let rtl = Checkbox::new(Bind::given(s.right_to_left)).label(right_to_left).enabled(several).show(ui); @@ -494,14 +495,37 @@ fn more_settings(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) { }); Field::new(columns.clone()).show(ui, |ui, _| { let n = f64::from(s.artboards.max(1)); - let shown = f64::from(s.columns.max(1)).min(n); + let shown = f64::from(shown_columns(s)); let field = NumberField::new(columns.clone(), Bind::given(Some(shown))).range(1.0..=n).step(1.0).commit_decimals(0).enabled(several && grid); if let Some(v) = field.show(ui).value().copied().flatten().filter(|v| v.is_finite()) { + // A column count replaces a preset's rows. s.columns = v.round().clamp(1.0, n) as u32; + s.rows = 0; } }); } +/// The columns More Settings shows: for a grid by column made with `file.new`'s `rows`, the columns +/// those rows give the current number of artboards, as `file.new` lays them out; otherwise the +/// stored count. At most one for each artboard. +fn shown_columns(s: &DocSettings) -> u32 { + let n = s.artboards.max(1); + if s.layout == ArtboardLayout::GridByColumn && s.rows > 0 { u32::try_from(s.grid_columns()).unwrap_or(n) } else { s.columns.max(1).min(n) } +} + +/// Chooses a layout in More Settings. Another layout replaces a preset's rows and keeps the column +/// count those rows showed; choosing the layout that is already selected keeps the rows. +fn choose_layout(s: &mut DocSettings, l: ArtboardLayout) { + if l == s.layout { + return; + } + if s.rows > 0 { + s.columns = shown_columns(s); + s.rows = 0; + } + s.layout = l; +} + /// Manage Profiles' pop-up: a row per New Document profile with Edit, which opens the profile as a /// document, and Reset, which brings back the shipped profile. The button pressed is put in `action`. fn manage_profiles(ui: &mut egui::Ui, setup: &Setup, action: &mut Option) { @@ -854,6 +878,39 @@ mod tests { assert_eq!(fields(&app)["name"], json!("Untitled-2")); } + /// The four Bleed fields stay inside the dialog in a 1280 by 900 window; in one row, Right ran past the dialog's + /// right edge. + #[test] + fn bleed_fields_stay_inside_the_dialog() { + let mut app = app(); + open(&mut app); + let ctx = ctx(&app); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + // Each frame gives the app's input once, as the hosts do. + let frame = |app: &mut VectorcraftApp, i: u32| { + let mut raw = egui::RawInput { time: Some(0.1 * f64::from(i)), screen_rect: Some(screen), ..Default::default() }; + app.adopt_context(&ctx); + app.raw_input(&ctx, &mut raw); + craft::ui::shell::embed::before_input(&ctx, |out| app.frame_input(out)); + let mut out = ctx.run_ui(raw, |ui| app.ui(ui)); + out.textures_delta.clear(); + out + }; + (0..3).for_each(|i| drop(frame(&mut app, i))); + let out = frame(&mut app, 3); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let bounds = |label: Option<&str>, role: egui::accesskit::Role| { + let found = nodes.iter().find(|(_, n)| n.role() == role && label.is_none_or(|l| n.label() == Some(l))); + let (_, n) = found.unwrap_or_else(|| panic!("no {role:?} {label:?}")); + n.bounds().expect("bounds") + }; + let dialog = bounds(None, egui::accesskit::Role::Dialog); + for side in ["Top", "Bottom", "Left", "Right"] { + let field = bounds(Some(side), egui::accesskit::Role::SpinButton); + assert!(dialog.x0 <= field.x0 && field.x1 <= dialog.x1, "Bleed {side} {field:?} stays inside the dialog {dialog:?}"); + } + } + /// More Settings edits only the artboard layout, spacing and columns, and creates nothing. #[test] fn more_settings_is_a_popup_holding_only_the_artboard_layout() { @@ -885,6 +942,53 @@ mod tests { assert_eq!((saved.layout, saved.spacing), (ArtboardLayout::Column, 30.0)); } + /// A grid by column with a preset's rows. + fn by_rows(artboards: u32, rows: u32) -> DocSettings { + DocSettings { artboards, layout: ArtboardLayout::GridByColumn, columns: 2, rows, ..DocSettings::default() } + } + + /// Columns shows what a preset's rows give the current number of artboards, and the stored + /// count without rows. + #[test] + fn columns_follow_a_presets_rows_as_artboards_change() { + for (artboards, shown) in [(5, 2), (9, 3), (2, 1)] { + assert_eq!(shown_columns(&by_rows(artboards, 4)), shown, "{artboards} artboards"); + } + assert_eq!(shown_columns(&by_rows(9, 0)), 2); + } + + /// Another layout replaces a preset's rows and keeps the columns they showed, so Create lays out + /// what the dialog showed; the layout already selected keeps the rows. + #[test] + fn a_new_layout_keeps_the_columns_a_presets_rows_showed() { + for to in [ArtboardLayout::GridByRow, ArtboardLayout::Row, ArtboardLayout::Column] { + let mut s = by_rows(9, 4); + choose_layout(&mut s, to); + assert_eq!((s.layout, s.columns, s.rows), (to, 3, 0), "{to:?}"); + } + let mut s = by_rows(9, 4); + choose_layout(&mut s, ArtboardLayout::GridByColumn); + assert_eq!(s, by_rows(9, 4)); + let mut s = by_rows(9, 0); + choose_layout(&mut s, ArtboardLayout::GridByRow); + assert_eq!((s.columns, s.rows), (2, 0)); + } + + /// A preset's rows reach the dialog's fields and Create puts that many artboards in each column. + #[test] + fn a_presets_rows_reach_the_document_create_makes() { + let mut app = app(); + open(&mut app); + set(&app, "artboards", json!(5)).unwrap(); + set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).unwrap(); + assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4)); + create(&mut app); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.artboards.len(), 5); + let first: Vec<_> = st.doc.artboards.iter().filter(|a| a.rect.x0 == 0.0).map(|a| a.rect.y0).collect(); + assert_eq!(first.len(), 4, "four artboards in the first column: {first:?}"); + } + /// Align New Objects to Pixel Grid reaches a saved preset and the document Create makes. #[test] fn align_new_objects_checkbox_follows_the_preset_and_reaches_the_document() { diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index 119228b39f..04e86b346d 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -15,7 +15,10 @@ use std::sync::Arc; +use craft::ui::buttons::Button; +use craft::ui::contract::{Props as _, Show as _, ShowContainer as _, clicked}; use craft::ui::dialog::DialogResult; +use craft::ui::layout_components::Row; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedPropertiesDialog, Param, ParamKind, PropertiesTab, PropertyRow}; use craft::ui::runtime::env::Label; use serde_json::{Map, Value, json}; @@ -599,8 +602,6 @@ fn seed_editors(fields: &mut DialogFields) { } } -// PLAN: the stop list is a Select over the stops and the buttons are egui buttons: the List and button -// components' signatures are not in the bundle. /// The Add, Delete Tab and Clear All Tabs buttons, which also keep the editors and the stop they edit in step. fn tabs_buttons(unit: Unit) -> Param { Param::custom("tabs", tl!("Tabs"), move |ui, fields, _| { @@ -608,10 +609,10 @@ fn tabs_buttons(unit: Unit) -> Param { let (rows, _, _) = tab_rows(fields); let can_add = new_tab_position(&rows, unit).is_some(); let (mut add, mut delete, mut clear) = (false, false, false); - let line = ui.horizontal(|ui| { - add = ui.add_enabled(can_add, egui::Button::new(tl!("Add"))).clicked(); - delete = ui.add_enabled(!rows.is_empty(), egui::Button::new(tl!("Delete Tab"))).clicked(); - clear = ui.add_enabled(!rows.is_empty(), egui::Button::new(tl!("Clear All Tabs"))).clicked(); + let line = Row::new().show(ui, |ui, _| { + add = clicked(&Button::new(tl!("Add")).enabled(can_add).show(ui)); + delete = clicked(&Button::new(tl!("Delete Tab")).enabled(!rows.is_empty()).show(ui)); + clear = clicked(&Button::new(tl!("Clear All Tabs")).enabled(!rows.is_empty()).show(ui)); }); if add { add_tab(fields, unit); @@ -621,7 +622,7 @@ fn tabs_buttons(unit: Unit) -> Param { clear_tabs(fields); } seed_editors(fields); - line.response + line.output }) .companions(["__tabSel", "__tabEdited", "__tabShown", "__tabAlign", "__tabPosition", "__tabLeader", "__tabAlignOn"]) } diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index a17ddcb027..64176e93ac 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -5,11 +5,16 @@ // PLAN: the framework import paths below are assumed from the contract rows (craft-ui-patterns re-exports contract and // runtime; the form-dialog items live under `patterns::form_dialogs`; `Field` and `NumberField` under craft-ui-widgets). -use craft::ui::contract::{Bind, FieldLabelRole, Show as _, ShowContainer as _, SideLabel}; +use craft::behavior::ColumnWidth; +use craft::ui::contract::{Bind, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel}; use craft::ui::dialog::DialogId; +use craft::ui::display::Text; use craft::ui::form::Field; +use craft::ui::layout::GridFit; +use craft::ui::layout_components::Grid; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind}; use craft::ui::runtime::env::{LengthUnits, UnitKind}; +use craft::ui::runtime::measure; use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; use craft::ui::text::{NumberField, NumberOutput}; use craft::ui::value_drag::SliderScale; @@ -29,6 +34,10 @@ use crate::VectorcraftApp; /// sends 180° less the threshold: 150° sends `object.path.simplify`'s default of 30°. pub(crate) const ANGLE_THRESHOLD: f64 = 150.0; +/// Split Into Grid's two columns, each as wide as its fields: the rows on the left, the columns on the right. The +/// grid keeps both columns in a narrow dialog. +const AXES: [ColumnWidth; 2] = [ColumnWidth::Content; 2]; + /// Simplify's tolerance when the dialog opens from the menu, in points. const DEFAULT_TOLERANCE: f64 = 1.0; @@ -174,7 +183,7 @@ pub(crate) fn split_fields(width: f64, height: f64) -> DialogFields { fn cell(ui: &mut egui::Ui, label: &'static str, name: String, describes: bool, value: f64, lengths: Option) -> Option { let role = if describes { FieldLabelRole::Describes } else { FieldLabelRole::Names }; let mut edited = None; - Field::new(label).side(SideLabel::new().role(role)).show(ui, |ui, _| { + Field::new(label).side(SideLabel::new().role(role)).id_salt(name.as_str()).show(ui, |ui, _| { let bind = Bind::given(Some(value)); let out: NumberOutput = match lengths { Some(l) => NumberField::length(name.clone(), bind, l).show(ui), @@ -193,41 +202,45 @@ fn split_grid(ui: &mut egui::Ui, f: &mut DialogFields, lengths: LengthUnits) -> ("rows", tl!("Rows:"), tl!("Height:"), "rowGutter", "totalHeight", 2.0), ("columns", tl!("Columns:"), tl!("Width:"), "columnGutter", "totalWidth", 2.0), ]; - egui::Grid::new("split-grid") - .num_columns(2) - .show(ui, |ui| { - for (number, label, _, _, _, default) in axes { - let n = f.number(number).unwrap_or(default); - if let Some(v) = cell(ui, label, label.to_string(), false, n, None) { - f.set(number, v); - } + // The grid can run its body twice in a pass, so the body edits a copy, kept only from the run that takes effect. + let before = f.clone(); + let mut edited = None; + let shown = Grid::new(&AXES).fit(GridFit::Fixed).id_salt("split-grid").show(ui, |ui, _| { + let mut f = before.clone(); + for (number, label, _, _, _, default) in axes { + let n = f.number(number).unwrap_or(default); + if let Some(v) = cell(ui, label, label.to_string(), false, n, None) { + f.set(number, v); } - ui.end_row(); - for (number, _, label, gutter, total, default) in axes { - let n = f.number(number).unwrap_or(default).max(1.0); - let gaps = f.number(gutter).unwrap_or(0.0) * (n - 1.0); - let size = (f.number(total).unwrap_or(0.0) - gaps) / n; - if let Some(v) = cell(ui, label, label.to_string(), false, size, Some(lengths)) { - f.set(total, n * v + gaps); - } + } + for (number, _, label, gutter, total, default) in axes { + let n = f.number(number).unwrap_or(default).max(1.0); + let gaps = f.number(gutter).unwrap_or(0.0) * (n - 1.0); + let size = (f.number(total).unwrap_or(0.0) - gaps) / n; + if let Some(v) = cell(ui, label, label.to_string(), false, size, Some(lengths)) { + f.set(total, n * v + gaps); } - ui.end_row(); - for (_, axis, _, gutter, _, _) in axes { - let label = tl!("Gutter:"); - if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(gutter).unwrap_or(0.0), Some(lengths)) { - f.set(gutter, v); - } + } + for (_, axis, _, gutter, _, _) in axes { + let label = tl!("Gutter:"); + if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(gutter).unwrap_or(0.0), Some(lengths)) { + f.set(gutter, v); } - ui.end_row(); - for (_, axis, _, _, total, _) in axes { - let label = tl!("Total:"); - if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(total).unwrap_or(0.0), Some(lengths)) { - f.set(total, v); - } + } + for (_, axis, _, _, total, _) in axes { + let label = tl!("Total:"); + if let Some(v) = cell(ui, label, format!("{axis} {label}"), true, f.number(total).unwrap_or(0.0), Some(lengths)) { + f.set(total, v); } - ui.end_row(); - }) - .response + } + if measure::effect(ui.ctx(), "Split Into Grid's fields edit their values") { + edited = Some(f); + } + }); + if let Some(edited) = edited { + *f = edited; + } + shown.output } /// Split Into Grid's rows: the grid and Add Guides. @@ -286,7 +299,7 @@ fn counts_row(ui: &mut egui::Ui, f: &DialogFields) { if let Some(FieldValue::Json(c)) = f.get(COUNTS) && let (Some(before), Some(after)) = (c["before"].as_u64(), c["after"].as_u64()) { - ui.label(format!("{} {before} → {after}", crate::i18n::colon(tl!("Anchor Points")))); + Text::new(format!("{} {before} → {after}", crate::i18n::colon(tl!("Anchor Points")))).show(ui); } } diff --git a/crates/ui-egui/src/dialogs/pdf_presets.rs b/crates/ui-egui/src/dialogs/pdf_presets.rs index a097f11537..4e36bbaddc 100644 --- a/crates/ui-egui/src/dialogs/pdf_presets.rs +++ b/crates/ui-egui/src/dialogs/pdf_presets.rs @@ -105,10 +105,7 @@ fn run(app: &mut VectorcraftApp, event: &ManagerEvent, current: &str) -> Result< Ok(app.session.pdf_presets().get(above).map(|p| p.name.clone())) } ManagerAction::Import => preset_manager::import(app, KEY, "pdf.preset.import", "PDF presets", PRESET_EXTS), - ManagerAction::Export => { - crate::io::save_command_output(app, "pdf.preset.export", PRESET_FORMAT, json!({ "names": [current] }), |_, _| Ok(Value::Null))?; - Ok(None) - } + ManagerAction::Export => preset_manager::export(app, "pdf.preset.export", PRESET_FORMAT, current), } } @@ -223,6 +220,33 @@ mod tests { assert!(!manager_open(&app), "Close"); } + #[test] + fn a_late_preset_import_keeps_the_reopened_managers_selection() { + let mut app = app(); + let picker = crate::tests_picks::scripted(&mut app); + app.run("pdf.preset.save", json!({"name": "Mine", "thumbnails": true})).unwrap(); + let exported = app.run("pdf.preset.export", json!({"names": ["Mine"]})).unwrap(); + let bytes = exported["data"].as_str().unwrap().as_bytes(); + + open(&mut app, Some("PDF/X-4:2010")); + press(&mut app, ManagerAction::Import); + assert_eq!(picker.requests().len(), 1, "Import requested a file"); + host(&app, |h| h.cancel_by_id(&ctx(&app), dialog_id(KEY))); + open(&mut app, Some("Press Quality")); + let ctx = ctx(&app); + picker.answer_contents(&[("mine.vcpdfpresets", bytes)]); + crate::tests_picks::poll(&mut app, &ctx); + frame(&mut app); + assert!(app.session.prefs.pdf_presets.iter().any(|preset| preset.name == "Mine 2"), "the late reply still imports: {}", app.ui.status); + assert_eq!(manager_fields(&mut app)["selected"], "Press Quality"); + + press(&mut app, ManagerAction::Import); + picker.answer_contents(&[("mine.vcpdfpresets", bytes)]); + crate::tests_picks::poll(&mut app, &ctx); + frame(&mut app); + assert_eq!(manager_fields(&mut app)["selected"], "Mine 3", "the original manager selects its own import"); + } + #[test] fn import_and_export_go_through_files() { let dir = std::env::temp_dir().join(format!("vc-pdfpresets-ui-{}", std::process::id())); @@ -234,6 +258,8 @@ mod tests { app.run("pdf.preset.save", json!({"name": "Mine", "thumbnails": true})).unwrap(); open(&mut app, Some("Mine")); press(&mut app, ManagerAction::Export); + // The save panel suggests the preset's name. + assert_eq!(picker.requests().last().and_then(|r| r.file_name.clone()).as_deref(), Some("Mine.vcpdfpresets")); picker.answer_saved(&file, None); let ctx = ctx(&app); crate::tests_picks::poll(&mut app, &ctx); diff --git a/crates/ui-egui/src/dialogs/perspective_grid.rs b/crates/ui-egui/src/dialogs/perspective_grid.rs index 1afd7dafbf..d75a811a74 100644 --- a/crates/ui-egui/src/dialogs/perspective_grid.rs +++ b/crates/ui-egui/src/dialogs/perspective_grid.rs @@ -134,6 +134,7 @@ fn open_on(app: &mut VectorcraftApp, def: GridDefinition, mode: GridMode) -> Res let dialog = GridDialog::new( def, mode, + app.session.active().map(|st| st.uid), (general_lengths(app).pixels_per_inch, app.session.prefs.numbers_without_units_are_points), app.session.perspective_presets(), app.session.new_perspective_preset_name(), @@ -171,6 +172,8 @@ pub fn open_edit(app: &mut VectorcraftApp, original: Option<&str>, base: &str) - pub(super) struct GridDialog { id: DialogId, mode: GridMode, + /// The document whose grid Define Grid edits. + source_document: Option, draft: GridDraft, /// The presets the Preset row offers, as the document and the preferences have them. presets: Vec, @@ -190,10 +193,18 @@ pub(super) struct GridDialog { } impl GridDialog { - fn new(def: GridDefinition, mode: GridMode, (ppi, bare_points): (f64, bool), presets: Vec, new_name: String) -> Self { + fn new( + def: GridDefinition, + mode: GridMode, + source_document: Option, + (ppi, bare_points): (f64, bool), + presets: Vec, + new_name: String, + ) -> Self { let mut dialog = GridDialog { id: dialog_id(KIND), mode, + source_document, draft: GridDraft { def }, presets: Vec::new(), rows: Vec::new(), @@ -482,7 +493,6 @@ impl StackDialog for GridDialog { .opened(Bind::bound(&mut self.open)) .ok_enabled(finish || !self.held.is_waiting()) .accept_stays_open(true) - .enter_confirms(false) .show(ui, |ui, form, draft| { if finish { form.request_close_as(CloseReason::Activated); @@ -517,9 +527,12 @@ enum Next { Presets(String), } -fn file(app: &mut VectorcraftApp, mode: &GridMode, def: &GridDefinition) -> Result { +fn file(app: &mut VectorcraftApp, mode: &GridMode, source_document: Option, def: &GridDefinition) -> Result { let mut params = serde_json::to_value(def).map_err(|e| e.to_string())?; if *mode == GridMode::Define { + if app.session.active().map(|st| st.uid) != source_document { + return Err(tl!("Define Grid can only change the document where it was opened.").to_owned()); + } app.run("perspective.grid.define", params)?; return Ok(Next::Close); } @@ -547,10 +560,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let filed = dialogs.with(|host| { let dialog = host.get_mut::()?; dialog.set_presets(presets, new_name); - dialog.held.take().map(|def| (dialog.mode.clone(), def)) + dialog.held.take().map(|def| (dialog.mode.clone(), dialog.source_document, def)) }); - let Some((mode, def)) = filed else { return }; - let next = file(app, &mode, &def); + let Some((mode, source_document, def)) = filed else { return }; + let next = file(app, &mode, source_document, &def); if let Err(why) = &next { app.status(why.clone()); } diff --git a/crates/ui-egui/src/dialogs/perspective_presets.rs b/crates/ui-egui/src/dialogs/perspective_presets.rs index c6d7ecb778..9d3f81d15d 100644 --- a/crates/ui-egui/src/dialogs/perspective_presets.rs +++ b/crates/ui-egui/src/dialogs/perspective_presets.rs @@ -307,7 +307,7 @@ pub(super) fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Resul }); } Action::Export => { - crate::io::save_command_output(app, "perspective.presets.export", PRESET_FORMAT, json!({ "names": [current] }), |_, _| Ok(Value::Null))?; + super::preset_manager::export(app, "perspective.presets.export", PRESET_FORMAT, current)?; } } Ok(()) diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index ff52df3db8..94b82a5259 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -12,6 +12,9 @@ //! filter or live effect with commands of its own is a submenu named after it, holding its item and //! then its commands; a command with parameters opens the same dialog for them ([`open_command`]). //! A command whose manifest names another menu is listed in that menu instead ([`place_commands`]). +//! Object › Plug-ins starts with Apply Last Filter and Last Filter…, which run the filter that last +//! ran again with the same parameters or open its dialog with them, and a filter's dialog opens with +//! the parameters it last ran with in the session ([`LastFilters`]). //! Exporters are formats of File › Export › Export As; one with parameters opens dialog //! `pluginExport` once the file is picked, and its Export button writes the file. Importers open the //! files File › Open finds no built-in format for, and File › Open With lists them; one with @@ -335,14 +338,20 @@ fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl } } -/// Opens the hosted dialog `key` for plug-in manifest `m` (an instance per `instance`), closing the -/// one open before → its id on the host and its rows. -fn open_hosted(app: &mut VectorcraftApp, key: &'static str, instance: &str, m: Manifest, look: Look) -> Result<(DialogId, Arc<[Param]>), String> { +/// Opens the hosted dialog `key` for plug-in manifest `m` (an instance per `instance`) with its rows +/// at `values`, closing the one open before → its id on the host and its rows. +fn open_hosted( + app: &mut VectorcraftApp, + key: &'static str, + instance: &str, + m: Manifest, + values: Map, + look: Look, +) -> Result<(DialogId, Arc<[Param]>), String> { let (Some(ctx), Some(dialogs)) = (app.ui_ctx.clone(), app.dialogs()) else { return Err("no window".into()) }; close_open(app); - let defaults = m.defaults(); - let all: Arc<[Param]> = form::plugin_params(&m, &defaults).into(); - let fields = form::fields_of(&all, &defaults); + let all: Arc<[Param]> = form::plugin_params(&m, &values).into(); + let fields = form::fields_of(&all, &values); let dialog = HostedParamDialog::new(&ctx, key, fields, build(key, m, Arc::clone(&all), look)).instance(instance.to_string()); let id = dialogs.with(|host| host.open(dialog)); Ok((id, all)) @@ -359,8 +368,186 @@ fn close_open(app: &mut VectorcraftApp) { } } +/// Object › Plug-ins' first items: Apply Last Filter, which runs the filter that last ran again with +/// the same parameters, and Last Filter…, which opens its dialog with them. Each is named after the +/// filter once one has run ([`last_filter_name`]). +pub fn last_filter_menu() -> Vec { + vec![c("Apply Last Filter", APPLY_LAST), c("Last Filter…", LAST), Sep] +} + +/// Apply Last Filter's command id. +pub const APPLY_LAST: &str = "plugin.applyLastFilter"; + +/// Last Filter…'s command id. +pub const LAST: &str = "plugin.lastFilter"; + +/// The error of Apply Last Filter and Last Filter… when no filter can run again: none ran in this +/// session, or the one that ran last was removed or installed again, or its parameters no longer fit it. +pub const NO_LAST_FILTER: &str = "no plug-in filter to repeat: run one from Object › Plug-ins first"; + +/// The most filters whose last parameters [`LastFilters`] keeps. +const MAX_REMEMBERED: usize = 64; + +/// The parameters filter `id` last ran with, as its manifest resolved them, and the installation +/// that ran with them (its [`Plugin::serial`]; installing the plug-in again gives it a new one). +#[derive(Clone, Debug, PartialEq)] +struct Used { + id: String, + serial: u64, + params: Map, +} + +/// The parameters each object filter last ran with in this session (`plugin.run`), the filter that +/// ran last at the end, for at most [`MAX_REMEMBERED`] filters. They are never saved. +#[derive(Default)] +pub struct LastFilters { + used: Vec, +} + +impl LastFilters { + /// The id of the filter that ran last, whether or not it can run again. + pub fn last_id(&self) -> Option<&str> { + self.used.last().map(|u| u.id.as_str()) + } +} + +/// Notes a `plugin.run` with params `p` that succeeded: its filter ran last, with the +/// parameters its manifest resolves from `p`. Anything else (not a filter, parameters the manifest +/// refuses) is not noted. +pub(crate) fn record(app: &mut VectorcraftApp, p: &Value) { + let Some(plugin) = p.get("id").and_then(Value::as_str).and_then(registry::get) else { return }; + let m = plugin.manifest(); + if m.kind != Kind::Filter { + return; + } + let Ok(params) = m.resolve_params(&vectorcraft_engine::cmd::plugin::plugin_params(p)) else { return }; + let used = &mut app.last_filters.used; + used.retain(|u| u.id != m.id); + used.push(Used { id: m.id.clone(), serial: plugin.serial(), params }); + if used.len() > MAX_REMEMBERED { + used.remove(0); + } +} + +/// The plug-in registry's revision before a command runs, for [`after_command`]. +pub(crate) fn before_command() -> u64 { + registry::revision() +} + +/// After command `id` with `params` ran with result `r`, the registry at revision `before` when it +/// started: a `plugin.run` that succeeded, or each `plugin.run` step of a batch that succeeded +/// (`command.batch`, or `action.batch` on at least one file or data set) in the order they ran, is +/// noted ([`record`]), so the last one is the filter that ran last. +pub(crate) fn after_command(app: &mut VectorcraftApp, id: &str, params: &Value, r: &Result, before: u64) { + let Ok(reply) = r else { return }; + // Action Batch returns success even when files or data sets fail, and runs every step on each + // one that doesn't. + let played = |v: &Value| v.get("count").and_then(Value::as_u64).unwrap_or(0) > v.get("failed").and_then(Value::as_u64).unwrap_or(0); + match id { + CMD => record(app, params), + "command.batch" | "action.batch" if id == "command.batch" || played(reply) => { + let steps = params.get("commands").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); + // `command.batch` returns each step's result; Action Batch returns none. + let results = reply.get("results").and_then(Value::as_array); + // Every filter step is noted in the order the steps ran, so the last one is the filter + // that ran last and a filter that ran twice keeps its newest parameters. + for (at, s) in steps.iter().enumerate().filter(|(_, s)| step_id(s) == Some(CMD)) { + let p = s.get("params").unwrap_or(&Value::Null); + let ran = p.get("id").and_then(Value::as_str).unwrap_or_default(); + // The plug-in installed under the id now is the one that ran when no later step may + // have changed it, or when it was installed before the batch (installing gives a new + // serial). + let changed_later = (at + 1..steps.len()).any(|i| may_change(&steps[i], results.and_then(|r| r.get(i)), ran)); + let installed_before = registry::get(ran).is_some_and(|q| q.serial() <= before); + match changed_later && !installed_before { + true => forget(app, p), + false => record(app, p), + } + } + } + _ => {} + } +} + +/// The command id of batch step `s`. +fn step_id(s: &Value) -> Option<&str> { + s.get("command").and_then(Value::as_str) +} + +/// Whether batch step `s`, which returned `result` if the batch reports it, may have installed, +/// removed or reloaded plug-in `id`: a removal names its id, an install reports the id it installed, +/// and a reload, or an install whose result is not known, may change any plug-in. +fn may_change(s: &Value, result: Option<&Value>, id: &str) -> bool { + match step_id(s) { + Some("plugin.remove") => s.get("params").and_then(|p| p.get("id")).and_then(Value::as_str) == Some(id), + Some("plugin.install") => result.and_then(|r| r.get("id")).and_then(Value::as_str).is_none_or(|i| i == id), + Some("plugin.reload") => true, + _ => false, + } +} + +/// Notes the filter `plugin.run` params `p` name as the one that ran last, without parameters or a +/// module, so that Apply Last Filter and Last Filter… stay off until a filter runs again. +fn forget(app: &mut VectorcraftApp, p: &Value) { + let Some(id) = p.get("id").and_then(Value::as_str) else { return }; + let used = &mut app.last_filters.used; + used.retain(|u| u.id != id); + // Serial 0 belongs to no installed plug-in. + used.push(Used { id: id.to_string(), serial: 0, params: Map::new() }); + if used.len() > MAX_REMEMBERED { + used.remove(0); + } +} + +/// Filter `id`'s last parameters, while the installation that ran with them is still installed under +/// its id and its manifest takes them as they are. +fn remembered(app: &VectorcraftApp, id: &str) -> Option<(Arc, Map)> { + let used = app.last_filters.used.iter().find(|u| u.id == id)?; + let plugin = registry::get(id).filter(|p| p.manifest().kind == Kind::Filter && p.serial() == used.serial)?; + let params = Value::Object(used.params.clone()); + plugin.manifest().resolve_params(¶ms).ok().filter(|r| *r == used.params)?; + Some((plugin, used.params.clone())) +} + +/// The filter that ran last and its parameters, while it can run again with them ([`remembered`]). +pub(crate) fn last_filter(app: &VectorcraftApp) -> Option<(Arc, Map)> { + remembered(app, app.last_filters.last_id()?) +} + +/// The name Apply Last Filter and Last Filter… show once a filter ran that can run again +/// ([`last_filter`]): the filter's own name, without an ellipsis at its end and with hidden +/// characters shown as escapes, as a submenu named after a plug-in shows it. `None` before. +pub(crate) fn last_filter_name(app: &VectorcraftApp) -> Option { + let (plugin, _) = last_filter(app)?; + let name = plugin.manifest().name.trim().trim_end_matches('…').trim_end().to_string(); + Some(permissions::display_text(&name, permissions::MAX_SHOWN_NAME)) +} + +/// `plugin.applyLastFilter`: runs the filter that ran last again, with the same parameters, on the +/// selection, without its dialog, as its menu item runs it ([`run`]). +pub fn apply_last(app: &mut VectorcraftApp) -> Result { + app.session.active().ok_or("no document open")?; + let (plugin, params) = last_filter(app).ok_or(NO_LAST_FILTER)?; + let p = json!({"id": plugin.id(), "params": params}); + run(app, &plugin, p) +} + +/// `plugin.lastFilter`: opens the dialog of the filter that ran last with the parameters it ran +/// with; one without parameters runs at once, as its menu item runs it. +pub fn open_last(app: &mut VectorcraftApp) -> Result { + app.session.active().ok_or("no document open")?; + let (plugin, params) = last_filter(app).ok_or(NO_LAST_FILTER)?; + if plugin.manifest().params.is_empty() { + return run(app, &plugin, json!({"id": plugin.id(), "params": params})); + } + let m = plugin.manifest(); + open_filter(app, &plugin, m.clone(), None, m.name.trim_end_matches('…').to_string(), params)?; + Ok(Value::Null) +} + /// `plugin.dialog {id, params?}`: run filter `id` at once when it takes no parameters or `params` -/// are given, else open its dialog prefilled with its defaults. +/// are given, else open its dialog prefilled with the parameters it last ran with in this session +/// ([`remembered`]), or with its defaults. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let id = p.get("id").and_then(Value::as_str).ok_or("missing `id` (see plugin.list)")?; let plugin = registry::get(id).ok_or_else(|| format!("no plug-in {id:?} is installed"))?; @@ -375,18 +562,26 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if m.params.is_empty() || given.is_some() { return run(app, &plugin, json!({"id": id, "params": given.cloned().unwrap_or(Value::Null)})); } - open_filter(app, &plugin, m.clone(), None, m.name.trim_end_matches('…').to_string())?; + let values = remembered(app, id).map(|(_, params)| params).unwrap_or_else(|| m.defaults()); + open_filter(app, &plugin, m.clone(), None, m.name.trim_end_matches('…').to_string(), values)?; Ok(Value::Null) } /// Opens the dialog of filter `plugin`, or of its command `command`, with `m` the manifest it runs -/// with, headed `heading`: the rows at their defaults, with a live Preview for a light filter. -fn open_filter(app: &mut VectorcraftApp, plugin: &Plugin, m: Manifest, command: Option, heading: String) -> Result<(), String> { +/// with, headed `heading`: the rows at `values`, with a live Preview for a light filter. +fn open_filter( + app: &mut VectorcraftApp, + plugin: &Plugin, + m: Manifest, + command: Option, + heading: String, + values: Map, +) -> Result<(), String> { let own = plugin.manifest(); let light = own.budget == Budget::Light; let look = Look { title: heading.clone(), description: own.description.clone(), previews: light, note: !light, ok: None }; let instance = command.as_deref().unwrap_or(plugin.id()).to_string(); - let (id, params) = open_hosted(app, KIND, &instance, m, look)?; + let (id, params) = open_hosted(app, KIND, &instance, m, values, look)?; let kind = Opened::Filter { plugin: plugin.id().to_string(), command, @@ -409,7 +604,9 @@ pub fn open_command(app: &mut VectorcraftApp, id: &str) -> bool { if c.params.is_empty() || app.session.active().is_none() { return false; } - if let Err(e) = open_filter(app, &plugin, plugin.manifest().for_command(&c), Some(id.to_string()), c.shown_label().to_string()) { + let m = plugin.manifest().for_command(&c); + let defaults = m.defaults(); + if let Err(e) = open_filter(app, &plugin, m, Some(id.to_string()), c.shown_label().to_string(), defaults) { app.status(e); } true @@ -457,7 +654,7 @@ pub fn open_export(app: &mut VectorcraftApp, plugin: &Plugin, export: Value) { note: false, ok: Some(tl!("Export")), }; - match open_hosted(app, EXPORT_KIND, plugin.id(), m.clone(), look) { + match open_hosted(app, EXPORT_KIND, plugin.id(), m.clone(), m.defaults(), look) { Ok((id, params)) => app.plugin_dialog = Some(PluginDialog { id, kind: Opened::Export { plugin: plugin.id().to_string(), export, params } }), Err(e) => app.status(e), } @@ -475,7 +672,7 @@ pub fn open_import(app: &mut VectorcraftApp, plugin: &Plugin, open: Value) { note: false, ok: Some(tl!("Open")), }; - match open_hosted(app, IMPORT_KIND, plugin.id(), m.clone(), look) { + match open_hosted(app, IMPORT_KIND, plugin.id(), m.clone(), m.defaults(), look) { Ok((id, params)) => app.plugin_dialog = Some(PluginDialog { id, kind: Opened::Import { plugin: plugin.id().to_string(), open, params } }), Err(e) => app.status(e), } @@ -511,7 +708,15 @@ fn confirm_filter(app: &mut VectorcraftApp, kind: Opened, values: Map preview.commit(app, &cmd, p), + _ => { + let r = preview.commit(app, &cmd, p.clone()); + // A kept preview commits without running `plugin.run` again ([`after_command`]); for + // the filter's own run, `p` is `plugin.run`'s `{id, params}`. + if r.is_ok() && own.is_none() { + record(app, &p); + } + r + } } } diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 8bf05fe7d8..3a69a42763 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -1,7 +1,7 @@ //! The raster export options: PNG Options (resolution, background, anti-aliasing, interlaced), //! JPEG Options (no transparency; colour model, quality 0–10, method and scans, profile, image //! map), WebP Options (lossless, or lossy at a quality 0–100), and PNG-8 and GIF Options (the palette: colour reduction, colours, dither, -//! transparency and matte), TIFF, BMP and Targa Options ([`super::tiff_bmp_tga`]) and PSD Options +//! transparency and its dither, matte), TIFF, BMP and Targa Options ([`super::tiff_bmp_tga`]) and PSD Options //! ([`super::psd_options`]). Fields //! are `document.export` params (format, path, artboard choice…); `__`-prefixed ones are the //! dialog's. @@ -43,6 +43,8 @@ const IMAGE_MAP_LABELS: [&str; 3] = ["None", "Client-side (.html)", "Server-side /// Matte param values and their labels (`Other`: a colour). const MATTES: [&str; 3] = ["none", "white", "black"]; const MATTE_LABELS: [&str; 4] = ["None", "White", "Black", "Other"]; +/// The Transparency Dither labels, in [`Dither::ALL`] order. +const TRANSPARENCY_DITHER_LABELS: [&str; 4] = ["No Transparency Dither", "Diffusion", "Pattern", "Noise"]; /// JPEG quality on the dialog's 0–10 scale: the band each step falls in. const QUALITY_BANDS: [&str; 11] = ["Low", "Low", "Low", "Medium", "Medium", "Medium", "High", "High", "Maximum", "Maximum", "Maximum"]; /// WebP compression labels: `lossless` true, then false. @@ -135,6 +137,8 @@ pub(super) fn defaults(app: &VectorcraftApp, f: &Format) -> Map { ("dither".into(), json!(p.dither.id())), ("ditherAmount".into(), json!(p.dither_amount)), ("transparency".into(), json!(p.transparency)), + ("transparencyDither".into(), json!(p.transparency_dither.id())), + ("transparencyDitherAmount".into(), json!(p.transparency_dither_amount)), ("matte".into(), json!(MATTES[1])), ("interlaced".into(), json!(false)), ]); @@ -248,7 +252,7 @@ fn resolution_row() -> Param { fn size_row(w: f64, h: f64) -> Param { Param::custom("__sizeText", tl!("Size:"), move |ui, fields, _| { let (pw, ph) = vectorcraft_render::region_pixels(vectorcraft_geom::Rect::new(0.0, 0.0, w, h), fields.number("ppi").unwrap_or(72.0) / 72.0); - ui.label(format!("{pw} × {ph} px")) + Text::new(format!("{pw} × {ph} px")).show(ui) }) } @@ -345,7 +349,8 @@ fn webp_rows() -> Vec { } /// The PNG-8 and GIF Options rows: the palette (reduction, colours, dither and amount), -/// transparency and matte, interlacing. +/// transparency and matte, interlacing, and Transparency Dither with the amount Diffusion uses +/// (both disabled while Transparency is off, keeping their values). fn palette_rows() -> Vec { let dithering = Dither::ALL.iter().copied().filter(|d| *d != Dither::None).map(Dither::id); vec![ @@ -355,6 +360,11 @@ fn palette_rows() -> Vec { Param::new("ditherAmount", tl!("Dither Amount:"), ParamKind::int(Some(0), Some(100), 100)).enabled_when_in("dither", dithering), color_choice("matte", tl!("Matte:"), &MATTES, &MATTE_LABELS, |_| 0), check("transparency", tl!("Transparency"), true), + choice("transparencyDither", tl!("Transparency Dither:"), &Dither::ALL.map(Dither::id), &TRANSPARENCY_DITHER_LABELS) + .enabled_when("transparency", true), + Param::new("transparencyDitherAmount", tl!("Transparency Dither Amount:"), ParamKind::int(Some(0), Some(100), 100)) + .visible_when("transparencyDither", Dither::Diffusion.id()) + .enabled_when("transparency", true), check("interlaced", tl!("Interlaced"), false), ] } diff --git a/crates/ui-egui/src/dialogs/preset_manager.rs b/crates/ui-egui/src/dialogs/preset_manager.rs index 1ec0cead83..ed62539226 100644 --- a/crates/ui-egui/src/dialogs/preset_manager.rs +++ b/crates/ui-egui/src/dialogs/preset_manager.rs @@ -160,8 +160,8 @@ pub(crate) fn above(saved: Option, built_ins: usize) -> usize { (saved.unwrap_or(0) + built_ins).saturating_sub(1) } -/// Ask for a preset file and run `command` on it, then select the first preset it imported in the open manager -/// `key`. Returns at once: the answer arrives later. +/// Ask for a preset file and run `command` on it. Select the first imported preset if the manager +/// that opened the picker is still open. pub(crate) fn import( app: &mut VectorcraftApp, key: &'static str, @@ -169,20 +169,43 @@ pub(crate) fn import( filter: &str, exts: &[&str], ) -> Result, String> { - // PLAN: assumed `file_asks::open_params(&Picked) -> Option>` (fl.A23) also names a picked file - // of the web, which the import commands may not read yet. + let id = dialog_id(key); + let opening = with_manager(app, id, |manager| Arc::clone(&manager.opening)); let request = PickRequest::open(key).filter(filter, exts); file_asks::ask(app, request, Owner::Free, move |app, picked| { - let params = file_asks::open_params(&picked).ok_or("cancelled")?; + let mut params = file_asks::open_params(&picked).ok_or("cancelled")?; + // Preset import commands take the file contents without the browser's suggested name. + params.remove("name"); let imported = app.run(command, Value::Object(params))?; - if let Some(first) = imported["imported"].get(0).and_then(Value::as_str) { - with_manager(app, dialog_id(key), |manager| manager.selected = first.to_owned()); + if let (Some(opening), Some(first)) = (opening, imported["imported"].get(0).and_then(Value::as_str)) { + with_manager(app, id, |manager| { + if Arc::ptr_eq(&opening, &manager.opening) { + manager.selected = first.to_owned(); + } + }); } Ok(imported) }); Ok(None) } +/// Export…: run `command` on the preset `name` and write its file through a save panel that suggests +/// [`export_file_name`] (the web downloads it under that name). Returns at once: the answer arrives later. +pub(crate) fn export(app: &mut VectorcraftApp, command: &str, ext: &str, name: &str) -> Result, String> { + let file = export_file_name(name, ext); + crate::io::save_command_output_named(app, command, &file, serde_json::json!({ "names": [name] }), |_, _| Ok(Value::Null))?; + Ok(None) +} + +/// The file name Export… suggests for the preset `name`: the name without a built-in preset's brackets +/// (`[Default]`), made safe as a file name as Export Library… makes a library's +/// (`library::file_stem_for`), with the extension `ext`; "Preset" when no name is left. +pub(crate) fn export_file_name(name: &str, ext: &str) -> String { + let stem = name.trim().trim_start_matches('[').trim_end_matches(']').trim(); + let stem = if stem.is_empty() { "Preset" } else { stem }; + format!("{}.{ext}", vectorcraft_engine::cmd::library::file_stem_for(stem)) +} + /// Opens the manager of `source` on the preset `selected` (the first one when none has that name). pub(crate) fn open(app: &mut VectorcraftApp, source: &'static Source, selected: &str) { let rows = (source.rows)(app); @@ -203,6 +226,8 @@ fn with_manager(app: &VectorcraftApp, id: DialogId, f: impl FnOnce(&mut Prese /// A preset manager dialog: draws the rows and the detail it holds and queues the user's events. pub(crate) struct PresetManager { id: DialogId, + /// Distinguishes successive openings that share the same dialog ID. + opening: Arc<()>, source: &'static Source, title: Label, rows: Vec, @@ -220,6 +245,7 @@ impl PresetManager { fn new(source: &'static Source, rows: Vec, selected: String, stored: Value, detail: Vec) -> Self { let mut manager = PresetManager { id: dialog_id(source.key), + opening: Arc::new(()), source, title: Label::from((source.title)()), rows: Vec::new(), diff --git a/crates/ui-egui/src/dialogs/preview.rs b/crates/ui-egui/src/dialogs/preview.rs index 2ef2bd99e7..60bf25a04a 100644 --- a/crates/ui-egui/src/dialogs/preview.rs +++ b/crates/ui-egui/src/dialogs/preview.rs @@ -48,20 +48,28 @@ impl LivePreview { Some(answer) } - /// OK: keeps the previewed `cmd` as one undo step (or runs it when no preview runs); the command's warning shows - /// in the status bar either way. On an error the dialog stays open. + /// OK: keeps the previewed `cmd` as one undo step (or runs it when no preview runs); the command's warning, or a + /// plug-in run's notice, shows in the status bar either way. On an error the dialog stays open. pub(crate) fn commit(self, app: &mut VectorcraftApp, cmd: &str, params: Value) -> Result { if !app.session.in_interaction() { return app.run(cmd, params); } - let v = app.session.preview(cmd, ¶ms).map_err(|e| e.to_string())?; - let r = app.session.commit_interaction().map(|_| Value::Null).map_err(|e| e.to_string()); - if r.is_ok() - && let Some(w) = v.get("warning").and_then(Value::as_str) - { - app.status(w.to_string()); + let result = app.session.preview(cmd, ¶ms).and_then(|answer| { + app.session.commit_interaction()?; + Ok(answer) + }); + let answer = match result { + Ok(answer) => answer, + Err(error) => { + self.cancel(app); + return Err(error.to_string()); + } + }; + if let Some(warning) = answer.get("warning").and_then(Value::as_str) { + app.status(warning.to_string()); } - r + crate::plugin_runs::show_notice(app, cmd, &answer); + Ok(Value::Null) } /// Cancel: rolls a shown preview back. @@ -103,6 +111,31 @@ mod tests { } } + #[test] + fn refused_confirmation_restores_the_art_and_ends_the_preview() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + let original = app.session.doc().unwrap().doc.clone(); + let undo = app.session.doc().unwrap().history.undo.len(); + + let mut preview = LivePreview::default(); + let fill = json!({"color": "#00a000"}); + assert!(matches!(preview.run(&mut app, true, "Fill Color", "paint.setFill", &fill), Some(Ok(_)))); + assert_ne!(app.session.doc().unwrap().doc, original); + assert!(preview.commit(&mut app, "paint.setFill", json!({"color": true})).is_err()); + assert!(!app.session.in_interaction(), "the refused edit left no open interaction"); + assert_eq!(app.session.doc().unwrap().doc, original); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + + let mut next = LivePreview::default(); + assert!(matches!(next.run(&mut app, true, "Next Fill", "paint.setFill", &fill), Some(Ok(_)))); + next.commit(&mut app, "paint.setFill", fill).unwrap(); + let history = &app.session.doc().unwrap().history; + assert_eq!(history.undo.len(), undo + 1); + assert_eq!(history.undo.last().unwrap().label, "Next Fill"); + } + /// A dialog's preview while typing is in progress keeps the typing as its own step and starts /// from it; the status bar shows the warning of the typing's preview that keeping it applied. #[test] diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 255495d286..e911e7c0a2 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -35,7 +35,7 @@ use craft::ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook}; use craft::ui::primitives::IconSpec; use craft::ui::runtime::env::{LengthUnits, UnitKind}; use craft::ui::shell::WindowDialogs; -use craft::ui::text::{LinkMode, LinkedFields, NumberField}; +use craft::ui::text::{LinkMode, LinkedFields, NumberField, SelectableText}; use serde_json::{Map, Value, json}; use vectorcraft_color::cms::Intent; use vectorcraft_engine::cmd::printpresets::DEFAULT_PRESET; @@ -669,9 +669,9 @@ fn scaling_ids(tiles: bool) -> Vec<&'static str> { PrintScaling::ALL.iter().filter(|s| s.tiles() == tiles).map(|s| s.id()).collect() } -/// A summary line that the pump fills (`key` is a `__` companion of the fields). -fn shown(key: &'static str) -> Param { - Param::custom(key, "", move |ui, fields, _| ui.label(fields.text(key).unwrap_or_default())) +/// A summary line that the pump fills (`key` is a `__` companion of the fields), selectable and named `label`. +fn shown(key: &'static str, label: &'static str) -> Param { + Param::custom(key, "", move |ui, fields, _| SelectableText::new(label, fields.text(key).unwrap_or_default()).multiline().show(ui)) } /// The sections of the dialog, with the rows of each. @@ -827,11 +827,11 @@ fn sections(lists: &Lists) -> Vec { ]; let summary = vec![ Param::section(tl!("Pages")), - shown("__summary.pages"), + shown("__summary.pages", tl!("Pages")), Param::section(tl!("Options")), - shown("__summary.options"), + shown("__summary.options", tl!("Options")), Param::section(tl!("Warnings")), - shown("__summary.warnings"), + shown("__summary.warnings", tl!("Warnings")), ]; [general, marks, output, graphics, color, advanced, summary] .into_iter() diff --git a/crates/ui-egui/src/dialogs/print_presets.rs b/crates/ui-egui/src/dialogs/print_presets.rs index e69e7f5e7e..fc5e1b1d0b 100644 --- a/crates/ui-egui/src/dialogs/print_presets.rs +++ b/crates/ui-egui/src/dialogs/print_presets.rs @@ -77,9 +77,6 @@ fn run(app: &mut VectorcraftApp, event: &ManagerEvent, current: &str) -> Result< Ok(rows(app).get(preset_manager::above(i, 1)).map(|row| row.name.clone())) } ManagerAction::Import => preset_manager::import(app, KEY, "print.presets.import", "Print presets", PRESET_EXTS), - ManagerAction::Export => { - crate::io::save_command_output(app, "print.presets.export", PRESET_FORMAT, json!({ "names": [current] }), |_, _| Ok(Value::Null))?; - Ok(None) - } + ManagerAction::Export => preset_manager::export(app, "print.presets.export", PRESET_FORMAT, current), } } diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs index 1ffc090a25..fc415fbcda 100644 --- a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -475,6 +475,7 @@ fn opening_and_pasting_ask_about_profiles() { assert_eq!(count(&app), before + 1); swatch_conflicts_are_asked_again_when_they_change(&mut app); all_artboards_leaves_backgrounds_out(&mut app); + all_artboards_asks_no_swatch_conflict_for_backgrounds(&mut app); // It changes the working space: last. app.run("edit.colorSettings", json!({"askMismatchOpen": true})).unwrap(); an_answer_waits_for_the_question_it_answers(&mut app, &tagged); @@ -500,3 +501,27 @@ fn all_artboards_leaves_backgrounds_out(app: &mut VectorcraftApp) { assert_eq!(listed(app, "edit.paste"), Some(1), "the background is RGB"); assert_eq!(listed(app, ALL_ARTBOARDS), Some(0)); } + +/// Swatch Conflict for Paste on All Artboards asks about the colors it brings, without the +/// backgrounds of copied artboards: pasting back into the document the art came from, where only +/// the RGB background now has another profile, converts nothing, so the edited CMYK swatch is no +/// conflict and the paste runs. A plain paste converts the background and asks. +fn all_artboards_asks_no_swatch_conflict_for_backgrounds(app: &mut VectorcraftApp) { + use super::super::swatch_conflict; + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Brand", "color": {"c": 20, "m": 40, "y": 60, "k": 10}, "global": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("paint.setFill", json!({"swatch": "Brand"})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + app.run("artboard.setProps", json!({"index": 0, "color": "#3366cc"})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("artboard.copy", json!({"index": 0})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": null })).unwrap(); + app.run("swatch.edit", json!({"name": "Brand", "color": {"c": 60, "m": 40, "y": 20, "k": 0}})).unwrap(); + let r = app.run("edit.paste", json!({"profileMismatch": "convert"})).unwrap(); + assert_eq!(r["dialog"], swatch_conflict::KIND, "{r}"); + answer_cancel(app, swatch_conflict::id(app).expect("Swatch Conflict is open")); + let r = app.run(ALL_ARTBOARDS, json!({"profileMismatch": "convert"})).unwrap(); + assert!(r.get("dialog").is_none() && r["ids"].as_array().is_some_and(|ids| !ids.is_empty()), "{r}"); + assert!(swatch_conflict::id(app).is_none()); +} diff --git a/crates/ui-egui/src/dialogs/proof_setup.rs b/crates/ui-egui/src/dialogs/proof_setup.rs index b4982f3710..a5987f699b 100644 --- a/crates/ui-egui/src/dialogs/proof_setup.rs +++ b/crates/ui-egui/src/dialogs/proof_setup.rs @@ -17,7 +17,7 @@ //! `intent`, `simulatePaper`, `simulateBlack` and `preview`. use std::path::{Path, PathBuf}; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use craft::host::queue::{JobQueue, Priority, QueueOptions}; use craft::host::{PickRequest, Picked, Wake}; @@ -32,7 +32,7 @@ use vectorcraft_render::proof; use super::host::{HeldOptions, open_held_with}; use crate::VectorcraftApp; -use crate::file_asks::{Owner, ask}; +use crate::file_asks::{Owner, ask, ask_while}; use crate::menus::Node; /// The dialog kind of Proof Setup › Customize. @@ -53,6 +53,8 @@ const LOAD_BUTTON: &str = "load"; pub(crate) struct Open { /// The dialog on the window's stack. id: DialogId, + /// The identity of this opening, since Proof Setup reuses the dialog ID. + opening: Arc<()>, /// The proof view the dialog found, which Cancel puts back after a preview. before: proof::ProofView, /// The proof view the preview last put on the canvas; `None` while no preview of this dialog is shown. @@ -89,7 +91,7 @@ pub fn open(app: &mut VectorcraftApp) { let dialog = HostedParamDialog::new(&ctx, KIND, fields, build); let options = HeldOptions { cancel: Some(Box::new(cancel)), ..Default::default() }; match open_held_with(app, dialog, |app, result: &ParamResult| confirm(app, &result.fields), options) { - Some(id) => app.ui.proof_setup = Some(Open { id, before, shown: None, sent: None }), + Some(id) => app.ui.proof_setup = Some(Open { id, opening: Arc::new(()), before, shown: None, sent: None }), None => app.status(tl!("There is no window to show Proof Setup in.")), } } @@ -330,12 +332,17 @@ fn save(app: &mut VectorcraftApp, fields: &DialogFields) { /// Load…: the picked file's settings fill the dialog `id` (Preview then shows them). fn load(app: &mut VectorcraftApp, id: DialogId) { + let Some(opening) = app.ui.proof_setup.as_ref().filter(|open| open.id == id).map(|open| Arc::clone(&open.opening)) else { return }; let mut request = PickRequest::open("proof-setups").filter("Proof setups", &[EXT]); // Before a setup is saved there is no folder, and the picker starts in its own default folder. if let Some(dir) = app.session.proof_setup_dir().filter(|dir| dir.is_dir()) { request = request.directory(dir); } - ask(app, request, Owner::Free, move |app, picked| { + let is_live = move |app: &VectorcraftApp| { + app.ui.proof_setup.as_ref().is_some_and(|open| open.id == id && Arc::ptr_eq(&opening, &open.opening)) + && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::(id).is_some())) + }; + ask_while(app, request, Owner::Free, is_live, move |app, picked| { let Some(path) = picked.first_path() else { return Ok(Value::Null) }; let r = app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))?; let fields = [ @@ -345,7 +352,6 @@ fn load(app: &mut VectorcraftApp, id: DialogId) { ("simulatePaper", "simulatePaper"), ("simulateBlack", "simulateBlack"), ]; - // The dialog may have closed while the picker was open: then there is nothing to fill. // PLAN: sh.K23's `set_json_fields` refuses a row that is disabled by the file's own device (an RGB // device disables paper and black ink), so the whole load would fail; the values are set unchecked. if let Some(dialogs) = app.dialogs() { @@ -811,6 +817,39 @@ mod tests { assert_eq!((v.setup.target, v.setup.intent), (ProofTarget::Rgb(cms::DISPLAY_P3.into()), Intent::Saturation)); } + #[test] + fn a_delayed_load_only_changes_the_proof_setup_that_requested_it() { + let _view = DefaultProofView::new(); + let (mut app, ctx) = app(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-delayed-load"); + let file = dir.join(format!("Pending.{EXT}")); + app.run("view.proofSetup.save", json!({"path": file.to_string_lossy(), "target": WORKING, "intent": "saturation"})).unwrap(); + let files = scripted(&mut app, ScriptedFiles::held()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + press(&mut app, &ctx, LOAD_BUTTON); + assert_eq!(files.requests().len(), 1, "Load requested a file"); + cancel_dialog(&mut app, &ctx); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + set(&mut app, &ctx, "intent", json!("perceptual")); + set(&mut app, &ctx, "preview", json!(true)); + let view = proof::view(); + + files.answer(Picked::Paths(vec![file.clone()])); + crate::file_asks::poll(&mut app); + pump(&mut app, &ctx); + assert_eq!(values(&app)["intent"], "perceptual", "the reopened dialog keeps its own rendering intent"); + assert_eq!(proof::view(), view, "the reopened dialog keeps its own proof preview"); + + press(&mut app, &ctx, LOAD_BUTTON); + assert_eq!(files.requests().len(), 2, "Load in the current opening requested a file"); + files.answer(Picked::Paths(vec![file])); + crate::file_asks::poll(&mut app); + pump(&mut app, &ctx); + assert_eq!(values(&app)["intent"], "saturation", "a reply to the current opening fills the dialog"); + assert_eq!(proof::view().setup.intent, Intent::Saturation, "the current opening previews the loaded setup"); + cancel_dialog(&mut app, &ctx); + } + /// Save… whose picker is canceled saves nothing and leaves no Proof Setups folder behind; the /// folder stays while the picker is open and when a file is saved in it. #[test] diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 9d2ca82832..3768c182d2 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -262,16 +262,45 @@ pub(crate) struct Open { pub preview: LivePreview, } -/// Open Recolor Artwork (`ui.recolorDialog {colors?, library?, group?}`) on the selected art and, -/// with `group`, on that colour group: art is reduced to as many rows as the group has colours, -/// which become their new colours; without art the rows are the group's colours. `colors` is a -/// count (an n-colour job) or the new colours to assign (without art or a group they are the +/// Open Recolor Artwork (`ui.recolorDialog {colors?, library?, group?, preset?}`) on the selected +/// art and, with `group`, on that colour group: art is reduced to as many rows as the group has +/// colours, which become their new colours; without art the rows are the group's colours. `colors` +/// is a count (an n-colour job) or the new colours to assign (without art or a group they are the /// rows, which OK saves as a new colour group); `library` limits to a library or "document" ("" -/// picks the first library). +/// picks the first library). With `preset: true` the Recolor with Preset dialog opens first. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { + match p.get("preset") { + None | Some(Value::Bool(false)) => {} + Some(Value::Bool(true)) => return super::recolor_preset::open(app, p), + Some(_) => return Err("`preset` must be true or false".into()), + } let st = app.session.active().ok_or("no document open")?; let art = !st.selection.is_empty(); - let group = p.get("group").and_then(Value::as_str); + let group = match p.get("group") { + None | Some(Value::Null) => None, + Some(Value::String(g)) => Some(g.as_str()), + Some(_) => return Err("`group` must be a colour group name".into()), + }; + // The group is looked for in the document without the preview of a Recolor Artwork this one + // replaces (which can rename the group), as that dialog's rollback below leaves it. + let unpreviewed = match &st.interaction { + Some(it) if app.color_dialogs.recolor.is_some() => &it.doc, + _ => &st.doc, + }; + if let Some(g) = group + && !unpreviewed.swatch_groups.iter().any(|x| x.name == g) + { + return Err(format!("no colour group `{g}`")); + } + // Colours alone (no art, no group) become a new colour group. + let new_group = !art && group.is_none(); + if new_group && !matches!(p.get("colors"), Some(Value::Array(cs)) if cs.iter().any(|c| color_value(c).is_some())) { + return Err("select artwork (or a colour group) to recolor".into()); + } + let limit = library_param(app, p)?; + // A Recolor Artwork still open is replaced: its preview goes before the group's colours are read. + cancel_open(app); + let st = app.session.active().ok_or("no document open")?; let group_colors: Option> = match group { Some(g) => { let g = st.doc.swatch_groups.iter().find(|x| x.name == g).ok_or_else(|| format!("no colour group `{g}`"))?; @@ -284,21 +313,11 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { (None, Some(Value::Array(cs))) => cs.iter().filter_map(color_value).map(|c| key(&c)).collect(), _ => vec![], }; - // Colours alone (no art, no group) become a new colour group. - let new_group = !art && group.is_none(); - if new_group && assign.is_empty() { - return Err("select artwork (or a colour group) to recolor".into()); - } let count = match p.get("colors").and_then(Value::as_u64) { Some(n) => json!(n.max(1)), None if !assign.is_empty() => json!(assign.len()), None => Value::Null, }; - let limit = match p.get("library").and_then(Value::as_str) { - Some("") => first_library(app).unwrap_or_default(), - Some(l) => limit_key(app, l)?, - None => String::new(), - }; // Without art the rows are the group's colours, as they are. let mut start: Vec = if art { vec![] } else { assign.iter().map(|k| json!({"from": [k], "to": k})).collect() }; number_slots(&mut start); @@ -317,10 +336,6 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let mut rs = rows(&d); snap(app, &d, &mut rs); d.fields.insert("rows".into(), Value::Array(rs)); - // A Recolor Artwork still open is replaced: its preview goes before this one's starts. - if let Some(old) = app.color_dialogs.recolor.take() { - old.preview.cancel(app); - } let dialog = RecolorDialog::new(app, d); let options = HeldOptions { cancel: Some(Box::new(cancelled)), ..HeldOptions::default() }; let id = open_held_with(app, dialog, confirm, options).ok_or("no window to show Recolor Artwork in")?; @@ -346,10 +361,43 @@ fn key(c: &Color) -> Value { /// The name a new colour group (opened on colours alone) starts with. const NEW_GROUP: &str = "Color Group"; +/// Ends an open Recolor Artwork as Cancel ends it: its preview is rolled back and it closes. +pub(super) fn cancel_open(app: &mut VectorcraftApp) { + let Some(old) = app.color_dialogs.recolor.take() else { return }; + let id = old.id; + old.preview.cancel(app); + if let (Some(dialogs), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) { + dialogs.with(|host| { + host.cancel_by_id(&ctx, id); + }); + } +} + fn first_library(app: &VectorcraftApp) -> Option { colour_libraries(app).into_iter().next().map(|l| l.id) } +/// Limit to Library's choices: the key `limitTo` takes and the name the menu shows. None, the +/// document's swatches, then the colour libraries: the built-in ones translated, those the user +/// saved or loaded by their names. +pub(super) fn library_choices(app: &VectorcraftApp) -> Vec<(String, String)> { + let libs = colour_libraries(app); + let fixed = [("", tl!("None")), (swatchlib::DOCUMENT_SWATCHES, tl!(DOCUMENT_SWATCHES))].map(|(k, n)| (k.to_owned(), n.to_owned())); + let named = libs.iter().map(|l| (l.id.clone(), library_panel::library_name(&l.id, &l.name).to_owned())); + fixed.into_iter().chain(named).collect() +} + +/// The `limitTo` key of `ui.recolorDialog`'s `library`: none without it or for null, the first +/// library for ""; a `library` that is not a string is an error. +pub(super) fn library_param(app: &VectorcraftApp, p: &Value) -> Result { + match p.get("library") { + Some(Value::String(l)) if l.is_empty() => Ok(first_library(app).unwrap_or_default()), + Some(Value::String(l)) => limit_key(app, l), + None | Some(Value::Null) => Ok(String::new()), + Some(_) => Err("`library` must be a library id or name".into()), + } +} + /// `recolor.reduce` parameters (Method only picks each row's colour, so changing it keeps the rows). fn reduce_params(d: &Fields) -> Value { json!({ @@ -1441,15 +1489,11 @@ struct Feed { impl Feed { fn of(app: &VectorcraftApp, d: &Fields) -> Feed { - // None, the document's swatches, then the colour libraries: the built-in ones translated, - // those the user saved or loaded by their names. - let libs = colour_libraries(app); - let fixed = [("", tl!("None")), (swatchlib::DOCUMENT_SWATCHES, tl!(DOCUMENT_SWATCHES))].map(|(k, n)| (k.to_owned(), n.to_owned())); - let named = libs.iter().map(|l| (l.id.clone(), library_panel::library_name(&l.id, &l.name).to_owned())); - let libraries = fixed.into_iter().chain(named).collect(); + let libraries = library_choices(app); Feed { + // The colour libraries follow None and the document's swatches. + first_library: libraries.get(2).map(|(k, _)| k.clone()), libraries, - first_library: libs.first().map(|l| l.id.clone()), groups: doc_groups(app), other_paints: other_paint_groups(app), previewing: app.session.in_interaction(), @@ -1461,6 +1505,7 @@ impl Feed { /// What the pump works on with the app, out of the host: the values, their steps and what `show` /// asked for. struct Work { + opening: Arc<()>, fields: Fields, steps: Steps, filed: Filed, @@ -1500,7 +1545,7 @@ impl Work { randomize(app, &mut self.fields, sb); } if filed.library { - pick_library(app); + pick_library(app, Arc::clone(&self.opening)); } let d = &mut self.fields; if let Some(before) = filed.edited { @@ -1547,16 +1592,16 @@ fn randomize(app: &mut VectorcraftApp, d: &mut Fields, sb: bool) { /// Other Library…: import a library (.ase, .acb, .gpl, .vcswatches or a document's swatches) and /// limit to it. -fn pick_library(app: &mut VectorcraftApp) { +fn pick_library(app: &mut VectorcraftApp, opening: Arc<()>) { let request = builtin_open_filters().fold(PickRequest::open("library"), |request, (name, exts)| request.filter(name, exts)); - // PLAN: assumed `file_asks::Owner::Free` (fl.A3's owner of a continuation no document holds), as appearance-w19 codes it. - crate::file_asks::ask(app, request, crate::file_asks::Owner::Free, |app, picked| { + // A loaded library belongs to the session. The Limit to Library choice belongs to the opening that asked. + crate::file_asks::ask(app, request, crate::file_asks::Owner::Free, move |app, picked| { let Some(path) = picked.first_path() else { return Ok(Value::Null) }; let r = app.run("swatch.library.load", json!({ "path": path }))?; let library = r["library"].clone(); if let Some(dialogs) = app.dialogs() { dialogs.with(|host| { - if let Some(d) = host.get_mut::() { + if let Some(d) = host.get_mut_by_id::(dialog_id(KIND)).filter(|d| Arc::ptr_eq(&opening, &d.opening)) { d.fields.fields.insert("limitTo".into(), library); } }); @@ -1577,6 +1622,12 @@ fn preview_params(d: &Fields) -> Option<(bool, &'static str, Value)> { }) } +/// The Limit to Library key (`"document"` or a library id) of `parent` when it is a Recolor Artwork +/// dialog that limits to a library: the library a Color Picker over it shows in its swatches view. +pub(super) fn limit_to(dialogs: &craft::ui::shell::WindowDialogs, parent: DialogId) -> Option { + dialogs.with(|host| host.get_by_id::(parent).map(|d| d.fields.str("limitTo"))).filter(|limit| !limit.is_empty()) +} + /// Runs the open dialog's live preview with `(on, command, params)`. fn run_preview(app: &mut VectorcraftApp, (on, cmd, params): (bool, &'static str, Value)) { let Some(mut live) = app.color_dialogs.recolor.as_mut().map(|open| std::mem::take(&mut open.preview)) else { return }; @@ -1715,6 +1766,8 @@ fn confirm(app: &mut VectorcraftApp, fields: &Fields) -> Result<(), String> { /// commits the recolour. pub(crate) struct RecolorDialog { id: DialogId, + /// The identity of this opening, since Recolor Artwork reuses its dialog ID. + opening: Arc<()>, fields: Fields, steps: Steps, held: HeldAnswer, @@ -1737,6 +1790,7 @@ impl RecolorDialog { fn new(app: &VectorcraftApp, fields: Fields) -> Self { RecolorDialog { id: dialog_id(KIND), + opening: Arc::new(()), feed: Feed::of(app, &fields), steps: Steps::opened(snapshot(&fields)), fields, @@ -1753,6 +1807,7 @@ impl RecolorDialog { /// The values, steps and requests, for the pump to work on with the app. fn take_work(&mut self) -> Work { Work { + opening: Arc::clone(&self.opening), fields: std::mem::take(&mut self.fields), steps: std::mem::replace(&mut self.steps, Steps::opened(Snapshot::new())), filed: std::mem::take(&mut self.filed), @@ -1807,10 +1862,7 @@ impl RecolorDialog { let mut preview = self.fields.bool("preview"); let footer = ResetFooter::new(ui, None, true); let RecolorDialog { fields, feed, filed, ends, row_menu, .. } = self; - // PLAN: Enter is not OK here: a form whose OK stays open closes on Enter without reporting it as its OK - // (form_dialogs/form.rs:429, :534), which would close a held dialog unanswered; the forms owner makes - // `FormDialog` report Enter as the pick of OK when `accept_stays_open` is on. - let mut form = FormDialog::new(tl!(TITLE), Bind::bound(fields)).accept_stays_open(true).enter_confirms(false).ok_enabled(!waiting); + let mut form = FormDialog::new(tl!(TITLE), Bind::bound(fields)).accept_stays_open(true).ok_enabled(!waiting); if art { form = form.preview(Some(Bind::bound(&mut preview))); } diff --git a/crates/ui-egui/src/dialogs/recolor/fixture.rs b/crates/ui-egui/src/dialogs/recolor/fixture.rs index a773d34093..b254285a5b 100644 --- a/crates/ui-egui/src/dialogs/recolor/fixture.rs +++ b/crates/ui-egui/src/dialogs/recolor/fixture.rs @@ -103,6 +103,11 @@ impl Recolor { self } + /// The widget that has the keyboard focus. + pub(crate) fn focused(&self) -> Option { + self.fixture.focused() + } + /// Sets `field` as `ui.dialog.set` does, before the next frame; a refused value leaves the /// dialog as it was. pub(crate) fn set(&mut self, field: &str, value: Value) -> Result<(), String> { diff --git a/crates/ui-egui/src/dialogs/recolor_preset.rs b/crates/ui-egui/src/dialogs/recolor_preset.rs new file mode 100644 index 0000000000..0d3020abb5 --- /dev/null +++ b/crates/ui-egui/src/dialogs/recolor_preset.rs @@ -0,0 +1,61 @@ +//! Edit → Edit Colors → Recolor with Preset: before Recolor Artwork opens on a preset (an n-color +//! job or Color Library), this dialog asks whether to limit the new colors to a swatch library +//! (`ui.recolorDialog {preset: true, colors?, library?}`, without `group`). OK opens Recolor Artwork with the +//! preset's colors and the library chosen (None: no limit); Cancel opens nothing. +//! +//! Fields: `limitTo` (a library id, `"document"` for the document's swatches, `""` for None), as +//! Recolor Artwork's. + +use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamKind, ParamResult}; +use craft::ui::runtime::env::Label; +use serde_json::{Value, json}; + +use super::recolor::{cancel_open, library_choices, library_param}; +use super::swatch_options::{NO_WINDOW, field_label, hosted}; +use crate::VectorcraftApp; + +/// The dialog kind of Recolor with Preset. +pub const KIND: &str = "recolorPreset"; + +/// Open the dialog for the preset of `p` (`colors`: a count; `library`: the library it starts on, +/// "" the first library) on the selected art. +pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { + let st = app.session.active().ok_or("no document open")?; + if st.selection.is_empty() { + return Err("select artwork to recolor".into()); + } + if p.get("group").is_some_and(|g| !g.is_null()) { + return Err("`group` does not apply to a preset".into()); + } + let colors = count(p.get("colors"))?; + let limit = library_param(app, p)?; + let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?; + // A Recolor Artwork this one opens over ends as Cancel ends it, its preview rolled back. + cancel_open(app); + let options = library_choices(app).into_iter().map(|(key, name)| (key, Label::from(name))).collect(); + let mut fields = DialogFields::new(); + fields.set("limitTo", limit.clone()); + let rows = vec![Param::new("limitTo", field_label(tl!("Limit to Library:")), ParamKind::choice(options, Some(limit)))]; + let dialog = hosted(&ctx, KIND, tl!("Recolor with Preset"), fields, rows, false); + // Recolor Artwork takes the dialog's place; when it cannot open, this dialog stays. + let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> { + let mut p = serde_json::Map::new(); + if let Some(n) = colors { + p.insert("colors".into(), json!(n)); + } + if let Some(limit) = answer.fields.text("limitTo").filter(|l| !l.is_empty()) { + p.insert("library".into(), json!(limit)); + } + super::recolor::open(app, &Value::Object(p)).map(|_| ()) + }; + super::host::open_held(app, dialog, ok).ok_or(NO_WINDOW)?; + Ok(Value::Null) +} + +/// The preset's count of new colors: none for Color Library, else at least 1. +fn count(v: Option<&Value>) -> Result, String> { + match v { + None | Some(Value::Null) => Ok(None), + Some(n) => n.as_u64().filter(|n| *n >= 1).map(Some).ok_or_else(|| "`colors` must be a count of at least 1".into()), + } +} diff --git a/crates/ui-egui/src/dialogs/rename_artboards.rs b/crates/ui-egui/src/dialogs/rename_artboards.rs index d6b74551f5..6eb9001c3b 100644 --- a/crates/ui-egui/src/dialogs/rename_artboards.rs +++ b/crates/ui-egui/src/dialogs/rename_artboards.rs @@ -19,14 +19,15 @@ pub(crate) const CMD: &str = "artboard.rename"; /// for several. pub(crate) fn open(app: &mut VectorcraftApp) -> Result { let ctx = app.ui_ctx.clone().ok_or("no window")?; - let (indices, name) = app.session.active().map_or((vec![], String::new()), |st| { - let indices = crate::panels::artboards::picked(app, st.doc.artboards.len()); - let name = match indices.as_slice() { - [one] => st.doc.artboards.get(*one).map_or("", |a| a.name.as_str()), - _ => "", - }; - (indices, name.to_owned()) - }); + let st = app.session.active().ok_or_else(|| tl!("No document").to_owned())?; + let document = st.uid; + let selected: Vec<_> = + crate::panels::artboards::picked(app, st.doc.artboards.len()).into_iter().filter_map(|index| st.doc.artboards.get(index)).collect(); + let name = match selected.as_slice() { + [one] => one.name.clone(), + _ => String::new(), + }; + let artboards: Vec<_> = selected.iter().map(|board| board.id).collect(); let mut fields = DialogFields::new(); fields.set("name", name); let dialog = HostedParamDialog::command(&ctx, CMD, fields, |fields| { @@ -39,6 +40,13 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { if name.trim().is_empty() { return Ok(()); } + let st = + app.session.active().filter(|st| st.uid == document).ok_or_else(|| tl!("This dialog was opened in a different document.").to_owned())?; + let indices = artboards + .iter() + .map(|id| st.doc.artboards.iter().position(|board| board.id == *id)) + .collect::>>() + .ok_or_else(|| tl!("One of the artboards being renamed no longer exists.").to_owned())?; if let Err(e) = app.run(CMD, json!({ "indices": indices, "name": name })) { app.status(e); } @@ -105,6 +113,51 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step"); } + #[test] + fn rename_follows_the_original_artboards_after_reordering() { + let mut app = app(); + app.session.set_tool_option("selected", &json!([0, 2])); + open(&mut app).unwrap(); + app.run("artboard.reorder", json!({"index": 0, "to": 2})).unwrap(); + assert_eq!(names(&app), ["Artboard 2", "Artboard 3", "Artboard 1"]); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Page"); + assert_eq!(names(&app), ["Artboard 2", "Page-1", "Page-2"]); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + } + + #[test] + fn rename_waits_for_the_document_it_opened_in() { + let mut app = app(); + open(&mut app).unwrap(); + app.run("file.new", json!({"width": 100, "height": 50, "artboards": 3})).unwrap(); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Source only"); + assert_eq!(names(&app), ["Artboard 1", "Artboard 2", "Artboard 3"]); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + assert!(app.any_dialog_open(), "the original document can still answer"); + + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + rename(&mut app, "Source only"); + assert_eq!(names(&app), ["Source only", "Artboard 2", "Artboard 3"]); + assert!(!app.any_dialog_open()); + } + + #[test] + fn rename_leaves_the_other_targets_alone_if_an_original_artboard_was_removed() { + let mut app = app(); + app.session.set_tool_option("selected", &json!([0, 2])); + open(&mut app).unwrap(); + app.run("artboard.delete", json!({"index": 2})).unwrap(); + app.run("artboard.duplicate", json!({"index": 1})).unwrap(); + let before = names(&app); + let steps = app.session.active().unwrap().history.undo.len(); + rename(&mut app, "Page"); + assert_eq!(names(&app), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + assert!(app.any_dialog_open()); + } + /// OK with an empty name or the name the artboard already has records no undo step. #[test] fn nothing_changes_for_an_empty_or_unchanged_name() { diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index a61190970e..edc9953497 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -175,8 +175,13 @@ impl Rows<'_> { self.defaults.get(key).and_then(Value::as_f64).unwrap_or(0.0) } - fn range(&self, key: &str, label: &'static str, (lo, hi): (f64, f64), decimals: u32, unit: UnitKind) -> Param { - Param::new(key, label, ParamKind::range(lo, hi, self.default_number(key), SliderScale::Linear)).decimals(decimals).unit(unit).resettable() + fn range(&self, key: &str, label: &'static str, range: (f64, f64), decimals: u32, unit: UnitKind) -> Param { + self.plain(key, label, range, decimals).unit(unit) + } + + /// A slider over a number shown with no unit after it, such as a count. + fn plain(&self, key: &str, label: &'static str, (lo, hi): (f64, f64), decimals: u32) -> Param { + Param::new(key, label, ParamKind::range(lo, hi, self.default_number(key), SliderScale::Linear)).decimals(decimals).resettable() } fn degrees(&self, key: &str, label: &'static str, range: (f64, f64), decimals: u32) -> Param { @@ -273,7 +278,7 @@ fn object_rows(data: &Data, rows: &Rows, effect: &str, place: Place) -> Vec Param { let defaults = bevel_defaults(); let keys: Vec = defaults.keys().cloned().collect(); Param::custom("__bevelHeading", c3("Bevel"), move |ui, fields, _| { - ui.horizontal(|ui| { - ui.label(egui::RichText::new(c3("Bevel")).strong()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if pressed(ui, tl!("Reset"), differs_from(fields, &defaults), None) { - defaults.iter().for_each(|(k, v)| set_value(fields, k, v)); - } - }); - }) - .response + let mut reset = false; + let changed = differs_from(fields, &defaults); + let shown = crate::panels::section(c3("Bevel")) + .id_salt("bevel") + .controls(|ui, _| reset = pressed(ui, tl!("Reset"), changed, None)) + .show(ui, |_, _| {}); + if reset { + defaults.iter().for_each(|(k, v)| set_value(fields, k, v)); + } + shown.output.response }) .companions(keys) .full_width() @@ -413,7 +419,7 @@ fn differs_from(fields: &DialogFields, defaults: &serde_json::Map /// Revolve's Rotation page: shape, view and the advanced settings. fn revolve_rows(rows: &Rows, effect: &str, place: Place) -> Vec { - let mut advanced = vec![rows.range("segments", tl!("Segments"), (8.0, 128.0), 0, UnitKind::Pixels)]; + let mut advanced = vec![rows.plain("segments", tl!("Segments"), (8.0, 128.0), 0)]; if place == Place::Dialog { advanced.push(rows.flag("__showAxis", tl!("Show axis"))); } @@ -721,7 +727,7 @@ pub(crate) fn light_editor(_data: &Data, place: Place, classic: bool) -> Param { fields.remove("__lightPick"); set_light_value(fields, "lightColor", json!(hex)); } - ui.vertical(|ui| { + super::form::stacked(ui, fields, |ui, fields| { let mut list = explicit_lights(fields).unwrap_or_else(|| vec![light_record(fields)]); let mut index = light_index(fields, list.len()); let titles: Vec = (1..=list.len()).map(|i| format!("{} {i}", c3("Light"))).collect(); @@ -767,7 +773,6 @@ pub(crate) fn light_editor(_data: &Data, place: Place, classic: bool) -> Param { store_selected(fields, &selected); } }) - .response }) .companions(LIGHT_KEYS.iter().map(|(_, k)| *k).chain(["__light", "__lightPick"])) .on_set(set_light_field) diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index 53f7a888fe..f0529ee590 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -406,6 +406,39 @@ fn the_bevel_reset_restores_the_bevel_settings_and_keeps_the_others() { assert_eq!(doc(&h), before); } +/// The Bevel heading is a section named Bevel that holds its Reset, on its own line between Cap and Bevel Shape. +#[test] +fn the_bevel_heading_is_a_section_between_cap_and_bevel_shape() { + use craft::ui::contract::Role; + let mut h = drawn(SQUARE, EXTRUDE); + h.set("__page", json!("object")); + let (cap, reset, shape) = (h.target("Cap").rect, h.target("Reset").rect, h.target("Bevel Shape").rect); + let tree = h.fixture.tree(); + let section = h.fixture.by_role(Role::GROUP).into_iter().find(|t| tree.name_of(t.node) == Some("Bevel")).map(|t| t.rect); + assert!(section.is_some_and(|s| s.contains_rect(reset)), "a section named Bevel holds Reset: {section:?} {reset:?}"); + assert!(reset.top() >= cap.bottom(), "Reset is below Cap: {cap:?} {reset:?}"); + assert!(shape.top() >= reset.bottom(), "Bevel Shape is below Reset: {reset:?} {shape:?}"); + h.cancel(); +} + +/// The bevel's Repeat and Revolve's Segments are counts: their rows show no unit after the number, while Taper, a +/// share, shows its percent sign. +#[test] +fn the_bevel_repeat_and_the_revolve_segments_show_no_unit() { + use craft::ui::patterns::form_dialogs::DialogFields; + use craft::ui::runtime::env::UnitKind; + let app = VectorcraftApp::new(Session::new(), crate::Services::default()); + let unit = |effect: &str, page: &str, key: &str| { + let data = super::super::three_d::data(&app, Some(effect), &serde_json::Map::new()); + let mut fields = DialogFields::new(); + fields.set("__page", FieldValue::Text(page.into())); + super::params(&data, &fields, super::Place::Dialog).into_iter().find(|p| p.key == key).map(|p| p.unit) + }; + assert_eq!(unit(EXTRUDE, "object", "bevelRepeat"), Some(None)); + assert_eq!(unit(REVOLVE, "rotation", "segments"), Some(None)); + assert_eq!(unit(EXTRUDE, "object", "taper"), Some(Some(UnitKind::Percent))); +} + #[test] fn reset_all_keeps_map_art_and_its_options() { let mut h = drawn(SQUARE, CLASSIC_EXTRUDE); diff --git a/crates/ui-egui/src/dialogs/revolve_lights.rs b/crates/ui-egui/src/dialogs/revolve_lights.rs index 992ccf44ae..342f032808 100644 --- a/crates/ui-egui/src/dialogs/revolve_lights.rs +++ b/crates/ui-egui/src/dialogs/revolve_lights.rs @@ -272,8 +272,8 @@ impl Component for LightSphere<'_> { /// The row's width and the height of the sphere that fits it, with its suns. fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { - let width = cx.picture_width((24.0 + SUN + 8.0) * 2.0, f32::INFINITY); - Vec2::new(width, (radius_in(width) + SUN + 6.0) * 2.0) + // The height follows the width: a column that measures the sphere with no room measures it again at its width. + cx.picture_size((24.0 + SUN + 8.0) * 2.0, f32::INFINITY, |width| (radius_in(width) + SUN + 6.0) * 2.0) } fn sense(&self) -> Sense { diff --git a/crates/ui-egui/src/dialogs/safe_mode.rs b/crates/ui-egui/src/dialogs/safe_mode.rs index 32ac3dd51a..6689cc6cc9 100644 --- a/crates/ui-egui/src/dialogs/safe_mode.rs +++ b/crates/ui-egui/src/dialogs/safe_mode.rs @@ -135,7 +135,8 @@ fn stopped_prompt(fields: &Value) -> StandardPrompt { /// The choice's Disable and Continue (`normal` false) or Start Normally: Safe Mode ends and the /// plug-ins load, without the stopped ones for Disable and Continue (kept off for later launches -/// too). +/// too), then the startup scripts run ([`crate::script_runs::run_at_launch`]), without a disabled +/// one. fn confirm_stopped(app: &mut VectorcraftApp, normal: bool) { let items = stopped_items(&app.ui.stopped_plugin.take().unwrap_or(Value::Null)); // When a disabled plug-in can't be saved for the next launch, that launch asks again. Every @@ -154,6 +155,8 @@ fn confirm_stopped(app: &mut VectorcraftApp, normal: bool) { } safe_mode::set_active(None); vectorcraft_engine::cmd::plugin::load_prefs_folder(&mut app.session); + // The launch's startup scripts waited for Safe Mode to end. + crate::script_runs::run_at_launch(app); } /// Help › Safe Mode: the disabled plug-ins, none ticked for Enable on Re-launch. A plug-in disabled diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index aaaf3d4e1c..0dd9edc19b 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -49,6 +49,19 @@ pub(crate) struct WebExport { optimized: Option, /// The engine's `colorTable` value: the edits the colour table's buttons made. table: Value, + /// The engine's settings the dialog has no option for ([`KEPT`]), as the dialog opened on them + /// or Optimize to File Size found them: the previews, Save… and the presets use them. A preset + /// picked in the dialog does not change them. + kept: Value, +} + +/// The engine's settings keys the dialog does not show; they pass through it unchanged. +const KEPT: [&str; 2] = ["transparencyDither", "transparencyDitherAmount"]; + +/// The [`KEPT`] keys of the engine's settings `s`. +fn kept_of(s: &WebSettings) -> Value { + let engine = s.to_json(); + Value::Object(KEPT.iter().filter_map(|k| engine.get(*k).map(|v| ((*k).to_string(), v.clone()))).collect()) } /// The key of the Original pane's texture in the pump's [`TextureStore`]; the panes use their index. @@ -129,11 +142,15 @@ pub(super) fn options_of(s: &WebSettings, natural: Option) -> SaveFor serde_json::from_value(v).unwrap_or_default() } -/// The engine's settings JSON for the dialog's `options`, the edited colour `table` and an optional -/// `path`: what `webExport.settings`, `document.exportForWeb` and `file.saveForWeb` read. -fn settings_of(options: &SaveForWebOptions, table: &Value, path: Option<&str>) -> Value { +/// The engine's settings JSON for the dialog's `options`, the edited colour `table`, the `kept` +/// settings the dialog does not show ([`WebExport::kept`]) and an optional `path`: what +/// `webExport.settings`, `document.exportForWeb` and `file.saveForWeb` read. +fn settings_of(options: &SaveForWebOptions, table: &Value, kept: &Value, path: Option<&str>) -> Value { let mut v = serde_json::to_value(options).unwrap_or(Value::Null); if let Some(o) = v.as_object_mut() { + if let Some(kept) = kept.as_object() { + o.extend(kept.clone()); + } let [r, g, b] = options.matte; o.insert("matte".into(), json!(format!("#{r:02x}{g:02x}{b:02x}"))); o.remove("colorTable"); @@ -170,7 +187,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let host = app.dialogs().ok_or("no window")?; let ctx = app.ui_ctx.clone().ok_or("no window")?; let s = remembered(app); - app.web_export = WebExport { table: serde_json::to_value(&s.color_table).unwrap_or_default(), ..WebExport::default() }; + app.web_export = WebExport { table: serde_json::to_value(&s.color_table).unwrap_or_default(), kept: kept_of(&s), ..WebExport::default() }; let (name, artboards, slices) = { let st = app.session.active().ok_or("no document")?; let slices: Vec = st @@ -472,7 +489,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { on_dialog(&host, |d| d.answer_optimize(answer.map_err(Into::into))); } if asked.browser { - let p = settings_of(&asked.options, &app.web_export.table, None); + let p = settings_of(&asked.options, &app.web_export.table, &app.web_export.kept, None); if let Err(e) = browser_preview(app, &p) { app.status(e); } @@ -488,11 +505,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { /// The encodes the dialog wants, as pictures, and the Original pane's picture when the rendering is new. fn answer_variants(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft::ui::shell::WindowDialogs, wanted: &[WantedVariant]) { - let table = app.web_export.table.clone(); + let (table, kept) = (app.web_export.table.clone(), app.web_export.kept.clone()); let mut answers = Vec::with_capacity(wanted.len()); for w in wanted { let (index, revision) = (w.index, w.request.revision); - let settings = app.session.web_settings(&settings_of(&w.request.options, &table, None)); + let settings = app.session.web_settings(&settings_of(&w.request.options, &table, &kept, None)); let rendered = settings.and_then(|s| render_for(app, &s).map(|(key, r)| (s, key, r))); answers.push(match (rendered, app.session.active()) { (Ok((s, key, r)), Some(st)) => optimise(ctx, &st.doc, &r, &key, &s, w), @@ -532,7 +549,7 @@ fn edit_table(app: &mut VectorcraftApp, ctx: &egui::Context, host: &craft::ui::s /// The source colours of the palette the dialog's settings `options` show, with the table as it stands. fn shown_colors(app: &mut VectorcraftApp, options: &SaveForWebOptions) -> Result, String> { - let settings = app.session.web_settings(&settings_of(options, &app.web_export.table, None))?; + let settings = app.session.web_settings(&settings_of(options, &app.web_export.table, &app.web_export.kept, None))?; Ok(encoded(app, &settings)?.colors.iter().map(|c| c.source).collect()) } @@ -565,7 +582,7 @@ fn store_presets(app: &mut VectorcraftApp, events: Vec) { for event in events { let r = match event { WebPresetEvent::Saved(p) => { - let mut v = settings_of(&p.options, &app.web_export.table, None); + let mut v = settings_of(&p.options, &app.web_export.table, &app.web_export.kept, None); v["name"] = json!(p.name); app.run("webExport.presets.save", v) } @@ -596,7 +613,7 @@ fn has_slices(app: &VectorcraftApp) -> bool { /// The `webExport.optimizeToFileSize` params: `options`, the desired size and, with slices, what it covers. fn optimize_params(app: &VectorcraftApp, options: &SaveForWebOptions, desired_k: f64, start: Option<&str>, scope: &str) -> Value { - let mut p = settings_of(options, &app.web_export.table, None); + let mut p = settings_of(options, &app.web_export.table, &app.web_export.kept, None); if let Some(o) = p.as_object_mut() { o.insert("desiredK".into(), json!(desired_k)); if let Some(start) = start { @@ -617,7 +634,7 @@ fn optimize_start(app: &mut VectorcraftApp, options: &SaveForWebOptions) -> Opti let r = app.run("webExport.optimizeToFileSize", p).ok()?; return r["achieved"].as_bool().filter(|a| *a).and_then(|_| r["bytes"].as_u64()); } - let s = app.session.web_settings(&settings_of(options, &app.web_export.table, None)).ok()?; + let s = app.session.web_settings(&settings_of(options, &app.web_export.table, &app.web_export.kept, None)).ok()?; encoded(app, &s).ok().map(|o| o.bytes.len() as u64) } @@ -637,6 +654,7 @@ fn run_optimize(app: &mut VectorcraftApp, req: &OptimizeRequest) -> Result Result s, Err(e) => { on_dialog(host, HostedSaveForWeb::cancel_requests); @@ -698,8 +716,9 @@ fn answer_path(app: &VectorcraftApp, id: DialogId, key: &str, path: PathBuf) { /// written. Failures show in the status line; the dialog has closed. fn finish(app: &mut VectorcraftApp, result: SaveForWebResult) { let table = std::mem::take(&mut app.web_export.table); + let kept = std::mem::take(&mut app.web_export.kept); app.web_export = WebExport::default(); - let params = settings_of(&result.options, &table, None); + let params = settings_of(&result.options, &table, &kept, None); if let Err(e) = app.run("webExport.settings", params.clone()) { return app.status(e); } diff --git a/crates/ui-egui/src/dialogs/save_for_web/tests.rs b/crates/ui-egui/src/dialogs/save_for_web/tests.rs index 400e43fe82..85cba5810d 100644 --- a/crates/ui-egui/src/dialogs/save_for_web/tests.rs +++ b/crates/ui-egui/src/dialogs/save_for_web/tests.rs @@ -312,6 +312,31 @@ fn save_remembers_and_writes_and_done_only_remembers() { assert!(!dir.join("Untitled-1.png").exists()); } +/// The remembered Transparency Dither, which the dialog does not show, reaches the file Save writes +/// and stays remembered after Done. +#[test] +fn save_keeps_the_remembered_transparency_dither() { + let dir = vectorcraft_testkit::temp_dir("sfw-tdither"); + let (mut app, _) = app(&dir, false); + let mut written = vec![]; + for method in ["none", "noise"] { + app.run("webExport.settings", json!({"format": "gif", "transparency": true, "transparencyDither": method})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + save(&mut app); + let path = dir.join("Untitled-1.gif"); + written.push(std::fs::read(&path).unwrap()); + std::fs::remove_file(&path).unwrap(); + assert_eq!(app.session.last_web_settings().transparency_dither.id(), method, "remembered"); + let expected = app.session.execute("document.exportForWeb", &json!({"format": "gif", "transparencyDither": method})).unwrap(); + assert_eq!(expected["files"][0]["dataBase64"].as_str().and_then(vectorcraft_format::base64_decode).as_ref(), written.last()); + } + assert_ne!(written[0], written[1], "the partly transparent edge is dithered"); + app.run("file.saveForWeb", json!({})).unwrap(); + set(&mut app, "choice", json!("done")); + confirm(&mut app); + assert_eq!(app.session.last_web_settings().transparency_dither.id(), "noise"); +} + #[test] fn html_output_with_slices_saves_the_page_and_images() { let dir = vectorcraft_testkit::temp_dir("sfw-html"); diff --git a/crates/ui-egui/src/dialogs/save_options.rs b/crates/ui-egui/src/dialogs/save_options.rs index b65a1f40cb..6576e17c73 100644 --- a/crates/ui-egui/src/dialogs/save_options.rs +++ b/crates/ui-egui/src/dialogs/save_options.rs @@ -36,6 +36,7 @@ use vectorcraft_eps::{Level, Overprint, Preview}; use craft::theme::variant::Tone; use craft::ui::buttons::Button; use craft::ui::contract::{Bind, CollectionEvent, Show as _, ShowCollection as _, ShowContainer as _, TooltipSpec}; +use craft::ui::display::Text; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{ThumbAspect, ToggleState}; use craft::ui::notices::Notice; @@ -404,7 +405,7 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> .show(ui, |ui, _| { // Each run of the body starts from the checks as they stood: a check flips them, and the body may run twice. boards.clone_from(&before); - ui.label(tl!("A legacy .ai file holds one artboard: each artboard you check is saved as a separate file.")); + Notice::new(Tone::Info, tl!("A legacy .ai file holds one artboard: each artboard you check is saved as a separate file.")).show(ui); Row::new().show(ui, |ui, _| { if Button::new(tl!("Select All")).show(ui).clicks > 0 { boards.iter_mut().for_each(|b| *b = true); @@ -414,14 +415,14 @@ fn boards_picker(ui: &mut egui::Ui, fields: &mut DialogFields, menus: &Menus) -> } let checked = boards.iter().filter(|b| **b).count(); let (count, total) = (checked.to_string(), n.to_string()); - ui.label(crate::i18n::fmt(tl!("{count} of {total} artboards"), &[("count", &count), ("total", &total)])); + Text::new(crate::i18n::fmt(tl!("{count} of {total} artboards"), &[("count", &count), ("total", &total)])).show(ui); }); if !boards.iter().any(|b| *b) { Notice::new(Tone::Warn, tl!("Check an artboard to save.")).show(ui); } // PLAN: assumed TileGrid::show_items(ui, &source, &mut |key, _| tile) as the framework's stories call it; // the checks arrive as `CollectionEvent::Item(key, TilePartEvent::Check { .. })` in `response.events`. - let grid = TileGrid::new("Artboards").checks(true).max_rows(BOARD_ROWS).show_items(ui, &Boards(n), &mut |i, _| { + let grid = TileGrid::new(tl!("Artboards")).checks(true).max_rows(BOARD_ROWS).show_items(ui, &Boards(n), &mut |i, _| { let on = boards.get(*i).copied().unwrap_or(false); let mut tile = Tile::new(menus.names.get(*i).cloned().unwrap_or_default()).check(if on { ToggleState::On } else { ToggleState::Off }); if let Some(file) = files.get(*i).cloned().flatten() { diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index a0e5dbbd56..200b91f458 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -247,6 +247,33 @@ fn legacy_ai_saves_the_artboards_checked_in_its_picker() { assert_eq!(boards_in(&dialog(&mut app)), Some(vec![true, false, true, false])); } +/// The legacy picker's note, grid name and count are announced. The count follows the checks and +/// the grid name follows the interface language. +#[test] +fn legacy_ai_announces_its_note_grid_name_and_artboard_count() { + let (mut app, _, _) = desktop("art.ai"); + app.run("artboard.new", json!({"x": 200, "y": 0, "width": 100, "height": 80})).unwrap(); + save_as(&mut app, "file.saveAs"); + set(&mut app, "aiVersion", json!("7")); + let labels = |app: &mut VectorcraftApp, role: Option| -> Vec { + frame(app); + let ctx = app.ui_ctx.clone().unwrap(); + let out = crate::testing::app_frame(app, &ctx, egui::RawInput::default()); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter(|(_, node)| role.is_none_or(|role| node.role() == role)).filter_map(|(_, node)| node.label()).map(str::to_owned).collect() + }; + let shown = labels(&mut app, None); + assert!(shown.iter().any(|l| l.starts_with("A legacy .ai file holds one artboard")), "{shown:?}"); + assert!(shown.iter().any(|l| l == "2 of 2 artboards"), "{shown:?}"); + set(&mut app, "boards", json!([true, false])); + let shown = labels(&mut app, None); + assert!(shown.iter().any(|l| l == "1 of 2 artboards") && !shown.iter().any(|l| l == "2 of 2 artboards"), "{shown:?}"); + + app.session.prefs.interface_language = "fr".into(); + let shown = labels(&mut app, Some(egui::accesskit::Role::ListBox)); + assert!(shown.iter().any(|label| label == "Plans de travail"), "{shown:?}"); +} + #[test] fn save_a_copy_and_template_suggest_their_names() { let (mut app, written, picks) = desktop("copy.vectorcraft"); diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 82a613dfc5..e003cf6a7e 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -14,7 +14,7 @@ use std::sync::Arc; -use craft::ui::dialog::DialogId; +use craft::ui::dialog::{DialogHost, DialogId}; use craft::ui::patterns::form_dialogs::{ HostedPdfExport, ParamResult, PdfArtboards, PdfExportAnswer, PdfExportMode, PdfExportWords, PdfPresetEvent, PresetDraft, }; @@ -378,6 +378,119 @@ pub(crate) fn dialog_set(app: &mut VectorcraftApp, params: &Value) -> Option Option> { + let named = (params["dialog"] == "top" && host.open_dialogs().last().map(|d| d.id) == Some(id)) + || params["dialog"] == id.value() + || params["dialog"].as_str() == Some(id.value().to_string().as_str()); + let known = params.as_object()?.keys().all(|k| matches!(k.as_str(), "dialog" | "field" | "value" | "fields")); + if !named || !known { + return None; + } + let item = |f: &Value| Some((f.get("field")?.as_str()?.to_owned(), f.get("value").cloned().unwrap_or(Value::Null))); + let items: Vec<(String, Value)> = match params.get("fields") { + Some(_) if params.get("field").is_some() || params.get("value").is_some() => return None, + Some(list) => { + list.as_array().filter(|l| l.len() <= craft::automation::dialogs::MAX_DIALOG_FIELDS)?.iter().map(item).collect::>()? + } + None => vec![item(params)?], + }; + let settings = |host: &DialogHost| host.get_by_id::(id).and_then(|d| serde_json::to_value(d.settings()).ok()); + let now = settings(host)?; + if !items.iter().any(|(field, _)| option_at(&now, field).is_some_and(Value::is_object)) { + return None; + } + let before = dialog_fields(host, id); + let passwords = host.get_by_id::(id).map(|d| { + let security = &d.settings().security; + [("security.openPassword", security.open_password.clone()), ("security.permissionsPassword", security.permissions_password.clone())] + }); + let mut changed = false; + for (field, value) in &items { + let set = match settings(host).as_ref().and_then(|s| option_at(s, field)).filter(|v| v.is_object()) { + Some(_) if !value.is_object() => Err(format!("`{field}` must be an object of options, not {value}")), + Some(old) => { + let mut merged = old.clone(); + merge_options(&mut merged, value); + host.set_json_field(ctx, id, field, merged) + } + None => host.set_json_field(ctx, id, field, value.clone()), + }; + if let Err(e) = set { + // A refused field leaves the dialog as it was, so only the fields set before it go back. + if changed { + restore_fields(host, ctx, id, before, passwords); + } + return Some(Err(e)); + } + changed = true; + } + Some(Ok(())) +} + +/// The JSON fields of the open dialog `id`. +fn dialog_fields(host: &DialogHost, id: DialogId) -> Option { + host.open_dialogs().into_iter().find(|d| d.id == id).and_then(|d| d.fields) +} + +/// The option at the dotted `path` (`compression.color`) of the settings `settings`. +fn option_at<'a>(settings: &'a Value, path: &str) -> Option<&'a Value> { + path.split('.').try_fold(settings, |at, key| at.get(key)) +} + +/// Set the options `over` holds on `base`, object by object; any other value replaces `base`. +fn merge_options(base: &mut Value, over: &Value) { + match (base, over) { + (Value::Object(b), Value::Object(o)) => { + for (k, v) in o { + match b.get_mut(k) { + Some(slot) => merge_options(slot, v), + None => { + b.insert(k.clone(), v.clone()); + } + } + } + } + (b, o) => *b = o.clone(), + } +} + +/// Set the dialog `id`'s fields that differ from `before` back to it. The preset goes first, since choosing it +/// replaces every setting and clears the passwords. The `passwords` the dialog had, which its fields leave out, are set +/// back last when they differ. +fn restore_fields(host: &mut DialogHost, ctx: &egui::Context, id: DialogId, before: Option, passwords: Option<[(&str, String); 2]>) { + let Some(Value::Object(before)) = before else { return }; + let preset = before.get("preset").filter(|old| dialog_fields(host, id).as_ref().and_then(|now| now.get("preset")) != Some(*old)); + if let Some(old) = preset { + let _ = host.set_json_field(ctx, id, "preset", old.clone()); + } + // The standard goes next, since it enables and sets other fields. A field that another one still disables is set + // again in a later pass, once that one is back; one that stays disabled keeps its value, as the framework's own + // rollback leaves it. + let rest = || before.get_key_value("standard").into_iter().chain(before.iter().filter(|(k, _)| !matches!(k.as_str(), "preset" | "standard"))); + for _ in 0..3 { + let now = dialog_fields(host, id).unwrap_or(Value::Null); + let differ: Vec<_> = rest().filter(|(name, old)| now.get(name.as_str()) != Some(*old)).collect(); + if differ.is_empty() { + break; + } + for (name, old) in differ { + let _ = host.set_json_field(ctx, id, name, old.clone()); + } + } + let now = host + .get_by_id::(id) + .map(|d| [d.settings().security.open_password.clone(), d.settings().security.permissions_password.clone()]); + for ((name, password), now) in passwords.into_iter().flatten().zip(now.into_iter().flatten()) { + if password != now { + let _ = host.set_json_field(ctx, id, name, Value::String(password)); + } + } +} + /// The dialog's `settings` with the job's Custom… flattener options, as the export gets them. fn with_custom(open: &SavePdfOpen, mut settings: Value) -> Value { if let Some(options) = open.job.as_ref().and_then(|job| job.flattener.as_ref()).and_then(|f| serde_json::to_value(f).ok()) { diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 571d0b4489..2f1ea8b8e2 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -640,6 +640,121 @@ fn presets_reset_the_settings_and_fields_fall_back_to_defaults() { assert!(!is_open(&app)); } +/// `ui.dialog.set` with `params` as a control request, and its reply. +fn dialog_request(app: &mut VectorcraftApp, params: Value) -> Value { + let ctx = app.ui_ctx.clone().expect("a UI context"); + let (req, _) = craft::automation::ControlRequest::new("ui.dialog.set", params); + let craft::automation::Reply::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("ui.dialog.set answered later") }; + r +} + +/// The four bleed sides the dialog shows: top, bottom, left, right. +fn bleed_sides(app: &VectorcraftApp) -> [Value; 4] { + ["top", "bottom", "left", "right"].map(|side| fget(app, &format!("bleed.{side}"))) +} + +/// A settings object `ui.dialog.set` sets changes only the options it holds: the others keep the dialog's values, +/// so linking the bleed gives every side the top value the dialog shows. +#[test] +fn a_settings_object_keeps_the_options_it_leaves_out() { + let (mut app, _) = app(); + app.run("pdf.preset.save", json!({"name": "Uneven", "bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + app.run("pdf.preset.save", json!({"name": "Marked", "marks": {"trim": true, "offset": 9}})).unwrap(); + app.run("pdf.preset.save", json!({"name": "Low", "compression": {"color": {"ppi": 123}}})).unwrap(); + app.run("ui.savePdfDialog", json!({"preset": "Uneven"})).unwrap(); + + dialog_set(&mut app, "bleed", json!({"useDocument": false})); + assert_eq!(bleed_sides(&app), [3.0, 5.0, 3.0, 3.0].map(Value::from), "the sides left out keep their values"); + dialog_set(&mut app, "bleedLinked", json!(true)); + assert_eq!(bleed_sides(&app), [3.0; 4].map(Value::from), "linking gives every side the top value"); + dialog_set(&mut app, "bleed", json!({"bottom": 5})); + assert_eq!(bleed_sides(&app), [3.0, 5.0, 3.0, 3.0].map(Value::from), "only the side set changes"); + let r = dialog_request(&mut app, json!({"fields": [{"field": "bleed", "value": {"top": 4}}, {"field": "bleed", "value": {"left": 6}}]})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(bleed_sides(&app), [4.0, 5.0, 6.0, 3.0].map(Value::from), "each object of a list builds on the one before"); + + // Every settings object, not only the bleed. + set_field(&app, "preset", json!("Marked")); + dialog_set(&mut app, "marks", json!({"weight": 0.5})); + assert_eq!((fget(&app, "marks.trim"), fget(&app, "marks.offset"), fget(&app, "marks.weight")), (json!(true), json!(9.0), json!(0.5))); + + // An object inside a settings object, set whole or by its dotted name. + set_field(&app, "preset", json!("Low")); + dialog_set(&mut app, "compression", json!({"color": {}, "compressText": false})); + assert_eq!((fget(&app, "compression.color.ppi"), fget(&app, "compression.compressText")), (json!(123.0), json!(false))); + dialog_set(&mut app, "compression.color", json!({"abovePpi": 200})); + assert_eq!((fget(&app, "compression.color.ppi"), fget(&app, "compression.color.abovePpi")), (json!(123.0), json!(200.0))); + + // A value that isn't an object is refused, and the dialog stays as it was. + let before = fields(&app); + for bad in [json!(5), json!("3 mm"), json!([false, 3, 3, 3, 3]), Value::Null] { + let r = dialog_request(&mut app, json!({"field": "bleed", "value": bad})); + assert_eq!(r["ok"], false, "{bad}: {r}"); + assert!(r["error"].as_str().is_some_and(|e| e.contains("`bleed` must be an object of options")), "{bad}: {r}"); + assert_eq!(fields(&app), before, "{bad}"); + } +} + +/// The preset editor's settings objects keep the options they leave out too. +#[test] +fn a_settings_object_in_the_preset_editor_keeps_the_options_it_leaves_out() { + let (mut app, _) = app(); + app.run("pdf.preset.save", json!({"name": "Marked", "marks": {"trim": true, "offset": 9}})).unwrap(); + open_preset(&mut app, &json!({"name": "Marked"})).unwrap(); + dialog_set(&mut app, "marks", json!({"weight": 0.5})); + assert_eq!((fget(&app, "marks.trim"), fget(&app, "marks.offset"), fget(&app, "marks.weight")), (json!(true), json!(9.0), json!(0.5))); +} + +/// A `fields` list whose later field is refused leaves the whole dialog as it was before the request: the settings +/// objects an earlier field set, and a bleed that differs from the chosen preset's. +#[test] +fn a_refused_field_leaves_the_whole_request_unset() { + let (mut app, _) = app(); + app.run("pdf.preset.save", json!({"name": "Uneven", "bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + app.run("ui.savePdfDialog", json!({"preset": "Uneven"})).unwrap(); + dialog_set(&mut app, "bleed", json!({"top": 7})); + let before = fields(&app); + let r = dialog_request( + &mut app, + json!({"fields": [ + {"field": "bleed", "value": {"top": 1, "bottom": 2, "left": 3, "right": 4}}, + {"field": "marks", "value": {"trim": true}}, + {"field": "bleedLinked", "value": "yes"}, + ]}), + ); + assert_eq!(r["ok"], false, "{r}"); + assert_eq!(fields(&app), before, "the dialog is unchanged"); + assert_eq!(fget(&app, "bleed.top"), 7.0); +} + +/// A refused settings object keeps the passwords the dialog holds, whether it is refused at once, after an earlier +/// settings object was set, after a preset the request chose, after a password the request set, or after a standard +/// that disables other fields. +#[test] +fn a_refused_settings_object_keeps_the_passwords() { + let (mut app, _) = app(); + app.run("pdf.preset.save", json!({"name": "Uneven", "bleed": {"top": 3, "bottom": 5, "left": 3, "right": 3}})).unwrap(); + app.run("ui.savePdfDialog", json!({})).unwrap(); + set_field(&app, "security.openPassword", json!("open")); + set_field(&app, "security.permissionsPassword", json!("own")); + let passwords = + |app: &VectorcraftApp| with_pdf(app, |d| (d.settings().security.open_password.clone(), d.settings().security.permissions_password.clone())); + let requests = [ + json!({"field": "bleed", "value": null}), + json!({"fields": [{"field": "marks", "value": {"trim": true}}, {"field": "bleed", "value": 5}]}), + json!({"fields": [{"field": "preset", "value": "Uneven"}, {"field": "marks", "value": {"trim": true}}, {"field": "bleed", "value": 5}]}), + json!({"fields": [{"field": "security.openPassword", "value": "other"}, {"field": "marks", "value": {"trim": true}}, {"field": "bleed", "value": 5}]}), + json!({"fields": [{"field": "standard", "value": "pdfX1a"}, {"field": "bleed", "value": 5}]}), + ]; + for request in requests { + let before = fields(&app); + let r = dialog_request(&mut app, request.clone()); + assert_eq!(r["ok"], false, "{request}: {r}"); + assert_eq!(fields(&app), before, "{request}"); + assert_eq!(passwords(&app), ("open".to_string(), "own".to_string()), "{request}"); + } +} + /// The bytes and status a save writes after `setup` and the given field writes. fn written_with(setup: impl FnOnce(&mut VectorcraftApp), options: &[(&str, Value)]) -> (Vec, String) { let (mut app, written) = app(); @@ -1015,3 +1130,23 @@ fn save_pdf_opens_with_the_flattener_options_given_and_refuses_bad_ones() { assert!(!is_open(&app), "{bad}"); } } + +/// The number and length fields of the sections that name them: the page range, the bleed sides and the font +/// subset threshold. +#[test] +fn the_range_bleed_and_subset_fields_are_named() { + let (mut app, _) = app(); + app.run("file.export.pdf", json!({})).unwrap(); + let sections: [(&str, &[&str]); 3] = + [("general", &["Range"]), ("marks", &["Offset", "Top", "Bottom", "Left", "Right"]), ("advanced", &["Subset fonts below"])]; + for (section, expected) in sections { + set_field(&app, "section", json!(section)); + pump(&mut app); + let ctx = app.ui_ctx.clone().expect("a UI context"); + let out = crate::testing::app_frame(&mut app, &ctx, Default::default()); + let names = super::super::tests_print::field_names(&out); + for name in expected { + assert!(names.iter().any(|n| n == name), "{section}: {name} in {names:?}"); + } + } +} diff --git a/crates/ui-egui/src/dialogs/saved_names.rs b/crates/ui-egui/src/dialogs/saved_names.rs index d14a41fb74..0bbf1e89ea 100644 --- a/crates/ui-egui/src/dialogs/saved_names.rs +++ b/crates/ui-egui/src/dialogs/saved_names.rs @@ -137,6 +137,7 @@ impl ItemSource for Shown<'_> {} /// The saved-names dialog of one kind. pub(crate) struct SavedNamesDialog { id: DialogId, + document: u64, names: SavedNames, draft: NamesDraft, /// The picked row, by its index in the draft; one at most. @@ -147,10 +148,10 @@ pub(crate) struct SavedNamesDialog { impl SavedNamesDialog { /// The dialog over `list`, with the first name picked. - fn new(names: SavedNames, list: Vec) -> Self { + fn new(document: u64, names: SavedNames, list: Vec) -> Self { let selection = if list.is_empty() { Selection::default() } else { Selection::single(0) }; let rows = list.into_iter().map(|name| NameRow { orig: name.clone(), name, deleted: false }).collect(); - SavedNamesDialog { id: id_of(names.kind), names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } + SavedNamesDialog { id: id_of(names.kind), document, names, draft: NamesDraft { rows }, selection, held: HeldAnswer::new() } } /// OK as its button gives it: with nothing edited the dialog closes at once (`Some`); with edits they wait for @@ -326,8 +327,9 @@ impl StackDialog for SavedNamesDialog { /// Opens the dialog of `names` on `list`, the saved names in their order (the first `names.max` of them). pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec) -> Result<(), String> { list.truncate(names.max); + let document = app.session.active().ok_or("no document open")?.uid; let dialogs = app.dialogs().ok_or("no window")?; - dialogs.with(|host| host.open(SavedNamesDialog::new(names, list))); + dialogs.with(|host| host.open(SavedNamesDialog::new(document, names, list))); Ok(()) } @@ -335,18 +337,22 @@ pub(crate) fn open(app: &mut VectorcraftApp, names: SavedNames, mut list: Vec)> = dialogs.with(|host| { + let filed: Vec<_> = dialogs.with(|host| { host.open_dialogs() .into_iter() .filter_map(|open| { let dialog = host.get_mut_by_id::(open.id)?; let edits = dialog.held.take()?; - Some((open.id, dialog.names.command, edits)) + Some((open.id, dialog.document, dialog.names.command, edits)) }) .collect() }); - for (id, command, edits) in filed { - let outcome = app.run(command, json!({ "edits": edits })); + for (id, document, command, edits) in filed { + let outcome = if app.session.active().is_some_and(|active| active.uid == document) { + app.run(command, json!({ "edits": edits })) + } else { + Err(tl!("Saved names can only be edited in the document this dialog was opened for.").to_owned()) + }; if let Err(reason) = &outcome { app.status(reason.clone()); } @@ -357,3 +363,62 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { }); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn saved_names_edits_stay_with_their_document() { + for is_view in [false, true] { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + for size in [100, 200] { + app.run("file.new", json!({"width": size, "height": size})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + for name in ["Shared", "Spare"] { + app.run(if is_view { "view.saved.new" } else { "select.save" }, json!({"name": name})).unwrap(); + } + } + let names = |app: &mut VectorcraftApp| { + if is_view { + let views = &app.session.active().unwrap().doc.views; + json!(views.iter().map(|view| &view.name).collect::>()) + } else { + app.run("select.savedList", json!({})).unwrap() + } + }; + let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap(); + activate(&mut app, 0); + let kind = if is_view { + crate::dialogs::edit_views::open(&mut app).unwrap(); + crate::dialogs::edit_views::KIND + } else { + crate::dialogs::edit_selection::open(&mut app).unwrap(); + crate::dialogs::edit_selection::KIND + }; + let id = id_of(kind); + let ctx = app.ui_ctx.clone().unwrap(); + let host = app.dialogs().unwrap(); + host.with(|h| { + h.set_json_field(&ctx, id, "name0", json!("Revised")).unwrap(); + h.set_json_field(&ctx, id, "deleted1", json!(true)).unwrap(); + h.confirm_by_id(&ctx, id); + }); + + activate(&mut app, 1); + let b_undo = app.session.active().unwrap().history.undo.len(); + pump(&mut app, &ctx); + assert_eq!(names(&mut app), json!(["Shared", "Spare"]), "the destination's saved names stay unchanged for {kind}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), b_undo); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + activate(&mut app, 0); + let a_undo = app.session.active().unwrap().history.undo.len(); + host.with(|h| h.confirm_by_id(&ctx, id)); + pump(&mut app, &ctx); + assert!(matches!(host.with(|h| h.held_state(id)), Some(HeldOk::Accepted))); + assert_eq!(names(&mut app), json!(["Revised"])); + assert_eq!(app.session.active().unwrap().history.undo.len(), a_undo + 1); + } + } +} diff --git a/crates/ui-egui/src/dialogs/screen_formats.rs b/crates/ui-egui/src/dialogs/screen_formats.rs index f01bc521ee..f85cdfe558 100644 --- a/crates/ui-egui/src/dialogs/screen_formats.rs +++ b/crates/ui-egui/src/dialogs/screen_formats.rs @@ -374,9 +374,10 @@ pub(crate) fn rows(ui: &mut Ui, fields: &mut Map, mut menu: Optio let one = rows.len() == 1; let first = settings_format(&rows); let shown = Stack::new().show(ui, |ui, _| { - Row::new().align(RowAlign::SpaceBetween).show(ui, |ui, _| { + // The buttons end at the right edge; a column too narrow for them puts them on more lines. + Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| { Text::new(tl!("Formats:")).shade(Shade::Muted).show(ui); - Row::new().show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { for (id, label) in PLATFORMS { if Button::new(tl!(label)).selected(preset == id).id_salt(id).show(ui).clicked() { platform = Some(id); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index ae13009775..488fb70e57 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -4,7 +4,8 @@ //! //! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it //! asks for a `.js` or `.jsx` file through the app's file asks. With Preferences › General › Show -//! External Script Warning off, the chosen script runs at once. The warning (kind `scriptRun`) is a +//! External Script Warning off, the chosen script runs at once. With General › Run Startup Scripts +//! on, the startup scripts run first (`script.startup.run`). The warning (kind `scriptRun`) is a //! prompt: its `choice` field (`proceed` runs, `cancel` does not) and `skip` (true: turn the //! warning off). The growth question (`scriptGrowth`) and the question quitting asks //! (`scriptClose`) have the `choice` field alone. @@ -32,16 +33,18 @@ use std::path::Path; use craft::host::{PickRequest, Picked}; use craft::theme::variant::Tone; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Outcome as _, Show as _}; +use craft::ui::contract::{Bind, Outcome as _, Props as _, Scroll, Show as _, ShowContainer as _}; use craft::ui::dialog::{ DialogHost, DialogId, DialogResult, DialogStack, FieldRefusal, Prompt, PromptChoice, StackDialog, StandardPrompt, dialog_id, }; use craft::ui::display::Text; +use craft::ui::layout_components::Stack; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::text::TextField; use egui::Ui; use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; +use vectorcraft_engine::file_access::ScopeHandle; use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog}; @@ -65,6 +68,8 @@ pub(crate) const BY_PERSON: &str = "Only the person at the keyboard can allow a /// The note the file dialog shows when the person picked more files than a script is given. const PICKED_LEFT_OUT: &str = "A script is given at most 2,048 files: the files picked after them were left out"; +/// The height of the Script File Access prompt's list of picked files before it scrolls, in points. +const PICKED_LIST_HEIGHT: f32 = 120.0; /// The warning before a script runs. One type per question, so the host's per-type results never /// mix the three questions of this area. @@ -82,6 +87,11 @@ crate::dialogs::confirm::wrapped_dialog!(CloseQuestion, StandardPrompt, CLOSE_KI /// The tag of the warning: the params `script.run` takes once the warning is answered. struct RunWarning { params: Value, + /// The automation roots in force when asked: the script runs under them, and under any in force + /// when the warning is answered. + scope: ScopeHandle, + /// Automation asked ([`VectorcraftApp::automation_asked`]): the script runs as automation. + automated: bool, } /// What a script's `alert`, `confirm` or `prompt` dialog answers with. @@ -353,7 +363,12 @@ impl StackDialog for ScriptFiles { } let rows = |ui: &mut Ui| paths.iter().for_each(|path| drop(Text::new(shown_text(path, false)).show(ui))); if paths.len() > 1 { - egui::ScrollArea::vertical().id_salt("script-picked").max_height(120.0).show(ui, rows); + Stack::new() + .label(tl!("Picked files")) + .scroll(Scroll::vertical()) + .room_height(PICKED_LIST_HEIGHT) + .id_salt("script-picked") + .show(ui, |ui, _| rows(ui)); } else { rows(ui); } @@ -407,6 +422,11 @@ pub(crate) fn with_host(app: &VectorcraftApp, f: impl FnOnce(&mut DialogHost, Some(app.dialogs()?.with(|host| f(host, &ctx))) } +/// Whether the question asked on quitting with a script running is open. +pub(crate) fn asking_to_close(app: &VectorcraftApp) -> bool { + with_host(app, |host, _| host.is_open::()).unwrap_or(false) +} + /// Whether a dialog is open or waits to open: a script's dialog opens only over nothing. pub(crate) fn busy(app: &VectorcraftApp) -> bool { app.any_dialog_open() || with_host(app, |host, _| !host.is_empty()).unwrap_or(false) @@ -463,7 +483,7 @@ pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result Result() + && let Some(RunWarning { params, scope, automated }) = answer.take_tag::() { let stored = if answer.skip { app.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false})).map(drop) } else { Ok(()) }; - if let Err(e) = stored.and_then(|()| app.run("script.run", params).map(drop)) { + let run = |app: &mut VectorcraftApp| crate::script_runs::run_chosen(app, params).map(drop); + let automated = automated || app.automation_asked(); + if let Err(e) = stored.and_then(|()| scope.within_current().run(|| file_asks::as_automated(app, automated, run))) { app.status(e); } } @@ -577,19 +599,42 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { } None => {} } + answer_close(app, close); + if with_host(app, |host, _| host.get_mut::().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) { + choose(app); + } +} + +/// Takes the answer to the quit question given between two queued runs, before the next run +/// starts. True when it stopped the runs. +pub(crate) fn answer_close_between_runs(app: &mut VectorcraftApp) -> bool { + let Some(close) = with_host(app, |host, _| host.take::()).flatten() else { + return false; + }; + answer_close(app, Some(close)); + !app.session.script_running() +} + +/// With Stop as the answer to the quit question, stops the run, or between two queued runs, the +/// runs not yet started. +fn answer_close(app: &mut VectorcraftApp, close: Option::Result>>) { + let startup = app.session.startup_script_running(); + // Between two queued runs: none runs, and the report is the last run's. + let between = app.session.script_running() && app.session.script_name().is_none(); if let Some(DialogResult::Ok(answer)) = close && answer.choice == PromptChoice::Proceed && app.session.script_abandon() { - let error = app.session.script_failure_text().unwrap_or_default(); - crate::script_runs::failed(app, error); + if between { + crate::script_runs::stopped_between_runs(app); + } else { + let error = app.session.script_failure_text().unwrap_or_default(); + crate::script_runs::ended_with_error(app, startup, error); + } forget::(app); forget::(app); app.sync_views(); } - if with_host(app, |host, _| host.get_mut::().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) { - choose(app); - } } /// Gives the running script the answer of its dialog. Cancel is Cancel for a prompt, No for a diff --git a/crates/ui-egui/src/dialogs/swatch_conflict.rs b/crates/ui-egui/src/dialogs/swatch_conflict.rs index 03adb3ea1b..b0d7b34fa0 100644 --- a/crates/ui-egui/src/dialogs/swatch_conflict.rs +++ b/crates/ui-egui/src/dialogs/swatch_conflict.rs @@ -220,7 +220,7 @@ pub fn ask(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option bool { - found(app, params).is_some_and(|now| Value::Array(now) != *asked) +/// Whether the conflicts paste `command` with `params` raises are no longer the `asked` ones (another profile +/// converts the pasted swatches meanwhile): it asks about them again. +pub(crate) fn changed(app: &mut VectorcraftApp, command: &str, params: &Value, asked: &Value) -> bool { + found(app, command, params).is_some_and(|now| Value::Array(now) != *asked) } -/// The swatch conflicts pasting with `params` raises (`clipboard.conflicts`), with the swatches as -/// the paste brings them: converted from another profile when it converts. -fn found(app: &mut VectorcraftApp, params: &Value) -> Option> { +/// The swatch conflicts paste `command` with `params` raises (`clipboard.conflicts`), with the +/// swatches as the paste brings them: converted from another profile when it converts, and for +/// Paste on All Artboards without the backgrounds of copied artboards, which it leaves behind. +fn found(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option> { let mut q = json!({}); if let Some(m) = params.get("profileMismatch") { q["profileMismatch"] = m.clone(); } + if command == "edit.pasteOnAllArtboards" { + q["allArtboards"] = json!(true); + } let found = app.session.execute("clipboard.conflicts", &q).ok()?; found["swatches"].as_array().cloned() } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 273853c045..c45284ba5a 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -213,6 +213,85 @@ fn effect_dialog_refuses_a_color_it_cannot_draw() { } } +/// Drop Shadow's, Inner Glow's and Outer Glow's Mode is a blend-mode menu of every mode the effect draws, opening on the +/// effect's default, in the dialog and in the Appearance panel's editor (the same rows over the stored values, where a +/// mode in another spelling shows as its menu entry). Picking Multiply in a glow's dialog stores `multiply`, and a mode +/// the menu lacks is refused as it is set. +#[test] +fn shadow_and_glow_dialogs_pick_mode_from_a_blend_mode_menu() { + use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, ParamKind}; + let modes: Vec = vectorcraft_doc::color::BlendMode::ALL.into_iter().map(vectorcraft_effects::blend_mode_id).collect(); + for (effect, default) in [("stylize.dropShadow", "multiply"), ("stylize.innerGlow", "screen"), ("stylize.outerGlow", "screen")] { + let mut app = app(); + for editing in [false, true] { + let cx = super::effect_params::EffectCx::new(&app, effect, editing); + let rows = super::effect_params::effect_params(&cx, &DialogFields::new()); + let row = rows.iter().find(|p| p.key == "mode").unwrap_or_else(|| panic!("{effect}: a Mode row")); + let ParamKind::Blend { modes: listed, default: shown, .. } = &row.kind else { panic!("{effect}: Mode is {:?}", row.kind) }; + let listed: Vec = listed.iter().map(|(entry, _)| entry.key.clone()).collect(); + assert_eq!(listed, modes, "{effect}"); + assert_eq!(shown.as_deref(), Some(default), "{effect}"); + let stored = serde_json::Map::from_iter([("mode".to_string(), json!("Color Burn"))]); + let fields = super::form::fields_of(&rows, &stored); + assert_eq!(fields.get("mode"), Some(&FieldValue::from("colorBurn")), "{effect}"); + } + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": effect})).unwrap(); + settle(&mut app); + assert_eq!(fields(&app)["mode"], json!(default), "{effect}"); + let (dialog, ctx) = (top(&app).0, app.ui_ctx.clone().expect("a window app")); + let refused = app.dialogs().expect("a window app").with(|h| h.set_json_field(&ctx, dialog, "mode", json!("multipy"))); + assert!(refused.is_err(), "{effect}: a mode the menu lacks"); + let want = if default == "multiply" { "colorBurn" } else { "multiply" }; + let mode = if default == "multiply" { "Color Burn" } else { "Multiply" }; + let params = match effect { + "stylize.dropShadow" => json!({"field": "mode", "value": mode}), + "stylize.innerGlow" => json!({"dialog": dialog.value(), "fields": [{"field": "mode", "value": mode}]}), + _ => json!({"dialog": dialog.value().to_string(), "fields": [{"field": "mode", "value": mode}]}), + }; + crate::tests_synthetic::control(&mut app, &ctx, "ui.dialog.set", params); + assert_eq!(fields(&app)["mode"], json!(want)); + frame(&mut app, vec![]); + assert!(confirm(&mut app), "{effect}"); + let n = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + assert_eq!(n.appearance.effects[0].params["mode"], json!(want), "{effect}"); + } +} + +/// Confirming an untouched legacy mode keeps the file's value and does not add an undo step. +/// Choosing a different mode updates the stored value. +#[test] +fn unchanged_effect_dialog_preserves_legacy_blend_modes() { + let mut app = app(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let effect = "stylize.dropShadow"; + app.run("effect.apply", json!({"ids": [id], "effect": effect, "item": null})).unwrap(); + for (old_mode, shown_mode) in [(Value::Null, "multiply"), (json!("multipy"), "normal")] { + app.session.replay("effect.setParams", &json!({"ids": [id], "index": 0, "item": null, "params": {"mode": old_mode}})).unwrap(); + let before = app.session.doc().unwrap().history.undo.len(); + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + settle(&mut app); + assert_eq!(fields(&app)["mode"], json!(shown_mode)); + assert!(confirm(&mut app)); + let state = app.session.doc().unwrap(); + let n = state.doc.node(vectorcraft_doc::NodeId(id)).unwrap(); + assert_eq!(n.appearance.effects[0].params.get("mode"), Some(&old_mode)); + assert_eq!(state.history.undo.len(), before); + + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + settle(&mut app); + let ctx = app.ui_ctx.clone().expect("a window app"); + crate::tests_synthetic::control(&mut app, &ctx, "ui.dialog.set", json!({"field": "mode", "value": "Screen"})); + frame(&mut app, vec![]); + assert!(confirm(&mut app)); + let state = app.session.doc().unwrap(); + let n = state.doc.node(vectorcraft_doc::NodeId(id)).unwrap(); + assert_eq!(n.appearance.effects[0].params["mode"], json!("screen")); + assert_eq!(state.history.undo.len(), before + 1); + } +} + /// After File › Document Color Mode, a Drop Shadow's, an Outer Glow's and a Shift to Color's dialog open on the /// converted color, and OK without editing it keeps the color. #[test] @@ -429,6 +508,53 @@ fn the_transform_effect_dialog_has_its_controls_previews_them_and_shows_them_aga assert_eq!((flag(&app, "objects"), flag(&app, "strokes")), (true, true)); } +/// The names of the sliders and number fields in the window's access tree. +fn slider_and_field_names(app: &mut VectorcraftApp) -> Vec { + let out = frame(app, vec![]); + let update = out.platform_output.accesskit_update.expect("an accessibility tree"); + update + .nodes + .iter() + .filter(|(_, node)| matches!(node.role(), Role::TextInput | Role::SpinButton | Role::Slider)) + .filter_map(|(_, node)| node.label()) + .map(str::to_owned) + .collect() +} + +/// Each Scale and Move slider and number field carries its row in its name, so the two Horizontal and two Vertical +/// labels are told apart; the visible labels only describe them. +fn assert_scale_and_move_names(names: &[String]) { + for name in ["Scale Horizontal:", "Scale Vertical:", "Move Horizontal:", "Move Vertical:"] { + let count = names.iter().filter(|n| n.as_str() == name).count(); + assert_eq!(count, 2, "a slider and a number field named {name}: {names:?}"); + } + for bare in ["Horizontal:", "Vertical:"] { + assert!(!names.iter().any(|n| n == bare), "no control named only {bare}: {names:?}"); + } +} + +/// Effect > Distort & Transform > Transform names its Scale and Move controls by their row. +#[test] +fn the_transform_effect_names_scale_and_move_controls_by_their_row() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.dialog", json!({"effect": "distort.transform"})).unwrap(); + settle(&mut app); + assert_scale_and_move_names(&slider_and_field_names(&mut app)); +} + +/// Object > Transform > Transform Each shares the rows, and so the names. +#[test] +fn transform_each_names_scale_and_move_controls_by_their_row() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap(); + app.run("select.all", json!({})).unwrap(); + open_each(&mut app, false); + settle(&mut app); + assert_scale_and_move_names(&slider_and_field_names(&mut app)); +} + /// Transform Each opened by its menu item, on Absolute when `absolute` (as it was last confirmed). fn open_each(app: &mut VectorcraftApp, absolute: bool) { if absolute { diff --git a/crates/ui-egui/src/dialogs/tests_accessibility.rs b/crates/ui-egui/src/dialogs/tests_accessibility.rs index 524c3ddcfc..0a060089d6 100644 --- a/crates/ui-egui/src/dialogs/tests_accessibility.rs +++ b/crates/ui-egui/src/dialogs/tests_accessibility.rs @@ -1,4 +1,5 @@ -//! The Split Into Grid dialog names its row and column fields with their axis, read from the access tree of the window. +//! The Split Into Grid dialog names its row and column fields with their axis and lays them out in two columns, read +//! from the access tree of the window. use egui::accesskit::Role; use serde_json::json; @@ -27,3 +28,24 @@ fn split_into_grid_names_row_and_column_fields_with_context() { assert!(names.contains(&name), "{name} among the text inputs: {names:?}"); } } + +/// Split Into Grid lays its fields out as a grid: the columns' fields stand right of the rows' fields on the same +/// lines, and Add Guides stands below the last of them. +#[test] +fn split_into_grid_lays_out_its_fields_above_add_guides() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 120, "height": 80})).unwrap(); + app.run("select.all", json!({})).unwrap(); + assert!(super::object_dialogs::open_from_menu(&mut app, "object.path.splitIntoGrid")); + settle(&mut app); + let out = frame(&mut app, vec![]); + let update = out.platform_output.accesskit_update.expect("an accessibility tree"); + let rect = |name: &str| { + let node = update.nodes.iter().map(|(_, node)| node).find(|node| node.label() == Some(name)); + node.and_then(|node| node.bounds()).unwrap_or_else(|| panic!("{name} has a rect")) + }; + let (rows, columns, guides) = (rect("Rows: Total:"), rect("Columns: Total:"), rect("Add Guides")); + assert!(columns.x0 > rows.x1, "the columns' fields stand right of the rows' fields: {rows:?} {columns:?}"); + assert!(columns.y0 < rows.y1 && rows.y0 < columns.y1, "the two Total fields share a line: {rows:?} {columns:?}"); + assert!(guides.y0 >= rows.y1.max(columns.y1), "Add Guides stands below the grid: {guides:?} {rows:?} {columns:?}"); +} diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index e81e7a81e4..016cf865aa 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -206,6 +206,67 @@ fn export_as_png_picks_the_file_then_shows_png_options() { assert_eq!(&written.borrow()[0].1[16..20], 120u32.to_be_bytes(), "60 pt at 144 ppi"); } +/// PNG Options' pixel size is in the window's accessibility tree, and it follows the resolution. +#[test] +fn png_options_name_the_pixel_size_in_the_accessibility_tree() { + let (mut app, _) = app(1); + app.run("file.export.png", json!({})).unwrap(); + answer_saves(&mut app); + let sizes = |app: &mut VectorcraftApp| -> Vec { + super::tests::settle(app); + let out = super::tests::frame(app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter_map(|(_, node)| node.label()).filter(|label| label.ends_with(" px")).map(str::to_owned).collect() + }; + let at_72 = sizes(&mut app); + assert_eq!(at_72, ["60 × 40 px"]); + set(&mut app, "ppi", json!(144)); + assert_eq!(sizes(&mut app), ["120 × 80 px"]); +} + +/// The role and name of each node of the window's accessibility tree, in a frame drawn once the dialogs have settled. +fn access_names(app: &mut VectorcraftApp) -> Vec<(egui::accesskit::Role, String)> { + super::tests::settle(app); + let out = super::tests::frame(app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter_map(|(_, node)| node.label().map(|label| (node.role(), label.to_owned()))).collect() +} + +/// The hints under Export As, DXF Options and EPS Options, the words of the DXF scale row and the HP-GL pen numbers +/// are in the window's accessibility tree, and the HP-GL pen error is announced as an alert. +#[test] +fn export_dialogs_name_their_hints_rows_and_errors_in_the_accessibility_tree() { + let names = |app: &mut VectorcraftApp| -> Vec { access_names(app).into_iter().map(|(_, name)| name).collect() }; + let (mut app, _) = app(1); + app.run("file.exportAs", json!({"format": "png", "useArtboards": false})).unwrap(); + let shown = names(&mut app); + assert!(shown.iter().any(|n| n == "The bounds of the visible art."), "{shown:?}"); + cancel(&mut app); + + crate::menus::invoke(&mut app, "ui.dxfOptionsDialog", json!({})); + let shown = names(&mut app); + for word in ["=", "Units"] { + assert!(shown.iter().any(|n| n == word), "{word} is not named in {shown:?}"); + } + assert!(shown.iter().any(|n| n.starts_with("Type becomes outlines")), "{shown:?}"); + cancel(&mut app); + + crate::menus::invoke(&mut app, "ui.epsOptionsDialog", json!({})); + let shown = names(&mut app); + assert!(shown.iter().any(|n| n.starts_with("Transparency is flattened with the preset.")), "{shown:?}"); + cancel(&mut app); + + app.run("ui.hpglOptionsDialog", json!({})).unwrap(); + set(&mut app, "pens", json!(["#ff0000", "#000000"])); + set(&mut app, "__penError", json!("The pens could not be listed.")); + let shown = access_names(&mut app); + assert!(shown.iter().any(|(_, n)| n == "2"), "the second pen's number is not named in {shown:?}"); + assert!( + shown.iter().any(|(role, n)| *role == egui::accesskit::Role::Alert && n.contains("The pens could not be listed.")), + "the pen error is not an alert in {shown:?}" + ); +} + /// File › Export › Export As PNG… exports the artboard in use, not the first (#5502), and each /// artboard the Artboard tool has selected, one file each. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 30a1aa9d65..622756a1bd 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -1,6 +1,7 @@ //! The Import PDF dialog: opening and placing multi-page and password-protected PDFs. use craft::ui::dialog::{HeldOk, StackDialog}; +use egui_kittest::kittest::Queryable; use serde_json::json; use vectorcraft_doc::NodeKind; use vectorcraft_engine::Session; @@ -72,6 +73,50 @@ fn artboard_widths(app: &VectorcraftApp) -> Vec { app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect.width()).collect() } +fn click_page_footer_ok(app: VectorcraftApp, dismiss: bool) -> egui_kittest::Harness<'static, VectorcraftApp> { + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::testing::install(ui.ctx()); + return; + } + app.dialogs().unwrap().with(|host| host.run(ui)); + super::import_pdf::pump(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + if dismiss { + h.get_by_label("OK").focus(); + h.run_steps(2); + h.get_by_label("OK").click_accesskit(); + h.input_mut().events.push(egui::Event::Key { + key: egui::Key::Escape, + physical_key: None, + pressed: true, + repeat: false, + modifiers: Default::default(), + }); + } else { + h.get_by_label("OK").click(); + } + h.run_steps(4); + assert!(!is_open(h.state())); + h +} + +#[test] +fn pdf_page_footer_ok_opens_the_chosen_range() { + let mut app = app(); + io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap(); + set(&mut app, "allPages", json!(false)); + set(&mut app, "range", json!("2-3")); + + let h = click_page_footer_ok(app, false); + assert_eq!(artboard_widths(h.state()), [200.0, 300.0]); +} + #[test] fn opening_a_multi_page_pdf_asks_for_the_pages() { let mut app = app(); @@ -228,6 +273,24 @@ fn place(app: &mut VectorcraftApp, bytes: &[u8], extra: serde_json::Value) -> Re crate::place::run(app, &p) } +#[test] +fn pdf_page_footer_ok_places_the_chosen_page_unless_dismissed() { + for dismiss in [false, true] { + let mut app = app(); + place(&mut app, &three_pages(), json!({"at": [100, 120], "link": false})).unwrap(); + set(&mut app, "page", json!(2)); + set(&mut app, "cropTo", json!("art")); + + let h = click_page_footer_ok(app, dismiss); + if dismiss { + assert!(h.state().session.active().unwrap().selection.objects.is_empty()); + } else { + let (_, bounds) = placed(h.state()); + assert_eq!((bounds.width(), bounds.height()), (50.0, 60.0)); + } + } +} + #[test] fn placing_a_pdf_page_asks_for_the_page_and_crop_box() { let mut app = app(); @@ -493,6 +556,81 @@ fn the_text_choice_applies_to_embedded_places_only() { assert_eq!(type_objects(&app), before, "placed as outlines"); } +/// `file.place` run as a command (MCP, scripts) without the dialog takes the PDF Text preference for +/// an embedded PDF with no `textAs`, as a place by the user does; a `textAs` given and a linked +/// place keep their own text. +#[test] +fn file_place_without_the_dialog_takes_the_pdf_text_preference() { + let mut app = app(); + set_pdf_text(&mut app, "outlines"); + let dir = vectorcraft_testkit::TempDir::new("import-pdf-text-at-once"); + let path = dir.join("two.pdf").to_string_lossy().into_owned(); + std::fs::write(&path, text_pages(2)).unwrap(); + let embedded = json!({"path": path, "link": false, "showImportOptions": false}); + crate::place::run(&mut app, &embedded).unwrap(); + assert!(!is_open(&app), "no dialog"); + assert_eq!(type_objects(&app), 0, "the preference: outlines"); + + let one = json!({"name": "one.pdf", "dataBase64": vectorcraft_format::base64_encode(&text_pages(1))}); + crate::place::run(&mut app, &one).unwrap(); + assert_eq!(type_objects(&app), 0, "one page from bytes: outlines"); + + let mut given = embedded.clone(); + given["textAs"] = json!("text"); + crate::place::run(&mut app, &given).unwrap(); + assert_eq!(type_objects(&app), 1, "a textAs given is kept"); + + crate::place::run(&mut app, &json!({"path": path, "showImportOptions": false})).unwrap(); + let st = app.session.active().unwrap(); + let placed = st.doc.node(st.selection.objects[0]).unwrap(); + assert!(matches!(placed.kind, NodeKind::PlacedDocument(_)), "linked: {:?}", placed.kind); + + // `file.place` reads an empty password as none, so the page stays linked. + crate::place::run(&mut app, &json!({"path": path, "password": "", "showImportOptions": false})).unwrap(); + let st = app.session.active().unwrap(); + let placed = st.doc.node(st.selection.objects[0]).unwrap(); + assert!(matches!(placed.kind, NodeKind::PlacedDocument(_)), "an empty password: linked: {:?}", placed.kind); + + set_pdf_text(&mut app, "text"); + crate::place::run(&mut app, &embedded).unwrap(); + assert_eq!(type_objects(&app), 2, "Editable: page 1's type object"); +} + +/// PDF bytes placed without a `name`, or under another extension, are a PDF by their content, as +/// `file.place` reads them, and take the PDF Text preference; under a `.ai` name they are placed as +/// the file says. +#[test] +fn pdf_bytes_without_a_pdf_name_take_the_pdf_text_preference() { + let mut app = app(); + set_pdf_text(&mut app, "outlines"); + let data = vectorcraft_format::base64_encode(&text_pages(1)); + crate::place::run(&mut app, &json!({"dataBase64": data, "showImportOptions": false})).unwrap(); + assert!(!is_open(&app), "no dialog"); + assert_eq!(type_objects(&app), 0, "unnamed bytes: outlines"); + + crate::place::run(&mut app, &json!({"name": "page.bin", "dataBase64": data, "showImportOptions": false})).unwrap(); + assert_eq!(type_objects(&app), 0, "another extension: outlines"); + + crate::place::run(&mut app, &json!({"name": "page.ai", "dataBase64": data, "showImportOptions": false})).unwrap(); + assert_eq!(type_objects(&app), 1, "a .ai file: its own text"); +} + +/// With Show Import Options off, an encrypted PDF placed with an empty `password` asks for its +/// password, as one placed without a `password` does. +#[test] +fn an_empty_password_asks_for_the_password_of_an_encrypted_pdf() { + let mut app = app(); + let bytes = pdf(&[PdfPage::new(120.0, 60.0, "1 0 0 rg 0 0 20 20 re f")], Some("pw")); + place(&mut app, &bytes, json!({"password": "", "showImportOptions": false})).unwrap(); + assert_eq!((field(&app, "__locked"), field(&app, "__passwordOnly")), (json!(true), json!(true))); + set(&mut app, "password", json!("pw")); + confirm(&mut app).unwrap(); + assert!(!is_open(&app)); + let st = app.session.active().unwrap(); + let b = st.doc.node(st.selection.objects[0]).and_then(|n| n.geometric_bounds()).unwrap(); + assert!((b.width() - 120.0).abs() < 0.01, "placed once unlocked: {}", b.width()); +} + /// `file.place` reads an empty or null `password` as none: a place from a path with Link on stays /// linked with the PDF Text preference at Outlines, and only a password that is given embeds it. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index f558c6690f..e551e71627 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -115,6 +115,18 @@ fn simplify_opens_a_slider_whose_drag_previews_fewer_or_more_points() { assert_eq!(anchor_count(&app), 2); } +/// The Simplify dialog's count of anchor points before and after is in the window's accessibility tree. +#[test] +fn the_simplify_dialog_names_its_anchor_point_counts() { + let mut app = app_with_dense_path(); + open_simplify_dialog(&mut app); + settle(&mut app); + let out = frame(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let names: Vec<&str> = nodes.iter().filter_map(|(_, node)| node.label()).collect(); + assert!(names.iter().any(|n| n.starts_with("Anchor Points:") && n.contains('→')), "{names:?}"); +} + /// A wave of 20 anchors `width` pt wide and `width / 5` pt high, selected. fn app_with_wave(width: f64) -> VectorcraftApp { let mut app = window(VectorcraftApp::new(Session::new(), Default::default())); diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index 81ecca1d9b..089296ae7a 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -104,6 +104,39 @@ fn define_grid_opens_on_the_grid_and_applies_its_fields() { assert_eq!((grid(&app).cell, grid(&app).viewing_angle()), (n.cell, n.viewing_angle())); } +#[test] +fn define_grid_applies_only_to_the_document_where_it_opened() { + let mut app = app(); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let destination = app.session.active().unwrap(); + let destination_uid = destination.uid; + let destination_undo = destination.history.undo.len(); + let destination_grid = grid(&app); + app.run("document.activate", json!({"index": 0})).unwrap(); + let source_uid = app.session.active().unwrap().uid; + app.run("ui.perspectiveGridDialog", json!({})).unwrap(); + set(&mut app, "rightColor", json!("#112233")).unwrap(); + let ctx = window(&app); + let id = dialog_id(super::perspective_grid::KIND); + host(&app, |h| { + assert!(!h.confirm_by_id(&ctx, id)); + assert_eq!(h.held_state(id), Some(HeldOk::Waiting)); + }); + + app.run("document.activate", json!({"index": 1})).unwrap(); + super::perspective_grid::pump(&mut app, &ctx); + assert_eq!(app.session.active().unwrap().uid, destination_uid); + assert_eq!(grid(&app), destination_grid, "the first document's draft leaves the active grid alone"); + assert_eq!(app.session.active().unwrap().history.undo.len(), destination_undo); + assert!(matches!(host(&app, |h| h.held_state(id)), Some(HeldOk::Refused(_)))); + + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source_uid); + ok(&mut app); + assert_eq!(kind(&app), None); + assert_eq!(grid(&app).right_color.hex(), "#112233"); +} + #[test] fn define_grid_loads_and_saves_presets() { let mut app = app(); @@ -147,6 +180,46 @@ fn define_grid_loads_and_saves_presets() { assert_eq!(app.session.prefs.perspective_presets.len(), 2); } +/// Enter pressed in the field that has the focus, then the passes that run the filed answer and close the dialog. +fn enter(app: &mut VectorcraftApp) { + let ctx = window(app); + let key = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + crate::tests::synthetic::key_frame(app, &ctx, vec![key(true)]); + crate::tests::synthetic::key_frame(app, &ctx, vec![key(false)]); + frame(app); + frame(app); +} + +#[test] +fn enter_is_ok_in_define_grid_and_save_grid_as_preset() { + let mut app = app(); + // Define Grid: Enter in the focused field defines the grid and closes the dialog. + app.run("ui.perspectiveGridDialog", json!({})).unwrap(); + set(&mut app, "angle", json!(30)).unwrap(); + frame(&mut app); + frame(&mut app); + assert!(window(&app).memory(|m| m.focused()).is_some(), "a field of the dialog has the focus"); + enter(&mut app); + assert_eq!(kind(&app), None, "Enter closes Define Grid"); + assert!((grid(&app).viewing_angle() - 30.0).abs() < 1e-9, "Enter defines the grid"); + // Save Grid as Preset: Enter in the name field saves the preset and closes the dialog. + app.run("ui.savePerspectivePreset", json!({})).unwrap(); + frame(&mut app); + frame(&mut app); + assert!(window(&app).memory(|m| m.focused()).is_some(), "a field of the dialog has the focus"); + enter(&mut app); + assert_eq!(kind(&app), None, "Enter closes Save Grid as Preset"); + assert_eq!(app.session.prefs.perspective_presets.len(), 1, "Enter saves the preset"); + // A name the presets refuse: Enter files it, the refusal shows, and the dialog stays. + app.run("ui.savePerspectivePreset", json!({})).unwrap(); + set(&mut app, "name", json!("[2P-Normal View]")).unwrap(); + frame(&mut app); + frame(&mut app); + enter(&mut app); + assert_eq!(kind(&app).as_deref(), Some(super::perspective_grid::KIND), "a refused name keeps the dialog open"); + assert_eq!(app.session.prefs.perspective_presets.len(), 1); +} + #[test] fn the_presets_manager_creates_edits_and_deletes_presets() { use super::perspective_presets::{self, Action}; @@ -187,6 +260,23 @@ fn the_presets_manager_creates_edits_and_deletes_presets() { assert!(app.run("ui.perspectiveUserPreset3.1", json!({})).is_err()); } +/// Export… suggests the selected preset's name as the file name, a built-in one's without its brackets. +#[test] +fn the_presets_manager_exports_to_a_file_named_after_the_preset() { + use super::perspective_presets::{self, Action}; + let mut app = app(); + let picker = crate::tests_picks::scripted(&mut app); + app.run("perspective.presets.save", json!({"name": "Street"})).unwrap(); + app.run("ui.perspectivePresetsDialog", json!({"selected": "Street"})).unwrap(); + frame(&mut app); + for (preset, file) in [("Street", "Street.vcperspective"), ("[2P-High View]", "2P-High View.vcperspective")] { + perspective_presets::run(&mut app, Action::Export, preset).unwrap(); + assert_eq!(picker.requests().last().and_then(|r| r.file_name.clone()).as_deref(), Some(file), "{preset}"); + picker.cancel(); + frame(&mut app); + } +} + #[test] fn perspective_preset_menus_list_the_views_of_each_type() { let app = app(); diff --git a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs index 166961be91..37b5555966 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs @@ -87,6 +87,21 @@ fn labels_units_sections_text_and_lists_come_from_the_manifest() { assert_eq!(rows.iter().filter(|p| p.key == "angles").count(), 1); } +#[test] +fn a_slider_widget_makes_a_whole_number_range_row_of_an_int_parameter() { + use craft::ui::patterns::form_dialogs::ParamKind; + let manifest = r#"{"id":"test.ui.fields.slider","name":"Slide","version":"1","kind":"filter","params":{ + "count":{"type":"int","min":1,"max":20,"default":4,"widget":"slider"}, + "plain":{"type":"int","min":1,"max":20,"default":4}}}"#; + let parsed = vectorcraft_plugins::manifest::Manifest::parse(manifest.as_bytes()).unwrap(); + let rows = super::form::plugin_params(&parsed, &Map::new()); + let kind = |key: &str| &rows.iter().find(|p| p.key == key).unwrap_or_else(|| panic!("no row for {key}")).kind; + assert!(matches!(kind("count"), ParamKind::Range { min, max, .. } if (*min, *max) == (1.0, 20.0)), "an int slider is a range row"); + assert!(matches!(kind("plain"), ParamKind::Int { .. }), "an int without the key stays a number field"); + // The slider's value reaches the plug-in as a whole number. + assert_eq!(super::form::typed_number(7.0), json!(7)); +} + #[test] fn visible_when_shows_a_parameter_only_while_its_condition_holds() { let id = "test.ui.fields.visible"; diff --git a/crates/ui-egui/src/dialogs/tests_plugin_import.rs b/crates/ui-egui/src/dialogs/tests_plugin_import.rs index 2fad4cf5dc..7a42d96f9f 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_import.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_import.rs @@ -8,7 +8,7 @@ use serde_json::json; use vectorcraft_engine::Session; use vectorcraft_plugins::wat::{self as tpl, Given}; -use super::tests_export::{fields, frame, kind, set, try_confirm}; +use super::tests_export::{cancel, fields, frame, kind, set, try_confirm}; use super::*; use crate::Services; use crate::VectorcraftApp; @@ -237,6 +237,180 @@ fn a_dropped_file_only_an_importer_reads_opens() { app.run("plugin.remove", json!({"id": "test.ui.dropshare"})).unwrap(); } +/// A file only an importer that places its files reads, dropped on the canvas, is placed there as +/// one group by that importer, as one undo step; dropped where the platform gives no position, it +/// opens as its own document, as a vector file does. +#[test] +fn a_dropped_file_a_placing_importer_reads_is_placed_on_the_canvas() { + use crate::place::{DropSpot, DropTarget, drop_files}; + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(800.0, 600.0)); + let on_canvas = DropSpot::Canvas(vectorcraft_geom::Point::new(400.0, 300.0)); + let manifest = tpl::importer("test.ui.dropplace", r#"["tdp"]"#, "{}").replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + assert!(manifest.contains(r#""place":true"#), "{manifest}"); + install(&mut app, &tpl::returning(&manifest, RECT)); + + let target = app.drop_target("Drawing.tdp", on_canvas, false); + assert!(matches!(target, DropTarget::Place(_)), "{target:?}"); + assert_eq!(app.drop_target("Drawing.tdp", DropSpot::Unknown, false), DropTarget::Open); + let steps = app.session.active().unwrap().history.undo.len(); + drop_files(&mut app, vec![(target, ("Drawing.tdp".into(), None, b"?".to_vec()))]); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), steps + 1, "one undo step"); + let [id] = st.selection.objects[..] else { panic!("one placed object: {:?}", st.selection.objects) }; + let n = st.doc.node(id).unwrap(); + assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. }) && n.name.as_deref() == Some("Drawing.tdp"), "{n:?}"); + + app.run("plugin.remove", json!({"id": "test.ui.dropplace"})).unwrap(); +} + +/// A text file or DXF drawing placed with the importer `importer` names goes to that importer, +/// without the text or DXF import options File › Place asks for those formats. +#[test] +fn a_named_placing_importer_skips_built_in_import_options() { + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let manifest = tpl::importer("test.ui.namedplace", r#"["txt","dxf"]"#, "{}").replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::returning(&manifest, RECT)); + for name in ["Notes.txt", "Plan.dxf"] { + let steps = app.session.active().unwrap().history.undo.len(); + let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(b"0\nSECTION\n"), "importer": "plugin.test.ui.namedplace"}); + let r = app.run("file.place", p).unwrap(); + assert!(kind(&app).is_none(), "{name}: no import options dialog"); + assert_eq!(r["format"], "plugin.test.ui.namedplace", "{name}: {r}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "{name}"); + } + app.run("plugin.remove", json!({"id": "test.ui.namedplace"})).unwrap(); +} + +/// `file.place` with `paths`, `importer` and `params` opens the Place dialog, and its OK places the +/// files with that importer and those parameters: one file at once, several through the place +/// cursor. The files are SVG files by their extension, which the built-in reader can't read. +#[test] +fn the_place_dialog_places_paths_with_the_importer_and_params_given() { + let dir = tmp_dir("placepaths"); + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#; + let manifest = tpl::importer("test.ui.placepaths", r#"["svg"]"#, params).replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::when_given(&manifest, Given::Params, r#""density":7.0"#, RECT)); + let paths: Vec = ["a.svg", "b.svg"] + .iter() + .map(|n| { + let p = dir.join(n); + std::fs::write(&p, b"?").unwrap(); + p.to_string_lossy().into_owned() + }) + .collect(); + let given = + |paths: &[String]| json!({"paths": paths, "importer": "plugin.test.ui.placepaths", "params": {"density": 7}, "showImportOptions": false}); + + app.run("file.place", given(&paths[..1])).unwrap(); + assert_eq!(kind(&app).as_deref(), Some(crate::dialogs::place::KIND)); + let steps = app.session.active().unwrap().history.undo.len(); + try_confirm(&mut app).unwrap(); + assert_eq!(placed_group(&app).as_deref(), Some("a.svg"), "{}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + + app.run("file.place", given(&paths)).unwrap(); + try_confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options()["count"], 2, "{}", app.ui.status); + + app.run("plugin.remove", json!({"id": "test.ui.placepaths"})).unwrap(); +} + +/// A PDF file placed with an importer plug-in named is not read to tell whether Link would place it +/// as a document: the Place dialog counts it as a file the importer embeds. The file here doesn't +/// exist, which counts as a document when its start is read. +#[test] +fn the_place_dialog_does_not_read_a_file_a_named_importer_places() { + let dir = tmp_dir("placenamedpdf"); + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let manifest = tpl::importer("test.ui.placepdf", r#"["pdf"]"#, "{}").replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::returning(&manifest, RECT)); + let path = dir.join("missing.pdf").to_string_lossy().into_owned(); + let counted = |app: &mut VectorcraftApp, p: serde_json::Value| { + app.run("file.place", p).unwrap(); + assert_eq!(kind(app).as_deref(), Some(crate::dialogs::place::KIND)); + let f = fields(app); + cancel(app); + (f["__documents"].clone(), f["__others"].clone()) + }; + assert_eq!(counted(&mut app, json!({"paths": [path]})), (json!(true), json!(false))); + assert_eq!(counted(&mut app, json!({"paths": [path], "importer": "plugin.test.ui.placepdf"})), (json!(false), json!(true))); + app.run("plugin.remove", json!({"id": "test.ui.placepdf"})).unwrap(); +} + +/// `file.place` with `importer` and `params` and no file asks for the files, and the Place dialog's +/// OK places the picked files with that importer and those parameters: files the picker gives by +/// their contents (the web) and by their paths. A pick without them places with neither, also while +/// a pick with them is open. +#[test] +fn a_pick_places_with_the_importer_and_params_given() { + let dir = tmp_dir("placepick"); + let mut app = app(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#; + let manifest = tpl::importer("test.ui.placepick", r#"["svg"]"#, params).replace(r#""kind":"importer""#, r#""kind":"importer","place":true"#); + install(&mut app, &tpl::when_given(&manifest, Given::Params, r#""density":7.0"#, RECT)); + let picker = scripted(&mut app); + let ctx = crate::testing::ui_context(); + let with = json!({"importer": "plugin.test.ui.placepick", "params": {"density": 7}, "showImportOptions": false}); + + // The web: the picker answers with the files' contents. + app.run("file.place", with.clone()).unwrap(); + picker.answer_contents(&[("a.svg", b"?")]); + poll(&mut app, &ctx); + assert_eq!(fields(&app)["files"], json!([{"name": "a.svg", "importer": "plugin.test.ui.placepick", "params": {"density": 7}}])); + let steps = app.session.active().unwrap().history.undo.len(); + try_confirm(&mut app).unwrap(); + assert_eq!(placed_group(&app).as_deref(), Some("a.svg"), "{}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + + // The desktop: the picker answers with paths. + let path = dir.join("b.svg"); + std::fs::write(&path, b"?").unwrap(); + let path = path.to_string_lossy().into_owned(); + app.run("file.place", with.clone()).unwrap(); + picker.answer(&[&path]); + poll(&mut app, &ctx); + assert_eq!(fields(&app)["files"], json!([{"path": path, "importer": "plugin.test.ui.placepick", "params": {"density": 7}}])); + try_confirm(&mut app).unwrap(); + assert_eq!(placed_group(&app).as_deref(), Some("b.svg"), "{}", app.ui.status); + + app.run("file.place", json!({})).unwrap(); + picker.answer_contents(&[("c.svg", b"?")]); + poll(&mut app, &ctx); + assert_eq!(fields(&app)["files"], json!([{"name": "c.svg"}])); + cancel(&mut app); + + // Two picks open at once: each one's files keep that pick's importer and parameters, also when + // the later pick is answered first. + app.run("file.place", with).unwrap(); + app.run("file.place", json!({})).unwrap(); + picker.answer_contents(&[("e.svg", b"?")]); + poll(&mut app, &ctx); + assert_eq!(fields(&app)["files"], json!([{"name": "e.svg"}])); + cancel(&mut app); + picker.answer_contents(&[("d.svg", b"?")]); + poll(&mut app, &ctx); + assert_eq!(fields(&app)["files"], json!([{"name": "d.svg", "importer": "plugin.test.ui.placepick", "params": {"density": 7}}])); + try_confirm(&mut app).unwrap(); + assert_eq!(placed_group(&app).as_deref(), Some("d.svg"), "{}", app.ui.status); + + app.run("plugin.remove", json!({"id": "test.ui.placepick"})).unwrap(); +} + +/// The name of the one selected object when it is a group: what an importer places. +fn placed_group(app: &VectorcraftApp) -> Option { + let st = app.session.active()?; + let [id] = st.selection.objects[..] else { return None }; + let n = st.doc.node(id)?; + matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. }).then(|| n.name.clone()).flatten() +} + /// The extensions File › Open's filters leave out of importers' (`fileio::opens_as_other`) are the /// ones File › Open installs, imports, checks or loads as something other than a document. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 3429cf323e..5fa18d848b 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -399,6 +399,23 @@ fn the_control_channel_fills_and_confirms_the_dialog() { assert_eq!(jobs.borrow().len(), 1); } +/// The Summary section's Pages, Options and Warnings are each named in the window's accessibility tree, with their +/// summary text as the value. +#[test] +fn the_summary_names_its_pages_options_and_warnings() { + let (mut app, _) = app(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "section", json!("Summary")); + pump(&mut app); + let ctx = ctx(&app); + let out = crate::testing::app_frame(&mut app, &ctx, Default::default()); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + for name in ["Pages", "Options", "Warnings"] { + assert!(nodes.iter().any(|(_, n)| n.label() == Some(name) && n.value().is_some_and(|v| !v.is_empty())), "{name} has no summary"); + } +} + /// Scale W and H of the open dialog, and its link. fn scale(app: &VectorcraftApp) -> (f64, f64, bool) { let f = fields(app); @@ -521,3 +538,40 @@ fn a_spot_inks_icon_converts_it_to_process_and_back() { pump(&mut app); assert_eq!(inks(&app), json!([{"name": "Gold", "print": true, "convertToProcess": false}])); } + +/// The names screen readers give the number and text fields in `out`'s accessibility tree: a field's own +/// name, else the text of a label it is labeled by, else "". +pub(super) fn field_names(out: &egui::FullOutput) -> Vec { + use egui::accesskit::Role; + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let text_of = |id| nodes.iter().find(|(n, _)| *n == id).and_then(|(_, n)| n.label().or(n.value())).map(str::to_string); + nodes + .iter() + .filter(|(_, n)| matches!(n.role(), Role::TextInput | Role::SpinButton)) + .map(|(_, n)| n.label().map(str::to_string).or_else(|| n.labelled_by().iter().find_map(|l| text_of(*l))).unwrap_or_default()) + .collect() +} + +/// Every number and length field of the dialog's sections has a name that tells it from the others in its row. +#[test] +fn every_number_and_length_field_is_named() { + let (mut app, _) = app(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + let sections: [(&str, &[&str]); 4] = [ + ("General", &["Copies", "Range", "Width", "Height", "Overlap", "Tile Range", "Gutter", "Scale 1", "Scale 2"]), + ("Marks and Bleed", &["Offset", "Top", "Bottom", "Left", "Right"]), + ("Graphics", &["Flatness"]), + ("Advanced", &["Unprintable margin"]), + ]; + for (section, expected) in sections { + set(&mut app, "section", json!(section)); + pump(&mut app); + let ctx = ctx(&app); + let out = crate::testing::app_frame(&mut app, &ctx, Default::default()); + let names = field_names(&out); + for name in expected { + assert!(names.iter().any(|n| n == name), "{section}: {name} in {names:?}"); + } + } +} diff --git a/crates/ui-egui/src/dialogs/tests_print_presets.rs b/crates/ui-egui/src/dialogs/tests_print_presets.rs index 65f4d2217f..a14ad40635 100644 --- a/crates/ui-egui/src/dialogs/tests_print_presets.rs +++ b/crates/ui-egui/src/dialogs/tests_print_presets.rs @@ -131,6 +131,8 @@ fn presets_files_import_and_export() { app.run("ui.printPresetsDialog", json!({"selected": "Mine"})).unwrap(); pump(&mut app); press(&mut app, ManagerAction::Export); + // The save panel suggests the preset's name. + assert_eq!(picker.requests().last().and_then(|r| r.file_name.clone()).as_deref(), Some("Mine.vcprintpresets")); picker.answer_saved(&file, None); let ctx = app.ui_ctx.clone().expect("the test app has a window"); crate::tests_picks::poll(&mut app, &ctx); @@ -141,5 +143,11 @@ fn presets_files_import_and_export() { assert_eq!(names, ["Mine", "Mine 2"]); assert_eq!(app.session.prefs.print_presets[1].settings.copies, 2); assert!(app.ui.status.contains("print presets"), "{}", app.ui.status); + // The built-in preset's file is named without its brackets. + app.run("ui.printPresetsDialog", json!({"selected": DEFAULT_PRESET})).unwrap(); + pump(&mut app); + press(&mut app, ManagerAction::Export); + assert_eq!(picker.requests().last().and_then(|r| r.file_name.clone()).as_deref(), Some("Default.vcprintpresets")); + picker.cancel(); let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/ui-egui/src/dialogs/tests_raster_formats.rs b/crates/ui-egui/src/dialogs/tests_raster_formats.rs index c56f69a7f0..be2d65a5cf 100644 --- a/crates/ui-egui/src/dialogs/tests_raster_formats.rs +++ b/crates/ui-egui/src/dialogs/tests_raster_formats.rs @@ -89,6 +89,62 @@ fn a_cmyk_document_exports_cmyk_by_default() { } } +/// GIF and PNG-8 Options start with No Transparency Dither at amount 100 and send the chosen +/// method and amount, which change the file of partly transparent art. +#[test] +fn palette_options_send_the_transparency_dither() { + let (mut app, written) = app(1); + app.run("transparency.set", json!({"opacity": 40})).unwrap(); + let export = |app: &mut VectorcraftApp, format: &str, sets: &[(&str, serde_json::Value)]| { + app.run("file.exportAs", json!({"format": format})).unwrap(); + confirm(app); + let d = fields(app); + assert_eq!((d.text("transparencyDither"), d.number("transparencyDitherAmount")), (Some("none"), Some(100.0)), "{format}"); + for (k, v) in sets { + set(app, k, v.clone()); + } + frame(app); + try_confirm(app).unwrap_or_else(|e| panic!("{format}: {e}")); + written.borrow().last().unwrap().1.clone() + }; + for format in ["gif", "png8"] { + let none = export(&mut app, format, &[]); + let diffusion = export(&mut app, format, &[("transparencyDither", json!("diffusion")), ("transparencyDitherAmount", json!(100))]); + assert_ne!(diffusion, none, "{format}"); + assert_eq!(export(&mut app, format, &[("transparencyDither", json!("diffusion")), ("transparencyDitherAmount", json!(0))]), none, "{format}"); + assert_ne!(export(&mut app, format, &[("transparencyDither", json!("pattern"))]), none, "{format}"); + // With Transparency off the rows keep their values and change nothing. + let opaque = export(&mut app, format, &[("transparency", json!(false))]); + assert_eq!(export(&mut app, format, &[("transparencyDither", json!("noise")), ("transparency", json!(false))]), opaque, "{format}"); + } +} + +/// The Transparency Dither row and Diffusion's amount row are named in the accessibility tree, +/// the amount row shows only for Diffusion, and both are disabled while Transparency is off. +#[test] +fn palette_options_name_the_transparency_dither_controls() { + let (mut app, _) = app(1); + app.run("file.exportAs", json!({"format": "png8"})).unwrap(); + confirm(&mut app); + let names = |app: &mut VectorcraftApp| -> Vec { + super::tests::settle(app); + let out = super::tests::frame(app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter(|(_, n)| n.role() != egui::accesskit::Role::Label).filter_map(|(_, n)| n.label().map(str::to_owned)).collect() + }; + let named = |shown: &[String], name: &str| shown.iter().any(|n| n == name); + let shown = names(&mut app); + assert!(named(&shown, "Transparency Dither"), "{shown:?}"); + assert!(!named(&shown, "Transparency Dither Amount"), "only Diffusion has an amount: {shown:?}"); + set(&mut app, "transparencyDither", json!("diffusion")); + let shown = names(&mut app); + assert!(named(&shown, "Transparency Dither Amount"), "{shown:?}"); + set(&mut app, "transparency", json!(false)); + assert!(try_set(&mut app, "transparencyDither", json!("noise")).is_err(), "disabled without Transparency"); + assert!(try_set(&mut app, "transparencyDitherAmount", json!(50)).is_err(), "disabled without Transparency"); + assert_eq!(fields(&app).text("transparencyDither"), Some("diffusion"), "kept"); +} + #[test] fn text_export_options_write_the_stories() { let (mut app, written) = app(1); diff --git a/crates/ui-egui/src/dialogs/tests_screens.rs b/crates/ui-egui/src/dialogs/tests_screens.rs index 544985b8d2..af68809f46 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -67,6 +67,36 @@ fn stays_open(app: &mut VectorcraftApp) { assert_eq!(kind(app).as_deref(), Some(export_for_screens::KIND)); } +#[test] +fn a_queued_export_requires_fresh_confirmation_after_switching_documents() { + use craft::ui::dialog::{HeldOk, dialog_id}; + + let (mut app, log) = app(1, true); + let source = app.session.active().unwrap().uid; + app.run("file.new", json!({"width": 40, "height": 30})).unwrap(); + app.run("artboard.rename", json!({"indices": [0], "name": "Destination"})).unwrap(); + let destination = app.session.active().unwrap().uid; + app.run("window.previousDocument", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, source); + open(&mut app); + + let ctx = app.ui_ctx.clone().unwrap(); + let dialogs = app.dialogs().unwrap(); + let id = dialog_id(export_for_screens::KIND); + dialogs.with(|host| { + assert!(!host.confirm_by_id(&ctx, id)); + assert_eq!(host.held_state(id), Some(HeldOk::Waiting)); + }); + app.run("window.nextDocument", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().uid, destination); + export_for_screens::pump(&mut app, &ctx); + + assert!(log.borrow().is_empty(), "the earlier OK cannot download from the destination tab"); + assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_)))); + try_confirm(&mut app).unwrap(); + assert_eq!(log.borrow().iter().map(|(name, _)| name.as_str()).collect::>(), ["Destination.png"]); +} + fn temp_folder(tag: &str) -> std::path::PathBuf { std::env::temp_dir().join(format!("vc-efs-{tag}-{}", std::process::id())) } @@ -837,18 +867,25 @@ fn big_tiff_tags(bytes: &[u8]) -> Vec<(u16, u16, u32, u16)> { } /// Frames of the app's own window (`app.ui_ctx`, where its dialogs are) with the accessibility -/// tree, input events and a clock; each frame runs the dialog layer's pump after it. +/// tree, input events and a clock; each frame runs the dialog layer's pump after it. The window is +/// 1280 by 900 unless `sized` gives another size. #[derive(Default)] pub(super) struct Window { time: f64, + size: Option, } impl Window { + /// A window of `size` instead of the default 1280 by 900. + fn sized(size: egui::Vec2) -> Self { + Self { size: Some(size), ..Self::default() } + } + fn run(&mut self, app: &mut VectorcraftApp, events: Vec) -> egui::FullOutput { let ctx = app.ui_ctx.clone().expect("a test app has a window"); ctx.enable_accesskit(); self.time += 0.1; - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, self.size.unwrap_or(egui::vec2(1280.0, 900.0))); let input = egui::RawInput { events, time: Some(self.time), screen_rect: Some(screen), ..Default::default() }; // The window's frame with the app's frame input, as the hosts run it: the controls' commands reach the app. let out = crate::testing::part_frame(app, &ctx, input, |app, ui| app.ui(ui)); @@ -1429,3 +1466,82 @@ fn an_artboard_name_stays_with_its_document() { assert_eq!(names(&app, 1), ["Artboard 1", "Artboard 2"]); assert!(log.borrow().is_empty(), "renaming must not export"); } + +/// In a window of the default size and in one of the app's least size, every control of the dialog stays between its +/// sides, the format rows stay in the right column, and in the default window the Formats heading's buttons end at +/// the column's right edge. +#[test] +fn the_format_rows_fit_the_right_column_at_the_default_and_least_window_sizes() { + let rows = json!([ + {"scale": "1x", "suffix": "", "format": "png"}, + {"scale": "2x", "suffix": "@2x-long-suffix", "format": "jpg", "quality": 100}, + {"scale": "100w", "format": "pdf"}, + ]); + // The default window, then the least size the desktop app's window takes. + for (size, default) in [(egui::vec2(1280.0, 900.0), true), (egui::vec2(800.0, 500.0), false)] { + let (mut app, _) = app(2, false); + let mut w = Window::sized(size); + w.run(&mut app, vec![]); + open(&mut app); + set(&mut app, "formats", rows.clone()); + w.run(&mut app, vec![]); + let out = w.run(&mut app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let rect = |n: &egui::accesskit::Node| { + n.bounds().map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) + }; + let find = |label: &str, role: Role| { + nodes + .iter() + .find(|(_, n)| n.label() == Some(label) && n.role() == role) + .and_then(|(_, n)| rect(n)) + .unwrap_or_else(|| panic!("no {role:?} {label:?}")) + }; + let Some((dialog_id, dialog)) = nodes.iter().find(|(_, n)| n.role() == Role::Dialog) else { panic!("no dialog at {size:?}") }; + let dialog = rect(dialog).expect("the dialog's bounds"); + // The Export to: section spans the right column. + let column = find("Export to:", Role::Group); + let by_id: std::collections::HashMap<_, _> = nodes.iter().map(|(id, n)| (*id, n)).collect(); + let mut under = vec![*dialog_id]; + while let Some(id) = under.pop() { + let Some(n) = by_id.get(&id) else { continue }; + under.extend(n.children().iter().copied()); + if let Some(r) = rect(n) { + assert!( + r.left() >= dialog.left() - 0.5 && r.right() <= dialog.right() + 0.5, + "{:?} {:?} at {r:?} is outside the dialog at {dialog:?} in a {size:?} window", + n.role(), + n.label() + ); + } + } + // Each control with how many of it the three rows show. + let format_rows = [ + ("Formats:", Role::Label, 1), + ("iOS", Role::Button, 1), + ("Android", Role::Button, 1), + ("Format Presets", Role::Button, 1), + ("Format Settings", Role::Button, 1), + ("Scale", Role::ComboBox, 3), + ("Suffix", Role::TextInput, 3), + ("Format", Role::ComboBox, 3), + ("Remove", Role::Button, 3), + ("+ Add Scale", Role::Button, 1), + ]; + for (label, role, count) in format_rows { + let shown: Vec<_> = nodes.iter().filter(|(_, n)| n.label() == Some(label) && n.role() == role).collect(); + assert_eq!(shown.len(), count, "{role:?} {label:?} in a {size:?} window"); + for (_, n) in shown { + let r = rect(n).expect("bounds"); + assert!( + r.left() >= column.left() - 0.5 && r.right() <= column.right() + 0.5, + "{label} at {r:?} is outside the column at {column:?} in a {size:?} window" + ); + } + } + if default { + let gear = find("Format Settings", Role::Button); + assert!((gear.right() - column.right()).abs() <= 0.5, "the gear at {gear:?} ends at the column's edge {column:?}"); + } + } +} diff --git a/crates/ui-egui/src/dialogs/three_d.rs b/crates/ui-egui/src/dialogs/three_d.rs index 8345aad401..1bf8a87680 100644 --- a/crates/ui-egui/src/dialogs/three_d.rs +++ b/crates/ui-egui/src/dialogs/three_d.rs @@ -55,6 +55,8 @@ pub(crate) struct Data { pub bevels_file: bool, /// The active document, for the symbol pictures. pub doc: Option>, + /// The document that owns the object IDs accepted by the Graphics drop target. + pub document_uid: Option, /// The active document's version. pub revision: u64, /// Whether the active document has a selection. @@ -77,6 +79,7 @@ pub(crate) fn data(app: &VectorcraftApp, effect: Option<&str>, params: &Map) -> Param { } } if !seen.get(current - 1).copied().unwrap_or(true) { - ui.label(tl!("Hidden")); + Text::new(tl!("Hidden")).show(ui); } }); let shown = next.map_or(current, |n| n.clamp(1, count)); diff --git a/crates/ui-egui/src/dialogs/three_d_materials.rs b/crates/ui-egui/src/dialogs/three_d_materials.rs index fb0a3b7a0e..7b8aa67e2f 100644 --- a/crates/ui-egui/src/dialogs/three_d_materials.rs +++ b/crates/ui-egui/src/dialogs/three_d_materials.rs @@ -174,11 +174,12 @@ fn body(ui: &mut Ui, fields: &mut DialogFields, cx: &mut CustomContext, data: &D fn library(ui: &mut Ui, data: &Data, apply: bool) -> Option { Text::new(tl!("Graphics")).show(ui); let mut action = None; - let (Some(doc), true) = (data.doc.clone(), true) else { return action }; + let (Some(doc), Some(uid)) = (data.doc.clone(), data.document_uid) else { return action }; let names: Vec = doc.symbols.iter().map(|s| s.name.clone()).collect(); let keys = crate::panels::symbols::document_symbols(&doc, data.revision); let source = keyed(&names[..], |name: &String| name.clone()).with_text(|name| Cow::Borrowed(name.as_str())); - let mut dropped = DropAction::::new(|drag| matches!(drag, PanelDrag::Art { .. })).show(ui, |ui, _| { + let drop_art = DropAction::::new(move |drag| matches!(drag, PanelDrag::Art { document, .. } if *document == uid)); + let mut dropped = drop_art.show(ui, |ui, _| { TileGrid::new(tl!("Graphics")).activate(ActivateOn::Click).show_items(ui, &source, &mut |name, _| { let tip = if apply { name.clone() } else { format!("{name}: {}", tl!("Select a 3D object to map the graphic onto it.")) }; let (doc, keys, name) = (doc.clone(), keys.clone(), name.clone()); diff --git a/crates/ui-egui/src/dialogs/transform_each.rs b/crates/ui-egui/src/dialogs/transform_each.rs index 0ca75cd8e0..3672552552 100644 --- a/crates/ui-egui/src/dialogs/transform_each.rs +++ b/crates/ui-egui/src/dialogs/transform_each.rs @@ -17,7 +17,7 @@ use craft::behavior::Mixed; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::contract::{Bind, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel}; use craft::ui::dialog::{DialogHost, DialogId, FieldRefusal}; use craft::ui::display::Text; use craft::ui::form::Field; @@ -290,30 +290,32 @@ enum Measure { } /// One captioned side: a slider over `rail` and a number field in ±`limit`, `value` being none -/// while the objects differ (the field reads Mixed). Returns the value the user set this pass. +/// while the objects differ (the field reads Mixed). `caption` is the row (Scale or Move) and the +/// visible label; the label repeats in each row, so it only describes the controls, and their +/// names start with the row. Returns the value the user set this pass. fn side( ui: &mut Ui, key: &'static str, - label: impl Into