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/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/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/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/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index 909fedd04d..b5c993a865 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -406,8 +406,10 @@ impl Document { /// 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. - pub fn transform_ruler_guides(&mut self, sel: &mut Selection, xf: Affine) { + /// 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) { @@ -431,7 +433,9 @@ impl Document { } 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. 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/engine/Cargo.toml b/crates/engine/Cargo.toml index 7e6028b045..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. diff --git a/crates/engine/src/cmd/addons/pathtools/shape.rs b/crates/engine/src/cmd/addons/pathtools/shape.rs index 6c16893aba..135c9d964e 100644 --- a/crates/engine/src/cmd/addons/pathtools/shape.rs +++ b/crates/engine/src/cmd/addons/pathtools/shape.rs @@ -33,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?, 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), 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)}", + "{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 ), diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 5ab9da102c..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; 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, 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/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/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 0c03b1ea11..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 ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 23b7a1c13f..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| { @@ -1159,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 0272bab874..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, ]; 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/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 68c681b0a5..527957f234 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -172,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) { @@ -181,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) => { @@ -231,7 +232,9 @@ fn apply_transform_moving_guides( d.edit_ruler_guide(i, |g| *g = g.moved(delta)); } } else if with_guides && !is_translation { - d.transform_ruler_guides(sel, xf); + // 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) })? 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 2859ecf1c0..525cef316a 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -330,18 +330,15 @@ pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Res /// [`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`]). -pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { +/// ([`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(); // 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)?; - if !is_translation { - doc.transform_ruler_guides(live, xf); - } - Ok(()) + Ok(if is_translation { vec![] } else { doc.transform_ruler_guides(live, xf) }) }) } diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 6f8ce2256f..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}; @@ -113,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); } @@ -377,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)); } @@ -393,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) { @@ -447,6 +486,23 @@ 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 @@ -464,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)); @@ -887,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) } @@ -1808,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); @@ -1827,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})) @@ -1860,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), 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), 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 ), @@ -1878,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, 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)", + "{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 ), @@ -1887,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 ), @@ -1905,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/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/script/dom.rs b/crates/engine/src/script/dom.rs index 39c740cb2e..9c137c96bd 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -772,6 +772,62 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer { 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 { @@ -1303,6 +1359,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result 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(); @@ -1317,7 +1374,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result Answer { 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)) @@ -2085,6 +2147,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("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")); @@ -2148,7 +2211,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("index", method(l, items_index)), ("getByName", method(l, items_by_name)), ("removeAll", method(l, items_remove_all)), - ("toString", class_text("PageItems")), + ("toString", method(l, items_to_string)), ]), Some(function(l, items_at)), )); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 66e2fdb67c..f6f2bd36f6 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1649,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)) @@ -1683,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 { @@ -2025,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; @@ -2034,6 +2042,9 @@ impl Session { Some(mut realm) => { realm.set_limits(limits); realm.set_es2015(es2015); + if es2015 { + realm.add_es2015(); + } realm } None => { @@ -2338,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()); @@ -2383,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 { @@ -2463,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()); 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/fill_area.rs b/crates/engine/src/tests/fill_area.rs index d6e82af05b..b0b511e661 100644 --- a/crates/engine/src/tests/fill_area.rs +++ b/crates/engine/src/tests/fill_area.rs @@ -232,6 +232,29 @@ fn fill_area_takes_clipped_art_only_where_its_mask_shows_it() { 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() { @@ -305,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. diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index d922be19dd..6f7fe9c581 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4644,6 +4644,47 @@ fn a_ruler_guide_rotates_with_the_selected_art() { 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/plugins.rs b/crates/engine/src/tests/plugins.rs index 0a255fb3a3..e47eb8377a 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2714,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(); @@ -2731,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:?}"); } @@ -2750,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(); @@ -2785,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 || { @@ -2800,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}"), }; @@ -3077,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()); @@ -3101,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()); @@ -3111,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(), @@ -3171,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()); @@ -3219,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); @@ -3252,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(); @@ -3285,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(); @@ -3315,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(); @@ -3331,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"); @@ -3346,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. @@ -3383,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"); @@ -3394,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(); @@ -3414,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"); @@ -3478,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()); @@ -3519,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(); @@ -3590,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(); @@ -3649,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="}"#; @@ -3781,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"); @@ -3802,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"); @@ -3891,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:?}"); } @@ -3951,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()); @@ -4195,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() } @@ -4497,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); @@ -4718,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). @@ -4880,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 @@ -5121,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(); @@ -5152,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"); @@ -5188,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"]})); @@ -5198,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] @@ -6397,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/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4e705538d9..43ee65ba46 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -680,9 +680,13 @@ fn a_listed_preset_keeps_more_rows_than_artboards() { 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"), ("l.typename", "Stale")] - { + 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}"); } @@ -1363,6 +1367,70 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { 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(); 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 0d766e238a..c12653602f 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -182,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"), diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index 933ed15874..7a28a84ec7 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -267,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] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 222657ac1c..965abf399c 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1582,7 +1582,15 @@ 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"; diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 25067f5c0e..07389dc866 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -82,8 +82,8 @@ const INSIDE: &[(&str, &str)] = &[ ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection selection= toString typename", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \ + getIsFileOpen selection selection= toString typename", ), ("DocumentPreset.", "prototype"), ( 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_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/js/src/builtins.rs b/crates/js/src/builtins.rs index 31414bb517..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(()) } @@ -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 { 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 bddab84fd6..57ec9d6680 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -268,6 +268,10 @@ pub(crate) enum Class { 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. @@ -331,7 +335,8 @@ 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::Host(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => "Object", @@ -779,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_classes.rs b/crates/js/src/host_classes.rs index 206f781ef3..d2994fb80b 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -91,6 +91,8 @@ pub(crate) struct Entry { 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 { @@ -143,7 +145,9 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { 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. + /// 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); @@ -152,6 +156,9 @@ impl Interp { if e.own.contains(k) { return Ok(true); } + if e.unavailable.contains(k) { + return Ok(false); + } class = e.parent; } Ok(false) @@ -307,7 +314,8 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { let r = fill_class(i, proto, &class); i.temp_roots.truncate(mark); let ctor = r?; - let members = class.members.iter().filter(|(_, m)| !matches!(m, HostMember::Unavailable(_))).map(|(name, _)| key(name)).collect(); + 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, @@ -315,7 +323,8 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { index: class.index, family, parent: parent_class, - own: Rc::new(members), + 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 }) diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 8213e989ae..25265086e5 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -756,6 +756,53 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() { ); } +#[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 9edea621c5..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 { @@ -354,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, @@ -625,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 @@ -676,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 { @@ -854,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()); @@ -890,13 +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. @@ -1904,16 +1940,18 @@ 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"), _ => {} } if !self.object(id)?.extensible { - // A name that an object of a host class with an indexer lacks is read with the indexer - // first, so assigning it throws what reading it throws. - if array_index(&k).is_none() + // 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)?; @@ -3247,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), @@ -4082,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")) { @@ -4094,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 25e16d2337..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; @@ -121,7 +129,9 @@ pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostIte 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. @@ -145,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, } @@ -266,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 71c42e0de0..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 }); } @@ -330,11 +359,15 @@ impl Realm { 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); @@ -345,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 }) } @@ -364,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 { @@ -385,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; @@ -400,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 @@ -483,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 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/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 17f665d58f..fa2bc204f6 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -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", "", "{}"), ( @@ -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", 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/manifest.rs b/crates/plugins/src/manifest.rs index ddbcb86582..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, @@ -519,6 +524,7 @@ impl Manifest { api: 1, permissions: None, inputs: Vec::new(), + writes: Vec::new(), context: Vec::new(), params: Vec::new(), extensions: Vec::new(), @@ -591,6 +597,7 @@ 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())); @@ -691,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`]). @@ -764,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<()> { @@ -933,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> { @@ -1419,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 4057af3eda..4b0a528703 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -82,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 @@ -295,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 @@ -332,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()); @@ -672,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()) } @@ -693,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)?); @@ -813,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), @@ -896,12 +916,12 @@ fn draws_nothing(c: char) -> bool { /// 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); } @@ -910,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() @@ -920,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), }) @@ -951,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 { @@ -1328,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(); @@ -1353,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() { @@ -1415,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 39d2d78776..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] 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/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/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/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index 9ae74c0936..c04ce6b22c 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -90,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, @@ -338,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; @@ -410,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 => { @@ -707,6 +710,24 @@ 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(); diff --git a/crates/tools/src/builder/fill_area.rs b/crates/tools/src/builder/fill_area.rs index 2ce72b15f3..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}; @@ -171,13 +172,39 @@ fn unmasked(doc: &Document, leaf: &Node, mut shape: po::Shape, masks: &mut Masks 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, -/// 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. -fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> Option { +/// 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; @@ -195,7 +222,17 @@ fn clip_to(shape: po::Shape, filled: bool, mask: &PathData, rule: FillRule) -> O 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 && path_contains(mask, rule, piece.segment(n / 2).eval(0.5)) + 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() { 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/circle.rs b/crates/tools/src/circle.rs index 37c0e33bcd..52c3de1664 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -224,6 +224,12 @@ fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods, centered 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], centered: bool, standard_anchors: bool) -> bool { @@ -573,10 +579,7 @@ impl Tool for CircleTool { 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 { 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/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 6c4f808359..ffe4d54ecd 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), diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 874146e102..1dbe830af4 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -406,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 e0bc44b304..1c6ef2dcf4 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; @@ -133,6 +134,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, } @@ -194,6 +197,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)) @@ -205,7 +213,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); } @@ -230,8 +238,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 = @@ -265,7 +277,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); 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/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/raster.rs b/crates/ui-egui/src/canvas/raster.rs index 8243444d39..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(); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4d11dc884d..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() }; @@ -1613,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] @@ -1777,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"); } @@ -1917,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"); @@ -1962,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"); @@ -5043,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(); @@ -5066,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(); @@ -5088,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(); @@ -5110,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(); @@ -5170,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)` @@ -5636,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/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 c4b6f8a5fe..04a7240cf7 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -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 diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 2c3b214c69..0d8ef2d500 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -716,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] @@ -806,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>) { @@ -2551,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/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/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/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/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/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/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index f45d77ab38..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) @@ -877,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() { 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/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 954aaac274..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)), ]); @@ -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/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index c219fe1eed..e9c0760844 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -1621,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 }; @@ -1851,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/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/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index ae13009775..2dec50814d 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -42,6 +42,7 @@ 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}; @@ -82,6 +83,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. @@ -473,7 +479,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_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index 775b3e1374..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}; 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_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index f4e4136188..5fa18d848b 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -538,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_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/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index 49308002f9..3ca925ed6a 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -391,6 +391,7 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { // Presentation Mode fits each floating window it shows to the main window: back in their // floating windows, those views fit their windows again. let presenting = presenting(app); + let restoring = !presenting && app.canvas.windows.presented.is_some(); if presenting { let is_floating = current.is_some_and(|k| floating(app, &k)); let shown = app.canvas.windows.presented.get_or_insert_default(); @@ -421,9 +422,15 @@ fn show_windows(app: &mut VectorcraftApp, ui: &mut egui::Ui) { return; } let raise = current.filter(|u| app.canvas.windows.current != Some(*u)); - app.canvas.windows.current = current; let ctx = ui.ctx().clone(); let os_windows = WindowHost::of(&ctx).viewports_available(); + if restoring && !os_windows && raise.is_some() { + // egui raises every reappearing area in this pass, preserving their old order. Repeat + // the current window's raise next frame, when the other windows no longer request it. + ctx.request_repaint(); + } else { + app.canvas.windows.current = current; + } // An OS window's place is in desktop points: the main window's own origin shifts it. let origin = if os_windows { ctx.input(|i| i.viewport().inner_rect.map(|r| r.min)).filter(|p| p.is_finite()).unwrap_or(egui::Pos2::ZERO).to_vec2() diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 5e519cf80b..99a979b982 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -417,23 +417,36 @@ fn presentation_mode_shows_the_floating_current_document_in_the_main_window() { #[test] fn a_document_made_current_in_presentation_mode_comes_to_the_front_after_it() { - let mut app = app_with(2); - let ctx = crate::testing::ui_context(); - frame(&mut app, &ctx, vec![]); - app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - frame(&mut app, &ctx, vec![]); - // Where the two windows overlap: document 1's title bar, over document 0's body. - let overlap = app.ui.floating[1].place.min + vec2(60.0, 10.0); - app.run("view.presentation", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - app.run("document.activate", json!({"index": 0})).unwrap(); - frame(&mut app, &ctx, vec![]); - app.run("view.presentation", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - frame(&mut app, &ctx, vec![]); - click(&mut app, &ctx, overlap); - assert_eq!(app.session.active_index(), Some(0), "document 0's window is in front where they overlap"); + for change_during_presentation in [false, true] { + let mut app = app_with(2); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatAllInWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + // Where the two windows overlap: document 1's title bar, over document 0's body. + let overlap = app.ui.floating[1].place.min + vec2(60.0, 10.0); + // Cover both an unchanged current document and one chosen while the windows are hidden. + if !change_during_presentation { + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + } + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + if change_during_presentation { + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + } + app.run("view.presentation", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + click(&mut app, &ctx, overlap); + assert_eq!( + app.session.active_index(), + Some(0), + "document 0's window is in front (changed during presentation: {change_during_presentation})" + ); + } } /// A stand-in for the window system of the documents' OS windows: it runs each one's frame and asks diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index cc5e2dda5a..b07e126478 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -511,7 +511,7 @@ impl StackDialog for FindFontDialog { .map_or_else(String::new, |f| format!("{} {} ({})", f["family"].as_str().unwrap_or(""), f["style"].as_str().unwrap_or(""), f["runs"])) }; let row_text = |at: usize| shown.get(at).and_then(|&i| rows.get(i)).map_or_else(String::new, |r| row_label(&r.family, &r.style)); - let out = Dialog::new(tl!("Find Font").to_string()).buttons(buttons).show(ui, |ui, _| { + let out = Dialog::new(tl!("Find Font").to_string()).buttons(buttons).close_on_enter(true).show(ui, |ui, _| { Stack::new().show(ui, |ui, _| { crate::panels::section(heading.clone()).show(ui, |ui, _| { let docs = Lines { len: count, text: &doc_text }; @@ -1463,6 +1463,28 @@ mod tests { assert_eq!(row(&app)["status"], "missing"); } + /// Enter in the field that has the focus is Done: the dialog closes, and no Find or Change runs. + #[test] + fn enter_is_done() { + let mut app = new_app(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Inter"})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let is_open = |app: &VectorcraftApp| app.dialogs().unwrap().with(|host| host.get::().is_some()); + open(&mut app); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + assert!(is_open(&app)); + assert!(ctx.memory(|m| m.focused()).is_some(), "a field of the dialog has the focus"); + let undo = app.session.active().unwrap().history.undo.len(); + let key = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![key(true)]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![key(false)]); + crate::tests::synthetic::key_frame(&mut app, &ctx, vec![]); + assert!(!is_open(&app), "Enter closes Find Font"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "Enter changes no font"); + } + /// Another document in front, and pattern editing entered and canceled, each give the list of /// the document in front as it is then. #[test] diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 87f76147b6..e17017d95b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7929,6 +7929,35 @@ variable-list-end {0}, {1} {0} i {1} @msg `inputs` lists `{shown}` twice `inputs` inclou `{shown}` dues vegades @msg `inputs` needs `api` 2 or later `inputs` requereix `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requereix el permís `doc.read` +@msg only a filter declares `writes` només un filtre declara `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` anomena un tipus d’objecte desconegut `{shown}`: feu servir type, image o symbolInstance +@msg `writes` lists `{shown}` twice `writes` inclou `{shown}` dues vegades +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` inclou `{shown}`, que `inputs` no inclou +@msg `writes` needs `api` {WRITES_API} or later `writes` requereix `api` {WRITES_API} o posterior +@msg `writes` needs the permission `doc.write` `writes` requereix el permís `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} no és text, ni una imatge ni una instància de símbol +@msg the text of type given as `truncated` can't be changed no es pot canviar el text d’un text donat com a `truncated` +@msg must be a list of at most {MAX_INPUT_RUNS} entries ha de ser una llista d’un màxim de {MAX_INPUT_RUNS} entrades +@msg type needs at least one run el text necessita almenys un tram +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes de text (límit {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paràgrafs (límit {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output més de {MAX_INPUT_TEXT_TOTAL} bytes de text en tota la sortida +@msg unknown key '{k}' clau desconeguda '{k}' +@msg must be a list of 6 numbers ha de ser una llista de 6 nombres +@msg a number is out of range (limit ±{MAX_COORD}) un nombre és fora de l’interval (límit ±{MAX_COORD}) +@msg flattens the object to a line or a point redueix l’objecte a una línia o un punt +@msg an object flattened to a line or a point can't be placed again un objecte reduït a una línia o un punt no es pot tornar a col·locar +@msg must be a number from 0 to 1 ha de ser un nombre de 0 a 1 +@msg must be the name of a symbol ha de ser el nom d’un símbol +@msg '{shown}' is not a symbol in this document '{shown}' no és un símbol d’aquest document +@msg a run must be {{"text", "style", "inline"?}} un tram ha de ser {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` conté el caràcter d’un gràfic en línia +@msg inline graphics can't be added, removed, reordered or changed els gràfics en línia no es poden afegir, eliminar, reordenar ni canviar +@msg the characters of threaded type can't be changed els caràcters del text enllaçat no es poden canviar +@msg the characters of type with ruby can't be changed els caràcters del text amb rubí no es poden canviar +@msg expected {count} paragraph styles, one per paragraph s’esperaven {count} estils de paràgraf, un per paràgraf +@msg the document has no Kinsoku set named '{shown}' el document no té cap conjunt Kinsoku anomenat '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters ha de tenir 1-{MAX_FAMILY} caràcters imprimibles Read the objects it is given, and the document's settings, artboards, layers and swatches Llegir els objectes que rep, i la configuració, els taulers, les capes i les mostres del document @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` ha de llistar seccions diferents: settings, artboards, layers o swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` és per a un filtre, o un efecte dinàmic amb `commands`, amb `api` 3 o posterior i el permís `doc.read` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 13129a99a0..2433a0b12e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7542,6 +7542,35 @@ axis Y Axis osa Y @msg `inputs` lists `{shown}` twice `inputs` uvádí `{shown}` dvakrát @msg `inputs` needs `api` 2 or later `inputs` vyžaduje `api` 2 nebo vyšší @msg `inputs` needs the permission `doc.read` `inputs` vyžaduje oprávnění `doc.read` +@msg only a filter declares `writes` `writes` deklaruje pouze filtr +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` uvádí neznámý druh objektu `{shown}`: použijte type, image nebo symbolInstance +@msg `writes` lists `{shown}` twice `writes` uvádí `{shown}` dvakrát +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` uvádí `{shown}`, který `inputs` neuvádí +@msg `writes` needs `api` {WRITES_API} or later `writes` vyžaduje `api` {WRITES_API} nebo vyšší +@msg `writes` needs the permission `doc.write` `writes` vyžaduje oprávnění `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} není text, obraz ani instance symbolu +@msg the text of type given as `truncated` can't be changed text objektu předaného jako `truncated` nelze změnit +@msg must be a list of at most {MAX_INPUT_RUNS} entries musí být seznam nejvýše {MAX_INPUT_RUNS} položek +@msg type needs at least one run text potřebuje alespoň jeden úsek +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bajtů textu (limit {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} odstavců (limit {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output více než {MAX_INPUT_TEXT_TOTAL} bajtů textu v celém výstupu +@msg unknown key '{k}' neznámý klíč '{k}' +@msg must be a list of 6 numbers musí být seznam 6 čísel +@msg a number is out of range (limit ±{MAX_COORD}) číslo je mimo rozsah (limit ±{MAX_COORD}) +@msg flattens the object to a line or a point zplošťuje objekt na čáru nebo bod +@msg an object flattened to a line or a point can't be placed again objekt zploštělý na čáru nebo bod nelze znovu umístit +@msg must be a number from 0 to 1 musí být číslo od 0 do 1 +@msg must be the name of a symbol musí být název symbolu +@msg '{shown}' is not a symbol in this document '{shown}' není symbol v tomto dokumentu +@msg a run must be {{"text", "style", "inline"?}} úsek musí být {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` obsahuje znak vložené grafiky +@msg inline graphics can't be added, removed, reordered or changed vloženou grafiku nelze přidávat, odebírat, přeřazovat ani měnit +@msg the characters of threaded type can't be changed znaky zřetězeného textu nelze změnit +@msg the characters of type with ruby can't be changed znaky textu s ruby nelze změnit +@msg expected {count} paragraph styles, one per paragraph očekáváno {count} stylů odstavců, jeden na každý odstavec +@msg the document has no Kinsoku set named '{shown}' dokument nemá sadu Kinsoku s názvem '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters musí mít 1-{MAX_FAMILY} tisknutelných znaků Read the objects it is given, and the document's settings, artboards, layers and swatches Číst objekty, které dostane, a nastavení, pracovní plochy, vrstvy a vzorky dokumentu @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` musí uvádět různé oddíly: settings, artboards, layers nebo swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` je pro filtr nebo živý efekt s `commands`, s `api` 3 nebo vyšším a s oprávněním `doc.read` diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 94df1eb83e..4fbda43ec7 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -722,6 +722,35 @@ liquify-list-end {0}, {1} {0} og {1} @msg `inputs` lists `{shown}` twice `inputs` angiver `{shown}` to gange @msg `inputs` needs `api` 2 or later `inputs` kræver `api` 2 eller nyere @msg `inputs` needs the permission `doc.read` `inputs` kræver tilladelsen `doc.read` +@msg only a filter declares `writes` kun et filter angiver `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` angiver en ukendt objekttype `{shown}`: brug type, image eller symbolInstance +@msg `writes` lists `{shown}` twice `writes` angiver `{shown}` to gange +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` angiver `{shown}`, som `inputs` ikke angiver +@msg `writes` needs `api` {WRITES_API} or later `writes` kræver `api` {WRITES_API} eller nyere +@msg `writes` needs the permission `doc.write` `writes` kræver tilladelsen `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} er hverken tekst, et billede eller en symbolforekomst +@msg the text of type given as `truncated` can't be changed teksten i et tekstobjekt givet som `truncated` kan ikke ændres +@msg must be a list of at most {MAX_INPUT_RUNS} entries skal være en liste med højst {MAX_INPUT_RUNS} elementer +@msg type needs at least one run tekst skal have mindst ét tekststykke +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte tekst (grænse {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} afsnit (grænse {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mere end {MAX_INPUT_TEXT_TOTAL} byte tekst i hele outputtet +@msg unknown key '{k}' ukendt nøgle '{k}' +@msg must be a list of 6 numbers skal være en liste med 6 tal +@msg a number is out of range (limit ±{MAX_COORD}) et tal er uden for området (grænse ±{MAX_COORD}) +@msg flattens the object to a line or a point gør objektet fladt til en linje eller et punkt +@msg an object flattened to a line or a point can't be placed again et objekt, der er gjort fladt til en linje eller et punkt, kan ikke placeres igen +@msg must be a number from 0 to 1 skal være et tal fra 0 til 1 +@msg must be the name of a symbol skal være navnet på et symbol +@msg '{shown}' is not a symbol in this document '{shown}' er ikke et symbol i dette dokument +@msg a run must be {{"text", "style", "inline"?}} et tekststykke skal være {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` indeholder tegnet for en indlejret grafik +@msg inline graphics can't be added, removed, reordered or changed indlejrede grafikker kan ikke tilføjes, fjernes, omarrangeres eller ændres +@msg the characters of threaded type can't be changed tegnene i sammenkædet tekst kan ikke ændres +@msg the characters of type with ruby can't be changed tegnene i tekst med ruby kan ikke ændres +@msg expected {count} paragraph styles, one per paragraph forventede {count} afsnitsstile, én pr. afsnit +@msg the document has no Kinsoku set named '{shown}' dokumentet har intet Kinsoku-sæt med navnet '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters skal være 1-{MAX_FAMILY} tegn, der kan udskrives Read the objects it is given, and the document's settings, artboards, layers and swatches Læse de objekter, den får, og dokumentets indstillinger, tegneflader, lag og farveprøver @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` skal angive forskellige afsnit: settings, artboards, layers eller swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` er til et filter eller en live-effekt med `commands`, ved `api` 3 eller senere og med tilladelsen `doc.read` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 0fb57437c4..7d788abf48 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7125,6 +7125,35 @@ axis Y Axis Y-Achse @msg `inputs` lists `{shown}` twice `inputs` führt `{shown}` doppelt auf @msg `inputs` needs `api` 2 or later `inputs` erfordert `api` 2 oder höher @msg `inputs` needs the permission `doc.read` `inputs` erfordert die Berechtigung `doc.read` +@msg only a filter declares `writes` nur ein Filter deklariert `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` nennt eine unbekannte Objektart `{shown}`: verwenden Sie type, image oder symbolInstance +@msg `writes` lists `{shown}` twice `writes` führt `{shown}` doppelt auf +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` führt `{shown}` auf, das `inputs` nicht aufführt +@msg `writes` needs `api` {WRITES_API} or later `writes` erfordert `api` {WRITES_API} oder höher +@msg `writes` needs the permission `doc.write` `writes` erfordert die Berechtigung `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} ist weder Text noch ein Bild noch eine Symbolinstanz +@msg the text of type given as `truncated` can't be changed der Text eines als `truncated` übergebenen Textobjekts kann nicht geändert werden +@msg must be a list of at most {MAX_INPUT_RUNS} entries muss eine Liste mit höchstens {MAX_INPUT_RUNS} Einträgen sein +@msg type needs at least one run Text braucht mindestens einen Abschnitt +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} Byte Text (Grenze {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} Absätze (Grenze {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mehr als {MAX_INPUT_TEXT_TOTAL} Byte Text in der gesamten Ausgabe +@msg unknown key '{k}' unbekannter Schlüssel '{k}' +@msg must be a list of 6 numbers muss eine Liste von 6 Zahlen sein +@msg a number is out of range (limit ±{MAX_COORD}) eine Zahl liegt außerhalb des Bereichs (Grenze ±{MAX_COORD}) +@msg flattens the object to a line or a point macht das Objekt zu einer Linie oder einem Punkt +@msg an object flattened to a line or a point can't be placed again ein zu einer Linie oder einem Punkt zusammengefallenes Objekt kann nicht neu platziert werden +@msg must be a number from 0 to 1 muss eine Zahl von 0 bis 1 sein +@msg must be the name of a symbol muss der Name eines Symbols sein +@msg '{shown}' is not a symbol in this document '{shown}' ist kein Symbol in diesem Dokument +@msg a run must be {{"text", "style", "inline"?}} ein Abschnitt muss {{"text", "style", "inline"?}} sein +@msg `text` holds the character of an inline graphic `text` enthält das Zeichen einer eingebundenen Grafik +@msg inline graphics can't be added, removed, reordered or changed eingebundene Grafiken können nicht hinzugefügt, entfernt, umgeordnet oder geändert werden +@msg the characters of threaded type can't be changed die Zeichen von verkettetem Text können nicht geändert werden +@msg the characters of type with ruby can't be changed die Zeichen von Text mit Ruby können nicht geändert werden +@msg expected {count} paragraph styles, one per paragraph {count} Absatzformate erwartet, eines pro Absatz +@msg the document has no Kinsoku set named '{shown}' das Dokument hat keinen Kinsoku-Satz namens '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters muss 1-{MAX_FAMILY} druckbare Zeichen haben Read the objects it is given, and the document's settings, artboards, layers and swatches Die Objekte lesen, die es erhält, sowie die Einstellungen, Zeichenflächen, Ebenen und Farbfelder des Dokuments @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` muss verschiedene Abschnitte aufführen: settings, artboards, layers oder swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` gilt für einen Filter oder einen Live-Effekt mit `commands`, mit `api` 3 oder höher und der Berechtigung `doc.read` diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 3bd10eceb1..2e7c180df4 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7532,6 +7532,35 @@ axis Y Axis Άξονας Y @msg `inputs` lists `{shown}` twice το `inputs` αναφέρει το `{shown}` δύο φορές @msg `inputs` needs `api` 2 or later το `inputs` απαιτεί `api` 2 ή νεότερο @msg `inputs` needs the permission `doc.read` το `inputs` απαιτεί το δικαίωμα `doc.read` +@msg only a filter declares `writes` μόνο ένα φίλτρο δηλώνει `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance το `writes` αναφέρει άγνωστο είδος αντικειμένου `{shown}`: χρησιμοποιήστε type, image ή symbolInstance +@msg `writes` lists `{shown}` twice το `writes` αναφέρει το `{shown}` δύο φορές +@msg `writes` lists `{shown}`, which `inputs` doesn't list το `writes` αναφέρει το `{shown}`, το οποίο δεν αναφέρει το `inputs` +@msg `writes` needs `api` {WRITES_API} or later το `writes` απαιτεί `api` {WRITES_API} ή νεότερο +@msg `writes` needs the permission `doc.write` το `writes` απαιτεί το δικαίωμα `doc.write` +@msg {_1} is not type, an image or a symbol instance το {_1} δεν είναι κείμενο, εικόνα ή στιγμιότυπο συμβόλου +@msg the text of type given as `truncated` can't be changed το κείμενο ενός αντικειμένου κειμένου που δόθηκε ως `truncated` δεν μπορεί να αλλάξει +@msg must be a list of at most {MAX_INPUT_RUNS} entries πρέπει να είναι λίστα με έως {MAX_INPUT_RUNS} στοιχεία +@msg type needs at least one run το κείμενο χρειάζεται τουλάχιστον ένα τμήμα +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte κειμένου (όριο {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} παράγραφοι (όριο {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output περισσότερα από {MAX_INPUT_TEXT_TOTAL} byte κειμένου σε όλη την έξοδο +@msg unknown key '{k}' άγνωστο κλειδί '{k}' +@msg must be a list of 6 numbers πρέπει να είναι λίστα 6 αριθμών +@msg a number is out of range (limit ±{MAX_COORD}) ένας αριθμός είναι εκτός εύρους (όριο ±{MAX_COORD}) +@msg flattens the object to a line or a point συμπιέζει το αντικείμενο σε γραμμή ή σημείο +@msg an object flattened to a line or a point can't be placed again ένα αντικείμενο που συμπιέστηκε σε γραμμή ή σημείο δεν μπορεί να τοποθετηθεί ξανά +@msg must be a number from 0 to 1 πρέπει να είναι αριθμός από 0 έως 1 +@msg must be the name of a symbol πρέπει να είναι το όνομα ενός συμβόλου +@msg '{shown}' is not a symbol in this document το '{shown}' δεν είναι σύμβολο σε αυτό το έγγραφο +@msg a run must be {{"text", "style", "inline"?}} ένα τμήμα πρέπει να είναι {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic το `text` περιέχει τον χαρακτήρα ενός ενσωματωμένου γραφικού +@msg inline graphics can't be added, removed, reordered or changed τα ενσωματωμένα γραφικά δεν μπορούν να προστεθούν, να αφαιρεθούν, να αναδιαταχθούν ή να αλλάξουν +@msg the characters of threaded type can't be changed οι χαρακτήρες συνδεδεμένου κειμένου δεν μπορούν να αλλάξουν +@msg the characters of type with ruby can't be changed οι χαρακτήρες κειμένου με ruby δεν μπορούν να αλλάξουν +@msg expected {count} paragraph styles, one per paragraph αναμένονταν {count} στυλ παραγράφων, ένα ανά παράγραφο +@msg the document has no Kinsoku set named '{shown}' το έγγραφο δεν έχει σύνολο Kinsoku με όνομα '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters πρέπει να έχει 1-{MAX_FAMILY} εκτυπώσιμους χαρακτήρες Read the objects it is given, and the document's settings, artboards, layers and swatches Ανάγνωση των αντικειμένων που του δίνονται, καθώς και των ρυθμίσεων, των πινάκων σχεδίασης, των επιπέδων και των δειγμάτων χρωμάτων του εγγράφου @msg `context` must list distinct sections: settings, artboards, layers or swatches το `context` πρέπει να απαριθμεί διαφορετικές ενότητες: settings, artboards, layers ή swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` το `context` ισχύει για φίλτρο ή ζωντανό εφέ με `commands`, με `api` 3 ή νεότερο και το δικαίωμα `doc.read` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 7e71c1c191..37eea18b4c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7518,6 +7518,35 @@ axis Y Axis Eje Y @msg `inputs` lists `{shown}` twice `inputs` incluye `{shown}` dos veces @msg `inputs` needs `api` 2 or later `inputs` requiere `api` 2 o posterior @msg `inputs` needs the permission `doc.read` `inputs` requiere el permiso `doc.read` +@msg only a filter declares `writes` solo un filtro declara `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` nombra un tipo de objeto desconocido `{shown}`: use type, image o symbolInstance +@msg `writes` lists `{shown}` twice `writes` incluye `{shown}` dos veces +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` incluye `{shown}`, que `inputs` no incluye +@msg `writes` needs `api` {WRITES_API} or later `writes` requiere `api` {WRITES_API} o posterior +@msg `writes` needs the permission `doc.write` `writes` requiere el permiso `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} no es texto, ni una imagen ni una instancia de símbolo +@msg the text of type given as `truncated` can't be changed no se puede cambiar el texto de un objeto de texto dado como `truncated` +@msg must be a list of at most {MAX_INPUT_RUNS} entries debe ser una lista de {MAX_INPUT_RUNS} entradas como máximo +@msg type needs at least one run el texto necesita al menos un tramo +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes de texto (límite {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} párrafos (límite {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output más de {MAX_INPUT_TEXT_TOTAL} bytes de texto en toda la salida +@msg unknown key '{k}' clave desconocida '{k}' +@msg must be a list of 6 numbers debe ser una lista de 6 números +@msg a number is out of range (limit ±{MAX_COORD}) un número está fuera de rango (límite ±{MAX_COORD}) +@msg flattens the object to a line or a point reduce el objeto a una línea o un punto +@msg an object flattened to a line or a point can't be placed again un objeto reducido a una línea o un punto no se puede volver a colocar +@msg must be a number from 0 to 1 debe ser un número de 0 a 1 +@msg must be the name of a symbol debe ser el nombre de un símbolo +@msg '{shown}' is not a symbol in this document '{shown}' no es un símbolo de este documento +@msg a run must be {{"text", "style", "inline"?}} un tramo debe ser {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` contiene el carácter de un gráfico en línea +@msg inline graphics can't be added, removed, reordered or changed los gráficos en línea no se pueden añadir, quitar, reordenar ni cambiar +@msg the characters of threaded type can't be changed los caracteres del texto enlazado no se pueden cambiar +@msg the characters of type with ruby can't be changed los caracteres del texto con ruby no se pueden cambiar +@msg expected {count} paragraph styles, one per paragraph se esperaban {count} estilos de párrafo, uno por párrafo +@msg the document has no Kinsoku set named '{shown}' el documento no tiene ningún conjunto de kinsoku llamado '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters debe tener 1-{MAX_FAMILY} caracteres imprimibles Read the objects it is given, and the document's settings, artboards, layers and swatches Leer los objetos que recibe, y los ajustes, las mesas de trabajo, las capas y las muestras del documento @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` debe enumerar secciones distintas: settings, artboards, layers o swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` es para un filtro, o un efecto dinámico con `commands`, con `api` 3 o posterior y el permiso `doc.read` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index cc6e0d2fd2..c95d681244 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7609,6 +7609,35 @@ axis Y Axis Y-akseli @msg `inputs` lists `{shown}` twice `inputs` luettelee kohteen `{shown}` kahdesti @msg `inputs` needs `api` 2 or later `inputs` edellyttää `api`-tasoa 2 tai uudempaa @msg `inputs` needs the permission `doc.read` `inputs` edellyttää käyttöoikeutta `doc.read` +@msg only a filter declares `writes` vain suodatin voi määrittää `writes`-avaimen +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` nimeää tuntemattoman objektilajin `{shown}`: käytä arvoa type, image tai symbolInstance +@msg `writes` lists `{shown}` twice `writes` luettelee kohteen `{shown}` kahdesti +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` luettelee kohteen `{shown}`, jota `inputs` ei luettele +@msg `writes` needs `api` {WRITES_API} or later `writes` edellyttää `api`-tasoa {WRITES_API} tai uudempaa +@msg `writes` needs the permission `doc.write` `writes` edellyttää käyttöoikeutta `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} ei ole teksti, kuva eikä symbolin ilmentymä +@msg the text of type given as `truncated` can't be changed `truncated`-merkinnällä annetun tekstiobjektin tekstiä ei voi muuttaa +@msg must be a list of at most {MAX_INPUT_RUNS} entries on oltava luettelo, jossa on enintään {MAX_INPUT_RUNS} kohdetta +@msg type needs at least one run tekstissä on oltava vähintään yksi tekstijakso +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} tavua tekstiä (raja {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} kappaletta (raja {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output yli {MAX_INPUT_TEXT_TOTAL} tavua tekstiä koko tulosteessa +@msg unknown key '{k}' tuntematon avain '{k}' +@msg must be a list of 6 numbers on oltava 6 luvun luettelo +@msg a number is out of range (limit ±{MAX_COORD}) luku on alueen ulkopuolella (raja ±{MAX_COORD}) +@msg flattens the object to a line or a point litistää objektin viivaksi tai pisteeksi +@msg an object flattened to a line or a point can't be placed again viivaksi tai pisteeksi litistynyttä objektia ei voi sijoittaa uudelleen +@msg must be a number from 0 to 1 on oltava luku väliltä 0-1 +@msg must be the name of a symbol on oltava symbolin nimi +@msg '{shown}' is not a symbol in this document '{shown}' ei ole symboli tässä dokumentissa +@msg a run must be {{"text", "style", "inline"?}} tekstijakson on oltava {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` sisältää upotetun grafiikan merkin +@msg inline graphics can't be added, removed, reordered or changed upotettuja grafiikoita ei voi lisätä, poistaa, järjestää uudelleen eikä muuttaa +@msg the characters of threaded type can't be changed ketjutetun tekstin merkkejä ei voi muuttaa +@msg the characters of type with ruby can't be changed ruby-merkintöjä sisältävän tekstin merkkejä ei voi muuttaa +@msg expected {count} paragraph styles, one per paragraph odotettiin {count} kappaletyyliä, yksi kutakin kappaletta kohden +@msg the document has no Kinsoku set named '{shown}' dokumentissa ei ole Kinsoku-joukkoa nimeltä '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters siinä on oltava 1-{MAX_FAMILY} tulostettavaa merkkiä Read the objects it is given, and the document's settings, artboards, layers and swatches Lukea sille annetut objektit sekä asiakirjan asetukset, piirtoalustat, tasot ja värimallit @msg `context` must list distinct sections: settings, artboards, layers or swatches `context`-avaimen on lueteltava eri osiot: settings, artboards, layers tai swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` on suodattimelle tai reaaliaikaiselle tehosteelle, jolla on `commands`, tasolla `api` 3 tai uudempi ja käyttöoikeudella `doc.read` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6bcf110355..efab0b71ea 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7539,6 +7539,35 @@ axis Y Axis Axe Y @msg `inputs` lists `{shown}` twice `inputs` mentionne `{shown}` deux fois @msg `inputs` needs `api` 2 or later `inputs` nécessite `api` 2 ou plus @msg `inputs` needs the permission `doc.read` `inputs` nécessite l’autorisation `doc.read` +@msg only a filter declares `writes` seul un filtre déclare `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` désigne un type d’objet inconnu `{shown}` : utilisez type, image ou symbolInstance +@msg `writes` lists `{shown}` twice `writes` mentionne `{shown}` deux fois +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` mentionne `{shown}`, que `inputs` ne mentionne pas +@msg `writes` needs `api` {WRITES_API} or later `writes` nécessite `api` {WRITES_API} ou plus +@msg `writes` needs the permission `doc.write` `writes` nécessite l’autorisation `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} n’est ni du texte, ni une image, ni une instance de symbole +@msg the text of type given as `truncated` can't be changed le texte d’un objet texte fourni comme `truncated` ne peut pas être modifié +@msg must be a list of at most {MAX_INPUT_RUNS} entries doit être une liste d’au plus {MAX_INPUT_RUNS} entrées +@msg type needs at least one run le texte doit compter au moins un segment +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} octets de texte (limite {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paragraphes (limite {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output plus de {MAX_INPUT_TEXT_TOTAL} octets de texte sur l’ensemble de la sortie +@msg unknown key '{k}' clé inconnue '{k}' +@msg must be a list of 6 numbers doit être une liste de 6 nombres +@msg a number is out of range (limit ±{MAX_COORD}) un nombre est hors limites (limite ±{MAX_COORD}) +@msg flattens the object to a line or a point réduit l’objet à une ligne ou à un point +@msg an object flattened to a line or a point can't be placed again un objet réduit à une ligne ou à un point ne peut pas être replacé +@msg must be a number from 0 to 1 doit être un nombre de 0 à 1 +@msg must be the name of a symbol doit être le nom d’un symbole +@msg '{shown}' is not a symbol in this document '{shown}' n’est pas un symbole de ce document +@msg a run must be {{"text", "style", "inline"?}} un segment doit être {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` contient le caractère d’un graphique incorporé +@msg inline graphics can't be added, removed, reordered or changed les graphiques incorporés ne peuvent pas être ajoutés, supprimés, réordonnés ni modifiés +@msg the characters of threaded type can't be changed les caractères d’un texte lié ne peuvent pas être modifiés +@msg the characters of type with ruby can't be changed les caractères d’un texte avec ruby ne peuvent pas être modifiés +@msg expected {count} paragraph styles, one per paragraph {count} styles de paragraphe attendus, un par paragraphe +@msg the document has no Kinsoku set named '{shown}' le document n’a aucun jeu de kinsoku nommé '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters doit compter 1-{MAX_FAMILY} caractères imprimables Read the objects it is given, and the document's settings, artboards, layers and swatches Lire les objets qui lui sont transmis, ainsi que les paramètres, les plans de travail, les calques et les nuances du document @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` doit lister des sections distinctes parmi settings, artboards, layers et swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` est réservé à un filtre, ou à un effet dynamique avec `commands`, avec `api` 3 ou plus et l’autorisation `doc.read` diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 986e007efc..082e4c8e03 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6702,6 +6702,35 @@ arrowhead Feather पंख @msg `inputs` lists `{shown}` twice `inputs` में `{shown}` दो बार सूचीबद्ध है @msg `inputs` needs `api` 2 or later `inputs` के लिए `api` 2 या बाद का स्तर आवश्यक है @msg `inputs` needs the permission `doc.read` `inputs` के लिए अनुमति `doc.read` आवश्यक है +@msg only a filter declares `writes` केवल फ़िल्टर `writes` घोषित करता है +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` में अज्ञात ऑब्जेक्ट प्रकार `{shown}` है: type, image या symbolInstance का उपयोग करें +@msg `writes` lists `{shown}` twice `writes` में `{shown}` दो बार सूचीबद्ध है +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` में `{shown}` सूचीबद्ध है, जो `inputs` में सूचीबद्ध नहीं है +@msg `writes` needs `api` {WRITES_API} or later `writes` के लिए `api` {WRITES_API} या बाद का स्तर आवश्यक है +@msg `writes` needs the permission `doc.write` `writes` के लिए अनुमति `doc.write` आवश्यक है +@msg {_1} is not type, an image or a symbol instance {_1} न टेक्स्ट है, न इमेज, न सिंबल इंस्टेंस +@msg the text of type given as `truncated` can't be changed `truncated` के रूप में दिए गए टेक्स्ट ऑब्जेक्ट का टेक्स्ट बदला नहीं जा सकता +@msg must be a list of at most {MAX_INPUT_RUNS} entries अधिकतम {MAX_INPUT_RUNS} प्रविष्टियों की सूची होनी चाहिए +@msg type needs at least one run टेक्स्ट में कम से कम एक रन होना चाहिए +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) टेक्स्ट के {bytes} बाइट (सीमा {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} अनुच्छेद (सीमा {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output पूरे आउटपुट में {MAX_INPUT_TEXT_TOTAL} बाइट से अधिक टेक्स्ट +@msg unknown key '{k}' अज्ञात कुंजी '{k}' +@msg must be a list of 6 numbers 6 संख्याओं की सूची होनी चाहिए +@msg a number is out of range (limit ±{MAX_COORD}) एक संख्या सीमा से बाहर है (सीमा ±{MAX_COORD}) +@msg flattens the object to a line or a point ऑब्जेक्ट को एक रेखा या बिंदु में चपटा कर देता है +@msg an object flattened to a line or a point can't be placed again रेखा या बिंदु में चपटे हुए ऑब्जेक्ट को फिर से रखा नहीं जा सकता +@msg must be a number from 0 to 1 0 से 1 तक की संख्या होनी चाहिए +@msg must be the name of a symbol किसी सिंबल का नाम होना चाहिए +@msg '{shown}' is not a symbol in this document '{shown}' इस दस्तावेज़ में कोई सिंबल नहीं है +@msg a run must be {{"text", "style", "inline"?}} रन {{"text", "style", "inline"?}} होना चाहिए +@msg `text` holds the character of an inline graphic `text` में इनलाइन ग्राफ़िक का वर्ण है +@msg inline graphics can't be added, removed, reordered or changed इनलाइन ग्राफ़िक जोड़े, हटाए, पुनः क्रमित या बदले नहीं जा सकते +@msg the characters of threaded type can't be changed थ्रेडेड टेक्स्ट के वर्ण बदले नहीं जा सकते +@msg the characters of type with ruby can't be changed रूबी वाले टेक्स्ट के वर्ण बदले नहीं जा सकते +@msg expected {count} paragraph styles, one per paragraph {count} पैराग्राफ़ स्टाइल अपेक्षित थे, हर पैराग्राफ़ के लिए एक +@msg the document has no Kinsoku set named '{shown}' दस्तावेज़ में '{shown}' नाम का कोई किनसोकू सेट नहीं है +@msg must be 1-{MAX_FAMILY} printable characters 1-{MAX_FAMILY} प्रिंट करने योग्य वर्ण होने चाहिए Read the objects it is given, and the document's settings, artboards, layers and swatches उसे दिए गए ऑब्जेक्ट्स, और डॉक्यूमेंट की सेटिंग्स, आर्टबोर्ड्स, लेयर्स और स्वॉचेस पढ़ना @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` में अलग-अलग सेक्शन होने चाहिए: settings, artboards, layers या swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` केवल फ़िल्टर, या `commands` वाले लाइव इफ़ेक्ट के लिए है, `api` 3 या उसके बाद और अनुमति `doc.read` के साथ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index ec8a60deaf..669e5723c9 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7527,6 +7527,35 @@ axis Y Axis Y tengely @msg `inputs` lists `{shown}` twice az `inputs` kétszer sorolja fel ezt: `{shown}` @msg `inputs` needs `api` 2 or later az `inputs` használatához `api` 2 vagy újabb szükséges @msg `inputs` needs the permission `doc.read` az `inputs` használatához a(z) `doc.read` engedély szükséges +@msg only a filter declares `writes` `writes` kulcsot csak szűrő adhat meg +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance a `writes` ismeretlen objektumfajtát nevez meg: `{shown}`; használja a type, image vagy symbolInstance értéket +@msg `writes` lists `{shown}` twice a `writes` kétszer sorolja fel ezt: `{shown}` +@msg `writes` lists `{shown}`, which `inputs` doesn't list a `writes` felsorolja ezt: `{shown}`, de az `inputs` nem sorolja fel +@msg `writes` needs `api` {WRITES_API} or later a `writes` használatához `api` {WRITES_API} vagy újabb szükséges +@msg `writes` needs the permission `doc.write` a `writes` használatához a(z) `doc.write` engedély szükséges +@msg {_1} is not type, an image or a symbol instance {_1} nem szöveg, nem kép és nem szimbólumpéldány +@msg the text of type given as `truncated` can't be changed a `truncated` jelöléssel átadott szövegobjektum szövege nem módosítható +@msg must be a list of at most {MAX_INPUT_RUNS} entries legfeljebb {MAX_INPUT_RUNS} elemű lista legyen +@msg type needs at least one run a szövegnek legalább egy szakaszra van szüksége +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bájt szöveg (korlát: {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} bekezdés (korlát: {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output több mint {MAX_INPUT_TEXT_TOTAL} bájt szöveg a teljes kimenetben +@msg unknown key '{k}' ismeretlen kulcs: '{k}' +@msg must be a list of 6 numbers 6 számból álló lista legyen +@msg a number is out of range (limit ±{MAX_COORD}) egy szám a tartományon kívül esik (korlát: ±{MAX_COORD}) +@msg flattens the object to a line or a point vonallá vagy ponttá lapítja az objektumot +@msg an object flattened to a line or a point can't be placed again a vonallá vagy ponttá lapított objektum nem helyezhető el újra +@msg must be a number from 0 to 1 0 és 1 közötti szám legyen +@msg must be the name of a symbol egy szimbólum neve legyen +@msg '{shown}' is not a symbol in this document '{shown}' nem szimbólum ebben a dokumentumban +@msg a run must be {{"text", "style", "inline"?}} egy szakasz formája {{"text", "style", "inline"?}} legyen +@msg `text` holds the character of an inline graphic a `text` egy szövegközi grafika karakterét tartalmazza +@msg inline graphics can't be added, removed, reordered or changed szövegközi grafikák nem adhatók hozzá, nem távolíthatók el, nem rendezhetők át és nem módosíthatók +@msg the characters of threaded type can't be changed a láncolt szöveg karakterei nem módosíthatók +@msg the characters of type with ruby can't be changed a rubyt tartalmazó szöveg karakterei nem módosíthatók +@msg expected {count} paragraph styles, one per paragraph {count} bekezdésstílus volt várható, bekezdésenként egy +@msg the document has no Kinsoku set named '{shown}' a dokumentumban nincs '{shown}' nevű Kinsoku-készlet +@msg must be 1-{MAX_FAMILY} printable characters 1-{MAX_FAMILY} nyomtatható karakter legyen Read the objects it is given, and the document's settings, artboards, layers and swatches Olvashatja a kapott objektumokat, valamint a dokumentum beállításait, rajztábláit, rétegeit és színmintáit @msg `context` must list distinct sections: settings, artboards, layers or swatches a `context` csak különböző szakaszokat sorolhat fel: settings, artboards, layers vagy swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` a `context` szűrőhöz vagy `commands` kulccsal rendelkező élő effektushoz való, `api` 3 vagy újabb mellett, a(z) `doc.read` engedéllyel diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 3b3069e023..725ef12327 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -604,6 +604,35 @@ @msg `inputs` lists `{shown}` twice `inputs` mencantumkan `{shown}` dua kali @msg `inputs` needs `api` 2 or later `inputs` memerlukan `api` 2 atau lebih baru @msg `inputs` needs the permission `doc.read` `inputs` memerlukan izin `doc.read` +@msg only a filter declares `writes` hanya filter yang mendeklarasikan `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` menyebut jenis objek yang tidak dikenal `{shown}`: gunakan type, image atau symbolInstance +@msg `writes` lists `{shown}` twice `writes` mencantumkan `{shown}` dua kali +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` mencantumkan `{shown}`, yang tidak dicantumkan `inputs` +@msg `writes` needs `api` {WRITES_API} or later `writes` memerlukan `api` {WRITES_API} atau lebih baru +@msg `writes` needs the permission `doc.write` `writes` memerlukan izin `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} bukan teks, gambar, atau instans simbol +@msg the text of type given as `truncated` can't be changed teks dari objek teks yang diberikan sebagai `truncated` tidak dapat diubah +@msg must be a list of at most {MAX_INPUT_RUNS} entries harus berupa daftar berisi paling banyak {MAX_INPUT_RUNS} entri +@msg type needs at least one run teks memerlukan setidaknya satu potongan +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte teks (batas {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paragraf (batas {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output lebih dari {MAX_INPUT_TEXT_TOTAL} byte teks di seluruh keluaran +@msg unknown key '{k}' kunci tidak dikenal '{k}' +@msg must be a list of 6 numbers harus berupa daftar 6 angka +@msg a number is out of range (limit ±{MAX_COORD}) sebuah angka di luar rentang (batas ±{MAX_COORD}) +@msg flattens the object to a line or a point memipihkan objek menjadi garis atau titik +@msg an object flattened to a line or a point can't be placed again objek yang dipipihkan menjadi garis atau titik tidak dapat ditempatkan lagi +@msg must be a number from 0 to 1 harus berupa angka dari 0 sampai 1 +@msg must be the name of a symbol harus berupa nama simbol +@msg '{shown}' is not a symbol in this document '{shown}' bukan simbol di dokumen ini +@msg a run must be {{"text", "style", "inline"?}} potongan harus berupa {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` berisi karakter grafik sebaris +@msg inline graphics can't be added, removed, reordered or changed grafik sebaris tidak dapat ditambahkan, dihapus, diurutkan ulang, atau diubah +@msg the characters of threaded type can't be changed karakter teks beruntun tidak dapat diubah +@msg the characters of type with ruby can't be changed karakter teks dengan ruby tidak dapat diubah +@msg expected {count} paragraph styles, one per paragraph diharapkan {count} gaya paragraf, satu per paragraf +@msg the document has no Kinsoku set named '{shown}' dokumen tidak memiliki set Kinsoku bernama '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters harus berupa 1-{MAX_FAMILY} karakter yang dapat dicetak Read the objects it is given, and the document's settings, artboards, layers and swatches Membaca objek yang diberikan kepadanya, serta pengaturan, artboard, lapisan, dan sampel warna dokumen @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` harus mencantumkan bagian yang berbeda: settings, artboards, layers, atau swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` untuk filter, atau efek langsung dengan `commands`, pada `api` 3 atau lebih baru dengan izin `doc.read` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8e7959999c..d00eb9be50 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7164,6 +7164,35 @@ axis Y Axis Asse Y @msg `inputs` lists `{shown}` twice `inputs` elenca `{shown}` due volte @msg `inputs` needs `api` 2 or later `inputs` richiede `api` 2 o successivo @msg `inputs` needs the permission `doc.read` `inputs` richiede l’autorizzazione `doc.read` +@msg only a filter declares `writes` solo un filtro dichiara `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` indica un tipo di oggetto sconosciuto `{shown}`: usa type, image o symbolInstance +@msg `writes` lists `{shown}` twice `writes` elenca `{shown}` due volte +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` elenca `{shown}`, che `inputs` non elenca +@msg `writes` needs `api` {WRITES_API} or later `writes` richiede `api` {WRITES_API} o successivo +@msg `writes` needs the permission `doc.write` `writes` richiede l’autorizzazione `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} non è testo, né un’immagine né un’istanza di simbolo +@msg the text of type given as `truncated` can't be changed il testo di un oggetto di testo fornito come `truncated` non può essere modificato +@msg must be a list of at most {MAX_INPUT_RUNS} entries deve essere un elenco di al massimo {MAX_INPUT_RUNS} voci +@msg type needs at least one run il testo richiede almeno un segmento +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte di testo (limite {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paragrafi (limite {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output più di {MAX_INPUT_TEXT_TOTAL} byte di testo nell’intero output +@msg unknown key '{k}' chiave sconosciuta '{k}' +@msg must be a list of 6 numbers deve essere un elenco di 6 numeri +@msg a number is out of range (limit ±{MAX_COORD}) un numero è fuori intervallo (limite ±{MAX_COORD}) +@msg flattens the object to a line or a point riduce l’oggetto a una linea o a un punto +@msg an object flattened to a line or a point can't be placed again un oggetto ridotto a una linea o a un punto non può essere ricollocato +@msg must be a number from 0 to 1 deve essere un numero da 0 a 1 +@msg must be the name of a symbol deve essere il nome di un simbolo +@msg '{shown}' is not a symbol in this document '{shown}' non è un simbolo di questo documento +@msg a run must be {{"text", "style", "inline"?}} un segmento deve essere {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` contiene il carattere di una grafica in linea +@msg inline graphics can't be added, removed, reordered or changed le grafiche in linea non possono essere aggiunte, rimosse, riordinate o modificate +@msg the characters of threaded type can't be changed i caratteri del testo concatenato non possono essere modificati +@msg the characters of type with ruby can't be changed i caratteri del testo con ruby non possono essere modificati +@msg expected {count} paragraph styles, one per paragraph attesi {count} stili paragrafo, uno per paragrafo +@msg the document has no Kinsoku set named '{shown}' il documento non ha alcun set kinsoku denominato '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters deve avere 1-{MAX_FAMILY} caratteri stampabili Read the objects it is given, and the document's settings, artboards, layers and swatches Leggere gli oggetti che riceve, e le impostazioni, le tavole da disegno, i livelli e i campioni del documento @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` deve elencare sezioni distinte: settings, artboards, layers o swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` vale per un filtro, o un effetto dinamico con `commands`, con `api` 3 o successiva e l’autorizzazione `doc.read` diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d14fc0f723..8dba701981 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7239,6 +7239,35 @@ axis Y Axis Y 軸 @msg `inputs` lists `{shown}` twice `inputs` に `{shown}` が 2 回指定されています @msg `inputs` needs `api` 2 or later `inputs` には `api` 2 以上が必要です @msg `inputs` needs the permission `doc.read` `inputs` には権限 `doc.read` が必要です +@msg only a filter declares `writes` `writes` を宣言できるのはフィルターだけです +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` に不明なオブジェクトの種類 `{shown}` があります。type、image、symbolInstance のいずれかを使ってください +@msg `writes` lists `{shown}` twice `writes` に `{shown}` が 2 回指定されています +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` に指定された `{shown}` は `inputs` に指定されていません +@msg `writes` needs `api` {WRITES_API} or later `writes` には `api` {WRITES_API} 以上が必要です +@msg `writes` needs the permission `doc.write` `writes` には権限 `doc.write` が必要です +@msg {_1} is not type, an image or a symbol instance {_1} はテキスト、画像、シンボルインスタンスのいずれでもありません +@msg the text of type given as `truncated` can't be changed `truncated` として渡されたテキストの文字列は変更できません +@msg must be a list of at most {MAX_INPUT_RUNS} entries {MAX_INPUT_RUNS} 項目以下のリストにしてください +@msg type needs at least one run テキストには 1 つ以上のランが必要です +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) テキストが {bytes} バイトあります (上限 {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) 段落が {paragraphs} 個あります (上限 {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 出力全体のテキストが {MAX_INPUT_TEXT_TOTAL} バイトを超えています +@msg unknown key '{k}' 不明なキー '{k}' +@msg must be a list of 6 numbers 6 つの数値のリストにしてください +@msg a number is out of range (limit ±{MAX_COORD}) 数値が範囲外です (上限 ±{MAX_COORD}) +@msg flattens the object to a line or a point オブジェクトが線または点につぶれます +@msg an object flattened to a line or a point can't be placed again 線または点につぶれたオブジェクトは配置し直せません +@msg must be a number from 0 to 1 0 から 1 までの数値にしてください +@msg must be the name of a symbol シンボルの名前にしてください +@msg '{shown}' is not a symbol in this document '{shown}' はこのドキュメントのシンボルではありません +@msg a run must be {{"text", "style", "inline"?}} ランは {{"text", "style", "inline"?}} にしてください +@msg `text` holds the character of an inline graphic `text` にインライングラフィックの文字が含まれています +@msg inline graphics can't be added, removed, reordered or changed インライングラフィックは追加、削除、並べ替え、変更できません +@msg the characters of threaded type can't be changed スレッドテキストの文字は変更できません +@msg the characters of type with ruby can't be changed ルビのあるテキストの文字は変更できません +@msg expected {count} paragraph styles, one per paragraph 段落スタイルは段落ごとに 1 つ、計 {count} 個必要です +@msg the document has no Kinsoku set named '{shown}' ドキュメントに '{shown}' という名前の禁則処理セットはありません +@msg must be 1-{MAX_FAMILY} printable characters 印刷可能な 1-{MAX_FAMILY} 文字にしてください Read the objects it is given, and the document's settings, artboards, layers and swatches 渡されたオブジェクトと、ドキュメントの設定、アートボード、レイヤー、スウォッチの読み取り @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` には重複しないセクションを指定してください: settings、artboards、layers、swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` は、`api` 3 以降で権限 `doc.read` を持つフィルターまたは `commands` のあるライブ効果専用です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 1991d156eb..0a29222b28 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9647,6 +9647,35 @@ axis Y Axis Y ღერძი @msg `inputs` lists `{shown}` twice `inputs`-ში `{shown}` ორჯერაა ჩამოთვლილი @msg `inputs` needs `api` 2 or later `inputs`-ს სჭირდება `api` 2 ან უფრო ახალი @msg `inputs` needs the permission `doc.read` `inputs`-ს სჭირდება ნებართვა `doc.read` +@msg only a filter declares `writes` `writes`-ის გამოცხადება მხოლოდ ფილტრს შეუძლია +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` უცნობ ობიექტის სახეობას ასახელებს `{shown}`: გამოიყენეთ type, image ან symbolInstance +@msg `writes` lists `{shown}` twice `writes`-ში `{shown}` ორჯერაა ჩამოთვლილი +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes`-ში ჩამოთვლილია `{shown}`, რომელიც `inputs`-ში არ არის ჩამოთვლილი +@msg `writes` needs `api` {WRITES_API} or later `writes`-ს სჭირდება `api` {WRITES_API} ან უფრო ახალი +@msg `writes` needs the permission `doc.write` `writes`-ს სჭირდება ნებართვა `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} არც ტექსტია, არც გამოსახულება და არც სიმბოლოს ეგზემპლარი +@msg the text of type given as `truncated` can't be changed `truncated`-ად გადაცემული ტექსტური ობიექტის ტექსტის შეცვლა შეუძლებელია +@msg must be a list of at most {MAX_INPUT_RUNS} entries უნდა იყოს სია მაქსიმუმ {MAX_INPUT_RUNS} ჩანაწერით +@msg type needs at least one run ტექსტს სჭირდება მინიმუმ ერთი მონაკვეთი +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) ტექსტის {bytes} ბაიტი (ლიმიტი {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} აბზაცი (ლიმიტი {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output მთელ გამონატანში {MAX_INPUT_TEXT_TOTAL} ბაიტზე მეტი ტექსტია +@msg unknown key '{k}' უცნობი გასაღები '{k}' +@msg must be a list of 6 numbers უნდა იყოს 6 რიცხვის სია +@msg a number is out of range (limit ±{MAX_COORD}) რიცხვი დიაპაზონს გარეთაა (ლიმიტი ±{MAX_COORD}) +@msg flattens the object to a line or a point ობიექტს ხაზად ან წერტილად აბრტყელებს +@msg an object flattened to a line or a point can't be placed again ხაზად ან წერტილად გაბრტყელებული ობიექტის ხელახლა განთავსება შეუძლებელია +@msg must be a number from 0 to 1 უნდა იყოს რიცხვი 0-დან 1-მდე +@msg must be the name of a symbol უნდა იყოს სიმბოლოს სახელი +@msg '{shown}' is not a symbol in this document '{shown}' ამ დოკუმენტში სიმბოლო არ არის +@msg a run must be {{"text", "style", "inline"?}} მონაკვეთი უნდა იყოს {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` შეიცავს ტექსტში ჩასმული გრაფიკის სიმბოლოს +@msg inline graphics can't be added, removed, reordered or changed ტექსტში ჩასმული გრაფიკის დამატება, წაშლა, გადალაგება ან შეცვლა შეუძლებელია +@msg the characters of threaded type can't be changed დაკავშირებული ტექსტის სიმბოლოების შეცვლა შეუძლებელია +@msg the characters of type with ruby can't be changed რუბის მქონე ტექსტის სიმბოლოების შეცვლა შეუძლებელია +@msg expected {count} paragraph styles, one per paragraph მოსალოდნელი იყო აბზაცის {count} სტილი, თითო აბზაცზე ერთი +@msg the document has no Kinsoku set named '{shown}' დოკუმენტს არ აქვს Kinsoku-ის ნაკრები სახელით '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters უნდა შედგებოდეს 1-{MAX_FAMILY} დასაბეჭდი სიმბოლოსგან Read the objects it is given, and the document's settings, artboards, layers and swatches მიღებული ობიექტების და დოკუმენტის პარამეტრების, სამუშაო დაფების, შრეებისა და ფერის ნიმუშების წაკითხვა @msg `context` must list distinct sections: settings, artboards, layers or swatches `context`-ში განსხვავებული სექციები უნდა იყოს: settings, artboards, layers ან swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` განკუთვნილია ფილტრისთვის ან `commands`-ის მქონე ცოცხალი ეფექტისთვის, `api` 3-ზე ან უფრო ახალზე, ნებართვით `doc.read` diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 005f8284ea..78dc8d7b97 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7136,6 +7136,35 @@ axis Y Axis Y축 @msg `inputs` lists `{shown}` twice `inputs`에 `{shown}`이(가) 두 번 나열되어 있습니다 @msg `inputs` needs `api` 2 or later `inputs`에는 `api` 2 이상이 필요합니다 @msg `inputs` needs the permission `doc.read` `inputs`에는 `doc.read` 권한이 필요합니다 +@msg only a filter declares `writes` 필터만 `writes`를 선언할 수 있습니다 +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes`에 알 수 없는 개체 종류 `{shown}`이(가) 있습니다. type, image 또는 symbolInstance를 사용하세요 +@msg `writes` lists `{shown}` twice `writes`에 `{shown}`이(가) 두 번 나열되어 있습니다 +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes`에 나열된 `{shown}`이(가) `inputs`에는 없습니다 +@msg `writes` needs `api` {WRITES_API} or later `writes`에는 `api` {WRITES_API} 이상이 필요합니다 +@msg `writes` needs the permission `doc.write` `writes`에는 `doc.write` 권한이 필요합니다 +@msg {_1} is not type, an image or a symbol instance {_1}은(는) 문자, 이미지, 심볼 인스턴스가 아닙니다 +@msg the text of type given as `truncated` can't be changed `truncated`로 전달된 문자 개체의 텍스트는 변경할 수 없습니다 +@msg must be a list of at most {MAX_INPUT_RUNS} entries 항목이 최대 {MAX_INPUT_RUNS}개인 목록이어야 합니다 +@msg type needs at least one run 문자에는 런이 하나 이상 있어야 합니다 +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) 텍스트 {bytes}바이트(한도 {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) 단락 {paragraphs}개(한도 {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 출력 전체의 텍스트가 {MAX_INPUT_TEXT_TOTAL}바이트를 넘습니다 +@msg unknown key '{k}' 알 수 없는 키 '{k}' +@msg must be a list of 6 numbers 숫자 6개의 목록이어야 합니다 +@msg a number is out of range (limit ±{MAX_COORD}) 숫자가 범위를 벗어났습니다(한도 ±{MAX_COORD}) +@msg flattens the object to a line or a point 개체를 선이나 점으로 납작하게 만듭니다 +@msg an object flattened to a line or a point can't be placed again 선이나 점으로 납작해진 개체는 다시 배치할 수 없습니다 +@msg must be a number from 0 to 1 0에서 1 사이의 숫자여야 합니다 +@msg must be the name of a symbol 심볼 이름이어야 합니다 +@msg '{shown}' is not a symbol in this document '{shown}'은(는) 이 문서의 심볼이 아닙니다 +@msg a run must be {{"text", "style", "inline"?}} 런은 {{"text", "style", "inline"?}} 형식이어야 합니다 +@msg `text` holds the character of an inline graphic `text`에 인라인 그래픽 문자가 들어 있습니다 +@msg inline graphics can't be added, removed, reordered or changed 인라인 그래픽은 추가, 제거, 순서 변경, 수정할 수 없습니다 +@msg the characters of threaded type can't be changed 연결된 문자의 글자는 변경할 수 없습니다 +@msg the characters of type with ruby can't be changed 루비가 있는 문자의 글자는 변경할 수 없습니다 +@msg expected {count} paragraph styles, one per paragraph 단락마다 하나씩 단락 스타일 {count}개가 필요합니다 +@msg the document has no Kinsoku set named '{shown}' 문서에 '{shown}'(이)라는 긴소쿠 세트가 없습니다 +@msg must be 1-{MAX_FAMILY} printable characters 인쇄 가능한 문자 1-{MAX_FAMILY}자여야 합니다 Read the objects it is given, and the document's settings, artboards, layers and swatches 전달받은 개체와 문서의 설정, 아트보드, 레이어, 견본 읽기 @msg `context` must list distinct sections: settings, artboards, layers or swatches `context`에는 서로 다른 섹션을 나열해야 합니다: settings, artboards, layers 또는 swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context`는 `api` 3 이상이고 `doc.read` 권한이 있는 필터 또는 `commands`가 있는 라이브 효과에만 쓸 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 731173eea6..bbe1681764 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -567,6 +567,35 @@ liquify-list-end {0}, {1} {0} en {1} @msg `inputs` lists `{shown}` twice `inputs` noemt `{shown}` twee keer @msg `inputs` needs `api` 2 or later `inputs` vereist `api` 2 of hoger @msg `inputs` needs the permission `doc.read` `inputs` vereist de machtiging `doc.read` +@msg only a filter declares `writes` alleen een filter declareert `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` noemt een onbekende objectsoort `{shown}`: gebruik type, image of symbolInstance +@msg `writes` lists `{shown}` twice `writes` noemt `{shown}` twee keer +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` noemt `{shown}`, dat `inputs` niet noemt +@msg `writes` needs `api` {WRITES_API} or later `writes` vereist `api` {WRITES_API} of hoger +@msg `writes` needs the permission `doc.write` `writes` vereist de machtiging `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} is geen tekst, afbeelding of symboolinstantie +@msg the text of type given as `truncated` can't be changed de tekst van een tekstobject dat als `truncated` is doorgegeven, kan niet worden gewijzigd +@msg must be a list of at most {MAX_INPUT_RUNS} entries moet een lijst van ten hoogste {MAX_INPUT_RUNS} items zijn +@msg type needs at least one run tekst heeft ten minste één tekstreeks nodig +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes tekst (limiet {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} alinea's (limiet {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output meer dan {MAX_INPUT_TEXT_TOTAL} bytes tekst in de hele uitvoer +@msg unknown key '{k}' onbekende sleutel '{k}' +@msg must be a list of 6 numbers moet een lijst van 6 getallen zijn +@msg a number is out of range (limit ±{MAX_COORD}) een getal valt buiten het bereik (limiet ±{MAX_COORD}) +@msg flattens the object to a line or a point drukt het object plat tot een lijn of een punt +@msg an object flattened to a line or a point can't be placed again een object dat tot een lijn of een punt is platgedrukt, kan niet opnieuw worden geplaatst +@msg must be a number from 0 to 1 moet een getal van 0 tot 1 zijn +@msg must be the name of a symbol moet de naam van een symbool zijn +@msg '{shown}' is not a symbol in this document '{shown}' is geen symbool in dit document +@msg a run must be {{"text", "style", "inline"?}} een tekstreeks moet {{"text", "style", "inline"?}} zijn +@msg `text` holds the character of an inline graphic `text` bevat het teken van een inline afbeelding +@msg inline graphics can't be added, removed, reordered or changed inline afbeeldingen kunnen niet worden toegevoegd, verwijderd, anders geordend of gewijzigd +@msg the characters of threaded type can't be changed de tekens van gekoppelde tekst kunnen niet worden gewijzigd +@msg the characters of type with ruby can't be changed de tekens van tekst met ruby kunnen niet worden gewijzigd +@msg expected {count} paragraph styles, one per paragraph {count} alineastijlen verwacht, één per alinea +@msg the document has no Kinsoku set named '{shown}' het document heeft geen Kinsoku-set met de naam '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters moet uit 1-{MAX_FAMILY} afdrukbare tekens bestaan Read the objects it is given, and the document's settings, artboards, layers and swatches De objecten lezen die het krijgt, en de instellingen, tekengebieden, lagen en stalen van het document @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` moet verschillende secties noemen: settings, artboards, layers of swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` is voor een filter, of een live-effect met `commands`, bij `api` 3 of later en met de machtiging `doc.read` diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 9152459071..be22f98247 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7397,6 +7397,35 @@ axis Y Axis Oś Y @msg `inputs` lists `{shown}` twice `inputs` wymienia `{shown}` dwa razy @msg `inputs` needs `api` 2 or later `inputs` wymaga `api` 2 lub nowszego @msg `inputs` needs the permission `doc.read` `inputs` wymaga uprawnienia `doc.read` +@msg only a filter declares `writes` tylko filtr deklaruje `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` wymienia nieznany rodzaj obiektu `{shown}`: użyj type, image lub symbolInstance +@msg `writes` lists `{shown}` twice `writes` wymienia `{shown}` dwa razy +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` wymienia `{shown}`, którego nie wymienia `inputs` +@msg `writes` needs `api` {WRITES_API} or later `writes` wymaga `api` {WRITES_API} lub nowszego +@msg `writes` needs the permission `doc.write` `writes` wymaga uprawnienia `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} nie jest tekstem, obrazem ani wystąpieniem symbolu +@msg the text of type given as `truncated` can't be changed nie można zmienić tekstu obiektu tekstowego przekazanego jako `truncated` +@msg must be a list of at most {MAX_INPUT_RUNS} entries musi być listą co najwyżej {MAX_INPUT_RUNS} pozycji +@msg type needs at least one run tekst potrzebuje co najmniej jednego fragmentu +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bajtów tekstu (limit {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} akapitów (limit {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output ponad {MAX_INPUT_TEXT_TOTAL} bajtów tekstu w całym wyniku +@msg unknown key '{k}' nieznany klucz '{k}' +@msg must be a list of 6 numbers musi być listą 6 liczb +@msg a number is out of range (limit ±{MAX_COORD}) liczba spoza zakresu (limit ±{MAX_COORD}) +@msg flattens the object to a line or a point spłaszcza obiekt do linii lub punktu +@msg an object flattened to a line or a point can't be placed again obiektu spłaszczonego do linii lub punktu nie można ponownie umieścić +@msg must be a number from 0 to 1 musi być liczbą od 0 do 1 +@msg must be the name of a symbol musi być nazwą symbolu +@msg '{shown}' is not a symbol in this document '{shown}' nie jest symbolem w tym dokumencie +@msg a run must be {{"text", "style", "inline"?}} fragment musi mieć postać {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` zawiera znak grafiki w wierszu +@msg inline graphics can't be added, removed, reordered or changed grafik w wierszu nie można dodawać, usuwać, zmieniać ich kolejności ani modyfikować +@msg the characters of threaded type can't be changed nie można zmienić znaków tekstu wątkowego +@msg the characters of type with ruby can't be changed nie można zmienić znaków tekstu z ruby +@msg expected {count} paragraph styles, one per paragraph oczekiwano {count} stylów akapitowych, po jednym na akapit +@msg the document has no Kinsoku set named '{shown}' dokument nie ma zestawu kinsoku o nazwie '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters musi mieć 1-{MAX_FAMILY} drukowalnych znaków Read the objects it is given, and the document's settings, artboards, layers and swatches Odczytywać obiekty, które otrzymuje, oraz ustawienia, obszary kompozycji, warstwy i próbki dokumentu @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` musi wymieniać różne sekcje: settings, artboards, layers lub swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` dotyczy filtra albo efektu na żywo z `commands`, z `api` 3 lub nowszym i z uprawnieniem `doc.read` diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b49b217c8f..a2be19bf7e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7441,6 +7441,35 @@ axis Y Axis Eixo Y @msg `inputs` lists `{shown}` twice `inputs` lista `{shown}` duas vezes @msg `inputs` needs `api` 2 or later `inputs` exige `api` 2 ou posterior @msg `inputs` needs the permission `doc.read` `inputs` exige a permissão `doc.read` +@msg only a filter declares `writes` somente um filtro declara `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` cita um tipo de objeto desconhecido `{shown}`: use type, image ou symbolInstance +@msg `writes` lists `{shown}` twice `writes` lista `{shown}` duas vezes +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` lista `{shown}`, que `inputs` não lista +@msg `writes` needs `api` {WRITES_API} or later `writes` exige `api` {WRITES_API} ou posterior +@msg `writes` needs the permission `doc.write` `writes` exige a permissão `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} não é texto, nem uma imagem, nem uma instância de símbolo +@msg the text of type given as `truncated` can't be changed o texto de um objeto de texto fornecido como `truncated` não pode ser alterado +@msg must be a list of at most {MAX_INPUT_RUNS} entries deve ser uma lista de no máximo {MAX_INPUT_RUNS} entradas +@msg type needs at least one run o texto precisa de pelo menos um trecho +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bytes de texto (limite {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} parágrafos (limite {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mais de {MAX_INPUT_TEXT_TOTAL} bytes de texto em toda a saída +@msg unknown key '{k}' chave desconhecida '{k}' +@msg must be a list of 6 numbers deve ser uma lista de 6 números +@msg a number is out of range (limit ±{MAX_COORD}) um número está fora do intervalo (limite ±{MAX_COORD}) +@msg flattens the object to a line or a point achata o objeto em uma linha ou um ponto +@msg an object flattened to a line or a point can't be placed again um objeto achatado em uma linha ou um ponto não pode ser posicionado de novo +@msg must be a number from 0 to 1 deve ser um número de 0 a 1 +@msg must be the name of a symbol deve ser o nome de um símbolo +@msg '{shown}' is not a symbol in this document '{shown}' não é um símbolo deste documento +@msg a run must be {{"text", "style", "inline"?}} um trecho deve ser {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` contém o caractere de um gráfico em linha +@msg inline graphics can't be added, removed, reordered or changed gráficos em linha não podem ser adicionados, removidos, reordenados nem alterados +@msg the characters of threaded type can't be changed os caracteres de texto encadeado não podem ser alterados +@msg the characters of type with ruby can't be changed os caracteres de texto com ruby não podem ser alterados +@msg expected {count} paragraph styles, one per paragraph eram esperados {count} estilos de parágrafo, um por parágrafo +@msg the document has no Kinsoku set named '{shown}' o documento não tem um conjunto Kinsoku chamado '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters deve ter 1-{MAX_FAMILY} caracteres imprimíveis Read the objects it is given, and the document's settings, artboards, layers and swatches Ler os objetos que recebe, e as configurações, as mesas de trabalho, as camadas e as amostras do documento @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` deve listar seções distintas: settings, artboards, layers ou swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` é para um filtro, ou um efeito dinâmico com `commands`, com `api` 3 ou posterior e a permissão `doc.read` diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index eec9216b69..e722b4e782 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7164,6 +7164,35 @@ axis Y Axis Ось Y @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано дважды @msg `inputs` needs `api` 2 or later для `inputs` нужен `api` 2 или выше @msg `inputs` needs the permission `doc.read` для `inputs` нужно разрешение `doc.read` +@msg only a filter declares `writes` `writes` может объявлять только фильтр +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance в `writes` указан неизвестный вид объекта `{shown}`: используйте type, image или symbolInstance +@msg `writes` lists `{shown}` twice в `writes` `{shown}` указано дважды +@msg `writes` lists `{shown}`, which `inputs` doesn't list в `writes` указано `{shown}`, которого нет в `inputs` +@msg `writes` needs `api` {WRITES_API} or later для `writes` нужен `api` {WRITES_API} или выше +@msg `writes` needs the permission `doc.write` для `writes` нужно разрешение `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} не является ни текстом, ни изображением, ни экземпляром символа +@msg the text of type given as `truncated` can't be changed текст текстового объекта, переданного как `truncated`, изменить нельзя +@msg must be a list of at most {MAX_INPUT_RUNS} entries должно быть списком не более чем из {MAX_INPUT_RUNS} элементов +@msg type needs at least one run у текста должен быть хотя бы один фрагмент +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} байт текста (предел {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} абзацев (предел {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output более {MAX_INPUT_TEXT_TOTAL} байт текста во всём выводе +@msg unknown key '{k}' неизвестный ключ '{k}' +@msg must be a list of 6 numbers должно быть списком из 6 чисел +@msg a number is out of range (limit ±{MAX_COORD}) число вне диапазона (предел ±{MAX_COORD}) +@msg flattens the object to a line or a point сплющивает объект в линию или точку +@msg an object flattened to a line or a point can't be placed again объект, сплющенный в линию или точку, нельзя разместить заново +@msg must be a number from 0 to 1 должно быть числом от 0 до 1 +@msg must be the name of a symbol должно быть именем символа +@msg '{shown}' is not a symbol in this document '{shown}' не является символом этого документа +@msg a run must be {{"text", "style", "inline"?}} фрагмент должен иметь вид {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` содержит символ встроенной в строку графики +@msg inline graphics can't be added, removed, reordered or changed встроенную в строку графику нельзя добавлять, удалять, переупорядочивать или изменять +@msg the characters of threaded type can't be changed знаки связанного текста изменить нельзя +@msg the characters of type with ruby can't be changed знаки текста с руби изменить нельзя +@msg expected {count} paragraph styles, one per paragraph ожидалось стилей абзацев: {count}, по одному на абзац +@msg the document has no Kinsoku set named '{shown}' в документе нет набора kinsoku с именем '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters должно содержать 1-{MAX_FAMILY} печатаемых символов Read the objects it is given, and the document's settings, artboards, layers and swatches Читать переданные ему объекты, а также параметры, монтажные области, слои и образцы документа @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` должен перечислять разные разделы: settings, artboards, layers или swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` допустим только для фильтра или динамического эффекта с `commands`, с `api` 3 или выше и с разрешением `doc.read` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index a4184199a4..2c9b16b092 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7542,6 +7542,35 @@ axis Y Axis Y-axel @msg `inputs` lists `{shown}` twice `inputs` anger `{shown}` två gånger @msg `inputs` needs `api` 2 or later `inputs` kräver `api` 2 eller senare @msg `inputs` needs the permission `doc.read` `inputs` kräver behörigheten `doc.read` +@msg only a filter declares `writes` bara ett filter anger `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` anger en okänd objekttyp `{shown}`: använd type, image eller symbolInstance +@msg `writes` lists `{shown}` twice `writes` anger `{shown}` två gånger +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` anger `{shown}`, som `inputs` inte anger +@msg `writes` needs `api` {WRITES_API} or later `writes` kräver `api` {WRITES_API} eller senare +@msg `writes` needs the permission `doc.write` `writes` kräver behörigheten `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} är varken text, en bild eller en symbolinstans +@msg the text of type given as `truncated` can't be changed texten i ett textobjekt som getts som `truncated` kan inte ändras +@msg must be a list of at most {MAX_INPUT_RUNS} entries måste vara en lista med högst {MAX_INPUT_RUNS} poster +@msg type needs at least one run text behöver minst ett textavsnitt +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte text (gräns {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} stycken (gräns {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output mer än {MAX_INPUT_TEXT_TOTAL} byte text i hela utdatan +@msg unknown key '{k}' okänd nyckel '{k}' +@msg must be a list of 6 numbers måste vara en lista med 6 tal +@msg a number is out of range (limit ±{MAX_COORD}) ett tal ligger utanför intervallet (gräns ±{MAX_COORD}) +@msg flattens the object to a line or a point plattar till objektet till en linje eller en punkt +@msg an object flattened to a line or a point can't be placed again ett objekt som plattats till en linje eller en punkt kan inte placeras igen +@msg must be a number from 0 to 1 måste vara ett tal från 0 till 1 +@msg must be the name of a symbol måste vara namnet på en symbol +@msg '{shown}' is not a symbol in this document '{shown}' är ingen symbol i det här dokumentet +@msg a run must be {{"text", "style", "inline"?}} ett textavsnitt måste vara {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` innehåller tecknet för en grafik i texten +@msg inline graphics can't be added, removed, reordered or changed grafik i texten kan inte läggas till, tas bort, ordnas om eller ändras +@msg the characters of threaded type can't be changed tecknen i länkad text kan inte ändras +@msg the characters of type with ruby can't be changed tecknen i text med ruby kan inte ändras +@msg expected {count} paragraph styles, one per paragraph {count} styckestilar förväntades, en per stycke +@msg the document has no Kinsoku set named '{shown}' dokumentet har ingen Kinsoku-uppsättning med namnet '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters måste vara 1-{MAX_FAMILY} utskrivbara tecken Read the objects it is given, and the document's settings, artboards, layers and swatches Läsa objekten den får, och dokumentets inställningar, ritytor, lager och färgrutor @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` måste ange olika avsnitt: settings, artboards, layers eller swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` gäller ett filter eller en liveeffekt med `commands`, med `api` 3 eller senare och behörigheten `doc.read` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 6f1d616aca..81accf43c5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7614,6 +7614,35 @@ axis Y Axis Y ekseni @msg `inputs` lists `{shown}` twice `inputs` `{shown}` değerini iki kez listeliyor @msg `inputs` needs `api` 2 or later `inputs` için `api` 2 veya üstü gerekir @msg `inputs` needs the permission `doc.read` `inputs` için `doc.read` izni gerekir +@msg only a filter declares `writes` `writes` yalnızca bir filtrede bildirilebilir +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` bilinmeyen bir nesne türü belirtiyor: `{shown}`; type, image veya symbolInstance kullanın +@msg `writes` lists `{shown}` twice `writes` `{shown}` değerini iki kez listeliyor +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` `{shown}` değerini listeliyor, ancak `inputs` listelemiyor +@msg `writes` needs `api` {WRITES_API} or later `writes` için `api` {WRITES_API} veya üstü gerekir +@msg `writes` needs the permission `doc.write` `writes` için `doc.write` izni gerekir +@msg {_1} is not type, an image or a symbol instance {_1} metin, görüntü veya sembol örneği değil +@msg the text of type given as `truncated` can't be changed `truncated` olarak verilen metin nesnesinin metni değiştirilemez +@msg must be a list of at most {MAX_INPUT_RUNS} entries en fazla {MAX_INPUT_RUNS} girişli bir liste olmalıdır +@msg type needs at least one run metnin en az bir parçası olmalıdır +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} bayt metin (sınır {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} paragraf (sınır {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output çıktının tamamında {MAX_INPUT_TEXT_TOTAL} bayttan fazla metin +@msg unknown key '{k}' bilinmeyen anahtar '{k}' +@msg must be a list of 6 numbers 6 sayılık bir liste olmalıdır +@msg a number is out of range (limit ±{MAX_COORD}) bir sayı aralık dışında (sınır ±{MAX_COORD}) +@msg flattens the object to a line or a point nesneyi bir çizgiye veya noktaya yassılaştırıyor +@msg an object flattened to a line or a point can't be placed again bir çizgiye veya noktaya yassılaşmış nesne yeniden yerleştirilemez +@msg must be a number from 0 to 1 0 ile 1 arasında bir sayı olmalıdır +@msg must be the name of a symbol bir sembolün adı olmalıdır +@msg '{shown}' is not a symbol in this document '{shown}' bu belgede bir sembol değil +@msg a run must be {{"text", "style", "inline"?}} bir parça {{"text", "style", "inline"?}} biçiminde olmalıdır +@msg `text` holds the character of an inline graphic `text` satır içi bir grafiğin karakterini içeriyor +@msg inline graphics can't be added, removed, reordered or changed satır içi grafikler eklenemez, kaldırılamaz, yeniden sıralanamaz veya değiştirilemez +@msg the characters of threaded type can't be changed zincirli metnin karakterleri değiştirilemez +@msg the characters of type with ruby can't be changed ruby içeren metnin karakterleri değiştirilemez +@msg expected {count} paragraph styles, one per paragraph her paragraf için bir tane olmak üzere {count} paragraf stili bekleniyordu +@msg the document has no Kinsoku set named '{shown}' belgede '{shown}' adlı Kinsoku seti yok +@msg must be 1-{MAX_FAMILY} printable characters 1-{MAX_FAMILY} yazdırılabilir karakter olmalıdır Read the objects it is given, and the document's settings, artboards, layers and swatches Kendisine verilen nesneleri ve belgenin ayarlarını, çalışma yüzeylerini, katmanlarını ve renk örneklerini okuma @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` farklı bölümleri listelemelidir: settings, artboards, layers veya swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` yalnızca `api` 3 veya sonrasında, `doc.read` izniyle bir filtre ya da `commands` içeren bir canlı efekt içindir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 89c20c44a5..e1700dbb94 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7146,6 +7146,35 @@ axis Y Axis Вісь Y @msg `inputs` lists `{shown}` twice в `inputs` `{shown}` указано двічі @msg `inputs` needs `api` 2 or later для `inputs` потрібен `api` 2 або новіший @msg `inputs` needs the permission `doc.read` для `inputs` потрібен дозвіл `doc.read` +@msg only a filter declares `writes` `writes` може оголошувати лише фільтр +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance в `writes` указано невідомий вид об’єкта `{shown}`: використовуйте type, image або symbolInstance +@msg `writes` lists `{shown}` twice в `writes` `{shown}` указано двічі +@msg `writes` lists `{shown}`, which `inputs` doesn't list в `writes` указано `{shown}`, якого немає в `inputs` +@msg `writes` needs `api` {WRITES_API} or later для `writes` потрібен `api` {WRITES_API} або новіший +@msg `writes` needs the permission `doc.write` для `writes` потрібен дозвіл `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} не є ні текстом, ні зображенням, ні екземпляром символу +@msg the text of type given as `truncated` can't be changed текст текстового об’єкта, переданого як `truncated`, змінити не можна +@msg must be a list of at most {MAX_INPUT_RUNS} entries має бути списком щонайбільше з {MAX_INPUT_RUNS} елементів +@msg type needs at least one run текст повинен мати щонайменше один фрагмент +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} байтів тексту (межа {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} абзаців (межа {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output понад {MAX_INPUT_TEXT_TOTAL} байтів тексту в усьому виводі +@msg unknown key '{k}' невідомий ключ '{k}' +@msg must be a list of 6 numbers має бути списком із 6 чисел +@msg a number is out of range (limit ±{MAX_COORD}) число поза діапазоном (межа ±{MAX_COORD}) +@msg flattens the object to a line or a point сплющує об’єкт у лінію чи точку +@msg an object flattened to a line or a point can't be placed again об’єкт, сплющений у лінію чи точку, не можна розмістити знову +@msg must be a number from 0 to 1 має бути числом від 0 до 1 +@msg must be the name of a symbol має бути назвою символу +@msg '{shown}' is not a symbol in this document '{shown}' не є символом цього документа +@msg a run must be {{"text", "style", "inline"?}} фрагмент має мати вигляд {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` містить знак вбудованої в рядок графіки +@msg inline graphics can't be added, removed, reordered or changed вбудовану в рядок графіку не можна додавати, вилучати, переставляти чи змінювати +@msg the characters of threaded type can't be changed знаки пов’язаного тексту змінити не можна +@msg the characters of type with ruby can't be changed знаки тексту з рубі змінити не можна +@msg expected {count} paragraph styles, one per paragraph очікувалося стилів абзаців: {count}, по одному на абзац +@msg the document has no Kinsoku set named '{shown}' у документі немає набору kinsoku з назвою '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters має містити 1-{MAX_FAMILY} друкованих символів Read the objects it is given, and the document's settings, artboards, layers and swatches Читати передані йому об’єкти, а також параметри, монтажні області, шари та зразки документа @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` має перелічувати різні розділи: settings, artboards, layers або swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` дозволено лише для фільтра або динамічного ефекту з `commands`, з `api` 3 або вище та з дозволом `doc.read` diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d358d49544..278a8c10e9 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7193,6 +7193,35 @@ axis Y Axis Trục Y @msg `inputs` lists `{shown}` twice `inputs` liệt kê `{shown}` hai lần @msg `inputs` needs `api` 2 or later `inputs` cần `api` 2 trở lên @msg `inputs` needs the permission `doc.read` `inputs` cần quyền `doc.read` +@msg only a filter declares `writes` chỉ bộ lọc mới khai báo `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` nêu một loại đối tượng không xác định `{shown}`: dùng type, image hoặc symbolInstance +@msg `writes` lists `{shown}` twice `writes` liệt kê `{shown}` hai lần +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` liệt kê `{shown}`, nhưng `inputs` không liệt kê +@msg `writes` needs `api` {WRITES_API} or later `writes` cần `api` {WRITES_API} trở lên +@msg `writes` needs the permission `doc.write` `writes` cần quyền `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} không phải là văn bản, hình ảnh hay thực thể ký hiệu +@msg the text of type given as `truncated` can't be changed không thể thay đổi văn bản của đối tượng văn bản được đưa vào dưới dạng `truncated` +@msg must be a list of at most {MAX_INPUT_RUNS} entries phải là danh sách có tối đa {MAX_INPUT_RUNS} mục +@msg type needs at least one run văn bản cần ít nhất một đoạn chạy +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) {bytes} byte văn bản (giới hạn {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) {paragraphs} đoạn văn (giới hạn {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output hơn {MAX_INPUT_TEXT_TOTAL} byte văn bản trên toàn bộ đầu ra +@msg unknown key '{k}' khóa không xác định '{k}' +@msg must be a list of 6 numbers phải là danh sách gồm 6 số +@msg a number is out of range (limit ±{MAX_COORD}) một số nằm ngoài phạm vi (giới hạn ±{MAX_COORD}) +@msg flattens the object to a line or a point làm dẹt đối tượng thành một đường hoặc một điểm +@msg an object flattened to a line or a point can't be placed again không thể đặt lại một đối tượng đã bị dẹt thành đường hoặc điểm +@msg must be a number from 0 to 1 phải là một số từ 0 đến 1 +@msg must be the name of a symbol phải là tên của một ký hiệu +@msg '{shown}' is not a symbol in this document '{shown}' không phải là ký hiệu trong tài liệu này +@msg a run must be {{"text", "style", "inline"?}} một đoạn chạy phải có dạng {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` chứa ký tự của một đồ họa nội dòng +@msg inline graphics can't be added, removed, reordered or changed không thể thêm, xóa, sắp xếp lại hoặc thay đổi đồ họa nội dòng +@msg the characters of threaded type can't be changed không thể thay đổi ký tự của văn bản chuỗi +@msg the characters of type with ruby can't be changed không thể thay đổi ký tự của văn bản có ruby +@msg expected {count} paragraph styles, one per paragraph cần {count} kiểu đoạn văn, mỗi đoạn một kiểu +@msg the document has no Kinsoku set named '{shown}' tài liệu không có bộ Kinsoku nào tên '{shown}' +@msg must be 1-{MAX_FAMILY} printable characters phải có 1-{MAX_FAMILY} ký tự in được Read the objects it is given, and the document's settings, artboards, layers and swatches Đọc các đối tượng được trao cho nó, cùng các thiết lập, bảng vẽ, lớp và mẫu màu của tài liệu @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` phải liệt kê các phần khác nhau: settings, artboards, layers hoặc swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` dành cho bộ lọc, hoặc hiệu ứng trực tiếp có `commands`, ở `api` 3 trở lên và có quyền `doc.read` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c48a32148a..ae265a4fc7 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7374,6 +7374,35 @@ axis Y Axis Y 轴 @msg `inputs` lists `{shown}` twice `inputs` 列出了两次 `{shown}` @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要权限 `doc.read` +@msg only a filter declares `writes` 只有滤镜才能声明 `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` 列出了未知的对象类型 `{shown}`:请使用 type、image 或 symbolInstance +@msg `writes` lists `{shown}` twice `writes` 列出了两次 `{shown}` +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` 列出了 `{shown}`,但 `inputs` 未列出它 +@msg `writes` needs `api` {WRITES_API} or later `writes` 需要 `api` {WRITES_API} 或更高 +@msg `writes` needs the permission `doc.write` `writes` 需要权限 `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} 不是文字、图像或符号实例 +@msg the text of type given as `truncated` can't be changed 作为 `truncated` 给出的文字对象的文本不能更改 +@msg must be a list of at most {MAX_INPUT_RUNS} entries 必须是最多 {MAX_INPUT_RUNS} 个条目的列表 +@msg type needs at least one run 文字至少需要一个文本段 +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) 文本 {bytes} 字节(上限 {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) 段落 {paragraphs} 个(上限 {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 整个输出中的文本超过 {MAX_INPUT_TEXT_TOTAL} 字节 +@msg unknown key '{k}' 未知键 '{k}' +@msg must be a list of 6 numbers 必须是 6 个数字的列表 +@msg a number is out of range (limit ±{MAX_COORD}) 有数字超出范围(上限 ±{MAX_COORD}) +@msg flattens the object to a line or a point 会把对象压扁成一条线或一个点 +@msg an object flattened to a line or a point can't be placed again 已压扁成线或点的对象无法重新放置 +@msg must be a number from 0 to 1 必须是 0 到 1 之间的数字 +@msg must be the name of a symbol 必须是符号的名称 +@msg '{shown}' is not a symbol in this document '{shown}' 不是此文档中的符号 +@msg a run must be {{"text", "style", "inline"?}} 文本段必须是 {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` 含有随文图形的字符 +@msg inline graphics can't be added, removed, reordered or changed 随文图形不能添加、删除、重新排序或更改 +@msg the characters of threaded type can't be changed 串接文本的字符不能更改 +@msg the characters of type with ruby can't be changed 带注音的文字的字符不能更改 +@msg expected {count} paragraph styles, one per paragraph 应有 {count} 个段落样式,每个段落一个 +@msg the document has no Kinsoku set named '{shown}' 文档中没有名为 '{shown}' 的 Kinsoku 集 +@msg must be 1-{MAX_FAMILY} printable characters 必须是 1-{MAX_FAMILY} 个可打印字符 Read the objects it is given, and the document's settings, artboards, layers and swatches 读取交给它的对象,以及文档的设置、画板、图层和色板 @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` 必须列出互不相同的部分:settings、artboards、layers 或 swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` 仅适用于 `api` 3 或更高、具有权限 `doc.read` 的滤镜或带 `commands` 的实时效果 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 58c451afd6..7d83822f05 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7195,6 +7195,35 @@ axis Y Axis Y 軸 @msg `inputs` lists `{shown}` twice `inputs` 列出了兩次 `{shown}` @msg `inputs` needs `api` 2 or later `inputs` 需要 `api` 2 或更高 @msg `inputs` needs the permission `doc.read` `inputs` 需要權限 `doc.read` +@msg only a filter declares `writes` 只有濾鏡才能宣告 `writes` +@msg `writes` names an unknown object kind `{shown}`: use type, image or symbolInstance `writes` 列出了未知的物件類型 `{shown}`:請使用 type、image 或 symbolInstance +@msg `writes` lists `{shown}` twice `writes` 列出了兩次 `{shown}` +@msg `writes` lists `{shown}`, which `inputs` doesn't list `writes` 列出了 `{shown}`,但 `inputs` 未列出它 +@msg `writes` needs `api` {WRITES_API} or later `writes` 需要 `api` {WRITES_API} 或更高 +@msg `writes` needs the permission `doc.write` `writes` 需要權限 `doc.write` +@msg {_1} is not type, an image or a symbol instance {_1} 不是文字、影像或符號範例 +@msg the text of type given as `truncated` can't be changed 以 `truncated` 提供的文字物件,其文字無法變更 +@msg must be a list of at most {MAX_INPUT_RUNS} entries 必須是最多 {MAX_INPUT_RUNS} 個項目的清單 +@msg type needs at least one run 文字至少需要一個文字段 +@msg {bytes} bytes of text (limit {MAX_INPUT_TEXT}) 文字 {bytes} 位元組(上限 {MAX_INPUT_TEXT}) +@msg {paragraphs} paragraphs (limit {MAX_INPUT_RUNS}) 段落 {paragraphs} 個(上限 {MAX_INPUT_RUNS}) +@msg more than {MAX_INPUT_TEXT_TOTAL} bytes of text over the output 整個輸出中的文字超過 {MAX_INPUT_TEXT_TOTAL} 位元組 +@msg unknown key '{k}' 未知的鍵 '{k}' +@msg must be a list of 6 numbers 必須是 6 個數字的清單 +@msg a number is out of range (limit ±{MAX_COORD}) 有數字超出範圍(上限 ±{MAX_COORD}) +@msg flattens the object to a line or a point 會把物件壓扁成一條線或一個點 +@msg an object flattened to a line or a point can't be placed again 已壓扁成線或點的物件無法重新放置 +@msg must be a number from 0 to 1 必須是 0 到 1 之間的數字 +@msg must be the name of a symbol 必須是符號的名稱 +@msg '{shown}' is not a symbol in this document '{shown}' 不是此文件中的符號 +@msg a run must be {{"text", "style", "inline"?}} 文字段必須是 {{"text", "style", "inline"?}} +@msg `text` holds the character of an inline graphic `text` 含有行內圖形的字元 +@msg inline graphics can't be added, removed, reordered or changed 行內圖形無法新增、移除、重新排序或變更 +@msg the characters of threaded type can't be changed 串連文字的字元無法變更 +@msg the characters of type with ruby can't be changed 含注音的文字,其字元無法變更 +@msg expected {count} paragraph styles, one per paragraph 應有 {count} 個段落樣式,每個段落一個 +@msg the document has no Kinsoku set named '{shown}' 文件中沒有名為 '{shown}' 的 Kinsoku 集 +@msg must be 1-{MAX_FAMILY} printable characters 必須是 1-{MAX_FAMILY} 個可列印字元 Read the objects it is given, and the document's settings, artboards, layers and swatches 讀取交給它的物件,以及文件的設定、工作區域、圖層和色票 @msg `context` must list distinct sections: settings, artboards, layers or swatches `context` 必須列出互不相同的部分:settings、artboards、layers 或 swatches @msg `context` is for a filter, or a live effect with `commands`, at `api` 3 or later with the permission `doc.read` `context` 僅適用於 `api` 3 或更高、具有權限 `doc.read` 的濾鏡或帶 `commands` 的即時效果 diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 6a6c34a5e6..30b6edfb49 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -207,6 +207,39 @@ mod tests { assert!(appearance.contains(" String { + let last = icon.rsplit(" f32 { + icon.split(r#"fill-opacity=""#).nth(1).and_then(|s| s.split('"').next()).and_then(|v| v.parse().ok()).unwrap_or(1.0) + }; + let icons = [("butt", svg("dc-cap-butt")), ("round", svg("dc-cap-round")), ("square", svg("dc-cap-square"))]; + let butt_end = end_line(&icons[0].1); + assert!(butt_end.starts_with('M') && butt_end.contains('V'), "the butt cap icon ends with a vertical end-of-path line: {butt_end}"); + for (name, icon) in &icons { + assert_eq!(end_line(icon), butt_end, "the {name} cap icon marks the end of the path where the butt cap icon does"); + assert!(stroke_opacity(icon) < 1.0, "the {name} cap icon's stroke is lighter than its end-of-path line"); + } + // The stroke bar, everything before the end-of-path line, shows each cap differently. + let bar = |icon: &str| -> String { icon.rsplit_once(" String { @@ -250,11 +251,18 @@ pub(super) fn spelling_item_label(id: &str, p: &Value) -> Option { /// The shortcut a menu item shows: its command's (items without params), a panel's for the /// Window menu's `window.panel {panel}` items, an effect's for the Effect menu's items, or a filter -/// plug-in's for Object › Plug-ins' `plugin.dialog {id}` items. +/// plug-in's for Object › Plug-ins' `plugin.dialog {id}` items. Settings' first page shows +/// Preferences' shortcut. pub fn item_shortcut(app: &VectorcraftApp, id: &str, p: &Value) -> Option { + item_shortcut_in(&command_shortcuts(app), id, p) +} + +/// [`item_shortcut`] with each entry's command looked up in `chord` ([`command_shortcuts`]). +pub(crate) fn item_shortcut_in(chord: &dyn Fn(&CommandRef) -> Option, id: &str, p: &Value) -> Option { let field = |name: &str| p.get(name).and_then(Value::as_str); let key = match (id, field("panel")) { ("window.panel", Some(panel)) => format!("panel:{panel}"), + ("edit.preferences", _) if field("category") == PREF_CATEGORIES.first().copied() => id.to_string(), ("effect.dialog" | "effect.apply", _) => format!("effect:{}", field("effect")?), ("plugin.dialog", _) => format!("plugin:{}", field("id")?), // The Artboard tool's canvas menu passes the point its Paste goes to. @@ -265,7 +273,7 @@ pub fn item_shortcut(app: &VectorcraftApp, id: &str, p: &Value) -> Option _ if p.is_null() => id.to_string(), _ => return None, }; - shortcut_of(app, &key) + chord(&crate::keymap::command_of(&key)) } /// Labels only the canvas context menu ([`context_items`]) shows, so the catalog tests can insist diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 421b763038..f00174b4ac 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -485,7 +485,8 @@ impl Build<'_> { match id { // A panel row shows the chord of the panel's shortcut (`panel:`), which binds `window.panel {panel}`; // a Window row runs it with `toggle: true`, so the framework finds no chord for the row's own command. - "window.panel" => { + // Settings' first page shows Preferences' shortcut, which binds `edit.preferences` with no page. + "window.panel" | "edit.preferences" if !params.is_null() => { let mut item = item; item.shortcut = super::labels::item_shortcut(self.app, id, params); item diff --git a/crates/ui-egui/src/menus/native.rs b/crates/ui-egui/src/menus/native.rs index 62fbc97da3..b9004c1ebb 100644 --- a/crates/ui-egui/src/menus/native.rs +++ b/crates/ui-egui/src/menus/native.rs @@ -1,12 +1,13 @@ //! The macOS menu bar on craft-menu's native menu: installed once, polled and run before the UI //! each frame, and synced after it. +use craft::keymap::{Chord, CommandRef}; use craft::menu::{Gate, ItemKind, LayoutOptions, MenuBar, NativeMenu, Node, mac, mac_layout}; use craft::ui::runtime::commands::{FirePhase, FireSource, Fired, holder}; use crate::VectorcraftApp; use crate::menus::model::{APP_NAME, item_title, pressed_pass, recording_shortcut, refresh, state_key, translate_label}; -use crate::menus::unbound; +use crate::menus::{command_shortcuts, item_shortcut_in, unbound}; /// The layout options every Mac layout of VectorCraft's menus uses: the app's name and its /// translation of the labels the layout writes itself. @@ -56,16 +57,20 @@ pub(crate) fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) { app.services.native_menu = Some(menu); } -/// The menus with each item's title, and whether it is on and checked, as they are now: AppKit's items show their own, -/// where the in-window bar reads them from the command states. Read here and not from the model, which is built before -/// the frame's input: a drag released or an Escape in this frame already shows. +/// The menus with each item's title, shortcut, and whether it is on and checked, as they are now: AppKit's items show +/// their own, where the in-window bar reads them from the command states. Read here and not from the model, which is +/// built before the frame's input: a drag released or an Escape in this frame already shows. Each item's shortcut is +/// the one the menus show for it ([`crate::menus::item_shortcut`]), else its command's chord in the keymap, the user's +/// set included, as the in-window bar's rows show it. It is also the item's key equivalent. The model's own shortcuts +/// (Window rows, Settings' first page) are read again here: the model built before the window's first keymap has none. fn stated(app: &VectorcraftApp) -> MenuBar { - fn walk(app: &VectorcraftApp, lang: crate::i18n::Lang, nodes: &mut [Node]) { + fn walk(app: &VectorcraftApp, lang: crate::i18n::Lang, chord: &dyn Fn(&CommandRef) -> Option, nodes: &mut [Node]) { for node in nodes { match node { Node::Item(it) if unbound(&it.command.id) => it.enabled = false, Node::Item(it) => { let (id, params) = (it.command.id.as_str(), &it.command.params); + it.shortcut = item_shortcut_in(chord, id, params).or_else(|| chord(&it.command)); if let Some((enabled, checked)) = crate::menus::shown_state(app, id, params) { it.enabled = enabled; if let Some(on) = checked { @@ -78,15 +83,16 @@ fn stated(app: &VectorcraftApp) -> MenuBar { it.label = title; } } - Node::Submenu { children, .. } => walk(app, lang, children), + Node::Submenu { children, .. } => walk(app, lang, chord, children), _ => {} } } } let mut bar = app.menus.bar.clone(); let lang = crate::i18n::current(); + let chord = command_shortcuts(app); for menu in &mut bar.menus { - walk(app, lang, &mut menu.children); + walk(app, lang, &chord, &mut menu.children); } bar } diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index b608e72feb..bce31f0fd0 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -2,7 +2,7 @@ use super::run::{normalize_panel, toolbar_double, toolbar_panel}; use super::slots::{perspective_grid, recent_slot, saved_selection_name, saved_selection_slot, saved_view, saved_view_slot}; use super::{Brightness, Value, VectorcraftApp}; use crate::i18n::LangExt as _; -use craft::keymap::Chord; +use craft::keymap::{Chord, CommandRef}; use craft::ui::runtime::commands; /// Checked state for toggle items. @@ -190,17 +190,33 @@ pub fn plugin_revision() -> u64 { /// the window's keymap, under the user's set in use (Edit → Keyboard Shortcuts). `None` before the /// window's first frame. pub fn shortcut_of(app: &VectorcraftApp, key: &str) -> Option { - let ctx = app.ui_ctx.as_ref()?; - let command = crate::keymap::command_of(key); - let window = commands::keymap(ctx)?; - let (now, built) = (&*app.shortcut_overrides, window.overrides()); - if now.len() == built.len() && now.iter().all(|(k, texts)| built.get(k) == Some(texts)) { - return commands::chord(ctx, &command); - } + command_shortcuts(app)(&crate::keymap::command_of(key)) +} + +/// The shortcut each command shows, as [`shortcut_of`] reads it, for a caller that asks for many: the +/// keymap is read once. `None` for every command before the window's first frame. +pub(crate) fn command_shortcuts(app: &VectorcraftApp) -> impl Fn(&CommandRef) -> Option + '_ { + let ctx = app.ui_ctx.as_ref(); + let window = ctx.and_then(commands::keymap); // The window's keymap takes a change of the set (`shortcuts.set`) from its next frame; the set is read until then. - let mut keymap = (*window).clone(); - keymap.set_overrides(now.clone()); - keymap.bindings(&command).into_iter().find(|b| b.trigger.press == craft::keymap::PressKind::Single).map(|b| b.trigger.chord) + let pending = window.as_ref().and_then(|window| { + let (now, built) = (&*app.shortcut_overrides, window.overrides()); + if now.len() == built.len() && now.iter().all(|(k, texts)| built.get(k) == Some(texts)) { + return None; + } + let mut keymap = (**window).clone(); + keymap.set_overrides(now.clone()); + Some(keymap) + }); + move |command| { + let ctx = ctx.filter(|_| window.is_some())?; + match &pending { + None => commands::chord(ctx, command), + Some(keymap) => { + keymap.bindings(command).into_iter().find(|b| b.trigger.press == craft::keymap::PressKind::Single).map(|b| b.trigger.chord) + } + } + } } /// Is a command currently enabled? diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index c1ea0a7b84..2e1ce41559 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -890,15 +890,11 @@ fn not_mac() -> Platforms { fn app_menu() -> Vec { let settings: Vec = vectorcraft_engine::cmd::prefscmds::PREF_CATEGORIES .iter() - .enumerate() - .map(|(i, page)| { - let mut item = - Item::new(CommandRef::with_params("edit.preferences", json!({ "category": page })), format!("{page}…")).role(ItemRole::Settings); - // Only the first page carries Preferences' shortcut. - if i == 0 { - item.shortcut = crate::shortcut_editor::default_command_shortcut("edit.preferences").and_then(crate::keymap::stored::parse_vc); - } - Node::Item(item) + // Only the first page carries Preferences' shortcut, which the menus' model gives it from the keymap. + .map(|page| { + Node::Item( + Item::new(CommandRef::with_params("edit.preferences", json!({ "category": page })), format!("{page}…")).role(ItemRole::Settings), + ) }) .collect(); let mut language = vec![cp("Automatic", "app.language", json!({ "lang": "auto" })), Sep]; diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 940a195e4b..7dcbb1d05d 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -659,19 +659,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", "", "{}"), ( @@ -1526,7 +1526,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", diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 9b1cfb58e2..678f797822 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -155,6 +155,12 @@ fn rail_owner_among(toolbars: impl Iterator, id: &str) -> Option Workspace { + builtin_workspace(fronts, 1) +} + +/// [`default_workspace`] with the Tools panel laying its tools out in `tools_steps` columns, as a +/// built-in workspace defines it. +pub(crate) fn builtin_workspace(fronts: &[&str], tools_steps: u16) -> Workspace { let mut placed: Vec = Vec::new(); let mut group = |ids: &[&str]| { let fresh: Vec = ids.iter().filter(|id| registered(id) && !placed.iter().any(|p| p == *id)).map(|id| (*id).to_owned()).collect(); @@ -168,7 +174,7 @@ pub(crate) fn default_workspace(fronts: &[&str]) -> Workspace { if !icons.is_empty() { columns.push(Column::new(icons).with_iconic(true)); } - let tools = Column::new(vec![Group::new(vec![crate::toolbar::TOOLS.to_owned()], 0)]).with_steps(1); + let tools = Column::new(vec![Group::new(vec![crate::toolbar::TOOLS.to_owned()], 0)]).with_steps(tools_steps); let centre = Node::split(Axis::X, BESIDE_DOCK, Node::tabs(vec![CANVAS.to_owned()], 0), Node::dock(DockEdge::End, columns)); let root = Node::split(Axis::X, BESIDE_DOCK, Node::dock(DockEdge::Start, vec![tools]), centre); Workspace::new(Layout::new(Some(root), Vec::new())) @@ -267,7 +273,7 @@ fn dock_columns(layout: &Layout) -> Vec<&Column> { } /// The columns of the dock on `edge`, from the window edge inwards; none when that edge has no dock. -fn edge_columns(layout: &Layout, edge: DockEdge) -> &[Column] { +pub(crate) fn edge_columns(layout: &Layout, edge: DockEdge) -> &[Column] { let dock = layout.dock_path(edge).and_then(|path| node_at(layout.root.as_ref()?, &path)); match dock { Some(Node::Dock { columns, .. }) => columns, @@ -1113,14 +1119,18 @@ pub(crate) fn place_floating(app: &mut VectorcraftApp, panel: &str, pos: egui::P } // A rail's window is a stepped column, which the dock fits to the rail's grid; it keeps the steps it had. let steps = is_rail(&id).then(|| column_of(layout, &id).and_then(|(_, column)| column.steps).unwrap_or(1)); - actions.push(match floating_window(layout, &id) { - Some(window) if window.panels().count() == 1 => Action::move_floating(id.clone(), rect), - _ => Action::float(id.clone(), rect), - }); + let ctx = app.ui_ctx.clone(); + match floating_window(layout, &id) { + // An open OS window moves with its window: the dock keeps it where its record says. + Some(window) if window.panels().count() == 1 => { + actions.push(Action::move_floating(id.clone(), rect)); + actions.extend(native_moved(ctx.as_ref(), window, rect)); + } + _ => actions.push(Action::float(id.clone(), rect)), + } if let Some(steps) = steps { actions.push(Action::set_column_steps(id, steps)); } - let ctx = app.ui_ctx.clone(); apply(app, ctx.as_ref(), actions).map(drop) } diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 996afc5964..543c06998e 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -242,6 +242,22 @@ fn an_explicit_float_command_updates_an_existing_native_windows_geometry() { } } +/// `window.toolbar.float` with x, y moves the OS window a toolbar made with New Toolbar already has. +#[test] +fn floating_a_toolbar_at_a_point_moves_its_native_window() { + let mut h = Harness::new(); + h.app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + h.app.run("window.toolbar.float", json!({"name": "Mine", "x": 240, "y": 160})).unwrap(); + h.frames(3); + let panel = crate::custom_toolbars::panel_id(crate::custom_toolbars::find(&h.app.ui, "Mine").unwrap().id); + let viewport = h.viewport(&panel); + assert_eq!(h.host.borrow().windows[&viewport].rect.min, ORIGIN + vec2(240.0, 160.0)); + h.app.run("window.toolbar.float", json!({"name": "Mine", "x": 300, "y": 220})).unwrap(); + h.frames(3); + assert_eq!(h.viewport(&panel), viewport); + assert_eq!(h.host.borrow().windows[&viewport].rect.min, ORIGIN + vec2(300.0, 220.0)); +} + #[test] fn keys_typed_in_a_native_window_run_the_main_windows_shortcuts() { let mut h = Harness::new(); diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 19ab69b734..68e297cd44 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -324,10 +324,18 @@ pub(crate) fn fit_has_art(app: &VectorcraftApp, indices: &[usize]) -> bool { /// isn't selected becomes the only selected one, and the menu's facts are measured. pub(crate) fn right_click(app: &mut VectorcraftApp, p: vectorcraft_geom::Point) { let Some(st) = app.session.active() else { return }; - let (uid, n, hit) = (st.uid, st.doc.artboards.len(), st.doc.artboard_at(p)); + let (n, hit) = (st.doc.artboards.len(), st.doc.artboard_at(p)); if let Some(i) = hit.filter(|i| !picked(app, n).contains(i)) { select(app, i); } + measure_menu(app, p); +} + +/// The canvas menu's facts for the selected artboards, with the menu opened at `p` (a right-click, or the Menu key or +/// Shift+F10, which select nothing). +pub(crate) fn measure_menu(app: &mut VectorcraftApp, p: vectorcraft_geom::Point) { + let Some(st) = app.session.active() else { return }; + let (uid, n) = (st.uid, st.doc.artboards.len()); let all = picked(app, n); let any_empty = vectorcraft_engine::find_command("artboard.deleteEmpty").is_some_and(|c| (c.enabled)(&app.session).is_ok()); let any_art = fit_has_art(app, &all); diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 9b9b45ab6b..5cc220b272 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -927,7 +927,7 @@ fn ratio_answer(app: &mut VectorcraftApp, panel: &mut WheelUi, pinned: Option r.clone(), diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index 88ee1d6f6f..87eb9f9880 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -31,13 +31,32 @@ pub struct DocInfoView { } /// A `label: value` row. `label` is shown as given: translate an interface label first, a name -/// stays as it is. -pub(crate) fn row(ui: &mut Ui, label: &str, value: String) { +/// stays as it is. Whether the value was clicked to copy it: a click with no key held, other than +/// the second or third click of a double or triple click. +pub(crate) fn row(ui: &mut Ui, label: &str, value: &str) -> bool { + let mut clicked = false; Row::new().fill_width().align(RowAlign::SpaceBetween).wrap(true).show(ui, |ui, _| { Text::new(label.to_string()).shade(Shade::Muted).show(ui); - // The value can be selected and copied (#8432). - SelectableText::new(label.to_string(), &value).show(ui); + // The value can be selected and copied, and a click copies all of it (#8432). A drag selects + // and a Shift-click extends the selection, so neither copies. + let shown = SelectableText::new(label.to_string(), value).show(ui); + // The click's own position and keys: a move or a key change after the release in the same + // frame leaves the pointer and the held keys elsewhere. A frame with more than one release + // copies nothing, since the click flags below do not say which release they describe. + let area = shown.interact_rect.intersect(ui.clip_rect()); + let primary = egui::PointerButton::Primary; + let release = ui.input(|i| { + let mut releases = i.events.iter().filter_map(|e| match e { + egui::Event::PointerButton { pos, button, pressed: false, modifiers } if *button == primary => Some((*pos, *modifiers)), + _ => None, + }); + let release = releases.next().filter(|_| releases.next().is_none()); + let single = i.pointer.button_clicked(primary) && !i.pointer.button_double_clicked(primary) && !i.pointer.button_triple_clicked(primary); + release.filter(|_| single) + }); + clicked = release.is_some_and(|(pos, keys)| keys.is_none() && area.contains(pos) && ui.ctx().layer_id_at(pos) == Some(ui.layer_id())); }); + clicked } /// `document.info` with its categories, fetched again only when the document, the scope or the @@ -64,6 +83,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; }; let DocInfoView { selection_only: sel_only, category } = app.ui.doc_info.clone(); + let mut copy = None; Stack::new().show(ui, |ui, _| { let sections = i["sections"].as_array().map_or(&[][..], Vec::as_slice); let shown = sections.iter().filter(|s| category.is_empty() || s["id"] == category.as_str()); @@ -92,11 +112,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Text::new(super::label_or_name(label, !named.contains(&k)).to_string()).shade(Shade::Muted).show(ui); } else { let shown = shown_value(&i, id, k, (label, value), named.contains(&k)).unwrap_or_else(|| value.to_string()); - row(ui, super::label_or_name(label, !named.contains(&k)), shown); + if row(ui, super::label_or_name(label, !named.contains(&k)), &shown) { + copy = Some(shown); + } } } } }); + if let Some(text) = copy { + app.clipboard_out = Some(text); + app.status("Copied the value"); + } } /// A Brushes row's value in the interface language: the brush's type (`Art Brush`), or that the diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 609056dffc..b2131ae600 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -25,7 +25,7 @@ //! gradient behind the active proxy, keeping its placement (`gradient.presets.*`). Hide Presets in //! the panel menu leaves the row out. -use craft::behavior::{EditEvent, IconId, Mixed}; +use craft::behavior::{ColumnWidth, EditEvent, IconId, Mixed}; use craft::color_ui::gradient::stops::AltDrop; use craft::color_ui::ui::DropperButton; use craft::color_ui::ui::gradient::{ColorStop, GradientEditor, GradientStops, StopDrop, StopRef, StopRow, StopRows, StopRules}; @@ -35,7 +35,8 @@ use craft::ui::buttons::{Button, IconButton}; use craft::ui::choice::{Checkbox, Radio, RadioGroup, Segmented, Swatch}; use craft::ui::contract::{Bind, EditResponse, Entry, MemoProps, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::display::{Divider, Icon, Shade, Text}; -use craft::ui::layout_components::{Row, Stack}; +use craft::ui::layout::CellAlign; +use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::list::ThumbAspect; use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::Notice; @@ -66,6 +67,9 @@ use crate::panel_drag::PanelDrag; /// The Angle field's preset menu, degrees. const ANGLE_PRESETS: [f64; 9] = [-180.0, -135.0, -90.0, -45.0, 0.0, 45.0, 90.0, 135.0, 180.0]; +/// The header's columns: the thumbnail with its swatch menu, and the type buttons with Edit Gradient, each as wide +/// as its content. +const BESIDE: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Content]; /// The Aspect Ratio field's preset menu, percent. const ASPECT_PRESETS: [f64; 9] = [10.0, 25.0, 50.0, 75.0, 100.0, 150.0, 200.0, 300.0, 400.0]; // PLAN: the sheet drops `HIDE_OPTIONS` and `HIDE_PRESETS`, but each key is read by `show`, `menu_states` and `run`; kept as the op.A5 hide-store keys. @@ -171,7 +175,7 @@ pub(crate) fn type_row(app: &mut VectorcraftApp, ui: &mut Ui) { (GradientKind::Diamond, "dc-grad-diamond", tl!("Diamond Gradient")), (GradientKind::Freeform, "dc-grad-freeform", tl!("Freeform Gradient")), ]); - Row::new().show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { Text::new(tl!("Type:")).shade(Shade::Muted).show(ui); let pick = Segmented::new(tl!("Type"), lit(kind), &entries).show(ui); if let Some(k) = pick.events.committed() { @@ -309,19 +313,23 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let kind = g.gradient.kind; let hidden = part_hidden(app, HIDE_OPTIONS); // Header: the thumbnail and its swatch menu, the type buttons and Edit Gradient. - Row::new().show(ui, |ui, _| { - fill_box(app, ui, &g, is_grad); - if hidden { + if hidden { + Row::new().show(ui, |ui, _| { + fill_box(app, ui, &g, is_grad); super::proxy(app, ui); - return; - } - Stack::new().show(ui, |ui, _| { - type_row(app, ui); - if Button::new(tl!("Edit Gradient")).show(ui).clicked() { - app.select_tool("gradient"); - } }); - }); + } else { + // The type buttons go beside the thumbnail, level with its top, or under it in a narrow panel. + Grid::new(&BESIDE).cells(CellAlign::Top).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| fill_box(app, ui, &g, is_grad)); + Stack::new().show(ui, |ui, _| { + type_row(app, ui); + if Button::new(tl!("Edit Gradient")).show(ui).clicked() { + app.select_tool("gradient"); + } + }); + }); + } let freeform = is_grad && kind == GradientKind::Freeform; let points = is_grad && edits_points(app, &g); if hidden { @@ -458,7 +466,7 @@ fn method_select(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gr ] .map(|(m, label)| Entry::new(m, label)); let current = g.gradient.method; - Row::new().show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { Text::new(tl!("Method:")).shade(Shade::Muted).show(ui); let pick = Select::new(tl!("Method"), Bind::given(current), &methods).enabled(is_grad).show(ui); if let Some(m) = pick.events.committed().filter(|m| **m != current) { @@ -475,7 +483,7 @@ fn spread_select(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gr .map(|(s, label)| Entry::new(s, label)); let current = g.gradient.spread; let presets = number_presets(&REPEAT_PRESETS, ""); - Row::new().show(ui, |ui, _| { + Row::new().wrap(true).show(ui, |ui, _| { Text::new(tl!("Spread:")).shade(Shade::Muted).show(ui); let pick = Select::new(tl!("Spread"), Bind::given(current), &spreads).enabled(is_grad).show(ui); if let Some(s) = pick.events.committed().filter(|s| **s != current) { @@ -690,34 +698,42 @@ fn host_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: boo } }); } - Row::new().show(ui, |ui, _| { - Text::new(tl!("Opacity:")).shade(Shade::Muted).show(ui); - let shown = stop.map_or(100.0, |s| f64::from(s.opacity) * 100.0); - let opacity = NumberField::new(tl!("Opacity"), Bind::given(Some(shown))).range(0.0..=100.0).unit("%").enabled(sel.is_some()).show(ui); - apply_number(app, &opacity.edit, |app, v, phase| { - let Some(i) = sel else { return }; - let mut v2 = stops.clone(); - if let Some(s) = v2.get_mut(i) { - s.opacity = (v / 100.0).clamp(0.0, 1.0) as f32; - } - set_stops(app, &v2, Some(i), phase); + // In a narrow panel the row wraps; each caption stays on the line of its field. + Row::new().wrap(true).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + Text::new(tl!("Opacity:")).shade(Shade::Muted).show(ui); + let shown = stop.map_or(100.0, |s| f64::from(s.opacity) * 100.0); + let opacity = NumberField::new(tl!("Opacity"), Bind::given(Some(shown))).range(0.0..=100.0).unit("%").enabled(sel.is_some()).show(ui); + apply_number(app, &opacity.edit, |app, v, phase| { + let Some(i) = sel else { return }; + let mut v2 = stops.clone(); + if let Some(s) = v2.get_mut(i) { + s.opacity = (v / 100.0).clamp(0.0, 1.0) as f32; + } + set_stops(app, &v2, Some(i), phase); + }); }); - Text::new(tl!("Location:")).shade(Shade::Muted).show(ui); - let loc = match (mid, stop) { - (Some(m), _) => stops.get(m).map_or(0.0, |s| percent(s.midpoint)), - (None, Some(s)) => percent(s.offset), - _ => 0.0, - }; - let location = - NumberField::new(tl!("Location"), Bind::given(Some(loc))).range(0.0..=100.0).unit("%").enabled(sel.is_some() || mid.is_some()).show(ui); - apply_number(app, &location.edit, |app, v, phase| { - let v = (v / 100.0) as f32; - if let Some(m) = mid { - set_stops(app, &set_midpoint(stops, m, v), None, phase); - } else if let Some(i) = sel { - let (v2, ni) = move_stop(stops, i, v); - set_stops(app, &v2, Some(ni), phase); - } + Row::new().show(ui, |ui, _| { + Text::new(tl!("Location:")).shade(Shade::Muted).show(ui); + let loc = match (mid, stop) { + (Some(m), _) => stops.get(m).map_or(0.0, |s| percent(s.midpoint)), + (None, Some(s)) => percent(s.offset), + _ => 0.0, + }; + let location = NumberField::new(tl!("Location"), Bind::given(Some(loc))) + .range(0.0..=100.0) + .unit("%") + .enabled(sel.is_some() || mid.is_some()) + .show(ui); + apply_number(app, &location.edit, |app, v, phase| { + let v = (v / 100.0) as f32; + if let Some(m) = mid { + set_stops(app, &set_midpoint(stops, m, v), None, phase); + } else if let Some(i) = sel { + let (v2, ni) = move_stop(stops, i, v); + set_stops(app, &v2, Some(ni), phase); + } + }); }); let can_del = sel.is_some() && stops.len() > MIN_STOPS; let delete = IconButton::new(IconId::new("trash-2")).label(tl!("Delete Stop")).tooltip(tl!("Delete Stop")).enabled(can_del).show(ui); diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index 9a71052c7c..f4b57b8c8b 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -6,6 +6,7 @@ use egui::{Key, Modifiers, Pos2, pos2, vec2}; use vectorcraft_engine::Session; use super::*; +use crate::tests::panel_harness::{Place, Shown, floated}; #[test] fn dropped_colours_recolour_or_add_an_opaque_stop() { @@ -364,6 +365,85 @@ fn escape_ends_the_stop_eyedropper_and_returns_to_the_gradient_tool() { assert_eq!(app.session.active().unwrap().selection.objects, selected, "the selection stays"); } +// ---------- the panel in the app window ---------- + +/// A selected gradient stop: the panel shows its Color row. +fn select_a_stop(app: &mut VectorcraftApp) { + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); +} + +/// The Gradient panel shown at `place` in the whole app window over a selected rectangle that `setup` paints, drawn +/// in `lang`, with the catalog strings `names` as `lang` shows them. The Gradient Fill box is always asked for, so a +/// docked panel is found by it. +fn shown(lang: &str, place: Place, setup: fn(&mut VectorcraftApp), names: &[&str]) -> Shown { + let mut app = super::super::tests_appearance::app_with_rect(); + setup(&mut app); + let asked: Vec<&str> = names.iter().copied().chain(["Gradient Fill"]).collect(); + floated(app, "gradient", lang, place, &asked) +} + +/// Docked, every control of the panel stays inside its column, with a solid fill (the panel shows its notice) and +/// with a stop selected (its Color row), in languages with longer words. +#[test] +fn the_gradient_panel_stays_inside_its_dock_column() { + for lang in ["en", "fr", "de"] { + for setup in [|_: &mut VectorcraftApp| {}, select_a_stop] { + let panel = shown(lang, Place::Docked, setup, &[]); + let past = panel.past(panel.nodes.clone()); + assert!(past.is_empty(), "past the docked panel in {lang}: {past:?}"); + } + } +} + +/// In a panel at the narrowest panel width the Type, Method, Spread and stop rows wrap: their controls stay inside +/// the panel, except the last type button. The five type buttons are one `Segmented` control, which keeps its +/// segments on one line, so at this width Freeform Gradient reaches 2 pt past the panel's right edge. The test +/// holds that button to the 2 pt until the widget can wrap its segments. +#[test] +fn the_gradient_rows_wrap_in_a_narrow_panel() { + /// How far Freeform Gradient reaches past the panel's right edge at the narrowest width. + const TYPE_OVERFLOW: f32 = 2.0; + let names = [ + "Linear Gradient", + "Radial Gradient", + "Conic Gradient", + "Diamond Gradient", + "Edit Gradient", + "Method", + "Spread", + "Repeats", + "Opacity", + "Location", + "Delete Stop", + ]; + for lang in ["en", "fr"] { + let asked: Vec<&str> = names.iter().copied().chain(["Freeform Gradient"]).collect(); + let panel = shown(lang, Place::Floating(crate::panel_docking::PANEL_MIN_WIDTH), select_a_stop, &asked); + let past = panel.past_named(&names); + assert!(past.is_empty(), "past the panel in {lang}: {past:?}"); + for freeform in panel.rects("Freeform Gradient") { + let inside = freeform.left() >= panel.body.left() - 0.5 && freeform.right() <= panel.body.right() + TYPE_OVERFLOW + 0.5; + assert!(inside, "Freeform Gradient at {freeform:?} is more than {TYPE_OVERFLOW} pt past {:?} in {lang}", panel.body); + } + } +} + +/// In a wide panel the rows stay on one line each, and the thumbnail stays level with the top of the type buttons. +#[test] +fn the_gradient_rows_stay_on_one_line_in_a_wide_panel() { + let rows: [&[&str]; 3] = + [&["Method:", "Method"], &["Spread:", "Spread", "Repeats"], &["Opacity:", "Opacity", "Location:", "Location", "Delete Stop"]]; + let names: Vec<&'static str> = rows.iter().flat_map(|row| row.iter().copied()).chain(["Gradient Fill", "Linear Gradient"]).collect(); + let panel = shown("en", Place::Floating(400.0), select_a_stop, &names); + for row in rows { + let middles = panel.middles(row); + assert!(middles.windows(2).all(|m| (m[0] - m[1]).abs() < 1.0), "{row:?} is not on one line: {middles:?}"); + } + let (thumb, linear) = (panel.rects("Gradient Fill")[0], panel.rects("Linear Gradient")[0]); + assert!((thumb.top() - linear.top()).abs() < 1.0, "the thumbnail {thumb:?} is not level with the type buttons {linear:?}"); +} + /// The paints of the selected object's appearance rows, in stack order. fn row_paints(app: &VectorcraftApp) -> Vec { let st = app.session.active().unwrap(); diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index e2096de5d5..31bb7ebd9f 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -230,11 +230,12 @@ fn shifted(mut view: CanvasView, region: DRect) -> CanvasView { view } -/// The `view.setZoom` params for `edited`, a view of the region's frame: the zoom as the status bar -/// shows it (with `print` screen points to an inch at 100%, [`crate::state::print_ppi`]), and the -/// centre back in document units. -fn view_params(edited: &CanvasView, region: DRect, print: Option) -> Value { - json!({"zoom": crate::state::zoom_display_percent(edited.zoom, print), "center": [edited.center.x + region.x0, edited.center.y + region.y0]}) +/// The `view.setZoom` params for `edited`, a canvas view of the region's frame at `ui_scaling`: the +/// zoom as the status bar shows it (with `print` screen points to an inch at 100%, +/// [`crate::state::print_ppi`]), and the centre back in document units. +fn view_params(edited: &CanvasView, region: DRect, print: Option, ui_scaling: f32) -> Value { + let zoom = crate::state::View::zoom_of_canvas(edited, ui_scaling); + json!({"zoom": crate::state::zoom_display_percent(zoom, print), "center": [edited.center.x + region.x0, edited.center.y + region.y0]}) } pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -280,7 +281,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { && *edited != given { let print = app.print_ppi(); - app.run("view.setZoom", view_params(edited, region, print)).ok(); + let scaling = app.ui_scaling(); + app.run("view.setZoom", view_params(edited, region, print, scaling)).ok(); } } @@ -299,7 +301,29 @@ mod tests { assert_eq!((given.center.x, given.center.y), (210.0, 170.0), "the centre minus the region's corner"); let mut edited = given; edited.center = (100.0, 100.0).into(); - assert_eq!(view_params(&edited, region, None)["center"], json!([90.0, 80.0]), "the edit plus the region's corner"); + assert_eq!(view_params(&edited, region, None, 1.0)["center"], json!([90.0, 80.0]), "the edit plus the region's corner"); + } + + /// At UI Scaling 150% the panel's 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 = VectorcraftApp::new(vectorcraft_engine::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 = Rect::from_min_size(pos2(0.0, 0.0), 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 panel = crate::tests::panel_harness::Panel::new(app, show); + assert!((panel.ctx().zoom_factor() - 1.5).abs() < 1e-6, "the interface is zoomed by UI Scaling"); + let shown = |panel: &crate::tests::panel_harness::Panel| panel.value("Zoom").unwrap_or_default(); + assert!(shown(&panel).starts_with("100"), "the field shows the zoom view.setZoom set: {}", shown(&panel)); + panel.type_into("Zoom", "200"); + let zoom = panel.app().view().unwrap().zoom; + assert!((zoom - wanted).abs() < 1e-9, "typing 200% gives the zoom of view.setZoom 200%: {zoom}, not {wanted}"); + assert!(shown(&panel).starts_with("200"), "the field shows the typed zoom: {}", shown(&panel)); } /// The panel menu's rows are titled, checked and enabled as the option says, and each row's diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 2dd7f1f39f..26102b5311 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -434,19 +434,19 @@ pub(crate) fn alignment_toggles(app: &mut VectorcraftApp, ui: &mut Ui, count: us /// The Control bar's paragraph controls while type is selected or edited (#5372), after its /// Character controls: the Paragraph link, which opens the Paragraph panel in a popover under it, /// and the Align left, Align center and Align right buttons. Always `true`: the bar trims these -/// itself as it narrows. +/// itself as it narrows, the link and the buttons as two members of the type groups' rank, so the +/// buttons leave before the link. pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { if text_style(app).is_none() { return true; } - // PLAN: the members' `Row::fit_rank` (ch.K30: toggles out before the link) belongs to chrome-w16's row. - Row::new().show(ui, |ui, _| { + Row::new().fit_rank(crate::chrome::rank::TYPE).show(ui, |ui, _| { let link = crate::panels::option_link(tl!("Paragraph:")).tooltip(tl!("Paragraph options")).show(ui); Popover::new(tl!("Paragraph"), Bind::kept()) .overlay(|overlay| overlay.opened_by(&link.response, Trigger::Click)) .show(ui, |ui, _| show(app, ui)); - alignment_toggles(app, ui, CONTROL_BAR_ALIGNMENTS); }); + Row::new().fit_rank(crate::chrome::rank::TYPE).show(ui, |ui, _| alignment_toggles(app, ui, CONTROL_BAR_ALIGNMENTS)); true } diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 48b324ccf4..0d56471f6d 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -751,7 +751,6 @@ fn bar_names(app: &mut VectorcraftApp) -> Vec { /// #5372: with type selected the Control bar shows a Paragraph section: the Paragraph: link and the /// Align left, Align center and Align right buttons (the justifying four are in the panel the link /// opens); with no type selected it shows none of them. -// PLAN: the trimming order as the bar narrows (toggles out before the link, ch.K30) is chrome-w16's `Row::fit_rank` and is tested with its fixture. #[test] fn the_control_bar_shows_its_paragraph_section_for_selected_type_only() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/panels/tests_panel_rows.rs b/crates/ui-egui/src/panels/tests_panel_rows.rs index 15a8dace13..e249c1ea95 100644 --- a/crates/ui-egui/src/panels/tests_panel_rows.rs +++ b/crates/ui-egui/src/panels/tests_panel_rows.rs @@ -1,12 +1,9 @@ //! Headless frames of panel rows that the framework lays out: controls side by side stay inside the panel's width. -use serde_json::json; - use super::tests_appearance::app_with_rect; use super::*; -use crate::i18n::Lang; use crate::panel_docking::PANEL_MIN_WIDTH; -use crate::tests::panel_harness::{Panel, ROOM}; +use crate::tests::panel_harness::{Panel, Place, ROOM, floated}; #[test] fn the_arrowhead_row_stays_inside_the_stroke_panel() { @@ -30,62 +27,19 @@ fn the_color_themes_hex_row_stays_inside_a_narrow_panel() { } } -/// Panel `panel` floated `width` wide in the whole app window, drawn in `lang`: the rect of its body, and the rects of -/// the controls named each of `names` (catalog strings, shown in `lang`). -fn floated(panel: &str, lang: &str, width: f32, names: &[&str]) -> (egui::Rect, Vec<(String, Vec)>) { - use egui::accesskit::Role; - const AT: f32 = 520.0; - let mut app = app_with_rect(); - app.session.prefs.interface_language = lang.into(); - app.run("window.panel", json!({ "panel": panel })).unwrap(); - app.run("window.panel.float", json!({ "panel": panel, "x": AT, "y": 120, "width": width, "height": 700 })).unwrap(); - let ctx = crate::testing::ui_context(); - ctx.enable_accesskit(); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0)); - let mut nodes = Vec::new(); - for at in 1..=8 { - let input = egui::RawInput { time: Some(f64::from(at) * 0.1), screen_rect: Some(screen), ..Default::default() }; - let out = crate::testing::app_frame(&mut app, &ctx, input); - nodes = out.platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes); - } - // The frames set the language from the preference; the names are looked up in it before English is put back. - let shown: Vec<&str> = names.iter().map(|name| crate::i18n::t(name)).collect(); - crate::i18n::set_current(Lang::EN); - let rect = |node: &egui::accesskit::Node| { - node.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))) - }; - // The floating panel's body: the tab panel at the left edge the float asked for. - let body = nodes - .iter() - .filter(|(_, n)| n.role() == Role::TabPanel) - .find_map(|(_, n)| rect(n).filter(|r| (r.left() - AT).abs() < 1.0)) - .unwrap_or_else(|| panic!("{panel} does not float at x {AT}")); - assert!(body.width() <= width + 1.0, "{panel}'s body {body:?} is wider than the {width} the float asked for"); - let controls = shown - .into_iter() - .map(|name| { - let found: Vec = nodes.iter().filter(|(_, n)| n.label().is_some_and(|l| l == name)).filter_map(|(_, n)| rect(n)).collect(); - assert!(!found.is_empty(), "{panel} shows no {name:?}"); - (name.to_owned(), found) - }) - .collect(); - (body, controls) -} - /// The controls named `names` (catalog strings, shown in `lang`) that reach past either side of panel `panel`, /// floated at the narrowest panel width in the whole app window, each with its rect. fn past_a_narrow_panel(panel: &str, lang: &str, names: &[&str]) -> Vec { - let (body, controls) = floated(panel, lang, PANEL_MIN_WIDTH, names); - let outside = |r: &egui::Rect| r.left() < body.left() - 0.5 || r.right() > body.right() + 0.5; - controls.iter().flat_map(|(name, found)| found.iter().filter(|r| outside(r)).map(move |r| format!("{name} at {r:?}"))).collect() + floated(app_with_rect(), panel, lang, Place::Floating(PANEL_MIN_WIDTH), names).past_named(names) } #[test] fn the_profile_row_stays_on_one_line_in_a_wide_stroke_panel() { - let (_, controls) = floated("stroke", "en", 360.0, &["Profile", "Flip Along", "Flip Across"]); + let names = ["Profile", "Flip Along", "Flip Across"]; + let panel = floated(app_with_rect(), "stroke", "en", Place::Floating(360.0), &names); // The field, its caption, the list and the two buttons share one line, so their middles are level. - let middles: Vec = controls.iter().flat_map(|(_, found)| found.iter().map(|r| r.center().y)).collect(); - assert!(middles.windows(2).all(|m| (m[0] - m[1]).abs() < 1.0), "{controls:?}"); + let middles = panel.middles(&names); + assert!(middles.windows(2).all(|m| (m[0] - m[1]).abs() < 1.0), "{middles:?}"); } #[test] diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 3ff0fd0191..b418d3d2b4 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -20,7 +20,7 @@ use craft::ui::contract::{ Bind, CollectionEvent, ColumnEvent, ColumnSort, ColumnSpec, PopupKind, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Trigger, Validity, }; -use craft::ui::display::{Icon, Shade, Text}; +use craft::ui::display::{Divider, Icon, Shade, Text}; use craft::ui::form::Field; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow}; @@ -278,7 +278,7 @@ struct Picked { has_selection: bool, /// Unbind needs a bound object under the selection, not just any selection. selection_bound: bool, - /// Make Text Dynamic needs exactly one type object: a text variable only drives type. + /// Make Text Dynamic needs one type object without an existing text variable. single_type: bool, /// Make Image Dynamic needs exactly one image object. single_image: bool, @@ -289,7 +289,15 @@ struct Picked { fn picked(st: &vectorcraft_engine::DocState) -> Picked { let selected: Vec = st.selection.objects.iter().map(|i| i.0).collect(); let selection_bound = selected.iter().any(|id| st.doc.variables.bindings.contains_key(&NodeId(*id))); - let single_type = matches!(selected.as_slice(), [one] if st.doc.node(NodeId(*one)).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))); + let single_type = match selected.as_slice() { + [one] if st.doc.node(NodeId(*one)).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) => st + .doc + .variables + .bindings + .get(&NodeId(*one)) + .is_none_or(|bound| !st.doc.variables.variables.iter().any(|v| v.kind == VariableKind::Text && bound.contains(&v.name))), + _ => false, + }; let single_image = matches!(selected.as_slice(), [one] if st.doc.node(NodeId(*one)).is_some_and(|n| matches!(n.kind, NodeKind::Image(_)))); let selection_graph = !selected.is_empty() && selected.iter().all(|id| st.doc.node(NodeId(*id)).is_some_and(|n| n.extras().graph.is_some())); Picked { has_selection: !selected.is_empty(), selected, selection_bound, single_type, single_image, selection_graph } @@ -408,6 +416,8 @@ enum Act { Rename(String, String), /// A click on a variable's row. Click(String), + /// A context request highlights its variable without changing the canvas selection. + Highlight(String), /// A double click on a variable's row: Variable Options for it. Options(String), } @@ -422,10 +432,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let rows = cached_rows(&mut app.canvas, st, xml_id); let states = row_states(st); let sort = st.variables_sort; + let doc_uid = st.uid; let (mut acts, mut pressed) = (Vec::new(), None); Stack::new().fill().footer(|ui, _| pressed = footer(ui, &states)).show(ui, |ui, _| { data_set_bar(ui, &rows.sets, &mut acts); - variable_table(ui, &rows.vars, sort, &states, &mut acts); + variable_table(ui, &rows.vars, sort, &states, doc_uid, &mut acts); Text::new(tl!("Data Sets")).role(TypeRole::Heading).show(ui); data_set_list(ui, &rows.sets, &mut acts); }); @@ -442,6 +453,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let bound = rows.vars.iter().find(|v| v.name == name).map(|v| v.bound.clone()).unwrap_or_default(); click_row(app, &name, &bound); } + Act::Highlight(name) => { + app.run("variable.highlight", json!({"variable": name})).ok(); + } Act::Options(name) => { crate::dialogs::variables::open(app, "variable.rename", Some(&name)); } @@ -492,7 +506,7 @@ fn data_set_bar(ui: &mut Ui, sets: &[SetRow], acts: &mut Vec) { /// The variables under their three sortable columns: a row's kind, its name and what it drives. /// A click highlights the row and selects what it drives; a double click opens Variable Options. -fn variable_table(ui: &mut Ui, vars: &[VarRow], sort: VariableSort, states: &RowStates, acts: &mut Vec) { +fn variable_table(ui: &mut Ui, vars: &[VarRow], sort: VariableSort, states: &RowStates, doc_uid: u64, acts: &mut Vec) { let columns = vec![ ColumnSpec::new(TYPE, tl!("Type"), ColumnWidth::Controls(1.0)).icon(IconId::new("arrow-up-down")).tip(tl!("Type")).sortable(), ColumnSpec::new(NAME, tl!("Variables"), ColumnWidth::fill(1.0)).sortable(), @@ -501,6 +515,7 @@ fn variable_table(ui: &mut Ui, vars: &[VarRow], sort: VariableSort, states: &Row let sorted = SORTS.iter().find(|(_, by)| *by == sort.by).map(|(key, _)| ColumnSort::new(key.clone(), sort.descending)); let by_name: HashMap<&str, &VarRow> = vars.iter().map(|v| (v.name.as_str(), v)).collect(); let out = Table::::new(tl!("Variables"), columns) + .id(ui.scope_id().with(("variables-table", doc_uid))) .select(SelectMode::Single) .sort(sorted) .empty(tl!("None")) @@ -514,20 +529,68 @@ fn variable_table(ui: &mut Ui, vars: &[VarRow], sort: VariableSort, states: &Row .cell(OBJECT, row.object.clone()) .cell_muted(OBJECT) }); + let opening_menu = out.events.iter().any(|event| matches!(event, CollectionEvent::ContextMenu(_))); + if let Some(request) = &out.menu + && let Some(row) = by_name.get(request.key.as_str()) + { + variable_menu(ui, &out.response, row, states, acts); + } for event in out.events { match event { + CollectionEvent::ContextMenu(request) => acts.push(Act::Highlight(request.key)), CollectionEvent::Column(ColumnEvent::Sort { key, descending, .. }) => { if let Some((_, by)) = SORTS.iter().find(|(column, _)| *column == key) { acts.push(Act::Run("variable.sort", json!({"by": by.id(), "descending": descending}))); } } - CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => acts.extend(keys.into_iter().next().map(Act::Click)), + CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } if !opening_menu => { + acts.extend(keys.into_iter().next().map(Act::Click)); + } CollectionEvent::Activate(name) if !states.locked => acts.push(Act::Options(name)), _ => {} } } } +/// A variable's item menu, retained by the table by key and scoped to its document. +/// Row actions name their target explicitly; dynamic actions use the canvas selection. +fn variable_menu(ui: &mut Ui, opener: &egui::Response, row: &VarRow, states: &RowStates, acts: &mut Vec) { + Menu::context(row.name.clone(), opener).id(opener.id.with("variable-row-menu")).show(ui, |ui, _| { + for id in [ + SELECT_BOUND, + "variable.rename", + UNBIND, + "", + "variable.makeTextDynamic", + "variable.makeVisibilityDynamic", + "variable.makeImageDynamic", + "variable.makeGraphDynamic", + "", + DELETE_VARIABLE, + ] { + if id.is_empty() { + Divider::horizontal().show(ui); + continue; + } + let enabled = match id { + SELECT_BOUND => !row.bound.is_empty(), + "variable.rename" | DELETE_VARIABLE => !states.locked, + UNBIND => !row.bound.is_empty() && !states.locked, + _ => states.enabled(id), + }; + if MenuItem::new(title(id, states.locked)).enabled(enabled).show(ui).ran { + acts.push(match id { + SELECT_BOUND => Act::Run("select.set", json!({"ids": row.bound})), + "variable.rename" => Act::Options(row.name.clone()), + UNBIND => Act::Run("variable.unbind", json!({"ids": row.bound, "variable": row.name})), + DELETE_VARIABLE => Act::Run("variable.delete", json!({"names": [row.name]})), + _ => Act::Run(id, json!({})), + }); + } + } + }); +} + /// The data sets, the active one selected; a row the art has drifted from is in italics, so an edit /// that left the document not matching it is visible. A click on another row applies it. fn data_set_list(ui: &mut Ui, sets: &[SetRow], acts: &mut Vec) { @@ -739,9 +802,14 @@ mod tests { /// Clicks the center of `node`. fn click(&mut self, app: &mut VectorcraftApp, node: &egui::accesskit::Node) { - use egui::{Event, Modifiers, PointerButton}; - let pos = center(node); - let (button, none) = (PointerButton::Primary, Modifiers::default()); + self.click_button(app, node, egui::PointerButton::Primary); + } + + fn click_button(&mut self, app: &mut VectorcraftApp, node: &egui::accesskit::Node, button: egui::PointerButton) { + use egui::{Event, Modifiers}; + let b = node.bounds().expect("bounds"); + let pos = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + let none = Modifiers::default(); self.frame(app, vec![Event::PointerMoved(pos), Event::PointerButton { pos, button, pressed: true, modifiers: none }]); self.frame(app, vec![Event::PointerButton { pos, button, pressed: false, modifiers: none }]); self.frame(app, vec![]); @@ -754,6 +822,222 @@ mod tests { egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5) } + fn open_row_menu(d: &mut Driver, app: &mut VectorcraftApp, name: &str) -> Vec { + let nodes = d.nodes(app); + let row = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::ListItem && n.label() == Some(name)).expect("variable row"); + d.click_button(app, &row.1, egui::PointerButton::Secondary); + d.nodes(app).into_iter().filter(|(id, _)| !nodes.iter().any(|(before, _)| before == id)).map(|(_, n)| n).collect() + } + + fn menu_button(nodes: &[egui::accesskit::Node], label: &str) -> egui::accesskit::Node { + nodes.iter().find(|n| n.role() == egui::accesskit::Role::MenuItem && n.label().is_some_and(|s| s.trim() == label)).expect(label).clone() + } + + #[test] + fn right_click_highlights_row_and_select_bound_object_uses_it() { + let mut app = app_with_data(); + app.run("variable.define", json!({"name": "Other", "kind": "visibility"})).unwrap(); + app.run("variable.highlight", json!({"variable": "Other"})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + let st = app.session.active().unwrap(); + assert_eq!(highlighted_row(st).as_deref(), Some("Name")); + assert!(st.selection.objects.is_empty(), "right click must preserve canvas selection"); + let bound = st.doc.variables.objects_of("Name"); + app.run("variable.highlight", json!({"variable": "Other"})).unwrap(); + d.click(&mut app, &menu_button(&nodes, "Select Bound Object")); + assert_eq!(app.session.active().unwrap().selection.objects, bound); + } + + #[test] + fn keyboard_opens_focused_row_menu_without_changing_canvas_selection() { + use egui::{Event, Key, Modifiers}; + let mut app = app_with_data(); + let selected = app.session.active().unwrap().selection.objects.clone(); + let mut d = Driver::new(); + let nodes = d.nodes(&mut app); + let table_id = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::Table).unwrap().0; + let key = |key, modifiers| Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + for _ in 0..20 { + if d.ctx.memory(|m| m.focused()).is_some_and(|id| id.value() == table_id.0) { + break; + } + d.frame(&mut app, vec![key(Key::Tab, Modifiers::NONE)]); + d.frame(&mut app, vec![]); + } + assert!(d.ctx.memory(|m| m.focused()).is_some_and(|id| id.value() == table_id.0), "Tab must focus the variable table"); + // The table owns keyboard focus; Down establishes its focused row before requesting its menu. + d.frame(&mut app, vec![key(Key::ArrowDown, Modifiers::NONE)]); + d.frame(&mut app, vec![key(Key::F10, Modifiers::SHIFT)]); + let nodes = d.nodes(&mut app).into_iter().map(|(_, n)| n).collect::>(); + assert!(!menu_button(&nodes, "Select Bound Object").is_disabled()); + assert_eq!(highlighted_row(app.session.active().unwrap()).as_deref(), Some("Name")); + assert_eq!(app.session.active().unwrap().selection.objects, selected); + d.frame(&mut app, vec![key(Key::Escape, Modifiers::NONE)]); + assert!(!d.nodes(&mut app).iter().any(|(_, n)| n.role() == egui::accesskit::Role::MenuItem)); + } + + #[test] + fn context_menu_deletes_clicked_variable_in_one_undo_step() { + let mut app = app_with_data(); + app.run("variable.define", json!({"name": "Other", "kind": "visibility"})).unwrap(); + app.run("variable.highlight", json!({"variable": "Other"})).unwrap(); + let before = undo_steps(&app); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + // A command can change the highlight while this row's menu remains open. + app.run("variable.highlight", json!({"variable": "Other"})).unwrap(); + app.run("variable.sort", json!({"by": "name", "descending": true})).unwrap(); + d.frame(&mut app, vec![]); + d.click(&mut app, &menu_button(&nodes, "Delete Variable")); + let st = app.session.active().unwrap(); + assert!(st.doc.variables.variable("Name").is_none()); + assert!(st.doc.variables.variable("Other").is_some()); + assert_eq!(undo_steps(&app), before + 1); + app.run("edit.undo", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.variables.variable("Name").is_some()); + assert!(!app.session.active().unwrap().doc.variables.objects_of("Name").is_empty()); + } + + #[test] + fn context_menu_unbinds_only_clicked_variable() { + let mut app = app_with_data(); + let bound = app.session.active().unwrap().doc.variables.objects_of("Name"); + app.run("variable.define", json!({"name": "Visible", "kind": "visibility"})).unwrap(); + app.run("variable.bind", json!({"variable": "Visible", "ids": [bound[0].0]})).unwrap(); + let before = undo_steps(&app); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + d.click(&mut app, &menu_button(&nodes, "Unbind Variable")); + let st = app.session.active().unwrap(); + assert!(st.doc.variables.objects_of("Name").is_empty()); + assert_eq!(st.doc.variables.objects_of("Visible"), bound); + assert_eq!(undo_steps(&app), before + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.variables.objects_of("Name"), bound); + } + + #[test] + fn context_menu_unbinds_both_group_and_nested_object() { + let mut app = app_with_data(); + let text = app.session.active().unwrap().doc.variables.objects_of("Name")[0]; + let rect = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [text.0, rect]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("variable.define", json!({"name": "Visible", "kind": "visibility"})).unwrap(); + // Bind separately so both the group and its child have the variable. + for id in [group, text.0] { + app.run("variable.bind", json!({"variable": "Visible", "ids": [id]})).unwrap(); + } + assert_eq!(app.session.active().unwrap().doc.variables.objects_of("Visible").len(), 2); + let before = undo_steps(&app); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Visible"); + d.click(&mut app, &menu_button(&nodes, "Unbind Variable")); + assert!(app.session.active().unwrap().doc.variables.objects_of("Visible").is_empty()); + assert_eq!(undo_steps(&app), before + 1); + assert_eq!(app.session.active().unwrap().doc.variables.objects_of("Name"), vec![text]); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.variables.objects_of("Visible").len(), 2); + } + + #[test] + fn context_menu_cannot_act_on_same_named_variable_in_another_document() { + use egui::accesskit::{Action, ActionRequest, TreeId}; + for label in ["Delete Variable", "Unbind Variable"] { + let mut app = app_with_data(); + let original = app.session.active().unwrap().doc.variables.clone(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let text = app.run("text.create", json!({"x": 10, "y": 40, "text": "Alice"})).unwrap()["id"].clone(); + app.run("variable.define", json!({"name": "Name", "kind": "text"})).unwrap(); + app.run("variable.bind", json!({"variable": "Name", "ids": [text]})).unwrap(); + let other = app.session.active().unwrap().doc.variables.clone(); + assert!(app.session.set_active(0)); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + let action = menu_button(&nodes, label); + let target_node = d + .nodes(&mut app) + .into_iter() + .find(|(_, n)| n.role() == egui::accesskit::Role::MenuItem && n.label() == action.label()) + .expect("the open menu action") + .0; + assert!(app.session.set_active(1)); + assert!(!d.nodes(&mut app).iter().any(|(id, _)| *id == target_node), "{label}: the old menu carried over"); + // A queued accessibility click must not dispatch the old menu action in the new document. + d.frame( + &mut app, + vec![egui::Event::AccessKitActionRequest(ActionRequest { + action: Action::Click, + target_node, + target_tree: TreeId::ROOT, + data: None, + })], + ); + assert_eq!(app.session.active().unwrap().doc.variables, other, "{label}: changed the second document"); + assert!(app.session.set_active(0)); + assert_eq!(app.session.active().unwrap().doc.variables, original, "{label}: changed the first document"); + } + } + + #[test] + fn context_menu_make_text_dynamic_requires_text_without_a_text_binding() { + let mut app = app_with_data(); + let text = app.session.active().unwrap().doc.variables.objects_of("Name")[0]; + app.run("select.set", json!({"ids": [text.0]})).unwrap(); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + assert!(menu_button(&nodes, "Make Text Dynamic").is_disabled()); + assert!(!menu_button(&nodes, "Make Visibility Dynamic").is_disabled()); + d.frame( + &mut app, + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ); + app.run("variable.unbind", json!({"ids": [text.0], "variable": "Name"})).unwrap(); + app.run("variable.define", json!({"name": "Visible", "kind": "visibility"})).unwrap(); + app.run("variable.bind", json!({"variable": "Visible", "ids": [text.0]})).unwrap(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + assert!(!menu_button(&nodes, "Make Text Dynamic").is_disabled(), "visibility bindings do not prevent a text variable"); + let before = undo_steps(&app); + d.click(&mut app, &menu_button(&nodes, "Make Text Dynamic")); + let vars = &app.session.active().unwrap().doc.variables; + let bound = vars.bindings.get(&text).unwrap(); + assert!(bound.contains("Visible")); + assert_eq!(vars.variables.iter().filter(|v| v.kind == VariableKind::Text && bound.contains(&v.name)).count(), 1); + assert_eq!(undo_steps(&app), before + 1); + } + + #[test] + fn context_menu_disables_edits_when_locked_and_selection_actions_when_empty() { + let mut app = app_with_data(); + app.run("variable.lock", json!({})).unwrap(); + let mut d = Driver::new(); + let nodes = open_row_menu(&mut d, &mut app, "Name"); + assert!(!menu_button(&nodes, "Select Bound Object").is_disabled()); + for label in [ + "Variable Options…", + "Unbind Variable", + "Make Text Dynamic", + "Make Visibility Dynamic", + "Make Image Dynamic", + "Make Graph Dynamic", + "Delete Variable", + ] { + assert!(menu_button(&nodes, label).is_disabled(), "{label}"); + } + let mut app = app_with_data(); + app.run("variable.define", json!({"name": "Unbound", "kind": "visibility"})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + let nodes = open_row_menu(&mut Driver::new(), &mut app, "Unbound"); + for label in + ["Select Bound Object", "Unbind Variable", "Make Text Dynamic", "Make Visibility Dynamic", "Make Image Dynamic", "Make Graph Dynamic"] + { + assert!(menu_button(&nodes, label).is_disabled(), "{label}"); + } + assert!(!menu_button(&nodes, "Delete Variable").is_disabled()); + } + fn set_names(app: &mut VectorcraftApp) -> Vec { let sets = app.run("dataset.list", json!({})).unwrap(); sets["datasets"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap_or_default().to_string()).collect() @@ -898,7 +1182,7 @@ mod tests { check(&app, ¬hing_picked, "with nothing selected or highlighted"); app.run("select.set", json!({"ids": [t]})).unwrap(); app.run("variable.highlight", json!({"variable": "Name"})).unwrap(); - check(&app, &[("variable.makeTextDynamic", true), (UNBIND, true), (DELETE_VARIABLE, true), (SELECT_BOUND, true)], "on the bound text"); + check(&app, &[("variable.makeTextDynamic", false), (UNBIND, true), (DELETE_VARIABLE, true), (SELECT_BOUND, true)], "on the bound text"); app.run("variable.lock", json!({})).unwrap(); let locked = [("variable.makeTextDynamic", false), ("variable.define", false), ("variable.rename", false), (DELETE_VARIABLE, false), (UNBIND, true)]; diff --git a/crates/ui-egui/src/plugin_runs.rs b/crates/ui-egui/src/plugin_runs.rs index f537dd91c8..8830ab7526 100644 --- a/crates/ui-egui/src/plugin_runs.rs +++ b/crates/ui-egui/src/plugin_runs.rs @@ -23,7 +23,7 @@ use std::sync::mpsc::{Receiver, TryRecvError, channel}; use serde_json::{Value, json}; use vectorcraft_engine::EngineError; use vectorcraft_engine::cmd::fileio::progress::{self, Progress}; -use vectorcraft_engine::cmd::plugin::FilterRun; +use vectorcraft_engine::cmd::plugin::{self, FilterRun}; use vectorcraft_plugins::{permissions, registry}; use crate::VectorcraftApp; @@ -75,6 +75,11 @@ pub fn start(app: &mut VectorcraftApp, p: Value) -> Result { } // Bad parameters and a missing document fail here, before anything runs. let run = FilterRun::prepare(&app.session, &p).map_err(|e| e.to_string())?; + // Typing Real-time Drawing off left out of the document is kept next, so the plug-in is given it. + let run = match plugin::keep_unapplied_typing(&mut app.session).map_err(|e| e.to_string())? { + true => FilterRun::prepare(&app.session, &p).map_err(|e| e.to_string())?, + false => run, + }; let who = format!("“{}”", run.plugin().manifest().name.trim_end_matches('…')); let mut params = p; params["ids"] = json!(run.inputs().iter().map(|i| i.0).collect::>()); @@ -141,7 +146,8 @@ fn finish(app: &mut VectorcraftApp, r: Running, done: Option) { return; } }; - if !run.current(&app.session) { + // Typing started meanwhile with Real-time Drawing off isn't in what the plug-in was given. + if !run.current(&app.session) || plugin::unapplied_typing(&app.session) { app.status(format!("{} finished, but the document or the plug-in changed meanwhile: run it again", r.who)); return; } diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index a60148af5e..903c9bdd02 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -166,7 +166,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { }; w.state = state; if let Some(request) = out.pick_color { - w.nested.open(ColorPickerDialog::from_request(request)); + w.nested.open(ColorPickerDialog::from_request(request).swatch_view(crate::dialogs::color_picker::swatch_view(app))); } if out.closed.is_none() { app.prefs = Some(w); diff --git a/crates/ui-egui/src/render_worker.rs b/crates/ui-egui/src/render_worker.rs index 9f1fcecb71..d7545f2df7 100644 --- a/crates/ui-egui/src/render_worker.rs +++ b/crates/ui-egui/src/render_worker.rs @@ -51,6 +51,9 @@ pub struct Done { /// The frame holds pixels copied from the worker's last frame ([`crate::canvas::render_job`]), /// and `ms` is the time of the copy and of the parts rendered. pub reused: bool, + /// The frame drew art in a way that depends on its size + /// ([`vectorcraft_render::FrameStats::view_sized`]): a part of it drawn on its own may differ. + pub view_sized: bool, } /// Render `job` as the worker thread does: inside the job's automation roots and deferred @@ -59,7 +62,7 @@ pub(crate) fn render(r: &mut Renderer, kept: &mut Option &'static (Vec, Vec) { if !own { by_the_menu_bar.insert(c.id); } - let group = if c.menu.is_empty() { id_group(c.id) } else { c.menu.join(" › ") }; + let group = command_group(c.id, c.menu); v.push(Entry { key: c.id.into(), label: c.label.into(), group, is_tool: false, shows_key: false }); } v.extend(crate::state::all_panels().map(|(id, label)| Entry { @@ -246,28 +246,30 @@ fn fixed_entries() -> &'static (Vec, Vec) { if !own { by_the_menu_bar.insert(id); } - tail.push(Entry { key: id.to_string(), label: label.to_string(), group: id_group(id), is_tool: false, shows_key: false }); + tail.push(Entry { key: id.to_string(), label: label.to_string(), group: command_group(id, &[]), is_tool: false, shows_key: false }); } // A command listed only because an item of the menu bar runs it can have the group and // label of another entry. When that entry is an engine command that no item of the menu bar - // runs, the command the item runs keeps the name and the other entry is shown in the group - // of its id: File › Export Selection… runs `file.exportSelection`, as the menu item does, - // and `document.exportSelection` shows as Document › Export Selection…. Otherwise the - // command is left out: Window › Learn stays the Learn panel's entry. Entries that still - // have the same name, plug-ins included, are given names of their own by - // [`distinct_names`]. + // runs, the command the item runs keeps the name and the other entry is shown in its own + // group ([`own_group`]): File › Export Selection… runs `file.exportSelection`, as the menu + // item does, and `document.exportSelection` shows as Document › Export Selection…. When + // that is the group the other entry has already, both are listed: Object › Expand… runs + // the Expand dialog, and `object.expand` shows its key. Otherwise the command is left out: + // Window › Learn stays the Learn panel's entry. Entries that still have the same name, + // plug-ins included, are given names of their own by [`distinct_names`]. let name = |e: &Entry| (e.group.clone(), e.label.clone()); - let new_names: HashSet<_> = v.iter().chain(&tail).filter(|e| by_the_menu_bar.contains(e.key.as_str())).map(name).collect(); - for e in v.iter_mut().chain(tail.iter_mut()) { - if new_names.contains(&name(e)) - && !by_the_menu_bar.contains(e.key.as_str()) + let movable = |e: &Entry| { + !by_the_menu_bar.contains(e.key.as_str()) && vectorcraft_engine::find_command(&e.key).is_some() && !menu_bar_items().contains_key(e.key.as_str()) - { - e.group = id_group(&e.key); + }; + let new_names: HashSet<_> = v.iter().chain(&tail).filter(|e| by_the_menu_bar.contains(e.key.as_str())).map(name).collect(); + for e in v.iter_mut().chain(tail.iter_mut()) { + if new_names.contains(&name(e)) && movable(e) { + e.group = own_group(&e.key); } } - let names: HashSet<_> = v.iter().chain(&tail).filter(|e| !by_the_menu_bar.contains(e.key.as_str())).map(name).collect(); + let names: HashSet<_> = v.iter().chain(&tail).filter(|e| !by_the_menu_bar.contains(e.key.as_str()) && !movable(e)).map(name).collect(); let keep = |e: &Entry| !by_the_menu_bar.contains(e.key.as_str()) || !names.contains(&name(e)); v.retain(keep); tail.retain(keep); @@ -402,6 +404,115 @@ fn name_of(e: &Entry, group: &str, label: &str) -> String { if e.shows_key { format!("{name} ({})", e.key) } else { name } } +/// The group of command `id`, whose menu path is `menu`: that path, or for a command no menu holds +/// the menu path of the item of the menu bar that runs it ([`menu_bar_path`]: Recolor Artwork… +/// goes under Edit › Edit Colors), or else [`own_group`]. +fn command_group(id: &str, menu: &[&str]) -> String { + if !menu.is_empty() { + return menu.join(" › "); + } + menu_bar_path(id).map_or_else(|| own_group(id), str::to_string) +} + +/// The group of a command that neither a menu nor an item of the menu bar holds: the menu path the +/// items of the menu bar that run the commands of its id's first two parts share (Remove Corners +/// goes under Object › Plug-ins › Path Precision Tools with Set Corners), else its [`GROUPS`] +/// entry, else [`id_group`]. +fn own_group(id: &str) -> String { + if let Some(path) = family_path(id) { + return path.to_string(); + } + GROUPS + .iter() + .find(|(key, _)| if key.ends_with('.') { id.starts_with(key) } else { id == *key }) + .map_or_else(|| id_group(id), |(_, g)| g.to_string()) +} + +/// The one menu path of the items of the menu bar that run the other commands whose id starts with +/// the first two parts of an id of three or more parts (`addon.pathtools.`). +fn family_path(id: &str) -> Option<&'static str> { + let mut parts = id.splitn(3, '.'); + let (Some(a), Some(b), Some(_)) = (parts.next(), parts.next(), parts.next()) else { return None }; + let prefix = format!("{a}.{b}."); + let mut paths = menu_bar_paths().keys().filter(|k| k.starts_with(&prefix) && k.as_str() != id).filter_map(|k| menu_bar_path(k)); + let first = paths.next()?; + paths.all(|p| p == first).then_some(first) +} + +/// The groups of the commands of Keyboard Shortcuts that no menu holds and whose id's first part +/// is no name: (id, or the start of ids when it ends with `.`; group). A panel's commands go under +/// the panel's Window menu item (Window › Layers), and a dialog's under the menu or panel that +/// opens it. +const GROUPS: &[(&str, &str)] = &[ + ("addon.", "Object › Plug-ins"), + ("app.", "Application"), + ("css.", "Window › CSS Properties"), + ("docInfo.", "Window › Document Info"), + ("imageTrace.", "Window › Image Trace"), + ("livePaint.", "Object › Live Paint"), + ("plugin.", "Object › Plug-ins"), + ("svgFilter.", "SVG Filters"), + ("svgInteractivity.", "Window › SVG Interactivity"), + ("threeD.", "Window › 3D and Materials"), + ("ui.action.", "Window › Actions"), + ("ui.actionSet.", "Window › Actions"), + ("ui.blendOptions", "Window › Properties"), + ("ui.brushObjectOptions", "Window › Brushes"), + ("ui.brushOptions", "Window › Brushes"), + ("ui.bulletsAndNumbering", "Window › Paragraph"), + ("ui.colorGroupOptions", "Window › Swatches"), + ("ui.colorGuideOptions", "Window › Color Guide"), + ("ui.colorPicker", "Color"), + ("ui.colorRgbPercent", "Window › Color"), + ("ui.corners", "Window › Transform"), + ("ui.dialogReset", "Dialogs"), + ("ui.dxfOptionsDialog", "File"), + ("ui.epsOptionsDialog", "File"), + ("ui.fileInfoDialog", "File"), + ("ui.findAndReplace", "Window › Properties"), + ("ui.findFontsInFolder", "Type"), + ("ui.hpglOptionsDialog", "File"), + ("ui.hyphenation", "Window › Paragraph"), + ("ui.javascriptFilesDialog", "Window › SVG Interactivity"), + ("ui.justification", "Window › Paragraph"), + ("ui.layerOptions", "Window › Layers"), + ("ui.layersPanelOptions", "Window › Layers"), + ("ui.loadAllStyles", "Window › Character Styles"), + ("ui.loadCharStyles", "Window › Character Styles"), + ("ui.loadParaStyles", "Window › Paragraph Styles"), + ("ui.missingFontsDialog", "Type"), + ("ui.newArtboard", "Window › Artboards"), + ("ui.newBrush", "Window › Brushes"), + ("ui.newCharStyle", "Window › Character Styles"), + ("ui.newColorGroup", "Window › Swatches"), + ("ui.newLayer", "Window › Layers"), + ("ui.newParaStyle", "Window › Paragraph Styles"), + ("ui.newSwatch", "Window › Swatches"), + ("ui.pdfSummary.", "File"), + ("ui.perspectivePlane", "View › Perspective Grid"), + ("ui.perspectiveUserPreset1.", "View › Perspective Grid › One Point Perspective"), + ("ui.perspectiveUserPreset2.", "View › Perspective Grid › Two Point Perspective"), + ("ui.perspectiveUserPreset3.", "View › Perspective Grid › Three Point Perspective"), + ("ui.placementOptionsDialog", "Window › Links"), + ("ui.rasterEffectsSettingsDialog", "Effect"), + ("ui.recolorRedo", "Edit › Edit Colors › Recolor Artwork"), + ("ui.recolorUndo", "Edit › Edit Colors › Recolor Artwork"), + ("ui.relinkDialog", "Window › Links"), + ("ui.rename", "Window › Layers"), + ("ui.retype", "Window › Properties"), + ("ui.runInstalledScript", "File › Scripts"), + ("ui.sampleScreenColor", "Color"), + ("ui.savePdfDialog", "File"), + ("ui.shortcutImportDialog", "Shortcuts"), + ("ui.simplifyAuto", "Object › Path › Simplify"), + ("ui.simplifyMoreOptions", "Object › Path › Simplify"), + ("ui.smoothAuto", "Object › Path › Smooth"), + ("ui.spotColors", "Window › Swatches"), + ("ui.symbolOptions", "Window › Symbols"), + ("ui.tateChuYokoSettings", "Window › Character"), + ("ui.warichuSettings", "Window › Character"), +]; + /// The group of a command no menu holds: the first part of its id, capitalised (`edit.x` → "Edit"). fn id_group(id: &str) -> String { let mut c = id.split('.').next().unwrap_or_default().chars(); @@ -410,7 +521,7 @@ fn id_group(id: &str) -> String { /// Gives entries that have the same group and label names of their own, and leaves the others as /// they are. It runs on the whole snapshot, plug-ins included, after [`fixed_entries`] has shown an -/// engine command in the group of its id or left out a command listed only because an item of the +/// engine command in its own group ([`own_group`]) or left out a command listed only because an item of the /// menu bar runs it: /// 1. A command that an item of the menu bar runs, as a key press would run it, is shown under /// that item's menu path ([`menu_bar_path`]): the four Other Library… commands go under Window › @@ -614,6 +725,29 @@ const NEEDS_A_PARAM: [&str; 77] = [ "type.ruby", ]; +/// UI commands with no default key, no menu bar item and a params doc whose fields are all optional +/// that a key press can run with no params: each opens its dialog for the selection, the current +/// item or the panel's selection, or reports in the status bar why it cannot. Rename names the +/// selection, Color Picker… opens for the proxy in front, Brush Options… for the selected path's +/// brush, and Layer Options for the highlighted rows. +pub(crate) const KEY_ONLY_UI: [&str; 15] = [ + "ui.rename", + "ui.colorPicker", + "ui.newSwatch", + "ui.newColorGroup", + "ui.colorGroupOptions", + "ui.newBrush", + "ui.brushOptions", + "ui.layerOptions", + "ui.corners", + "ui.placementOptionsDialog", + "ui.relinkDialog", + "ui.perspectivePlane", + "ui.bulletsAndNumbering", + "ui.missingFontsDialog", + "ui.findFontsInFolder", +]; + /// The (label, params) of each menu bar item, by command id. fn menu_bar_items() -> &'static HashMap> { static ITEMS: OnceLock>> = OnceLock::new(); @@ -704,11 +838,9 @@ fn listed_on_its_own(c: &vectorcraft_engine::CommandSpec) -> bool { /// Is UI command `id` (default key `sc`, params doc `params`) listed in Edit › Keyboard Shortcuts /// whether or not an item of the menu bar runs it? It is when it has a default key or a params doc -/// of `{}` or `{path…}`. Rename has no default key, and a key press names the selection: it needs -/// no `id`. Color Picker… has no default key either, and a key press opens it for the proxy in -/// front. +/// of `{}` or `{path…}`, or is one of [`KEY_ONLY_UI`]. fn ui_listed_on_its_own(id: &str, sc: &str, params: &str) -> bool { - !sc.is_empty() || params.starts_with("{}") || params.starts_with("{path") || id == "ui.rename" || id == "ui.colorPicker" + !sc.is_empty() || params.starts_with("{}") || params.starts_with("{path") || KEY_ONLY_UI.contains(&id) } /// Does a menu bar item run the command with no params, so that it does what its label says and opens @@ -2219,8 +2351,8 @@ mod tests { /// params, or with the one set of params all its items give) is listed in Edit › Keyboard /// Shortcuts, also when the command has no menu path of its own: Set Corners…, whose params doc /// names a field a call must give, the Perspective Grid toggles, Edit Custom Dictionary…, a - /// query, and Recolor Artwork…, a UI command. Such a command is listed in the group of its id, - /// next to the commands of its family that were listed before. A shortcut given to one survives + /// query, and Recolor Artwork…, a UI command. Such a command is listed under the menu path of + /// the item that runs it. A shortcut given to one survives /// a saved set's round trip. Find Next is left out: its menu item gives `find` empty, which the /// command rejects. When another entry has the same group and label, the command the menu item /// runs keeps the name if no menu item runs the other: File › Export Selection… is @@ -2244,7 +2376,9 @@ mod tests { assert_eq!(shown("file.exportSelection"), Some(("File".into(), "Export Selection…".into()))); assert_eq!(shown("document.exportSelection"), Some(("Document".into(), "Export Selection…".into()))); // No command listed only because an item of the menu bar runs it shares its group and label - // with another entry. + // with another entry, except an engine command that no item of the menu bar runs, whose own + // group is the same: that one shows its key. + let off_the_bar = |k: &str| vectorcraft_engine::find_command(k).is_some() && !menu_bar_items().contains_key(k); let own = |k: &str| { vectorcraft_engine::command_specs() .iter() @@ -2258,13 +2392,19 @@ mod tests { for e in v.iter().chain(tail) { names.entry((e.group.as_str(), e.label.as_str())).or_default().push(e.key.as_str()); } - let shared: Vec<_> = names.iter().filter(|(_, keys)| keys.len() > 1 && keys.iter().any(|k| !own(k))).collect(); + let shared: Vec<_> = names + .iter() + .filter(|(_, keys)| keys.len() > 1 && keys.iter().any(|k| !own(k)) && !keys.iter().filter(|k| own(k)).all(|k| off_the_bar(k))) + .collect(); assert!(shared.is_empty(), "{shared:?}"); + let keyed = |id: &str| entry(id).map(|e| (e.group, e.label, e.shows_key)); + assert_eq!(keyed("ui.expandDialog"), Some(("Object".into(), "Expand…".into(), false))); + assert_eq!(keyed("object.expand"), Some(("Object".into(), "Expand…".into(), true))); for (id, group) in [ - (crate::addons::pathtools::set_corners::COMMAND, "Addon"), - ("perspective.grid.snap", "Perspective"), - (crate::dialogs::custom_dictionary::COMMAND, "Text"), - ("ui.recolorDialog", "Ui"), + (crate::addons::pathtools::set_corners::COMMAND, "Object › Plug-ins › Path Precision Tools"), + ("perspective.grid.snap", "View › Perspective Grid"), + (crate::dialogs::custom_dictionary::COMMAND, "Edit"), + ("ui.recolorDialog", "Edit › Edit Colors"), ] { let e = entry(id).unwrap_or_else(|| panic!("{id} is listed")); assert_eq!(e.group, group, "{id}"); @@ -2575,4 +2715,46 @@ mod tests { assert!(needs_a_value("document.setUnits")); assert!(crate::palette::items().iter().all(|(_, id)| id != "document.setUnits")); } + + /// A command no menu holds is grouped under the menu path of the item of the menu bar that runs + /// it, or under the menu or panel it belongs to: no entry's group is a run-together id part + /// such as "Ui", "ImageTrace" or "ThreeD". + #[test] + fn commands_no_menu_holds_are_grouped_by_their_menu_or_panel() { + let menu_less = + |key: &str| vectorcraft_engine::find_command(key).map_or_else(|| menus::UI_COMMANDS.iter().any(|c| c.0 == key), |c| c.menu.is_empty()); + let mut names: HashSet = ["Tools", "Window"].into_iter().map(String::from).collect(); + names.extend(crate::state::all_panels().map(|(_, label)| label.to_string())); + names.extend(menus::menu_tree().into_iter().map(|(top, _)| top.to_string())); + names.extend(menu_bar_paths().values().flatten().flat_map(|(path, _)| path.split(" › ")).map(String::from)); + // A dialog's commands go under its command's label: Recolor Artwork, Character Style Options. + let labels = menus::UI_COMMANDS.iter().map(|c| c.1).chain(vectorcraft_engine::command_specs().iter().map(|c| c.label)); + names.extend(labels.map(|label| label.trim_end_matches('…').to_string())); + let mut wrong = vec![]; + for e in entries().iter().filter(|e| !e.is_tool && !e.key.contains(':') && menu_less(&e.key)) { + if let Some(path) = menu_bar_path(&e.key) + && e.group != path + { + wrong.push(format!("{}: {} is not under {path}", e.key, e.group)); + } + for part in e.group.split(" › ") { + let one_word = !part.contains(' ') && part.chars().skip(1).all(|c| !c.is_uppercase()); + if !names.contains(part) && (!one_word || ["Ui", "App", "Addon", "Css", "Plugin"].contains(&part)) { + wrong.push(format!("{}: {}", e.key, e.group)); + } + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + // Every row of GROUPS groups a listed command. + let unused: Vec<_> = GROUPS + .iter() + .filter(|(key, _)| !entries().iter().any(|e| if key.ends_with('.') { e.key.starts_with(key) } else { e.key == *key })) + .collect(); + assert!(unused.is_empty(), "{unused:?}"); + let group = |id: &str| entry(id).map(|e| e.group); + assert_eq!(group("ui.recolorDialog").as_deref(), Some("Edit › Edit Colors")); + assert_eq!(group("ui.rename").as_deref(), Some("Window › Layers")); + assert_eq!(group("ui.justification").as_deref(), Some("Window › Paragraph")); + assert_eq!(group("addon.pathtools.cornerRemove").as_deref(), Some("Object › Plug-ins › Path Precision Tools")); + } } diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index eaa0065ba4..decf0abcfa 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -30,13 +30,14 @@ pub(crate) fn run_fired(app: &mut VectorcraftApp, ctx: &egui::Context, fired: &F return; } // A menu's Cut, Copy or Paste that no framework part took, while an egui text field has the keys, goes to that - // field as its clipboard event, as its keys would; Paste pastes the text of a Copy's formats, written first. + // field as its clipboard event, as its keys would; Paste pastes the text of a Copy's formats, written first, or + // nothing when they could not be written and have no text ([`VectorcraftApp::field_paste_text`]). if fired.source == FireSource::Menu && let Some(field) = ctx.memory(|m| m.focused()).filter(|&id| egui::TextEdit::load_state(ctx, id).is_some()) && let Some(event) = match fired.command.id.as_str() { "edit.copy" => Some(egui::Event::Copy), "edit.cut" => Some(egui::Event::Cut), - "edit.paste" | "edit.pasteWithoutFormatting" => app.written_clipboard_text().map(egui::Event::Paste), + "edit.paste" | "edit.pasteWithoutFormatting" => app.field_paste_text().map(egui::Event::Paste), _ => None, } { diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index cabde4b445..491b075729 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1839,3 +1839,26 @@ fn a_filter_plugin_row_translates_its_path_and_not_its_name() { assert_eq!(filter, format!("{path} › Group")); assert_eq!(command, format!("{path} › {}", crate::i18n::tr(zh, "Group"))); } + +/// A UI command whose params are all optional and that no item of the menu bar runs can be given a +/// key: Keyboard Shortcuts lists it, and the key opens its dialog or says in the status bar why it +/// cannot. +#[test] +fn a_key_runs_a_ui_command_whose_params_are_all_optional() { + for id in crate::shortcut_editor::KEY_ONLY_UI { + let mut app = app_with_a_selected_rectangle(); + let listed = app.run("shortcuts.list", json!({"query": id})).unwrap(); + assert!(listed.as_array().is_some_and(|rows| rows.iter().any(|r| r["id"] == id)), "{id} is listed: {listed}"); + // Rename edits the name in place and Color Picker… opens the framework's picker; other tests + // check what they open. + if ["ui.rename", "ui.colorPicker"].contains(&id) { + continue; + } + let ctx = ready(&mut app); + bind(&mut app, id, "Cmd+Alt+Shift+F12"); + app.ui.status.clear(); + key_frame(&mut app, &ctx, tap(Key::F12, cmd() | Modifiers::ALT | Modifiers::SHIFT)); + key_frame(&mut app, &ctx, vec![]); + assert!(dialog_kind(&app).is_some() || !app.ui.status.is_empty(), "{id}: the key opens a dialog or reports why not"); + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index b37805eb57..1ed56d8faa 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -156,10 +156,16 @@ impl View { /// Takes the view the canvas reports back, the inverse of [`Self::canvas`]. pub fn set_canvas(&mut self, view: &CanvasView, ui_scaling: f32) { self.center = view.center; - self.zoom = view.zoom * f64::from(ui_scaling); + self.zoom = Self::zoom_of_canvas(view, ui_scaling); self.rotation = view.rotation; self.rect = view.rect; } + + /// The zoom [`Self::zoom`] holds for the canvas view `view` at `ui_scaling`, the inverse of the + /// zoom in [`Self::canvas`]: the zoom `view.setZoom` and the View menu set and the status bar shows. + pub fn zoom_of_canvas(view: &CanvasView, ui_scaling: f32) -> f64 { + view.zoom * f64::from(ui_scaling) + } } /// The status bar's angle menu and View › Rotate View list these preset view angles, each as diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index cc214b08dd..9371e118fd 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -85,8 +85,8 @@ pub(crate) struct Publishing { /// The latest one's formats wait to be written. pending: bool, /// The latest one's formats could not be written: what the system clipboard's text was when the - /// write failed, and the text of those formats. - unwritten: Option<(Held, String)>, + /// write failed, and the text of those formats, if they have text. + unwritten: Option<(Held, Option)>, /// The status bar's message when the latest one ran, with [`crate::state::UiState::status_sets`] /// then. Its formats' notes replace the message only while the status bar still shows it and /// nothing has set the status since. @@ -120,6 +120,22 @@ impl Publishing { fn shows_status(&self, ui: &crate::state::UiState) -> bool { ui.status == self.status.0 && ui.status_sets == self.status.1 } + + /// Is the latest Copy or Cut one whose formats could not be written to `cb`, with nothing + /// copied since ([`VectorcraftApp::holds_unwritten_copy`])? Different text read from `cb` shows + /// a later copy: the record of the failed write is then dropped, so the clipboard holding the + /// older text again later does not bring it back. Text that could not be read keeps the record. + fn holds_unwritten(&mut self, cb: &mut Clipboard) -> bool { + let Some((held, _)) = &self.unwritten else { return false }; + let now = held_text(cb); + if now == *held { + return true; + } + if now.is_some() { + self.unwritten = None; + } + false + } } /// The status bar's line after a Copy (or with `cut`, a Cut) whose formats have `n` notes, the @@ -185,14 +201,31 @@ impl VectorcraftApp { || self.clipboard.holds_ours() } + /// Is the latest Copy or Cut one whose formats could not be written to the system clipboard, + /// with nothing copied since? Paste then takes the internal clipboard, and a paste into type or + /// a text field takes that copy's text (nothing when its formats have no text), until another + /// app copies something. A copy is noticed only when it changes the clipboard's text, so the + /// copy is kept only when the clipboard held text when the write failed. When it held only a + /// picture, or nothing that could be read, Paste takes what the clipboard holds. + fn holds_unwritten_copy(&mut self) -> bool { + self.clipboard_publishing.holds_unwritten(&mut self.clipboard) + } + /// The text of the latest Copy or Cut whose formats could not be written to the system - /// clipboard, while nothing has been copied since that Copy or Cut. A paste into type or a text - /// field takes this text until another app copies something. A copy is noticed only when it - /// changes the clipboard's text, so the copy is kept only when the clipboard held text when the - /// write failed. + /// clipboard, while nothing has been copied since that Copy or Cut + /// ([`Self::holds_unwritten_copy`]). pub(crate) fn unwritten_clipboard_text(&mut self) -> Option { - let (held, text) = self.clipboard_publishing.unwritten.as_ref()?; - (held_text(&mut self.clipboard) == *held).then(|| text.clone()) + self.clipboard_publishing.unwritten.as_ref()?.1.as_ref()?; + self.unwritten_copy().flatten() + } + + /// While [`Self::holds_unwritten_copy`]: the text of that copy's formats, `None` inside when + /// they have no text. + fn unwritten_copy(&mut self) -> Option> { + if !self.holds_unwritten_copy() { + return None; + } + self.clipboard_publishing.unwritten.as_ref().map(|(_, text)| text.clone()) } /// After Copy or Cut: offer the copied objects to other apps. The background worker makes the @@ -279,8 +312,8 @@ impl VectorcraftApp { /// Writes `formats` to the system clipboard; `before` is the clipboard's text at the Copy or Cut. /// When that fails, another app may hold the clipboard open: it keeps what it held (or what the - /// failed write left), and a paste into text takes this copy's text until something else is - /// copied ([`Self::unwritten_clipboard_text`]). + /// failed write left). Until something else is copied, Paste takes this copy, and a paste into + /// text takes its text ([`Self::holds_unwritten_copy`]). fn write_formats(&mut self, formats: &[Flavor], before: &Held) -> Result { let cb = &mut self.clipboard; let before_write = held_text(cb); @@ -306,7 +339,7 @@ impl VectorcraftApp { // A clipboard with no text can't show a later copy of a picture, or tell an empty clipboard // from one that couldn't be read: unless it held text the write emptied, and it reads. let trackable = held.is_some() || (before_write.is_some() && cb.read(&[TEXT]).is_ok()); - self.clipboard_publishing.unwritten = text.filter(|_| current && left_by_write && trackable).map(|text| (held, text)); + self.clipboard_publishing.unwritten = (current && left_by_write && trackable).then_some((held, text)); Err(e.to_string()) } @@ -389,17 +422,20 @@ impl VectorcraftApp { let waited = ctx.data(|d| d.get_temp::(egui::Id::unique("clipboard.pending-at-tick"))).unwrap_or(false); ctx.data_mut(|d| d.remove::(egui::Id::unique("clipboard.pending-at-tick"))); if !(self.clipboard_publishing.pending || waited) { - // A copy whose formats could not be written: a paste takes its text, not the text the - // clipboard kept ([`Self::unwritten_clipboard_text`]). + // A copy whose formats could not be written: a paste takes its text, or nothing when + // they have none, not the text the clipboard kept ([`Self::unwritten_copy`]). let pasting = textless || ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Paste(_)))); - if pasting && let Some(text) = self.unwritten_clipboard_text() { + if pasting && let Some(text) = self.unwritten_copy() { ctx.input_mut(|i| { - for e in &mut i.events { - if let egui::Event::Paste(t) = e { - t.clone_from(&text); + i.events.retain_mut(|e| match (e, &text) { + (egui::Event::Paste(t), Some(text)) => { + t.clone_from(text); + true } - } - if textless { + (egui::Event::Paste(_), None) => false, + _ => true, + }); + if textless && let Some(text) = text { i.events.insert(0, egui::Event::Paste(text)); } }); @@ -474,7 +510,10 @@ impl VectorcraftApp { // A picture or file the host read from the paste. Some(f) if f.mime != TEXT => import_command(&f, center), _ if self.clipboard.readable_any_time() => { - if self.clipboard_publishing.pending || self.clipboard.holds_ours() { + // After a Copy or Cut whose formats could not be written, with nothing copied + // since, what the clipboard still holds is older than the internal clipboard. + let publishing = &mut self.clipboard_publishing; + if publishing.pending || publishing.holds_unwritten(&mut self.clipboard) || self.clipboard.holds_ours() { return Ok(None); } // Art and text load at once, so a paste that waits behind another takes them as it was given; only a @@ -554,12 +593,24 @@ impl VectorcraftApp { } /// The text on the system clipboard once the formats a Copy or Cut is making are written, for a - /// paste into a text field or type. When they could not be written, their text - /// ([`Self::unwritten_clipboard_text`]). + /// paste into a text field or type. When they could not be written, their text, or `None` when + /// they have none ([`Self::unwritten_copy`]). pub(crate) fn written_clipboard_text(&mut self) -> Option { // Only other copies' formats are ahead of them on the worker ([`Self::publish_clipboard`]). background::wait_until(self, |app| !app.clipboard_publishing.pending); - self.unwritten_clipboard_text().or_else(|| self.system_clipboard_text()) + self.unwritten_copy().unwrap_or_else(|| self.system_clipboard_text()) + } + + /// The text a paste from the Edit menu gives a focused text field ([`Self::written_clipboard_text`]): + /// empty when the formats of a Copy or Cut could not be written and have no text, so the field + /// takes nothing and the art is not pasted onto the canvas. `None` when the system clipboard + /// holds no text. + pub(crate) fn field_paste_text(&mut self) -> Option { + background::wait_until(self, |app| !app.clipboard_publishing.pending); + match self.unwritten_copy() { + Some(text) => Some(text.unwrap_or_default()), + None => self.system_clipboard_text(), + } } /// The text on the system clipboard, if any. diff --git a/crates/ui-egui/src/tests/clipboard.rs b/crates/ui-egui/src/tests/clipboard.rs index f54e222b98..240a578ac5 100644 --- a/crates/ui-egui/src/tests/clipboard.rs +++ b/crates/ui-egui/src/tests/clipboard.rs @@ -474,6 +474,49 @@ fn type_paste_drops_a_refused_copy_it_cannot_track() { assert_eq!(paste_at(&mut app, 5), "Own: "); } +/// After a Copy whose formats have no text (On Copy: Include SVG Code off) and could not be +/// written, a paste into type takes nothing, from the menu or a paste event, not the text another +/// app left on the clipboard. A later copy in another app still pastes. +#[test] +fn a_paste_into_type_after_a_refused_textless_copy_takes_nothing() { + use vectorcraft_engine::cmd::clipboard::TEXT; + let _guard = TEST_CLIP_LOCK.lock().unwrap(); + let (mut app, board) = super::sysclip::app(); + run(&mut app, "prefs.set", json!({"key": "copyAsSvg", "value": false})); + let rect = run(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 20}))["id"].clone(); + run(&mut app, "select.set", json!({"ids": [rect]})); + super::sysclip::copy_elsewhere(&board, vec![(TEXT, b"Old".to_vec())]); + super::sysclip::refuse_writes(&board, true); + run(&mut app, "edit.copy", json!({})); + crate::background::wait_all(&mut app); + super::sysclip::refuse_writes(&board, false); + + let destination = + run(&mut app, "text.create", json!({"x": 20, "y": 60, "text": "Own: ", "size": 12, "color": "#000000"}))["id"].as_u64().unwrap(); + let v = app.view_info(); + let text = |app: &VectorcraftApp| { + let node = app.session.doc().unwrap().doc.node(NodeId(destination)).unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { panic!() }; + t.plain_text() + }; + let place = |app: &mut VectorcraftApp| { + app.session.select_tool("selection", v).unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": destination, "start": 5, "end": 5})); + }; + place(&mut app); + crate::panels::character::intercept_text_command(&mut app, "edit.paste"); + assert_eq!(text(&app), "Own: ", "the menu's Paste"); + place(&mut app); + super::sysclip::frame(&mut app, vec![egui::Event::Paste("Old".into())]); + assert_eq!(text(&app), "Own: ", "a paste event"); + + super::sysclip::copy_elsewhere(&board, vec![(TEXT, b"New".to_vec())]); + place(&mut app); + crate::panels::character::intercept_text_command(&mut app, "edit.paste"); + assert_eq!(text(&app), "Own: New", "the later copy"); +} + #[test] fn a_paste_event_waiting_on_a_refused_copy_pastes_that_copy() { let _guard = TEST_CLIP_LOCK.lock().unwrap(); diff --git a/crates/ui-egui/src/tests/contextmenu.rs b/crates/ui-egui/src/tests/contextmenu.rs index 2ec147e593..441817c8b8 100644 --- a/crates/ui-egui/src/tests/contextmenu.rs +++ b/crates/ui-egui/src/tests/contextmenu.rs @@ -134,6 +134,128 @@ fn right_click_on_empty_canvas_offers_the_view_and_selects_nothing() { assert_eq!(app.session.active().unwrap().doc.art_bounds(), None); } +/// The document point at the centre of the canvas view, where a key request reports itself. +fn view_centre(app: &VectorcraftApp) -> Point { + let view = app.canvas_view().unwrap(); + view.to_doc(view.rect.center()) +} + +/// `key` with `modifiers`, pressed on the focused canvas, then a frame to show the result. +fn menu_key(app: &mut VectorcraftApp, ctx: &egui::Context, key: egui::Key, modifiers: egui::Modifiers) { + frame(app, ctx, vec![Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }]); + frame(app, ctx, vec![]); +} + +/// Rectangle A, selected with a click (which also gives the canvas the keyboard focus), and an unselected +/// rectangle B under the view's centre with a locked rectangle over it. +fn selection_away_from_the_centre(app: &mut VectorcraftApp, ctx: &egui::Context) -> (NodeId, NodeId) { + let a = rect(app, 0.0, 0.0); + frame(app, ctx, vec![]); + let c = view_centre(app); + let b = rect(app, c.x - 50.0, c.y - 50.0); + let locked = rect(app, c.x - 25.0, c.y - 25.0); + app.run("layer.setProps", json!({"ids": [locked.0], "locked": true})).unwrap(); + app.run("select.none", json!({})).unwrap(); + let p = screen(app, 50.0, 50.0); + click(app, ctx, p, PointerButton::Primary); + assert_eq!(app.session.active().unwrap().selection.objects, [a]); + (a, b) +} + +/// Asserts the menu opened for `a` as selected, at a point over it, without what lies under the view's centre. +fn opened_for_the_selection(app: &VectorcraftApp, a: NodeId) { + assert_eq!(app.session.active().unwrap().selection.objects, [a], "a key request keeps the selection"); + let at = app.ui.context_menu_at.expect("the menu is open"); + let over_a = Rect::from_two_pos(screen(app, 0.0, 0.0), screen(app, 100.0, 100.0)); + assert!(over_a.contains(at), "the menu opens at the selection: {at:?} in {over_a:?}"); + assert!(has(app, "Arrange") && has_command(app, "object.arrange.bringToFront"), "{:?}", labels(app)); + assert!(app.ui.context_locked.is_none() && !has(app, "Unlock"), "nothing under the view's centre is measured"); +} + +#[test] +fn shift_f10_opens_the_menu_for_the_selection_without_changing_it() { + let mut app = app(); + let ctx = crate::testing::ui_context(); + let (a, _) = selection_away_from_the_centre(&mut app, &ctx); + menu_key(&mut app, &ctx, egui::Key::F10, egui::Modifiers::SHIFT); + opened_for_the_selection(&app, a); +} + +#[cfg(not(target_os = "macos"))] +#[test] +fn menu_key_opens_the_menu_for_the_selection_without_changing_it() { + let mut app = app(); + let ctx = crate::testing::ui_context(); + let (a, _) = selection_away_from_the_centre(&mut app, &ctx); + menu_key(&mut app, &ctx, egui::Key::Menu, egui::Modifiers::NONE); + opened_for_the_selection(&app, a); +} + +/// With nothing selected, Shift+F10 opens the menu at the view's centre and selects nothing, even over an object. +#[test] +fn shift_f10_with_nothing_selected_opens_the_menu_at_the_view_centre() { + let mut app = app(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + let c = view_centre(&app); + rect(&mut app, c.x - 50.0, c.y - 50.0); + app.run("select.none", json!({})).unwrap(); + // A click on the empty artboard gives the canvas the focus and keeps the selection empty. + let p = screen(&app, 380.0, 280.0); + click(&mut app, &ctx, p, PointerButton::Primary); + assert!(app.session.active().unwrap().selection.objects.is_empty()); + menu_key(&mut app, &ctx, egui::Key::F10, egui::Modifiers::SHIFT); + assert!(app.session.active().unwrap().selection.objects.is_empty(), "the object under the view's centre stays unselected"); + let at = app.ui.context_menu_at.expect("the menu is open"); + let centre = app.canvas_view().unwrap().rect.center(); + assert!(at.distance(centre) < 0.5, "{at:?} at {centre:?}"); + assert!(has(&app, "Select All") && !has(&app, "Arrange"), "{:?}", labels(&app)); +} + +/// With the Artboard tool, Shift+F10 opens the menu for the selected artboard, at it, and selects no other artboard; +/// the menu's Paste would put artboards on it. +#[test] +fn shift_f10_with_the_artboard_tool_keeps_the_selected_artboard() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + crate::menus::invoke(&mut app, "view.fitAll", json!({})); + for _ in 0..3 { + frame(&mut app, &ctx, vec![]); + } + let boards: Vec = app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let centre = view_centre(&app); + let away = boards.iter().position(|r| !r.contains(centre)).unwrap(); + app.select_tool("artboard"); + // A click on the artboard selects it and gives the canvas the focus. + let c = boards[away].center(); + let p = screen(&app, c.x, c.y); + click(&mut app, &ctx, p, PointerButton::Primary); + assert_eq!(crate::panels::artboards::picked(&app, boards.len()), [away]); + menu_key(&mut app, &ctx, egui::Key::F10, egui::Modifiers::SHIFT); + assert_eq!(crate::panels::artboards::picked(&app, boards.len()), [away], "a key request keeps the selected artboard"); + let at = app.ui.context_menu_at.expect("the menu is open"); + let on_board = Rect::from_two_pos(screen(&app, boards[away].x0, boards[away].y0), screen(&app, boards[away].x1, boards[away].y1)); + assert!(on_board.contains(at), "the menu opens at the selected artboard: {at:?} in {on_board:?}"); + let pasted_at = app.ui.context_artboards.as_ref().map(|f| f.at).expect("the menu's artboard facts"); + assert!(boards[away].contains(pasted_at), "{pasted_at:?} on {:?}", boards[away]); +} + +/// A right-click on an object that is not selected still selects it, with another object selected before. +#[test] +fn right_click_still_selects_the_object_under_the_pointer() { + let mut app = app(); + let ctx = crate::testing::ui_context(); + let (_, b) = selection_away_from_the_centre(&mut app, &ctx); + // Inside B, outside the locked rectangle over its middle. + let c = view_centre(&app); + let p = screen(&app, c.x - 40.0, c.y - 40.0); + click(&mut app, &ctx, p, PointerButton::Secondary); + assert_eq!(app.session.active().unwrap().selection.objects, [b]); + assert!(app.ui.context_menu_at.is_some_and(|at| at.distance(p) < 0.5), "the menu opens at the pointer"); +} + /// A right-click over a locked object adds an Unlock submenu that lists the object by its name; once /// the menu is closed, the menu lists no Unlock items. #[test] diff --git a/crates/ui-egui/src/tests/nativemenu.rs b/crates/ui-egui/src/tests/nativemenu.rs index 8a13fbda07..f1f6bcd09c 100644 --- a/crates/ui-egui/src/tests/nativemenu.rs +++ b/crates/ui-egui/src/tests/nativemenu.rs @@ -63,6 +63,57 @@ fn settings_lists_every_preferences_page() { assert_eq!(crate::prefs_dialog::page(&m.app), Some("Units")); } +/// The default shortcut of command `id`, as the shortcut editor lists it. +fn default_chord(id: &str) -> Option { + crate::shortcut_editor::default_command_shortcut(id).and_then(crate::keymap::stored::parse_vc) +} + +/// The Settings › General… item of `bar`. +fn general(bar: &MenuBar) -> &Item { + let page = PREF_CATEGORIES[0]; + bar.items().into_iter().find(|it| it.command.id == "edit.preferences" && it.command.params["category"] == page).expect("Settings › General…") +} + +/// The menu bar hands every item its command's shortcut, so Save, Open, Undo and Group show their keys and AppKit +/// takes them as key equivalents. +#[test] +fn native_items_carry_their_commands_shortcuts() { + let m = Mac::new(true); + let bar = m.fake.last(); + for id in ["file.save", "file.open", "edit.undo", "object.group"] { + let chord = default_chord(id); + assert!(chord.is_some(), "{id} has a default shortcut"); + assert_eq!(find(&bar, id).shortcut, chord, "{id}"); + } +} + +/// A command bound to another key shows that key in the menu bar, and its old key is no longer the item's. +#[test] +fn a_rebound_command_shows_its_new_key_in_the_menu_bar() { + let mut m = Mac::new(true); + let old = default_chord("object.group"); + m.app.run("shortcuts.set", json!({"id": "object.group", "shortcut": "Cmd+Alt+Shift+F8"})).unwrap(); + m.frame(vec![]); + m.frame(vec![]); + let shown = find(&m.fake.last(), "object.group").shortcut; + assert_eq!(shown, Chord::parse("Cmd+Alt+Shift+F8").ok()); + assert_ne!(shown, old); +} + +/// Settings › General… carries Preferences' shortcut as the user set it, not the default one. +#[test] +fn settings_general_follows_a_rebound_preferences() { + let mut m = Mac::new(true); + let old = default_chord("edit.preferences"); + assert_eq!(general(&m.fake.last()).shortcut, old); + m.app.run("shortcuts.set", json!({"id": "edit.preferences", "shortcut": "Cmd+Alt+Shift+F8"})).unwrap(); + m.frame(vec![]); + m.frame(vec![]); + let shown = general(&m.fake.last()).shortcut; + assert_eq!(shown, Chord::parse("Cmd+Alt+Shift+F8").ok()); + assert_ne!(shown, old); +} + /// A native menu can't turn a plain item into a check item in place: the app's read of the menus /// is guarded by a state key, and these tests count the reads through a fake backend. /// diff --git a/crates/ui-egui/src/tests/panel_harness.rs b/crates/ui-egui/src/tests/panel_harness.rs index 0b36cec615..9c61500431 100644 --- a/crates/ui-egui/src/tests/panel_harness.rs +++ b/crates/ui-egui/src/tests/panel_harness.rs @@ -6,6 +6,7 @@ use std::{ cell::{RefCell, RefMut}, + collections::HashMap, rc::Rc, }; @@ -13,7 +14,8 @@ use craft::behavior::PartRef; use craft::ui::runtime::frame::take_output; use craft::ui::testing::pointer::part_rect_of_node; use craft::ui::testing::{Fixture, Target}; -use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, Ui, Vec2, vec2}; +use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, Ui, Vec2, pos2, vec2}; +use serde_json::json; use crate::VectorcraftApp; @@ -361,3 +363,103 @@ impl Panel { self.fixture.tree().focused_key() == self.look(name).node } } + +/// Where [`floated`] shows a panel in the app window. +#[derive(Clone, Copy, Debug)] +pub(crate) enum Place { + /// Docked in its column. + Docked, + /// Floating at x 520, this many points wide. + Floating(f32), +} + +/// A panel as one frame of the whole app window drew it. +pub(crate) struct Shown { + /// The panel's body. + pub(crate) body: Rect, + /// The name and rect of every named node in the body. + pub(crate) nodes: Vec<(String, Rect)>, + /// Each catalog string asked for, with the text the panel's language shows for it. + names: Vec<(String, String)>, +} + +impl Shown { + /// The rects of the nodes named `name` (a catalog string asked for). + pub(crate) fn rects(&self, name: &str) -> Vec { + let shown = self.names.iter().find(|(asked, _)| asked == name).map_or(name, |(_, shown)| shown.as_str()); + let found: Vec = self.nodes.iter().filter(|(label, _)| label == shown).map(|(_, r)| *r).collect(); + assert!(!found.is_empty(), "the panel shows no {shown:?}"); + found + } + + /// The nodes of `nodes` that reach past either side of the body, each with its rect. + pub(crate) fn past(&self, nodes: impl IntoIterator) -> Vec { + let outside = |r: &Rect| r.left() < self.body.left() - 0.5 || r.right() > self.body.right() + 0.5; + nodes.into_iter().filter(|(_, r)| outside(r)).map(|(name, r)| format!("{name} at {r:?}")).collect() + } + + /// The nodes named each of `names` (catalog strings asked for) that reach past either side of the body, each with + /// its rect. + pub(crate) fn past_named(&self, names: &[&str]) -> Vec { + self.past(names.iter().flat_map(|name| self.rects(name).into_iter().map(|r| ((*name).to_owned(), r)))) + } + + /// The vertical middles of the nodes named `names`, in order. + pub(crate) fn middles(&self, names: &[&str]) -> Vec { + names.iter().flat_map(|name| self.rects(name)).map(|r| r.center().y).collect() + } +} + +/// Panel `panel` of `app` shown at `place` in the whole app window (1440 by 900 pt), drawn in `lang`, with the catalog +/// strings `names` as `lang` shows them. The test sets `app` up before the call. A floating panel's body is the tab +/// panel at the left edge the float asked for; a docked panel's body is the tab panel that shows every one of `names`. +pub(crate) fn floated(mut app: VectorcraftApp, panel: &str, lang: &str, place: Place, names: &[&str]) -> Shown { + use egui::accesskit::{Node, NodeId, Role}; + const AT: f32 = 520.0; + app.session.prefs.interface_language = lang.into(); + app.run("window.panel", json!({ "panel": panel })).unwrap(); + match place { + Place::Docked => app.run("window.panel.dock", json!({ "panel": panel })).unwrap(), + Place::Floating(width) => app.run("window.panel.float", json!({ "panel": panel, "x": AT, "y": 120, "width": width, "height": 700 })).unwrap(), + }; + app.run("window.panel.activate", json!({ "panel": panel })).unwrap(); + let ctx = crate::testing::ui_context(); + ctx.enable_accesskit(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 900.0)); + let mut nodes: Vec<(NodeId, Node)> = Vec::new(); + for at in 1..=8 { + let input = egui::RawInput { time: Some(f64::from(at) * 0.1), screen_rect: Some(screen), ..Default::default() }; + let out = crate::testing::app_frame(&mut app, &ctx, input); + nodes = out.platform_output.accesskit_update.map_or_else(Vec::new, |update| update.nodes); + } + // The frames set the language from the preference; the names are looked up in it before English is put back. + let names: Vec<(String, String)> = names.iter().map(|name| ((*name).to_owned(), crate::i18n::t(name).to_owned())).collect(); + crate::i18n::set_current(crate::i18n::Lang::EN); + let rect = |node: &Node| node.bounds().map(|b| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32))); + let by_id: HashMap = nodes.iter().map(|(id, n)| (*id, n)).collect(); + let under = |root: NodeId| { + let mut found = Vec::new(); + let mut todo = vec![root]; + while let Some(id) = todo.pop() { + let Some(node) = by_id.get(&id) else { continue }; + if let (Some(label), Some(r)) = (node.label(), rect(node)) { + found.push((label.to_owned(), r)); + } + todo.extend(node.children().iter().copied()); + } + found + }; + let mut bodies = nodes.iter().filter(|(_, n)| n.role() == Role::TabPanel).filter_map(|(id, n)| Some((rect(n)?, under(*id)))); + let found = match place { + Place::Docked => { + assert!(!names.is_empty(), "a docked panel is found by the names it shows"); + bodies.find(|(_, named)| names.iter().all(|(_, shown)| named.iter().any(|(label, _)| label == shown))) + } + Place::Floating(_) => bodies.find(|(r, _)| (r.left() - AT).abs() < 1.0), + }; + let (body, nodes) = found.unwrap_or_else(|| panic!("no {panel} panel at {place:?} in {lang}")); + if let Place::Floating(width) = place { + assert!(body.width() <= width + 1.0, "{panel}'s body {body:?} is wider than the {width} the float asked for"); + } + Shown { body, nodes, names } +} diff --git a/crates/ui-egui/src/tests/plugin_runs.rs b/crates/ui-egui/src/tests/plugin_runs.rs index ed161e797f..ef910a800e 100644 --- a/crates/ui-egui/src/tests/plugin_runs.rs +++ b/crates/ui-egui/src/tests/plugin_runs.rs @@ -201,6 +201,69 @@ fn a_heavy_filter_s_result_needs_the_document_as_it_was() { assert_eq!(app.ui.status, format!("“Test {id}” finished, but the document or the plug-in changed meanwhile: run it again")); } +/// A heavy filter that writes type, run while typing is in progress with Real-time Drawing off: +/// the typing is kept before the run starts, so the plug-in is given the typed text and its result +/// applies once it is done. A run that can't start keeps no typing. Typing started with Real-time +/// Drawing off while it runs isn't in what it was given: nothing changes, and the status bar says +/// to run it again. +#[test] +fn a_heavy_filter_is_given_the_typing_in_progress() { + use vectorcraft_doc::{NodeId, NodeKind}; + use vectorcraft_engine::ViewInfo; + use vectorcraft_engine::tools::{PointerEvent, PointerKind}; + let id = "test.ui.heavy.typing"; + let plain = |app: &VectorcraftApp, t: NodeId| match &app.session.doc().unwrap().doc.node(t).unwrap().kind { + NodeKind::Text(x) => x.plain_text(), + _ => panic!("type"), + }; + // Clicks into the end of `t` with the Type tool and types `text`. + let type_into = |app: &mut VectorcraftApp, t: NodeId, text: &str| { + let v = ViewInfo::default(); + app.session.select_tool("type", v).unwrap(); + let b = app.session.doc().unwrap().doc.bounds_of(&[t], false).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(k, b.x1 - 1.0, b.center().y), v).unwrap(); + } + app.session.tool_text(text, v).unwrap(); + }; + let mut app = app(); + app.session.prefs.real_time_drawing = false; + let t = NodeId(app.run("text.create", json!({"x": 100, "y": 100, "text": "A", "size": 20})).unwrap()["id"].as_u64().unwrap()); + let style = match &app.session.doc().unwrap().doc.node(t).unwrap().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(); + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","kind":"filter","budget":"heavy","api":3,"permissions":["doc.read","doc.write"],"inputs":["type"],"writes":["type"]}}"# + ); + // It adds "!" to the text it is given: "AB" or, given only "A", "A". + let src = tpl::when_given_else(&manifest, tpl::Given::Input, r#""AB""#, &retyped("AB!"), &retyped("A!")); + let data = vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap()); + app.run("plugin.install", json!({"dataBase64": data, "allowHeavy": true, "grant": ["doc.read", "doc.write"]})).unwrap(); + type_into(&mut app, t, "B"); + assert_eq!(plain(&app, t), "A", "Real-time Drawing off leaves the typing out of the document"); + // A run that can't start leaves the typing in progress, out of the document. + let undo = app.session.doc().unwrap().history.undo.len(); + assert!(plugin_runs::start(&mut app, json!({"id": "test.ui.heavy.missing", "ids": [t.0]})).is_err()); + assert_eq!(plain(&app, t), "A", "a run that can't start keeps no typing"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + assert!(app.session.in_interaction(), "the typing is still in progress"); + let p = json!({"id": id, "ids": [t.0]}); + assert_eq!(plugin_runs::start(&mut app, p.clone()).unwrap()["background"], true); + assert_eq!(plain(&app, t), "AB", "the typing is kept before the run starts"); + finish_runs(&mut app); + assert_eq!(plain(&app, t), "AB!", "{}", app.ui.status); + assert!(app.ui.status.is_empty(), "{}", app.ui.status); + // Typing started while it runs, Real-time Drawing off. + plugin_runs::start(&mut app, p).unwrap(); + type_into(&mut app, t, "C"); + let doc = app.session.doc().unwrap().doc.clone(); + finish_runs(&mut app); + assert_eq!(app.session.doc().unwrap().doc, doc, "nothing changed"); + assert_eq!(app.ui.status, format!("“Test {id}” finished, but the document or the plug-in changed meanwhile: run it again")); +} + /// The progress window is the run's: headed by it, with Cancel and Continue in Background; Cancel /// stops the run, which changes nothing, and the window goes. #[test] diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index f904500cdf..b56303f960 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -276,6 +276,25 @@ fn the_dialog_reduces_previews_and_applies_as_one_undo_step() { assert_eq!(colors(&mut r.app()), 5); } +/// Enter in the field that has the focus is OK: the color group is made with the name typed, and the dialog closes. +#[test] +fn enter_in_a_field_is_ok() { + let mut r = open(app(), json!({"colors": ["#ff8000", "#0080ff"]})); + r.settled(); + r.set("groupName", json!("Enter Group")).unwrap(); + r.settled(); + r.click_label("Color Group:"); + r.settled(); + assert!(r.focused().is_some(), "a field of the dialog has the focus"); + let groups = r.app().session.doc().unwrap().doc.swatch_groups.len(); + key(&mut r, Key::Enter); + assert!(!r.is_open(), "Enter closes Recolor Artwork"); + let app = r.app(); + let doc = &app.session.doc().unwrap().doc; + assert_eq!(doc.swatch_groups.len(), groups + 1, "Enter makes the color group, as OK does"); + assert_eq!(doc.swatch_groups.last().map(|g| g.name.as_str()), Some("Enter Group")); +} + #[test] fn presets_open_colour_jobs_and_libraries_and_both_tabs_draw() { let mut app = app(); @@ -1318,6 +1337,37 @@ fn row_context_menu_pick_from_swatches_and_limit_to_library() { } } +/// A Color Picker opened over the dialog, on its color models, has the Color Swatches button that +/// switches it to the swatches. +#[test] +fn a_picker_over_the_dialog_offers_the_color_swatches_view() { + let mut r = edit(&["#ff0000", "#0000ff"]); + let at = marker(&r, 0); + right_click(&mut r, at); + tap(&mut r, "Color Picker"); + assert!(picker(&r).is_some(), "the marker's Color Picker opens the picker"); + assert!(has(&r, "Color Swatches"), "the picker has the Color Swatches button"); + tap(&mut r, "Color Swatches"); + assert!(has(&r, "Color Models"), "the button switches the picker to its swatches"); +} + +/// Pick from Swatches opens the picker on its swatches, showing the library that Limit to Library +/// limits the rows to. +#[test] +fn pick_from_swatches_shows_the_limit_to_library_library() { + let mut app = app(); + art(&mut app, &["#ff0000", "#0000ff"]); + let lib = library_of(&mut app, &[json!({"name": "Lib Teal", "color": "#008080"}), json!({"name": "Lib Plum", "color": "#8e4585"})]); + let mut r = assign(app, json!({"library": lib})); + assert_eq!(field(&r, "limitTo"), json!(lib)); + let at = rect(&r, "New 1").center(); + right_click(&mut r, at); + tap(&mut r, "Pick from Swatches"); + assert!(picker(&r).is_some(), "Pick from Swatches opens the Color Picker"); + assert!(has(&r, "Color Models"), "the picker shows its swatches, with the button back to the color models"); + assert!(has(&r, "Lib Teal") && has(&r, "Lib Plum"), "the swatches are the Limit to Library library's"); +} + /// Undo Changes and Redo Changes step back and forward through the dialog's own color edits, and /// the art previews each step; the document's undo history is unchanged until OK, which records /// one step. Both buttons start disabled, and a new edit after Undo Changes leaves nothing to redo. diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 4022cb7c65..42d47ab1cd 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -103,6 +103,46 @@ fn a_run_goes_frame_by_frame_and_is_one_undo_step() { let _ = std::fs::remove_dir_all(&dir); } +/// The warning automation asked while confined to a folder: Run runs the script as automation's, +/// with that folder still the only place it may read. +#[test] +fn the_warning_runs_the_script_under_the_access_it_was_asked_with() { + let mut app = app(); + let (inside, outside) = (folder("scope-in"), folder("scope-out")); + let path = outside.join("draw.js"); + std::fs::write(&path, DRAW).unwrap(); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + vectorcraft_engine::file_access::confine(roots.as_ref(), || { + crate::file_asks::as_automated(&mut app, true, |app| { + menus::run_ui_command(app, "ui.runScript", &json!({"path": path.to_string_lossy()})).unwrap().unwrap(); + }) + }); + assert!(confirm(&mut app, KIND)); + assert!(app.ui.status.contains("outside the read root"), "the script outside the folder is refused: {}", app.ui.status); + assert!(!app.session.script_running()); + finish(&mut app); + assert_eq!(objects(&app), 0); + let _ = std::fs::remove_dir_all(&inside); + let _ = std::fs::remove_dir_all(&outside); +} + +/// The warning a person asked, answered by automation confined to a folder: the script runs with +/// that folder still the only place it may read. +#[test] +fn the_warning_answered_under_narrower_access_keeps_it() { + let mut app = app(); + let (inside, outside) = (folder("narrow-in"), folder("narrow-out")); + let path = outside.join("draw.js"); + std::fs::write(&path, DRAW).unwrap(); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": path.to_string_lossy()})).unwrap().unwrap(); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap(); + assert!(vectorcraft_engine::file_access::confine(roots.as_ref(), || confirm(&mut app, KIND))); + assert!(app.ui.status.contains("outside the read root"), "the script outside the folder is refused: {}", app.ui.status); + assert!(!app.session.script_running()); + let _ = std::fs::remove_dir_all(&inside); + let _ = std::fs::remove_dir_all(&outside); +} + #[test] fn do_not_show_again_is_remembered_and_the_script_still_runs() { let mut app = app(); diff --git a/crates/ui-egui/src/tests/selectall.rs b/crates/ui-egui/src/tests/selectall.rs index 9c20603db8..ed97ffcdb7 100644 --- a/crates/ui-egui/src/tests/selectall.rs +++ b/crates/ui-egui/src/tests/selectall.rs @@ -380,6 +380,79 @@ fn copy_and_cut_copy_the_text_selected_in_a_panel_label() { assert!(copied(&after).iter().any(|t| t.starts_with(">| frames.into_iter().flat_map(|events| copied(&a.frame(events))).collect::>(); + let (status, sets) = (a.app.ui.status.clone(), a.app.ui.status_sets); + let clicked = copies(&mut a, vec![vec![Event::PointerMoved(at)], vec![click(at, true)], vec![click(at, false)], vec![]]); + assert_eq!(clicked, [length], "a click copies the value, once"); + assert!(a.app.ui.status_sets != sets && a.app.ui.status != status, "the status bar says it was copied"); + assert_eq!(a.selected(), 1, "the art stays selected"); + assert!(a.app.session.clipboard.is_empty(), "no art copied"); + a.time += 1.0; + let twice = copies(&mut a, vec![vec![click(at, true)], vec![click(at, false)], vec![click(at, true)], vec![click(at, false)], vec![]]); + assert_eq!(twice, [length], "a double click copies the value once"); + a.time += 1.0; + let (from, to) = (text_rect(&out, length).left_center() + vec2(1.0, 0.0), text_rect(&out, length).right_center() - vec2(1.0, 0.0)); + let mut drag = vec![vec![Event::PointerMoved(from)], vec![click(from, true)]]; + drag.extend((1..=4).map(|k| vec![Event::PointerMoved(from + (to - from) * k as f32 / 4.0)])); + drag.extend([vec![click(to, false)], vec![]]); + assert!(copies(&mut a, drag).is_empty(), "a drag selects and copies nothing"); + a.time += 1.0; + let shift = Event::ModifiersChanged(Modifiers::SHIFT); + let shift_click = + |at: Pos2, pressed: bool| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::SHIFT }; + let extended = copies( + &mut a, + vec![ + vec![shift.clone(), Event::PointerMoved(at)], + vec![shift_click(at, true)], + vec![shift_click(at, false)], + vec![Event::ModifiersChanged(Modifiers::NONE)], + ], + ); + assert!(extended.is_empty(), "a Shift-click copies nothing"); + a.time += 1.0; + // Shift let go in the frame of the release: the click was still a Shift-click. + let let_go = copies( + &mut a, + vec![ + vec![shift, Event::PointerMoved(at)], + vec![shift_click(at, true)], + vec![shift_click(at, false), Event::ModifiersChanged(Modifiers::NONE)], + vec![], + ], + ); + assert!(let_go.is_empty(), "a Shift-click copies nothing when Shift is let go in the same frame"); + a.time += 1.0; + // Released on the length, then moved onto the Paths count in the same frame. + let there = text_rect(&out, "2").center(); + let moved = + copies(&mut a, vec![vec![Event::PointerMoved(at)], vec![click(at, true)], vec![click(at, false), Event::PointerMoved(there)], vec![]]); + assert_eq!(moved, [length], "a click copies the value it was released on, not the one the pointer moved to"); + a.time += 1.0; + // A click on the Paths count, then a drag across the length, in one frame. + let (from, to) = (text_rect(&out, length).left_center() + vec2(1.0, 0.0), text_rect(&out, length).right_center() - vec2(1.0, 0.0)); + let both = copies( + &mut a, + vec![ + vec![Event::PointerMoved(there)], + vec![click(there, true), click(there, false), Event::PointerMoved(from), click(from, true), Event::PointerMoved(to), click(to, false)], + vec![], + ], + ); + assert!(!both.iter().any(|t| t == length), "a drag after a click in the same frame does not copy the dragged value"); +} + /// Drag across a label in a window of its own (a floating panel's), selecting its text there. The /// main window's labels then copy nothing on Copy or Cut, which run on the art a pass later. fn select_label_text_in_another_window(a: &mut App) { diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index baa21396ed..38efb55e1f 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -398,6 +398,90 @@ fn our_own_copy_pastes_the_lossless_internal_clipboard() { assert!(matches!(pasted(&app)[0].kind, NodeKind::Path { .. })); } +/// SVG markup of three closed paths, a group of two more and a compound path with a hole: five +/// objects. +fn closed_paths_svg() -> String { + let mut svg = String::from(r#""#); + for x in [10, 20, 30] { + svg.push_str(&format!(r##""##)); + } + svg.push_str(r#""#); + svg.push_str(r#""#); + svg +} + +/// Paste the objects of [`closed_paths_svg`] from another app and select them all → their count. +fn paste_closed_paths(app: &mut VectorcraftApp, board: &Arc>) -> usize { + copy_elsewhere(board, vec![(SVG, closed_paths_svg().into_bytes())]); + run(app, "edit.paste", json!({})); + run(app, "select.all", json!({})); + let objects = count(app); + assert_eq!(app.session.active().unwrap().selection.objects.len(), objects); + objects +} + +/// A Copy or Cut whose formats can't be written to the system clipboard (another app holds it +/// open, or refuses the write) stays what every Paste command takes while nothing else is copied, +/// also when its formats have no text; the clipboard's older text does not replace it, and a paste +/// into text takes the copy's text, or nothing. A later copy in another app still wins. A later copy is +/// noticed only when it changes the clipboard's text, so when the clipboard held only a picture, +/// or could not be read (another app holds it open), Paste takes what the clipboard holds. +#[test] +fn a_copy_the_system_clipboard_refused_still_pastes_the_copied_art() { + type Fail = fn(&Arc>, bool); + // Case, Copy or Cut, how the write fails, On Copy: Include SVG Code, the other app's copy + // before it is a picture, Paste takes the copied art. + let cases: [(&str, &str, Fail, bool, bool, bool); 5] = [ + ("refused", "edit.cut", refuse_writes, true, false, true), + ("refused, no text", "edit.cut", refuse_writes, false, false, true), + ("refused copy", "edit.copy", refuse_writes, true, false, true), + ("locked", "edit.cut", lock, true, false, false), + ("refused, over a picture", "edit.cut", refuse_writes, true, true, false), + ]; + let pastes = + ["edit.paste", "edit.pasteInFront", "edit.pasteInBack", "edit.pasteInPlace", "edit.pasteOnAllArtboards", "edit.pasteWithoutFormatting"]; + for (case, op, fail, svg_text, over_picture, kept) in cases { + let (mut app, board) = app(); + run(&mut app, "prefs.set", json!({"key": "copyAsSvg", "value": svg_text})); + let objects = paste_closed_paths(&mut app, &board); + if over_picture { + copy_elsewhere(&board, vec![(PNG, blue_png())]); + } else { + copy_elsewhere(&board, vec![(TEXT, b"Words another app copied".to_vec())]); + } + fail(&board, true); + run(&mut app, op, json!({})); + background::wait_all(&mut app); + fail(&board, false); + assert!(app.ui.status.starts_with("Couldn't copy to the system clipboard"), "{case}: {}", app.ui.status); + let left = if op == "edit.cut" { 0 } else { objects }; + assert_eq!(count(&app), left, "{case}"); + if !kept { + run(&mut app, "edit.paste", json!({})); + match &pasted(&app)[0].kind { + NodeKind::Image { .. } => assert!(over_picture, "{case}: the picture"), + NodeKind::Text(t) => assert_eq!((over_picture, t.plain_text().as_str()), (false, "Words another app copied"), "{case}"), + kind => panic!("{case}: not what the clipboard holds: {kind:?}"), + } + continue; + } + let text = app.written_clipboard_text(); + assert_eq!(text.is_some(), svg_text, "{case}: a paste into text takes the copy's text, or nothing: {text:?}"); + assert!(text.is_none_or(|t| t.contains(" Self { + self.tools_steps = 2; + self + } +} + /// The id of a built-in workspace: its lower-case name with dashes. fn builtin_id(name: &str) -> String { name.to_lowercase().replace(' ', "-") @@ -226,7 +236,7 @@ pub fn builtins() -> Vec { let w = |name: &'static str, fronts: &'static [&'static str], f: &dyn Fn(&mut WorkspaceRecord)| { let mut record = WorkspaceRecord::default(); f(&mut record); - Builtin { name, fronts, record } + Builtin { name, fronts, tools_steps: 1, record } }; vec![ w(ESSENTIALS, &[], &|_| {}), @@ -248,7 +258,8 @@ pub fn builtins() -> Vec { w("Painting", &["brushes"], &|x| { x.control_bar = true; x.toolbar_advanced = true; - }), + }) + .double_tools(), w("Printing and Proofing", &["info"], &|x| { x.control_bar = true; x.rulers = true; @@ -279,7 +290,10 @@ pub fn builtins() -> Vec { /// The built-ins as the framework's named workspaces. fn builtin_set() -> Vec> { - builtins().into_iter().map(|b| NamedWorkspace::new(builtin_id(b.name), b.name, crate::panel_docking::default_workspace(b.fronts))).collect() + builtins() + .into_iter() + .map(|b| NamedWorkspace::new(builtin_id(b.name), b.name, crate::panel_docking::builtin_workspace(b.fronts, b.tools_steps))) + .collect() } /// The chrome the set stores beside a layout, from `record`. Never read back: the record is the truth. @@ -745,6 +759,36 @@ mod tests { } } + /// Painting lays the Tools panel out in two columns and Window › Toolbars › Double Column reads + /// checked; every other built-in workspace has one column. Switching back to Essentials brings + /// back its own column count, as it was left, and Reset Painting gives two columns again. + #[test] + fn painting_shows_tools_in_two_columns_and_essentials_keeps_its_own() { + let steps = |app: &VectorcraftApp| { + crate::panel_docking::column_of(crate::panel_docking::layout_of(&app.ui), crate::toolbar::TOOLS).and_then(|(_, column)| column.steps) + }; + let double = |app: &VectorcraftApp| crate::menus::checked(app, "window.toolbarColumns", &json!({})); + let mut app = app(); + assert_eq!((steps(&app), double(&app)), (Some(1), Some(false)), "Essentials starts with one column"); + for b in builtins() { + switch(&mut app, b.name).unwrap(); + let painting = b.name == "Painting"; + assert_eq!(steps(&app), Some(if painting { 2 } else { 1 }), "{}", b.name); + assert_eq!(double(&app), Some(painting), "Double Column in {}", b.name); + } + switch(&mut app, ESSENTIALS).unwrap(); + assert_eq!((steps(&app), double(&app)), (Some(1), Some(false)), "Essentials has one column again"); + app.run("window.toolbarColumns", json!({"double": true})).unwrap(); + switch(&mut app, "Painting").unwrap(); + app.run("window.toolbarColumns", json!({"double": false})).unwrap(); + switch(&mut app, ESSENTIALS).unwrap(); + assert_eq!(double(&app), Some(true), "Essentials keeps the two columns it was left with"); + switch(&mut app, "Painting").unwrap(); + assert_eq!(double(&app), Some(false), "Painting keeps the one column it was left with"); + reset(&mut app); + assert_eq!((steps(&app), double(&app)), (Some(2), Some(true)), "Reset Painting gives two columns again"); + } + /// A file saved before `WorkspaceSet` names workspaces in any case: the layout remembered under /// another spelling belongs to the saved workspace, once; a name no workspace has is dropped, /// and a saved name equal to a built-in's is refused and reported. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 220bdf2e45..f3b8a18d85 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -494,9 +494,8 @@ button (Add Tool…) opens a menu of every tool under the drawer's headings: a c there. `window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with it. `window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, shown flag, two-column flag, top-left corner, the groups torn off it, and `dock` and `dock_right` while docked or once docked). -`window.toolbar.dock {name, side?, order?}` docks a toolbar in the lane along the window's left or right edge, and -`window.toolbar.float {name, x?, y?}` floats it again; dropping its title bar on an edge or dragging it out of its -lane does the same (see the docking section in `docs/mcp.md`). They are kept with the workspace they were made in: +`window.toolbar.dock {name, side?, order?}` docks a toolbar as a column of the dock along the window's left or right +edge, and `window.toolbar.float {name, x?, y?}` floats it again; dragging its title bar does the same (see the docking section in `docs/mcp.md`). They are kept with the workspace they were made in: switching workspaces shows that workspace's toolbars, Reset Workspace keeps them, and New Workspace starts the new workspace with a copy of them. @@ -817,7 +816,9 @@ lists to the system clipboard (once they are written, the status bar shows the f another message has replaced the Copy or Cut's meanwhile), and every Paste command first loads what another app copied (`clipboard.importSvg`, `importPdf`, `importEps`, `importText` or `importImage`, centred in the view; the desktop app reads PDF and EPS from the Windows clipboard and, with SVG, from the macOS pasteboard, and an `.eps` file, or a `.ai` or `.ait` file that holds a PDF or PostScript, copied in a file manager anywhere; a copied `.ai` or `.ait` file that holds a PDF loads with `importPdf {editingData: true}`, which reads its editing data); an import error answers the Paste with that error -and pastes nothing. Cmd+V also pastes a bitmap or PDF with no text beside it (on the key's release, as egui sends no +and pastes nothing. After a Copy or Cut whose formats could not be written to the system clipboard, every Paste +command takes the internal clipboard instead until another app copies something (only while the clipboard held text +that could be read when the write failed). Cmd+V also pastes a bitmap or PDF with no text beside it (on the key's release, as egui sends no Paste event for it). Screenshots paste on every platform: Windows reads `PNG`, else `CF_DIBV5`/`CF_DIB`, macOS the pasteboard's PNG or TIFF, Linux `image/png`, and the web the picture the browser's paste event carries (#457). In the desktop app a Paste from the menus or the keys (`ui.key`) decodes a bitmap off the UI thread: `ui.inspect` lists diff --git a/docs/gaps.md b/docs/gaps.md index 41d263851f..879c8cace8 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (G3 lists shadows from the first light and graphics as done and drops angular cut caps, which Revolve's Cap closes, #8312; scores and estimates unchanged; previously: G12: Variables panel row context menus; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. @@ -12,6 +12,8 @@ ## Feature submission evidence +- **Implemented and tested (2026-11-20, G12):** Variables panel row context menus: Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. + Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. **Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. @@ -60,6 +62,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | G12: Variables panel row context menus implemented with row highlighting, bound-object selection, options, unbinding, selection-based dynamic actions and single-step deletion; headless regression coverage. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Properties panel Quick Actions include contextual text actions (Create Outlines, Retype, Find and Replace…); headless tests in crates/ui-egui/src/panels/properties/tests.rs; scores and estimates unchanged. | | 2026-11-20 | minor | G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index b3cea3265f..437569a1f9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1485,6 +1485,13 @@ a larger file. A lossy file keeps the alpha exactly when some pixels are not opa that is not a whole number, is refused; a lossless file ignores `quality`. Export for Screens takes both in a WebP row or in `settings.webp`. +GIF and PNG-8 exports take Save for Web's `transparencyDither` (`none`, the default, `diffusion`, `pattern` or `noise`) +and `transparencyDitherAmount` (0 to 100, default 100) next to `dither` and `ditherAmount`, and they change the file as +in `document.exportForWeb`: with `transparency` on, some partly transparent pixels become transparent and the rest keep +their color, and without `transparency` the keys do not change the file. For GIF and PNG-8 an unknown method, or an +amount that is not a whole number from 0 to 100, is refused; other formats do not read the keys, and the warnings name +them. GIF and PNG-8 Options show both as Transparency Dither and its amount, disabled while Transparency is off. + `shape.ellipse` (and `draw_shape` with `shape: "ellipse"`) takes `anchors`, the number of smooth anchors (default 4). Without it, or at 4, it draws a live ellipse. Any other count from 2 to 1000 draws a closed plain path with that many anchors spaced evenly by angle, clockwise from the left one and fitted to `width` × `height`. The Ellipse dialog (a @@ -2710,8 +2717,11 @@ string, `?.` and `??` are syntax errors. Which files read these forms is VectorC https://ecma-international.org/publications-and-standards/standards/ecma-357/): XML and XMLList literals, the `..`, `.@`, `.*`, `.()` and `::` selectors, `for each`, `default xml namespace`, and the global `XML`, `XMLList`, `Namespace`, `QName`, `isXMLName` and `setDefaultXMLNamespace`, as the XML object pages describe them -(https://extendscript.docsforadobe.dev/integrating-xml/the-xml-object/). The script reaches the -app through the global object `vc`, and writes to the Script Console and runs other files through `$`: +(https://extendscript.docsforadobe.dev/integrating-xml/the-xml-object/). A script run from a `.js` file also has +`Promise` (described below); a `.jsx` file and a script given as `source` do not, except that a named engine +(`#targetengine`) has `Promise` from the first `.js` run that names it and keeps it for every later run, as it keeps +its globals. The script reaches the app through the global object `vc`, and writes to the Script Console and runs +other files through `$`: - `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can catch. The documents and the session state the command changed, preferences included, go back, and any file it @@ -2723,8 +2733,20 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.log(value)` adds a value to the report and a line to the Script Console. - `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/ describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), - `app.selection` (assigning it sets the active document's selection), `app.coordinateSystem` and - `app.getIsFileOpen(path)`. A script may name the application's members without `app.`, as + `app.selection` (assigning it sets the active document's selection), `app.coordinateSystem`, + `app.getIsFileOpen(path)` and `app.executeMenuCommand(name)`. `executeMenuCommand` runs the command of a menu item + on the active document, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts + describe the method, and takes these names from the list at + https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510: + `selectall` (`select.all`), `deselectall` (`select.none`), `group` (`object.group`), `ungroup` + (`object.ungroup`), `makeMask` (`object.clippingMask.make`), `releaseMask` (`object.clippingMask.release`), + `compoundPath` (`object.compoundPath.make`) and `noCompoundPath` (`object.compoundPath.release`), and + `Fit Artboard to artwork bounds` (https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee), which runs + `artboard.fitToArt` on the active artboard. Names are matched exactly. Any other name throws an error that names + it, and a name that is not a string throws a `TypeError`. VectorCraft's own rule: a menu item that is not + available, with no document open, nothing selected that it acts on, or a locked active artboard or one with no art + for `Fit Artboard to artwork bounds`, does nothing and adds no undo step. An available menu item runs its command, + and an error that command returns throws. A script may name the application's members without `app.`, as [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. VectorCraft's own rules: assigning `activeDocument` or `selection` without `app.` assigns the application's member. A top-level @@ -2853,6 +2875,27 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.args` gives a read-only copy of the `args` object each time it is read. - `vc.api.version` is `"1.0"`, and `vc.api.has(feature)` says whether the API has a feature. +In a `.js` script, `Promise` follows ECMA-262 11th edition section 25.6 +(https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, +`Promise.resolve`, `reject`, `all`, `allSettled` and `race`. `Promise.any` is not provided. These are VectorCraft's +own rules: + +- The callbacks `then`, `catch` and `finally` register run as jobs, one at a time, in the order they were queued, after + the script's own code ends and before the run ends; a job a callback queues runs after the jobs already waiting. + A promise still pending when no job is left stays pending, and the run ends. +- The jobs run on the run's fuel and limits, and each job takes 1 unit of fuel. A chain of callbacks that never ends + stops at the fuel limit. More than 1,048,576 jobs waiting at once end the run with the limit error + `limit reached: Jobs (more than 1048576 promise jobs were waiting to run)`. A run that ends with an error, a limit or + `script.stop` drops the jobs still waiting, and the documents go back as for any failed run. +- `all`, `allSettled` and `race` take an array, another object whose `length` is a whole number, or a string (one + item per character); any other value rejects the promise they return with a `TypeError`. The promises `then` and the + statics make are always plain `Promise` objects; `Symbol.species` and subclasses are not read. +- A promise rejected with no rejection handler that still has none when the run ends successfully is reported: the + report's `unhandledRejections` lists the first 20 as `{message, messageOrigin, line, column, file?}`, where it was + rejected (the `throw`, or the call of its reject function or of `Promise.reject`), `unhandledRejectionCount` counts + all of them, and the Script Console shows an error line for each, as in + `tidy.js:12:5: unhandled promise rejection: Error: not found`. Both fields are left out when there are none. + The first run in an engine decides whether the engine has `Symbol` and the iterators of arrays, strings and `arguments` objects, and each run's script decides which syntax that run reads. The built-in functions' names follow the rule above. A `.jsx` script or a `source` string that starts a new engine has no `Symbol` and no iterators of arrays, @@ -3065,7 +3108,8 @@ VectorCraft sets these limits itself: In the app, a script past the growth limit stops at a question to continue or to stop and undo. Stop, Escape and `ui.dialog.cancel` all stop the run. A run with nobody to ask, such as a call over MCP or the command line, ends with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls, -runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`. In +runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`, with +`unhandledRejections` and `unhandledRejectionCount` as well when a `.js` script left rejected promises unhandled. In the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. The report of a failed run has the same fields after `kind`, `message`, `messageOrigin`, `line`, `column`, `file` (when the error is in another file than the script) and `fuelLeft`. `messageOrigin` is `script` when `message` is text the @@ -3912,36 +3956,23 @@ the window's edge. ## Docking toolbars made with New Toolbar -A toolbar made with New Toolbar floats when it is made. `window.toolbar.dock {name, side?, order?}` (Dock to Left and -Dock to Right in the context menu of the toolbar's title bar, remote mode, `invoke_menu`) docks it in a lane along the -window's left or right edge. On the left, the lane is right of the Tools panel when the Tools panel is docked at the -window's edge. With Keep Tools Beside the Canvas on and the Tools panel docked on the left, the lane is right of the -Tools panel beside the canvas, and dropping a title bar on the Tools panel or on the lane docks the toolbar there. `side` is `left` or `right` (`start` and `end` also work); without it, the toolbar docks at the edge it -docked at last, or at the left the first time. Toolbars docked at one edge stack from the top. `order` is the -toolbar's place in that stack, 0 at the top, from 0 to the number of other toolbars docked there; without it, the -toolbar goes at the end, or stays where it is when it is already docked at that edge. Each toolbar takes an equal -share of the lane's height and its tools scroll in it, and the lane is as wide as its widest toolbar. When the lane -is too short to give each toolbar 88 points of height, the stack wraps into more columns, left to right, and the lane -widens, so no toolbar covers another. A lane takes at most half the width the canvas and panels would have (beside -the canvas, it also leaves the canvas at least 200 points, and the canvas keeps room for one column); when that -many columns still give a toolbar less than 88 points, the toolbars in those columns show only their title bars, which -still float, dock and show the context menu. A column too short for all of its title bars shows as many as fit, and -the mouse wheel over the column scrolls through the others, one toolbar per notch. -`window.toolbar.float {name, x?, y?}` (Float Toolbar in the same menu) floats it with its top-left corner at `x`, `y` -in screen points, or where it floated last when both are omitted. Both commands answer -`{toolbar, floating, side, order, pos}`: `side` is the edge the toolbar docks at (while it floats, the edge it docked -at last), `order` its place in that edge's stack (null while it floats) and `pos` where it floats (while it is docked, -where it floated last). A missing or unknown name, a `side` other than left or right, an `order` that is not a whole -number in range, or only one of `x` and `y` is an error and changes nothing. `window.toolbar.list` reports `floating`, -`side` and `order` for each toolbar. +A toolbar made with New Toolbar floats when it is made. `window.toolbar.dock {name, side?, order?}` (remote mode, +`invoke_menu`) docks it as a column of the dock along the window's left or right edge, and a hidden toolbar shows. +`side` is `left` or `right` (`start` and `end` also work); without it, the toolbar docks at the edge it docks at +now, else at the edge of the docked panel it left when it floated or was hidden, else at the left. `order` is the +place of the toolbar's column in that edge's dock, 0 at the window's edge, from 0 to the number of the dock's other +columns; without it, the toolbar docks as the innermost column, or stays where it is when it already docks at that +edge. `window.toolbar.float {name, x?, y?}` floats it with its top-left corner at `x`, `y` in window points, each +from -1000000 to 1000000. When both are omitted, the dock floats it as it floats a panel, and a toolbar that floats +already stays where it is. Both commands answer `{toolbar, floating, side, order, pos}`: `side` is the edge the +toolbar docks at (while it floats or is hidden, the edge `window.toolbar.dock` uses without `side`), `order` its +column's place in that edge's dock (null while it floats) and `pos` its top-left corner while it floats (null while it +is docked). A missing or unknown name, a `side` other than left or right, an `order` that is not a whole number in +range, or only one of `x` and `y` is an error and changes nothing. `window.toolbar.list` reports `floating`, `side` +and `order` for each toolbar. -With the pointer, dropping a floating toolbar's title bar on the window's left or right edge, or on that edge's lane, -docks it at the end of that edge's stack; the target lights up while the title bar is dragged over it. Dragging a -docked toolbar's title bar out of its lane floats it under the pointer. Escape, or the window losing focus, during -the drag puts the toolbar back where it was. Hiding a docked toolbar keeps its place, renaming it keeps its place, a -copy made with Manage Toolbars' + floats, and deleting one closes up the stack. Placement is kept with the workspace. -Toolbars saved before docking existed load floating. The lanes, the edge targets and the stacking are VectorCraft's -own layout rules. +Dragging the toolbar's title bar also docks and floats it. Placement is kept with the +workspace. These are VectorCraft's own layout rules. ```json {"name":"invoke_menu","arguments":{"command":"window.toolbar.dock","params":{"name":"Toolbar 1","side":"left","order":0}}} @@ -4134,7 +4165,8 @@ Copy) and `object.transformAgain`, also when no object is selected, in one undo guide transforms as the line `view.guides.release` makes of it, and the default origin is the center of the selected objects' box and those lines together. A guide that ends up vertical or horizontal stays a ruler guide at its new place: a turn of 180° keeps it, and a turn of 90° makes a horizontal guide vertical. A guide at any other angle -becomes a guide path along its line, on the guide's layer, and is selected as one. Locked or hidden guides do not +becomes a guide path along its line, on the guide's layer, and is selected as one; the reply's `ids` list it after +the transformed objects. Locked or hidden guides do not transform, nor do guides when `ids` is given or `objects` is false. `object.rotate` with `absolute` and only ruler guides selected is an error, as guides have no bounding box angle. @@ -5006,9 +5038,13 @@ already walks Image Trace. Short agent entry points: `replace` is true. Every preset in the file is checked first, and a file with a built-in preset's or `Custom`'s name, two presets of one name, a preset without a name or `params`, settings `imageTrace.presets.save` refuses, or a newer `version` changes nothing. In the app, opening a `.vctracepresets` file (File › Open, a drop, or the file picked - for Import… on the web) imports it as Import… does. Also in the app, - `ui.imageTracePresetDialog {params?, rename?}` opens the Image Trace panel's Save as New Preset… or Rename… dialog, - and `ui.tracingPresetsDialog {selected?}` opens Edit › Tracing Presets…: the built-in presets in brackets (read-only) + for Import… on the web) imports it as Import… does. Also in the app, the Image Trace panel's Preset row has a Manage + presets menu. Its Save as New Preset… and Rename… (a saved preset; also F2 on the picker) open a name field in the + row, which starts with the first free "Tracing Preset N" for a new preset and with the preset's name for a rename. + Enter or OK runs `imageTrace.presets.save` (with the panel's settings for a new preset, with `newName` for a rename), + and Escape or Cancel saves nothing. A built-in preset's name, `Custom` or another saved preset's name shows a message + under the field and keeps it open. Its Delete (a saved preset) runs `imageTrace.presets.delete`. + `ui.tracingPresetsDialog {selected?}` opens Edit › Tracing Presets…: the built-in presets in brackets (read-only) and the saved ones, with the selected preset's settings. Its New… (from the selected preset) and Edit… (a saved preset) open an editor with the Image Trace panel's settings; OK saves with `imageTrace.presets.save` and Cancel saves nothing, and a built-in preset's name, `Custom` or another saved preset's name keeps the editor open. Delete selects @@ -8224,7 +8260,8 @@ the Direct Selection tool those of any path. `rectanglesOnly: true` sets them on alone and leaves the other objects as they are (the Rectangle Properties corner fields and menus send it with the selection, so an action that records them acts on the rectangles selected when it plays). Several objects each with their own corners are one call: `items: [{id, corners?}]` in place of `ids` and `corners`. Alt-clicking one cycles their kind. Double-clicking one with Direct Selection opens Corners (`ui.corners {id?, corners?}`, -dialog `corners`: `kind`, `radius`; OK runs `object.setLiveShape`). Double-clicking a selected live shape's corner +dialog `corners`: `kind`, `radii`, `radius`, a percentage of each corner's own maximum while `radii` is `relative`; OK runs +`object.setLiveShape`, as one undo step for corners whose maximums differ). Double-clicking a selected live shape's corner widget with the Selection tool shows and selects the Transform panel, as the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools do. With the headless backend, the `pointer_gesture` reply carries `{"panel": "transform"}` in its `requests`; the desktop app runs `window.panel.activate {"panel": "transform"}` instead, and its reply has no `requests`. The tool, the selection and the document stay as they are, and @@ -8390,6 +8427,13 @@ Commands listed this way include `type.fractionalWidths`, `type.systemLayout`, ` `links.embed`, `links.update`, `object.slice.delete`, `artboard.switchOrientation`, `artboard.distributeSpacing`, `appearance.targetContents` and `paint.invert`. +They also list these UI commands, which have no menu bar item and no default shortcut and whose params are all +optional: `ui.newSwatch`, `ui.newColorGroup`, `ui.colorGroupOptions`, `ui.newBrush`, `ui.brushOptions`, +`ui.layerOptions`, `ui.corners`, `ui.placementOptionsDialog`, `ui.relinkDialog`, `ui.perspectivePlane`, +`ui.bulletsAndNumbering`, `ui.missingFontsDialog` and `ui.findFontsInFolder`. A key assigned to one runs it with no +params, as `{}` does: it opens the dialog for the selection or the current item, or the status bar shows why it cannot, +for example "no brush selected". + Edit › Keyboard Shortcuts and `shortcuts.list` leave out a command with no default shortcut when a key press cannot run it: no item of the menu bar runs it, it opens no dialog when run without params, and it is one of these: @@ -10360,8 +10404,13 @@ copied (SVG, then PDF, then text, then a bitmap; SVG markup in text counts as SV formats and they are published when they are ready. While that thread has a save, an export, a print or a recovery copy to finish, Copy and Cut make and publish them at once. When another Copy or Cut, or a copy of text in VectorCraft, comes first, they are dropped. Pasting what VectorCraft copied keeps the lossless internal clipboard, -also before its formats are published. While a text field or the Type tool has the keyboard, the app waits for -them. Windows carries every format both ways and pastes a bitmap from PNG, else +also before its formats are published. When the formats could not be written (another app held the clipboard open +or refused the write), every Paste takes the internal clipboard until another app copies something, and a paste +into a text field or type takes the copy's text, or nothing when the formats have no text. The app notices that +copy only when it changes the clipboard's text, so Paste reads the system clipboard when it held only a picture, or +nothing that could be read, at the failed write. Once a paste has read the changed text, the older text coming back +does not restore the copy. While a +text field or the Type tool has the keyboard, the app waits for them. Windows carries every format both ways and pastes a bitmap from PNG, else from the device-independent bitmap screenshots copy (`CF_DIBV5`, then `CF_DIB`; alpha kept, opaque when it is zero throughout, at most 32768 px a side); macOS and Linux carry one format (the text, else the PNG) and paste text and bitmaps (macOS the pasteboard's PNG, else TIFF, as screenshots copy them). A Paste from the menus or the keys decodes @@ -13684,8 +13733,10 @@ its features turned off, distinct from unset. not a global swatch of the document, a stroke weight outside 0 to 4000000, more than 256 feature tags and an OpenType feature tag the shaper does not know, unless the style or the text it is made from already has that value. They also reject a size outside 0.1 to 1296, explicit leading outside 0.1 to 5000, horizontal or vertical scale -outside 1 to 10000, and baseline shift or Tate-chu-yoko offsets outside -1296 to 1296. `leading: null` keeps -Auto leading. An invalid value leaves the style, its text, and Undo history unchanged. +outside 1 to 10000, baseline shift or Tate-chu-yoko offsets outside -1296 to 1296, tracking or kerning +outside -1000 to 10000, rotation outside -360 to 360, a stroke miter limit outside 1 to 500, a +stroke dash length outside 0 to 4000000 or offset outside -4000000 to 4000000, Small Caps outside 1 to 200 and a +variable font axis setting that is not a number. `leading: null` keeps Auto leading. An invalid value leaves the style, its text, and Undo history unchanged. The New Character Style dialog accepts the same character fields and starts with the selected text's captured attributes. Without selected text, it starts with the character defaults for the interface language (including `charAlign: "emBoxCenter"` in Japanese); changing a Basic field keeps other seeded attributes. @@ -13817,9 +13868,16 @@ transforms and names included: pixels and runs that don't fit come the same way, fit makes `plugin.run` return a memory-budget error naming the object and its size, with nothing changed. A path or compound path that doesn't fit makes it return the memory-budget error `the selection is too large to hand over`, and more than 100,000 of these objects make it return an object-budget error. Its output returns -each of them as `{"id": …}` or exactly as given, otherwise `plugin.run` returns an error naming the object and the -field, and the document and undo history are unchanged. A filter, or a live effect with commands, at plug-in API level 3 -whose manifest lists `context` (`settings`, `artboards`, `layers`, `swatches`; `context` in its `plugin.list` entry) +each of them as `{"id": …}` or exactly as given (an image may leave out `opacity`), otherwise `plugin.run` returns an +error naming the object and the field, and the document and undo history are unchanged. A filter at plug-in API level 3 whose manifest also lists some of +those kinds in `writes` (with `doc.write`; `writes` in its `plugin.list` entry) may return an object of such a kind with +only the fields it changes: its name and `transform`, type's `text.runs` (at most 4,096 runs and 4,096 paragraphs, and +fills and strokes with only the keys their `type` reads) and `text.paragraphs` (one style per paragraph of the new text, +also when returned as given next to changed runs), an image's `opacity` and +an instance's `symbolId`, which must name a symbol in the document. Any other changed field, or a value out of range, +makes `plugin.run` return an error naming the object and the field, with nothing changed (docs/plugins.md, "Writing +type, images and symbols"). An output that changes nothing records no undo step. A filter, or a live effect with +commands, at plug-in API level 3 whose manifest lists `context` (`settings`, `artboards`, `layers`, `swatches`; `context` in its `plugin.list` entry) also lists `doc.read` in its `permissions`, and each filter or command run is given those parts of the active document in `_context.document`, with or without a selection: the document's name without its folder, color mode, units, active artboard size, bleed and raster effects resolution; every artboard's id, name and rectangle; every layer and sublayer @@ -13907,13 +13965,21 @@ naming the permissions needed. With `VECTORCRAFT_NO_PREFS` set there is no store flag lasts for that session only. In other sessions the approval, or a `grant` accepted under the flag, is kept with the module's hash, counts as approved in later sessions and in the desktop app, and covers only that module: the same bytes install again without one, also from a headless session that reads the same `grants.json`, and a module -with other bytes has `needsApproval: true` and needs a new one even when it lists the same permissions. `plugin.remove` +with other bytes has `needsApproval: true` and needs a new one even when it lists the same permissions. A +`grants.json` that does not carry VectorCraft's MAC for its folder, or is at another generation than the one the key +store keeps for the folder, such as an earlier copy put back (see [plug-ins](plugins.md#grants-file-integrity)), grants +nothing, and its plug-ins have `needsApproval: true` again. When the system key store can't be reached, an +approval lasts for that session only and the file is left as it is. `plugin.remove` forgets the approval, and so does installing a module that lists no permissions under that id: the earlier bytes then need a new approval. A refused install keeps the grant. A failed write of the module to the plug-in store leaves the grant in the store. A stored module that is disabled, or not read in Safe Mode, keeps the grant for its id. When -`plugin.remove` can't remove the grant from the plug-in store, it returns an error and the plug-in stays installed. -When the plug-in's settings and cache can't be moved back from their `.removed` folder then either, the error names -that folder, and the next load, install or `plugin.remove` of the plug-in moves them back. A +`plugin.remove` can't remove the grant from the plug-in store, it returns an error and the plug-in stays installed; +so does a `plugin.remove` while the system key store can't be reached, also when `grants.json` is missing or doesn't +name the plug-in. When `plugin.remove` can't delete an installed plug-in's stored module, it returns an error naming +the file, and the plug-in stays installed with its grant kept in the store. For an id that isn't installed, +`plugin.remove` also deletes the module stored for it that didn't +load and returns `{removed}`. When the plug-in's settings and cache can't be moved back from their `.removed` folder +then either, the error names that folder, and the next load, install or `plugin.remove` of the plug-in moves them back. A filter without `doc.write` or `state` that returns output needing them gets an error and the document is unchanged. A plug-in of API level 2 (`api: 2` in its entry) that lists `progress` may report its progress, see Cancel and write log lines: `notifications/cancelled` makes its `vc_cancelled` return 1, and its log lines go to the server's log @@ -14354,9 +14420,10 @@ The new path takes the current fill, stroke and stroke weight (`fill` and `strok above the front-most object along the area (one whose outline touches the area's outline, or that covers it) and is selected. When a group, Live Paint group, Shaper group or clipping group holds that object, the new path goes above the outermost group in its layer, not inside it, and the group keeps its members. In isolation mode only the paths in -the isolated layer or group bound areas, for the tool's hover and click and for the command (with `ids`, only the -paths of the listed objects that are in it), and the new path goes inside the isolated layer or group, 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 +the isolated layer or group bound areas, for the tool's hover and click and for the command. With `ids`, the paths +of the listed objects that are in it bound areas, and all of its paths do when `ids` lists the isolated layer or group +or a layer or group that holds it; the other listed objects are ignored. The new path goes inside the isolated layer +or group, 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. A point in no enclosed area is the error "Fill Area: no enclosed area under the pointer" and records no undo @@ -15471,7 +15538,7 @@ Commands: - `addon.pathtools.shape.set {id, …}` changes a parametric shape's numbers (the same keys; a new `kind` takes its own defaults for the values not given) and redraws it in place. With `reference` (0 to 8 on the 9-point grid of the bounding box as `object.setBounds` measures it, rotated with rotated objects) and no `center`, that point of the box - keeps its place, as with the Transform panel's W and H; otherwise the shape's center stays. Snapping to the pixel + keeps its place, as with the Transform panel's W and H; with `center`, the shape's center moves to it; otherwise the shape's center stays. Snapping to the pixel grid and an attachment to a path apply after that, as they do for the Transform panel's W and H, and can move the point. A `reference` outside 0 to 8 is an error. With no change it makes no step. → `{id, shape}` (its numbers now, so `{id}` alone reads them; `null` when snapping to the pixel grid left a plain path). diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md index fd323a5928..3d9d1fe494 100644 --- a/docs/nightly-release-preparation.md +++ b/docs/nightly-release-preparation.md @@ -1,11 +1,12 @@ # Windows, Linux and macOS release-ref nightly: supervised manual go-live -**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the -signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed -manual actors dispatches them. There is no schedule yet. The installed policy -[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 -policy. Once `nightly.yml` reaches `main`, populate `producer_workflow_id` with its registration ID -before promoting the policy to `release`: +**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and +the signer (`nightly-sign.yml`, on the dedicated `nightly-signer` branch) keep only their exact +context guards and run when one of the reviewed manual actors dispatches them. +`nightly-dispatch.yml` stays literally off: it only forwards scheduled producers. There is no +schedule. The installed policy +[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3 policy. +Its `producer_workflow_id` is the registration of `nightly.yml` on main, read with: ```bash gh api repos/storytold/vectorcraft/actions/workflows/nightly.yml --jq .id @@ -14,38 +15,66 @@ gh api repos/storytold/vectorcraft/actions/workflows/nightly.yml --jq .id The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation permissions are for its isolated attester; its compiler narrows to contents and Actions read only, with no OIDC, attestation write, release environment or platform signing secrets. -Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions -main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded -lineage compares and an issue reread at the end of candidate admission) on top of -[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input -and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is reviewed -source availability, not provider, queue, native signing or crypto qualification. -Existing stable workflows are unchanged. +Shared tooling is pinned to `be00e5ccd18b68e950c8a08532f2230e7c3d0cba`, the craft-common-actions +main commit that merged [#371](https://github.com/storytold/craft-common-actions/pull/371) (the +candidate is admitted on the built commit's own Sonar analysis, not main's latest) after +[#370](https://github.com/storytold/craft-common-actions/pull/370) (the Windows and macOS nightly +registry rows for the 14 apps) and +[#369](https://github.com/storytold/craft-common-actions/pull/369) (shared helper checkouts kept out +of the app's clean-source check, and macOS on `macos-15`), following +[#364](https://github.com/storytold/craft-common-actions/pull/364) (the signer may run on the +policy's signer branch) and [#363](https://github.com/storytold/craft-common-actions/pull/363) (the +multi-app pipeline, which makes the signer's `app-name` input required and admits any reviewed +registry app), with #342 (`a4f6fd51`, policy v3 and the `platforms` input) and #339 (`605d5876`) +earlier. Both callers name it in `uses` and `tooling-revision`. A pin is reviewed source +availability, not provider, queue, native signing or crypto qualification. Existing stable workflows are unchanged. **First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a -listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that -producer run ID and attempt, by a listed manual actor. +listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `nightly-signer` +with that producer run ID and attempt, by a listed manual actor. `nightly-dispatch.yml` only matters +once a schedule is approved. + +**Signer branch.** The signer runs on `refs/heads/nightly-signer`, not on the stable `release` +branch, so nightly signer files never need a stable release sync. The policy's `release_branch` +names it, the signer's guard requires it and the dispatcher targets it. The branch only +fast-forwards to reviewed main commits, through the settings script's `advance` (no queued signer +run, a trust-closure scan, then the full diff of `.github/` and `packaging/`), and the existing +`release` environment must admit `nightly-signer` alongside `release` before the first dispatch (a +repository settings change, not a workflow one). Its trust closure is all of `.github/` and +`packaging/`, including `packaging/env.sh`, which `packaging/macos/import-cert.sh` sources with the +Apple keys. On that branch only the pinned `nightly-sign.yml` caller may reach an environment: no +app workflow binds one, nothing else calls `nightly-release.yml`, and the only caller of the shared +stable `release.yml` is `release.yml`, whose callee must carry the stable-only environment guard. +The contract tests check the in-repo part on every main PR; the settings scan also resolves the +callee. Stable releases still come only from `refs/heads/release`. History does not carry over a +switch between `release` and `nightly-signer`, so the switch happens before the first publication. + +**Registry admission.** The signer requires the protected policy's `platforms` map to equal the +run app's admitted targets in craft-common-actions' `nightly-apps.json`, and it refuses rather +than sign a subset. VectorCraft's row admits `linux-x86_64`, `windows-x86_64` and `macos-aarch64`, with +each target's entrypoint and asset pattern, since craft-common-actions #370 (in the pin). **Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers -team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team changes. +team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team +changes. **Platform rows.** The producer caller lists `platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer run builds every listed platform for one all-or-nothing release (one failed or -skipped platform stops that night's release, Windows included), and the release-ref signer admits +skipped platform stops that night's release, Windows included), and the signer admits platforms only from the protected policy, so there is no separate Linux or macOS caller job and the signer caller has no platform input. ## Installed policy values and their sources -Read on 2026-11-24; re-read anything that may have moved (and populate `producer_workflow_id` after `nightly.yml` lands on `main`) before the policy is promoted to `release`. +Read on 2026-11-24; re-read anything that may have moved before `nightly-signer` is advanced to it. | Field | Value | Source | |---|---|---| | `repository_id` | `1398097510` | `gh api repos/storytold/vectorcraft --jq .id` | -| `producer_workflow_id` | `null` (pending first registration on `main`) | Read via `gh api repos/storytold/vectorcraft/actions/workflows/nightly.yml --jq .id` once `nightly.yml` is on `main` | -| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin | +| `producer_workflow_id` | `430275079` | `gh api repos/storytold/vectorcraft/actions/workflows/nightly.yml --jq .id` | +| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `be00e5cc…` (craft-common-actions #371 after #370, #369 and #364) | The callers' pin | | `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` | | `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | | `platforms` | three rows | Learning Machines stable identities (Windows Authenticode publisher subject, Linux OpenPGP fingerprint, Apple Developer ID team `DJ6XS33FX8`) | @@ -57,11 +86,15 @@ Read on 2026-11-24; re-read anything that may have moved (and populate `producer - `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named `VectorCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets may be passed or inherited. -- `.github/workflows/nightly-sign.yml`: top-level release registration, enabled for manual dispatch, - and identical on main and release after reviewed promotion. It rejects wrong repository/event/actual branch, +- `.github/workflows/nightly-sign.yml`: top-level registration on `nightly-signer`, enabled for manual dispatch, + and only ever fast-forwards to reviewed main commits. It rejects wrong repository/event/actual branch, including same-name tags. Its constant whole-run concurrency (`vectorcraft-nightly-release`) is distinct from stable, cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no - credentials; only the shared callee's sign jobs bind the `release` environment. + credentials; only the shared callee's sign jobs bind the `release` environment, which must admit + `nightly-signer` alongside `release` before the first dispatch. +- `.github/workflows/nightly-dispatch.yml`: transport only, never authorization. It is literally + off (`false &&`) and forwards only a first-attempt scheduled producer to `nightly-sign.yml` on + `nightly-signer`. No schedule is registered until activation is reviewed. - Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in `storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable commit**; the defining workflow SHA and tooling input must match. @@ -73,7 +106,14 @@ Read on 2026-11-24; re-read anything that may have moved (and populate `producer - Manual actors match the reviewed release-managers list in both `nightly.yml` and `.github/nightly-signing-policy.json`, with `automatic_signer_actors` empty. - Both callers pin the same immutable `craft-common-actions` commit in `uses` and `tooling-revision`. - No nightly schedule is registered, no cache actions or secrets appear in the app callers, and `nightly-sign.yml` retains its literal root `concurrency` block (`group: vectorcraft-nightly-release`, `cancel-in-progress: false`, `queue: max`). -- Policy v3 schema, platform rows, bounds, required main-push CI workflow, and SonarCloud project identity match `sonar-project.properties`. +- Policy v3 schema, platform rows, bounds, required main-push CI workflow, and SonarCloud project identity match `sonar-project.properties`, and the Sonar gate shape keeps every live condition once with accepted failures inside the reviewed issue scope. +- The signer guards `refs/heads/nightly-signer`, passes `app-name: vectorcraft`, and the policy's + `release_branch` names it. +- A trust-closure scan reads every workflow: nothing binds an `environment`, only `nightly-sign.yml` + calls `nightly-release.yml` (at a full SHA), and the only caller of the shared stable `release.yml` + is `release.yml`. +- `nightly-dispatch.yml` keeps a literal-off guard, a `workflow_run`-only trigger and a + `refs/heads/nightly-signer` request. ## The app side of a Nightly build @@ -139,12 +179,14 @@ enabled, so no `app.ron` is written anywhere); if it is ever turned on, its stat installation on every platform, and `apps/vectorcraft/src/profile.rs` (`install_data_root`) is the one hook every data path follows. -## Activation prerequisite: the Sonar issue scope +## The Sonar issue scope The pinned candidate validator requires every entry in `candidate_policy.sonar.issue_types` to map from a reviewed `accepted_conditions` row, and it requires the gate condition set to equal -`accepted_conditions` plus `required_conditions`. The installed policy lists `VULNERABILITY` with no -accepted condition, so it fails that contract before SonarCloud is read. Correct the policy in this -app's activation review with Skylar, together with the live gate conditions, before the first run: -the callers cannot run before that review anyway, because their `producer_workflow_id` stays null -until `nightly.yml` is registered on `main` and the signer is promoted to `release`. +`accepted_conditions` plus `required_conditions`. The installed policy lists `VULNERABILITY` with +`new_security_rating` accepted (max 5) and the other five gate conditions required - the same shape +PhotoCraft and WordCraft ship - so it satisfies that contract before SonarCloud is read. `debt` stays +empty, so any unresolved vulnerability on `main` is still refused, and the live gate is still compared +condition by condition against the policy. `producer_workflow_id` is now populated and the signer runs +on `nightly-signer`; the registry's Windows and macOS targets are what still stand between this tree +and a first signed nightly. diff --git a/docs/plugins.md b/docs/plugins.md index 64dc663710..1e98bf058d 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -356,8 +356,10 @@ capability model proposed for PhotoCraft plug-ins `grants.json`, and installs a module that lists permissions only under a grant recorded for this very module, also when it loads the Additional Plug-ins Folder. The approval does not protect against native code linked into VectorCraft or against another program running as the same user, which can change the files in the `Plug-ins` - folder. `grants.json` is not signed, so such a program can add a grant to it. `--allow-plugin-grants` is a choice - the person starting a headless session makes. + folder. `grants.json` carries a MAC made with a key kept in the system key store ([grants file + integrity](#grants-file-integrity)), so a program that only edits the file can't add a grant to it; one running as + the same user can still read the key or change VectorCraft. `--allow-plugin-grants` is a choice the person starting + a headless session makes. - **Replacing asks first.** When the file is another module than the plug-in installed with its id, or, with none installed, its id has settings and a cache in the `Plug-ins` folder, Install Plug-in… and File › Open show its id and SHA-256 and ask whether to install it in place of that plug-in, which gives it the settings and cache kept for @@ -378,7 +380,8 @@ capability model proposed for PhotoCraft plug-ins hexadecimal digits covers nothing. `plugin.remove` forgets the grant, and so does a successful `plugin.install` of a module that lists no permissions under that id, so the earlier bytes need a new approval. When `plugin.remove` can't remove the grant from `grants.json`, it returns an error, the plug-in stays installed, and a second `plugin.remove` - tries again. A refused install leaves the grant, the plug-in installed with the id, the `Plug-ins` folder and the + tries again. The same happens when it can't delete the plug-in's stored module, and the grant stays in `grants.json`. + A refused install leaves the grant, the plug-in installed with the id, the `Plug-ins` folder and the list of disabled plug-ins as they are. When another session installs a plug-in with the id or changes its grant while `plugin.install` checks a module, the install is refused, before anything is written to the `Plug-ins` folder, if the other plug-in would need `replace: true` or the changed grant no longer approves the module. A @@ -395,8 +398,8 @@ capability model proposed for PhotoCraft plug-ins it held and `grants.json` keeps the grant. The new module runs until the session ends. When the grant can't be removed and the module already stored can't be read back or written back, the new module stays in the folder, and the grant stops counting. The grant also stops counting when the folder held no module for that id. A - `grants.json` larger than 1 MiB, or one that is not a JSON list, grants nothing: the new module stays in the folder, - and `plugin.remove` removes the plug-in. A `grants.json` that can't be opened or read counts as a grant that can't be + `grants.json` larger than 1 MiB, or one that is neither a grants object nor a JSON list, grants nothing: the new + module stays in the folder, and `plugin.remove` removes the plug-in. A `grants.json` that can't be opened or read counts as a grant that can't be removed. When VectorCraft loads the `Plug-ins` folder, it forgets any grant for an id whose stored module lists no permissions. When it can't remove that grant from `grants.json`, or can't read the file, the grant stops counting, including for the next load, which tries the removal again. When a later file in the folder holds a module with the @@ -413,8 +416,8 @@ capability model proposed for PhotoCraft plug-ins covers. An entry of `grants.json` that this version can't use (a permission it doesn't know, an invalid id) is skipped and stays in the file until its plug-in is granted again, replaced by a module that lists no permissions, or removed. When such an entry can't be removed from the file, `plugin.install` and `plugin.remove` treat it as a grant - that can't be removed. A `grants.json` that is not a JSON list is never overwritten, and the file is never written - larger than 1 MiB, the most that is read. When a `Plug-ins` folder is in use, only the grants kept in it count for + that can't be removed. A `grants.json` that is neither a grants object nor a JSON list is never overwritten, and + the file is never written larger than 1 MiB, the most that is read. When a `Plug-ins` folder is in use, only the grants kept in it count for `plugin.install`, `plugin.inspect`, `plugin.reload` and the Additional Plug-ins Folder. At startup, a stored plug-in is skipped when no grant covers its bytes and the permissions it lists. The Additional Plug-ins Folder and `plugin.reload` install only plug-ins that such a grant covers, and report the others. A module without a @@ -425,7 +428,8 @@ capability model proposed for PhotoCraft plug-ins - `api` is the plug-in API level the manifest is written for: `1` (the default); `2`, which adds the [host imports](#host-imports-api-level-2), a filter's `inputs` ([reading type, images and symbols](#reading-type-images-and-symbols)) and a live effect's [`paintOutput`](#painted-live-effects); or `3`, which - adds `context` ([document information](#document-information)). A higher one is refused. `plugin.list` and + adds a filter's `writes` ([writing type, images and symbols](#writing-type-images-and-symbols)) and `context` + ([document information](#document-information)). A higher one is refused. `plugin.list` and `plugin.info` give it as `api`. `inputs` is not a permission: the objects it asks for are read under `doc.read`, which a filter that lists `inputs` must list in `permissions`, so installing it asks the user to grant them. `context` is not a permission either: it is read under `doc.read` in the same way, and the install prompt says that the plug-in @@ -454,6 +458,67 @@ geometry, fill rule, reference box and the paints the effect is given: a plug-in changes. Failures are cached too. The swatches and patterns a painted result names are checked against the document each time it is drawn, and a paint linked to a global swatch is drawn in that swatch's current color at its own tint. +#### Grants file integrity + +`grants.json` holds the grants in a JSON object, `{"version": 1, "generation": 3, "grants": [...], "mac": "..."}`. +`mac` is an HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)), in lower-case hexadecimal, of the +folder the file is in, the `generation` and the `grants` list written as compact JSON. The key is 32 random bytes that +VectorCraft makes when it records the first grant. VectorCraft keeps the key in the system key store, as the secret of +the account `hmac-sha256-v1` of the service `org.storytold.vectorcraft.plugin-grants`, written as 64 lower-case +hexadecimal digits, and never in a file: + +- On macOS the key is in the user's Keychain. +- On Windows the key is a generic credential in Credential Manager. +- On Linux and the BSDs the key is in the Secret Service, for example GNOME Keyring. When its collection is locked, + the desktop may ask to unlock it. + +When VectorCraft can't connect to the key store, it tries again the next time it needs the key, so a key store that +starts after VectorCraft is used without a restart. VectorCraft reads the key from the key store each time it checks or +signs `grants.json`, so a key removed or replaced there is not used. + +VectorCraft makes the key while it holds `vectorcraft-plugin-grant-key.lock` in `%LOCALAPPDATA%` on Windows, in the +temporary folder on macOS, and in `$XDG_RUNTIME_DIR` elsewhere. When that file can't be locked, or `%LOCALAPPDATA%` or +`$XDG_RUNTIME_DIR` is not set, no key is made, and approvals last for the session only, as when the key store can't be +reached. + +The key store also keeps a generation for each `Plug-ins` folder, as a secret of 16 lower-case hexadecimal digits (the +generation as an 8-byte big-endian number) of the account `generation-v1-` followed by the SHA-256 of the folder's +resolved path in hexadecimal, in the same service. A key store that holds no generation for a folder counts as +generation 0. VectorCraft reads the generation from the key store only, never from `grants.json`. Each time VectorCraft writes a signed `grants.json`, in the folder's turn (`disabled.lock`), it first +raises the kept generation by two, then writes the file at the generation after the raised one, and then keeps that +generation. When it removes a signed `grants.json`, it raises the generation by two first. The kept generation never +goes down: when the file can't be written or removed after the raise, the generation stays raised, the file left in +place grants nothing, and each plug-in it names that lists permissions asks for approval again. VectorCraft checks +before the raise whether the signed file would be larger than 1 MiB; when it would, VectorCraft logs a warning and +leaves the file and the generation as they are, and the file keeps its grants. When the key store can't keep the generation of a write, the file +just written grants nothing, and the write reports a failure. That file is one generation past the kept one, so the +next raise by two moves past it. When the kept generation is within two of the largest 64-bit value, VectorCraft +logs a warning and leaves the file and the generation as they are. + +VectorCraft compares the MAC in constant time. A `grants.json` without the MAC of its generation, its grants and its +folder, or at another generation than the one the key store keeps for the folder, grants nothing, and each plug-in it +names that lists permissions asks for approval again. This covers a file that an earlier version wrote (a plain JSON +list), a grant that another program edited or added, a file whose `mac` was removed or changed, a file copied from +another `Plug-ins` folder or another computer, an earlier copy of the file put back after a grant was revoked or the +file was removed, a write whose generation the key store didn't keep, a file left in place by a write or removal that +failed after the generation was raised, and a file whose key is no longer in the key store. The next approval replaces such a file with a signed file that holds that grant alone, making a key first when +the key store has none. When a grant is forgotten without an approval (`plugin.remove`, installing a module that lists +no permissions under that id, or a folder load that forgets the grant), VectorCraft raises the generation by two, then +takes that entry out of such a file and leaves the rest unsigned, so no earlier signed copy brings the entry back. It +also raises the generation by two when a grant is forgotten while there is no `grants.json`, or while the file in its +place grants nothing (no valid MAC, too large, or neither a grants object nor a JSON list) and has no entry to take out, +whenever the key store holds a key. A `generation` written into such a file has no effect on the raise. When the key +store can't raise the generation, VectorCraft logs a warning. + +When the key store can't be reached (it is locked, or a headless Linux session has no Secret Service), no +`grants.json` grants anything and VectorCraft writes none: an approval lasts for the session only, the module stored +for the id is not replaced, and `plugin.remove` of a plug-in returns an error and leaves the plug-in installed, as for a +grant that can't be removed. This also happens when there is no `grants.json` or the file doesn't name the plug-in. +`plugin.remove` of an id that isn't installed deletes the module stored for it that didn't load, such as one an +earlier version's `grants.json` approved, and returns `{removed}`. With `VECTORCRAFT_NO_PREFS` set there is no plug-in store, and the web build keeps no grants file. The +MAC does not protect against another program running as the same user, which can read the key from the key store or +change VectorCraft itself. + ## ABI v1 A plug-in is a core WebAssembly module (MVP + these post-MVP features: mutable globals, sign extension, saturating @@ -671,11 +736,17 @@ the module's start function, in a run that isn't a filter's run on a document, o filters](#heavy-filters)). Hosts from before it ignore the key, so there the filter gets a light run's budget. - `api`: the plug-in API level, `1` when left out. `permissions`: what the plug-in may do, a list of names ([permissions](#permissions)); without it, what its kind implies. -- `inputs` (filters at `api` 2 only): the kinds of object besides paths and compound paths the filter reads, any of +- `inputs` (filters at `api` 2 or later): the kinds of object besides paths and compound paths the filter reads, any of `"type"`, `"image"` and `"symbolInstance"`, each at most once (`"inputs": ["type", "image"]`). Left out or `[]`, the filter gets paths and compound paths alone, as before. An unknown, repeated or wrongly typed entry, `inputs` on another kind, below `api` 2, or without a `permissions` list that holds `doc.read`, is refused when the plug-in is installed, and so is `api` 2 on hosts from before it. +- `writes` (filters at `api` 3 only): the kinds among `inputs` the filter may change ([writing type, images and + symbols](#writing-type-images-and-symbols)), each at most once (`"writes": ["type"]`). Left out or `[]`, everything + the filter reads stays read-only. An unknown, repeated or wrongly typed entry, a kind `inputs` doesn't list, `writes` + on another kind, below `api` 3, or without `doc.write` in `permissions`, is refused when the plug-in is installed. + Hosts from before `api` 3 refuse the manifest. A host at `api` 3 that doesn't read `writes` installs the filter, + ignores the key and keeps everything the filter reads read-only, so an output that changes those objects is refused. - `context` (filters, and live effects with `commands`, at `api` 3 only): the parts of the active document a run reads in `_context.document`, any of `"settings"`, `"artboards"`, `"layers"` and `"swatches"`, each at most once (`"context": ["artboards", "layers"]`). Left out or `[]`, a run gets none, as before. An unknown, repeated or wrongly @@ -733,10 +804,12 @@ declares them still installs there: | `help` | Shows what the parameter does when the pointer rests on its label (1–1,000 characters; line breaks allowed). | | `helpUrl` | Opens this `https://` page (at most 512 bytes) from a button after the field. | | `visibleWhen` | `{"pattern": ["lines", "crosshatch"], "outline": [true]}` shows the parameter only while each parameter it names (a checkbox or a choice declared before it) has one of the values listed and is shown itself. | +| `widget` | `"slider"` shows an `int` parameter as a slider over `min..max` with its number field, moving by 1. A `number` parameter with `min` below `max` always shows a slider with its field, with or without the key. The key needs `min` below `max`, and an `int`'s range within ±9,007,199,254,740,992; on any other parameter, or with another value, the manifest is refused at install. | A hidden parameter still goes to the plug-in with its value: what the dialog showed never changes a run. The filter, live-effect and exporter dialogs use all of these keys. The Appearance panel's editor of a plug-in effect's -parameters uses `label`, `unit`, `help` and `visibleWhen`, and lists the parameters without sections or help buttons. +parameters uses `label`, `unit`, `help`, `visibleWhen` and `widget`, and lists the parameters without sections or +help buttons. ### Input @@ -810,7 +883,7 @@ every attribute: "runs": [{"text": "Hello\nthere", "style": {"font_family": "Source Sans 3", "size": 12}}], "paragraphs": [{"justify": "Left"}, {"justify": "Center"}]}, "truncated": false}, - {"id": 18, "type": "image", "bounds": [0, 0, 4, 2], "transform": [2, 0, 0, 2, 0, 0], "pixelSize": [2, 1], + {"id": 18, "type": "image", "bounds": [0, 0, 4, 2], "transform": [2, 0, 0, 2, 0, 0], "opacity": 1, "pixelSize": [2, 1], "colorMode": "rgb", "linked": false, "pixelsOmitted": false, "pixelsBase64": "AAAegGQAHoA="}, {"id": 19, "type": "symbolInstance", "bounds": [100, 0, 110, 10], "transform": [1, 0, 0, 1, 100, 0], "symbolId": "Star", "overrides": {}} @@ -824,7 +897,7 @@ every attribute: true` and empty `runs` and `paragraphs`. The runs and paragraphs of all the type in one input take at most 16 MiB of JSON: type whose runs and paragraphs don't fit what the type before it in paint order left comes with `truncated: true` too. -- An image (`"image"`): `pixelSize` is its width and height in pixels; `colorMode` is `"rgb"`, `"cmyk"`, `"gray"` or +- An image (`"image"`): `opacity` is its opacity, 0 to 1; `pixelSize` is its width and height in pixels; `colorMode` is `"rgb"`, `"cmyk"`, `"gray"` or `"unknown"`, read from the image itself. An image whose corners Perspective Distort or Free Distort moved to a shape that is not a parallelogram also has `corners`, its pixel rectangle's corners on the page (top left, top right, bottom right, bottom left), and its `transform` is then the affine placement nearest them, the one that matches the @@ -844,10 +917,13 @@ every attribute: - A symbol instance (`"symbolInstance"`): `symbolId` is the name of the symbol it shows, with `missing: true` when the document has no symbol of that name. `overrides` is `{}`. -These objects are read only. The output must list each of them exactly once, as `{"id": 17}` alone or exactly as it -was given (numbers compare by value, so `1` and `1.0` are the same). A changed or added field, one left out, an object -listed twice or left out, and a new object with one of these types are refused, and the document and undo history -stay as they were: `objects[1] (id 17): read-only field 'text.runs[0].text' changed`, `objects (id 17): a read-only +Objects of a kind that the manifest's `writes` doesn't list are read only. The output must list each of them exactly +once, as `{"id": 17}` alone or exactly as it was given (numbers compare by value, so `1` and `1.0` are the same). An +image may leave out `opacity`, which hosts before `api` 3 don't give. An object of a kind that `writes` lists is also +listed exactly once, and its entry may give only the fields it changes ([writing type, images and +symbols](#writing-type-images-and-symbols)). An output deletes the paths and compound paths it leaves out +([output](#output)), but none of these objects. A changed or added field, one left out, an object listed twice or left +out, and a new object with one of these types are refused, and the document and undo history stay as they were: `objects[1] (id 17): read-only field 'text.runs[0].text' changed`, `objects (id 17): a read-only object was left out`. The field is named with control and bidirectional characters escaped (`\u{202E}`), cut to 64 characters. New objects listed after one of them go just above it. @@ -861,6 +937,61 @@ the objects after it are written. An output lists at most 100,000 objects, so a objects fails with `plug-in exceeded its object budget (more than 100000 read-only objects)`. An echo of them counts toward the 64 MiB output cap. +### Writing type, images and symbols + +A filter at `api` 3 whose manifest lists some of its `inputs` kinds in `writes`, with `doc.write` in its +`permissions`, may change the objects of those kinds it is given. It returns such an object as `{"id": 17}` alone, +exactly as given, or with the fields it changes; a field it leaves out keeps its value. Each kind takes these fields: + +| Kind | Fields a filter may change | +|------|----------------------------| +| `type` | `name`, `transform`, `text.runs`, `text.paragraphs` | +| `image` | `name`, `transform`, `opacity` | +| `symbolInstance` | `name`, `transform`, `symbolId` | + +```json +{"objects": [ + {"id": 17, "text": {"runs": [{"text": "Goodbye", "style": {"font_family": "Source Sans 3", "size": 14}}]}}, + {"id": 18, "transform": [2, 0, 0, 2, 50, 60], "opacity": 0.5}, + {"id": 19, "symbolId": "Moon"} +]} +``` + +- `name` is a string, or `null` for no name. +- `transform` is six finite numbers, each within ±4,000,000, that don't flatten the object to a line. The object moves + by the change from its given transform, so an image's distorted corners move with it. +- `text.runs` replaces the type's runs: each is `{text, style, inline?}` with the character attributes as the native + file stores them, and an attribute the host doesn't know is refused, as is a key of a fill or stroke that its `type` + doesn't read. There is at least one run, at most 4,096, at most 4,096 paragraphs, and at most 256 KiB of UTF-8 text; + the runs written in one output take at most 16 MiB. Every number in every run's style is + checked against the range `charStyle.new` keeps it to, including a style one of the type's runs already has: size + 0.1 to 1296 pt, leading 0.1 to 5000 pt, tracking and kerning -1000 to 10000, horizontal and vertical scale 1 to + 10000 %, baseline shift -1296 to 1296 pt, rotation -360 to 360°, and the ranges `docs/mcp.md` gives for + `charStyle.new` for the East Asian, Warichu and stroke attributes. A style that none of the type's runs has also needs a font family of 1 to 256 + printable characters, and fills and strokes that a path's appearance would take. Inline graphics stay where they + were: the runs keep each `inline` run as it was given, in the same order. The characters of threaded type, and of + type with ruby, can't change, though their attributes can. The runs and paragraphs of type given with + `truncated: true` can't change. +- `text.paragraphs` holds one paragraph style per paragraph of the new text, each checked as `paraStyle.new` checks + its attributes: indents and space before and after within ±1296 pt, the Hyphenation and Justification options in + their ranges, at most 256 tab stops at 0 to 100,000 pt, and a custom Kinsoku set only by the name of one of the + document's sets, whose characters the paragraph takes. A `text.paragraphs` list returned as it was given next to + changed `text.runs` must also hold one style per paragraph of the new text. With `text.runs` alone, each paragraph keeps its style when + the number of paragraphs stays the same. When runs add or join paragraphs, the host matches the old and new + paragraphs by their text: a paragraph whose text is unchanged keeps its style, changed paragraphs take the styles of + the paragraphs they replace in order, and a paragraph added between others takes the style of the one before it (of + the next one at the start), without a list number. Apart from the paragraphs both texts start and end with, when + the old paragraphs times the new ones pass 262,144, the host pairs them in order instead. +- `opacity` is a number from 0 to 1. +- `symbolId` names a symbol in the document. An instance that shows another symbol loses its overrides, as Replace + Symbol does. + +Every other field, including `type`, `bounds`, `text.kind` and an image's pixels, stays read-only, and objects of these +kinds can't be added or left out. A changed read-only field or a value out of range refuses the whole output, naming +the object and the field (`objects[2] (id 18).opacity: must be a number from 0 to 1`), and the document and undo history +stay as they were. The changes of one run are one undo step, with the type laid out again; an output that changes +nothing records no undo step. The host never reads or gives a linked image's file when a filter writes. + ### Document information A filter, or a live effect with [commands](#commands), whose manifest lists `context` (plug-in API level 3) gets those @@ -948,7 +1079,9 @@ For an **object filter**, the output is the new state of the input objects: - An object without an `id` is new and needs a `path`. It goes just above the object listed before it, or, listed before any input object, just below the first one listed after it. New objects take a path's defaults: no fills or strokes, full opacity. -- Input objects missing from the output are deleted. The order of the input objects themselves doesn't change. +- Input paths and compound paths missing from the output are deleted; type, images and symbol instances can't be left + out ([reading type, images and symbols](#reading-type-images-and-symbols)). The order of the input objects themselves + doesn't change. - `type` turns a path into a compound path (one member per subpath) or back; `name: ""` clears the name. - `guide: true` makes the object a guide, as View › Guides › Make Guides does (a compound path's members become guide paths), and `guide: false` a plain path again; `locked: true` locks it and `locked: false` unlocks it. Objects @@ -1102,7 +1235,7 @@ per change of their input, parameters or paints (results are cached), not per fr - Tool plug-ins (pointer events on the canvas, a guide line or rectangle, geometry back), panel plug-ins, importers that make type, images, layers or artboards, and placed importer files that stay linked to their file. - Live effects that change opacity, blending or effects (at `api` 2 one may [paint](#painted-live-effects) the pieces - it returns), and filters that change type, images or symbol instances (a filter at `api` 2 reads them, see - [`inputs`](#reading-type-images-and-symbols)). + it returns), filters that add or delete type, images or symbol instances or change their pixels and other fields + (a filter at `api` 3 changes [some of their fields](#writing-type-images-and-symbols)). - Scripts can't run object filters (`plugin.*` commands are refused there), so a script doesn't change what Apply Last Filter runs. diff --git a/docs/releasing.md b/docs/releasing.md index bfa3f4e21c..3a4969acca 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -243,10 +243,17 @@ the job fails and asks for a version bump (`cargo xtask version set`). ## Secrets The jobs that sign (macOS, Windows) and the draft-release job run in the `release` environment, -which only the `release` branch can use and which holds the signing secrets. The other jobs get no +which only the `release` branch can use today and which holds the signing secrets. The other jobs get no secrets. Every secret is optional: a missing one produces unsigned artifacts and a warning, never a failed build. +The supervised nightly signer does not sign from `release`: it runs on `refs/heads/nightly-signer`, +which only ever fast-forwards to reviewed main commits, and the `release` environment must admit +`nightly-signer` alongside `release` before the first dispatch. Everything that can reach it is the +trust closure: all of `.github/` and `packaging/`, including `packaging/env.sh`, which +`packaging/macos/import-cert.sh` sources with the Apple keys. Stable releases still come only from +`refs/heads/release`. + | Secret | Used for | |---|---| | `APPLE_CERTIFICATE`, `APPLE_CERTIFICATE_PASSWORD`, `KEYCHAIN_PASSWORD` | the Developer ID certificate (base64 `.p12`), imported into a temporary keychain by `packaging/macos/import-cert.sh` | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 90367efd7c..043ae5c403 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -32,6 +32,8 @@ ## Feature submission evidence +Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. + Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. **Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. @@ -58,7 +60,7 @@ Spiral decay now applies after each full wind of four segments. A newly drawn sp Creating a gradient from solid or empty paint uses the document's color model for its default stops, including drawing its vector with the Gradient tool. Explicit `keepModel: true` retains RGB defaults, and existing gradients keep their own colors. Scores and estimates are unchanged. -**Feature evidence last updated:** 2026-11-19. +**Feature evidence last updated:** 2026-11-20. Window → Help Bar toggles the bottom tool-help strip independently of the status bar. Its visibility is saved with workspaces and UI preferences; Presentation Mode hides both bars. Scores and estimates are unchanged. @@ -80,6 +82,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| | 2026-11-22 | minor | Essentials readiness row: the Shape Builder item names what its 4–8 h still covers: checking #937's fix on the reporter's file, still unconfirmed (the reproduced case is fixed), #8314. Scores and estimates unchanged. | +| 2026-11-20 | minor | G12: Variables panel row context menus implemented with row highlighting, bound-object selection, options, unbinding, selection-based dynamic actions and single-step deletion; headless regression coverage. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged. | | 2026-11-20 | minor | G12: Appearance panel row context menus (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance); right-clicking an unselected row targets that row first. Headless regressions: `panels::tests_appearance`. Scores and estimates unchanged. | @@ -815,6 +818,7 @@ since 2026-10-01. - **EPS Options custom flattener settings:** the help page describes flattening an EPS's transparency with a preset or with custom options, adjusted through Custom ([saving in EPS](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/save-artwork-in-eps-format.html)). EPS Options now has Custom… beside the flattener Preset. It opens Custom Transparency Flattener Options on the settings the export would use: the raster/vector balance, both resolutions, the text and stroke outline switches, Clip Complex Regions and Anti-alias Rasters. OK goes back to EPS Options with the preset shown as [Custom], the export flattens with those settings, and the next EPS Options start from them; choosing a preset drops them, and Cancel goes back to EPS Options unchanged. Preserve Alpha Transparency stays off, and overprints are kept only with Overprints set to Preserve. The [Custom] label, the remembering, the Cancel behavior, Anti-alias Rasters and the ranges (balance 0 to 100, resolutions 1 to 2400 ppi) are VectorCraft's own. Evidence: `dialogs::tests_eps::custom_flattener_options_start_from_the_preset_and_cancel_goes_back_unchanged`, `custom_flattener_options_are_exported_and_remembered_until_a_preset_is_chosen`, `bad_custom_flattener_options_keep_the_dialog_open`. - **EPS export and Discard White Overprint:** the help page describes Discard White Overprint as taking the overprint attribute off white objects in output, without changing the artwork ([white overprint](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/white-overprint.html)). EPS export and PostScript printing, composite and separated, now follow Discard White Overprint in Output (Document Setup), as PDF export does: a white fill or stroke marked to overprint knocks out while the setting is on and overprints while it is off. The same page says the setting covers process white and not spot white, so a white fill linked to a spot swatch that has a color keeps overprinting. The tiles of an overprinting pattern fill overprint with it. Evidence: `cmd::fileio::tests_eps::overprints_are_kept_or_discarded`, `tests::tiles_overprint_with_their_overprinting_pattern`, `tests::white_type_fills_knock_out_with_discard_white_overprint`, `tests::spot_white_fills_overprint_with_discard_white_overprint`, `print::tests::white_overprints_knock_out_on_postscript_plates_with_discard_white_overprint`. - **Save PDF custom flattener settings:** the help page describes the Advanced section's flattener preset for PDF 1.3 saves of transparent art, with a Custom button for adjusting the flattener settings, and says neither is available at PDF 1.4 and later ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)). Save PDF › Advanced now has Custom… beside Flattener preset, enabled for PDF 1.3, PDF/X-1a and PDF/X-3. It opens Custom Transparency Flattener Options on the settings the save would use: the raster/vector balance, both resolutions, the text and stroke outline switches and Anti-alias Rasters; Clip Complex Regions shows on, as the PDF 1.3 writer always clips, overprints are kept only with Overprint set to Preserve, and Preserve Alpha Transparency shows off, as PDF 1.3 rasters keep no alpha. OK goes back to Save PDF with the preset shown as [Custom] and the save flattens with those settings; settings equal to the preset's leave its name, choosing a preset drops them, and Cancel goes back unchanged. PDF presets keep the flattener preset but not these settings, and Save Preset… says so while they are set. `ui.savePdfDialog` keeps a `flattener` it is given. The [Custom] label, the Cancel behavior, Anti-alias Rasters, the editor's absence from the PDF preset editor and the ranges (balance 0 to 100, resolutions 1 to 2400 ppi) are VectorCraft's own. Evidence: `dialogs::save_pdf::tests::custom_is_enabled_where_the_save_flattens`, `custom_starts_from_the_preset_and_cancel_goes_back_unchanged`, `custom_options_are_written_until_a_preset_is_chosen`, `custom_options_equal_to_the_preset_leave_its_name`, `custom_shows_alpha_as_the_pdf_1_3_writer_drops_it`, `save_preset_says_it_leaves_the_custom_flattener_options_out`, `save_pdf_opens_with_the_flattener_options_given_and_refuses_bad_ones`. +- **Save PDF and Print field names for screen readers:** the number, length and range fields of Print (copies, range, width, height, overlap, tile range, gutter, scale, bleed sides, flatness, unprintable margin) and of Save PDF (range, bleed sides, font subset threshold) have a name in the accessibility tree. Evidence: `dialogs::save_pdf::tests::the_range_bleed_and_subset_fields_are_named`, `dialogs::tests_print::every_number_and_length_field_is_named`. - **Raster export backgrounds (#6125):** a raster export draws its background under the finished art, and blend modes read only the art below them, as on the canvas. An Outer Glow in Screen mode on the bare page shows in a PNG on white and in a JPEG. Flatten Transparency puts its white under the finished art the same way. Evidence: `tests::file::a_screen_outer_glow_is_in_raster_exports`, `tests::objectfx::a_screen_outer_glow_on_the_bare_page_shows_on_a_background`, `tests::knockout::page_knockout_and_isolated_blending`, `tests::knockout::no_blend_mode_reads_the_background`, `tests::cmykflatten::every_blend_mode_flattens_to_the_canvas_pixels_in_cmyk`. @@ -840,7 +844,7 @@ since 2026-10-01. - **Composite fonts' custom character sets:** Type › Composite Fonts… › Custom adds named character sets to a composite font, each setting the characters it lists in its own font, style, size, baseline and scales ahead of their class; the later of two sets that list a character sets it ([the help page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Characters are added by Direct Entry or by Unicode code and deleted one at a time; the sets are saved with the document and in `.vccomposite` files (`custom` in `type.compositeFonts.set`). Evidence: `tests::composite::custom_character_sets_take_their_characters_first` (`crates/text`), `compositefonts::tests::custom_character_sets_set_their_characters` (`crates/engine`), `dialogs::composite_fonts::tests::custom_character_sets_are_edited_in_the_dialog` (`crates/ui-egui`). Scores unchanged (estimated). - **Composite fonts' Show Sample:** Type › Composite Fonts… › Show Sample draws the font picked in a line of sample text with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the magnification Zoom picks ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352)). The sample text, the zoom steps and what each line measures are VectorCraft's own. Evidence: `dialogs::composite_fonts::tests::sample_lines_follow_the_parts`, `show_sample_shows_and_hides_the_sample` and `sample_fields_are_set_and_checked` (`crates/ui-egui`). Scores unchanged (estimated). - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). -- **Character-style numeric bounds:** `charStyle.new`, `charStyle.edit`, and `charStyle.setAttrs` accept size from 0.1 to 1296 pt, explicit leading from 0.1 to 5000 pt, horizontal and vertical scale from 1% to 10,000%, and baseline shift and Tate-chu-yoko offsets from -1296 to 1296 pt. Out-of-range input leaves the style and Undo history unchanged; Auto leading remains available. These limits match the Character panel controls. +- **Character-style numeric bounds:** `charStyle.new`, `charStyle.edit`, and `charStyle.setAttrs` accept size from 0.1 to 1296 pt, explicit leading from 0.1 to 5000 pt, horizontal and vertical scale from 1% to 10,000%, baseline shift and Tate-chu-yoko offsets from -1296 to 1296 pt, tracking and kerning from -1000 to 10,000, rotation from -360° to 360°, a stroke miter limit from 1 to 500, Small Caps from 1% to 200%, finite stroke dashes and variable font axis settings. Out-of-range input leaves the style and Undo history unchanged; Auto leading remains available. These limits match the Character panel controls. - **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Character Style Options, Advanced Character Formats:** Character Style Options and New Character Style set a style's Horizontal Scale and Vertical Scale (1% to 10,000%), Baseline Shift (-1296 pt to 1296 pt), the Tate-chu-yoko Settings Up/Down and Left/Right (-1296 pt to 1296 pt), Character Rotation (stored from -180° to 180°) and Language; text that uses the style takes them and keeps its local overrides. Empty fields remain unset, an explicit 100%, 0 pt, 0° or English: USA stays distinct from unset, and the section's Reset Panel clears only these seven. Language sets the language the characters are shaped in, not hyphenation or spelling. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html). - **Character Style Options, Character Color and OpenType Features:** Character Style Options and New Character Style set a style's fill and stroke (None or a document swatch; a global swatch stays linked, with a Tint from 0% to 100%), stroke Weight, Overprint Fill and Overprint Stroke, and its Figure, Position, Standard and Discretionary Ligatures, Contextual, Stylistic and Titling Alternates, Swash, Ordinals, Fractions and Stylistic Sets 1 to 20; text that uses the style takes them and keeps its local overrides, and editing a global swatch later updates the style and its text. Empty controls remain unset, an explicit None, off, Default Figure or Default Position stays distinct from unset, each stylistic set is on, off or unset, a gradient or pattern paint stays until another paint is chosen, a changed OpenType control keeps the style's other feature tags, and each section's Reset Panel clears only its own attributes. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html). @@ -962,6 +966,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Tool option errors:** `tool.setOption` checks every option it is given before it sets any: an option the tool doesn't have, a value of the wrong type, a number outside the tool's range or an unknown choice is an error naming the tool and the option (``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, saved preference or undo step changes; `{}` only reads. Most ranges are the ones each tool's setter clamped to; the Arc tool's `lengthX` and `lengthY` take more than 0 up to 1e6 and the Line tool's `length` 0 to 1e6, where a negative length was taken as its absolute value. The Live Paint tools' `width` and the Shape Builder's `gapLength` are still set to the nearest end of their range. A Tool Options dialog with a refused value stays open. This is VectorCraft's own rule; no score changes. Tests: `option_check::tests` in `vectorcraft-tools`, `tests::toolsettings` in `vectorcraft-engine`, `tests::liquify` in `vectorcraft-mcp`, `dialogs::freehand::tests::a_refused_fidelity_keeps_the_dialog_open`. - **Text command parameter errors:** `text.editRange`'s `insert`, `text.setText`'s `text` and `text.createInPath`'s `mode` and `text` must be strings, `text.createInPath`'s `at` must be two numbers, and `start` in `text.touchType`, `text.glyphAlternates` and `text.setGlyphAlternate` must be a whole number of at least 0. A wrong value is an error naming the parameter, and the document and undo history do not change; null is read as the parameter left out. Pathfinder `precision` takes a number, a string that is all one number or a length with a unit, and refuses a string such as `"1abc"`. This is VectorCraft's own rule; no score changes. Tests: `tests::textedit::text_edits_refuse_a_param_of_the_wrong_type` and `tests::pathops::pathfinder_options_round_trip_and_refuse_bad_values` in `vectorcraft-engine`. - **Automation:** + - Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. - Variables: Update Data Set writes what the art holds into the active data set for the variables that data set holds, and keeps the data set's value for a text, image or graph variable whose objects are locked or inside a locked layer or group; `dataset.update {all: true}` also adds the other variables that the art reports a value for. - Variables: `dataset.select`, `dataset.next` and `dataset.prev` rewrite type and apply the other values on hidden objects and in hidden layers and groups, which stay hidden unless a visibility value shows them, so a layer shown later holds the selected data set's text; objects that are locked or in a locked layer or group are skipped, except by a visibility value. - Variables: a visibility variable binds a locked layer, a locked object and objects inside a locked layer or group, and `dataset.select`, `dataset.next` and `dataset.prev` show and hide them without unlocking them; `dataset.list`, `dataset.capture` and `dataset.update` read whether they show. A text, image or graph variable refuses locked art. @@ -1018,7 +1023,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - SVG Options: Show in Browser opens the SVG in the default web browser, beside Show Code, which shows the code instead; the SVG export options on the help page (https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) list both. VectorCraft writes the SVG of the dialog's current choices for one page to a new folder inside `VectorCraft SVG Preview` in the system's temporary folder, which is kept and cleaned up as Save for Web's previews are, and the dialog stays open without remembering the choices or writing the chosen file. The page is VectorCraft's own choice: under Export Selection the selection's crop, otherwise the first artboard the options choose, and a range the document does not have is an error. The web build disables the button, and control and MCP requests for `file.export.svg.browser` are refused. `crates/ui-egui/src/dialogs/svg_options.rs` (`show_in_browser_opens_what_ok_writes_without_confirming`, `show_in_browser_is_refused_on_the_web_and_for_automation`, `svg_preview_folders_leave_save_for_web_previews_alone`). - Save for Web: Optimize to File Size… opens rows for a desired file size in K, Start With (Current Settings, Auto Select GIF/JPEG) and, with slices, Use (Total of All Slices, Each Slice, Current Slice); OK takes the settings whose files fit and shows the size found, or says that no setting tried fits ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=395)). The search lowers JPEG quality or palette colors (GIF then lossy) and encodes at most 32 trial settings; Auto Select chooses GIF for transparent art or art of at most 256 colors and JPEG otherwise. The slices share one setting, so every Use choice changes all of them (`webExport.optimizeToFileSize`). Scores and estimates are unchanged. - Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`). - - Save for Web: with Transparency on, GIF and PNG-8 exports take a Transparency Dither (none, diffusion, pattern and noise), which makes part of the partly transparent pixels transparent and keeps the rest instead of cutting them at half opacity, with an amount for diffusion ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400)). These rules are VectorCraft's own: the default is none with amount 100; with pattern, noise, or diffusion at amount 100, about as many pixels stay opaque as their opacity says, and a lower diffusion amount comes closer to none; pattern uses an 8×8 ordered pattern and noise a fixed noise, so the same art always gives the same file; amount 0 gives the same file as none; fully transparent and fully opaque pixels do not change, and a kept pixel is blended over the matte as before; without Transparency both settings are kept and do not change the file; presets and the remembered settings keep them (`document.exportForWeb`, `webExport.settings`: `transparencyDither`, `transparencyDitherAmount`). The Save for Web dialog does not show these settings yet; its previews and Save… use the remembered ones, and a preset picked in the dialog does not change them. + - Save for Web: with Transparency on, GIF and PNG-8 offer Transparency Dither (No Transparency Dither, Diffusion, Pattern and Noise), which makes part of the partly transparent pixels transparent and keeps the rest instead of cutting them at half opacity, with an Amount for Diffusion ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=400)). These rules are VectorCraft's own: the default is No Transparency Dither with Amount 100; with Pattern, Noise, or Diffusion at Amount 100, about as many pixels stay opaque as their opacity says, and a lower Diffusion Amount comes closer to No Transparency Dither; Pattern uses an 8×8 ordered pattern and Noise a fixed noise, so the same art always gives the same file; Amount 0 gives the same file as No Transparency Dither; fully transparent and fully opaque pixels do not change, and a kept pixel is blended over the matte as before; both rows are disabled while Transparency is off and keep their values; presets and the remembered settings keep them (`transparencyDither`, `transparencyDitherAmount`). + - Export As: GIF and PNG-8 Options offer the same Transparency Dither and Amount as Save for Web, disabled while Transparency is off, and `document.export` takes `transparencyDither` and `transparencyDitherAmount` for GIF and PNG-8 with the same values, refusing an unknown method or an amount that is not a whole number from 0 to 100; other formats do not read the keys, and the warnings name them. Using Save for Web's keys in the other export is VectorCraft's own rule. `crates/engine/src/cmd/fileio/tests_palette.rs` (`palette_exports_take_the_transparency_dither`), `crates/ui-egui/src/dialogs/tests_raster_formats.rs` (`palette_options_send_the_transparency_dither`, `palette_options_name_the_transparency_dither_controls`). - Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged. - Save for Web: double-clicking a GIF or PNG-8 color-table swatch opens the Color Picker, and its OK changes that color to the one picked everywhere it appears in the image. The swatch then shows the original color in its upper-left half and the new one in its lower-right half, with the lock mark, and the color stays through a lower color count. Double-clicking a changed swatch opens the picker on the original color, and OK on it changes the color back; Unshift All Colors in the table's menu undoes every change, web shifts included ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). These rules are VectorCraft's own: Cancel changes nothing; a changed color wins over Web Shift, Web Snap and Lock, and pressing Web Shift replaces it; a color mapped to transparent stays transparent; two colors may change to the same color; a changed color takes a kept palette slot before a locked one, and one slot always stays for the reduction; the change is kept by source color when the reduction changes and applies only while that source is in the table; presets and the remembered settings keep it; the picker opens with Only Web Colors off (`colorTable.shifted`). GIF lossy compression moves no pixel into or out of a changed color. Scores and estimates are unchanged. - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). @@ -1040,7 +1046,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. @@ -1098,9 +1104,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread uses the iterator protocol (see the `for`-`of` line below). Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`. - - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. + - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. + - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. + - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column. `all`, `allSettled` and `race` take arrays, objects with a whole-number `length` and strings, and do not read `Symbol.iterator`, and the statics always make plain `Promise` objects (VectorCraft's own rules). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. @@ -2699,6 +2706,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size, before any of it is read when `importer` names the importer) and `_context.mode` `"place"`, and its objects are placed as one group named after the file, in the order it returned them, at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. +- **Plug-in int parameters as sliders (G17):** an `int` parameter with `"widget": "slider"` shows a slider over its range with its number field, in the filter, live-effect and exporter dialogs and in the Appearance panel's effect editor; the manifest is refused at install when the parameter cannot have one. Regressions: `crates/plugins/src/dialog.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`. Scores and hours unchanged. - **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged. - **Live-effect plug-ins before a fill's or stroke's own 3D effect:** a live effect listed before a fill's or stroke's own Extrude & Bevel, Inflate or Rotate effect is given `_context.item` for that fill or stroke (`{"fill": i}` or `{"stroke": i}`), not `"object"`, in the drawn art, in the 3D meshes and in Expand as Wireframes; a deferred stage there is listed at that fill's or stroke's place. Regressions: `crates/effects/src/tests/solidcontext.rs`. Scores and hours unchanged. - **Filter plug-ins set effects and stroke styles (G17):** a filter is given each object's effect records and its strokes' `join`, `cap` and `miterLimit`, and may return them; the records are admitted as `effect.apply` admits them (a known effect or installed live-effect plug-in, parameters it takes, one 3D effect that fits, no texture read from a file), and one refused refuses the output. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. @@ -2715,11 +2723,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Bulk memory fuzz cases use the host's fuel constants:** `crates/engine/tests/plugin_fuzz.rs` samples runs around one slice of the instruction budget and lengths around the bytes one unit of fuel pays for with `vectorcraft_plugins`' own `FUEL_SLICE` and `BYTES_COPIED_PER_FUEL`, so the sampled cases move when either value changes. Regressions: `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Plug-in permissions (G17):** a manifest may list `permissions` (`doc.read`, `doc.write`, `state`, `effect.render`, `export.write`; the first three follow storytold/photocraft#662) and an `api` level; without the list a plug-in gets what its kind implies and installs as before. Install Plug-in… and File › Open show the name, id, version, file SHA-256 and each permission in plain words, with control and bidirectional characters escaped, and install nothing on Cancel; for a plug-in that lists permissions, `plugin.install` needs `grant` and folders install it only when it is granted. The grant is kept with the module's hash, a module asking for more asks again, and a filter run refuses output its permissions don't allow. Regressions: `crates/plugins/src/permissions.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins read type, images and symbol instances (G17, #4333):** a filter at plug-in API level 2 lists `inputs` (`type`, `image`, `symbolInstance`) with `doc.read` in its `permissions`, so installing it asks for approval, and is also given the selected objects of those kinds, read only: type with its runs, character and paragraph attributes (no text past 256 KiB or 4,096 runs or paragraphs, or 16 MiB of runs over the input), images with their size, color mode and, when embedded and at most 1 MiB in base64 (16 MiB over the input), their RGBA pixels (a CMYK image's through the working CMYK profile; never a linked file's), and symbol instances with their symbol and transform. The objects come in paint order from the bottom, and an image that reaches the decoder counts toward the 16 MiB of pixels even when decoding fails. Every object counts toward the input's half of the memory cap; one whose fields besides its pixels and runs don't fit fails the run naming it and its size, a path or compound path that doesn't fit fails it too, and so do more than 100,000 of these objects. Its output returns each as `{id}` or exactly as given; any change or omission is refused before the document changes. Filters without `inputs` get the same input as before, except that compound paths that clip a clip group and paths inside a group that clips one are left out for every filter. Regressions: `crates/plugins/src/objects/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. +- **Filter plug-ins change type, images and symbol instances (G17):** a filter at plug-in API level 3 lists in `writes` the kinds among its `inputs` it may change, with `doc.write` in its `permissions`, and may return those objects with changed fields: type's runs (characters and character attributes, inline graphics kept as they were) and paragraph styles, an image's transform and opacity, an instance's transform and the symbol it shows (one already in the document; its overrides are cleared as Replace Symbol clears them), and each one's name. Runs are held to the input's limits (4,096 runs and 256 KiB of text a type object, 16 MiB over the output), every number in every run's and paragraph's style is checked against the range `charStyle.new` and `paraStyle.new` keep it to (one shared check, also for a style the type already has), a custom Kinsoku set must be one of the document's, a style of the filter's own needs a font family and its paints are checked as a path's are, and the characters of threaded type and type with ruby stay as they were. Any other changed field, or a value out of range, refuses the run naming the object and the field, with the document unchanged. The changes are one undo step, and an output that changes nothing, for every filter, records none. Images now also come with their `opacity`. Regressions: `crates/plugins/src/objects/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-ins read document information without a selection (G17):** a filter, or a live effect with commands, at plug-in API level 3 lists `context` (`settings`, `artboards`, `layers`, `swatches`) with `doc.read` in its `permissions`, so installing it asks for approval and the prompt names the document information, and each filter or command run is given those sections in `_context.document` whether or not anything is selected: the document's name without its folder, color mode, units, active artboard size, bleed and raster effects resolution; every artboard's id, index, name, rectangle and whether it is active; every layer and sublayer with its id, parent, depth, name, own visibility, lock and template settings, color and whether it is current; and every swatch as `swatch.list` lists it, with the document's revision. No path, object or other document is given, and drawing a live effect gets none. More than 10,000 rows or 4 MiB of them fail the run before the plug-in starts, and each row takes 1,000 instructions from its budget (VectorCraft's own values). Regressions: `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in grants cover one module (G17):** a grant counts only for the module with the id and SHA-256 it records. A module that lists permissions and has other bytes under the same id needs a new approval, even with the same permissions: `plugin.inspect` reports `needsApproval`, `plugin.install` refuses it without `grant`, Install Plug-in… and File › Open ask again, and the plug-in store and plug-in folders skip it. A module with a missing or empty permissions list needs no grant; without the list, it gets its kind's implied permissions. A grant with a malformed hash covers nothing. Regressions: `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in approval needs a person (G17):** a plug-in's permissions and heavy budget are approved in a dialog that only a person can confirm: the control channel, MCP and injected input are refused, and `plugin.install` takes `grant` or `allowHeavy` only with that approval. `vectorcraft-cli mcp` and `run` refuse them unless started with `--allow-plugin-grants`. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/automation.rs`, `apps/vectorcraft-cli/tests/it/cli.rs`. Scores and hours unchanged. - **A dialog's OK runs what it was opened for:** `ui.dialog.set`, and MCP's `answer_dialog` through it, can set a `__` field only when it is a control of that kind of dialog (a section or tab shown, a link between two fields, a name or search being typed). Every other `__` field, such as the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command` and `__plugin`, or the paste a swatch conflict waits to finish, is refused with "the `` dialog cannot set protected field ``"; the request sets no field, and with `action: "confirm"` OK does not run. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/control/tests.rs`. Scores and hours unchanged. -- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user, the unsigned `grants.json`). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **A refused plug-in install writes nothing (G17):** `plugin.install` checks the plug-in installed under the module's id and its grant again while it records the grant and installs the module (`registry::install_checked`), and only then writes the module and its grant to the `Plug-ins` folder, attaches its settings and cache and turns a disabled plug-in on. When another session installed a plug-in with the id that would need `replace: true`, or changed the grant the checks relied on, the install is refused and the folder, `grants.json`, the disabled list and the installed plug-in stay as they were. Without a plug-in store, the approval comes from the grant the install checks again. A `plugin.remove`, or a load of the folder or of a plug-ins folder, in another session waits until the install has written the folder. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **A plug-in's manifest from a custom section (G17):** a module that carries its manifest in a `vc_manifest` custom section, with `"abi": 1`, is inspected, installed and loaded at startup without being instantiated, so none of its code runs (its start function, data segments, `vc_abi_version` and `vc_manifest`); the host checks its imports against the manifest's permissions, its `memory`, `vc_alloc` and `vc_run` exports by type, and its initial memory and tables against the limits its runs have. A repeated section, one over 64 KiB, or one that is not a valid manifest or gives another `abi` is refused. Such a module whose start function traps installs and fails at each run. Modules without the section load as before. The example plug-in carries the section. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Windows and processes take turns on the Plug-ins folder:** each one locks `disabled.lock` in the `Plug-ins` folder while it reads and changes the stored modules, `grants.json`, `disabled.json` and the plug-ins' settings and caches, so two installs of one id keep each module with its own grant, and grants or settings written by two processes are all kept. When the file can't be locked, `plugin.install` and `plugin.remove` fail and change nothing. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. @@ -2727,6 +2736,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **An install automation asked for needs the person to start it (G17):** an approval question that a control request, MCP, injected input or a file dialog one of them opened leads to keeps OK disabled and refuses every confirm, a person's click included; it says to choose Object › Plug-ins › Install Plug-in…, and `ui.installPlugin` answers `approval: "personMustStartInstall"`. The person's own Install Plug-in…, File › Open or drop inspects the module again and asks a new question. Automation's `replace: true` no longer skips the question about taking another module's place, and that question now opens in the approval dialog for everyone. VectorCraft's own rule. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **A plug-in with no permissions ends its id's grant (G17):** installing a module that lists no permissions under a granted id forgets the grant, in the process and in `grants.json`, so the formerly approved bytes need a new approval. Attaching a `Plug-ins` folder whose module for that id lists no permissions forgets it too, and plug-in folders forget the process's grant. A refused install leaves the grant. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_safe_mode.rs`. Scores and hours unchanged. - **A grant that can't be forgotten stops counting in the whole process (G17):** when such a grant can't be removed from `grants.json`, no session in the process that uses the same `Plug-ins` folder, by any path to it, counts it for `plugin.inspect`, `plugin.install` or loading plug-ins, until `grants.json` can be written for that plug-in; another process on the folder reads `grants.json` as it is. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **An edited grants file grants nothing (G17):** `grants.json` carries a generation and an HMAC-SHA-256 of its folder, generation and grants, made with a random key kept in the system key store (Keychain, Credential Manager, the Secret Service) and compared in constant time; the key store keeps each folder's generation, raised on every signed write and removal and never lowered. A file without that MAC or at another generation (an earlier version's plain list, an edited or added grant, a removed or changed MAC, a file copied from another folder, an earlier copy put back after a revoke, a write whose generation wasn't kept, a file left in place by a write or removal that failed after the generation was raised) grants nothing, and its plug-ins ask for approval again; the next approval replaces it with a signed file, and `plugin.remove` of a stored plug-in that didn't load deletes its module and reports it removed. When the key store can't be reached, an approval lasts for the session only, the file is left as it is, and `plugin.remove` fails and leaves the plug-in installed. A key store that can't be reached is tried again the next time it is needed. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/src/store/grant_keys.rs`. Scores and hours unchanged. - **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin..` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) unless its manifest places it in another menu, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in commands in other menus (G17):** at plug-in API level 2 a command's `menu` (`{path, after?}`) lists it in one of 14 menus of Edit, Object, Type, Select, Effect and View (never File, Window, Help, the application menu or a submenu that lists files, fonts, panels or plug-ins), right after the built-in item `after` names or at the end of the menu, with the plug-in's name in parentheses after its label. Keyboard Shortcuts, the command palette and `command_list` list it under that menu, and `plugin.list` gives its `menu`. Commands at one spot keep plug-in id order and then manifest order; a filter whose commands are all placed elsewhere is a single item in Object › Plug-ins, and such a live effect is a single item in Effect › Plug-ins. A command whose label with the plug-in's name reads like a built-in item or submenu of that menu, or like a command a plug-in with a lower id places there, stays in its plug-in's submenu. Any other `menu` is refused by command when the module is installed; at API level 1 the key is still ignored. VectorCraft's own rule. Regressions: `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. A command counts as taking a file or folder when its params description or schema names a file key as a param; a word in the description's prose or result does not count. Each exemption for a key that names part of the document names a param its command takes, which `every_command_is_sorted` checks, and Image Trace's path fidelity setting (`params.paths`, `savedPreset.paths`) is exempt only inside those settings. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 29cc1b5a18..e4e7cbbbea 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -416,7 +416,9 @@ the type shortcuts (tracking/kerning/leading/baseline steps with Alt/Shift), and Layers panel. The shortcut editor also lists the commands that are in no menu but run without parameters (Edit › Duplicate, panel-menu commands such as Break Link to Symbol), so they can be given shortcuts (#1539). It lists each button of the Align panel's Align Objects, Distribute Objects and Distribute Spacing rows under Align, with no default shortcut, and a -shortcut set there runs what a click on the button runs, with the panel's Align To choice and Distribute Spacing value. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). +shortcut set there runs what a click on the button runs, with the panel's Align To choice and Distribute Spacing value. +It also lists the panel and dialog commands whose parameters are all optional, such as New Swatch…, Brush Options… +and Corners…, and a shortcut set there opens the dialog for the selection or says in the status bar why it cannot. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Cmd/Ctrl+Alt+. (`stroke.weightUp`, Stroke Weight Up) and Cmd/Ctrl+Alt+, (`stroke.weightDown`, Stroke Weight Down), the keys a [public feature request reply](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/32307397-increment-decrement-stroke-weight-key-commands) gives them, step the weight of each selected stroke from its own weight: by a quarter unit of Units › Stroke up to one unit, then by whole units, down to a quarter unit; with nothing selected they step the weight of the next object drawn (#5797). diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index c3c0b3e399..d0a2037a61 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 """Local regression checks for VectorCraft nightly workflow and signing-policy contracts.""" import copy +from decimal import Decimal import json from pathlib import Path import re @@ -9,6 +10,23 @@ import unittest ROOT = Path(__file__).resolve().parents[1] INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json" + +def security_bound_problem(maximum): + """None when an accepted security-rating maximum is the reviewed whole A..E rating. + + Decimal, not float: "5.0000000000000001" rounds to 5.0 as a float, so the shared candidate + contract would refuse a bound this suite had already accepted. + """ + value = Decimal(maximum) + if int(value) != value: + return "the A..E bound is a whole rating" + if not 1 <= value <= 5: + return "the security bound stays A..E" + return None + +APP_NAME = "vectorcraft" +PRODUCER_WORKFLOW_NAME = "VectorCraft unsigned nightly" + NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64") # Each platform's one trust field in policy v3, and the public stable identity it must name. NIGHTLY_TRUST = { @@ -262,7 +280,7 @@ class NightlyEnabledCallers(unittest.TestCase): "github.ref_type == 'branch' && (github.event_name == 'schedule' || " "github.event_name == 'workflow_dispatch')", "nightly-sign.yml": "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'", } def test_enabled_jobs_keep_exact_context_guards(self): @@ -334,7 +352,8 @@ class NightlyInstalledPolicy(unittest.TestCase): self.assertEqual(set(self.policy), expected) self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3") self.assertEqual(self.policy["repository"], "storytold/vectorcraft") - self.assertEqual(self.policy["release_branch"], "release") + self.assertEqual(self.policy["release_branch"], SIGNER_BRANCH, + "the signer runs on its dedicated branch") self.assertIs(type(self.policy["repository_id"]), int) self.assertGreater(self.policy["repository_id"], 0) producer_id = self.policy["producer_workflow_id"] @@ -425,6 +444,360 @@ class NightlyInstalledPolicy(unittest.TestCase): self.assertIn(item["type"], sonar["issue_types"]) self.assertRegex(item["hash"], r"^[0-9a-f]{32}$") + def test_sonar_policy_keeps_the_shared_candidate_contract(self): + """The Sonar shape craft-common-actions' candidate contract() admits, refused here first. + + An empty issue scope, an accepted condition outside the reviewed issue types, a metric in both + lists, a missing live gate condition or a widened security bound is refused at admission, so + this suite must catch it before a nightly run can. `debt` stays empty, so any unresolved + vulnerability on main is still refused; accepting the new-code rating only records the + reviewed A threshold instead of demanding a clean rating the live gate does not. + """ + sonar = self.policy["candidate_policy"]["sonar"] + accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL", + "security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"} + gate = {"new_reliability_rating", "new_security_rating", "new_maintainability_rating", + "new_coverage", "new_duplicated_lines_density", "new_security_hotspots_reviewed"} + self.assertTrue(sonar["issue_types"], "an empty issue scope is refused as unreviewed") + self.assertEqual(len(sonar["issue_types"]), len(set(sonar["issue_types"]))) + metrics = {} + for field in ("accepted_conditions", "required_conditions"): + for condition in sonar[field]: + with self.subTest(field=field, metric=condition.get("metric")): + expected = {"metric", "comparator", "error_threshold"} + if field == "accepted_conditions": + expected.add("maximum") + self.assertEqual(set(condition), expected) + self.assertNotIn(condition["metric"], metrics, "one condition per gate metric") + metrics[condition["metric"]] = condition + self.assertIn(condition["comparator"], ("GT", "LT")) + self.assertRegex(condition["error_threshold"], r"^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$") + if field != "accepted_conditions": + continue + self.assertIn(condition["metric"], accepted, "an accepted metric outside the reviewed map") + self.assertIn(accepted[condition["metric"]], sonar["issue_types"], + "an accepted failure must lie inside the reviewed issue scope") + self.assertEqual(condition["comparator"], "GT") + self.assertRegex(condition["maximum"], r"^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$") + maximum = Decimal(condition["maximum"]) + if condition["metric"] in ("security_rating", "new_security_rating"): + self.assertIsNone(security_bound_problem(condition["maximum"]), + "the security bound stays the reviewed whole A..E rating") + self.assertEqual(condition["error_threshold"], "1", "the reviewed A threshold stays") + else: + self.assertLessEqual(maximum, len(sonar["debt"]), "accepted failures exceed the reviewed debt") + self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"]), + "accepted conditions and reviewed issue types must cover the same scope") + self.assertEqual(set(metrics), gate, "every live gate condition stays gated exactly once") + + def test_security_bound_rejects_a_maximum_float_rounds_to_five(self): + """The shared candidate contract reads the bound as a decimal; float() would hide the widening.""" + self.assertIsNone(security_bound_problem("5")) + self.assertIsNone(security_bound_problem("5.0")) + self.assertEqual(security_bound_problem("5.0000000000000001"), "the A..E bound is a whole rating") + self.assertEqual(security_bound_problem("6"), "the security bound stays A..E") + + +SIGNER_BRANCH = "nightly-signer" +SHARED = "storytold/craft-common-actions/.github/workflows/" +# App workflows reviewed to call the shared stable release.yml. That callee must carry the +# stable-only environment guard (dry runs and non-release refs bind no environment); the +# nightly-signer settings scan checks the resolved callee before creating or advancing the branch. +REVIEWED_STABLE_RELEASE_CALLERS = {"release.yml"} + + +def app_workflows(): + return {path.name: path.read_text() for path in sorted((ROOT / ".github/workflows").glob("*.y*ml"))} + + +WORKFLOW_KEY = re.compile(r'''("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s'"#{}\[\],:&*!|>%@`?-][^:#,{}]*?|-[^\s:#][^:#,{}]*?)\s*:(?:\s+(.*))?$''') + + +def _workflow_key(text): + if text.startswith('"'): + return None if "\\" in text else text[1:-1] + if text.startswith("'"): + return text[1:-1].replace("''", "'") + return text + + +def _workflow_value(text): + """A one-line scalar value without its comment and quotes; None when escaped or unterminated.""" + text = text.strip() + if text.startswith('"'): + quoted = re.match(r'"((?:[^"\\]|\\.)*)"\s*(?:#.*)?$', text) + return None if quoted is None or "\\" in quoted.group(1) else quoted.group(1) + if text.startswith("'"): + quoted = re.match(r"'((?:[^']|'')*)'\s*(?:#.*)?$", text) + return None if quoted is None else quoted.group(1).replace("''", "'") + return re.split(r"\s+#", text, maxsplit=1)[0].strip() + + +def _strip_comment(text): + """(text without its comment, unterminated) using a quote-aware scan. + + As in YAML, a quote opens a quoted scalar only where a scalar starts (line start or after + `:`, `-`, `,`, `{` or `[`), and a `#` starts a comment only outside quotes, at the start or + after whitespace. + """ + quote, index = None, 0 + while index < len(text): + char = text[index] + if quote == '"': + if char == "\\": + index += 2 + continue + if char == '"': + quote = None + elif quote == "'": + if char == "'": + if text[index + 1:index + 2] == "'": + index += 2 + continue + quote = None + elif char in "\"'" and text[:index].rstrip()[-1:] in ("", ":", "-", ",", "{", "["): + quote = char + elif char == "#" and (index == 0 or text[index - 1] in " \t"): + return text[:index].rstrip(), False + index += 1 + return text.rstrip(), quote is not None + + +FLOW_QUOTED = re.compile(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'") +FLOW_FORBIDDEN_KEYS = {"environment", "uses"} + + +def workflow_entries(source): + """Every mapping entry in a workflow, plus the YAML forms this reader refuses. + + A narrow reader, not a YAML parser (none ships with the runner's Python). Each entry is + (line, key, value, multiline): plain, single- and double-quoted keys and one-line values in + block and simple one-line flow mappings. Block scalar bodies are skipped, and an entry whose + value is a block scalar or continues on the next lines is marked multiline. It refuses whatever + could hide a key from it: escaped double-quoted keys, explicit `?` keys, merge keys, anchors, + aliases, tags, tab indentation and nested or multi-line flow. + """ + lines = source.splitlines() + entries, refused, block = [], [], None + + def continues(index, indent): + for follow in lines[index + 1:]: + stripped = follow.strip() + if not stripped or stripped.startswith("#"): + continue + deeper = len(follow) - len(follow.lstrip(" ")) > indent + return deeper and not stripped.startswith("- ") and WORKFLOW_KEY.match(stripped) is None + return False + + for index, raw in enumerate(lines): + number = index + 1 + stripped = raw.strip() + indent = len(raw) - len(raw.lstrip(" ")) + if block is not None: + if not stripped or indent > block: + continue + block = None + if not stripped or stripped.startswith("#"): + continue + if "\t" in raw[:indent + 1]: + refused.append(f"line {number}: tab indentation"); continue + body, unterminated = _strip_comment(stripped) + if unterminated: + refused.append(f"line {number}: unterminated or multi-line quoted scalar"); continue + if not body: + continue + while body.startswith("- "): + body = body[2:].lstrip() + if body == "?" or body.startswith("? "): + refused.append(f"line {number}: explicit key"); continue + match = WORKFLOW_KEY.match(body) + value = body + if match is not None: + key, value = _workflow_key(match.group(1)), match.group(2) or "" + if key is None: + refused.append(f"line {number}: escaped double-quoted key"); continue + if key == "<<": + refused.append(f"line {number}: merge key"); continue + plain = re.sub(r"\$\{\{.*?\}\}", "", value).strip() + bare = re.sub(r"\"(?:[^\"\\]|\\.)*\"|'(?:[^']|'')*'", "''", plain) + if re.match(r"[&*!]", plain): + refused.append(f"line {number}: anchor, alias or tag") + is_block = re.fullmatch(r"[|>][0-9+-]*", plain) is not None + if match is not None: + entries.append((number, key, _workflow_value(value), + is_block or ((value == "" or not is_block) and continues(index, indent)))) + if "{" in bare and bare != "{}": + masked = re.fullmatch(r"\{([^{}\[\]]*)\}", FLOW_QUOTED.sub("''", value.strip())) + flow = re.fullmatch(r"\{([^{}\[\]]*)\}", value.strip()) + if any(set(scalar[1:-1]) & set("#{}[],") for scalar in FLOW_QUOTED.findall(value)): + refused.append(f"line {number}: flow mapping quoted scalar with # or flow punctuation") + elif masked is None or flow is None: + refused.append(f"line {number}: nested or multi-line flow mapping") + else: + # The masked text only proves the shape: a quoted key ("uses", 'environment') keeps + # its identity, so the entries are read from the original mapping text, never ''. + for item in flow.group(1).split(","): + entry = WORKFLOW_KEY.match(item.strip()) + key = _workflow_key(entry.group(1)) if entry else None + if key is None: + refused.append(f"line {number}: unreadable flow mapping entry") + elif key in FLOW_FORBIDDEN_KEYS: + refused.append(f"line {number}: {key} in a flow mapping (must be block style)") + else: + entries.append((number, key, _workflow_value(entry.group(2) or ""), False)) + if match is not None and is_block: + block = indent + return entries, refused + + +def workflow_keys(source): + """(line, key) for every mapping entry, plus the refused YAML forms.""" + entries, refused = workflow_entries(source) + return [(number, key) for number, key, _, _ in entries], refused + + +SHARED_CALLEE = re.compile(r"storytold/craft-common-actions/\.github/workflows/([\w.-]+\.ya?ml)@(\S+)", re.IGNORECASE) +INSPECTED_KEYS = {"environment", "uses"} + + +def trust_closure_problems(workflows): + """The nightly-signer trust-closure scan over app workflow sources; empty when the tree is safe. + + Every key it inspects comes from workflow_entries(), never a regex over the raw text. + """ + problems, stable_callers, signer_calls = [], set(), 0 + for name, source in workflows.items(): + entries, refused = workflow_entries(source) + problems.extend(name + " uses YAML the scan cannot read (" + reason + ")" for reason in refused) + for number, key, value, multiline in entries: + if key not in INSPECTED_KEYS: + continue + if key == "environment": + problems.append(f"{name} binds an environment directly (line {number})") + continue + if value is None or multiline: + problems.append(f"{name} has a uses value the scan cannot read (line {number})") + continue + callee = SHARED_CALLEE.fullmatch(value) + if callee is None: + if re.search(r"craft-common-actions", value, re.IGNORECASE) and re.search(r"workflows/(nightly-)?release\.ya?ml", value, re.IGNORECASE): + problems.append(f"{name} has an unrecognised shared release caller (line {number})") + continue + workflow, ref = callee.group(1), callee.group(2) + if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"): + if name == "nightly-sign.yml": + signer_calls += 1 + if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref): + problems.append(name + " calls nightly-release.yml@" + ref) + if workflow.lower() in ("release.yml", "release.yaml"): + stable_callers.add(name) + if ref != "main" and not re.fullmatch(r"[0-9a-f]{40}", ref): + problems.append(name + " calls release.yml@" + ref + "; use @main or a reviewed full SHA") + if stable_callers != REVIEWED_STABLE_RELEASE_CALLERS: + problems.append("shared release.yml callers are " + ", ".join(sorted(stable_callers))) + if signer_calls != 1: + problems.append("nightly-sign.yml must call nightly-release.yml exactly once") + return problems + + +class NightlySignerBranchTrustClosure(unittest.TestCase): + """On refs/heads/nightly-signer, only the pinned signer caller may reach an environment.""" + + def test_trust_closure_scan_passes_on_this_tree(self): + self.assertEqual(trust_closure_problems(app_workflows()), []) + + def test_trust_closure_scan_refuses_each_route_into_an_environment(self): + tree = app_workflows() + bad = { + "a workflow binds an environment": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment: release\n"}, + "a double-quoted environment key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environment": release\n'}, + "a single-quoted environment key": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n 'environment' : release\n"}, + "an environment mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n environment:\n name: release\n"}, + "an environment in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {runs-on: ubuntu-latest, environment: release}\n"}, + "an escaped key": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n "environ\\u006dent": release\n'}, + "a merge key": {**tree, "extra.yml": "base: &b\n runs-on: ubuntu-latest\njobs:\n x:\n <<: *b\n"}, + "an explicit key": {**tree, "extra.yml": "jobs:\n x:\n ? environment\n : release\n"}, + "a nested flow mapping": {**tree, "extra.yml": "jobs:\n x: {steps: [{run: a}]}\n"}, + "a double-quoted uses key copying the signer": {**tree, "extra.yml": 'jobs:\n x:\n "uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a single-quoted uses key": {**tree, "extra.yml": "jobs:\n x:\n 'uses': " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a quoted uses value": {**tree, "extra.yml": 'jobs:\n x:\n uses: "' + SHARED + "nightly-release.yml@" + "a" * 40 + '"\n'}, + "uses in a flow mapping": {**tree, "extra.yml": "jobs:\n x: {uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, + "a differently cased owner": {**tree, "extra.yml": "jobs:\n x:\n uses: Storytold/Craft-Common-Actions/.github/workflows/nightly-release.yml@" + "a" * 40 + "\n"}, + "a folded uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: >-\n " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a continued uses value": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "\n nightly-release.yml@" + "a" * 40 + "\n"}, + "a quoted second signer call": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"] + " again:\n \"uses\": " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a hash inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a} # b", runs-on: ubuntu-latest, environment: release, steps: []}\n'}, + "a single-quoted hash in a flow scalar": {**tree, "extra.yml": "jobs:\n x: {name: 'a # b', runs-on: ubuntu-latest}\n"}, + "a comma inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "a, environment: release", runs-on: ubuntu-latest}\n'}, + "a bracket inside a quoted flow scalar": {**tree, "extra.yml": 'jobs:\n x: {name: "[a]", runs-on: ubuntu-latest}\n'}, + "an unterminated quote": {**tree, "extra.yml": 'jobs:\n x:\n name: "a\n b"\n runs-on: ubuntu-latest\n'}, + "environment in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {environment: release}\n"}, + "a double-quoted environment key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x:\n runs-on: ubuntu-latest\n with: {"environment": release}\n'}, + "a single-quoted environment key in a flow mapping": {**tree, "extra.yml": "jobs:\n x:\n runs-on: ubuntu-latest\n with: {'environment': release}\n"}, + "a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, + "uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"}, + "another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, + "a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])}, + "a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"}, + "a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")}, + } + for label, workflows in bad.items(): + with self.subTest(case=label): + self.assertTrue(trust_closure_problems(workflows)) + + def test_quoted_keys_in_a_flow_mapping_are_read_not_masked(self): + entries, refused = workflow_entries('jobs:\n x: {runs-on: ubuntu-latest, "name": build}\n') + self.assertEqual(refused, []) + self.assertIn((2, "name", "build", False), entries, "a quoted key keeps its identity") + self.assertIn((2, "runs-on", "ubuntu-latest", False), entries) + _, refused = workflow_entries("jobs:\n x: {runs-on: ubuntu-latest, 'environment': release}\n") + self.assertEqual(refused, ["line 2: environment in a flow mapping (must be block style)"]) + + def test_signer_dispatch_guard_and_policy_name_the_same_branch(self): + sign = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + (_, guard), = job_conditions(sign.split("\njobs:\n", 1)[1]) + self.assertIn("github.ref == 'refs/heads/" + SIGNER_BRANCH + "'", guard) + self.assertNotIn("refs/heads/release", sign, "the signer no longer runs on the stable branch") + self.assertEqual(re.findall(r"(?m)^ app-name: (\S+)$", sign), [APP_NAME], + "the shared signer needs the reviewed registry app") + dispatch = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text() + self.assertEqual(re.findall(r"'ref': '([^']+)'", dispatch), ["refs/heads/" + SIGNER_BRANCH]) + self.assertEqual(json.loads(INSTALLED_POLICY.read_text())["release_branch"], SIGNER_BRANCH) + + +def dispatch_triggers(source): + """The dispatch workflow's own triggers, one per line, as a caller may register them.""" + events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0] + return [line for line in events.splitlines() if line.startswith(" ") and not line.startswith(" ") + and line.strip() and not line.lstrip().startswith("#")] + + +class NightlyDispatchTransport(unittest.TestCase): + """The scheduled transport stays literally off and can only reach the signer branch.""" + + def setUp(self): + self.source = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text() + + def test_every_dispatch_job_is_literal_off(self): + jobs = self.source.split("\njobs:\n", 1)[1] + headers = re.findall(r"(?m)^ (?![\s#])[^\n]+", jobs) + conditions = job_conditions(jobs) + self.assertTrue(headers) + self.assertEqual(len(conditions), len(headers), "every job needs a literal-off condition") + for _, expression in conditions: + self.assertTrue(literal_off(expression), "nightly activation requires reviewed test update") + + def test_only_a_completed_scheduled_producer_is_transported(self): + self.assertEqual(re.findall(r"(?m)^ workflows: (.+)$", self.source), + ["[" + PRODUCER_WORKFLOW_NAME + "]"]) + self.assertEqual(dispatch_triggers(self.source), [" workflow_run:"], + "the transport is not a second entry point") + self.assertNotIn("schedule:", self.source) + self.assertIn("producer.get('event') == 'schedule'", self.source) + + def test_the_request_names_the_signer_workflow_and_branch(self): + self.assertIn("repos/storytold/" + APP_NAME + "/actions/workflows/nightly-sign.yml/dispatches", self.source) + self.assertNotIn("'ref': 'release'", self.source) if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/xtask/src/test262.rs b/xtask/src/test262.rs index 7ee456a6c2..3caf8f4a81 100644 --- a/xtask/src/test262.rs +++ b/xtask/src/test262.rs @@ -5,8 +5,8 @@ //! `test/language` tests and the tests of the ES5 built-ins under `test/built-ins` and //! `test/annexB/built-ins` that need only the interpreter's built-ins, run the `test/built-ins` //! tests for `String`, `Number`, `RegExp` and `Date`, parse and run the `test/annexB/language` -//! tests and run the other `test/annexB/built-ins` tests (`String`, `Date`, `RegExp` and -//! `Function`), and print each one's counts. +//! tests, run the other `test/annexB/built-ins` tests (`String`, `Date`, `RegExp` and +//! `Function`) and the `test/built-ins/Promise` tests, and print each one's counts. //! //! It also fetches `json2.js`, Douglas Crockford's public-domain JSON polyfill //! (https://github.com/douglascrockford/JSON-js), at a pinned commit, checks it against its SHA-256