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..5e3dc3281c 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -141,6 +141,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 +215,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..0417aba6f0 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", @@ -8277,6 +8529,7 @@ dependencies = [ name = "vectorcraft-engine" version = "0.24.1" dependencies = [ + "apple-native-keyring-store", "cfb", "chrono", "craft-cdr", @@ -8290,12 +8543,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 +8561,7 @@ dependencies = [ "same-file", "serde", "serde_json", + "sha2 0.10.9", "skrifa 0.47.0", "thiserror 2.0.21", "tiff", @@ -8331,6 +8588,8 @@ dependencies = [ "vectorcraft-tools", "vectorcraft-trace", "wat", + "windows-native-keyring-store", + "zbus-secret-service-keyring-store", "zune-core", "zune-jpegxl", ] @@ -8479,7 +8738,7 @@ dependencies = [ name = "vectorcraft-pdf" version = "0.24.1" dependencies = [ - "aes", + "aes 0.8.4", "chrono", "craft", "craft-image-codecs", @@ -8497,7 +8756,7 @@ dependencies = [ "objc2-core-graphics", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "siphasher", "skrifa 0.47.0", "smallvec", @@ -8522,7 +8781,7 @@ dependencies = [ "rustix 1.1.6", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", "vectorcraft-color", "vectorcraft-doc", @@ -9464,6 +9723,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 +10093,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 +10313,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/ROADMAP.md b/ROADMAP.md index 4d415cc0ba..abd6a3548b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -147,6 +147,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 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. 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/main.rs b/apps/vectorcraft/src/main.rs index 9bfb5ea3d2..7c23fe71ba 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,6 +70,8 @@ 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 xwayland; @@ -206,6 +209,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 @@ -989,6 +995,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..b4940d192d 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); } } 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/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/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/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..5c52b167a1 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -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/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/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/params.rs b/crates/effects/src/params.rs index ab588838a6..fed9df7811 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -131,9 +131,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..74a10d337f 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -855,7 +855,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; 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..c474cfae85 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(); 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/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..42ee145c94 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -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..9e28b5805c 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 ), @@ -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, 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..33455ea9d9 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 ), @@ -1224,6 +1224,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 +1258,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/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/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..1178906459 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,10 +84,10 @@ 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. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct StopOwner { doc: Option, @@ -98,7 +98,8 @@ 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 { @@ -111,19 +112,24 @@ impl StopOwner { 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())) } @@ -526,9 +532,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 +553,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 +657,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..182dc0601f 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!( 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/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..b93db7b8a2 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -42,7 +42,9 @@ //! //! 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 @@ -53,7 +55,7 @@ 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 +103,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,6 +115,9 @@ 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); } @@ -147,7 +155,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 +382,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 +390,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 +398,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 +466,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 +486,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 +520,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 +884,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 +920,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 +945,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) } @@ -1533,9 +1608,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 +1873,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 +1923,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 +1958,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), 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 +1976,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 +1985,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 (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, 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 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)", always, install ), @@ -1893,7 +2003,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 ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index ec7d3ac989..9a715abf11 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -243,6 +243,7 @@ pub(super) const ALLOWED: &[&str] = &[ "layer.releaseToLayersBuild", "layer.reverse", "layer.selectAll", + "layer.selectHighlighted", "layer.setCurrent", "layer.setProps", "layer.showAll", @@ -741,6 +742,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..7c271a326a 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -710,6 +710,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 +823,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 +1006,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/stroke.rs b/crates/engine/src/cmd/stroke.rs index 78e56e8f33..420b3ed1eb 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() { @@ -622,7 +622,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/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index cde1456589..1d3c8f7d7b 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, )); @@ -636,52 +636,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 +648,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 +704,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). @@ -1204,17 +1090,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 +1117,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/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..f578bcd61d 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -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 ), @@ -403,6 +403,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 +455,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 +505,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 +816,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 +924,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 +991,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(|| { 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/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/interaction.rs b/crates/engine/src/interaction.rs index f7f9197f1d..6dd833263b 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -22,6 +22,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..04461b332c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -74,11 +74,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 +136,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 diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 1e0edb076e..87d6c6df80 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -93,6 +93,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, @@ -503,7 +505,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..9c137c96bd --- /dev/null +++ b/crates/engine/src/script/dom.rs @@ -0,0 +1,2321 @@ +//! 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}; + +/// 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 | Data::Undefined => 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 a change to the item's appearance, place, stacking order or size while a layer it is in +/// is hidden or locked. Its name and note may still change. +fn refuse_in_closed_layer(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)); + d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item")) + }); + match refused { + Some(name) => Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", 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_in_closed_layer(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_in_closed_layer(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_in_closed_layer(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_in_closed_layer(h, item)?; + 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_in_closed_layer(h, item)?; + 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, and so is an object in a hidden or locked layer. +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_in_closed_layer(h, item)?; + 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)), + ); + 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)), + ("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", + "tags", + "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, + )); + 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/mod.rs b/crates/engine/src/script/mod.rs index fdec594f69..f6f2bd36f6 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}; @@ -799,6 +800,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 +1075,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 +1266,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 +1336,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 +1385,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 +1649,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 +1690,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 { @@ -2007,7 +2032,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 +2042,9 @@ impl Session { Some(mut realm) => { realm.set_limits(limits); realm.set_es2015(es2015); + if es2015 { + realm.add_es2015(); + } realm } None => { @@ -2084,6 +2113,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 +2160,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); @@ -2318,6 +2349,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 +2399,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 +2502,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 +2608,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 +2634,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/session/documents.rs b/crates/engine/src/session/documents.rs index 770cfd2bea..d1e51ea792 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, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index cc7af44898..c82f7ca32c 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -518,6 +518,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 +539,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 +558,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)) @@ -720,15 +723,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..eb7de6e7c4 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -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()); } 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..f581be4dd6 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,6 +177,7 @@ mod scalestrokes; mod script_console; mod script_dialogs; mod script_dollar; +mod script_dom; mod script_engines; mod script_folder; mod script_include; 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/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/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/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/script_dom.rs b/crates/engine/src/tests/script_dom.rs new file mode 100644 index 0000000000..43ee65ba46 --- /dev/null +++ b/crates/engine/src/tests/script_dom.rs @@ -0,0 +1,1846 @@ +//! 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()); +} + +#[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)); +} + +/// Reading `editable` on every member of a group on a locked artboard measures the group once. +#[test] +fn editable_measures_a_group_on_a_locked_artboard_once() { + let (mut s, a, b) = doc(); + let mut ids = vec![a.0, b.0]; + ids.extend((0..20).map(|i| rect(&mut s, 10.0 + f64::from(i), 200.0, 5.0, 5.0).0)); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let before = vectorcraft_doc::locked_artboard_measures(); + let out = log(&mut s, "var p = app.activeDocument.pageItems, n = 0; for (var i = 0; i < p.length; i++) if (!p[i].editable) n++; vc.log(n);"); + assert_eq!(out, vec![json!(23)], "the group and its 22 members are on the locked artboard"); + assert_eq!(vectorcraft_doc::locked_artboard_measures() - before, 1); +} + +#[test] +fn get_is_file_open_cannot_probe_outside_script_scope() { + let (mut s, _, _) = doc(); + let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let p = path.to_string_lossy().replace('\\', "\\\\"); + let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let out = log(&mut s, &query); + assert_eq!(out, vec![json!(true), json!(false)]); + // Read roots that leave out the document's file: the same path does not count. + let elsewhere = std::env::temp_dir().join(format!("vc-dom-roots-{}", std::process::id())); + std::fs::create_dir_all(&elsewhere).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&elsewhere], &[]).unwrap().unwrap(); + let out = crate::file_access::confine(Some(&roots), || log(&mut s, &query)); + assert_eq!(out, vec![json!(false), json!(false)]); + let _ = std::fs::remove_dir_all(&elsewhere); + for bad in ["../x.svg", "a/../b.svg", "\\\\\\\\host\\\\share\\\\x.svg", "//host/share/x.svg", "a\\u0000b", ""] { + assert!(failure(&mut s, &format!("app.getIsFileOpen('{bad}');")).contains("cannot check"), "{bad}"); + } + assert!(failure(&mut s, "app.getIsFileOpen(new Array(5000).join('a'));").contains("too long")); + let _ = std::fs::remove_file(path); +} + +#[test] +fn a_menu_command_runs_its_command_on_the_selection() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + let out = log(&mut s, "app.executeMenuCommand('ungroup'); vc.log(app.activeDocument.selection.length);"); + assert_eq!(out, vec![json!(2)]); + let st = s.active().unwrap(); + assert!(st.doc.node(g).is_none(), "the group is gone"); + assert!(st.doc.node(a).is_some() && st.doc.node(b).is_some()); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + // With nothing selected the menu item does nothing and adds no undo step. + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + let before = s.active().unwrap().doc.clone(); + log(&mut s, "app.executeMenuCommand('ungroup'); app.executeMenuCommand('releaseMask');"); + assert_eq!(undo_steps(&s), steps); + assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc), "nothing changed"); + // selectall then group makes one group of both rectangles. + let out = log(&mut s, "app.executeMenuCommand('selectall'); app.executeMenuCommand('group'); vc.log(app.activeDocument.selection[0].typename);"); + assert_eq!(out, vec![json!("GroupItem")]); +} + +#[test] +fn the_fit_to_artwork_menu_command_fits_the_artboard_to_the_art() { + let (mut s, _, _) = doc(); + let before = s.active().unwrap().doc.artboards[0].rect; + log(&mut s, "app.executeMenuCommand('Fit Artboard to artwork bounds');"); + let after = s.active().unwrap().doc.artboards[0].rect; + assert!(after.width() < before.width() && after.height() < before.height(), "{before:?} -> {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_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_run.rs b/crates/engine/src/tests/script_run.rs index 56bc5854a1..c12653602f 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. 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/webexport.rs b/crates/engine/src/tests/webexport.rs index 39c95da3f6..9ab1aab001 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(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 446d441fc4..965abf399c 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, @@ -1486,6 +1495,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 +1582,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 +1787,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 +1806,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..61bfba6fb3 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 diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 2ec927bd48..07389dc866 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,70 @@ 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= 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= 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 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", + ), + ("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 +156,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 +186,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_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/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/js/src/builtins.rs b/crates/js/src/builtins.rs index 49eeebf9f4..86b31414b3 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -1,8 +1,8 @@ //! 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 +//! 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`) and //! the iterators of arrays, strings and `arguments` objects (in `iterator`). //! @@ -17,6 +17,7 @@ pub(crate) mod iterator; mod json; mod math; mod object; +pub(crate) mod promise; mod symbol; use std::rc::Rc; @@ -242,6 +243,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)?; @@ -262,6 +265,9 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { if interp.options.e4x { crate::xml_builtins::install(interp)?; } + if interp.options.es2015 { + promise::install(interp)?; + } Ok(()) } @@ -293,7 +299,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. @@ -516,6 +522,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 +575,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 +602,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 ---- 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..276acf7e96 --- /dev/null +++ b/crates/js/src/builtins/promise.rs @@ -0,0 +1,1191 @@ +//! `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. +//! +//! Until the language has iterators, `all`, `allSettled` and `race` read an array or another object +//! whose `length` is a whole number by index, and a string by code point; other 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, Class, Func, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, Roots, key}; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::string_builtins::flat_charged; +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), + /// 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) | 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); + 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)), + } + } + 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 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 = 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); + 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 or a +/// 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), + 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)) + }) +} + +/// Where the inputs of `Promise.all`, `allSettled` and `race` come from. An array is read up to +/// its length at each step, as an array iterator reads it, and another object up to the `length` +/// it had at the start. +enum Inputs { + Indexed { object: ObjId, length: f64 }, + CodePoints(Rc<[u16]>), +} + +impl Inputs { + fn new(interp: &mut Interp, input: &Value, how: Combine) -> JsResult { + match input { + Value::Object(o) => match interp.get_from(*o, &key("length"), input)? { + Value::Number(length) if length >= 0.0 && length.fract() == 0.0 && length <= 9_007_199_254_740_991.0 => { + Ok(Inputs::Indexed { object: *o, length }) + } + _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), + }, + Value::String(s) => Ok(Inputs::CodePoints(flat_charged(interp, s)?)), + _ => Err(interp.type_error(&format!("Promise.{} needs an array, a string or an object with a whole-number length", how.name()))), + } + } + + /// The input at `index`, which counts code units for a string; `None` past the end. + fn get(&self, interp: &mut Interp, index: &mut f64) -> JsResult> { + match self { + Inputs::Indexed { object, length } => { + let end = match interp.heap.object(*object).map(|o| &o.class) { + Some(Class::Array { length, .. }) => f64::from(*length), + _ => *length, + }; + if *index >= end { + return Ok(None); + } + let v = super::get_at(interp, *object, *index)?; + *index += 1.0; + Ok(Some(v)) + } + Inputs::CodePoints(units) => { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let i = *index as usize; + let Some(&first) = units.get(i) else { return Ok(None) }; + let pair = (0xD800..0xDC00).contains(&first) && units.get(i + 1).is_some_and(|u| (0xDC00..0xE000).contains(u)); + let n = if pair { 2 } else { 1 }; + let piece = units.get(i..i + n).unwrap_or_default().to_vec(); + *index += n as f64; + let bytes = crate::heap::string_bytes(piece.len()); + interp.reserve_heap(bytes)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); + Ok(Some(Value::String(crate::value::Str::from_units(piece)))) + } + } + } +} + +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 inputs = Inputs::new(interp, input, how)?; + 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 position = 0.0; + let mut index: u32 = 0; + loop { + interp.use_fuel()?; + let mark = interp.temp_roots.len(); + let Some(next) = inputs.get(interp, &mut position)? 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_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/heap.rs b/crates/js/src/heap.rs index af98f259df..57ec9d6680 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -264,8 +264,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 +335,11 @@ 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(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", @@ -777,6 +784,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..4e0275441a 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -113,6 +113,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 +192,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 +265,10 @@ 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.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); + } + 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)?; @@ -313,6 +324,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 +362,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 +404,32 @@ 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()), + ArgRead::Hosted => { + let this = match this { + Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined), + _ => Data::Undefined, + }; + let mut data = vec![this]; + data.extend(self.read_args(name, args, how)?); + data + } _ => self.read_args(name, 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) } @@ -478,7 +507,15 @@ impl Interp { /// 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() }; + 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, @@ -486,14 +523,14 @@ impl Interp { let mut data = Vec::with_capacity(args.len()); // 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), @@ -518,7 +555,7 @@ impl Interp { /// 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..d2994fb80b --- /dev/null +++ b/crates/js/src/host_classes.rs @@ -0,0 +1,368 @@ +//! 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))) + } + + /// 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()?; + let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) }; + let mut args = vec![this, k]; + if probe { + args.push(Data::Bool(true)); + } + 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..25265086e5 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -675,6 +675,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..c2b707e3c6 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -55,12 +55,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 { @@ -279,6 +304,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 +335,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 +379,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, @@ -583,6 +623,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 +636,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 +652,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 +704,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 { @@ -836,6 +882,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()); @@ -857,6 +904,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 +919,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. @@ -1573,6 +1629,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 +1940,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) { @@ -2782,7 +2869,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)?)); @@ -2893,6 +2980,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")), } } @@ -3139,7 +3245,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 +3285,21 @@ 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), + } + } + 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), @@ -3836,7 +3957,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 +4135,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 +4153,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/lib.rs b/crates/js/src/lib.rs index 0086d8ede6..17f2b1de0f 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 @@ -78,6 +78,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; @@ -90,6 +98,7 @@ mod error; mod file_classes; mod heap; mod host; +mod host_classes; mod interp; mod iteration; mod lexer; @@ -117,9 +126,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 +155,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, } @@ -264,6 +277,8 @@ 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/promise_tests.rs b/crates/js/src/promise_tests.rs new file mode 100644 index 0000000000..915427de89 --- /dev/null +++ b/crates/js/src/promise_tests.rs @@ -0,0 +1,424 @@ +//! `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 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 the_combinators_read_an_array_to_its_length_at_each_step_and_another_object_to_its_first_length() { + // `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(function (v) { log.push('object ' + v.join(',')); });"; + let out = log(src); + assert!(out.contains("array 1,2,3"), "{out}"); + assert!(out.contains("object 1"), "{out}"); + assert!(!out.contains("object 1,"), "{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 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..b1273cb760 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,21 @@ 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. 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.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 +300,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; @@ -324,13 +355,19 @@ impl Realm { 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 +378,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 }) } @@ -360,12 +402,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 +425,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 +440,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 +507,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 +544,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 +611,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/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..bd8c406b79 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -40,6 +40,12 @@ //! `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 @@ -58,7 +64,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 +369,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 +904,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] = &[ 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..fa2bc204f6 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", "", "{}"), ( @@ -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", @@ -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; 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 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", 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/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/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/manifest.rs b/crates/plugins/src/manifest.rs index f20756e149..e4274fc716 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. @@ -456,6 +456,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 +474,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, @@ -514,9 +524,11 @@ 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(), @@ -585,11 +597,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) => { @@ -682,6 +698,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 +802,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 +976,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 +1320,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 +1472,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/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/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/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..c04ce6b22c 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -16,6 +16,16 @@ //! 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. +//! +//! The tool's options (its options dialog, `tool.setOption`; kept with the preferences): `radius`; +//! `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 the +//! cross and the lines show, the color is red, the tolerance is 3 px and `snapWithoutGuides` is on. use kurbo::{CubicBez, Shape}; use serde_json::{Value, json}; @@ -42,6 +52,22 @@ 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 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] = &["center", "radii", "snapWithoutGuides"]; /// A segment under the pointer: where on it, and the segment itself. #[derive(Clone, Debug, PartialEq)] @@ -64,6 +90,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 +101,14 @@ struct Press { pub struct TangentCircleTool { radius: f64, + /// 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 +128,45 @@ 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, + 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; @@ -197,6 +266,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 +341,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; @@ -304,12 +393,12 @@ impl Tool for TangentCircleTool { self.pointer = ev.pos; 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 +413,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 => { @@ -415,21 +504,26 @@ 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 }); } out } @@ -439,14 +533,29 @@ impl Tool for TangentCircleTool { } fn options(&self) -> Value { - json!({ "radius": self.radius }) + json!({ + "radius": self.radius, + "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), + "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 +563,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 +710,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(); 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/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/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..6bbdc737d2 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)}))], @@ -2089,7 +2110,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 +2141,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 +2163,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 +2175,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 +2195,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..db755ccae5 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. diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 486de86876..acc5ff594e 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -639,6 +639,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/settings.rs b/crates/tools/src/settings.rs index 1d9d8c4a54..97b3c75cd2 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,8 @@ 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"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( @@ -108,7 +108,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", "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/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/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 307d4a3e29..8765b57c00 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -301,7 +301,18 @@ 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("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 +322,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..3c7af267e9 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -93,6 +93,90 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() { 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"), + ("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 +196,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..89d64872e8 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -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, @@ -382,7 +385,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 +445,9 @@ impl VectorcraftApp { let now = self.now(); self.perf.fps = self.frame_rate.frame(now, self.perf.frame_ms / 1000.0); self.sync_views(); + // 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 @@ -537,6 +544,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 @@ -692,15 +702,16 @@ impl VectorcraftApp { } /// 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 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..1dbe830af4 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()?; @@ -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..a4f97d7f6e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -5,7 +5,8 @@ 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::runtime::env::Env; @@ -108,6 +109,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 +138,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 +154,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 +182,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 +201,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 +217,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 +242,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 +259,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; } @@ -242,7 +281,12 @@ pub(crate) fn show_document(app: &mut VectorcraftApp, ui: &mut Ui, win: Win, kin 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); @@ -333,7 +377,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/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..50ab4ed40a 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -8,9 +8,9 @@ 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). +/// 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). pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { let mut bp = BezPath::new(); walk_drawn(n, &mut |c| match &c.kind { @@ -27,13 +27,19 @@ 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) { + } else if let Some(q) = c.drawn_corners(symbols) { + corners(&mut bp, q); + } + } + NodeKind::Image(_) => { + if let Some(b) = c.geometric_bounds_with(symbols) { bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); } } - NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => { - if let Some(b) = c.geometric_bounds_with(symbols) { - bp.extend(vectorcraft_geom::shapes::rectangle(b).to_bezpath()); + // 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 +62,14 @@ pub(super) fn node_outline(n: &Node, symbols: &SymbolBoxes) -> BezPath { 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 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/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/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 8722616ac2..7c4cb6aebf 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -53,6 +53,94 @@ fn a_symbol_instance_is_outlined_around_its_art() { assert_eq!(node_outline(inst.unwrap(), &st.doc.symbol_boxes()).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)); + 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)); + 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())); + assert!(same_points(&got, &drawn), "{got:?} is not the projected box {drawn:?}"); +} + /// One headless canvas frame on an 800 × 600 window. fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; @@ -905,6 +993,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 +1701,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 +1948,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 +2090,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 +2137,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 +3125,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 +3147,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 +3157,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 +3247,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"); } @@ -4927,6 +5222,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 +5246,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 +5269,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 +5292,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 +5353,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 +5828,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..0ccc63be2c 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); 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/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index ab90d71dc2..a0d69c55c5 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -609,9 +609,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..04a7240cf7 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()`. @@ -34,6 +34,9 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { 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 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 +71,18 @@ 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) + .show(ui) + .value() + .copied(); }); Divider::vertical().show(ui); for (icon, to, tip, enabled) in @@ -310,15 +318,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..0fbfa24fd4 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`]). diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 532c6ffef0..0d8ef2d500 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,33 @@ 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°")); +} + /// 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 +813,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 +833,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 +1188,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 +1213,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 { @@ -2476,6 +2600,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] diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index b7914c350f..813ed31d97 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 diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index fdda88b384..e7e617a74e 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] 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..86e918f876 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -117,6 +117,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/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/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 9584166098..12e13a36b3 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,8 +82,18 @@ 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. @@ -110,6 +121,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 +138,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 +200,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). @@ -240,8 +258,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); } @@ -273,8 +291,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 +308,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/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/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..ebb78e8c90 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -561,6 +561,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] 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/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..8a31fafae0 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -298,7 +298,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..300d5543a3 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] @@ -60,7 +86,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}), @@ -306,3 +332,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..2ac4764bf5 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -712,7 +712,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)) @@ -1015,6 +1014,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/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/kinsoku_sets.rs b/crates/ui-egui/src/dialogs/kinsoku_sets.rs index c2c334f148..1aac4c28b8 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, }; @@ -408,9 +410,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/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..e0e68d0eda 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), } } @@ -234,6 +231,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..bed5ab085b 100644 --- a/crates/ui-egui/src/dialogs/perspective_grid.rs +++ b/crates/ui-egui/src/dialogs/perspective_grid.rs @@ -482,7 +482,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); 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..319d3a49b3 100644 --- a/crates/ui-egui/src/dialogs/preset_manager.rs +++ b/crates/ui-egui/src/dialogs/preset_manager.rs @@ -183,6 +183,23 @@ pub(crate) fn import( 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); diff --git a/crates/ui-egui/src/dialogs/preview.rs b/crates/ui-egui/src/dialogs/preview.rs index 2ef2bd99e7..c65dc15f45 100644 --- a/crates/ui-egui/src/dialogs/preview.rs +++ b/crates/ui-egui/src/dialogs/preview.rs @@ -48,8 +48,8 @@ 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); @@ -61,6 +61,9 @@ impl LivePreview { { app.status(w.to_string()); } + if r.is_ok() { + crate::plugin_runs::show_notice(app, cmd, &v); + } r } 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/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 9d2ca82832..e9c0760844 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(), @@ -1577,6 +1621,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 }; @@ -1807,10 +1857,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/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/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..5713d3d27e 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,7 +415,7 @@ 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); diff --git a/crates/ui-egui/src/dialogs/save_options/tests.rs b/crates/ui-egui/src/dialogs/save_options/tests.rs index a0e5dbbd56..8227766b4a 100644 --- a/crates/ui-egui/src/dialogs/save_options/tests.rs +++ b/crates/ui-egui/src/dialogs/save_options/tests.rs @@ -247,6 +247,29 @@ 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 and its count of checked artboards are in the window's accessibility tree, and the count +/// follows the checks. +#[test] +fn legacy_ai_names_its_note_and_artboard_count_in_the_accessibility_tree() { + 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| -> Vec { + frame(app); + let ctx = app.ui_ctx.clone().unwrap(); + let out = crate::testing::part_frame(app, &ctx, egui::RawInput::default(), |app, ui| app.ui(ui)); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter_map(|(_, node)| node.label()).map(str::to_owned).collect() + }; + let shown = labels(&mut app); + 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); + assert!(shown.iter().any(|l| l == "1 of 2 artboards") && !shown.iter().any(|l| l == "2 of 2 artboards"), "{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/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 571d0b4489..f41ee64794 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -1015,3 +1015,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/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..7e15614537 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -32,16 +32,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 +67,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 +86,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 +362,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); } @@ -473,7 +487,7 @@ pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> 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| app.run("script.run", 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); } } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 273853c045..1eeec2d52d 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -429,6 +429,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_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..90af85ee0c 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -147,6 +147,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 +227,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..8a73810d89 100644 --- a/crates/ui-egui/src/dialogs/tests_screens.rs +++ b/crates/ui-egui/src/dialogs/tests_screens.rs @@ -837,18 +837,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 +1436,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_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 8f1d65807f..577ece6fb1 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -13,7 +13,7 @@ use craft::ui::canvas::Canvas; use craft::ui::canvas::{CanvasSpace, canvas_space}; use craft::ui::canvas_controls::SelectionOutline; use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; -use craft::ui::display::Picture; +use craft::ui::display::{Picture, Text}; use craft::ui::layout_components::Row; use craft::ui::list::ThumbAspect; use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamKind}; @@ -315,7 +315,7 @@ fn navigator(count: usize, seen: Vec) -> 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/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